project
stringclasses
765 values
commit_id
stringlengths
6
81
func
stringlengths
19
482k
vul
int64
0
1
CVE ID
stringlengths
13
16
CWE ID
stringclasses
13 values
CWE Name
stringclasses
13 values
CWE Description
stringclasses
13 values
Potential Mitigation
stringclasses
11 values
__index_level_0__
int64
0
23.9k
linux
99d825822eade8d827a1817357cbf3f889a552d6
static int rock_ridge_symlink_readpage(struct file *file, struct page *page) { struct inode *inode = page->mapping->host; struct iso_inode_info *ei = ISOFS_I(inode); struct isofs_sb_info *sbi = ISOFS_SB(inode->i_sb); char *link = page_address(page); unsigned long bufsize = ISOFS_BUFFER_SIZE(inode); struct buffer_head *bh; char *rpnt = link; unsigned char *pnt; struct iso_directory_record *raw_de; unsigned long block, offset; int sig; struct rock_ridge *rr; struct rock_state rs; int ret; if (!sbi->s_rock) goto error; init_rock_state(&rs, inode); block = ei->i_iget5_block; bh = sb_bread(inode->i_sb, block); if (!bh) goto out_noread; offset = ei->i_iget5_offset; pnt = (unsigned char *)bh->b_data + offset; raw_de = (struct iso_directory_record *)pnt; /* * If we go past the end of the buffer, there is some sort of error. */ if (offset + *pnt > bufsize) goto out_bad_span; /* * Now test for possible Rock Ridge extensions which will override * some of these numbers in the inode structure. */ setup_rock_ridge(raw_de, inode, &rs); repeat: while (rs.len > 2) { /* There may be one byte for padding somewhere */ rr = (struct rock_ridge *)rs.chr; if (rr->len < 3) goto out; /* Something got screwed up here */ sig = isonum_721(rs.chr); if (rock_check_overflow(&rs, sig)) goto out; rs.chr += rr->len; rs.len -= rr->len; if (rs.len < 0) goto out; /* corrupted isofs */ switch (sig) { case SIG('R', 'R'): if ((rr->u.RR.flags[0] & RR_SL) == 0) goto out; break; case SIG('S', 'P'): if (check_sp(rr, inode)) goto out; break; case SIG('S', 'L'): rpnt = get_symlink_chunk(rpnt, rr, link + (PAGE_SIZE - 1)); if (rpnt == NULL) goto out; break; case SIG('C', 'E'): /* This tells is if there is a continuation record */ rs.cont_extent = isonum_733(rr->u.CE.extent); rs.cont_offset = isonum_733(rr->u.CE.offset); rs.cont_size = isonum_733(rr->u.CE.size); default: break; } } ret = rock_continue(&rs); if (ret == 0) goto repeat; if (ret < 0) goto fail; if (rpnt == link) goto fail; brelse(bh); *rpnt = '\0'; SetPageUptodate(page); unlock_page(page); return 0; /* error exit from macro */ out: kfree(rs.buffer); goto fail; out_noread: printk("unable to read i-node block"); goto fail; out_bad_span: printk("symlink spans iso9660 blocks\n"); fail: brelse(bh); error: SetPageError(page); unlock_page(page); return -EIO; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
22,602
linux-2.6
176df2457ef6207156ca1a40991c54ca01fef567
static int putreg(struct task_struct *child, unsigned long regno, unsigned long value) { unsigned long tmp; switch (regno) { case offsetof(struct user_regs_struct,fs): if (value && (value & 3) != 3) return -EIO; child->thread.fsindex = value & 0xffff; return 0; case offsetof(struct user_regs_struct,gs): if (value && (value & 3) != 3) return -EIO; child->thread.gsindex = value & 0xffff; return 0; case offsetof(struct user_regs_struct,ds): if (value && (value & 3) != 3) return -EIO; child->thread.ds = value & 0xffff; return 0; case offsetof(struct user_regs_struct,es): if (value && (value & 3) != 3) return -EIO; child->thread.es = value & 0xffff; return 0; case offsetof(struct user_regs_struct,ss): if ((value & 3) != 3) return -EIO; value &= 0xffff; return 0; case offsetof(struct user_regs_struct,fs_base): if (value >= TASK_SIZE_OF(child)) return -EIO; child->thread.fs = value; return 0; case offsetof(struct user_regs_struct,gs_base): if (value >= TASK_SIZE_OF(child)) return -EIO; child->thread.gs = value; return 0; case offsetof(struct user_regs_struct, eflags): value &= FLAG_MASK; tmp = get_stack_long(child, EFL_OFFSET); tmp &= ~FLAG_MASK; value |= tmp; break; case offsetof(struct user_regs_struct,cs): if ((value & 3) != 3) return -EIO; value &= 0xffff; break; } put_stack_long(child, regno - sizeof(struct pt_regs), value); return 0; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
23,767
Chrome
746da1cc6b2fbc2f725934542eedc49b41e5f17b
bool PrintViewManager::BasicPrint(content::RenderFrameHost* rfh) { PrintPreviewDialogController* dialog_controller = PrintPreviewDialogController::GetInstance(); if (!dialog_controller) return false; content::WebContents* print_preview_dialog = dialog_controller->GetPrintPreviewForContents(web_contents()); if (!print_preview_dialog) return PrintNow(rfh); if (!print_preview_dialog->GetWebUI()) return false; PrintPreviewUI* print_preview_ui = static_cast<PrintPreviewUI*>( print_preview_dialog->GetWebUI()->GetController()); print_preview_ui->OnShowSystemDialog(); return true; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
23,840
linux
635682a14427d241bab7bbdeebb48a7d7b91638e
static void sctp_cmd_new_state(sctp_cmd_seq_t *cmds, struct sctp_association *asoc, sctp_state_t state) { struct sock *sk = asoc->base.sk; asoc->state = state; pr_debug("%s: asoc:%p[%s]\n", __func__, asoc, sctp_state_tbl[state]); if (sctp_style(sk, TCP)) { /* Change the sk->sk_state of a TCP-style socket that has * successfully completed a connect() call. */ if (sctp_state(asoc, ESTABLISHED) && sctp_sstate(sk, CLOSED)) sk->sk_state = SCTP_SS_ESTABLISHED; /* Set the RCV_SHUTDOWN flag when a SHUTDOWN is received. */ if (sctp_state(asoc, SHUTDOWN_RECEIVED) && sctp_sstate(sk, ESTABLISHED)) sk->sk_shutdown |= RCV_SHUTDOWN; } if (sctp_state(asoc, COOKIE_WAIT)) { /* Reset init timeouts since they may have been * increased due to timer expirations. */ asoc->timeouts[SCTP_EVENT_TIMEOUT_T1_INIT] = asoc->rto_initial; asoc->timeouts[SCTP_EVENT_TIMEOUT_T1_COOKIE] = asoc->rto_initial; } if (sctp_state(asoc, ESTABLISHED) || sctp_state(asoc, CLOSED) || sctp_state(asoc, SHUTDOWN_RECEIVED)) { /* Wake up any processes waiting in the asoc's wait queue in * sctp_wait_for_connect() or sctp_wait_for_sndbuf(). */ if (waitqueue_active(&asoc->wait)) wake_up_interruptible(&asoc->wait); /* Wake up any processes waiting in the sk's sleep queue of * a TCP-style or UDP-style peeled-off socket in * sctp_wait_for_accept() or sctp_wait_for_packet(). * For a UDP-style socket, the waiters are woken up by the * notifications. */ if (!sctp_style(sk, UDP)) sk->sk_state_change(sk); } }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
17,722
Chrome
f85a87ec670ad0fce9d98d90c9a705b72a288154
static void locationWithExceptionAttributeSetter(v8::Local<v8::Value> jsValue, const v8::PropertyCallbackInfo<void>& info) { TestObjectPython* proxyImp = V8TestObjectPython::toNative(info.Holder()); TestNode* imp = WTF::getPtr(proxyImp->locationWithException()); if (!imp) return; V8TRYCATCH_FOR_V8STRINGRESOURCE_VOID(V8StringResource<>, cppValue, jsValue); imp->setHrefThrows(cppValue); }
1
CVE-2014-1713
CWE-399
Resource Management Errors
Weaknesses in this category are related to improper management of system resources.
Not Found in CWE Page
9,173
Chrome
4e4c9b553ae124ed9bb60356e2ecff9106abddd0
void SetRecordActionTaskRunner( scoped_refptr<SingleThreadTaskRunner> task_runner) { DCHECK(task_runner->BelongsToCurrentThread()); DCHECK(!g_task_runner.Get() || g_task_runner.Get()->BelongsToCurrentThread()); g_task_runner.Get() = task_runner; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
19,295
dbus
9a6bce9b615abca6068348c1606ba8eaf13d9ae0
my_object_unstringify (MyObject *obj, const char *str, GValue *value, GError **error) { if (str[0] == '\0' || !g_ascii_isdigit (str[0])) { g_value_init (value, G_TYPE_STRING); g_value_set_string (value, str); } else { g_value_init (value, G_TYPE_INT); g_value_set_int (value, (int) g_ascii_strtoull (str, NULL, 10)); } return TRUE; }
1
CVE-2010-1172
CWE-264
Permissions, Privileges, and Access Controls
Weaknesses in this category are related to the management of permissions, privileges, and other security features that are used to perform access control.
Not Found in CWE Page
3,039
linux-stable
f53dc67c5e7babafe239b93a11678b0e05bead51
int dccp_send_reset(struct sock *sk, enum dccp_reset_codes code) { struct sk_buff *skb; /* * FIXME: what if rebuild_header fails? * Should we be doing a rebuild_header here? */ int err = inet_sk_rebuild_header(sk); if (err != 0) return err; skb = sock_wmalloc(sk, sk->sk_prot->max_header, 1, GFP_ATOMIC); if (skb == NULL) return -ENOBUFS; /* Reserve space for headers and prepare control bits. */ skb_reserve(skb, sk->sk_prot->max_header); DCCP_SKB_CB(skb)->dccpd_type = DCCP_PKT_RESET; DCCP_SKB_CB(skb)->dccpd_reset_code = code; return dccp_transmit_skb(sk, skb); }
1
CVE-2017-2634
CWE-119
Improper Restriction of Operations within the Bounds of a Memory Buffer
The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data.
Phase: Requirements Strategy: Language Selection Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. For example, many languages that perform their own memory management, such as Java and Perl, are not subject to buffer overflows. Other languages, such as Ada and C#, typically provide overflow protection, but the protection can be disabled by the programmer. Be wary that a language's interface to native code may still be subject to overflows, even if the language itself is theoretically safe. Phase: Architecture and Design Strategy: Libraries or Frameworks Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. Examples include the Safe C String Library (SafeStr) by Messier and Viega [REF-57], and the Strsafe.h library from Microsoft [REF-56]. These libraries provide safer versions of overflow-prone string-handling functions. Note: This is not a complete solution, since many buffer overflows are not related to strings. Phases: Operation; Build and Compilation Strategy: Environment Hardening Use automatic buffer overflow detection mechanisms that are offered by certain compilers or compiler extensions. Examples include: the Microsoft Visual Studio /GS flag, Fedora/Red Hat FORTIFY_SOURCE GCC flag, StackGuard, and ProPolice, which provide various mechanisms including canary-based detection and range/index checking. D3-SFCV (Stack Frame Canary Validation) from D3FEND [REF-1334] discusses canary-based detection in detail. Effectiveness: Defense in Depth Note: This is not necessarily a complete solution, since these mechanisms only detect certain types of overflows. In addition, the result is still a denial of service, since the typical response is to exit the application. Phase: Implementation Consider adhering to the following rules when allocating and managing an application's memory: Double check that the buffer is as large as specified. When using functions that accept a number of bytes to copy, such as strncpy(), be aware that if the destination buffer size is equal to the source buffer size, it may not NULL-terminate the string. Check buffer boundaries if accessing the buffer in a loop and make sure there is no danger of writing past the allocated space. If necessary, truncate all input strings to a reasonable length before passing them to the copy and concatenation functions. Phases: Operation; Build and Compilation Strategy: Environment Hardening Run or compile the software using features or extensions that randomly arrange the positions of a program's executable and libraries in memory. Because this makes the addresses unpredictable, it can prevent an attacker from reliably jumping to exploitable code. Examples include Address Space Layout Randomization (ASLR) [REF-58] [REF-60] and Position-Independent Executables (PIE) [REF-64]. Imported modules may be similarly realigned if their default memory addresses conflict with other modules, in a process known as "rebasing" (for Windows) and "prelinking" (for Linux) [REF-1332] using randomly generated addresses. ASLR for libraries cannot be used in conjunction with prelink since it would require relocating the libraries at run-time, defeating the whole purpose of prelinking. For more information on these techniques see D3-SAOR (Segment Address Offset Randomization) from D3FEND [REF-1335]. Effectiveness: Defense in Depth Note: These techniques do not provide a complete solution. For instance, exploits frequently use a bug that discloses memory addresses in order to maximize reliability of code execution [REF-1337]. It has also been shown that a side-channel attack can bypass ASLR [REF-1333] Phase: Operation Strategy: Environment Hardening Use a CPU and operating system that offers Data Execution Protection (using hardware NX or XD bits) or the equivalent techniques that simulate this feature in software, such as PaX [REF-60] [REF-61]. These techniques ensure that any instruction executed is exclusively at a memory address that is part of the code segment. For more information on these techniques see D3-PSEP (Process Segment Execution Prevention) from D3FEND [REF-1336]. Effectiveness: Defense in Depth Note: This is not a complete solution, since buffer overflows could be used to overwrite nearby variables to modify the software's state in dangerous ways. In addition, it cannot be used in cases in which self-modifying code is required. Finally, an attack could still cause a denial of service, since the typical response is to exit the application. Phase: Implementation Replace unbounded copy functions with analogous functions that support length arguments, such as strcpy with strncpy. Create these if they are not available. Effectiveness: Moderate Note: This approach is still susceptible to calculation errors, including issues such as off-by-one errors (CWE-193) and incorrectly calculating buffer lengths (CWE-131).
5,016
php-src
6559fe912661ca5ce5f0eeeb591d928451428ed0
PHPAPI void php_register_variable_ex(char *var_name, zval *val, zval *track_vars_array) { char *p = NULL; char *ip = NULL; /* index pointer */ char *index; char *var, *var_orig; size_t var_len, index_len; zval gpc_element, *gpc_element_p; zend_bool is_array = 0; HashTable *symtable1 = NULL; ALLOCA_FLAG(use_heap) assert(var_name != NULL); if (track_vars_array && Z_TYPE_P(track_vars_array) == IS_ARRAY) { symtable1 = Z_ARRVAL_P(track_vars_array); } if (!symtable1) { /* Nothing to do */ zval_dtor(val); return; } /* ignore leading spaces in the variable name */ while (*var_name==' ') { var_name++; } /* * Prepare variable name */ var_len = strlen(var_name); var = var_orig = do_alloca(var_len + 1, use_heap); memcpy(var_orig, var_name, var_len + 1); /* ensure that we don't have spaces or dots in the variable name (not binary safe) */ for (p = var; *p; p++) { if (*p == ' ' || *p == '.') { *p='_'; } else if (*p == '[') { is_array = 1; ip = p; *p = 0; break; } } var_len = p - var; if (var_len==0) { /* empty variable name, or variable name with a space in it */ zval_dtor(val); free_alloca(var_orig, use_heap); return; } if (var_len == sizeof("this")-1 && EG(current_execute_data)) { zend_execute_data *ex = EG(current_execute_data); while (ex) { if (ex->func && ZEND_USER_CODE(ex->func->common.type)) { if ((ZEND_CALL_INFO(ex) & ZEND_CALL_HAS_SYMBOL_TABLE) && ex->symbol_table == symtable1) { if (memcmp(var, "this", sizeof("this")-1) == 0) { zend_throw_error(NULL, "Cannot re-assign $this"); zval_dtor(val); free_alloca(var_orig, use_heap); return; } } break; } ex = ex->prev_execute_data; } } /* GLOBALS hijack attempt, reject parameter */ if (symtable1 == &EG(symbol_table) && var_len == sizeof("GLOBALS")-1 && !memcmp(var, "GLOBALS", sizeof("GLOBALS")-1)) { zval_dtor(val); free_alloca(var_orig, use_heap); return; } index = var; index_len = var_len; if (is_array) { int nest_level = 0; while (1) { char *index_s; size_t new_idx_len = 0; if(++nest_level > PG(max_input_nesting_level)) { HashTable *ht; /* too many levels of nesting */ if (track_vars_array) { ht = Z_ARRVAL_P(track_vars_array); zend_symtable_str_del(ht, var, var_len); } zval_dtor(val); /* do not output the error message to the screen, this helps us to to avoid "information disclosure" */ if (!PG(display_errors)) { php_error_docref(NULL, E_WARNING, "Input variable nesting level exceeded " ZEND_LONG_FMT ". To increase the limit change max_input_nesting_level in php.ini.", PG(max_input_nesting_level)); } free_alloca(var_orig, use_heap); return; } ip++; index_s = ip; if (isspace(*ip)) { ip++; } if (*ip==']') { index_s = NULL; } else { ip = strchr(ip, ']'); if (!ip) { /* PHP variables cannot contain '[' in their names, so we replace the character with a '_' */ *(index_s - 1) = '_'; index_len = 0; if (index) { index_len = strlen(index); } goto plain_var; return; } *ip = 0; new_idx_len = strlen(index_s); } if (!index) { array_init(&gpc_element); if ((gpc_element_p = zend_hash_next_index_insert(symtable1, &gpc_element)) == NULL) { zval_ptr_dtor(&gpc_element); zval_dtor(val); free_alloca(var_orig, use_heap); return; } } else { gpc_element_p = zend_symtable_str_find(symtable1, index, index_len); if (!gpc_element_p) { zval tmp; array_init(&tmp); gpc_element_p = zend_symtable_str_update_ind(symtable1, index, index_len, &tmp); } else { if (Z_TYPE_P(gpc_element_p) == IS_INDIRECT) { gpc_element_p = Z_INDIRECT_P(gpc_element_p); } if (Z_TYPE_P(gpc_element_p) != IS_ARRAY) { zval_ptr_dtor(gpc_element_p); array_init(gpc_element_p); } else { SEPARATE_ARRAY(gpc_element_p); } } } symtable1 = Z_ARRVAL_P(gpc_element_p); /* ip pointed to the '[' character, now obtain the key */ index = index_s; index_len = new_idx_len; ip++; if (*ip == '[') { is_array = 1; *ip = 0; } else { goto plain_var; } } } else { plain_var: ZVAL_COPY_VALUE(&gpc_element, val); if (!index) { if ((gpc_element_p = zend_hash_next_index_insert(symtable1, &gpc_element)) == NULL) { zval_ptr_dtor(&gpc_element); } } else { /* * According to rfc2965, more specific paths are listed above the less specific ones. * If we encounter a duplicate cookie name, we should skip it, since it is not possible * to have the same (plain text) cookie name for the same path and we should not overwrite * more specific cookies with the less specific ones. */ if (Z_TYPE(PG(http_globals)[TRACK_VARS_COOKIE]) != IS_UNDEF && symtable1 == Z_ARRVAL(PG(http_globals)[TRACK_VARS_COOKIE]) && zend_symtable_str_exists(symtable1, index, index_len)) { zval_ptr_dtor(&gpc_element); } else { gpc_element_p = zend_symtable_str_update_ind(symtable1, index, index_len, &gpc_element); } } } free_alloca(var_orig, use_heap); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
21,942
linux
ca4da5dd1f99fe9c59f1709fb43e818b18ad20e0
struct key *keyring_alloc(const char *description, kuid_t uid, kgid_t gid, const struct cred *cred, key_perm_t perm, unsigned long flags, struct key *dest) { struct key *keyring; int ret; keyring = key_alloc(&key_type_keyring, description, uid, gid, cred, perm, flags); if (!IS_ERR(keyring)) { ret = key_instantiate_and_link(keyring, NULL, 0, dest, NULL); if (ret < 0) { key_put(keyring); keyring = ERR_PTR(ret); } } return keyring; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
13,196
Android
eeb4e45d5683f88488c083ecf142dc89bc3f0b47
static int _determine_node_bytes(long used, int leafwidth){ /* special case small books to size 4 to avoid multiple special cases in repack */ if(used<2) return 4; if(leafwidth==3)leafwidth=4; if(_ilog(3*used-6)+1 <= leafwidth*4) return leafwidth/2?leafwidth/2:1; return leafwidth; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
23,095
linux
9d538fa60bad4f7b23193c89e843797a1cf71ef3
int sock_no_getsockopt(struct socket *sock, int level, int optname, char __user *optval, int __user *optlen) { return -EOPNOTSUPP; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
16,949
vino
9c8b9f81205203db6c31068babbfb8a734acacdb
rfbSendServerCutText(rfbScreenInfoPtr rfbScreen,char *str, int len) { rfbClientPtr cl; rfbServerCutTextMsg sct; rfbClientIteratorPtr iterator; iterator = rfbGetClientIterator(rfbScreen); while ((cl = rfbClientIteratorNext(iterator)) != NULL) { /* Client is not authenticated, ignore. See GNOME bug 678434. */ if (cl->state != RFB_NORMAL) continue; sct.type = rfbServerCutText; sct.length = Swap32IfLE(len); if (WriteExact(cl, (char *)&sct, sz_rfbServerCutTextMsg) < 0) { rfbLogPerror("rfbSendServerCutText: write"); rfbCloseClient(cl); continue; } if (WriteExact(cl, str, len) < 0) { rfbLogPerror("rfbSendServerCutText: write"); rfbCloseClient(cl); } } rfbReleaseClientIterator(iterator); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
21,769
linux
371528caec553785c37f73fa3926ea0de84f986f
struct lruvec *mem_cgroup_lru_add_list(struct zone *zone, struct page *page, enum lru_list lru) { struct mem_cgroup_per_zone *mz; struct mem_cgroup *memcg; struct page_cgroup *pc; if (mem_cgroup_disabled()) return &zone->lruvec; pc = lookup_page_cgroup(page); memcg = pc->mem_cgroup; mz = page_cgroup_zoneinfo(memcg, page); /* compound_order() is stabilized through lru_lock */ MEM_CGROUP_ZSTAT(mz, lru) += 1 << compound_order(page); return &mz->lruvec; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
11,465
krb5
83ed75feba32e46f736fcce0d96a0445f29b96c2
getprivs_ret * get_privs_2_svc(krb5_ui_4 *arg, struct svc_req *rqstp) { static getprivs_ret ret; gss_buffer_desc client_name, service_name; OM_uint32 minor_stat; kadm5_server_handle_t handle; const char *errmsg = NULL; xdr_free(xdr_getprivs_ret, &ret); if ((ret.code = new_server_handle(*arg, rqstp, &handle))) goto exit_func; if ((ret.code = check_handle((void *)handle))) goto exit_func; ret.api_version = handle->api_version; if (setup_gss_names(rqstp, &client_name, &service_name) < 0) { ret.code = KADM5_FAILURE; goto exit_func; } ret.code = kadm5_get_privs((void *)handle, &ret.privs); if( ret.code != 0 ) errmsg = krb5_get_error_message(handle->context, ret.code); log_done("kadm5_get_privs", client_name.value, errmsg, &client_name, &service_name, rqstp); if (errmsg != NULL) krb5_free_error_message(handle->context, errmsg); gss_release_buffer(&minor_stat, &client_name); gss_release_buffer(&minor_stat, &service_name); exit_func: free_server_handle(handle); return &ret; }
1
CVE-2015-8631
CWE-119
Improper Restriction of Operations within the Bounds of a Memory Buffer
The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data.
Phase: Requirements Strategy: Language Selection Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. For example, many languages that perform their own memory management, such as Java and Perl, are not subject to buffer overflows. Other languages, such as Ada and C#, typically provide overflow protection, but the protection can be disabled by the programmer. Be wary that a language's interface to native code may still be subject to overflows, even if the language itself is theoretically safe. Phase: Architecture and Design Strategy: Libraries or Frameworks Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. Examples include the Safe C String Library (SafeStr) by Messier and Viega [REF-57], and the Strsafe.h library from Microsoft [REF-56]. These libraries provide safer versions of overflow-prone string-handling functions. Note: This is not a complete solution, since many buffer overflows are not related to strings. Phases: Operation; Build and Compilation Strategy: Environment Hardening Use automatic buffer overflow detection mechanisms that are offered by certain compilers or compiler extensions. Examples include: the Microsoft Visual Studio /GS flag, Fedora/Red Hat FORTIFY_SOURCE GCC flag, StackGuard, and ProPolice, which provide various mechanisms including canary-based detection and range/index checking. D3-SFCV (Stack Frame Canary Validation) from D3FEND [REF-1334] discusses canary-based detection in detail. Effectiveness: Defense in Depth Note: This is not necessarily a complete solution, since these mechanisms only detect certain types of overflows. In addition, the result is still a denial of service, since the typical response is to exit the application. Phase: Implementation Consider adhering to the following rules when allocating and managing an application's memory: Double check that the buffer is as large as specified. When using functions that accept a number of bytes to copy, such as strncpy(), be aware that if the destination buffer size is equal to the source buffer size, it may not NULL-terminate the string. Check buffer boundaries if accessing the buffer in a loop and make sure there is no danger of writing past the allocated space. If necessary, truncate all input strings to a reasonable length before passing them to the copy and concatenation functions. Phases: Operation; Build and Compilation Strategy: Environment Hardening Run or compile the software using features or extensions that randomly arrange the positions of a program's executable and libraries in memory. Because this makes the addresses unpredictable, it can prevent an attacker from reliably jumping to exploitable code. Examples include Address Space Layout Randomization (ASLR) [REF-58] [REF-60] and Position-Independent Executables (PIE) [REF-64]. Imported modules may be similarly realigned if their default memory addresses conflict with other modules, in a process known as "rebasing" (for Windows) and "prelinking" (for Linux) [REF-1332] using randomly generated addresses. ASLR for libraries cannot be used in conjunction with prelink since it would require relocating the libraries at run-time, defeating the whole purpose of prelinking. For more information on these techniques see D3-SAOR (Segment Address Offset Randomization) from D3FEND [REF-1335]. Effectiveness: Defense in Depth Note: These techniques do not provide a complete solution. For instance, exploits frequently use a bug that discloses memory addresses in order to maximize reliability of code execution [REF-1337]. It has also been shown that a side-channel attack can bypass ASLR [REF-1333] Phase: Operation Strategy: Environment Hardening Use a CPU and operating system that offers Data Execution Protection (using hardware NX or XD bits) or the equivalent techniques that simulate this feature in software, such as PaX [REF-60] [REF-61]. These techniques ensure that any instruction executed is exclusively at a memory address that is part of the code segment. For more information on these techniques see D3-PSEP (Process Segment Execution Prevention) from D3FEND [REF-1336]. Effectiveness: Defense in Depth Note: This is not a complete solution, since buffer overflows could be used to overwrite nearby variables to modify the software's state in dangerous ways. In addition, it cannot be used in cases in which self-modifying code is required. Finally, an attack could still cause a denial of service, since the typical response is to exit the application. Phase: Implementation Replace unbounded copy functions with analogous functions that support length arguments, such as strcpy with strncpy. Create these if they are not available. Effectiveness: Moderate Note: This approach is still susceptible to calculation errors, including issues such as off-by-one errors (CWE-193) and incorrectly calculating buffer lengths (CWE-131).
567
openssl
77c77f0a1b9f15b869ca3342186dfbedd1119d0e
static int do_ssl3_write(SSL *s, int type, const unsigned char *buf, unsigned int len, int create_empty_fragment) { unsigned char *p, *plen; int i, mac_size, clear = 0; int prefix_len = 0; int eivlen; long align = 0; SSL3_RECORD *wr; SSL3_BUFFER *wb = &(s->s3->wbuf); SSL_SESSION *sess; /* * first check if there is a SSL3_BUFFER still being written out. This * will happen with non blocking IO */ if (wb->left != 0) return (ssl3_write_pending(s, type, buf, len)); /* If we have an alert to send, lets send it */ if (s->s3->alert_dispatch) { i = s->method->ssl_dispatch_alert(s); if (i <= 0) return (i); /* if it went, fall through and send more stuff */ } if (wb->buf == NULL) if (!ssl3_setup_write_buffer(s)) return -1; if (len == 0 && !create_empty_fragment) return 0; wr = &(s->s3->wrec); sess = s->session; if ((sess == NULL) || (s->enc_write_ctx == NULL) || (EVP_MD_CTX_md(s->write_hash) == NULL)) { #if 1 clear = s->enc_write_ctx ? 0 : 1; /* must be AEAD cipher */ #else clear = 1; #endif mac_size = 0; } else { mac_size = EVP_MD_CTX_size(s->write_hash); if (mac_size < 0) goto err; } /* * 'create_empty_fragment' is true only when this function calls itself */ if (!clear && !create_empty_fragment && !s->s3->empty_fragment_done) { /* * countermeasure against known-IV weakness in CBC ciphersuites (see * http://www.openssl.org/~bodo/tls-cbc.txt) */ if (s->s3->need_empty_fragments && type == SSL3_RT_APPLICATION_DATA) { /* * recursive function call with 'create_empty_fragment' set; this * prepares and buffers the data for an empty fragment (these * 'prefix_len' bytes are sent out later together with the actual * payload) */ prefix_len = do_ssl3_write(s, type, buf, 0, 1); if (prefix_len <= 0) goto err; if (prefix_len > (SSL3_RT_HEADER_LENGTH + SSL3_RT_SEND_MAX_ENCRYPTED_OVERHEAD)) { /* insufficient space */ SSLerr(SSL_F_DO_SSL3_WRITE, ERR_R_INTERNAL_ERROR); goto err; } } s->s3->empty_fragment_done = 1; } if (create_empty_fragment) { #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD!=0 /* * extra fragment would be couple of cipher blocks, which would be * multiple of SSL3_ALIGN_PAYLOAD, so if we want to align the real * payload, then we can just pretent we simply have two headers. */ align = (long)wb->buf + 2 * SSL3_RT_HEADER_LENGTH; align = (-align) & (SSL3_ALIGN_PAYLOAD - 1); #endif p = wb->buf + align; wb->offset = align; } else if (prefix_len) { p = wb->buf + wb->offset + prefix_len; } else { #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD!=0 align = (long)wb->buf + SSL3_RT_HEADER_LENGTH; align = (-align) & (SSL3_ALIGN_PAYLOAD - 1); #endif p = wb->buf + align; wb->offset = align; } /* write the header */ *(p++) = type & 0xff; wr->type = type; *(p++) = (s->version >> 8); /* * Some servers hang if iniatial client hello is larger than 256 bytes * and record version number > TLS 1.0 */ if (s->state == SSL3_ST_CW_CLNT_HELLO_B && !s->renegotiate && TLS1_get_version(s) > TLS1_VERSION) *(p++) = 0x1; else *(p++) = s->version & 0xff; /* field where we are to write out packet length */ plen = p; p += 2; /* Explicit IV length, block ciphers appropriate version flag */ if (s->enc_write_ctx && SSL_USE_EXPLICIT_IV(s)) { int mode = EVP_CIPHER_CTX_mode(s->enc_write_ctx); if (mode == EVP_CIPH_CBC_MODE) { eivlen = EVP_CIPHER_CTX_iv_length(s->enc_write_ctx); if (eivlen <= 1) eivlen = 0; } /* Need explicit part of IV for GCM mode */ else if (mode == EVP_CIPH_GCM_MODE) eivlen = EVP_GCM_TLS_EXPLICIT_IV_LEN; else eivlen = 0; } else eivlen = 0; /* lets setup the record stuff. */ wr->data = p + eivlen; wr->length = (int)len; wr->input = (unsigned char *)buf; /* * we now 'read' from wr->input, wr->length bytes into wr->data */ /* first we compress */ if (s->compress != NULL) { if (!ssl3_do_compress(s)) { SSLerr(SSL_F_DO_SSL3_WRITE, SSL_R_COMPRESSION_FAILURE); goto err; } } else { memcpy(wr->data, wr->input, wr->length); wr->input = wr->data; } /* * we should still have the output to wr->data and the input from * wr->input. Length should be wr->length. wr->data still points in the * wb->buf */ if (mac_size != 0) { if (s->method->ssl3_enc->mac(s, &(p[wr->length + eivlen]), 1) < 0) goto err; wr->length += mac_size; } wr->input = p; wr->data = p; if (eivlen) { /* * if (RAND_pseudo_bytes(p, eivlen) <= 0) goto err; */ wr->length += eivlen; } if (s->method->ssl3_enc->enc(s, 1) < 1) goto err; /* record length after mac and block padding */ s2n(wr->length, plen); if (s->msg_callback) s->msg_callback(1, 0, SSL3_RT_HEADER, plen - 5, 5, s, s->msg_callback_arg); /* * we should now have wr->data pointing to the encrypted data, which is * wr->length long */ wr->type = type; /* not needed but helps for debugging */ wr->length += SSL3_RT_HEADER_LENGTH; if (create_empty_fragment) { /* * we are in a recursive call; just return the length, don't write * out anything here */ return wr->length; } /* now let's set up wb */ wb->left = prefix_len + wr->length; /* * memorize arguments so that ssl3_write_pending can detect bad write * retries later */ s->s3->wpend_tot = len; s->s3->wpend_buf = buf; s->s3->wpend_type = type; s->s3->wpend_ret = len; /* we now just need to write the buffer */ return ssl3_write_pending(s, type, buf, len); err: return -1; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
21,284
bash
951bdaad7a18cc0dc1036bba86b18b90874d39ff
disable_priv_mode () { int e; if (setuid (current_user.uid) < 0) { e = errno; sys_error (_("cannot set uid to %d: effective uid %d"), current_user.uid, current_user.euid); #if defined (EXIT_ON_SETUID_FAILURE) if (e == EAGAIN) exit (e); #endif } if (setgid (current_user.gid) < 0) sys_error (_("cannot set gid to %d: effective gid %d"), current_user.gid, current_user.egid); current_user.euid = current_user.uid; current_user.egid = current_user.gid; }
1
CVE-2019-18276
CWE-787
Out-of-bounds Write
The product writes data past the end, or before the beginning, of the intended buffer.
Phase: Requirements Strategy: Language Selection Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. For example, many languages that perform their own memory management, such as Java and Perl, are not subject to buffer overflows. Other languages, such as Ada and C#, typically provide overflow protection, but the protection can be disabled by the programmer. Be wary that a language's interface to native code may still be subject to overflows, even if the language itself is theoretically safe. Phase: Architecture and Design Strategy: Libraries or Frameworks Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. Examples include the Safe C String Library (SafeStr) by Messier and Viega [REF-57], and the Strsafe.h library from Microsoft [REF-56]. These libraries provide safer versions of overflow-prone string-handling functions. Note: This is not a complete solution, since many buffer overflows are not related to strings. Phases: Operation; Build and Compilation Strategy: Environment Hardening Use automatic buffer overflow detection mechanisms that are offered by certain compilers or compiler extensions. Examples include: the Microsoft Visual Studio /GS flag, Fedora/Red Hat FORTIFY_SOURCE GCC flag, StackGuard, and ProPolice, which provide various mechanisms including canary-based detection and range/index checking. D3-SFCV (Stack Frame Canary Validation) from D3FEND [REF-1334] discusses canary-based detection in detail. Effectiveness: Defense in Depth Note: This is not necessarily a complete solution, since these mechanisms only detect certain types of overflows. In addition, the result is still a denial of service, since the typical response is to exit the application. Phase: Implementation Consider adhering to the following rules when allocating and managing an application's memory: Double check that the buffer is as large as specified. When using functions that accept a number of bytes to copy, such as strncpy(), be aware that if the destination buffer size is equal to the source buffer size, it may not NULL-terminate the string. Check buffer boundaries if accessing the buffer in a loop and make sure there is no danger of writing past the allocated space. If necessary, truncate all input strings to a reasonable length before passing them to the copy and concatenation functions. Phases: Operation; Build and Compilation Strategy: Environment Hardening Run or compile the software using features or extensions that randomly arrange the positions of a program's executable and libraries in memory. Because this makes the addresses unpredictable, it can prevent an attacker from reliably jumping to exploitable code. Examples include Address Space Layout Randomization (ASLR) [REF-58] [REF-60] and Position-Independent Executables (PIE) [REF-64]. Imported modules may be similarly realigned if their default memory addresses conflict with other modules, in a process known as "rebasing" (for Windows) and "prelinking" (for Linux) [REF-1332] using randomly generated addresses. ASLR for libraries cannot be used in conjunction with prelink since it would require relocating the libraries at run-time, defeating the whole purpose of prelinking. For more information on these techniques see D3-SAOR (Segment Address Offset Randomization) from D3FEND [REF-1335]. Effectiveness: Defense in Depth Note: These techniques do not provide a complete solution. For instance, exploits frequently use a bug that discloses memory addresses in order to maximize reliability of code execution [REF-1337]. It has also been shown that a side-channel attack can bypass ASLR [REF-1333]. Phase: Operation Strategy: Environment Hardening Use a CPU and operating system that offers Data Execution Protection (using hardware NX or XD bits) or the equivalent techniques that simulate this feature in software, such as PaX [REF-60] [REF-61]. These techniques ensure that any instruction executed is exclusively at a memory address that is part of the code segment. For more information on these techniques see D3-PSEP (Process Segment Execution Prevention) from D3FEND [REF-1336]. Effectiveness: Defense in Depth Note: This is not a complete solution, since buffer overflows could be used to overwrite nearby variables to modify the software's state in dangerous ways. In addition, it cannot be used in cases in which self-modifying code is required. Finally, an attack could still cause a denial of service, since the typical response is to exit the application. Phase: Implementation Replace unbounded copy functions with analogous functions that support length arguments, such as strcpy with strncpy. Create these if they are not available. Effectiveness: Moderate Note: This approach is still susceptible to calculation errors, including issues such as off-by-one errors (CWE-193) and incorrectly calculating buffer lengths (CWE-131).
6,056
core
1a29ed2f96da1be22fa5a4d96c7583aa81b8b060
time_t auth_client_request_get_create_time(struct auth_client_request *request) { return request->created; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
17,960
php
1ddf72180a52d247db88ea42a3e35f824a8fbda1
static int phar_dir_seek(php_stream *stream, off_t offset, int whence, off_t *newoffset TSRMLS_DC) /* {{{ */ { HashTable *data = (HashTable *)stream->abstract; if (!data) { return -1; } if (whence == SEEK_END) { whence = SEEK_SET; offset = zend_hash_num_elements(data) + offset; } if (whence == SEEK_SET) { zend_hash_internal_pointer_reset(data); } if (offset < 0) { return -1; } else { *newoffset = 0; while (*newoffset < offset && zend_hash_move_forward(data) == SUCCESS) { ++(*newoffset); } return 0; } } /* }}} */
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
19,425
Android
c677ee92595335233eb0e7b59809a1a94e7a678a
static BOOLEAN btm_sec_check_prefetch_pin (tBTM_SEC_DEV_REC *p_dev_rec) { UINT8 major = (UINT8)(p_dev_rec->dev_class[1] & BTM_COD_MAJOR_CLASS_MASK); UINT8 minor = (UINT8)(p_dev_rec->dev_class[2] & BTM_COD_MINOR_CLASS_MASK); BOOLEAN rv = FALSE; if ((major == BTM_COD_MAJOR_AUDIO) && ((minor == BTM_COD_MINOR_CONFM_HANDSFREE) || (minor == BTM_COD_MINOR_CAR_AUDIO)) ) { BTM_TRACE_EVENT ("btm_sec_check_prefetch_pin: Skipping pre-fetch PIN for carkit COD Major: 0x%02x Minor: 0x%02x", major, minor); if (btm_cb.security_mode_changed == FALSE) { btm_cb.security_mode_changed = TRUE; #ifdef APPL_AUTH_WRITE_EXCEPTION if(!(APPL_AUTH_WRITE_EXCEPTION)(p_dev_rec->bd_addr)) #endif btsnd_hcic_write_auth_enable (TRUE); } } else { btm_sec_change_pairing_state (BTM_PAIR_STATE_WAIT_LOCAL_PIN); /* If we got a PIN, use that, else try to get one */ if (btm_cb.pin_code_len) { BTM_PINCodeReply (p_dev_rec->bd_addr, BTM_SUCCESS, btm_cb.pin_code_len, btm_cb.pin_code, p_dev_rec->trusted_mask); } else { /* pin was not supplied - pre-fetch pin code now */ if (btm_cb.api.p_pin_callback && ((btm_cb.pairing_flags & BTM_PAIR_FLAGS_PIN_REQD) == 0)) { BTM_TRACE_DEBUG("btm_sec_check_prefetch_pin: PIN code callback called"); if (btm_bda_to_acl(p_dev_rec->bd_addr, BT_TRANSPORT_BR_EDR) == NULL) btm_cb.pairing_flags |= BTM_PAIR_FLAGS_PIN_REQD; (btm_cb.api.p_pin_callback) (p_dev_rec->bd_addr, p_dev_rec->dev_class, p_dev_rec->sec_bd_name); } } rv = TRUE; } return rv; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
10,888
iproute2
b45e300024bb0936a41821ad75117dc08b65669f
int rta_addattr64(struct rtattr *rta, int maxlen, int type, __u64 data) { return rta_addattr_l(rta, maxlen, type, &data, sizeof(__u64)); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
15,662
linux
fe685aabf7c8c9f138e5ea900954d295bf229175
isofs_export_encode_fh(struct inode *inode, __u32 *fh32, int *max_len, struct inode *parent) { struct iso_inode_info * ei = ISOFS_I(inode); int len = *max_len; int type = 1; __u16 *fh16 = (__u16*)fh32; /* * WARNING: max_len is 5 for NFSv2. Because of this * limitation, we use the lower 16 bits of fh32[1] to hold the * offset of the inode and the upper 16 bits of fh32[1] to * hold the offset of the parent. */ if (parent && (len < 5)) { *max_len = 5; return 255; } else if (len < 3) { *max_len = 3; return 255; } len = 3; fh32[0] = ei->i_iget5_block; fh16[2] = (__u16)ei->i_iget5_offset; /* fh16 [sic] */ fh16[3] = 0; /* avoid leaking uninitialized data */ fh32[2] = inode->i_generation; if (parent) { struct iso_inode_info *eparent; eparent = ISOFS_I(parent); fh32[3] = eparent->i_iget5_block; fh16[3] = (__u16)eparent->i_iget5_offset; /* fh16 [sic] */ fh32[4] = parent->i_generation; len = 5; type = 2; } *max_len = len; return type; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
21,720
tensorflow
e746adbfcfee15e9cfdb391ff746c765b99bdf9b
void DecodePngV2(OpKernelContext* context, StringPiece input) { int channel_bits = (data_type_ == DataType::DT_UINT8) ? 8 : 16; png::DecodeContext decode; OP_REQUIRES( context, png::CommonInitDecode(input, channels_, channel_bits, &decode), errors::InvalidArgument("Invalid PNG. Failed to initialize decoder.")); // Verify that width and height are not too large: // - verify width and height don't overflow int. // - width can later be multiplied by channels_ and sizeof(uint16), so // verify single dimension is not too large. // - verify when width and height are multiplied together, there are a few // bits to spare as well. const int width = static_cast<int>(decode.width); const int height = static_cast<int>(decode.height); const int64_t total_size = static_cast<int64_t>(width) * static_cast<int64_t>(height); if (width != static_cast<int64_t>(decode.width) || width <= 0 || width >= (1LL << 27) || height != static_cast<int64_t>(decode.height) || height <= 0 || height >= (1LL << 27) || total_size >= (1LL << 29)) { png::CommonFreeDecode(&decode); OP_REQUIRES(context, false, errors::InvalidArgument("PNG size too large for int: ", decode.width, " by ", decode.height)); } Tensor* output = nullptr; Status status; // By the existing API, we support decoding PNG with `DecodeGif` op. // We need to make sure to return 4-D shapes when using `DecodeGif`. if (op_type_ == "DecodeGif") { status = context->allocate_output( 0, TensorShape({1, height, width, decode.channels}), &output); } else { status = context->allocate_output( 0, TensorShape({height, width, decode.channels}), &output); } if (op_type_ == "DecodeBmp") { // TODO(b/171060723): Only DecodeBmp as op_type_ is not acceptable here // because currently `decode_(jpeg|png|gif)` ops can decode any one of // jpeg, png or gif but not bmp. Similarly, `decode_bmp` cannot decode // anything but bmp formats. This behavior needs to be revisited. For more // details, please refer to the bug. OP_REQUIRES(context, false, errors::InvalidArgument( "Trying to decode PNG format using DecodeBmp op. Use " "`decode_png` or `decode_image` instead.")); } else if (op_type_ == "DecodeAndCropJpeg") { OP_REQUIRES(context, false, errors::InvalidArgument( "DecodeAndCropJpeg operation can run on JPEG only, but " "detected PNG.")); } if (!status.ok()) png::CommonFreeDecode(&decode); OP_REQUIRES_OK(context, status); if (data_type_ == DataType::DT_UINT8) { OP_REQUIRES( context, png::CommonFinishDecode( reinterpret_cast<png_bytep>(output->flat<uint8>().data()), decode.channels * width * sizeof(uint8), &decode), errors::InvalidArgument("Invalid PNG data, size ", input.size())); } else if (data_type_ == DataType::DT_UINT16) { OP_REQUIRES( context, png::CommonFinishDecode( reinterpret_cast<png_bytep>(output->flat<uint16>().data()), decode.channels * width * sizeof(uint16), &decode), errors::InvalidArgument("Invalid PNG data, size ", input.size())); } else if (data_type_ == DataType::DT_FLOAT) { // `png::CommonFinishDecode` does not support `float`. First allocate // uint16 buffer for the image and decode in uint16 (lossless). Wrap the // buffer in `unique_ptr` so that we don't forget to delete the buffer. std::unique_ptr<uint16[]> buffer( new uint16[height * width * decode.channels]); OP_REQUIRES( context, png::CommonFinishDecode(reinterpret_cast<png_bytep>(buffer.get()), decode.channels * width * sizeof(uint16), &decode), errors::InvalidArgument("Invalid PNG data, size ", input.size())); // Convert uint16 image data to desired data type. // Use eigen threadpooling to speed up the copy operation. const auto& device = context->eigen_device<Eigen::ThreadPoolDevice>(); TTypes<uint16, 3>::UnalignedConstTensor buf(buffer.get(), height, width, decode.channels); float scale = 1. / std::numeric_limits<uint16>::max(); // Fill output tensor with desired dtype. output->tensor<float, 3>().device(device) = buf.cast<float>() * scale; } }
1
CVE-2022-23584
CWE-416
Use After Free
The product reuses or references memory after it has been freed. At some point afterward, the memory may be allocated again and saved in another pointer, while the original pointer references a location somewhere within the new allocation. Any operations using the original pointer are no longer valid because the memory "belongs" to the code that operates on the new pointer.
Phase: Architecture and Design Strategy: Language Selection Choose a language that provides automatic memory management. Phase: Implementation Strategy: Attack Surface Reduction When freeing pointers, be sure to set them to NULL once they are freed. However, the utilization of multiple or complex data structures may lower the usefulness of this strategy. Effectiveness: Defense in Depth Note: If a bug causes an attempted access of this pointer, then a NULL dereference could still lead to a crash or other unexpected behavior, but it will reduce or eliminate the risk of code execution.
7,094
krb5
5d2d9a1abe46a2c1a8614d4672d08d9d30a5f8bf
setup_server_realm(struct server_handle *handle, krb5_principal sprinc) { kdc_realm_t *newrealm; kdc_realm_t **kdc_realmlist = handle->kdc_realmlist; int kdc_numrealms = handle->kdc_numrealms; if (kdc_numrealms > 1) { if (!(newrealm = find_realm_data(handle, sprinc->realm.data, (krb5_ui_4) sprinc->realm.length))) return NULL; else return newrealm; } else return kdc_realmlist[0]; }
1
CVE-2013-1418
CWE-476
NULL Pointer Dereference
The product dereferences a pointer that it expects to be valid but is NULL.
Phase: Implementation If all pointers that could have been modified are checked for NULL before use, nearly all NULL pointer dereferences can be prevented. Phase: Requirements Select a programming language that is not susceptible to these issues. Phase: Implementation Check the results of all functions that return a value and verify that the value is non-null before acting upon it. Effectiveness: Moderate Note: Checking the return value of the function will typically be sufficient, however beware of race conditions (CWE-362) in a concurrent environment. This solution does not handle the use of improperly initialized variables (CWE-665). Phase: Architecture and Design Identify all variables and data stores that receive information from external sources, and apply input validation to make sure that they are only initialized to expected values. Phase: Implementation Explicitly initialize all variables and other data stores, either during declaration or just before the first usage.
7,087
ImageMagick6
0b7d3675438cbcde824e751895847a0794406e08
MagickExport MagickBooleanType AnnotateImage(Image *image, const DrawInfo *draw_info) { char *p, primitive[MaxTextExtent], *text, **textlist; DrawInfo *annotate, *annotate_info; GeometryInfo geometry_info; MagickBooleanType status; PointInfo offset; RectangleInfo geometry; register ssize_t i; TypeMetric metrics; size_t height, number_lines; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(draw_info != (DrawInfo *) NULL); assert(draw_info->signature == MagickCoreSignature); if (draw_info->text == (char *) NULL) return(MagickFalse); if (*draw_info->text == '\0') return(MagickTrue); annotate=CloneDrawInfo((ImageInfo *) NULL,draw_info); text=annotate->text; annotate->text=(char *) NULL; annotate_info=CloneDrawInfo((ImageInfo *) NULL,draw_info); number_lines=1; for (p=text; *p != '\0'; p++) if (*p == '\n') number_lines++; textlist=AcquireQuantumMemory(number_lines+1,sizeof(*textlist)); if (textlist == (char **) NULL) { annotate_info=DestroyDrawInfo(annotate_info); annotate=DestroyDrawInfo(annotate); return(MagickFalse); } p=text; for (i=0; i < number_lines; i++) { char *q; textlist[i]=p; for (q=p; *q != '\0'; q++) if ((*q == '\r') || (*q == '\n')) break; if (*q == '\r') { *q='\0'; q++; } *q='\0'; p=q+1; } textlist[i]=(char *) NULL; SetGeometry(image,&geometry); SetGeometryInfo(&geometry_info); if (annotate_info->geometry != (char *) NULL) { (void) ParsePageGeometry(image,annotate_info->geometry,&geometry, &image->exception); (void) ParseGeometry(annotate_info->geometry,&geometry_info); } if (SetImageStorageClass(image,DirectClass) == MagickFalse) { annotate_info=DestroyDrawInfo(annotate_info); annotate=DestroyDrawInfo(annotate); textlist=(char **) RelinquishMagickMemory(textlist); return(MagickFalse); } if (IsGrayColorspace(image->colorspace) != MagickFalse) (void) SetImageColorspace(image,sRGBColorspace); status=MagickTrue; (void) memset(&metrics,0,sizeof(metrics)); for (i=0; textlist[i] != (char *) NULL; i++) { if (*textlist[i] == '\0') continue; /* Position text relative to image. */ annotate_info->affine.tx=geometry_info.xi-image->page.x; annotate_info->affine.ty=geometry_info.psi-image->page.y; (void) CloneString(&annotate->text,textlist[i]); if ((metrics.width == 0) || (annotate->gravity != NorthWestGravity)) (void) GetTypeMetrics(image,annotate,&metrics); height=(ssize_t) (metrics.ascent-metrics.descent+ draw_info->interline_spacing+0.5); switch (annotate->gravity) { case UndefinedGravity: default: { offset.x=annotate_info->affine.tx+i*annotate_info->affine.ry*height; offset.y=annotate_info->affine.ty+i*annotate_info->affine.sy*height; break; } case NorthWestGravity: { offset.x=(geometry.width == 0 ? -1.0 : 1.0)*annotate_info->affine.tx+i* annotate_info->affine.ry*height+annotate_info->affine.ry* (metrics.ascent+metrics.descent); offset.y=(geometry.height == 0 ? -1.0 : 1.0)*annotate_info->affine.ty+i* annotate_info->affine.sy*height+annotate_info->affine.sy* metrics.ascent; break; } case NorthGravity: { offset.x=(geometry.width == 0 ? -1.0 : 1.0)*annotate_info->affine.tx+ geometry.width/2.0+i*annotate_info->affine.ry*height- annotate_info->affine.sx*metrics.width/2.0+annotate_info->affine.ry* (metrics.ascent+metrics.descent); offset.y=(geometry.height == 0 ? -1.0 : 1.0)*annotate_info->affine.ty+i* annotate_info->affine.sy*height+annotate_info->affine.sy* metrics.ascent-annotate_info->affine.rx*metrics.width/2.0; break; } case NorthEastGravity: { offset.x=(geometry.width == 0 ? 1.0 : -1.0)*annotate_info->affine.tx+ geometry.width+i*annotate_info->affine.ry*height- annotate_info->affine.sx*metrics.width+annotate_info->affine.ry* (metrics.ascent+metrics.descent)-1.0; offset.y=(geometry.height == 0 ? -1.0 : 1.0)*annotate_info->affine.ty+i* annotate_info->affine.sy*height+annotate_info->affine.sy* metrics.ascent-annotate_info->affine.rx*metrics.width; break; } case WestGravity: { offset.x=(geometry.width == 0 ? -1.0 : 1.0)*annotate_info->affine.tx+i* annotate_info->affine.ry*height+annotate_info->affine.ry* (metrics.ascent+metrics.descent-(number_lines-1.0)*height)/2.0; offset.y=(geometry.height == 0 ? -1.0 : 1.0)*annotate_info->affine.ty+ geometry.height/2.0+i*annotate_info->affine.sy*height+ annotate_info->affine.sy*(metrics.ascent+metrics.descent- (number_lines-1.0)*height)/2.0; break; } case StaticGravity: case CenterGravity: { offset.x=(geometry.width == 0 ? -1.0 : 1.0)*annotate_info->affine.tx+ geometry.width/2.0+i*annotate_info->affine.ry*height- annotate_info->affine.sx*metrics.width/2.0+annotate_info->affine.ry* (metrics.ascent+metrics.descent-(number_lines-1)*height)/2.0; offset.y=(geometry.height == 0 ? -1.0 : 1.0)*annotate_info->affine.ty+ geometry.height/2.0+i*annotate_info->affine.sy*height- annotate_info->affine.rx*metrics.width/2.0+annotate_info->affine.sy* (metrics.ascent+metrics.descent-(number_lines-1.0)*height)/2.0; break; } case EastGravity: { offset.x=(geometry.width == 0 ? 1.0 : -1.0)*annotate_info->affine.tx+ geometry.width+i*annotate_info->affine.ry*height- annotate_info->affine.sx*metrics.width+annotate_info->affine.ry* (metrics.ascent+metrics.descent-(number_lines-1.0)*height)/2.0-1.0; offset.y=(geometry.height == 0 ? -1.0 : 1.0)*annotate_info->affine.ty+ geometry.height/2.0+i*annotate_info->affine.sy*height- annotate_info->affine.rx*metrics.width+annotate_info->affine.sy* (metrics.ascent+metrics.descent-(number_lines-1.0)*height)/2.0; break; } case SouthWestGravity: { offset.x=(geometry.width == 0 ? -1.0 : 1.0)*annotate_info->affine.tx+i* annotate_info->affine.ry*height-annotate_info->affine.ry* (number_lines-1.0)*height; offset.y=(geometry.height == 0 ? 1.0 : -1.0)*annotate_info->affine.ty+ geometry.height+i*annotate_info->affine.sy*height- annotate_info->affine.sy*(number_lines-1.0)*height+metrics.descent; break; } case SouthGravity: { offset.x=(geometry.width == 0 ? -1.0 : 1.0)*annotate_info->affine.tx+ geometry.width/2.0+i*annotate_info->affine.ry*height- annotate_info->affine.sx*metrics.width/2.0-annotate_info->affine.ry* (number_lines-1.0)*height/2.0; offset.y=(geometry.height == 0 ? 1.0 : -1.0)*annotate_info->affine.ty+ geometry.height+i*annotate_info->affine.sy*height- annotate_info->affine.rx*metrics.width/2.0-annotate_info->affine.sy* (number_lines-1.0)*height+metrics.descent; break; } case SouthEastGravity: { offset.x=(geometry.width == 0 ? 1.0 : -1.0)*annotate_info->affine.tx+ geometry.width+i*annotate_info->affine.ry*height- annotate_info->affine.sx*metrics.width-annotate_info->affine.ry* (number_lines-1.0)*height-1.0; offset.y=(geometry.height == 0 ? 1.0 : -1.0)*annotate_info->affine.ty+ geometry.height+i*annotate_info->affine.sy*height- annotate_info->affine.rx*metrics.width-annotate_info->affine.sy* (number_lines-1.0)*height+metrics.descent; break; } } switch (annotate->align) { case LeftAlign: { offset.x=annotate_info->affine.tx+i*annotate_info->affine.ry*height; offset.y=annotate_info->affine.ty+i*annotate_info->affine.sy*height; break; } case CenterAlign: { offset.x=annotate_info->affine.tx+i*annotate_info->affine.ry*height- annotate_info->affine.sx*metrics.width/2.0; offset.y=annotate_info->affine.ty+i*annotate_info->affine.sy*height- annotate_info->affine.rx*metrics.width/2.0; break; } case RightAlign: { offset.x=annotate_info->affine.tx+i*annotate_info->affine.ry*height- annotate_info->affine.sx*metrics.width; offset.y=annotate_info->affine.ty+i*annotate_info->affine.sy*height- annotate_info->affine.rx*metrics.width; break; } default: break; } if (draw_info->undercolor.opacity != TransparentOpacity) { DrawInfo *undercolor_info; /* Text box. */ undercolor_info=CloneDrawInfo((ImageInfo *) NULL,(DrawInfo *) NULL); undercolor_info->fill=draw_info->undercolor; undercolor_info->affine=draw_info->affine; undercolor_info->affine.tx=offset.x-draw_info->affine.ry*metrics.ascent; undercolor_info->affine.ty=offset.y-draw_info->affine.sy*metrics.ascent; (void) FormatLocaleString(primitive,MaxTextExtent, "rectangle 0.0,0.0 %g,%g",metrics.origin.x,(double) height); (void) CloneString(&undercolor_info->primitive,primitive); (void) DrawImage(image,undercolor_info); (void) DestroyDrawInfo(undercolor_info); } annotate_info->affine.tx=offset.x; annotate_info->affine.ty=offset.y; (void) FormatLocaleString(primitive,MaxTextExtent,"stroke-width %g " "line 0,0 %g,0",metrics.underline_thickness,metrics.width); if (annotate->decorate == OverlineDecoration) { annotate_info->affine.ty-=(draw_info->affine.sy*(metrics.ascent+ metrics.descent-metrics.underline_position)); (void) CloneString(&annotate_info->primitive,primitive); (void) DrawImage(image,annotate_info); } else if (annotate->decorate == UnderlineDecoration) { annotate_info->affine.ty-=(draw_info->affine.sy* metrics.underline_position); (void) CloneString(&annotate_info->primitive,primitive); (void) DrawImage(image,annotate_info); } /* Annotate image with text. */ status=RenderType(image,annotate,&offset,&metrics); if (status == MagickFalse) break; if (annotate->decorate == LineThroughDecoration) { annotate_info->affine.ty-=(draw_info->affine.sy*(height+ metrics.underline_position+metrics.descent)/2.0); (void) CloneString(&annotate_info->primitive,primitive); (void) DrawImage(image,annotate_info); } } /* Relinquish resources. */ annotate_info=DestroyDrawInfo(annotate_info); annotate=DestroyDrawInfo(annotate); textlist=(char **) RelinquishMagickMemory(textlist); return(status); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
18,840
tensorflow
0657c83d08845cc434175934c642299de2c0f042
StatusOr<FullTypeDef> SpecializeType(const AttrSlice& attrs, const OpDef& op_def) { FullTypeDef ft; ft.set_type_id(TFT_PRODUCT); for (int i = 0; i < op_def.output_arg_size(); i++) { auto* t = ft.add_args(); *t = op_def.output_arg(i).experimental_full_type(); // Resolve dependent types. The convention for op registrations is to use // attributes as type variables. // See https://www.tensorflow.org/guide/create_op#type_polymorphism. // Once the op signature can be defined entirely in FullType, this // convention can be deprecated. // // Note: While this code performs some basic verifications, it generally // assumes consistent op defs and attributes. If more complete // verifications are needed, they should be done by separately, and in a // way that can be reused for type inference. for (int j = 0; j < t->args_size(); j++) { auto* arg = t->mutable_args(i); if (arg->type_id() == TFT_VAR) { const auto* attr = attrs.Find(arg->s()); if (attr == nullptr) { return Status( error::INVALID_ARGUMENT, absl::StrCat("Could not find an attribute for key ", arg->s())); } if (attr->value_case() == AttrValue::kList) { const auto& attr_list = attr->list(); arg->set_type_id(TFT_PRODUCT); for (int i = 0; i < attr_list.type_size(); i++) { map_dtype_to_tensor(attr_list.type(i), arg->add_args()); } } else if (attr->value_case() == AttrValue::kType) { map_dtype_to_tensor(attr->type(), arg); } else { return Status(error::UNIMPLEMENTED, absl::StrCat("unknown attribute type", attrs.DebugString(), " key=", arg->s())); } arg->clear_s(); } } } return ft; }
1
CVE-2022-23574
CWE-787
Out-of-bounds Write
The product writes data past the end, or before the beginning, of the intended buffer.
Phase: Requirements Strategy: Language Selection Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. For example, many languages that perform their own memory management, such as Java and Perl, are not subject to buffer overflows. Other languages, such as Ada and C#, typically provide overflow protection, but the protection can be disabled by the programmer. Be wary that a language's interface to native code may still be subject to overflows, even if the language itself is theoretically safe. Phase: Architecture and Design Strategy: Libraries or Frameworks Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. Examples include the Safe C String Library (SafeStr) by Messier and Viega [REF-57], and the Strsafe.h library from Microsoft [REF-56]. These libraries provide safer versions of overflow-prone string-handling functions. Note: This is not a complete solution, since many buffer overflows are not related to strings. Phases: Operation; Build and Compilation Strategy: Environment Hardening Use automatic buffer overflow detection mechanisms that are offered by certain compilers or compiler extensions. Examples include: the Microsoft Visual Studio /GS flag, Fedora/Red Hat FORTIFY_SOURCE GCC flag, StackGuard, and ProPolice, which provide various mechanisms including canary-based detection and range/index checking. D3-SFCV (Stack Frame Canary Validation) from D3FEND [REF-1334] discusses canary-based detection in detail. Effectiveness: Defense in Depth Note: This is not necessarily a complete solution, since these mechanisms only detect certain types of overflows. In addition, the result is still a denial of service, since the typical response is to exit the application. Phase: Implementation Consider adhering to the following rules when allocating and managing an application's memory: Double check that the buffer is as large as specified. When using functions that accept a number of bytes to copy, such as strncpy(), be aware that if the destination buffer size is equal to the source buffer size, it may not NULL-terminate the string. Check buffer boundaries if accessing the buffer in a loop and make sure there is no danger of writing past the allocated space. If necessary, truncate all input strings to a reasonable length before passing them to the copy and concatenation functions. Phases: Operation; Build and Compilation Strategy: Environment Hardening Run or compile the software using features or extensions that randomly arrange the positions of a program's executable and libraries in memory. Because this makes the addresses unpredictable, it can prevent an attacker from reliably jumping to exploitable code. Examples include Address Space Layout Randomization (ASLR) [REF-58] [REF-60] and Position-Independent Executables (PIE) [REF-64]. Imported modules may be similarly realigned if their default memory addresses conflict with other modules, in a process known as "rebasing" (for Windows) and "prelinking" (for Linux) [REF-1332] using randomly generated addresses. ASLR for libraries cannot be used in conjunction with prelink since it would require relocating the libraries at run-time, defeating the whole purpose of prelinking. For more information on these techniques see D3-SAOR (Segment Address Offset Randomization) from D3FEND [REF-1335]. Effectiveness: Defense in Depth Note: These techniques do not provide a complete solution. For instance, exploits frequently use a bug that discloses memory addresses in order to maximize reliability of code execution [REF-1337]. It has also been shown that a side-channel attack can bypass ASLR [REF-1333]. Phase: Operation Strategy: Environment Hardening Use a CPU and operating system that offers Data Execution Protection (using hardware NX or XD bits) or the equivalent techniques that simulate this feature in software, such as PaX [REF-60] [REF-61]. These techniques ensure that any instruction executed is exclusively at a memory address that is part of the code segment. For more information on these techniques see D3-PSEP (Process Segment Execution Prevention) from D3FEND [REF-1336]. Effectiveness: Defense in Depth Note: This is not a complete solution, since buffer overflows could be used to overwrite nearby variables to modify the software's state in dangerous ways. In addition, it cannot be used in cases in which self-modifying code is required. Finally, an attack could still cause a denial of service, since the typical response is to exit the application. Phase: Implementation Replace unbounded copy functions with analogous functions that support length arguments, such as strcpy with strncpy. Create these if they are not available. Effectiveness: Moderate Note: This approach is still susceptible to calculation errors, including issues such as off-by-one errors (CWE-193) and incorrectly calculating buffer lengths (CWE-131).
5,967
linux
ceabee6c59943bdd5e1da1a6a20dc7ee5f8113a2
static int genl_rcv_msg(struct sk_buff *skb, struct nlmsghdr *nlh, struct netlink_ext_ack *extack) { const struct genl_family *family; int err; family = genl_family_find_byid(nlh->nlmsg_type); if (family == NULL) return -ENOENT; if (!family->parallel_ops) genl_lock(); err = genl_family_rcv_msg(family, skb, nlh, extack); if (!family->parallel_ops) genl_unlock(); return err; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
11,951
haproxy
3f0e1ec70173593f4c2b3681b26c04a4ed5fc588
static int h2_frt_decode_headers(struct h2s *h2s, struct buffer *buf, int count) { struct h2c *h2c = h2s->h2c; const uint8_t *hdrs = (uint8_t *)h2c->dbuf->p; struct chunk *tmp = get_trash_chunk(); struct http_hdr list[MAX_HTTP_HDR * 2]; struct chunk *copy = NULL; int flen = h2c->dfl; int outlen = 0; int wrap; int try; if (!h2c->dfl) { h2s_error(h2s, H2_ERR_PROTOCOL_ERROR); // empty headers frame! h2c->st0 = H2_CS_FRAME_E; return 0; } if (h2c->dbuf->i < h2c->dfl && h2c->dbuf->i < h2c->dbuf->size) return 0; // incomplete input frame /* if the input buffer wraps, take a temporary copy of it (rare) */ wrap = h2c->dbuf->data + h2c->dbuf->size - h2c->dbuf->p; if (wrap < h2c->dfl) { copy = alloc_trash_chunk(); if (!copy) { h2c_error(h2c, H2_ERR_INTERNAL_ERROR); goto fail; } memcpy(copy->str, h2c->dbuf->p, wrap); memcpy(copy->str + wrap, h2c->dbuf->data, h2c->dfl - wrap); hdrs = (uint8_t *)copy->str; } /* The padlen is the first byte before data, and the padding appears * after data. padlen+data+padding are included in flen. */ if (h2c->dff & H2_F_HEADERS_PADDED) { h2c->dpl = *hdrs; if (h2c->dpl >= flen) { /* RFC7540#6.2 : pad length = length of frame payload or greater */ h2c_error(h2c, H2_ERR_PROTOCOL_ERROR); return 0; } flen -= h2c->dpl + 1; hdrs += 1; // skip Pad Length } /* Skip StreamDep and weight for now (we don't support PRIORITY) */ if (h2c->dff & H2_F_HEADERS_PRIORITY) { if (read_n32(hdrs) == h2s->id) { /* RFC7540#5.3.1 : stream dep may not depend on itself */ h2c_error(h2c, H2_ERR_PROTOCOL_ERROR); return 0;//goto fail_stream; } hdrs += 5; // stream dep = 4, weight = 1 flen -= 5; } /* FIXME: lack of END_HEADERS means there's a continuation frame, we * don't support this for now and can't even decompress so we have to * break the connection. */ if (!(h2c->dff & H2_F_HEADERS_END_HEADERS)) { h2c_error(h2c, H2_ERR_INTERNAL_ERROR); goto fail; } /* we can't retry a failed decompression operation so we must be very * careful not to take any risks. In practice the output buffer is * always empty except maybe for trailers, so these operations almost * never happen. */ if (unlikely(buf->o)) { /* need to let the output buffer flush and * mark the buffer for later wake up. */ goto fail; } if (unlikely(buffer_space_wraps(buf))) { /* it doesn't fit and the buffer is fragmented, * so let's defragment it and try again. */ buffer_slow_realign(buf); } /* first check if we have some room after p+i */ try = buf->data + buf->size - (buf->p + buf->i); /* otherwise continue between data and p-o */ if (try <= 0) { try = buf->p - (buf->data + buf->o); if (try <= 0) goto fail; } if (try > count) try = count; outlen = hpack_decode_frame(h2c->ddht, hdrs, flen, list, sizeof(list)/sizeof(list[0]), tmp); if (outlen < 0) { h2c_error(h2c, H2_ERR_COMPRESSION_ERROR); goto fail; } /* OK now we have our header list in <list> */ outlen = h2_make_h1_request(list, bi_end(buf), try); if (outlen < 0) { h2c_error(h2c, H2_ERR_COMPRESSION_ERROR); goto fail; } /* now consume the input data */ bi_del(h2c->dbuf, h2c->dfl); h2c->st0 = H2_CS_FRAME_H; buf->i += outlen; /* don't send it before returning data! * FIXME: should we instead try to send it much later, after the * response ? This would require that we keep a copy of it in h2s. */ if (h2c->dff & H2_F_HEADERS_END_STREAM) { h2s->cs->flags |= CS_FL_EOS; h2s->flags |= H2_SF_ES_RCVD; } leave: free_trash_chunk(copy); return outlen; fail: outlen = 0; goto leave; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
11,223
linux
cff109768b2d9c03095848f4cd4b0754117262aa
static int net_ctl_permissions(struct ctl_table_header *head, struct ctl_table *table) { struct net *net = container_of(head->set, struct net, sysctls); kuid_t root_uid = make_kuid(net->user_ns, 0); kgid_t root_gid = make_kgid(net->user_ns, 0); /* Allow network administrator to have same access as root. */ if (ns_capable(net->user_ns, CAP_NET_ADMIN) || uid_eq(root_uid, current_uid())) { int mode = (table->mode >> 6) & 7; return (mode << 6) | (mode << 3) | mode; } /* Allow netns root group to have the same assess as the root group */ if (gid_eq(root_gid, current_gid())) { int mode = (table->mode >> 3) & 7; return (mode << 3) | (mode << 3) | mode; } return table->mode; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
23,368
linux
b49a0e69a7b1a68c8d3f64097d06dabb770fec96
static int aspeed_lpc_ctrl_mmap(struct file *file, struct vm_area_struct *vma) { struct aspeed_lpc_ctrl *lpc_ctrl = file_aspeed_lpc_ctrl(file); unsigned long vsize = vma->vm_end - vma->vm_start; pgprot_t prot = vma->vm_page_prot; if (vma->vm_pgoff + vma_pages(vma) > lpc_ctrl->mem_size >> PAGE_SHIFT) return -EINVAL; /* ast2400/2500 AHB accesses are not cache coherent */ prot = pgprot_noncached(prot); if (remap_pfn_range(vma, vma->vm_start, (lpc_ctrl->mem_base >> PAGE_SHIFT) + vma->vm_pgoff, vsize, prot)) return -EAGAIN; return 0; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
12,258
openssl
470990fee0182566d439ef7e82d1abf18b7085d7
void dtls1_stop_timer(SSL *s) { /* Reset everything */ memset(&(s->d1->timeout), 0, sizeof(struct dtls1_timeout_st)); memset(&(s->d1->next_timeout), 0, sizeof(struct timeval)); s->d1->timeout_duration = 1; BIO_ctrl(SSL_get_rbio(s), BIO_CTRL_DGRAM_SET_NEXT_TIMEOUT, 0, &(s->d1->next_timeout)); /* Clear retransmission buffer */ dtls1_clear_record_buffer(s); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
11,409
kvm-guest-drivers-windows
fbfa4d1083ea84c5429992ca3e996d7d4fbc8238
void ParaNdis_DeleteQueue(PARANDIS_ADAPTER *pContext, struct virtqueue **ppq, tCompletePhysicalAddress *ppa) { if (*ppq) VirtIODeviceDeleteQueue(*ppq, NULL); *ppq = NULL; if (ppa->Virtual) ParaNdis_FreePhysicalMemory(pContext, ppa); RtlZeroMemory(ppa, sizeof(*ppa)); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
14,374
ghostscript
961b10cdd71403072fb99401a45f3bef6ce53626
xps_count_font_encodings(xps_font_t *font) { return font->cmapsubcount; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
19,574
linux
c919a3069c775c1c876bec55e00b2305d5125caa
static int gs_usb_probe(struct usb_interface *intf, const struct usb_device_id *id) { struct gs_usb *dev; int rc = -ENOMEM; unsigned int icount, i; struct gs_host_config hconf = { .byte_order = 0x0000beef, }; struct gs_device_config dconf; /* send host config */ rc = usb_control_msg(interface_to_usbdev(intf), usb_sndctrlpipe(interface_to_usbdev(intf), 0), GS_USB_BREQ_HOST_FORMAT, USB_DIR_OUT|USB_TYPE_VENDOR|USB_RECIP_INTERFACE, 1, intf->altsetting[0].desc.bInterfaceNumber, &hconf, sizeof(hconf), 1000); if (rc < 0) { dev_err(&intf->dev, "Couldn't send data format (err=%d)\n", rc); return rc; } /* read device config */ rc = usb_control_msg(interface_to_usbdev(intf), usb_rcvctrlpipe(interface_to_usbdev(intf), 0), GS_USB_BREQ_DEVICE_CONFIG, USB_DIR_IN|USB_TYPE_VENDOR|USB_RECIP_INTERFACE, 1, intf->altsetting[0].desc.bInterfaceNumber, &dconf, sizeof(dconf), 1000); if (rc < 0) { dev_err(&intf->dev, "Couldn't get device config: (err=%d)\n", rc); return rc; } icount = dconf.icount + 1; dev_info(&intf->dev, "Configuring for %d interfaces\n", icount); if (icount > GS_MAX_INTF) { dev_err(&intf->dev, "Driver cannot handle more that %d CAN interfaces\n", GS_MAX_INTF); return -EINVAL; } dev = kzalloc(sizeof(*dev), GFP_KERNEL); if (!dev) return -ENOMEM; init_usb_anchor(&dev->rx_submitted); atomic_set(&dev->active_channels, 0); usb_set_intfdata(intf, dev); dev->udev = interface_to_usbdev(intf); for (i = 0; i < icount; i++) { dev->canch[i] = gs_make_candev(i, intf, &dconf); if (IS_ERR_OR_NULL(dev->canch[i])) { /* save error code to return later */ rc = PTR_ERR(dev->canch[i]); /* on failure destroy previously created candevs */ icount = i; for (i = 0; i < icount; i++) gs_destroy_candev(dev->canch[i]); usb_kill_anchored_urbs(&dev->rx_submitted); kfree(dev); return rc; } dev->canch[i]->parent = dev; } return 0; }
1
CVE-2017-8066
CWE-119
Improper Restriction of Operations within the Bounds of a Memory Buffer
The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data.
Phase: Requirements Strategy: Language Selection Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. For example, many languages that perform their own memory management, such as Java and Perl, are not subject to buffer overflows. Other languages, such as Ada and C#, typically provide overflow protection, but the protection can be disabled by the programmer. Be wary that a language's interface to native code may still be subject to overflows, even if the language itself is theoretically safe. Phase: Architecture and Design Strategy: Libraries or Frameworks Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. Examples include the Safe C String Library (SafeStr) by Messier and Viega [REF-57], and the Strsafe.h library from Microsoft [REF-56]. These libraries provide safer versions of overflow-prone string-handling functions. Note: This is not a complete solution, since many buffer overflows are not related to strings. Phases: Operation; Build and Compilation Strategy: Environment Hardening Use automatic buffer overflow detection mechanisms that are offered by certain compilers or compiler extensions. Examples include: the Microsoft Visual Studio /GS flag, Fedora/Red Hat FORTIFY_SOURCE GCC flag, StackGuard, and ProPolice, which provide various mechanisms including canary-based detection and range/index checking. D3-SFCV (Stack Frame Canary Validation) from D3FEND [REF-1334] discusses canary-based detection in detail. Effectiveness: Defense in Depth Note: This is not necessarily a complete solution, since these mechanisms only detect certain types of overflows. In addition, the result is still a denial of service, since the typical response is to exit the application. Phase: Implementation Consider adhering to the following rules when allocating and managing an application's memory: Double check that the buffer is as large as specified. When using functions that accept a number of bytes to copy, such as strncpy(), be aware that if the destination buffer size is equal to the source buffer size, it may not NULL-terminate the string. Check buffer boundaries if accessing the buffer in a loop and make sure there is no danger of writing past the allocated space. If necessary, truncate all input strings to a reasonable length before passing them to the copy and concatenation functions. Phases: Operation; Build and Compilation Strategy: Environment Hardening Run or compile the software using features or extensions that randomly arrange the positions of a program's executable and libraries in memory. Because this makes the addresses unpredictable, it can prevent an attacker from reliably jumping to exploitable code. Examples include Address Space Layout Randomization (ASLR) [REF-58] [REF-60] and Position-Independent Executables (PIE) [REF-64]. Imported modules may be similarly realigned if their default memory addresses conflict with other modules, in a process known as "rebasing" (for Windows) and "prelinking" (for Linux) [REF-1332] using randomly generated addresses. ASLR for libraries cannot be used in conjunction with prelink since it would require relocating the libraries at run-time, defeating the whole purpose of prelinking. For more information on these techniques see D3-SAOR (Segment Address Offset Randomization) from D3FEND [REF-1335]. Effectiveness: Defense in Depth Note: These techniques do not provide a complete solution. For instance, exploits frequently use a bug that discloses memory addresses in order to maximize reliability of code execution [REF-1337]. It has also been shown that a side-channel attack can bypass ASLR [REF-1333] Phase: Operation Strategy: Environment Hardening Use a CPU and operating system that offers Data Execution Protection (using hardware NX or XD bits) or the equivalent techniques that simulate this feature in software, such as PaX [REF-60] [REF-61]. These techniques ensure that any instruction executed is exclusively at a memory address that is part of the code segment. For more information on these techniques see D3-PSEP (Process Segment Execution Prevention) from D3FEND [REF-1336]. Effectiveness: Defense in Depth Note: This is not a complete solution, since buffer overflows could be used to overwrite nearby variables to modify the software's state in dangerous ways. In addition, it cannot be used in cases in which self-modifying code is required. Finally, an attack could still cause a denial of service, since the typical response is to exit the application. Phase: Implementation Replace unbounded copy functions with analogous functions that support length arguments, such as strcpy with strncpy. Create these if they are not available. Effectiveness: Moderate Note: This approach is still susceptible to calculation errors, including issues such as off-by-one errors (CWE-193) and incorrectly calculating buffer lengths (CWE-131).
7,652
curl
curl-7_51_0-162-g3ab3c16
int test(char *URL) { int errors = 0; (void)URL; /* not used */ errors += test_weird_arguments(); errors += test_unsigned_short_formatting(); errors += test_signed_short_formatting(); errors += test_unsigned_int_formatting(); errors += test_signed_int_formatting(); errors += test_unsigned_long_formatting(); errors += test_signed_long_formatting(); errors += test_curl_off_t_formatting(); errors += test_string_formatting(); if(errors) return TEST_ERR_MAJOR_BAD; else return 0; }
1
CVE-2016-9586
CWE-119
Improper Restriction of Operations within the Bounds of a Memory Buffer
The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data.
Phase: Requirements Strategy: Language Selection Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. For example, many languages that perform their own memory management, such as Java and Perl, are not subject to buffer overflows. Other languages, such as Ada and C#, typically provide overflow protection, but the protection can be disabled by the programmer. Be wary that a language's interface to native code may still be subject to overflows, even if the language itself is theoretically safe. Phase: Architecture and Design Strategy: Libraries or Frameworks Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. Examples include the Safe C String Library (SafeStr) by Messier and Viega [REF-57], and the Strsafe.h library from Microsoft [REF-56]. These libraries provide safer versions of overflow-prone string-handling functions. Note: This is not a complete solution, since many buffer overflows are not related to strings. Phases: Operation; Build and Compilation Strategy: Environment Hardening Use automatic buffer overflow detection mechanisms that are offered by certain compilers or compiler extensions. Examples include: the Microsoft Visual Studio /GS flag, Fedora/Red Hat FORTIFY_SOURCE GCC flag, StackGuard, and ProPolice, which provide various mechanisms including canary-based detection and range/index checking. D3-SFCV (Stack Frame Canary Validation) from D3FEND [REF-1334] discusses canary-based detection in detail. Effectiveness: Defense in Depth Note: This is not necessarily a complete solution, since these mechanisms only detect certain types of overflows. In addition, the result is still a denial of service, since the typical response is to exit the application. Phase: Implementation Consider adhering to the following rules when allocating and managing an application's memory: Double check that the buffer is as large as specified. When using functions that accept a number of bytes to copy, such as strncpy(), be aware that if the destination buffer size is equal to the source buffer size, it may not NULL-terminate the string. Check buffer boundaries if accessing the buffer in a loop and make sure there is no danger of writing past the allocated space. If necessary, truncate all input strings to a reasonable length before passing them to the copy and concatenation functions. Phases: Operation; Build and Compilation Strategy: Environment Hardening Run or compile the software using features or extensions that randomly arrange the positions of a program's executable and libraries in memory. Because this makes the addresses unpredictable, it can prevent an attacker from reliably jumping to exploitable code. Examples include Address Space Layout Randomization (ASLR) [REF-58] [REF-60] and Position-Independent Executables (PIE) [REF-64]. Imported modules may be similarly realigned if their default memory addresses conflict with other modules, in a process known as "rebasing" (for Windows) and "prelinking" (for Linux) [REF-1332] using randomly generated addresses. ASLR for libraries cannot be used in conjunction with prelink since it would require relocating the libraries at run-time, defeating the whole purpose of prelinking. For more information on these techniques see D3-SAOR (Segment Address Offset Randomization) from D3FEND [REF-1335]. Effectiveness: Defense in Depth Note: These techniques do not provide a complete solution. For instance, exploits frequently use a bug that discloses memory addresses in order to maximize reliability of code execution [REF-1337]. It has also been shown that a side-channel attack can bypass ASLR [REF-1333] Phase: Operation Strategy: Environment Hardening Use a CPU and operating system that offers Data Execution Protection (using hardware NX or XD bits) or the equivalent techniques that simulate this feature in software, such as PaX [REF-60] [REF-61]. These techniques ensure that any instruction executed is exclusively at a memory address that is part of the code segment. For more information on these techniques see D3-PSEP (Process Segment Execution Prevention) from D3FEND [REF-1336]. Effectiveness: Defense in Depth Note: This is not a complete solution, since buffer overflows could be used to overwrite nearby variables to modify the software's state in dangerous ways. In addition, it cannot be used in cases in which self-modifying code is required. Finally, an attack could still cause a denial of service, since the typical response is to exit the application. Phase: Implementation Replace unbounded copy functions with analogous functions that support length arguments, such as strcpy with strncpy. Create these if they are not available. Effectiveness: Moderate Note: This approach is still susceptible to calculation errors, including issues such as off-by-one errors (CWE-193) and incorrectly calculating buffer lengths (CWE-131).
5,605
sqlite
54d501092d88c0cf89bec4279951f548fb0b8618
static u32 zipfileGetU32(const u8 *aBuf){ return ((u32)(aBuf[3]) << 24) + ((u32)(aBuf[2]) << 16) + ((u32)(aBuf[1]) << 8) + ((u32)(aBuf[0]) << 0); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
16,603
Android
04839626ed859623901ebd3a5fd483982186b59d
BlockEntry::BlockEntry(Cluster* p, long idx) : m_pCluster(p), m_index(idx) { }
1
CVE-2016-1621
CWE-119
Improper Restriction of Operations within the Bounds of a Memory Buffer
The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data.
Phase: Requirements Strategy: Language Selection Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. For example, many languages that perform their own memory management, such as Java and Perl, are not subject to buffer overflows. Other languages, such as Ada and C#, typically provide overflow protection, but the protection can be disabled by the programmer. Be wary that a language's interface to native code may still be subject to overflows, even if the language itself is theoretically safe. Phase: Architecture and Design Strategy: Libraries or Frameworks Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. Examples include the Safe C String Library (SafeStr) by Messier and Viega [REF-57], and the Strsafe.h library from Microsoft [REF-56]. These libraries provide safer versions of overflow-prone string-handling functions. Note: This is not a complete solution, since many buffer overflows are not related to strings. Phases: Operation; Build and Compilation Strategy: Environment Hardening Use automatic buffer overflow detection mechanisms that are offered by certain compilers or compiler extensions. Examples include: the Microsoft Visual Studio /GS flag, Fedora/Red Hat FORTIFY_SOURCE GCC flag, StackGuard, and ProPolice, which provide various mechanisms including canary-based detection and range/index checking. D3-SFCV (Stack Frame Canary Validation) from D3FEND [REF-1334] discusses canary-based detection in detail. Effectiveness: Defense in Depth Note: This is not necessarily a complete solution, since these mechanisms only detect certain types of overflows. In addition, the result is still a denial of service, since the typical response is to exit the application. Phase: Implementation Consider adhering to the following rules when allocating and managing an application's memory: Double check that the buffer is as large as specified. When using functions that accept a number of bytes to copy, such as strncpy(), be aware that if the destination buffer size is equal to the source buffer size, it may not NULL-terminate the string. Check buffer boundaries if accessing the buffer in a loop and make sure there is no danger of writing past the allocated space. If necessary, truncate all input strings to a reasonable length before passing them to the copy and concatenation functions. Phases: Operation; Build and Compilation Strategy: Environment Hardening Run or compile the software using features or extensions that randomly arrange the positions of a program's executable and libraries in memory. Because this makes the addresses unpredictable, it can prevent an attacker from reliably jumping to exploitable code. Examples include Address Space Layout Randomization (ASLR) [REF-58] [REF-60] and Position-Independent Executables (PIE) [REF-64]. Imported modules may be similarly realigned if their default memory addresses conflict with other modules, in a process known as "rebasing" (for Windows) and "prelinking" (for Linux) [REF-1332] using randomly generated addresses. ASLR for libraries cannot be used in conjunction with prelink since it would require relocating the libraries at run-time, defeating the whole purpose of prelinking. For more information on these techniques see D3-SAOR (Segment Address Offset Randomization) from D3FEND [REF-1335]. Effectiveness: Defense in Depth Note: These techniques do not provide a complete solution. For instance, exploits frequently use a bug that discloses memory addresses in order to maximize reliability of code execution [REF-1337]. It has also been shown that a side-channel attack can bypass ASLR [REF-1333] Phase: Operation Strategy: Environment Hardening Use a CPU and operating system that offers Data Execution Protection (using hardware NX or XD bits) or the equivalent techniques that simulate this feature in software, such as PaX [REF-60] [REF-61]. These techniques ensure that any instruction executed is exclusively at a memory address that is part of the code segment. For more information on these techniques see D3-PSEP (Process Segment Execution Prevention) from D3FEND [REF-1336]. Effectiveness: Defense in Depth Note: This is not a complete solution, since buffer overflows could be used to overwrite nearby variables to modify the software's state in dangerous ways. In addition, it cannot be used in cases in which self-modifying code is required. Finally, an attack could still cause a denial of service, since the typical response is to exit the application. Phase: Implementation Replace unbounded copy functions with analogous functions that support length arguments, such as strcpy with strncpy. Create these if they are not available. Effectiveness: Moderate Note: This approach is still susceptible to calculation errors, including issues such as off-by-one errors (CWE-193) and incorrectly calculating buffer lengths (CWE-131).
7,049
Android
122feb9a0b04290f55183ff2f0384c6c53756bd8
static jboolean enableNative(JNIEnv* env, jobject obj) { ALOGV("%s:",__FUNCTION__); jboolean result = JNI_FALSE; if (!sBluetoothInterface) return result; int ret = sBluetoothInterface->enable(); result = (ret == BT_STATUS_SUCCESS || ret == BT_STATUS_DONE) ? JNI_TRUE : JNI_FALSE; return result; }
1
CVE-2016-3760
CWE-20
Improper Input Validation
The product receives input or data, but it does not validate or incorrectly validates that the input has the properties that are required to process the data safely and correctly.
Phase: Architecture and Design Strategy: Attack Surface Reduction Consider using language-theoretic security (LangSec) techniques that characterize inputs using a formal language and build "recognizers" for that language. This effectively requires parsing to be a distinct layer that effectively enforces a boundary between raw input and internal data representations, instead of allowing parser code to be scattered throughout the program, where it could be subject to errors or inconsistencies that create weaknesses. [REF-1109] [REF-1110] [REF-1111] Phase: Architecture and Design Strategy: Libraries or Frameworks Use an input validation framework such as Struts or the OWASP ESAPI Validation API. Note that using a framework does not automatically address all input validation problems; be mindful of weaknesses that could arise from misusing the framework itself (CWE-1173). Phases: Architecture and Design; Implementation Strategy: Attack Surface Reduction Understand all the potential areas where untrusted inputs can enter your software: parameters or arguments, cookies, anything read from the network, environment variables, reverse DNS lookups, query results, request headers, URL components, e-mail, files, filenames, databases, and any external systems that provide data to the application. Remember that such inputs may be obtained indirectly through API calls. Phase: Implementation Strategy: Input Validation Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a list of acceptable inputs that strictly conform to specifications. Reject any input that does not strictly conform to specifications, or transform it into something that does. When performing input validation, consider all potentially relevant properties, including length, type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency across related fields, and conformance to business rules. As an example of business rule logic, "boat" may be syntactically valid because it only contains alphanumeric characters, but it is not valid if the input is only expected to contain colors such as "red" or "blue." Do not rely exclusively on looking for malicious or malformed inputs. This is likely to miss at least one undesirable input, especially if the code's environment changes. This can give attackers enough room to bypass the intended validation. However, denylists can be useful for detecting potential attacks or determining which inputs are so malformed that they should be rejected outright. Effectiveness: High Phase: Architecture and Design For any security checks that are performed on the client side, ensure that these checks are duplicated on the server side, in order to avoid CWE-602. Attackers can bypass the client-side checks by modifying values after the checks have been performed, or by changing the client to remove the client-side checks entirely. Then, these modified values would be submitted to the server. Even though client-side checks provide minimal benefits with respect to server-side security, they are still useful. First, they can support intrusion detection. If the server receives input that should have been rejected by the client, then it may be an indication of an attack. Second, client-side error-checking can provide helpful feedback to the user about the expectations for valid input. Third, there may be a reduction in server-side processing time for accidental input errors, although this is typically a small savings. Phase: Implementation When your application combines data from multiple sources, perform the validation after the sources have been combined. The individual data elements may pass the validation step but violate the intended restrictions after they have been combined. Phase: Implementation Be especially careful to validate all input when invoking code that crosses language boundaries, such as from an interpreted language to native code. This could create an unexpected interaction between the language boundaries. Ensure that you are not violating any of the expectations of the language with which you are interfacing. For example, even though Java may not be susceptible to buffer overflows, providing a large argument in a call to native code might trigger an overflow. Phase: Implementation Directly convert your input type into the expected data type, such as using a conversion function that translates a string into a number. After converting to the expected data type, ensure that the input's values fall within the expected range of allowable values and that multi-field consistencies are maintained. Phase: Implementation Inputs should be decoded and canonicalized to the application's current internal representation before being validated (CWE-180, CWE-181). Make sure that your application does not inadvertently decode the same input twice (CWE-174). Such errors could be used to bypass allowlist schemes by introducing dangerous inputs after they have been checked. Use libraries such as the OWASP ESAPI Canonicalization control. Consider performing repeated canonicalization until your input does not change any more. This will avoid double-decoding and similar scenarios, but it might inadvertently modify inputs that are allowed to contain properly-encoded dangerous content. Phase: Implementation When exchanging data between components, ensure that both components are using the same character encoding. Ensure that the proper encoding is applied at each interface. Explicitly set the encoding you are using whenever the protocol allows you to do so.
0
Android
7a3246b870ddd11861eda2ab458b11d723c7f62c
ID3::getAlbumArt(size_t *length, String8 *mime) const { *length = 0; mime->setTo(""); Iterator it( *this, (mVersion == ID3_V2_3 || mVersion == ID3_V2_4) ? "APIC" : "PIC"); while (!it.done()) { size_t size; const uint8_t *data = it.getData(&size); if (!data) { return NULL; } if (mVersion == ID3_V2_3 || mVersion == ID3_V2_4) { uint8_t encoding = data[0]; mime->setTo((const char *)&data[1]); size_t mimeLen = strlen((const char *)&data[1]) + 1; #if 0 uint8_t picType = data[1 + mimeLen]; if (picType != 0x03) { it.next(); continue; } #endif size_t descLen = StringSize(&data[2 + mimeLen], encoding); if (size < 2 || size - 2 < mimeLen || size - 2 - mimeLen < descLen) { ALOGW("bogus album art sizes"); return NULL; } *length = size - 2 - mimeLen - descLen; return &data[2 + mimeLen + descLen]; } else { uint8_t encoding = data[0]; if (!memcmp(&data[1], "PNG", 3)) { mime->setTo("image/png"); } else if (!memcmp(&data[1], "JPG", 3)) { mime->setTo("image/jpeg"); } else if (!memcmp(&data[1], "-->", 3)) { mime->setTo("text/plain"); } else { return NULL; } #if 0 uint8_t picType = data[4]; if (picType != 0x03) { it.next(); continue; } #endif size_t descLen = StringSize(&data[5], encoding); *length = size - 5 - descLen; return &data[5 + descLen]; } } return NULL; }
1
CVE-2017-0397
CWE-200
Exposure of Sensitive Information to an Unauthorized Actor
The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information.
Phase: Architecture and Design Strategy: Separation of Privilege Compartmentalize the system to have "safe" areas where trust boundaries can be unambiguously drawn. Do not allow sensitive data to go outside of the trust boundary and always be careful when interfacing with a compartment outside of the safe area. Ensure that appropriate compartmentalization is built into the system design, and the compartmentalization allows for and reinforces privilege separation functionality. Architects and designers should rely on the principle of least privilege to decide the appropriate time to use privileges and the time to drop privileges.
3,885
Android
659030a2e80c38fb8da0a4eb68695349eec6778b
void res_clear_info(vorbis_info_residue *info){ if(info){ if(info->stagemasks)_ogg_free(info->stagemasks); if(info->stagebooks)_ogg_free(info->stagebooks); memset(info,0,sizeof(*info)); } }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
23,620
linux
4edbe1d7bcffcd6269f3b5eb63f710393ff2ec7a
static void list_version_get_info(struct target_type *tt, void *param) { struct vers_iter *info = param; /* Check space - it might have changed since the first iteration */ if ((char *)info->vers + sizeof(tt->version) + strlen(tt->name) + 1 > info->end) { info->flags = DM_BUFFER_FULL_FLAG; return; } if (info->old_vers) info->old_vers->next = (uint32_t) ((void *)info->vers - (void *)info->old_vers); info->vers->version[0] = tt->version[0]; info->vers->version[1] = tt->version[1]; info->vers->version[2] = tt->version[2]; info->vers->next = 0; strcpy(info->vers->name, tt->name); info->old_vers = info->vers; info->vers = align_ptr(((void *) ++info->vers) + strlen(tt->name) + 1); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
15,660
tensorflow
6da6620efad397c85493b8f8667b821403516708
void Compute(OpKernelContext* ctx) override { const Tensor& input = ctx->input(0); const Tensor& input_min_range = ctx->input(1); const Tensor& input_max_range = ctx->input(2); int num_slices = 1; if (axis_ > -1) { num_slices = input.dim_size(axis_); } const TensorShape& minmax_shape = ctx->input(1).shape(); Tensor* output = nullptr; OP_REQUIRES_OK(ctx, ctx->allocate_output(0, input.shape(), &output)); Tensor* output_min_tensor = nullptr; Tensor* output_max_tensor = nullptr; if (num_slices == 1) { OP_REQUIRES_OK(ctx, ctx->allocate_output(1, {}, &output_min_tensor)); OP_REQUIRES_OK(ctx, ctx->allocate_output(2, {}, &output_max_tensor)); const float min_range = input_min_range.template flat<float>()(0); const float max_range = input_max_range.template flat<float>()(0); QuantizeTensor(ctx, input, min_range, max_range, output, output_min_tensor, output_max_tensor); return; } OP_REQUIRES(ctx, mode_ != QUANTIZE_MODE_MIN_FIRST, errors::Unimplemented("MIN_FIRST mode is not implemented for " "Quantize with axis != -1.")); OP_REQUIRES_OK(ctx, ctx->allocate_output(1, minmax_shape, &output_min_tensor)); OP_REQUIRES_OK(ctx, ctx->allocate_output(2, minmax_shape, &output_max_tensor)); auto input_tensor = input.template flat_inner_outer_dims<float, 3>(axis_ - 1); int64_t pre_dim = 1, post_dim = 1; for (int i = 0; i < axis_; ++i) { pre_dim *= output->dim_size(i); } for (int i = axis_ + 1; i < output->dims(); ++i) { post_dim *= output->dim_size(i); } auto output_tensor = output->template bit_casted_shaped<T, 3>( {pre_dim, num_slices, post_dim}); auto min_ranges = input_min_range.template vec<float>(); auto max_ranges = input_max_range.template vec<float>(); for (int i = 0; i < num_slices; ++i) { QuantizeSlice(ctx->eigen_device<Device>(), ctx, input_tensor.template chip<1>(i), min_ranges(i), max_ranges(i), output_tensor.template chip<1>(i), &output_min_tensor->flat<float>()(i), &output_max_tensor->flat<float>()(i)); } }
1
CVE-2021-37663
CWE-476
NULL Pointer Dereference
The product dereferences a pointer that it expects to be valid but is NULL.
Phase: Implementation If all pointers that could have been modified are checked for NULL before use, nearly all NULL pointer dereferences can be prevented. Phase: Requirements Select a programming language that is not susceptible to these issues. Phase: Implementation Check the results of all functions that return a value and verify that the value is non-null before acting upon it. Effectiveness: Moderate Note: Checking the return value of the function will typically be sufficient, however beware of race conditions (CWE-362) in a concurrent environment. This solution does not handle the use of improperly initialized variables (CWE-665). Phase: Architecture and Design Identify all variables and data stores that receive information from external sources, and apply input validation to make sure that they are only initialized to expected values. Phase: Implementation Explicitly initialize all variables and other data stores, either during declaration or just before the first usage.
8,436
linux
604c499cbbcc3d5fe5fb8d53306aa0fae1990109
static inline void put_free_pages(struct xen_blkif *blkif, struct page **page, int num) { unsigned long flags; int i; spin_lock_irqsave(&blkif->free_pages_lock, flags); for (i = 0; i < num; i++) list_add(&page[i]->lru, &blkif->free_pages); blkif->free_pages_num += num; spin_unlock_irqrestore(&blkif->free_pages_lock, flags); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
12,772
neomutt
6296f7153f0c9d5e5cd3aaf08f9731e56621bdd3
static int nntp_hcache_namer(const char *path, char *dest, size_t destlen) { return snprintf(dest, destlen, "%s.hcache", path); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
22,664
Chrome
244c78b3f737f2cacab2d212801b0524cbcc3a7b
void BrowserPolicyConnector::SetDeviceCredentials( const std::string& owner_email, const std::string& token, TokenType token_type) { #if defined(OS_CHROMEOS) if (device_data_store_.get()) { device_data_store_->set_user_name(owner_email); switch (token_type) { case TOKEN_TYPE_OAUTH: device_data_store_->SetOAuthToken(token); break; case TOKEN_TYPE_GAIA: device_data_store_->SetGaiaToken(token); break; default: NOTREACHED() << "Invalid token type " << token_type; } } #endif }
1
CVE-2011-2880
CWE-399
Resource Management Errors
Weaknesses in this category are related to improper management of system resources.
Not Found in CWE Page
1,036
linux
b22f5126a24b3b2f15448c3f2a254fc10cbc2b92
static bool dccp_pkt_to_tuple(const struct sk_buff *skb, unsigned int dataoff, struct nf_conntrack_tuple *tuple) { struct dccp_hdr _hdr, *dh; dh = skb_header_pointer(skb, dataoff, sizeof(_hdr), &_hdr); if (dh == NULL) return false; tuple->src.u.dccp.port = dh->dccph_sport; tuple->dst.u.dccp.port = dh->dccph_dport; return true; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
15,106
openjpeg
15f081c89650dccee4aa4ae66f614c3fdb268767
void color_apply_icc_profile(opj_image_t *image) { cmsHPROFILE in_prof, out_prof; cmsHTRANSFORM transform; cmsColorSpaceSignature in_space, out_space; cmsUInt32Number intent, in_type, out_type; int *r, *g, *b; size_t nr_samples; int prec, i, max, max_w, max_h, ok = 0; OPJ_COLOR_SPACE new_space; in_prof = cmsOpenProfileFromMem(image->icc_profile_buf, image->icc_profile_len); #ifdef DEBUG_PROFILE FILE *icm = fopen("debug.icm","wb"); fwrite( image->icc_profile_buf,1, image->icc_profile_len,icm); fclose(icm); #endif if(in_prof == NULL) return; in_space = cmsGetPCS(in_prof); out_space = cmsGetColorSpace(in_prof); intent = cmsGetHeaderRenderingIntent(in_prof); max_w = (int)image->comps[0].w; max_h = (int)image->comps[0].h; prec = (int)image->comps[0].prec; if(out_space == cmsSigRgbData) /* enumCS 16 */ { if( prec <= 8 ) { in_type = TYPE_RGB_8; out_type = TYPE_RGB_8; } else { in_type = TYPE_RGB_16; out_type = TYPE_RGB_16; } out_prof = cmsCreate_sRGBProfile(); new_space = OPJ_CLRSPC_SRGB; } else if(out_space == cmsSigGrayData) /* enumCS 17 */ { in_type = TYPE_GRAY_8; out_type = TYPE_RGB_8; out_prof = cmsCreate_sRGBProfile(); new_space = OPJ_CLRSPC_SRGB; } else if(out_space == cmsSigYCbCrData) /* enumCS 18 */ { in_type = TYPE_YCbCr_16; out_type = TYPE_RGB_16; out_prof = cmsCreate_sRGBProfile(); new_space = OPJ_CLRSPC_SRGB; } else { #ifdef DEBUG_PROFILE fprintf(stderr,"%s:%d: color_apply_icc_profile\n\tICC Profile has unknown " "output colorspace(%#x)(%c%c%c%c)\n\tICC Profile ignored.\n", __FILE__,__LINE__,out_space, (out_space>>24) & 0xff,(out_space>>16) & 0xff, (out_space>>8) & 0xff, out_space & 0xff); #endif cmsCloseProfile(in_prof); return; } if(out_prof == NULL) { cmsCloseProfile(in_prof); return; } #ifdef DEBUG_PROFILE fprintf(stderr,"%s:%d:color_apply_icc_profile\n\tchannels(%d) prec(%d) w(%d) h(%d)" "\n\tprofile: in(%p) out(%p)\n",__FILE__,__LINE__,image->numcomps,prec, max_w,max_h, (void*)in_prof,(void*)out_prof); fprintf(stderr,"\trender_intent (%u)\n\t" "color_space: in(%#x)(%c%c%c%c) out:(%#x)(%c%c%c%c)\n\t" " type: in(%u) out:(%u)\n", intent, in_space, (in_space>>24) & 0xff,(in_space>>16) & 0xff, (in_space>>8) & 0xff, in_space & 0xff, out_space, (out_space>>24) & 0xff,(out_space>>16) & 0xff, (out_space>>8) & 0xff, out_space & 0xff, in_type,out_type ); #else (void)prec; (void)in_space; #endif /* DEBUG_PROFILE */ transform = cmsCreateTransform(in_prof, in_type, out_prof, out_type, intent, 0); #ifdef OPJ_HAVE_LIBLCMS2 /* Possible for: LCMS_VERSION >= 2000 :*/ cmsCloseProfile(in_prof); cmsCloseProfile(out_prof); #endif if(transform == NULL) { #ifdef DEBUG_PROFILE fprintf(stderr,"%s:%d:color_apply_icc_profile\n\tcmsCreateTransform failed. " "ICC Profile ignored.\n",__FILE__,__LINE__); #endif #ifdef OPJ_HAVE_LIBLCMS1 cmsCloseProfile(in_prof); cmsCloseProfile(out_prof); #endif return; } if(image->numcomps > 2)/* RGB, RGBA */ { if( prec <= 8 ) { unsigned char *inbuf, *outbuf, *in, *out; max = max_w * max_h; nr_samples = (size_t)(max * 3 * sizeof(unsigned char)); in = inbuf = (unsigned char*)malloc(nr_samples); out = outbuf = (unsigned char*)malloc(nr_samples); if(inbuf == NULL || outbuf == NULL) goto fails0; r = image->comps[0].data; g = image->comps[1].data; b = image->comps[2].data; for(i = 0; i < max; ++i) { *in++ = (unsigned char)*r++; *in++ = (unsigned char)*g++; *in++ = (unsigned char)*b++; } cmsDoTransform(transform, inbuf, outbuf, (cmsUInt32Number)max); r = image->comps[0].data; g = image->comps[1].data; b = image->comps[2].data; for(i = 0; i < max; ++i) { *r++ = (int)*out++; *g++ = (int)*out++; *b++ = (int)*out++; } ok = 1; fails0: if(inbuf) free(inbuf); if(outbuf) free(outbuf); } else /* prec > 8 */ { unsigned short *inbuf, *outbuf, *in, *out; max = max_w * max_h; nr_samples = (size_t)(max * 3 * sizeof(unsigned short)); in = inbuf = (unsigned short*)malloc(nr_samples); out = outbuf = (unsigned short*)malloc(nr_samples); if(inbuf == NULL || outbuf == NULL) goto fails1; r = image->comps[0].data; g = image->comps[1].data; b = image->comps[2].data; for(i = 0; i < max; ++i) { *in++ = (unsigned short)*r++; *in++ = (unsigned short)*g++; *in++ = (unsigned short)*b++; } cmsDoTransform(transform, inbuf, outbuf, (cmsUInt32Number)max); r = image->comps[0].data; g = image->comps[1].data; b = image->comps[2].data; for(i = 0; i < max; ++i) { *r++ = (int)*out++; *g++ = (int)*out++; *b++ = (int)*out++; } ok = 1; fails1: if(inbuf) free(inbuf); if(outbuf) free(outbuf); } } else /* image->numcomps <= 2 : GRAY, GRAYA */ { if(prec <= 8) { unsigned char *in, *inbuf, *out, *outbuf; opj_image_comp_t *new_comps; max = max_w * max_h; nr_samples = (size_t)(max * 3 * sizeof(unsigned char)); in = inbuf = (unsigned char*)malloc(nr_samples); out = outbuf = (unsigned char*)malloc(nr_samples); g = (int*)calloc((size_t)max, sizeof(int)); b = (int*)calloc((size_t)max, sizeof(int)); if(inbuf == NULL || outbuf == NULL || g == NULL || b == NULL) goto fails2; new_comps = (opj_image_comp_t*) realloc(image->comps, (image->numcomps+2)*sizeof(opj_image_comp_t)); if(new_comps == NULL) goto fails2; image->comps = new_comps; if(image->numcomps == 2) image->comps[3] = image->comps[1]; image->comps[1] = image->comps[0]; image->comps[2] = image->comps[0]; image->comps[1].data = g; image->comps[2].data = b; image->numcomps += 2; r = image->comps[0].data; for(i = 0; i < max; ++i) { *in++ = (unsigned char)*r++; } cmsDoTransform(transform, inbuf, outbuf, (cmsUInt32Number)max); r = image->comps[0].data; g = image->comps[1].data; b = image->comps[2].data; for(i = 0; i < max; ++i) { *r++ = (int)*out++; *g++ = (int)*out++; *b++ = (int)*out++; } r = g = b = NULL; ok = 1; fails2: if(inbuf) free(inbuf); if(outbuf) free(outbuf); if(g) free(g); if(b) free(b); } else /* prec > 8 */ { unsigned short *in, *inbuf, *out, *outbuf; opj_image_comp_t *new_comps; max = max_w * max_h; nr_samples = (size_t)(max * 3 * sizeof(unsigned short)); in = inbuf = (unsigned short*)malloc(nr_samples); out = outbuf = (unsigned short*)malloc(nr_samples); g = (int*)calloc((size_t)max, sizeof(int)); b = (int*)calloc((size_t)max, sizeof(int)); if(inbuf == NULL || outbuf == NULL || g == NULL || b == NULL) goto fails3; new_comps = (opj_image_comp_t*) realloc(image->comps, (image->numcomps+2)*sizeof(opj_image_comp_t)); if(new_comps == NULL) goto fails3; image->comps = new_comps; if(image->numcomps == 2) image->comps[3] = image->comps[1]; image->comps[1] = image->comps[0]; image->comps[2] = image->comps[0]; image->comps[1].data = g; image->comps[2].data = b; image->numcomps += 2; r = image->comps[0].data; for(i = 0; i < max; ++i) { *in++ = (unsigned short)*r++; } cmsDoTransform(transform, inbuf, outbuf, (cmsUInt32Number)max); r = image->comps[0].data; g = image->comps[1].data; b = image->comps[2].data; for(i = 0; i < max; ++i) { *r++ = (int)*out++; *g++ = (int)*out++; *b++ = (int)*out++; } r = g = b = NULL; ok = 1; fails3: if(inbuf) free(inbuf); if(outbuf) free(outbuf); if(g) free(g); if(b) free(b); } }/* if(image->numcomps > 2) */ cmsDeleteTransform(transform); #ifdef OPJ_HAVE_LIBLCMS1 cmsCloseProfile(in_prof); cmsCloseProfile(out_prof); #endif if(ok) { image->color_space = new_space; } }/* color_apply_icc_profile() */
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
18,720
linux
206a81c18401c0cde6e579164f752c4b147324ce
int lzo1x_decompress_safe(const unsigned char *in, size_t in_len, unsigned char *out, size_t *out_len) { unsigned char *op; const unsigned char *ip; size_t t, next; size_t state = 0; const unsigned char *m_pos; const unsigned char * const ip_end = in + in_len; unsigned char * const op_end = out + *out_len; op = out; ip = in; if (unlikely(in_len < 3)) goto input_overrun; if (*ip > 17) { t = *ip++ - 17; if (t < 4) { next = t; goto match_next; } goto copy_literal_run; } for (;;) { t = *ip++; if (t < 16) { if (likely(state == 0)) { if (unlikely(t == 0)) { while (unlikely(*ip == 0)) { t += 255; ip++; NEED_IP(1, 0); } t += 15 + *ip++; } t += 3; copy_literal_run: #if defined(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS) if (likely(HAVE_IP(t, 15) && HAVE_OP(t, 15))) { const unsigned char *ie = ip + t; unsigned char *oe = op + t; do { COPY8(op, ip); op += 8; ip += 8; COPY8(op, ip); op += 8; ip += 8; } while (ip < ie); ip = ie; op = oe; } else #endif { NEED_OP(t, 0); NEED_IP(t, 3); do { *op++ = *ip++; } while (--t > 0); } state = 4; continue; } else if (state != 4) { next = t & 3; m_pos = op - 1; m_pos -= t >> 2; m_pos -= *ip++ << 2; TEST_LB(m_pos); NEED_OP(2, 0); op[0] = m_pos[0]; op[1] = m_pos[1]; op += 2; goto match_next; } else { next = t & 3; m_pos = op - (1 + M2_MAX_OFFSET); m_pos -= t >> 2; m_pos -= *ip++ << 2; t = 3; } } else if (t >= 64) { next = t & 3; m_pos = op - 1; m_pos -= (t >> 2) & 7; m_pos -= *ip++ << 3; t = (t >> 5) - 1 + (3 - 1); } else if (t >= 32) { t = (t & 31) + (3 - 1); if (unlikely(t == 2)) { while (unlikely(*ip == 0)) { t += 255; ip++; NEED_IP(1, 0); } t += 31 + *ip++; NEED_IP(2, 0); } m_pos = op - 1; next = get_unaligned_le16(ip); ip += 2; m_pos -= next >> 2; next &= 3; } else { m_pos = op; m_pos -= (t & 8) << 11; t = (t & 7) + (3 - 1); if (unlikely(t == 2)) { while (unlikely(*ip == 0)) { t += 255; ip++; NEED_IP(1, 0); } t += 7 + *ip++; NEED_IP(2, 0); } next = get_unaligned_le16(ip); ip += 2; m_pos -= next >> 2; next &= 3; if (m_pos == op) goto eof_found; m_pos -= 0x4000; } TEST_LB(m_pos); #if defined(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS) if (op - m_pos >= 8) { unsigned char *oe = op + t; if (likely(HAVE_OP(t, 15))) { do { COPY8(op, m_pos); op += 8; m_pos += 8; COPY8(op, m_pos); op += 8; m_pos += 8; } while (op < oe); op = oe; if (HAVE_IP(6, 0)) { state = next; COPY4(op, ip); op += next; ip += next; continue; } } else { NEED_OP(t, 0); do { *op++ = *m_pos++; } while (op < oe); } } else #endif { unsigned char *oe = op + t; NEED_OP(t, 0); op[0] = m_pos[0]; op[1] = m_pos[1]; op += 2; m_pos += 2; do { *op++ = *m_pos++; } while (op < oe); } match_next: state = next; t = next; #if defined(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS) if (likely(HAVE_IP(6, 0) && HAVE_OP(4, 0))) { COPY4(op, ip); op += t; ip += t; } else #endif { NEED_IP(t, 3); NEED_OP(t, 0); while (t > 0) { *op++ = *ip++; t--; } } } eof_found: *out_len = op - out; return (t != 3 ? LZO_E_ERROR : ip == ip_end ? LZO_E_OK : ip < ip_end ? LZO_E_INPUT_NOT_CONSUMED : LZO_E_INPUT_OVERRUN); input_overrun: *out_len = op - out; return LZO_E_INPUT_OVERRUN; output_overrun: *out_len = op - out; return LZO_E_OUTPUT_OVERRUN; lookbehind_overrun: *out_len = op - out; return LZO_E_LOOKBEHIND_OVERRUN; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
22,314
Android
04839626ed859623901ebd3a5fd483982186b59d
long Segment::DoParseNext( const Cluster*& pResult, long long& pos, long& len) { long long total, avail; long status = m_pReader->Length(&total, &avail); if (status < 0) //error return status; assert((total < 0) || (avail <= total)); const long long segment_stop = (m_size < 0) ? -1 : m_start + m_size; long long off_next = 0; long long cluster_size = -1; for (;;) { if ((total >= 0) && (pos >= total)) return 1; //EOF if ((segment_stop >= 0) && (pos >= segment_stop)) return 1; //EOF if ((pos + 1) > avail) { len = 1; return E_BUFFER_NOT_FULL; } long long result = GetUIntLength(m_pReader, pos, len); if (result < 0) //error return static_cast<long>(result); if (result > 0) //weird return E_BUFFER_NOT_FULL; if ((segment_stop >= 0) && ((pos + len) > segment_stop)) return E_FILE_FORMAT_INVALID; if ((pos + len) > avail) return E_BUFFER_NOT_FULL; const long long idpos = pos; //absolute const long long idoff = pos - m_start; //relative const long long id = ReadUInt(m_pReader, idpos, len); //absolute if (id < 0) //error return static_cast<long>(id); if (id == 0) //weird return -1; //generic error pos += len; //consume ID if ((pos + 1) > avail) { len = 1; return E_BUFFER_NOT_FULL; } result = GetUIntLength(m_pReader, pos, len); if (result < 0) //error return static_cast<long>(result); if (result > 0) //weird return E_BUFFER_NOT_FULL; if ((segment_stop >= 0) && ((pos + len) > segment_stop)) return E_FILE_FORMAT_INVALID; if ((pos + len) > avail) return E_BUFFER_NOT_FULL; const long long size = ReadUInt(m_pReader, pos, len); if (size < 0) //error return static_cast<long>(size); pos += len; //consume length of size of element if (size == 0) //weird continue; const long long unknown_size = (1LL << (7 * len)) - 1; if ((segment_stop >= 0) && (size != unknown_size) && ((pos + size) > segment_stop)) { return E_FILE_FORMAT_INVALID; } if (id == 0x0C53BB6B) //Cues ID { if (size == unknown_size) return E_FILE_FORMAT_INVALID; const long long element_stop = pos + size; if ((segment_stop >= 0) && (element_stop > segment_stop)) return E_FILE_FORMAT_INVALID; const long long element_start = idpos; const long long element_size = element_stop - element_start; if (m_pCues == NULL) { m_pCues = new Cues(this, pos, size, element_start, element_size); assert(m_pCues); //TODO } pos += size; //consume payload assert((segment_stop < 0) || (pos <= segment_stop)); continue; } if (id != 0x0F43B675) //not a Cluster ID { if (size == unknown_size) return E_FILE_FORMAT_INVALID; pos += size; //consume payload assert((segment_stop < 0) || (pos <= segment_stop)); continue; } #if 0 //this is commented-out to support incremental cluster parsing len = static_cast<long>(size); if (element_stop > avail) return E_BUFFER_NOT_FULL; #endif off_next = idoff; if (size != unknown_size) cluster_size = size; break; } assert(off_next > 0); //have cluster Cluster** const ii = m_clusters + m_clusterCount; Cluster** i = ii; Cluster** const jj = ii + m_clusterPreloadCount; Cluster** j = jj; while (i < j) { Cluster** const k = i + (j - i) / 2; assert(k < jj); const Cluster* const pNext = *k; assert(pNext); assert(pNext->m_index < 0); pos = pNext->GetPosition(); assert(pos >= 0); if (pos < off_next) i = k + 1; else if (pos > off_next) j = k; else { pResult = pNext; return 0; //success } } assert(i == j); long long pos_; long len_; status = Cluster::HasBlockEntries(this, off_next, pos_, len_); if (status < 0) //error or underflow { pos = pos_; len = len_; return status; } if (status > 0) //means "found at least one block entry" { Cluster* const pNext = Cluster::Create(this, -1, //preloaded off_next); assert(pNext); const ptrdiff_t idx_next = i - m_clusters; //insertion position PreloadCluster(pNext, idx_next); assert(m_clusters); assert(idx_next < m_clusterSize); assert(m_clusters[idx_next] == pNext); pResult = pNext; return 0; //success } if (cluster_size < 0) //unknown size { const long long payload_pos = pos; //absolute pos of cluster payload for (;;) //determine cluster size { if ((total >= 0) && (pos >= total)) break; if ((segment_stop >= 0) && (pos >= segment_stop)) break; //no more clusters if ((pos + 1) > avail) { len = 1; return E_BUFFER_NOT_FULL; } long long result = GetUIntLength(m_pReader, pos, len); if (result < 0) //error return static_cast<long>(result); if (result > 0) //weird return E_BUFFER_NOT_FULL; if ((segment_stop >= 0) && ((pos + len) > segment_stop)) return E_FILE_FORMAT_INVALID; if ((pos + len) > avail) return E_BUFFER_NOT_FULL; const long long idpos = pos; const long long id = ReadUInt(m_pReader, idpos, len); if (id < 0) //error (or underflow) return static_cast<long>(id); if (id == 0x0F43B675) //Cluster ID break; if (id == 0x0C53BB6B) //Cues ID break; pos += len; //consume ID (of sub-element) if ((pos + 1) > avail) { len = 1; return E_BUFFER_NOT_FULL; } result = GetUIntLength(m_pReader, pos, len); if (result < 0) //error return static_cast<long>(result); if (result > 0) //weird return E_BUFFER_NOT_FULL; if ((segment_stop >= 0) && ((pos + len) > segment_stop)) return E_FILE_FORMAT_INVALID; if ((pos + len) > avail) return E_BUFFER_NOT_FULL; const long long size = ReadUInt(m_pReader, pos, len); if (size < 0) //error return static_cast<long>(size); pos += len; //consume size field of element if (size == 0) //weird continue; const long long unknown_size = (1LL << (7 * len)) - 1; if (size == unknown_size) return E_FILE_FORMAT_INVALID; //not allowed for sub-elements if ((segment_stop >= 0) && ((pos + size) > segment_stop)) //weird return E_FILE_FORMAT_INVALID; pos += size; //consume payload of sub-element assert((segment_stop < 0) || (pos <= segment_stop)); } //determine cluster size cluster_size = pos - payload_pos; assert(cluster_size >= 0); //TODO: handle cluster_size = 0 pos = payload_pos; //reset and re-parse original cluster } pos += cluster_size; //consume payload assert((segment_stop < 0) || (pos <= segment_stop)); return 2; //try to find a cluster that follows next }
1
CVE-2016-1621
CWE-119
Improper Restriction of Operations within the Bounds of a Memory Buffer
The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data.
Phase: Requirements Strategy: Language Selection Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. For example, many languages that perform their own memory management, such as Java and Perl, are not subject to buffer overflows. Other languages, such as Ada and C#, typically provide overflow protection, but the protection can be disabled by the programmer. Be wary that a language's interface to native code may still be subject to overflows, even if the language itself is theoretically safe. Phase: Architecture and Design Strategy: Libraries or Frameworks Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. Examples include the Safe C String Library (SafeStr) by Messier and Viega [REF-57], and the Strsafe.h library from Microsoft [REF-56]. These libraries provide safer versions of overflow-prone string-handling functions. Note: This is not a complete solution, since many buffer overflows are not related to strings. Phases: Operation; Build and Compilation Strategy: Environment Hardening Use automatic buffer overflow detection mechanisms that are offered by certain compilers or compiler extensions. Examples include: the Microsoft Visual Studio /GS flag, Fedora/Red Hat FORTIFY_SOURCE GCC flag, StackGuard, and ProPolice, which provide various mechanisms including canary-based detection and range/index checking. D3-SFCV (Stack Frame Canary Validation) from D3FEND [REF-1334] discusses canary-based detection in detail. Effectiveness: Defense in Depth Note: This is not necessarily a complete solution, since these mechanisms only detect certain types of overflows. In addition, the result is still a denial of service, since the typical response is to exit the application. Phase: Implementation Consider adhering to the following rules when allocating and managing an application's memory: Double check that the buffer is as large as specified. When using functions that accept a number of bytes to copy, such as strncpy(), be aware that if the destination buffer size is equal to the source buffer size, it may not NULL-terminate the string. Check buffer boundaries if accessing the buffer in a loop and make sure there is no danger of writing past the allocated space. If necessary, truncate all input strings to a reasonable length before passing them to the copy and concatenation functions. Phases: Operation; Build and Compilation Strategy: Environment Hardening Run or compile the software using features or extensions that randomly arrange the positions of a program's executable and libraries in memory. Because this makes the addresses unpredictable, it can prevent an attacker from reliably jumping to exploitable code. Examples include Address Space Layout Randomization (ASLR) [REF-58] [REF-60] and Position-Independent Executables (PIE) [REF-64]. Imported modules may be similarly realigned if their default memory addresses conflict with other modules, in a process known as "rebasing" (for Windows) and "prelinking" (for Linux) [REF-1332] using randomly generated addresses. ASLR for libraries cannot be used in conjunction with prelink since it would require relocating the libraries at run-time, defeating the whole purpose of prelinking. For more information on these techniques see D3-SAOR (Segment Address Offset Randomization) from D3FEND [REF-1335]. Effectiveness: Defense in Depth Note: These techniques do not provide a complete solution. For instance, exploits frequently use a bug that discloses memory addresses in order to maximize reliability of code execution [REF-1337]. It has also been shown that a side-channel attack can bypass ASLR [REF-1333] Phase: Operation Strategy: Environment Hardening Use a CPU and operating system that offers Data Execution Protection (using hardware NX or XD bits) or the equivalent techniques that simulate this feature in software, such as PaX [REF-60] [REF-61]. These techniques ensure that any instruction executed is exclusively at a memory address that is part of the code segment. For more information on these techniques see D3-PSEP (Process Segment Execution Prevention) from D3FEND [REF-1336]. Effectiveness: Defense in Depth Note: This is not a complete solution, since buffer overflows could be used to overwrite nearby variables to modify the software's state in dangerous ways. In addition, it cannot be used in cases in which self-modifying code is required. Finally, an attack could still cause a denial of service, since the typical response is to exit the application. Phase: Implementation Replace unbounded copy functions with analogous functions that support length arguments, such as strcpy with strncpy. Create these if they are not available. Effectiveness: Moderate Note: This approach is still susceptible to calculation errors, including issues such as off-by-one errors (CWE-193) and incorrectly calculating buffer lengths (CWE-131).
1,867
ImageMagick
728dc6a600cf4cbdac846964c85cc04339db8ac1
static MagickBooleanType WriteTIFFImage(const ImageInfo *image_info, Image *image,ExceptionInfo *exception) { #if !defined(TIFFDefaultStripSize) #define TIFFDefaultStripSize(tiff,request) (8192UL/TIFFScanlineSize(tiff)) #endif const char *mode, *option; CompressionType compression; EndianType endian_type; MagickBooleanType debug, status; MagickOffsetType scene; QuantumInfo *quantum_info; QuantumType quantum_type; register ssize_t i; size_t length; ssize_t y; TIFF *tiff; TIFFInfo tiff_info; uint16 bits_per_sample, compress_tag, endian, photometric; uint32 rows_per_strip; unsigned char *pixels; /* Open TIFF file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); if (status == MagickFalse) return(status); (void) SetMagickThreadValue(tiff_exception,exception); endian_type=UndefinedEndian; option=GetImageOption(image_info,"tiff:endian"); if (option != (const char *) NULL) { if (LocaleNCompare(option,"msb",3) == 0) endian_type=MSBEndian; if (LocaleNCompare(option,"lsb",3) == 0) endian_type=LSBEndian;; } switch (endian_type) { case LSBEndian: mode="wl"; break; case MSBEndian: mode="wb"; break; default: mode="w"; break; } #if defined(TIFF_VERSION_BIG) if (LocaleCompare(image_info->magick,"TIFF64") == 0) switch (endian_type) { case LSBEndian: mode="wl8"; break; case MSBEndian: mode="wb8"; break; default: mode="w8"; break; } #endif tiff=TIFFClientOpen(image->filename,mode,(thandle_t) image,TIFFReadBlob, TIFFWriteBlob,TIFFSeekBlob,TIFFCloseBlob,TIFFGetBlobSize,TIFFMapBlob, TIFFUnmapBlob); if (tiff == (TIFF *) NULL) return(MagickFalse); scene=0; debug=IsEventLogging(); (void) debug; do { /* Initialize TIFF fields. */ if ((image_info->type != UndefinedType) && (image_info->type != OptimizeType)) (void) SetImageType(image,image_info->type,exception); compression=UndefinedCompression; if (image->compression != JPEGCompression) compression=image->compression; if (image_info->compression != UndefinedCompression) compression=image_info->compression; switch (compression) { case FaxCompression: case Group4Compression: { (void) SetImageType(image,BilevelType,exception); (void) SetImageDepth(image,1,exception); break; } case JPEGCompression: { (void) SetImageStorageClass(image,DirectClass,exception); (void) SetImageDepth(image,8,exception); break; } default: break; } quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); if ((image->storage_class != PseudoClass) && (image->depth >= 32) && (quantum_info->format == UndefinedQuantumFormat) && (IsHighDynamicRangeImage(image,exception) != MagickFalse)) { status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat); if (status == MagickFalse) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); } if ((LocaleCompare(image_info->magick,"PTIF") == 0) && (GetPreviousImageInList(image) != (Image *) NULL)) (void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_REDUCEDIMAGE); if ((image->columns != (uint32) image->columns) || (image->rows != (uint32) image->rows)) ThrowWriterException(ImageError,"WidthOrHeightExceedsLimit"); (void) TIFFSetField(tiff,TIFFTAG_IMAGELENGTH,(uint32) image->rows); (void) TIFFSetField(tiff,TIFFTAG_IMAGEWIDTH,(uint32) image->columns); switch (compression) { case FaxCompression: { compress_tag=COMPRESSION_CCITTFAX3; SetQuantumMinIsWhite(quantum_info,MagickTrue); break; } case Group4Compression: { compress_tag=COMPRESSION_CCITTFAX4; SetQuantumMinIsWhite(quantum_info,MagickTrue); break; } #if defined(COMPRESSION_JBIG) case JBIG1Compression: { compress_tag=COMPRESSION_JBIG; break; } #endif case JPEGCompression: { compress_tag=COMPRESSION_JPEG; break; } #if defined(COMPRESSION_LZMA) case LZMACompression: { compress_tag=COMPRESSION_LZMA; break; } #endif case LZWCompression: { compress_tag=COMPRESSION_LZW; break; } case RLECompression: { compress_tag=COMPRESSION_PACKBITS; break; } case ZipCompression: { compress_tag=COMPRESSION_ADOBE_DEFLATE; break; } case NoCompression: default: { compress_tag=COMPRESSION_NONE; break; } } #if defined(MAGICKCORE_HAVE_TIFFISCODECCONFIGURED) || (TIFFLIB_VERSION > 20040919) if ((compress_tag != COMPRESSION_NONE) && (TIFFIsCODECConfigured(compress_tag) == 0)) { (void) ThrowMagickException(exception,GetMagickModule(),CoderError, "CompressionNotSupported","`%s'",CommandOptionToMnemonic( MagickCompressOptions,(ssize_t) compression)); compress_tag=COMPRESSION_NONE; compression=NoCompression; } #else switch (compress_tag) { #if defined(CCITT_SUPPORT) case COMPRESSION_CCITTFAX3: case COMPRESSION_CCITTFAX4: #endif #if defined(YCBCR_SUPPORT) && defined(JPEG_SUPPORT) case COMPRESSION_JPEG: #endif #if defined(LZMA_SUPPORT) && defined(COMPRESSION_LZMA) case COMPRESSION_LZMA: #endif #if defined(LZW_SUPPORT) case COMPRESSION_LZW: #endif #if defined(PACKBITS_SUPPORT) case COMPRESSION_PACKBITS: #endif #if defined(ZIP_SUPPORT) case COMPRESSION_ADOBE_DEFLATE: #endif case COMPRESSION_NONE: break; default: { (void) ThrowMagickException(exception,GetMagickModule(),CoderError, "CompressionNotSupported","`%s'",CommandOptionToMnemonic( MagickCompressOptions,(ssize_t) compression)); compress_tag=COMPRESSION_NONE; compression=NoCompression; break; } } #endif if (image->colorspace == CMYKColorspace) { photometric=PHOTOMETRIC_SEPARATED; (void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,4); (void) TIFFSetField(tiff,TIFFTAG_INKSET,INKSET_CMYK); } else { /* Full color TIFF raster. */ if (image->colorspace == LabColorspace) { photometric=PHOTOMETRIC_CIELAB; EncodeLabImage(image,exception); } else if (image->colorspace == YCbCrColorspace) { photometric=PHOTOMETRIC_YCBCR; (void) TIFFSetField(tiff,TIFFTAG_YCBCRSUBSAMPLING,1,1); (void) SetImageStorageClass(image,DirectClass,exception); (void) SetImageDepth(image,8,exception); } else photometric=PHOTOMETRIC_RGB; (void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,3); if ((image_info->type != TrueColorType) && (image_info->type != TrueColorAlphaType)) { if ((image_info->type != PaletteType) && (SetImageGray(image,exception) != MagickFalse)) { photometric=(uint16) (quantum_info->min_is_white != MagickFalse ? PHOTOMETRIC_MINISWHITE : PHOTOMETRIC_MINISBLACK); (void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,1); if ((image->depth == 1) && (image->alpha_trait == UndefinedPixelTrait)) SetImageMonochrome(image,exception); } else if (image->storage_class == PseudoClass) { size_t depth; /* Colormapped TIFF raster. */ (void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,1); photometric=PHOTOMETRIC_PALETTE; depth=1; while ((GetQuantumRange(depth)+1) < image->colors) depth<<=1; status=SetQuantumDepth(image,quantum_info,depth); if (status == MagickFalse) ThrowWriterException(ResourceLimitError, "MemoryAllocationFailed"); } } } (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_FILLORDER,&endian); if ((compress_tag == COMPRESSION_CCITTFAX3) && (photometric != PHOTOMETRIC_MINISWHITE)) { compress_tag=COMPRESSION_NONE; endian=FILLORDER_MSB2LSB; } else if ((compress_tag == COMPRESSION_CCITTFAX4) && (photometric != PHOTOMETRIC_MINISWHITE)) { compress_tag=COMPRESSION_NONE; endian=FILLORDER_MSB2LSB; } option=GetImageOption(image_info,"tiff:fill-order"); if (option != (const char *) NULL) { if (LocaleNCompare(option,"msb",3) == 0) endian=FILLORDER_MSB2LSB; if (LocaleNCompare(option,"lsb",3) == 0) endian=FILLORDER_LSB2MSB; } (void) TIFFSetField(tiff,TIFFTAG_COMPRESSION,compress_tag); (void) TIFFSetField(tiff,TIFFTAG_FILLORDER,endian); (void) TIFFSetField(tiff,TIFFTAG_BITSPERSAMPLE,quantum_info->depth); if (image->alpha_trait != UndefinedPixelTrait) { uint16 extra_samples, sample_info[1], samples_per_pixel; /* TIFF has a matte channel. */ extra_samples=1; sample_info[0]=EXTRASAMPLE_UNASSALPHA; option=GetImageOption(image_info,"tiff:alpha"); if (option != (const char *) NULL) { if (LocaleCompare(option,"associated") == 0) sample_info[0]=EXTRASAMPLE_ASSOCALPHA; else if (LocaleCompare(option,"unspecified") == 0) sample_info[0]=EXTRASAMPLE_UNSPECIFIED; } (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLESPERPIXEL, &samples_per_pixel); (void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,samples_per_pixel+1); (void) TIFFSetField(tiff,TIFFTAG_EXTRASAMPLES,extra_samples, &sample_info); if (sample_info[0] == EXTRASAMPLE_ASSOCALPHA) SetQuantumAlphaType(quantum_info,AssociatedQuantumAlpha); } (void) TIFFSetField(tiff,TIFFTAG_PHOTOMETRIC,photometric); switch (quantum_info->format) { case FloatingPointQuantumFormat: { (void) TIFFSetField(tiff,TIFFTAG_SAMPLEFORMAT,SAMPLEFORMAT_IEEEFP); (void) TIFFSetField(tiff,TIFFTAG_SMINSAMPLEVALUE,quantum_info->minimum); (void) TIFFSetField(tiff,TIFFTAG_SMAXSAMPLEVALUE,quantum_info->maximum); break; } case SignedQuantumFormat: { (void) TIFFSetField(tiff,TIFFTAG_SAMPLEFORMAT,SAMPLEFORMAT_INT); break; } case UnsignedQuantumFormat: { (void) TIFFSetField(tiff,TIFFTAG_SAMPLEFORMAT,SAMPLEFORMAT_UINT); break; } default: break; } (void) TIFFSetField(tiff,TIFFTAG_ORIENTATION,ORIENTATION_TOPLEFT); (void) TIFFSetField(tiff,TIFFTAG_PLANARCONFIG,PLANARCONFIG_CONTIG); if (photometric == PHOTOMETRIC_RGB) if ((image_info->interlace == PlaneInterlace) || (image_info->interlace == PartitionInterlace)) (void) TIFFSetField(tiff,TIFFTAG_PLANARCONFIG,PLANARCONFIG_SEPARATE); rows_per_strip=1; if (TIFFScanlineSize(tiff) != 0) rows_per_strip=TIFFDefaultStripSize(tiff,0); option=GetImageOption(image_info,"tiff:rows-per-strip"); if (option != (const char *) NULL) rows_per_strip=(size_t) strtol(option,(char **) NULL,10); switch (compress_tag) { case COMPRESSION_JPEG: { #if defined(JPEG_SUPPORT) const char *sampling_factor; GeometryInfo geometry_info; MagickStatusType flags; rows_per_strip+=(16-(rows_per_strip % 16)); if (image_info->quality != UndefinedCompressionQuality) (void) TIFFSetField(tiff,TIFFTAG_JPEGQUALITY,image_info->quality); (void) TIFFSetField(tiff,TIFFTAG_JPEGCOLORMODE,JPEGCOLORMODE_RAW); if (IssRGBCompatibleColorspace(image->colorspace) != MagickFalse) { const char *value; (void) TIFFSetField(tiff,TIFFTAG_JPEGCOLORMODE,JPEGCOLORMODE_RGB); sampling_factor=(const char *) NULL; value=GetImageProperty(image,"jpeg:sampling-factor",exception); if (value != (char *) NULL) { sampling_factor=value; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Input sampling-factors=%s",sampling_factor); } if (image_info->sampling_factor != (char *) NULL) sampling_factor=image_info->sampling_factor; if (sampling_factor != (const char *) NULL) { flags=ParseGeometry(sampling_factor,&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=geometry_info.rho; if (image->colorspace == YCbCrColorspace) (void) TIFFSetField(tiff,TIFFTAG_YCBCRSUBSAMPLING,(uint16) geometry_info.rho,(uint16) geometry_info.sigma); } } (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE, &bits_per_sample); if (bits_per_sample == 12) (void) TIFFSetField(tiff,TIFFTAG_JPEGTABLESMODE,JPEGTABLESMODE_QUANT); #endif break; } case COMPRESSION_ADOBE_DEFLATE: { rows_per_strip=(uint32) image->rows; (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE, &bits_per_sample); if (((photometric == PHOTOMETRIC_RGB) || (photometric == PHOTOMETRIC_MINISBLACK)) && ((bits_per_sample == 8) || (bits_per_sample == 16))) (void) TIFFSetField(tiff,TIFFTAG_PREDICTOR,PREDICTOR_HORIZONTAL); (void) TIFFSetField(tiff,TIFFTAG_ZIPQUALITY,(long) ( image_info->quality == UndefinedCompressionQuality ? 7 : MagickMin((ssize_t) image_info->quality/10,9))); break; } case COMPRESSION_CCITTFAX3: { /* Byte-aligned EOL. */ rows_per_strip=(uint32) image->rows; (void) TIFFSetField(tiff,TIFFTAG_GROUP3OPTIONS,4); break; } case COMPRESSION_CCITTFAX4: { rows_per_strip=(uint32) image->rows; break; } #if defined(LZMA_SUPPORT) && defined(COMPRESSION_LZMA) case COMPRESSION_LZMA: { if (((photometric == PHOTOMETRIC_RGB) || (photometric == PHOTOMETRIC_MINISBLACK)) && ((bits_per_sample == 8) || (bits_per_sample == 16))) (void) TIFFSetField(tiff,TIFFTAG_PREDICTOR,PREDICTOR_HORIZONTAL); (void) TIFFSetField(tiff,TIFFTAG_LZMAPRESET,(long) ( image_info->quality == UndefinedCompressionQuality ? 7 : MagickMin((ssize_t) image_info->quality/10,9))); break; } #endif case COMPRESSION_LZW: { (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE, &bits_per_sample); if (((photometric == PHOTOMETRIC_RGB) || (photometric == PHOTOMETRIC_MINISBLACK)) && ((bits_per_sample == 8) || (bits_per_sample == 16))) (void) TIFFSetField(tiff,TIFFTAG_PREDICTOR,PREDICTOR_HORIZONTAL); break; } default: break; } if (rows_per_strip < 1) rows_per_strip=1; if ((image->rows/rows_per_strip) >= (1UL << 15)) rows_per_strip=(uint32) (image->rows >> 15); (void) TIFFSetField(tiff,TIFFTAG_ROWSPERSTRIP,rows_per_strip); if ((image->resolution.x != 0.0) && (image->resolution.y != 0.0)) { unsigned short units; /* Set image resolution. */ units=RESUNIT_NONE; if (image->units == PixelsPerInchResolution) units=RESUNIT_INCH; if (image->units == PixelsPerCentimeterResolution) units=RESUNIT_CENTIMETER; (void) TIFFSetField(tiff,TIFFTAG_RESOLUTIONUNIT,(uint16) units); (void) TIFFSetField(tiff,TIFFTAG_XRESOLUTION,image->resolution.x); (void) TIFFSetField(tiff,TIFFTAG_YRESOLUTION,image->resolution.y); if ((image->page.x < 0) || (image->page.y < 0)) (void) ThrowMagickException(exception,GetMagickModule(),CoderError, "TIFF: negative image positions unsupported","%s",image->filename); if ((image->page.x > 0) && (image->resolution.x > 0.0)) { /* Set horizontal image position. */ (void) TIFFSetField(tiff,TIFFTAG_XPOSITION,(float) image->page.x/ image->resolution.x); } if ((image->page.y > 0) && (image->resolution.y > 0.0)) { /* Set vertical image position. */ (void) TIFFSetField(tiff,TIFFTAG_YPOSITION,(float) image->page.y/ image->resolution.y); } } if (image->chromaticity.white_point.x != 0.0) { float chromaticity[6]; /* Set image chromaticity. */ chromaticity[0]=(float) image->chromaticity.red_primary.x; chromaticity[1]=(float) image->chromaticity.red_primary.y; chromaticity[2]=(float) image->chromaticity.green_primary.x; chromaticity[3]=(float) image->chromaticity.green_primary.y; chromaticity[4]=(float) image->chromaticity.blue_primary.x; chromaticity[5]=(float) image->chromaticity.blue_primary.y; (void) TIFFSetField(tiff,TIFFTAG_PRIMARYCHROMATICITIES,chromaticity); chromaticity[0]=(float) image->chromaticity.white_point.x; chromaticity[1]=(float) image->chromaticity.white_point.y; (void) TIFFSetField(tiff,TIFFTAG_WHITEPOINT,chromaticity); } if ((LocaleCompare(image_info->magick,"PTIF") != 0) && (image_info->adjoin != MagickFalse) && (GetImageListLength(image) > 1)) { (void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_PAGE); if (image->scene != 0) (void) TIFFSetField(tiff,TIFFTAG_PAGENUMBER,(uint16) image->scene, GetImageListLength(image)); } if (image->orientation != UndefinedOrientation) (void) TIFFSetField(tiff,TIFFTAG_ORIENTATION,(uint16) image->orientation); (void) TIFFSetProfiles(tiff,image); { uint16 page, pages; page=(uint16) scene; pages=(uint16) GetImageListLength(image); if ((LocaleCompare(image_info->magick,"PTIF") != 0) && (image_info->adjoin != MagickFalse) && (pages > 1)) (void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_PAGE); (void) TIFFSetField(tiff,TIFFTAG_PAGENUMBER,page,pages); } (void) TIFFSetProperties(tiff,image_info,image,exception); DisableMSCWarning(4127) if (0) RestoreMSCWarning (void) TIFFSetEXIFProperties(tiff,image,exception); /* Write image scanlines. */ if (GetTIFFInfo(image_info,tiff,&tiff_info) == MagickFalse) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); quantum_info->endian=LSBEndian; pixels=(unsigned char *) GetQuantumPixels(quantum_info); tiff_info.scanline=(unsigned char *) GetQuantumPixels(quantum_info); switch (photometric) { case PHOTOMETRIC_CIELAB: case PHOTOMETRIC_YCBCR: case PHOTOMETRIC_RGB: { /* RGB TIFF image. */ switch (image_info->interlace) { case NoInterlace: default: { quantum_type=RGBQuantum; if (image->alpha_trait != UndefinedPixelTrait) quantum_type=RGBAQuantum; for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); (void) length; if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } break; } case PlaneInterlace: case PartitionInterlace: { /* Plane interlacing: RRRRRR...GGGGGG...BBBBBB... */ for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, RedQuantum,pixels,exception); if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,100,400); if (status == MagickFalse) break; } for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, GreenQuantum,pixels,exception); if (TIFFWritePixels(tiff,&tiff_info,y,1,image) == -1) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,200,400); if (status == MagickFalse) break; } for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, BlueQuantum,pixels,exception); if (TIFFWritePixels(tiff,&tiff_info,y,2,image) == -1) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,300,400); if (status == MagickFalse) break; } if (image->alpha_trait != UndefinedPixelTrait) for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; length=ExportQuantumPixels(image,(CacheView *) NULL, quantum_info,AlphaQuantum,pixels,exception); if (TIFFWritePixels(tiff,&tiff_info,y,3,image) == -1) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,400,400); if (status == MagickFalse) break; } break; } } break; } case PHOTOMETRIC_SEPARATED: { /* CMYK TIFF image. */ quantum_type=CMYKQuantum; if (image->alpha_trait != UndefinedPixelTrait) quantum_type=CMYKAQuantum; if (image->colorspace != CMYKColorspace) (void) TransformImageColorspace(image,CMYKColorspace,exception); for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case PHOTOMETRIC_PALETTE: { uint16 *blue, *green, *red; /* Colormapped TIFF image. */ red=(uint16 *) AcquireQuantumMemory(65536,sizeof(*red)); green=(uint16 *) AcquireQuantumMemory(65536,sizeof(*green)); blue=(uint16 *) AcquireQuantumMemory(65536,sizeof(*blue)); if ((red == (uint16 *) NULL) || (green == (uint16 *) NULL) || (blue == (uint16 *) NULL)) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); /* Initialize TIFF colormap. */ (void) ResetMagickMemory(red,0,65536*sizeof(*red)); (void) ResetMagickMemory(green,0,65536*sizeof(*green)); (void) ResetMagickMemory(blue,0,65536*sizeof(*blue)); for (i=0; i < (ssize_t) image->colors; i++) { red[i]=ScaleQuantumToShort(image->colormap[i].red); green[i]=ScaleQuantumToShort(image->colormap[i].green); blue[i]=ScaleQuantumToShort(image->colormap[i].blue); } (void) TIFFSetField(tiff,TIFFTAG_COLORMAP,red,green,blue); red=(uint16 *) RelinquishMagickMemory(red); green=(uint16 *) RelinquishMagickMemory(green); blue=(uint16 *) RelinquishMagickMemory(blue); } default: { /* Convert PseudoClass packets to contiguous grayscale scanlines. */ quantum_type=IndexQuantum; if (image->alpha_trait != UndefinedPixelTrait) { if (photometric != PHOTOMETRIC_PALETTE) quantum_type=GrayAlphaQuantum; else quantum_type=IndexAlphaQuantum; } else if (photometric != PHOTOMETRIC_PALETTE) quantum_type=GrayQuantum; for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } } quantum_info=DestroyQuantumInfo(quantum_info); if (image->colorspace == LabColorspace) DecodeLabImage(image,exception); DestroyTIFFInfo(&tiff_info); DisableMSCWarning(4127) if (0 && (image_info->verbose != MagickFalse)) RestoreMSCWarning TIFFPrintDirectory(tiff,stdout,MagickFalse); (void) TIFFWriteDirectory(tiff); image=SyncNextImageInList(image); if (image == (Image *) NULL) break; status=SetImageProgress(image,SaveImagesTag,scene++, GetImageListLength(image)); if (status == MagickFalse) break; } while (image_info->adjoin != MagickFalse); TIFFClose(tiff); return(MagickTrue); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
23,061
src
3095060f479b86288e31c79ecbc5131a66bcd2f9
ssh_packet_set_state(struct ssh *ssh, struct sshbuf *m) { struct session_state *state = ssh->state; const u_char *ssh1key, *ivin, *ivout, *keyin, *keyout, *input, *output; size_t ssh1keylen, rlen, slen, ilen, olen; int r; u_int ssh1cipher = 0; if (!compat20) { if ((r = sshbuf_get_u32(m, &state->remote_protocol_flags)) != 0 || (r = sshbuf_get_u32(m, &ssh1cipher)) != 0 || (r = sshbuf_get_string_direct(m, &ssh1key, &ssh1keylen)) != 0 || (r = sshbuf_get_string_direct(m, &ivout, &slen)) != 0 || (r = sshbuf_get_string_direct(m, &ivin, &rlen)) != 0) return r; if (ssh1cipher > INT_MAX) return SSH_ERR_KEY_UNKNOWN_CIPHER; ssh_packet_set_encryption_key(ssh, ssh1key, ssh1keylen, (int)ssh1cipher); if (cipher_get_keyiv_len(state->send_context) != (int)slen || cipher_get_keyiv_len(state->receive_context) != (int)rlen) return SSH_ERR_INVALID_FORMAT; if ((r = cipher_set_keyiv(state->send_context, ivout)) != 0 || (r = cipher_set_keyiv(state->receive_context, ivin)) != 0) return r; } else { if ((r = kex_from_blob(m, &ssh->kex)) != 0 || (r = newkeys_from_blob(m, ssh, MODE_OUT)) != 0 || (r = newkeys_from_blob(m, ssh, MODE_IN)) != 0 || (r = sshbuf_get_u64(m, &state->rekey_limit)) != 0 || (r = sshbuf_get_u32(m, &state->rekey_interval)) != 0 || (r = sshbuf_get_u32(m, &state->p_send.seqnr)) != 0 || (r = sshbuf_get_u64(m, &state->p_send.blocks)) != 0 || (r = sshbuf_get_u32(m, &state->p_send.packets)) != 0 || (r = sshbuf_get_u64(m, &state->p_send.bytes)) != 0 || (r = sshbuf_get_u32(m, &state->p_read.seqnr)) != 0 || (r = sshbuf_get_u64(m, &state->p_read.blocks)) != 0 || (r = sshbuf_get_u32(m, &state->p_read.packets)) != 0 || (r = sshbuf_get_u64(m, &state->p_read.bytes)) != 0) return r; /* * We set the time here so that in post-auth privsep slave we * count from the completion of the authentication. */ state->rekey_time = monotime(); /* XXX ssh_set_newkeys overrides p_read.packets? XXX */ if ((r = ssh_set_newkeys(ssh, MODE_IN)) != 0 || (r = ssh_set_newkeys(ssh, MODE_OUT)) != 0) return r; } if ((r = sshbuf_get_string_direct(m, &keyout, &slen)) != 0 || (r = sshbuf_get_string_direct(m, &keyin, &rlen)) != 0) return r; if (cipher_get_keycontext(state->send_context, NULL) != (int)slen || cipher_get_keycontext(state->receive_context, NULL) != (int)rlen) return SSH_ERR_INVALID_FORMAT; cipher_set_keycontext(state->send_context, keyout); cipher_set_keycontext(state->receive_context, keyin); if ((r = ssh_packet_set_compress_state(ssh, m)) != 0 || (r = ssh_packet_set_postauth(ssh)) != 0) return r; sshbuf_reset(state->input); sshbuf_reset(state->output); if ((r = sshbuf_get_string_direct(m, &input, &ilen)) != 0 || (r = sshbuf_get_string_direct(m, &output, &olen)) != 0 || (r = sshbuf_put(state->input, input, ilen)) != 0 || (r = sshbuf_put(state->output, output, olen)) != 0) return r; if (sshbuf_len(m)) return SSH_ERR_INVALID_FORMAT; debug3("%s: done", __func__); return 0; }
1
CVE-2016-10012
CWE-119
Improper Restriction of Operations within the Bounds of a Memory Buffer
The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data.
Phase: Requirements Strategy: Language Selection Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. For example, many languages that perform their own memory management, such as Java and Perl, are not subject to buffer overflows. Other languages, such as Ada and C#, typically provide overflow protection, but the protection can be disabled by the programmer. Be wary that a language's interface to native code may still be subject to overflows, even if the language itself is theoretically safe. Phase: Architecture and Design Strategy: Libraries or Frameworks Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. Examples include the Safe C String Library (SafeStr) by Messier and Viega [REF-57], and the Strsafe.h library from Microsoft [REF-56]. These libraries provide safer versions of overflow-prone string-handling functions. Note: This is not a complete solution, since many buffer overflows are not related to strings. Phases: Operation; Build and Compilation Strategy: Environment Hardening Use automatic buffer overflow detection mechanisms that are offered by certain compilers or compiler extensions. Examples include: the Microsoft Visual Studio /GS flag, Fedora/Red Hat FORTIFY_SOURCE GCC flag, StackGuard, and ProPolice, which provide various mechanisms including canary-based detection and range/index checking. D3-SFCV (Stack Frame Canary Validation) from D3FEND [REF-1334] discusses canary-based detection in detail. Effectiveness: Defense in Depth Note: This is not necessarily a complete solution, since these mechanisms only detect certain types of overflows. In addition, the result is still a denial of service, since the typical response is to exit the application. Phase: Implementation Consider adhering to the following rules when allocating and managing an application's memory: Double check that the buffer is as large as specified. When using functions that accept a number of bytes to copy, such as strncpy(), be aware that if the destination buffer size is equal to the source buffer size, it may not NULL-terminate the string. Check buffer boundaries if accessing the buffer in a loop and make sure there is no danger of writing past the allocated space. If necessary, truncate all input strings to a reasonable length before passing them to the copy and concatenation functions. Phases: Operation; Build and Compilation Strategy: Environment Hardening Run or compile the software using features or extensions that randomly arrange the positions of a program's executable and libraries in memory. Because this makes the addresses unpredictable, it can prevent an attacker from reliably jumping to exploitable code. Examples include Address Space Layout Randomization (ASLR) [REF-58] [REF-60] and Position-Independent Executables (PIE) [REF-64]. Imported modules may be similarly realigned if their default memory addresses conflict with other modules, in a process known as "rebasing" (for Windows) and "prelinking" (for Linux) [REF-1332] using randomly generated addresses. ASLR for libraries cannot be used in conjunction with prelink since it would require relocating the libraries at run-time, defeating the whole purpose of prelinking. For more information on these techniques see D3-SAOR (Segment Address Offset Randomization) from D3FEND [REF-1335]. Effectiveness: Defense in Depth Note: These techniques do not provide a complete solution. For instance, exploits frequently use a bug that discloses memory addresses in order to maximize reliability of code execution [REF-1337]. It has also been shown that a side-channel attack can bypass ASLR [REF-1333] Phase: Operation Strategy: Environment Hardening Use a CPU and operating system that offers Data Execution Protection (using hardware NX or XD bits) or the equivalent techniques that simulate this feature in software, such as PaX [REF-60] [REF-61]. These techniques ensure that any instruction executed is exclusively at a memory address that is part of the code segment. For more information on these techniques see D3-PSEP (Process Segment Execution Prevention) from D3FEND [REF-1336]. Effectiveness: Defense in Depth Note: This is not a complete solution, since buffer overflows could be used to overwrite nearby variables to modify the software's state in dangerous ways. In addition, it cannot be used in cases in which self-modifying code is required. Finally, an attack could still cause a denial of service, since the typical response is to exit the application. Phase: Implementation Replace unbounded copy functions with analogous functions that support length arguments, such as strcpy with strncpy. Create these if they are not available. Effectiveness: Moderate Note: This approach is still susceptible to calculation errors, including issues such as off-by-one errors (CWE-193) and incorrectly calculating buffer lengths (CWE-131).
71
ghostscript
1e03c06456d997435019fb3526fa2d4be7dbc6ec
pdf_repair_obj_stm(fz_context *ctx, pdf_document *doc, int stm_num) { pdf_obj *obj; fz_stream *stm = NULL; pdf_token tok; int i, n, count; pdf_lexbuf buf; fz_var(stm); pdf_lexbuf_init(ctx, &buf, PDF_LEXBUF_SMALL); fz_try(ctx) { obj = pdf_load_object(ctx, doc, stm_num); count = pdf_to_int(ctx, pdf_dict_get(ctx, obj, PDF_NAME_N)); pdf_drop_obj(ctx, obj); stm = pdf_open_stream_number(ctx, doc, stm_num); for (i = 0; i < count; i++) { pdf_xref_entry *entry; tok = pdf_lex(ctx, stm, &buf); if (tok != PDF_TOK_INT) fz_throw(ctx, FZ_ERROR_GENERIC, "corrupt object stream (%d 0 R)", stm_num); n = buf.i; if (n < 0) { fz_warn(ctx, "ignoring object with invalid object number (%d %d R)", n, i); continue; } else if (n >= pdf_xref_len(ctx, doc)) { fz_warn(ctx, "ignoring object with invalid object number (%d %d R)", n, i); continue; } entry = pdf_get_populating_xref_entry(ctx, doc, n); entry->ofs = stm_num; entry->gen = i; entry->num = n; entry->stm_ofs = 0; pdf_drop_obj(ctx, entry->obj); entry->obj = NULL; entry->type = 'o'; tok = pdf_lex(ctx, stm, &buf); if (tok != PDF_TOK_INT) fz_throw(ctx, FZ_ERROR_GENERIC, "corrupt object stream (%d 0 R)", stm_num); } } fz_always(ctx) { fz_drop_stream(ctx, stm); pdf_lexbuf_fin(ctx, &buf); } fz_catch(ctx) { fz_rethrow(ctx); } }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
14,905
engine
c6655a0b620a3e31f085cc906f8073fe81b2fad3
static int pkey_gost2018_encrypt(EVP_PKEY_CTX *pctx, unsigned char *out, size_t *out_len, const unsigned char *key, size_t key_len) { PSKeyTransport_gost *pst = NULL; EVP_PKEY *pubk = EVP_PKEY_CTX_get0_pkey(pctx); struct gost_pmeth_data *data = EVP_PKEY_CTX_get_data(pctx); int pkey_nid = EVP_PKEY_base_id(pubk); unsigned char expkeys[64]; EVP_PKEY *sec_key = NULL; int ret = 0; int mac_nid = NID_undef; size_t mac_len = 0; int exp_len = 0, iv_len = 0; unsigned char *exp_buf = NULL; int key_is_ephemeral = 0; switch (data->cipher_nid) { case NID_magma_ctr: mac_nid = NID_magma_mac; mac_len = 8; iv_len = 4; break; case NID_grasshopper_ctr: mac_nid = NID_grasshopper_mac; mac_len = 16; iv_len = 8; break; default: GOSTerr(GOST_F_PKEY_GOST2018_ENCRYPT, GOST_R_INVALID_CIPHER); return -1; break; } exp_len = key_len + mac_len; exp_buf = OPENSSL_malloc(exp_len); if (!exp_buf) { GOSTerr(GOST_F_PKEY_GOST2018_ENCRYPT, ERR_R_MALLOC_FAILURE); return -1; } sec_key = EVP_PKEY_CTX_get0_peerkey(pctx); if (!sec_key) { sec_key = EVP_PKEY_new(); if (sec_key == NULL) { GOSTerr(GOST_F_PKEY_GOST2018_ENCRYPT, ERR_R_MALLOC_FAILURE ); goto err; } if (!EVP_PKEY_assign(sec_key, EVP_PKEY_base_id(pubk), EC_KEY_new()) || !EVP_PKEY_copy_parameters(sec_key, pubk) || !gost_ec_keygen(EVP_PKEY_get0(sec_key))) { GOSTerr(GOST_F_PKEY_GOST2018_ENCRYPT, GOST_R_ERROR_COMPUTING_SHARED_KEY); goto err; } key_is_ephemeral = 1; } if (data->shared_ukm_size == 0) { if (RAND_bytes(data->shared_ukm, 32) <= 0) { GOSTerr(GOST_F_PKEY_GOST2018_ENCRYPT, ERR_R_INTERNAL_ERROR); goto err; } data->shared_ukm_size = 32; } if (gost_keg(data->shared_ukm, pkey_nid, EC_KEY_get0_public_key(EVP_PKEY_get0(pubk)), EVP_PKEY_get0(sec_key), expkeys) <= 0) { GOSTerr(GOST_F_PKEY_GOST2018_ENCRYPT, GOST_R_ERROR_COMPUTING_EXPORT_KEYS); goto err; } if (gost_kexp15(key, key_len, data->cipher_nid, expkeys + 32, mac_nid, expkeys + 0, data->shared_ukm + 24, iv_len, exp_buf, &exp_len) <= 0) { GOSTerr(GOST_F_PKEY_GOST2018_ENCRYPT, GOST_R_CANNOT_PACK_EPHEMERAL_KEY); goto err; } pst = PSKeyTransport_gost_new(); if (!pst) { GOSTerr(GOST_F_PKEY_GOST2018_ENCRYPT, ERR_R_MALLOC_FAILURE); goto err; } pst->ukm = ASN1_OCTET_STRING_new(); if (pst->ukm == NULL) { GOSTerr(GOST_F_PKEY_GOST2018_ENCRYPT, ERR_R_MALLOC_FAILURE); goto err; } if (!ASN1_OCTET_STRING_set(pst->ukm, data->shared_ukm, data->shared_ukm_size)) { GOSTerr(GOST_F_PKEY_GOST2018_ENCRYPT, ERR_R_MALLOC_FAILURE); goto err; } if (!ASN1_OCTET_STRING_set(pst->psexp, exp_buf, exp_len)) { GOSTerr(GOST_F_PKEY_GOST2018_ENCRYPT, ERR_R_MALLOC_FAILURE); goto err; } if (!X509_PUBKEY_set(&pst->ephem_key, out ? sec_key : pubk)) { GOSTerr(GOST_F_PKEY_GOST2018_ENCRYPT, GOST_R_CANNOT_PACK_EPHEMERAL_KEY); goto err; } if ((*out_len = i2d_PSKeyTransport_gost(pst, out ? &out : NULL)) > 0) ret = 1; err: OPENSSL_cleanse(expkeys, sizeof(expkeys)); if (key_is_ephemeral) EVP_PKEY_free(sec_key); PSKeyTransport_gost_free(pst); OPENSSL_free(exp_buf); return ret; }
1
CVE-2022-29242
CWE-787
Out-of-bounds Write
The product writes data past the end, or before the beginning, of the intended buffer.
Phase: Requirements Strategy: Language Selection Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. For example, many languages that perform their own memory management, such as Java and Perl, are not subject to buffer overflows. Other languages, such as Ada and C#, typically provide overflow protection, but the protection can be disabled by the programmer. Be wary that a language's interface to native code may still be subject to overflows, even if the language itself is theoretically safe. Phase: Architecture and Design Strategy: Libraries or Frameworks Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. Examples include the Safe C String Library (SafeStr) by Messier and Viega [REF-57], and the Strsafe.h library from Microsoft [REF-56]. These libraries provide safer versions of overflow-prone string-handling functions. Note: This is not a complete solution, since many buffer overflows are not related to strings. Phases: Operation; Build and Compilation Strategy: Environment Hardening Use automatic buffer overflow detection mechanisms that are offered by certain compilers or compiler extensions. Examples include: the Microsoft Visual Studio /GS flag, Fedora/Red Hat FORTIFY_SOURCE GCC flag, StackGuard, and ProPolice, which provide various mechanisms including canary-based detection and range/index checking. D3-SFCV (Stack Frame Canary Validation) from D3FEND [REF-1334] discusses canary-based detection in detail. Effectiveness: Defense in Depth Note: This is not necessarily a complete solution, since these mechanisms only detect certain types of overflows. In addition, the result is still a denial of service, since the typical response is to exit the application. Phase: Implementation Consider adhering to the following rules when allocating and managing an application's memory: Double check that the buffer is as large as specified. When using functions that accept a number of bytes to copy, such as strncpy(), be aware that if the destination buffer size is equal to the source buffer size, it may not NULL-terminate the string. Check buffer boundaries if accessing the buffer in a loop and make sure there is no danger of writing past the allocated space. If necessary, truncate all input strings to a reasonable length before passing them to the copy and concatenation functions. Phases: Operation; Build and Compilation Strategy: Environment Hardening Run or compile the software using features or extensions that randomly arrange the positions of a program's executable and libraries in memory. Because this makes the addresses unpredictable, it can prevent an attacker from reliably jumping to exploitable code. Examples include Address Space Layout Randomization (ASLR) [REF-58] [REF-60] and Position-Independent Executables (PIE) [REF-64]. Imported modules may be similarly realigned if their default memory addresses conflict with other modules, in a process known as "rebasing" (for Windows) and "prelinking" (for Linux) [REF-1332] using randomly generated addresses. ASLR for libraries cannot be used in conjunction with prelink since it would require relocating the libraries at run-time, defeating the whole purpose of prelinking. For more information on these techniques see D3-SAOR (Segment Address Offset Randomization) from D3FEND [REF-1335]. Effectiveness: Defense in Depth Note: These techniques do not provide a complete solution. For instance, exploits frequently use a bug that discloses memory addresses in order to maximize reliability of code execution [REF-1337]. It has also been shown that a side-channel attack can bypass ASLR [REF-1333]. Phase: Operation Strategy: Environment Hardening Use a CPU and operating system that offers Data Execution Protection (using hardware NX or XD bits) or the equivalent techniques that simulate this feature in software, such as PaX [REF-60] [REF-61]. These techniques ensure that any instruction executed is exclusively at a memory address that is part of the code segment. For more information on these techniques see D3-PSEP (Process Segment Execution Prevention) from D3FEND [REF-1336]. Effectiveness: Defense in Depth Note: This is not a complete solution, since buffer overflows could be used to overwrite nearby variables to modify the software's state in dangerous ways. In addition, it cannot be used in cases in which self-modifying code is required. Finally, an attack could still cause a denial of service, since the typical response is to exit the application. Phase: Implementation Replace unbounded copy functions with analogous functions that support length arguments, such as strcpy with strncpy. Create these if they are not available. Effectiveness: Moderate Note: This approach is still susceptible to calculation errors, including issues such as off-by-one errors (CWE-193) and incorrectly calculating buffer lengths (CWE-131).
797
Android
dd28d8ddf2985d654781770c691c60b45d7f32b4
static void cleanup_src(void) { BTIF_TRACE_EVENT("%s", __func__); btif_queue_cleanup(UUID_SERVCLASS_AUDIO_SOURCE); if (bt_av_src_callbacks) { bt_av_src_callbacks = NULL; if (bt_av_sink_callbacks == NULL) cleanup(BTA_A2DP_SOURCE_SERVICE_ID); } }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
13,893
linux
6d1c0f3d28f98ea2736128ed3e46821496dc3a8c
static unsigned int xdr_set_page_base(struct xdr_stream *xdr, unsigned int base, unsigned int len) { unsigned int pgnr; unsigned int maxlen; unsigned int pgoff; unsigned int pgend; void *kaddr; maxlen = xdr->buf->page_len; if (base >= maxlen) { base = maxlen; maxlen = 0; } else maxlen -= base; if (len > maxlen) len = maxlen; xdr_stream_page_set_pos(xdr, base); base += xdr->buf->page_base; pgnr = base >> PAGE_SHIFT; xdr->page_ptr = &xdr->buf->pages[pgnr]; kaddr = page_address(*xdr->page_ptr); pgoff = base & ~PAGE_MASK; xdr->p = (__be32*)(kaddr + pgoff); pgend = pgoff + len; if (pgend > PAGE_SIZE) pgend = PAGE_SIZE; xdr->end = (__be32*)(kaddr + pgend); xdr->iov = NULL; return len; }
1
CVE-2021-38201
CWE-787
Out-of-bounds Write
The product writes data past the end, or before the beginning, of the intended buffer.
Phase: Requirements Strategy: Language Selection Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. For example, many languages that perform their own memory management, such as Java and Perl, are not subject to buffer overflows. Other languages, such as Ada and C#, typically provide overflow protection, but the protection can be disabled by the programmer. Be wary that a language's interface to native code may still be subject to overflows, even if the language itself is theoretically safe. Phase: Architecture and Design Strategy: Libraries or Frameworks Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. Examples include the Safe C String Library (SafeStr) by Messier and Viega [REF-57], and the Strsafe.h library from Microsoft [REF-56]. These libraries provide safer versions of overflow-prone string-handling functions. Note: This is not a complete solution, since many buffer overflows are not related to strings. Phases: Operation; Build and Compilation Strategy: Environment Hardening Use automatic buffer overflow detection mechanisms that are offered by certain compilers or compiler extensions. Examples include: the Microsoft Visual Studio /GS flag, Fedora/Red Hat FORTIFY_SOURCE GCC flag, StackGuard, and ProPolice, which provide various mechanisms including canary-based detection and range/index checking. D3-SFCV (Stack Frame Canary Validation) from D3FEND [REF-1334] discusses canary-based detection in detail. Effectiveness: Defense in Depth Note: This is not necessarily a complete solution, since these mechanisms only detect certain types of overflows. In addition, the result is still a denial of service, since the typical response is to exit the application. Phase: Implementation Consider adhering to the following rules when allocating and managing an application's memory: Double check that the buffer is as large as specified. When using functions that accept a number of bytes to copy, such as strncpy(), be aware that if the destination buffer size is equal to the source buffer size, it may not NULL-terminate the string. Check buffer boundaries if accessing the buffer in a loop and make sure there is no danger of writing past the allocated space. If necessary, truncate all input strings to a reasonable length before passing them to the copy and concatenation functions. Phases: Operation; Build and Compilation Strategy: Environment Hardening Run or compile the software using features or extensions that randomly arrange the positions of a program's executable and libraries in memory. Because this makes the addresses unpredictable, it can prevent an attacker from reliably jumping to exploitable code. Examples include Address Space Layout Randomization (ASLR) [REF-58] [REF-60] and Position-Independent Executables (PIE) [REF-64]. Imported modules may be similarly realigned if their default memory addresses conflict with other modules, in a process known as "rebasing" (for Windows) and "prelinking" (for Linux) [REF-1332] using randomly generated addresses. ASLR for libraries cannot be used in conjunction with prelink since it would require relocating the libraries at run-time, defeating the whole purpose of prelinking. For more information on these techniques see D3-SAOR (Segment Address Offset Randomization) from D3FEND [REF-1335]. Effectiveness: Defense in Depth Note: These techniques do not provide a complete solution. For instance, exploits frequently use a bug that discloses memory addresses in order to maximize reliability of code execution [REF-1337]. It has also been shown that a side-channel attack can bypass ASLR [REF-1333]. Phase: Operation Strategy: Environment Hardening Use a CPU and operating system that offers Data Execution Protection (using hardware NX or XD bits) or the equivalent techniques that simulate this feature in software, such as PaX [REF-60] [REF-61]. These techniques ensure that any instruction executed is exclusively at a memory address that is part of the code segment. For more information on these techniques see D3-PSEP (Process Segment Execution Prevention) from D3FEND [REF-1336]. Effectiveness: Defense in Depth Note: This is not a complete solution, since buffer overflows could be used to overwrite nearby variables to modify the software's state in dangerous ways. In addition, it cannot be used in cases in which self-modifying code is required. Finally, an attack could still cause a denial of service, since the typical response is to exit the application. Phase: Implementation Replace unbounded copy functions with analogous functions that support length arguments, such as strcpy with strncpy. Create these if they are not available. Effectiveness: Moderate Note: This approach is still susceptible to calculation errors, including issues such as off-by-one errors (CWE-193) and incorrectly calculating buffer lengths (CWE-131).
4,466
Chrome
7f0126ff011142c8619b10a6e64d04d1745c503a
void setRewriteURLFolder(const char* folder) { m_rewriteFolder = folder; }
1
CVE-2012-5157
CWE-119
Improper Restriction of Operations within the Bounds of a Memory Buffer
The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data.
Phase: Requirements Strategy: Language Selection Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. For example, many languages that perform their own memory management, such as Java and Perl, are not subject to buffer overflows. Other languages, such as Ada and C#, typically provide overflow protection, but the protection can be disabled by the programmer. Be wary that a language's interface to native code may still be subject to overflows, even if the language itself is theoretically safe. Phase: Architecture and Design Strategy: Libraries or Frameworks Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. Examples include the Safe C String Library (SafeStr) by Messier and Viega [REF-57], and the Strsafe.h library from Microsoft [REF-56]. These libraries provide safer versions of overflow-prone string-handling functions. Note: This is not a complete solution, since many buffer overflows are not related to strings. Phases: Operation; Build and Compilation Strategy: Environment Hardening Use automatic buffer overflow detection mechanisms that are offered by certain compilers or compiler extensions. Examples include: the Microsoft Visual Studio /GS flag, Fedora/Red Hat FORTIFY_SOURCE GCC flag, StackGuard, and ProPolice, which provide various mechanisms including canary-based detection and range/index checking. D3-SFCV (Stack Frame Canary Validation) from D3FEND [REF-1334] discusses canary-based detection in detail. Effectiveness: Defense in Depth Note: This is not necessarily a complete solution, since these mechanisms only detect certain types of overflows. In addition, the result is still a denial of service, since the typical response is to exit the application. Phase: Implementation Consider adhering to the following rules when allocating and managing an application's memory: Double check that the buffer is as large as specified. When using functions that accept a number of bytes to copy, such as strncpy(), be aware that if the destination buffer size is equal to the source buffer size, it may not NULL-terminate the string. Check buffer boundaries if accessing the buffer in a loop and make sure there is no danger of writing past the allocated space. If necessary, truncate all input strings to a reasonable length before passing them to the copy and concatenation functions. Phases: Operation; Build and Compilation Strategy: Environment Hardening Run or compile the software using features or extensions that randomly arrange the positions of a program's executable and libraries in memory. Because this makes the addresses unpredictable, it can prevent an attacker from reliably jumping to exploitable code. Examples include Address Space Layout Randomization (ASLR) [REF-58] [REF-60] and Position-Independent Executables (PIE) [REF-64]. Imported modules may be similarly realigned if their default memory addresses conflict with other modules, in a process known as "rebasing" (for Windows) and "prelinking" (for Linux) [REF-1332] using randomly generated addresses. ASLR for libraries cannot be used in conjunction with prelink since it would require relocating the libraries at run-time, defeating the whole purpose of prelinking. For more information on these techniques see D3-SAOR (Segment Address Offset Randomization) from D3FEND [REF-1335]. Effectiveness: Defense in Depth Note: These techniques do not provide a complete solution. For instance, exploits frequently use a bug that discloses memory addresses in order to maximize reliability of code execution [REF-1337]. It has also been shown that a side-channel attack can bypass ASLR [REF-1333] Phase: Operation Strategy: Environment Hardening Use a CPU and operating system that offers Data Execution Protection (using hardware NX or XD bits) or the equivalent techniques that simulate this feature in software, such as PaX [REF-60] [REF-61]. These techniques ensure that any instruction executed is exclusively at a memory address that is part of the code segment. For more information on these techniques see D3-PSEP (Process Segment Execution Prevention) from D3FEND [REF-1336]. Effectiveness: Defense in Depth Note: This is not a complete solution, since buffer overflows could be used to overwrite nearby variables to modify the software's state in dangerous ways. In addition, it cannot be used in cases in which self-modifying code is required. Finally, an attack could still cause a denial of service, since the typical response is to exit the application. Phase: Implementation Replace unbounded copy functions with analogous functions that support length arguments, such as strcpy with strncpy. Create these if they are not available. Effectiveness: Moderate Note: This approach is still susceptible to calculation errors, including issues such as off-by-one errors (CWE-193) and incorrectly calculating buffer lengths (CWE-131).
8,702
linux
78c9c4dfbf8c04883941445a195276bb4bb92c76
static void common_hrtimer_rearm(struct k_itimer *timr) { struct hrtimer *timer = &timr->it.real.timer; if (!timr->it_interval) return; timr->it_overrun += (unsigned int) hrtimer_forward(timer, timer->base->get_time(), timr->it_interval); hrtimer_restart(timer); }
1
CVE-2018-12896
CWE-190
Integer Overflow or Wraparound
The product performs a calculation that can produce an integer overflow or wraparound when the logic assumes that the resulting value will always be larger than the original value. This occurs when an integer value is incremented to a value that is too large to store in the associated representation. When this occurs, the value may become a very small or negative number.
Phase: Requirements Ensure that all protocols are strictly defined, such that all out-of-bounds behavior can be identified simply, and require strict conformance to the protocol. Phase: Requirements Strategy: Language Selection Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. If possible, choose a language or compiler that performs automatic bounds checking. Phase: Architecture and Design Strategy: Libraries or Frameworks Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. Use libraries or frameworks that make it easier to handle numbers without unexpected consequences. Examples include safe integer handling packages such as SafeInt (C++) or IntegerLib (C or C++). [REF-106] Phase: Implementation Strategy: Input Validation Perform input validation on any numeric input by ensuring that it is within the expected range. Enforce that the input meets both the minimum and maximum requirements for the expected range. Use unsigned integers where possible. This makes it easier to perform validation for integer overflows. When signed integers are required, ensure that the range check includes minimum values as well as maximum values. Phase: Implementation Understand the programming language's underlying representation and how it interacts with numeric calculation (CWE-681). Pay close attention to byte size discrepancies, precision, signed/unsigned distinctions, truncation, conversion and casting between types, "not-a-number" calculations, and how the language handles numbers that are too large or too small for its underlying representation. [REF-7] Also be careful to account for 32-bit, 64-bit, and other potential differences that may affect the numeric representation. Phase: Architecture and Design For any security checks that are performed on the client side, ensure that these checks are duplicated on the server side, in order to avoid CWE-602. Attackers can bypass the client-side checks by modifying values after the checks have been performed, or by changing the client to remove the client-side checks entirely. Then, these modified values would be submitted to the server. Phase: Implementation Strategy: Compilation or Build Hardening Examine compiler warnings closely and eliminate problems with potential security implications, such as signed / unsigned mismatch in memory operations, or use of uninitialized variables. Even if the weakness is rarely exploitable, a single failure may lead to the compromise of the entire system.
8,456
linux
ebe48d368e97d007bfeb76fcb065d6cfc4c96645
static int esp6_rcv_cb(struct sk_buff *skb, int err) { return 0; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
14,063
savannah
efb795c74fe954b9544074aafcebb1be4452b03a
hook_hdata (struct t_weechat_plugin *plugin, const char *hdata_name, const char *description, t_hook_callback_hdata *callback, void *callback_data) { struct t_hook *new_hook; struct t_hook_hdata *new_hook_hdata; int priority; const char *ptr_hdata_name; if (!hdata_name || !hdata_name[0] || !callback) return NULL; new_hook = malloc (sizeof (*new_hook)); if (!new_hook) return NULL; new_hook_hdata = malloc (sizeof (*new_hook_hdata)); if (!new_hook_hdata) { free (new_hook); return NULL; } hook_get_priority_and_name (hdata_name, &priority, &ptr_hdata_name); hook_init_data (new_hook, plugin, HOOK_TYPE_HDATA, priority, callback_data); new_hook->hook_data = new_hook_hdata; new_hook_hdata->callback = callback; new_hook_hdata->hdata_name = strdup ((ptr_hdata_name) ? ptr_hdata_name : hdata_name); new_hook_hdata->description = strdup ((description) ? description : ""); hook_add_to_list (new_hook); return new_hook; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
10,622
openmpt
7ebf02af2e90f03e0dbd0e18b8b3164f372fb97c
std::vector<GetLengthType> CSoundFile::GetLength(enmGetLengthResetMode adjustMode, GetLengthTarget target) { std::vector<GetLengthType> results; GetLengthType retval; retval.startOrder = target.startOrder; retval.startRow = target.startRow; // Are we trying to reach a certain pattern position? const bool hasSearchTarget = target.mode != GetLengthTarget::NoTarget; const bool adjustSamplePos = (adjustMode & eAdjustSamplePositions) == eAdjustSamplePositions; SEQUENCEINDEX sequence = target.sequence; if(sequence >= Order.GetNumSequences()) sequence = Order.GetCurrentSequenceIndex(); const ModSequence &orderList = Order(sequence); GetLengthMemory memory(*this); CSoundFile::PlayState &playState = *memory.state; // Temporary visited rows vector (so that GetLength() won't interfere with the player code if the module is playing at the same time) RowVisitor visitedRows(*this, sequence); playState.m_nNextRow = playState.m_nRow = target.startRow; playState.m_nNextOrder = playState.m_nCurrentOrder = target.startOrder; // Fast LUTs for commands that are too weird / complicated / whatever to emulate in sample position adjust mode. std::bitset<MAX_EFFECTS> forbiddenCommands; std::bitset<MAX_VOLCMDS> forbiddenVolCommands; if(adjustSamplePos) { forbiddenCommands.set(CMD_ARPEGGIO); forbiddenCommands.set(CMD_PORTAMENTOUP); forbiddenCommands.set(CMD_PORTAMENTODOWN); forbiddenCommands.set(CMD_XFINEPORTAUPDOWN); forbiddenCommands.set(CMD_NOTESLIDEUP); forbiddenCommands.set(CMD_NOTESLIDEUPRETRIG); forbiddenCommands.set(CMD_NOTESLIDEDOWN); forbiddenCommands.set(CMD_NOTESLIDEDOWNRETRIG); forbiddenVolCommands.set(VOLCMD_PORTAUP); forbiddenVolCommands.set(VOLCMD_PORTADOWN); // Optimize away channels for which it's pointless to adjust sample positions for(CHANNELINDEX i = 0; i < GetNumChannels(); i++) { if(ChnSettings[i].dwFlags[CHN_MUTE]) memory.chnSettings[i].ticksToRender = GetLengthMemory::IGNORE_CHANNEL; } if(target.mode == GetLengthTarget::SeekPosition && target.pos.order < orderList.size()) { // If we know where to seek, we can directly rule out any channels on which a new note would be triggered right at the start. const PATTERNINDEX seekPat = orderList[target.pos.order]; if(Patterns.IsValidPat(seekPat) && Patterns[seekPat].IsValidRow(target.pos.row)) { const ModCommand *m = Patterns[seekPat].GetRow(target.pos.row); for(CHANNELINDEX i = 0; i < GetNumChannels(); i++, m++) { if(m->note == NOTE_NOTECUT || m->note == NOTE_KEYOFF || (m->note == NOTE_FADE && GetNumInstruments()) || (m->IsNote() && !m->IsPortamento())) { memory.chnSettings[i].ticksToRender = GetLengthMemory::IGNORE_CHANNEL; } } } } } // If samples are being synced, force them to resync if tick duration changes uint32 oldTickDuration = 0; for (;;) { // Time target reached. if(target.mode == GetLengthTarget::SeekSeconds && memory.elapsedTime >= target.time) { retval.targetReached = true; break; } uint32 rowDelay = 0, tickDelay = 0; playState.m_nRow = playState.m_nNextRow; playState.m_nCurrentOrder = playState.m_nNextOrder; if(orderList.IsValidPat(playState.m_nCurrentOrder) && playState.m_nRow >= Patterns[orderList[playState.m_nCurrentOrder]].GetNumRows()) { playState.m_nRow = 0; if(m_playBehaviour[kFT2LoopE60Restart]) { playState.m_nRow = playState.m_nNextPatStartRow; playState.m_nNextPatStartRow = 0; } playState.m_nCurrentOrder = ++playState.m_nNextOrder; } // Check if pattern is valid playState.m_nPattern = playState.m_nCurrentOrder < orderList.size() ? orderList[playState.m_nCurrentOrder] : orderList.GetInvalidPatIndex(); bool positionJumpOnThisRow = false; bool patternBreakOnThisRow = false; bool patternLoopEndedOnThisRow = false, patternLoopStartedOnThisRow = false; if(!Patterns.IsValidPat(playState.m_nPattern) && playState.m_nPattern != orderList.GetInvalidPatIndex() && target.mode == GetLengthTarget::SeekPosition && playState.m_nCurrentOrder == target.pos.order) { // Early test: Target is inside +++ or non-existing pattern retval.targetReached = true; break; } while(playState.m_nPattern >= Patterns.Size()) { // End of song? if((playState.m_nPattern == orderList.GetInvalidPatIndex()) || (playState.m_nCurrentOrder >= orderList.size())) { if(playState.m_nCurrentOrder == orderList.GetRestartPos()) break; else playState.m_nCurrentOrder = orderList.GetRestartPos(); } else { playState.m_nCurrentOrder++; } playState.m_nPattern = (playState.m_nCurrentOrder < orderList.size()) ? orderList[playState.m_nCurrentOrder] : orderList.GetInvalidPatIndex(); playState.m_nNextOrder = playState.m_nCurrentOrder; if((!Patterns.IsValidPat(playState.m_nPattern)) && visitedRows.IsVisited(playState.m_nCurrentOrder, 0, true)) { if(!hasSearchTarget || !visitedRows.GetFirstUnvisitedRow(playState.m_nNextOrder, playState.m_nRow, true)) { // We aren't searching for a specific row, or we couldn't find any more unvisited rows. break; } else { // We haven't found the target row yet, but we found some other unplayed row... continue searching from here. retval.duration = memory.elapsedTime; results.push_back(retval); retval.startRow = playState.m_nRow; retval.startOrder = playState.m_nNextOrder; memory.Reset(); playState.m_nCurrentOrder = playState.m_nNextOrder; playState.m_nPattern = orderList[playState.m_nCurrentOrder]; playState.m_nNextRow = playState.m_nRow; break; } } } if(playState.m_nNextOrder == ORDERINDEX_INVALID) { // GetFirstUnvisitedRow failed, so there is nothing more to play break; } // Skip non-existing patterns if(!Patterns.IsValidPat(playState.m_nPattern)) { // If there isn't even a tune, we should probably stop here. if(playState.m_nCurrentOrder == orderList.GetRestartPos()) { if(!hasSearchTarget || !visitedRows.GetFirstUnvisitedRow(playState.m_nNextOrder, playState.m_nRow, true)) { // We aren't searching for a specific row, or we couldn't find any more unvisited rows. break; } else { // We haven't found the target row yet, but we found some other unplayed row... continue searching from here. retval.duration = memory.elapsedTime; results.push_back(retval); retval.startRow = playState.m_nRow; retval.startOrder = playState.m_nNextOrder; memory.Reset(); playState.m_nNextRow = playState.m_nRow; continue; } } playState.m_nNextOrder = playState.m_nCurrentOrder + 1; continue; } // Should never happen if(playState.m_nRow >= Patterns[playState.m_nPattern].GetNumRows()) playState.m_nRow = 0; // Check whether target was reached. if(target.mode == GetLengthTarget::SeekPosition && playState.m_nCurrentOrder == target.pos.order && playState.m_nRow == target.pos.row) { retval.targetReached = true; break; } if(visitedRows.IsVisited(playState.m_nCurrentOrder, playState.m_nRow, true)) { if(!hasSearchTarget || !visitedRows.GetFirstUnvisitedRow(playState.m_nNextOrder, playState.m_nRow, true)) { // We aren't searching for a specific row, or we couldn't find any more unvisited rows. break; } else { // We haven't found the target row yet, but we found some other unplayed row... continue searching from here. retval.duration = memory.elapsedTime; results.push_back(retval); retval.startRow = playState.m_nRow; retval.startOrder = playState.m_nNextOrder; memory.Reset(); playState.m_nNextRow = playState.m_nRow; continue; } } retval.endOrder = playState.m_nCurrentOrder; retval.endRow = playState.m_nRow; // Update next position playState.m_nNextRow = playState.m_nRow + 1; // Jumped to invalid pattern row? if(playState.m_nRow >= Patterns[playState.m_nPattern].GetNumRows()) { playState.m_nRow = 0; } // New pattern? if(!playState.m_nRow) { for(CHANNELINDEX chn = 0; chn < GetNumChannels(); chn++) { memory.chnSettings[chn].patLoop = memory.elapsedTime; memory.chnSettings[chn].patLoopSmp = playState.m_lTotalSampleCount; } } ModChannel *pChn = playState.Chn; // For various effects, we need to know first how many ticks there are in this row. const ModCommand *p = Patterns[playState.m_nPattern].GetpModCommand(playState.m_nRow, 0); for(CHANNELINDEX nChn = 0; nChn < GetNumChannels(); nChn++, p++) { if(m_playBehaviour[kST3NoMutedChannels] && ChnSettings[nChn].dwFlags[CHN_MUTE]) // not even effects are processed on muted S3M channels continue; if(p->IsPcNote()) { #ifndef NO_PLUGINS if((adjustMode & eAdjust) && p->instr > 0 && p->instr <= MAX_MIXPLUGINS) { memory.plugParams[std::make_pair(p->instr, p->GetValueVolCol())] = p->GetValueEffectCol(); } #endif // NO_PLUGINS pChn[nChn].rowCommand.Clear(); continue; } pChn[nChn].rowCommand = *p; switch(p->command) { case CMD_SPEED: SetSpeed(playState, p->param); break; case CMD_TEMPO: if(m_playBehaviour[kMODVBlankTiming]) { // ProTracker MODs with VBlank timing: All Fxx parameters set the tick count. if(p->param != 0) SetSpeed(playState, p->param); } break; case CMD_S3MCMDEX: if((p->param & 0xF0) == 0x60) { // Fine Pattern Delay tickDelay += (p->param & 0x0F); } else if((p->param & 0xF0) == 0xE0 && !rowDelay) { // Pattern Delay if(!(GetType() & MOD_TYPE_S3M) || (p->param & 0x0F) != 0) { // While Impulse Tracker *does* count S60 as a valid row delay (and thus ignores any other row delay commands on the right), // Scream Tracker 3 simply ignores such commands. rowDelay = 1 + (p->param & 0x0F); } } break; case CMD_MODCMDEX: if((p->param & 0xF0) == 0xE0) { // Pattern Delay rowDelay = 1 + (p->param & 0x0F); } break; } } if(rowDelay == 0) rowDelay = 1; const uint32 numTicks = (playState.m_nMusicSpeed + tickDelay) * rowDelay; const uint32 nonRowTicks = numTicks - rowDelay; for(CHANNELINDEX nChn = 0; nChn < GetNumChannels(); pChn++, nChn++) if(!pChn->rowCommand.IsEmpty()) { if(m_playBehaviour[kST3NoMutedChannels] && ChnSettings[nChn].dwFlags[CHN_MUTE]) // not even effects are processed on muted S3M channels continue; ModCommand::COMMAND command = pChn->rowCommand.command; ModCommand::PARAM param = pChn->rowCommand.param; ModCommand::NOTE note = pChn->rowCommand.note; if (pChn->rowCommand.instr) { pChn->nNewIns = pChn->rowCommand.instr; pChn->nLastNote = NOTE_NONE; memory.chnSettings[nChn].vol = 0xFF; } if (pChn->rowCommand.IsNote()) pChn->nLastNote = note; // Update channel panning if(pChn->rowCommand.IsNote() || pChn->rowCommand.instr) { SAMPLEINDEX smp = 0; if(GetNumInstruments()) { ModInstrument *pIns; if(pChn->nNewIns <= GetNumInstruments() && (pIns = Instruments[pChn->nNewIns]) != nullptr) { if(pIns->dwFlags[INS_SETPANNING]) pChn->nPan = pIns->nPan; if(ModCommand::IsNote(note)) smp = pIns->Keyboard[note - NOTE_MIN]; } } else { smp = pChn->nNewIns; } if(smp > 0 && smp <= GetNumSamples() && Samples[smp].uFlags[CHN_PANNING]) { pChn->nPan = Samples[smp].nPan; } } switch(pChn->rowCommand.volcmd) { case VOLCMD_VOLUME: memory.chnSettings[nChn].vol = pChn->rowCommand.vol; break; case VOLCMD_VOLSLIDEUP: case VOLCMD_VOLSLIDEDOWN: if(pChn->rowCommand.vol != 0) pChn->nOldVolParam = pChn->rowCommand.vol; break; } switch(command) { // Position Jump case CMD_POSITIONJUMP: positionJumpOnThisRow = true; playState.m_nNextOrder = static_cast<ORDERINDEX>(CalculateXParam(playState.m_nPattern, playState.m_nRow, nChn)); playState.m_nNextPatStartRow = 0; // FT2 E60 bug // see https://forum.openmpt.org/index.php?topic=2769.0 - FastTracker resets Dxx if Bxx is called _after_ Dxx // Test case: PatternJump.mod if(!patternBreakOnThisRow || (GetType() & (MOD_TYPE_MOD | MOD_TYPE_XM))) playState.m_nNextRow = 0; if (adjustMode & eAdjust) { pChn->nPatternLoopCount = 0; pChn->nPatternLoop = 0; } break; // Pattern Break case CMD_PATTERNBREAK: { ROWINDEX row = PatternBreak(playState, nChn, param); if(row != ROWINDEX_INVALID) { patternBreakOnThisRow = true; playState.m_nNextRow = row; if(!positionJumpOnThisRow) { playState.m_nNextOrder = playState.m_nCurrentOrder + 1; } if(adjustMode & eAdjust) { pChn->nPatternLoopCount = 0; pChn->nPatternLoop = 0; } } } break; // Set Tempo case CMD_TEMPO: if(!m_playBehaviour[kMODVBlankTiming]) { TEMPO tempo(CalculateXParam(playState.m_nPattern, playState.m_nRow, nChn), 0); if ((adjustMode & eAdjust) && (GetType() & (MOD_TYPE_S3M | MOD_TYPE_IT | MOD_TYPE_MPT))) { if (tempo.GetInt()) pChn->nOldTempo = static_cast<uint8>(tempo.GetInt()); else tempo.Set(pChn->nOldTempo); } if (tempo.GetInt() >= 0x20) playState.m_nMusicTempo = tempo; else { // Tempo Slide TEMPO tempoDiff((tempo.GetInt() & 0x0F) * nonRowTicks, 0); if ((tempo.GetInt() & 0xF0) == 0x10) { playState.m_nMusicTempo += tempoDiff; } else { if(tempoDiff < playState.m_nMusicTempo) playState.m_nMusicTempo -= tempoDiff; else playState.m_nMusicTempo.Set(0); } } TEMPO tempoMin = GetModSpecifications().GetTempoMin(), tempoMax = GetModSpecifications().GetTempoMax(); if(m_playBehaviour[kTempoClamp]) // clamp tempo correctly in compatible mode { tempoMax.Set(255); } Limit(playState.m_nMusicTempo, tempoMin, tempoMax); } break; case CMD_S3MCMDEX: switch(param & 0xF0) { case 0x90: if(param <= 0x91) { pChn->dwFlags.set(CHN_SURROUND, param == 0x91); } break; case 0xA0: // High sample offset pChn->nOldHiOffset = param & 0x0F; break; case 0xB0: // Pattern Loop if (param & 0x0F) { patternLoopEndedOnThisRow = true; } else { CHANNELINDEX firstChn = nChn, lastChn = nChn; if(GetType() == MOD_TYPE_S3M) { // ST3 has only one global loop memory. firstChn = 0; lastChn = GetNumChannels() - 1; } for(CHANNELINDEX c = firstChn; c <= lastChn; c++) { memory.chnSettings[c].patLoop = memory.elapsedTime; memory.chnSettings[c].patLoopSmp = playState.m_lTotalSampleCount; memory.chnSettings[c].patLoopStart = playState.m_nRow; } patternLoopStartedOnThisRow = true; } break; case 0xF0: // Active macro pChn->nActiveMacro = param & 0x0F; break; } break; case CMD_MODCMDEX: switch(param & 0xF0) { case 0x60: // Pattern Loop if (param & 0x0F) { playState.m_nNextPatStartRow = memory.chnSettings[nChn].patLoopStart; // FT2 E60 bug patternLoopEndedOnThisRow = true; } else { patternLoopStartedOnThisRow = true; memory.chnSettings[nChn].patLoop = memory.elapsedTime; memory.chnSettings[nChn].patLoopSmp = playState.m_lTotalSampleCount; memory.chnSettings[nChn].patLoopStart = playState.m_nRow; } break; case 0xF0: // Active macro pChn->nActiveMacro = param & 0x0F; break; } break; case CMD_XFINEPORTAUPDOWN: // ignore high offset in compatible mode if(((param & 0xF0) == 0xA0) && !m_playBehaviour[kFT2RestrictXCommand]) pChn->nOldHiOffset = param & 0x0F; break; } // The following calculations are not interesting if we just want to get the song length. if (!(adjustMode & eAdjust)) continue; switch(command) { // Portamento Up/Down case CMD_PORTAMENTOUP: if(param) { // FT2 compatibility: Separate effect memory for all portamento commands // Test case: Porta-LinkMem.xm if(!m_playBehaviour[kFT2PortaUpDownMemory]) pChn->nOldPortaDown = param; pChn->nOldPortaUp = param; } break; case CMD_PORTAMENTODOWN: if(param) { // FT2 compatibility: Separate effect memory for all portamento commands // Test case: Porta-LinkMem.xm if(!m_playBehaviour[kFT2PortaUpDownMemory]) pChn->nOldPortaUp = param; pChn->nOldPortaDown = param; } break; // Tone-Portamento case CMD_TONEPORTAMENTO: if (param) pChn->nPortamentoSlide = param << 2; break; // Offset case CMD_OFFSET: if (param) pChn->oldOffset = param << 8; break; // Volume Slide case CMD_VOLUMESLIDE: case CMD_TONEPORTAVOL: if (param) pChn->nOldVolumeSlide = param; break; // Set Volume case CMD_VOLUME: memory.chnSettings[nChn].vol = param; break; // Global Volume case CMD_GLOBALVOLUME: if(!(GetType() & GLOBALVOL_7BIT_FORMATS) && param < 128) param *= 2; // IT compatibility 16. ST3 and IT ignore out-of-range values if(param <= 128) { playState.m_nGlobalVolume = param * 2; } else if(!(GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT | MOD_TYPE_S3M))) { playState.m_nGlobalVolume = 256; } break; // Global Volume Slide case CMD_GLOBALVOLSLIDE: if(m_playBehaviour[kPerChannelGlobalVolSlide]) { // IT compatibility 16. Global volume slide params are stored per channel (FT2/IT) if (param) pChn->nOldGlobalVolSlide = param; else param = pChn->nOldGlobalVolSlide; } else { if (param) playState.Chn[0].nOldGlobalVolSlide = param; else param = playState.Chn[0].nOldGlobalVolSlide; } if (((param & 0x0F) == 0x0F) && (param & 0xF0)) { param >>= 4; if (!(GetType() & GLOBALVOL_7BIT_FORMATS)) param <<= 1; playState.m_nGlobalVolume += param << 1; } else if (((param & 0xF0) == 0xF0) && (param & 0x0F)) { param = (param & 0x0F) << 1; if (!(GetType() & GLOBALVOL_7BIT_FORMATS)) param <<= 1; playState.m_nGlobalVolume -= param; } else if (param & 0xF0) { param >>= 4; param <<= 1; if (!(GetType() & GLOBALVOL_7BIT_FORMATS)) param <<= 1; playState.m_nGlobalVolume += param * nonRowTicks; } else { param = (param & 0x0F) << 1; if (!(GetType() & GLOBALVOL_7BIT_FORMATS)) param <<= 1; playState.m_nGlobalVolume -= param * nonRowTicks; } Limit(playState.m_nGlobalVolume, 0, 256); break; case CMD_CHANNELVOLUME: if (param <= 64) pChn->nGlobalVol = param; break; case CMD_CHANNELVOLSLIDE: { if (param) pChn->nOldChnVolSlide = param; else param = pChn->nOldChnVolSlide; int32 volume = pChn->nGlobalVol; if((param & 0x0F) == 0x0F && (param & 0xF0)) volume += (param >> 4); // Fine Up else if((param & 0xF0) == 0xF0 && (param & 0x0F)) volume -= (param & 0x0F); // Fine Down else if(param & 0x0F) // Down volume -= (param & 0x0F) * nonRowTicks; else // Up volume += ((param & 0xF0) >> 4) * nonRowTicks; Limit(volume, 0, 64); pChn->nGlobalVol = volume; } break; case CMD_PANNING8: Panning(pChn, param, Pan8bit); break; case CMD_MODCMDEX: if(param < 0x10) { // LED filter for(CHANNELINDEX chn = 0; chn < GetNumChannels(); chn++) { playState.Chn[chn].dwFlags.set(CHN_AMIGAFILTER, !(param & 1)); } } MPT_FALLTHROUGH; case CMD_S3MCMDEX: if((param & 0xF0) == 0x80) { Panning(pChn, (param & 0x0F), Pan4bit); } break; case CMD_VIBRATOVOL: if (param) pChn->nOldVolumeSlide = param; param = 0; MPT_FALLTHROUGH; case CMD_VIBRATO: Vibrato(pChn, param); break; case CMD_FINEVIBRATO: FineVibrato(pChn, param); break; case CMD_TREMOLO: Tremolo(pChn, param); break; case CMD_PANBRELLO: Panbrello(pChn, param); break; } switch(pChn->rowCommand.volcmd) { case VOLCMD_PANNING: Panning(pChn, pChn->rowCommand.vol, Pan6bit); break; case VOLCMD_VIBRATOSPEED: // FT2 does not automatically enable vibrato with the "set vibrato speed" command if(m_playBehaviour[kFT2VolColVibrato]) pChn->nVibratoSpeed = pChn->rowCommand.vol & 0x0F; else Vibrato(pChn, pChn->rowCommand.vol << 4); break; case VOLCMD_VIBRATODEPTH: Vibrato(pChn, pChn->rowCommand.vol); break; } // Process vibrato / tremolo / panbrello switch(pChn->rowCommand.command) { case CMD_VIBRATO: case CMD_FINEVIBRATO: case CMD_VIBRATOVOL: if(adjustMode & eAdjust) { uint32 vibTicks = ((GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT)) && !m_SongFlags[SONG_ITOLDEFFECTS]) ? numTicks : nonRowTicks; uint32 inc = pChn->nVibratoSpeed * vibTicks; if(m_playBehaviour[kITVibratoTremoloPanbrello]) inc *= 4; pChn->nVibratoPos += static_cast<uint8>(inc); } break; case CMD_TREMOLO: if(adjustMode & eAdjust) { uint32 tremTicks = ((GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT)) && !m_SongFlags[SONG_ITOLDEFFECTS]) ? numTicks : nonRowTicks; uint32 inc = pChn->nTremoloSpeed * tremTicks; if(m_playBehaviour[kITVibratoTremoloPanbrello]) inc *= 4; pChn->nTremoloPos += static_cast<uint8>(inc); } break; case CMD_PANBRELLO: if(adjustMode & eAdjust) { // Panbrello effect is permanent in compatible mode, so actually apply panbrello for the last tick of this row pChn->nPanbrelloPos += static_cast<uint8>(pChn->nPanbrelloSpeed * (numTicks - 1)); ProcessPanbrello(pChn); } break; } } // Interpret F00 effect in XM files as "stop song" if(GetType() == MOD_TYPE_XM && playState.m_nMusicSpeed == uint16_max) { break; } playState.m_nCurrentRowsPerBeat = m_nDefaultRowsPerBeat; if(Patterns[playState.m_nPattern].GetOverrideSignature()) { playState.m_nCurrentRowsPerBeat = Patterns[playState.m_nPattern].GetRowsPerBeat(); } const uint32 tickDuration = GetTickDuration(playState); const uint32 rowDuration = tickDuration * numTicks; memory.elapsedTime += static_cast<double>(rowDuration) / static_cast<double>(m_MixerSettings.gdwMixingFreq); playState.m_lTotalSampleCount += rowDuration; if(adjustSamplePos) { // Super experimental and dirty sample seeking pChn = playState.Chn; for(CHANNELINDEX nChn = 0; nChn < GetNumChannels(); pChn++, nChn++) { if(memory.chnSettings[nChn].ticksToRender == GetLengthMemory::IGNORE_CHANNEL) continue; uint32 startTick = 0; const ModCommand &m = pChn->rowCommand; uint32 paramHi = m.param >> 4, paramLo = m.param & 0x0F; bool porta = m.command == CMD_TONEPORTAMENTO || m.command == CMD_TONEPORTAVOL || m.volcmd == VOLCMD_TONEPORTAMENTO; bool stopNote = patternLoopStartedOnThisRow; // It's too much trouble to keep those pattern loops in sync... if(m.instr) pChn->proTrackerOffset = 0; if(m.IsNote()) { if(porta && memory.chnSettings[nChn].incChanged) { // If there's a portamento, the current channel increment mustn't be 0 in NoteChange() pChn->increment = GetChannelIncrement(pChn, pChn->nPeriod, 0); } int32 setPan = pChn->nPan; pChn->nNewNote = pChn->nLastNote; if(pChn->nNewIns != 0) InstrumentChange(pChn, pChn->nNewIns, porta); NoteChange(pChn, m.note, porta); memory.chnSettings[nChn].incChanged = true; if((m.command == CMD_MODCMDEX || m.command == CMD_S3MCMDEX) && (m.param & 0xF0) == 0xD0 && paramLo < numTicks) { startTick = paramLo; } else if(m.command == CMD_DELAYCUT && paramHi < numTicks) { startTick = paramHi; } if(rowDelay > 1 && startTick != 0 && (GetType() & (MOD_TYPE_S3M | MOD_TYPE_IT | MOD_TYPE_MPT))) { startTick += (playState.m_nMusicSpeed + tickDelay) * (rowDelay - 1); } if(!porta) memory.chnSettings[nChn].ticksToRender = 0; // Panning commands have to be re-applied after a note change with potential pan change. if(m.command == CMD_PANNING8 || ((m.command == CMD_MODCMDEX || m.command == CMD_S3MCMDEX) && paramHi == 0x8) || m.volcmd == VOLCMD_PANNING) { pChn->nPan = setPan; } if(m.command == CMD_OFFSET) { bool isExtended = false; SmpLength offset = CalculateXParam(playState.m_nPattern, playState.m_nRow, nChn, &isExtended); if(!isExtended) { offset <<= 8; if(offset == 0) offset = pChn->oldOffset; offset += static_cast<SmpLength>(pChn->nOldHiOffset) << 16; } SampleOffset(*pChn, offset); } else if(m.command == CMD_OFFSETPERCENTAGE) { SampleOffset(*pChn, Util::muldiv_unsigned(pChn->nLength, m.param, 255)); } else if(m.command == CMD_REVERSEOFFSET && pChn->pModSample != nullptr) { memory.RenderChannel(nChn, oldTickDuration); // Re-sync what we've got so far ReverseSampleOffset(*pChn, m.param); startTick = playState.m_nMusicSpeed - 1; } else if(m.volcmd == VOLCMD_OFFSET) { if(m.vol <= CountOf(pChn->pModSample->cues) && pChn->pModSample != nullptr) { SmpLength offset; if(m.vol == 0) offset = pChn->oldOffset; else offset = pChn->oldOffset = pChn->pModSample->cues[m.vol - 1]; SampleOffset(*pChn, offset); } } } if(m.note == NOTE_KEYOFF || m.note == NOTE_NOTECUT || (m.note == NOTE_FADE && GetNumInstruments()) || ((m.command == CMD_MODCMDEX || m.command == CMD_S3MCMDEX) && (m.param & 0xF0) == 0xC0 && paramLo < numTicks) || (m.command == CMD_DELAYCUT && paramLo != 0 && startTick + paramLo < numTicks)) { stopNote = true; } if(m.command == CMD_VOLUME) { pChn->nVolume = m.param * 4; } else if(m.volcmd == VOLCMD_VOLUME) { pChn->nVolume = m.vol * 4; } if(pChn->pModSample && !stopNote) { // Check if we don't want to emulate some effect and thus stop processing. if(m.command < MAX_EFFECTS) { if(forbiddenCommands[m.command]) { stopNote = true; } else if(m.command == CMD_MODCMDEX) { // Special case: Slides using extended commands switch(m.param & 0xF0) { case 0x10: case 0x20: stopNote = true; } } } if(m.volcmd < forbiddenVolCommands.size() && forbiddenVolCommands[m.volcmd]) { stopNote = true; } } if(stopNote) { pChn->Stop(); memory.chnSettings[nChn].ticksToRender = 0; } else { if(oldTickDuration != tickDuration && oldTickDuration != 0) { memory.RenderChannel(nChn, oldTickDuration); // Re-sync what we've got so far } switch(m.command) { case CMD_TONEPORTAVOL: case CMD_VOLUMESLIDE: case CMD_VIBRATOVOL: if(m.param || (GetType() != MOD_TYPE_MOD)) { for(uint32 i = 0; i < numTicks; i++) { pChn->isFirstTick = (i == 0); VolumeSlide(pChn, m.param); } } break; case CMD_MODCMDEX: if((m.param & 0x0F) || (GetType() & (MOD_TYPE_XM | MOD_TYPE_MT2))) { pChn->isFirstTick = true; switch(m.param & 0xF0) { case 0xA0: FineVolumeUp(pChn, m.param & 0x0F, false); break; case 0xB0: FineVolumeDown(pChn, m.param & 0x0F, false); break; } } break; case CMD_S3MCMDEX: if(m.param == 0x9E) { // Play forward memory.RenderChannel(nChn, oldTickDuration); // Re-sync what we've got so far pChn->dwFlags.reset(CHN_PINGPONGFLAG); } else if(m.param == 0x9F) { // Reverse memory.RenderChannel(nChn, oldTickDuration); // Re-sync what we've got so far pChn->dwFlags.set(CHN_PINGPONGFLAG); if(!pChn->position.GetInt() && pChn->nLength && (m.IsNote() || !pChn->dwFlags[CHN_LOOP])) { pChn->position.Set(pChn->nLength - 1, SamplePosition::fractMax); } } else if((m.param & 0xF0) == 0x70) { // TODO //ExtendedS3MCommands(nChn, param); } break; } pChn->isFirstTick = true; switch(m.volcmd) { case VOLCMD_FINEVOLUP: FineVolumeUp(pChn, m.vol, m_playBehaviour[kITVolColMemory]); break; case VOLCMD_FINEVOLDOWN: FineVolumeDown(pChn, m.vol, m_playBehaviour[kITVolColMemory]); break; case VOLCMD_VOLSLIDEUP: case VOLCMD_VOLSLIDEDOWN: { // IT Compatibility: Volume column volume slides have their own memory // Test case: VolColMemory.it ModCommand::VOL vol = m.vol; if(vol == 0 && m_playBehaviour[kITVolColMemory]) { vol = pChn->nOldVolParam; if(vol == 0) break; } if(m.volcmd == VOLCMD_VOLSLIDEUP) vol <<= 4; for(uint32 i = 0; i < numTicks; i++) { pChn->isFirstTick = (i == 0); VolumeSlide(pChn, vol); } } break; } if(porta) { // Portamento needs immediate syncing, as the pitch changes on each tick uint32 portaTick = memory.chnSettings[nChn].ticksToRender + startTick + 1; memory.chnSettings[nChn].ticksToRender += numTicks; memory.RenderChannel(nChn, tickDuration, portaTick); } else { memory.chnSettings[nChn].ticksToRender += (numTicks - startTick); } } } } oldTickDuration = tickDuration; // Pattern loop is not executed in FT2 if there are any position jump or pattern break commands on the same row. // Pattern loop is not executed in IT if there are any position jump commands on the same row. // Test case for FT2 exception: PatLoop-Jumps.xm, PatLoop-Various.xm // Test case for IT: exception: LoopBreak.it if(patternLoopEndedOnThisRow && (!m_playBehaviour[kFT2PatternLoopWithJumps] || !(positionJumpOnThisRow || patternBreakOnThisRow)) && (!m_playBehaviour[kITPatternLoopWithJumps] || !positionJumpOnThisRow)) { std::map<double, int> startTimes; // This is really just a simple estimation for nested pattern loops. It should handle cases correctly where all parallel loops start and end on the same row. // If one of them starts or ends "in between", it will most likely calculate a wrong duration. // For S3M files, it's also way off. pChn = playState.Chn; for(CHANNELINDEX nChn = 0; nChn < GetNumChannels(); nChn++, pChn++) { ModCommand::COMMAND command = pChn->rowCommand.command; ModCommand::PARAM param = pChn->rowCommand.param; if((command == CMD_S3MCMDEX && param >= 0xB1 && param <= 0xBF) || (command == CMD_MODCMDEX && param >= 0x61 && param <= 0x6F)) { const double start = memory.chnSettings[nChn].patLoop; if(!startTimes[start]) startTimes[start] = 1; startTimes[start] = mpt::lcm(startTimes[start], 1 + (param & 0x0F)); } } for(const auto &i : startTimes) { memory.elapsedTime += (memory.elapsedTime - i.first) * (double)(i.second - 1); for(CHANNELINDEX nChn = 0; nChn < GetNumChannels(); nChn++, pChn++) { if(memory.chnSettings[nChn].patLoop == i.first) { playState.m_lTotalSampleCount += (playState.m_lTotalSampleCount - memory.chnSettings[nChn].patLoopSmp) * (i.second - 1); if(m_playBehaviour[kITPatternLoopTargetReset] || (GetType() == MOD_TYPE_S3M)) { memory.chnSettings[nChn].patLoop = memory.elapsedTime; memory.chnSettings[nChn].patLoopSmp = playState.m_lTotalSampleCount; memory.chnSettings[nChn].patLoopStart = playState.m_nRow + 1; } break; } } } if(GetType() == MOD_TYPE_IT) { // IT pattern loop start row update - at the end of a pattern loop, set pattern loop start to next row (for upcoming pattern loops with missing SB0) for(CHANNELINDEX nChn = 0; nChn < GetNumChannels(); nChn++) { if((pChn->rowCommand.command == CMD_S3MCMDEX && pChn->rowCommand.param >= 0xB1 && pChn->rowCommand.param <= 0xBF)) { memory.chnSettings[nChn].patLoop = memory.elapsedTime; memory.chnSettings[nChn].patLoopSmp = playState.m_lTotalSampleCount; } } } } } // Now advance the sample positions for sample seeking on channels that are still playing if(adjustSamplePos) { for(CHANNELINDEX nChn = 0; nChn < GetNumChannels(); nChn++) { if(memory.chnSettings[nChn].ticksToRender != GetLengthMemory::IGNORE_CHANNEL) { memory.RenderChannel(nChn, oldTickDuration); } } } if(retval.targetReached || target.mode == GetLengthTarget::NoTarget) { retval.lastOrder = playState.m_nCurrentOrder; retval.lastRow = playState.m_nRow; } retval.duration = memory.elapsedTime; results.push_back(retval); // Store final variables if(adjustMode & eAdjust) { if(retval.targetReached || target.mode == GetLengthTarget::NoTarget) { // Target found, or there is no target (i.e. play whole song)... m_PlayState = std::move(playState); m_PlayState.m_nNextRow = m_PlayState.m_nRow; m_PlayState.m_nFrameDelay = m_PlayState.m_nPatternDelay = 0; m_PlayState.m_nTickCount = Util::MaxValueOfType(m_PlayState.m_nTickCount) - 1; m_PlayState.m_bPositionChanged = true; for(CHANNELINDEX n = 0; n < GetNumChannels(); n++) { if(m_PlayState.Chn[n].nLastNote != NOTE_NONE) { m_PlayState.Chn[n].nNewNote = m_PlayState.Chn[n].nLastNote; } if(memory.chnSettings[n].vol != 0xFF && !adjustSamplePos) { m_PlayState.Chn[n].nVolume = std::min(memory.chnSettings[n].vol, uint8(64)) * 4; } } #ifndef NO_PLUGINS // If there were any PC events, update plugin parameters to their latest value. std::bitset<MAX_MIXPLUGINS> plugSetProgram; for(const auto &param : memory.plugParams) { PLUGINDEX plug = param.first.first - 1; IMixPlugin *plugin = m_MixPlugins[plug].pMixPlugin; if(plugin != nullptr) { if(!plugSetProgram[plug]) { // Used for bridged plugins to avoid sending out individual messages for each parameter. plugSetProgram.set(plug); plugin->BeginSetProgram(); } plugin->SetParameter(param.first.second, param.second / PlugParamValue(ModCommand::maxColumnValue)); } } if(plugSetProgram.any()) { for(PLUGINDEX i = 0; i < MAX_MIXPLUGINS; i++) { if(plugSetProgram[i]) { m_MixPlugins[i].pMixPlugin->EndSetProgram(); } } } #endif // NO_PLUGINS } else if(adjustMode != eAdjustOnSuccess) { // Target not found (e.g. when jumping to a hidden sub song), reset global variables... m_PlayState.m_nMusicSpeed = m_nDefaultSpeed; m_PlayState.m_nMusicTempo = m_nDefaultTempo; m_PlayState.m_nGlobalVolume = m_nDefaultGlobalVolume; } // When adjusting the playback status, we will also want to update the visited rows vector according to the current position. if(sequence != Order.GetCurrentSequenceIndex()) { Order.SetSequence(sequence); } visitedSongRows.Set(visitedRows); } return results; }
1
CVE-2018-10017
CWE-125
Out-of-bounds Read
The product reads data past the end, or before the beginning, of the intended buffer.
Phase: Implementation Strategy: Input Validation Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a list of acceptable inputs that strictly conform to specifications. Reject any input that does not strictly conform to specifications, or transform it into something that does. When performing input validation, consider all potentially relevant properties, including length, type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency across related fields, and conformance to business rules. As an example of business rule logic, "boat" may be syntactically valid because it only contains alphanumeric characters, but it is not valid if the input is only expected to contain colors such as "red" or "blue." Do not rely exclusively on looking for malicious or malformed inputs. This is likely to miss at least one undesirable input, especially if the code's environment changes. This can give attackers enough room to bypass the intended validation. However, denylists can be useful for detecting potential attacks or determining which inputs are so malformed that they should be rejected outright. To reduce the likelihood of introducing an out-of-bounds read, ensure that you validate and ensure correct calculations for any length argument, buffer size calculation, or offset. Be especially careful of relying on a sentinel (i.e. special character such as NUL) in untrusted inputs. Phase: Architecture and Design Strategy: Language Selection Use a language that provides appropriate memory abstractions.
4,868
weechat
2fb346f25f79e412cf0ed314fdf791763c19b70b
irc_ctcp_display_reply_from_nick (struct t_irc_server *server, time_t date, const char *command, const char *nick, const char *address, char *arguments) { char *pos_end, *pos_space, *pos_args, *pos_usec; struct timeval tv; long sec1, usec1, sec2, usec2, difftime; while (arguments && arguments[0]) { pos_end = strrchr (arguments + 1, '\01'); if (pos_end) pos_end[0] = '\0'; pos_space = strchr (arguments + 1, ' '); if (pos_space) { pos_space[0] = '\0'; pos_args = pos_space + 1; while (pos_args[0] == ' ') { pos_args++; } if (strcmp (arguments + 1, "PING") == 0) { pos_usec = strchr (pos_args, ' '); if (pos_usec) { pos_usec[0] = '\0'; gettimeofday (&tv, NULL); sec1 = atol (pos_args); usec1 = atol (pos_usec + 1); sec2 = tv.tv_sec; usec2 = tv.tv_usec; difftime = ((sec2 * 1000000) + usec2) - ((sec1 * 1000000) + usec1); weechat_printf_date_tags ( irc_msgbuffer_get_target_buffer ( server, nick, NULL, "ctcp", NULL), date, irc_protocol_tags (command, "irc_ctcp", NULL, NULL), /* TRANSLATORS: %.3fs is a float number + "s" ("seconds") */ _("%sCTCP reply from %s%s%s: %s%s%s %.3fs"), weechat_prefix ("network"), irc_nick_color_for_msg (server, 0, NULL, nick), nick, IRC_COLOR_RESET, IRC_COLOR_CHAT_CHANNEL, arguments + 1, IRC_COLOR_RESET, (float)difftime / 1000000.0); pos_usec[0] = ' '; } } else { weechat_printf_date_tags ( irc_msgbuffer_get_target_buffer ( server, nick, NULL, "ctcp", NULL), date, irc_protocol_tags (command, "irc_ctcp", NULL, address), _("%sCTCP reply from %s%s%s: %s%s%s%s%s"), weechat_prefix ("network"), irc_nick_color_for_msg (server, 0, NULL, nick), nick, IRC_COLOR_RESET, IRC_COLOR_CHAT_CHANNEL, arguments + 1, IRC_COLOR_RESET, " ", pos_args); } pos_space[0] = ' '; } else { weechat_printf_date_tags ( irc_msgbuffer_get_target_buffer ( server, nick, NULL, "ctcp", NULL), date, irc_protocol_tags (command, NULL, NULL, address), _("%sCTCP reply from %s%s%s: %s%s%s%s%s"), weechat_prefix ("network"), irc_nick_color_for_msg (server, 0, NULL, nick), nick, IRC_COLOR_RESET, IRC_COLOR_CHAT_CHANNEL, arguments + 1, "", "", ""); } if (pos_end) pos_end[0] = '\01'; arguments = (pos_end) ? pos_end + 1 : NULL; } }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
20,050
linux
e8d5f92b8d30bb4ade76494490c3c065e12411b1
static void gprinter_cleanup(void) { if (major) { unregister_chrdev_region(MKDEV(major, 0), minors); major = minors = 0; } class_destroy(usb_gadget_class); usb_gadget_class = NULL; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
15,166
samba
2632e8ebae826a7305fe7d3948ee28b77d2ffbc0
static bool cname_self_reference(const char* node_name, const char* zone_name, struct DNS_RPC_NAME name) { size_t node_len, zone_len; if (node_name == NULL || zone_name == NULL) { return false; } node_len = strlen(node_name); zone_len = strlen(zone_name); if (node_len == 0 || zone_len == 0 || (name.len != node_len + zone_len + 1)) { return false; } if (strncmp(node_name, name.str, node_len) == 0 && name.str[node_len] == '.' && strncmp(zone_name, name.str + node_len + 1, zone_len) == 0) { return true; } return false; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
15,149
Chrome
17368442aec0f48859a3561ae5e441175c7041ba
service_manager::Connector* DownloadManagerImpl::GetServiceManagerConnector() { DCHECK_CURRENTLY_ON(BrowserThread::UI); if (auto* connection = ServiceManagerConnection::GetForProcess()) return connection->GetConnector(); return nullptr; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
13,023
linux
c91815b596245fd7da349ecc43c8def670d2269e
static void dwc3_reset_gadget(struct dwc3 *dwc) { if (!dwc->gadget_driver) return; if (dwc->gadget.speed != USB_SPEED_UNKNOWN) { spin_unlock(&dwc->lock); usb_gadget_udc_reset(&dwc->gadget, dwc->gadget_driver); spin_lock(&dwc->lock); } }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
13,875
Android
81df1cc77722000f8d0025c1ab00ced123aa573c
static const char* get_sigcode(int signo, int code) { switch (signo) { case SIGILL: switch (code) { case ILL_ILLOPC: return "ILL_ILLOPC"; case ILL_ILLOPN: return "ILL_ILLOPN"; case ILL_ILLADR: return "ILL_ILLADR"; case ILL_ILLTRP: return "ILL_ILLTRP"; case ILL_PRVOPC: return "ILL_PRVOPC"; case ILL_PRVREG: return "ILL_PRVREG"; case ILL_COPROC: return "ILL_COPROC"; case ILL_BADSTK: return "ILL_BADSTK"; } static_assert(NSIGILL == ILL_BADSTK, "missing ILL_* si_code"); break; case SIGBUS: switch (code) { case BUS_ADRALN: return "BUS_ADRALN"; case BUS_ADRERR: return "BUS_ADRERR"; case BUS_OBJERR: return "BUS_OBJERR"; case BUS_MCEERR_AR: return "BUS_MCEERR_AR"; case BUS_MCEERR_AO: return "BUS_MCEERR_AO"; } static_assert(NSIGBUS == BUS_MCEERR_AO, "missing BUS_* si_code"); break; case SIGFPE: switch (code) { case FPE_INTDIV: return "FPE_INTDIV"; case FPE_INTOVF: return "FPE_INTOVF"; case FPE_FLTDIV: return "FPE_FLTDIV"; case FPE_FLTOVF: return "FPE_FLTOVF"; case FPE_FLTUND: return "FPE_FLTUND"; case FPE_FLTRES: return "FPE_FLTRES"; case FPE_FLTINV: return "FPE_FLTINV"; case FPE_FLTSUB: return "FPE_FLTSUB"; } static_assert(NSIGFPE == FPE_FLTSUB, "missing FPE_* si_code"); break; case SIGSEGV: switch (code) { case SEGV_MAPERR: return "SEGV_MAPERR"; case SEGV_ACCERR: return "SEGV_ACCERR"; } static_assert(NSIGSEGV == SEGV_ACCERR, "missing SEGV_* si_code"); break; case SIGTRAP: switch (code) { case TRAP_BRKPT: return "TRAP_BRKPT"; case TRAP_TRACE: return "TRAP_TRACE"; case TRAP_BRANCH: return "TRAP_BRANCH"; case TRAP_HWBKPT: return "TRAP_HWBKPT"; } static_assert(NSIGTRAP == TRAP_HWBKPT, "missing TRAP_* si_code"); break; } switch (code) { case SI_USER: return "SI_USER"; case SI_KERNEL: return "SI_KERNEL"; case SI_QUEUE: return "SI_QUEUE"; case SI_TIMER: return "SI_TIMER"; case SI_MESGQ: return "SI_MESGQ"; case SI_ASYNCIO: return "SI_ASYNCIO"; case SI_SIGIO: return "SI_SIGIO"; case SI_TKILL: return "SI_TKILL"; case SI_DETHREAD: return "SI_DETHREAD"; } return "?"; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
16,686
Chrome
0720b02e4f303ea6b114d4ae9453e3a7ff55f8dc
void WebContentsImpl::EnsureOpenerProxiesExist(RenderFrameHost* source_rfh) { WebContentsImpl* source_web_contents = static_cast<WebContentsImpl*>( WebContents::FromRenderFrameHost(source_rfh)); if (source_web_contents) { if (GetBrowserPluginEmbedder() && GuestMode::IsCrossProcessFrameGuest(source_web_contents)) { return; } if (this != source_web_contents && GetBrowserPluginGuest()) { source_web_contents->GetRenderManager()->CreateRenderFrameProxy( GetSiteInstance()); } else { RenderFrameHostImpl* source_rfhi = static_cast<RenderFrameHostImpl*>(source_rfh); source_rfhi->frame_tree_node()->render_manager()->CreateOpenerProxies( GetSiteInstance(), nullptr); } } }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
10,493
ImageMagick
9f375e7080a2c1044cd546854d0548b4bfb429d0
static MagickBooleanType ReadDCMPixels(Image *image,DCMInfo *info, DCMStreamInfo *stream_info,MagickBooleanType first_segment, ExceptionInfo *exception) { int byte, index; MagickBooleanType status; LongPixelPacket pixel; register ssize_t i, x; register IndexPacket *indexes; register PixelPacket *q; ssize_t y; /* Convert DCM Medical image to pixel packets. */ byte=0; i=0; status=MagickTrue; for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) { if (info->samples_per_pixel == 1) { int pixel_value; if (info->bytes_per_pixel == 1) pixel_value=info->polarity != MagickFalse ? ((int) info->max_value- ReadDCMByte(stream_info,image)) : ReadDCMByte(stream_info,image); else if ((info->bits_allocated != 12) || (info->significant_bits != 12)) { if (info->signed_data) pixel_value=ReadDCMSignedShort(stream_info,image); else pixel_value=(int) ReadDCMShort(stream_info,image); if (info->polarity != MagickFalse) pixel_value=(int) info->max_value-pixel_value; } else { if ((i & 0x01) != 0) pixel_value=(ReadDCMByte(stream_info,image) << 8) | byte; else { pixel_value=ReadDCMSignedShort(stream_info,image); byte=(int) (pixel_value & 0x0f); pixel_value>>=4; } i++; } if (info->signed_data == 1) pixel_value-=32767; if (info->rescale) { double scaled_value; scaled_value=pixel_value*info->rescale_slope+ info->rescale_intercept; if (info->window_width == 0) { index=(int) scaled_value; } else { double window_max, window_min; window_min=ceil(info->window_center- (info->window_width-1.0)/2.0-0.5); window_max=floor(info->window_center+ (info->window_width-1.0)/2.0+0.5); if (scaled_value <= window_min) index=0; else if (scaled_value > window_max) index=(int) info->max_value; else index=(int) (info->max_value*(((scaled_value- info->window_center-0.5)/(info->window_width-1))+0.5)); } } else { index=pixel_value; } index&=info->mask; index=(int) ConstrainColormapIndex(image,(size_t) index); if (first_segment != MagickFalse) SetPixelIndex(indexes+x,index); else SetPixelIndex(indexes+x,(((size_t) index) | (((size_t) GetPixelIndex(indexes+x)) << 8))); pixel.red=1U*image->colormap[index].red; pixel.green=1U*image->colormap[index].green; pixel.blue=1U*image->colormap[index].blue; } else { if (info->bytes_per_pixel == 1) { pixel.red=(unsigned int) ReadDCMByte(stream_info,image); pixel.green=(unsigned int) ReadDCMByte(stream_info,image); pixel.blue=(unsigned int) ReadDCMByte(stream_info,image); } else { pixel.red=ReadDCMShort(stream_info,image); pixel.green=ReadDCMShort(stream_info,image); pixel.blue=ReadDCMShort(stream_info,image); } pixel.red&=info->mask; pixel.green&=info->mask; pixel.blue&=info->mask; if (info->scale != (Quantum *) NULL) { if ((MagickSizeType) pixel.red <= GetQuantumRange(info->depth)) pixel.red=info->scale[pixel.red]; if ((MagickSizeType) pixel.green <= GetQuantumRange(info->depth)) pixel.green=info->scale[pixel.green]; if ((MagickSizeType) pixel.blue <= GetQuantumRange(info->depth)) pixel.blue=info->scale[pixel.blue]; } } if (first_segment != MagickFalse) { SetPixelRed(q,pixel.red); SetPixelGreen(q,pixel.green); SetPixelBlue(q,pixel.blue); } else { SetPixelRed(q,(((size_t) pixel.red) | (((size_t) GetPixelRed(q)) << 8))); SetPixelGreen(q,(((size_t) pixel.green) | (((size_t) GetPixelGreen(q)) << 8))); SetPixelBlue(q,(((size_t) pixel.blue) | (((size_t) GetPixelBlue(q)) << 8))); } q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } return(status); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
23,003
ImageMagick6
4a334bbf5584de37c6f5a47c380a531c8c4b140a
WandExport MagickBooleanType MogrifyImageCommand(ImageInfo *image_info, int argc,char **argv,char **wand_unused(metadata),ExceptionInfo *exception) { #define DestroyMogrify() \ { \ if (format != (char *) NULL) \ format=DestroyString(format); \ if (path != (char *) NULL) \ path=DestroyString(path); \ DestroyImageStack(); \ for (i=0; i < (ssize_t) argc; i++) \ argv[i]=DestroyString(argv[i]); \ argv=(char **) RelinquishMagickMemory(argv); \ } #define ThrowMogrifyException(asperity,tag,option) \ { \ (void) ThrowMagickException(exception,GetMagickModule(),asperity,tag,"`%s'", \ option); \ DestroyMogrify(); \ return(MagickFalse); \ } #define ThrowMogrifyInvalidArgumentException(option,argument) \ { \ (void) ThrowMagickException(exception,GetMagickModule(),OptionError, \ "InvalidArgument","'%s': %s",argument,option); \ DestroyMogrify(); \ return(MagickFalse); \ } char *format, *option, *path; Image *image; ImageStack image_stack[MaxImageStackDepth+1]; MagickBooleanType global_colormap; MagickBooleanType fire, pend, respect_parenthesis; MagickStatusType status; register ssize_t i; ssize_t j, k; wand_unreferenced(metadata); /* Set defaults. */ assert(image_info != (ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(exception != (ExceptionInfo *) NULL); if (argc == 2) { option=argv[1]; if ((LocaleCompare("version",option+1) == 0) || (LocaleCompare("-version",option+1) == 0)) { ListMagickVersion(stdout); return(MagickTrue); } } if (argc < 2) return(MogrifyUsage()); format=(char *) NULL; path=(char *) NULL; global_colormap=MagickFalse; k=0; j=1; NewImageStack(); option=(char *) NULL; pend=MagickFalse; respect_parenthesis=MagickFalse; status=MagickTrue; /* Parse command line. */ ReadCommandlLine(argc,&argv); status=ExpandFilenames(&argc,&argv); if (status == MagickFalse) ThrowMogrifyException(ResourceLimitError,"MemoryAllocationFailed", GetExceptionMessage(errno)); for (i=1; i < (ssize_t) argc; i++) { option=argv[i]; if (LocaleCompare(option,"(") == 0) { FireImageStack(MagickFalse,MagickTrue,pend); if (k == MaxImageStackDepth) ThrowMogrifyException(OptionError,"ParenthesisNestedTooDeeply", option); PushImageStack(); continue; } if (LocaleCompare(option,")") == 0) { FireImageStack(MagickFalse,MagickTrue,MagickTrue); if (k == 0) ThrowMogrifyException(OptionError,"UnableToParseExpression",option); PopImageStack(); continue; } if (IsCommandOption(option) == MagickFalse) { char backup_filename[MagickPathExtent], *filename; Image *images; struct stat properties; /* Option is a file name: begin by reading image from specified file. */ FireImageStack(MagickFalse,MagickFalse,pend); filename=argv[i]; if ((LocaleCompare(filename,"--") == 0) && (i < (ssize_t) (argc-1))) filename=argv[++i]; images=ReadImages(image_info,filename,exception); status&=(images != (Image *) NULL) && (exception->severity < ErrorException); if (images == (Image *) NULL) continue; properties=(*GetBlobProperties(images)); if (format != (char *) NULL) (void) CopyMagickString(images->filename,images->magick_filename, MagickPathExtent); if (path != (char *) NULL) { GetPathComponent(option,TailPath,filename); (void) FormatLocaleString(images->filename,MagickPathExtent, "%s%c%s",path,*DirectorySeparator,filename); } if (format != (char *) NULL) AppendImageFormat(format,images->filename); AppendImageStack(images); FinalizeImageSettings(image_info,image,MagickFalse); if (global_colormap != MagickFalse) { QuantizeInfo *quantize_info; quantize_info=AcquireQuantizeInfo(image_info); (void) RemapImages(quantize_info,images,(Image *) NULL,exception); quantize_info=DestroyQuantizeInfo(quantize_info); } *backup_filename='\0'; if ((LocaleCompare(image->filename,"-") != 0) && (IsPathWritable(image->filename) != MagickFalse)) { /* Rename image file as backup. */ (void) CopyMagickString(backup_filename,image->filename, MagickPathExtent); for (j=0; j < 6; j++) { (void) ConcatenateMagickString(backup_filename,"~", MagickPathExtent); if (IsPathAccessible(backup_filename) == MagickFalse) break; } if ((IsPathAccessible(backup_filename) != MagickFalse) || (rename_utf8(image->filename,backup_filename) != 0)) *backup_filename='\0'; } /* Write transmogrified image to disk. */ image_info->synchronize=MagickTrue; status&=WriteImages(image_info,image,image->filename,exception); if (status != MagickFalse) { #if defined(MAGICKCORE_HAVE_UTIME) { MagickBooleanType preserve_timestamp; preserve_timestamp=IsStringTrue(GetImageOption(image_info, "preserve-timestamp")); if (preserve_timestamp != MagickFalse) { struct utimbuf timestamp; timestamp.actime=properties.st_atime; timestamp.modtime=properties.st_mtime; (void) utime(image->filename,&timestamp); } } #endif if (*backup_filename != '\0') (void) remove_utf8(backup_filename); } RemoveAllImageStack(); continue; } pend=image != (Image *) NULL ? MagickTrue : MagickFalse; switch (*(option+1)) { case 'a': { if (LocaleCompare("adaptive-blur",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare("adaptive-resize",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare("adaptive-sharpen",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare("affine",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); break; } if (LocaleCompare("alpha",option+1) == 0) { ssize_t type; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); type=ParseCommandOption(MagickAlphaChannelOptions,MagickFalse, argv[i]); if (type < 0) ThrowMogrifyException(OptionError, "UnrecognizedAlphaChannelOption",argv[i]); break; } if (LocaleCompare("annotate",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); i++; break; } if (LocaleCompare("antialias",option+1) == 0) break; if (LocaleCompare("append",option+1) == 0) break; if (LocaleCompare("attenuate",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare("authenticate",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); break; } if (LocaleCompare("auto-gamma",option+1) == 0) break; if (LocaleCompare("auto-level",option+1) == 0) break; if (LocaleCompare("auto-orient",option+1) == 0) break; if (LocaleCompare("auto-threshold",option+1) == 0) { ssize_t method; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); method=ParseCommandOption(MagickAutoThresholdOptions,MagickFalse, argv[i]); if (method < 0) ThrowMogrifyException(OptionError,"UnrecognizedThresholdMethod", argv[i]); break; } if (LocaleCompare("average",option+1) == 0) break; ThrowMogrifyException(OptionError,"UnrecognizedOption",option) } case 'b': { if (LocaleCompare("background",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); break; } if (LocaleCompare("bias",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare("black-point-compensation",option+1) == 0) break; if (LocaleCompare("black-threshold",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare("blue-primary",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare("blue-shift",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare("blur",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare("border",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare("bordercolor",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); break; } if (LocaleCompare("box",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); break; } if (LocaleCompare("brightness-contrast",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } ThrowMogrifyException(OptionError,"UnrecognizedOption",option) } case 'c': { if (LocaleCompare("cache",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare("canny",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare("caption",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); break; } if (LocaleCompare("channel",option+1) == 0) { ssize_t channel; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); channel=ParseChannelOption(argv[i]); if (channel < 0) ThrowMogrifyException(OptionError,"UnrecognizedChannelType", argv[i]); break; } if (LocaleCompare("channel-fx",option+1) == 0) { ssize_t channel; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); channel=ParsePixelChannelOption(argv[i]); if (channel < 0) ThrowMogrifyException(OptionError,"UnrecognizedChannelType", argv[i]); break; } if (LocaleCompare("cdl",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); break; } if (LocaleCompare("charcoal",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare("chop",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare("clahe",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare("clamp",option+1) == 0) break; if (LocaleCompare("clip",option+1) == 0) break; if (LocaleCompare("clip-mask",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); break; } if (LocaleCompare("clut",option+1) == 0) break; if (LocaleCompare("coalesce",option+1) == 0) break; if (LocaleCompare("colorize",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare("color-matrix",option+1) == 0) { KernelInfo *kernel_info; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); kernel_info=AcquireKernelInfo(argv[i],exception); if (kernel_info == (KernelInfo *) NULL) ThrowMogrifyInvalidArgumentException(option,argv[i]); kernel_info=DestroyKernelInfo(kernel_info); break; } if (LocaleCompare("colors",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare("colorspace",option+1) == 0) { ssize_t colorspace; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); colorspace=ParseCommandOption(MagickColorspaceOptions,MagickFalse, argv[i]); if (colorspace < 0) ThrowMogrifyException(OptionError,"UnrecognizedColorspace", argv[i]); break; } if (LocaleCompare("combine",option+1) == 0) { ssize_t colorspace; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); colorspace=ParseCommandOption(MagickColorspaceOptions,MagickFalse, argv[i]); if (colorspace < 0) ThrowMogrifyException(OptionError,"UnrecognizedColorspace", argv[i]); break; } if (LocaleCompare("compare",option+1) == 0) break; if (LocaleCompare("comment",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); break; } if (LocaleCompare("composite",option+1) == 0) break; if (LocaleCompare("compress",option+1) == 0) { ssize_t compress; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); compress=ParseCommandOption(MagickCompressOptions,MagickFalse, argv[i]); if (compress < 0) ThrowMogrifyException(OptionError,"UnrecognizedImageCompression", argv[i]); break; } if (LocaleCompare("concurrent",option+1) == 0) break; if (LocaleCompare("connected-components",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare("contrast",option+1) == 0) break; if (LocaleCompare("contrast-stretch",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare("convolve",option+1) == 0) { KernelInfo *kernel_info; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); kernel_info=AcquireKernelInfo(argv[i],exception); if (kernel_info == (KernelInfo *) NULL) ThrowMogrifyInvalidArgumentException(option,argv[i]); kernel_info=DestroyKernelInfo(kernel_info); break; } if (LocaleCompare("copy",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare("crop",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare("cycle",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } ThrowMogrifyException(OptionError,"UnrecognizedOption",option) } case 'd': { if (LocaleCompare("decipher",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); break; } if (LocaleCompare("deconstruct",option+1) == 0) break; if (LocaleCompare("debug",option+1) == 0) { ssize_t event; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); event=ParseCommandOption(MagickLogEventOptions,MagickFalse,argv[i]); if (event < 0) ThrowMogrifyException(OptionError,"UnrecognizedEventType", argv[i]); (void) SetLogEventMask(argv[i]); break; } if (LocaleCompare("define",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); if (*option == '+') { const char *define; define=GetImageOption(image_info,argv[i]); if (define == (const char *) NULL) ThrowMogrifyException(OptionError,"NoSuchOption",argv[i]); break; } break; } if (LocaleCompare("delay",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare("delete",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare("density",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare("depth",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare("deskew",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare("despeckle",option+1) == 0) break; if (LocaleCompare("dft",option+1) == 0) break; if (LocaleCompare("direction",option+1) == 0) { ssize_t direction; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); direction=ParseCommandOption(MagickDirectionOptions,MagickFalse, argv[i]); if (direction < 0) ThrowMogrifyException(OptionError,"UnrecognizedDirectionType", argv[i]); break; } if (LocaleCompare("display",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); break; } if (LocaleCompare("dispose",option+1) == 0) { ssize_t dispose; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); dispose=ParseCommandOption(MagickDisposeOptions,MagickFalse, argv[i]); if (dispose < 0) ThrowMogrifyException(OptionError,"UnrecognizedDisposeMethod", argv[i]); break; } if (LocaleCompare("distort",option+1) == 0) { ssize_t op; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); op=ParseCommandOption(MagickDistortOptions,MagickFalse,argv[i]); if (op < 0) ThrowMogrifyException(OptionError,"UnrecognizedDistortMethod", argv[i]); i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); break; } if (LocaleCompare("dither",option+1) == 0) { ssize_t method; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); method=ParseCommandOption(MagickDitherOptions,MagickFalse,argv[i]); if (method < 0) ThrowMogrifyException(OptionError,"UnrecognizedDitherMethod", argv[i]); break; } if (LocaleCompare("draw",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); break; } if (LocaleCompare("duplicate",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare("duration",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } ThrowMogrifyException(OptionError,"UnrecognizedOption",option) } case 'e': { if (LocaleCompare("edge",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare("emboss",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare("encipher",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); break; } if (LocaleCompare("encoding",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); break; } if (LocaleCompare("endian",option+1) == 0) { ssize_t endian; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); endian=ParseCommandOption(MagickEndianOptions,MagickFalse,argv[i]); if (endian < 0) ThrowMogrifyException(OptionError,"UnrecognizedEndianType", argv[i]); break; } if (LocaleCompare("enhance",option+1) == 0) break; if (LocaleCompare("equalize",option+1) == 0) break; if (LocaleCompare("evaluate",option+1) == 0) { ssize_t op; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); op=ParseCommandOption(MagickEvaluateOptions,MagickFalse,argv[i]); if (op < 0) ThrowMogrifyException(OptionError,"UnrecognizedEvaluateOperator", argv[i]); i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare("evaluate-sequence",option+1) == 0) { ssize_t op; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); op=ParseCommandOption(MagickEvaluateOptions,MagickFalse,argv[i]); if (op < 0) ThrowMogrifyException(OptionError,"UnrecognizedEvaluateOperator", argv[i]); break; } if (LocaleCompare("extent",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare("extract",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } ThrowMogrifyException(OptionError,"UnrecognizedOption",option) } case 'f': { if (LocaleCompare("family",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); break; } if (LocaleCompare("features",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare("fill",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); break; } if (LocaleCompare("filter",option+1) == 0) { ssize_t filter; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); filter=ParseCommandOption(MagickFilterOptions,MagickFalse,argv[i]); if (filter < 0) ThrowMogrifyException(OptionError,"UnrecognizedImageFilter", argv[i]); break; } if (LocaleCompare("flatten",option+1) == 0) break; if (LocaleCompare("flip",option+1) == 0) break; if (LocaleCompare("flop",option+1) == 0) break; if (LocaleCompare("floodfill",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); break; } if (LocaleCompare("font",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); break; } if (LocaleCompare("format",option+1) == 0) { (void) CopyMagickString(argv[i]+1,"sans",MagickPathExtent); (void) CloneString(&format,(char *) NULL); if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); (void) CloneString(&format,argv[i]); (void) CopyMagickString(image_info->filename,format, MagickPathExtent); (void) ConcatenateMagickString(image_info->filename,":", MagickPathExtent); (void) SetImageInfo(image_info,0,exception); if (*image_info->magick == '\0') ThrowMogrifyException(OptionError,"UnrecognizedImageFormat", format); break; } if (LocaleCompare("frame",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare("function",option+1) == 0) { ssize_t op; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); op=ParseCommandOption(MagickFunctionOptions,MagickFalse,argv[i]); if (op < 0) ThrowMogrifyException(OptionError,"UnrecognizedFunction",argv[i]); i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); break; } if (LocaleCompare("fuzz",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare("fx",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); break; } ThrowMogrifyException(OptionError,"UnrecognizedOption",option) } case 'g': { if (LocaleCompare("gamma",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if ((LocaleCompare("gaussian-blur",option+1) == 0) || (LocaleCompare("gaussian",option+1) == 0)) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare("geometry",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare("gravity",option+1) == 0) { ssize_t gravity; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); gravity=ParseCommandOption(MagickGravityOptions,MagickFalse, argv[i]); if (gravity < 0) ThrowMogrifyException(OptionError,"UnrecognizedGravityType", argv[i]); break; } if (LocaleCompare("grayscale",option+1) == 0) { ssize_t method; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); method=ParseCommandOption(MagickPixelIntensityOptions,MagickFalse, argv[i]); if (method < 0) ThrowMogrifyException(OptionError,"UnrecognizedIntensityMethod", argv[i]); break; } if (LocaleCompare("green-primary",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } ThrowMogrifyException(OptionError,"UnrecognizedOption",option) } case 'h': { if (LocaleCompare("hald-clut",option+1) == 0) break; if ((LocaleCompare("help",option+1) == 0) || (LocaleCompare("-help",option+1) == 0)) return(MogrifyUsage()); if (LocaleCompare("hough-lines",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } ThrowMogrifyException(OptionError,"UnrecognizedOption",option) } case 'i': { if (LocaleCompare("identify",option+1) == 0) break; if (LocaleCompare("idft",option+1) == 0) break; if (LocaleCompare("implode",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare("intensity",option+1) == 0) { ssize_t intensity; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); intensity=ParseCommandOption(MagickPixelIntensityOptions, MagickFalse,argv[i]); if (intensity < 0) ThrowMogrifyException(OptionError, "UnrecognizedPixelIntensityMethod",argv[i]); break; } if (LocaleCompare("intent",option+1) == 0) { ssize_t intent; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); intent=ParseCommandOption(MagickIntentOptions,MagickFalse,argv[i]); if (intent < 0) ThrowMogrifyException(OptionError,"UnrecognizedIntentType", argv[i]); break; } if (LocaleCompare("interlace",option+1) == 0) { ssize_t interlace; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); interlace=ParseCommandOption(MagickInterlaceOptions,MagickFalse, argv[i]); if (interlace < 0) ThrowMogrifyException(OptionError,"UnrecognizedInterlaceType", argv[i]); break; } if (LocaleCompare("interline-spacing",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare("interpolate",option+1) == 0) { ssize_t interpolate; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); interpolate=ParseCommandOption(MagickInterpolateOptions,MagickFalse, argv[i]); if (interpolate < 0) ThrowMogrifyException(OptionError,"UnrecognizedInterpolateMethod", argv[i]); break; } if (LocaleCompare("interword-spacing",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } ThrowMogrifyException(OptionError,"UnrecognizedOption",option) } case 'k': { if (LocaleCompare("kerning",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare("kuwahara",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } ThrowMogrifyException(OptionError,"UnrecognizedOption",option) } case 'l': { if (LocaleCompare("label",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); break; } if (LocaleCompare("lat",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); } if (LocaleCompare("layers",option+1) == 0) { ssize_t type; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); type=ParseCommandOption(MagickLayerOptions,MagickFalse,argv[i]); if (type < 0) ThrowMogrifyException(OptionError,"UnrecognizedLayerMethod", argv[i]); break; } if (LocaleCompare("level",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare("level-colors",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); break; } if (LocaleCompare("limit",option+1) == 0) { char *p; double value; ssize_t resource; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); resource=ParseCommandOption(MagickResourceOptions,MagickFalse, argv[i]); if (resource < 0) ThrowMogrifyException(OptionError,"UnrecognizedResourceType", argv[i]); i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); value=StringToDouble(argv[i],&p); (void) value; if ((p == argv[i]) && (LocaleCompare("unlimited",argv[i]) != 0)) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare("liquid-rescale",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare("list",option+1) == 0) { ssize_t list; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); list=ParseCommandOption(MagickListOptions,MagickFalse,argv[i]); if (list < 0) ThrowMogrifyException(OptionError,"UnrecognizedListType",argv[i]); status=MogrifyImageInfo(image_info,(int) (i-j+1),(const char **) argv+j,exception); return(status == 0 ? MagickFalse : MagickTrue); } if (LocaleCompare("log",option+1) == 0) { if (*option == '+') break; i++; if ((i == (ssize_t) argc) || (strchr(argv[i],'%') == (char *) NULL)) ThrowMogrifyException(OptionError,"MissingArgument",option); break; } if (LocaleCompare("loop",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } ThrowMogrifyException(OptionError,"UnrecognizedOption",option) } case 'm': { if (LocaleCompare("magnify",option+1) == 0) break; if (LocaleCompare("map",option+1) == 0) { global_colormap=(*option == '+') ? MagickTrue : MagickFalse; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); break; } if (LocaleCompare("mask",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); break; } if (LocaleCompare("matte",option+1) == 0) break; if (LocaleCompare("mattecolor",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); break; } if (LocaleCompare("maximum",option+1) == 0) break; if (LocaleCompare("mean-shift",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare("median",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare("metric",option+1) == 0) { ssize_t type; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); type=ParseCommandOption(MagickMetricOptions,MagickTrue,argv[i]); if (type < 0) ThrowMogrifyException(OptionError,"UnrecognizedMetricType", argv[i]); break; } if (LocaleCompare("minimum",option+1) == 0) break; if (LocaleCompare("modulate",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare("mode",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare("monitor",option+1) == 0) break; if (LocaleCompare("monochrome",option+1) == 0) break; if (LocaleCompare("morph",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare("morphology",option+1) == 0) { char token[MagickPathExtent]; KernelInfo *kernel_info; ssize_t op; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); GetNextToken(argv[i],(const char **) NULL,MagickPathExtent,token); op=ParseCommandOption(MagickMorphologyOptions,MagickFalse,token); if (op < 0) ThrowMogrifyException(OptionError,"UnrecognizedMorphologyMethod", token); i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); kernel_info=AcquireKernelInfo(argv[i],exception); if (kernel_info == (KernelInfo *) NULL) ThrowMogrifyInvalidArgumentException(option,argv[i]); kernel_info=DestroyKernelInfo(kernel_info); break; } if (LocaleCompare("mosaic",option+1) == 0) break; if (LocaleCompare("motion-blur",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } ThrowMogrifyException(OptionError,"UnrecognizedOption",option) } case 'n': { if (LocaleCompare("negate",option+1) == 0) break; if (LocaleCompare("noise",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); if (*option == '+') { ssize_t noise; noise=ParseCommandOption(MagickNoiseOptions,MagickFalse, argv[i]); if (noise < 0) ThrowMogrifyException(OptionError,"UnrecognizedNoiseType", argv[i]); break; } if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare("noop",option+1) == 0) break; if (LocaleCompare("normalize",option+1) == 0) break; ThrowMogrifyException(OptionError,"UnrecognizedOption",option) } case 'o': { if (LocaleCompare("opaque",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); break; } if (LocaleCompare("ordered-dither",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); break; } if (LocaleCompare("orient",option+1) == 0) { ssize_t orientation; orientation=UndefinedOrientation; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); orientation=ParseCommandOption(MagickOrientationOptions,MagickFalse, argv[i]); if (orientation < 0) ThrowMogrifyException(OptionError,"UnrecognizedImageOrientation", argv[i]); break; } ThrowMogrifyException(OptionError,"UnrecognizedOption",option) } case 'p': { if (LocaleCompare("page",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); break; } if (LocaleCompare("paint",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare("path",option+1) == 0) { (void) CloneString(&path,(char *) NULL); if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); (void) CloneString(&path,argv[i]); break; } if (LocaleCompare("perceptible",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare("pointsize",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare("polaroid",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare("poly",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare("posterize",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare("precision",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare("print",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); break; } if (LocaleCompare("process",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); break; } if (LocaleCompare("profile",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); break; } ThrowMogrifyException(OptionError,"UnrecognizedOption",option) } case 'q': { if (LocaleCompare("quality",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare("quantize",option+1) == 0) { ssize_t colorspace; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); colorspace=ParseCommandOption(MagickColorspaceOptions,MagickFalse, argv[i]); if (colorspace < 0) ThrowMogrifyException(OptionError,"UnrecognizedColorspace", argv[i]); break; } if (LocaleCompare("quiet",option+1) == 0) break; ThrowMogrifyException(OptionError,"UnrecognizedOption",option) } case 'r': { if (LocaleCompare("rotational-blur",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare("raise",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare("random-threshold",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare("range-threshold",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare("read-mask",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); break; } if (LocaleCompare("red-primary",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); } if (LocaleCompare("regard-warnings",option+1) == 0) break; if (LocaleCompare("region",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare("remap",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); break; } if (LocaleCompare("render",option+1) == 0) break; if (LocaleCompare("repage",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare("resample",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare("resize",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleNCompare("respect-parentheses",option+1,17) == 0) { respect_parenthesis=(*option == '-') ? MagickTrue : MagickFalse; break; } if (LocaleCompare("reverse",option+1) == 0) break; if (LocaleCompare("roll",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare("rotate",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } ThrowMogrifyException(OptionError,"UnrecognizedOption",option) } case 's': { if (LocaleCompare("sample",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare("sampling-factor",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare("scale",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare("scene",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare("seed",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare("segment",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare("selective-blur",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare("separate",option+1) == 0) break; if (LocaleCompare("sepia-tone",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare("set",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); break; } if (LocaleCompare("shade",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare("shadow",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare("sharpen",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare("shave",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare("shear",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare("sigmoidal-contrast",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare("size",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare("sketch",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare("smush",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); i++; break; } if (LocaleCompare("solarize",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare("sparse-color",option+1) == 0) { ssize_t op; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); op=ParseCommandOption(MagickSparseColorOptions,MagickFalse,argv[i]); if (op < 0) ThrowMogrifyException(OptionError,"UnrecognizedSparseColorMethod", argv[i]); i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); break; } if (LocaleCompare("splice",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare("spread",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare("statistic",option+1) == 0) { ssize_t op; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); op=ParseCommandOption(MagickStatisticOptions,MagickFalse,argv[i]); if (op < 0) ThrowMogrifyException(OptionError,"UnrecognizedStatisticType", argv[i]); i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare("stretch",option+1) == 0) { ssize_t stretch; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); stretch=ParseCommandOption(MagickStretchOptions,MagickFalse, argv[i]); if (stretch < 0) ThrowMogrifyException(OptionError,"UnrecognizedStyleType", argv[i]); break; } if (LocaleCompare("strip",option+1) == 0) break; if (LocaleCompare("stroke",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); break; } if (LocaleCompare("strokewidth",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare("style",option+1) == 0) { ssize_t style; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); style=ParseCommandOption(MagickStyleOptions,MagickFalse,argv[i]); if (style < 0) ThrowMogrifyException(OptionError,"UnrecognizedStyleType", argv[i]); break; } if (LocaleCompare("swap",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare("swirl",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare("synchronize",option+1) == 0) break; ThrowMogrifyException(OptionError,"UnrecognizedOption",option) } case 't': { if (LocaleCompare("taint",option+1) == 0) break; if (LocaleCompare("texture",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); break; } if (LocaleCompare("tile",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); break; } if (LocaleCompare("tile-offset",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare("tint",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare("transform",option+1) == 0) break; if (LocaleCompare("transpose",option+1) == 0) break; if (LocaleCompare("transverse",option+1) == 0) break; if (LocaleCompare("threshold",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare("thumbnail",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare("transparent",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); break; } if (LocaleCompare("transparent-color",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); break; } if (LocaleCompare("treedepth",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare("trim",option+1) == 0) break; if (LocaleCompare("type",option+1) == 0) { ssize_t type; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); type=ParseCommandOption(MagickTypeOptions,MagickFalse,argv[i]); if (type < 0) ThrowMogrifyException(OptionError,"UnrecognizedImageType", argv[i]); break; } ThrowMogrifyException(OptionError,"UnrecognizedOption",option) } case 'u': { if (LocaleCompare("undercolor",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); break; } if (LocaleCompare("unique-colors",option+1) == 0) break; if (LocaleCompare("units",option+1) == 0) { ssize_t units; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); units=ParseCommandOption(MagickResolutionOptions,MagickFalse, argv[i]); if (units < 0) ThrowMogrifyException(OptionError,"UnrecognizedUnitsType", argv[i]); break; } if (LocaleCompare("unsharp",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } ThrowMogrifyException(OptionError,"UnrecognizedOption",option) } case 'v': { if (LocaleCompare("verbose",option+1) == 0) { image_info->verbose=(*option == '-') ? MagickTrue : MagickFalse; break; } if ((LocaleCompare("version",option+1) == 0) || (LocaleCompare("-version",option+1) == 0)) { ListMagickVersion(stdout); break; } if (LocaleCompare("vignette",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare("virtual-pixel",option+1) == 0) { ssize_t method; if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); method=ParseCommandOption(MagickVirtualPixelOptions,MagickFalse, argv[i]); if (method < 0) ThrowMogrifyException(OptionError, "UnrecognizedVirtualPixelMethod",argv[i]); break; } ThrowMogrifyException(OptionError,"UnrecognizedOption",option) } case 'w': { if (LocaleCompare("wave",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare("wavelet-denoise",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare("weight",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); break; } if (LocaleCompare("white-point",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare("white-threshold",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); if (IsGeometry(argv[i]) == MagickFalse) ThrowMogrifyInvalidArgumentException(option,argv[i]); break; } if (LocaleCompare("write",option+1) == 0) { i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); break; } if (LocaleCompare("write-mask",option+1) == 0) { if (*option == '+') break; i++; if (i == (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingArgument",option); break; } ThrowMogrifyException(OptionError,"UnrecognizedOption",option) } case '?': break; default: ThrowMogrifyException(OptionError,"UnrecognizedOption",option) } fire=(GetCommandOptionFlags(MagickCommandOptions,MagickFalse,option) & FireOptionFlag) == 0 ? MagickFalse : MagickTrue; if (fire != MagickFalse) FireImageStack(MagickFalse,MagickTrue,MagickTrue); } if (k != 0) ThrowMogrifyException(OptionError,"UnbalancedParenthesis",argv[i]); if (i != (ssize_t) argc) ThrowMogrifyException(OptionError,"MissingAnImageFilename",argv[i]); DestroyMogrify(); return(status != 0 ? MagickTrue : MagickFalse); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
17,764
Chrome
eea3300239f0b53e172a320eb8de59d0bea65f27
void DevToolsUIBindings::SetWhitelistedShortcuts(const std::string& message) { delegate_->SetWhitelistedShortcuts(message); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
11,531
tk
ebd0fc80d62eeb7b8556522256f8d035e013eb65
call_queue_handler(evPtr, flags) Tcl_Event *evPtr; int flags; { struct call_queue *q = (struct call_queue *)evPtr; volatile VALUE ret; volatile VALUE q_dat; volatile VALUE thread = q->thread; struct tcltkip *ptr; DUMP2("do_call_queue_handler : evPtr = %p", evPtr); DUMP2("call_queue_handler thread : %"PRIxVALUE, rb_thread_current()); DUMP2("added by thread : %"PRIxVALUE, thread); if (*(q->done)) { DUMP1("processed by another event-loop"); return 0; } else { DUMP1("process it on current event-loop"); } if (RTEST(rb_thread_alive_p(thread)) && ! RTEST(rb_funcall(thread, ID_stop_p, 0))) { DUMP1("caller is not yet ready to receive the result -> pending"); return 0; } /* process it */ *(q->done) = 1; /* deleted ipterp ? */ ptr = get_ip(q->interp); if (deleted_ip(ptr)) { /* deleted IP --> ignore */ return 1; } /* incr internal handler mark */ rbtk_internal_eventloop_handler++; /* check safe-level */ if (rb_safe_level() != q->safe_level) { /* q_dat = Data_Wrap_Struct(rb_cData,0,-1,q); */ q_dat = Data_Wrap_Struct(0,call_queue_mark,-1,q); ret = rb_funcall(rb_proc_new(callq_safelevel_handler, q_dat), ID_call, 0); rb_gc_force_recycle(q_dat); q_dat = (VALUE)NULL; } else { DUMP2("call function (for caller thread:%"PRIxVALUE")", thread); DUMP2("call function (current thread:%"PRIxVALUE")", rb_thread_current()); ret = (q->func)(q->interp, q->argc, q->argv); } /* set result */ RARRAY_PTR(q->result)[0] = ret; ret = (VALUE)NULL; /* decr internal handler mark */ rbtk_internal_eventloop_handler--; /* complete */ *(q->done) = -1; /* unlink ruby objects */ q->argv = (VALUE*)NULL; q->interp = (VALUE)NULL; q->result = (VALUE)NULL; q->thread = (VALUE)NULL; /* back to caller */ if (RTEST(rb_thread_alive_p(thread))) { DUMP2("back to caller (caller thread:%"PRIxVALUE")", thread); DUMP2(" (current thread:%"PRIxVALUE")", rb_thread_current()); #if CONTROL_BY_STATUS_OF_RB_THREAD_WAITING_FOR_VALUE have_rb_thread_waiting_for_value = 1; rb_thread_wakeup(thread); #else rb_thread_run(thread); #endif DUMP1("finish back to caller"); #if DO_THREAD_SCHEDULE_AT_CALLBACK_DONE rb_thread_schedule(); #endif } else { DUMP2("caller is dead (caller thread:%"PRIxVALUE")", thread); DUMP2(" (current thread:%"PRIxVALUE")", rb_thread_current()); } /* end of handler : remove it */ return 1; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
21,265
Chrome
faaa2fd0a05f1622d9a8806da118d4f3b602e707
void HTMLMediaElement::selectedVideoTrackChanged(VideoTrack* track) { BLINK_MEDIA_LOG << "selectedVideoTrackChanged(" << (void*)this << ") selectedTrackId=" << (track->selected() ? String(track->id()) : "none"); DCHECK(mediaTracksEnabledInternally()); if (track->selected()) videoTracks().trackSelected(track->id()); videoTracks().scheduleChangeEvent(); if (m_mediaSource) m_mediaSource->onTrackChanged(track); WebMediaPlayer::TrackId id = track->id(); webMediaPlayer()->selectedVideoTrackChanged(track->selected() ? &id : nullptr); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
10,178
civetweb
8fd069f6dedb064339f1091069ac96f3f8bdb552
event_signal(void *eventhdl) { return (int)SetEvent((HANDLE)eventhdl); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
15,252
Chrome
96dbafe288dbe2f0cc45fa3c39daf6d0c37acbab
xsltNumberFormatAlpha(xmlBufferPtr buffer, double number, int is_upper) { char temp_string[sizeof(double) * CHAR_BIT * sizeof(xmlChar) + 1]; char *pointer; int i; char *alpha_list; double alpha_size = (double)(sizeof(alpha_upper_list) - 1); /* Build buffer from back */ pointer = &temp_string[sizeof(temp_string)]; *(--pointer) = 0; alpha_list = (is_upper) ? alpha_upper_list : alpha_lower_list; for (i = 1; i < (int)sizeof(temp_string); i++) { number--; *(--pointer) = alpha_list[((int)fmod(number, alpha_size))]; number /= alpha_size; if (fabs(number) < 1.0) break; /* for */ } xmlBufferCCat(buffer, pointer); }
1
CVE-2016-1683
CWE-119
Improper Restriction of Operations within the Bounds of a Memory Buffer
The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data.
Phase: Requirements Strategy: Language Selection Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. For example, many languages that perform their own memory management, such as Java and Perl, are not subject to buffer overflows. Other languages, such as Ada and C#, typically provide overflow protection, but the protection can be disabled by the programmer. Be wary that a language's interface to native code may still be subject to overflows, even if the language itself is theoretically safe. Phase: Architecture and Design Strategy: Libraries or Frameworks Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. Examples include the Safe C String Library (SafeStr) by Messier and Viega [REF-57], and the Strsafe.h library from Microsoft [REF-56]. These libraries provide safer versions of overflow-prone string-handling functions. Note: This is not a complete solution, since many buffer overflows are not related to strings. Phases: Operation; Build and Compilation Strategy: Environment Hardening Use automatic buffer overflow detection mechanisms that are offered by certain compilers or compiler extensions. Examples include: the Microsoft Visual Studio /GS flag, Fedora/Red Hat FORTIFY_SOURCE GCC flag, StackGuard, and ProPolice, which provide various mechanisms including canary-based detection and range/index checking. D3-SFCV (Stack Frame Canary Validation) from D3FEND [REF-1334] discusses canary-based detection in detail. Effectiveness: Defense in Depth Note: This is not necessarily a complete solution, since these mechanisms only detect certain types of overflows. In addition, the result is still a denial of service, since the typical response is to exit the application. Phase: Implementation Consider adhering to the following rules when allocating and managing an application's memory: Double check that the buffer is as large as specified. When using functions that accept a number of bytes to copy, such as strncpy(), be aware that if the destination buffer size is equal to the source buffer size, it may not NULL-terminate the string. Check buffer boundaries if accessing the buffer in a loop and make sure there is no danger of writing past the allocated space. If necessary, truncate all input strings to a reasonable length before passing them to the copy and concatenation functions. Phases: Operation; Build and Compilation Strategy: Environment Hardening Run or compile the software using features or extensions that randomly arrange the positions of a program's executable and libraries in memory. Because this makes the addresses unpredictable, it can prevent an attacker from reliably jumping to exploitable code. Examples include Address Space Layout Randomization (ASLR) [REF-58] [REF-60] and Position-Independent Executables (PIE) [REF-64]. Imported modules may be similarly realigned if their default memory addresses conflict with other modules, in a process known as "rebasing" (for Windows) and "prelinking" (for Linux) [REF-1332] using randomly generated addresses. ASLR for libraries cannot be used in conjunction with prelink since it would require relocating the libraries at run-time, defeating the whole purpose of prelinking. For more information on these techniques see D3-SAOR (Segment Address Offset Randomization) from D3FEND [REF-1335]. Effectiveness: Defense in Depth Note: These techniques do not provide a complete solution. For instance, exploits frequently use a bug that discloses memory addresses in order to maximize reliability of code execution [REF-1337]. It has also been shown that a side-channel attack can bypass ASLR [REF-1333] Phase: Operation Strategy: Environment Hardening Use a CPU and operating system that offers Data Execution Protection (using hardware NX or XD bits) or the equivalent techniques that simulate this feature in software, such as PaX [REF-60] [REF-61]. These techniques ensure that any instruction executed is exclusively at a memory address that is part of the code segment. For more information on these techniques see D3-PSEP (Process Segment Execution Prevention) from D3FEND [REF-1336]. Effectiveness: Defense in Depth Note: This is not a complete solution, since buffer overflows could be used to overwrite nearby variables to modify the software's state in dangerous ways. In addition, it cannot be used in cases in which self-modifying code is required. Finally, an attack could still cause a denial of service, since the typical response is to exit the application. Phase: Implementation Replace unbounded copy functions with analogous functions that support length arguments, such as strcpy with strncpy. Create these if they are not available. Effectiveness: Moderate Note: This approach is still susceptible to calculation errors, including issues such as off-by-one errors (CWE-193) and incorrectly calculating buffer lengths (CWE-131).
2,524
Chrome
dc7b094a338c6c521f918f478e993f0f74bbea0d
InputMethodDescriptors* GetInputMethodDescriptorsForTesting() { InputMethodDescriptors* descriptions = new InputMethodDescriptors; descriptions->push_back(InputMethodDescriptor( "xkb:nl::nld", "Netherlands", "nl", "nl", "nld")); descriptions->push_back(InputMethodDescriptor( "xkb:be::nld", "Belgium", "be", "be", "nld")); descriptions->push_back(InputMethodDescriptor( "xkb:fr::fra", "France", "fr", "fr", "fra")); descriptions->push_back(InputMethodDescriptor( "xkb:be::fra", "Belgium", "be", "be", "fra")); descriptions->push_back(InputMethodDescriptor( "xkb:ca::fra", "Canada", "ca", "ca", "fra")); descriptions->push_back(InputMethodDescriptor( "xkb:ch:fr:fra", "Switzerland - French", "ch(fr)", "ch(fr)", "fra")); descriptions->push_back(InputMethodDescriptor( "xkb:de::ger", "Germany", "de", "de", "ger")); descriptions->push_back(InputMethodDescriptor( "xkb:de:neo:ger", "Germany - Neo 2", "de(neo)", "de(neo)", "ger")); descriptions->push_back(InputMethodDescriptor( "xkb:be::ger", "Belgium", "be", "be", "ger")); descriptions->push_back(InputMethodDescriptor( "xkb:ch::ger", "Switzerland", "ch", "ch", "ger")); descriptions->push_back(InputMethodDescriptor( "mozc", "Mozc (US keyboard layout)", "us", "us", "ja")); descriptions->push_back(InputMethodDescriptor( "mozc-jp", "Mozc (Japanese keyboard layout)", "jp", "jp", "ja")); descriptions->push_back(InputMethodDescriptor( "mozc-dv", "Mozc (US Dvorak keyboard layout)", "us(dvorak)", "us(dvorak)", "ja")); descriptions->push_back(InputMethodDescriptor( "xkb:jp::jpn", "Japan", "jp", "jp", "jpn")); descriptions->push_back(InputMethodDescriptor( "xkb:ru::rus", "Russia", "ru", "ru", "rus")); descriptions->push_back(InputMethodDescriptor( "xkb:ru:phonetic:rus", "Russia - Phonetic", "ru(phonetic)", "ru(phonetic)", "rus")); descriptions->push_back(InputMethodDescriptor( "m17n:th:kesmanee", "kesmanee (m17n)", "us", "us", "th")); descriptions->push_back(InputMethodDescriptor( "m17n:th:pattachote", "pattachote (m17n)", "us", "us", "th")); descriptions->push_back(InputMethodDescriptor( "m17n:th:tis820", "tis820 (m17n)", "us", "us", "th")); descriptions->push_back(InputMethodDescriptor( "mozc-chewing", "Mozc Chewing (Chewing)", "us", "us", "zh_TW")); descriptions->push_back(InputMethodDescriptor( "m17n:zh:cangjie", "cangjie (m17n)", "us", "us", "zh")); descriptions->push_back(InputMethodDescriptor( "m17n:zh:quick", "quick (m17n)", "us", "us", "zh")); descriptions->push_back(InputMethodDescriptor( "m17n:vi:tcvn", "tcvn (m17n)", "us", "us", "vi")); descriptions->push_back(InputMethodDescriptor( "m17n:vi:telex", "telex (m17n)", "us", "us", "vi")); descriptions->push_back(InputMethodDescriptor( "m17n:vi:viqr", "viqr (m17n)", "us", "us", "vi")); descriptions->push_back(InputMethodDescriptor( "m17n:vi:vni", "vni (m17n)", "us", "us", "vi")); descriptions->push_back(InputMethodDescriptor( "xkb:us::eng", "USA", "us", "us", "eng")); descriptions->push_back(InputMethodDescriptor( "xkb:us:intl:eng", "USA - International (with dead keys)", "us(intl)", "us(intl)", "eng")); descriptions->push_back(InputMethodDescriptor( "xkb:us:altgr-intl:eng", "USA - International (AltGr dead keys)", "us(altgr-intl)", "us(altgr-intl)", "eng")); descriptions->push_back(InputMethodDescriptor( "xkb:us:dvorak:eng", "USA - Dvorak", "us(dvorak)", "us(dvorak)", "eng")); descriptions->push_back(InputMethodDescriptor( "xkb:us:colemak:eng", "USA - Colemak", "us(colemak)", "us(colemak)", "eng")); descriptions->push_back(InputMethodDescriptor( "hangul", "Korean", "kr(kr104)", "kr(kr104)", "ko")); descriptions->push_back(InputMethodDescriptor( "pinyin", "Pinyin", "us", "us", "zh")); descriptions->push_back(InputMethodDescriptor( "pinyin-dv", "Pinyin (for US Dvorak keyboard)", "us(dvorak)", "us(dvorak)", "zh")); descriptions->push_back(InputMethodDescriptor( "m17n:ar:kbd", "kbd (m17n)", "us", "us", "ar")); descriptions->push_back(InputMethodDescriptor( "m17n:hi:itrans", "itrans (m17n)", "us", "us", "hi")); descriptions->push_back(InputMethodDescriptor( "m17n:fa:isiri", "isiri (m17n)", "us", "us", "fa")); descriptions->push_back(InputMethodDescriptor( "xkb:br::por", "Brazil", "br", "br", "por")); descriptions->push_back(InputMethodDescriptor( "xkb:bg::bul", "Bulgaria", "bg", "bg", "bul")); descriptions->push_back(InputMethodDescriptor( "xkb:bg:phonetic:bul", "Bulgaria - Traditional phonetic", "bg(phonetic)", "bg(phonetic)", "bul")); descriptions->push_back(InputMethodDescriptor( "xkb:ca:eng:eng", "Canada - English", "ca(eng)", "ca(eng)", "eng")); descriptions->push_back(InputMethodDescriptor( "xkb:cz::cze", "Czechia", "cz", "cz", "cze")); descriptions->push_back(InputMethodDescriptor( "xkb:ee::est", "Estonia", "ee", "ee", "est")); descriptions->push_back(InputMethodDescriptor( "xkb:es::spa", "Spain", "es", "es", "spa")); descriptions->push_back(InputMethodDescriptor( "xkb:es:cat:cat", "Spain - Catalan variant with middle-dot L", "es(cat)", "es(cat)", "cat")); descriptions->push_back(InputMethodDescriptor( "xkb:dk::dan", "Denmark", "dk", "dk", "dan")); descriptions->push_back(InputMethodDescriptor( "xkb:gr::gre", "Greece", "gr", "gr", "gre")); descriptions->push_back(InputMethodDescriptor( "xkb:il::heb", "Israel", "il", "il", "heb")); descriptions->push_back(InputMethodDescriptor( "xkb:kr:kr104:kor", "Korea, Republic of - 101/104 key Compatible", "kr(kr104)", "kr(kr104)", "kor")); descriptions->push_back(InputMethodDescriptor( "xkb:latam::spa", "Latin American", "latam", "latam", "spa")); descriptions->push_back(InputMethodDescriptor( "xkb:lt::lit", "Lithuania", "lt", "lt", "lit")); descriptions->push_back(InputMethodDescriptor( "xkb:lv:apostrophe:lav", "Latvia - Apostrophe (') variant", "lv(apostrophe)", "lv(apostrophe)", "lav")); descriptions->push_back(InputMethodDescriptor( "xkb:hr::scr", "Croatia", "hr", "hr", "scr")); descriptions->push_back(InputMethodDescriptor( "xkb:gb:extd:eng", "United Kingdom - Extended - Winkeys", "gb(extd)", "gb(extd)", "eng")); descriptions->push_back(InputMethodDescriptor( "xkb:gb:dvorak:eng", "United Kingdom - Dvorak", "gb(dvorak)", "gb(dvorak)", "eng")); descriptions->push_back(InputMethodDescriptor( "xkb:fi::fin", "Finland", "fi", "fi", "fin")); descriptions->push_back(InputMethodDescriptor( "xkb:hu::hun", "Hungary", "hu", "hu", "hun")); descriptions->push_back(InputMethodDescriptor( "xkb:it::ita", "Italy", "it", "it", "ita")); descriptions->push_back(InputMethodDescriptor( "xkb:no::nob", "Norway", "no", "no", "nob")); descriptions->push_back(InputMethodDescriptor( "xkb:pl::pol", "Poland", "pl", "pl", "pol")); descriptions->push_back(InputMethodDescriptor( "xkb:pt::por", "Portugal", "pt", "pt", "por")); descriptions->push_back(InputMethodDescriptor( "xkb:ro::rum", "Romania", "ro", "ro", "rum")); descriptions->push_back(InputMethodDescriptor( "xkb:se::swe", "Sweden", "se", "se", "swe")); descriptions->push_back(InputMethodDescriptor( "xkb:sk::slo", "Slovakia", "sk", "sk", "slo")); descriptions->push_back(InputMethodDescriptor( "xkb:si::slv", "Slovenia", "si", "si", "slv")); descriptions->push_back(InputMethodDescriptor( "xkb:rs::srp", "Serbia", "rs", "rs", "srp")); descriptions->push_back(InputMethodDescriptor( "xkb:tr::tur", "Turkey", "tr", "tr", "tur")); descriptions->push_back(InputMethodDescriptor( "xkb:ua::ukr", "Ukraine", "ua", "ua", "ukr")); return descriptions; }
1
CVE-2011-2804
CWE-399
Resource Management Errors
Weaknesses in this category are related to improper management of system resources.
Not Found in CWE Page
5,858
linux
35556bed836f8dc07ac55f69c8d17dce3e7f0e25
static inline int hid_hw_power(struct hid_device *hdev, int level) { return hdev->ll_driver->power ? hdev->ll_driver->power(hdev, level) : 0; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
13,758
ImageMagick
0474237508f39c4f783208123431815f1ededb76
MagickExport void *AcquireAlignedMemory(const size_t count,const size_t quantum) { #define AlignedExtent(size,alignment) \ (((size)+((alignment)-1)) & ~((alignment)-1)) size_t alignment, extent, size; void *memory; if (CheckMemoryOverflow(count,quantum) != MagickFalse) return((void *) NULL); memory=NULL; alignment=CACHE_LINE_SIZE; size=count*quantum; extent=AlignedExtent(size,alignment); if ((size == 0) || (alignment < sizeof(void *)) || (extent < size)) return((void *) NULL); #if defined(MAGICKCORE_HAVE_POSIX_MEMALIGN) if (posix_memalign(&memory,alignment,extent) != 0) memory=NULL; #elif defined(MAGICKCORE_HAVE__ALIGNED_MALLOC) memory=_aligned_malloc(extent,alignment); #else { void *p; extent=(size+alignment-1)+sizeof(void *); if (extent > size) { p=malloc(extent); if (p != NULL) { memory=(void *) AlignedExtent((size_t) p+sizeof(void *),alignment); *((void **) memory-1)=p; } } } #endif return(memory); }
1
CVE-2016-10067
CWE-119
Improper Restriction of Operations within the Bounds of a Memory Buffer
The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data.
Phase: Requirements Strategy: Language Selection Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. For example, many languages that perform their own memory management, such as Java and Perl, are not subject to buffer overflows. Other languages, such as Ada and C#, typically provide overflow protection, but the protection can be disabled by the programmer. Be wary that a language's interface to native code may still be subject to overflows, even if the language itself is theoretically safe. Phase: Architecture and Design Strategy: Libraries or Frameworks Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. Examples include the Safe C String Library (SafeStr) by Messier and Viega [REF-57], and the Strsafe.h library from Microsoft [REF-56]. These libraries provide safer versions of overflow-prone string-handling functions. Note: This is not a complete solution, since many buffer overflows are not related to strings. Phases: Operation; Build and Compilation Strategy: Environment Hardening Use automatic buffer overflow detection mechanisms that are offered by certain compilers or compiler extensions. Examples include: the Microsoft Visual Studio /GS flag, Fedora/Red Hat FORTIFY_SOURCE GCC flag, StackGuard, and ProPolice, which provide various mechanisms including canary-based detection and range/index checking. D3-SFCV (Stack Frame Canary Validation) from D3FEND [REF-1334] discusses canary-based detection in detail. Effectiveness: Defense in Depth Note: This is not necessarily a complete solution, since these mechanisms only detect certain types of overflows. In addition, the result is still a denial of service, since the typical response is to exit the application. Phase: Implementation Consider adhering to the following rules when allocating and managing an application's memory: Double check that the buffer is as large as specified. When using functions that accept a number of bytes to copy, such as strncpy(), be aware that if the destination buffer size is equal to the source buffer size, it may not NULL-terminate the string. Check buffer boundaries if accessing the buffer in a loop and make sure there is no danger of writing past the allocated space. If necessary, truncate all input strings to a reasonable length before passing them to the copy and concatenation functions. Phases: Operation; Build and Compilation Strategy: Environment Hardening Run or compile the software using features or extensions that randomly arrange the positions of a program's executable and libraries in memory. Because this makes the addresses unpredictable, it can prevent an attacker from reliably jumping to exploitable code. Examples include Address Space Layout Randomization (ASLR) [REF-58] [REF-60] and Position-Independent Executables (PIE) [REF-64]. Imported modules may be similarly realigned if their default memory addresses conflict with other modules, in a process known as "rebasing" (for Windows) and "prelinking" (for Linux) [REF-1332] using randomly generated addresses. ASLR for libraries cannot be used in conjunction with prelink since it would require relocating the libraries at run-time, defeating the whole purpose of prelinking. For more information on these techniques see D3-SAOR (Segment Address Offset Randomization) from D3FEND [REF-1335]. Effectiveness: Defense in Depth Note: These techniques do not provide a complete solution. For instance, exploits frequently use a bug that discloses memory addresses in order to maximize reliability of code execution [REF-1337]. It has also been shown that a side-channel attack can bypass ASLR [REF-1333] Phase: Operation Strategy: Environment Hardening Use a CPU and operating system that offers Data Execution Protection (using hardware NX or XD bits) or the equivalent techniques that simulate this feature in software, such as PaX [REF-60] [REF-61]. These techniques ensure that any instruction executed is exclusively at a memory address that is part of the code segment. For more information on these techniques see D3-PSEP (Process Segment Execution Prevention) from D3FEND [REF-1336]. Effectiveness: Defense in Depth Note: This is not a complete solution, since buffer overflows could be used to overwrite nearby variables to modify the software's state in dangerous ways. In addition, it cannot be used in cases in which self-modifying code is required. Finally, an attack could still cause a denial of service, since the typical response is to exit the application. Phase: Implementation Replace unbounded copy functions with analogous functions that support length arguments, such as strcpy with strncpy. Create these if they are not available. Effectiveness: Moderate Note: This approach is still susceptible to calculation errors, including issues such as off-by-one errors (CWE-193) and incorrectly calculating buffer lengths (CWE-131).
2,105
Chrome
454434f6100cb6a529652a25b5fc181caa7c7f32
bool ExtensionService::IsDownloadFromGallery(const GURL& download_url, const GURL& referrer_url) { if (IsDownloadFromMiniGallery(download_url) && StartsWithASCII(referrer_url.spec(), extension_urls::kMiniGalleryBrowsePrefix, false)) { return true; } const Extension* download_extension = GetExtensionByWebExtent(download_url); const Extension* referrer_extension = GetExtensionByWebExtent(referrer_url); const Extension* webstore_app = GetWebStoreApp(); bool referrer_valid = (referrer_extension == webstore_app); bool download_valid = (download_extension == webstore_app); GURL store_url = GURL(CommandLine::ForCurrentProcess()->GetSwitchValueASCII( switches::kAppsGalleryURL)); if (!store_url.is_empty()) { std::string store_tld = net::RegistryControlledDomainService::GetDomainAndRegistry(store_url); if (!referrer_valid) { std::string referrer_tld = net::RegistryControlledDomainService::GetDomainAndRegistry( referrer_url); referrer_valid = referrer_url.is_empty() || (referrer_tld == store_tld); } if (!download_valid) { std::string download_tld = net::RegistryControlledDomainService::GetDomainAndRegistry( download_url); download_valid = (download_tld == store_tld); } } return (referrer_valid && download_valid); }
1
CVE-2011-2859
CWE-264
Permissions, Privileges, and Access Controls
Weaknesses in this category are related to the management of permissions, privileges, and other security features that are used to perform access control.
Not Found in CWE Page
4,830
file
39c7ac1106be844a5296d3eb5971946cc09ffda0
doshn(struct magic_set *ms, int clazz, int swap, int fd, off_t off, int num, size_t size, off_t fsize, int *flags, int mach, int strtab) { Elf32_Shdr sh32; Elf64_Shdr sh64; int stripped = 1; void *nbuf; off_t noff, coff, name_off; uint64_t cap_hw1 = 0; /* SunOS 5.x hardware capabilites */ uint64_t cap_sf1 = 0; /* SunOS 5.x software capabilites */ char name[50]; if (size != xsh_sizeof) { if (file_printf(ms, ", corrupted section header size") == -1) return -1; return 0; } /* Read offset of name section to be able to read section names later */ if (pread(fd, xsh_addr, xsh_sizeof, off + size * strtab) == -1) { file_badread(ms); return -1; } name_off = xsh_offset; for ( ; num; num--) { /* Read the name of this section. */ if (pread(fd, name, sizeof(name), name_off + xsh_name) == -1) { file_badread(ms); return -1; } name[sizeof(name) - 1] = '\0'; if (strcmp(name, ".debug_info") == 0) stripped = 0; if (pread(fd, xsh_addr, xsh_sizeof, off) == -1) { file_badread(ms); return -1; } off += size; /* Things we can determine before we seek */ switch (xsh_type) { case SHT_SYMTAB: #if 0 case SHT_DYNSYM: #endif stripped = 0; break; default: if (xsh_offset > fsize) { /* Perhaps warn here */ continue; } break; } /* Things we can determine when we seek */ switch (xsh_type) { case SHT_NOTE: if ((nbuf = malloc(xsh_size)) == NULL) { file_error(ms, errno, "Cannot allocate memory" " for note"); return -1; } if (pread(fd, nbuf, xsh_size, xsh_offset) == -1) { file_badread(ms); free(nbuf); return -1; } noff = 0; for (;;) { if (noff >= (off_t)xsh_size) break; noff = donote(ms, nbuf, (size_t)noff, xsh_size, clazz, swap, 4, flags); if (noff == 0) break; } free(nbuf); break; case SHT_SUNW_cap: switch (mach) { case EM_SPARC: case EM_SPARCV9: case EM_IA_64: case EM_386: case EM_AMD64: break; default: goto skip; } if (lseek(fd, xsh_offset, SEEK_SET) == (off_t)-1) { file_badseek(ms); return -1; } coff = 0; for (;;) { Elf32_Cap cap32; Elf64_Cap cap64; char cbuf[/*CONSTCOND*/ MAX(sizeof cap32, sizeof cap64)]; if ((coff += xcap_sizeof) > (off_t)xsh_size) break; if (read(fd, cbuf, (size_t)xcap_sizeof) != (ssize_t)xcap_sizeof) { file_badread(ms); return -1; } if (cbuf[0] == 'A') { #ifdef notyet char *p = cbuf + 1; uint32_t len, tag; memcpy(&len, p, sizeof(len)); p += 4; len = getu32(swap, len); if (memcmp("gnu", p, 3) != 0) { if (file_printf(ms, ", unknown capability %.3s", p) == -1) return -1; break; } p += strlen(p) + 1; tag = *p++; memcpy(&len, p, sizeof(len)); p += 4; len = getu32(swap, len); if (tag != 1) { if (file_printf(ms, ", unknown gnu" " capability tag %d", tag) == -1) return -1; break; } #endif break; } (void)memcpy(xcap_addr, cbuf, xcap_sizeof); switch (xcap_tag) { case CA_SUNW_NULL: break; case CA_SUNW_HW_1: cap_hw1 |= xcap_val; break; case CA_SUNW_SF_1: cap_sf1 |= xcap_val; break; default: if (file_printf(ms, ", with unknown capability " "0x%" INT64_T_FORMAT "x = 0x%" INT64_T_FORMAT "x", (unsigned long long)xcap_tag, (unsigned long long)xcap_val) == -1) return -1; break; } } /*FALLTHROUGH*/ skip: default: break; } } if (file_printf(ms, ", %sstripped", stripped ? "" : "not ") == -1) return -1; if (cap_hw1) { const cap_desc_t *cdp; switch (mach) { case EM_SPARC: case EM_SPARC32PLUS: case EM_SPARCV9: cdp = cap_desc_sparc; break; case EM_386: case EM_IA_64: case EM_AMD64: cdp = cap_desc_386; break; default: cdp = NULL; break; } if (file_printf(ms, ", uses") == -1) return -1; if (cdp) { while (cdp->cd_name) { if (cap_hw1 & cdp->cd_mask) { if (file_printf(ms, " %s", cdp->cd_name) == -1) return -1; cap_hw1 &= ~cdp->cd_mask; } ++cdp; } if (cap_hw1) if (file_printf(ms, " unknown hardware capability 0x%" INT64_T_FORMAT "x", (unsigned long long)cap_hw1) == -1) return -1; } else { if (file_printf(ms, " hardware capability 0x%" INT64_T_FORMAT "x", (unsigned long long)cap_hw1) == -1) return -1; } } if (cap_sf1) { if (cap_sf1 & SF1_SUNW_FPUSED) { if (file_printf(ms, (cap_sf1 & SF1_SUNW_FPKNWN) ? ", uses frame pointer" : ", not known to use frame pointer") == -1) return -1; } cap_sf1 &= ~SF1_SUNW_MASK; if (cap_sf1) if (file_printf(ms, ", with unknown software capability 0x%" INT64_T_FORMAT "x", (unsigned long long)cap_sf1) == -1) return -1; } return 0; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
14,613
linux
06deeec77a5a689cc94b21a8a91a76e42176685d
mdfour(unsigned char *md4_hash, unsigned char *link_str, int link_len) { int rc; unsigned int size; struct crypto_shash *md4; struct sdesc *sdescmd4; md4 = crypto_alloc_shash("md4", 0, 0); if (IS_ERR(md4)) { rc = PTR_ERR(md4); cifs_dbg(VFS, "%s: Crypto md4 allocation error %d\n", __func__, rc); return rc; } size = sizeof(struct shash_desc) + crypto_shash_descsize(md4); sdescmd4 = kmalloc(size, GFP_KERNEL); if (!sdescmd4) { rc = -ENOMEM; goto mdfour_err; } sdescmd4->shash.tfm = md4; sdescmd4->shash.flags = 0x0; rc = crypto_shash_init(&sdescmd4->shash); if (rc) { cifs_dbg(VFS, "%s: Could not init md4 shash\n", __func__); goto mdfour_err; } rc = crypto_shash_update(&sdescmd4->shash, link_str, link_len); if (rc) { cifs_dbg(VFS, "%s: Could not update with link_str\n", __func__); goto mdfour_err; } rc = crypto_shash_final(&sdescmd4->shash, md4_hash); if (rc) cifs_dbg(VFS, "%s: Could not generate md4 hash\n", __func__); mdfour_err: crypto_free_shash(md4); kfree(sdescmd4); return rc; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
20,913
Android
5c3fd5d93a268abb20ff22f26009535b40db3c7d
void ih264d_assign_pic_num(dec_struct_t *ps_dec) { dpb_manager_t *ps_dpb_mgr; struct dpb_info_t *ps_next_dpb; WORD8 i; WORD32 i4_cur_frame_num, i4_max_frame_num; WORD32 i4_ref_frame_num; UWORD8 u1_fld_pic_flag = ps_dec->ps_cur_slice->u1_field_pic_flag; i4_max_frame_num = ps_dec->ps_cur_sps->u2_u4_max_pic_num_minus1 + 1; i4_cur_frame_num = ps_dec->ps_cur_pic->i4_frame_num; ps_dpb_mgr = ps_dec->ps_dpb_mgr; /* Start from ST head */ ps_next_dpb = ps_dpb_mgr->ps_dpb_st_head; for(i = 0; i < ps_dpb_mgr->u1_num_st_ref_bufs; i++) { WORD32 i4_pic_num; i4_ref_frame_num = ps_next_dpb->ps_pic_buf->i4_frame_num; if(i4_ref_frame_num > i4_cur_frame_num) { /* RefPic Buf frame_num is before Current frame_num in decode order */ i4_pic_num = i4_ref_frame_num - i4_max_frame_num; } else { /* RefPic Buf frame_num is after Current frame_num in decode order */ i4_pic_num = i4_ref_frame_num; } ps_next_dpb->ps_pic_buf->i4_pic_num = i4_pic_num; ps_next_dpb->i4_frame_num = i4_pic_num; ps_next_dpb->ps_pic_buf->u1_long_term_frm_idx = MAX_REF_BUFS + 1; if(u1_fld_pic_flag) { /* Assign the pic num to top fields and bot fields */ ps_next_dpb->s_top_field.i4_pic_num = i4_pic_num * 2 + !(ps_dec->ps_cur_slice->u1_bottom_field_flag); ps_next_dpb->s_bot_field.i4_pic_num = i4_pic_num * 2 + ps_dec->ps_cur_slice->u1_bottom_field_flag; } /* Chase the next link */ ps_next_dpb = ps_next_dpb->ps_prev_short; } if(ps_dec->ps_cur_sps->u1_gaps_in_frame_num_value_allowed_flag && ps_dpb_mgr->u1_num_gaps) { WORD32 i4_start_frm, i4_end_frm; /* Assign pic numbers for gaps */ for(i = 0; i < MAX_FRAMES; i++) { i4_start_frm = ps_dpb_mgr->ai4_gaps_start_frm_num[i]; if(i4_start_frm != INVALID_FRAME_NUM) { if(i4_start_frm > i4_cur_frame_num) { /* gap's frame_num is before Current frame_num in decode order */ i4_start_frm -= i4_max_frame_num; } ps_dpb_mgr->ai4_gaps_start_frm_num[i] = i4_start_frm; i4_end_frm = ps_dpb_mgr->ai4_gaps_end_frm_num[i]; if(i4_end_frm > i4_cur_frame_num) { /* gap's frame_num is before Current frame_num in decode order */ i4_end_frm -= i4_max_frame_num; } ps_dpb_mgr->ai4_gaps_end_frm_num[i] = i4_end_frm; } } } }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
11,685
zstd
3e5cdf1b6a85843e991d7d10f6a2567c15580da0
ZSTD_compressSequences_internal(seqStore_t* seqStorePtr, ZSTD_entropyCTables_t const* prevEntropy, ZSTD_entropyCTables_t* nextEntropy, ZSTD_CCtx_params const* cctxParams, void* dst, size_t dstCapacity, void* workspace, size_t wkspSize, const int bmi2) { const int longOffsets = cctxParams->cParams.windowLog > STREAM_ACCUMULATOR_MIN; ZSTD_strategy const strategy = cctxParams->cParams.strategy; U32 count[MaxSeq+1]; FSE_CTable* CTable_LitLength = nextEntropy->fse.litlengthCTable; FSE_CTable* CTable_OffsetBits = nextEntropy->fse.offcodeCTable; FSE_CTable* CTable_MatchLength = nextEntropy->fse.matchlengthCTable; U32 LLtype, Offtype, MLtype; /* compressed, raw or rle */ const seqDef* const sequences = seqStorePtr->sequencesStart; const BYTE* const ofCodeTable = seqStorePtr->ofCode; const BYTE* const llCodeTable = seqStorePtr->llCode; const BYTE* const mlCodeTable = seqStorePtr->mlCode; BYTE* const ostart = (BYTE*)dst; BYTE* const oend = ostart + dstCapacity; BYTE* op = ostart; size_t const nbSeq = seqStorePtr->sequences - seqStorePtr->sequencesStart; BYTE* seqHead; BYTE* lastNCount = NULL; ZSTD_STATIC_ASSERT(HUF_WORKSPACE_SIZE >= (1<<MAX(MLFSELog,LLFSELog))); /* Compress literals */ { const BYTE* const literals = seqStorePtr->litStart; size_t const litSize = seqStorePtr->lit - literals; int const disableLiteralCompression = (cctxParams->cParams.strategy == ZSTD_fast) && (cctxParams->cParams.targetLength > 0); size_t const cSize = ZSTD_compressLiterals( &prevEntropy->huf, &nextEntropy->huf, cctxParams->cParams.strategy, disableLiteralCompression, op, dstCapacity, literals, litSize, workspace, wkspSize, bmi2); if (ZSTD_isError(cSize)) return cSize; assert(cSize <= dstCapacity); op += cSize; } /* Sequences Header */ if ((oend-op) < 3 /*max nbSeq Size*/ + 1 /*seqHead*/) return ERROR(dstSize_tooSmall); if (nbSeq < 0x7F) *op++ = (BYTE)nbSeq; else if (nbSeq < LONGNBSEQ) op[0] = (BYTE)((nbSeq>>8) + 0x80), op[1] = (BYTE)nbSeq, op+=2; else op[0]=0xFF, MEM_writeLE16(op+1, (U16)(nbSeq - LONGNBSEQ)), op+=3; if (nbSeq==0) { /* Copy the old tables over as if we repeated them */ memcpy(&nextEntropy->fse, &prevEntropy->fse, sizeof(prevEntropy->fse)); return op - ostart; } /* seqHead : flags for FSE encoding type */ seqHead = op++; /* convert length/distances into codes */ ZSTD_seqToCodes(seqStorePtr); /* build CTable for Literal Lengths */ { U32 max = MaxLL; size_t const mostFrequent = HIST_countFast_wksp(count, &max, llCodeTable, nbSeq, workspace, wkspSize); /* can't fail */ DEBUGLOG(5, "Building LL table"); nextEntropy->fse.litlength_repeatMode = prevEntropy->fse.litlength_repeatMode; LLtype = ZSTD_selectEncodingType(&nextEntropy->fse.litlength_repeatMode, count, max, mostFrequent, nbSeq, LLFSELog, prevEntropy->fse.litlengthCTable, LL_defaultNorm, LL_defaultNormLog, ZSTD_defaultAllowed, strategy); assert(set_basic < set_compressed && set_rle < set_compressed); assert(!(LLtype < set_compressed && nextEntropy->fse.litlength_repeatMode != FSE_repeat_none)); /* We don't copy tables */ { size_t const countSize = ZSTD_buildCTable(op, oend - op, CTable_LitLength, LLFSELog, (symbolEncodingType_e)LLtype, count, max, llCodeTable, nbSeq, LL_defaultNorm, LL_defaultNormLog, MaxLL, prevEntropy->fse.litlengthCTable, sizeof(prevEntropy->fse.litlengthCTable), workspace, wkspSize); if (ZSTD_isError(countSize)) return countSize; if (LLtype == set_compressed) lastNCount = op; op += countSize; } } /* build CTable for Offsets */ { U32 max = MaxOff; size_t const mostFrequent = HIST_countFast_wksp(count, &max, ofCodeTable, nbSeq, workspace, wkspSize); /* can't fail */ /* We can only use the basic table if max <= DefaultMaxOff, otherwise the offsets are too large */ ZSTD_defaultPolicy_e const defaultPolicy = (max <= DefaultMaxOff) ? ZSTD_defaultAllowed : ZSTD_defaultDisallowed; DEBUGLOG(5, "Building OF table"); nextEntropy->fse.offcode_repeatMode = prevEntropy->fse.offcode_repeatMode; Offtype = ZSTD_selectEncodingType(&nextEntropy->fse.offcode_repeatMode, count, max, mostFrequent, nbSeq, OffFSELog, prevEntropy->fse.offcodeCTable, OF_defaultNorm, OF_defaultNormLog, defaultPolicy, strategy); assert(!(Offtype < set_compressed && nextEntropy->fse.offcode_repeatMode != FSE_repeat_none)); /* We don't copy tables */ { size_t const countSize = ZSTD_buildCTable(op, oend - op, CTable_OffsetBits, OffFSELog, (symbolEncodingType_e)Offtype, count, max, ofCodeTable, nbSeq, OF_defaultNorm, OF_defaultNormLog, DefaultMaxOff, prevEntropy->fse.offcodeCTable, sizeof(prevEntropy->fse.offcodeCTable), workspace, wkspSize); if (ZSTD_isError(countSize)) return countSize; if (Offtype == set_compressed) lastNCount = op; op += countSize; } } /* build CTable for MatchLengths */ { U32 max = MaxML; size_t const mostFrequent = HIST_countFast_wksp(count, &max, mlCodeTable, nbSeq, workspace, wkspSize); /* can't fail */ DEBUGLOG(5, "Building ML table"); nextEntropy->fse.matchlength_repeatMode = prevEntropy->fse.matchlength_repeatMode; MLtype = ZSTD_selectEncodingType(&nextEntropy->fse.matchlength_repeatMode, count, max, mostFrequent, nbSeq, MLFSELog, prevEntropy->fse.matchlengthCTable, ML_defaultNorm, ML_defaultNormLog, ZSTD_defaultAllowed, strategy); assert(!(MLtype < set_compressed && nextEntropy->fse.matchlength_repeatMode != FSE_repeat_none)); /* We don't copy tables */ { size_t const countSize = ZSTD_buildCTable(op, oend - op, CTable_MatchLength, MLFSELog, (symbolEncodingType_e)MLtype, count, max, mlCodeTable, nbSeq, ML_defaultNorm, ML_defaultNormLog, MaxML, prevEntropy->fse.matchlengthCTable, sizeof(prevEntropy->fse.matchlengthCTable), workspace, wkspSize); if (ZSTD_isError(countSize)) return countSize; if (MLtype == set_compressed) lastNCount = op; op += countSize; } } *seqHead = (BYTE)((LLtype<<6) + (Offtype<<4) + (MLtype<<2)); { size_t const bitstreamSize = ZSTD_encodeSequences( op, oend - op, CTable_MatchLength, mlCodeTable, CTable_OffsetBits, ofCodeTable, CTable_LitLength, llCodeTable, sequences, nbSeq, longOffsets, bmi2); if (ZSTD_isError(bitstreamSize)) return bitstreamSize; op += bitstreamSize; /* zstd versions <= 1.3.4 mistakenly report corruption when * FSE_readNCount() recieves a buffer < 4 bytes. * Fixed by https://github.com/facebook/zstd/pull/1146. * This can happen when the last set_compressed table present is 2 * bytes and the bitstream is only one byte. * In this exceedingly rare case, we will simply emit an uncompressed * block, since it isn't worth optimizing. */ if (lastNCount && (op - lastNCount) < 4) { /* NCountSize >= 2 && bitstreamSize > 0 ==> lastCountSize == 3 */ assert(op - lastNCount == 3); DEBUGLOG(5, "Avoiding bug in zstd decoder in versions <= 1.3.4 by " "emitting an uncompressed block."); return 0; } } return op - ostart; }
1
CVE-2019-11922
CWE-362
Concurrent Execution using Shared Resource with Improper Synchronization ('Race Condition')
The product contains a concurrent code sequence that requires temporary, exclusive access to a shared resource, but a timing window exists in which the shared resource can be modified by another code sequence operating concurrently.
Phase: Architecture and Design In languages that support it, use synchronization primitives. Only wrap these around critical code to minimize the impact on performance. Phase: Architecture and Design Use thread-safe capabilities such as the data access abstraction in Spring. Phase: Architecture and Design Minimize the usage of shared resources in order to remove as much complexity as possible from the control flow and to reduce the likelihood of unexpected conditions occurring. Additionally, this will minimize the amount of synchronization necessary and may even help to reduce the likelihood of a denial of service where an attacker may be able to repeatedly trigger a critical section (CWE-400). Phase: Implementation When using multithreading and operating on shared variables, only use thread-safe functions. Phase: Implementation Use atomic operations on shared variables. Be wary of innocent-looking constructs such as "x++". This may appear atomic at the code layer, but it is actually non-atomic at the instruction layer, since it involves a read, followed by a computation, followed by a write. Phase: Implementation Use a mutex if available, but be sure to avoid related weaknesses such as CWE-412. Phase: Implementation Avoid double-checked locking (CWE-609) and other implementation errors that arise when trying to avoid the overhead of synchronization. Phase: Implementation Disable interrupts or signals over critical parts of the code, but also make sure that the code does not go into a large or infinite loop. Phase: Implementation Use the volatile type modifier for critical variables to avoid unexpected compiler optimization or reordering. This does not necessarily solve the synchronization problem, but it can help. Phases: Architecture and Design; Operation Strategy: Environment Hardening Run your code using the lowest privileges that are required to accomplish the necessary tasks [REF-76]. If possible, create isolated accounts with limited privileges that are only used for a single task. That way, a successful attack will not immediately give the attacker access to the rest of the software or its environment. For example, database applications rarely need to run as the database administrator, especially in day-to-day operations
995
linux
6c342ce2239c182c2428ce5a44cb32330434ae6e
static void mctp_serial_rx(struct mctp_serial *dev) { struct mctp_skb_cb *cb; struct sk_buff *skb; if (dev->rxfcs != dev->rxfcs_rcvd) { dev->netdev->stats.rx_dropped++; dev->netdev->stats.rx_crc_errors++; return; } skb = netdev_alloc_skb(dev->netdev, dev->rxlen); if (!skb) { dev->netdev->stats.rx_dropped++; return; } skb->protocol = htons(ETH_P_MCTP); skb_put_data(skb, dev->rxbuf, dev->rxlen); skb_reset_network_header(skb); cb = __mctp_cb(skb); cb->halen = 0; netif_rx_ni(skb); dev->netdev->stats.rx_packets++; dev->netdev->stats.rx_bytes += dev->rxlen; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
14,237
zlib
e54e1299404101a5a9d0cf5e45512b543967f958
long ZEXPORT inflateMark(strm) z_streamp strm; { struct inflate_state FAR *state; if (strm == Z_NULL || strm->state == Z_NULL) return (long)(((unsigned long)0 - 1) << 16); state = (struct inflate_state FAR *)strm->state; return (long)(((unsigned long)((long)state->back)) << 16) + (state->mode == COPY ? state->length : (state->mode == MATCH ? state->was - state->length : 0)); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
17,645
Android
5a9753fca56f0eeb9f61e342b2fccffc364f9426
void fdct4x4_ref(const int16_t *in, int16_t *out, int stride, int tx_type) { vp9_fdct4x4_c(in, out, stride); }
1
CVE-2016-1621
CWE-119
Improper Restriction of Operations within the Bounds of a Memory Buffer
The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data.
Phase: Requirements Strategy: Language Selection Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. For example, many languages that perform their own memory management, such as Java and Perl, are not subject to buffer overflows. Other languages, such as Ada and C#, typically provide overflow protection, but the protection can be disabled by the programmer. Be wary that a language's interface to native code may still be subject to overflows, even if the language itself is theoretically safe. Phase: Architecture and Design Strategy: Libraries or Frameworks Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. Examples include the Safe C String Library (SafeStr) by Messier and Viega [REF-57], and the Strsafe.h library from Microsoft [REF-56]. These libraries provide safer versions of overflow-prone string-handling functions. Note: This is not a complete solution, since many buffer overflows are not related to strings. Phases: Operation; Build and Compilation Strategy: Environment Hardening Use automatic buffer overflow detection mechanisms that are offered by certain compilers or compiler extensions. Examples include: the Microsoft Visual Studio /GS flag, Fedora/Red Hat FORTIFY_SOURCE GCC flag, StackGuard, and ProPolice, which provide various mechanisms including canary-based detection and range/index checking. D3-SFCV (Stack Frame Canary Validation) from D3FEND [REF-1334] discusses canary-based detection in detail. Effectiveness: Defense in Depth Note: This is not necessarily a complete solution, since these mechanisms only detect certain types of overflows. In addition, the result is still a denial of service, since the typical response is to exit the application. Phase: Implementation Consider adhering to the following rules when allocating and managing an application's memory: Double check that the buffer is as large as specified. When using functions that accept a number of bytes to copy, such as strncpy(), be aware that if the destination buffer size is equal to the source buffer size, it may not NULL-terminate the string. Check buffer boundaries if accessing the buffer in a loop and make sure there is no danger of writing past the allocated space. If necessary, truncate all input strings to a reasonable length before passing them to the copy and concatenation functions. Phases: Operation; Build and Compilation Strategy: Environment Hardening Run or compile the software using features or extensions that randomly arrange the positions of a program's executable and libraries in memory. Because this makes the addresses unpredictable, it can prevent an attacker from reliably jumping to exploitable code. Examples include Address Space Layout Randomization (ASLR) [REF-58] [REF-60] and Position-Independent Executables (PIE) [REF-64]. Imported modules may be similarly realigned if their default memory addresses conflict with other modules, in a process known as "rebasing" (for Windows) and "prelinking" (for Linux) [REF-1332] using randomly generated addresses. ASLR for libraries cannot be used in conjunction with prelink since it would require relocating the libraries at run-time, defeating the whole purpose of prelinking. For more information on these techniques see D3-SAOR (Segment Address Offset Randomization) from D3FEND [REF-1335]. Effectiveness: Defense in Depth Note: These techniques do not provide a complete solution. For instance, exploits frequently use a bug that discloses memory addresses in order to maximize reliability of code execution [REF-1337]. It has also been shown that a side-channel attack can bypass ASLR [REF-1333] Phase: Operation Strategy: Environment Hardening Use a CPU and operating system that offers Data Execution Protection (using hardware NX or XD bits) or the equivalent techniques that simulate this feature in software, such as PaX [REF-60] [REF-61]. These techniques ensure that any instruction executed is exclusively at a memory address that is part of the code segment. For more information on these techniques see D3-PSEP (Process Segment Execution Prevention) from D3FEND [REF-1336]. Effectiveness: Defense in Depth Note: This is not a complete solution, since buffer overflows could be used to overwrite nearby variables to modify the software's state in dangerous ways. In addition, it cannot be used in cases in which self-modifying code is required. Finally, an attack could still cause a denial of service, since the typical response is to exit the application. Phase: Implementation Replace unbounded copy functions with analogous functions that support length arguments, such as strcpy with strncpy. Create these if they are not available. Effectiveness: Moderate Note: This approach is still susceptible to calculation errors, including issues such as off-by-one errors (CWE-193) and incorrectly calculating buffer lengths (CWE-131).
8,908
weechat
efb795c74fe954b9544074aafcebb1be4452b03a
string_free_split_command (char **split_command) { int i; if (split_command) { for (i = 0; split_command[i]; i++) free (split_command[i]); free (split_command); } }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
10,304
FreeRDP
0773bb9303d24473fe1185d85a424dfe159aff53
rdpCredssp* credssp_new(freerdp* instance, rdpTransport* transport, rdpSettings* settings) { rdpCredssp* credssp; credssp = (rdpCredssp*) malloc(sizeof(rdpCredssp)); ZeroMemory(credssp, sizeof(rdpCredssp)); if (credssp != NULL) { HKEY hKey; LONG status; DWORD dwType; DWORD dwSize; credssp->instance = instance; credssp->settings = settings; credssp->server = settings->ServerMode; credssp->transport = transport; credssp->send_seq_num = 0; credssp->recv_seq_num = 0; ZeroMemory(&credssp->negoToken, sizeof(SecBuffer)); ZeroMemory(&credssp->pubKeyAuth, sizeof(SecBuffer)); ZeroMemory(&credssp->authInfo, sizeof(SecBuffer)); if (credssp->server) { status = RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("Software\\FreeRDP\\Server"), 0, KEY_READ | KEY_WOW64_64KEY, &hKey); if (status == ERROR_SUCCESS) { status = RegQueryValueEx(hKey, _T("SspiModule"), NULL, &dwType, NULL, &dwSize); if (status == ERROR_SUCCESS) { credssp->SspiModule = (LPTSTR) malloc(dwSize + sizeof(TCHAR)); status = RegQueryValueEx(hKey, _T("SspiModule"), NULL, &dwType, (BYTE*) credssp->SspiModule, &dwSize); if (status == ERROR_SUCCESS) { _tprintf(_T("Using SSPI Module: %s\n"), credssp->SspiModule); RegCloseKey(hKey); } } } } } return credssp; }
1
CVE-2013-4119
CWE-476
NULL Pointer Dereference
The product dereferences a pointer that it expects to be valid but is NULL.
Phase: Implementation If all pointers that could have been modified are checked for NULL before use, nearly all NULL pointer dereferences can be prevented. Phase: Requirements Select a programming language that is not susceptible to these issues. Phase: Implementation Check the results of all functions that return a value and verify that the value is non-null before acting upon it. Effectiveness: Moderate Note: Checking the return value of the function will typically be sufficient, however beware of race conditions (CWE-362) in a concurrent environment. This solution does not handle the use of improperly initialized variables (CWE-665). Phase: Architecture and Design Identify all variables and data stores that receive information from external sources, and apply input validation to make sure that they are only initialized to expected values. Phase: Implementation Explicitly initialize all variables and other data stores, either during declaration or just before the first usage.
3,585
autotrace
e96bffadc25ff0ba0e10745f8012efcc5f920ea9
static long ToL(unsigned char *puffer) { return (puffer[0] | puffer[1] << 8 | puffer[2] << 16 | puffer[3] << 24); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
17,631
FFmpeg
3819db745da2ac7fb3faacb116788c32f4753f34
static void rpza_decode_stream(RpzaContext *s) { int width = s->avctx->width; int stride = s->frame.linesize[0] / 2; int row_inc = stride - 4; int stream_ptr = 0; int chunk_size; unsigned char opcode; int n_blocks; unsigned short colorA = 0, colorB; unsigned short color4[4]; unsigned char index, idx; unsigned short ta, tb; unsigned short *pixels = (unsigned short *)s->frame.data[0]; int row_ptr = 0; int pixel_ptr = 0; int block_ptr; int pixel_x, pixel_y; int total_blocks; /* First byte is always 0xe1. Warn if it's different */ if (s->buf[stream_ptr] != 0xe1) av_log(s->avctx, AV_LOG_ERROR, "First chunk byte is 0x%02x instead of 0xe1\n", s->buf[stream_ptr]); /* Get chunk size, ingnoring first byte */ chunk_size = AV_RB32(&s->buf[stream_ptr]) & 0x00FFFFFF; stream_ptr += 4; /* If length mismatch use size from MOV file and try to decode anyway */ if (chunk_size != s->size) av_log(s->avctx, AV_LOG_ERROR, "MOV chunk size != encoded chunk size; using MOV chunk size\n"); chunk_size = s->size; /* Number of 4x4 blocks in frame. */ total_blocks = ((s->avctx->width + 3) / 4) * ((s->avctx->height + 3) / 4); /* Process chunk data */ while (stream_ptr < chunk_size) { opcode = s->buf[stream_ptr++]; /* Get opcode */ n_blocks = (opcode & 0x1f) + 1; /* Extract block counter from opcode */ /* If opcode MSbit is 0, we need more data to decide what to do */ if ((opcode & 0x80) == 0) { colorA = (opcode << 8) | (s->buf[stream_ptr++]); opcode = 0; if ((s->buf[stream_ptr] & 0x80) != 0) { /* Must behave as opcode 110xxxxx, using colorA computed * above. Use fake opcode 0x20 to enter switch block at * the right place */ opcode = 0x20; n_blocks = 1; } } switch (opcode & 0xe0) { /* Skip blocks */ case 0x80: while (n_blocks--) { ADVANCE_BLOCK(); } break; /* Fill blocks with one color */ case 0xa0: colorA = AV_RB16 (&s->buf[stream_ptr]); stream_ptr += 2; while (n_blocks--) { block_ptr = row_ptr + pixel_ptr; for (pixel_y = 0; pixel_y < 4; pixel_y++) { for (pixel_x = 0; pixel_x < 4; pixel_x++){ pixels[block_ptr] = colorA; block_ptr++; } block_ptr += row_inc; } ADVANCE_BLOCK(); } break; /* Fill blocks with 4 colors */ case 0xc0: colorA = AV_RB16 (&s->buf[stream_ptr]); stream_ptr += 2; case 0x20: colorB = AV_RB16 (&s->buf[stream_ptr]); stream_ptr += 2; /* sort out the colors */ color4[0] = colorB; color4[1] = 0; color4[2] = 0; color4[3] = colorA; /* red components */ ta = (colorA >> 10) & 0x1F; tb = (colorB >> 10) & 0x1F; color4[1] |= ((11 * ta + 21 * tb) >> 5) << 10; color4[2] |= ((21 * ta + 11 * tb) >> 5) << 10; /* green components */ ta = (colorA >> 5) & 0x1F; tb = (colorB >> 5) & 0x1F; color4[1] |= ((11 * ta + 21 * tb) >> 5) << 5; color4[2] |= ((21 * ta + 11 * tb) >> 5) << 5; /* blue components */ ta = colorA & 0x1F; tb = colorB & 0x1F; color4[1] |= ((11 * ta + 21 * tb) >> 5); color4[2] |= ((21 * ta + 11 * tb) >> 5); if (s->size - stream_ptr < n_blocks * 4) return; while (n_blocks--) { block_ptr = row_ptr + pixel_ptr; for (pixel_y = 0; pixel_y < 4; pixel_y++) { index = s->buf[stream_ptr++]; for (pixel_x = 0; pixel_x < 4; pixel_x++){ idx = (index >> (2 * (3 - pixel_x))) & 0x03; pixels[block_ptr] = color4[idx]; block_ptr++; } block_ptr += row_inc; } ADVANCE_BLOCK(); } break; /* Fill block with 16 colors */ case 0x00: if (s->size - stream_ptr < 16) return; block_ptr = row_ptr + pixel_ptr; for (pixel_y = 0; pixel_y < 4; pixel_y++) { for (pixel_x = 0; pixel_x < 4; pixel_x++){ /* We already have color of upper left pixel */ if ((pixel_y != 0) || (pixel_x !=0)) { colorA = AV_RB16 (&s->buf[stream_ptr]); stream_ptr += 2; } pixels[block_ptr] = colorA; block_ptr++; } block_ptr += row_inc; } ADVANCE_BLOCK(); break; /* Unknown opcode */ default: av_log(s->avctx, AV_LOG_ERROR, "Unknown opcode %d in rpza chunk." " Skip remaining %d bytes of chunk data.\n", opcode, chunk_size - stream_ptr); return; } /* Opcode switch */ } }
1
CVE-2013-7009
CWE-119
Improper Restriction of Operations within the Bounds of a Memory Buffer
The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data.
Phase: Requirements Strategy: Language Selection Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. For example, many languages that perform their own memory management, such as Java and Perl, are not subject to buffer overflows. Other languages, such as Ada and C#, typically provide overflow protection, but the protection can be disabled by the programmer. Be wary that a language's interface to native code may still be subject to overflows, even if the language itself is theoretically safe. Phase: Architecture and Design Strategy: Libraries or Frameworks Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. Examples include the Safe C String Library (SafeStr) by Messier and Viega [REF-57], and the Strsafe.h library from Microsoft [REF-56]. These libraries provide safer versions of overflow-prone string-handling functions. Note: This is not a complete solution, since many buffer overflows are not related to strings. Phases: Operation; Build and Compilation Strategy: Environment Hardening Use automatic buffer overflow detection mechanisms that are offered by certain compilers or compiler extensions. Examples include: the Microsoft Visual Studio /GS flag, Fedora/Red Hat FORTIFY_SOURCE GCC flag, StackGuard, and ProPolice, which provide various mechanisms including canary-based detection and range/index checking. D3-SFCV (Stack Frame Canary Validation) from D3FEND [REF-1334] discusses canary-based detection in detail. Effectiveness: Defense in Depth Note: This is not necessarily a complete solution, since these mechanisms only detect certain types of overflows. In addition, the result is still a denial of service, since the typical response is to exit the application. Phase: Implementation Consider adhering to the following rules when allocating and managing an application's memory: Double check that the buffer is as large as specified. When using functions that accept a number of bytes to copy, such as strncpy(), be aware that if the destination buffer size is equal to the source buffer size, it may not NULL-terminate the string. Check buffer boundaries if accessing the buffer in a loop and make sure there is no danger of writing past the allocated space. If necessary, truncate all input strings to a reasonable length before passing them to the copy and concatenation functions. Phases: Operation; Build and Compilation Strategy: Environment Hardening Run or compile the software using features or extensions that randomly arrange the positions of a program's executable and libraries in memory. Because this makes the addresses unpredictable, it can prevent an attacker from reliably jumping to exploitable code. Examples include Address Space Layout Randomization (ASLR) [REF-58] [REF-60] and Position-Independent Executables (PIE) [REF-64]. Imported modules may be similarly realigned if their default memory addresses conflict with other modules, in a process known as "rebasing" (for Windows) and "prelinking" (for Linux) [REF-1332] using randomly generated addresses. ASLR for libraries cannot be used in conjunction with prelink since it would require relocating the libraries at run-time, defeating the whole purpose of prelinking. For more information on these techniques see D3-SAOR (Segment Address Offset Randomization) from D3FEND [REF-1335]. Effectiveness: Defense in Depth Note: These techniques do not provide a complete solution. For instance, exploits frequently use a bug that discloses memory addresses in order to maximize reliability of code execution [REF-1337]. It has also been shown that a side-channel attack can bypass ASLR [REF-1333] Phase: Operation Strategy: Environment Hardening Use a CPU and operating system that offers Data Execution Protection (using hardware NX or XD bits) or the equivalent techniques that simulate this feature in software, such as PaX [REF-60] [REF-61]. These techniques ensure that any instruction executed is exclusively at a memory address that is part of the code segment. For more information on these techniques see D3-PSEP (Process Segment Execution Prevention) from D3FEND [REF-1336]. Effectiveness: Defense in Depth Note: This is not a complete solution, since buffer overflows could be used to overwrite nearby variables to modify the software's state in dangerous ways. In addition, it cannot be used in cases in which self-modifying code is required. Finally, an attack could still cause a denial of service, since the typical response is to exit the application. Phase: Implementation Replace unbounded copy functions with analogous functions that support length arguments, such as strcpy with strncpy. Create these if they are not available. Effectiveness: Moderate Note: This approach is still susceptible to calculation errors, including issues such as off-by-one errors (CWE-193) and incorrectly calculating buffer lengths (CWE-131).
131
hexchat
c9b63f7f9be01692b03fa15275135a4910a7e02d
_SSL_get_cert_info (struct cert_info *cert_info, SSL * ssl) { X509 *peer_cert; EVP_PKEY *peer_pkey; /* EVP_PKEY *ca_pkey; */ /* EVP_PKEY *tmp_pkey; */ char notBefore[64]; char notAfter[64]; int alg; int sign_alg; if (!(peer_cert = SSL_get_peer_certificate (ssl))) return (1); /* FATAL? */ X509_NAME_oneline (X509_get_subject_name (peer_cert), cert_info->subject, sizeof (cert_info->subject)); X509_NAME_oneline (X509_get_issuer_name (peer_cert), cert_info->issuer, sizeof (cert_info->issuer)); broke_oneline (cert_info->subject, cert_info->subject_word); broke_oneline (cert_info->issuer, cert_info->issuer_word); alg = OBJ_obj2nid (peer_cert->cert_info->key->algor->algorithm); sign_alg = OBJ_obj2nid (peer_cert->sig_alg->algorithm); ASN1_TIME_snprintf (notBefore, sizeof (notBefore), X509_get_notBefore (peer_cert)); ASN1_TIME_snprintf (notAfter, sizeof (notAfter), X509_get_notAfter (peer_cert)); peer_pkey = X509_get_pubkey (peer_cert); safe_strcpy (cert_info->algorithm, (alg == NID_undef) ? "Unknown" : OBJ_nid2ln (alg), sizeof (cert_info->algorithm)); cert_info->algorithm_bits = EVP_PKEY_bits (peer_pkey); safe_strcpy (cert_info->sign_algorithm, (sign_alg == NID_undef) ? "Unknown" : OBJ_nid2ln (sign_alg), sizeof (cert_info->sign_algorithm)); /* EVP_PKEY_bits(ca_pkey)); */ cert_info->sign_algorithm_bits = 0; safe_strcpy (cert_info->notbefore, notBefore, sizeof (cert_info->notbefore)); safe_strcpy (cert_info->notafter, notAfter, sizeof (cert_info->notafter)); EVP_PKEY_free (peer_pkey); /* SSL_SESSION_print_fp(stdout, SSL_get_session(ssl)); */ /* if (ssl->session->sess_cert->peer_rsa_tmp) { tmp_pkey = EVP_PKEY_new(); EVP_PKEY_assign_RSA(tmp_pkey, ssl->session->sess_cert->peer_rsa_tmp); cert_info->rsa_tmp_bits = EVP_PKEY_bits (tmp_pkey); EVP_PKEY_free(tmp_pkey); } else fprintf(stderr, "REMOTE SIDE DOESN'T PROVIDES ->peer_rsa_tmp\n"); */ cert_info->rsa_tmp_bits = 0; X509_free (peer_cert); return (0); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
12,072
linux
f6bbf0010ba004f5e90c7aefdebc0ee4bd3283b9
static long vhost_vdpa_set_config(struct vhost_vdpa *v, struct vhost_vdpa_config __user *c) { struct vdpa_device *vdpa = v->vdpa; const struct vdpa_config_ops *ops = vdpa->config; struct vhost_vdpa_config config; unsigned long size = offsetof(struct vhost_vdpa_config, buf); u8 *buf; if (copy_from_user(&config, c, size)) return -EFAULT; if (vhost_vdpa_config_validate(v, &config)) return -EINVAL; buf = vmemdup_user(c->buf, config.len); if (IS_ERR(buf)) return PTR_ERR(buf); ops->set_config(vdpa, config.off, buf, config.len); kvfree(buf); return 0; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
19,856
ImageMagick6
b4391bdd60df0a77e97a6ef1674f2ffef0e19e24
ModuleExport size_t RegisterVIDImage(void) { MagickInfo *entry; entry=SetMagickInfo("VID"); entry->decoder=(DecodeImageHandler *) ReadVIDImage; entry->encoder=(EncodeImageHandler *) WriteVIDImage; entry->format_type=ImplicitFormatType; entry->description=ConstantString("Visual Image Directory"); entry->module=ConstantString("VID"); (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
20,759
Chrome
9eb1fd426a04adac0906c81ed88f1089969702ba
void BeginInstallWithManifestFunction::OnParseSuccess( const SkBitmap& icon, DictionaryValue* parsed_manifest) { CHECK(parsed_manifest); icon_ = icon; parsed_manifest_.reset(parsed_manifest); std::string init_errors; dummy_extension_ = Extension::Create( FilePath(), Extension::INTERNAL, *static_cast<DictionaryValue*>(parsed_manifest_.get()), Extension::NO_FLAGS, &init_errors); if (!dummy_extension_.get()) { OnParseFailure(MANIFEST_ERROR, std::string(kInvalidManifestError)); return; } if (icon_.empty()) icon_ = Extension::GetDefaultIcon(dummy_extension_->is_app()); ShowExtensionInstallDialog(profile(), this, dummy_extension_.get(), &icon_, dummy_extension_->GetPermissionMessageStrings(), ExtensionInstallUI::INSTALL_PROMPT); }
1
CVE-2011-2358
CWE-20
Improper Input Validation
The product receives input or data, but it does not validate or incorrectly validates that the input has the properties that are required to process the data safely and correctly.
Phase: Architecture and Design Strategy: Attack Surface Reduction Consider using language-theoretic security (LangSec) techniques that characterize inputs using a formal language and build "recognizers" for that language. This effectively requires parsing to be a distinct layer that effectively enforces a boundary between raw input and internal data representations, instead of allowing parser code to be scattered throughout the program, where it could be subject to errors or inconsistencies that create weaknesses. [REF-1109] [REF-1110] [REF-1111] Phase: Architecture and Design Strategy: Libraries or Frameworks Use an input validation framework such as Struts or the OWASP ESAPI Validation API. Note that using a framework does not automatically address all input validation problems; be mindful of weaknesses that could arise from misusing the framework itself (CWE-1173). Phases: Architecture and Design; Implementation Strategy: Attack Surface Reduction Understand all the potential areas where untrusted inputs can enter your software: parameters or arguments, cookies, anything read from the network, environment variables, reverse DNS lookups, query results, request headers, URL components, e-mail, files, filenames, databases, and any external systems that provide data to the application. Remember that such inputs may be obtained indirectly through API calls. Phase: Implementation Strategy: Input Validation Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a list of acceptable inputs that strictly conform to specifications. Reject any input that does not strictly conform to specifications, or transform it into something that does. When performing input validation, consider all potentially relevant properties, including length, type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency across related fields, and conformance to business rules. As an example of business rule logic, "boat" may be syntactically valid because it only contains alphanumeric characters, but it is not valid if the input is only expected to contain colors such as "red" or "blue." Do not rely exclusively on looking for malicious or malformed inputs. This is likely to miss at least one undesirable input, especially if the code's environment changes. This can give attackers enough room to bypass the intended validation. However, denylists can be useful for detecting potential attacks or determining which inputs are so malformed that they should be rejected outright. Effectiveness: High Phase: Architecture and Design For any security checks that are performed on the client side, ensure that these checks are duplicated on the server side, in order to avoid CWE-602. Attackers can bypass the client-side checks by modifying values after the checks have been performed, or by changing the client to remove the client-side checks entirely. Then, these modified values would be submitted to the server. Even though client-side checks provide minimal benefits with respect to server-side security, they are still useful. First, they can support intrusion detection. If the server receives input that should have been rejected by the client, then it may be an indication of an attack. Second, client-side error-checking can provide helpful feedback to the user about the expectations for valid input. Third, there may be a reduction in server-side processing time for accidental input errors, although this is typically a small savings. Phase: Implementation When your application combines data from multiple sources, perform the validation after the sources have been combined. The individual data elements may pass the validation step but violate the intended restrictions after they have been combined. Phase: Implementation Be especially careful to validate all input when invoking code that crosses language boundaries, such as from an interpreted language to native code. This could create an unexpected interaction between the language boundaries. Ensure that you are not violating any of the expectations of the language with which you are interfacing. For example, even though Java may not be susceptible to buffer overflows, providing a large argument in a call to native code might trigger an overflow. Phase: Implementation Directly convert your input type into the expected data type, such as using a conversion function that translates a string into a number. After converting to the expected data type, ensure that the input's values fall within the expected range of allowable values and that multi-field consistencies are maintained. Phase: Implementation Inputs should be decoded and canonicalized to the application's current internal representation before being validated (CWE-180, CWE-181). Make sure that your application does not inadvertently decode the same input twice (CWE-174). Such errors could be used to bypass allowlist schemes by introducing dangerous inputs after they have been checked. Use libraries such as the OWASP ESAPI Canonicalization control. Consider performing repeated canonicalization until your input does not change any more. This will avoid double-decoding and similar scenarios, but it might inadvertently modify inputs that are allowed to contain properly-encoded dangerous content. Phase: Implementation When exchanging data between components, ensure that both components are using the same character encoding. Ensure that the proper encoding is applied at each interface. Explicitly set the encoding you are using whenever the protocol allows you to do so.
5,171
ippusbxd
46844402bca7a38fc224483ba6f0a93c4613203f
void tcp_packet_send(struct tcp_conn_t *conn, struct http_packet_t *pkt) { size_t remaining = pkt->filled_size; size_t total = 0; while (remaining > 0) { ssize_t sent = send(conn->sd, pkt->buffer + total, remaining, MSG_NOSIGNAL); if (sent < 0) { if (errno == EPIPE) { conn->is_closed = 1; return; } ERR_AND_EXIT("Failed to sent data over TCP"); } size_t sent_ulong = (unsigned) sent; total += sent_ulong; if (sent_ulong >= remaining) remaining = 0; else remaining -= sent_ulong; } NOTE("TCP: sent %lu bytes", total); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
18,678
qemu
ff82911cd3f69f028f2537825c9720ff78bc3f19
static void nbd_recv_coroutines_enter_all(NBDClientSession *s) { int i; for (i = 0; i < MAX_NBD_REQUESTS; i++) { qemu_coroutine_enter(s->recv_coroutine[i]); qemu_coroutine_enter(s->recv_coroutine[i]); } }
1
CVE-2017-7539
CWE-20
Improper Input Validation
The product receives input or data, but it does not validate or incorrectly validates that the input has the properties that are required to process the data safely and correctly.
Phase: Architecture and Design Strategy: Attack Surface Reduction Consider using language-theoretic security (LangSec) techniques that characterize inputs using a formal language and build "recognizers" for that language. This effectively requires parsing to be a distinct layer that effectively enforces a boundary between raw input and internal data representations, instead of allowing parser code to be scattered throughout the program, where it could be subject to errors or inconsistencies that create weaknesses. [REF-1109] [REF-1110] [REF-1111] Phase: Architecture and Design Strategy: Libraries or Frameworks Use an input validation framework such as Struts or the OWASP ESAPI Validation API. Note that using a framework does not automatically address all input validation problems; be mindful of weaknesses that could arise from misusing the framework itself (CWE-1173). Phases: Architecture and Design; Implementation Strategy: Attack Surface Reduction Understand all the potential areas where untrusted inputs can enter your software: parameters or arguments, cookies, anything read from the network, environment variables, reverse DNS lookups, query results, request headers, URL components, e-mail, files, filenames, databases, and any external systems that provide data to the application. Remember that such inputs may be obtained indirectly through API calls. Phase: Implementation Strategy: Input Validation Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a list of acceptable inputs that strictly conform to specifications. Reject any input that does not strictly conform to specifications, or transform it into something that does. When performing input validation, consider all potentially relevant properties, including length, type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency across related fields, and conformance to business rules. As an example of business rule logic, "boat" may be syntactically valid because it only contains alphanumeric characters, but it is not valid if the input is only expected to contain colors such as "red" or "blue." Do not rely exclusively on looking for malicious or malformed inputs. This is likely to miss at least one undesirable input, especially if the code's environment changes. This can give attackers enough room to bypass the intended validation. However, denylists can be useful for detecting potential attacks or determining which inputs are so malformed that they should be rejected outright. Effectiveness: High Phase: Architecture and Design For any security checks that are performed on the client side, ensure that these checks are duplicated on the server side, in order to avoid CWE-602. Attackers can bypass the client-side checks by modifying values after the checks have been performed, or by changing the client to remove the client-side checks entirely. Then, these modified values would be submitted to the server. Even though client-side checks provide minimal benefits with respect to server-side security, they are still useful. First, they can support intrusion detection. If the server receives input that should have been rejected by the client, then it may be an indication of an attack. Second, client-side error-checking can provide helpful feedback to the user about the expectations for valid input. Third, there may be a reduction in server-side processing time for accidental input errors, although this is typically a small savings. Phase: Implementation When your application combines data from multiple sources, perform the validation after the sources have been combined. The individual data elements may pass the validation step but violate the intended restrictions after they have been combined. Phase: Implementation Be especially careful to validate all input when invoking code that crosses language boundaries, such as from an interpreted language to native code. This could create an unexpected interaction between the language boundaries. Ensure that you are not violating any of the expectations of the language with which you are interfacing. For example, even though Java may not be susceptible to buffer overflows, providing a large argument in a call to native code might trigger an overflow. Phase: Implementation Directly convert your input type into the expected data type, such as using a conversion function that translates a string into a number. After converting to the expected data type, ensure that the input's values fall within the expected range of allowable values and that multi-field consistencies are maintained. Phase: Implementation Inputs should be decoded and canonicalized to the application's current internal representation before being validated (CWE-180, CWE-181). Make sure that your application does not inadvertently decode the same input twice (CWE-174). Such errors could be used to bypass allowlist schemes by introducing dangerous inputs after they have been checked. Use libraries such as the OWASP ESAPI Canonicalization control. Consider performing repeated canonicalization until your input does not change any more. This will avoid double-decoding and similar scenarios, but it might inadvertently modify inputs that are allowed to contain properly-encoded dangerous content. Phase: Implementation When exchanging data between components, ensure that both components are using the same character encoding. Ensure that the proper encoding is applied at each interface. Explicitly set the encoding you are using whenever the protocol allows you to do so.
7,018
nettle
971bed6ab4b27014eb23085e8176917e1a096fd5
_eddsa_verify_itch (const struct ecc_curve *ecc) { assert (_eddsa_decompress_itch (ecc) <= ecc->mul_itch); return 8*ecc->p.size + ecc->mul_itch; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
21,097
vim
c6fdb15d423df22e1776844811d082322475e48a
find_ex_command( exarg_T *eap, int *full UNUSED, int (*lookup)(char_u *, size_t, int cmd, cctx_T *) UNUSED, cctx_T *cctx UNUSED) { int len; char_u *p; int i; #ifndef FEAT_EVAL int vim9 = FALSE; #else int vim9 = in_vim9script(); /* * Recognize a Vim9 script function/method call and assignment: * "lvar = value", "lvar(arg)", "[1, 2 3]->Func()" */ p = eap->cmd; if (lookup != NULL) { char_u *pskip = skip_option_env_lead(eap->cmd); if (vim_strchr((char_u *)"{('[\"@&$", *p) != NULL || ((p = to_name_const_end(pskip)) > eap->cmd && *p != NUL) || (p[0] == '0' && p[1] == 'z')) { int oplen; int heredoc; char_u *swp; if (*eap->cmd == '&' || (eap->cmd[0] == '$' && eap->cmd[1] != '\'' && eap->cmd[1] != '"') || (eap->cmd[0] == '@' && (valid_yank_reg(eap->cmd[1], FALSE) || eap->cmd[1] == '@'))) { if (*eap->cmd == '&') { p = eap->cmd + 1; if (STRNCMP("l:", p, 2) == 0 || STRNCMP("g:", p, 2) == 0) p += 2; p = to_name_end(p, FALSE); } else if (*eap->cmd == '$') p = to_name_end(eap->cmd + 1, FALSE); else p = eap->cmd + 2; if (ends_excmd(*skipwhite(p))) { // "&option <NL>", "$ENV <NL>" and "@r <NL>" are the start // of an expression. eap->cmdidx = CMD_eval; return eap->cmd; } // "&option" can be followed by "->" or "=", check below } swp = skipwhite(p); if ( // "(..." is an expression. // "funcname(" is always a function call. *p == '(' || (p == eap->cmd ? ( // "{..." is a dict expression or block start. *eap->cmd == '{' // "'string'->func()" is an expression. || *eap->cmd == '\'' // '"string"->func()' is an expression. || *eap->cmd == '"' // '$"string"->func()' is an expression. // "$'string'->func()" is an expression. || (eap->cmd[0] == '$' && (eap->cmd[1] == '\'' || eap->cmd[1] == '"')) // '0z1234->func()' is an expression. || (eap->cmd[0] == '0' && eap->cmd[1] == 'z') // "g:varname" is an expression. || eap->cmd[1] == ':' ) // "varname->func()" is an expression. : (*swp == '-' && swp[1] == '>'))) { if (*eap->cmd == '{' && ends_excmd(*skipwhite(eap->cmd + 1))) { // "{" by itself is the start of a block. eap->cmdidx = CMD_block; return eap->cmd + 1; } eap->cmdidx = CMD_eval; return eap->cmd; } if ((p != eap->cmd && ( // "varname[]" is an expression. *p == '[' // "varname.key" is an expression. || (*p == '.' && (ASCII_ISALPHA(p[1]) || p[1] == '_')))) // g:[key] is an expression || STRNCMP(eap->cmd, "g:[", 3) == 0) { char_u *after = eap->cmd; // When followed by "=" or "+=" then it is an assignment. // Skip over the whole thing, it can be: // name.member = val // name[a : b] = val // name[idx] = val // name[idx].member = val // etc. eap->cmdidx = CMD_eval; ++emsg_silent; if (skip_expr(&after, NULL) == OK) { after = skipwhite(after); if (*after == '=' || (*after != NUL && after[1] == '=') || (after[0] == '.' && after[1] == '.' && after[2] == '=')) eap->cmdidx = CMD_var; } --emsg_silent; return eap->cmd; } // "[...]->Method()" is a list expression, but "[a, b] = Func()" is // an assignment. // If there is no line break inside the "[...]" then "p" is // advanced to after the "]" by to_name_const_end(): check if a "=" // follows. // If "[...]" has a line break "p" still points at the "[" and it // can't be an assignment. if (*eap->cmd == '[') { char_u *eq; p = to_name_const_end(eap->cmd); if (p == eap->cmd && *p == '[') { int count = 0; int semicolon = FALSE; p = skip_var_list(eap->cmd, TRUE, &count, &semicolon, TRUE); } eq = p; if (eq != NULL) { eq = skipwhite(eq); if (vim_strchr((char_u *)"+-*/%", *eq) != NULL) ++eq; } if (p == NULL || p == eap->cmd || *eq != '=') { eap->cmdidx = CMD_eval; return eap->cmd; } if (p > eap->cmd && *eq == '=') { eap->cmdidx = CMD_var; return eap->cmd; } } // Recognize an assignment if we recognize the variable name: // "g:var = expr" // "@r = expr" // "&opt = expr" // "var = expr" where "var" is a variable name or we are skipping // (variable declaration might have been skipped). // Not "redir => var" (when skipping). oplen = assignment_len(skipwhite(p), &heredoc); if (oplen > 0) { if (((p - eap->cmd) > 2 && eap->cmd[1] == ':') || *eap->cmd == '&' || *eap->cmd == '$' || *eap->cmd == '@' || (eap->skip && IS_WHITE_OR_NUL( *(skipwhite(p) + oplen))) || lookup(eap->cmd, p - eap->cmd, TRUE, cctx) == OK) { eap->cmdidx = CMD_var; return eap->cmd; } } // Recognize using a type for a w:, b:, t: or g: variable: // "w:varname: number = 123". if (eap->cmd[1] == ':' && *p == ':') { eap->cmdidx = CMD_eval; return eap->cmd; } } // 1234->func() is a method call if (number_method(eap->cmd)) { eap->cmdidx = CMD_eval; return eap->cmd; } // "g:", "s:" and "l:" are always assumed to be a variable, thus start // an expression. A global/substitute/list command needs to use a // longer name. if (vim_strchr((char_u *)"gsl", *p) != NULL && p[1] == ':') { eap->cmdidx = CMD_eval; return eap->cmd; } // If it is an ID it might be a variable with an operator on the next // line, if the variable exists it can't be an Ex command. if (p > eap->cmd && ends_excmd(*skipwhite(p)) && (lookup(eap->cmd, p - eap->cmd, TRUE, cctx) == OK || (ASCII_ISALPHA(eap->cmd[0]) && eap->cmd[1] == ':'))) { eap->cmdidx = CMD_eval; return eap->cmd; } // Check for "++nr" and "--nr". if (p == eap->cmd && p[0] != NUL && p[0] == p[1] && (*p == '+' || *p == '-')) { eap->cmdidx = *p == '+' ? CMD_increment : CMD_decrement; return eap->cmd + 2; } } #endif /* * Isolate the command and search for it in the command table. */ p = eap->cmd; if (one_letter_cmd(p, &eap->cmdidx)) { ++p; } else { while (ASCII_ISALPHA(*p)) ++p; // for python 3.x support ":py3", ":python3", ":py3file", etc. if (eap->cmd[0] == 'p' && eap->cmd[1] == 'y') { while (ASCII_ISALNUM(*p)) ++p; } else if (*p == '9' && STRNCMP("vim9", eap->cmd, 4) == 0) { // include "9" for "vim9*" commands; "vim9cmd" and "vim9script". ++p; while (ASCII_ISALPHA(*p)) ++p; } // check for non-alpha command if (p == eap->cmd && vim_strchr((char_u *)"@*!=><&~#}", *p) != NULL) ++p; len = (int)(p - eap->cmd); // The "d" command can directly be followed by 'l' or 'p' flag, when // not in Vim9 script. if (!vim9 && *eap->cmd == 'd' && (p[-1] == 'l' || p[-1] == 'p')) { // Check for ":dl", ":dell", etc. to ":deletel": that's // :delete with the 'l' flag. Same for 'p'. for (i = 0; i < len; ++i) if (eap->cmd[i] != ((char_u *)"delete")[i]) break; if (i == len - 1) { --len; if (p[-1] == 'l') eap->flags |= EXFLAG_LIST; else eap->flags |= EXFLAG_PRINT; } } if (ASCII_ISLOWER(eap->cmd[0])) { int c1 = eap->cmd[0]; int c2 = len == 1 ? NUL : eap->cmd[1]; if (command_count != (int)CMD_SIZE) { iemsg(_(e_command_table_needs_to_be_updated_run_make_cmdidxs)); getout(1); } // Use a precomputed index for fast look-up in cmdnames[] // taking into account the first 2 letters of eap->cmd. eap->cmdidx = cmdidxs1[CharOrdLow(c1)]; if (ASCII_ISLOWER(c2)) eap->cmdidx += cmdidxs2[CharOrdLow(c1)][CharOrdLow(c2)]; } else if (ASCII_ISUPPER(eap->cmd[0])) eap->cmdidx = CMD_Next; else eap->cmdidx = CMD_bang; for ( ; (int)eap->cmdidx < (int)CMD_SIZE; eap->cmdidx = (cmdidx_T)((int)eap->cmdidx + 1)) if (STRNCMP(cmdnames[(int)eap->cmdidx].cmd_name, (char *)eap->cmd, (size_t)len) == 0) { #ifdef FEAT_EVAL if (full != NULL && cmdnames[eap->cmdidx].cmd_name[len] == NUL) *full = TRUE; #endif break; } // :Print and :mode are not supported in Vim9 script. // Some commands cannot be shortened in Vim9 script. if (vim9 && eap->cmdidx != CMD_SIZE) { if (eap->cmdidx == CMD_mode || eap->cmdidx == CMD_Print) eap->cmdidx = CMD_SIZE; else if ((cmdnames[eap->cmdidx].cmd_argt & EX_WHOLE) && len < (int)STRLEN(cmdnames[eap->cmdidx].cmd_name)) { semsg(_(e_command_cannot_be_shortened_str), eap->cmd); eap->cmdidx = CMD_SIZE; } } // Do not recognize ":*" as the star command unless '*' is in // 'cpoptions'. if (eap->cmdidx == CMD_star && vim_strchr(p_cpo, CPO_STAR) == NULL) p = eap->cmd; // Look for a user defined command as a last resort. Let ":Print" be // overruled by a user defined command. if ((eap->cmdidx == CMD_SIZE || eap->cmdidx == CMD_Print) && *eap->cmd >= 'A' && *eap->cmd <= 'Z') { // User defined commands may contain digits. while (ASCII_ISALNUM(*p)) ++p; p = find_ucmd(eap, p, full, NULL, NULL); } if (p == NULL || p == eap->cmd) eap->cmdidx = CMD_SIZE; } // ":fina" means ":finally" in legacy script, for backwards compatibility. if (eap->cmdidx == CMD_final && p - eap->cmd == 4 && !vim9) eap->cmdidx = CMD_finally; #ifdef FEAT_EVAL if (eap->cmdidx < CMD_SIZE && vim9 && !IS_WHITE_OR_NUL(*p) && *p != '\n' && *p != '!' && *p != '|' && (eap->cmdidx < 0 || (cmdnames[eap->cmdidx].cmd_argt & EX_NONWHITE_OK) == 0)) { char_u *cmd = vim_strnsave(eap->cmd, p - eap->cmd); semsg(_(e_command_str_not_followed_by_white_space_str), cmd, eap->cmd); eap->cmdidx = CMD_SIZE; vim_free(cmd); } #endif return p; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
20,871
hhvm
851fff90a9b7461df2393af32239ba217bc25946
bool Capability::ChangeUnixUser(uid_t uid) { if (setInitialCapabilities()) { struct passwd *pw; if ((pw = getpwuid(uid)) == nullptr) { Logger::Error("unable to getpwuid(%d): %s", uid, folly::errnoStr(errno).c_str()); return false; } if (initgroups(pw->pw_name, pw->pw_gid) < 0) { Logger::Error("unable to drop supplementary group privs: %s", folly::errnoStr(errno).c_str()); return false; } if (pw->pw_gid == 0 || setgid(pw->pw_gid) < 0) { Logger::Error("unable to drop gid privs: %s", folly::errnoStr(errno).c_str()); return false; } if (uid == 0 || setuid(uid) < 0) { Logger::Error("unable to drop uid privs: %s", folly::errnoStr(errno).c_str()); return false; } if (!setMinimalCapabilities()) { Logger::Error("unable to set minimal server capabiltiies"); return false; } return true; } return false; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
16,750
FFmpeg
2171dfae8c065878a2e130390eb78cf2947a5b69
static int decompress_i(AVCodecContext *avctx, uint32_t *dst, int linesize) { SCPRContext *s = avctx->priv_data; GetByteContext *gb = &s->gb; int cx = 0, cx1 = 0, k = 0, clr = 0; int run, r, g, b, off, y = 0, x = 0, z, ret; unsigned backstep = linesize - avctx->width; const int cxshift = s->cxshift; unsigned lx, ly, ptype; reinit_tables(s); bytestream2_skip(gb, 2); init_rangecoder(&s->rc, gb); while (k < avctx->width + 1) { ret = decode_unit(s, &s->pixel_model[0][cx + cx1], 400, &r); if (ret < 0) return ret; cx1 = (cx << 6) & 0xFC0; cx = r >> cxshift; ret = decode_unit(s, &s->pixel_model[1][cx + cx1], 400, &g); if (ret < 0) return ret; cx1 = (cx << 6) & 0xFC0; cx = g >> cxshift; ret = decode_unit(s, &s->pixel_model[2][cx + cx1], 400, &b); if (ret < 0) return ret; cx1 = (cx << 6) & 0xFC0; cx = b >> cxshift; ret = decode_value(s, s->run_model[0], 256, 400, &run); if (ret < 0) return ret; clr = (b << 16) + (g << 8) + r; k += run; while (run-- > 0) { if (y >= avctx->height) return AVERROR_INVALIDDATA; dst[y * linesize + x] = clr; lx = x; ly = y; x++; if (x >= avctx->width) { x = 0; y++; } } } off = -linesize - 1; ptype = 0; while (x < avctx->width && y < avctx->height) { ret = decode_value(s, s->op_model[ptype], 6, 1000, &ptype); if (ret < 0) return ret; if (ptype == 0) { ret = decode_unit(s, &s->pixel_model[0][cx + cx1], 400, &r); if (ret < 0) return ret; cx1 = (cx << 6) & 0xFC0; cx = r >> cxshift; ret = decode_unit(s, &s->pixel_model[1][cx + cx1], 400, &g); if (ret < 0) return ret; cx1 = (cx << 6) & 0xFC0; cx = g >> cxshift; ret = decode_unit(s, &s->pixel_model[2][cx + cx1], 400, &b); if (ret < 0) return ret; clr = (b << 16) + (g << 8) + r; } if (ptype > 5) return AVERROR_INVALIDDATA; ret = decode_value(s, s->run_model[ptype], 256, 400, &run); if (ret < 0) return ret; switch (ptype) { case 0: while (run-- > 0) { if (y >= avctx->height) return AVERROR_INVALIDDATA; dst[y * linesize + x] = clr; lx = x; ly = y; x++; if (x >= avctx->width) { x = 0; y++; } } break; case 1: while (run-- > 0) { if (y >= avctx->height) return AVERROR_INVALIDDATA; dst[y * linesize + x] = dst[ly * linesize + lx]; lx = x; ly = y; x++; if (x >= avctx->width) { x = 0; y++; } } clr = dst[ly * linesize + lx]; break; case 2: while (run-- > 0) { if (y < 1 || y >= avctx->height) return AVERROR_INVALIDDATA; clr = dst[y * linesize + x + off + 1]; dst[y * linesize + x] = clr; lx = x; ly = y; x++; if (x >= avctx->width) { x = 0; y++; } } break; case 4: while (run-- > 0) { uint8_t *odst = (uint8_t *)dst; if (y < 1 || y >= avctx->height || (y == 1 && x == 0)) return AVERROR_INVALIDDATA; if (x == 0) { z = backstep; } else { z = 0; } r = odst[(ly * linesize + lx) * 4] + odst[((y * linesize + x) + off - z) * 4 + 4] - odst[((y * linesize + x) + off - z) * 4]; g = odst[(ly * linesize + lx) * 4 + 1] + odst[((y * linesize + x) + off - z) * 4 + 5] - odst[((y * linesize + x) + off - z) * 4 + 1]; b = odst[(ly * linesize + lx) * 4 + 2] + odst[((y * linesize + x) + off - z) * 4 + 6] - odst[((y * linesize + x) + off - z) * 4 + 2]; clr = ((b & 0xFF) << 16) + ((g & 0xFF) << 8) + (r & 0xFF); dst[y * linesize + x] = clr; lx = x; ly = y; x++; if (x >= avctx->width) { x = 0; y++; } } break; case 5: while (run-- > 0) { if (y < 1 || y >= avctx->height || (y == 1 && x == 0)) return AVERROR_INVALIDDATA; if (x == 0) { z = backstep; } else { z = 0; } clr = dst[y * linesize + x + off - z]; dst[y * linesize + x] = clr; lx = x; ly = y; x++; if (x >= avctx->width) { x = 0; y++; } } break; } if (avctx->bits_per_coded_sample == 16) { cx1 = (clr & 0x3F00) >> 2; cx = (clr & 0xFFFFFF) >> 16; } else { cx1 = (clr & 0xFC00) >> 4; cx = (clr & 0xFFFFFF) >> 18; } } return 0; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
22,339
hexchat
15600f405f2d5bda6ccf0dd73957395716e0d4d3
sound_beep (session *sess) { if (!prefs.hex_gui_focus_omitalerts || fe_gui_info (sess, 0) != 1) { if (sound_files[XP_TE_BEEP] && sound_files[XP_TE_BEEP][0]) /* user defined beep _file_ */ sound_play_event (XP_TE_BEEP); else /* system beep */ fe_beep (sess); } }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
17,741