instruction
stringclasses
1 value
input
stringlengths
93
3.53k
output
stringlengths
16
15.4k
__index_level_0__
int64
165k
175k
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: cJSON *cJSON_CreateBool( int b ) { cJSON *item = cJSON_New_Item(); if ( item ) item->type = b ? cJSON_True : cJSON_False; return item; } Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a malformed JSON string was passed on the control channel. This issue, present in the cJSON library, was already fixed upstream, so was addressed here in iperf3 by importing a newer version of cJSON (plus local ESnet modifications). Discovered and reported by Dave McDaniel, Cisco Talos. Based on a patch by @dopheide-esnet, with input from @DaveGamble. Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001, CVE-2016-4303 (cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40) Signed-off-by: Bruce A. Mah <[email protected]> CWE ID: CWE-119
cJSON *cJSON_CreateBool( int b )
167,270
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: StorageHandler::StorageHandler() : DevToolsDomainHandler(Storage::Metainfo::domainName), process_(nullptr), weak_ptr_factory_(this) {} Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable This keeps BrowserContext* and StoragePartition* instead of RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost upon closure of DevTools front-end. Bug: 801117, 783067, 780694 Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b Reviewed-on: https://chromium-review.googlesource.com/876657 Commit-Queue: Andrey Kosyakov <[email protected]> Reviewed-by: Dmitry Gozman <[email protected]> Cr-Commit-Position: refs/heads/master@{#531157} CWE ID: CWE-20
StorageHandler::StorageHandler() : DevToolsDomainHandler(Storage::Metainfo::domainName), storage_partition_(nullptr), weak_ptr_factory_(this) {}
172,775
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static int uhid_write(int fd, const struct uhid_event *ev) { ssize_t ret = write(fd, ev, sizeof(*ev)); if (ret < 0){ int rtn = -errno; APPL_TRACE_ERROR("%s: Cannot write to uhid:%s", __FUNCTION__, strerror(errno)); return rtn; } else if (ret != (ssize_t)sizeof(*ev)) { APPL_TRACE_ERROR("%s: Wrong size written to uhid: %zd != %zu", __FUNCTION__, ret, sizeof(*ev)); return -EFAULT; } return 0; } Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process Bug: 28885210 Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360 Conflicts: btif/co/bta_hh_co.c btif/src/btif_core.c Merge conflict resolution of ag/1161415 (referencing ag/1164670) - Directly into mnc-mr2-release CWE ID: CWE-284
static int uhid_write(int fd, const struct uhid_event *ev) { ssize_t ret = TEMP_FAILURE_RETRY(write(fd, ev, sizeof(*ev))); if (ret < 0){ int rtn = -errno; APPL_TRACE_ERROR("%s: Cannot write to uhid:%s", __FUNCTION__, strerror(errno)); return rtn; } else if (ret != (ssize_t)sizeof(*ev)) { APPL_TRACE_ERROR("%s: Wrong size written to uhid: %zd != %zu", __FUNCTION__, ret, sizeof(*ev)); return -EFAULT; } return 0; }
173,433
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: INST_HANDLER (cpse) { // CPSE Rd, Rr int r = (buf[0] & 0xf) | ((buf[1] & 0x2) << 3); int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x1) << 4); RAnalOp next_op; avr_op_analyze (anal, &next_op, op->addr + op->size, buf + op->size, len - op->size, cpu); r_strbuf_fini (&next_op.esil); op->jump = op->addr + next_op.size + 2; op->cycles = 1; // XXX: This is a bug, because depends on eval state, ESIL_A ("r%d,r%d,^,!,", r, d); // Rr == Rd ESIL_A ("?{,%"PFMT64d",pc,=,},", op->jump); // ?true => jmp } Commit Message: Fix #9943 - Invalid free on RAnal.avr CWE ID: CWE-416
INST_HANDLER (cpse) { // CPSE Rd, Rr int r = (buf[0] & 0xf) | ((buf[1] & 0x2) << 3); int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x1) << 4); RAnalOp next_op = {0}; avr_op_analyze (anal, &next_op, op->addr + op->size, buf + op->size, len - op->size, cpu); r_strbuf_fini (&next_op.esil); op->jump = op->addr + next_op.size + 2; op->cycles = 1; // XXX: This is a bug, because depends on eval state, ESIL_A ("r%d,r%d,^,!,", r, d); // Rr == Rd ESIL_A ("?{,%"PFMT64d",pc,=,},", op->jump); // ?true => jmp }
169,222
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static int vrend_decode_create_ve(struct vrend_decode_ctx *ctx, uint32_t handle, uint16_t length) { struct pipe_vertex_element *ve = NULL; int num_elements; int i; int ret; if (length < 1) return EINVAL; if ((length - 1) % 4) return EINVAL; num_elements = (length - 1) / 4; if (num_elements) { ve = calloc(num_elements, sizeof(struct pipe_vertex_element)); if (!ve) return ENOMEM; for (i = 0; i < num_elements; i++) { ve[i].src_offset = get_buf_entry(ctx, VIRGL_OBJ_VERTEX_ELEMENTS_V0_SRC_OFFSET(i)); ve[i].instance_divisor = get_buf_entry(ctx, VIRGL_OBJ_VERTEX_ELEMENTS_V0_INSTANCE_DIVISOR(i)); ve[i].vertex_buffer_index = get_buf_entry(ctx, VIRGL_OBJ_VERTEX_ELEMENTS_V0_VERTEX_BUFFER_INDEX(i)); ve[i].src_format = get_buf_entry(ctx, VIRGL_OBJ_VERTEX_ELEMENTS_V0_SRC_FORMAT(i)); } } return ret; } Commit Message: CWE ID: CWE-125
static int vrend_decode_create_ve(struct vrend_decode_ctx *ctx, uint32_t handle, uint16_t length) { struct pipe_vertex_element *ve = NULL; int num_elements; int i; int ret; if (length < 1) return EINVAL; if ((length - 1) % 4) return EINVAL; num_elements = (length - 1) / 4; if (num_elements) { ve = calloc(num_elements, sizeof(struct pipe_vertex_element)); if (!ve) return ENOMEM; for (i = 0; i < num_elements; i++) { ve[i].src_offset = get_buf_entry(ctx, VIRGL_OBJ_VERTEX_ELEMENTS_V0_SRC_OFFSET(i)); ve[i].instance_divisor = get_buf_entry(ctx, VIRGL_OBJ_VERTEX_ELEMENTS_V0_INSTANCE_DIVISOR(i)); ve[i].vertex_buffer_index = get_buf_entry(ctx, VIRGL_OBJ_VERTEX_ELEMENTS_V0_VERTEX_BUFFER_INDEX(i)); if (ve[i].vertex_buffer_index >= PIPE_MAX_ATTRIBS) return EINVAL; ve[i].src_format = get_buf_entry(ctx, VIRGL_OBJ_VERTEX_ELEMENTS_V0_SRC_FORMAT(i)); } } return ret; }
164,957
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: bool FrameSelection::SetSelectionDeprecated( const SelectionInDOMTree& passed_selection, const SetSelectionData& options) { DCHECK(IsAvailable()); passed_selection.AssertValidFor(GetDocument()); SelectionInDOMTree::Builder builder(passed_selection); if (ShouldAlwaysUseDirectionalSelection(frame_)) builder.SetIsDirectional(true); SelectionInDOMTree new_selection = builder.Build(); if (granularity_strategy_ && !options.DoNotClearStrategy()) granularity_strategy_->Clear(); granularity_ = options.Granularity(); if (options.ShouldCloseTyping()) TypingCommand::CloseTyping(frame_); if (options.ShouldClearTypingStyle()) frame_->GetEditor().ClearTypingStyle(); const SelectionInDOMTree old_selection_in_dom_tree = selection_editor_->GetSelectionInDOMTree(); if (old_selection_in_dom_tree == new_selection) return false; selection_editor_->SetSelection(new_selection); ScheduleVisualUpdateForPaintInvalidationIfNeeded(); const Document& current_document = GetDocument(); frame_->GetEditor().RespondToChangedSelection( old_selection_in_dom_tree.ComputeStartPosition(), options.ShouldCloseTyping() ? TypingContinuation::kEnd : TypingContinuation::kContinue); DCHECK_EQ(current_document, GetDocument()); return true; } Commit Message: Move SelectionTemplate::is_handle_visible_ to FrameSelection This patch moves |is_handle_visible_| to |FrameSelection| from |SelectionTemplate| since handle visibility is used only for setting |FrameSelection|, hence it is a redundant member variable of |SelectionTemplate|. Bug: 742093 Change-Id: I3add4da3844fb40be34dcb4d4b46b5fa6fed1d7e Reviewed-on: https://chromium-review.googlesource.com/595389 Commit-Queue: Yoshifumi Inoue <[email protected]> Reviewed-by: Xiaocheng Hu <[email protected]> Reviewed-by: Kent Tamura <[email protected]> Cr-Commit-Position: refs/heads/master@{#491660} CWE ID: CWE-119
bool FrameSelection::SetSelectionDeprecated( const SelectionInDOMTree& passed_selection, const SetSelectionData& options) { DCHECK(IsAvailable()); passed_selection.AssertValidFor(GetDocument()); SelectionInDOMTree::Builder builder(passed_selection); if (ShouldAlwaysUseDirectionalSelection(frame_)) builder.SetIsDirectional(true); SelectionInDOMTree new_selection = builder.Build(); if (granularity_strategy_ && !options.DoNotClearStrategy()) granularity_strategy_->Clear(); granularity_ = options.Granularity(); if (options.ShouldCloseTyping()) TypingCommand::CloseTyping(frame_); if (options.ShouldClearTypingStyle()) frame_->GetEditor().ClearTypingStyle(); const SelectionInDOMTree old_selection_in_dom_tree = selection_editor_->GetSelectionInDOMTree(); const bool is_changed = old_selection_in_dom_tree != new_selection; const bool should_show_handle = options.ShouldShowHandle(); if (!is_changed && is_handle_visible_ == should_show_handle) return false; if (is_changed) selection_editor_->SetSelection(new_selection); is_handle_visible_ = should_show_handle; ScheduleVisualUpdateForPaintInvalidationIfNeeded(); const Document& current_document = GetDocument(); frame_->GetEditor().RespondToChangedSelection( old_selection_in_dom_tree.ComputeStartPosition(), options.ShouldCloseTyping() ? TypingContinuation::kEnd : TypingContinuation::kContinue); DCHECK_EQ(current_document, GetDocument()); return true; }
171,760
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: kg_unseal_iov(OM_uint32 *minor_status, gss_ctx_id_t context_handle, int *conf_state, gss_qop_t *qop_state, gss_iov_buffer_desc *iov, int iov_count, int toktype) { krb5_gss_ctx_id_rec *ctx; OM_uint32 code; ctx = (krb5_gss_ctx_id_rec *)context_handle; if (!ctx->established) { *minor_status = KG_CTX_INCOMPLETE; return GSS_S_NO_CONTEXT; } if (kg_locate_iov(iov, iov_count, GSS_IOV_BUFFER_TYPE_STREAM) != NULL) { code = kg_unseal_stream_iov(minor_status, ctx, conf_state, qop_state, iov, iov_count, toktype); } else { code = kg_unseal_iov_token(minor_status, ctx, conf_state, qop_state, iov, iov_count, toktype); } return code; } Commit Message: Fix gss_process_context_token() [CVE-2014-5352] [MITKRB5-SA-2015-001] The krb5 gss_process_context_token() should not actually delete the context; that leaves the caller with a dangling pointer and no way to know that it is invalid. Instead, mark the context as terminated, and check for terminated contexts in the GSS functions which expect established contexts. Also add checks in export_sec_context and pseudo_random, and adjust t_prf.c for the pseudo_random check. ticket: 8055 (new) target_version: 1.13.1 tags: pullup CWE ID:
kg_unseal_iov(OM_uint32 *minor_status, gss_ctx_id_t context_handle, int *conf_state, gss_qop_t *qop_state, gss_iov_buffer_desc *iov, int iov_count, int toktype) { krb5_gss_ctx_id_rec *ctx; OM_uint32 code; ctx = (krb5_gss_ctx_id_rec *)context_handle; if (ctx->terminated || !ctx->established) { *minor_status = KG_CTX_INCOMPLETE; return GSS_S_NO_CONTEXT; } if (kg_locate_iov(iov, iov_count, GSS_IOV_BUFFER_TYPE_STREAM) != NULL) { code = kg_unseal_stream_iov(minor_status, ctx, conf_state, qop_state, iov, iov_count, toktype); } else { code = kg_unseal_iov_token(minor_status, ctx, conf_state, qop_state, iov, iov_count, toktype); } return code; }
166,820
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static int asn1_d2i_ex_primitive(ASN1_VALUE **pval, static int asn1_template_ex_d2i(ASN1_VALUE **pval, const unsigned char **in, long len, const ASN1_TEMPLATE *tt, char opt, ASN1_TLC *ctx); static int asn1_template_noexp_d2i(ASN1_VALUE **val, const unsigned char **in, long len, const ASN1_TEMPLATE *tt, char opt, ASN1_TLC *ctx); static int asn1_d2i_ex_primitive(ASN1_VALUE **pval, const unsigned char **in, long len, const ASN1_ITEM *it, /* tags 4- 7 */ B_ASN1_OCTET_STRING, 0, 0, B_ASN1_UNKNOWN, /* tags 8-11 */ B_ASN1_UNKNOWN, B_ASN1_UNKNOWN, B_ASN1_UNKNOWN, B_ASN1_UNKNOWN, /* tags 12-15 */ B_ASN1_UTF8STRING, B_ASN1_UNKNOWN, B_ASN1_UNKNOWN, B_ASN1_UNKNOWN, /* tags 16-19 */ B_ASN1_SEQUENCE, 0, B_ASN1_NUMERICSTRING, B_ASN1_PRINTABLESTRING, /* tags 20-22 */ B_ASN1_T61STRING, B_ASN1_VIDEOTEXSTRING, B_ASN1_IA5STRING, /* tags 23-24 */ B_ASN1_UTCTIME, B_ASN1_GENERALIZEDTIME, /* tags 25-27 */ B_ASN1_GRAPHICSTRING, B_ASN1_ISO64STRING, B_ASN1_GENERALSTRING, /* tags 28-31 */ B_ASN1_UNIVERSALSTRING, B_ASN1_UNKNOWN, B_ASN1_BMPSTRING, B_ASN1_UNKNOWN, }; unsigned long ASN1_tag2bit(int tag) { Commit Message: CWE ID: CWE-400
static int asn1_d2i_ex_primitive(ASN1_VALUE **pval, static int asn1_template_ex_d2i(ASN1_VALUE **pval, const unsigned char **in, long len, const ASN1_TEMPLATE *tt, char opt, ASN1_TLC *ctx, int depth); static int asn1_template_noexp_d2i(ASN1_VALUE **val, const unsigned char **in, long len, const ASN1_TEMPLATE *tt, char opt, ASN1_TLC *ctx, int depth); static int asn1_d2i_ex_primitive(ASN1_VALUE **pval, const unsigned char **in, long len, const ASN1_ITEM *it, /* tags 4- 7 */ B_ASN1_OCTET_STRING, 0, 0, B_ASN1_UNKNOWN, /* tags 8-11 */ B_ASN1_UNKNOWN, B_ASN1_UNKNOWN, B_ASN1_UNKNOWN, B_ASN1_UNKNOWN, /* tags 12-15 */ B_ASN1_UTF8STRING, B_ASN1_UNKNOWN, B_ASN1_UNKNOWN, B_ASN1_UNKNOWN, /* tags 16-19 */ B_ASN1_SEQUENCE, 0, B_ASN1_NUMERICSTRING, B_ASN1_PRINTABLESTRING, /* tags 20-22 */ B_ASN1_T61STRING, B_ASN1_VIDEOTEXSTRING, B_ASN1_IA5STRING, /* tags 23-24 */ B_ASN1_UTCTIME, B_ASN1_GENERALIZEDTIME, /* tags 25-27 */ B_ASN1_GRAPHICSTRING, B_ASN1_ISO64STRING, B_ASN1_GENERALSTRING, /* tags 28-31 */ B_ASN1_UNIVERSALSTRING, B_ASN1_UNKNOWN, B_ASN1_BMPSTRING, B_ASN1_UNKNOWN, }; unsigned long ASN1_tag2bit(int tag) {
165,326
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: uint8_t* output() const { return output_ + BorderTop() * kOuterBlockSize + BorderLeft(); } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119
uint8_t* output() const { uint8_t *output() const { #if CONFIG_VP9_HIGHBITDEPTH if (UUT_->use_highbd_ == 0) { return output_ + BorderTop() * kOuterBlockSize + BorderLeft(); } else { return CONVERT_TO_BYTEPTR(output16_ + BorderTop() * kOuterBlockSize + BorderLeft()); } #else return output_ + BorderTop() * kOuterBlockSize + BorderLeft(); #endif } uint8_t *output_ref() const { #if CONFIG_VP9_HIGHBITDEPTH if (UUT_->use_highbd_ == 0) { return output_ref_ + BorderTop() * kOuterBlockSize + BorderLeft(); } else { return CONVERT_TO_BYTEPTR(output16_ref_ + BorderTop() * kOuterBlockSize + BorderLeft()); } #else return output_ref_ + BorderTop() * kOuterBlockSize + BorderLeft(); #endif } uint16_t lookup(uint8_t *list, int index) const { #if CONFIG_VP9_HIGHBITDEPTH if (UUT_->use_highbd_ == 0) { return list[index]; } else { return CONVERT_TO_SHORTPTR(list)[index]; } #else return list[index]; #endif } void assign_val(uint8_t *list, int index, uint16_t val) const { #if CONFIG_VP9_HIGHBITDEPTH if (UUT_->use_highbd_ == 0) { list[index] = (uint8_t) val; } else { CONVERT_TO_SHORTPTR(list)[index] = val; } #else list[index] = (uint8_t) val; #endif } void wrapper_filter_average_block2d_8_c(const uint8_t *src_ptr, const unsigned int src_stride, const int16_t *HFilter, const int16_t *VFilter, uint8_t *dst_ptr, unsigned int dst_stride, unsigned int output_width, unsigned int output_height) { #if CONFIG_VP9_HIGHBITDEPTH if (UUT_->use_highbd_ == 0) { filter_average_block2d_8_c(src_ptr, src_stride, HFilter, VFilter, dst_ptr, dst_stride, output_width, output_height); } else { highbd_filter_average_block2d_8_c(CONVERT_TO_SHORTPTR(src_ptr), src_stride, HFilter, VFilter, CONVERT_TO_SHORTPTR(dst_ptr), dst_stride, output_width, output_height, UUT_->use_highbd_); } #else filter_average_block2d_8_c(src_ptr, src_stride, HFilter, VFilter, dst_ptr, dst_stride, output_width, output_height); #endif } void wrapper_filter_block2d_8_c(const uint8_t *src_ptr, const unsigned int src_stride, const int16_t *HFilter, const int16_t *VFilter, uint8_t *dst_ptr, unsigned int dst_stride, unsigned int output_width, unsigned int output_height) { #if CONFIG_VP9_HIGHBITDEPTH if (UUT_->use_highbd_ == 0) { filter_block2d_8_c(src_ptr, src_stride, HFilter, VFilter, dst_ptr, dst_stride, output_width, output_height); } else { highbd_filter_block2d_8_c(CONVERT_TO_SHORTPTR(src_ptr), src_stride, HFilter, VFilter, CONVERT_TO_SHORTPTR(dst_ptr), dst_stride, output_width, output_height, UUT_->use_highbd_); } #else filter_block2d_8_c(src_ptr, src_stride, HFilter, VFilter, dst_ptr, dst_stride, output_width, output_height); #endif }
174,511
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: status_t OMXNodeInstance::enableNativeBuffers( OMX_U32 portIndex, OMX_BOOL graphic, OMX_BOOL enable) { Mutex::Autolock autoLock(mLock); CLOG_CONFIG(enableNativeBuffers, "%s:%u%s, %d", portString(portIndex), portIndex, graphic ? ", graphic" : "", enable); OMX_STRING name = const_cast<OMX_STRING>( graphic ? "OMX.google.android.index.enableAndroidNativeBuffers" : "OMX.google.android.index.allocateNativeHandle"); OMX_INDEXTYPE index; OMX_ERRORTYPE err = OMX_GetExtensionIndex(mHandle, name, &index); if (err == OMX_ErrorNone) { EnableAndroidNativeBuffersParams params; InitOMXParams(&params); params.nPortIndex = portIndex; params.enable = enable; err = OMX_SetParameter(mHandle, index, &params); CLOG_IF_ERROR(setParameter, err, "%s(%#x): %s:%u en=%d", name, index, portString(portIndex), portIndex, enable); if (!graphic) { if (err == OMX_ErrorNone) { mSecureBufferType[portIndex] = enable ? kSecureBufferTypeNativeHandle : kSecureBufferTypeOpaque; } else if (mSecureBufferType[portIndex] == kSecureBufferTypeUnknown) { mSecureBufferType[portIndex] = kSecureBufferTypeOpaque; } } } else { CLOG_ERROR_IF(enable, getExtensionIndex, err, "%s", name); if (!graphic) { char value[PROPERTY_VALUE_MAX]; if (property_get("media.mediadrmservice.enable", value, NULL) && (!strcmp("1", value) || !strcasecmp("true", value))) { CLOG_CONFIG(enableNativeBuffers, "system property override: using native-handles"); mSecureBufferType[portIndex] = kSecureBufferTypeNativeHandle; } else if (mSecureBufferType[portIndex] == kSecureBufferTypeUnknown) { mSecureBufferType[portIndex] = kSecureBufferTypeOpaque; } err = OMX_ErrorNone; } } return StatusFromOMXError(err); } Commit Message: OMXNodeInstance: sanity check portIndex. Bug: 31385713 Change-Id: Ib91d00eb5cc8c51c84d37f5d36d6b7ca594d201f (cherry picked from commit f80a1f5075a7c6e1982d37c68bfed7c9a611bb20) CWE ID: CWE-264
status_t OMXNodeInstance::enableNativeBuffers( OMX_U32 portIndex, OMX_BOOL graphic, OMX_BOOL enable) { if (portIndex >= NELEM(mSecureBufferType)) { ALOGE("b/31385713, portIndex(%u)", portIndex); android_errorWriteLog(0x534e4554, "31385713"); return BAD_VALUE; } Mutex::Autolock autoLock(mLock); CLOG_CONFIG(enableNativeBuffers, "%s:%u%s, %d", portString(portIndex), portIndex, graphic ? ", graphic" : "", enable); OMX_STRING name = const_cast<OMX_STRING>( graphic ? "OMX.google.android.index.enableAndroidNativeBuffers" : "OMX.google.android.index.allocateNativeHandle"); OMX_INDEXTYPE index; OMX_ERRORTYPE err = OMX_GetExtensionIndex(mHandle, name, &index); if (err == OMX_ErrorNone) { EnableAndroidNativeBuffersParams params; InitOMXParams(&params); params.nPortIndex = portIndex; params.enable = enable; err = OMX_SetParameter(mHandle, index, &params); CLOG_IF_ERROR(setParameter, err, "%s(%#x): %s:%u en=%d", name, index, portString(portIndex), portIndex, enable); if (!graphic) { if (err == OMX_ErrorNone) { mSecureBufferType[portIndex] = enable ? kSecureBufferTypeNativeHandle : kSecureBufferTypeOpaque; } else if (mSecureBufferType[portIndex] == kSecureBufferTypeUnknown) { mSecureBufferType[portIndex] = kSecureBufferTypeOpaque; } } } else { CLOG_ERROR_IF(enable, getExtensionIndex, err, "%s", name); if (!graphic) { char value[PROPERTY_VALUE_MAX]; if (property_get("media.mediadrmservice.enable", value, NULL) && (!strcmp("1", value) || !strcasecmp("true", value))) { CLOG_CONFIG(enableNativeBuffers, "system property override: using native-handles"); mSecureBufferType[portIndex] = kSecureBufferTypeNativeHandle; } else if (mSecureBufferType[portIndex] == kSecureBufferTypeUnknown) { mSecureBufferType[portIndex] = kSecureBufferTypeOpaque; } err = OMX_ErrorNone; } } return StatusFromOMXError(err); }
173,385
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static void usage(char *progname) { printf("Usage:\n"); printf("%s <input_yuv> <width>x<height> <target_width>x<target_height> ", progname); printf("<output_yuv> [<frames>]\n"); } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119
static void usage(char *progname) { static const char *exec_name = NULL; static void usage() { printf("Usage:\n"); printf("%s <input_yuv> <width>x<height> <target_width>x<target_height> ", exec_name); printf("<output_yuv> [<frames>]\n"); }
174,480
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static void *load_bytes(RBinFile *arch, const ut8 *buf, ut64 sz, ut64 loaddr, Sdb *sdb) { if (!buf || !sz || sz == UT64_MAX) { return NULL; } RBuffer *tbuf = r_buf_new (); r_buf_set_bytes (tbuf, buf, sz); struct r_bin_bflt_obj *res = r_bin_bflt_new_buf (tbuf); r_buf_free (tbuf); return res ? res : NULL; } Commit Message: Fix #6829 oob write because of using wrong struct CWE ID: CWE-119
static void *load_bytes(RBinFile *arch, const ut8 *buf, ut64 sz, ut64 loaddr, Sdb *sdb) { if (!buf || !sz || sz == UT64_MAX) { return NULL; } RBuffer *tbuf = r_buf_new (); if (!tbuf) { return NULL; } r_buf_set_bytes (tbuf, buf, sz); struct r_bin_bflt_obj *res = r_bin_bflt_new_buf (tbuf); r_buf_free (tbuf); return res ? res : NULL; }
168,363
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: CursorImpl::IDBThreadHelper::~IDBThreadHelper() { cursor_->RemoveCursorFromTransaction(); } Commit Message: [IndexedDB] Fix Cursor UAF If the connection is closed before we return a cursor, it dies in IndexedDBCallbacks::IOThreadHelper::SendSuccessCursor. It's deleted on the correct thread, but we also need to makes sure to remove it from its transaction. To make things simpler, we have the cursor remove itself from its transaction on destruction. R: [email protected] Bug: 728887 Change-Id: I8c76e6195c2490137a05213e47c635d12f4d3dd2 Reviewed-on: https://chromium-review.googlesource.com/526284 Commit-Queue: Daniel Murphy <[email protected]> Reviewed-by: Victor Costan <[email protected]> Cr-Commit-Position: refs/heads/master@{#477504} CWE ID: CWE-416
CursorImpl::IDBThreadHelper::~IDBThreadHelper() {
172,306
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: v8::MaybeLocal<v8::Value> V8Debugger::functionScopes(v8::Local<v8::Function> function) { if (!enabled()) { NOTREACHED(); return v8::Local<v8::Value>::New(m_isolate, v8::Undefined(m_isolate)); } v8::Local<v8::Value> argv[] = { function }; v8::Local<v8::Value> scopesValue; if (!callDebuggerMethod("getFunctionScopes", 1, argv).ToLocal(&scopesValue) || !scopesValue->IsArray()) return v8::MaybeLocal<v8::Value>(); v8::Local<v8::Array> scopes = scopesValue.As<v8::Array>(); v8::Local<v8::Context> context = m_debuggerContext.Get(m_isolate); if (!markAsInternal(context, scopes, V8InternalValueType::kScopeList)) return v8::MaybeLocal<v8::Value>(); if (!markArrayEntriesAsInternal(context, scopes, V8InternalValueType::kScope)) return v8::MaybeLocal<v8::Value>(); if (!scopes->SetPrototype(context, v8::Null(m_isolate)).FromMaybe(false)) return v8::Undefined(m_isolate); return scopes; } Commit Message: [DevTools] Copy objects from debugger context to inspected context properly. BUG=637594 Review-Url: https://codereview.chromium.org/2253643002 Cr-Commit-Position: refs/heads/master@{#412436} CWE ID: CWE-79
v8::MaybeLocal<v8::Value> V8Debugger::functionScopes(v8::Local<v8::Function> function) v8::MaybeLocal<v8::Value> V8Debugger::functionScopes(v8::Local<v8::Context> context, v8::Local<v8::Function> function) { if (!enabled()) { NOTREACHED(); return v8::Local<v8::Value>::New(m_isolate, v8::Undefined(m_isolate)); } v8::Local<v8::Value> argv[] = { function }; v8::Local<v8::Value> scopesValue; if (!callDebuggerMethod("getFunctionScopes", 1, argv).ToLocal(&scopesValue)) return v8::MaybeLocal<v8::Value>(); v8::Local<v8::Value> copied; if (!copyValueFromDebuggerContext(m_isolate, debuggerContext(), context, scopesValue).ToLocal(&copied) || !copied->IsArray()) return v8::MaybeLocal<v8::Value>(); if (!markAsInternal(context, v8::Local<v8::Array>::Cast(copied), V8InternalValueType::kScopeList)) return v8::MaybeLocal<v8::Value>(); if (!markArrayEntriesAsInternal(context, v8::Local<v8::Array>::Cast(copied), V8InternalValueType::kScope)) return v8::MaybeLocal<v8::Value>(); return copied; }
172,066
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void PepperRendererConnection::OnMsgDidCreateInProcessInstance( PP_Instance instance, const PepperRendererInstanceData& instance_data) { PepperRendererInstanceData data = instance_data; data.render_process_id = render_process_id_; in_process_host_->AddInstance(instance, data); } Commit Message: Validate in-process plugin instance messages. Bug: 733548, 733549 Cq-Include-Trybots: master.tryserver.chromium.linux:linux_site_isolation Change-Id: Ie5572c7bcafa05399b09c44425ddd5ce9b9e4cba Reviewed-on: https://chromium-review.googlesource.com/538908 Commit-Queue: Bill Budge <[email protected]> Reviewed-by: Raymes Khoury <[email protected]> Cr-Commit-Position: refs/heads/master@{#480696} CWE ID: CWE-20
void PepperRendererConnection::OnMsgDidCreateInProcessInstance( PP_Instance instance, const PepperRendererInstanceData& instance_data) { PepperRendererInstanceData data = instance_data; // It's important that we supply the render process ID ourselves since the // message may be coming from a compromised renderer. data.render_process_id = render_process_id_; // 'instance' is possibly invalid. The host must be careful not to trust it. in_process_host_->AddInstance(instance, data); }
172,311
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static bool svc_rdma_prealloc_maps(struct svcxprt_rdma *xprt) { unsigned int i; /* One for each receive buffer on this connection. */ i = xprt->sc_max_requests; while (i--) { struct svc_rdma_req_map *map; map = alloc_req_map(GFP_KERNEL); if (!map) { dprintk("svcrdma: No memory for request map\n"); return false; } list_add(&map->free, &xprt->sc_maps); } return true; } Commit Message: Merge tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux Pull nfsd updates from Bruce Fields: "Another RDMA update from Chuck Lever, and a bunch of miscellaneous bugfixes" * tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux: (26 commits) nfsd: Fix up the "supattr_exclcreat" attributes nfsd: encoders mustn't use unitialized values in error cases nfsd: fix undefined behavior in nfsd4_layout_verify lockd: fix lockd shutdown race NFSv4: Fix callback server shutdown SUNRPC: Refactor svc_set_num_threads() NFSv4.x/callback: Create the callback service through svc_create_pooled lockd: remove redundant check on block svcrdma: Clean out old XDR encoders svcrdma: Remove the req_map cache svcrdma: Remove unused RDMA Write completion handler svcrdma: Reduce size of sge array in struct svc_rdma_op_ctxt svcrdma: Clean up RPC-over-RDMA backchannel reply processing svcrdma: Report Write/Reply chunk overruns svcrdma: Clean up RDMA_ERROR path svcrdma: Use rdma_rw API in RPC reply path svcrdma: Introduce local rdma_rw API helpers svcrdma: Clean up svc_rdma_get_inv_rkey() svcrdma: Add helper to save pages under I/O svcrdma: Eliminate RPCRDMA_SQ_DEPTH_MULT ... CWE ID: CWE-404
static bool svc_rdma_prealloc_maps(struct svcxprt_rdma *xprt)
168,182
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: WebString WebPageSerializer::generateMetaCharsetDeclaration(const WebString& charset) { String charsetString = "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=" + static_cast<const String&>(charset) + "\">"; return charsetString; } Commit Message: Escape "--" in the page URL at page serialization This patch makes page serializer to escape the page URL embed into a HTML comment of result HTML[1] to avoid inserting text as HTML from URL by introducing a static member function |PageSerialzier::markOfTheWebDeclaration()| for sharing it between |PageSerialzier| and |WebPageSerialzier| classes. [1] We use following format for serialized HTML: saved from url=(${lengthOfURL})${URL} BUG=503217 TEST=webkit_unit_tests --gtest_filter=PageSerializerTest.markOfTheWebDeclaration TEST=webkit_unit_tests --gtest_filter=WebPageSerializerTest.fromUrlWithMinusMinu Review URL: https://codereview.chromium.org/1371323003 Cr-Commit-Position: refs/heads/master@{#351736} CWE ID: CWE-20
WebString WebPageSerializer::generateMetaCharsetDeclaration(const WebString& charset) { // TODO(yosin) We should call |PageSerializer::metaCharsetDeclarationOf()|. String charsetString = "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=" + static_cast<const String&>(charset) + "\">"; return charsetString; }
171,788
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: xfs_acl_from_disk(struct xfs_acl *aclp) { struct posix_acl_entry *acl_e; struct posix_acl *acl; struct xfs_acl_entry *ace; int count, i; count = be32_to_cpu(aclp->acl_cnt); acl = posix_acl_alloc(count, GFP_KERNEL); if (!acl) return ERR_PTR(-ENOMEM); for (i = 0; i < count; i++) { acl_e = &acl->a_entries[i]; ace = &aclp->acl_entry[i]; /* * The tag is 32 bits on disk and 16 bits in core. * * Because every access to it goes through the core * format first this is not a problem. */ acl_e->e_tag = be32_to_cpu(ace->ae_tag); acl_e->e_perm = be16_to_cpu(ace->ae_perm); switch (acl_e->e_tag) { case ACL_USER: case ACL_GROUP: acl_e->e_id = be32_to_cpu(ace->ae_id); break; case ACL_USER_OBJ: case ACL_GROUP_OBJ: case ACL_MASK: case ACL_OTHER: acl_e->e_id = ACL_UNDEFINED_ID; break; default: goto fail; } } return acl; fail: posix_acl_release(acl); return ERR_PTR(-EINVAL); } Commit Message: xfs: validate acl count This prevents in-memory corruption and possible panics if the on-disk ACL is badly corrupted. Signed-off-by: Christoph Hellwig <[email protected]> Signed-off-by: Ben Myers <[email protected]> CWE ID: CWE-189
xfs_acl_from_disk(struct xfs_acl *aclp) { struct posix_acl_entry *acl_e; struct posix_acl *acl; struct xfs_acl_entry *ace; int count, i; count = be32_to_cpu(aclp->acl_cnt); if (count > XFS_ACL_MAX_ENTRIES) return ERR_PTR(-EFSCORRUPTED); acl = posix_acl_alloc(count, GFP_KERNEL); if (!acl) return ERR_PTR(-ENOMEM); for (i = 0; i < count; i++) { acl_e = &acl->a_entries[i]; ace = &aclp->acl_entry[i]; /* * The tag is 32 bits on disk and 16 bits in core. * * Because every access to it goes through the core * format first this is not a problem. */ acl_e->e_tag = be32_to_cpu(ace->ae_tag); acl_e->e_perm = be16_to_cpu(ace->ae_perm); switch (acl_e->e_tag) { case ACL_USER: case ACL_GROUP: acl_e->e_id = be32_to_cpu(ace->ae_id); break; case ACL_USER_OBJ: case ACL_GROUP_OBJ: case ACL_MASK: case ACL_OTHER: acl_e->e_id = ACL_UNDEFINED_ID; break; default: goto fail; } } return acl; fail: posix_acl_release(acl); return ERR_PTR(-EINVAL); }
165,656
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: const Extension* ExtensionAppItem::GetExtension() const { const ExtensionService* service = extensions::ExtensionSystem::Get(profile_)->extension_service(); const Extension* extension = service->GetInstalledExtension(extension_id_); return extension; } Commit Message: [Extensions] Add GetInstalledExtension() method to ExtensionRegistry This CL adds GetInstalledExtension() method to ExtensionRegistry and uses it instead of deprecated ExtensionService::GetInstalledExtension() in chrome/browser/ui/app_list/. Part of removing the deprecated GetInstalledExtension() call from the ExtensionService. BUG=489687 Review URL: https://codereview.chromium.org/1130353010 Cr-Commit-Position: refs/heads/master@{#333036} CWE ID:
const Extension* ExtensionAppItem::GetExtension() const { const extensions::ExtensionRegistry* registry = extensions::ExtensionRegistry::Get(profile_); const Extension* extension = registry->GetInstalledExtension( extension_id_); return extension; }
171,723
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static int mpeg4_decode_profile_level(MpegEncContext *s, GetBitContext *gb) { s->avctx->profile = get_bits(gb, 4); s->avctx->level = get_bits(gb, 4); if (s->avctx->profile == 0 && s->avctx->level == 8) { s->avctx->level = 0; } return 0; } Commit Message: avcodec/mpeg4videodec: Check read profile before setting it Fixes: null pointer dereference Fixes: ffmpeg_crash_7.avi Found-by: Thuan Pham, Marcel Böhme, Andrew Santosa and Alexandru Razvan Caciulescu with AFLSmart Signed-off-by: Michael Niedermayer <[email protected]> CWE ID: CWE-476
static int mpeg4_decode_profile_level(MpegEncContext *s, GetBitContext *gb) static int mpeg4_decode_profile_level(MpegEncContext *s, GetBitContext *gb, int *profile, int *level) { *profile = get_bits(gb, 4); *level = get_bits(gb, 4); if (*profile == 0 && *level == 8) { *level = 0; } return 0; }
169,161
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: png_get_uint_32(png_bytep buf) { png_uint_32 i = ((png_uint_32)(*buf) << 24) + ((png_uint_32)(*(buf + 1)) << 16) + ((png_uint_32)(*(buf + 2)) << 8) + (png_uint_32)(*(buf + 3)); return (i); } Commit Message: third_party/libpng: update to 1.2.54 [email protected] BUG=560291 Review URL: https://codereview.chromium.org/1467263003 Cr-Commit-Position: refs/heads/master@{#362298} CWE ID: CWE-119
png_get_uint_32(png_bytep buf) { png_uint_32 i = ((png_uint_32)((*(buf )) & 0xff) << 24) + ((png_uint_32)((*(buf + 1)) & 0xff) << 16) + ((png_uint_32)((*(buf + 2)) & 0xff) << 8) + ((png_uint_32)((*(buf + 3)) & 0xff) ); return (i); }
172,176
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static void calcstepsizes(uint_fast16_t refstepsize, int numrlvls, uint_fast16_t *stepsizes) { int bandno; int numbands; uint_fast16_t expn; uint_fast16_t mant; expn = JPC_QCX_GETEXPN(refstepsize); mant = JPC_QCX_GETMANT(refstepsize); numbands = 3 * numrlvls - 2; for (bandno = 0; bandno < numbands; ++bandno) { ////jas_eprintf("DEBUG %d %d %d %d %d\n", bandno, expn, numrlvls, bandno, ((numrlvls - 1) - (numrlvls - 1 - ((bandno > 0) ? ((bandno + 2) / 3) : (0))))); stepsizes[bandno] = JPC_QCX_MANT(mant) | JPC_QCX_EXPN(expn + (numrlvls - 1) - (numrlvls - 1 - ((bandno > 0) ? ((bandno + 2) / 3) : (0)))); } } Commit Message: Changed the JPC bitstream code to more gracefully handle a request for a larger sized integer than what can be handled (i.e., return with an error instead of failing an assert). CWE ID:
static void calcstepsizes(uint_fast16_t refstepsize, int numrlvls, uint_fast16_t *stepsizes) { int bandno; int numbands; uint_fast16_t expn; uint_fast16_t mant; expn = JPC_QCX_GETEXPN(refstepsize); mant = JPC_QCX_GETMANT(refstepsize); numbands = 3 * numrlvls - 2; for (bandno = 0; bandno < numbands; ++bandno) { ////jas_eprintf("DEBUG %d %d %d %d %d\n", bandno, expn, numrlvls, bandno, ((numrlvls - 1) - (numrlvls - 1 - ((bandno > 0) ? ((bandno + 2) / 3) : (0))))); stepsizes[bandno] = JPC_QCX_MANT(mant) | JPC_QCX_EXPN(expn + (numrlvls - 1) - (numrlvls - 1 - ((bandno > 0) ? ((bandno + 2) / 3) : (0)))); } }
168,735
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: nfs3svc_decode_readlinkargs(struct svc_rqst *rqstp, __be32 *p, struct nfsd3_readlinkargs *args) { p = decode_fh(p, &args->fh); if (!p) return 0; args->buffer = page_address(*(rqstp->rq_next_page++)); return xdr_argsize_check(rqstp, p); } Commit Message: Merge tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux Pull nfsd updates from Bruce Fields: "Another RDMA update from Chuck Lever, and a bunch of miscellaneous bugfixes" * tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux: (26 commits) nfsd: Fix up the "supattr_exclcreat" attributes nfsd: encoders mustn't use unitialized values in error cases nfsd: fix undefined behavior in nfsd4_layout_verify lockd: fix lockd shutdown race NFSv4: Fix callback server shutdown SUNRPC: Refactor svc_set_num_threads() NFSv4.x/callback: Create the callback service through svc_create_pooled lockd: remove redundant check on block svcrdma: Clean out old XDR encoders svcrdma: Remove the req_map cache svcrdma: Remove unused RDMA Write completion handler svcrdma: Reduce size of sge array in struct svc_rdma_op_ctxt svcrdma: Clean up RPC-over-RDMA backchannel reply processing svcrdma: Report Write/Reply chunk overruns svcrdma: Clean up RDMA_ERROR path svcrdma: Use rdma_rw API in RPC reply path svcrdma: Introduce local rdma_rw API helpers svcrdma: Clean up svc_rdma_get_inv_rkey() svcrdma: Add helper to save pages under I/O svcrdma: Eliminate RPCRDMA_SQ_DEPTH_MULT ... CWE ID: CWE-404
nfs3svc_decode_readlinkargs(struct svc_rqst *rqstp, __be32 *p, struct nfsd3_readlinkargs *args) { p = decode_fh(p, &args->fh); if (!p) return 0; if (!xdr_argsize_check(rqstp, p)) return 0; args->buffer = page_address(*(rqstp->rq_next_page++)); return 1; }
168,143
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void ImageFetched(const ContentSuggestion::ID& id, const GURL& url, const base::string16& title, const base::string16& text, base::Time timeout_at, const gfx::Image& image) { if (!ShouldNotifyInState(app_status_listener_.GetState())) { return; // Became foreground while we were fetching the image; forget it. } DVLOG(1) << "Fetched " << image.Size().width() << "x" << image.Size().height() << " image for " << url.spec(); if (ContentSuggestionsNotificationHelper::SendNotification( id, url, title, text, CropSquare(image), timeout_at)) { RecordContentSuggestionsNotificationImpression( id.category().IsKnownCategory(KnownCategories::ARTICLES) ? CONTENT_SUGGESTIONS_ARTICLE : CONTENT_SUGGESTIONS_NONARTICLE); } } Commit Message: NTP: cap number of notifications/day 1 by default; Finch-configurable. BUG=689465 Review-Url: https://codereview.chromium.org/2691023002 Cr-Commit-Position: refs/heads/master@{#450389} CWE ID: CWE-399
void ImageFetched(const ContentSuggestion::ID& id, const GURL& url, const base::string16& title, const base::string16& text, base::Time timeout_at, const gfx::Image& image) { if (!ShouldNotifyInState(app_status_listener_.GetState())) { return; // Became foreground while we were fetching the image; forget it. } DVLOG(1) << "Fetched " << image.Size().width() << "x" << image.Size().height() << " image for " << url.spec(); ConsumeQuota(profile_->GetPrefs()); if (ContentSuggestionsNotificationHelper::SendNotification( id, url, title, text, CropSquare(image), timeout_at)) { RecordContentSuggestionsNotificationImpression( id.category().IsKnownCategory(KnownCategories::ARTICLES) ? CONTENT_SUGGESTIONS_ARTICLE : CONTENT_SUGGESTIONS_NONARTICLE); } }
172,037
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void BluetoothDeviceChromeOS::SetPasskey(uint32 passkey) { if (!agent_.get() || passkey_callback_.is_null()) return; passkey_callback_.Run(SUCCESS, passkey); passkey_callback_.Reset(); } Commit Message: Refactor to support default Bluetooth pairing delegate In order to support a default pairing delegate we need to move the agent service provider delegate implementation from BluetoothDevice to BluetoothAdapter while retaining the existing API. BUG=338492 TEST=device_unittests, unit_tests, browser_tests Review URL: https://codereview.chromium.org/148293003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@252216 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
void BluetoothDeviceChromeOS::SetPasskey(uint32 passkey) { if (!pairing_context_.get()) return; pairing_context_->SetPasskey(passkey); }
171,239
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: CURLcode Curl_auth_create_plain_message(struct Curl_easy *data, const char *userp, const char *passwdp, char **outptr, size_t *outlen) { CURLcode result; char *plainauth; size_t ulen; size_t plen; size_t plainlen; *outlen = 0; *outptr = NULL; ulen = strlen(userp); plen = strlen(passwdp); /* Compute binary message length. Check for overflows. */ if((ulen > SIZE_T_MAX/2) || (plen > (SIZE_T_MAX/2 - 2))) return CURLE_OUT_OF_MEMORY; plainlen = 2 * ulen + plen + 2; plainauth = malloc(plainlen); if(!plainauth) return CURLE_OUT_OF_MEMORY; /* Calculate the reply */ memcpy(plainauth, userp, ulen); plainauth[ulen] = '\0'; memcpy(plainauth + ulen + 1, userp, ulen); plainauth[2 * ulen + 1] = '\0'; memcpy(plainauth + 2 * ulen + 2, passwdp, plen); /* Base64 encode the reply */ result = Curl_base64_encode(data, plainauth, plainlen, outptr, outlen); free(plainauth); return result; } Commit Message: Curl_auth_create_plain_message: fix too-large-input-check CVE-2018-16839 Reported-by: Harry Sintonen Bug: https://curl.haxx.se/docs/CVE-2018-16839.html CWE ID: CWE-119
CURLcode Curl_auth_create_plain_message(struct Curl_easy *data, const char *userp, const char *passwdp, char **outptr, size_t *outlen) { CURLcode result; char *plainauth; size_t ulen; size_t plen; size_t plainlen; *outlen = 0; *outptr = NULL; ulen = strlen(userp); plen = strlen(passwdp); /* Compute binary message length. Check for overflows. */ if((ulen > SIZE_T_MAX/4) || (plen > (SIZE_T_MAX/2 - 2))) return CURLE_OUT_OF_MEMORY; plainlen = 2 * ulen + plen + 2; plainauth = malloc(plainlen); if(!plainauth) return CURLE_OUT_OF_MEMORY; /* Calculate the reply */ memcpy(plainauth, userp, ulen); plainauth[ulen] = '\0'; memcpy(plainauth + ulen + 1, userp, ulen); plainauth[2 * ulen + 1] = '\0'; memcpy(plainauth + 2 * ulen + 2, passwdp, plen); /* Base64 encode the reply */ result = Curl_base64_encode(data, plainauth, plainlen, outptr, outlen); free(plainauth); return result; }
169,031
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: int create_flush_cmd_control(struct f2fs_sb_info *sbi) { dev_t dev = sbi->sb->s_bdev->bd_dev; struct flush_cmd_control *fcc; int err = 0; if (SM_I(sbi)->fcc_info) { fcc = SM_I(sbi)->fcc_info; goto init_thread; } fcc = kzalloc(sizeof(struct flush_cmd_control), GFP_KERNEL); if (!fcc) return -ENOMEM; atomic_set(&fcc->issued_flush, 0); atomic_set(&fcc->issing_flush, 0); init_waitqueue_head(&fcc->flush_wait_queue); init_llist_head(&fcc->issue_list); SM_I(sbi)->fcc_info = fcc; init_thread: fcc->f2fs_issue_flush = kthread_run(issue_flush_thread, sbi, "f2fs_flush-%u:%u", MAJOR(dev), MINOR(dev)); if (IS_ERR(fcc->f2fs_issue_flush)) { err = PTR_ERR(fcc->f2fs_issue_flush); kfree(fcc); SM_I(sbi)->fcc_info = NULL; return err; } return err; } Commit Message: f2fs: fix a panic caused by NULL flush_cmd_control Mount fs with option noflush_merge, boot failed for illegal address fcc in function f2fs_issue_flush: if (!test_opt(sbi, FLUSH_MERGE)) { ret = submit_flush_wait(sbi); atomic_inc(&fcc->issued_flush); -> Here, fcc illegal return ret; } Signed-off-by: Yunlei He <[email protected]> Signed-off-by: Jaegeuk Kim <[email protected]> CWE ID: CWE-476
int create_flush_cmd_control(struct f2fs_sb_info *sbi) { dev_t dev = sbi->sb->s_bdev->bd_dev; struct flush_cmd_control *fcc; int err = 0; if (SM_I(sbi)->fcc_info) { fcc = SM_I(sbi)->fcc_info; goto init_thread; } fcc = kzalloc(sizeof(struct flush_cmd_control), GFP_KERNEL); if (!fcc) return -ENOMEM; atomic_set(&fcc->issued_flush, 0); atomic_set(&fcc->issing_flush, 0); init_waitqueue_head(&fcc->flush_wait_queue); init_llist_head(&fcc->issue_list); SM_I(sbi)->fcc_info = fcc; if (!test_opt(sbi, FLUSH_MERGE)) return err; init_thread: fcc->f2fs_issue_flush = kthread_run(issue_flush_thread, sbi, "f2fs_flush-%u:%u", MAJOR(dev), MINOR(dev)); if (IS_ERR(fcc->f2fs_issue_flush)) { err = PTR_ERR(fcc->f2fs_issue_flush); kfree(fcc); SM_I(sbi)->fcc_info = NULL; return err; } return err; }
169,382
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: int get_sda(void) { return qrio_get_gpio(DEBLOCK_PORT1, DEBLOCK_SDA1); } Commit Message: Merge branch '2020-01-22-master-imports' - Re-add U8500 platform support - Add bcm968360bg support - Assorted Keymile fixes - Other assorted bugfixes CWE ID: CWE-787
int get_sda(void)
169,630
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void WebLocalFrameImpl::LoadJavaScriptURL(const KURL& url) { DCHECK(GetFrame()); Document* owner_document = GetFrame()->GetDocument(); if (!owner_document || !GetFrame()->GetPage()) return; if (SchemeRegistry::ShouldTreatURLSchemeAsNotAllowingJavascriptURLs( owner_document->Url().Protocol())) return; String script = DecodeURLEscapeSequences( url.GetString().Substring(strlen("javascript:"))); UserGestureIndicator gesture_indicator( UserGestureToken::Create(owner_document, UserGestureToken::kNewGesture)); v8::HandleScope handle_scope(ToIsolate(GetFrame())); v8::Local<v8::Value> result = GetFrame()->GetScriptController().ExecuteScriptInMainWorldAndReturnValue( ScriptSourceCode(script)); if (result.IsEmpty() || !result->IsString()) return; String script_result = ToCoreString(v8::Local<v8::String>::Cast(result)); if (!GetFrame()->GetNavigationScheduler().LocationChangePending()) { GetFrame()->Loader().ReplaceDocumentWhileExecutingJavaScriptURL( script_result, owner_document); } } Commit Message: Inherit CSP when we inherit the security origin This prevents attacks that use main window navigation to get out of the existing csp constraints such as the related bug Bug: 747847 Change-Id: I1e57b50da17f65d38088205b0a3c7c49ef2ae4d8 Reviewed-on: https://chromium-review.googlesource.com/592027 Reviewed-by: Mike West <[email protected]> Commit-Queue: Andy Paicu <[email protected]> Cr-Commit-Position: refs/heads/master@{#492333} CWE ID: CWE-732
void WebLocalFrameImpl::LoadJavaScriptURL(const KURL& url) { DCHECK(GetFrame()); Document* owner_document = GetFrame()->GetDocument(); if (!owner_document || !GetFrame()->GetPage()) return; if (SchemeRegistry::ShouldTreatURLSchemeAsNotAllowingJavascriptURLs( owner_document->Url().Protocol())) return; String script = DecodeURLEscapeSequences( url.GetString().Substring(strlen("javascript:"))); UserGestureIndicator gesture_indicator( UserGestureToken::Create(owner_document, UserGestureToken::kNewGesture)); v8::HandleScope handle_scope(ToIsolate(GetFrame())); v8::Local<v8::Value> result = GetFrame()->GetScriptController().ExecuteScriptInMainWorldAndReturnValue( ScriptSourceCode(script)); if (result.IsEmpty() || !result->IsString()) return; String script_result = ToCoreString(v8::Local<v8::String>::Cast(result)); if (!GetFrame()->GetNavigationScheduler().LocationChangePending()) { GetFrame()->Loader().ReplaceDocumentWhileExecutingJavaScriptURL( script_result, owner_document); } }
172,301
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: store_current_palette(png_store *ps, int *npalette) { /* This is an internal error (the call has been made outside a read * operation.) */ if (ps->current == NULL) store_log(ps, ps->pread, "no current stream for palette", 1); /* The result may be null if there is no palette. */ *npalette = ps->current->npalette; return ps->current->palette; } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
store_current_palette(png_store *ps, int *npalette) { /* This is an internal error (the call has been made outside a read * operation.) */ if (ps->current == NULL) { store_log(ps, ps->pread, "no current stream for palette", 1); return NULL; } /* The result may be null if there is no palette. */ *npalette = ps->current->npalette; return ps->current->palette; }
173,703
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void ImageBitmapFactories::ImageBitmapLoader::Trace(blink::Visitor* visitor) { visitor->Trace(factory_); visitor->Trace(resolver_); visitor->Trace(options_); } Commit Message: Fix UAP in ImageBitmapLoader/FileReaderLoader FileReaderLoader stores its client as a raw pointer, so in cases like ImageBitmapLoader where the FileReaderLoaderClient really is garbage collected we have to make sure to destroy the FileReaderLoader when the ExecutionContext that owns it is destroyed. Bug: 913970 Change-Id: I40b02115367cf7bf5bbbbb8e9b57874d2510f861 Reviewed-on: https://chromium-review.googlesource.com/c/1374511 Reviewed-by: Jeremy Roman <[email protected]> Commit-Queue: Marijn Kruisselbrink <[email protected]> Cr-Commit-Position: refs/heads/master@{#616342} CWE ID: CWE-416
void ImageBitmapFactories::ImageBitmapLoader::Trace(blink::Visitor* visitor) { ContextLifecycleObserver::Trace(visitor); visitor->Trace(factory_); visitor->Trace(resolver_); visitor->Trace(options_); }
173,071
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: BlockEntry::Kind Track::EOSBlock::GetKind() const { return kBlockEOS; } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
BlockEntry::Kind Track::EOSBlock::GetKind() const
174,331
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void Cues::Init() const { if (m_cue_points) return; assert(m_count == 0); assert(m_preload_count == 0); IMkvReader* const pReader = m_pSegment->m_pReader; const long long stop = m_start + m_size; long long pos = m_start; long cue_points_size = 0; while (pos < stop) { const long long idpos = pos; long len; const long long id = ReadUInt(pReader, pos, len); assert(id >= 0); //TODO assert((pos + len) <= stop); pos += len; //consume ID const long long size = ReadUInt(pReader, pos, len); assert(size >= 0); assert((pos + len) <= stop); pos += len; //consume Size field assert((pos + size) <= stop); if (id == 0x3B) //CuePoint ID PreloadCuePoint(cue_points_size, idpos); pos += size; //consume payload assert(pos <= stop); } } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
void Cues::Init() const long len; const long long id = ReadUInt(pReader, m_pos, len); assert(id >= 0); // TODO assert((m_pos + len) <= stop); m_pos += len; // consume ID const long long size = ReadUInt(pReader, m_pos, len); assert(size >= 0); assert((m_pos + len) <= stop); m_pos += len; // consume Size field assert((m_pos + size) <= stop); if (id != 0x3B) { // CuePoint ID m_pos += size; // consume payload assert(m_pos <= stop);
174,390
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static int check_line_charstring(void) { char *p = line; while (isspace(*p)) p++; return (*p == '/' || (p[0] == 'd' && p[1] == 'u' && p[2] == 'p')); } Commit Message: Security fixes. - Don't overflow the small cs_start buffer (reported by Niels Thykier via the debian tracker (Jakub Wilk), found with a fuzzer ("American fuzzy lop")). - Cast arguments to <ctype.h> functions to unsigned char. CWE ID: CWE-119
static int check_line_charstring(void) { char *p = line; while (isspace((unsigned char) *p)) p++; return (*p == '/' || (p[0] == 'd' && p[1] == 'u' && p[2] == 'p')); }
166,620
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static inline void VectorClamp(DDSVector4 *value) { value->x = MinF(1.0f,MaxF(0.0f,value->x)); value->y = MinF(1.0f,MaxF(0.0f,value->y)); value->z = MinF(1.0f,MaxF(0.0f,value->z)); value->w = MinF(1.0f,MaxF(0.0f,value->w)); } Commit Message: Added extra EOF check and some minor refactoring. CWE ID: CWE-20
static inline void VectorClamp(DDSVector4 *value) { value->x = MagickMin(1.0f,MagickMax(0.0f,value->x)); value->y = MagickMin(1.0f,MagickMax(0.0f,value->y)); value->z = MagickMin(1.0f,MagickMax(0.0f,value->z)); value->w = MagickMin(1.0f,MagickMax(0.0f,value->w)); }
168,906
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: long ParseElementHeader(IMkvReader* pReader, long long& pos, long long stop, long long& id, long long& size) { if (stop >= 0 && pos >= stop) return E_FILE_FORMAT_INVALID; long len; id = ReadID(pReader, pos, len); if (id < 0) return E_FILE_FORMAT_INVALID; pos += len; // consume id if (stop >= 0 && pos >= stop) return E_FILE_FORMAT_INVALID; size = ReadUInt(pReader, pos, len); if (size < 0 || len < 1 || len > 8) { return E_FILE_FORMAT_INVALID; } const unsigned long long rollover_check = static_cast<unsigned long long>(pos) + len; if (rollover_check > LONG_LONG_MAX) return E_FILE_FORMAT_INVALID; pos += len; // consume length of size if (stop >= 0 && pos >= stop) return E_FILE_FORMAT_INVALID; return 0; // success } Commit Message: Fix ParseElementHeader to support 0 payload elements Cherry-pick'ing Change 5c83bbec9a5f6f00a349674ddad85b753d2ea219 from upstream. This fixes regression in some edge cases for mkv playback. BUG=26499283 Change-Id: I88de03219a3d941b6b2f251d384e29c36bdd4d9b CWE ID: CWE-20
long ParseElementHeader(IMkvReader* pReader, long long& pos, long long stop, long long& id, long long& size) { if (stop >= 0 && pos >= stop) return E_FILE_FORMAT_INVALID; long len; id = ReadID(pReader, pos, len); if (id < 0) return E_FILE_FORMAT_INVALID; pos += len; // consume id if (stop >= 0 && pos >= stop) return E_FILE_FORMAT_INVALID; size = ReadUInt(pReader, pos, len); if (size < 0 || len < 1 || len > 8) { return E_FILE_FORMAT_INVALID; } const unsigned long long rollover_check = static_cast<unsigned long long>(pos) + len; if (rollover_check > LONG_LONG_MAX) return E_FILE_FORMAT_INVALID; pos += len; // consume length of size if (stop >= 0 && pos > stop) return E_FILE_FORMAT_INVALID; return 0; // success }
174,229
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: WindowOpenDisposition BrowserView::GetDispositionForPopupBounds( const gfx::Rect& bounds) { return WindowOpenDisposition::NEW_POPUP; } Commit Message: Mac: turn popups into new tabs while in fullscreen. It's platform convention to show popups as new tabs while in non-HTML5 fullscreen. (Popups cause tabs to lose HTML5 fullscreen.) This was implemented for Cocoa in a BrowserWindow override, but it makes sense to just stick it into Browser and remove a ton of override code put in just to support this. BUG=858929, 868416 TEST=as in bugs Change-Id: I43471f242813ec1159d9c690bab73dab3e610b7d Reviewed-on: https://chromium-review.googlesource.com/1153455 Reviewed-by: Sidney San Martín <[email protected]> Commit-Queue: Avi Drissman <[email protected]> Cr-Commit-Position: refs/heads/master@{#578755} CWE ID: CWE-20
WindowOpenDisposition BrowserView::GetDispositionForPopupBounds(
173,207
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: int ptrace_setxregs(struct task_struct *child, void __user *uregs) { struct thread_info *ti = task_thread_info(child); struct pt_regs *regs = task_pt_regs(child); elf_xtregs_t *xtregs = uregs; int ret = 0; #if XTENSA_HAVE_COPROCESSORS /* Flush all coprocessors before we overwrite them. */ coprocessor_flush_all(ti); coprocessor_release_all(ti); ret |= __copy_from_user(&ti->xtregs_cp, &xtregs->cp0, sizeof(xtregs_coprocessor_t)); #endif ret |= __copy_from_user(&regs->xtregs_opt, &xtregs->opt, sizeof(xtregs->opt)); ret |= __copy_from_user(&ti->xtregs_user, &xtregs->user, sizeof(xtregs->user)); return ret ? -EFAULT : 0; } Commit Message: xtensa: prevent arbitrary read in ptrace Prevent an arbitrary kernel read. Check the user pointer with access_ok() before copying data in. [[email protected]: s/EIO/EFAULT/] Signed-off-by: Dan Rosenberg <[email protected]> Cc: Christian Zankel <[email protected]> Cc: Oleg Nesterov <[email protected]> Cc: <[email protected]> Signed-off-by: Andrew Morton <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-20
int ptrace_setxregs(struct task_struct *child, void __user *uregs) { struct thread_info *ti = task_thread_info(child); struct pt_regs *regs = task_pt_regs(child); elf_xtregs_t *xtregs = uregs; int ret = 0; if (!access_ok(VERIFY_READ, uregs, sizeof(elf_xtregs_t))) return -EFAULT; #if XTENSA_HAVE_COPROCESSORS /* Flush all coprocessors before we overwrite them. */ coprocessor_flush_all(ti); coprocessor_release_all(ti); ret |= __copy_from_user(&ti->xtregs_cp, &xtregs->cp0, sizeof(xtregs_coprocessor_t)); #endif ret |= __copy_from_user(&regs->xtregs_opt, &xtregs->opt, sizeof(xtregs->opt)); ret |= __copy_from_user(&ti->xtregs_user, &xtregs->user, sizeof(xtregs->user)); return ret ? -EFAULT : 0; }
165,849
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: bool RenderFrameHostManager::CanSubframeSwapProcess( const GURL& dest_url, SiteInstance* source_instance, SiteInstance* dest_instance, bool was_server_redirect) { DCHECK(!source_instance || !dest_instance); GURL resolved_url = dest_url; if (url::Origin::Create(resolved_url).unique()) { if (source_instance) { resolved_url = source_instance->GetSiteURL(); } else if (dest_instance) { resolved_url = dest_instance->GetSiteURL(); } else { if (!was_server_redirect) return false; } } if (!IsRendererTransferNeededForNavigation(render_frame_host_.get(), resolved_url)) { DCHECK(!dest_instance || dest_instance == render_frame_host_->GetSiteInstance()); return false; } return true; } Commit Message: Use unique processes for data URLs on restore. Data URLs are usually put into the process that created them, but this info is not tracked after a tab restore. Ensure that they do not end up in the parent frame's process (or each other's process), in case they are malicious. BUG=863069 Change-Id: Ib391f90c7bdf28a0a9c057c5cc7918c10aed968b Reviewed-on: https://chromium-review.googlesource.com/1150767 Reviewed-by: Alex Moshchuk <[email protected]> Reviewed-by: Lei Zhang <[email protected]> Commit-Queue: Charlie Reis <[email protected]> Cr-Commit-Position: refs/heads/master@{#581023} CWE ID: CWE-285
bool RenderFrameHostManager::CanSubframeSwapProcess( const GURL& dest_url, SiteInstance* source_instance, SiteInstance* dest_instance) { DCHECK(!source_instance || !dest_instance); GURL resolved_url = dest_url; if (url::Origin::Create(resolved_url).unique()) { if (source_instance) { resolved_url = source_instance->GetSiteURL(); } else if (dest_instance) { resolved_url = dest_instance->GetSiteURL(); } else { // then check whether it is safe to put into the parent frame's process. // This is the case for about:blank URLs (with or without fragments), // since they contain no active data. This is also the case for // about:srcdoc, since such URLs only get active content from their parent // frame. Using the parent frame's process avoids putting blank frames // into OOPIFs and preserves scripting for about:srcdoc. // // Allow a process swap for other unique origin URLs, such as data: URLs. // These have active content and may have come from an untrusted source, // such as a restored frame from a different site or a redirect. // (Normally, redirects to data: or about: URLs are disallowed as // example, see ExtensionWebRequestApiTest.WebRequestDeclarative1).) if (resolved_url.IsAboutBlank() || resolved_url == GURL(content::kAboutSrcDocURL)) { return false; } } } if (!IsRendererTransferNeededForNavigation(render_frame_host_.get(), resolved_url)) { DCHECK(!dest_instance || dest_instance == render_frame_host_->GetSiteInstance()); return false; } return true; }
173,181
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: EBMLHeader::EBMLHeader() : m_docType(NULL) { Init(); } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
EBMLHeader::EBMLHeader() :
174,269
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: ExtensionBookmarksTest() : client_(NULL), model_(NULL), node_(NULL), folder_(NULL) {} Commit Message: Added unit test for new portion of GetMetaInfo API BUG=383600 Review URL: https://codereview.chromium.org/348833003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@278908 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
ExtensionBookmarksTest()
171,186
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: vhost_scsi_send_evt(struct vhost_scsi *vs, struct vhost_scsi_tpg *tpg, struct se_lun *lun, u32 event, u32 reason) { struct vhost_scsi_evt *evt; evt = vhost_scsi_allocate_evt(vs, event, reason); if (!evt) return; if (tpg && lun) { /* TODO: share lun setup code with virtio-scsi.ko */ /* * Note: evt->event is zeroed when we allocate it and * lun[4-7] need to be zero according to virtio-scsi spec. */ evt->event.lun[0] = 0x01; evt->event.lun[1] = tpg->tport_tpgt & 0xFF; if (lun->unpacked_lun >= 256) evt->event.lun[2] = lun->unpacked_lun >> 8 | 0x40 ; evt->event.lun[3] = lun->unpacked_lun & 0xFF; } llist_add(&evt->list, &vs->vs_event_list); vhost_work_queue(&vs->dev, &vs->vs_event_work); } Commit Message: vhost/scsi: potential memory corruption This code in vhost_scsi_make_tpg() is confusing because we limit "tpgt" to UINT_MAX but the data type of "tpg->tport_tpgt" and that is a u16. I looked at the context and it turns out that in vhost_scsi_set_endpoint(), "tpg->tport_tpgt" is used as an offset into the vs_tpg[] array which has VHOST_SCSI_MAX_TARGET (256) elements so anything higher than 255 then it is invalid. I have made that the limit now. In vhost_scsi_send_evt() we mask away values higher than 255, but now that the limit has changed, we don't need the mask. Signed-off-by: Dan Carpenter <[email protected]> Signed-off-by: Nicholas Bellinger <[email protected]> CWE ID: CWE-119
vhost_scsi_send_evt(struct vhost_scsi *vs, struct vhost_scsi_tpg *tpg, struct se_lun *lun, u32 event, u32 reason) { struct vhost_scsi_evt *evt; evt = vhost_scsi_allocate_evt(vs, event, reason); if (!evt) return; if (tpg && lun) { /* TODO: share lun setup code with virtio-scsi.ko */ /* * Note: evt->event is zeroed when we allocate it and * lun[4-7] need to be zero according to virtio-scsi spec. */ evt->event.lun[0] = 0x01; evt->event.lun[1] = tpg->tport_tpgt; if (lun->unpacked_lun >= 256) evt->event.lun[2] = lun->unpacked_lun >> 8 | 0x40 ; evt->event.lun[3] = lun->unpacked_lun & 0xFF; } llist_add(&evt->list, &vs->vs_event_list); vhost_work_queue(&vs->dev, &vs->vs_event_work); }
166,616
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: transform_display_init(transform_display *dp, png_modifier *pm, png_uint_32 id, PNG_CONST image_transform *transform_list) { memset(dp, 0, sizeof *dp); /* Standard fields */ standard_display_init(&dp->this, &pm->this, id, 0/*do_interlace*/, pm->use_update_info); /* Parameter fields */ dp->pm = pm; dp->transform_list = transform_list; /* Local variable fields */ dp->output_colour_type = 255; /* invalid */ dp->output_bit_depth = 255; /* invalid */ } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
transform_display_init(transform_display *dp, png_modifier *pm, png_uint_32 id, const image_transform *transform_list) { memset(dp, 0, sizeof *dp); /* Standard fields */ standard_display_init(&dp->this, &pm->this, id, do_read_interlace, pm->use_update_info); /* Parameter fields */ dp->pm = pm; dp->transform_list = transform_list; dp->max_gamma_8 = 16; /* Local variable fields */ dp->output_colour_type = 255; /* invalid */ dp->output_bit_depth = 255; /* invalid */ dp->unpacked = 0; /* not unpacked */ }
173,712
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: virtual void PreEncodeFrameHook(::libvpx_test::VideoSource *video, ::libvpx_test::Encoder *encoder) { if (video->frame() == 1) { encoder->Control(VP8E_SET_CPUUSED, set_cpu_used_); encoder->Control(VP8E_SET_ENABLEAUTOALTREF, 1); encoder->Control(VP8E_SET_ARNR_MAXFRAMES, 7); encoder->Control(VP8E_SET_ARNR_STRENGTH, 5); encoder->Control(VP8E_SET_ARNR_TYPE, 3); } } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119
virtual void PreEncodeFrameHook(::libvpx_test::VideoSource *video, ::libvpx_test::Encoder *encoder) { if (video->frame() == 1) { encoder->Control(VP8E_SET_CPUUSED, set_cpu_used_); if (encoding_mode_ != ::libvpx_test::kRealTime) { encoder->Control(VP8E_SET_ENABLEAUTOALTREF, 1); encoder->Control(VP8E_SET_ARNR_MAXFRAMES, 7); encoder->Control(VP8E_SET_ARNR_STRENGTH, 5); encoder->Control(VP8E_SET_ARNR_TYPE, 3); } } }
174,513
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: SecureProxyChecker::SecureProxyChecker( scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory) : url_loader_factory_(std::move(url_loader_factory)) {} Commit Message: Disable all DRP URL fetches when holdback is enabled Disable secure proxy checker, warmup url fetcher and client config fetch when the client is in DRP (Data Reduction Proxy) holdback. This CL does not disable pingbacks when client is in the holdback, but the pingback code is going away soon. Change-Id: Icbb59d814d1452123869c609e0770d1439c1db51 Bug: 984964 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1709965 Commit-Queue: Tarun Bansal <[email protected]> Reviewed-by: Robert Ogden <[email protected]> Cr-Commit-Position: refs/heads/master@{#679649} CWE ID: CWE-416
SecureProxyChecker::SecureProxyChecker( scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory)
172,423
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: BluetoothChooserDesktop::~BluetoothChooserDesktop() { bluetooth_chooser_controller_->ResetEventHandler(); } Commit Message: Ensure device choosers are closed on navigation The requestDevice() IPCs can race with navigation. This change ensures that choosers are closed on navigation and adds browser tests to exercise this for Web Bluetooth and WebUSB. Bug: 723503 Change-Id: I66760161220e17bd2be9309cca228d161fe76e9c Reviewed-on: https://chromium-review.googlesource.com/1099961 Commit-Queue: Reilly Grant <[email protected]> Reviewed-by: Michael Wasserman <[email protected]> Reviewed-by: Jeffrey Yasskin <[email protected]> Cr-Commit-Position: refs/heads/master@{#569900} CWE ID: CWE-362
BluetoothChooserDesktop::~BluetoothChooserDesktop() { bluetooth_chooser_controller_->ResetEventHandler(); if (bubble_) bubble_->CloseBubble(BUBBLE_CLOSE_FORCED); }
173,202
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: xfs_file_splice_write( struct pipe_inode_info *pipe, struct file *outfilp, loff_t *ppos, size_t count, unsigned int flags) { struct inode *inode = outfilp->f_mapping->host; struct xfs_inode *ip = XFS_I(inode); int ioflags = 0; ssize_t ret; XFS_STATS_INC(xs_write_calls); if (outfilp->f_mode & FMODE_NOCMTIME) ioflags |= IO_INVIS; if (XFS_FORCED_SHUTDOWN(ip->i_mount)) return -EIO; xfs_ilock(ip, XFS_IOLOCK_EXCL); trace_xfs_file_splice_write(ip, count, *ppos, ioflags); ret = generic_file_splice_write(pipe, outfilp, ppos, count, flags); if (ret > 0) XFS_STATS_ADD(xs_write_bytes, ret); xfs_iunlock(ip, XFS_IOLOCK_EXCL); return ret; } Commit Message: ->splice_write() via ->write_iter() iter_file_splice_write() - a ->splice_write() instance that gathers the pipe buffers, builds a bio_vec-based iov_iter covering those and feeds it to ->write_iter(). A bunch of simple cases coverted to that... [AV: fixed the braino spotted by Cyrill] Signed-off-by: Al Viro <[email protected]> CWE ID: CWE-264
xfs_file_splice_write(
166,810
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: de_dotdot( char* file ) { char* cp; char* cp2; int l; /* Collapse any multiple / sequences. */ while ( ( cp = strstr( file, "//") ) != (char*) 0 ) { for ( cp2 = cp + 2; *cp2 == '/'; ++cp2 ) continue; (void) strcpy( cp + 1, cp2 ); } /* Remove leading ./ and any /./ sequences. */ while ( strncmp( file, "./", 2 ) == 0 ) (void) memmove( file, file + 2, strlen( file ) - 1 ); while ( ( cp = strstr( file, "/./") ) != (char*) 0 ) (void) memmove( cp, cp + 2, strlen( file ) - 1 ); /* Alternate between removing leading ../ and removing xxx/../ */ for (;;) { while ( strncmp( file, "../", 3 ) == 0 ) (void) memmove( file, file + 3, strlen( file ) - 2 ); cp = strstr( file, "/../" ); if ( cp == (char*) 0 ) break; for ( cp2 = cp - 1; cp2 >= file && *cp2 != '/'; --cp2 ) continue; (void) strcpy( cp2 + 1, cp + 4 ); } /* Also elide any xxx/.. at the end. */ while ( ( l = strlen( file ) ) > 3 && strcmp( ( cp = file + l - 3 ), "/.." ) == 0 ) { for ( cp2 = cp - 1; cp2 >= file && *cp2 != '/'; --cp2 ) continue; if ( cp2 < file ) break; *cp2 = '\0'; } } Commit Message: Fix heap buffer overflow in de_dotdot CWE ID: CWE-119
de_dotdot( char* file ) { char* cp; char* cp2; int l; /* Collapse any multiple / sequences. */ while ( ( cp = strstr( file, "//") ) != (char*) 0 ) { for ( cp2 = cp + 2; *cp2 == '/'; ++cp2 ) continue; (void) strcpy( cp + 1, cp2 ); } /* Remove leading ./ and any /./ sequences. */ while ( strncmp( file, "./", 2 ) == 0 ) (void) memmove( file, file + 2, strlen( file ) - 1 ); while ( ( cp = strstr( file, "/./") ) != (char*) 0 ) (void) memmove( cp, cp + 2, strlen( cp ) - 1 ); /* Alternate between removing leading ../ and removing xxx/../ */ for (;;) { while ( strncmp( file, "../", 3 ) == 0 ) (void) memmove( file, file + 3, strlen( file ) - 2 ); cp = strstr( file, "/../" ); if ( cp == (char*) 0 ) break; for ( cp2 = cp - 1; cp2 >= file && *cp2 != '/'; --cp2 ) continue; (void) strcpy( cp2 + 1, cp + 4 ); } /* Also elide any xxx/.. at the end. */ while ( ( l = strlen( file ) ) > 3 && strcmp( ( cp = file + l - 3 ), "/.." ) == 0 ) { for ( cp2 = cp - 1; cp2 >= file && *cp2 != '/'; --cp2 ) continue; if ( cp2 < file ) break; *cp2 = '\0'; } }
168,063
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: bool Init() { DCHECK(!initialized_successfully_) << "Already initialized"; if (!CrosLibrary::Get()->EnsureLoaded()) return false; input_method_status_connection_ = chromeos::MonitorInputMethodStatus( this, &InputMethodChangedHandler, &RegisterPropertiesHandler, &UpdatePropertyHandler, &ConnectionChangeHandler); if (!input_method_status_connection_) return false; initialized_successfully_ = true; return true; } Commit Message: Remove use of libcros from InputMethodLibrary. BUG=chromium-os:16238 TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before. Review URL: http://codereview.chromium.org/7003086 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
bool Init() { DCHECK(!initialized_successfully_) << "Already initialized"; ibus_controller_ = input_method::IBusController::Create(); // The observer should be added before Connect() so we can capture the // initial connection change. ibus_controller_->AddObserver(this); ibus_controller_->Connect(); initialized_successfully_ = true; return true; }
170,494
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void CtcpHandler::defaultHandler(const QString &cmd, CtcpType ctcptype, const QString &prefix, const QString &target, const QString &param) { Q_UNUSED(ctcptype); Q_UNUSED(target); if(!_ignoreListManager->ctcpMatch(prefix, network()->networkName())) { QString str = tr("Received unknown CTCP %1 by %2").arg(cmd).arg(prefix); if(!param.isEmpty()) str.append(tr(" with arguments: %1").arg(param)); emit displayMsg(Message::Error, BufferInfo::StatusBuffer, "", str); } } Commit Message: CWE ID: CWE-399
void CtcpHandler::defaultHandler(const QString &cmd, CtcpType ctcptype, const QString &prefix, const QString &target, const QString &param) { void CtcpHandler::defaultHandler(const QString &cmd, CtcpType ctcptype, const QString &prefix, const QString &target, const QString &param, QString &reply) { Q_UNUSED(ctcptype); Q_UNUSED(target); Q_UNUSED(reply); QString str = tr("Received unknown CTCP %1 by %2").arg(cmd).arg(prefix); if(!param.isEmpty()) str.append(tr(" with arguments: %1").arg(param)); emit displayMsg(Message::Error, BufferInfo::StatusBuffer, "", str); }
164,876
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: scoped_ptr<cc::CompositorFrame> TestSynchronousCompositor::DemandDrawHw( gfx::Size surface_size, const gfx::Transform& transform, gfx::Rect viewport, gfx::Rect clip, gfx::Rect viewport_rect_for_tile_priority, const gfx::Transform& transform_for_tile_priority) { return hardware_frame_.Pass(); } Commit Message: sync compositor: pass simple gfx types by const ref See bug for reasoning BUG=159273 Review URL: https://codereview.chromium.org/1417893006 Cr-Commit-Position: refs/heads/master@{#356653} CWE ID: CWE-399
scoped_ptr<cc::CompositorFrame> TestSynchronousCompositor::DemandDrawHw( const gfx::Size& surface_size, const gfx::Transform& transform, const gfx::Rect& viewport, const gfx::Rect& clip, const gfx::Rect& viewport_rect_for_tile_priority, const gfx::Transform& transform_for_tile_priority) { return hardware_frame_.Pass(); }
171,620
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static void InputMethodChangedHandler( void* object, const chromeos::InputMethodDescriptor& current_input_method) { if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) { LOG(ERROR) << "Not on UI thread"; return; } InputMethodLibraryImpl* input_method_library = static_cast<InputMethodLibraryImpl*>(object); input_method_library->ChangeCurrentInputMethod(current_input_method); } Commit Message: Remove use of libcros from InputMethodLibrary. BUG=chromium-os:16238 TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before. Review URL: http://codereview.chromium.org/7003086 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
static void InputMethodChangedHandler( // IBusController override. virtual void OnCurrentInputMethodChanged( const input_method::InputMethodDescriptor& current_input_method) { if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) { LOG(ERROR) << "Not on UI thread"; return; } ChangeCurrentInputMethod(current_input_method); }
170,495
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: normalize_color_encoding(color_encoding *encoding) { PNG_CONST double whiteY = encoding->red.Y + encoding->green.Y + encoding->blue.Y; if (whiteY != 1) { encoding->red.X /= whiteY; encoding->red.Y /= whiteY; encoding->red.Z /= whiteY; encoding->green.X /= whiteY; encoding->green.Y /= whiteY; encoding->green.Z /= whiteY; encoding->blue.X /= whiteY; encoding->blue.Y /= whiteY; encoding->blue.Z /= whiteY; } } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
normalize_color_encoding(color_encoding *encoding) { const double whiteY = encoding->red.Y + encoding->green.Y + encoding->blue.Y; if (whiteY != 1) { encoding->red.X /= whiteY; encoding->red.Y /= whiteY; encoding->red.Z /= whiteY; encoding->green.X /= whiteY; encoding->green.Y /= whiteY; encoding->green.Z /= whiteY; encoding->blue.X /= whiteY; encoding->blue.Y /= whiteY; encoding->blue.Z /= whiteY; } }
173,673
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static int nbd_negotiate_read(QIOChannel *ioc, void *buffer, size_t size) { ssize_t ret; guint watch; assert(qemu_in_coroutine()); /* Negotiation are always in main loop. */ watch = qio_channel_add_watch(ioc, G_IO_IN, nbd_negotiate_continue, qemu_coroutine_self(), NULL); ret = nbd_read(ioc, buffer, size, NULL); g_source_remove(watch); return ret; } Commit Message: CWE ID: CWE-20
static int nbd_negotiate_read(QIOChannel *ioc, void *buffer, size_t size)
165,454
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: long Track::Create( Segment* pSegment, const Info& info, long long element_start, long long element_size, Track*& pResult) { if (pResult) return -1; Track* const pTrack = new (std::nothrow) Track(pSegment, element_start, element_size); if (pTrack == NULL) return -1; //generic error const int status = info.Copy(pTrack->m_info); if (status) // error { delete pTrack; return status; } pResult = pTrack; return 0; //success } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
long Track::Create( Track::Info::Info() : uid(0), defaultDuration(0), codecDelay(0), seekPreRoll(0), nameAsUTF8(NULL), language(NULL), codecId(NULL), codecNameAsUTF8(NULL), codecPrivate(NULL), codecPrivateSize(0), lacing(false) {} Track::Info::~Info() { Clear(); } void Track::Info::Clear() { delete[] nameAsUTF8; nameAsUTF8 = NULL; delete[] language; language = NULL; delete[] codecId; codecId = NULL; delete[] codecPrivate; codecPrivate = NULL; codecPrivateSize = 0; delete[] codecNameAsUTF8; codecNameAsUTF8 = NULL; }
174,255
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static char *decode_text_string(const char *str, size_t str_len) { int idx, is_hex, is_utf16be, ascii_idx; char *ascii, hex_buf[5] = {0}; is_hex = is_utf16be = idx = ascii_idx = 0; /* Regular encoding */ if (str[0] == '(') { ascii = malloc(strlen(str) + 1); strncpy(ascii, str, strlen(str) + 1); return ascii; } else if (str[0] == '<') { is_hex = 1; ++idx; } /* Text strings can be either PDFDocEncoding or UTF-16BE */ if (is_hex && (str_len > 5) && (str[idx] == 'F') && (str[idx+1] == 'E') && (str[idx+2] == 'F') && (str[idx+3] == 'F')) { is_utf16be = 1; idx += 4; } else return NULL; /* Now decode as hex */ ascii = malloc(str_len); for ( ; idx<str_len; ++idx) { hex_buf[0] = str[idx++]; hex_buf[1] = str[idx++]; hex_buf[2] = str[idx++]; hex_buf[3] = str[idx]; ascii[ascii_idx++] = strtol(hex_buf, NULL, 16); } return ascii; } Commit Message: Zero and sanity check all dynamic allocs. This addresses the memory issues in Issue #6 expressed in calloc_some.pdf and malloc_some.pdf CWE ID: CWE-787
static char *decode_text_string(const char *str, size_t str_len) { int idx, is_hex, is_utf16be, ascii_idx; char *ascii, hex_buf[5] = {0}; is_hex = is_utf16be = idx = ascii_idx = 0; /* Regular encoding */ if (str[0] == '(') { ascii = safe_calloc(strlen(str) + 1); strncpy(ascii, str, strlen(str) + 1); return ascii; } else if (str[0] == '<') { is_hex = 1; ++idx; } /* Text strings can be either PDFDocEncoding or UTF-16BE */ if (is_hex && (str_len > 5) && (str[idx] == 'F') && (str[idx+1] == 'E') && (str[idx+2] == 'F') && (str[idx+3] == 'F')) { is_utf16be = 1; idx += 4; } else return NULL; /* Now decode as hex */ ascii = safe_calloc(str_len); for ( ; idx<str_len; ++idx) { hex_buf[0] = str[idx++]; hex_buf[1] = str[idx++]; hex_buf[2] = str[idx++]; hex_buf[3] = str[idx]; ascii[ascii_idx++] = strtol(hex_buf, NULL, 16); } return ascii; }
169,566
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void ScreenPositionController::ConvertHostPointToRelativeToRootWindow( aura::Window* root_window, const aura::Window::Windows& root_windows, gfx::Point* point, aura::Window** target_root) { DCHECK(!root_window->parent()); gfx::Point point_in_root(*point); root_window->GetHost()->ConvertPointFromHost(&point_in_root); *target_root = root_window; *point = point_in_root; #if defined(USE_X11) || defined(USE_OZONE) if (!root_window->GetHost()->GetBounds().Contains(*point)) { gfx::Point location_in_native(point_in_root); root_window->GetHost()->ConvertPointToNativeScreen(&location_in_native); for (size_t i = 0; i < root_windows.size(); ++i) { aura::WindowTreeHost* host = root_windows[i]->GetHost(); const gfx::Rect native_bounds = host->GetBounds(); if (native_bounds.Contains(location_in_native)) { *target_root = root_windows[i]; *point = location_in_native; host->ConvertPointFromNativeScreen(point); break; } } } #else NOTIMPLEMENTED(); #endif } Commit Message: Use the host coordinate when comparing to host window bounds. I somehow overlooked this and the test was not strict enough to catch this. BUG=521919 TEST=Updated ScreenPositionControllerTest.ConvertHostPointToScreenHiDPI so that it fails without the patch. Review URL: https://codereview.chromium.org/1293373002 Cr-Commit-Position: refs/heads/master@{#344186} CWE ID: CWE-399
void ScreenPositionController::ConvertHostPointToRelativeToRootWindow( aura::Window* root_window, const aura::Window::Windows& root_windows, gfx::Point* point, aura::Window** target_root) { DCHECK(!root_window->parent()); gfx::Point point_in_root(*point); root_window->GetHost()->ConvertPointFromHost(&point_in_root); #if defined(USE_X11) || defined(USE_OZONE) gfx::Rect host_bounds(root_window->GetHost()->GetBounds().size()); if (!host_bounds.Contains(*point)) { gfx::Point location_in_native(point_in_root); root_window->GetHost()->ConvertPointToNativeScreen(&location_in_native); for (size_t i = 0; i < root_windows.size(); ++i) { aura::WindowTreeHost* host = root_windows[i]->GetHost(); const gfx::Rect native_bounds = host->GetBounds(); if (native_bounds.Contains(location_in_native)) { *target_root = root_windows[i]; *point = location_in_native; host->ConvertPointFromNativeScreen(point); return; } } } #endif *target_root = root_window; *point = point_in_root; }
171,711
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static int klsi_105_get_line_state(struct usb_serial_port *port, unsigned long *line_state_p) { int rc; u8 *status_buf; __u16 status; dev_info(&port->serial->dev->dev, "sending SIO Poll request\n"); status_buf = kmalloc(KLSI_STATUSBUF_LEN, GFP_KERNEL); if (!status_buf) return -ENOMEM; status_buf[0] = 0xff; status_buf[1] = 0xff; rc = usb_control_msg(port->serial->dev, usb_rcvctrlpipe(port->serial->dev, 0), KL5KUSB105A_SIO_POLL, USB_TYPE_VENDOR | USB_DIR_IN, 0, /* value */ 0, /* index */ status_buf, KLSI_STATUSBUF_LEN, 10000 ); if (rc < 0) dev_err(&port->dev, "Reading line status failed (error = %d)\n", rc); else { status = get_unaligned_le16(status_buf); dev_info(&port->serial->dev->dev, "read status %x %x\n", status_buf[0], status_buf[1]); *line_state_p = klsi_105_status2linestate(status); } kfree(status_buf); return rc; } Commit Message: USB: serial: kl5kusb105: fix line-state error handling The current implementation failed to detect short transfers when attempting to read the line state, and also, to make things worse, logged the content of the uninitialised heap transfer buffer. Fixes: abf492e7b3ae ("USB: kl5kusb105: fix DMA buffers on stack") Fixes: 1da177e4c3f4 ("Linux-2.6.12-rc2") Cc: stable <[email protected]> Reviewed-by: Greg Kroah-Hartman <[email protected]> Signed-off-by: Johan Hovold <[email protected]> CWE ID: CWE-532
static int klsi_105_get_line_state(struct usb_serial_port *port, unsigned long *line_state_p) { int rc; u8 *status_buf; __u16 status; dev_info(&port->serial->dev->dev, "sending SIO Poll request\n"); status_buf = kmalloc(KLSI_STATUSBUF_LEN, GFP_KERNEL); if (!status_buf) return -ENOMEM; status_buf[0] = 0xff; status_buf[1] = 0xff; rc = usb_control_msg(port->serial->dev, usb_rcvctrlpipe(port->serial->dev, 0), KL5KUSB105A_SIO_POLL, USB_TYPE_VENDOR | USB_DIR_IN, 0, /* value */ 0, /* index */ status_buf, KLSI_STATUSBUF_LEN, 10000 ); if (rc != KLSI_STATUSBUF_LEN) { dev_err(&port->dev, "reading line status failed: %d\n", rc); if (rc >= 0) rc = -EIO; } else { status = get_unaligned_le16(status_buf); dev_info(&port->serial->dev->dev, "read status %x %x\n", status_buf[0], status_buf[1]); *line_state_p = klsi_105_status2linestate(status); } kfree(status_buf); return rc; }
168,389
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void smp_proc_enc_info(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { uint8_t* p = p_data->p_data; SMP_TRACE_DEBUG("%s", __func__); STREAM_TO_ARRAY(p_cb->ltk, p, BT_OCTET16_LEN); smp_key_distribution(p_cb, NULL); } Commit Message: Checks the SMP length to fix OOB read Bug: 111937065 Test: manual Change-Id: I330880a6e1671d0117845430db4076dfe1aba688 Merged-In: I330880a6e1671d0117845430db4076dfe1aba688 (cherry picked from commit fceb753bda651c4135f3f93a510e5fcb4c7542b8) CWE ID: CWE-200
void smp_proc_enc_info(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { uint8_t* p = p_data->p_data; SMP_TRACE_DEBUG("%s", __func__); if (smp_command_has_invalid_parameters(p_cb)) { tSMP_INT_DATA smp_int_data; smp_int_data.status = SMP_INVALID_PARAMETERS; android_errorWriteLog(0x534e4554, "111937065"); smp_sm_event(p_cb, SMP_AUTH_CMPL_EVT, &smp_int_data); return; } STREAM_TO_ARRAY(p_cb->ltk, p, BT_OCTET16_LEN); smp_key_distribution(p_cb, NULL); }
174,074
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: client_x11_display_valid(const char *display) { size_t i, dlen; dlen = strlen(display); for (i = 0; i < dlen; i++) { if (!isalnum((u_char)display[i]) && } } Commit Message: CWE ID: CWE-254
client_x11_display_valid(const char *display) { size_t i, dlen; if (display == NULL) return 0; dlen = strlen(display); for (i = 0; i < dlen; i++) { if (!isalnum((u_char)display[i]) && } }
165,351
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: cJSON *cJSON_DetachItemFromArray( cJSON *array, int which ) { cJSON *c = array->child; while ( c && which > 0 ) { c = c->next; --which; } if ( ! c ) return 0; if ( c->prev ) c->prev->next = c->next; if ( c->next ) c->next->prev = c->prev; if ( c == array->child ) array->child = c->next; c->prev = c->next = 0; return c; } Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a malformed JSON string was passed on the control channel. This issue, present in the cJSON library, was already fixed upstream, so was addressed here in iperf3 by importing a newer version of cJSON (plus local ESnet modifications). Discovered and reported by Dave McDaniel, Cisco Talos. Based on a patch by @dopheide-esnet, with input from @DaveGamble. Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001, CVE-2016-4303 (cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40) Signed-off-by: Bruce A. Mah <[email protected]> CWE ID: CWE-119
cJSON *cJSON_DetachItemFromArray( cJSON *array, int which )
167,284
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: InstallVerifyFrame::InstallVerifyFrame(const wxString& lDmodFilePath) : InstallVerifyFrame_Base(NULL, wxID_ANY, _T("")) { mConfig = Config::GetConfig(); prepareDialog(); int flags = wxPD_AUTO_HIDE | wxPD_APP_MODAL | wxPD_REMAINING_TIME; wxProgressDialog lPrepareProgress(_("Preparing"), _("The D-Mod archive is being decompressed in a temporary file."), 100, this, flags); BZip lBZip(lDmodFilePath); mTarFilePath = lBZip.Extract(&lPrepareProgress); if (mTarFilePath.Len() != 0) { Tar lTar(mTarFilePath); lTar.ReadHeaders(); wxString lDmodDescription = lTar.getmDmodDescription(); "\n" "The D-Mod will be installed in subdirectory '%s'."), lTar.getInstalledDmodDirectory().c_str()); } else { int lBreakChar = lDmodDescription.Find( '\r' ); if ( lBreakChar <= 0 ) { lBreakChar = lDmodDescription.Find( '\n' ); } mDmodName = lDmodDescription.SubString( 0, lBreakChar - 1 ); this->SetTitle(_("DFArc - Install D-Mod - ") + mDmodName); } mDmodDescription->SetValue(lDmodDescription); mInstallButton->Enable(true); } Commit Message: CWE ID: CWE-22
InstallVerifyFrame::InstallVerifyFrame(const wxString& lDmodFilePath) : InstallVerifyFrame_Base(NULL, wxID_ANY, _T("")) { mConfig = Config::GetConfig(); prepareDialog(); int flags = wxPD_AUTO_HIDE | wxPD_APP_MODAL | wxPD_REMAINING_TIME; wxProgressDialog lPrepareProgress(_("Preparing"), _("The D-Mod archive is being decompressed in a temporary file."), 100, this, flags); BZip lBZip(lDmodFilePath); mTarFilePath = lBZip.Extract(&lPrepareProgress); if (mTarFilePath.Len() != 0) { Tar lTar(mTarFilePath); if (lTar.ReadHeaders() == 1) { this->EndModal(wxID_CANCEL); return; } wxString lDmodDescription = lTar.getmDmodDescription(); "\n" "The D-Mod will be installed in subdirectory '%s'."), lTar.getInstalledDmodDirectory().c_str()); } else { int lBreakChar = lDmodDescription.Find( '\r' ); if ( lBreakChar <= 0 ) { lBreakChar = lDmodDescription.Find( '\n' ); } mDmodName = lDmodDescription.SubString( 0, lBreakChar - 1 ); this->SetTitle(_("DFArc - Install D-Mod - ") + mDmodName); } mDmodDescription->SetValue(lDmodDescription); mInstallButton->Enable(true); }
165,346
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: SPL_METHOD(SplFileObject, hasChildren) { if (zend_parse_parameters_none() == FAILURE) { return; } RETURN_FALSE; } /* }}} */ /* {{{ proto bool SplFileObject::getChildren() Commit Message: Fix bug #72262 - do not overflow int CWE ID: CWE-190
SPL_METHOD(SplFileObject, hasChildren) { if (zend_parse_parameters_none() == FAILURE) { return; } RETURN_FALSE; } /* }}} */ /* {{{ proto bool SplFileObject::getChildren()
167,060
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static zend_bool add_post_var(zval *arr, post_var_data_t *var, zend_bool eof) { char *ksep, *vsep, *val; size_t klen, vlen; size_t new_vlen; if (var->ptr >= var->end) { return 0; } vsep = memchr(var->ptr, '&', var->end - var->ptr); if (!vsep) { if (!eof) { return 0; } else { vsep = var->end; } } ksep = memchr(var->ptr, '=', vsep - var->ptr); if (ksep) { *ksep = '\0'; /* "foo=bar&" or "foo=&" */ klen = ksep - var->ptr; vlen = vsep - ++ksep; } else { ksep = ""; /* "foo&" */ klen = vsep - var->ptr; vlen = 0; } php_url_decode(var->ptr, klen); val = estrndup(ksep, vlen); if (vlen) { vlen = php_url_decode(val, vlen); } if (sapi_module.input_filter(PARSE_POST, var->ptr, &val, vlen, &new_vlen)) { php_register_variable_safe(var->ptr, val, new_vlen, arr); } efree(val); var->ptr = vsep + (vsep != var->end); return 1; } Commit Message: Fix bug #73807 CWE ID: CWE-400
static zend_bool add_post_var(zval *arr, post_var_data_t *var, zend_bool eof) { char *start, *ksep, *vsep, *val; size_t klen, vlen; size_t new_vlen; if (var->ptr >= var->end) { return 0; } start = var->ptr + var->already_scanned; vsep = memchr(start, '&', var->end - start); if (!vsep) { if (!eof) { var->already_scanned = var->end - var->ptr; return 0; } else { vsep = var->end; } } ksep = memchr(var->ptr, '=', vsep - var->ptr); if (ksep) { *ksep = '\0'; /* "foo=bar&" or "foo=&" */ klen = ksep - var->ptr; vlen = vsep - ++ksep; } else { ksep = ""; /* "foo&" */ klen = vsep - var->ptr; vlen = 0; } php_url_decode(var->ptr, klen); val = estrndup(ksep, vlen); if (vlen) { vlen = php_url_decode(val, vlen); } if (sapi_module.input_filter(PARSE_POST, var->ptr, &val, vlen, &new_vlen)) { php_register_variable_safe(var->ptr, val, new_vlen, arr); } efree(val); var->ptr = vsep + (vsep != var->end); var->already_scanned = 0; return 1; }
170,041
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void FormAssociatedElement::formRemovedFromTree(const Node* formRoot) { ASSERT(m_form); if (toHTMLElement(this)->highestAncestor() != formRoot) setForm(0); } Commit Message: Fix a crash when a form control is in a past naems map of a demoted form element. Note that we wanted to add the protector in FormAssociatedElement::setForm(), but we couldn't do it because it is called from the constructor. BUG=326854 TEST=automated. Review URL: https://codereview.chromium.org/105693013 git-svn-id: svn://svn.chromium.org/blink/trunk@163680 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-287
void FormAssociatedElement::formRemovedFromTree(const Node* formRoot) { ASSERT(m_form); if (toHTMLElement(this)->highestAncestor() == formRoot) return; RefPtr<HTMLElement> protector(toHTMLElement(this)); setForm(0); }
171,718
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static UINT drdynvc_process_capability_request(drdynvcPlugin* drdynvc, int Sp, int cbChId, wStream* s) { UINT status; if (!drdynvc) return CHANNEL_RC_BAD_INIT_HANDLE; WLog_Print(drdynvc->log, WLOG_TRACE, "capability_request Sp=%d cbChId=%d", Sp, cbChId); Stream_Seek(s, 1); /* pad */ Stream_Read_UINT16(s, drdynvc->version); /* RDP8 servers offer version 3, though Microsoft forgot to document it * in their early documents. It behaves the same as version 2. */ if ((drdynvc->version == 2) || (drdynvc->version == 3)) { Stream_Read_UINT16(s, drdynvc->PriorityCharge0); Stream_Read_UINT16(s, drdynvc->PriorityCharge1); Stream_Read_UINT16(s, drdynvc->PriorityCharge2); Stream_Read_UINT16(s, drdynvc->PriorityCharge3); } status = drdynvc_send_capability_response(drdynvc); drdynvc->state = DRDYNVC_STATE_READY; return status; } Commit Message: Fix for #4866: Added additional length checks CWE ID:
static UINT drdynvc_process_capability_request(drdynvcPlugin* drdynvc, int Sp, int cbChId, wStream* s) { UINT status; if (!drdynvc) return CHANNEL_RC_BAD_INIT_HANDLE; if (Stream_GetRemainingLength(s) < 3) return ERROR_INVALID_DATA; WLog_Print(drdynvc->log, WLOG_TRACE, "capability_request Sp=%d cbChId=%d", Sp, cbChId); Stream_Seek(s, 1); /* pad */ Stream_Read_UINT16(s, drdynvc->version); /* RDP8 servers offer version 3, though Microsoft forgot to document it * in their early documents. It behaves the same as version 2. */ if ((drdynvc->version == 2) || (drdynvc->version == 3)) { if (Stream_GetRemainingLength(s) < 8) return ERROR_INVALID_DATA; Stream_Read_UINT16(s, drdynvc->PriorityCharge0); Stream_Read_UINT16(s, drdynvc->PriorityCharge1); Stream_Read_UINT16(s, drdynvc->PriorityCharge2); Stream_Read_UINT16(s, drdynvc->PriorityCharge3); } status = drdynvc_send_capability_response(drdynvc); drdynvc->state = DRDYNVC_STATE_READY; return status; }
168,934
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: status_t OMXNodeInstance::updateGraphicBufferInMeta_l( OMX_U32 portIndex, const sp<GraphicBuffer>& graphicBuffer, OMX::buffer_id buffer, OMX_BUFFERHEADERTYPE *header) { if (portIndex != kPortIndexInput && portIndex != kPortIndexOutput) { return BAD_VALUE; } BufferMeta *bufferMeta = (BufferMeta *)(header->pAppPrivate); bufferMeta->setGraphicBuffer(graphicBuffer); if (mMetadataType[portIndex] == kMetadataBufferTypeGrallocSource && header->nAllocLen >= sizeof(VideoGrallocMetadata)) { VideoGrallocMetadata &metadata = *(VideoGrallocMetadata *)(header->pBuffer); metadata.eType = kMetadataBufferTypeGrallocSource; metadata.pHandle = graphicBuffer == NULL ? NULL : graphicBuffer->handle; } else if (mMetadataType[portIndex] == kMetadataBufferTypeANWBuffer && header->nAllocLen >= sizeof(VideoNativeMetadata)) { VideoNativeMetadata &metadata = *(VideoNativeMetadata *)(header->pBuffer); metadata.eType = kMetadataBufferTypeANWBuffer; metadata.pBuffer = graphicBuffer == NULL ? NULL : graphicBuffer->getNativeBuffer(); metadata.nFenceFd = -1; } else { CLOG_BUFFER(updateGraphicBufferInMeta, "%s:%u, %#x bad type (%d) or size (%u)", portString(portIndex), portIndex, buffer, mMetadataType[portIndex], header->nAllocLen); return BAD_VALUE; } CLOG_BUFFER(updateGraphicBufferInMeta, "%s:%u, %#x := %p", portString(portIndex), portIndex, buffer, graphicBuffer == NULL ? NULL : graphicBuffer->handle); return OK; } Commit Message: DO NOT MERGE omx: check buffer port before using Bug: 28816827 Change-Id: I3d5bad4a1ef96dec544b05bb31cc6f7109aae0a5 CWE ID: CWE-119
status_t OMXNodeInstance::updateGraphicBufferInMeta_l( OMX_U32 portIndex, const sp<GraphicBuffer>& graphicBuffer, OMX::buffer_id buffer, OMX_BUFFERHEADERTYPE *header) { if (header == NULL) { return BAD_VALUE; } if (portIndex != kPortIndexInput && portIndex != kPortIndexOutput) { return BAD_VALUE; } BufferMeta *bufferMeta = (BufferMeta *)(header->pAppPrivate); bufferMeta->setGraphicBuffer(graphicBuffer); if (mMetadataType[portIndex] == kMetadataBufferTypeGrallocSource && header->nAllocLen >= sizeof(VideoGrallocMetadata)) { VideoGrallocMetadata &metadata = *(VideoGrallocMetadata *)(header->pBuffer); metadata.eType = kMetadataBufferTypeGrallocSource; metadata.pHandle = graphicBuffer == NULL ? NULL : graphicBuffer->handle; } else if (mMetadataType[portIndex] == kMetadataBufferTypeANWBuffer && header->nAllocLen >= sizeof(VideoNativeMetadata)) { VideoNativeMetadata &metadata = *(VideoNativeMetadata *)(header->pBuffer); metadata.eType = kMetadataBufferTypeANWBuffer; metadata.pBuffer = graphicBuffer == NULL ? NULL : graphicBuffer->getNativeBuffer(); metadata.nFenceFd = -1; } else { CLOG_BUFFER(updateGraphicBufferInMeta, "%s:%u, %#x bad type (%d) or size (%u)", portString(portIndex), portIndex, buffer, mMetadataType[portIndex], header->nAllocLen); return BAD_VALUE; } CLOG_BUFFER(updateGraphicBufferInMeta, "%s:%u, %#x := %p", portString(portIndex), portIndex, buffer, graphicBuffer == NULL ? NULL : graphicBuffer->handle); return OK; }
173,532
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static uint32_t scsi_init_iovec(SCSIDiskReq *r) { r->iov.iov_len = MIN(r->sector_count * 512, SCSI_DMA_BUF_SIZE); qemu_iovec_init_external(&r->qiov, &r->iov, 1); return r->qiov.size / 512; } Commit Message: scsi-disk: lazily allocate bounce buffer It will not be needed for reads and writes if the HBA provides a sglist. In addition, this lets scsi-disk refuse commands with an excessive allocation length, as well as limit memory on usual well-behaved guests. Signed-off-by: Paolo Bonzini <[email protected]> Signed-off-by: Kevin Wolf <[email protected]> CWE ID: CWE-119
static uint32_t scsi_init_iovec(SCSIDiskReq *r) { SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev); if (!r->iov.iov_base) { r->buflen = SCSI_DMA_BUF_SIZE; r->iov.iov_base = qemu_blockalign(s->bs, r->buflen); } r->iov.iov_len = MIN(r->sector_count * 512, r->buflen); qemu_iovec_init_external(&r->qiov, &r->iov, 1); return r->qiov.size / 512; }
166,554
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: ssize_t NaClDescCustomRecvMsg(void* handle, NaClImcTypedMsgHdr* msg, int /* flags */) { if (msg->iov_length != 1) return -1; msg->ndesc_length = 0; // Messages with descriptors aren't supported yet. return static_cast<ssize_t>( ToAdapter(handle)->BlockingReceive(static_cast<char*>(msg->iov[0].base), msg->iov[0].length)); } Commit Message: Revert 143656 - Add an IPC channel between the NaCl loader process and the renderer. BUG=116317 TEST=ppapi, nacl tests, manual testing for experimental IPC proxy. Review URL: https://chromiumcodereview.appspot.com/10641016 [email protected] Review URL: https://chromiumcodereview.appspot.com/10625007 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143665 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
ssize_t NaClDescCustomRecvMsg(void* handle, NaClImcTypedMsgHdr* msg, int /* flags */) { if (msg->iov_length != 1) return -1; return static_cast<ssize_t>( ToAdapter(handle)->BlockingReceive(static_cast<char*>(msg->iov[0].base), msg->iov[0].length)); }
170,730
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void vrend_renderer_context_destroy(uint32_t handle) { struct vrend_decode_ctx *ctx; bool ret; if (handle >= VREND_MAX_CTX) return; ctx = dec_ctx[handle]; if (!ctx) return; vrend_hw_switch_context(dec_ctx[0]->grctx, true); } Commit Message: CWE ID: CWE-476
void vrend_renderer_context_destroy(uint32_t handle) { struct vrend_decode_ctx *ctx; bool ret; if (handle >= VREND_MAX_CTX) return; /* never destroy context 0 here, it will be destroyed in vrend_decode_reset()*/ if (handle == 0) { return; } ctx = dec_ctx[handle]; if (!ctx) return; vrend_hw_switch_context(dec_ctx[0]->grctx, true); }
164,949
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: const Block* BlockGroup::GetBlock() const { return &m_block; } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
const Block* BlockGroup::GetBlock() const
174,286
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: http_rxchunk(struct http *hp) { char *q; int l, i; l = hp->prxbuf; do (void)http_rxchar(hp, 1, 0); while (hp->rxbuf[hp->prxbuf - 1] != '\n'); vtc_dump(hp->vl, 4, "len", hp->rxbuf + l, -1); i = strtoul(hp->rxbuf + l, &q, 16); bprintf(hp->chunklen, "%d", i); if ((q == hp->rxbuf + l) || (*q != '\0' && !vct_islws(*q))) { vtc_log(hp->vl, hp->fatal, "chunked fail %02x @ %d", *q, q - (hp->rxbuf + l)); } assert(q != hp->rxbuf + l); assert(*q == '\0' || vct_islws(*q)); hp->prxbuf = l; if (i > 0) { (void)http_rxchar(hp, i, 0); vtc_dump(hp->vl, 4, "chunk", hp->rxbuf + l, i); } l = hp->prxbuf; (void)http_rxchar(hp, 2, 0); if(!vct_iscrlf(hp->rxbuf[l])) vtc_log(hp->vl, hp->fatal, "Wrong chunk tail[0] = %02x", hp->rxbuf[l] & 0xff); if(!vct_iscrlf(hp->rxbuf[l + 1])) vtc_log(hp->vl, hp->fatal, "Wrong chunk tail[1] = %02x", hp->rxbuf[l + 1] & 0xff); hp->prxbuf = l; hp->rxbuf[l] = '\0'; return (i); } Commit Message: Do not consider a CR by itself as a valid line terminator Varnish (prior to version 4.0) was not following the standard with regard to line separator. Spotted and analyzed by: Régis Leroy [regilero] [email protected] CWE ID:
http_rxchunk(struct http *hp) { char *q; int l, i; l = hp->prxbuf; do (void)http_rxchar(hp, 1, 0); while (hp->rxbuf[hp->prxbuf - 1] != '\n'); vtc_dump(hp->vl, 4, "len", hp->rxbuf + l, -1); i = strtoul(hp->rxbuf + l, &q, 16); bprintf(hp->chunklen, "%d", i); if ((q == hp->rxbuf + l) || (*q != '\0' && !vct_islws(*q))) { vtc_log(hp->vl, hp->fatal, "chunked fail %02x @ %d", *q, q - (hp->rxbuf + l)); } assert(q != hp->rxbuf + l); assert(*q == '\0' || vct_islws(*q)); hp->prxbuf = l; if (i > 0) { (void)http_rxchar(hp, i, 0); vtc_dump(hp->vl, 4, "chunk", hp->rxbuf + l, i); } l = hp->prxbuf; (void)http_rxchar(hp, 2, 0); if(!vct_iscrlf(&hp->rxbuf[l])) vtc_log(hp->vl, hp->fatal, "Wrong chunk tail[0] = %02x", hp->rxbuf[l] & 0xff); if(!vct_iscrlf(&hp->rxbuf[l + 1])) vtc_log(hp->vl, hp->fatal, "Wrong chunk tail[1] = %02x", hp->rxbuf[l + 1] & 0xff); hp->prxbuf = l; hp->rxbuf[l] = '\0'; return (i); }
169,999
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: PrintPreviewUI::~PrintPreviewUI() { print_preview_data_service()->RemoveEntry(preview_ui_addr_str_); g_print_preview_request_id_map.Get().Erase(preview_ui_addr_str_); } Commit Message: Print preview: Use an ID instead of memory pointer string in WebUI. BUG=144051 Review URL: https://chromiumcodereview.appspot.com/10870003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@153342 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-200
PrintPreviewUI::~PrintPreviewUI() { print_preview_data_service()->RemoveEntry(id_); g_print_preview_request_id_map.Get().Erase(id_); g_print_preview_ui_id_map.Get().Remove(id_); }
170,844
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: PHP_FUNCTION(mcrypt_get_block_size) { char *cipher; char *module; int cipher_len, module_len; char *cipher_dir_string; char *module_dir_string; MCRYPT td; MCRYPT_GET_INI if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss", &cipher, &cipher_len, &module, &module_len) == FAILURE) { return; } td = mcrypt_module_open(cipher, cipher_dir_string, module, module_dir_string); if (td != MCRYPT_FAILED) { RETVAL_LONG(mcrypt_enc_get_block_size(td)); mcrypt_module_close(td); } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, MCRYPT_OPEN_MODULE_FAILED); RETURN_FALSE; } } Commit Message: Fix bug #72455: Heap Overflow due to integer overflows CWE ID: CWE-190
PHP_FUNCTION(mcrypt_get_block_size) { char *cipher; char *module; int cipher_len, module_len; char *cipher_dir_string; char *module_dir_string; MCRYPT td; MCRYPT_GET_INI if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss", &cipher, &cipher_len, &module, &module_len) == FAILURE) { return; } td = mcrypt_module_open(cipher, cipher_dir_string, module, module_dir_string); if (td != MCRYPT_FAILED) { RETVAL_LONG(mcrypt_enc_get_block_size(td)); mcrypt_module_close(td); } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, MCRYPT_OPEN_MODULE_FAILED); RETURN_FALSE; } }
167,104
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void StorageHandler::ClearDataForOrigin( const std::string& origin, const std::string& storage_types, std::unique_ptr<ClearDataForOriginCallback> callback) { if (!process_) return callback->sendFailure(Response::InternalError()); StoragePartition* partition = process_->GetStoragePartition(); std::vector<std::string> types = base::SplitString( storage_types, ",", base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY); std::unordered_set<std::string> set(types.begin(), types.end()); uint32_t remove_mask = 0; if (set.count(Storage::StorageTypeEnum::Appcache)) remove_mask |= StoragePartition::REMOVE_DATA_MASK_APPCACHE; if (set.count(Storage::StorageTypeEnum::Cookies)) remove_mask |= StoragePartition::REMOVE_DATA_MASK_COOKIES; if (set.count(Storage::StorageTypeEnum::File_systems)) remove_mask |= StoragePartition::REMOVE_DATA_MASK_FILE_SYSTEMS; if (set.count(Storage::StorageTypeEnum::Indexeddb)) remove_mask |= StoragePartition::REMOVE_DATA_MASK_INDEXEDDB; if (set.count(Storage::StorageTypeEnum::Local_storage)) remove_mask |= StoragePartition::REMOVE_DATA_MASK_LOCAL_STORAGE; if (set.count(Storage::StorageTypeEnum::Shader_cache)) remove_mask |= StoragePartition::REMOVE_DATA_MASK_SHADER_CACHE; if (set.count(Storage::StorageTypeEnum::Websql)) remove_mask |= StoragePartition::REMOVE_DATA_MASK_WEBSQL; if (set.count(Storage::StorageTypeEnum::Service_workers)) remove_mask |= StoragePartition::REMOVE_DATA_MASK_SERVICE_WORKERS; if (set.count(Storage::StorageTypeEnum::Cache_storage)) remove_mask |= StoragePartition::REMOVE_DATA_MASK_CACHE_STORAGE; if (set.count(Storage::StorageTypeEnum::All)) remove_mask |= StoragePartition::REMOVE_DATA_MASK_ALL; if (!remove_mask) { return callback->sendFailure( Response::InvalidParams("No valid storage type specified")); } partition->ClearData(remove_mask, StoragePartition::QUOTA_MANAGED_STORAGE_MASK_ALL, GURL(origin), StoragePartition::OriginMatcherFunction(), base::Time(), base::Time::Max(), base::BindOnce(&ClearDataForOriginCallback::sendSuccess, std::move(callback))); } Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable This keeps BrowserContext* and StoragePartition* instead of RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost upon closure of DevTools front-end. Bug: 801117, 783067, 780694 Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b Reviewed-on: https://chromium-review.googlesource.com/876657 Commit-Queue: Andrey Kosyakov <[email protected]> Reviewed-by: Dmitry Gozman <[email protected]> Cr-Commit-Position: refs/heads/master@{#531157} CWE ID: CWE-20
void StorageHandler::ClearDataForOrigin( const std::string& origin, const std::string& storage_types, std::unique_ptr<ClearDataForOriginCallback> callback) { if (!storage_partition_) return callback->sendFailure(Response::InternalError()); std::vector<std::string> types = base::SplitString( storage_types, ",", base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY); std::unordered_set<std::string> set(types.begin(), types.end()); uint32_t remove_mask = 0; if (set.count(Storage::StorageTypeEnum::Appcache)) remove_mask |= StoragePartition::REMOVE_DATA_MASK_APPCACHE; if (set.count(Storage::StorageTypeEnum::Cookies)) remove_mask |= StoragePartition::REMOVE_DATA_MASK_COOKIES; if (set.count(Storage::StorageTypeEnum::File_systems)) remove_mask |= StoragePartition::REMOVE_DATA_MASK_FILE_SYSTEMS; if (set.count(Storage::StorageTypeEnum::Indexeddb)) remove_mask |= StoragePartition::REMOVE_DATA_MASK_INDEXEDDB; if (set.count(Storage::StorageTypeEnum::Local_storage)) remove_mask |= StoragePartition::REMOVE_DATA_MASK_LOCAL_STORAGE; if (set.count(Storage::StorageTypeEnum::Shader_cache)) remove_mask |= StoragePartition::REMOVE_DATA_MASK_SHADER_CACHE; if (set.count(Storage::StorageTypeEnum::Websql)) remove_mask |= StoragePartition::REMOVE_DATA_MASK_WEBSQL; if (set.count(Storage::StorageTypeEnum::Service_workers)) remove_mask |= StoragePartition::REMOVE_DATA_MASK_SERVICE_WORKERS; if (set.count(Storage::StorageTypeEnum::Cache_storage)) remove_mask |= StoragePartition::REMOVE_DATA_MASK_CACHE_STORAGE; if (set.count(Storage::StorageTypeEnum::All)) remove_mask |= StoragePartition::REMOVE_DATA_MASK_ALL; if (!remove_mask) { return callback->sendFailure( Response::InvalidParams("No valid storage type specified")); } storage_partition_->ClearData( remove_mask, StoragePartition::QUOTA_MANAGED_STORAGE_MASK_ALL, GURL(origin), StoragePartition::OriginMatcherFunction(), base::Time(), base::Time::Max(), base::BindOnce(&ClearDataForOriginCallback::sendSuccess, std::move(callback))); }
172,770
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: chunk_type_valid(png_uint_32 c) /* Bit whacking approach to chunk name validation that is intended to avoid * branches. The cost is that it uses a lot of 32-bit constants, which might * be bad on some architectures. */ { png_uint_32 t; /* Remove bit 5 from all but the reserved byte; this means every * 8-bit unit must be in the range 65-90 to be valid. So bit 5 * must be zero, bit 6 must be set and bit 7 zero. */ c &= ~PNG_U32(32,32,0,32); t = (c & ~0x1f1f1f1f) ^ 0x40404040; /* Subtract 65 for each 8 bit quantity, this must not overflow * and each byte must then be in the range 0-25. */ c -= PNG_U32(65,65,65,65); t |=c ; /* Subtract 26, handling the overflow which should set the top * three bits of each byte. */ c -= PNG_U32(25,25,25,26); t |= ~c; return (t & 0xe0e0e0e0) == 0; } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
chunk_type_valid(png_uint_32 c) /* Bit whacking approach to chunk name validation that is intended to avoid * branches. The cost is that it uses a lot of 32-bit constants, which might * be bad on some architectures. */ { png_uint_32 t; /* Remove bit 5 from all but the reserved byte; this means every * 8-bit unit must be in the range 65-90 to be valid. So bit 5 * must be zero, bit 6 must be set and bit 7 zero. */ c &= ~PNG_U32(32,32,0,32); t = (c & ~0x1f1f1f1f) ^ 0x40404040; /* Subtract 65 for each 8-bit quantity, this must not overflow * and each byte must then be in the range 0-25. */ c -= PNG_U32(65,65,65,65); t |=c ; /* Subtract 26, handling the overflow which should set the top * three bits of each byte. */ c -= PNG_U32(25,25,25,26); t |= ~c; return (t & 0xe0e0e0e0) == 0; }
173,730
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void StoreAccumulatedContentLength(int received_content_length, int original_content_length, bool data_reduction_proxy_was_used) { BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, base::Bind(&UpdateContentLengthPrefs, received_content_length, original_content_length, data_reduction_proxy_was_used)); } Commit Message: Added daily UMA for non-data-reduction-proxy data usage when the proxy is enabled. BUG=325325 Review URL: https://codereview.chromium.org/106113002 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@239897 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-416
void StoreAccumulatedContentLength(int received_content_length, void StoreAccumulatedContentLength( int received_content_length, int original_content_length, chrome_browser_net::DataReductionRequestType data_reduction_type) { BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, base::Bind(&UpdateContentLengthPrefs, received_content_length, original_content_length, data_reduction_type)); }
171,333
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: bool IsTraceEventArgsWhitelisted(const char* category_group_name, const char* event_name) { if (base::MatchPattern(category_group_name, "benchmark") && base::MatchPattern(event_name, "whitelisted")) { return true; } return false; } Commit Message: Tracing: Add support for PII whitelisting of individual trace event arguments R=dsinclair,shatch BUG=546093 Review URL: https://codereview.chromium.org/1415013003 Cr-Commit-Position: refs/heads/master@{#356690} CWE ID: CWE-399
bool IsTraceEventArgsWhitelisted(const char* category_group_name, bool IsTraceEventArgsWhitelisted( const char* category_group_name, const char* event_name, base::trace_event::ArgumentNameFilterPredicate* arg_filter) { if (base::MatchPattern(category_group_name, "benchmark") && base::MatchPattern(event_name, "whitelisted")) { return true; } return false; }
171,681
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void InitPrefMembers() { settings_->InitPrefMembers(); } Commit Message: Move IsDataSaverEnabledByUser to be a static method and use it This method now officially becomes the source of truth that everything in the code base eventually calls into to determine whether or not DataSaver is enabled. Bug: 934399 Change-Id: Iae837b710ace8cc3101188f79d02cbc2d4f0fd93 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1537242 Reviewed-by: Joshua Pawlicki <[email protected]> Reviewed-by: Tarun Bansal <[email protected]> Commit-Queue: Robert Ogden <[email protected]> Cr-Commit-Position: refs/heads/master@{#643948} CWE ID: CWE-119
void InitPrefMembers() {
172,560
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: display_sigset( const char *msg, sigset_t *mask ) { int signo; NameTableIterator next_sig( SigNames ); if( msg ) { dprintf( D_ALWAYS, msg ); } while( (signo = next_sig()) != -1 ) { if( sigismember(mask,signo) ) { dprintf( D_ALWAYS | D_NOHEADER, "%s ", SigNames.get_name(signo) ); } } dprintf( D_ALWAYS | D_NOHEADER, "\n" ); } Commit Message: CWE ID: CWE-134
display_sigset( const char *msg, sigset_t *mask ) { int signo; NameTableIterator next_sig( SigNames ); if( msg ) { dprintf( D_ALWAYS, "%s", msg ); } while( (signo = next_sig()) != -1 ) { if( sigismember(mask,signo) ) { dprintf( D_ALWAYS | D_NOHEADER, "%s ", SigNames.get_name(signo) ); } } dprintf( D_ALWAYS | D_NOHEADER, "\n" ); }
165,385
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: status_t OMXNodeInstance::emptyBuffer( OMX::buffer_id buffer, OMX_U32 rangeOffset, OMX_U32 rangeLength, OMX_U32 flags, OMX_TICKS timestamp, int fenceFd) { Mutex::Autolock autoLock(mLock); OMX_BUFFERHEADERTYPE *header = findBufferHeader(buffer, kPortIndexInput); if (header == NULL) { ALOGE("b/25884056"); return BAD_VALUE; } BufferMeta *buffer_meta = static_cast<BufferMeta *>(header->pAppPrivate); sp<ABuffer> backup = buffer_meta->getBuffer(header, true /* backup */, false /* limit */); sp<ABuffer> codec = buffer_meta->getBuffer(header, false /* backup */, false /* limit */); if (mMetadataType[kPortIndexInput] == kMetadataBufferTypeGrallocSource && backup->capacity() >= sizeof(VideoNativeMetadata) && codec->capacity() >= sizeof(VideoGrallocMetadata) && ((VideoNativeMetadata *)backup->base())->eType == kMetadataBufferTypeANWBuffer) { VideoNativeMetadata &backupMeta = *(VideoNativeMetadata *)backup->base(); VideoGrallocMetadata &codecMeta = *(VideoGrallocMetadata *)codec->base(); CLOG_BUFFER(emptyBuffer, "converting ANWB %p to handle %p", backupMeta.pBuffer, backupMeta.pBuffer->handle); codecMeta.pHandle = backupMeta.pBuffer != NULL ? backupMeta.pBuffer->handle : NULL; codecMeta.eType = kMetadataBufferTypeGrallocSource; header->nFilledLen = rangeLength ? sizeof(codecMeta) : 0; header->nOffset = 0; } else { if (rangeOffset > header->nAllocLen || rangeLength > header->nAllocLen - rangeOffset) { CLOG_ERROR(emptyBuffer, OMX_ErrorBadParameter, FULL_BUFFER(NULL, header, fenceFd)); if (fenceFd >= 0) { ::close(fenceFd); } return BAD_VALUE; } header->nFilledLen = rangeLength; header->nOffset = rangeOffset; buffer_meta->CopyToOMX(header); } return emptyBuffer_l(header, flags, timestamp, (intptr_t)buffer, fenceFd); } Commit Message: DO NOT MERGE: IOMX: work against metadata buffer spoofing - Prohibit direct set/getParam/Settings for extensions meant for OMXNodeInstance alone. This disallows enabling metadata mode without the knowledge of OMXNodeInstance. - Use a backup buffer for metadata mode buffers and do not directly share with clients. - Disallow setting up metadata mode/tunneling/input surface after first sendCommand. - Disallow store-meta for input cross process. - Disallow emptyBuffer for surface input (via IOMX). - Fix checking for input surface. Bug: 29422020 Change-Id: I801c77b80e703903f62e42d76fd2e76a34e4bc8e (cherry picked from commit 7c3c2fa3e233c656fc8c2fc2a6634b3ecf8a23e8) CWE ID: CWE-200
status_t OMXNodeInstance::emptyBuffer( OMX::buffer_id buffer, OMX_U32 rangeOffset, OMX_U32 rangeLength, OMX_U32 flags, OMX_TICKS timestamp, int fenceFd) { Mutex::Autolock autoLock(mLock); // no emptybuffer if using input surface if (getGraphicBufferSource() != NULL) { android_errorWriteLog(0x534e4554, "29422020"); return INVALID_OPERATION; } OMX_BUFFERHEADERTYPE *header = findBufferHeader(buffer, kPortIndexInput); if (header == NULL) { ALOGE("b/25884056"); return BAD_VALUE; } BufferMeta *buffer_meta = static_cast<BufferMeta *>(header->pAppPrivate); sp<ABuffer> backup = buffer_meta->getBuffer(header, true /* backup */, false /* limit */); sp<ABuffer> codec = buffer_meta->getBuffer(header, false /* backup */, false /* limit */); if (mMetadataType[kPortIndexInput] == kMetadataBufferTypeGrallocSource && backup->capacity() >= sizeof(VideoNativeMetadata) && codec->capacity() >= sizeof(VideoGrallocMetadata) && ((VideoNativeMetadata *)backup->base())->eType == kMetadataBufferTypeANWBuffer) { VideoNativeMetadata &backupMeta = *(VideoNativeMetadata *)backup->base(); VideoGrallocMetadata &codecMeta = *(VideoGrallocMetadata *)codec->base(); CLOG_BUFFER(emptyBuffer, "converting ANWB %p to handle %p", backupMeta.pBuffer, backupMeta.pBuffer->handle); codecMeta.pHandle = backupMeta.pBuffer != NULL ? backupMeta.pBuffer->handle : NULL; codecMeta.eType = kMetadataBufferTypeGrallocSource; header->nFilledLen = rangeLength ? sizeof(codecMeta) : 0; header->nOffset = 0; } else { if (rangeOffset > header->nAllocLen || rangeLength > header->nAllocLen - rangeOffset) { CLOG_ERROR(emptyBuffer, OMX_ErrorBadParameter, FULL_BUFFER(NULL, header, fenceFd)); if (fenceFd >= 0) { ::close(fenceFd); } return BAD_VALUE; } header->nFilledLen = rangeLength; header->nOffset = rangeOffset; buffer_meta->CopyToOMX(header); } return emptyBuffer_l(header, flags, timestamp, (intptr_t)buffer, fenceFd); }
174,133
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: GURL DevToolsWindow::GetDevToolsURL(Profile* profile, const GURL& base_url, bool shared_worker_frontend, bool v8_only_frontend, const std::string& remote_frontend, bool can_dock, const std::string& panel) { if (base_url.SchemeIs("data")) return base_url; std::string frontend_url( !remote_frontend.empty() ? remote_frontend : base_url.is_empty() ? chrome::kChromeUIDevToolsURL : base_url.spec()); std::string url_string( frontend_url + ((frontend_url.find("?") == std::string::npos) ? "?" : "&")); if (shared_worker_frontend) url_string += "&isSharedWorker=true"; if (v8_only_frontend) url_string += "&v8only=true"; if (remote_frontend.size()) { url_string += "&remoteFrontend=true"; } else { url_string += "&remoteBase=" + DevToolsUI::GetRemoteBaseURL().spec(); } if (can_dock) url_string += "&can_dock=true"; if (panel.size()) url_string += "&panel=" + panel; return DevToolsUI::SanitizeFrontendURL(GURL(url_string)); } Commit Message: DevTools: move front-end URL handling to DevToolsUIBindingds BUG=662859 Review-Url: https://codereview.chromium.org/2607833002 Cr-Commit-Position: refs/heads/master@{#440926} CWE ID: CWE-200
GURL DevToolsWindow::GetDevToolsURL(Profile* profile, const GURL& base_url, bool shared_worker_frontend, bool v8_only_frontend, const std::string& remote_frontend, bool can_dock, const std::string& panel) { if (base_url.SchemeIs("data")) return base_url; std::string frontend_url( !remote_frontend.empty() ? remote_frontend : base_url.is_empty() ? chrome::kChromeUIDevToolsURL : base_url.spec()); std::string url_string( frontend_url + ((frontend_url.find("?") == std::string::npos) ? "?" : "&")); if (shared_worker_frontend) url_string += "&isSharedWorker=true"; if (v8_only_frontend) url_string += "&v8only=true"; if (remote_frontend.size()) { url_string += "&remoteFrontend=true"; } else { url_string += "&remoteBase=" + DevToolsUI::GetRemoteBaseURL().spec(); } if (can_dock) url_string += "&can_dock=true"; if (panel.size()) url_string += "&panel=" + panel; return DevToolsUIBindings::SanitizeFrontendURL(GURL(url_string)); }
172,455
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void WebDevToolsAgentImpl::clearBrowserCache() { m_client->clearBrowserCache(); } Commit Message: [4/4] Process clearBrowserCahce/cookies commands in browser. BUG=366585 Review URL: https://codereview.chromium.org/251183005 git-svn-id: svn://svn.chromium.org/blink/trunk@172984 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID:
void WebDevToolsAgentImpl::clearBrowserCache()
171,348
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: horDiff8(TIFF* tif, uint8* cp0, tmsize_t cc) { TIFFPredictorState* sp = PredictorState(tif); tmsize_t stride = sp->stride; unsigned char* cp = (unsigned char*) cp0; assert((cc%stride)==0); if (cc > stride) { cc -= stride; /* * Pipeline the most common cases. */ if (stride == 3) { unsigned int r1, g1, b1; unsigned int r2 = cp[0]; unsigned int g2 = cp[1]; unsigned int b2 = cp[2]; do { r1 = cp[3]; cp[3] = (unsigned char)((r1-r2)&0xff); r2 = r1; g1 = cp[4]; cp[4] = (unsigned char)((g1-g2)&0xff); g2 = g1; b1 = cp[5]; cp[5] = (unsigned char)((b1-b2)&0xff); b2 = b1; cp += 3; } while ((cc -= 3) > 0); } else if (stride == 4) { unsigned int r1, g1, b1, a1; unsigned int r2 = cp[0]; unsigned int g2 = cp[1]; unsigned int b2 = cp[2]; unsigned int a2 = cp[3]; do { r1 = cp[4]; cp[4] = (unsigned char)((r1-r2)&0xff); r2 = r1; g1 = cp[5]; cp[5] = (unsigned char)((g1-g2)&0xff); g2 = g1; b1 = cp[6]; cp[6] = (unsigned char)((b1-b2)&0xff); b2 = b1; a1 = cp[7]; cp[7] = (unsigned char)((a1-a2)&0xff); a2 = a1; cp += 4; } while ((cc -= 4) > 0); } else { cp += cc - 1; do { REPEAT4(stride, cp[stride] = (unsigned char)((cp[stride] - cp[0])&0xff); cp--) } while ((cc -= stride) > 0); } } } Commit Message: * libtiff/tif_predict.h, libtiff/tif_predict.c: Replace assertions by runtime checks to avoid assertions in debug mode, or buffer overflows in release mode. Can happen when dealing with unusual tile size like YCbCr with subsampling. Reported as MSVR 35105 by Axel Souchet & Vishal Chauhan from the MSRC Vulnerabilities & Mitigations team. CWE ID: CWE-119
horDiff8(TIFF* tif, uint8* cp0, tmsize_t cc) { TIFFPredictorState* sp = PredictorState(tif); tmsize_t stride = sp->stride; unsigned char* cp = (unsigned char*) cp0; if((cc%stride)!=0) { TIFFErrorExt(tif->tif_clientdata, "horDiff8", "%s", "(cc%stride)!=0"); return 0; } if (cc > stride) { cc -= stride; /* * Pipeline the most common cases. */ if (stride == 3) { unsigned int r1, g1, b1; unsigned int r2 = cp[0]; unsigned int g2 = cp[1]; unsigned int b2 = cp[2]; do { r1 = cp[3]; cp[3] = (unsigned char)((r1-r2)&0xff); r2 = r1; g1 = cp[4]; cp[4] = (unsigned char)((g1-g2)&0xff); g2 = g1; b1 = cp[5]; cp[5] = (unsigned char)((b1-b2)&0xff); b2 = b1; cp += 3; } while ((cc -= 3) > 0); } else if (stride == 4) { unsigned int r1, g1, b1, a1; unsigned int r2 = cp[0]; unsigned int g2 = cp[1]; unsigned int b2 = cp[2]; unsigned int a2 = cp[3]; do { r1 = cp[4]; cp[4] = (unsigned char)((r1-r2)&0xff); r2 = r1; g1 = cp[5]; cp[5] = (unsigned char)((g1-g2)&0xff); g2 = g1; b1 = cp[6]; cp[6] = (unsigned char)((b1-b2)&0xff); b2 = b1; a1 = cp[7]; cp[7] = (unsigned char)((a1-a2)&0xff); a2 = a1; cp += 4; } while ((cc -= 4) > 0); } else { cp += cc - 1; do { REPEAT4(stride, cp[stride] = (unsigned char)((cp[stride] - cp[0])&0xff); cp--) } while ((cc -= stride) > 0); } } return 1; }
166,887
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static void ikev2_parent_outI1_continue(struct pluto_crypto_req_cont *pcrc, struct pluto_crypto_req *r, err_t ugh) { struct ke_continuation *ke = (struct ke_continuation *)pcrc; struct msg_digest *md = ke->md; struct state *const st = md->st; stf_status e; DBG(DBG_CONTROLMORE, DBG_log("ikev2 parent outI1: calculated ke+nonce, sending I1")); if (st == NULL) { loglog(RC_LOG_SERIOUS, "%s: Request was disconnected from state", __FUNCTION__); if (ke->md) release_md(ke->md); return; } /* XXX should check out ugh */ passert(ugh == NULL); passert(cur_state == NULL); passert(st != NULL); passert(st->st_suspended_md == ke->md); set_suspended(st, NULL); /* no longer connected or suspended */ set_cur_state(st); st->st_calculating = FALSE; e = ikev2_parent_outI1_tail(pcrc, r); if (ke->md != NULL) { complete_v2_state_transition(&ke->md, e); if (ke->md) release_md(ke->md); } reset_cur_state(); reset_globals(); passert(GLOBALS_ARE_RESET()); } Commit Message: SECURITY: Properly handle IKEv2 I1 notification packet without KE payload CWE ID: CWE-20
static void ikev2_parent_outI1_continue(struct pluto_crypto_req_cont *pcrc, struct pluto_crypto_req *r, err_t ugh) { struct ke_continuation *ke = (struct ke_continuation *)pcrc; struct msg_digest *md = ke->md; struct state *const st = md->st; stf_status e; DBG(DBG_CONTROLMORE, DBG_log("ikev2 parent outI1: calculated ke+nonce, sending I1")); if (st == NULL) { loglog(RC_LOG_SERIOUS, "%s: Request was disconnected from state", __FUNCTION__); if (ke->md) release_md(ke->md); return; } /* XXX should check out ugh */ passert(ugh == NULL); passert(cur_state == NULL); passert(st != NULL); passert(st->st_suspended_md == ke->md); set_suspended(st, NULL); /* no longer connected or suspended */ set_cur_state(st); st->st_calculating = FALSE; e = ikev2_parent_outI1_tail(pcrc, r); if (ke->md != NULL) { complete_v2_state_transition(&ke->md, e); if (ke->md) release_md(ke->md); } reset_cur_state(); reset_globals(); }
166,473
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: ExtensionInstallDialogView::ExtensionInstallDialogView( Profile* profile, content::PageNavigator* navigator, const ExtensionInstallPrompt::DoneCallback& done_callback, std::unique_ptr<ExtensionInstallPrompt::Prompt> prompt) : profile_(profile), navigator_(navigator), done_callback_(done_callback), prompt_(std::move(prompt)), container_(NULL), scroll_view_(NULL), handled_result_(false) { InitView(); } Commit Message: [Extensions UI] Initially disabled OK button for extension install prompts and enable them after a 500 ms time period. BUG=394518 Review-Url: https://codereview.chromium.org/2716353003 Cr-Commit-Position: refs/heads/master@{#461933} CWE ID: CWE-20
ExtensionInstallDialogView::ExtensionInstallDialogView( Profile* profile, content::PageNavigator* navigator, const ExtensionInstallPrompt::DoneCallback& done_callback, std::unique_ptr<ExtensionInstallPrompt::Prompt> prompt) : profile_(profile), navigator_(navigator), done_callback_(done_callback), prompt_(std::move(prompt)), container_(NULL), scroll_view_(NULL), handled_result_(false), install_button_enabled_(false) { InitView(); }
173,159
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: my_object_unstringify (MyObject *obj, const char *str, GValue *value, GError **error) { if (str[0] == '\0' || !g_ascii_isdigit (str[0])) { g_value_init (value, G_TYPE_STRING); g_value_set_string (value, str); } else { g_value_init (value, G_TYPE_INT); g_value_set_int (value, (int) g_ascii_strtoull (str, NULL, 10)); } return TRUE; } Commit Message: CWE ID: CWE-264
my_object_unstringify (MyObject *obj, const char *str, GValue *value, GError **error)
165,125
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: pipe_iov_copy_from_user(void *to, struct iovec *iov, unsigned long len, int atomic) { unsigned long copy; while (len > 0) { while (!iov->iov_len) iov++; copy = min_t(unsigned long, len, iov->iov_len); if (atomic) { if (__copy_from_user_inatomic(to, iov->iov_base, copy)) return -EFAULT; } else { if (copy_from_user(to, iov->iov_base, copy)) return -EFAULT; } to += copy; len -= copy; iov->iov_base += copy; iov->iov_len -= copy; } return 0; } Commit Message: new helper: copy_page_from_iter() parallel to copy_page_to_iter(). pipe_write() switched to it (and became ->write_iter()). Signed-off-by: Al Viro <[email protected]> CWE ID: CWE-17
pipe_iov_copy_from_user(void *to, struct iovec *iov, unsigned long len,
166,686
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void usage_exit() { fprintf(stderr, "Usage: %s <codec> <width> <height> <infile> <outfile> " "<keyframe-interval> [<error-resilient>]\nSee comments in " "simple_encoder.c for more information.\n", exec_name); exit(EXIT_FAILURE); } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119
void usage_exit() { void usage_exit(void) { fprintf(stderr, "Usage: %s <codec> <width> <height> <infile> <outfile> " "<keyframe-interval> [<error-resilient>]\nSee comments in " "simple_encoder.c for more information.\n", exec_name); exit(EXIT_FAILURE); }
174,490
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static int asymmetric_key_match(const struct key *key, const struct key_match_data *match_data) { const struct asymmetric_key_subtype *subtype = asymmetric_key_subtype(key); const char *description = match_data->raw_data; const char *spec = description; const char *id; ptrdiff_t speclen; if (!subtype || !spec || !*spec) return 0; /* See if the full key description matches as is */ if (key->description && strcmp(key->description, description) == 0) return 1; /* All tests from here on break the criterion description into a * specifier, a colon and then an identifier. */ id = strchr(spec, ':'); if (!id) return 0; speclen = id - spec; id++; if (speclen == 2 && memcmp(spec, "id", 2) == 0) return asymmetric_keyid_match(asymmetric_key_id(key), id); if (speclen == subtype->name_len && memcmp(spec, subtype->name, speclen) == 0) return 1; return 0; } Commit Message: KEYS: Remove key_type::match in favour of overriding default by match_preparse A previous patch added a ->match_preparse() method to the key type. This is allowed to override the function called by the iteration algorithm. Therefore, we can just set a default that simply checks for an exact match of the key description with the original criterion data and allow match_preparse to override it as needed. The key_type::match op is then redundant and can be removed, as can the user_match() function. Signed-off-by: David Howells <[email protected]> Acked-by: Vivek Goyal <[email protected]> CWE ID: CWE-476
static int asymmetric_key_match(const struct key *key, static int asymmetric_key_cmp(const struct key *key, const struct key_match_data *match_data) { const struct asymmetric_key_subtype *subtype = asymmetric_key_subtype(key); const char *description = match_data->raw_data; const char *spec = description; const char *id; ptrdiff_t speclen; if (!subtype || !spec || !*spec) return 0; /* See if the full key description matches as is */ if (key->description && strcmp(key->description, description) == 0) return 1; /* All tests from here on break the criterion description into a * specifier, a colon and then an identifier. */ id = strchr(spec, ':'); if (!id) return 0; speclen = id - spec; id++; if (speclen == 2 && memcmp(spec, "id", 2) == 0) return asymmetric_keyid_match(asymmetric_key_id(key), id); if (speclen == subtype->name_len && memcmp(spec, subtype->name, speclen) == 0) return 1; return 0; }
168,436
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: long long BlockGroup::GetDurationTimeCode() const { return m_duration; } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
long long BlockGroup::GetDurationTimeCode() const
174,308
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: image_transform_png_set_strip_alpha_mod(PNG_CONST image_transform *this, image_pixel *that, png_const_structp pp, PNG_CONST transform_display *display) { if (that->colour_type == PNG_COLOR_TYPE_GRAY_ALPHA) that->colour_type = PNG_COLOR_TYPE_GRAY; else if (that->colour_type == PNG_COLOR_TYPE_RGB_ALPHA) that->colour_type = PNG_COLOR_TYPE_RGB; that->have_tRNS = 0; that->alphaf = 1; this->next->mod(this->next, that, pp, display); } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
image_transform_png_set_strip_alpha_mod(PNG_CONST image_transform *this, image_transform_png_set_strip_alpha_mod(const image_transform *this, image_pixel *that, png_const_structp pp, const transform_display *display) { if (that->colour_type == PNG_COLOR_TYPE_GRAY_ALPHA) that->colour_type = PNG_COLOR_TYPE_GRAY; else if (that->colour_type == PNG_COLOR_TYPE_RGB_ALPHA) that->colour_type = PNG_COLOR_TYPE_RGB; that->have_tRNS = 0; that->alphaf = 1; this->next->mod(this->next, that, pp, display); }
173,652
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void WorkerProcessLauncherTest::SetUp() { task_runner_ = new AutoThreadTaskRunner( message_loop_.message_loop_proxy(), base::Bind(&WorkerProcessLauncherTest::QuitMainMessageLoop, base::Unretained(this))); exit_code_ = STILL_ACTIVE; launcher_delegate_.reset(new MockProcessLauncherDelegate()); EXPECT_CALL(*launcher_delegate_, Send(_)) .Times(AnyNumber()) .WillRepeatedly(Return(false)); EXPECT_CALL(*launcher_delegate_, GetExitCode()) .Times(AnyNumber()) .WillRepeatedly(ReturnPointee(&exit_code_)); EXPECT_CALL(*launcher_delegate_, KillProcess(_)) .Times(AnyNumber()) .WillRepeatedly(Invoke(this, &WorkerProcessLauncherTest::KillProcess)); EXPECT_CALL(ipc_delegate_, OnMessageReceived(_)) .Times(AnyNumber()) .WillRepeatedly(Return(false)); } Commit Message: Validate and report peer's PID to WorkerProcessIpcDelegate so it will be able to duplicate handles to and from the worker process. As a side effect WorkerProcessLauncher::Delegate is now responsible for retrieving the client's PID and deciding whether a launch failed due to a permanent error condition. BUG=134694 Review URL: https://chromiumcodereview.appspot.com/11143025 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@162778 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void WorkerProcessLauncherTest::SetUp() { task_runner_ = new AutoThreadTaskRunner( message_loop_.message_loop_proxy(), base::Bind(&WorkerProcessLauncherTest::QuitMainMessageLoop, base::Unretained(this))); launcher_delegate_.reset(new MockProcessLauncherDelegate()); EXPECT_CALL(*launcher_delegate_, Send(_)) .Times(AnyNumber()) .WillRepeatedly(Return(false)); EXPECT_CALL(*launcher_delegate_, GetProcessId()) .Times(AnyNumber()) .WillRepeatedly(ReturnPointee(&client_pid_)); EXPECT_CALL(*launcher_delegate_, IsPermanentError(_)) .Times(AnyNumber()) .WillRepeatedly(ReturnPointee(&permanent_error_)); EXPECT_CALL(*launcher_delegate_, KillProcess(_)) .Times(AnyNumber()) .WillRepeatedly(Invoke(this, &WorkerProcessLauncherTest::KillProcess)); EXPECT_CALL(ipc_delegate_, OnMessageReceived(_)) .Times(AnyNumber()) .WillRepeatedly(Return(false)); }
171,552
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: LogLuvClose(TIFF* tif) { TIFFDirectory *td = &tif->tif_dir; /* * For consistency, we always want to write out the same * bitspersample and sampleformat for our TIFF file, * regardless of the data format being used by the application. * Since this routine is called after tags have been set but * before they have been recorded in the file, we reset them here. */ td->td_samplesperpixel = (td->td_photometric == PHOTOMETRIC_LOGL) ? 1 : 3; td->td_bitspersample = 16; td->td_sampleformat = SAMPLEFORMAT_INT; } Commit Message: * libtiff/tif_pixarlog.c, libtiff/tif_luv.c: fix heap-based buffer overflow on generation of PixarLog / LUV compressed files, with ColorMap, TransferFunction attached and nasty plays with bitspersample. The fix for LUV has not been tested, but suffers from the same kind of issue of PixarLog. Reported by Agostino Sarubbo. Fixes http://bugzilla.maptools.org/show_bug.cgi?id=2604 CWE ID: CWE-125
LogLuvClose(TIFF* tif) { LogLuvState* sp = (LogLuvState*) tif->tif_data; TIFFDirectory *td = &tif->tif_dir; assert(sp != 0); /* * For consistency, we always want to write out the same * bitspersample and sampleformat for our TIFF file, * regardless of the data format being used by the application. * Since this routine is called after tags have been set but * before they have been recorded in the file, we reset them here. * Note: this is really a nasty approach. See PixarLogClose */ if( sp->encoder_state ) { /* See PixarLogClose. Might avoid issues with tags whose size depends * on those below, but not completely sure this is enough. */ td->td_samplesperpixel = (td->td_photometric == PHOTOMETRIC_LOGL) ? 1 : 3; td->td_bitspersample = 16; td->td_sampleformat = SAMPLEFORMAT_INT; } }
168,464
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: HeapObjectHeader* NormalPage::findHeaderFromAddress(Address address) { if (address < payload()) return nullptr; if (!m_objectStartBitMapComputed) populateObjectStartBitMap(); size_t objectOffset = address - payload(); size_t objectStartNumber = objectOffset / allocationGranularity; size_t mapIndex = objectStartNumber / 8; ASSERT(mapIndex < objectStartBitMapSize); size_t bit = objectStartNumber & 7; uint8_t byte = m_objectStartBitMap[mapIndex] & ((1 << (bit + 1)) - 1); while (!byte) { ASSERT(mapIndex > 0); byte = m_objectStartBitMap[--mapIndex]; } int leadingZeroes = numberOfLeadingZeroes(byte); objectStartNumber = (mapIndex * 8) + 7 - leadingZeroes; objectOffset = objectStartNumber * allocationGranularity; Address objectAddress = objectOffset + payload(); HeapObjectHeader* header = reinterpret_cast<HeapObjectHeader*>(objectAddress); if (header->isFree()) return nullptr; ASSERT(header->checkHeader()); return header; } Commit Message: Call HeapObjectHeader::checkHeader solely for its side-effect. This requires changing its signature. This is a preliminary stage to making it private. BUG=633030 Review-Url: https://codereview.chromium.org/2698673003 Cr-Commit-Position: refs/heads/master@{#460489} CWE ID: CWE-119
HeapObjectHeader* NormalPage::findHeaderFromAddress(Address address) { if (address < payload()) return nullptr; if (!m_objectStartBitMapComputed) populateObjectStartBitMap(); size_t objectOffset = address - payload(); size_t objectStartNumber = objectOffset / allocationGranularity; size_t mapIndex = objectStartNumber / 8; ASSERT(mapIndex < objectStartBitMapSize); size_t bit = objectStartNumber & 7; uint8_t byte = m_objectStartBitMap[mapIndex] & ((1 << (bit + 1)) - 1); while (!byte) { ASSERT(mapIndex > 0); byte = m_objectStartBitMap[--mapIndex]; } int leadingZeroes = numberOfLeadingZeroes(byte); objectStartNumber = (mapIndex * 8) + 7 - leadingZeroes; objectOffset = objectStartNumber * allocationGranularity; Address objectAddress = objectOffset + payload(); HeapObjectHeader* header = reinterpret_cast<HeapObjectHeader*>(objectAddress); if (header->isFree()) return nullptr; header->checkHeader(); return header; }
172,711
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: BIGNUM *SRP_Calc_u(BIGNUM *A, BIGNUM *B, BIGNUM *N) { /* k = SHA1(PAD(A) || PAD(B) ) -- tls-srp draft 8 */ BIGNUM *u; unsigned char cu[SHA_DIGEST_LENGTH]; unsigned char *cAB; EVP_MD_CTX ctxt; int longN; if ((A == NULL) ||(B == NULL) || (N == NULL)) return NULL; if ((A == NULL) ||(B == NULL) || (N == NULL)) return NULL; longN= BN_num_bytes(N); if ((cAB = OPENSSL_malloc(2*longN)) == NULL) EVP_DigestUpdate(&ctxt, cAB + BN_bn2bin(A,cAB+longN), longN); EVP_DigestUpdate(&ctxt, cAB + BN_bn2bin(B,cAB+longN), longN); OPENSSL_free(cAB); EVP_DigestFinal_ex(&ctxt, cu, NULL); EVP_MD_CTX_cleanup(&ctxt); if (!(u = BN_bin2bn(cu, sizeof(cu), NULL))) return NULL; if (!BN_is_zero(u)) return u; BN_free(u); return NULL; } Commit Message: CWE ID: CWE-119
BIGNUM *SRP_Calc_u(BIGNUM *A, BIGNUM *B, BIGNUM *N) { /* k = SHA1(PAD(A) || PAD(B) ) -- tls-srp draft 8 */ BIGNUM *u; unsigned char cu[SHA_DIGEST_LENGTH]; unsigned char *cAB; EVP_MD_CTX ctxt; int longN; if ((A == NULL) ||(B == NULL) || (N == NULL)) return NULL; if ((A == NULL) ||(B == NULL) || (N == NULL)) return NULL; if (BN_ucmp(A, N) >= 0 || BN_ucmp(B, N) >= 0) return NULL; longN= BN_num_bytes(N); if ((cAB = OPENSSL_malloc(2*longN)) == NULL) EVP_DigestUpdate(&ctxt, cAB + BN_bn2bin(A,cAB+longN), longN); EVP_DigestUpdate(&ctxt, cAB + BN_bn2bin(B,cAB+longN), longN); OPENSSL_free(cAB); EVP_DigestFinal_ex(&ctxt, cu, NULL); EVP_MD_CTX_cleanup(&ctxt); if (!(u = BN_bin2bn(cu, sizeof(cu), NULL))) return NULL; if (!BN_is_zero(u)) return u; BN_free(u); return NULL; }
165,172
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void MarkingVisitor::ConservativelyMarkHeader(HeapObjectHeader* header) { const GCInfo* gc_info = ThreadHeap::GcInfo(header->GcInfoIndex()); if (gc_info->HasVTable() && !VTableInitialized(header->Payload())) { MarkHeaderNoTracing(header); #if DCHECK_IS_ON() DCHECK(IsUninitializedMemory(header->Payload(), header->PayloadSize())); #endif } else { MarkHeader(header, gc_info->trace_); } } Commit Message: [oilpan] Fix GCInfoTable for multiple threads Previously, grow and access from different threads could lead to a race on the table backing; see bug. - Rework the table to work on an existing reservation. - Commit upon growing, avoiding any copies. Drive-by: Fix over-allocation of table. Bug: chromium:841280 Change-Id: I329cb6f40091e14e8c05334ba1104a9440c31d43 Reviewed-on: https://chromium-review.googlesource.com/1061525 Commit-Queue: Michael Lippautz <[email protected]> Reviewed-by: Kentaro Hara <[email protected]> Cr-Commit-Position: refs/heads/master@{#560434} CWE ID: CWE-362
void MarkingVisitor::ConservativelyMarkHeader(HeapObjectHeader* header) { const GCInfo* gc_info = GCInfoTable::Get().GCInfoFromIndex(header->GcInfoIndex()); if (gc_info->HasVTable() && !VTableInitialized(header->Payload())) { MarkHeaderNoTracing(header); #if DCHECK_IS_ON() DCHECK(IsUninitializedMemory(header->Payload(), header->PayloadSize())); #endif } else { MarkHeader(header, gc_info->trace_); } }
173,141
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static struct nfs4_state *nfs4_do_open(struct inode *dir, struct path *path, int flags, struct iattr *sattr, struct rpc_cred *cred) { struct nfs4_exception exception = { }; struct nfs4_state *res; int status; do { status = _nfs4_do_open(dir, path, flags, sattr, cred, &res); if (status == 0) break; /* NOTE: BAD_SEQID means the server and client disagree about the * book-keeping w.r.t. state-changing operations * (OPEN/CLOSE/LOCK/LOCKU...) * It is actually a sign of a bug on the client or on the server. * * If we receive a BAD_SEQID error in the particular case of * doing an OPEN, we assume that nfs_increment_open_seqid() will * have unhashed the old state_owner for us, and that we can * therefore safely retry using a new one. We should still warn * the user though... */ if (status == -NFS4ERR_BAD_SEQID) { printk(KERN_WARNING "NFS: v4 server %s " " returned a bad sequence-id error!\n", NFS_SERVER(dir)->nfs_client->cl_hostname); exception.retry = 1; continue; } /* * BAD_STATEID on OPEN means that the server cancelled our * state before it received the OPEN_CONFIRM. * Recover by retrying the request as per the discussion * on Page 181 of RFC3530. */ if (status == -NFS4ERR_BAD_STATEID) { exception.retry = 1; continue; } if (status == -EAGAIN) { /* We must have found a delegation */ exception.retry = 1; continue; } res = ERR_PTR(nfs4_handle_exception(NFS_SERVER(dir), status, &exception)); } while (exception.retry); return res; } Commit Message: NFSv4: Convert the open and close ops to use fmode Signed-off-by: Trond Myklebust <[email protected]> CWE ID:
static struct nfs4_state *nfs4_do_open(struct inode *dir, struct path *path, int flags, struct iattr *sattr, struct rpc_cred *cred) static struct nfs4_state *nfs4_do_open(struct inode *dir, struct path *path, fmode_t fmode, int flags, struct iattr *sattr, struct rpc_cred *cred) { struct nfs4_exception exception = { }; struct nfs4_state *res; int status; do { status = _nfs4_do_open(dir, path, fmode, flags, sattr, cred, &res); if (status == 0) break; /* NOTE: BAD_SEQID means the server and client disagree about the * book-keeping w.r.t. state-changing operations * (OPEN/CLOSE/LOCK/LOCKU...) * It is actually a sign of a bug on the client or on the server. * * If we receive a BAD_SEQID error in the particular case of * doing an OPEN, we assume that nfs_increment_open_seqid() will * have unhashed the old state_owner for us, and that we can * therefore safely retry using a new one. We should still warn * the user though... */ if (status == -NFS4ERR_BAD_SEQID) { printk(KERN_WARNING "NFS: v4 server %s " " returned a bad sequence-id error!\n", NFS_SERVER(dir)->nfs_client->cl_hostname); exception.retry = 1; continue; } /* * BAD_STATEID on OPEN means that the server cancelled our * state before it received the OPEN_CONFIRM. * Recover by retrying the request as per the discussion * on Page 181 of RFC3530. */ if (status == -NFS4ERR_BAD_STATEID) { exception.retry = 1; continue; } if (status == -EAGAIN) { /* We must have found a delegation */ exception.retry = 1; continue; } res = ERR_PTR(nfs4_handle_exception(NFS_SERVER(dir), status, &exception)); } while (exception.retry); return res; }
165,692
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: bool SharedMemory::Create(const SharedMemoryCreateOptions& options) { DCHECK(!options.executable); DCHECK(!mapped_file_); if (options.size == 0) return false; uint32 rounded_size = (options.size + 0xffff) & ~0xffff; name_ = ASCIIToWide(options.name == NULL ? "" : *options.name); mapped_file_ = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, static_cast<DWORD>(rounded_size), name_.empty() ? NULL : name_.c_str()); if (!mapped_file_) return false; created_size_ = options.size; if (GetLastError() == ERROR_ALREADY_EXISTS) { created_size_ = 0; if (!options.open_existing) { Close(); return false; } } return true; } Commit Message: Fix integer overflow in Windows shared memory handling. BUG=164490 Review URL: https://codereview.chromium.org/11450016 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171369 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-189
bool SharedMemory::Create(const SharedMemoryCreateOptions& options) { DCHECK(!options.executable); DCHECK(!mapped_file_); if (options.size == 0) return false; uint32 rounded_size = (options.size + 0xffff) & ~0xffff; if (rounded_size < options.size) return false; name_ = ASCIIToWide(options.name == NULL ? "" : *options.name); mapped_file_ = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, static_cast<DWORD>(rounded_size), name_.empty() ? NULL : name_.c_str()); if (!mapped_file_) return false; created_size_ = options.size; if (GetLastError() == ERROR_ALREADY_EXISTS) { created_size_ = 0; if (!options.open_existing) { Close(); return false; } } return true; }
171,538
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void PrintWebViewHelper::OnPrintPreview(const base::DictionaryValue& settings) { print_preview_context_.OnPrintPreview(); UMA_HISTOGRAM_ENUMERATION("PrintPreview.PreviewEvent", PREVIEW_EVENT_REQUESTED, PREVIEW_EVENT_MAX); if (!print_preview_context_.source_frame()) { DidFinishPrinting(FAIL_PREVIEW); return; } if (!UpdatePrintSettings(print_preview_context_.source_frame(), print_preview_context_.source_node(), settings)) { if (print_preview_context_.last_error() != PREVIEW_ERROR_BAD_SETTING) { Send(new PrintHostMsg_PrintPreviewInvalidPrinterSettings( routing_id(), print_pages_params_ ? print_pages_params_->params.document_cookie : 0)); notify_browser_of_print_failure_ = false; // Already sent. } DidFinishPrinting(FAIL_PREVIEW); return; } if (print_pages_params_->params.is_first_request && !print_preview_context_.IsModifiable()) { PrintHostMsg_SetOptionsFromDocument_Params options; if (SetOptionsFromPdfDocument(&options)) Send(new PrintHostMsg_SetOptionsFromDocument(routing_id(), options)); } is_print_ready_metafile_sent_ = false; print_pages_params_->params.supports_alpha_blend = true; bool generate_draft_pages = false; if (!settings.GetBoolean(kSettingGenerateDraftData, &generate_draft_pages)) { NOTREACHED(); } print_preview_context_.set_generate_draft_pages(generate_draft_pages); PrepareFrameForPreviewDocument(); } Commit Message: Crash on nested IPC handlers in PrintWebViewHelper Class is not designed to handle nested IPC. Regular flows also does not expect them. Still during printing of plugging them may show message boxes and start nested message loops. For now we are going just crash. If stats show us that this case is frequent we will have to do something more complicated. BUG=502562 Review URL: https://codereview.chromium.org/1228693002 Cr-Commit-Position: refs/heads/master@{#338100} CWE ID:
void PrintWebViewHelper::OnPrintPreview(const base::DictionaryValue& settings) { CHECK_LE(ipc_nesting_level_, 1); print_preview_context_.OnPrintPreview(); UMA_HISTOGRAM_ENUMERATION("PrintPreview.PreviewEvent", PREVIEW_EVENT_REQUESTED, PREVIEW_EVENT_MAX); if (!print_preview_context_.source_frame()) { DidFinishPrinting(FAIL_PREVIEW); return; } if (!UpdatePrintSettings(print_preview_context_.source_frame(), print_preview_context_.source_node(), settings)) { if (print_preview_context_.last_error() != PREVIEW_ERROR_BAD_SETTING) { Send(new PrintHostMsg_PrintPreviewInvalidPrinterSettings( routing_id(), print_pages_params_ ? print_pages_params_->params.document_cookie : 0)); notify_browser_of_print_failure_ = false; // Already sent. } DidFinishPrinting(FAIL_PREVIEW); return; } if (print_pages_params_->params.is_first_request && !print_preview_context_.IsModifiable()) { PrintHostMsg_SetOptionsFromDocument_Params options; if (SetOptionsFromPdfDocument(&options)) Send(new PrintHostMsg_SetOptionsFromDocument(routing_id(), options)); } is_print_ready_metafile_sent_ = false; print_pages_params_->params.supports_alpha_blend = true; bool generate_draft_pages = false; if (!settings.GetBoolean(kSettingGenerateDraftData, &generate_draft_pages)) { NOTREACHED(); } print_preview_context_.set_generate_draft_pages(generate_draft_pages); PrepareFrameForPreviewDocument(); }
171,876