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
|
---|---|---|---|---|---|---|---|---|---|
Android | 04839626ed859623901ebd3a5fd483982186b59d | SeekHead::SeekHead(
Segment* pSegment,
long long start,
long long size_,
long long element_start,
long long element_size) :
m_pSegment(pSegment),
m_start(start),
m_size(size_),
m_element_start(element_start),
m_element_size(element_size),
m_entries(0),
m_entry_count(0),
m_void_elements(0),
m_void_element_count(0)
{
}
| 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). | 478 |
openssl | 259b664f950c2ba66fbf4b0fe5281327904ead21 | static int init_ssl_connection(SSL *con)
{
int i;
const char *str;
X509 *peer;
long verify_error;
MS_STATIC char buf[BUFSIZ];
#ifndef OPENSSL_NO_KRB5
char *client_princ;
#endif
#if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_NEXTPROTONEG)
const unsigned char *next_proto_neg;
unsigned next_proto_neg_len;
#endif
unsigned char *exportedkeymat;
i = SSL_accept(con);
#ifdef CERT_CB_TEST_RETRY
{
while (i <= 0 && SSL_get_error(con, i) == SSL_ERROR_WANT_X509_LOOKUP
&& SSL_state(con) == SSL3_ST_SR_CLNT_HELLO_C) {
fprintf(stderr,
"LOOKUP from certificate callback during accept\n");
i = SSL_accept(con);
}
}
#endif
#ifndef OPENSSL_NO_SRP
while (i <= 0 && SSL_get_error(con, i) == SSL_ERROR_WANT_X509_LOOKUP) {
BIO_printf(bio_s_out, "LOOKUP during accept %s\n",
srp_callback_parm.login);
srp_callback_parm.user =
SRP_VBASE_get_by_user(srp_callback_parm.vb,
srp_callback_parm.login);
if (srp_callback_parm.user)
BIO_printf(bio_s_out, "LOOKUP done %s\n",
while (i <= 0 && SSL_get_error(con, i) == SSL_ERROR_WANT_X509_LOOKUP) {
BIO_printf(bio_s_out, "LOOKUP during accept %s\n",
srp_callback_parm.login);
srp_callback_parm.user =
SRP_VBASE_get_by_user(srp_callback_parm.vb,
srp_callback_parm.login);
if (srp_callback_parm.user)
BIO_printf(bio_s_out, "LOOKUP done %s\n",
srp_callback_parm.user->info);
return (1);
}
BIO_printf(bio_err, "ERROR\n");
verify_error = SSL_get_verify_result(con);
if (verify_error != X509_V_OK) {
BIO_printf(bio_err, "verify error:%s\n",
X509_verify_cert_error_string(verify_error));
}
/* Always print any error messages */
ERR_print_errors(bio_err);
return (0);
}
if (s_brief)
print_ssl_summary(bio_err, con);
PEM_write_bio_SSL_SESSION(bio_s_out, SSL_get_session(con));
peer = SSL_get_peer_certificate(con);
if (peer != NULL) {
BIO_printf(bio_s_out, "Client certificate\n");
PEM_write_bio_X509(bio_s_out, peer);
X509_NAME_oneline(X509_get_subject_name(peer), buf, sizeof buf);
BIO_printf(bio_s_out, "subject=%s\n", buf);
X509_NAME_oneline(X509_get_issuer_name(peer), buf, sizeof buf);
BIO_printf(bio_s_out, "issuer=%s\n", buf);
X509_free(peer);
}
if (SSL_get_shared_ciphers(con, buf, sizeof buf) != NULL)
BIO_printf(bio_s_out, "Shared ciphers:%s\n", buf);
str = SSL_CIPHER_get_name(SSL_get_current_cipher(con));
ssl_print_sigalgs(bio_s_out, con);
#ifndef OPENSSL_NO_EC
ssl_print_point_formats(bio_s_out, con);
ssl_print_curves(bio_s_out, con, 0);
#endif
BIO_printf(bio_s_out, "CIPHER is %s\n", (str != NULL) ? str : "(NONE)");
#if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_NEXTPROTONEG)
SSL_get0_next_proto_negotiated(con, &next_proto_neg, &next_proto_neg_len);
if (next_proto_neg) {
BIO_printf(bio_s_out, "NEXTPROTO is ");
BIO_write(bio_s_out, next_proto_neg, next_proto_neg_len);
BIO_printf(bio_s_out, "\n");
}
#endif
#ifndef OPENSSL_NO_SRTP
{
SRTP_PROTECTION_PROFILE *srtp_profile
= SSL_get_selected_srtp_profile(con);
if (srtp_profile)
BIO_printf(bio_s_out, "SRTP Extension negotiated, profile=%s\n",
srtp_profile->name);
}
#endif
if (SSL_cache_hit(con))
BIO_printf(bio_s_out, "Reused session-id\n");
if (SSL_ctrl(con, SSL_CTRL_GET_FLAGS, 0, NULL) &
TLS1_FLAGS_TLS_PADDING_BUG)
BIO_printf(bio_s_out, "Peer has incorrect TLSv1 block padding\n");
#ifndef OPENSSL_NO_KRB5
client_princ = kssl_ctx_get0_client_princ(SSL_get0_kssl_ctx(con));
if (client_princ != NULL) {
BIO_printf(bio_s_out, "Kerberos peer principal is %s\n",
client_princ);
}
#endif /* OPENSSL_NO_KRB5 */
BIO_printf(bio_s_out, "Secure Renegotiation IS%s supported\n",
SSL_get_secure_renegotiation_support(con) ? "" : " NOT");
if (keymatexportlabel != NULL) {
BIO_printf(bio_s_out, "Keying material exporter:\n");
BIO_printf(bio_s_out, " Label: '%s'\n", keymatexportlabel);
BIO_printf(bio_s_out, " Length: %i bytes\n", keymatexportlen);
exportedkeymat = OPENSSL_malloc(keymatexportlen);
if (exportedkeymat != NULL) {
if (!SSL_export_keying_material(con, exportedkeymat,
keymatexportlen,
keymatexportlabel,
strlen(keymatexportlabel),
NULL, 0, 0)) {
BIO_printf(bio_s_out, " Error\n");
} else {
BIO_printf(bio_s_out, " Keying material: ");
for (i = 0; i < keymatexportlen; i++)
BIO_printf(bio_s_out, "%02X", exportedkeymat[i]);
BIO_printf(bio_s_out, "\n");
}
OPENSSL_free(exportedkeymat);
}
}
return (1);
}
| 1 | CVE-2016-0798 | CWE-399 | Resource Management Errors | Weaknesses in this category are related to improper management of system resources. | Not Found in CWE Page | 4,367 |
Chrome | d0947db40187f4708c58e64cbd6013faf9eddeed | xmlParseStringEntityRef(xmlParserCtxtPtr ctxt, const xmlChar ** str) {
xmlChar *name;
const xmlChar *ptr;
xmlChar cur;
xmlEntityPtr ent = NULL;
if ((str == NULL) || (*str == NULL))
return(NULL);
ptr = *str;
cur = *ptr;
if (cur != '&')
return(NULL);
ptr++;
name = xmlParseStringName(ctxt, &ptr);
if (name == NULL) {
xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED,
"xmlParseStringEntityRef: no name\n");
*str = ptr;
return(NULL);
}
if (*ptr != ';') {
xmlFatalErr(ctxt, XML_ERR_ENTITYREF_SEMICOL_MISSING, NULL);
xmlFree(name);
*str = ptr;
return(NULL);
}
ptr++;
/*
* Predefined entites override any extra definition
*/
if ((ctxt->options & XML_PARSE_OLDSAX) == 0) {
ent = xmlGetPredefinedEntity(name);
if (ent != NULL) {
xmlFree(name);
*str = ptr;
return(ent);
}
}
/*
* Increate the number of entity references parsed
*/
ctxt->nbentities++;
/*
* Ask first SAX for entity resolution, otherwise try the
* entities which may have stored in the parser context.
*/
if (ctxt->sax != NULL) {
if (ctxt->sax->getEntity != NULL)
ent = ctxt->sax->getEntity(ctxt->userData, name);
if ((ent == NULL) && (ctxt->options & XML_PARSE_OLDSAX))
ent = xmlGetPredefinedEntity(name);
if ((ent == NULL) && (ctxt->userData==ctxt)) {
ent = xmlSAX2GetEntity(ctxt, name);
}
}
/*
* [ WFC: Entity Declared ]
* In a document without any DTD, a document with only an
* internal DTD subset which contains no parameter entity
* references, or a document with "standalone='yes'", the
* Name given in the entity reference must match that in an
* entity declaration, except that well-formed documents
* need not declare any of the following entities: amp, lt,
* gt, apos, quot.
* The declaration of a parameter entity must precede any
* reference to it.
* Similarly, the declaration of a general entity must
* precede any reference to it which appears in a default
* value in an attribute-list declaration. Note that if
* entities are declared in the external subset or in
* external parameter entities, a non-validating processor
* is not obligated to read and process their declarations;
* for such documents, the rule that an entity must be
* declared is a well-formedness constraint only if
* standalone='yes'.
*/
if (ent == NULL) {
if ((ctxt->standalone == 1) ||
((ctxt->hasExternalSubset == 0) &&
(ctxt->hasPErefs == 0))) {
xmlFatalErrMsgStr(ctxt, XML_ERR_UNDECLARED_ENTITY,
"Entity '%s' not defined\n", name);
} else {
xmlErrMsgStr(ctxt, XML_WAR_UNDECLARED_ENTITY,
"Entity '%s' not defined\n",
name);
}
/* TODO ? check regressions ctxt->valid = 0; */
}
/*
* [ WFC: Parsed Entity ]
* An entity reference must not contain the name of an
* unparsed entity
*/
else if (ent->etype == XML_EXTERNAL_GENERAL_UNPARSED_ENTITY) {
xmlFatalErrMsgStr(ctxt, XML_ERR_UNPARSED_ENTITY,
"Entity reference to unparsed entity %s\n", name);
}
/*
* [ WFC: No External Entity References ]
* Attribute values cannot contain direct or indirect
* entity references to external entities.
*/
else if ((ctxt->instate == XML_PARSER_ATTRIBUTE_VALUE) &&
(ent->etype == XML_EXTERNAL_GENERAL_PARSED_ENTITY)) {
xmlFatalErrMsgStr(ctxt, XML_ERR_ENTITY_IS_EXTERNAL,
"Attribute references external entity '%s'\n", name);
}
/*
* [ WFC: No < in Attribute Values ]
* The replacement text of any entity referred to directly or
* indirectly in an attribute value (other than "<") must
* not contain a <.
*/
else if ((ctxt->instate == XML_PARSER_ATTRIBUTE_VALUE) &&
(ent != NULL) && (ent->content != NULL) &&
(ent->etype != XML_INTERNAL_PREDEFINED_ENTITY) &&
(xmlStrchr(ent->content, '<'))) {
xmlFatalErrMsgStr(ctxt, XML_ERR_LT_IN_ATTRIBUTE,
"'<' in entity '%s' is not allowed in attributes values\n",
name);
}
/*
* Internal check, no parameter entities here ...
*/
else {
switch (ent->etype) {
case XML_INTERNAL_PARAMETER_ENTITY:
case XML_EXTERNAL_PARAMETER_ENTITY:
xmlFatalErrMsgStr(ctxt, XML_ERR_ENTITY_IS_PARAMETER,
"Attempt to reference the parameter entity '%s'\n",
name);
break;
default:
break;
}
}
/*
* [ WFC: No Recursion ]
* A parsed entity must not contain a recursive reference
* to itself, either directly or indirectly.
* Done somewhere else
*/
xmlFree(name);
*str = ptr;
return(ent);
}
| 1 | CVE-2013-2877 | 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). | 6,985 |
openjpeg | d27ccf01c68a31ad62b33d2dc1ba2bb1eeaafe7b | static OPJ_BOOL opj_pi_check_next_level(OPJ_INT32 pos,
opj_cp_t *cp,
OPJ_UINT32 tileno,
OPJ_UINT32 pino,
const OPJ_CHAR *prog)
{
OPJ_INT32 i;
opj_tcp_t *tcps = &cp->tcps[tileno];
opj_poc_t *tcp = &tcps->pocs[pino];
if (pos >= 0) {
for (i = pos; pos >= 0; i--) {
switch (prog[i]) {
case 'R':
if (tcp->res_t == tcp->resE) {
if (opj_pi_check_next_level(pos - 1, cp, tileno, pino, prog)) {
return OPJ_TRUE;
} else {
return OPJ_FALSE;
}
} else {
return OPJ_TRUE;
}
break;
case 'C':
if (tcp->comp_t == tcp->compE) {
if (opj_pi_check_next_level(pos - 1, cp, tileno, pino, prog)) {
return OPJ_TRUE;
} else {
return OPJ_FALSE;
}
} else {
return OPJ_TRUE;
}
break;
case 'L':
if (tcp->lay_t == tcp->layE) {
if (opj_pi_check_next_level(pos - 1, cp, tileno, pino, prog)) {
return OPJ_TRUE;
} else {
return OPJ_FALSE;
}
} else {
return OPJ_TRUE;
}
break;
case 'P':
switch (tcp->prg) {
case OPJ_LRCP: /* fall through */
case OPJ_RLCP:
if (tcp->prc_t == tcp->prcE) {
if (opj_pi_check_next_level(i - 1, cp, tileno, pino, prog)) {
return OPJ_TRUE;
} else {
return OPJ_FALSE;
}
} else {
return OPJ_TRUE;
}
break;
default:
if (tcp->tx0_t == tcp->txE) {
/*TY*/
if (tcp->ty0_t == tcp->tyE) {
if (opj_pi_check_next_level(i - 1, cp, tileno, pino, prog)) {
return OPJ_TRUE;
} else {
return OPJ_FALSE;
}
} else {
return OPJ_TRUE;
}/*TY*/
} else {
return OPJ_TRUE;
}
break;
}/*end case P*/
}/*end switch*/
}/*end for*/
}/*end if*/
return OPJ_FALSE;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 17,815 |
linux | 3ce424e45411cf5a13105e0386b6ecf6eeb4f66f | static int vmx_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
struct shared_msr_entry *msr;
int ret = 0;
u32 msr_index = msr_info->index;
u64 data = msr_info->data;
switch (msr_index) {
case MSR_EFER:
ret = kvm_set_msr_common(vcpu, msr_info);
break;
#ifdef CONFIG_X86_64
case MSR_FS_BASE:
vmx_segment_cache_clear(vmx);
vmcs_writel(GUEST_FS_BASE, data);
break;
case MSR_GS_BASE:
vmx_segment_cache_clear(vmx);
vmcs_writel(GUEST_GS_BASE, data);
break;
case MSR_KERNEL_GS_BASE:
vmx_load_host_state(vmx);
vmx->msr_guest_kernel_gs_base = data;
break;
#endif
case MSR_IA32_SYSENTER_CS:
vmcs_write32(GUEST_SYSENTER_CS, data);
break;
case MSR_IA32_SYSENTER_EIP:
vmcs_writel(GUEST_SYSENTER_EIP, data);
break;
case MSR_IA32_SYSENTER_ESP:
vmcs_writel(GUEST_SYSENTER_ESP, data);
break;
case MSR_IA32_BNDCFGS:
if (!kvm_mpx_supported())
return 1;
vmcs_write64(GUEST_BNDCFGS, data);
break;
case MSR_IA32_TSC:
kvm_write_tsc(vcpu, msr_info);
break;
case MSR_IA32_CR_PAT:
if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT) {
if (!kvm_mtrr_valid(vcpu, MSR_IA32_CR_PAT, data))
return 1;
vmcs_write64(GUEST_IA32_PAT, data);
vcpu->arch.pat = data;
break;
}
ret = kvm_set_msr_common(vcpu, msr_info);
break;
case MSR_IA32_TSC_ADJUST:
ret = kvm_set_msr_common(vcpu, msr_info);
break;
case MSR_IA32_FEATURE_CONTROL:
if (!nested_vmx_allowed(vcpu) ||
(to_vmx(vcpu)->nested.msr_ia32_feature_control &
FEATURE_CONTROL_LOCKED && !msr_info->host_initiated))
return 1;
vmx->nested.msr_ia32_feature_control = data;
if (msr_info->host_initiated && data == 0)
vmx_leave_nested(vcpu);
break;
case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
return 1; /* they are read-only */
case MSR_IA32_XSS:
if (!vmx_xsaves_supported())
return 1;
/*
* The only supported bit as of Skylake is bit 8, but
* it is not supported on KVM.
*/
if (data != 0)
return 1;
vcpu->arch.ia32_xss = data;
if (vcpu->arch.ia32_xss != host_xss)
add_atomic_switch_msr(vmx, MSR_IA32_XSS,
vcpu->arch.ia32_xss, host_xss);
else
clear_atomic_switch_msr(vmx, MSR_IA32_XSS);
break;
case MSR_TSC_AUX:
if (!guest_cpuid_has_rdtscp(vcpu) && !msr_info->host_initiated)
return 1;
/* Check reserved bit, higher 32 bits should be zero */
if ((data >> 32) != 0)
return 1;
/* Otherwise falls through */
default:
msr = find_msr_entry(vmx, msr_index);
if (msr) {
u64 old_msr_data = msr->data;
msr->data = data;
if (msr - vmx->guest_msrs < vmx->save_nmsrs) {
preempt_disable();
ret = kvm_set_shared_msr(msr->index, msr->data,
msr->mask);
preempt_enable();
if (ret)
msr->data = old_msr_data;
}
break;
}
ret = kvm_set_msr_common(vcpu, msr_info);
}
return ret;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 15,163 |
jdk11u-dev | 9a62b8af48af6c506d2fc4a3482116de26357f16 | LIR_Opr LIRGenerator::syncLockOpr() { return new_register(T_INT); } | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 19,001 |
quagga | cfb1fae25f8c092e0d17073eaf7bd428ce1cd546 | rtadv_recv_packet (int sock, u_char *buf, int buflen,
struct sockaddr_in6 *from, ifindex_t *ifindex,
int *hoplimit)
{
int ret;
struct msghdr msg;
struct iovec iov;
struct cmsghdr *cmsgptr;
struct in6_addr dst;
char adata[1024];
/* Fill in message and iovec. */
msg.msg_name = (void *) from;
msg.msg_namelen = sizeof (struct sockaddr_in6);
msg.msg_iov = &iov;
msg.msg_iovlen = 1;
msg.msg_control = (void *) adata;
msg.msg_controllen = sizeof adata;
iov.iov_base = buf;
iov.iov_len = buflen;
/* If recvmsg fail return minus value. */
ret = recvmsg (sock, &msg, 0);
if (ret < 0)
return ret;
for (cmsgptr = ZCMSG_FIRSTHDR(&msg); cmsgptr != NULL;
cmsgptr = CMSG_NXTHDR(&msg, cmsgptr))
{
/* I want interface index which this packet comes from. */
if (cmsgptr->cmsg_level == IPPROTO_IPV6 &&
cmsgptr->cmsg_type == IPV6_PKTINFO)
{
struct in6_pktinfo *ptr;
ptr = (struct in6_pktinfo *) CMSG_DATA (cmsgptr);
*ifindex = ptr->ipi6_ifindex;
memcpy(&dst, &ptr->ipi6_addr, sizeof(ptr->ipi6_addr));
}
/* Incoming packet's hop limit. */
if (cmsgptr->cmsg_level == IPPROTO_IPV6 &&
cmsgptr->cmsg_type == IPV6_HOPLIMIT)
{
int *hoptr = (int *) CMSG_DATA (cmsgptr);
*hoplimit = *hoptr;
}
}
return ret;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 12,858 |
vim | d88934406c5375d88f8f1b65331c9f0cab68cc6c | append_command(char_u *cmd)
{
char_u *s = cmd;
char_u *d;
STRCAT(IObuff, ": ");
d = IObuff + STRLEN(IObuff);
while (*s != NUL && d - IObuff < IOSIZE - 7)
{
if (enc_utf8 ? (s[0] == 0xc2 && s[1] == 0xa0) : *s == 0xa0)
{
s += enc_utf8 ? 2 : 1;
STRCPY(d, "<a0>");
d += 4;
}
else
MB_COPY_CHAR(s, d);
}
*d = NUL;
} | 1 | CVE-2022-1616 | 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. | 9,391 |
ImageMagick6 | a78d92dc0f468e79c3d761aae9707042952cdaca | static void FreePictureMemoryList (PictureMemory* head) {
PictureMemory* next;
while(head != NULL) {
next = head->next;
if(head->pixel_info != NULL)
RelinquishVirtualMemory(head->pixel_info);
free(head);
head = next;
}
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 18,765 |
Chrome | 3b0d77670a0613f409110817455d2137576b485a | void NaClProcessHost::EarlyStartup() {
#if defined(OS_LINUX) && !defined(OS_CHROMEOS)
NaClBrowser::GetInstance()->EnsureIrtAvailable();
#endif
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 12,475 |
Chrome | 648cbc15a6830523b3a4eb78d674f059bd2a7ce9 | NetworkSelectionView* NetworkScreen::AllocateView() {
return new NetworkSelectionView(this);
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 17,034 |
edk2 | 0a0d5296e448fc350de1594c49b9c0deff7fad60 | InitializeExceptionStackSwitchHandlers (
IN OUT VOID *Buffer
)
{
CPU_EXCEPTION_INIT_DATA *EssData;
IA32_DESCRIPTOR Idtr;
EFI_STATUS Status;
EssData = Buffer;
//
// We don't plan to replace IDT table with a new one, but we should not assume
// the AP's IDT is the same as BSP's IDT either.
//
AsmReadIdtr (&Idtr);
EssData->Ia32.IdtTable = (VOID *)Idtr.Base;
EssData->Ia32.IdtTableSize = Idtr.Limit + 1;
Status = InitializeCpuExceptionHandlersEx (NULL, EssData);
ASSERT_EFI_ERROR (Status);
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 12,964 |
savannah | 7f2e4f4f553f6836be7683f66226afac3fa979b8 | bdf_get_font_property( bdf_font_t* font,
const char* name )
{
hashnode hn;
if ( font == 0 || font->props_size == 0 || name == 0 || *name == 0 )
return 0;
hn = hash_lookup( name, (hashtable *)font->internal );
return hn ? ( font->props + hn->data ) : 0;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 16,950 |
savannah | 94e01571507835ff59dd8ce2a0b56a4b566965a4 | main (int argc _GL_UNUSED, char **argv)
{
struct timespec result;
struct timespec result2;
struct timespec expected;
struct timespec now;
const char *p;
int i;
long gmtoff;
time_t ref_time = 1304250918;
/* Set the time zone to US Eastern time with the 2012 rules. This
should disable any leap second support. Otherwise, there will be
a problem with glibc on sites that default to leap seconds; see
<http://bugs.gnu.org/12206>. */
setenv ("TZ", "EST5EDT,M3.2.0,M11.1.0", 1);
gmtoff = gmt_offset (ref_time);
/* ISO 8601 extended date and time of day representation,
'T' separator, local time zone */
p = "2011-05-01T11:55:18";
expected.tv_sec = ref_time - gmtoff;
expected.tv_nsec = 0;
ASSERT (parse_datetime (&result, p, 0));
LOG (p, expected, result);
ASSERT (expected.tv_sec == result.tv_sec
&& expected.tv_nsec == result.tv_nsec);
/* ISO 8601 extended date and time of day representation,
' ' separator, local time zone */
p = "2011-05-01 11:55:18";
expected.tv_sec = ref_time - gmtoff;
expected.tv_nsec = 0;
ASSERT (parse_datetime (&result, p, 0));
LOG (p, expected, result);
ASSERT (expected.tv_sec == result.tv_sec
&& expected.tv_nsec == result.tv_nsec);
/* ISO 8601, extended date and time of day representation,
'T' separator, UTC */
p = "2011-05-01T11:55:18Z";
expected.tv_sec = ref_time;
expected.tv_nsec = 0;
ASSERT (parse_datetime (&result, p, 0));
LOG (p, expected, result);
ASSERT (expected.tv_sec == result.tv_sec
&& expected.tv_nsec == result.tv_nsec);
/* ISO 8601, extended date and time of day representation,
' ' separator, UTC */
p = "2011-05-01 11:55:18Z";
expected.tv_sec = ref_time;
expected.tv_nsec = 0;
ASSERT (parse_datetime (&result, p, 0));
LOG (p, expected, result);
ASSERT (expected.tv_sec == result.tv_sec
&& expected.tv_nsec == result.tv_nsec);
/* ISO 8601 extended date and time of day representation,
'T' separator, w/UTC offset */
p = "2011-05-01T11:55:18-07:00";
expected.tv_sec = 1304276118;
expected.tv_nsec = 0;
ASSERT (parse_datetime (&result, p, 0));
LOG (p, expected, result);
ASSERT (expected.tv_sec == result.tv_sec
&& expected.tv_nsec == result.tv_nsec);
/* ISO 8601 extended date and time of day representation,
' ' separator, w/UTC offset */
p = "2011-05-01 11:55:18-07:00";
expected.tv_sec = 1304276118;
expected.tv_nsec = 0;
ASSERT (parse_datetime (&result, p, 0));
LOG (p, expected, result);
ASSERT (expected.tv_sec == result.tv_sec
&& expected.tv_nsec == result.tv_nsec);
/* ISO 8601 extended date and time of day representation,
'T' separator, w/hour only UTC offset */
p = "2011-05-01T11:55:18-07";
expected.tv_sec = 1304276118;
expected.tv_nsec = 0;
ASSERT (parse_datetime (&result, p, 0));
LOG (p, expected, result);
ASSERT (expected.tv_sec == result.tv_sec
&& expected.tv_nsec == result.tv_nsec);
/* ISO 8601 extended date and time of day representation,
' ' separator, w/hour only UTC offset */
p = "2011-05-01 11:55:18-07";
expected.tv_sec = 1304276118;
expected.tv_nsec = 0;
ASSERT (parse_datetime (&result, p, 0));
LOG (p, expected, result);
ASSERT (expected.tv_sec == result.tv_sec
&& expected.tv_nsec == result.tv_nsec);
now.tv_sec = 4711;
now.tv_nsec = 1267;
p = "now";
ASSERT (parse_datetime (&result, p, &now));
LOG (p, now, result);
ASSERT (now.tv_sec == result.tv_sec && now.tv_nsec == result.tv_nsec);
now.tv_sec = 4711;
now.tv_nsec = 1267;
p = "tomorrow";
ASSERT (parse_datetime (&result, p, &now));
LOG (p, now, result);
ASSERT (now.tv_sec + 24 * 60 * 60 == result.tv_sec
&& now.tv_nsec == result.tv_nsec);
now.tv_sec = 4711;
now.tv_nsec = 1267;
p = "yesterday";
ASSERT (parse_datetime (&result, p, &now));
LOG (p, now, result);
ASSERT (now.tv_sec - 24 * 60 * 60 == result.tv_sec
&& now.tv_nsec == result.tv_nsec);
now.tv_sec = 4711;
now.tv_nsec = 1267;
p = "4 hours";
ASSERT (parse_datetime (&result, p, &now));
LOG (p, now, result);
ASSERT (now.tv_sec + 4 * 60 * 60 == result.tv_sec
&& now.tv_nsec == result.tv_nsec);
/* test if timezone is not being ignored for day offset */
now.tv_sec = 4711;
now.tv_nsec = 1267;
p = "UTC+400 +24 hours";
ASSERT (parse_datetime (&result, p, &now));
LOG (p, now, result);
p = "UTC+400 +1 day";
ASSERT (parse_datetime (&result2, p, &now));
LOG (p, now, result2);
ASSERT (result.tv_sec == result2.tv_sec
&& result.tv_nsec == result2.tv_nsec);
/* test if several time zones formats are handled same way */
now.tv_sec = 4711;
now.tv_nsec = 1267;
p = "UTC+14:00";
ASSERT (parse_datetime (&result, p, &now));
LOG (p, now, result);
p = "UTC+14";
ASSERT (parse_datetime (&result2, p, &now));
LOG (p, now, result2);
ASSERT (result.tv_sec == result2.tv_sec
&& result.tv_nsec == result2.tv_nsec);
p = "UTC+1400";
ASSERT (parse_datetime (&result2, p, &now));
LOG (p, now, result2);
ASSERT (result.tv_sec == result2.tv_sec
&& result.tv_nsec == result2.tv_nsec);
now.tv_sec = 4711;
now.tv_nsec = 1267;
p = "UTC-14:00";
ASSERT (parse_datetime (&result, p, &now));
LOG (p, now, result);
p = "UTC-14";
ASSERT (parse_datetime (&result2, p, &now));
LOG (p, now, result2);
ASSERT (result.tv_sec == result2.tv_sec
&& result.tv_nsec == result2.tv_nsec);
p = "UTC-1400";
ASSERT (parse_datetime (&result2, p, &now));
LOG (p, now, result2);
ASSERT (result.tv_sec == result2.tv_sec
&& result.tv_nsec == result2.tv_nsec);
now.tv_sec = 4711;
now.tv_nsec = 1267;
p = "UTC+0:15";
ASSERT (parse_datetime (&result, p, &now));
LOG (p, now, result);
p = "UTC+0015";
ASSERT (parse_datetime (&result2, p, &now));
LOG (p, now, result2);
ASSERT (result.tv_sec == result2.tv_sec
&& result.tv_nsec == result2.tv_nsec);
now.tv_sec = 4711;
now.tv_nsec = 1267;
p = "UTC-1:30";
ASSERT (parse_datetime (&result, p, &now));
LOG (p, now, result);
p = "UTC-130";
ASSERT (parse_datetime (&result2, p, &now));
LOG (p, now, result2);
ASSERT (result.tv_sec == result2.tv_sec
&& result.tv_nsec == result2.tv_nsec);
/* TZ out of range should cause parse_datetime failure */
now.tv_sec = 4711;
now.tv_nsec = 1267;
p = "UTC+25:00";
ASSERT (!parse_datetime (&result, p, &now));
/* Check for several invalid countable dayshifts */
now.tv_sec = 4711;
now.tv_nsec = 1267;
p = "UTC+4:00 +40 yesterday";
ASSERT (!parse_datetime (&result, p, &now));
p = "UTC+4:00 next yesterday";
ASSERT (!parse_datetime (&result, p, &now));
p = "UTC+4:00 tomorrow ago";
ASSERT (!parse_datetime (&result, p, &now));
p = "UTC+4:00 tomorrow hence";
ASSERT (!parse_datetime (&result, p, &now));
p = "UTC+4:00 40 now ago";
ASSERT (!parse_datetime (&result, p, &now));
p = "UTC+4:00 last tomorrow";
ASSERT (!parse_datetime (&result, p, &now));
p = "UTC+4:00 -4 today";
ASSERT (!parse_datetime (&result, p, &now));
/* And check correct usage of dayshifts */
now.tv_sec = 4711;
now.tv_nsec = 1267;
p = "UTC+400 tomorrow";
ASSERT (parse_datetime (&result, p, &now));
LOG (p, now, result);
p = "UTC+400 +1 day";
ASSERT (parse_datetime (&result2, p, &now));
LOG (p, now, result2);
ASSERT (result.tv_sec == result2.tv_sec
&& result.tv_nsec == result2.tv_nsec);
p = "UTC+400 1 day hence";
ASSERT (parse_datetime (&result2, p, &now));
LOG (p, now, result2);
ASSERT (result.tv_sec == result2.tv_sec
&& result.tv_nsec == result2.tv_nsec);
now.tv_sec = 4711;
now.tv_nsec = 1267;
p = "UTC+400 yesterday";
ASSERT (parse_datetime (&result, p, &now));
LOG (p, now, result);
p = "UTC+400 1 day ago";
ASSERT (parse_datetime (&result2, p, &now));
LOG (p, now, result2);
ASSERT (result.tv_sec == result2.tv_sec
&& result.tv_nsec == result2.tv_nsec);
now.tv_sec = 4711;
now.tv_nsec = 1267;
p = "UTC+400 now";
ASSERT (parse_datetime (&result, p, &now));
LOG (p, now, result);
p = "UTC+400 +0 minutes"; /* silly, but simple "UTC+400" is different*/
ASSERT (parse_datetime (&result2, p, &now));
LOG (p, now, result2);
ASSERT (result.tv_sec == result2.tv_sec
&& result.tv_nsec == result2.tv_nsec);
/* Check that some "next Monday", "last Wednesday", etc. are correct. */
setenv ("TZ", "UTC0", 1);
for (i = 0; day_table[i]; i++)
{
unsigned int thur2 = 7 * 24 * 3600; /* 2nd thursday */
char tmp[32];
sprintf (tmp, "NEXT %s", day_table[i]);
now.tv_sec = thur2 + 4711;
now.tv_nsec = 1267;
ASSERT (parse_datetime (&result, tmp, &now));
LOG (tmp, now, result);
ASSERT (result.tv_nsec == 0);
ASSERT (result.tv_sec == thur2 + (i == 4 ? 7 : (i + 3) % 7) * 24 * 3600);
sprintf (tmp, "LAST %s", day_table[i]);
now.tv_sec = thur2 + 4711;
now.tv_nsec = 1267;
ASSERT (parse_datetime (&result, tmp, &now));
LOG (tmp, now, result);
ASSERT (result.tv_nsec == 0);
ASSERT (result.tv_sec == thur2 + ((i + 3) % 7 - 7) * 24 * 3600);
}
p = "THURSDAY UTC+00"; /* The epoch was on Thursday. */
now.tv_sec = 0;
now.tv_nsec = 0;
ASSERT (parse_datetime (&result, p, &now));
LOG (p, now, result);
ASSERT (result.tv_sec == now.tv_sec
&& result.tv_nsec == now.tv_nsec);
p = "FRIDAY UTC+00";
now.tv_sec = 0;
now.tv_nsec = 0;
ASSERT (parse_datetime (&result, p, &now));
LOG (p, now, result);
ASSERT (result.tv_sec == 24 * 3600
&& result.tv_nsec == now.tv_nsec);
/* Exercise a sign-extension bug. Before July 2012, an input
starting with a high-bit-set byte would be treated like "0". */
ASSERT ( ! parse_datetime (&result, "\xb0", &now));
/* Exercise TZ="" parsing code. */
/* These two would infloop or segfault before Feb 2014. */
ASSERT ( ! parse_datetime (&result, "TZ=\"\"\"", &now));
ASSERT ( ! parse_datetime (&result, "TZ=\"\" \"", &now));
/* Exercise invalid patterns. */
ASSERT ( ! parse_datetime (&result, "TZ=\"", &now));
ASSERT ( ! parse_datetime (&result, "TZ=\"\\\"", &now));
ASSERT ( ! parse_datetime (&result, "TZ=\"\\n", &now));
ASSERT ( ! parse_datetime (&result, "TZ=\"\\n\"", &now));
/* Exercise valid patterns. */
ASSERT ( parse_datetime (&result, "TZ=\"\"", &now));
ASSERT ( parse_datetime (&result, "TZ=\"\" ", &now));
ASSERT ( parse_datetime (&result, " TZ=\"\"", &now));
ASSERT ( parse_datetime (&result, "TZ=\"\\\\\"", &now));
ASSERT ( parse_datetime (&result, "TZ=\"\\\"\"", &now));
/* Outlandishly-long time zone abbreviations should not cause problems. */
{
static char const bufprefix[] = "TZ=\"";
enum { tzname_len = 2000 };
static char const bufsuffix[] = "0\" 1970-01-01 01:02:03.123456789";
enum { bufsize = sizeof bufprefix - 1 + tzname_len + sizeof bufsuffix };
char buf[bufsize];
memcpy (buf, bufprefix, sizeof bufprefix - 1);
memset (buf + sizeof bufprefix - 1, 'X', tzname_len);
strcpy (buf + bufsize - sizeof bufsuffix, bufsuffix);
ASSERT (parse_datetime (&result, buf, &now));
LOG (buf, now, result);
ASSERT (result.tv_sec == 1 * 60 * 60 + 2 * 60 + 3
&& result.tv_nsec == 123456789);
}
return 0;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 16,946 |
php-src | 7245bff300d3fa8bacbef7897ff080a6f1c23eba?w=1 | SPL_METHOD(DirectoryIterator, rewind)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
if (zend_parse_parameters_none() == FAILURE) {
return;
}
intern->u.dir.index = 0;
if (intern->u.dir.dirp) {
php_stream_rewinddir(intern->u.dir.dirp);
}
spl_filesystem_dir_read(intern TSRMLS_CC);
}
| 1 | CVE-2016-5770 | 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. | 7,920 |
linux | 51aa68e7d57e3217192d88ce90fd5b8ef29ec94f | static int handle_exception(struct kvm_vcpu *vcpu)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
struct kvm_run *kvm_run = vcpu->run;
u32 intr_info, ex_no, error_code;
unsigned long cr2, rip, dr6;
u32 vect_info;
enum emulation_result er;
vect_info = vmx->idt_vectoring_info;
intr_info = vmx->exit_intr_info;
if (is_machine_check(intr_info))
return handle_machine_check(vcpu);
if (is_nmi(intr_info))
return 1; /* already handled by vmx_vcpu_run() */
if (is_invalid_opcode(intr_info)) {
if (is_guest_mode(vcpu)) {
kvm_queue_exception(vcpu, UD_VECTOR);
return 1;
}
er = emulate_instruction(vcpu, EMULTYPE_TRAP_UD);
if (er != EMULATE_DONE)
kvm_queue_exception(vcpu, UD_VECTOR);
return 1;
}
error_code = 0;
if (intr_info & INTR_INFO_DELIVER_CODE_MASK)
error_code = vmcs_read32(VM_EXIT_INTR_ERROR_CODE);
/*
* The #PF with PFEC.RSVD = 1 indicates the guest is accessing
* MMIO, it is better to report an internal error.
* See the comments in vmx_handle_exit.
*/
if ((vect_info & VECTORING_INFO_VALID_MASK) &&
!(is_page_fault(intr_info) && !(error_code & PFERR_RSVD_MASK))) {
vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_SIMUL_EX;
vcpu->run->internal.ndata = 3;
vcpu->run->internal.data[0] = vect_info;
vcpu->run->internal.data[1] = intr_info;
vcpu->run->internal.data[2] = error_code;
return 0;
}
if (is_page_fault(intr_info)) {
cr2 = vmcs_readl(EXIT_QUALIFICATION);
/* EPT won't cause page fault directly */
WARN_ON_ONCE(!vcpu->arch.apf.host_apf_reason && enable_ept);
return kvm_handle_page_fault(vcpu, error_code, cr2, NULL, 0,
true);
}
ex_no = intr_info & INTR_INFO_VECTOR_MASK;
if (vmx->rmode.vm86_active && rmode_exception(vcpu, ex_no))
return handle_rmode_exception(vcpu, ex_no, error_code);
switch (ex_no) {
case AC_VECTOR:
kvm_queue_exception_e(vcpu, AC_VECTOR, error_code);
return 1;
case DB_VECTOR:
dr6 = vmcs_readl(EXIT_QUALIFICATION);
if (!(vcpu->guest_debug &
(KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))) {
vcpu->arch.dr6 &= ~15;
vcpu->arch.dr6 |= dr6 | DR6_RTM;
if (!(dr6 & ~DR6_RESERVED)) /* icebp */
skip_emulated_instruction(vcpu);
kvm_queue_exception(vcpu, DB_VECTOR);
return 1;
}
kvm_run->debug.arch.dr6 = dr6 | DR6_FIXED_1;
kvm_run->debug.arch.dr7 = vmcs_readl(GUEST_DR7);
/* fall through */
case BP_VECTOR:
/*
* Update instruction length as we may reinject #BP from
* user space while in guest debugging mode. Reading it for
* #DB as well causes no harm, it is not used in that case.
*/
vmx->vcpu.arch.event_exit_inst_len =
vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
kvm_run->exit_reason = KVM_EXIT_DEBUG;
rip = kvm_rip_read(vcpu);
kvm_run->debug.arch.pc = vmcs_readl(GUEST_CS_BASE) + rip;
kvm_run->debug.arch.exception = ex_no;
break;
default:
kvm_run->exit_reason = KVM_EXIT_EXCEPTION;
kvm_run->ex.exception = ex_no;
kvm_run->ex.error_code = error_code;
break;
}
return 0;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 15,754 |
exiv2 | bd0afe0390439b2c424d881c8c6eb0c5624e31d9 | int MemIo::seek(int64 offset, Position pos )
{
int64 newIdx = 0;
switch (pos) {
case BasicIo::cur:
newIdx = p_->idx_ + offset;
break;
case BasicIo::beg:
newIdx = offset;
break;
case BasicIo::end:
newIdx = p_->size_ + offset;
break;
}
if (newIdx < 0)
return 1;
p_->idx_ = static_cast<long>(newIdx); //not very sure about this. need more test!! - note by Shawn [email protected] //TODO
p_->eof_ = false;
return 0;
} | 1 | CVE-2019-13504 | 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. | 6,842 |
php-src | 2871c70efaaaa0f102557a17c727fd4d5204dd4b | PHP_FUNCTION(escapeshellarg)
{
char *argument;
size_t argument_len;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &argument, &argument_len) == FAILURE) {
return;
}
if (argument) {
RETVAL_STR(php_escape_shell_arg(argument));
}
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 21,807 |
Chrome | c391f54a210dd792f140650b886e92480d8eaf9e | float AudioParam::smoothedValue()
{
return narrowPrecisionToFloat(m_smoothedValue);
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 19,477 |
tcpdump | 86326e880d31b328a151d45348c35220baa9a1ff | bgp_notification_print(netdissect_options *ndo,
const u_char *dat, int length)
{
struct bgp_notification bgpn;
const u_char *tptr;
ND_TCHECK2(dat[0], BGP_NOTIFICATION_SIZE);
memcpy(&bgpn, dat, BGP_NOTIFICATION_SIZE);
/* some little sanity checking */
if (length<BGP_NOTIFICATION_SIZE)
return;
ND_PRINT((ndo, ", %s (%u)",
tok2str(bgp_notify_major_values, "Unknown Error",
bgpn.bgpn_major),
bgpn.bgpn_major));
switch (bgpn.bgpn_major) {
case BGP_NOTIFY_MAJOR_MSG:
ND_PRINT((ndo, ", subcode %s (%u)",
tok2str(bgp_notify_minor_msg_values, "Unknown",
bgpn.bgpn_minor),
bgpn.bgpn_minor));
break;
case BGP_NOTIFY_MAJOR_OPEN:
ND_PRINT((ndo, ", subcode %s (%u)",
tok2str(bgp_notify_minor_open_values, "Unknown",
bgpn.bgpn_minor),
bgpn.bgpn_minor));
break;
case BGP_NOTIFY_MAJOR_UPDATE:
ND_PRINT((ndo, ", subcode %s (%u)",
tok2str(bgp_notify_minor_update_values, "Unknown",
bgpn.bgpn_minor),
bgpn.bgpn_minor));
break;
case BGP_NOTIFY_MAJOR_FSM:
ND_PRINT((ndo, " subcode %s (%u)",
tok2str(bgp_notify_minor_fsm_values, "Unknown",
bgpn.bgpn_minor),
bgpn.bgpn_minor));
break;
case BGP_NOTIFY_MAJOR_CAP:
ND_PRINT((ndo, " subcode %s (%u)",
tok2str(bgp_notify_minor_cap_values, "Unknown",
bgpn.bgpn_minor),
bgpn.bgpn_minor));
break;
case BGP_NOTIFY_MAJOR_CEASE:
ND_PRINT((ndo, ", subcode %s (%u)",
tok2str(bgp_notify_minor_cease_values, "Unknown",
bgpn.bgpn_minor),
bgpn.bgpn_minor));
/* draft-ietf-idr-cease-subcode-02 mentions optionally 7 bytes
* for the maxprefix subtype, which may contain AFI, SAFI and MAXPREFIXES
*/
if(bgpn.bgpn_minor == BGP_NOTIFY_MINOR_CEASE_MAXPRFX && length >= BGP_NOTIFICATION_SIZE + 7) {
tptr = dat + BGP_NOTIFICATION_SIZE;
ND_TCHECK2(*tptr, 7);
ND_PRINT((ndo, ", AFI %s (%u), SAFI %s (%u), Max Prefixes: %u",
tok2str(af_values, "Unknown",
EXTRACT_16BITS(tptr)),
EXTRACT_16BITS(tptr),
tok2str(bgp_safi_values, "Unknown", *(tptr+2)),
*(tptr+2),
EXTRACT_32BITS(tptr+3)));
}
break;
default:
break;
}
return;
trunc:
ND_PRINT((ndo, "[|BGP]"));
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 23,341 |
php-src | 9c673083cd46ee2a954a62156acbe4b6e657c048 | static int is_userinfo_valid(const char *str, size_t len)
{
char *valid = "-._~!$&'()*+,;=:";
char *p = str;
while (p - str < len) {
if (isalpha(*p) || isdigit(*p) || strchr(valid, *p)) {
p++;
} else if (*p == '%' && p - str <= len - 3 && isdigit(*(p+1)) && isxdigit(*(p+2))) {
p += 3;
} else {
return 0;
}
}
return 1;
} | 1 | CVE-2020-7071 | 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,972 |
Chrome | d0947db40187f4708c58e64cbd6013faf9eddeed | xmlLoadEntityContent(xmlParserCtxtPtr ctxt, xmlEntityPtr entity) {
xmlParserInputPtr input;
xmlBufferPtr buf;
int l, c;
int count = 0;
if ((ctxt == NULL) || (entity == NULL) ||
((entity->etype != XML_EXTERNAL_PARAMETER_ENTITY) &&
(entity->etype != XML_EXTERNAL_GENERAL_PARSED_ENTITY)) ||
(entity->content != NULL)) {
xmlFatalErr(ctxt, XML_ERR_INTERNAL_ERROR,
"xmlLoadEntityContent parameter error");
return(-1);
}
if (xmlParserDebugEntities)
xmlGenericError(xmlGenericErrorContext,
"Reading %s entity content input\n", entity->name);
buf = xmlBufferCreate();
if (buf == NULL) {
xmlFatalErr(ctxt, XML_ERR_INTERNAL_ERROR,
"xmlLoadEntityContent parameter error");
return(-1);
}
input = xmlNewEntityInputStream(ctxt, entity);
if (input == NULL) {
xmlFatalErr(ctxt, XML_ERR_INTERNAL_ERROR,
"xmlLoadEntityContent input error");
xmlBufferFree(buf);
return(-1);
}
/*
* Push the entity as the current input, read char by char
* saving to the buffer until the end of the entity or an error
*/
if (xmlPushInput(ctxt, input) < 0) {
xmlBufferFree(buf);
return(-1);
}
GROW;
c = CUR_CHAR(l);
while ((ctxt->input == input) && (ctxt->input->cur < ctxt->input->end) &&
(IS_CHAR(c))) {
xmlBufferAdd(buf, ctxt->input->cur, l);
if (count++ > 100) {
count = 0;
GROW;
}
NEXTL(l);
c = CUR_CHAR(l);
}
if ((ctxt->input == input) && (ctxt->input->cur >= ctxt->input->end)) {
xmlPopInput(ctxt);
} else if (!IS_CHAR(c)) {
xmlFatalErrMsgInt(ctxt, XML_ERR_INVALID_CHAR,
"xmlLoadEntityContent: invalid char value %d\n",
c);
xmlBufferFree(buf);
return(-1);
}
entity->content = buf->content;
buf->content = NULL;
xmlBufferFree(buf);
return(0);
}
| 1 | CVE-2013-2877 | 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). | 6,925 |
vim | 143367256836b0f69881dc0c65ff165ae091dbc5 | exec_instructions(ectx_T *ectx)
{
int ret = FAIL;
int save_trylevel_at_start = ectx->ec_trylevel_at_start;
int dict_stack_len_at_start = dict_stack.ga_len;
// Start execution at the first instruction.
ectx->ec_iidx = 0;
// Only catch exceptions in this instruction list.
ectx->ec_trylevel_at_start = trylevel;
for (;;)
{
static int breakcheck_count = 0; // using "static" makes it faster
isn_T *iptr;
typval_T *tv;
if (unlikely(++breakcheck_count >= 100))
{
line_breakcheck();
breakcheck_count = 0;
}
if (unlikely(got_int))
{
// Turn CTRL-C into an exception.
got_int = FALSE;
if (throw_exception("Vim:Interrupt", ET_INTERRUPT, NULL) == FAIL)
goto theend;
did_throw = TRUE;
}
if (unlikely(did_emsg && msg_list != NULL && *msg_list != NULL))
{
// Turn an error message into an exception.
did_emsg = FALSE;
if (throw_exception(*msg_list, ET_ERROR, NULL) == FAIL)
goto theend;
did_throw = TRUE;
*msg_list = NULL;
}
if (unlikely(did_throw))
{
garray_T *trystack = &ectx->ec_trystack;
trycmd_T *trycmd = NULL;
int index = trystack->ga_len;
// An exception jumps to the first catch, finally, or returns from
// the current function.
while (index > 0)
{
trycmd = ((trycmd_T *)trystack->ga_data) + index - 1;
if (!trycmd->tcd_in_catch || trycmd->tcd_finally_idx != 0)
break;
// In the catch and finally block of this try we have to go up
// one level.
--index;
trycmd = NULL;
}
if (trycmd != NULL && trycmd->tcd_frame_idx == ectx->ec_frame_idx)
{
if (trycmd->tcd_in_catch)
{
// exception inside ":catch", jump to ":finally" once
ectx->ec_iidx = trycmd->tcd_finally_idx;
trycmd->tcd_finally_idx = 0;
}
else
// jump to first ":catch"
ectx->ec_iidx = trycmd->tcd_catch_idx;
trycmd->tcd_in_catch = TRUE;
did_throw = FALSE; // don't come back here until :endtry
trycmd->tcd_did_throw = TRUE;
}
else
{
// Not inside try or need to return from current functions.
// Push a dummy return value.
if (GA_GROW_FAILS(&ectx->ec_stack, 1))
goto theend;
tv = STACK_TV_BOT(0);
tv->v_type = VAR_NUMBER;
tv->vval.v_number = 0;
++ectx->ec_stack.ga_len;
if (ectx->ec_frame_idx == ectx->ec_initial_frame_idx)
{
// At the toplevel we are done.
need_rethrow = TRUE;
if (handle_closure_in_use(ectx, FALSE) == FAIL)
goto theend;
goto done;
}
if (func_return(ectx) == FAIL)
goto theend;
}
continue;
}
iptr = &ectx->ec_instr[ectx->ec_iidx++];
switch (iptr->isn_type)
{
// execute Ex command line
case ISN_EXEC:
if (exec_command(iptr) == FAIL)
goto on_error;
break;
// execute Ex command line split at NL characters.
case ISN_EXEC_SPLIT:
{
source_cookie_T cookie;
char_u *line;
SOURCING_LNUM = iptr->isn_lnum;
CLEAR_FIELD(cookie);
cookie.sourcing_lnum = iptr->isn_lnum - 1;
cookie.nextline = iptr->isn_arg.string;
line = get_split_sourceline(0, &cookie, 0, 0);
if (do_cmdline(line,
get_split_sourceline, &cookie,
DOCMD_VERBOSE|DOCMD_NOWAIT|DOCMD_KEYTYPED)
== FAIL
|| did_emsg)
{
vim_free(line);
goto on_error;
}
vim_free(line);
}
break;
// execute Ex command line that is only a range
case ISN_EXECRANGE:
{
exarg_T ea;
char *error = NULL;
CLEAR_FIELD(ea);
ea.cmdidx = CMD_SIZE;
ea.addr_type = ADDR_LINES;
ea.cmd = iptr->isn_arg.string;
parse_cmd_address(&ea, &error, FALSE);
if (ea.cmd == NULL)
goto on_error;
if (error == NULL)
error = ex_range_without_command(&ea);
if (error != NULL)
{
SOURCING_LNUM = iptr->isn_lnum;
emsg(error);
goto on_error;
}
}
break;
// Evaluate an expression with legacy syntax, push it onto the
// stack.
case ISN_LEGACY_EVAL:
{
char_u *arg = iptr->isn_arg.string;
int res;
int save_flags = cmdmod.cmod_flags;
if (GA_GROW_FAILS(&ectx->ec_stack, 1))
goto theend;
tv = STACK_TV_BOT(0);
init_tv(tv);
cmdmod.cmod_flags |= CMOD_LEGACY;
res = eval0(arg, tv, NULL, &EVALARG_EVALUATE);
cmdmod.cmod_flags = save_flags;
if (res == FAIL)
goto on_error;
++ectx->ec_stack.ga_len;
}
break;
// push typeval VAR_INSTR with instructions to be executed
case ISN_INSTR:
{
if (GA_GROW_FAILS(&ectx->ec_stack, 1))
goto theend;
tv = STACK_TV_BOT(0);
tv->vval.v_instr = ALLOC_ONE(instr_T);
if (tv->vval.v_instr == NULL)
goto on_error;
++ectx->ec_stack.ga_len;
tv->v_type = VAR_INSTR;
tv->vval.v_instr->instr_ectx = ectx;
tv->vval.v_instr->instr_instr = iptr->isn_arg.instr;
}
break;
// execute :substitute with an expression
case ISN_SUBSTITUTE:
{
subs_T *subs = &iptr->isn_arg.subs;
source_cookie_T cookie;
struct subs_expr_S *save_instr = substitute_instr;
struct subs_expr_S subs_instr;
int res;
subs_instr.subs_ectx = ectx;
subs_instr.subs_instr = subs->subs_instr;
subs_instr.subs_status = OK;
substitute_instr = &subs_instr;
SOURCING_LNUM = iptr->isn_lnum;
// This is very much like ISN_EXEC
CLEAR_FIELD(cookie);
cookie.sourcing_lnum = iptr->isn_lnum - 1;
res = do_cmdline(subs->subs_cmd,
getsourceline, &cookie,
DOCMD_VERBOSE|DOCMD_NOWAIT|DOCMD_KEYTYPED);
substitute_instr = save_instr;
if (res == FAIL || did_emsg
|| subs_instr.subs_status == FAIL)
goto on_error;
}
break;
case ISN_FINISH:
goto done;
case ISN_REDIRSTART:
// create a dummy entry for var_redir_str()
if (alloc_redir_lval() == FAIL)
goto on_error;
// The output is stored in growarray "redir_ga" until
// redirection ends.
init_redir_ga();
redir_vname = 1;
break;
case ISN_REDIREND:
{
char_u *res = get_clear_redir_ga();
// End redirection, put redirected text on the stack.
clear_redir_lval();
redir_vname = 0;
if (GA_GROW_FAILS(&ectx->ec_stack, 1))
{
vim_free(res);
goto theend;
}
tv = STACK_TV_BOT(0);
tv->v_type = VAR_STRING;
tv->vval.v_string = res;
++ectx->ec_stack.ga_len;
}
break;
case ISN_CEXPR_AUCMD:
#ifdef FEAT_QUICKFIX
if (trigger_cexpr_autocmd(iptr->isn_arg.number) == FAIL)
goto on_error;
#endif
break;
case ISN_CEXPR_CORE:
#ifdef FEAT_QUICKFIX
{
exarg_T ea;
int res;
CLEAR_FIELD(ea);
ea.cmdidx = iptr->isn_arg.cexpr.cexpr_ref->cer_cmdidx;
ea.forceit = iptr->isn_arg.cexpr.cexpr_ref->cer_forceit;
ea.cmdlinep = &iptr->isn_arg.cexpr.cexpr_ref->cer_cmdline;
--ectx->ec_stack.ga_len;
tv = STACK_TV_BOT(0);
res = cexpr_core(&ea, tv);
clear_tv(tv);
if (res == FAIL)
goto on_error;
}
#endif
break;
// execute Ex command from pieces on the stack
case ISN_EXECCONCAT:
{
int count = iptr->isn_arg.number;
size_t len = 0;
int pass;
int i;
char_u *cmd = NULL;
char_u *str;
for (pass = 1; pass <= 2; ++pass)
{
for (i = 0; i < count; ++i)
{
tv = STACK_TV_BOT(i - count);
str = tv->vval.v_string;
if (str != NULL && *str != NUL)
{
if (pass == 2)
STRCPY(cmd + len, str);
len += STRLEN(str);
}
if (pass == 2)
clear_tv(tv);
}
if (pass == 1)
{
cmd = alloc(len + 1);
if (unlikely(cmd == NULL))
goto theend;
len = 0;
}
}
SOURCING_LNUM = iptr->isn_lnum;
do_cmdline_cmd(cmd);
vim_free(cmd);
}
break;
// execute :echo {string} ...
case ISN_ECHO:
{
int count = iptr->isn_arg.echo.echo_count;
int atstart = TRUE;
int needclr = TRUE;
int idx;
for (idx = 0; idx < count; ++idx)
{
tv = STACK_TV_BOT(idx - count);
echo_one(tv, iptr->isn_arg.echo.echo_with_white,
&atstart, &needclr);
clear_tv(tv);
}
if (needclr)
msg_clr_eos();
ectx->ec_stack.ga_len -= count;
}
break;
// :execute {string} ...
// :echomsg {string} ...
// :echoconsole {string} ...
// :echoerr {string} ...
case ISN_EXECUTE:
case ISN_ECHOMSG:
case ISN_ECHOCONSOLE:
case ISN_ECHOERR:
{
int count = iptr->isn_arg.number;
garray_T ga;
char_u buf[NUMBUFLEN];
char_u *p;
int len;
int failed = FALSE;
int idx;
ga_init2(&ga, 1, 80);
for (idx = 0; idx < count; ++idx)
{
tv = STACK_TV_BOT(idx - count);
if (iptr->isn_type == ISN_EXECUTE)
{
if (tv->v_type == VAR_CHANNEL
|| tv->v_type == VAR_JOB)
{
SOURCING_LNUM = iptr->isn_lnum;
semsg(_(e_using_invalid_value_as_string_str),
vartype_name(tv->v_type));
break;
}
else
p = tv_get_string_buf(tv, buf);
}
else
p = tv_stringify(tv, buf);
len = (int)STRLEN(p);
if (GA_GROW_FAILS(&ga, len + 2))
failed = TRUE;
else
{
if (ga.ga_len > 0)
((char_u *)(ga.ga_data))[ga.ga_len++] = ' ';
STRCPY((char_u *)(ga.ga_data) + ga.ga_len, p);
ga.ga_len += len;
}
clear_tv(tv);
}
ectx->ec_stack.ga_len -= count;
if (failed)
{
ga_clear(&ga);
goto on_error;
}
if (ga.ga_data != NULL)
{
if (iptr->isn_type == ISN_EXECUTE)
{
SOURCING_LNUM = iptr->isn_lnum;
do_cmdline_cmd((char_u *)ga.ga_data);
if (did_emsg)
{
ga_clear(&ga);
goto on_error;
}
}
else
{
msg_sb_eol();
if (iptr->isn_type == ISN_ECHOMSG)
{
msg_attr(ga.ga_data, echo_attr);
out_flush();
}
else if (iptr->isn_type == ISN_ECHOCONSOLE)
{
ui_write(ga.ga_data, (int)STRLEN(ga.ga_data),
TRUE);
ui_write((char_u *)"\r\n", 2, TRUE);
}
else
{
SOURCING_LNUM = iptr->isn_lnum;
emsg(ga.ga_data);
}
}
}
ga_clear(&ga);
}
break;
// load local variable or argument
case ISN_LOAD:
if (GA_GROW_FAILS(&ectx->ec_stack, 1))
goto theend;
copy_tv(STACK_TV_VAR(iptr->isn_arg.number), STACK_TV_BOT(0));
++ectx->ec_stack.ga_len;
break;
// load v: variable
case ISN_LOADV:
if (GA_GROW_FAILS(&ectx->ec_stack, 1))
goto theend;
copy_tv(get_vim_var_tv(iptr->isn_arg.number), STACK_TV_BOT(0));
++ectx->ec_stack.ga_len;
break;
// load s: variable in Vim9 script
case ISN_LOADSCRIPT:
{
scriptref_T *sref = iptr->isn_arg.script.scriptref;
svar_T *sv;
sv = get_script_svar(sref, ectx->ec_dfunc_idx);
if (sv == NULL)
goto theend;
allocate_if_null(sv->sv_tv);
if (GA_GROW_FAILS(&ectx->ec_stack, 1))
goto theend;
copy_tv(sv->sv_tv, STACK_TV_BOT(0));
++ectx->ec_stack.ga_len;
}
break;
// load s: variable in old script
case ISN_LOADS:
{
hashtab_T *ht = &SCRIPT_VARS(
iptr->isn_arg.loadstore.ls_sid);
char_u *name = iptr->isn_arg.loadstore.ls_name;
dictitem_T *di = find_var_in_ht(ht, 0, name, TRUE);
if (di == NULL)
{
SOURCING_LNUM = iptr->isn_lnum;
semsg(_(e_undefined_variable_str), name);
goto on_error;
}
else
{
if (GA_GROW_FAILS(&ectx->ec_stack, 1))
goto theend;
copy_tv(&di->di_tv, STACK_TV_BOT(0));
++ectx->ec_stack.ga_len;
}
}
break;
// load g:/b:/w:/t: variable
case ISN_LOADG:
case ISN_LOADB:
case ISN_LOADW:
case ISN_LOADT:
{
dictitem_T *di = NULL;
hashtab_T *ht = NULL;
char namespace;
switch (iptr->isn_type)
{
case ISN_LOADG:
ht = get_globvar_ht();
namespace = 'g';
break;
case ISN_LOADB:
ht = &curbuf->b_vars->dv_hashtab;
namespace = 'b';
break;
case ISN_LOADW:
ht = &curwin->w_vars->dv_hashtab;
namespace = 'w';
break;
case ISN_LOADT:
ht = &curtab->tp_vars->dv_hashtab;
namespace = 't';
break;
default: // Cannot reach here
goto theend;
}
di = find_var_in_ht(ht, 0, iptr->isn_arg.string, TRUE);
if (di == NULL)
{
SOURCING_LNUM = iptr->isn_lnum;
semsg(_(e_undefined_variable_char_str),
namespace, iptr->isn_arg.string);
goto on_error;
}
else
{
if (GA_GROW_FAILS(&ectx->ec_stack, 1))
goto theend;
copy_tv(&di->di_tv, STACK_TV_BOT(0));
++ectx->ec_stack.ga_len;
}
}
break;
// load autoload variable
case ISN_LOADAUTO:
{
char_u *name = iptr->isn_arg.string;
if (GA_GROW_FAILS(&ectx->ec_stack, 1))
goto theend;
SOURCING_LNUM = iptr->isn_lnum;
if (eval_variable(name, (int)STRLEN(name), 0,
STACK_TV_BOT(0), NULL, EVAL_VAR_VERBOSE) == FAIL)
goto on_error;
++ectx->ec_stack.ga_len;
}
break;
// load g:/b:/w:/t: namespace
case ISN_LOADGDICT:
case ISN_LOADBDICT:
case ISN_LOADWDICT:
case ISN_LOADTDICT:
{
dict_T *d = NULL;
switch (iptr->isn_type)
{
case ISN_LOADGDICT: d = get_globvar_dict(); break;
case ISN_LOADBDICT: d = curbuf->b_vars; break;
case ISN_LOADWDICT: d = curwin->w_vars; break;
case ISN_LOADTDICT: d = curtab->tp_vars; break;
default: // Cannot reach here
goto theend;
}
if (GA_GROW_FAILS(&ectx->ec_stack, 1))
goto theend;
tv = STACK_TV_BOT(0);
tv->v_type = VAR_DICT;
tv->v_lock = 0;
tv->vval.v_dict = d;
++d->dv_refcount;
++ectx->ec_stack.ga_len;
}
break;
// load &option
case ISN_LOADOPT:
{
typval_T optval;
char_u *name = iptr->isn_arg.string;
// This is not expected to fail, name is checked during
// compilation: don't set SOURCING_LNUM.
if (GA_GROW_FAILS(&ectx->ec_stack, 1))
goto theend;
if (eval_option(&name, &optval, TRUE) == FAIL)
goto theend;
*STACK_TV_BOT(0) = optval;
++ectx->ec_stack.ga_len;
}
break;
// load $ENV
case ISN_LOADENV:
{
typval_T optval;
char_u *name = iptr->isn_arg.string;
if (GA_GROW_FAILS(&ectx->ec_stack, 1))
goto theend;
// name is always valid, checked when compiling
(void)eval_env_var(&name, &optval, TRUE);
*STACK_TV_BOT(0) = optval;
++ectx->ec_stack.ga_len;
}
break;
// load @register
case ISN_LOADREG:
if (GA_GROW_FAILS(&ectx->ec_stack, 1))
goto theend;
tv = STACK_TV_BOT(0);
tv->v_type = VAR_STRING;
tv->v_lock = 0;
// This may result in NULL, which should be equivalent to an
// empty string.
tv->vval.v_string = get_reg_contents(
iptr->isn_arg.number, GREG_EXPR_SRC);
++ectx->ec_stack.ga_len;
break;
// store local variable
case ISN_STORE:
--ectx->ec_stack.ga_len;
tv = STACK_TV_VAR(iptr->isn_arg.number);
clear_tv(tv);
*tv = *STACK_TV_BOT(0);
break;
// store s: variable in old script
case ISN_STORES:
{
hashtab_T *ht = &SCRIPT_VARS(
iptr->isn_arg.loadstore.ls_sid);
char_u *name = iptr->isn_arg.loadstore.ls_name;
dictitem_T *di = find_var_in_ht(ht, 0, name + 2, TRUE);
--ectx->ec_stack.ga_len;
if (di == NULL)
store_var(name, STACK_TV_BOT(0));
else
{
SOURCING_LNUM = iptr->isn_lnum;
if (var_check_permission(di, name) == FAIL)
{
clear_tv(STACK_TV_BOT(0));
goto on_error;
}
clear_tv(&di->di_tv);
di->di_tv = *STACK_TV_BOT(0);
}
}
break;
// store script-local variable in Vim9 script
case ISN_STORESCRIPT:
{
scriptref_T *sref = iptr->isn_arg.script.scriptref;
svar_T *sv;
sv = get_script_svar(sref, ectx->ec_dfunc_idx);
if (sv == NULL)
goto theend;
--ectx->ec_stack.ga_len;
// "const" and "final" are checked at compile time, locking
// the value needs to be checked here.
SOURCING_LNUM = iptr->isn_lnum;
if (value_check_lock(sv->sv_tv->v_lock, sv->sv_name, FALSE))
{
clear_tv(STACK_TV_BOT(0));
goto on_error;
}
clear_tv(sv->sv_tv);
*sv->sv_tv = *STACK_TV_BOT(0);
}
break;
// store option
case ISN_STOREOPT:
case ISN_STOREFUNCOPT:
{
char_u *opt_name = iptr->isn_arg.storeopt.so_name;
int opt_flags = iptr->isn_arg.storeopt.so_flags;
long n = 0;
char_u *s = NULL;
char *msg;
char_u numbuf[NUMBUFLEN];
char_u *tofree = NULL;
--ectx->ec_stack.ga_len;
tv = STACK_TV_BOT(0);
if (tv->v_type == VAR_STRING)
{
s = tv->vval.v_string;
if (s == NULL)
s = (char_u *)"";
}
else if (iptr->isn_type == ISN_STOREFUNCOPT)
{
SOURCING_LNUM = iptr->isn_lnum;
// If the option can be set to a function reference or
// a lambda and the passed value is a function
// reference, then convert it to the name (string) of
// the function reference.
s = tv2string(tv, &tofree, numbuf, 0);
if (s == NULL || *s == NUL)
{
clear_tv(tv);
goto on_error;
}
}
else
// must be VAR_NUMBER, CHECKTYPE makes sure
n = tv->vval.v_number;
msg = set_option_value(opt_name, n, s, opt_flags);
clear_tv(tv);
vim_free(tofree);
if (msg != NULL)
{
SOURCING_LNUM = iptr->isn_lnum;
emsg(_(msg));
goto on_error;
}
}
break;
// store $ENV
case ISN_STOREENV:
--ectx->ec_stack.ga_len;
tv = STACK_TV_BOT(0);
vim_setenv_ext(iptr->isn_arg.string, tv_get_string(tv));
clear_tv(tv);
break;
// store @r
case ISN_STOREREG:
{
int reg = iptr->isn_arg.number;
--ectx->ec_stack.ga_len;
tv = STACK_TV_BOT(0);
write_reg_contents(reg, tv_get_string(tv), -1, FALSE);
clear_tv(tv);
}
break;
// store v: variable
case ISN_STOREV:
--ectx->ec_stack.ga_len;
if (set_vim_var_tv(iptr->isn_arg.number, STACK_TV_BOT(0))
== FAIL)
// should not happen, type is checked when compiling
goto on_error;
break;
// store g:/b:/w:/t: variable
case ISN_STOREG:
case ISN_STOREB:
case ISN_STOREW:
case ISN_STORET:
{
dictitem_T *di;
hashtab_T *ht;
char_u *name = iptr->isn_arg.string + 2;
switch (iptr->isn_type)
{
case ISN_STOREG:
ht = get_globvar_ht();
break;
case ISN_STOREB:
ht = &curbuf->b_vars->dv_hashtab;
break;
case ISN_STOREW:
ht = &curwin->w_vars->dv_hashtab;
break;
case ISN_STORET:
ht = &curtab->tp_vars->dv_hashtab;
break;
default: // Cannot reach here
goto theend;
}
--ectx->ec_stack.ga_len;
di = find_var_in_ht(ht, 0, name, TRUE);
if (di == NULL)
store_var(iptr->isn_arg.string, STACK_TV_BOT(0));
else
{
SOURCING_LNUM = iptr->isn_lnum;
if (var_check_permission(di, name) == FAIL)
goto on_error;
clear_tv(&di->di_tv);
di->di_tv = *STACK_TV_BOT(0);
}
}
break;
// store an autoload variable
case ISN_STOREAUTO:
SOURCING_LNUM = iptr->isn_lnum;
set_var(iptr->isn_arg.string, STACK_TV_BOT(-1), TRUE);
clear_tv(STACK_TV_BOT(-1));
--ectx->ec_stack.ga_len;
break;
// store number in local variable
case ISN_STORENR:
tv = STACK_TV_VAR(iptr->isn_arg.storenr.stnr_idx);
clear_tv(tv);
tv->v_type = VAR_NUMBER;
tv->vval.v_number = iptr->isn_arg.storenr.stnr_val;
break;
// store value in list or dict variable
case ISN_STOREINDEX:
{
vartype_T dest_type = iptr->isn_arg.vartype;
typval_T *tv_idx = STACK_TV_BOT(-2);
typval_T *tv_dest = STACK_TV_BOT(-1);
int status = OK;
// Stack contains:
// -3 value to be stored
// -2 index
// -1 dict or list
tv = STACK_TV_BOT(-3);
SOURCING_LNUM = iptr->isn_lnum;
if (dest_type == VAR_ANY)
{
dest_type = tv_dest->v_type;
if (dest_type == VAR_DICT)
status = do_2string(tv_idx, TRUE, FALSE);
else if (dest_type == VAR_LIST
&& tv_idx->v_type != VAR_NUMBER)
{
emsg(_(e_number_expected));
status = FAIL;
}
}
else if (dest_type != tv_dest->v_type)
{
// just in case, should be OK
semsg(_(e_expected_str_but_got_str),
vartype_name(dest_type),
vartype_name(tv_dest->v_type));
status = FAIL;
}
if (status == OK && dest_type == VAR_LIST)
{
long lidx = (long)tv_idx->vval.v_number;
list_T *list = tv_dest->vval.v_list;
if (list == NULL)
{
emsg(_(e_list_not_set));
goto on_error;
}
if (lidx < 0 && list->lv_len + lidx >= 0)
// negative index is relative to the end
lidx = list->lv_len + lidx;
if (lidx < 0 || lidx > list->lv_len)
{
semsg(_(e_list_index_out_of_range_nr), lidx);
goto on_error;
}
if (lidx < list->lv_len)
{
listitem_T *li = list_find(list, lidx);
if (error_if_locked(li->li_tv.v_lock,
e_cannot_change_list_item))
goto on_error;
// overwrite existing list item
clear_tv(&li->li_tv);
li->li_tv = *tv;
}
else
{
if (error_if_locked(list->lv_lock,
e_cannot_change_list))
goto on_error;
// append to list, only fails when out of memory
if (list_append_tv(list, tv) == FAIL)
goto theend;
clear_tv(tv);
}
}
else if (status == OK && dest_type == VAR_DICT)
{
char_u *key = tv_idx->vval.v_string;
dict_T *dict = tv_dest->vval.v_dict;
dictitem_T *di;
SOURCING_LNUM = iptr->isn_lnum;
if (dict == NULL)
{
emsg(_(e_dictionary_not_set));
goto on_error;
}
if (key == NULL)
key = (char_u *)"";
di = dict_find(dict, key, -1);
if (di != NULL)
{
if (error_if_locked(di->di_tv.v_lock,
e_cannot_change_dict_item))
goto on_error;
// overwrite existing value
clear_tv(&di->di_tv);
di->di_tv = *tv;
}
else
{
if (error_if_locked(dict->dv_lock,
e_cannot_change_dict))
goto on_error;
// add to dict, only fails when out of memory
if (dict_add_tv(dict, (char *)key, tv) == FAIL)
goto theend;
clear_tv(tv);
}
}
else if (status == OK && dest_type == VAR_BLOB)
{
long lidx = (long)tv_idx->vval.v_number;
blob_T *blob = tv_dest->vval.v_blob;
varnumber_T nr;
int error = FALSE;
int len;
if (blob == NULL)
{
emsg(_(e_blob_not_set));
goto on_error;
}
len = blob_len(blob);
if (lidx < 0 && len + lidx >= 0)
// negative index is relative to the end
lidx = len + lidx;
// Can add one byte at the end.
if (lidx < 0 || lidx > len)
{
semsg(_(e_blob_index_out_of_range_nr), lidx);
goto on_error;
}
if (value_check_lock(blob->bv_lock,
(char_u *)"blob", FALSE))
goto on_error;
nr = tv_get_number_chk(tv, &error);
if (error)
goto on_error;
blob_set_append(blob, lidx, nr);
}
else
{
status = FAIL;
semsg(_(e_cannot_index_str), vartype_name(dest_type));
}
clear_tv(tv_idx);
clear_tv(tv_dest);
ectx->ec_stack.ga_len -= 3;
if (status == FAIL)
{
clear_tv(tv);
goto on_error;
}
}
break;
// store value in blob range
case ISN_STORERANGE:
{
typval_T *tv_idx1 = STACK_TV_BOT(-3);
typval_T *tv_idx2 = STACK_TV_BOT(-2);
typval_T *tv_dest = STACK_TV_BOT(-1);
int status = OK;
// Stack contains:
// -4 value to be stored
// -3 first index or "none"
// -2 second index or "none"
// -1 destination list or blob
tv = STACK_TV_BOT(-4);
if (tv_dest->v_type == VAR_LIST)
{
long n1;
long n2;
int error = FALSE;
SOURCING_LNUM = iptr->isn_lnum;
n1 = (long)tv_get_number_chk(tv_idx1, &error);
if (error)
status = FAIL;
else
{
if (tv_idx2->v_type == VAR_SPECIAL
&& tv_idx2->vval.v_number == VVAL_NONE)
n2 = list_len(tv_dest->vval.v_list) - 1;
else
n2 = (long)tv_get_number_chk(tv_idx2, &error);
if (error)
status = FAIL;
else
{
listitem_T *li1 = check_range_index_one(
tv_dest->vval.v_list, &n1, FALSE);
if (li1 == NULL)
status = FAIL;
else
{
status = check_range_index_two(
tv_dest->vval.v_list,
&n1, li1, &n2, FALSE);
if (status != FAIL)
status = list_assign_range(
tv_dest->vval.v_list,
tv->vval.v_list,
n1,
n2,
tv_idx2->v_type == VAR_SPECIAL,
(char_u *)"=",
(char_u *)"[unknown]");
}
}
}
}
else if (tv_dest->v_type == VAR_BLOB)
{
varnumber_T n1;
varnumber_T n2;
int error = FALSE;
n1 = tv_get_number_chk(tv_idx1, &error);
if (error)
status = FAIL;
else
{
if (tv_idx2->v_type == VAR_SPECIAL
&& tv_idx2->vval.v_number == VVAL_NONE)
n2 = blob_len(tv_dest->vval.v_blob) - 1;
else
n2 = tv_get_number_chk(tv_idx2, &error);
if (error)
status = FAIL;
else
{
long bloblen = blob_len(tv_dest->vval.v_blob);
if (check_blob_index(bloblen,
n1, FALSE) == FAIL
|| check_blob_range(bloblen,
n1, n2, FALSE) == FAIL)
status = FAIL;
else
status = blob_set_range(
tv_dest->vval.v_blob, n1, n2, tv);
}
}
}
else
{
status = FAIL;
emsg(_(e_blob_required));
}
clear_tv(tv_idx1);
clear_tv(tv_idx2);
clear_tv(tv_dest);
ectx->ec_stack.ga_len -= 4;
clear_tv(tv);
if (status == FAIL)
goto on_error;
}
break;
// load or store variable or argument from outer scope
case ISN_LOADOUTER:
case ISN_STOREOUTER:
{
int depth = iptr->isn_arg.outer.outer_depth;
outer_T *outer = ectx->ec_outer_ref == NULL ? NULL
: ectx->ec_outer_ref->or_outer;
while (depth > 1 && outer != NULL)
{
outer = outer->out_up;
--depth;
}
if (outer == NULL)
{
SOURCING_LNUM = iptr->isn_lnum;
if (ectx->ec_frame_idx == ectx->ec_initial_frame_idx
|| ectx->ec_outer_ref == NULL)
// Possibly :def function called from legacy
// context.
emsg(_(e_closure_called_from_invalid_context));
else
iemsg("LOADOUTER depth more than scope levels");
goto theend;
}
tv = ((typval_T *)outer->out_stack->ga_data)
+ outer->out_frame_idx + STACK_FRAME_SIZE
+ iptr->isn_arg.outer.outer_idx;
if (iptr->isn_type == ISN_LOADOUTER)
{
if (GA_GROW_FAILS(&ectx->ec_stack, 1))
goto theend;
copy_tv(tv, STACK_TV_BOT(0));
++ectx->ec_stack.ga_len;
}
else
{
--ectx->ec_stack.ga_len;
clear_tv(tv);
*tv = *STACK_TV_BOT(0);
}
}
break;
// unlet item in list or dict variable
case ISN_UNLETINDEX:
{
typval_T *tv_idx = STACK_TV_BOT(-2);
typval_T *tv_dest = STACK_TV_BOT(-1);
int status = OK;
// Stack contains:
// -2 index
// -1 dict or list
if (tv_dest->v_type == VAR_DICT)
{
// unlet a dict item, index must be a string
if (tv_idx->v_type != VAR_STRING)
{
SOURCING_LNUM = iptr->isn_lnum;
semsg(_(e_expected_str_but_got_str),
vartype_name(VAR_STRING),
vartype_name(tv_idx->v_type));
status = FAIL;
}
else
{
dict_T *d = tv_dest->vval.v_dict;
char_u *key = tv_idx->vval.v_string;
dictitem_T *di = NULL;
if (d != NULL && value_check_lock(
d->dv_lock, NULL, FALSE))
status = FAIL;
else
{
SOURCING_LNUM = iptr->isn_lnum;
if (key == NULL)
key = (char_u *)"";
if (d != NULL)
di = dict_find(d, key, (int)STRLEN(key));
if (di == NULL)
{
// NULL dict is equivalent to empty dict
semsg(_(e_key_not_present_in_dictionary), key);
status = FAIL;
}
else if (var_check_fixed(di->di_flags,
NULL, FALSE)
|| var_check_ro(di->di_flags,
NULL, FALSE))
status = FAIL;
else
dictitem_remove(d, di);
}
}
}
else if (tv_dest->v_type == VAR_LIST)
{
// unlet a List item, index must be a number
SOURCING_LNUM = iptr->isn_lnum;
if (check_for_number(tv_idx) == FAIL)
{
status = FAIL;
}
else
{
list_T *l = tv_dest->vval.v_list;
long n = (long)tv_idx->vval.v_number;
if (l != NULL && value_check_lock(
l->lv_lock, NULL, FALSE))
status = FAIL;
else
{
listitem_T *li = list_find(l, n);
if (li == NULL)
{
SOURCING_LNUM = iptr->isn_lnum;
semsg(_(e_list_index_out_of_range_nr), n);
status = FAIL;
}
else if (value_check_lock(li->li_tv.v_lock,
NULL, FALSE))
status = FAIL;
else
listitem_remove(l, li);
}
}
}
else
{
status = FAIL;
semsg(_(e_cannot_index_str),
vartype_name(tv_dest->v_type));
}
clear_tv(tv_idx);
clear_tv(tv_dest);
ectx->ec_stack.ga_len -= 2;
if (status == FAIL)
goto on_error;
}
break;
// unlet range of items in list variable
case ISN_UNLETRANGE:
{
// Stack contains:
// -3 index1
// -2 index2
// -1 dict or list
typval_T *tv_idx1 = STACK_TV_BOT(-3);
typval_T *tv_idx2 = STACK_TV_BOT(-2);
typval_T *tv_dest = STACK_TV_BOT(-1);
int status = OK;
if (tv_dest->v_type == VAR_LIST)
{
// indexes must be a number
SOURCING_LNUM = iptr->isn_lnum;
if (check_for_number(tv_idx1) == FAIL
|| (tv_idx2->v_type != VAR_SPECIAL
&& check_for_number(tv_idx2) == FAIL))
{
status = FAIL;
}
else
{
list_T *l = tv_dest->vval.v_list;
long n1 = (long)tv_idx1->vval.v_number;
long n2 = tv_idx2->v_type == VAR_SPECIAL
? 0 : (long)tv_idx2->vval.v_number;
listitem_T *li;
li = list_find_index(l, &n1);
if (li == NULL)
status = FAIL;
else
{
if (n1 < 0)
n1 = list_idx_of_item(l, li);
if (n2 < 0)
{
listitem_T *li2 = list_find(l, n2);
if (li2 == NULL)
status = FAIL;
else
n2 = list_idx_of_item(l, li2);
}
if (status != FAIL
&& tv_idx2->v_type != VAR_SPECIAL
&& n2 < n1)
{
semsg(_(e_list_index_out_of_range_nr), n2);
status = FAIL;
}
if (status != FAIL
&& list_unlet_range(l, li, NULL, n1,
tv_idx2->v_type != VAR_SPECIAL, n2)
== FAIL)
status = FAIL;
}
}
}
else
{
status = FAIL;
SOURCING_LNUM = iptr->isn_lnum;
semsg(_(e_cannot_index_str),
vartype_name(tv_dest->v_type));
}
clear_tv(tv_idx1);
clear_tv(tv_idx2);
clear_tv(tv_dest);
ectx->ec_stack.ga_len -= 3;
if (status == FAIL)
goto on_error;
}
break;
// push constant
case ISN_PUSHNR:
case ISN_PUSHBOOL:
case ISN_PUSHSPEC:
case ISN_PUSHF:
case ISN_PUSHS:
case ISN_PUSHBLOB:
case ISN_PUSHFUNC:
case ISN_PUSHCHANNEL:
case ISN_PUSHJOB:
if (GA_GROW_FAILS(&ectx->ec_stack, 1))
goto theend;
tv = STACK_TV_BOT(0);
tv->v_lock = 0;
++ectx->ec_stack.ga_len;
switch (iptr->isn_type)
{
case ISN_PUSHNR:
tv->v_type = VAR_NUMBER;
tv->vval.v_number = iptr->isn_arg.number;
break;
case ISN_PUSHBOOL:
tv->v_type = VAR_BOOL;
tv->vval.v_number = iptr->isn_arg.number;
break;
case ISN_PUSHSPEC:
tv->v_type = VAR_SPECIAL;
tv->vval.v_number = iptr->isn_arg.number;
break;
#ifdef FEAT_FLOAT
case ISN_PUSHF:
tv->v_type = VAR_FLOAT;
tv->vval.v_float = iptr->isn_arg.fnumber;
break;
#endif
case ISN_PUSHBLOB:
blob_copy(iptr->isn_arg.blob, tv);
break;
case ISN_PUSHFUNC:
tv->v_type = VAR_FUNC;
if (iptr->isn_arg.string == NULL)
tv->vval.v_string = NULL;
else
tv->vval.v_string =
vim_strsave(iptr->isn_arg.string);
break;
case ISN_PUSHCHANNEL:
#ifdef FEAT_JOB_CHANNEL
tv->v_type = VAR_CHANNEL;
tv->vval.v_channel = iptr->isn_arg.channel;
if (tv->vval.v_channel != NULL)
++tv->vval.v_channel->ch_refcount;
#endif
break;
case ISN_PUSHJOB:
#ifdef FEAT_JOB_CHANNEL
tv->v_type = VAR_JOB;
tv->vval.v_job = iptr->isn_arg.job;
if (tv->vval.v_job != NULL)
++tv->vval.v_job->jv_refcount;
#endif
break;
default:
tv->v_type = VAR_STRING;
tv->vval.v_string = vim_strsave(
iptr->isn_arg.string == NULL
? (char_u *)"" : iptr->isn_arg.string);
}
break;
case ISN_UNLET:
if (do_unlet(iptr->isn_arg.unlet.ul_name,
iptr->isn_arg.unlet.ul_forceit) == FAIL)
goto on_error;
break;
case ISN_UNLETENV:
vim_unsetenv(iptr->isn_arg.unlet.ul_name);
break;
case ISN_LOCKUNLOCK:
{
typval_T *lval_root_save = lval_root;
int res;
// Stack has the local variable, argument the whole :lock
// or :unlock command, like ISN_EXEC.
--ectx->ec_stack.ga_len;
lval_root = STACK_TV_BOT(0);
res = exec_command(iptr);
clear_tv(lval_root);
lval_root = lval_root_save;
if (res == FAIL)
goto on_error;
}
break;
case ISN_LOCKCONST:
item_lock(STACK_TV_BOT(-1), 100, TRUE, TRUE);
break;
// create a list from items on the stack; uses a single allocation
// for the list header and the items
case ISN_NEWLIST:
if (exe_newlist(iptr->isn_arg.number, ectx) == FAIL)
goto theend;
break;
// create a dict from items on the stack
case ISN_NEWDICT:
{
int count = iptr->isn_arg.number;
dict_T *dict = dict_alloc();
dictitem_T *item;
char_u *key;
int idx;
if (unlikely(dict == NULL))
goto theend;
for (idx = 0; idx < count; ++idx)
{
// have already checked key type is VAR_STRING
tv = STACK_TV_BOT(2 * (idx - count));
// check key is unique
key = tv->vval.v_string == NULL
? (char_u *)"" : tv->vval.v_string;
item = dict_find(dict, key, -1);
if (item != NULL)
{
SOURCING_LNUM = iptr->isn_lnum;
semsg(_(e_duplicate_key_in_dicitonary), key);
dict_unref(dict);
goto on_error;
}
item = dictitem_alloc(key);
clear_tv(tv);
if (unlikely(item == NULL))
{
dict_unref(dict);
goto theend;
}
item->di_tv = *STACK_TV_BOT(2 * (idx - count) + 1);
item->di_tv.v_lock = 0;
if (dict_add(dict, item) == FAIL)
{
// can this ever happen?
dict_unref(dict);
goto theend;
}
}
if (count > 0)
ectx->ec_stack.ga_len -= 2 * count - 1;
else if (GA_GROW_FAILS(&ectx->ec_stack, 1))
goto theend;
else
++ectx->ec_stack.ga_len;
tv = STACK_TV_BOT(-1);
tv->v_type = VAR_DICT;
tv->v_lock = 0;
tv->vval.v_dict = dict;
++dict->dv_refcount;
}
break;
// call a :def function
case ISN_DCALL:
SOURCING_LNUM = iptr->isn_lnum;
if (call_dfunc(iptr->isn_arg.dfunc.cdf_idx,
NULL,
iptr->isn_arg.dfunc.cdf_argcount,
ectx) == FAIL)
goto on_error;
break;
// call a builtin function
case ISN_BCALL:
SOURCING_LNUM = iptr->isn_lnum;
if (call_bfunc(iptr->isn_arg.bfunc.cbf_idx,
iptr->isn_arg.bfunc.cbf_argcount,
ectx) == FAIL)
goto on_error;
break;
// call a funcref or partial
case ISN_PCALL:
{
cpfunc_T *pfunc = &iptr->isn_arg.pfunc;
int r;
typval_T partial_tv;
SOURCING_LNUM = iptr->isn_lnum;
if (pfunc->cpf_top)
{
// funcref is above the arguments
tv = STACK_TV_BOT(-pfunc->cpf_argcount - 1);
}
else
{
// Get the funcref from the stack.
--ectx->ec_stack.ga_len;
partial_tv = *STACK_TV_BOT(0);
tv = &partial_tv;
}
r = call_partial(tv, pfunc->cpf_argcount, ectx);
if (tv == &partial_tv)
clear_tv(&partial_tv);
if (r == FAIL)
goto on_error;
}
break;
case ISN_PCALL_END:
// PCALL finished, arguments have been consumed and replaced by
// the return value. Now clear the funcref from the stack,
// and move the return value in its place.
--ectx->ec_stack.ga_len;
clear_tv(STACK_TV_BOT(-1));
*STACK_TV_BOT(-1) = *STACK_TV_BOT(0);
break;
// call a user defined function or funcref/partial
case ISN_UCALL:
{
cufunc_T *cufunc = &iptr->isn_arg.ufunc;
SOURCING_LNUM = iptr->isn_lnum;
if (call_eval_func(cufunc->cuf_name, cufunc->cuf_argcount,
ectx, iptr) == FAIL)
goto on_error;
}
break;
// return from a :def function call without a value
case ISN_RETURN_VOID:
if (GA_GROW_FAILS(&ectx->ec_stack, 1))
goto theend;
tv = STACK_TV_BOT(0);
++ectx->ec_stack.ga_len;
tv->v_type = VAR_VOID;
tv->vval.v_number = 0;
tv->v_lock = 0;
// FALLTHROUGH
// return from a :def function call with what is on the stack
case ISN_RETURN:
{
garray_T *trystack = &ectx->ec_trystack;
trycmd_T *trycmd = NULL;
if (trystack->ga_len > 0)
trycmd = ((trycmd_T *)trystack->ga_data)
+ trystack->ga_len - 1;
if (trycmd != NULL
&& trycmd->tcd_frame_idx == ectx->ec_frame_idx)
{
// jump to ":finally" or ":endtry"
if (trycmd->tcd_finally_idx != 0)
ectx->ec_iidx = trycmd->tcd_finally_idx;
else
ectx->ec_iidx = trycmd->tcd_endtry_idx;
trycmd->tcd_return = TRUE;
}
else
goto func_return;
}
break;
// push a partial, a reference to a compiled function
case ISN_FUNCREF:
{
partial_T *pt = ALLOC_CLEAR_ONE(partial_T);
ufunc_T *ufunc;
funcref_T *funcref = &iptr->isn_arg.funcref;
if (pt == NULL)
goto theend;
if (GA_GROW_FAILS(&ectx->ec_stack, 1))
{
vim_free(pt);
goto theend;
}
if (funcref->fr_func_name == NULL)
{
dfunc_T *pt_dfunc = ((dfunc_T *)def_functions.ga_data)
+ funcref->fr_dfunc_idx;
ufunc = pt_dfunc->df_ufunc;
}
else
{
ufunc = find_func(funcref->fr_func_name, FALSE, NULL);
}
if (ufunc == NULL)
{
SOURCING_LNUM = iptr->isn_lnum;
emsg(_(e_function_reference_invalid));
goto theend;
}
if (fill_partial_and_closure(pt, ufunc, ectx) == FAIL)
goto theend;
tv = STACK_TV_BOT(0);
++ectx->ec_stack.ga_len;
tv->vval.v_partial = pt;
tv->v_type = VAR_PARTIAL;
tv->v_lock = 0;
}
break;
// Create a global function from a lambda.
case ISN_NEWFUNC:
{
newfunc_T *newfunc = &iptr->isn_arg.newfunc;
if (copy_func(newfunc->nf_lambda, newfunc->nf_global,
ectx) == FAIL)
goto theend;
}
break;
// List functions
case ISN_DEF:
if (iptr->isn_arg.string == NULL)
list_functions(NULL);
else
{
exarg_T ea;
char_u *line_to_free = NULL;
CLEAR_FIELD(ea);
ea.cmd = ea.arg = iptr->isn_arg.string;
define_function(&ea, NULL, &line_to_free);
vim_free(line_to_free);
}
break;
// jump if a condition is met
case ISN_JUMP:
{
jumpwhen_T when = iptr->isn_arg.jump.jump_when;
int error = FALSE;
int jump = TRUE;
if (when != JUMP_ALWAYS)
{
tv = STACK_TV_BOT(-1);
if (when == JUMP_IF_COND_FALSE
|| when == JUMP_IF_FALSE
|| when == JUMP_IF_COND_TRUE)
{
SOURCING_LNUM = iptr->isn_lnum;
jump = tv_get_bool_chk(tv, &error);
if (error)
goto on_error;
}
else
jump = tv2bool(tv);
if (when == JUMP_IF_FALSE
|| when == JUMP_AND_KEEP_IF_FALSE
|| when == JUMP_IF_COND_FALSE)
jump = !jump;
if (when == JUMP_IF_FALSE || !jump)
{
// drop the value from the stack
clear_tv(tv);
--ectx->ec_stack.ga_len;
}
}
if (jump)
ectx->ec_iidx = iptr->isn_arg.jump.jump_where;
}
break;
// Jump if an argument with a default value was already set and not
// v:none.
case ISN_JUMP_IF_ARG_SET:
tv = STACK_TV_VAR(iptr->isn_arg.jumparg.jump_arg_off);
if (tv->v_type != VAR_UNKNOWN
&& !(tv->v_type == VAR_SPECIAL
&& tv->vval.v_number == VVAL_NONE))
ectx->ec_iidx = iptr->isn_arg.jumparg.jump_where;
break;
// top of a for loop
case ISN_FOR:
{
typval_T *ltv = STACK_TV_BOT(-1);
typval_T *idxtv =
STACK_TV_VAR(iptr->isn_arg.forloop.for_idx);
if (GA_GROW_FAILS(&ectx->ec_stack, 1))
goto theend;
if (ltv->v_type == VAR_LIST)
{
list_T *list = ltv->vval.v_list;
// push the next item from the list
++idxtv->vval.v_number;
if (list == NULL
|| idxtv->vval.v_number >= list->lv_len)
{
// past the end of the list, jump to "endfor"
ectx->ec_iidx = iptr->isn_arg.forloop.for_end;
may_restore_cmdmod(&ectx->ec_funclocal);
}
else if (list->lv_first == &range_list_item)
{
// non-materialized range() list
tv = STACK_TV_BOT(0);
tv->v_type = VAR_NUMBER;
tv->v_lock = 0;
tv->vval.v_number = list_find_nr(
list, idxtv->vval.v_number, NULL);
++ectx->ec_stack.ga_len;
}
else
{
listitem_T *li = list_find(list,
idxtv->vval.v_number);
copy_tv(&li->li_tv, STACK_TV_BOT(0));
++ectx->ec_stack.ga_len;
}
}
else if (ltv->v_type == VAR_STRING)
{
char_u *str = ltv->vval.v_string;
// The index is for the last byte of the previous
// character.
++idxtv->vval.v_number;
if (str == NULL || str[idxtv->vval.v_number] == NUL)
{
// past the end of the string, jump to "endfor"
ectx->ec_iidx = iptr->isn_arg.forloop.for_end;
may_restore_cmdmod(&ectx->ec_funclocal);
}
else
{
int clen = mb_ptr2len(str + idxtv->vval.v_number);
// Push the next character from the string.
tv = STACK_TV_BOT(0);
tv->v_type = VAR_STRING;
tv->vval.v_string = vim_strnsave(
str + idxtv->vval.v_number, clen);
++ectx->ec_stack.ga_len;
idxtv->vval.v_number += clen - 1;
}
}
else if (ltv->v_type == VAR_BLOB)
{
blob_T *blob = ltv->vval.v_blob;
// When we get here the first time make a copy of the
// blob, so that the iteration still works when it is
// changed.
if (idxtv->vval.v_number == -1 && blob != NULL)
{
blob_copy(blob, ltv);
blob_unref(blob);
blob = ltv->vval.v_blob;
}
// The index is for the previous byte.
++idxtv->vval.v_number;
if (blob == NULL
|| idxtv->vval.v_number >= blob_len(blob))
{
// past the end of the blob, jump to "endfor"
ectx->ec_iidx = iptr->isn_arg.forloop.for_end;
may_restore_cmdmod(&ectx->ec_funclocal);
}
else
{
// Push the next byte from the blob.
tv = STACK_TV_BOT(0);
tv->v_type = VAR_NUMBER;
tv->vval.v_number = blob_get(blob,
idxtv->vval.v_number);
++ectx->ec_stack.ga_len;
}
}
else
{
semsg(_(e_for_loop_on_str_not_supported),
vartype_name(ltv->v_type));
goto theend;
}
}
break;
// start of ":try" block
case ISN_TRY:
{
trycmd_T *trycmd = NULL;
if (GA_GROW_FAILS(&ectx->ec_trystack, 1))
goto theend;
trycmd = ((trycmd_T *)ectx->ec_trystack.ga_data)
+ ectx->ec_trystack.ga_len;
++ectx->ec_trystack.ga_len;
++trylevel;
CLEAR_POINTER(trycmd);
trycmd->tcd_frame_idx = ectx->ec_frame_idx;
trycmd->tcd_stack_len = ectx->ec_stack.ga_len;
trycmd->tcd_catch_idx =
iptr->isn_arg.tryref.try_ref->try_catch;
trycmd->tcd_finally_idx =
iptr->isn_arg.tryref.try_ref->try_finally;
trycmd->tcd_endtry_idx =
iptr->isn_arg.tryref.try_ref->try_endtry;
}
break;
case ISN_PUSHEXC:
if (current_exception == NULL)
{
SOURCING_LNUM = iptr->isn_lnum;
iemsg("Evaluating catch while current_exception is NULL");
goto theend;
}
if (GA_GROW_FAILS(&ectx->ec_stack, 1))
goto theend;
tv = STACK_TV_BOT(0);
++ectx->ec_stack.ga_len;
tv->v_type = VAR_STRING;
tv->v_lock = 0;
tv->vval.v_string = vim_strsave(
(char_u *)current_exception->value);
break;
case ISN_CATCH:
{
garray_T *trystack = &ectx->ec_trystack;
may_restore_cmdmod(&ectx->ec_funclocal);
if (trystack->ga_len > 0)
{
trycmd_T *trycmd = ((trycmd_T *)trystack->ga_data)
+ trystack->ga_len - 1;
trycmd->tcd_caught = TRUE;
trycmd->tcd_did_throw = FALSE;
}
did_emsg = got_int = did_throw = FALSE;
force_abort = need_rethrow = FALSE;
catch_exception(current_exception);
}
break;
case ISN_TRYCONT:
{
garray_T *trystack = &ectx->ec_trystack;
trycont_T *trycont = &iptr->isn_arg.trycont;
int i;
trycmd_T *trycmd;
int iidx = trycont->tct_where;
if (trystack->ga_len < trycont->tct_levels)
{
siemsg("TRYCONT: expected %d levels, found %d",
trycont->tct_levels, trystack->ga_len);
goto theend;
}
// Make :endtry jump to any outer try block and the last
// :endtry inside the loop to the loop start.
for (i = trycont->tct_levels; i > 0; --i)
{
trycmd = ((trycmd_T *)trystack->ga_data)
+ trystack->ga_len - i;
// Add one to tcd_cont to be able to jump to
// instruction with index zero.
trycmd->tcd_cont = iidx + 1;
iidx = trycmd->tcd_finally_idx == 0
? trycmd->tcd_endtry_idx : trycmd->tcd_finally_idx;
}
// jump to :finally or :endtry of current try statement
ectx->ec_iidx = iidx;
}
break;
case ISN_FINALLY:
{
garray_T *trystack = &ectx->ec_trystack;
trycmd_T *trycmd = ((trycmd_T *)trystack->ga_data)
+ trystack->ga_len - 1;
// Reset the index to avoid a return statement jumps here
// again.
trycmd->tcd_finally_idx = 0;
break;
}
// end of ":try" block
case ISN_ENDTRY:
{
garray_T *trystack = &ectx->ec_trystack;
if (trystack->ga_len > 0)
{
trycmd_T *trycmd;
--trystack->ga_len;
--trylevel;
trycmd = ((trycmd_T *)trystack->ga_data)
+ trystack->ga_len;
if (trycmd->tcd_did_throw)
did_throw = TRUE;
if (trycmd->tcd_caught && current_exception != NULL)
{
// discard the exception
if (caught_stack == current_exception)
caught_stack = caught_stack->caught;
discard_current_exception();
}
if (trycmd->tcd_return)
goto func_return;
while (ectx->ec_stack.ga_len > trycmd->tcd_stack_len)
{
--ectx->ec_stack.ga_len;
clear_tv(STACK_TV_BOT(0));
}
if (trycmd->tcd_cont != 0)
// handling :continue: jump to outer try block or
// start of the loop
ectx->ec_iidx = trycmd->tcd_cont - 1;
}
}
break;
case ISN_THROW:
{
garray_T *trystack = &ectx->ec_trystack;
if (trystack->ga_len == 0 && trylevel == 0 && emsg_silent)
{
// throwing an exception while using "silent!" causes
// the function to abort but not display an error.
tv = STACK_TV_BOT(-1);
clear_tv(tv);
tv->v_type = VAR_NUMBER;
tv->vval.v_number = 0;
goto done;
}
--ectx->ec_stack.ga_len;
tv = STACK_TV_BOT(0);
if (tv->vval.v_string == NULL
|| *skipwhite(tv->vval.v_string) == NUL)
{
vim_free(tv->vval.v_string);
SOURCING_LNUM = iptr->isn_lnum;
emsg(_(e_throw_with_empty_string));
goto theend;
}
// Inside a "catch" we need to first discard the caught
// exception.
if (trystack->ga_len > 0)
{
trycmd_T *trycmd = ((trycmd_T *)trystack->ga_data)
+ trystack->ga_len - 1;
if (trycmd->tcd_caught && current_exception != NULL)
{
// discard the exception
if (caught_stack == current_exception)
caught_stack = caught_stack->caught;
discard_current_exception();
trycmd->tcd_caught = FALSE;
}
}
if (throw_exception(tv->vval.v_string, ET_USER, NULL)
== FAIL)
{
vim_free(tv->vval.v_string);
goto theend;
}
did_throw = TRUE;
}
break;
// compare with special values
case ISN_COMPAREBOOL:
case ISN_COMPARESPECIAL:
{
typval_T *tv1 = STACK_TV_BOT(-2);
typval_T *tv2 = STACK_TV_BOT(-1);
varnumber_T arg1 = tv1->vval.v_number;
varnumber_T arg2 = tv2->vval.v_number;
int res;
switch (iptr->isn_arg.op.op_type)
{
case EXPR_EQUAL: res = arg1 == arg2; break;
case EXPR_NEQUAL: res = arg1 != arg2; break;
default: res = 0; break;
}
--ectx->ec_stack.ga_len;
tv1->v_type = VAR_BOOL;
tv1->vval.v_number = res ? VVAL_TRUE : VVAL_FALSE;
}
break;
// Operation with two number arguments
case ISN_OPNR:
case ISN_COMPARENR:
{
typval_T *tv1 = STACK_TV_BOT(-2);
typval_T *tv2 = STACK_TV_BOT(-1);
varnumber_T arg1 = tv1->vval.v_number;
varnumber_T arg2 = tv2->vval.v_number;
varnumber_T res = 0;
int div_zero = FALSE;
switch (iptr->isn_arg.op.op_type)
{
case EXPR_MULT: res = arg1 * arg2; break;
case EXPR_DIV: if (arg2 == 0)
div_zero = TRUE;
else
res = arg1 / arg2;
break;
case EXPR_REM: if (arg2 == 0)
div_zero = TRUE;
else
res = arg1 % arg2;
break;
case EXPR_SUB: res = arg1 - arg2; break;
case EXPR_ADD: res = arg1 + arg2; break;
case EXPR_EQUAL: res = arg1 == arg2; break;
case EXPR_NEQUAL: res = arg1 != arg2; break;
case EXPR_GREATER: res = arg1 > arg2; break;
case EXPR_GEQUAL: res = arg1 >= arg2; break;
case EXPR_SMALLER: res = arg1 < arg2; break;
case EXPR_SEQUAL: res = arg1 <= arg2; break;
default: break;
}
--ectx->ec_stack.ga_len;
if (iptr->isn_type == ISN_COMPARENR)
{
tv1->v_type = VAR_BOOL;
tv1->vval.v_number = res ? VVAL_TRUE : VVAL_FALSE;
}
else
tv1->vval.v_number = res;
if (div_zero)
{
SOURCING_LNUM = iptr->isn_lnum;
emsg(_(e_divide_by_zero));
goto on_error;
}
}
break;
// Computation with two float arguments
case ISN_OPFLOAT:
case ISN_COMPAREFLOAT:
#ifdef FEAT_FLOAT
{
typval_T *tv1 = STACK_TV_BOT(-2);
typval_T *tv2 = STACK_TV_BOT(-1);
float_T arg1 = tv1->vval.v_float;
float_T arg2 = tv2->vval.v_float;
float_T res = 0;
int cmp = FALSE;
switch (iptr->isn_arg.op.op_type)
{
case EXPR_MULT: res = arg1 * arg2; break;
case EXPR_DIV: res = arg1 / arg2; break;
case EXPR_SUB: res = arg1 - arg2; break;
case EXPR_ADD: res = arg1 + arg2; break;
case EXPR_EQUAL: cmp = arg1 == arg2; break;
case EXPR_NEQUAL: cmp = arg1 != arg2; break;
case EXPR_GREATER: cmp = arg1 > arg2; break;
case EXPR_GEQUAL: cmp = arg1 >= arg2; break;
case EXPR_SMALLER: cmp = arg1 < arg2; break;
case EXPR_SEQUAL: cmp = arg1 <= arg2; break;
default: cmp = 0; break;
}
--ectx->ec_stack.ga_len;
if (iptr->isn_type == ISN_COMPAREFLOAT)
{
tv1->v_type = VAR_BOOL;
tv1->vval.v_number = cmp ? VVAL_TRUE : VVAL_FALSE;
}
else
tv1->vval.v_float = res;
}
#endif
break;
case ISN_COMPARELIST:
case ISN_COMPAREDICT:
case ISN_COMPAREFUNC:
case ISN_COMPARESTRING:
case ISN_COMPAREBLOB:
{
typval_T *tv1 = STACK_TV_BOT(-2);
typval_T *tv2 = STACK_TV_BOT(-1);
exprtype_T exprtype = iptr->isn_arg.op.op_type;
int ic = iptr->isn_arg.op.op_ic;
int res = FALSE;
int status = OK;
SOURCING_LNUM = iptr->isn_lnum;
if (iptr->isn_type == ISN_COMPARELIST)
{
status = typval_compare_list(tv1, tv2,
exprtype, ic, &res);
}
else if (iptr->isn_type == ISN_COMPAREDICT)
{
status = typval_compare_dict(tv1, tv2,
exprtype, ic, &res);
}
else if (iptr->isn_type == ISN_COMPAREFUNC)
{
status = typval_compare_func(tv1, tv2,
exprtype, ic, &res);
}
else if (iptr->isn_type == ISN_COMPARESTRING)
{
status = typval_compare_string(tv1, tv2,
exprtype, ic, &res);
}
else
{
status = typval_compare_blob(tv1, tv2, exprtype, &res);
}
--ectx->ec_stack.ga_len;
clear_tv(tv1);
clear_tv(tv2);
tv1->v_type = VAR_BOOL;
tv1->vval.v_number = res ? VVAL_TRUE : VVAL_FALSE;
if (status == FAIL)
goto theend;
}
break;
case ISN_COMPAREANY:
{
typval_T *tv1 = STACK_TV_BOT(-2);
typval_T *tv2 = STACK_TV_BOT(-1);
exprtype_T exprtype = iptr->isn_arg.op.op_type;
int ic = iptr->isn_arg.op.op_ic;
int status;
SOURCING_LNUM = iptr->isn_lnum;
status = typval_compare(tv1, tv2, exprtype, ic);
clear_tv(tv2);
--ectx->ec_stack.ga_len;
if (status == FAIL)
goto theend;
}
break;
case ISN_ADDLIST:
case ISN_ADDBLOB:
{
typval_T *tv1 = STACK_TV_BOT(-2);
typval_T *tv2 = STACK_TV_BOT(-1);
// add two lists or blobs
if (iptr->isn_type == ISN_ADDLIST)
{
if (iptr->isn_arg.op.op_type == EXPR_APPEND
&& tv1->vval.v_list != NULL)
list_extend(tv1->vval.v_list, tv2->vval.v_list,
NULL);
else
eval_addlist(tv1, tv2);
}
else
eval_addblob(tv1, tv2);
clear_tv(tv2);
--ectx->ec_stack.ga_len;
}
break;
case ISN_LISTAPPEND:
{
typval_T *tv1 = STACK_TV_BOT(-2);
typval_T *tv2 = STACK_TV_BOT(-1);
list_T *l = tv1->vval.v_list;
// add an item to a list
SOURCING_LNUM = iptr->isn_lnum;
if (l == NULL)
{
emsg(_(e_cannot_add_to_null_list));
goto on_error;
}
if (value_check_lock(l->lv_lock, NULL, FALSE))
goto on_error;
if (list_append_tv(l, tv2) == FAIL)
goto theend;
clear_tv(tv2);
--ectx->ec_stack.ga_len;
}
break;
case ISN_BLOBAPPEND:
{
typval_T *tv1 = STACK_TV_BOT(-2);
typval_T *tv2 = STACK_TV_BOT(-1);
blob_T *b = tv1->vval.v_blob;
int error = FALSE;
varnumber_T n;
// add a number to a blob
if (b == NULL)
{
SOURCING_LNUM = iptr->isn_lnum;
emsg(_(e_cannot_add_to_null_blob));
goto on_error;
}
n = tv_get_number_chk(tv2, &error);
if (error)
goto on_error;
ga_append(&b->bv_ga, (int)n);
--ectx->ec_stack.ga_len;
}
break;
// Computation with two arguments of unknown type
case ISN_OPANY:
{
typval_T *tv1 = STACK_TV_BOT(-2);
typval_T *tv2 = STACK_TV_BOT(-1);
varnumber_T n1, n2;
#ifdef FEAT_FLOAT
float_T f1 = 0, f2 = 0;
#endif
int error = FALSE;
if (iptr->isn_arg.op.op_type == EXPR_ADD)
{
if (tv1->v_type == VAR_LIST && tv2->v_type == VAR_LIST)
{
eval_addlist(tv1, tv2);
clear_tv(tv2);
--ectx->ec_stack.ga_len;
break;
}
else if (tv1->v_type == VAR_BLOB
&& tv2->v_type == VAR_BLOB)
{
eval_addblob(tv1, tv2);
clear_tv(tv2);
--ectx->ec_stack.ga_len;
break;
}
}
#ifdef FEAT_FLOAT
if (tv1->v_type == VAR_FLOAT)
{
f1 = tv1->vval.v_float;
n1 = 0;
}
else
#endif
{
SOURCING_LNUM = iptr->isn_lnum;
n1 = tv_get_number_chk(tv1, &error);
if (error)
goto on_error;
#ifdef FEAT_FLOAT
if (tv2->v_type == VAR_FLOAT)
f1 = n1;
#endif
}
#ifdef FEAT_FLOAT
if (tv2->v_type == VAR_FLOAT)
{
f2 = tv2->vval.v_float;
n2 = 0;
}
else
#endif
{
n2 = tv_get_number_chk(tv2, &error);
if (error)
goto on_error;
#ifdef FEAT_FLOAT
if (tv1->v_type == VAR_FLOAT)
f2 = n2;
#endif
}
#ifdef FEAT_FLOAT
// if there is a float on either side the result is a float
if (tv1->v_type == VAR_FLOAT || tv2->v_type == VAR_FLOAT)
{
switch (iptr->isn_arg.op.op_type)
{
case EXPR_MULT: f1 = f1 * f2; break;
case EXPR_DIV: f1 = f1 / f2; break;
case EXPR_SUB: f1 = f1 - f2; break;
case EXPR_ADD: f1 = f1 + f2; break;
default: SOURCING_LNUM = iptr->isn_lnum;
emsg(_(e_cannot_use_percent_with_float));
goto on_error;
}
clear_tv(tv1);
clear_tv(tv2);
tv1->v_type = VAR_FLOAT;
tv1->vval.v_float = f1;
--ectx->ec_stack.ga_len;
}
else
#endif
{
int failed = FALSE;
switch (iptr->isn_arg.op.op_type)
{
case EXPR_MULT: n1 = n1 * n2; break;
case EXPR_DIV: n1 = num_divide(n1, n2, &failed);
if (failed)
goto on_error;
break;
case EXPR_SUB: n1 = n1 - n2; break;
case EXPR_ADD: n1 = n1 + n2; break;
default: n1 = num_modulus(n1, n2, &failed);
if (failed)
goto on_error;
break;
}
clear_tv(tv1);
clear_tv(tv2);
tv1->v_type = VAR_NUMBER;
tv1->vval.v_number = n1;
--ectx->ec_stack.ga_len;
}
}
break;
case ISN_CONCAT:
{
char_u *str1 = STACK_TV_BOT(-2)->vval.v_string;
char_u *str2 = STACK_TV_BOT(-1)->vval.v_string;
char_u *res;
res = concat_str(str1, str2);
clear_tv(STACK_TV_BOT(-2));
clear_tv(STACK_TV_BOT(-1));
--ectx->ec_stack.ga_len;
STACK_TV_BOT(-1)->vval.v_string = res;
}
break;
case ISN_STRINDEX:
case ISN_STRSLICE:
{
int is_slice = iptr->isn_type == ISN_STRSLICE;
varnumber_T n1 = 0, n2;
char_u *res;
// string index: string is at stack-2, index at stack-1
// string slice: string is at stack-3, first index at
// stack-2, second index at stack-1
if (is_slice)
{
tv = STACK_TV_BOT(-2);
n1 = tv->vval.v_number;
}
tv = STACK_TV_BOT(-1);
n2 = tv->vval.v_number;
ectx->ec_stack.ga_len -= is_slice ? 2 : 1;
tv = STACK_TV_BOT(-1);
if (is_slice)
// Slice: Select the characters from the string
res = string_slice(tv->vval.v_string, n1, n2, FALSE);
else
// Index: The resulting variable is a string of a
// single character (including composing characters).
// If the index is too big or negative the result is
// empty.
res = char_from_string(tv->vval.v_string, n2);
vim_free(tv->vval.v_string);
tv->vval.v_string = res;
}
break;
case ISN_LISTINDEX:
case ISN_LISTSLICE:
case ISN_BLOBINDEX:
case ISN_BLOBSLICE:
{
int is_slice = iptr->isn_type == ISN_LISTSLICE
|| iptr->isn_type == ISN_BLOBSLICE;
int is_blob = iptr->isn_type == ISN_BLOBINDEX
|| iptr->isn_type == ISN_BLOBSLICE;
varnumber_T n1, n2;
typval_T *val_tv;
// list index: list is at stack-2, index at stack-1
// list slice: list is at stack-3, indexes at stack-2 and
// stack-1
// Same for blob.
val_tv = is_slice ? STACK_TV_BOT(-3) : STACK_TV_BOT(-2);
tv = STACK_TV_BOT(-1);
n1 = n2 = tv->vval.v_number;
clear_tv(tv);
if (is_slice)
{
tv = STACK_TV_BOT(-2);
n1 = tv->vval.v_number;
clear_tv(tv);
}
ectx->ec_stack.ga_len -= is_slice ? 2 : 1;
tv = STACK_TV_BOT(-1);
SOURCING_LNUM = iptr->isn_lnum;
if (is_blob)
{
if (blob_slice_or_index(val_tv->vval.v_blob, is_slice,
n1, n2, FALSE, tv) == FAIL)
goto on_error;
}
else
{
if (list_slice_or_index(val_tv->vval.v_list, is_slice,
n1, n2, FALSE, tv, TRUE) == FAIL)
goto on_error;
}
}
break;
case ISN_ANYINDEX:
case ISN_ANYSLICE:
{
int is_slice = iptr->isn_type == ISN_ANYSLICE;
typval_T *var1, *var2;
int res;
// index: composite is at stack-2, index at stack-1
// slice: composite is at stack-3, indexes at stack-2 and
// stack-1
tv = is_slice ? STACK_TV_BOT(-3) : STACK_TV_BOT(-2);
SOURCING_LNUM = iptr->isn_lnum;
if (check_can_index(tv, TRUE, TRUE) == FAIL)
goto on_error;
var1 = is_slice ? STACK_TV_BOT(-2) : STACK_TV_BOT(-1);
var2 = is_slice ? STACK_TV_BOT(-1) : NULL;
res = eval_index_inner(tv, is_slice, var1, var2,
FALSE, NULL, -1, TRUE);
clear_tv(var1);
if (is_slice)
clear_tv(var2);
ectx->ec_stack.ga_len -= is_slice ? 2 : 1;
if (res == FAIL)
goto on_error;
}
break;
case ISN_SLICE:
{
list_T *list;
int count = iptr->isn_arg.number;
// type will have been checked to be a list
tv = STACK_TV_BOT(-1);
list = tv->vval.v_list;
// no error for short list, expect it to be checked earlier
if (list != NULL && list->lv_len >= count)
{
list_T *newlist = list_slice(list,
count, list->lv_len - 1);
if (newlist != NULL)
{
list_unref(list);
tv->vval.v_list = newlist;
++newlist->lv_refcount;
}
}
}
break;
case ISN_GETITEM:
{
listitem_T *li;
getitem_T *gi = &iptr->isn_arg.getitem;
// Get list item: list is at stack-1, push item.
// List type and length is checked for when compiling.
tv = STACK_TV_BOT(-1 - gi->gi_with_op);
li = list_find(tv->vval.v_list, gi->gi_index);
if (GA_GROW_FAILS(&ectx->ec_stack, 1))
goto theend;
++ectx->ec_stack.ga_len;
copy_tv(&li->li_tv, STACK_TV_BOT(-1));
// Useful when used in unpack assignment. Reset at
// ISN_DROP.
ectx->ec_where.wt_index = gi->gi_index + 1;
ectx->ec_where.wt_variable = TRUE;
}
break;
case ISN_MEMBER:
{
dict_T *dict;
char_u *key;
dictitem_T *di;
// dict member: dict is at stack-2, key at stack-1
tv = STACK_TV_BOT(-2);
// no need to check for VAR_DICT, CHECKTYPE will check.
dict = tv->vval.v_dict;
tv = STACK_TV_BOT(-1);
// no need to check for VAR_STRING, 2STRING will check.
key = tv->vval.v_string;
if (key == NULL)
key = (char_u *)"";
if ((di = dict_find(dict, key, -1)) == NULL)
{
SOURCING_LNUM = iptr->isn_lnum;
semsg(_(e_key_not_present_in_dictionary), key);
// If :silent! is used we will continue, make sure the
// stack contents makes sense and the dict stack is
// updated.
clear_tv(tv);
--ectx->ec_stack.ga_len;
tv = STACK_TV_BOT(-1);
(void) dict_stack_save(tv);
tv->v_type = VAR_NUMBER;
tv->vval.v_number = 0;
goto on_fatal_error;
}
clear_tv(tv);
--ectx->ec_stack.ga_len;
// Put the dict used on the dict stack, it might be used by
// a dict function later.
tv = STACK_TV_BOT(-1);
if (dict_stack_save(tv) == FAIL)
goto on_fatal_error;
copy_tv(&di->di_tv, tv);
}
break;
// dict member with string key
case ISN_STRINGMEMBER:
{
dict_T *dict;
dictitem_T *di;
tv = STACK_TV_BOT(-1);
if (tv->v_type != VAR_DICT || tv->vval.v_dict == NULL)
{
SOURCING_LNUM = iptr->isn_lnum;
emsg(_(e_dictionary_required));
goto on_error;
}
dict = tv->vval.v_dict;
if ((di = dict_find(dict, iptr->isn_arg.string, -1))
== NULL)
{
SOURCING_LNUM = iptr->isn_lnum;
semsg(_(e_key_not_present_in_dictionary), iptr->isn_arg.string);
goto on_error;
}
// Put the dict used on the dict stack, it might be used by
// a dict function later.
if (dict_stack_save(tv) == FAIL)
goto on_fatal_error;
copy_tv(&di->di_tv, tv);
}
break;
case ISN_CLEARDICT:
dict_stack_drop();
break;
case ISN_USEDICT:
{
typval_T *dict_tv = dict_stack_get_tv();
// Turn "dict.Func" into a partial for "Func" bound to
// "dict". Don't do this when "Func" is already a partial
// that was bound explicitly (pt_auto is FALSE).
tv = STACK_TV_BOT(-1);
if (dict_tv != NULL
&& dict_tv->v_type == VAR_DICT
&& dict_tv->vval.v_dict != NULL
&& (tv->v_type == VAR_FUNC
|| (tv->v_type == VAR_PARTIAL
&& (tv->vval.v_partial->pt_auto
|| tv->vval.v_partial->pt_dict == NULL))))
dict_tv->vval.v_dict =
make_partial(dict_tv->vval.v_dict, tv);
dict_stack_drop();
}
break;
case ISN_NEGATENR:
tv = STACK_TV_BOT(-1);
if (tv->v_type != VAR_NUMBER
#ifdef FEAT_FLOAT
&& tv->v_type != VAR_FLOAT
#endif
)
{
SOURCING_LNUM = iptr->isn_lnum;
emsg(_(e_number_expected));
goto on_error;
}
#ifdef FEAT_FLOAT
if (tv->v_type == VAR_FLOAT)
tv->vval.v_float = -tv->vval.v_float;
else
#endif
tv->vval.v_number = -tv->vval.v_number;
break;
case ISN_CHECKNR:
{
int error = FALSE;
tv = STACK_TV_BOT(-1);
SOURCING_LNUM = iptr->isn_lnum;
if (check_not_string(tv) == FAIL)
goto on_error;
(void)tv_get_number_chk(tv, &error);
if (error)
goto on_error;
}
break;
case ISN_CHECKTYPE:
{
checktype_T *ct = &iptr->isn_arg.type;
tv = STACK_TV_BOT((int)ct->ct_off);
SOURCING_LNUM = iptr->isn_lnum;
if (!ectx->ec_where.wt_variable)
ectx->ec_where.wt_index = ct->ct_arg_idx;
if (check_typval_type(ct->ct_type, tv, ectx->ec_where)
== FAIL)
goto on_error;
if (!ectx->ec_where.wt_variable)
ectx->ec_where.wt_index = 0;
// number 0 is FALSE, number 1 is TRUE
if (tv->v_type == VAR_NUMBER
&& ct->ct_type->tt_type == VAR_BOOL
&& (tv->vval.v_number == 0
|| tv->vval.v_number == 1))
{
tv->v_type = VAR_BOOL;
tv->vval.v_number = tv->vval.v_number
? VVAL_TRUE : VVAL_FALSE;
}
}
break;
case ISN_CHECKLEN:
{
int min_len = iptr->isn_arg.checklen.cl_min_len;
list_T *list = NULL;
tv = STACK_TV_BOT(-1);
if (tv->v_type == VAR_LIST)
list = tv->vval.v_list;
if (list == NULL || list->lv_len < min_len
|| (list->lv_len > min_len
&& !iptr->isn_arg.checklen.cl_more_OK))
{
SOURCING_LNUM = iptr->isn_lnum;
semsg(_(e_expected_nr_items_but_got_nr),
min_len, list == NULL ? 0 : list->lv_len);
goto on_error;
}
}
break;
case ISN_SETTYPE:
{
checktype_T *ct = &iptr->isn_arg.type;
tv = STACK_TV_BOT(-1);
if (tv->v_type == VAR_DICT && tv->vval.v_dict != NULL)
{
free_type(tv->vval.v_dict->dv_type);
tv->vval.v_dict->dv_type = alloc_type(ct->ct_type);
}
else if (tv->v_type == VAR_LIST && tv->vval.v_list != NULL)
{
free_type(tv->vval.v_list->lv_type);
tv->vval.v_list->lv_type = alloc_type(ct->ct_type);
}
}
break;
case ISN_2BOOL:
case ISN_COND2BOOL:
{
int n;
int error = FALSE;
if (iptr->isn_type == ISN_2BOOL)
{
tv = STACK_TV_BOT(iptr->isn_arg.tobool.offset);
n = tv2bool(tv);
if (iptr->isn_arg.tobool.invert)
n = !n;
}
else
{
tv = STACK_TV_BOT(-1);
SOURCING_LNUM = iptr->isn_lnum;
n = tv_get_bool_chk(tv, &error);
if (error)
goto on_error;
}
clear_tv(tv);
tv->v_type = VAR_BOOL;
tv->vval.v_number = n ? VVAL_TRUE : VVAL_FALSE;
}
break;
case ISN_2STRING:
case ISN_2STRING_ANY:
SOURCING_LNUM = iptr->isn_lnum;
if (do_2string(STACK_TV_BOT(iptr->isn_arg.tostring.offset),
iptr->isn_type == ISN_2STRING_ANY,
iptr->isn_arg.tostring.tolerant) == FAIL)
goto on_error;
break;
case ISN_RANGE:
{
exarg_T ea;
char *errormsg;
ea.line2 = 0;
ea.addr_count = 0;
ea.addr_type = ADDR_LINES;
ea.cmd = iptr->isn_arg.string;
ea.skip = FALSE;
if (parse_cmd_address(&ea, &errormsg, FALSE) == FAIL)
goto on_error;
if (GA_GROW_FAILS(&ectx->ec_stack, 1))
goto theend;
++ectx->ec_stack.ga_len;
tv = STACK_TV_BOT(-1);
tv->v_type = VAR_NUMBER;
tv->v_lock = 0;
if (ea.addr_count == 0)
tv->vval.v_number = curwin->w_cursor.lnum;
else
tv->vval.v_number = ea.line2;
}
break;
case ISN_PUT:
{
int regname = iptr->isn_arg.put.put_regname;
linenr_T lnum = iptr->isn_arg.put.put_lnum;
char_u *expr = NULL;
int dir = FORWARD;
if (lnum < -2)
{
// line number was put on the stack by ISN_RANGE
tv = STACK_TV_BOT(-1);
curwin->w_cursor.lnum = tv->vval.v_number;
if (lnum == LNUM_VARIABLE_RANGE_ABOVE)
dir = BACKWARD;
--ectx->ec_stack.ga_len;
}
else if (lnum == -2)
// :put! above cursor
dir = BACKWARD;
else if (lnum >= 0)
curwin->w_cursor.lnum = iptr->isn_arg.put.put_lnum;
if (regname == '=')
{
tv = STACK_TV_BOT(-1);
if (tv->v_type == VAR_STRING)
expr = tv->vval.v_string;
else
{
expr = typval2string(tv, TRUE); // allocates value
clear_tv(tv);
}
--ectx->ec_stack.ga_len;
}
check_cursor();
do_put(regname, expr, dir, 1L, PUT_LINE|PUT_CURSLINE);
vim_free(expr);
}
break;
case ISN_CMDMOD:
ectx->ec_funclocal.floc_save_cmdmod = cmdmod;
ectx->ec_funclocal.floc_restore_cmdmod = TRUE;
ectx->ec_funclocal.floc_restore_cmdmod_stacklen =
ectx->ec_stack.ga_len;
cmdmod = *iptr->isn_arg.cmdmod.cf_cmdmod;
apply_cmdmod(&cmdmod);
break;
case ISN_CMDMOD_REV:
// filter regprog is owned by the instruction, don't free it
cmdmod.cmod_filter_regmatch.regprog = NULL;
undo_cmdmod(&cmdmod);
cmdmod = ectx->ec_funclocal.floc_save_cmdmod;
ectx->ec_funclocal.floc_restore_cmdmod = FALSE;
break;
case ISN_UNPACK:
{
int count = iptr->isn_arg.unpack.unp_count;
int semicolon = iptr->isn_arg.unpack.unp_semicolon;
list_T *l;
listitem_T *li;
int i;
// Check there is a valid list to unpack.
tv = STACK_TV_BOT(-1);
if (tv->v_type != VAR_LIST)
{
SOURCING_LNUM = iptr->isn_lnum;
emsg(_(e_for_argument_must_be_sequence_of_lists));
goto on_error;
}
l = tv->vval.v_list;
if (l == NULL
|| l->lv_len < (semicolon ? count - 1 : count))
{
SOURCING_LNUM = iptr->isn_lnum;
emsg(_(e_list_value_does_not_have_enough_items));
goto on_error;
}
else if (!semicolon && l->lv_len > count)
{
SOURCING_LNUM = iptr->isn_lnum;
emsg(_(e_list_value_has_more_items_than_targets));
goto on_error;
}
CHECK_LIST_MATERIALIZE(l);
if (GA_GROW_FAILS(&ectx->ec_stack, count - 1))
goto theend;
ectx->ec_stack.ga_len += count - 1;
// Variable after semicolon gets a list with the remaining
// items.
if (semicolon)
{
list_T *rem_list =
list_alloc_with_items(l->lv_len - count + 1);
if (rem_list == NULL)
goto theend;
tv = STACK_TV_BOT(-count);
tv->vval.v_list = rem_list;
++rem_list->lv_refcount;
tv->v_lock = 0;
li = l->lv_first;
for (i = 0; i < count - 1; ++i)
li = li->li_next;
for (i = 0; li != NULL; ++i)
{
list_set_item(rem_list, i, &li->li_tv);
li = li->li_next;
}
--count;
}
// Produce the values in reverse order, first item last.
li = l->lv_first;
for (i = 0; i < count; ++i)
{
tv = STACK_TV_BOT(-i - 1);
copy_tv(&li->li_tv, tv);
li = li->li_next;
}
list_unref(l);
}
break;
case ISN_PROF_START:
case ISN_PROF_END:
{
#ifdef FEAT_PROFILE
funccall_T cookie;
ufunc_T *cur_ufunc =
(((dfunc_T *)def_functions.ga_data)
+ ectx->ec_dfunc_idx)->df_ufunc;
cookie.func = cur_ufunc;
if (iptr->isn_type == ISN_PROF_START)
{
func_line_start(&cookie, iptr->isn_lnum);
// if we get here the instruction is executed
func_line_exec(&cookie);
}
else
func_line_end(&cookie);
#endif
}
break;
case ISN_DEBUG:
handle_debug(iptr, ectx);
break;
case ISN_SHUFFLE:
{
typval_T tmp_tv;
int item = iptr->isn_arg.shuffle.shfl_item;
int up = iptr->isn_arg.shuffle.shfl_up;
tmp_tv = *STACK_TV_BOT(-item);
for ( ; up > 0 && item > 1; --up)
{
*STACK_TV_BOT(-item) = *STACK_TV_BOT(-item + 1);
--item;
}
*STACK_TV_BOT(-item) = tmp_tv;
}
break;
case ISN_DROP:
--ectx->ec_stack.ga_len;
clear_tv(STACK_TV_BOT(0));
ectx->ec_where.wt_index = 0;
ectx->ec_where.wt_variable = FALSE;
break;
}
continue;
func_return:
// Restore previous function. If the frame pointer is where we started
// then there is none and we are done.
if (ectx->ec_frame_idx == ectx->ec_initial_frame_idx)
goto done;
if (func_return(ectx) == FAIL)
// only fails when out of memory
goto theend;
continue;
on_error:
// Jump here for an error that does not require aborting execution.
// If "emsg_silent" is set then ignore the error, unless it was set
// when calling the function.
if (did_emsg_cumul + did_emsg == ectx->ec_did_emsg_before
&& emsg_silent && did_emsg_def == 0)
{
// If a sequence of instructions causes an error while ":silent!"
// was used, restore the stack length and jump ahead to restoring
// the cmdmod.
if (ectx->ec_funclocal.floc_restore_cmdmod)
{
while (ectx->ec_stack.ga_len
> ectx->ec_funclocal.floc_restore_cmdmod_stacklen)
{
--ectx->ec_stack.ga_len;
clear_tv(STACK_TV_BOT(0));
}
while (ectx->ec_instr[ectx->ec_iidx].isn_type != ISN_CMDMOD_REV)
++ectx->ec_iidx;
}
continue;
}
on_fatal_error:
// Jump here for an error that messes up the stack.
// If we are not inside a try-catch started here, abort execution.
if (trylevel <= ectx->ec_trylevel_at_start)
goto theend;
}
done:
ret = OK;
theend:
dict_stack_clear(dict_stack_len_at_start);
ectx->ec_trylevel_at_start = save_trylevel_at_start;
return ret;
} | 1 | CVE-2022-0156 | 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,265 |
php-src | ecb7f58a069be0dec4a6131b6351a761f808f22e?w=1 | static int spl_array_has_dimension_ex(int check_inherited, zval *object, zval *offset, int check_empty TSRMLS_DC) /* {{{ */
{
spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC);
long index;
zval *rv, *value = NULL, **tmp;
if (check_inherited && intern->fptr_offset_has) {
zval *offset_tmp = offset;
SEPARATE_ARG_IF_REF(offset_tmp);
zend_call_method_with_1_params(&object, Z_OBJCE_P(object), &intern->fptr_offset_has, "offsetExists", &rv, offset_tmp);
zval_ptr_dtor(&offset_tmp);
if (rv && zend_is_true(rv)) {
zval_ptr_dtor(&rv);
if (check_empty != 1) {
return 1;
} else if (intern->fptr_offset_get) {
value = spl_array_read_dimension_ex(1, object, offset, BP_VAR_R TSRMLS_CC);
}
} else {
if (rv) {
zval_ptr_dtor(&rv);
}
return 0;
}
}
if (!value) {
HashTable *ht = spl_array_get_hash_table(intern, 0 TSRMLS_CC);
switch(Z_TYPE_P(offset)) {
case IS_STRING:
if (zend_symtable_find(ht, Z_STRVAL_P(offset), Z_STRLEN_P(offset)+1, (void **) &tmp) != FAILURE) {
if (check_empty == 2) {
return 1;
}
} else {
return 0;
}
break;
case IS_DOUBLE:
case IS_RESOURCE:
case IS_BOOL:
case IS_LONG:
if (offset->type == IS_DOUBLE) {
index = (long)Z_DVAL_P(offset);
} else {
index = Z_LVAL_P(offset);
}
if (zend_hash_index_find(ht, index, (void **)&tmp) != FAILURE) {
if (check_empty == 2) {
return 1;
}
} else {
return 0;
}
break;
default:
zend_error(E_WARNING, "Illegal offset type");
return 0;
}
if (check_empty && check_inherited && intern->fptr_offset_get) {
value = spl_array_read_dimension_ex(1, object, offset, BP_VAR_R TSRMLS_CC);
} else {
value = *tmp;
}
}
return check_empty ? zend_is_true(value) : Z_TYPE_P(value) != IS_NULL;
} /* }}} */
| 1 | CVE-2016-7417 | 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. | 6,522 |
linux | 09ca8e1173bcb12e2a449698c9ae3b86a8a10195 | void kvm_vcpu_uninit(struct kvm_vcpu *vcpu)
{
put_pid(vcpu->pid);
kvm_arch_vcpu_uninit(vcpu);
free_page((unsigned long)vcpu->run);
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 10,647 |
nginx | c1be55f97211d38b69ac0c2027e6812ab8b1b94e | ngx_http_send_special_response(ngx_http_request_t *r,
ngx_http_core_loc_conf_t *clcf, ngx_uint_t err)
{
u_char *tail;
size_t len;
ngx_int_t rc;
ngx_buf_t *b;
ngx_uint_t msie_padding;
ngx_chain_t out[3];
if (clcf->server_tokens == NGX_HTTP_SERVER_TOKENS_ON) {
len = sizeof(ngx_http_error_full_tail) - 1;
tail = ngx_http_error_full_tail;
} else if (clcf->server_tokens == NGX_HTTP_SERVER_TOKENS_BUILD) {
len = sizeof(ngx_http_error_build_tail) - 1;
tail = ngx_http_error_build_tail;
} else {
len = sizeof(ngx_http_error_tail) - 1;
tail = ngx_http_error_tail;
}
msie_padding = 0;
if (ngx_http_error_pages[err].len) {
r->headers_out.content_length_n = ngx_http_error_pages[err].len + len;
if (clcf->msie_padding
&& (r->headers_in.msie || r->headers_in.chrome)
&& r->http_version >= NGX_HTTP_VERSION_10
&& err >= NGX_HTTP_OFF_4XX)
{
r->headers_out.content_length_n +=
sizeof(ngx_http_msie_padding) - 1;
msie_padding = 1;
}
r->headers_out.content_type_len = sizeof("text/html") - 1;
ngx_str_set(&r->headers_out.content_type, "text/html");
r->headers_out.content_type_lowcase = NULL;
} else {
r->headers_out.content_length_n = 0;
}
if (r->headers_out.content_length) {
r->headers_out.content_length->hash = 0;
r->headers_out.content_length = NULL;
}
ngx_http_clear_accept_ranges(r);
ngx_http_clear_last_modified(r);
ngx_http_clear_etag(r);
rc = ngx_http_send_header(r);
if (rc == NGX_ERROR || r->header_only) {
return rc;
}
if (ngx_http_error_pages[err].len == 0) {
return ngx_http_send_special(r, NGX_HTTP_LAST);
}
b = ngx_calloc_buf(r->pool);
if (b == NULL) {
return NGX_ERROR;
}
b->memory = 1;
b->pos = ngx_http_error_pages[err].data;
b->last = ngx_http_error_pages[err].data + ngx_http_error_pages[err].len;
out[0].buf = b;
out[0].next = &out[1];
b = ngx_calloc_buf(r->pool);
if (b == NULL) {
return NGX_ERROR;
}
b->memory = 1;
b->pos = tail;
b->last = tail + len;
out[1].buf = b;
out[1].next = NULL;
if (msie_padding) {
b = ngx_calloc_buf(r->pool);
if (b == NULL) {
return NGX_ERROR;
}
b->memory = 1;
b->pos = ngx_http_msie_padding;
b->last = ngx_http_msie_padding + sizeof(ngx_http_msie_padding) - 1;
out[1].next = &out[2];
out[2].buf = b;
out[2].next = NULL;
}
if (r == r->main) {
b->last_buf = 1;
}
b->last_in_chain = 1;
return ngx_http_output_filter(r, &out[0]);
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 14,852 |
ImageMagick6 | 4a8a6274f5e690f9106a998de9b8a8f3929402bc | static int formatIPTCfromBuffer(Image *ofile, char *s, ssize_t len)
{
char
temp[MaxTextExtent];
unsigned int
foundiptc,
tagsfound;
unsigned char
recnum,
dataset;
unsigned char
*readable,
*str;
ssize_t
tagindx,
taglen;
int
i,
tagcount = (int) (sizeof(tags) / sizeof(tag_spec));
int
c;
foundiptc = 0; /* found the IPTC-Header */
tagsfound = 0; /* number of tags found */
while (len > 0)
{
c = *s++; len--;
if (c == 0x1c)
foundiptc = 1;
else
{
if (foundiptc)
return -1;
else
continue;
}
/*
We found the 0x1c tag and now grab the dataset and record number tags.
*/
c = *s++; len--;
if (len < 0) return -1;
dataset = (unsigned char) c;
c = *s++; len--;
if (len < 0) return -1;
recnum = (unsigned char) c;
/* try to match this record to one of the ones in our named table */
for (i=0; i< tagcount; i++)
if (tags[i].id == (short) recnum)
break;
if (i < tagcount)
readable=(unsigned char *) tags[i].name;
else
readable=(unsigned char *) "";
/*
We decode the length of the block that follows - ssize_t or short fmt.
*/
c=(*s++);
len--;
if (len < 0)
return(-1);
if (c & (unsigned char) 0x80)
return(0);
else
{
s--;
len++;
taglen=readWordFromBuffer(&s, &len);
}
if (taglen < 0)
return(-1);
if (taglen > 65535)
return(-1);
/* make a buffer to hold the tag datand snag it from the input stream */
str=(unsigned char *) AcquireQuantumMemory((size_t) (taglen+MaxTextExtent),
sizeof(*str));
if (str == (unsigned char *) NULL)
{
printf("MemoryAllocationFailed");
return 0;
}
for (tagindx=0; tagindx<taglen; tagindx++)
{
c = *s++; len--;
if (len < 0)
return(-1);
str[tagindx]=(unsigned char) c;
}
str[taglen]=0;
/* now finish up by formatting this binary data into ASCII equivalent */
if (strlen((char *)readable) > 0)
(void) FormatLocaleString(temp,MaxTextExtent,"%d#%d#%s=",
(unsigned int) dataset,(unsigned int) recnum, readable);
else
(void) FormatLocaleString(temp,MaxTextExtent,"%d#%d=",
(unsigned int) dataset,(unsigned int) recnum);
(void) WriteBlobString(ofile,temp);
formatString( ofile, (char *)str, taglen );
str=(unsigned char *) RelinquishMagickMemory(str);
tagsfound++;
}
return ((int) tagsfound);
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 22,773 |
linux | 6aeb75e6adfaed16e58780309613a578fe1ee90b | static void change_port_settings(struct tty_struct *tty,
struct edgeport_port *edge_port, struct ktermios *old_termios)
{
struct device *dev = &edge_port->port->dev;
struct ump_uart_config *config;
int baud;
unsigned cflag;
int status;
int port_number = edge_port->port->port_number;
config = kmalloc (sizeof (*config), GFP_KERNEL);
if (!config) {
tty->termios = *old_termios;
return;
}
cflag = tty->termios.c_cflag;
config->wFlags = 0;
/* These flags must be set */
config->wFlags |= UMP_MASK_UART_FLAGS_RECEIVE_MS_INT;
config->wFlags |= UMP_MASK_UART_FLAGS_AUTO_START_ON_ERR;
config->bUartMode = (__u8)(edge_port->bUartMode);
switch (cflag & CSIZE) {
case CS5:
config->bDataBits = UMP_UART_CHAR5BITS;
dev_dbg(dev, "%s - data bits = 5\n", __func__);
break;
case CS6:
config->bDataBits = UMP_UART_CHAR6BITS;
dev_dbg(dev, "%s - data bits = 6\n", __func__);
break;
case CS7:
config->bDataBits = UMP_UART_CHAR7BITS;
dev_dbg(dev, "%s - data bits = 7\n", __func__);
break;
default:
case CS8:
config->bDataBits = UMP_UART_CHAR8BITS;
dev_dbg(dev, "%s - data bits = 8\n", __func__);
break;
}
if (cflag & PARENB) {
if (cflag & PARODD) {
config->wFlags |= UMP_MASK_UART_FLAGS_PARITY;
config->bParity = UMP_UART_ODDPARITY;
dev_dbg(dev, "%s - parity = odd\n", __func__);
} else {
config->wFlags |= UMP_MASK_UART_FLAGS_PARITY;
config->bParity = UMP_UART_EVENPARITY;
dev_dbg(dev, "%s - parity = even\n", __func__);
}
} else {
config->bParity = UMP_UART_NOPARITY;
dev_dbg(dev, "%s - parity = none\n", __func__);
}
if (cflag & CSTOPB) {
config->bStopBits = UMP_UART_STOPBIT2;
dev_dbg(dev, "%s - stop bits = 2\n", __func__);
} else {
config->bStopBits = UMP_UART_STOPBIT1;
dev_dbg(dev, "%s - stop bits = 1\n", __func__);
}
/* figure out the flow control settings */
if (cflag & CRTSCTS) {
config->wFlags |= UMP_MASK_UART_FLAGS_OUT_X_CTS_FLOW;
config->wFlags |= UMP_MASK_UART_FLAGS_RTS_FLOW;
dev_dbg(dev, "%s - RTS/CTS is enabled\n", __func__);
} else {
dev_dbg(dev, "%s - RTS/CTS is disabled\n", __func__);
restart_read(edge_port);
}
/*
* if we are implementing XON/XOFF, set the start and stop
* character in the device
*/
config->cXon = START_CHAR(tty);
config->cXoff = STOP_CHAR(tty);
/* if we are implementing INBOUND XON/XOFF */
if (I_IXOFF(tty)) {
config->wFlags |= UMP_MASK_UART_FLAGS_IN_X;
dev_dbg(dev, "%s - INBOUND XON/XOFF is enabled, XON = %2x, XOFF = %2x\n",
__func__, config->cXon, config->cXoff);
} else
dev_dbg(dev, "%s - INBOUND XON/XOFF is disabled\n", __func__);
/* if we are implementing OUTBOUND XON/XOFF */
if (I_IXON(tty)) {
config->wFlags |= UMP_MASK_UART_FLAGS_OUT_X;
dev_dbg(dev, "%s - OUTBOUND XON/XOFF is enabled, XON = %2x, XOFF = %2x\n",
__func__, config->cXon, config->cXoff);
} else
dev_dbg(dev, "%s - OUTBOUND XON/XOFF is disabled\n", __func__);
tty->termios.c_cflag &= ~CMSPAR;
/* Round the baud rate */
baud = tty_get_baud_rate(tty);
if (!baud) {
/* pick a default, any default... */
baud = 9600;
} else {
/* Avoid a zero divisor. */
baud = min(baud, 461550);
tty_encode_baud_rate(tty, baud, baud);
}
edge_port->baud_rate = baud;
config->wBaudRate = (__u16)((461550L + baud/2) / baud);
/* FIXME: Recompute actual baud from divisor here */
dev_dbg(dev, "%s - baud rate = %d, wBaudRate = %d\n", __func__, baud, config->wBaudRate);
dev_dbg(dev, "wBaudRate: %d\n", (int)(461550L / config->wBaudRate));
dev_dbg(dev, "wFlags: 0x%x\n", config->wFlags);
dev_dbg(dev, "bDataBits: %d\n", config->bDataBits);
dev_dbg(dev, "bParity: %d\n", config->bParity);
dev_dbg(dev, "bStopBits: %d\n", config->bStopBits);
dev_dbg(dev, "cXon: %d\n", config->cXon);
dev_dbg(dev, "cXoff: %d\n", config->cXoff);
dev_dbg(dev, "bUartMode: %d\n", config->bUartMode);
/* move the word values into big endian mode */
cpu_to_be16s(&config->wFlags);
cpu_to_be16s(&config->wBaudRate);
status = send_cmd(edge_port->port->serial->dev, UMPC_SET_CONFIG,
(__u8)(UMPM_UART1_PORT + port_number),
0, (__u8 *)config, sizeof(*config));
if (status)
dev_dbg(dev, "%s - error %d when trying to write config to device\n",
__func__, status);
kfree(config);
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 17,292 |
linux | 95389b08d93d5c06ec63ab49bd732b0069b7c35e | int assoc_array_gc(struct assoc_array *array,
const struct assoc_array_ops *ops,
bool (*iterator)(void *object, void *iterator_data),
void *iterator_data)
{
struct assoc_array_shortcut *shortcut, *new_s;
struct assoc_array_node *node, *new_n;
struct assoc_array_edit *edit;
struct assoc_array_ptr *cursor, *ptr;
struct assoc_array_ptr *new_root, *new_parent, **new_ptr_pp;
unsigned long nr_leaves_on_tree;
int keylen, slot, nr_free, next_slot, i;
pr_devel("-->%s()\n", __func__);
if (!array->root)
return 0;
edit = kzalloc(sizeof(struct assoc_array_edit), GFP_KERNEL);
if (!edit)
return -ENOMEM;
edit->array = array;
edit->ops = ops;
edit->ops_for_excised_subtree = ops;
edit->set[0].ptr = &array->root;
edit->excised_subtree = array->root;
new_root = new_parent = NULL;
new_ptr_pp = &new_root;
cursor = array->root;
descend:
/* If this point is a shortcut, then we need to duplicate it and
* advance the target cursor.
*/
if (assoc_array_ptr_is_shortcut(cursor)) {
shortcut = assoc_array_ptr_to_shortcut(cursor);
keylen = round_up(shortcut->skip_to_level, ASSOC_ARRAY_KEY_CHUNK_SIZE);
keylen >>= ASSOC_ARRAY_KEY_CHUNK_SHIFT;
new_s = kmalloc(sizeof(struct assoc_array_shortcut) +
keylen * sizeof(unsigned long), GFP_KERNEL);
if (!new_s)
goto enomem;
pr_devel("dup shortcut %p -> %p\n", shortcut, new_s);
memcpy(new_s, shortcut, (sizeof(struct assoc_array_shortcut) +
keylen * sizeof(unsigned long)));
new_s->back_pointer = new_parent;
new_s->parent_slot = shortcut->parent_slot;
*new_ptr_pp = new_parent = assoc_array_shortcut_to_ptr(new_s);
new_ptr_pp = &new_s->next_node;
cursor = shortcut->next_node;
}
/* Duplicate the node at this position */
node = assoc_array_ptr_to_node(cursor);
new_n = kzalloc(sizeof(struct assoc_array_node), GFP_KERNEL);
if (!new_n)
goto enomem;
pr_devel("dup node %p -> %p\n", node, new_n);
new_n->back_pointer = new_parent;
new_n->parent_slot = node->parent_slot;
*new_ptr_pp = new_parent = assoc_array_node_to_ptr(new_n);
new_ptr_pp = NULL;
slot = 0;
continue_node:
/* Filter across any leaves and gc any subtrees */
for (; slot < ASSOC_ARRAY_FAN_OUT; slot++) {
ptr = node->slots[slot];
if (!ptr)
continue;
if (assoc_array_ptr_is_leaf(ptr)) {
if (iterator(assoc_array_ptr_to_leaf(ptr),
iterator_data))
/* The iterator will have done any reference
* counting on the object for us.
*/
new_n->slots[slot] = ptr;
continue;
}
new_ptr_pp = &new_n->slots[slot];
cursor = ptr;
goto descend;
}
pr_devel("-- compress node %p --\n", new_n);
/* Count up the number of empty slots in this node and work out the
* subtree leaf count.
*/
new_n->nr_leaves_on_branch = 0;
nr_free = 0;
for (slot = 0; slot < ASSOC_ARRAY_FAN_OUT; slot++) {
ptr = new_n->slots[slot];
if (!ptr)
nr_free++;
else if (assoc_array_ptr_is_leaf(ptr))
new_n->nr_leaves_on_branch++;
}
pr_devel("free=%d, leaves=%lu\n", nr_free, new_n->nr_leaves_on_branch);
/* See what we can fold in */
next_slot = 0;
for (slot = 0; slot < ASSOC_ARRAY_FAN_OUT; slot++) {
struct assoc_array_shortcut *s;
struct assoc_array_node *child;
ptr = new_n->slots[slot];
if (!ptr || assoc_array_ptr_is_leaf(ptr))
continue;
s = NULL;
if (assoc_array_ptr_is_shortcut(ptr)) {
s = assoc_array_ptr_to_shortcut(ptr);
ptr = s->next_node;
}
child = assoc_array_ptr_to_node(ptr);
new_n->nr_leaves_on_branch += child->nr_leaves_on_branch;
if (child->nr_leaves_on_branch <= nr_free + 1) {
/* Fold the child node into this one */
pr_devel("[%d] fold node %lu/%d [nx %d]\n",
slot, child->nr_leaves_on_branch, nr_free + 1,
next_slot);
/* We would already have reaped an intervening shortcut
* on the way back up the tree.
*/
BUG_ON(s);
new_n->slots[slot] = NULL;
nr_free++;
if (slot < next_slot)
next_slot = slot;
for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) {
struct assoc_array_ptr *p = child->slots[i];
if (!p)
continue;
BUG_ON(assoc_array_ptr_is_meta(p));
while (new_n->slots[next_slot])
next_slot++;
BUG_ON(next_slot >= ASSOC_ARRAY_FAN_OUT);
new_n->slots[next_slot++] = p;
nr_free--;
}
kfree(child);
} else {
pr_devel("[%d] retain node %lu/%d [nx %d]\n",
slot, child->nr_leaves_on_branch, nr_free + 1,
next_slot);
}
}
pr_devel("after: %lu\n", new_n->nr_leaves_on_branch);
nr_leaves_on_tree = new_n->nr_leaves_on_branch;
/* Excise this node if it is singly occupied by a shortcut */
if (nr_free == ASSOC_ARRAY_FAN_OUT - 1) {
for (slot = 0; slot < ASSOC_ARRAY_FAN_OUT; slot++)
if ((ptr = new_n->slots[slot]))
break;
if (assoc_array_ptr_is_meta(ptr) &&
assoc_array_ptr_is_shortcut(ptr)) {
pr_devel("excise node %p with 1 shortcut\n", new_n);
new_s = assoc_array_ptr_to_shortcut(ptr);
new_parent = new_n->back_pointer;
slot = new_n->parent_slot;
kfree(new_n);
if (!new_parent) {
new_s->back_pointer = NULL;
new_s->parent_slot = 0;
new_root = ptr;
goto gc_complete;
}
if (assoc_array_ptr_is_shortcut(new_parent)) {
/* We can discard any preceding shortcut also */
struct assoc_array_shortcut *s =
assoc_array_ptr_to_shortcut(new_parent);
pr_devel("excise preceding shortcut\n");
new_parent = new_s->back_pointer = s->back_pointer;
slot = new_s->parent_slot = s->parent_slot;
kfree(s);
if (!new_parent) {
new_s->back_pointer = NULL;
new_s->parent_slot = 0;
new_root = ptr;
goto gc_complete;
}
}
new_s->back_pointer = new_parent;
new_s->parent_slot = slot;
new_n = assoc_array_ptr_to_node(new_parent);
new_n->slots[slot] = ptr;
goto ascend_old_tree;
}
}
/* Excise any shortcuts we might encounter that point to nodes that
* only contain leaves.
*/
ptr = new_n->back_pointer;
if (!ptr)
goto gc_complete;
if (assoc_array_ptr_is_shortcut(ptr)) {
new_s = assoc_array_ptr_to_shortcut(ptr);
new_parent = new_s->back_pointer;
slot = new_s->parent_slot;
if (new_n->nr_leaves_on_branch <= ASSOC_ARRAY_FAN_OUT) {
struct assoc_array_node *n;
pr_devel("excise shortcut\n");
new_n->back_pointer = new_parent;
new_n->parent_slot = slot;
kfree(new_s);
if (!new_parent) {
new_root = assoc_array_node_to_ptr(new_n);
goto gc_complete;
}
n = assoc_array_ptr_to_node(new_parent);
n->slots[slot] = assoc_array_node_to_ptr(new_n);
}
} else {
new_parent = ptr;
}
new_n = assoc_array_ptr_to_node(new_parent);
ascend_old_tree:
ptr = node->back_pointer;
if (assoc_array_ptr_is_shortcut(ptr)) {
shortcut = assoc_array_ptr_to_shortcut(ptr);
slot = shortcut->parent_slot;
cursor = shortcut->back_pointer;
} else {
slot = node->parent_slot;
cursor = ptr;
}
BUG_ON(!ptr);
node = assoc_array_ptr_to_node(cursor);
slot++;
goto continue_node;
gc_complete:
edit->set[0].to = new_root;
assoc_array_apply_edit(edit);
array->nr_leaves_on_tree = nr_leaves_on_tree;
return 0;
enomem:
pr_devel("enomem\n");
assoc_array_destroy_subtree(new_root, edit->ops);
kfree(edit);
return -ENOMEM;
}
| 1 | CVE-2014-3631 | CWE-399 | Resource Management Errors | Weaknesses in this category are related to improper management of system resources. | Not Found in CWE Page | 8,831 |
ImageMagick | a7bb158b7bedd1449a34432feb3a67c8f1873bfa | MagickBooleanType SyncExifProfile(Image *image,StringInfo *profile)
{
#define MaxDirectoryStack 16
#define EXIF_DELIMITER "\n"
#define EXIF_NUM_FORMATS 12
#define TAG_EXIF_OFFSET 0x8769
#define TAG_INTEROP_OFFSET 0xa005
typedef struct _DirectoryInfo
{
unsigned char
*directory;
size_t
entry;
} DirectoryInfo;
DirectoryInfo
directory_stack[MaxDirectoryStack];
EndianType
endian;
size_t
entry,
length,
number_entries;
ssize_t
id,
level,
offset;
static int
format_bytes[] = {0, 1, 1, 2, 4, 8, 1, 1, 2, 4, 8, 4, 8};
unsigned char
*directory,
*exif;
/*
Set EXIF resolution tag.
*/
length=GetStringInfoLength(profile);
exif=GetStringInfoDatum(profile);
if (length < 16)
return(MagickFalse);
id=(ssize_t) ReadProfileShort(LSBEndian,exif);
if ((id != 0x4949) && (id != 0x4D4D))
{
while (length != 0)
{
if (ReadProfileByte(&exif,&length) != 0x45)
continue;
if (ReadProfileByte(&exif,&length) != 0x78)
continue;
if (ReadProfileByte(&exif,&length) != 0x69)
continue;
if (ReadProfileByte(&exif,&length) != 0x66)
continue;
if (ReadProfileByte(&exif,&length) != 0x00)
continue;
if (ReadProfileByte(&exif,&length) != 0x00)
continue;
break;
}
if (length < 16)
return(MagickFalse);
id=(ssize_t) ReadProfileShort(LSBEndian,exif);
}
endian=LSBEndian;
if (id == 0x4949)
endian=LSBEndian;
else
if (id == 0x4D4D)
endian=MSBEndian;
else
return(MagickFalse);
if (ReadProfileShort(endian,exif+2) != 0x002a)
return(MagickFalse);
/*
This the offset to the first IFD.
*/
offset=(ssize_t) ReadProfileLong(endian,exif+4);
if ((offset < 0) || (size_t) offset >= length)
return(MagickFalse);
directory=exif+offset;
level=0;
entry=0;
do
{
if (level > 0)
{
level--;
directory=directory_stack[level].directory;
entry=directory_stack[level].entry;
}
if ((directory < exif) || (directory > (exif+length-2)))
break;
/*
Determine how many entries there are in the current IFD.
*/
number_entries=ReadProfileShort(endian,directory);
for ( ; entry < number_entries; entry++)
{
int
components;
register unsigned char
*p,
*q;
size_t
number_bytes;
ssize_t
format,
tag_value;
q=(unsigned char *) (directory+2+(12*entry));
if (q > (exif+length-12))
break; /* corrupt EXIF */
tag_value=(ssize_t) ReadProfileShort(endian,q);
format=(ssize_t) ReadProfileShort(endian,q+2);
if ((format < 0) || ((format-1) >= EXIF_NUM_FORMATS))
break;
components=(ssize_t) ReadProfileLong(endian,q+4);
if (components < 0)
break; /* corrupt EXIF */
number_bytes=(size_t) components*format_bytes[format];
if ((ssize_t) number_bytes < components)
break; /* prevent overflow */
if (number_bytes <= 4)
p=q+8;
else
{
/*
The directory entry contains an offset.
*/
offset=(ssize_t) ReadProfileLong(endian,q+8);
if ((size_t) (offset+number_bytes) > length)
continue;
if (~length < number_bytes)
continue; /* prevent overflow */
p=(unsigned char *) (exif+offset);
}
switch (tag_value)
{
case 0x011a:
{
(void) WriteProfileLong(endian,(size_t) (image->resolution.x+0.5),p);
(void) WriteProfileLong(endian,1UL,p+4);
break;
}
case 0x011b:
{
(void) WriteProfileLong(endian,(size_t) (image->resolution.y+0.5),p);
(void) WriteProfileLong(endian,1UL,p+4);
break;
}
case 0x0112:
{
if (number_bytes == 4)
{
(void) WriteProfileLong(endian,(size_t) image->orientation,p);
break;
}
(void) WriteProfileShort(endian,(unsigned short) image->orientation,
p);
break;
}
case 0x0128:
{
if (number_bytes == 4)
{
(void) WriteProfileLong(endian,(size_t) (image->units+1),p);
break;
}
(void) WriteProfileShort(endian,(unsigned short) (image->units+1),p);
break;
}
default:
break;
}
if ((tag_value == TAG_EXIF_OFFSET) || (tag_value == TAG_INTEROP_OFFSET))
{
offset=(ssize_t) ReadProfileLong(endian,p);
if (((size_t) offset < length) && (level < (MaxDirectoryStack-2)))
{
directory_stack[level].directory=directory;
entry++;
directory_stack[level].entry=entry;
level++;
directory_stack[level].directory=exif+offset;
directory_stack[level].entry=0;
level++;
if ((directory+2+(12*number_entries)) > (exif+length))
break;
offset=(ssize_t) ReadProfileLong(endian,directory+2+(12*
number_entries));
if ((offset != 0) && ((size_t) offset < length) &&
(level < (MaxDirectoryStack-2)))
{
directory_stack[level].directory=exif+offset;
directory_stack[level].entry=0;
level++;
}
}
break;
}
}
} while (level > 0);
return(MagickTrue);
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 15,680 |
poppler | 0868c499a9f5f37f8df5c9fef03c37496b40fc8a | Stream *Parser::makeStream(Object &&dict, Guchar *fileKey,
CryptAlgorithm encAlgorithm, int keyLength,
int objNum, int objGen, int recursion,
GBool strict) {
BaseStream *baseStr;
Stream *str;
Goffset length;
Goffset pos, endPos;
// get stream start position
lexer->skipToNextLine();
if (!(str = lexer->getStream())) {
return nullptr;
}
pos = str->getPos();
// get length
Object obj = dict.dictLookup("Length", recursion);
if (obj.isInt()) {
length = obj.getInt();
} else if (obj.isInt64()) {
length = obj.getInt64();
} else {
error(errSyntaxError, getPos(), "Bad 'Length' attribute in stream");
if (strict) return nullptr;
length = 0;
}
// check for length in damaged file
if (xref && xref->getStreamEnd(pos, &endPos)) {
length = endPos - pos;
}
// in badly damaged PDF files, we can run off the end of the input
// stream immediately after the "stream" token
if (!lexer->getStream()) {
return nullptr;
}
baseStr = lexer->getStream()->getBaseStream();
// skip over stream data
if (Lexer::LOOK_VALUE_NOT_CACHED != lexer->lookCharLastValueCached) {
// take into account the fact that we've cached one value
pos = pos - 1;
lexer->lookCharLastValueCached = Lexer::LOOK_VALUE_NOT_CACHED;
}
lexer->setPos(pos + length);
// refill token buffers and check for 'endstream'
shift(); // kill '>>'
shift("endstream", objNum); // kill 'stream'
if (buf1.isCmd("endstream")) {
shift();
} else {
error(errSyntaxError, getPos(), "Missing 'endstream' or incorrect stream length");
if (strict) return nullptr;
if (xref && lexer->getStream()) {
// shift until we find the proper endstream or we change to another object or reach eof
length = lexer->getPos() - pos;
if (buf1.isCmd("endstream")) {
dict.dictSet("Length", Object(length));
}
} else {
// When building the xref we can't use it so use this
// kludge for broken PDF files: just add 5k to the length, and
// hope its enough
length += 5000;
}
}
// make base stream
str = baseStr->makeSubStream(pos, gTrue, length, std::move(dict));
// handle decryption
if (fileKey) {
str = new DecryptStream(str, fileKey, encAlgorithm, keyLength,
objNum, objGen);
}
// get filters
str = str->addFilters(str->getDict(), recursion);
return str;
} | 1 | CVE-2018-21009 | 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. | 4,119 |
gst-plugins-good | 02174790726dd20a5c73ce2002189bf240ad4fe0 | gst_matroska_cluster_compare (gint64 * i1, gint64 * i2)
{
if (*i1 < *i2)
return -1;
else if (*i1 > *i2)
return 1;
else
return 0;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 15,458 |
systemd | a924f43f30f9c4acaf70618dd2a055f8b0f166be | int dns_packet_append_name(
DnsPacket *p,
const char *name,
bool allow_compression,
bool canonical_candidate,
size_t *start) {
size_t saved_size;
int r;
assert(p);
assert(name);
if (p->refuse_compression)
allow_compression = false;
saved_size = p->size;
while (!dns_name_is_root(name)) {
const char *z = name;
char label[DNS_LABEL_MAX];
size_t n = 0;
if (allow_compression)
n = PTR_TO_SIZE(hashmap_get(p->names, name));
if (n > 0) {
assert(n < p->size);
if (n < 0x4000) {
r = dns_packet_append_uint16(p, 0xC000 | n, NULL);
if (r < 0)
goto fail;
goto done;
}
}
r = dns_label_unescape(&name, label, sizeof(label));
if (r < 0)
goto fail;
r = dns_packet_append_label(p, label, r, canonical_candidate, &n);
if (r < 0)
goto fail;
if (allow_compression) {
_cleanup_free_ char *s = NULL;
s = strdup(z);
if (!s) {
r = -ENOMEM;
goto fail;
}
r = hashmap_ensure_allocated(&p->names, &dns_name_hash_ops);
if (r < 0)
goto fail;
r = hashmap_put(p->names, s, SIZE_TO_PTR(n));
if (r < 0)
goto fail;
s = NULL;
}
}
r = dns_packet_append_uint8(p, 0, NULL);
if (r < 0)
return r;
done:
if (start)
*start = saved_size;
return 0;
fail:
dns_packet_truncate(p, saved_size);
return r;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 11,772 |
Android | 04839626ed859623901ebd3a5fd483982186b59d | long Chapters::Atom::ParseDisplay(
IMkvReader* pReader,
long long pos,
long long size)
{
if (!ExpandDisplaysArray())
return -1;
Display& d = m_displays[m_displays_count++];
d.Init();
return d.Parse(pReader, pos, size);
}
| 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). | 352 |
Chrome | 6a7063ae61cf031630b48bdcdb09863ffc199962 | void OffscreenCanvas::Commit(scoped_refptr<CanvasResource> canvas_resource,
const SkIRect& damage_rect) {
if (!HasPlaceholderCanvas() || !canvas_resource)
return;
RecordCanvasSizeToUMA(
Size(), CanvasRenderingContextHost::HostType::kOffscreenCanvasHost);
base::TimeTicks commit_start_time = WTF::CurrentTimeTicks();
current_frame_damage_rect_.join(damage_rect);
GetOrCreateResourceDispatcher()->DispatchFrameSync(
std::move(canvas_resource), commit_start_time, current_frame_damage_rect_,
!RenderingContext()->IsOriginTopLeft() /* needs_vertical_flip */,
IsOpaque());
current_frame_damage_rect_ = SkIRect::MakeEmpty();
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 17,293 |
keepalived | 17f944144b3d9c5131569b1cc988cc90fd676671 | FILE *fopen_safe(const char *path, const char *mode)
{
int fd;
FILE *file;
int flags = O_NOFOLLOW | O_CREAT;
int sav_errno;
if (mode[0] == 'r')
return fopen(path, mode);
if ((mode[0] != 'a' && mode[0] != 'w') ||
(mode[1] &&
(mode[1] != '+' || mode[2]))) {
errno = EINVAL;
return NULL;
}
if (mode[0] == 'w')
flags |= O_TRUNC;
else
flags |= O_APPEND;
if (mode[1])
flags |= O_RDWR;
else
flags |= O_WRONLY;
if (mode[0] == 'w') {
/* Ensure that any existing file isn't currently opened for read by a non-privileged user.
* We do this by unlinking the file, so that the open() below will create a new file. */
if (unlink(path) && errno != ENOENT) {
log_message(LOG_INFO, "Failed to remove existing file '%s' prior to write", path);
return NULL;
}
}
else {
/* Only allow append mode if debugging features requiring append are enabled. Since we
* can't unlink the file, there may be a non privileged user who already has the file open
* for read (e.g. tail -f). If these debug option aren't enabled, there is no potential
* security risk. */
#ifndef ENABLE_LOG_FILE_APPEND
log_message(LOG_INFO, "BUG - shouldn't be opening file for append with current build options");
errno = EINVAL;
return NULL;
#endif
}
fd = open(path, flags, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH);
if (fd == -1)
return NULL;
/* Change file ownership to root */
if (fchown(fd, 0, 0)) {
sav_errno = errno;
log_message(LOG_INFO, "Unable to change file ownership of %s- errno %d (%m)", path, errno);
close(fd);
errno = sav_errno;
return NULL;
}
/* Set file mode to rw------- */
if (fchmod(fd, S_IRUSR | S_IWUSR)) {
sav_errno = errno;
log_message(LOG_INFO, "Unable to change file permission of %s - errno %d (%m)", path, errno);
close(fd);
errno = sav_errno;
return NULL;
}
file = fdopen (fd, "w");
if (!file) {
sav_errno = errno;
log_message(LOG_INFO, "fdopen(\"%s\") failed - errno %d (%m)", path, errno);
close(fd);
errno = sav_errno;
return NULL;
}
return file;
} | 1 | CVE-2018-19046 | 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. | 6,168 |
linux | cc16eecae687912238ee6efbff71ad31e2bc414e | int jbd2_journal_start_reserved(handle_t *handle, unsigned int type,
unsigned int line_no)
{
journal_t *journal = handle->h_journal;
int ret = -EIO;
if (WARN_ON(!handle->h_reserved)) {
/* Someone passed in normal handle? Just stop it. */
jbd2_journal_stop(handle);
return ret;
}
/*
* Usefulness of mixing of reserved and unreserved handles is
* questionable. So far nobody seems to need it so just error out.
*/
if (WARN_ON(current->journal_info)) {
jbd2_journal_free_reserved(handle);
return ret;
}
handle->h_journal = NULL;
/*
* GFP_NOFS is here because callers are likely from writeback or
* similarly constrained call sites
*/
ret = start_this_handle(journal, handle, GFP_NOFS);
if (ret < 0) {
handle->h_journal = journal;
jbd2_journal_free_reserved(handle);
return ret;
}
handle->h_type = type;
handle->h_line_no = line_no;
trace_jbd2_handle_start(journal->j_fs_dev->bd_dev,
handle->h_transaction->t_tid, type,
line_no, handle->h_total_credits);
return 0;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 15,942 |
rizin | aa6917772d2f32e5a7daab25a46c72df0b5ea406 | static const ut8 *parse_die(const ut8 *buf, const ut8 *buf_end, RzBinDwarfDebugInfo *info, RzBinDwarfAbbrevDecl *abbrev,
RzBinDwarfCompUnitHdr *hdr, RzBinDwarfDie *die, const ut8 *debug_str, size_t debug_str_len, bool big_endian) {
size_t i;
const char *comp_dir = NULL;
ut64 line_info_offset = UT64_MAX;
for (i = 0; i < abbrev->count - 1; i++) {
memset(&die->attr_values[i], 0, sizeof(die->attr_values[i]));
buf = parse_attr_value(buf, buf_end - buf, &abbrev->defs[i],
&die->attr_values[i], hdr, debug_str, debug_str_len, big_endian);
RzBinDwarfAttrValue *attribute = &die->attr_values[i];
if (attribute->attr_name == DW_AT_comp_dir && (attribute->attr_form == DW_FORM_strp || attribute->attr_form == DW_FORM_string) && attribute->string.content) {
comp_dir = attribute->string.content;
}
if (attribute->attr_name == DW_AT_stmt_list) {
if (attribute->kind == DW_AT_KIND_CONSTANT) {
line_info_offset = attribute->uconstant;
} else if (attribute->kind == DW_AT_KIND_REFERENCE) {
line_info_offset = attribute->reference;
}
}
die->count++;
}
// If this is a compilation unit dir attribute, we want to cache it so the line info parsing
// which will need this info can quickly look it up.
if (comp_dir && line_info_offset != UT64_MAX) {
char *name = strdup(comp_dir);
if (name) {
if (!ht_up_insert(info->line_info_offset_comp_dir, line_info_offset, name)) {
free(name);
}
}
}
return buf;
} | 1 | CVE-2021-43814 | 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). | 1,071 |
linux | e0bccd315db0c2f919e7fcf9cb60db21d9986f52 | void rose_link_device_down(struct net_device *dev)
{
struct rose_neigh *rose_neigh;
for (rose_neigh = rose_neigh_list; rose_neigh != NULL; rose_neigh = rose_neigh->next) {
if (rose_neigh->dev == dev) {
rose_del_route_by_neigh(rose_neigh);
rose_kill_by_neigh(rose_neigh);
}
}
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 11,551 |
libtiff | 9657bbe3cdce4aaa90e07d50c1c70ae52da0ba6a | static int readContigStripsIntoBuffer (TIFF* in, uint8* buf)
{
uint8* bufp = buf;
int32 bytes_read = 0;
uint32 strip, nstrips = TIFFNumberOfStrips(in);
uint32 stripsize = TIFFStripSize(in);
uint32 rows = 0;
uint32 rps = TIFFGetFieldDefaulted(in, TIFFTAG_ROWSPERSTRIP, &rps);
tsize_t scanline_size = TIFFScanlineSize(in);
if (scanline_size == 0) {
TIFFError("", "TIFF scanline size is zero!");
return 0;
}
for (strip = 0; strip < nstrips; strip++) {
bytes_read = TIFFReadEncodedStrip (in, strip, bufp, -1);
rows = bytes_read / scanline_size;
if ((strip < (nstrips - 1)) && (bytes_read != (int32)stripsize))
TIFFError("", "Strip %d: read %lu bytes, strip size %lu",
(int)strip + 1, (unsigned long) bytes_read,
(unsigned long)stripsize);
if (bytes_read < 0 && !ignore) {
TIFFError("", "Error reading strip %lu after %lu rows",
(unsigned long) strip, (unsigned long)rows);
return 0;
}
bufp += bytes_read;
}
return 1;
} /* end readContigStripsIntoBuffer */
| 1 | CVE-2016-10092 | 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,096 |
curl | 13c9a9ded3ae744a1e11cbc14e9146d9fa427040 | static CURLcode imap_block_statemach(struct connectdata *conn)
{
CURLcode result = CURLE_OK;
struct imap_conn *imapc = &conn->proto.imapc;
while(imapc->state != IMAP_STOP && !result)
result = Curl_pp_statemach(&imapc->pp, TRUE);
return result;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 17,551 |
libgit2 | b5c6a1b407b7f8b952bded2789593b68b1876211 | static int gen_request(
git_buf *buf,
http_stream *s,
size_t content_length)
{
http_subtransport *t = OWNING_SUBTRANSPORT(s);
const char *path = t->connection_data.path ? t->connection_data.path : "/";
size_t i;
git_buf_printf(buf, "%s %s%s HTTP/1.1\r\n", s->verb, path, s->service_url);
git_buf_printf(buf, "User-Agent: git/1.0 (%s)\r\n", user_agent());
git_buf_printf(buf, "Host: %s\r\n", t->connection_data.host);
if (s->chunked || content_length > 0) {
git_buf_printf(buf, "Accept: application/x-git-%s-result\r\n", s->service);
git_buf_printf(buf, "Content-Type: application/x-git-%s-request\r\n", s->service);
if (s->chunked)
git_buf_puts(buf, "Transfer-Encoding: chunked\r\n");
else
git_buf_printf(buf, "Content-Length: %"PRIuZ "\r\n", content_length);
} else
git_buf_puts(buf, "Accept: */*\r\n");
for (i = 0; i < t->owner->custom_headers.count; i++) {
if (t->owner->custom_headers.strings[i])
git_buf_printf(buf, "%s\r\n", t->owner->custom_headers.strings[i]);
}
/* Apply credentials to the request */
if (apply_credentials(buf, t) < 0)
return -1;
git_buf_puts(buf, "\r\n");
if (git_buf_oom(buf))
return -1;
return 0;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 22,909 |
FFmpeg | 5aba5b89d0b1d73164d3b81764828bb8b20ff32a | static av_cold int init_studio_vlcs(Mpeg4DecContext *ctx)
{
int i, ret;
for (i = 0; i < 12; i++) {
ret = init_vlc(&ctx->studio_intra_tab[i], STUDIO_INTRA_BITS, 22,
&ff_mpeg4_studio_intra[i][0][1], 4, 2,
&ff_mpeg4_studio_intra[i][0][0], 4, 2,
0);
if (ret < 0)
return ret;
}
ret = init_vlc(&ctx->studio_luma_dc, STUDIO_INTRA_BITS, 19,
&ff_mpeg4_studio_dc_luma[0][1], 4, 2,
&ff_mpeg4_studio_dc_luma[0][0], 4, 2,
0);
if (ret < 0)
return ret;
ret = init_vlc(&ctx->studio_chroma_dc, STUDIO_INTRA_BITS, 19,
&ff_mpeg4_studio_dc_chroma[0][1], 4, 2,
&ff_mpeg4_studio_dc_chroma[0][0], 4, 2,
0);
if (ret < 0)
return ret;
return 0;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 15,329 |
sleuthkit | bc04aa017c0bd297de8a3b7fc40ffc6ddddbb95d | static int hfs_file_read_zlib_attr(TSK_FS_FILE* fs_file,
char* buffer,
uint32_t attributeLength,
uint64_t uncSize)
{
return hfs_file_read_compressed_attr(
fs_file, DECMPFS_TYPE_ZLIB_ATTR,
buffer, attributeLength, uncSize,
hfs_decompress_zlib_attr
);
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 12,977 |
Android | 5a9753fca56f0eeb9f61e342b2fccffc364f9426 | int ReturnFrameBuffer(vpx_codec_frame_buffer_t *fb) {
EXPECT_TRUE(fb != NULL);
ExternalFrameBuffer *const ext_fb =
reinterpret_cast<ExternalFrameBuffer*>(fb->priv);
EXPECT_TRUE(ext_fb != NULL);
EXPECT_EQ(1, ext_fb->in_use);
ext_fb->in_use = 0;
return 0;
}
| 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,230 |
Android | cc274e2abe8b2a6698a5c47d8aa4bb45f1f9538d | const Cluster* Segment::GetNext(const Cluster* pCurr) {
assert(pCurr);
assert(pCurr != &m_eos);
assert(m_clusters);
long idx = pCurr->m_index;
if (idx >= 0) {
assert(m_clusterCount > 0);
assert(idx < m_clusterCount);
assert(pCurr == m_clusters[idx]);
++idx;
if (idx >= m_clusterCount)
return &m_eos; // caller will LoadCluster as desired
Cluster* const pNext = m_clusters[idx];
assert(pNext);
assert(pNext->m_index >= 0);
assert(pNext->m_index == idx);
return pNext;
}
assert(m_clusterPreloadCount > 0);
long long pos = pCurr->m_element_start;
assert(m_size >= 0); // TODO
const long long stop = m_start + m_size; // end of segment
{
long len;
long long result = GetUIntLength(m_pReader, pos, len);
assert(result == 0);
assert((pos + len) <= stop); // TODO
if (result != 0)
return NULL;
const long long id = ReadUInt(m_pReader, pos, len);
assert(id == 0x0F43B675); // Cluster ID
if (id != 0x0F43B675)
return NULL;
pos += len; // consume ID
result = GetUIntLength(m_pReader, pos, len);
assert(result == 0); // TODO
assert((pos + len) <= stop); // TODO
const long long size = ReadUInt(m_pReader, pos, len);
assert(size > 0); // TODO
pos += len; // consume length of size of element
assert((pos + size) <= stop); // TODO
pos += size; // consume payload
}
long long off_next = 0;
while (pos < stop) {
long len;
long long result = GetUIntLength(m_pReader, pos, len);
assert(result == 0);
assert((pos + len) <= stop); // TODO
if (result != 0)
return NULL;
const long long idpos = pos; // pos of next (potential) cluster
const long long id = ReadUInt(m_pReader, idpos, len);
assert(id > 0); // TODO
pos += len; // consume ID
result = GetUIntLength(m_pReader, pos, len);
assert(result == 0); // TODO
assert((pos + len) <= stop); // TODO
const long long size = ReadUInt(m_pReader, pos, len);
assert(size >= 0); // TODO
pos += len; // consume length of size of element
assert((pos + size) <= stop); // TODO
if (size == 0) // weird
continue;
if (id == 0x0F43B675) { // Cluster ID
const long long off_next_ = idpos - m_start;
long long pos_;
long len_;
const long status = Cluster::HasBlockEntries(this, off_next_, pos_, len_);
assert(status >= 0);
if (status > 0) {
off_next = off_next_;
break;
}
}
pos += size; // consume payload
}
if (off_next <= 0)
return 0;
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);
Cluster* const pNext = *k;
assert(pNext);
assert(pNext->m_index < 0);
pos = pNext->GetPosition();
if (pos < off_next)
i = k + 1;
else if (pos > off_next)
j = k;
else
return pNext;
}
assert(i == j);
Cluster* const pNext = Cluster::Create(this, -1, 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);
return pNext;
}
| 1 | CVE-2016-2464 | 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. | 6,046 |
systemd | 06eeacb6fe029804f296b065b3ce91e796e1cd0e | int symlink_idempotent(const char *from, const char *to) {
_cleanup_free_ char *p = NULL;
int r;
assert(from);
assert(to);
if (symlink(from, to) < 0) {
if (errno != EEXIST)
return -errno;
r = readlink_malloc(to, &p);
if (r < 0)
return r;
if (!streq(p, from))
return -EINVAL;
}
return 0;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 18,276 |
krb5 | a7886f0ed1277c69142b14a2c6629175a6331edc | acc_ctx_cont(OM_uint32 *minstat,
gss_buffer_t buf,
gss_ctx_id_t *ctx,
gss_buffer_t *responseToken,
gss_buffer_t *mechListMIC,
OM_uint32 *negState,
send_token_flag *return_token)
{
OM_uint32 ret, tmpmin;
gss_OID supportedMech;
spnego_gss_ctx_id_t sc;
unsigned int len;
unsigned char *ptr, *bufstart;
sc = (spnego_gss_ctx_id_t)*ctx;
ret = GSS_S_DEFECTIVE_TOKEN;
*negState = REJECT;
*minstat = 0;
supportedMech = GSS_C_NO_OID;
*return_token = ERROR_TOKEN_SEND;
*responseToken = *mechListMIC = GSS_C_NO_BUFFER;
ptr = bufstart = buf->value;
#define REMAIN (buf->length - (ptr - bufstart))
if (REMAIN > INT_MAX)
return GSS_S_DEFECTIVE_TOKEN;
/*
* Attempt to work with old Sun SPNEGO.
*/
if (*ptr == HEADER_ID) {
ret = g_verify_token_header(gss_mech_spnego,
&len, &ptr, 0, REMAIN);
if (ret) {
*minstat = ret;
return GSS_S_DEFECTIVE_TOKEN;
}
}
if (*ptr != (CONTEXT | 0x01)) {
return GSS_S_DEFECTIVE_TOKEN;
}
ret = get_negTokenResp(minstat, ptr, REMAIN,
negState, &supportedMech,
responseToken, mechListMIC);
if (ret != GSS_S_COMPLETE)
goto cleanup;
if (*responseToken == GSS_C_NO_BUFFER &&
*mechListMIC == GSS_C_NO_BUFFER) {
ret = GSS_S_DEFECTIVE_TOKEN;
goto cleanup;
}
if (supportedMech != GSS_C_NO_OID) {
ret = GSS_S_DEFECTIVE_TOKEN;
goto cleanup;
}
sc->firstpass = 0;
*negState = ACCEPT_INCOMPLETE;
*return_token = CONT_TOKEN_SEND;
cleanup:
if (supportedMech != GSS_C_NO_OID) {
generic_gss_release_oid(&tmpmin, &supportedMech);
}
return ret;
#undef REMAIN
}
| 1 | CVE-2014-4344 | 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,445 |
drogon | 3c785326c63a34aa1799a639ae185bc9453cb447 | DROGON_TEST(HttpFile)
{
SUBSECTION(Save)
{
HttpFileImpl file;
file.setFileName("test_file_name");
file.setFile("test", 4);
auto out = file.save("./test_uploads_dir");
CHECK(out == 0);
CHECK(filesystem::exists("./test_uploads_dir/test_file_name"));
filesystem::remove_all("./test_uploads_dir");
}
SUBSECTION(SavePathRelativeTraversal)
{
auto uploadPath = filesystem::current_path() / "test_uploads_dir";
HttpFileImpl file;
file.setFileName("../test_malicious_file_name");
file.setFile("test", 4);
auto out = file.save(uploadPath.string());
CHECK(out == -1);
CHECK(!filesystem::exists(uploadPath / "../test_malicious_file_name"));
filesystem::remove_all(uploadPath);
filesystem::remove(uploadPath / "../test_malicious_file_name");
}
SUBSECTION(SavePathAbsoluteTraversal)
{
HttpFileImpl file;
file.setFileName("/tmp/test_malicious_file_name");
file.setFile("test", 4);
auto out = file.save("./test_uploads_dir");
CHECK(out == -1);
CHECK(!filesystem::exists("/tmp/test_malicious_file_name"));
filesystem::remove_all("test_uploads_dir");
filesystem::remove_all("/tmp/test_malicious_file_name");
}
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 11,619 |
curl | 9b5e12a5491d2e6b68e0c88ca56f3a9ef9fba400 | static CURLcode override_login(struct Curl_easy *data,
struct connectdata *conn,
char **userp, char **passwdp, char **optionsp)
{
if(data->set.str[STRING_USERNAME]) {
free(*userp);
*userp = strdup(data->set.str[STRING_USERNAME]);
if(!*userp)
return CURLE_OUT_OF_MEMORY;
}
if(data->set.str[STRING_PASSWORD]) {
free(*passwdp);
*passwdp = strdup(data->set.str[STRING_PASSWORD]);
if(!*passwdp)
return CURLE_OUT_OF_MEMORY;
}
if(data->set.str[STRING_OPTIONS]) {
free(*optionsp);
*optionsp = strdup(data->set.str[STRING_OPTIONS]);
if(!*optionsp)
return CURLE_OUT_OF_MEMORY;
}
conn->bits.netrc = FALSE;
if(data->set.use_netrc != CURL_NETRC_IGNORED) {
int ret = Curl_parsenetrc(conn->host.name,
userp, passwdp,
data->set.str[STRING_NETRC_FILE]);
if(ret > 0) {
infof(data, "Couldn't find host %s in the "
DOT_CHAR "netrc file; using defaults\n",
conn->host.name);
}
else if(ret < 0) {
return CURLE_OUT_OF_MEMORY;
}
else {
/* set bits.netrc TRUE to remember that we got the name from a .netrc
file, so that it is safe to use even if we followed a Location: to a
different host or similar. */
conn->bits.netrc = TRUE;
conn->bits.user_passwd = TRUE; /* enable user+password */
}
}
return CURLE_OK;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 16,137 |
curl | 9069838b30fb3b48af0123e39f664cea683254a5 | static ssize_t sec_recv(struct connectdata *conn, int sockindex,
char *buffer, size_t len, CURLcode *err)
{
size_t bytes_read;
size_t total_read = 0;
curl_socket_t fd = conn->sock[sockindex];
*err = CURLE_OK;
/* Handle clear text response. */
if(conn->sec_complete == 0 || conn->data_prot == PROT_CLEAR)
return read(fd, buffer, len);
if(conn->in_buffer.eof_flag) {
conn->in_buffer.eof_flag = 0;
return 0;
}
bytes_read = buffer_read(&conn->in_buffer, buffer, len);
len -= bytes_read;
total_read += bytes_read;
buffer += bytes_read;
while(len > 0) {
if(read_data(conn, fd, &conn->in_buffer))
return -1;
if(conn->in_buffer.size == 0) {
if(bytes_read > 0)
conn->in_buffer.eof_flag = 1;
return bytes_read;
}
bytes_read = buffer_read(&conn->in_buffer, buffer, len);
len -= bytes_read;
total_read += bytes_read;
buffer += bytes_read;
}
return total_read;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 16,632 |
FFmpeg | 6b67d7f05918f7a1ee8fc6ff21355d7e8736aa10 | static void put_timestamp(AVIOContext *pb, int64_t ts) {
avio_wb24(pb, ts & 0xFFFFFF);
avio_w8(pb, (ts >> 24) & 0x7F);
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 19,950 |
libgsf | 95a8351a75758cf10b3bf6abae0b6b461f90d9e5 | tar_directory_for_file (GsfInfileTar *dir, const char *name, gboolean last)
{
const char *s = name;
while (1) {
const char *s0 = s;
char *dirname;
/* Find a directory component, if any. */
while (1) {
if (*s == 0) {
if (last && s != s0)
break;
else
return dir;
}
/* This is deliberately slash-only. */
if (*s == '/')
break;
s++;
}
dirname = g_strndup (s0, s - s0);
while (*s == '/')
s++;
if (strcmp (dirname, ".") != 0) {
GsfInput *subdir =
gsf_infile_child_by_name (GSF_INFILE (dir),
dirname);
if (subdir) {
/* Undo the ref. */
g_object_unref (subdir);
dir = GSF_INFILE_TAR (subdir);
} else
dir = tar_create_dir (dir, dirname);
}
g_free (dirname);
}
}
| 1 | CVE-2016-9888 | 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. | 5,662 |
linux | e6bd18f57aad1a2d1ef40e646d03ed0f2515c9e3 | static ssize_t ib_ucm_write(struct file *filp, const char __user *buf,
size_t len, loff_t *pos)
{
struct ib_ucm_file *file = filp->private_data;
struct ib_ucm_cmd_hdr hdr;
ssize_t result;
if (len < sizeof(hdr))
return -EINVAL;
if (copy_from_user(&hdr, buf, sizeof(hdr)))
return -EFAULT;
if (hdr.cmd >= ARRAY_SIZE(ucm_cmd_table))
return -EINVAL;
if (hdr.in + sizeof(hdr) > len)
return -EINVAL;
result = ucm_cmd_table[hdr.cmd](file, buf + sizeof(hdr),
hdr.in, hdr.out);
if (!result)
result = len;
return result;
}
| 1 | CVE-2016-4565 | 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 | 8,797 |
libcomps | e3a5d056633677959ad924a51758876d415e7046 | void comps_rtree_unite(COMPS_RTree *rt1, COMPS_RTree *rt2) {
COMPS_HSList *tmplist, *tmp_subnodes;
COMPS_HSListItem *it;
struct Pair {
COMPS_HSList * subnodes;
char * key;
char added;
} *pair, *parent_pair;
pair = malloc(sizeof(struct Pair));
pair->subnodes = rt2->subnodes;
pair->key = NULL;
tmplist = comps_hslist_create();
comps_hslist_init(tmplist, NULL, NULL, &free);
comps_hslist_append(tmplist, pair, 0);
while (tmplist->first != NULL) {
it = tmplist->first;
comps_hslist_remove(tmplist, tmplist->first);
tmp_subnodes = ((struct Pair*)it->data)->subnodes;
parent_pair = (struct Pair*) it->data;
free(it);
for (it = tmp_subnodes->first; it != NULL; it=it->next) {
pair = malloc(sizeof(struct Pair));
pair->subnodes = ((COMPS_RTreeData*)it->data)->subnodes;
if (parent_pair->key != NULL) {
pair->key = malloc(sizeof(char)
* (strlen(((COMPS_RTreeData*)it->data)->key)
+ strlen(parent_pair->key) + 1));
memcpy(pair->key, parent_pair->key,
sizeof(char) * strlen(parent_pair->key));
memcpy(pair->key + strlen(parent_pair->key),
((COMPS_RTreeData*)it->data)->key,
sizeof(char)*(strlen(((COMPS_RTreeData*)it->data)->key)+1));
} else {
pair->key = malloc(sizeof(char)*
(strlen(((COMPS_RTreeData*)it->data)->key) +1));
memcpy(pair->key, ((COMPS_RTreeData*)it->data)->key,
sizeof(char)*(strlen(((COMPS_RTreeData*)it->data)->key)+1));
}
/* current node has data */
if (((COMPS_RTreeData*)it->data)->data != NULL) {
comps_rtree_set(rt1,
pair->key,
rt2->data_cloner(((COMPS_RTreeData*)it->data)->data));
}
if (((COMPS_RTreeData*)it->data)->subnodes->first) {
comps_hslist_append(tmplist, pair, 0);
} else {
free(pair->key);
free(pair);
}
}
free(parent_pair->key);
free(parent_pair);
}
comps_hslist_destroy(&tmplist);
}
| 1 | CVE-2019-3817 | 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. | 8,997 |
FFmpeg | 7ba100d3e6e8b1e5d5342feb960a7f081d6e15af | static int read_data(void *opaque, uint8_t *buf, int buf_size)
{
struct playlist *v = opaque;
HLSContext *c = v->parent->priv_data;
int ret, i;
int just_opened = 0;
int reload_count = 0;
restart:
if (!v->needed)
return AVERROR_EOF;
if (!v->input) {
int64_t reload_interval;
/* Check that the playlist is still needed before opening a new
* segment. */
if (v->ctx && v->ctx->nb_streams &&
v->parent->nb_streams >= v->stream_offset + v->ctx->nb_streams) {
v->needed = 0;
for (i = v->stream_offset; i < v->stream_offset + v->ctx->nb_streams;
i++) {
if (v->parent->streams[i]->discard < AVDISCARD_ALL)
v->needed = 1;
}
}
if (!v->needed) {
av_log(v->parent, AV_LOG_INFO, "No longer receiving playlist %d\n",
v->index);
return AVERROR_EOF;
}
/* If this is a live stream and the reload interval has elapsed since
* the last playlist reload, reload the playlists now. */
reload_interval = default_reload_interval(v);
reload:
reload_count++;
if (reload_count > c->max_reload)
return AVERROR_EOF;
if (!v->finished &&
av_gettime() - v->last_load_time >= reload_interval) {
if ((ret = parse_playlist(c, v->url, v, NULL)) < 0) {
av_log(v->parent, AV_LOG_WARNING, "Failed to reload playlist %d\n",
v->index);
return ret;
}
/* If we need to reload the playlist again below (if
* there's still no more segments), switch to a reload
* interval of half the target duration. */
reload_interval = v->target_duration / 2;
}
if (v->cur_seq_no < v->start_seq_no) {
av_log(NULL, AV_LOG_WARNING,
"skipping %d segments ahead, expired from playlists\n",
v->start_seq_no - v->cur_seq_no);
v->cur_seq_no = v->start_seq_no;
}
if (v->cur_seq_no >= v->start_seq_no + v->n_segments) {
if (v->finished)
return AVERROR_EOF;
while (av_gettime() - v->last_load_time < reload_interval) {
if (ff_check_interrupt(c->interrupt_callback))
return AVERROR_EXIT;
av_usleep(100*1000);
}
/* Enough time has elapsed since the last reload */
goto reload;
}
ret = open_input(c, v);
if (ret < 0) {
av_log(v->parent, AV_LOG_WARNING, "Failed to open segment of playlist %d\n",
v->index);
return ret;
}
just_opened = 1;
}
ret = read_from_url(v, buf, buf_size, READ_NORMAL);
if (ret > 0) {
if (just_opened && v->is_id3_timestamped != 0) {
/* Intercept ID3 tags here, elementary audio streams are required
* to convey timestamps using them in the beginning of each segment. */
intercept_id3(v, buf, buf_size, &ret);
}
return ret;
}
ffurl_close(v->input);
v->input = NULL;
v->cur_seq_no++;
c->cur_seq_no = v->cur_seq_no;
goto restart;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 17,079 |
ImageMagick | cfd829bd3581b092e0a267b3deba46fa90b9bc88 | static MagickBooleanType WritePALMImage(const ImageInfo *image_info,
Image *image,ExceptionInfo *exception)
{
MagickBooleanType
status;
MagickOffsetType
currentOffset,
offset,
scene;
MagickSizeType
cc;
PixelInfo
transpix;
QuantizeInfo
*quantize_info;
register ssize_t
x;
register const Quantum
*p;
register Quantum
*q;
ssize_t
y;
size_t
count,
bits_per_pixel,
bytes_per_row,
imageListLength,
nextDepthOffset,
one;
unsigned char
bit,
byte,
color,
*last_row,
*one_row,
*ptr,
version;
unsigned int
transparentIndex;
unsigned short
color16,
flags;
/*
Open output image 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);
quantize_info=AcquireQuantizeInfo(image_info);
flags=0;
currentOffset=0;
transparentIndex=0;
transpix.red=0.0;
transpix.green=0.0;
transpix.blue=0.0;
transpix.alpha=0.0;
one=1;
version=0;
scene=0;
imageListLength=GetImageListLength(image);
do
{
(void) TransformImageColorspace(image,sRGBColorspace,exception);
count=GetNumberColors(image,NULL,exception);
for (bits_per_pixel=1; (one << bits_per_pixel) < count; bits_per_pixel*=2) ;
if (bits_per_pixel > 16)
bits_per_pixel=16;
else
if (bits_per_pixel < 16)
(void) TransformImageColorspace(image,image->colorspace,exception);
if (bits_per_pixel < 8)
{
(void) TransformImageColorspace(image,GRAYColorspace,exception);
(void) SetImageType(image,PaletteType,exception);
(void) SortColormapByIntensity(image,exception);
}
if ((image->storage_class == PseudoClass) && (image->colors > 256))
(void) SetImageStorageClass(image,DirectClass,exception);
if (image->storage_class == PseudoClass)
flags|=PALM_HAS_COLORMAP_FLAG;
else
flags|=PALM_IS_DIRECT_COLOR;
(void) WriteBlobMSBShort(image,(unsigned short) image->columns); /* width */
(void) WriteBlobMSBShort(image,(unsigned short) image->rows); /* height */
bytes_per_row=((image->columns+(16/bits_per_pixel-1))/(16/
bits_per_pixel))*2;
(void) WriteBlobMSBShort(image,(unsigned short) bytes_per_row);
if ((image_info->compression == RLECompression) ||
(image_info->compression == FaxCompression))
flags|=PALM_IS_COMPRESSED_FLAG;
(void) WriteBlobMSBShort(image, flags);
(void) WriteBlobByte(image,(unsigned char) bits_per_pixel);
if (bits_per_pixel > 1)
version=1;
if ((image_info->compression == RLECompression) ||
(image_info->compression == FaxCompression))
version=2;
(void) WriteBlobByte(image,version);
(void) WriteBlobMSBShort(image,0); /* nextDepthOffset */
(void) WriteBlobByte(image,(unsigned char) transparentIndex);
if (image_info->compression == RLECompression)
(void) WriteBlobByte(image,PALM_COMPRESSION_RLE);
else
if (image_info->compression == FaxCompression)
(void) WriteBlobByte(image,PALM_COMPRESSION_SCANLINE);
else
(void) WriteBlobByte(image,PALM_COMPRESSION_NONE);
(void) WriteBlobMSBShort(image,0); /* reserved */
offset=16;
if (bits_per_pixel == 16)
{
(void) WriteBlobByte(image,5); /* # of bits of red */
(void) WriteBlobByte(image,6); /* # of bits of green */
(void) WriteBlobByte(image,5); /* # of bits of blue */
(void) WriteBlobByte(image,0); /* reserved by Palm */
(void) WriteBlobMSBLong(image,0); /* no transparent color, YET */
offset+=8;
}
if (bits_per_pixel == 8)
{
if (flags & PALM_HAS_COLORMAP_FLAG) /* Write out colormap */
{
quantize_info->dither_method=IdentifyPaletteImage(image,exception)
== MagickFalse ? RiemersmaDitherMethod : NoDitherMethod;
quantize_info->number_colors=image->colors;
(void) QuantizeImage(quantize_info,image,exception);
(void) WriteBlobMSBShort(image,(unsigned short) image->colors);
for (count = 0; count < image->colors; count++)
{
(void) WriteBlobByte(image,(unsigned char) count);
(void) WriteBlobByte(image,ScaleQuantumToChar(ClampToQuantum(
image->colormap[count].red)));
(void) WriteBlobByte(image,ScaleQuantumToChar(ClampToQuantum(
image->colormap[count].green)));
(void) WriteBlobByte(image,ScaleQuantumToChar(ClampToQuantum(
image->colormap[count].blue)));
}
offset+=2+count*4;
}
else /* Map colors to Palm standard colormap */
{
Image
*affinity_image;
affinity_image=ConstituteImage(256,1,"RGB",CharPixel,&PalmPalette,
exception);
(void) TransformImageColorspace(affinity_image,
affinity_image->colorspace,exception);
(void) RemapImage(quantize_info,image,affinity_image,exception);
for (y=0; y < (ssize_t) image->rows; y++)
{
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelIndex(image,(Quantum) FindColor(&image->colormap[(ssize_t)
GetPixelIndex(image,q)]),q);
q+=GetPixelChannels(image);
}
}
affinity_image=DestroyImage(affinity_image);
}
}
if (flags & PALM_IS_COMPRESSED_FLAG)
(void) WriteBlobMSBShort(image,0); /* fill in size later */
last_row=(unsigned char *) NULL;
if (image_info->compression == FaxCompression)
{
last_row=(unsigned char *) AcquireQuantumMemory(bytes_per_row,
sizeof(*last_row));
if (last_row == (unsigned char *) NULL)
{
quantize_info=DestroyQuantizeInfo(quantize_info);
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
}
}
one_row=(unsigned char *) AcquireQuantumMemory(bytes_per_row,
sizeof(*one_row));
if (one_row == (unsigned char *) NULL)
{
if (last_row != (unsigned char *) NULL)
last_row=(unsigned char *) RelinquishMagickMemory(last_row);
quantize_info=DestroyQuantizeInfo(quantize_info);
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
}
for (y=0; y < (ssize_t) image->rows; y++)
{
ptr=one_row;
(void) memset(ptr,0,bytes_per_row);
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
if (bits_per_pixel == 16)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
color16=(unsigned short) ((((31*(size_t) GetPixelRed(image,p))/
(size_t) QuantumRange) << 11) | (((63*(size_t)
GetPixelGreen(image,p))/(size_t) QuantumRange) << 5) |
((31*(size_t) GetPixelBlue(image,p))/(size_t) QuantumRange));
if (GetPixelAlpha(image,p) == (Quantum) TransparentAlpha)
{
transpix.red=(MagickRealType) GetPixelRed(image,p);
transpix.green=(MagickRealType) GetPixelGreen(image,p);
transpix.blue=(MagickRealType) GetPixelBlue(image,p);
transpix.alpha=(MagickRealType) GetPixelAlpha(image,p);
flags|=PALM_HAS_TRANSPARENCY_FLAG;
}
*ptr++=(unsigned char) ((color16 >> 8) & 0xff);
*ptr++=(unsigned char) (color16 & 0xff);
p+=GetPixelChannels(image);
}
}
else
{
byte=0x00;
bit=(unsigned char) (8-bits_per_pixel);
for (x=0; x < (ssize_t) image->columns; x++)
{
if (bits_per_pixel >= 8)
color=(unsigned char) GetPixelIndex(image,p);
else
color=(unsigned char) (GetPixelIndex(image,p)*
((one << bits_per_pixel)-1)/MagickMax(1*image->colors-1,1));
byte|=color << bit;
if (bit != 0)
bit-=(unsigned char) bits_per_pixel;
else
{
*ptr++=byte;
byte=0x00;
bit=(unsigned char) (8-bits_per_pixel);
}
p+=GetPixelChannels(image);
}
if ((image->columns % (8/bits_per_pixel)) != 0)
*ptr++=byte;
}
if (image_info->compression == RLECompression)
{
x=0;
while (x < (ssize_t) bytes_per_row)
{
byte=one_row[x];
count=1;
while ((one_row[++x] == byte) && (count < 255) &&
(x < (ssize_t) bytes_per_row))
count++;
(void) WriteBlobByte(image,(unsigned char) count);
(void) WriteBlobByte(image,(unsigned char) byte);
}
}
else
if (image_info->compression == FaxCompression)
{
char
tmpbuf[8],
*tptr;
for (x = 0; x < (ssize_t) bytes_per_row; x += 8)
{
tptr = tmpbuf;
for (bit=0, byte=0; bit < (unsigned char) MagickMin(8,(ssize_t) bytes_per_row-x); bit++)
{
if ((y == 0) || (last_row[x + bit] != one_row[x + bit]))
{
byte |= (1 << (7 - bit));
*tptr++ = (char) one_row[x + bit];
}
}
(void) WriteBlobByte(image, byte);
(void) WriteBlob(image,tptr-tmpbuf,(unsigned char *) tmpbuf);
}
(void) memcpy(last_row,one_row,bytes_per_row);
}
else
(void) WriteBlob(image,bytes_per_row,one_row);
}
if (flags & PALM_HAS_TRANSPARENCY_FLAG)
{
offset=SeekBlob(image,currentOffset+6,SEEK_SET);
(void) WriteBlobMSBShort(image,flags);
offset=SeekBlob(image,currentOffset+12,SEEK_SET);
(void) WriteBlobByte(image,(unsigned char) transparentIndex); /* trans index */
}
if (bits_per_pixel == 16)
{
offset=SeekBlob(image,currentOffset+20,SEEK_SET);
(void) WriteBlobByte(image,0); /* reserved by Palm */
(void) WriteBlobByte(image,(unsigned char) ((31*transpix.red)/
QuantumRange));
(void) WriteBlobByte(image,(unsigned char) ((63*transpix.green)/
QuantumRange));
(void) WriteBlobByte(image,(unsigned char) ((31*transpix.blue)/
QuantumRange));
}
if (flags & PALM_IS_COMPRESSED_FLAG) /* fill in size now */
{
offset=SeekBlob(image,currentOffset+offset,SEEK_SET);
(void) WriteBlobMSBShort(image,(unsigned short) (GetBlobSize(image)-
currentOffset-offset));
}
if (one_row != (unsigned char *) NULL)
one_row=(unsigned char *) RelinquishMagickMemory(one_row);
if (last_row != (unsigned char *) NULL)
last_row=(unsigned char *) RelinquishMagickMemory(last_row);
if (GetNextImageInList(image) == (Image *) NULL)
break;
/* padding to 4 byte word */
for (cc=(GetBlobSize(image)) % 4; cc > 0; cc--)
(void) WriteBlobByte(image,0);
/* write nextDepthOffset and return to end of image */
offset=SeekBlob(image,currentOffset+10,SEEK_SET);
nextDepthOffset=(size_t) ((GetBlobSize(image)-currentOffset)/4);
(void) WriteBlobMSBShort(image,(unsigned short) nextDepthOffset);
currentOffset=(MagickOffsetType) GetBlobSize(image);
offset=SeekBlob(image,currentOffset,SEEK_SET);
image=SyncNextImageInList(image);
status=SetImageProgress(image,SaveImagesTag,scene++,imageListLength);
if (status == MagickFalse)
break;
} while (image_info->adjoin != MagickFalse);
quantize_info=DestroyQuantizeInfo(quantize_info);
(void) CloseBlob(image);
return(MagickTrue);
} | 1 | CVE-2020-25665 | 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. | 1,874 |
linux | 48900cb6af4282fa0fb6ff4d72a81aa3dadb5c39 | static void virtnet_netpoll(struct net_device *dev)
{
struct virtnet_info *vi = netdev_priv(dev);
int i;
for (i = 0; i < vi->curr_queue_pairs; i++)
napi_schedule(&vi->rq[i].napi);
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 14,214 |
ntfs-3g | fb28eef6f1c26170566187c1ab7dc913a13ea43c | static void fuse_lib_unlink(fuse_req_t req, fuse_ino_t parent,
const char *name)
{
struct fuse *f = req_fuse_prepare(req);
char *path;
int err;
err = -ENOENT;
pthread_rwlock_wrlock(&f->tree_lock);
path = get_path_name(f, parent, name);
if (path != NULL) {
struct fuse_intr_data d;
if (f->conf.debug)
fprintf(stderr, "UNLINK %s\n", path);
fuse_prepare_interrupt(f, req, &d);
if (!f->conf.hard_remove && is_open(f, parent, name))
err = hide_node(f, path, parent, name);
else {
err = fuse_fs_unlink(f->fs, path);
if (!err)
remove_node(f, parent, name);
}
fuse_finish_interrupt(f, req, &d);
free(path);
}
pthread_rwlock_unlock(&f->tree_lock);
reply_err(req, err);
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 13,773 |
php-src | b585a3aed7880a5fa5c18e2b838fc96f40e075bd | static inline int process_nested_data(UNSERIALIZE_PARAMETER, HashTable *ht, long elements, int objprops)
{
while (elements-- > 0) {
zval *key, *data, **old_data;
ALLOC_INIT_ZVAL(key);
if (!php_var_unserialize(&key, p, max, NULL TSRMLS_CC)) {
zval_dtor(key);
FREE_ZVAL(key);
return 0;
}
if (Z_TYPE_P(key) != IS_LONG && Z_TYPE_P(key) != IS_STRING) {
zval_dtor(key);
FREE_ZVAL(key);
return 0;
}
ALLOC_INIT_ZVAL(data);
if (!php_var_unserialize(&data, p, max, var_hash TSRMLS_CC)) {
zval_dtor(key);
FREE_ZVAL(key);
zval_dtor(data);
FREE_ZVAL(data);
return 0;
}
if (!objprops) {
switch (Z_TYPE_P(key)) {
case IS_LONG:
if (zend_hash_index_find(ht, Z_LVAL_P(key), (void **)&old_data)==SUCCESS) {
var_push_dtor(var_hash, old_data);
}
zend_hash_index_update(ht, Z_LVAL_P(key), &data, sizeof(data), NULL);
break;
case IS_STRING:
if (zend_symtable_find(ht, Z_STRVAL_P(key), Z_STRLEN_P(key) + 1, (void **)&old_data)==SUCCESS) {
var_push_dtor(var_hash, old_data);
}
zend_symtable_update(ht, Z_STRVAL_P(key), Z_STRLEN_P(key) + 1, &data, sizeof(data), NULL);
break;
}
} else {
/* object properties should include no integers */
convert_to_string(key);
if (zend_hash_find(ht, Z_STRVAL_P(key), Z_STRLEN_P(key) + 1, (void **)&old_data)==SUCCESS) {
var_push_dtor(var_hash, old_data);
}
zend_hash_update(ht, Z_STRVAL_P(key), Z_STRLEN_P(key) + 1, &data,
sizeof data, NULL);
}
zval_dtor(key);
FREE_ZVAL(key);
if (elements && *(*p-1) != ';' && *(*p-1) != '}') {
(*p)--;
return 0;
}
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 23,871 |
net | 85f1bd9a7b5a79d5baa8bf44af19658f7bf77bfa | int ip_local_out(struct net *net, struct sock *sk, struct sk_buff *skb)
{
int err;
err = __ip_local_out(net, sk, skb);
if (likely(err == 1))
err = dst_output(net, sk, skb);
return err;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 10,738 |
ImageMagick | e88532bd4418e95b70cbc415fe911d22ab27a5fd | static inline Quantum ScaleLongToQuantum(const unsigned int value)
{
return((Quantum) (4294967297.0*value));
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 18,898 |
hhvm | b3679121bb3c7017ff04b4c08402ffff5cf59b13 | void append(char c) {
assertx(p < end);
*p++ = c;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 15,257 |
ghostpdl | 961b10cdd71403072fb99401a45f3bef6ce53626 | xps_decode_font_char_imp(xps_font_t *font, int code)
{
byte *table;
/* no cmap selected: return identity */
if (font->cmapsubtable <= 0)
return code;
table = font->data + font->cmapsubtable;
switch (u16(table))
{
case 0: /* Apple standard 1-to-1 mapping. */
{
int i, length = u16(&table[2]) - 6;
if (length < 0 || length > 256)
return gs_error_invalidfont;
for (i=0;i<length;i++) {
if (table[6 + i] == code)
return i;
}
}
return 0;
case 4: /* Microsoft/Adobe segmented mapping. */
{
int segCount2 = u16(table + 6);
byte *endCount = table + 14;
byte *startCount = endCount + segCount2 + 2;
byte *idDelta = startCount + segCount2;
byte *idRangeOffset = idDelta + segCount2;
byte *giddata;
int i2;
if (segCount2 < 3 || segCount2 > 65535 ||
idRangeOffset > font->data + font->length)
return gs_error_invalidfont;
for (i2 = 0; i2 < segCount2 - 3; i2 += 2)
{
int delta = s16(idDelta + i2), roff = s16(idRangeOffset + i2);
int start = u16(startCount + i2);
int end = u16(endCount + i2);
int glyph, i;
if (end < start)
return gs_error_invalidfont;
for (i=start;i<=end;i++) {
if (roff == 0) {
glyph = (i + delta) & 0xffff;
} else {
if ((giddata = (idRangeOffset + i2 + roff + ((i - start) << 1))) >
font->data + font->length) {
return_error(gs_error_invalidfont);
}
glyph = u16(giddata);
}
if (glyph == code) {
return i;
}
}
}
}
return 0;
case 6: /* Single interval lookup. */
{
int ch, i, length = u16(&table[8]);
int firstCode = u16(&table[6]);
if (length < 0 || length > 65535)
return gs_error_invalidfont;
for (i=0;i<length;i++) {
ch = u16(&table[10 + (i * 2)]);
if (ch == code)
return (firstCode + i);
}
}
return 0;
case 10: /* Trimmed array (like 6) */
{
unsigned int ch, i, length = u32(&table[20]);
int firstCode = u32(&table[16]);
for (i=0;i<length;i++) {
ch = u16(&table[10 + (i * 2)]);
if (ch == code)
return (firstCode + i);
}
}
return 0;
case 12: /* Segmented coverage. (like 4) */
{
unsigned int nGroups = u32(&table[12]);
int Group;
for (Group=0;Group<nGroups;Group++)
{
int startCharCode = u32(&table[16 + (Group * 12)]);
int endCharCode = u32(&table[16 + (Group * 12) + 4]);
int startGlyphCode = u32(&table[16 + (Group * 12) + 8]);
if (code >= startGlyphCode && code <= (startGlyphCode + (endCharCode - startCharCode))) {
return startGlyphCode + (code - startCharCode);
}
}
}
return 0;
case 2: /* High-byte mapping through table. */
case 8: /* Mixed 16-bit and 32-bit coverage (like 2) */
default:
gs_warn1("unknown cmap format: %d\n", u16(table));
return 0;
}
return 0;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 15,209 |
Chrome | dcd538eb3daf6c52d3ebef0a7afea758f6c657c8 | void Compositor::OnFirstSurfaceActivation(
const viz::SurfaceInfo& surface_info) {
}
| 1 | CVE-2016-1661 | 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,389 |
Chrome | 33827275411b33371e7bb750cce20f11de85002d | void SelectionController::SendContextMenuEvent(
const MouseEventWithHitTestResults& mev,
const LayoutPoint& position) {
if (!Selection().IsAvailable())
return;
if (Selection().Contains(position) || mev.GetScrollbar() ||
!(Selection()
.ComputeVisibleSelectionInDOMTreeDeprecated()
.IsContentEditable() ||
(mev.InnerNode() && mev.InnerNode()->IsTextNode())))
return;
AutoReset<bool> mouse_down_may_start_select_change(
&mouse_down_may_start_select_, true);
if (mev.Event().menu_source_type != kMenuSourceTouchHandle &&
HitTestResultIsMisspelled(mev.GetHitTestResult()))
return SelectClosestMisspellingFromMouseEvent(mev);
if (!frame_->GetEditor().Behavior().ShouldSelectOnContextualMenuClick())
return;
SelectClosestWordOrLinkFromMouseEvent(mev);
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 11,149 |
gpac | 96047e0e6166407c40cc19f4e94fb35cd7624391 | const GF_FilterRegister *xviddec_register(GF_FilterSession *session)
{
#if !defined(GPAC_DISABLE_AV_PARSERS) && defined(GPAC_HAS_XVID)
return &XVIDRegister;
#else
return NULL;
#endif
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 21,175 |
Android | 37c88107679d36c419572732b4af6e18bb2f7dce | static int enable(void) {
LOG_INFO("%s", __func__);
if (!interface_ready())
return BT_STATUS_NOT_READY;
stack_manager_get_interface()->start_up_stack_async();
return BT_STATUS_SUCCESS;
}
| 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. | 6,524 |
FFmpeg | c953baa084607dd1d84c3bfcce3cf6a87c3e6e05 | static int mov_read_dops(MOVContext *c, AVIOContext *pb, MOVAtom atom)
{
const int OPUS_SEEK_PREROLL_MS = 80;
int ret;
AVStream *st;
size_t size;
uint16_t pre_skip;
if (c->fc->nb_streams < 1)
return 0;
st = c->fc->streams[c->fc->nb_streams-1];
if ((uint64_t)atom.size > (1<<30) || atom.size < 11)
return AVERROR_INVALIDDATA;
/* Check OpusSpecificBox version. */
if (avio_r8(pb) != 0) {
av_log(c->fc, AV_LOG_ERROR, "unsupported OpusSpecificBox version\n");
return AVERROR_INVALIDDATA;
}
/* OpusSpecificBox size plus magic for Ogg OpusHead header. */
size = atom.size + 8;
if ((ret = ff_alloc_extradata(st->codecpar, size)) < 0)
return ret;
AV_WL32(st->codecpar->extradata, MKTAG('O','p','u','s'));
AV_WL32(st->codecpar->extradata + 4, MKTAG('H','e','a','d'));
AV_WB8(st->codecpar->extradata + 8, 1); /* OpusHead version */
avio_read(pb, st->codecpar->extradata + 9, size - 9);
/* OpusSpecificBox is stored in big-endian, but OpusHead is
little-endian; aside from the preceeding magic and version they're
otherwise currently identical. Data after output gain at offset 16
doesn't need to be bytewapped. */
pre_skip = AV_RB16(st->codecpar->extradata + 10);
AV_WL16(st->codecpar->extradata + 10, pre_skip);
AV_WL32(st->codecpar->extradata + 12, AV_RB32(st->codecpar->extradata + 12));
AV_WL16(st->codecpar->extradata + 16, AV_RB16(st->codecpar->extradata + 16));
st->codecpar->initial_padding = pre_skip;
st->codecpar->seek_preroll = av_rescale_q(OPUS_SEEK_PREROLL_MS,
(AVRational){1, 1000},
(AVRational){1, 48000});
return 0;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 11,166 |
radare2 | 9d348bcc2c4bbd3805e7eec97b594be9febbdf9a | static int set_reg_profile(RAnal *anal) {
const char *p =
"=PC pcl\n"
"=SP sp\n"
"=A0 r25\n"
"=A1 r24\n"
"=A2 r23\n"
"=A3 r22\n"
"=R0 r24\n"
#if 0
PC: 16- or 22-bit program counter
SP: 8- or 16-bit stack pointer
SREG: 8-bit status register
RAMPX, RAMPY, RAMPZ, RAMPD and EIND:
#endif
"gpr r0 .8 0 0\n"
"gpr r1 .8 1 0\n"
"gpr r2 .8 2 0\n"
"gpr r3 .8 3 0\n"
"gpr r4 .8 4 0\n"
"gpr r5 .8 5 0\n"
"gpr r6 .8 6 0\n"
"gpr r7 .8 7 0\n"
"gpr text .64 0 0\n"
"gpr r8 .8 8 0\n"
"gpr r9 .8 9 0\n"
"gpr r10 .8 10 0\n"
"gpr r11 .8 11 0\n"
"gpr r12 .8 12 0\n"
"gpr r13 .8 13 0\n"
"gpr r14 .8 14 0\n"
"gpr r15 .8 15 0\n"
"gpr deskey .64 8 0\n"
"gpr r16 .8 16 0\n"
"gpr r17 .8 17 0\n"
"gpr r18 .8 18 0\n"
"gpr r19 .8 19 0\n"
"gpr r20 .8 20 0\n"
"gpr r21 .8 21 0\n"
"gpr r22 .8 22 0\n"
"gpr r23 .8 23 0\n"
"gpr r24 .8 24 0\n"
"gpr r25 .8 25 0\n"
"gpr r26 .8 26 0\n"
"gpr r27 .8 27 0\n"
"gpr r28 .8 28 0\n"
"gpr r29 .8 29 0\n"
"gpr r30 .8 30 0\n"
"gpr r31 .8 31 0\n"
"gpr r17:r16 .16 16 0\n"
"gpr r19:r18 .16 18 0\n"
"gpr r21:r20 .16 20 0\n"
"gpr r23:r22 .16 22 0\n"
"gpr r25:r24 .16 24 0\n"
"gpr r27:r26 .16 26 0\n"
"gpr r29:r28 .16 28 0\n"
"gpr r31:r30 .16 30 0\n"
"gpr x .16 26 0\n"
"gpr y .16 28 0\n"
"gpr z .16 30 0\n"
"gpr pc .32 32 0\n"
"gpr pcl .16 32 0\n"
"gpr pch .16 34 0\n"
"gpr sp .16 36 0\n"
"gpr spl .8 36 0\n"
"gpr sph .8 37 0\n"
"gpr sreg .8 38 0\n"
"gpr cf .1 38.0 0\n" // Carry. This is a borrow flag on subtracts.
"gpr zf .1 38.1 0\n" // Zero. Set to 1 when an arithmetic result is zero.
"gpr nf .1 38.2 0\n" // Negative. Set to a copy of the most significant bit of an arithmetic result.
"gpr vf .1 38.3 0\n" // Overflow flag. Set in case of two's complement overflow.
"gpr sf .1 38.4 0\n" // Sign flag. Unique to AVR, this is always (N ^ V) (xor), and shows the true sign of a comparison.
"gpr hf .1 38.5 0\n" // Half carry. This is an internal carry from additions and is used to support BCD arithmetic.
"gpr tf .1 38.6 0\n" // Bit copy. Special bit load and bit store instructions use this bit.
"gpr if .1 38.7 0\n" // Interrupt flag. Set when interrupts are enabled.
"gpr rampx .8 39 0\n"
"gpr rampy .8 40 0\n"
"gpr rampz .8 41 0\n"
"gpr rampd .8 42 0\n"
"gpr eind .8 43 0\n"
"gpr _prog .32 44 0\n"
"gpr _page .32 48 0\n"
"gpr _eeprom .32 52 0\n"
"gpr _ram .32 56 0\n"
"gpr _io .32 56 0\n"
"gpr _sram .32 60 0\n"
"gpr spmcsr .8 64 0\n"
;
return r_reg_set_profile_string (anal->reg, p);
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 14,308 |
Subsets and Splits