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: static void become_daemon(const char *pidfile) { #ifndef _WIN32 pid_t pid, sid; pid = fork(); if (pid < 0) { exit(EXIT_FAILURE); } if (pid > 0) { exit(EXIT_SUCCESS); } if (pidfile) { if (!ga_open_pidfile(pidfile)) { g_critical("failed to create pidfile"); exit(EXIT_FAILURE); } } umask(0); sid = setsid(); if (sid < 0) { goto fail; } if ((chdir("/")) < 0) { goto fail; } reopen_fd_to_null(STDIN_FILENO); reopen_fd_to_null(STDOUT_FILENO); reopen_fd_to_null(STDERR_FILENO); return; fail: if (pidfile) { unlink(pidfile); } g_critical("failed to daemonize"); exit(EXIT_FAILURE); #endif } Commit Message: CWE ID: CWE-264
static void become_daemon(const char *pidfile) { #ifndef _WIN32 pid_t pid, sid; pid = fork(); if (pid < 0) { exit(EXIT_FAILURE); } if (pid > 0) { exit(EXIT_SUCCESS); } if (pidfile) { if (!ga_open_pidfile(pidfile)) { g_critical("failed to create pidfile"); exit(EXIT_FAILURE); } } umask(S_IRWXG | S_IRWXO); sid = setsid(); if (sid < 0) { goto fail; } if ((chdir("/")) < 0) { goto fail; } reopen_fd_to_null(STDIN_FILENO); reopen_fd_to_null(STDOUT_FILENO); reopen_fd_to_null(STDERR_FILENO); return; fail: if (pidfile) { unlink(pidfile); } g_critical("failed to daemonize"); exit(EXIT_FAILURE); #endif }
164,724
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 copyMono16( short *dst, const int *const *src, unsigned nSamples, unsigned /* nChannels */) { for (unsigned i = 0; i < nSamples; ++i) { *dst++ = src[0][i]; } } Commit Message: FLACExtractor: copy protect mWriteBuffer Bug: 30895578 Change-Id: I4cba36bbe3502678210e5925181683df9726b431 CWE ID: CWE-119
static void copyMono16( short *dst, const int * src[FLACParser::kMaxChannels], unsigned nSamples, unsigned /* nChannels */) { for (unsigned i = 0; i < nSamples; ++i) { *dst++ = src[0][i]; } }
174,015
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 InspectorTraceEvents::WillSendRequest( ExecutionContext*, unsigned long identifier, DocumentLoader* loader, ResourceRequest& request, const ResourceResponse& redirect_response, const FetchInitiatorInfo&) { LocalFrame* frame = loader ? loader->GetFrame() : nullptr; TRACE_EVENT_INSTANT1( "devtools.timeline", "ResourceSendRequest", TRACE_EVENT_SCOPE_THREAD, "data", InspectorSendRequestEvent::Data(identifier, frame, request)); probe::AsyncTaskScheduled(frame ? frame->GetDocument() : nullptr, "SendRequest", AsyncId(identifier)); } Commit Message: DevTools: send proper resource type in Network.RequestWillBeSent This patch plumbs resoure type into the DispatchWillSendRequest instrumenation. This allows us to report accurate type in Network.RequestWillBeSent event, instead of "Other", that we report today. BUG=765501 R=dgozman Change-Id: I0134c08b841e8dd247fdc8ff208bfd51e462709c Reviewed-on: https://chromium-review.googlesource.com/667504 Reviewed-by: Pavel Feldman <pfeldman@chromium.org> Reviewed-by: Dmitry Gozman <dgozman@chromium.org> Commit-Queue: Andrey Lushnikov <lushnikov@chromium.org> Cr-Commit-Position: refs/heads/master@{#507936} CWE ID: CWE-119
void InspectorTraceEvents::WillSendRequest( ExecutionContext*, unsigned long identifier, DocumentLoader* loader, ResourceRequest& request, const ResourceResponse& redirect_response, const FetchInitiatorInfo&, Resource::Type) { LocalFrame* frame = loader ? loader->GetFrame() : nullptr; TRACE_EVENT_INSTANT1( "devtools.timeline", "ResourceSendRequest", TRACE_EVENT_SCOPE_THREAD, "data", InspectorSendRequestEvent::Data(identifier, frame, request)); probe::AsyncTaskScheduled(frame ? frame->GetDocument() : nullptr, "SendRequest", AsyncId(identifier)); }
172,471
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 utf16_to_utf8_length(const char16_t *src, size_t src_len) { if (src == NULL || src_len == 0) { return -1; } size_t ret = 0; const char16_t* const end = src + src_len; while (src < end) { if ((*src & 0xFC00) == 0xD800 && (src + 1) < end && (*++src & 0xFC00) == 0xDC00) { ret += 4; src++; } else { ret += utf32_codepoint_utf8_length((char32_t) *src++); } } return ret; } Commit Message: libutils/Unicode.cpp: Correct length computation and add checks for utf16->utf8 Inconsistent behaviour between utf16_to_utf8 and utf16_to_utf8_length is causing a heap overflow. Correcting the length computation and adding bound checks to the conversion functions. Test: ran libutils_tests Bug: 29250543 Change-Id: I6115e3357141ed245c63c6eb25fc0fd0a9a7a2bb (cherry picked from commit c4966a363e46d2e1074d1a365e232af0dcedd6a1) CWE ID: CWE-119
ssize_t utf16_to_utf8_length(const char16_t *src, size_t src_len) { if (src == NULL || src_len == 0) { return -1; } size_t ret = 0; const char16_t* const end = src + src_len; while (src < end) { if ((*src & 0xFC00) == 0xD800 && (src + 1) < end && (*(src + 1) & 0xFC00) == 0xDC00) { ret += 4; src += 2; } else { ret += utf32_codepoint_utf8_length((char32_t) *src++); } } return ret; }
173,420
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: psf_fwrite (const void *ptr, sf_count_t bytes, sf_count_t items, SF_PRIVATE *psf) { sf_count_t total = 0 ; ssize_t count ; if (psf->virtual_io) return psf->vio.write (ptr, bytes*items, psf->vio_user_data) / bytes ; items *= bytes ; /* Do this check after the multiplication above. */ if (items <= 0) return 0 ; while (items > 0) { /* Break the writes down to a sensible size. */ count = (items > SENSIBLE_SIZE) ? SENSIBLE_SIZE : items ; count = write (psf->file.filedes, ((const char*) ptr) + total, count) ; if (count == -1) { if (errno == EINTR) continue ; psf_log_syserr (psf, errno) ; break ; } ; if (count == 0) break ; total += count ; items -= count ; } ; if (psf->is_pipe) psf->pipeoffset += total ; return total / bytes ; } /* psf_fwrite */ Commit Message: src/file_io.c : Prevent potential divide-by-zero. Closes: https://github.com/erikd/libsndfile/issues/92 CWE ID: CWE-189
psf_fwrite (const void *ptr, sf_count_t bytes, sf_count_t items, SF_PRIVATE *psf) { sf_count_t total = 0 ; ssize_t count ; if (bytes == 0 || items == 0) return 0 ; if (psf->virtual_io) return psf->vio.write (ptr, bytes*items, psf->vio_user_data) / bytes ; items *= bytes ; /* Do this check after the multiplication above. */ if (items <= 0) return 0 ; while (items > 0) { /* Break the writes down to a sensible size. */ count = (items > SENSIBLE_SIZE) ? SENSIBLE_SIZE : items ; count = write (psf->file.filedes, ((const char*) ptr) + total, count) ; if (count == -1) { if (errno == EINTR) continue ; psf_log_syserr (psf, errno) ; break ; } ; if (count == 0) break ; total += count ; items -= count ; } ; if (psf->is_pipe) psf->pipeoffset += total ; return total / bytes ; } /* psf_fwrite */
166,754
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 vp9_alloc_context_buffers(VP9_COMMON *cm, int width, int height) { int new_mi_size; vp9_set_mb_mi(cm, width, height); new_mi_size = cm->mi_stride * calc_mi_size(cm->mi_rows); if (cm->mi_alloc_size < new_mi_size) { cm->free_mi(cm); if (cm->alloc_mi(cm, new_mi_size)) goto fail; } if (cm->seg_map_alloc_size < cm->mi_rows * cm->mi_cols) { free_seg_map(cm); if (alloc_seg_map(cm, cm->mi_rows * cm->mi_cols)) goto fail; } if (cm->above_context_alloc_cols < cm->mi_cols) { vpx_free(cm->above_context); cm->above_context = (ENTROPY_CONTEXT *)vpx_calloc( 2 * mi_cols_aligned_to_sb(cm->mi_cols) * MAX_MB_PLANE, sizeof(*cm->above_context)); if (!cm->above_context) goto fail; vpx_free(cm->above_seg_context); cm->above_seg_context = (PARTITION_CONTEXT *)vpx_calloc( mi_cols_aligned_to_sb(cm->mi_cols), sizeof(*cm->above_seg_context)); if (!cm->above_seg_context) goto fail; cm->above_context_alloc_cols = cm->mi_cols; } return 0; fail: vp9_free_context_buffers(cm); return 1; } Commit Message: DO NOT MERGE libvpx: Cherry-pick 8b4c315 from upstream Description from upstream: vp9_alloc_context_buffers: clear cm->mi* on failure this fixes a crash in vp9_dec_setup_mi() via vp9_init_context_buffers() should decoding continue and the decoder resyncs on a smaller frame Bug: 30593752 Change-Id: Iafbf1c4114062bf796f51a6b03be71328f7bcc69 (cherry picked from commit 737c8493693243838128788fe9c3abc51f17338e) (cherry picked from commit 3e88ffac8c80b76e15286ef8a7b3bd8fa246c761) CWE ID: CWE-20
int vp9_alloc_context_buffers(VP9_COMMON *cm, int width, int height) { int new_mi_size; vp9_set_mb_mi(cm, width, height); new_mi_size = cm->mi_stride * calc_mi_size(cm->mi_rows); if (cm->mi_alloc_size < new_mi_size) { cm->free_mi(cm); if (cm->alloc_mi(cm, new_mi_size)) goto fail; } if (cm->seg_map_alloc_size < cm->mi_rows * cm->mi_cols) { free_seg_map(cm); if (alloc_seg_map(cm, cm->mi_rows * cm->mi_cols)) goto fail; } if (cm->above_context_alloc_cols < cm->mi_cols) { vpx_free(cm->above_context); cm->above_context = (ENTROPY_CONTEXT *)vpx_calloc( 2 * mi_cols_aligned_to_sb(cm->mi_cols) * MAX_MB_PLANE, sizeof(*cm->above_context)); if (!cm->above_context) goto fail; vpx_free(cm->above_seg_context); cm->above_seg_context = (PARTITION_CONTEXT *)vpx_calloc( mi_cols_aligned_to_sb(cm->mi_cols), sizeof(*cm->above_seg_context)); if (!cm->above_seg_context) goto fail; cm->above_context_alloc_cols = cm->mi_cols; } return 0; fail: vp9_set_mb_mi(cm, 0, 0); vp9_free_context_buffers(cm); return 1; }
173,381
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 write_version( FILE *fp, const char *fname, const char *dirname, xref_t *xref) { long start; char *c, *new_fname, data; FILE *new_fp; start = ftell(fp); /* Create file */ if ((c = strstr(fname, ".pdf"))) *c = '\0'; new_fname = malloc(strlen(fname) + strlen(dirname) + 16); snprintf(new_fname, strlen(fname) + strlen(dirname) + 16, "%s/%s-version-%d.pdf", dirname, fname, xref->version); if (!(new_fp = fopen(new_fname, "w"))) { ERR("Could not create file '%s'\n", new_fname); fseek(fp, start, SEEK_SET); free(new_fname); return; } /* Copy original PDF */ fseek(fp, 0, SEEK_SET); while (fread(&data, 1, 1, fp)) fwrite(&data, 1, 1, new_fp); /* Emit an older startxref, refering to an older version. */ fprintf(new_fp, "\r\nstartxref\r\n%ld\r\n%%%%EOF", xref->start); /* Clean */ fclose(new_fp); free(new_fname); fseek(fp, start, SEEK_SET); } 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 void write_version( FILE *fp, const char *fname, const char *dirname, xref_t *xref) { long start; char *c, *new_fname, data; FILE *new_fp; start = ftell(fp); /* Create file */ if ((c = strstr(fname, ".pdf"))) *c = '\0'; new_fname = safe_calloc(strlen(fname) + strlen(dirname) + 16); snprintf(new_fname, strlen(fname) + strlen(dirname) + 16, "%s/%s-version-%d.pdf", dirname, fname, xref->version); if (!(new_fp = fopen(new_fname, "w"))) { ERR("Could not create file '%s'\n", new_fname); fseek(fp, start, SEEK_SET); free(new_fname); return; } /* Copy original PDF */ fseek(fp, 0, SEEK_SET); while (fread(&data, 1, 1, fp)) fwrite(&data, 1, 1, new_fp); /* Emit an older startxref, refering to an older version. */ fprintf(new_fp, "\r\nstartxref\r\n%ld\r\n%%%%EOF", xref->start); /* Clean */ fclose(new_fp); free(new_fname); fseek(fp, start, SEEK_SET); }
169,565
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: ContentEncoding::ContentEncoding() : compression_entries_(NULL), compression_entries_end_(NULL), encryption_entries_(NULL), encryption_entries_end_(NULL), encoding_order_(0), encoding_scope_(1), encoding_type_(0) { } 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
ContentEncoding::ContentEncoding() : compression_entries_(NULL), compression_entries_end_(NULL), encryption_entries_(NULL), encryption_entries_end_(NULL), encoding_order_(0), encoding_scope_(1),
174,251
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 AutofillDownloadManager::StartUploadRequest( const FormStructure& form, bool form_was_autofilled, const FieldTypeSet& available_field_types) { if (next_upload_request_ > base::Time::Now()) { VLOG(1) << "AutofillDownloadManager: Upload request is throttled."; return false; } double upload_rate = form_was_autofilled ? GetPositiveUploadRate() : GetNegativeUploadRate(); if (base::RandDouble() > upload_rate) { VLOG(1) << "AutofillDownloadManager: Upload request is ignored."; return false; } std::string form_xml; if (!form.EncodeUploadRequest(available_field_types, form_was_autofilled, &form_xml)) return false; FormRequestData request_data; request_data.form_signatures.push_back(form.FormSignature()); request_data.request_type = AutofillDownloadManager::REQUEST_UPLOAD; return StartRequest(form_xml, request_data); } Commit Message: Add support for the "uploadrequired" attribute for Autofill query responses BUG=84693 TEST=unit_tests --gtest_filter=AutofillDownloadTest.QueryAndUploadTest Review URL: http://codereview.chromium.org/6969090 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@87729 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
bool AutofillDownloadManager::StartUploadRequest( const FormStructure& form, bool form_was_autofilled, const FieldTypeSet& available_field_types) { if (next_upload_request_ > base::Time::Now()) { VLOG(1) << "AutofillDownloadManager: Upload request is throttled."; return false; } double upload_rate = form_was_autofilled ? GetPositiveUploadRate() : GetNegativeUploadRate(); if (form.upload_required() == UPLOAD_NOT_REQUIRED || (form.upload_required() == USE_UPLOAD_RATES && base::RandDouble() > upload_rate)) { VLOG(1) << "AutofillDownloadManager: Upload request is ignored."; return false; } std::string form_xml; if (!form.EncodeUploadRequest(available_field_types, form_was_autofilled, &form_xml)) return false; FormRequestData request_data; request_data.form_signatures.push_back(form.FormSignature()); request_data.request_type = AutofillDownloadManager::REQUEST_UPLOAD; return StartRequest(form_xml, request_data); }
170,446
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 voutf(struct GlobalConfig *config, const char *prefix, const char *fmt, va_list ap) { size_t width = (79 - strlen(prefix)); if(!config->mute) { size_t len; char *ptr; char *print_buffer; print_buffer = curlx_mvaprintf(fmt, ap); if(!print_buffer) return; len = strlen(print_buffer); ptr = print_buffer; while(len > 0) { fputs(prefix, config->errors); if(len > width) { size_t cut = width-1; while(!ISSPACE(ptr[cut]) && cut) { cut--; } if(0 == cut) /* not a single cutting position was found, just cut it at the max text width then! */ cut = width-1; (void)fwrite(ptr, cut + 1, 1, config->errors); fputs("\n", config->errors); ptr += cut + 1; /* skip the space too */ len -= cut; } else { fputs(ptr, config->errors); len = 0; } } curl_free(print_buffer); } } Commit Message: voutf: fix bad arethmetic when outputting warnings to stderr CVE-2018-16842 Reported-by: Brian Carpenter Bug: https://curl.haxx.se/docs/CVE-2018-16842.html CWE ID: CWE-125
static void voutf(struct GlobalConfig *config, const char *prefix, const char *fmt, va_list ap) { size_t width = (79 - strlen(prefix)); if(!config->mute) { size_t len; char *ptr; char *print_buffer; print_buffer = curlx_mvaprintf(fmt, ap); if(!print_buffer) return; len = strlen(print_buffer); ptr = print_buffer; while(len > 0) { fputs(prefix, config->errors); if(len > width) { size_t cut = width-1; while(!ISSPACE(ptr[cut]) && cut) { cut--; } if(0 == cut) /* not a single cutting position was found, just cut it at the max text width then! */ cut = width-1; (void)fwrite(ptr, cut + 1, 1, config->errors); fputs("\n", config->errors); ptr += cut + 1; /* skip the space too */ len -= cut + 1; } else { fputs(ptr, config->errors); len = 0; } } curl_free(print_buffer); } }
169,029
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 nsc_encode_subsampling(NSC_CONTEXT* context) { UINT16 x; UINT16 y; BYTE* co_dst; BYTE* cg_dst; INT8* co_src0; INT8* co_src1; INT8* cg_src0; INT8* cg_src1; UINT32 tempWidth; UINT32 tempHeight; tempWidth = ROUND_UP_TO(context->width, 8); tempHeight = ROUND_UP_TO(context->height, 2); for (y = 0; y < tempHeight >> 1; y++) { co_dst = context->priv->PlaneBuffers[1] + y * (tempWidth >> 1); cg_dst = context->priv->PlaneBuffers[2] + y * (tempWidth >> 1); co_src0 = (INT8*) context->priv->PlaneBuffers[1] + (y << 1) * tempWidth; co_src1 = co_src0 + tempWidth; cg_src0 = (INT8*) context->priv->PlaneBuffers[2] + (y << 1) * tempWidth; cg_src1 = cg_src0 + tempWidth; for (x = 0; x < tempWidth >> 1; x++) { *co_dst++ = (BYTE)(((INT16) * co_src0 + (INT16) * (co_src0 + 1) + (INT16) * co_src1 + (INT16) * (co_src1 + 1)) >> 2); *cg_dst++ = (BYTE)(((INT16) * cg_src0 + (INT16) * (cg_src0 + 1) + (INT16) * cg_src1 + (INT16) * (cg_src1 + 1)) >> 2); co_src0 += 2; co_src1 += 2; cg_src0 += 2; cg_src1 += 2; } } } Commit Message: Fixed CVE-2018-8788 Thanks to Eyal Itkin from Check Point Software Technologies. CWE ID: CWE-787
static void nsc_encode_subsampling(NSC_CONTEXT* context) static BOOL nsc_encode_subsampling(NSC_CONTEXT* context) { UINT16 x; UINT16 y; UINT32 tempWidth; UINT32 tempHeight; if (!context) return FALSE; tempWidth = ROUND_UP_TO(context->width, 8); tempHeight = ROUND_UP_TO(context->height, 2); if (tempHeight == 0) return FALSE; if (tempWidth > context->priv->PlaneBuffersLength / tempHeight) return FALSE; for (y = 0; y < tempHeight >> 1; y++) { BYTE* co_dst = context->priv->PlaneBuffers[1] + y * (tempWidth >> 1); BYTE* cg_dst = context->priv->PlaneBuffers[2] + y * (tempWidth >> 1); const INT8* co_src0 = (INT8*) context->priv->PlaneBuffers[1] + (y << 1) * tempWidth; const INT8* co_src1 = co_src0 + tempWidth; const INT8* cg_src0 = (INT8*) context->priv->PlaneBuffers[2] + (y << 1) * tempWidth; const INT8* cg_src1 = cg_src0 + tempWidth; for (x = 0; x < tempWidth >> 1; x++) { *co_dst++ = (BYTE)(((INT16) * co_src0 + (INT16) * (co_src0 + 1) + (INT16) * co_src1 + (INT16) * (co_src1 + 1)) >> 2); *cg_dst++ = (BYTE)(((INT16) * cg_src0 + (INT16) * (cg_src0 + 1) + (INT16) * cg_src1 + (INT16) * (cg_src1 + 1)) >> 2); co_src0 += 2; co_src1 += 2; cg_src0 += 2; cg_src1 += 2; } } return TRUE; }
169,289
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 TearDownTestCase() { vpx_free(source_data_); source_data_ = NULL; vpx_free(reference_data_); reference_data_ = NULL; } 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 TearDownTestCase() { vpx_free(source_data8_); source_data8_ = NULL; vpx_free(reference_data8_); reference_data8_ = NULL; vpx_free(second_pred8_); second_pred8_ = NULL; vpx_free(source_data16_); source_data16_ = NULL; vpx_free(reference_data16_); reference_data16_ = NULL; vpx_free(second_pred16_); second_pred16_ = NULL; }
174,579
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: OMX_ERRORTYPE SoftOpus::internalSetParameter( OMX_INDEXTYPE index, const OMX_PTR params) { switch ((int)index) { case OMX_IndexParamStandardComponentRole: { const OMX_PARAM_COMPONENTROLETYPE *roleParams = (const OMX_PARAM_COMPONENTROLETYPE *)params; if (strncmp((const char *)roleParams->cRole, "audio_decoder.opus", OMX_MAX_STRINGNAME_SIZE - 1)) { return OMX_ErrorUndefined; } return OMX_ErrorNone; } case OMX_IndexParamAudioAndroidOpus: { const OMX_AUDIO_PARAM_ANDROID_OPUSTYPE *opusParams = (const OMX_AUDIO_PARAM_ANDROID_OPUSTYPE *)params; if (opusParams->nPortIndex != 0) { return OMX_ErrorUndefined; } return OMX_ErrorNone; } default: return SimpleSoftOMXComponent::internalSetParameter(index, params); } } Commit Message: DO NOT MERGE Verify OMX buffer sizes prior to access Bug: 27207275 Change-Id: I4412825d1ee233d993af0a67708bea54304ff62d CWE ID: CWE-119
OMX_ERRORTYPE SoftOpus::internalSetParameter( OMX_INDEXTYPE index, const OMX_PTR params) { switch ((int)index) { case OMX_IndexParamStandardComponentRole: { const OMX_PARAM_COMPONENTROLETYPE *roleParams = (const OMX_PARAM_COMPONENTROLETYPE *)params; if (!isValidOMXParam(roleParams)) { return OMX_ErrorBadParameter; } if (strncmp((const char *)roleParams->cRole, "audio_decoder.opus", OMX_MAX_STRINGNAME_SIZE - 1)) { return OMX_ErrorUndefined; } return OMX_ErrorNone; } case OMX_IndexParamAudioAndroidOpus: { const OMX_AUDIO_PARAM_ANDROID_OPUSTYPE *opusParams = (const OMX_AUDIO_PARAM_ANDROID_OPUSTYPE *)params; if (!isValidOMXParam(opusParams)) { return OMX_ErrorBadParameter; } if (opusParams->nPortIndex != 0) { return OMX_ErrorUndefined; } return OMX_ErrorNone; } default: return SimpleSoftOMXComponent::internalSetParameter(index, params); } }
174,217
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 timer_config_save(UNUSED_ATTR void *data) { assert(config != NULL); assert(alarm_timer != NULL); static const size_t CACHE_MAX = 256; const char *keys[CACHE_MAX]; size_t num_keys = 0; size_t total_candidates = 0; pthread_mutex_lock(&lock); for (const config_section_node_t *snode = config_section_begin(config); snode != config_section_end(config); snode = config_section_next(snode)) { const char *section = config_section_name(snode); if (!string_is_bdaddr(section)) continue; if (config_has_key(config, section, "LinkKey") || config_has_key(config, section, "LE_KEY_PENC") || config_has_key(config, section, "LE_KEY_PID") || config_has_key(config, section, "LE_KEY_PCSRK") || config_has_key(config, section, "LE_KEY_LENC") || config_has_key(config, section, "LE_KEY_LCSRK")) continue; if (num_keys < CACHE_MAX) keys[num_keys++] = section; ++total_candidates; } if (total_candidates > CACHE_MAX * 2) while (num_keys > 0) config_remove_section(config, keys[--num_keys]); config_save(config, CONFIG_FILE_PATH); pthread_mutex_unlock(&lock); } Commit Message: Fix crashes with lots of discovered LE devices When loads of devices are discovered a config file which is too large can be written out, which causes the BT daemon to crash on startup. This limits the number of config entries for unpaired devices which are initialized, and prevents a large number from being saved to the filesystem. Bug: 26071376 Change-Id: I4a74094f57a82b17f94e99a819974b8bc8082184 CWE ID: CWE-119
static void timer_config_save(UNUSED_ATTR void *data) { static void timer_config_save_cb(UNUSED_ATTR void *data) { btif_config_write(); } static void btif_config_write(void) { assert(config != NULL); assert(alarm_timer != NULL); btif_config_devcache_cleanup(); pthread_mutex_lock(&lock); config_save(config, CONFIG_FILE_PATH); pthread_mutex_unlock(&lock); }
173,931
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 RenderWidgetHostViewAura::WasHidden() { if (host_->is_hidden()) return; host_->WasHidden(); released_front_lock_ = NULL; if (ShouldReleaseFrontSurface() && host_->is_accelerated_compositing_active()) { current_surface_ = 0; UpdateExternalTexture(); } AdjustSurfaceProtection(); #if defined(OS_WIN) aura::RootWindow* root_window = window_->GetRootWindow(); if (root_window) { HWND parent = root_window->GetAcceleratedWidget(); LPARAM lparam = reinterpret_cast<LPARAM>(this); EnumChildWindows(parent, HideWindowsCallback, lparam); } #endif } Commit Message: Implement TextureImageTransportSurface using texture mailbox This has a couple of advantages: - allow tearing down and recreating the UI parent context without losing the renderer contexts - do not require a context to be able to generate textures when creating the GLSurfaceHandle - clearer ownership semantics that potentially allows for more robust and easier lost context handling/thumbnailing/etc., since a texture is at any given time owned by either: UI parent, mailbox, or TextureImageTransportSurface - simplify frontbuffer protection logic; the frontbuffer textures are now owned by RWHV where they are refcounted The TextureImageTransportSurface informs RenderWidgetHostView of the mailbox names for the front- and backbuffer textures by associating them with a surface_handle (1 or 2) in the AcceleratedSurfaceNew message. During SwapBuffers() or PostSubBuffer() cycles, it then uses produceTextureCHROMIUM() and consumeTextureCHROMIUM() to transfer ownership between renderer and browser compositor. RWHV sends back the surface_handle of the buffer being returned with the Swap ACK (or 0 if no buffer is being returned in which case TextureImageTransportSurface will allocate a new texture - note that this could be used to simply keep textures for thumbnailing). BUG=154815,139616 TBR=sky@chromium.org Review URL: https://chromiumcodereview.appspot.com/11194042 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171569 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
void RenderWidgetHostViewAura::WasHidden() { if (host_->is_hidden()) return; host_->WasHidden(); released_front_lock_ = NULL; #if defined(OS_WIN) aura::RootWindow* root_window = window_->GetRootWindow(); if (root_window) { HWND parent = root_window->GetAcceleratedWidget(); LPARAM lparam = reinterpret_cast<LPARAM>(this); EnumChildWindows(parent, HideWindowsCallback, lparam); } #endif }
171,388
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: BlobDataHandle::~BlobDataHandle() { ThreadableBlobRegistry::unregisterBlobURL(m_internalURL); } Commit Message: Remove BlobRegistry indirection since there is only one implementation. BUG= Review URL: https://chromiumcodereview.appspot.com/15851008 git-svn-id: svn://svn.chromium.org/blink/trunk@152746 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID:
BlobDataHandle::~BlobDataHandle() { BlobRegistry::unregisterBlobURL(m_internalURL); }
170,695
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: TabGroupHeader::TabGroupHeader(const base::string16& group_title) { constexpr gfx::Insets kPlaceholderInsets = gfx::Insets(4, 27); SetBorder(views::CreateEmptyBorder(kPlaceholderInsets)); views::FlexLayout* layout = SetLayoutManager(std::make_unique<views::FlexLayout>()); layout->SetOrientation(views::LayoutOrientation::kHorizontal) .SetCollapseMargins(true) .SetMainAxisAlignment(views::LayoutAlignment::kStart) .SetCrossAxisAlignment(views::LayoutAlignment::kCenter); auto title = std::make_unique<views::Label>(group_title); title->SetHorizontalAlignment(gfx::ALIGN_TO_HEAD); title->SetElideBehavior(gfx::FADE_TAIL); auto* title_ptr = AddChildView(std::move(title)); layout->SetFlexForView(title_ptr, views::FlexSpecification::ForSizeRule( views::MinimumFlexSizeRule::kScaleToZero, views::MaximumFlexSizeRule::kUnbounded)); auto group_menu_button = views::CreateVectorImageButton(/*listener*/ nullptr); views::SetImageFromVectorIcon(group_menu_button.get(), kBrowserToolsIcon); AddChildView(std::move(group_menu_button)); } Commit Message: Paint tab groups with the group color. * The background of TabGroupHeader now uses the group color. * The backgrounds of tabs in the group are tinted with the group color. This treatment, along with the colors chosen, are intended to be a placeholder. Bug: 905491 Change-Id: Ic808548f8eba23064606e7fb8c9bba281d0d117f Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1610504 Commit-Queue: Bret Sepulveda <bsep@chromium.org> Reviewed-by: Taylor Bergquist <tbergquist@chromium.org> Cr-Commit-Position: refs/heads/master@{#660498} CWE ID: CWE-20
TabGroupHeader::TabGroupHeader(const base::string16& group_title) { TabGroupHeader::TabGroupHeader(TabController* controller, int group) : controller_(controller), group_(group) { DCHECK(controller); constexpr gfx::Insets kPlaceholderInsets = gfx::Insets(4, 27); SetBorder(views::CreateEmptyBorder(kPlaceholderInsets)); views::FlexLayout* layout = SetLayoutManager(std::make_unique<views::FlexLayout>()); layout->SetOrientation(views::LayoutOrientation::kHorizontal) .SetCollapseMargins(true) .SetMainAxisAlignment(views::LayoutAlignment::kStart) .SetCrossAxisAlignment(views::LayoutAlignment::kCenter); auto title = std::make_unique<views::Label>(GetGroupData()->title()); title->SetHorizontalAlignment(gfx::ALIGN_TO_HEAD); title->SetElideBehavior(gfx::FADE_TAIL); title_label_ = AddChildView(std::move(title)); layout->SetFlexForView(title_label_, views::FlexSpecification::ForSizeRule( views::MinimumFlexSizeRule::kScaleToZero, views::MaximumFlexSizeRule::kUnbounded)); auto group_menu_button = views::CreateVectorImageButton(/*listener*/ nullptr); views::SetImageFromVectorIcon(group_menu_button.get(), kBrowserToolsIcon); AddChildView(std::move(group_menu_button)); }
172,519
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 fe_netjoin_deinit(void) { while (joinservers != NULL) netjoin_server_remove(joinservers->data); if (join_tag != -1) { g_source_remove(join_tag); signal_remove("print starting", (SIGNAL_FUNC) sig_print_starting); } signal_remove("setup changed", (SIGNAL_FUNC) read_settings); signal_remove("message quit", (SIGNAL_FUNC) msg_quit); signal_remove("message join", (SIGNAL_FUNC) msg_join); signal_remove("message irc mode", (SIGNAL_FUNC) msg_mode); } Commit Message: Merge branch 'netjoin-timeout' into 'master' fe-netjoin: remove irc servers on "server disconnected" signal Closes #7 See merge request !10 CWE ID: CWE-416
void fe_netjoin_deinit(void) { while (joinservers != NULL) netjoin_server_remove(joinservers->data); if (join_tag != -1) { g_source_remove(join_tag); signal_remove("print starting", (SIGNAL_FUNC) sig_print_starting); } signal_remove("setup changed", (SIGNAL_FUNC) read_settings); signal_remove("server disconnected", (SIGNAL_FUNC) sig_server_disconnected); signal_remove("message quit", (SIGNAL_FUNC) msg_quit); signal_remove("message join", (SIGNAL_FUNC) msg_join); signal_remove("message irc mode", (SIGNAL_FUNC) msg_mode); }
168,290
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 LoadingStatsCollectorTest::TestRedirectStatusHistogram( const std::string& initial_url, const std::string& prediction_url, const std::string& navigation_url, RedirectStatus expected_status) { const std::string& script_url = "https://cdn.google.com/script.js"; PreconnectPrediction prediction = CreatePreconnectPrediction( GURL(prediction_url).host(), initial_url != prediction_url, {{GURL(script_url).GetOrigin(), 1, net::NetworkIsolationKey()}}); EXPECT_CALL(*mock_predictor_, PredictPreconnectOrigins(GURL(initial_url), _)) .WillOnce(DoAll(SetArgPointee<1>(prediction), Return(true))); std::vector<content::mojom::ResourceLoadInfoPtr> resources; resources.push_back( CreateResourceLoadInfoWithRedirects({initial_url, navigation_url})); resources.push_back( CreateResourceLoadInfo(script_url, content::ResourceType::kScript)); PageRequestSummary summary = CreatePageRequestSummary(navigation_url, initial_url, resources); stats_collector_->RecordPageRequestSummary(summary); histogram_tester_->ExpectUniqueSample( internal::kLoadingPredictorPreconnectLearningRedirectStatus, static_cast<int>(expected_status), 1); } Commit Message: Origins should be represented as url::Origin (not as GURL). As pointed out in //docs/security/origin-vs-url.md, origins should be represented as url::Origin (not as GURL). This CL applies this guideline to predictor-related code and changes the type of the following fields from GURL to url::Origin: - OriginRequestSummary::origin - PreconnectedRequestStats::origin - PreconnectRequest::origin The old code did not depend on any non-origin parts of GURL (like path and/or query). Therefore, this CL has no intended behavior change. Bug: 973885 Change-Id: Idd14590b4834cb9d50c74ed747b595fe1a4ba357 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1895167 Commit-Queue: Łukasz Anforowicz <lukasza@chromium.org> Reviewed-by: Alex Ilin <alexilin@chromium.org> Cr-Commit-Position: refs/heads/master@{#716311} CWE ID: CWE-125
void LoadingStatsCollectorTest::TestRedirectStatusHistogram( const std::string& initial_url, const std::string& prediction_url, const std::string& navigation_url, RedirectStatus expected_status) { const std::string& script_url = "https://cdn.google.com/script.js"; PreconnectPrediction prediction = CreatePreconnectPrediction( GURL(prediction_url).host(), initial_url != prediction_url, {{url::Origin::Create(GURL(script_url)), 1, net::NetworkIsolationKey()}}); EXPECT_CALL(*mock_predictor_, PredictPreconnectOrigins(GURL(initial_url), _)) .WillOnce(DoAll(SetArgPointee<1>(prediction), Return(true))); std::vector<content::mojom::ResourceLoadInfoPtr> resources; resources.push_back( CreateResourceLoadInfoWithRedirects({initial_url, navigation_url})); resources.push_back( CreateResourceLoadInfo(script_url, content::ResourceType::kScript)); PageRequestSummary summary = CreatePageRequestSummary(navigation_url, initial_url, resources); stats_collector_->RecordPageRequestSummary(summary); histogram_tester_->ExpectUniqueSample( internal::kLoadingPredictorPreconnectLearningRedirectStatus, static_cast<int>(expected_status), 1); }
172,373
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 char* Chapters::Atom::GetStringUID() const { return m_string_uid; } 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 char* Chapters::Atom::GetStringUID() const
174,360
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 rng_backend_request_entropy(RngBackend *s, size_t size, EntropyReceiveFunc *receive_entropy, void *opaque) { RngBackendClass *k = RNG_BACKEND_GET_CLASS(s); if (k->request_entropy) { k->request_entropy(s, size, receive_entropy, opaque); } } Commit Message: CWE ID: CWE-119
void rng_backend_request_entropy(RngBackend *s, size_t size, EntropyReceiveFunc *receive_entropy, void *opaque) { RngBackendClass *k = RNG_BACKEND_GET_CLASS(s); RngRequest *req; if (k->request_entropy) { req = g_malloc(sizeof(*req)); req->offset = 0; req->size = size; req->receive_entropy = receive_entropy; req->opaque = opaque; req->data = g_malloc(req->size); k->request_entropy(s, req); s->requests = g_slist_append(s->requests, req); } }
165,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: static int vp8_lossy_decode_frame(AVCodecContext *avctx, AVFrame *p, int *got_frame, uint8_t *data_start, unsigned int data_size) { WebPContext *s = avctx->priv_data; AVPacket pkt; int ret; if (!s->initialized) { ff_vp8_decode_init(avctx); s->initialized = 1; if (s->has_alpha) avctx->pix_fmt = AV_PIX_FMT_YUVA420P; } s->lossless = 0; if (data_size > INT_MAX) { av_log(avctx, AV_LOG_ERROR, "unsupported chunk size\n"); return AVERROR_PATCHWELCOME; } av_init_packet(&pkt); pkt.data = data_start; pkt.size = data_size; ret = ff_vp8_decode_frame(avctx, p, got_frame, &pkt); if (ret < 0) return ret; update_canvas_size(avctx, avctx->width, avctx->height); if (s->has_alpha) { ret = vp8_lossy_decode_alpha(avctx, p, s->alpha_data, s->alpha_data_size); if (ret < 0) return ret; } return ret; } Commit Message: avcodec/webp: Always set pix_fmt Fixes: out of array access Fixes: 1434/clusterfuzz-testcase-minimized-6314998085189632 Fixes: 1435/clusterfuzz-testcase-minimized-6483783723253760 Found-by: continuous fuzzing process https://github.com/google/oss-fuzz/tree/master/targets/ffmpeg Reviewed-by: "Ronald S. Bultje" <rsbultje@gmail.com> Signed-off-by: Michael Niedermayer <michael@niedermayer.cc> CWE ID: CWE-119
static int vp8_lossy_decode_frame(AVCodecContext *avctx, AVFrame *p, int *got_frame, uint8_t *data_start, unsigned int data_size) { WebPContext *s = avctx->priv_data; AVPacket pkt; int ret; if (!s->initialized) { ff_vp8_decode_init(avctx); s->initialized = 1; } avctx->pix_fmt = s->has_alpha ? AV_PIX_FMT_YUVA420P : AV_PIX_FMT_YUV420P; s->lossless = 0; if (data_size > INT_MAX) { av_log(avctx, AV_LOG_ERROR, "unsupported chunk size\n"); return AVERROR_PATCHWELCOME; } av_init_packet(&pkt); pkt.data = data_start; pkt.size = data_size; ret = ff_vp8_decode_frame(avctx, p, got_frame, &pkt); if (ret < 0) return ret; update_canvas_size(avctx, avctx->width, avctx->height); if (s->has_alpha) { ret = vp8_lossy_decode_alpha(avctx, p, s->alpha_data, s->alpha_data_size); if (ret < 0) return ret; } return ret; }
168,072
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 MockNetworkTransaction::RestartWithAuth( const AuthCredentials& credentials, const CompletionCallback& callback) { if (!IsReadyToRestartForAuth()) return ERR_FAILED; HttpRequestInfo auth_request_info = *request_; auth_request_info.extra_headers.AddHeaderFromString("Authorization: Bar"); return StartInternal(&auth_request_info, callback, BoundNetLog()); } Commit Message: Replace fixed string uses of AddHeaderFromString Uses of AddHeaderFromString() with a static string may as well be replaced with SetHeader(). Do so. BUG=None Review-Url: https://codereview.chromium.org/2236933005 Cr-Commit-Position: refs/heads/master@{#418161} CWE ID: CWE-119
int MockNetworkTransaction::RestartWithAuth( const AuthCredentials& credentials, const CompletionCallback& callback) { if (!IsReadyToRestartForAuth()) return ERR_FAILED; HttpRequestInfo auth_request_info = *request_; auth_request_info.extra_headers.SetHeader("Authorization", "Bar"); return StartInternal(&auth_request_info, callback, BoundNetLog()); }
171,601
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: SProcXFixesSelectCursorInput(ClientPtr client) { REQUEST(xXFixesSelectCursorInputReq); swaps(&stuff->length); swapl(&stuff->window); return (*ProcXFixesVector[stuff->xfixesReqType]) (client); } Commit Message: CWE ID: CWE-20
SProcXFixesSelectCursorInput(ClientPtr client) { REQUEST(xXFixesSelectCursorInputReq); REQUEST_SIZE_MATCH(xXFixesSelectCursorInputReq); swaps(&stuff->length); swapl(&stuff->window); return (*ProcXFixesVector[stuff->xfixesReqType]) (client); }
165,441
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: poppler_page_prepare_output_dev (PopplerPage *page, double scale, int rotation, gboolean transparent, OutputDevData *output_dev_data) { CairoOutputDev *output_dev; cairo_surface_t *surface; double width, height; int cairo_width, cairo_height, cairo_rowstride, rotate; unsigned char *cairo_data; rotate = rotation + page->page->getRotate (); if (rotate == 90 || rotate == 270) { height = page->page->getCropWidth (); width = page->page->getCropHeight (); } else { width = page->page->getCropWidth (); height = page->page->getCropHeight (); } cairo_width = (int) ceil(width * scale); cairo_height = (int) ceil(height * scale); output_dev = page->document->output_dev; cairo_rowstride = cairo_width * 4; cairo_data = (guchar *) gmalloc (cairo_height * cairo_rowstride); if (transparent) memset (cairo_data, 0x00, cairo_height * cairo_rowstride); else memset (cairo_data, 0xff, cairo_height * cairo_rowstride); surface = cairo_image_surface_create_for_data(cairo_data, CAIRO_FORMAT_ARGB32, cairo_width, cairo_height, cairo_rowstride); output_dev_data->cairo_data = cairo_data; output_dev_data->surface = surface; output_dev_data->cairo = cairo_create (surface); output_dev->setCairo (output_dev_data->cairo); } Commit Message: CWE ID: CWE-189
poppler_page_prepare_output_dev (PopplerPage *page, double scale, int rotation, gboolean transparent, OutputDevData *output_dev_data) { CairoOutputDev *output_dev; cairo_surface_t *surface; double width, height; int cairo_width, cairo_height, cairo_rowstride, rotate; unsigned char *cairo_data; rotate = rotation + page->page->getRotate (); if (rotate == 90 || rotate == 270) { height = page->page->getCropWidth (); width = page->page->getCropHeight (); } else { width = page->page->getCropWidth (); height = page->page->getCropHeight (); } cairo_width = (int) ceil(width * scale); cairo_height = (int) ceil(height * scale); output_dev = page->document->output_dev; cairo_rowstride = cairo_width * 4; cairo_data = (guchar *) gmallocn (cairo_height, cairo_rowstride); if (transparent) memset (cairo_data, 0x00, cairo_height * cairo_rowstride); else memset (cairo_data, 0xff, cairo_height * cairo_rowstride); surface = cairo_image_surface_create_for_data(cairo_data, CAIRO_FORMAT_ARGB32, cairo_width, cairo_height, cairo_rowstride); output_dev_data->cairo_data = cairo_data; output_dev_data->surface = surface; output_dev_data->cairo = cairo_create (surface); output_dev->setCairo (output_dev_data->cairo); }
164,617
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 buffer_pipe_buf_get(struct pipe_inode_info *pipe, struct pipe_buffer *buf) { struct buffer_ref *ref = (struct buffer_ref *)buf->private; ref->ref++; } Commit Message: Merge branch 'page-refs' (page ref overflow) Merge page ref overflow branch. Jann Horn reported that he can overflow the page ref count with sufficient memory (and a filesystem that is intentionally extremely slow). Admittedly it's not exactly easy. To have more than four billion references to a page requires a minimum of 32GB of kernel memory just for the pointers to the pages, much less any metadata to keep track of those pointers. Jann needed a total of 140GB of memory and a specially crafted filesystem that leaves all reads pending (in order to not ever free the page references and just keep adding more). Still, we have a fairly straightforward way to limit the two obvious user-controllable sources of page references: direct-IO like page references gotten through get_user_pages(), and the splice pipe page duplication. So let's just do that. * branch page-refs: fs: prevent page refcount overflow in pipe_buf_get mm: prevent get_user_pages() from overflowing page refcount mm: add 'try_get_page()' helper function mm: make page ref count overflow check tighter and more explicit CWE ID: CWE-416
static void buffer_pipe_buf_get(struct pipe_inode_info *pipe, static bool buffer_pipe_buf_get(struct pipe_inode_info *pipe, struct pipe_buffer *buf) { struct buffer_ref *ref = (struct buffer_ref *)buf->private; if (ref->ref > INT_MAX/2) return false; ref->ref++; return true; }
170,221
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* get_private_subtags(const char* loc_name) { char* result =NULL; int singletonPos = 0; int len =0; const char* mod_loc_name =NULL; if( loc_name && (len = strlen(loc_name)>0 ) ){ mod_loc_name = loc_name ; len = strlen(mod_loc_name); while( (singletonPos = getSingletonPos(mod_loc_name))!= -1){ if( singletonPos!=-1){ if( (*(mod_loc_name+singletonPos)=='x') || (*(mod_loc_name+singletonPos)=='X') ){ /* private subtag start found */ if( singletonPos + 2 == len){ /* loc_name ends with '-x-' ; return NULL */ } else{ /* result = mod_loc_name + singletonPos +2; */ result = estrndup(mod_loc_name + singletonPos+2 , (len -( singletonPos +2) ) ); } break; } else{ if( singletonPos + 1 >= len){ /* String end */ break; } else { /* singleton found but not a private subtag , hence check further in the string for the private subtag */ mod_loc_name = mod_loc_name + singletonPos +1; len = strlen(mod_loc_name); } } } } /* end of while */ } return result; } Commit Message: Fix bug #72241: get_icu_value_internal out-of-bounds read CWE ID: CWE-125
static char* get_private_subtags(const char* loc_name) { char* result =NULL; int singletonPos = 0; int len =0; const char* mod_loc_name =NULL; if( loc_name && (len = strlen(loc_name)>0 ) ){ mod_loc_name = loc_name ; len = strlen(mod_loc_name); while( (singletonPos = getSingletonPos(mod_loc_name))!= -1){ if( singletonPos!=-1){ if( (*(mod_loc_name+singletonPos)=='x') || (*(mod_loc_name+singletonPos)=='X') ){ /* private subtag start found */ if( singletonPos + 2 == len){ /* loc_name ends with '-x-' ; return NULL */ } else{ /* result = mod_loc_name + singletonPos +2; */ result = estrndup(mod_loc_name + singletonPos+2 , (len -( singletonPos +2) ) ); } break; } else{ if( singletonPos + 1 >= len){ /* String end */ break; } else { /* singleton found but not a private subtag , hence check further in the string for the private subtag */ mod_loc_name = mod_loc_name + singletonPos +1; len = strlen(mod_loc_name); } } } } /* end of while */ } return result; }
167,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: DrawingBuffer::DrawingBuffer( std::unique_ptr<WebGraphicsContext3DProvider> context_provider, std::unique_ptr<Extensions3DUtil> extensions_util, Client* client, bool discard_framebuffer_supported, bool want_alpha_channel, bool premultiplied_alpha, PreserveDrawingBuffer preserve, WebGLVersion web_gl_version, bool want_depth, bool want_stencil, ChromiumImageUsage chromium_image_usage, const CanvasColorParams& color_params) : client_(client), preserve_drawing_buffer_(preserve), web_gl_version_(web_gl_version), context_provider_(WTF::WrapUnique(new WebGraphicsContext3DProviderWrapper( std::move(context_provider)))), gl_(this->ContextProvider()->ContextGL()), extensions_util_(std::move(extensions_util)), discard_framebuffer_supported_(discard_framebuffer_supported), want_alpha_channel_(want_alpha_channel), premultiplied_alpha_(premultiplied_alpha), software_rendering_(this->ContextProvider()->IsSoftwareRendering()), want_depth_(want_depth), want_stencil_(want_stencil), color_space_(color_params.GetGfxColorSpace()), chromium_image_usage_(chromium_image_usage) { TRACE_EVENT_INSTANT0("test_gpu", "DrawingBufferCreation", TRACE_EVENT_SCOPE_GLOBAL); } Commit Message: Reset ES3 pixel pack parameters and PIXEL_PACK_BUFFER binding in DrawingBuffer before ReadPixels() and recover them later. BUG=740603 TEST=new conformance test R=kbr@chromium.org,piman@chromium.org Change-Id: I3ea54c6cc34f34e249f7c8b9f792d93c5e1958f4 Reviewed-on: https://chromium-review.googlesource.com/570840 Reviewed-by: Antoine Labour <piman@chromium.org> Reviewed-by: Kenneth Russell <kbr@chromium.org> Commit-Queue: Zhenyao Mo <zmo@chromium.org> Cr-Commit-Position: refs/heads/master@{#486518} CWE ID: CWE-119
DrawingBuffer::DrawingBuffer( std::unique_ptr<WebGraphicsContext3DProvider> context_provider, std::unique_ptr<Extensions3DUtil> extensions_util, Client* client, bool discard_framebuffer_supported, bool want_alpha_channel, bool premultiplied_alpha, PreserveDrawingBuffer preserve, WebGLVersion webgl_version, bool want_depth, bool want_stencil, ChromiumImageUsage chromium_image_usage, const CanvasColorParams& color_params) : client_(client), preserve_drawing_buffer_(preserve), webgl_version_(webgl_version), context_provider_(WTF::WrapUnique(new WebGraphicsContext3DProviderWrapper( std::move(context_provider)))), gl_(this->ContextProvider()->ContextGL()), extensions_util_(std::move(extensions_util)), discard_framebuffer_supported_(discard_framebuffer_supported), want_alpha_channel_(want_alpha_channel), premultiplied_alpha_(premultiplied_alpha), software_rendering_(this->ContextProvider()->IsSoftwareRendering()), want_depth_(want_depth), want_stencil_(want_stencil), color_space_(color_params.GetGfxColorSpace()), chromium_image_usage_(chromium_image_usage) { TRACE_EVENT_INSTANT0("test_gpu", "DrawingBufferCreation", TRACE_EVENT_SCOPE_GLOBAL); }
172,291
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: GPMF_ERR IsValidSize(GPMF_stream *ms, uint32_t size) // size is in longs not bytes. { if (ms) { int32_t nestsize = (int32_t)ms->nest_size[ms->nest_level]; if (nestsize == 0 && ms->nest_level == 0) nestsize = ms->buffer_size_longs; if (size + 2 <= nestsize) return GPMF_OK; } return GPMF_ERROR_BAD_STRUCTURE; } Commit Message: fixed many security issues with the too crude mp4 reader CWE ID: CWE-787
GPMF_ERR IsValidSize(GPMF_stream *ms, uint32_t size) // size is in longs not bytes. { if (ms) { uint32_t nestsize = (uint32_t)ms->nest_size[ms->nest_level]; if (nestsize == 0 && ms->nest_level == 0) nestsize = ms->buffer_size_longs; if (size + 2 <= nestsize) return GPMF_OK; } return GPMF_ERROR_BAD_STRUCTURE; }
169,544
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 HTMLMediaElement::ProgressEventTimerFired(TimerBase*) { if (network_state_ != kNetworkLoading) return; double time = WTF::CurrentTime(); double timedelta = time - previous_progress_time_; if (GetWebMediaPlayer() && GetWebMediaPlayer()->DidLoadingProgress()) { ScheduleEvent(EventTypeNames::progress); previous_progress_time_ = time; sent_stalled_event_ = false; if (GetLayoutObject()) GetLayoutObject()->UpdateFromElement(); } else if (timedelta > 3.0 && !sent_stalled_event_) { ScheduleEvent(EventTypeNames::stalled); sent_stalled_event_ = true; SetShouldDelayLoadEvent(false); } } Commit Message: defeat cors attacks on audio/video tags Neutralize error messages and fire no progress events until media metadata has been loaded for media loaded from cross-origin locations. Bug: 828265, 826187 Change-Id: Iaf15ef38676403687d6a913cbdc84f2d70a6f5c6 Reviewed-on: https://chromium-review.googlesource.com/1015794 Reviewed-by: Mounir Lamouri <mlamouri@chromium.org> Reviewed-by: Dale Curtis <dalecurtis@chromium.org> Commit-Queue: Fredrik Hubinette <hubbe@chromium.org> Cr-Commit-Position: refs/heads/master@{#557312} CWE ID: CWE-200
void HTMLMediaElement::ProgressEventTimerFired(TimerBase*) { if (network_state_ != kNetworkLoading) return; // If this is an cross-origin request, and we haven't discovered whether // the media is actually playable yet, don't fire any progress events as // those may let the page know information about the resource that it's // not supposed to know. if (MediaShouldBeOpaque()) return; double time = WTF::CurrentTime(); double timedelta = time - previous_progress_time_; if (GetWebMediaPlayer() && GetWebMediaPlayer()->DidLoadingProgress()) { ScheduleEvent(EventTypeNames::progress); previous_progress_time_ = time; sent_stalled_event_ = false; if (GetLayoutObject()) GetLayoutObject()->UpdateFromElement(); } else if (timedelta > 3.0 && !sent_stalled_event_) { ScheduleEvent(EventTypeNames::stalled); sent_stalled_event_ = true; SetShouldDelayLoadEvent(false); } }
173,164
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: DWORD SetProcessIntegrityLevel(IntegrityLevel integrity_level) { if (base::win::GetVersion() < base::win::VERSION_VISTA) return ERROR_SUCCESS; const wchar_t* integrity_level_str = GetIntegrityLevelString(integrity_level); if (!integrity_level_str) { return ERROR_SUCCESS; } std::wstring ace_access = SDDL_NO_READ_UP; ace_access += SDDL_NO_WRITE_UP; DWORD error = SetObjectIntegrityLabel(::GetCurrentProcess(), SE_KERNEL_OBJECT, ace_access.c_str(), integrity_level_str); if (ERROR_SUCCESS != error) return error; HANDLE token_handle; if (!::OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_DEFAULT, &token_handle)) return ::GetLastError(); base::win::ScopedHandle token(token_handle); return SetTokenIntegrityLevel(token.Get(), integrity_level); } Commit Message: Prevent sandboxed processes from opening each other TBR=brettw BUG=117627 BUG=119150 TEST=sbox_validation_tests Review URL: https://chromiumcodereview.appspot.com/9716027 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132477 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
DWORD SetProcessIntegrityLevel(IntegrityLevel integrity_level) { if (base::win::GetVersion() < base::win::VERSION_VISTA) return ERROR_SUCCESS; // We don't check for an invalid level here because we'll just let it // fail on the SetTokenIntegrityLevel call later on. if (integrity_level == INTEGRITY_LEVEL_LAST) { return ERROR_SUCCESS; } HANDLE token_handle; if (!::OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_DEFAULT, &token_handle)) return ::GetLastError(); base::win::ScopedHandle token(token_handle); return SetTokenIntegrityLevel(token.Get(), integrity_level); }
170,914
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 CheckClientDownloadRequest::ShouldUploadForDlpScan() { if (!base::FeatureList::IsEnabled(kDeepScanningOfDownloads)) return false; int check_content_compliance = g_browser_process->local_state()->GetInteger( prefs::kCheckContentCompliance); if (check_content_compliance != CheckContentComplianceValues::CHECK_DOWNLOADS && check_content_compliance != CheckContentComplianceValues::CHECK_UPLOADS_AND_DOWNLOADS) return false; if (policy::BrowserDMTokenStorage::Get()->RetrieveDMToken().empty()) return false; const base::ListValue* domains = g_browser_process->local_state()->GetList( prefs::kURLsToCheckComplianceOfDownloadedContent); url_matcher::URLMatcher matcher; policy::url_util::AddAllowFilters(&matcher, domains); return !matcher.MatchURL(item_->GetURL()).empty(); } Commit Message: Migrate download_protection code to new DM token class. Migrates RetrieveDMToken calls to use the new BrowserDMToken class. Bug: 1020296 Change-Id: Icef580e243430d73b6c1c42b273a8540277481d9 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1904234 Commit-Queue: Dominique Fauteux-Chapleau <domfc@chromium.org> Reviewed-by: Tien Mai <tienmai@chromium.org> Reviewed-by: Daniel Rubery <drubery@chromium.org> Cr-Commit-Position: refs/heads/master@{#714196} CWE ID: CWE-20
bool CheckClientDownloadRequest::ShouldUploadForDlpScan() { if (!base::FeatureList::IsEnabled(kDeepScanningOfDownloads)) return false; int check_content_compliance = g_browser_process->local_state()->GetInteger( prefs::kCheckContentCompliance); if (check_content_compliance != CheckContentComplianceValues::CHECK_DOWNLOADS && check_content_compliance != CheckContentComplianceValues::CHECK_UPLOADS_AND_DOWNLOADS) return false; // If there's no valid DM token, the upload will fail, so we can skip // uploading now. if (!BrowserDMTokenStorage::Get()->RetrieveBrowserDMToken().is_valid()) return false; const base::ListValue* domains = g_browser_process->local_state()->GetList( prefs::kURLsToCheckComplianceOfDownloadedContent); url_matcher::URLMatcher matcher; policy::url_util::AddAllowFilters(&matcher, domains); return !matcher.MatchURL(item_->GetURL()).empty(); }
172,356
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: int32_t PepperFlashRendererHost::OnNavigate( ppapi::host::HostMessageContext* host_context, const ppapi::URLRequestInfoData& data, const std::string& target, bool from_user_action) { content::PepperPluginInstance* plugin_instance = host_->GetPluginInstance(pp_instance()); if (!plugin_instance) return PP_ERROR_FAILED; ppapi::proxy::HostDispatcher* host_dispatcher = ppapi::proxy::HostDispatcher::GetForInstance(pp_instance()); host_dispatcher->set_allow_plugin_reentrancy(); base::WeakPtr<PepperFlashRendererHost> weak_ptr = weak_factory_.GetWeakPtr(); navigate_replies_.push_back(host_context->MakeReplyMessageContext()); plugin_instance->Navigate(data, target.c_str(), from_user_action); if (weak_ptr.get()) { SendReply(navigate_replies_.back(), IPC::Message()); navigate_replies_.pop_back(); } return PP_OK_COMPLETIONPENDING; } Commit Message: PPB_Flash.Navigate(): Disallow certain HTTP request headers. With this CL, PPB_Flash.Navigate() fails the operation with PP_ERROR_NOACCESS if the request headers contain non-simple headers. BUG=332023 TEST=None Review URL: https://codereview.chromium.org/136393004 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@249114 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
int32_t PepperFlashRendererHost::OnNavigate( ppapi::host::HostMessageContext* host_context, const ppapi::URLRequestInfoData& data, const std::string& target, bool from_user_action) { content::PepperPluginInstance* plugin_instance = host_->GetPluginInstance(pp_instance()); if (!plugin_instance) return PP_ERROR_FAILED; std::map<std::string, FlashNavigateUsage>& rejected_headers = g_rejected_headers.Get(); if (rejected_headers.empty()) { for (size_t i = 0; i < arraysize(kRejectedHttpRequestHeaders); ++i) rejected_headers[kRejectedHttpRequestHeaders[i]] = static_cast<FlashNavigateUsage>(i); } net::HttpUtil::HeadersIterator header_iter(data.headers.begin(), data.headers.end(), "\n\r"); bool rejected = false; while (header_iter.GetNext()) { std::string lower_case_header_name = StringToLowerASCII(header_iter.name()); if (!IsSimpleHeader(lower_case_header_name, header_iter.values())) { rejected = true; std::map<std::string, FlashNavigateUsage>::const_iterator iter = rejected_headers.find(lower_case_header_name); FlashNavigateUsage usage = iter != rejected_headers.end() ? iter->second : REJECT_OTHER_HEADERS; RecordFlashNavigateUsage(usage); } } RecordFlashNavigateUsage(TOTAL_NAVIGATE_REQUESTS); if (rejected) { RecordFlashNavigateUsage(TOTAL_REJECTED_NAVIGATE_REQUESTS); return PP_ERROR_NOACCESS; } ppapi::proxy::HostDispatcher* host_dispatcher = ppapi::proxy::HostDispatcher::GetForInstance(pp_instance()); host_dispatcher->set_allow_plugin_reentrancy(); base::WeakPtr<PepperFlashRendererHost> weak_ptr = weak_factory_.GetWeakPtr(); navigate_replies_.push_back(host_context->MakeReplyMessageContext()); plugin_instance->Navigate(data, target.c_str(), from_user_action); if (weak_ptr.get()) { SendReply(navigate_replies_.back(), IPC::Message()); navigate_replies_.pop_back(); } return PP_OK_COMPLETIONPENDING; }
171,709
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 AXNodeObject::isChecked() const { Node* node = this->getNode(); if (!node) return false; if (isHTMLInputElement(*node)) return toHTMLInputElement(*node).shouldAppearChecked(); switch (ariaRoleAttribute()) { case CheckBoxRole: case MenuItemCheckBoxRole: case MenuItemRadioRole: case RadioButtonRole: case SwitchRole: if (equalIgnoringCase( getAOMPropertyOrARIAAttribute(AOMStringProperty::kChecked), "true")) return true; return false; default: break; } return false; } Commit Message: Switch to equalIgnoringASCIICase throughout modules/accessibility BUG=627682 Review-Url: https://codereview.chromium.org/2793913007 Cr-Commit-Position: refs/heads/master@{#461858} CWE ID: CWE-254
bool AXNodeObject::isChecked() const { Node* node = this->getNode(); if (!node) return false; if (isHTMLInputElement(*node)) return toHTMLInputElement(*node).shouldAppearChecked(); switch (ariaRoleAttribute()) { case CheckBoxRole: case MenuItemCheckBoxRole: case MenuItemRadioRole: case RadioButtonRole: case SwitchRole: if (equalIgnoringASCIICase( getAOMPropertyOrARIAAttribute(AOMStringProperty::kChecked), "true")) return true; return false; default: break; } return false; }
171,914
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 DatabaseMessageFilter::OnHandleSqliteError( const string16& origin_identifier, const string16& database_name, int error) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); db_tracker_->HandleSqliteError(origin_identifier, database_name, error); } Commit Message: WebDatabase: check path traversal in origin_identifier BUG=172264 Review URL: https://chromiumcodereview.appspot.com/12212091 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@183141 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-22
void DatabaseMessageFilter::OnHandleSqliteError( const string16& origin_identifier, const string16& database_name, int error) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); if (!DatabaseUtil::IsValidOriginIdentifier(origin_identifier)) { RecordAction(UserMetricsAction("BadMessageTerminate_DBMF")); BadMessageReceived(); return; } db_tracker_->HandleSqliteError(origin_identifier, database_name, error); }
171,478
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 AcceleratedSurfaceBuffersSwappedCompletedForGPU(int host_id, int route_id, bool alive, bool did_swap) { if (!BrowserThread::CurrentlyOn(BrowserThread::IO)) { BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::Bind(&AcceleratedSurfaceBuffersSwappedCompletedForGPU, host_id, route_id, alive, did_swap)); return; } GpuProcessHost* host = GpuProcessHost::FromID(host_id); if (host) { if (alive) host->Send(new AcceleratedSurfaceMsg_BufferPresented( route_id, did_swap, 0)); else host->ForceShutdown(); } } Commit Message: Implement TextureImageTransportSurface using texture mailbox This has a couple of advantages: - allow tearing down and recreating the UI parent context without losing the renderer contexts - do not require a context to be able to generate textures when creating the GLSurfaceHandle - clearer ownership semantics that potentially allows for more robust and easier lost context handling/thumbnailing/etc., since a texture is at any given time owned by either: UI parent, mailbox, or TextureImageTransportSurface - simplify frontbuffer protection logic; the frontbuffer textures are now owned by RWHV where they are refcounted The TextureImageTransportSurface informs RenderWidgetHostView of the mailbox names for the front- and backbuffer textures by associating them with a surface_handle (1 or 2) in the AcceleratedSurfaceNew message. During SwapBuffers() or PostSubBuffer() cycles, it then uses produceTextureCHROMIUM() and consumeTextureCHROMIUM() to transfer ownership between renderer and browser compositor. RWHV sends back the surface_handle of the buffer being returned with the Swap ACK (or 0 if no buffer is being returned in which case TextureImageTransportSurface will allocate a new texture - note that this could be used to simply keep textures for thumbnailing). BUG=154815,139616 TBR=sky@chromium.org Review URL: https://chromiumcodereview.appspot.com/11194042 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171569 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
void AcceleratedSurfaceBuffersSwappedCompletedForGPU(int host_id, int route_id, bool alive, uint64 surface_handle) { if (!BrowserThread::CurrentlyOn(BrowserThread::IO)) { BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::Bind(&AcceleratedSurfaceBuffersSwappedCompletedForGPU, host_id, route_id, alive, surface_handle)); return; } GpuProcessHost* host = GpuProcessHost::FromID(host_id); if (host) { if (alive) host->Send(new AcceleratedSurfaceMsg_BufferPresented( route_id, surface_handle, 0)); else host->ForceShutdown(); } }
171,354
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: cmsNAMEDCOLORLIST* CMSEXPORT cmsAllocNamedColorList(cmsContext ContextID, cmsUInt32Number n, cmsUInt32Number ColorantCount, const char* Prefix, const char* Suffix) { cmsNAMEDCOLORLIST* v = (cmsNAMEDCOLORLIST*) _cmsMallocZero(ContextID, sizeof(cmsNAMEDCOLORLIST)); if (v == NULL) return NULL; v ->List = NULL; v ->nColors = 0; v ->ContextID = ContextID; while (v -> Allocated < n) GrowNamedColorList(v); strncpy(v ->Prefix, Prefix, sizeof(v ->Prefix)); strncpy(v ->Suffix, Suffix, sizeof(v ->Suffix)); v->Prefix[32] = v->Suffix[32] = 0; v -> ColorantCount = ColorantCount; return v; } Commit Message: Non happy-path fixes CWE ID:
cmsNAMEDCOLORLIST* CMSEXPORT cmsAllocNamedColorList(cmsContext ContextID, cmsUInt32Number n, cmsUInt32Number ColorantCount, const char* Prefix, const char* Suffix) { cmsNAMEDCOLORLIST* v = (cmsNAMEDCOLORLIST*) _cmsMallocZero(ContextID, sizeof(cmsNAMEDCOLORLIST)); if (v == NULL) return NULL; v ->List = NULL; v ->nColors = 0; v ->ContextID = ContextID; while (v -> Allocated < n) GrowNamedColorList(v); strncpy(v ->Prefix, Prefix, sizeof(v ->Prefix)-1); strncpy(v ->Suffix, Suffix, sizeof(v ->Suffix)-1); v->Prefix[32] = v->Suffix[32] = 0; v -> ColorantCount = ColorantCount; return v; }
166,541
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 SetUp() { fwd_txfm_ = GET_PARAM(0); inv_txfm_ = GET_PARAM(1); tx_type_ = GET_PARAM(2); pitch_ = 16; fwd_txfm_ref = fht16x16_ref; } 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 SetUp() { fwd_txfm_ = GET_PARAM(0); inv_txfm_ = GET_PARAM(1); tx_type_ = GET_PARAM(2); bit_depth_ = GET_PARAM(3); pitch_ = 16; fwd_txfm_ref = fht16x16_ref; inv_txfm_ref = iht16x16_ref; mask_ = (1 << bit_depth_) - 1; #if CONFIG_VP9_HIGHBITDEPTH switch (bit_depth_) { case VPX_BITS_10: inv_txfm_ref = iht16x16_10; break; case VPX_BITS_12: inv_txfm_ref = iht16x16_12; break; default: inv_txfm_ref = iht16x16_ref; break; } #else inv_txfm_ref = iht16x16_ref; #endif }
174,528
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 VarianceTest<VarianceFunctionType>::RefTest() { for (int i = 0; i < 10; ++i) { for (int j = 0; j < block_size_; j++) { src_[j] = rnd.Rand8(); ref_[j] = rnd.Rand8(); } unsigned int sse1, sse2; unsigned int var1; REGISTER_STATE_CHECK(var1 = variance_(src_, width_, ref_, width_, &sse1)); const unsigned int var2 = variance_ref(src_, ref_, log2width_, log2height_, &sse2); EXPECT_EQ(sse1, sse2); EXPECT_EQ(var1, var2); } } 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 VarianceTest<VarianceFunctionType>::RefTest() { for (int i = 0; i < 10; ++i) { for (int j = 0; j < block_size_; j++) { if (!use_high_bit_depth_) { src_[j] = rnd_.Rand8(); ref_[j] = rnd_.Rand8(); #if CONFIG_VP9_HIGHBITDEPTH } else { CONVERT_TO_SHORTPTR(src_)[j] = rnd_.Rand16() && mask_; CONVERT_TO_SHORTPTR(ref_)[j] = rnd_.Rand16() && mask_; #endif // CONFIG_VP9_HIGHBITDEPTH } } unsigned int sse1, sse2; unsigned int var1; const int stride_coeff = 1; ASM_REGISTER_STATE_CHECK( var1 = variance_(src_, width_, ref_, width_, &sse1)); const unsigned int var2 = variance_ref(src_, ref_, log2width_, log2height_, stride_coeff, stride_coeff, &sse2, use_high_bit_depth_, bit_depth_); EXPECT_EQ(sse1, sse2); EXPECT_EQ(var1, var2); } } template<typename VarianceFunctionType> void VarianceTest<VarianceFunctionType>::RefStrideTest() { for (int i = 0; i < 10; ++i) { int ref_stride_coeff = i % 2; int src_stride_coeff = (i >> 1) % 2; for (int j = 0; j < block_size_; j++) { int ref_ind = (j / width_) * ref_stride_coeff * width_ + j % width_; int src_ind = (j / width_) * src_stride_coeff * width_ + j % width_; if (!use_high_bit_depth_) { src_[src_ind] = rnd_.Rand8(); ref_[ref_ind] = rnd_.Rand8(); #if CONFIG_VP9_HIGHBITDEPTH } else { CONVERT_TO_SHORTPTR(src_)[src_ind] = rnd_.Rand16() && mask_; CONVERT_TO_SHORTPTR(ref_)[ref_ind] = rnd_.Rand16() && mask_; #endif // CONFIG_VP9_HIGHBITDEPTH } } unsigned int sse1, sse2; unsigned int var1; ASM_REGISTER_STATE_CHECK( var1 = variance_(src_, width_ * src_stride_coeff, ref_, width_ * ref_stride_coeff, &sse1)); const unsigned int var2 = variance_ref(src_, ref_, log2width_, log2height_, src_stride_coeff, ref_stride_coeff, &sse2, use_high_bit_depth_, bit_depth_); EXPECT_EQ(sse1, sse2); EXPECT_EQ(var1, var2); } }
174,586
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: sf_open (const char *path, int mode, SF_INFO *sfinfo) { SF_PRIVATE *psf ; /* Ultimate sanity check. */ assert (sizeof (sf_count_t) == 8) ; if ((psf = calloc (1, sizeof (SF_PRIVATE))) == NULL) { sf_errno = SFE_MALLOC_FAILED ; return NULL ; } ; psf_init_files (psf) ; psf_log_printf (psf, "File : %s\n", path) ; if (copy_filename (psf, path) != 0) { sf_errno = psf->error ; return NULL ; } ; psf->file.mode = mode ; if (strcmp (path, "-") == 0) psf->error = psf_set_stdio (psf) ; else psf->error = psf_fopen (psf) ; return psf_open_file (psf, sfinfo) ; } /* sf_open */ Commit Message: src/ : Move to a variable length header buffer Previously, the `psf->header` buffer was a fixed length specified by `SF_HEADER_LEN` which was set to `12292`. This was problematic for two reasons; this value was un-necessarily large for the majority of files and too small for some others. Now the size of the header buffer starts at 256 bytes and grows as necessary up to a maximum of 100k. CWE ID: CWE-119
sf_open (const char *path, int mode, SF_INFO *sfinfo) { SF_PRIVATE *psf ; /* Ultimate sanity check. */ assert (sizeof (sf_count_t) == 8) ; if ((psf = psf_allocate ()) == NULL) { sf_errno = SFE_MALLOC_FAILED ; return NULL ; } ; psf_init_files (psf) ; psf_log_printf (psf, "File : %s\n", path) ; if (copy_filename (psf, path) != 0) { sf_errno = psf->error ; return NULL ; } ; psf->file.mode = mode ; if (strcmp (path, "-") == 0) psf->error = psf_set_stdio (psf) ; else psf->error = psf_fopen (psf) ; return psf_open_file (psf, sfinfo) ; } /* sf_open */
170,067
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_@_set(PNG_CONST image_transform *this, transform_display *that, png_structp pp, png_infop pi) { png_set_@(pp); this->next->set(this->next, that, pp, pi); } 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_@_set(PNG_CONST image_transform *this,
173,602
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: SortDirection AXTableCell::getSortDirection() const { if (roleValue() != RowHeaderRole && roleValue() != ColumnHeaderRole) return SortDirectionUndefined; const AtomicString& ariaSort = getAOMPropertyOrARIAAttribute(AOMStringProperty::kSort); if (ariaSort.isEmpty()) return SortDirectionUndefined; if (equalIgnoringCase(ariaSort, "none")) return SortDirectionNone; if (equalIgnoringCase(ariaSort, "ascending")) return SortDirectionAscending; if (equalIgnoringCase(ariaSort, "descending")) return SortDirectionDescending; if (equalIgnoringCase(ariaSort, "other")) return SortDirectionOther; return SortDirectionUndefined; } Commit Message: Switch to equalIgnoringASCIICase throughout modules/accessibility BUG=627682 Review-Url: https://codereview.chromium.org/2793913007 Cr-Commit-Position: refs/heads/master@{#461858} CWE ID: CWE-254
SortDirection AXTableCell::getSortDirection() const { if (roleValue() != RowHeaderRole && roleValue() != ColumnHeaderRole) return SortDirectionUndefined; const AtomicString& ariaSort = getAOMPropertyOrARIAAttribute(AOMStringProperty::kSort); if (ariaSort.isEmpty()) return SortDirectionUndefined; if (equalIgnoringASCIICase(ariaSort, "none")) return SortDirectionNone; if (equalIgnoringASCIICase(ariaSort, "ascending")) return SortDirectionAscending; if (equalIgnoringASCIICase(ariaSort, "descending")) return SortDirectionDescending; if (equalIgnoringASCIICase(ariaSort, "other")) return SortDirectionOther; return SortDirectionUndefined; }
171,931
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: SampleTable::SampleTable(const sp<DataSource> &source) : mDataSource(source), mChunkOffsetOffset(-1), mChunkOffsetType(0), mNumChunkOffsets(0), mSampleToChunkOffset(-1), mNumSampleToChunkOffsets(0), mSampleSizeOffset(-1), mSampleSizeFieldSize(0), mDefaultSampleSize(0), mNumSampleSizes(0), mTimeToSampleCount(0), mTimeToSample(NULL), mSampleTimeEntries(NULL), mCompositionTimeDeltaEntries(NULL), mNumCompositionTimeDeltaEntries(0), mCompositionDeltaLookup(new CompositionDeltaLookup), mSyncSampleOffset(-1), mNumSyncSamples(0), mSyncSamples(NULL), mLastSyncSampleIndex(0), mSampleToChunkEntries(NULL) { mSampleIterator = new SampleIterator(this); } Commit Message: Resolve merge conflict when cp'ing ag/931301 to mnc-mr1-release Change-Id: I079d1db2d30d126f8aed348bd62451acf741037d CWE ID: CWE-20
SampleTable::SampleTable(const sp<DataSource> &source) : mDataSource(source), mChunkOffsetOffset(-1), mChunkOffsetType(0), mNumChunkOffsets(0), mSampleToChunkOffset(-1), mNumSampleToChunkOffsets(0), mSampleSizeOffset(-1), mSampleSizeFieldSize(0), mDefaultSampleSize(0), mNumSampleSizes(0), mTimeToSampleCount(0), mTimeToSample(), mSampleTimeEntries(NULL), mCompositionTimeDeltaEntries(NULL), mNumCompositionTimeDeltaEntries(0), mCompositionDeltaLookup(new CompositionDeltaLookup), mSyncSampleOffset(-1), mNumSyncSamples(0), mSyncSamples(NULL), mLastSyncSampleIndex(0), mSampleToChunkEntries(NULL) { mSampleIterator = new SampleIterator(this); }
174,171
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: OMX_BUFFERHEADERTYPE *OMXNodeInstance::findBufferHeader(OMX::buffer_id buffer) { return (OMX_BUFFERHEADERTYPE *)buffer; } Commit Message: IOMX: Enable buffer ptr to buffer id translation for arm32 Bug: 20634516 Change-Id: Iac9eac3cb251eccd9bbad5df7421a07edc21da0c (cherry picked from commit 2d6b6601743c3c6960c6511a2cb774ef902759f4) CWE ID: CWE-119
OMX_BUFFERHEADERTYPE *OMXNodeInstance::findBufferHeader(OMX::buffer_id buffer) {
173,357
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 SeekHead::GetVoidElementCount() const { return m_void_element_count; } 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
int SeekHead::GetVoidElementCount() const
174,381
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 BaseRenderingContext2D::setStrokeStyle( const StringOrCanvasGradientOrCanvasPattern& style) { DCHECK(!style.IsNull()); String color_string; CanvasStyle* canvas_style = nullptr; if (style.IsString()) { color_string = style.GetAsString(); if (color_string == GetState().UnparsedStrokeColor()) return; Color parsed_color = 0; if (!ParseColorOrCurrentColor(parsed_color, color_string)) return; if (GetState().StrokeStyle()->IsEquivalentRGBA(parsed_color.Rgb())) { ModifiableState().SetUnparsedStrokeColor(color_string); return; } canvas_style = CanvasStyle::CreateFromRGBA(parsed_color.Rgb()); } else if (style.IsCanvasGradient()) { canvas_style = CanvasStyle::CreateFromGradient(style.GetAsCanvasGradient()); } else if (style.IsCanvasPattern()) { CanvasPattern* canvas_pattern = style.GetAsCanvasPattern(); if (OriginClean() && !canvas_pattern->OriginClean()) { SetOriginTainted(); ClearResolvedFilters(); } canvas_style = CanvasStyle::CreateFromPattern(canvas_pattern); } DCHECK(canvas_style); ModifiableState().SetStrokeStyle(canvas_style); ModifiableState().SetUnparsedStrokeColor(color_string); ModifiableState().ClearResolvedFilter(); } Commit Message: [PE] Distinguish between tainting due to canvas content and filter. A filter on a canvas can itself lead to origin tainting, for reasons other than that the canvas contents are tainted. This CL changes to distinguish these two causes, so that we recompute filters on content-tainting change. Bug: 778506 Change-Id: I3cec8ef3b2772f2af78cdd4b290520113092cca6 Reviewed-on: https://chromium-review.googlesource.com/811767 Reviewed-by: Fredrik Söderquist <fs@opera.com> Commit-Queue: Chris Harrelson <chrishtr@chromium.org> Cr-Commit-Position: refs/heads/master@{#522274} CWE ID: CWE-200
void BaseRenderingContext2D::setStrokeStyle( const StringOrCanvasGradientOrCanvasPattern& style) { DCHECK(!style.IsNull()); String color_string; CanvasStyle* canvas_style = nullptr; if (style.IsString()) { color_string = style.GetAsString(); if (color_string == GetState().UnparsedStrokeColor()) return; Color parsed_color = 0; if (!ParseColorOrCurrentColor(parsed_color, color_string)) return; if (GetState().StrokeStyle()->IsEquivalentRGBA(parsed_color.Rgb())) { ModifiableState().SetUnparsedStrokeColor(color_string); return; } canvas_style = CanvasStyle::CreateFromRGBA(parsed_color.Rgb()); } else if (style.IsCanvasGradient()) { canvas_style = CanvasStyle::CreateFromGradient(style.GetAsCanvasGradient()); } else if (style.IsCanvasPattern()) { CanvasPattern* canvas_pattern = style.GetAsCanvasPattern(); if (!origin_tainted_by_content_ && !canvas_pattern->OriginClean()) SetOriginTaintedByContent(); canvas_style = CanvasStyle::CreateFromPattern(canvas_pattern); } DCHECK(canvas_style); ModifiableState().SetStrokeStyle(canvas_style); ModifiableState().SetUnparsedStrokeColor(color_string); ModifiableState().ClearResolvedFilter(); }
172,909
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: base::string16 FormatBookmarkURLForDisplay(const GURL& url) { return url_formatter::FormatUrl( url, url_formatter::kFormatUrlOmitAll & ~url_formatter::kFormatUrlOmitUsernamePassword, net::UnescapeRule::SPACES, nullptr, nullptr, nullptr); } Commit Message: Prevent interpretating userinfo as url scheme when editing bookmarks Chrome's Edit Bookmark dialog formats urls for display such that a url of http://javascript:scripttext@host.com is later converted to a javascript url scheme, allowing persistence of a script injection attack within the user's bookmarks. This fix prevents such misinterpretations by always showing the scheme when a userinfo component is present within the url. BUG=639126 Review-Url: https://codereview.chromium.org/2368593002 Cr-Commit-Position: refs/heads/master@{#422467} CWE ID: CWE-79
base::string16 FormatBookmarkURLForDisplay(const GURL& url) { // and trailing slash, and unescape most characters. However, it's url_formatter::FormatUrlTypes format_types = url_formatter::kFormatUrlOmitAll & ~url_formatter::kFormatUrlOmitUsernamePassword; // If username is present, we must not omit the scheme because FixupURL() will // subsequently interpret the username as a scheme. crbug.com/639126 if (url.has_username()) format_types &= ~url_formatter::kFormatUrlOmitHTTP; return url_formatter::FormatUrl(url, format_types, net::UnescapeRule::SPACES, nullptr, nullptr, nullptr); }
172,103
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 TestPlaybackRate(double playback_rate, int buffer_size_in_frames, int total_frames_requested) { int initial_bytes_enqueued = bytes_enqueued_; int initial_bytes_buffered = algorithm_.bytes_buffered(); algorithm_.SetPlaybackRate(static_cast<float>(playback_rate)); scoped_array<uint8> buffer( new uint8[buffer_size_in_frames * algorithm_.bytes_per_frame()]); if (playback_rate == 0.0) { int frames_written = algorithm_.FillBuffer(buffer.get(), buffer_size_in_frames); EXPECT_EQ(0, frames_written); return; } int frames_remaining = total_frames_requested; while (frames_remaining > 0) { int frames_requested = std::min(buffer_size_in_frames, frames_remaining); int frames_written = algorithm_.FillBuffer(buffer.get(), frames_requested); CHECK_GT(frames_written, 0); CheckFakeData(buffer.get(), frames_written, playback_rate); frames_remaining -= frames_written; } int bytes_requested = total_frames_requested * algorithm_.bytes_per_frame(); int bytes_consumed = ComputeConsumedBytes(initial_bytes_enqueued, initial_bytes_buffered); if (playback_rate == 1.0) { EXPECT_EQ(bytes_requested, bytes_consumed); return; } static const double kMaxAcceptableDelta = 0.01; double actual_playback_rate = 1.0 * bytes_consumed / bytes_requested; double delta = std::abs(1.0 - (actual_playback_rate / playback_rate)); EXPECT_LE(delta, kMaxAcceptableDelta); } Commit Message: Protect AudioRendererAlgorithm from invalid step sizes. BUG=165430 TEST=unittests and asan pass. Review URL: https://codereview.chromium.org/11573023 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@173249 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
void TestPlaybackRate(double playback_rate, int buffer_size_in_frames, int total_frames_requested) { int initial_bytes_enqueued = bytes_enqueued_; int initial_bytes_buffered = algorithm_.bytes_buffered(); algorithm_.SetPlaybackRate(static_cast<float>(playback_rate)); scoped_array<uint8> buffer( new uint8[buffer_size_in_frames * algorithm_.bytes_per_frame()]); if (playback_rate == 0.0) { int frames_written = algorithm_.FillBuffer(buffer.get(), buffer_size_in_frames); EXPECT_EQ(0, frames_written); return; } int frames_remaining = total_frames_requested; while (frames_remaining > 0) { int frames_requested = std::min(buffer_size_in_frames, frames_remaining); int frames_written = algorithm_.FillBuffer(buffer.get(), frames_requested); ASSERT_GT(frames_written, 0); CheckFakeData(buffer.get(), frames_written); frames_remaining -= frames_written; } int bytes_requested = total_frames_requested * algorithm_.bytes_per_frame(); int bytes_consumed = ComputeConsumedBytes(initial_bytes_enqueued, initial_bytes_buffered); if (playback_rate == 1.0) { EXPECT_EQ(bytes_requested, bytes_consumed); return; } static const double kMaxAcceptableDelta = 0.01; double actual_playback_rate = 1.0 * bytes_consumed / bytes_requested; double delta = std::abs(1.0 - (actual_playback_rate / playback_rate)); EXPECT_LE(delta, kMaxAcceptableDelta); }
171,536
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_set_tIME(png_structp png_ptr, png_infop info_ptr, png_timep mod_time) { png_debug1(1, "in %s storage function", "tIME"); if (png_ptr == NULL || info_ptr == NULL || (png_ptr->mode & PNG_WROTE_tIME)) return; png_memcpy(&(info_ptr->mod_time), mod_time, png_sizeof(png_time)); info_ptr->valid |= PNG_INFO_tIME; } Commit Message: third_party/libpng: update to 1.2.54 TBR=darin@chromium.org BUG=560291 Review URL: https://codereview.chromium.org/1467263003 Cr-Commit-Position: refs/heads/master@{#362298} CWE ID: CWE-119
png_set_tIME(png_structp png_ptr, png_infop info_ptr, png_timep mod_time) { png_debug1(1, "in %s storage function", "tIME"); if (png_ptr == NULL || info_ptr == NULL || (png_ptr->mode & PNG_WROTE_tIME)) return; if (mod_time->month == 0 || mod_time->month > 12 || mod_time->day == 0 || mod_time->day > 31 || mod_time->hour > 23 || mod_time->minute > 59 || mod_time->second > 60) { png_warning(png_ptr, "Ignoring invalid time value"); return; } png_memcpy(&(info_ptr->mod_time), mod_time, png_sizeof(png_time)); info_ptr->valid |= PNG_INFO_tIME; }
172,184
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 Cluster::GetIndex() const { return m_index; } 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 Cluster::GetIndex() const Cluster::Cluster(Segment* pSegment, long idx, long long element_start /* long long element_size */) : m_pSegment(pSegment), m_element_start(element_start), m_index(idx), m_pos(element_start), m_element_size(-1 /* element_size */), m_timecode(-1), m_entries(NULL), m_entries_size(0), m_entries_count(-1) // means "has not been parsed yet" {} Cluster::~Cluster() { if (m_entries_count <= 0) return; BlockEntry** i = m_entries; BlockEntry** const j = m_entries + m_entries_count; while (i != j) { BlockEntry* p = *i++; assert(p); delete p; } delete[] m_entries; }
174,328
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_size_of_type(int color_type, int bit_depth, unsigned int *colors) { if (*colors) return 16; else { int pixel_depth = pixel_depth_of_type(color_type, bit_depth); if (pixel_depth < 8) return 64; else if (pixel_depth > 16) return 1024; else return 256; } } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
image_size_of_type(int color_type, int bit_depth, unsigned int *colors) image_size_of_type(int color_type, int bit_depth, unsigned int *colors, int small) { if (*colors) return 16; else { int pixel_depth = pixel_depth_of_type(color_type, bit_depth); if (small) { if (pixel_depth <= 8) /* there will be one row */ return 1 << pixel_depth; else return 256; } else if (pixel_depth < 8) return 64; else if (pixel_depth > 16) return 1024; else return 256; } }
173,581
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 msg_cache_check(const char *id, struct BodyCache *bcache, void *data) { struct Context *ctx = (struct Context *) data; if (!ctx) return -1; struct PopData *pop_data = (struct PopData *) ctx->data; if (!pop_data) return -1; #ifdef USE_HCACHE /* keep hcache file if hcache == bcache */ if (strcmp(HC_FNAME "." HC_FEXT, id) == 0) return 0; #endif for (int i = 0; i < ctx->msgcount; i++) { /* if the id we get is known for a header: done (i.e. keep in cache) */ if (ctx->hdrs[i]->data && (mutt_str_strcmp(ctx->hdrs[i]->data, id) == 0)) return 0; } /* message not found in context -> remove it from cache * return the result of bcache, so we stop upon its first error */ return mutt_bcache_del(bcache, id); } Commit Message: sanitise cache paths Co-authored-by: JerikoOne <jeriko.one@gmx.us> CWE ID: CWE-22
static int msg_cache_check(const char *id, struct BodyCache *bcache, void *data) { struct Context *ctx = (struct Context *) data; if (!ctx) return -1; struct PopData *pop_data = (struct PopData *) ctx->data; if (!pop_data) return -1; #ifdef USE_HCACHE /* keep hcache file if hcache == bcache */ if (strcmp(HC_FNAME "." HC_FEXT, id) == 0) return 0; #endif for (int i = 0; i < ctx->msgcount; i++) { /* if the id we get is known for a header: done (i.e. keep in cache) */ if (ctx->hdrs[i]->data && (mutt_str_strcmp(ctx->hdrs[i]->data, id) == 0)) return 0; } /* message not found in context -> remove it from cache * return the result of bcache, so we stop upon its first error */ return mutt_bcache_del(bcache, cache_id(id)); }
169,120
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::RequestConfirmation( const dbus::ObjectPath& device_path, uint32 passkey, const ConfirmationCallback& callback) { DCHECK(agent_.get()); DCHECK(device_path == object_path_); VLOG(1) << object_path_.value() << ": RequestConfirmation: " << passkey; UMA_HISTOGRAM_ENUMERATION("Bluetooth.PairingMethod", UMA_PAIRING_METHOD_CONFIRM_PASSKEY, UMA_PAIRING_METHOD_COUNT); DCHECK(pairing_delegate_); DCHECK(confirmation_callback_.is_null()); confirmation_callback_ = callback; pairing_delegate_->ConfirmPasskey(this, passkey); pairing_delegate_used_ = true; } 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::RequestConfirmation(
171,235
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 add_ballooned_pages(int nr_pages) { enum bp_state st; if (xen_hotplug_unpopulated) { st = reserve_additional_memory(); if (st != BP_ECANCELED) { mutex_unlock(&balloon_mutex); wait_event(balloon_wq, !list_empty(&ballooned_pages)); mutex_lock(&balloon_mutex); return 0; } } st = decrease_reservation(nr_pages, GFP_USER); if (st != BP_DONE) return -ENOMEM; return 0; } Commit Message: xen: let alloc_xenballooned_pages() fail if not enough memory free commit a1078e821b605813b63bf6bca414a85f804d5c66 upstream. Instead of trying to allocate pages with GFP_USER in add_ballooned_pages() check the available free memory via si_mem_available(). GFP_USER is far less limiting memory exhaustion than the test via si_mem_available(). This will avoid dom0 running out of memory due to excessive foreign page mappings especially on ARM and on x86 in PVH mode, as those don't have a pre-ballooned area which can be used for foreign mappings. As the normal ballooning suffers from the same problem don't balloon down more than si_mem_available() pages in one iteration. At the same time limit the default maximum number of retries. This is part of XSA-300. Signed-off-by: Juergen Gross <jgross@suse.com> Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org> CWE ID: CWE-400
static int add_ballooned_pages(int nr_pages) { enum bp_state st; if (xen_hotplug_unpopulated) { st = reserve_additional_memory(); if (st != BP_ECANCELED) { mutex_unlock(&balloon_mutex); wait_event(balloon_wq, !list_empty(&ballooned_pages)); mutex_lock(&balloon_mutex); return 0; } } if (si_mem_available() < nr_pages) return -ENOMEM; st = decrease_reservation(nr_pages, GFP_USER); if (st != BP_DONE) return -ENOMEM; return 0; }
169,492
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: PrintWebViewHelper::PrintWebViewHelper(content::RenderView* render_view, scoped_ptr<Delegate> delegate) : content::RenderViewObserver(render_view), content::RenderViewObserverTracker<PrintWebViewHelper>(render_view), reset_prep_frame_view_(false), is_print_ready_metafile_sent_(false), ignore_css_margins_(false), is_scripted_printing_blocked_(false), notify_browser_of_print_failure_(true), print_for_preview_(false), delegate_(delegate.Pass()), print_node_in_progress_(false), is_loading_(false), is_scripted_preview_delayed_(false), weak_ptr_factory_(this) { if (!delegate_->IsPrintPreviewEnabled()) DisablePreview(); } 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:
PrintWebViewHelper::PrintWebViewHelper(content::RenderView* render_view, scoped_ptr<Delegate> delegate) : content::RenderViewObserver(render_view), content::RenderViewObserverTracker<PrintWebViewHelper>(render_view), reset_prep_frame_view_(false), is_print_ready_metafile_sent_(false), ignore_css_margins_(false), is_scripted_printing_blocked_(false), notify_browser_of_print_failure_(true), print_for_preview_(false), delegate_(delegate.Pass()), print_node_in_progress_(false), is_loading_(false), is_scripted_preview_delayed_(false), ipc_nesting_level_(0), weak_ptr_factory_(this) { if (!delegate_->IsPrintPreviewEnabled()) DisablePreview(); }
171,878
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 HarfBuzzShaper::shape(GlyphBuffer* glyphBuffer) { if (!createHarfBuzzRuns()) return false; m_totalWidth = 0; if (!shapeHarfBuzzRuns()) return false; if (glyphBuffer && !fillGlyphBuffer(glyphBuffer)) return false; return true; } Commit Message: Always initialize |m_totalWidth| in HarfBuzzShaper::shape. R=leviw@chromium.org BUG=476647 Review URL: https://codereview.chromium.org/1108663003 git-svn-id: svn://svn.chromium.org/blink/trunk@194541 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID:
bool HarfBuzzShaper::shape(GlyphBuffer* glyphBuffer) { if (!createHarfBuzzRuns()) return false; if (!shapeHarfBuzzRuns()) return false; if (glyphBuffer && !fillGlyphBuffer(glyphBuffer)) return false; return true; }
172,005
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_enc_get_supported_key_sizes) { int i, count = 0; int *key_sizes; MCRYPT_GET_TD_ARG array_init(return_value); key_sizes = mcrypt_enc_get_supported_key_sizes(pm->td, &count); for (i = 0; i < count; i++) { add_index_long(return_value, i, key_sizes[i]); } mcrypt_free(key_sizes); } Commit Message: Fix bug #72455: Heap Overflow due to integer overflows CWE ID: CWE-190
PHP_FUNCTION(mcrypt_enc_get_supported_key_sizes) { int i, count = 0; int *key_sizes; MCRYPT_GET_TD_ARG array_init(return_value); key_sizes = mcrypt_enc_get_supported_key_sizes(pm->td, &count); for (i = 0; i < count; i++) { add_index_long(return_value, i, key_sizes[i]); } mcrypt_free(key_sizes); }
167,093
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 DataReductionProxySettings::IsDataReductionProxyManaged() { return spdy_proxy_auth_enabled_.IsManaged(); } 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 <waffles@chromium.org> Reviewed-by: Tarun Bansal <tbansal@chromium.org> Commit-Queue: Robert Ogden <robertogden@chromium.org> Cr-Commit-Position: refs/heads/master@{#643948} CWE ID: CWE-119
bool DataReductionProxySettings::IsDataReductionProxyManaged() { const PrefService::Preference* pref = GetOriginalProfilePrefs()->FindPreference(prefs::kDataSaverEnabled); return pref && pref->IsManaged(); }
172,555
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 ConnectPanelServiceSignals() { if (!ibus_) { return; } IBusPanelService* ibus_panel_service = IBUS_PANEL_SERVICE( g_object_get_data(G_OBJECT(ibus_), kPanelObjectKey)); if (!ibus_panel_service) { LOG(ERROR) << "IBusPanelService is NOT available."; return; } g_signal_connect(ibus_panel_service, "focus-in", G_CALLBACK(FocusInCallback), this); g_signal_connect(ibus_panel_service, "register-properties", G_CALLBACK(RegisterPropertiesCallback), this); g_signal_connect(ibus_panel_service, "update-property", G_CALLBACK(UpdatePropertyCallback), this); } 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
void ConnectPanelServiceSignals() { if (!ibus_) { return; } IBusPanelService* ibus_panel_service = IBUS_PANEL_SERVICE( g_object_get_data(G_OBJECT(ibus_), kPanelObjectKey)); if (!ibus_panel_service) { LOG(ERROR) << "IBusPanelService is NOT available."; return; } g_signal_connect(ibus_panel_service, "focus-in", G_CALLBACK(FocusInThunk), this); g_signal_connect(ibus_panel_service, "register-properties", G_CALLBACK(RegisterPropertiesThunk), this); g_signal_connect(ibus_panel_service, "update-property", G_CALLBACK(UpdatePropertyThunk), this); }
170,530
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 BN_hex2bn(BIGNUM **bn, const char *a) { BIGNUM *ret = NULL; BN_ULONG l = 0; int neg = 0, h, m, i, j, k, c; int num; if ((a == NULL) || (*a == '\0')) return (0); if (*a == '-') { neg = 1; a++; a++; } for (i = 0; isxdigit((unsigned char)a[i]); i++) ; num = i + neg; if (bn == NULL) return (0); } else { ret = *bn; BN_zero(ret); } Commit Message: CWE ID:
int BN_hex2bn(BIGNUM **bn, const char *a) { BIGNUM *ret = NULL; BN_ULONG l = 0; int neg = 0, h, m, i, j, k, c; int num; if ((a == NULL) || (*a == '\0')) return (0); if (*a == '-') { neg = 1; a++; a++; } for (i = 0; i <= (INT_MAX/4) && isxdigit((unsigned char)a[i]); i++) continue; if (i > INT_MAX/4) goto err; num = i + neg; if (bn == NULL) return (0); } else { ret = *bn; BN_zero(ret); }
165,250
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 GraphicsContext::clipPath(const Path&, WindRule) { notImplemented(); } Commit Message: Reviewed by Kevin Ollivier. [wx] Fix strokeArc and fillRoundedRect drawing, and add clipPath support. https://bugs.webkit.org/show_bug.cgi?id=60847 git-svn-id: svn://svn.chromium.org/blink/trunk@86502 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399
void GraphicsContext::clipPath(const Path&, WindRule) void GraphicsContext::clipPath(const Path& path, WindRule clipRule) { if (paintingDisabled()) return; if (path.isEmpty()) return; wxGraphicsContext* gc = m_data->context->GetGraphicsContext(); #if __WXMAC__ CGContextRef context = (CGContextRef)gc->GetNativeContext(); CGPathRef nativePath = (CGPathRef)path.platformPath()->GetNativePath(); CGContextBeginPath(context); CGContextAddPath(context, nativePath); if (clipRule == RULE_EVENODD) CGContextEOClip(context); else CGContextClip(context); #elif __WXMSW__ Gdiplus::Graphics* g = (Gdiplus::Graphics*)gc->GetNativeContext(); Gdiplus::GraphicsPath* nativePath = (Gdiplus::GraphicsPath*)path.platformPath()->GetNativePath(); if (clipRule == RULE_EVENODD) nativePath->SetFillMode(Gdiplus::FillModeAlternate); else nativePath->SetFillMode(Gdiplus::FillModeWinding); g->SetClip(nativePath); #endif }
170,424
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: IndexedDBTransaction* IndexedDBConnection::CreateTransaction( int64_t id, const std::set<int64_t>& scope, blink::WebIDBTransactionMode mode, IndexedDBBackingStore::Transaction* backing_store_transaction) { DCHECK_EQ(GetTransaction(id), nullptr) << "Duplicate transaction id." << id; std::unique_ptr<IndexedDBTransaction> transaction = IndexedDBClassFactory::Get()->CreateIndexedDBTransaction( id, this, scope, mode, backing_store_transaction); IndexedDBTransaction* transaction_ptr = transaction.get(); transactions_[id] = std::move(transaction); return transaction_ptr; } Commit Message: [IndexedDB] Fixed transaction use-after-free vuln Bug: 725032 Change-Id: I689ded6c74d5563403587b149c3f3e02e807e4aa Reviewed-on: https://chromium-review.googlesource.com/518483 Reviewed-by: Joshua Bell <jsbell@chromium.org> Commit-Queue: Daniel Murphy <dmurph@chromium.org> Cr-Commit-Position: refs/heads/master@{#475952} CWE ID: CWE-416
IndexedDBTransaction* IndexedDBConnection::CreateTransaction( int64_t id, const std::set<int64_t>& scope, blink::WebIDBTransactionMode mode, IndexedDBBackingStore::Transaction* backing_store_transaction) { CHECK_EQ(GetTransaction(id), nullptr) << "Duplicate transaction id." << id; std::unique_ptr<IndexedDBTransaction> transaction = IndexedDBClassFactory::Get()->CreateIndexedDBTransaction( id, this, scope, mode, backing_store_transaction); IndexedDBTransaction* transaction_ptr = transaction.get(); transactions_[id] = std::move(transaction); return transaction_ptr; }
172,352
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 spl_filesystem_file_is_empty_line(spl_filesystem_object *intern TSRMLS_DC) /* {{{ */ { if (intern->u.file.current_line) { return intern->u.file.current_line_len == 0; } else if (intern->u.file.current_zval) { switch(Z_TYPE_P(intern->u.file.current_zval)) { case IS_STRING: return Z_STRLEN_P(intern->u.file.current_zval) == 0; case IS_ARRAY: if (SPL_HAS_FLAG(intern->flags, SPL_FILE_OBJECT_READ_CSV) && zend_hash_num_elements(Z_ARRVAL_P(intern->u.file.current_zval)) == 1) { zval ** first = Z_ARRVAL_P(intern->u.file.current_zval)->pListHead->pData; return Z_TYPE_PP(first) == IS_STRING && Z_STRLEN_PP(first) == 0; } return zend_hash_num_elements(Z_ARRVAL_P(intern->u.file.current_zval)) == 0; case IS_NULL: return 1; default: return 0; } } else { return 1; } } /* }}} */ Commit Message: Fix bug #72262 - do not overflow int CWE ID: CWE-190
static int spl_filesystem_file_is_empty_line(spl_filesystem_object *intern TSRMLS_DC) /* {{{ */ { if (intern->u.file.current_line) { return intern->u.file.current_line_len == 0; } else if (intern->u.file.current_zval) { switch(Z_TYPE_P(intern->u.file.current_zval)) { case IS_STRING: return Z_STRLEN_P(intern->u.file.current_zval) == 0; case IS_ARRAY: if (SPL_HAS_FLAG(intern->flags, SPL_FILE_OBJECT_READ_CSV) && zend_hash_num_elements(Z_ARRVAL_P(intern->u.file.current_zval)) == 1) { zval ** first = Z_ARRVAL_P(intern->u.file.current_zval)->pListHead->pData; return Z_TYPE_PP(first) == IS_STRING && Z_STRLEN_PP(first) == 0; } return zend_hash_num_elements(Z_ARRVAL_P(intern->u.file.current_zval)) == 0; case IS_NULL: return 1; default: return 0; } } else { return 1; } } /* }}} */
167,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: void Huff_transmit (huff_t *huff, int ch, byte *fout) { int i; if (huff->loc[ch] == NULL) { /* node_t hasn't been transmitted, send a NYT, then the symbol */ Huff_transmit(huff, NYT, fout); for (i = 7; i >= 0; i--) { add_bit((char)((ch >> i) & 0x1), fout); } } else { send(huff->loc[ch], NULL, fout); } } Commit Message: Fix/improve buffer overflow in MSG_ReadBits/MSG_WriteBits Prevent reading past end of message in MSG_ReadBits. If read past end of msg->data buffer (16348 bytes) the engine could SEGFAULT. Make MSG_WriteBits use an exact buffer overflow check instead of possibly failing with a few bytes left. CWE ID: CWE-119
void Huff_transmit (huff_t *huff, int ch, byte *fout) { void Huff_transmit (huff_t *huff, int ch, byte *fout, int maxoffset) { int i; if (huff->loc[ch] == NULL) { /* node_t hasn't been transmitted, send a NYT, then the symbol */ Huff_transmit(huff, NYT, fout, maxoffset); for (i = 7; i >= 0; i--) { add_bit((char)((ch >> i) & 0x1), fout); } } else { send(huff->loc[ch], NULL, fout, maxoffset); } }
167,996
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: xcalloc (size_t num, size_t size) { void *ptr = malloc(num * size); if (ptr) { memset (ptr, '\0', (num * size)); } return ptr; } Commit Message: Fix integer overflows and harden memory allocator. CWE ID: CWE-190
xcalloc (size_t num, size_t size) { size_t res; if (check_mul_overflow(num, size, &res)) abort(); void *ptr; ptr = malloc(res); if (ptr) { memset (ptr, '\0', (res)); } return ptr; }
168,358
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 UsbDevice::OpenInterface(int interface_id, const OpenCallback& callback) { Open(callback); } Commit Message: Remove fallback when requesting a single USB interface. This reverts commit 2d475d0ed37bf8f19385537ad31e361f1b21624b. The permission broker now supports opening devices that are partially claimed through the OpenPath method and RequestPathAccess will always fail for these devices so the fallback path from RequestPathAccess to OpenPath is always taken. BUG=500057 Review URL: https://codereview.chromium.org/1227313003 Cr-Commit-Position: refs/heads/master@{#338354} CWE ID: CWE-399
void UsbDevice::OpenInterface(int interface_id, const OpenCallback& callback) {
171,700
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: BufferMeta(const sp<GraphicBuffer> &graphicBuffer) : mGraphicBuffer(graphicBuffer), mIsBackup(false) { } Commit Message: DO NOT MERGE omx: check buffer port before using Bug: 28816827 Change-Id: I3d5bad4a1ef96dec544b05bb31cc6f7109aae0a5 CWE ID: CWE-119
BufferMeta(const sp<GraphicBuffer> &graphicBuffer) BufferMeta(const sp<GraphicBuffer> &graphicBuffer, OMX_U32 portIndex) : mGraphicBuffer(graphicBuffer), mIsBackup(false), mPortIndex(portIndex) { }
173,523
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: setPath(JsonbIterator **it, Datum *path_elems, bool *path_nulls, int path_len, JsonbParseState **st, int level, Jsonb *newval, bool create) { JsonbValue v; JsonbValue *res = NULL; int r; if (path_nulls[level]) elog(ERROR, "path element at the position %d is NULL", level + 1); switch (r) { case WJB_BEGIN_ARRAY: (void) pushJsonbValue(st, r, NULL); setPathArray(it, path_elems, path_nulls, path_len, st, level, newval, v.val.array.nElems, create); r = JsonbIteratorNext(it, &v, false); Assert(r == WJB_END_ARRAY); res = pushJsonbValue(st, r, NULL); break; case WJB_BEGIN_OBJECT: (void) pushJsonbValue(st, r, NULL); setPathObject(it, path_elems, path_nulls, path_len, st, level, newval, v.val.object.nPairs, create); r = JsonbIteratorNext(it, &v, true); Assert(r == WJB_END_OBJECT); res = pushJsonbValue(st, r, NULL); break; case WJB_ELEM: case WJB_VALUE: res = pushJsonbValue(st, r, &v); break; default: elog(ERROR, "impossible state"); } return res; } Commit Message: CWE ID: CWE-119
setPath(JsonbIterator **it, Datum *path_elems, bool *path_nulls, int path_len, JsonbParseState **st, int level, Jsonb *newval, bool create) { JsonbValue v; JsonbValue *res = NULL; int r; check_stack_depth(); if (path_nulls[level]) elog(ERROR, "path element at the position %d is NULL", level + 1); switch (r) { case WJB_BEGIN_ARRAY: (void) pushJsonbValue(st, r, NULL); setPathArray(it, path_elems, path_nulls, path_len, st, level, newval, v.val.array.nElems, create); r = JsonbIteratorNext(it, &v, false); Assert(r == WJB_END_ARRAY); res = pushJsonbValue(st, r, NULL); break; case WJB_BEGIN_OBJECT: (void) pushJsonbValue(st, r, NULL); setPathObject(it, path_elems, path_nulls, path_len, st, level, newval, v.val.object.nPairs, create); r = JsonbIteratorNext(it, &v, true); Assert(r == WJB_END_OBJECT); res = pushJsonbValue(st, r, NULL); break; case WJB_ELEM: case WJB_VALUE: res = pushJsonbValue(st, r, &v); break; default: elog(ERROR, "impossible state"); } return res; }
164,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 PrintViewManager::RenderFrameDeleted( content::RenderFrameHost* render_frame_host) { if (render_frame_host == print_preview_rfh_) print_preview_state_ = NOT_PREVIEWING; PrintViewManagerBase::RenderFrameDeleted(render_frame_host); } Commit Message: Properly clean up in PrintViewManager::RenderFrameCreated(). BUG=694382,698622 Review-Url: https://codereview.chromium.org/2742853003 Cr-Commit-Position: refs/heads/master@{#457363} CWE ID: CWE-125
void PrintViewManager::RenderFrameDeleted( content::RenderFrameHost* render_frame_host) { if (render_frame_host == print_preview_rfh_) PrintPreviewDone(); PrintViewManagerBase::RenderFrameDeleted(render_frame_host); }
172,405
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 ext4_end_io_nolock(ext4_io_end_t *io) { struct inode *inode = io->inode; loff_t offset = io->offset; ssize_t size = io->size; int ret = 0; ext4_debug("ext4_end_io_nolock: io 0x%p from inode %lu,list->next 0x%p," "list->prev 0x%p\n", io, inode->i_ino, io->list.next, io->list.prev); if (list_empty(&io->list)) return ret; if (io->flag != EXT4_IO_UNWRITTEN) return ret; if (offset + size <= i_size_read(inode)) ret = ext4_convert_unwritten_extents(inode, offset, size); if (ret < 0) { printk(KERN_EMERG "%s: failed to convert unwritten" "extents to written extents, error is %d" " io is still on inode %lu aio dio list\n", __func__, ret, inode->i_ino); return ret; } /* clear the DIO AIO unwritten flag */ io->flag = 0; return ret; } Commit Message: ext4: use ext4_get_block_write in buffer write Allocate uninitialized extent before ext4 buffer write and convert the extent to initialized after io completes. The purpose is to make sure an extent can only be marked initialized after it has been written with new data so we can safely drop the i_mutex lock in ext4 DIO read without exposing stale data. This helps to improve multi-thread DIO read performance on high-speed disks. Skip the nobh and data=journal mount cases to make things simple for now. Signed-off-by: Jiaying Zhang <jiayingz@google.com> Signed-off-by: "Theodore Ts'o" <tytso@mit.edu> CWE ID:
static int ext4_end_io_nolock(ext4_io_end_t *io) { struct inode *inode = io->inode; loff_t offset = io->offset; ssize_t size = io->size; int ret = 0; ext4_debug("ext4_end_io_nolock: io 0x%p from inode %lu,list->next 0x%p," "list->prev 0x%p\n", io, inode->i_ino, io->list.next, io->list.prev); if (list_empty(&io->list)) return ret; if (io->flag != EXT4_IO_UNWRITTEN) return ret; ret = ext4_convert_unwritten_extents(inode, offset, size); if (ret < 0) { printk(KERN_EMERG "%s: failed to convert unwritten" "extents to written extents, error is %d" " io is still on inode %lu aio dio list\n", __func__, ret, inode->i_ino); return ret; } /* clear the DIO AIO unwritten flag */ io->flag = 0; return ret; }
167,541
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: std::string SanitizeFrontendPath(const std::string& path) { for (size_t i = 0; i < path.length(); i++) { if (path[i] != '/' && path[i] != '-' && path[i] != '_' && path[i] != '.' && path[i] != '@' && !(path[i] >= '0' && path[i] <= '9') && !(path[i] >= 'a' && path[i] <= 'z') && !(path[i] >= 'A' && path[i] <= 'Z')) { return std::string(); } } return path; } 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
std::string SanitizeFrontendPath(const std::string& path) {
172,458
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: CSSStyleSheet* CSSStyleSheet::CreateInline(Node& owner_node, const KURL& base_url, const TextPosition& start_position, const WTF::TextEncoding& encoding) { CSSParserContext* parser_context = CSSParserContext::Create( owner_node.GetDocument(), owner_node.GetDocument().BaseURL(), owner_node.GetDocument().GetReferrerPolicy(), encoding); StyleSheetContents* sheet = StyleSheetContents::Create(base_url.GetString(), parser_context); return new CSSStyleSheet(sheet, owner_node, true, start_position); } Commit Message: Disallow access to opaque CSS responses. Bug: 848786 Change-Id: Ie53fbf644afdd76d7c65649a05c939c63d89b4ec Reviewed-on: https://chromium-review.googlesource.com/1088335 Reviewed-by: Kouhei Ueno <kouhei@chromium.org> Commit-Queue: Matt Falkenhagen <falken@chromium.org> Cr-Commit-Position: refs/heads/master@{#565537} CWE ID: CWE-200
CSSStyleSheet* CSSStyleSheet::CreateInline(Node& owner_node, const KURL& base_url, const TextPosition& start_position, const WTF::TextEncoding& encoding) { CSSParserContext* parser_context = CSSParserContext::Create( owner_node.GetDocument(), owner_node.GetDocument().BaseURL(), false /* is_opaque_response_from_service_worker */, owner_node.GetDocument().GetReferrerPolicy(), encoding); StyleSheetContents* sheet = StyleSheetContents::Create(base_url.GetString(), parser_context); return new CSSStyleSheet(sheet, owner_node, true, start_position); }
173,154
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: ScrollAnchor::ExamineResult ScrollAnchor::Examine( const LayoutObject* candidate) const { if (candidate == ScrollerLayoutBox(scroller_)) return ExamineResult(kContinue); if (candidate->StyleRef().OverflowAnchor() == EOverflowAnchor::kNone) return ExamineResult(kSkip); if (candidate->IsLayoutInline()) return ExamineResult(kContinue); if (candidate->IsAnonymous()) return ExamineResult(kContinue); if (!candidate->IsText() && !candidate->IsBox()) return ExamineResult(kSkip); if (!CandidateMayMoveWithScroller(candidate, scroller_)) return ExamineResult(kSkip); LayoutRect candidate_rect = RelativeBounds(candidate, scroller_); LayoutRect visible_rect = ScrollerLayoutBox(scroller_)->OverflowClipRect(LayoutPoint()); bool occupies_space = candidate_rect.Width() > 0 && candidate_rect.Height() > 0; if (occupies_space && visible_rect.Intersects(candidate_rect)) { return ExamineResult( visible_rect.Contains(candidate_rect) ? kReturn : kConstrain, CornerToAnchor(scroller_)); } else { return ExamineResult(kSkip); } } Commit Message: Consider scroll-padding when determining scroll anchor node Scroll anchoring should not anchor to a node that is behind scroll padding. Bug: 1010002 Change-Id: Icbd89fb85ea2c97a6de635930a9896f6a87b8f07 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1887745 Reviewed-by: Chris Harrelson <chrishtr@chromium.org> Commit-Queue: Nick Burris <nburris@chromium.org> Cr-Commit-Position: refs/heads/master@{#711020} CWE ID:
ScrollAnchor::ExamineResult ScrollAnchor::Examine( const LayoutObject* candidate) const { if (candidate == ScrollerLayoutBox(scroller_)) return ExamineResult(kContinue); if (candidate->StyleRef().OverflowAnchor() == EOverflowAnchor::kNone) return ExamineResult(kSkip); if (candidate->IsLayoutInline()) return ExamineResult(kContinue); if (candidate->IsAnonymous()) return ExamineResult(kContinue); if (!candidate->IsText() && !candidate->IsBox()) return ExamineResult(kSkip); if (!CandidateMayMoveWithScroller(candidate, scroller_)) return ExamineResult(kSkip); LayoutRect candidate_rect = RelativeBounds(candidate, scroller_); LayoutRect visible_rect = ScrollerLayoutBox(scroller_)->OverflowClipRect(LayoutPoint()); const ComputedStyle* style = ScrollerLayoutBox(scroller_)->Style(); LayoutRectOutsets scroll_padding( MinimumValueForLength(style->ScrollPaddingTop(), visible_rect.Height()), MinimumValueForLength(style->ScrollPaddingRight(), visible_rect.Width()), MinimumValueForLength(style->ScrollPaddingBottom(), visible_rect.Height()), MinimumValueForLength(style->ScrollPaddingLeft(), visible_rect.Width())); visible_rect.Contract(scroll_padding); bool occupies_space = candidate_rect.Width() > 0 && candidate_rect.Height() > 0; if (occupies_space && visible_rect.Intersects(candidate_rect)) { return ExamineResult( visible_rect.Contains(candidate_rect) ? kReturn : kConstrain, CornerToAnchor(scroller_)); } else { return ExamineResult(kSkip); } }
172,383
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 ssize_t driver_override_show(struct device *dev, struct device_attribute *attr, char *buf) { struct platform_device *pdev = to_platform_device(dev); return sprintf(buf, "%s\n", pdev->driver_override); } Commit Message: driver core: platform: fix race condition with driver_override The driver_override implementation is susceptible to race condition when different threads are reading vs storing a different driver override. Add locking to avoid race condition. Fixes: 3d713e0e382e ("driver core: platform: add device binding path 'driver_override'") Cc: stable@vger.kernel.org Signed-off-by: Adrian Salido <salidoa@google.com> Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org> CWE ID: CWE-362
static ssize_t driver_override_show(struct device *dev, struct device_attribute *attr, char *buf) { struct platform_device *pdev = to_platform_device(dev); ssize_t len; device_lock(dev); len = sprintf(buf, "%s\n", pdev->driver_override); device_unlock(dev); return len; }
167,991
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 ChromotingInstance::Init(uint32_t argc, const char* argn[], const char* argv[]) { CHECK(!initialized_); initialized_ = true; VLOG(1) << "Started ChromotingInstance::Init"; if (!media::IsMediaLibraryInitialized()) { LOG(ERROR) << "Media library not initialized."; return false; } net::EnableSSLServerSockets(); context_.Start(); scoped_refptr<FrameConsumerProxy> consumer_proxy = new FrameConsumerProxy(plugin_task_runner_); rectangle_decoder_ = new RectangleUpdateDecoder(context_.main_task_runner(), context_.decode_task_runner(), consumer_proxy); view_.reset(new PepperView(this, &context_, rectangle_decoder_.get())); consumer_proxy->Attach(view_->AsWeakPtr()); return true; } Commit Message: Restrict the Chromoting client plugin to use by extensions & apps. BUG=160456 Review URL: https://chromiumcodereview.appspot.com/11365276 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@168289 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
bool ChromotingInstance::Init(uint32_t argc, const char* argn[], const char* argv[]) { CHECK(!initialized_); initialized_ = true; VLOG(1) << "Started ChromotingInstance::Init"; if (!media::IsMediaLibraryInitialized()) { LOG(ERROR) << "Media library not initialized."; return false; } // Check that the calling content is part of an app or extension. if (!IsCallerAppOrExtension()) { LOG(ERROR) << "Not an app or extension"; return false; } net::EnableSSLServerSockets(); context_.Start(); scoped_refptr<FrameConsumerProxy> consumer_proxy = new FrameConsumerProxy(plugin_task_runner_); rectangle_decoder_ = new RectangleUpdateDecoder(context_.main_task_runner(), context_.decode_task_runner(), consumer_proxy); view_.reset(new PepperView(this, &context_, rectangle_decoder_.get())); consumer_proxy->Attach(view_->AsWeakPtr()); return true; }
170,671
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: FileBrowserHandlerCustomBindings::FileBrowserHandlerCustomBindings( ScriptContext* context) : ObjectBackedNativeHandler(context) { RouteFunction( "GetExternalFileEntry", base::Bind(&FileBrowserHandlerCustomBindings::GetExternalFileEntry, base::Unretained(this))); RouteFunction("GetEntryURL", base::Bind(&FileBrowserHandlerCustomBindings::GetEntryURL, base::Unretained(this))); } Commit Message: [Extensions] Add more bindings access checks BUG=598165 Review URL: https://codereview.chromium.org/1854983002 Cr-Commit-Position: refs/heads/master@{#385282} CWE ID:
FileBrowserHandlerCustomBindings::FileBrowserHandlerCustomBindings( ScriptContext* context) : ObjectBackedNativeHandler(context) { RouteFunction( "GetExternalFileEntry", "fileBrowserHandler", base::Bind( &FileBrowserHandlerCustomBindings::GetExternalFileEntryCallback, base::Unretained(this))); }
173,271
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: InspectorResourceAgent::InspectorResourceAgent(InspectorPageAgent* pageAgent, InspectorClient* client) : InspectorBaseAgent<InspectorResourceAgent>("Network") , m_pageAgent(pageAgent) , m_client(client) , m_frontend(0) , m_resourcesData(adoptPtr(new NetworkResourcesData())) , m_isRecalculatingStyle(false) { } 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:
InspectorResourceAgent::InspectorResourceAgent(InspectorPageAgent* pageAgent, InspectorClient* client) InspectorResourceAgent::InspectorResourceAgent(InspectorPageAgent* pageAgent) : InspectorBaseAgent<InspectorResourceAgent>("Network") , m_pageAgent(pageAgent) , m_frontend(0) , m_resourcesData(adoptPtr(new NetworkResourcesData())) , m_isRecalculatingStyle(false) { }
171,345
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 XMLHttpRequest::genericError() { clearResponse(); clearRequest(); m_error = true; changeState(DONE); } Commit Message: Don't dispatch events when XHR is set to sync mode Any of readystatechange, progress, abort, error, timeout and loadend event are not specified to be dispatched in sync mode in the latest spec. Just an exception corresponding to the failure is thrown. Clean up for readability done in this CL - factor out dispatchEventAndLoadEnd calling code - make didTimeout() private - give error handling methods more descriptive names - set m_exceptionCode in failure type specific methods -- Note that for didFailRedirectCheck, m_exceptionCode was not set in networkError(), but was set at the end of createRequest() This CL is prep for fixing crbug.com/292422 BUG=292422 Review URL: https://chromiumcodereview.appspot.com/24225002 git-svn-id: svn://svn.chromium.org/blink/trunk@158046 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399
void XMLHttpRequest::genericError() void XMLHttpRequest::handleDidFailGeneric() { clearResponse(); clearRequest(); m_error = true; }
171,168
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: ASN1_INTEGER *BN_to_ASN1_INTEGER(const BIGNUM *bn, ASN1_INTEGER *ai) { ASN1_INTEGER *ret; int len, j; if (ai == NULL) ret = M_ASN1_INTEGER_new(); else ret = ai; if (ret == NULL) { ASN1err(ASN1_F_BN_TO_ASN1_INTEGER, ERR_R_NESTED_ASN1_ERROR); goto err; ASN1err(ASN1_F_BN_TO_ASN1_INTEGER, ERR_R_NESTED_ASN1_ERROR); goto err; } if (BN_is_negative(bn)) ret->type = V_ASN1_NEG_INTEGER; else ret->type = V_ASN1_INTEGER; if (ret->length < len + 4) { unsigned char *new_data = OPENSSL_realloc(ret->data, len + 4); if (!new_data) { ASN1err(ASN1_F_BN_TO_ASN1_INTEGER, ERR_R_MALLOC_FAILURE); goto err; } ret->data = new_data; } ret->length = BN_bn2bin(bn, ret->data); /* Correct zero case */ if (!ret->length) { ret->data[0] = 0; ret->length = 1; } return (ret); err: if (ret != ai) M_ASN1_INTEGER_free(ret); return (NULL); } Commit Message: CWE ID: CWE-119
ASN1_INTEGER *BN_to_ASN1_INTEGER(const BIGNUM *bn, ASN1_INTEGER *ai) { ASN1_INTEGER *ret; int len, j; if (ai == NULL) ret = M_ASN1_INTEGER_new(); else ret = ai; if (ret == NULL) { ASN1err(ASN1_F_BN_TO_ASN1_INTEGER, ERR_R_NESTED_ASN1_ERROR); goto err; ASN1err(ASN1_F_BN_TO_ASN1_INTEGER, ERR_R_NESTED_ASN1_ERROR); goto err; } if (BN_is_negative(bn) && !BN_is_zero(bn)) ret->type = V_ASN1_NEG_INTEGER; else ret->type = V_ASN1_INTEGER; if (ret->length < len + 4) { unsigned char *new_data = OPENSSL_realloc(ret->data, len + 4); if (!new_data) { ASN1err(ASN1_F_BN_TO_ASN1_INTEGER, ERR_R_MALLOC_FAILURE); goto err; } ret->data = new_data; } ret->length = BN_bn2bin(bn, ret->data); /* Correct zero case */ if (!ret->length) { ret->data[0] = 0; ret->length = 1; } return (ret); err: if (ret != ai) M_ASN1_INTEGER_free(ret); return (NULL); }
165,209
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 InspectorPageAgent::setDeviceOrientationOverride(ErrorString* error, double alpha, double beta, double gamma) { DeviceOrientationController* controller = DeviceOrientationController::from(mainFrame()->document()); if (!controller) { *error = "Internal error: unable to override device orientation"; return; } controller->didChangeDeviceOrientation(DeviceOrientationData::create(true, alpha, true, beta, true, gamma).get()); } Commit Message: DevTools: remove references to modules/device_orientation from core BUG=340221 Review URL: https://codereview.chromium.org/150913003 git-svn-id: svn://svn.chromium.org/blink/trunk@166493 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID:
void InspectorPageAgent::setDeviceOrientationOverride(ErrorString* error, double alpha, double beta, double gamma)
171,403
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 ObserverOnLogoAvailable(LogoObserver* observer, bool from_cache, LogoCallbackReason type, const base::Optional<Logo>& logo) { switch (type) { case LogoCallbackReason::DISABLED: case LogoCallbackReason::CANCELED: case LogoCallbackReason::FAILED: break; case LogoCallbackReason::REVALIDATED: break; case LogoCallbackReason::DETERMINED: observer->OnLogoAvailable(logo ? &logo.value() : nullptr, from_cache); break; } if (!from_cache) { observer->OnObserverRemoved(); } } Commit Message: Local NTP: add smoke tests for doodles Split LogoService into LogoService interface and LogoServiceImpl to make it easier to provide fake data to the test. Bug: 768419 Cq-Include-Trybots: master.tryserver.chromium.linux:closure_compilation Change-Id: I84639189d2db1b24a2e139936c99369352bab587 Reviewed-on: https://chromium-review.googlesource.com/690198 Reviewed-by: Sylvain Defresne <sdefresne@chromium.org> Reviewed-by: Marc Treib <treib@chromium.org> Commit-Queue: Chris Pickel <sfiera@chromium.org> Cr-Commit-Position: refs/heads/master@{#505374} CWE ID: CWE-119
void ObserverOnLogoAvailable(LogoObserver* observer,
171,956
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 RenderFrameHostImpl::OnDidAddMessageToConsole( int32_t level, const base::string16& message, int32_t line_no, const base::string16& source_id) { if (level < logging::LOG_VERBOSE || level > logging::LOG_FATAL) { bad_message::ReceivedBadMessage( GetProcess(), bad_message::RFH_DID_ADD_CONSOLE_MESSAGE_BAD_SEVERITY); return; } if (delegate_->DidAddMessageToConsole(level, message, line_no, source_id)) return; const bool is_builtin_component = HasWebUIScheme(delegate_->GetMainFrameLastCommittedURL()) || GetContentClient()->browser()->IsBuiltinComponent( GetProcess()->GetBrowserContext(), GetLastCommittedOrigin()); const bool is_off_the_record = GetSiteInstance()->GetBrowserContext()->IsOffTheRecord(); LogConsoleMessage(level, message, line_no, is_builtin_component, is_off_the_record, source_id); } Commit Message: Convert FrameHostMsg_DidAddMessageToConsole to Mojo. Note: Since this required changing the test RenderViewImplTest.DispatchBeforeUnloadCanDetachFrame, I manually re-introduced https://crbug.com/666714 locally (the bug the test was added for), and reran the test to confirm that it still covers the bug. Bug: 786836 Change-Id: I110668fa6f0f261fd2ac36bb91a8d8b31c99f4f1 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1526270 Commit-Queue: Lowell Manners <lowell@chromium.org> Reviewed-by: Daniel Cheng <dcheng@chromium.org> Reviewed-by: Camille Lamy <clamy@chromium.org> Cr-Commit-Position: refs/heads/master@{#653137} CWE ID: CWE-416
void RenderFrameHostImpl::OnDidAddMessageToConsole( void RenderFrameHostImpl::DidAddMessageToConsole( blink::mojom::ConsoleMessageLevel log_level, const base::string16& message, int32_t line_no, const base::string16& source_id) { // TODO(https://crbug.com/786836): Update downstream code to use // ConsoleMessageLevel everywhere to avoid this conversion. logging::LogSeverity log_severity = logging::LOG_VERBOSE; switch (log_level) { case blink::mojom::ConsoleMessageLevel::kVerbose: log_severity = logging::LOG_VERBOSE; break; case blink::mojom::ConsoleMessageLevel::kInfo: log_severity = logging::LOG_INFO; break; case blink::mojom::ConsoleMessageLevel::kWarning: log_severity = logging::LOG_WARNING; break; case blink::mojom::ConsoleMessageLevel::kError: log_severity = logging::LOG_ERROR; break; } if (delegate_->DidAddMessageToConsole(log_severity, message, line_no, source_id)) { return; } // Pass through log severity only on builtin components pages to limit console const bool is_builtin_component = HasWebUIScheme(delegate_->GetMainFrameLastCommittedURL()) || GetContentClient()->browser()->IsBuiltinComponent( GetProcess()->GetBrowserContext(), GetLastCommittedOrigin()); const bool is_off_the_record = GetSiteInstance()->GetBrowserContext()->IsOffTheRecord(); LogConsoleMessage(log_severity, message, line_no, is_builtin_component, is_off_the_record, source_id); }
172,485
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 ssize_t yurex_read(struct file *file, char __user *buffer, size_t count, loff_t *ppos) { struct usb_yurex *dev; int retval = 0; int bytes_read = 0; char in_buffer[20]; unsigned long flags; dev = file->private_data; mutex_lock(&dev->io_mutex); if (!dev->interface) { /* already disconnected */ retval = -ENODEV; goto exit; } spin_lock_irqsave(&dev->lock, flags); bytes_read = snprintf(in_buffer, 20, "%lld\n", dev->bbu); spin_unlock_irqrestore(&dev->lock, flags); if (*ppos < bytes_read) { if (copy_to_user(buffer, in_buffer + *ppos, bytes_read - *ppos)) retval = -EFAULT; else { retval = bytes_read - *ppos; *ppos += bytes_read; } } exit: mutex_unlock(&dev->io_mutex); return retval; } Commit Message: USB: yurex: fix out-of-bounds uaccess in read handler In general, accessing userspace memory beyond the length of the supplied buffer in VFS read/write handlers can lead to both kernel memory corruption (via kernel_read()/kernel_write(), which can e.g. be triggered via sys_splice()) and privilege escalation inside userspace. Fix it by using simple_read_from_buffer() instead of custom logic. Fixes: 6bc235a2e24a ("USB: add driver for Meywa-Denki & Kayac YUREX") Signed-off-by: Jann Horn <jannh@google.com> Cc: stable <stable@vger.kernel.org> Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org> CWE ID: CWE-20
static ssize_t yurex_read(struct file *file, char __user *buffer, size_t count, loff_t *ppos) { struct usb_yurex *dev; int len = 0; char in_buffer[20]; unsigned long flags; dev = file->private_data; mutex_lock(&dev->io_mutex); if (!dev->interface) { /* already disconnected */ mutex_unlock(&dev->io_mutex); return -ENODEV; } spin_lock_irqsave(&dev->lock, flags); len = snprintf(in_buffer, 20, "%lld\n", dev->bbu); spin_unlock_irqrestore(&dev->lock, flags); mutex_unlock(&dev->io_mutex); return simple_read_from_buffer(buffer, count, ppos, in_buffer, len); }
169,084
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 RenderWidgetHostViewAura::CopyFromCompositingSurface( const gfx::Rect& src_subrect, const gfx::Size& dst_size, const base::Callback<void(bool)>& callback, skia::PlatformBitmap* output) { base::ScopedClosureRunner scoped_callback_runner(base::Bind(callback, false)); std::map<uint64, scoped_refptr<ui::Texture> >::iterator it = image_transport_clients_.find(current_surface_); if (it == image_transport_clients_.end()) return; ui::Texture* container = it->second; DCHECK(container); gfx::Size dst_size_in_pixel = ConvertSizeToPixel(this, dst_size); if (!output->Allocate( dst_size_in_pixel.width(), dst_size_in_pixel.height(), true)) return; ImageTransportFactory* factory = ImageTransportFactory::GetInstance(); GLHelper* gl_helper = factory->GetGLHelper(); if (!gl_helper) return; unsigned char* addr = static_cast<unsigned char*>( output->GetBitmap().getPixels()); scoped_callback_runner.Release(); base::Callback<void(bool)> wrapper_callback = base::Bind( &RenderWidgetHostViewAura::CopyFromCompositingSurfaceFinished, AsWeakPtr(), callback); ++pending_thumbnail_tasks_; gfx::Rect src_subrect_in_gl = src_subrect; src_subrect_in_gl.set_y(GetViewBounds().height() - src_subrect.bottom()); gfx::Rect src_subrect_in_pixel = ConvertRectToPixel(this, src_subrect_in_gl); gl_helper->CropScaleReadbackAndCleanTexture(container->PrepareTexture(), container->size(), src_subrect_in_pixel, dst_size_in_pixel, addr, wrapper_callback); } Commit Message: Implement TextureImageTransportSurface using texture mailbox This has a couple of advantages: - allow tearing down and recreating the UI parent context without losing the renderer contexts - do not require a context to be able to generate textures when creating the GLSurfaceHandle - clearer ownership semantics that potentially allows for more robust and easier lost context handling/thumbnailing/etc., since a texture is at any given time owned by either: UI parent, mailbox, or TextureImageTransportSurface - simplify frontbuffer protection logic; the frontbuffer textures are now owned by RWHV where they are refcounted The TextureImageTransportSurface informs RenderWidgetHostView of the mailbox names for the front- and backbuffer textures by associating them with a surface_handle (1 or 2) in the AcceleratedSurfaceNew message. During SwapBuffers() or PostSubBuffer() cycles, it then uses produceTextureCHROMIUM() and consumeTextureCHROMIUM() to transfer ownership between renderer and browser compositor. RWHV sends back the surface_handle of the buffer being returned with the Swap ACK (or 0 if no buffer is being returned in which case TextureImageTransportSurface will allocate a new texture - note that this could be used to simply keep textures for thumbnailing). BUG=154815,139616 TBR=sky@chromium.org Review URL: https://chromiumcodereview.appspot.com/11194042 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171569 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
void RenderWidgetHostViewAura::CopyFromCompositingSurface( const gfx::Rect& src_subrect, const gfx::Size& dst_size, const base::Callback<void(bool)>& callback, skia::PlatformBitmap* output) { base::ScopedClosureRunner scoped_callback_runner(base::Bind(callback, false)); std::map<uint64, scoped_refptr<ui::Texture> >::iterator it = image_transport_clients_.find(current_surface_); if (it == image_transport_clients_.end()) return; ui::Texture* container = it->second; DCHECK(container); gfx::Size dst_size_in_pixel = ConvertSizeToPixel(this, dst_size); if (!output->Allocate( dst_size_in_pixel.width(), dst_size_in_pixel.height(), true)) return; ImageTransportFactory* factory = ImageTransportFactory::GetInstance(); GLHelper* gl_helper = factory->GetGLHelper(); if (!gl_helper) return; unsigned char* addr = static_cast<unsigned char*>( output->GetBitmap().getPixels()); scoped_callback_runner.Release(); // own completion handlers (where we can try to free the frontbuffer). base::Callback<void(bool)> wrapper_callback = base::Bind( &RenderWidgetHostViewAura::CopyFromCompositingSurfaceFinished, AsWeakPtr(), callback); ++pending_thumbnail_tasks_; gfx::Rect src_subrect_in_gl = src_subrect; src_subrect_in_gl.set_y(GetViewBounds().height() - src_subrect.bottom()); gfx::Rect src_subrect_in_pixel = ConvertRectToPixel(this, src_subrect_in_gl); gl_helper->CropScaleReadbackAndCleanTexture(container->PrepareTexture(), container->size(), src_subrect_in_pixel, dst_size_in_pixel, addr, wrapper_callback); }
171,377
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 die(const char *fmt, ...) { va_list ap; va_start(ap, fmt); vprintf(fmt, ap); if(fmt[strlen(fmt)-1] != '\n') printf("\n"); 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
static void die(const char *fmt, ...) {
174,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: void PageRequestSummary::UpdateOrAddToOrigins( const GURL& url, const content::mojom::CommonNetworkInfoPtr& network_info) { GURL origin = url.GetOrigin(); if (!origin.is_valid()) return; auto it = origins.find(origin); if (it == origins.end()) { OriginRequestSummary summary; summary.origin = origin; summary.first_occurrence = origins.size(); it = origins.insert({origin, summary}).first; } it->second.always_access_network |= network_info->always_access_network; it->second.accessed_network |= network_info->network_accessed; } Commit Message: Origins should be represented as url::Origin (not as GURL). As pointed out in //docs/security/origin-vs-url.md, origins should be represented as url::Origin (not as GURL). This CL applies this guideline to predictor-related code and changes the type of the following fields from GURL to url::Origin: - OriginRequestSummary::origin - PreconnectedRequestStats::origin - PreconnectRequest::origin The old code did not depend on any non-origin parts of GURL (like path and/or query). Therefore, this CL has no intended behavior change. Bug: 973885 Change-Id: Idd14590b4834cb9d50c74ed747b595fe1a4ba357 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1895167 Commit-Queue: Łukasz Anforowicz <lukasza@chromium.org> Reviewed-by: Alex Ilin <alexilin@chromium.org> Cr-Commit-Position: refs/heads/master@{#716311} CWE ID: CWE-125
void PageRequestSummary::UpdateOrAddToOrigins( const url::Origin& origin, const content::mojom::CommonNetworkInfoPtr& network_info) { if (origin.opaque()) return; auto it = origins.find(origin); if (it == origins.end()) { OriginRequestSummary summary; summary.origin = origin; summary.first_occurrence = origins.size(); it = origins.insert({origin, summary}).first; } it->second.always_access_network |= network_info->always_access_network; it->second.accessed_network |= network_info->network_accessed; }
172,368
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 EnsureInitializeForAndroidLayoutTests() { CHECK(CommandLine::ForCurrentProcess()->HasSwitch(switches::kDumpRenderTree)); JNIEnv* env = base::android::AttachCurrentThread(); content::NestedMessagePumpAndroid::RegisterJni(env); content::RegisterNativesImpl(env); bool success = base::MessageLoop::InitMessagePumpForUIFactory( &CreateMessagePumpForUI); CHECK(success) << "Unable to initialize the message pump for Android."; base::FilePath files_dir(GetTestFilesDirectory(env)); base::FilePath stdout_fifo(files_dir.Append(FILE_PATH_LITERAL("test.fifo"))); EnsureCreateFIFO(stdout_fifo); base::FilePath stderr_fifo( files_dir.Append(FILE_PATH_LITERAL("stderr.fifo"))); EnsureCreateFIFO(stderr_fifo); base::FilePath stdin_fifo(files_dir.Append(FILE_PATH_LITERAL("stdin.fifo"))); EnsureCreateFIFO(stdin_fifo); success = base::android::RedirectStream(stdout, stdout_fifo, "w") && base::android::RedirectStream(stdin, stdin_fifo, "r") && base::android::RedirectStream(stderr, stderr_fifo, "w"); CHECK(success) << "Unable to initialize the Android FIFOs."; } Commit Message: Content Shell: Move shell_layout_tests_android into layout_tests/. BUG=420994 Review URL: https://codereview.chromium.org/661743002 Cr-Commit-Position: refs/heads/master@{#299892} CWE ID: CWE-119
void EnsureInitializeForAndroidLayoutTests() { JNIEnv* env = base::android::AttachCurrentThread(); content::NestedMessagePumpAndroid::RegisterJni(env); content::RegisterNativesImpl(env); bool success = base::MessageLoop::InitMessagePumpForUIFactory( &CreateMessagePumpForUI); CHECK(success) << "Unable to initialize the message pump for Android."; base::FilePath files_dir(GetTestFilesDirectory(env)); base::FilePath stdout_fifo(files_dir.Append(FILE_PATH_LITERAL("test.fifo"))); EnsureCreateFIFO(stdout_fifo); base::FilePath stderr_fifo( files_dir.Append(FILE_PATH_LITERAL("stderr.fifo"))); EnsureCreateFIFO(stderr_fifo); base::FilePath stdin_fifo(files_dir.Append(FILE_PATH_LITERAL("stdin.fifo"))); EnsureCreateFIFO(stdin_fifo); success = base::android::RedirectStream(stdout, stdout_fifo, "w") && base::android::RedirectStream(stdin, stdin_fifo, "r") && base::android::RedirectStream(stderr, stderr_fifo, "w"); CHECK(success) << "Unable to initialize the Android FIFOs."; }
171,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: void AssertObserverCount(int added_count, int removed_count, int changed_count) { ASSERT_EQ(added_count, added_count_); ASSERT_EQ(removed_count, removed_count_); ASSERT_EQ(changed_count, changed_count_); } Commit Message: Add OVERRIDE to ui::TreeModelObserver overridden methods. BUG=None TEST=None R=sky@chromium.org Review URL: http://codereview.chromium.org/7046093 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@88827 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
void AssertObserverCount(int added_count, int removed_count, void AssertObserverCount(int added_count, int removed_count, int changed_count) { ASSERT_EQ(added_count, added_count_); ASSERT_EQ(removed_count, removed_count_); ASSERT_EQ(changed_count, changed_count_); }
170,468
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 SoftVPX::outputBufferSafe(OMX_BUFFERHEADERTYPE *outHeader) { uint32_t width = outputBufferWidth(); uint32_t height = outputBufferHeight(); uint64_t nFilledLen = width; nFilledLen *= height; if (nFilledLen > UINT32_MAX / 3) { ALOGE("b/29421675, nFilledLen overflow %llu w %u h %u", nFilledLen, width, height); android_errorWriteLog(0x534e4554, "29421675"); return false; } else if (outHeader->nAllocLen < outHeader->nFilledLen) { ALOGE("b/27597103, buffer too small"); android_errorWriteLog(0x534e4554, "27597103"); return false; } return true; } Commit Message: fix build Change-Id: I9bb8c659d3fc97a8e748451d82d0f3448faa242b CWE ID: CWE-119
bool SoftVPX::outputBufferSafe(OMX_BUFFERHEADERTYPE *outHeader) { uint32_t width = outputBufferWidth(); uint32_t height = outputBufferHeight(); uint64_t nFilledLen = width; nFilledLen *= height; if (nFilledLen > UINT32_MAX / 3) { ALOGE("b/29421675, nFilledLen overflow %llu w %u h %u", (unsigned long long)nFilledLen, width, height); android_errorWriteLog(0x534e4554, "29421675"); return false; } else if (outHeader->nAllocLen < outHeader->nFilledLen) { ALOGE("b/27597103, buffer too small"); android_errorWriteLog(0x534e4554, "27597103"); return false; } return true; }
173,414
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: SProcXSendExtensionEvent(ClientPtr client) { CARD32 *p; int i; xEvent eventT; xEvent *eventP; EventSwapPtr proc; REQUEST(xSendExtensionEventReq); swaps(&stuff->length); REQUEST_AT_LEAST_SIZE(xSendExtensionEventReq); swapl(&stuff->destination); swaps(&stuff->count); if (stuff->length != bytes_to_int32(sizeof(xSendExtensionEventReq)) + stuff->count + bytes_to_int32(stuff->num_events * sizeof(xEvent))) return BadLength; eventP = (xEvent *) &stuff[1]; for (i = 0; i < stuff->num_events; i++, eventP++) { proc = EventSwapVector[eventP->u.u.type & 0177]; if (proc == NotImplemented) /* no swapping proc; invalid event type? */ return BadValue; (*proc) (eventP, &eventT); *eventP = eventT; } p = (CARD32 *) (((xEvent *) &stuff[1]) + stuff->num_events); SwapLongs(p, stuff->count); return (ProcXSendExtensionEvent(client)); } Commit Message: CWE ID: CWE-665
SProcXSendExtensionEvent(ClientPtr client) { CARD32 *p; int i; xEvent eventT = { .u.u.type = 0 }; xEvent *eventP; EventSwapPtr proc; REQUEST(xSendExtensionEventReq); swaps(&stuff->length); REQUEST_AT_LEAST_SIZE(xSendExtensionEventReq); swapl(&stuff->destination); swaps(&stuff->count); if (stuff->length != bytes_to_int32(sizeof(xSendExtensionEventReq)) + stuff->count + bytes_to_int32(stuff->num_events * sizeof(xEvent))) return BadLength; eventP = (xEvent *) &stuff[1]; for (i = 0; i < stuff->num_events; i++, eventP++) { proc = EventSwapVector[eventP->u.u.type & 0177]; if (proc == NotImplemented) /* no swapping proc; invalid event type? */ return BadValue; (*proc) (eventP, &eventT); *eventP = eventT; } p = (CARD32 *) (((xEvent *) &stuff[1]) + stuff->num_events); SwapLongs(p, stuff->count); return (ProcXSendExtensionEvent(client)); }
164,763
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 enable_nmi_window(struct kvm_vcpu *vcpu) { struct vcpu_svm *svm = to_svm(vcpu); if ((svm->vcpu.arch.hflags & (HF_NMI_MASK | HF_IRET_MASK)) == HF_NMI_MASK) return; /* IRET will cause a vm exit */ /* * Something prevents NMI from been injected. Single step over possible * problem (IRET or exception injection or interrupt shadow) */ svm->nmi_singlestep = true; svm->vmcb->save.rflags |= (X86_EFLAGS_TF | X86_EFLAGS_RF); update_db_bp_intercept(vcpu); } Commit Message: KVM: svm: unconditionally intercept #DB This is needed to avoid the possibility that the guest triggers an infinite stream of #DB exceptions (CVE-2015-8104). VMX is not affected: because it does not save DR6 in the VMCS, it already intercepts #DB unconditionally. Reported-by: Jan Beulich <jbeulich@suse.com> Cc: stable@vger.kernel.org Signed-off-by: Paolo Bonzini <pbonzini@redhat.com> CWE ID: CWE-399
static void enable_nmi_window(struct kvm_vcpu *vcpu) { struct vcpu_svm *svm = to_svm(vcpu); if ((svm->vcpu.arch.hflags & (HF_NMI_MASK | HF_IRET_MASK)) == HF_NMI_MASK) return; /* IRET will cause a vm exit */ /* * Something prevents NMI from been injected. Single step over possible * problem (IRET or exception injection or interrupt shadow) */ svm->nmi_singlestep = true; svm->vmcb->save.rflags |= (X86_EFLAGS_TF | X86_EFLAGS_RF); }
166,569
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 PPB_NaCl_Private* GetNaclInterface() { pp::Module *module = pp::Module::Get(); CHECK(module); return static_cast<const PPB_NaCl_Private*>( module->GetBrowserInterface(PPB_NACL_PRIVATE_INTERFACE)); } 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 TBR=bbudge@chromium.org 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
const PPB_NaCl_Private* GetNaclInterface() {
170,741
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 balloon_process(struct work_struct *work) { enum bp_state state = BP_DONE; long credit; do { mutex_lock(&balloon_mutex); credit = current_credit(); if (credit > 0) { if (balloon_is_inflated()) state = increase_reservation(credit); else state = reserve_additional_memory(); } if (credit < 0) state = decrease_reservation(-credit, GFP_BALLOON); state = update_schedule(state); mutex_unlock(&balloon_mutex); cond_resched(); } while (credit && state == BP_DONE); /* Schedule more work if there is some still to be done. */ if (state == BP_EAGAIN) schedule_delayed_work(&balloon_worker, balloon_stats.schedule_delay * HZ); } Commit Message: xen: let alloc_xenballooned_pages() fail if not enough memory free commit a1078e821b605813b63bf6bca414a85f804d5c66 upstream. Instead of trying to allocate pages with GFP_USER in add_ballooned_pages() check the available free memory via si_mem_available(). GFP_USER is far less limiting memory exhaustion than the test via si_mem_available(). This will avoid dom0 running out of memory due to excessive foreign page mappings especially on ARM and on x86 in PVH mode, as those don't have a pre-ballooned area which can be used for foreign mappings. As the normal ballooning suffers from the same problem don't balloon down more than si_mem_available() pages in one iteration. At the same time limit the default maximum number of retries. This is part of XSA-300. Signed-off-by: Juergen Gross <jgross@suse.com> Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org> CWE ID: CWE-400
static void balloon_process(struct work_struct *work) { enum bp_state state = BP_DONE; long credit; do { mutex_lock(&balloon_mutex); credit = current_credit(); if (credit > 0) { if (balloon_is_inflated()) state = increase_reservation(credit); else state = reserve_additional_memory(); } if (credit < 0) { long n_pages; n_pages = min(-credit, si_mem_available()); state = decrease_reservation(n_pages, GFP_BALLOON); if (state == BP_DONE && n_pages != -credit && n_pages < totalreserve_pages) state = BP_EAGAIN; } state = update_schedule(state); mutex_unlock(&balloon_mutex); cond_resched(); } while (credit && state == BP_DONE); /* Schedule more work if there is some still to be done. */ if (state == BP_EAGAIN) schedule_delayed_work(&balloon_worker, balloon_stats.schedule_delay * HZ); }
169,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: static void mptsas_fetch_request(MPTSASState *s) { PCIDevice *pci = (PCIDevice *) s; char req[MPTSAS_MAX_REQUEST_SIZE]; MPIRequestHeader *hdr = (MPIRequestHeader *)req; hwaddr addr; int size; if (s->state != MPI_IOC_STATE_OPERATIONAL) { mptsas_set_fault(s, MPI_IOCSTATUS_INVALID_STATE); return; } /* Read the message header from the guest first. */ addr = s->host_mfa_high_addr | MPTSAS_FIFO_GET(s, request_post); pci_dma_read(pci, addr, req, sizeof(hdr)); } Commit Message: CWE ID: CWE-20
static void mptsas_fetch_request(MPTSASState *s) { PCIDevice *pci = (PCIDevice *) s; char req[MPTSAS_MAX_REQUEST_SIZE]; MPIRequestHeader *hdr = (MPIRequestHeader *)req; hwaddr addr; int size; /* Read the message header from the guest first. */ addr = s->host_mfa_high_addr | MPTSAS_FIFO_GET(s, request_post); pci_dma_read(pci, addr, req, sizeof(hdr)); }
165,017
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 FeatureInfo::EnableOESTextureHalfFloatLinear() { if (!oes_texture_half_float_linear_available_) return; AddExtensionString("GL_OES_texture_half_float_linear"); feature_flags_.enable_texture_half_float_linear = true; feature_flags_.gpu_memory_buffer_formats.Add(gfx::BufferFormat::RGBA_F16); } Commit Message: gpu: Disallow use of IOSurfaces for half-float format with swiftshader. R=kbr@chromium.org Bug: 998038 Change-Id: Ic31d28938ef205b36657fc7bd297fe8a63d08543 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1798052 Commit-Queue: Kenneth Russell <kbr@chromium.org> Reviewed-by: Kenneth Russell <kbr@chromium.org> Auto-Submit: Khushal <khushalsagar@chromium.org> Cr-Commit-Position: refs/heads/master@{#695826} CWE ID: CWE-125
void FeatureInfo::EnableOESTextureHalfFloatLinear() { if (!oes_texture_half_float_linear_available_) return; AddExtensionString("GL_OES_texture_half_float_linear"); feature_flags_.enable_texture_half_float_linear = true; // TODO(capn) : Re-enable this once we have ANGLE+SwiftShader supporting // IOSurfaces. if (workarounds_.disable_half_float_for_gmb) return; feature_flags_.gpu_memory_buffer_formats.Add(gfx::BufferFormat::RGBA_F16); }
172,387
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 iwch_cxgb3_ofld_send(struct t3cdev *tdev, struct sk_buff *skb) { int error = 0; struct cxio_rdev *rdev; rdev = (struct cxio_rdev *)tdev->ulp; if (cxio_fatal_error(rdev)) { kfree_skb(skb); return -EIO; } error = cxgb3_ofld_send(tdev, skb); if (error < 0) kfree_skb(skb); return error; } Commit Message: iw_cxgb3: Fix incorrectly returning error on success The cxgb3_*_send() functions return NET_XMIT_ values, which are positive integers values. So don't treat positive return values as an error. Signed-off-by: Steve Wise <swise@opengridcomputing.com> Signed-off-by: Hariprasad Shenai <hariprasad@chelsio.com> Signed-off-by: Doug Ledford <dledford@redhat.com> CWE ID:
int iwch_cxgb3_ofld_send(struct t3cdev *tdev, struct sk_buff *skb) { int error = 0; struct cxio_rdev *rdev; rdev = (struct cxio_rdev *)tdev->ulp; if (cxio_fatal_error(rdev)) { kfree_skb(skb); return -EIO; } error = cxgb3_ofld_send(tdev, skb); if (error < 0) kfree_skb(skb); return error < 0 ? error : 0; }
167,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: RenderFrameHostManager::GetSiteInstanceForNavigationRequest( const NavigationRequest& request) { SiteInstance* current_site_instance = render_frame_host_->GetSiteInstance(); bool no_renderer_swap_allowed = false; bool was_server_redirect = request.navigation_handle() && request.navigation_handle()->WasServerRedirect(); if (frame_tree_node_->IsMainFrame()) { bool can_renderer_initiate_transfer = (request.state() == NavigationRequest::FAILED && SiteIsolationPolicy::IsErrorPageIsolationEnabled( true /* in_main_frame */)) || (render_frame_host_->IsRenderFrameLive() && IsURLHandledByNetworkStack(request.common_params().url) && IsRendererTransferNeededForNavigation(render_frame_host_.get(), request.common_params().url)); no_renderer_swap_allowed |= request.from_begin_navigation() && !can_renderer_initiate_transfer; } else { no_renderer_swap_allowed |= !CanSubframeSwapProcess( request.common_params().url, request.source_site_instance(), request.dest_site_instance(), was_server_redirect); } if (no_renderer_swap_allowed) return scoped_refptr<SiteInstance>(current_site_instance); SiteInstance* candidate_site_instance = speculative_render_frame_host_ ? speculative_render_frame_host_->GetSiteInstance() : nullptr; scoped_refptr<SiteInstance> dest_site_instance = GetSiteInstanceForNavigation( request.common_params().url, request.source_site_instance(), request.dest_site_instance(), candidate_site_instance, request.common_params().transition, request.state() == NavigationRequest::FAILED, request.restore_type() != RestoreType::NONE, request.is_view_source(), was_server_redirect); return dest_site_instance; } 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 <alexmos@chromium.org> Reviewed-by: Lei Zhang <thestig@chromium.org> Commit-Queue: Charlie Reis <creis@chromium.org> Cr-Commit-Position: refs/heads/master@{#581023} CWE ID: CWE-285
RenderFrameHostManager::GetSiteInstanceForNavigationRequest( const NavigationRequest& request) { SiteInstance* current_site_instance = render_frame_host_->GetSiteInstance(); bool no_renderer_swap_allowed = false; bool was_server_redirect = request.navigation_handle() && request.navigation_handle()->WasServerRedirect(); if (frame_tree_node_->IsMainFrame()) { bool can_renderer_initiate_transfer = (request.state() == NavigationRequest::FAILED && SiteIsolationPolicy::IsErrorPageIsolationEnabled( true /* in_main_frame */)) || (render_frame_host_->IsRenderFrameLive() && IsURLHandledByNetworkStack(request.common_params().url) && IsRendererTransferNeededForNavigation(render_frame_host_.get(), request.common_params().url)); no_renderer_swap_allowed |= request.from_begin_navigation() && !can_renderer_initiate_transfer; } else { no_renderer_swap_allowed |= !CanSubframeSwapProcess( request.common_params().url, request.source_site_instance(), request.dest_site_instance()); } if (no_renderer_swap_allowed) return scoped_refptr<SiteInstance>(current_site_instance); SiteInstance* candidate_site_instance = speculative_render_frame_host_ ? speculative_render_frame_host_->GetSiteInstance() : nullptr; scoped_refptr<SiteInstance> dest_site_instance = GetSiteInstanceForNavigation( request.common_params().url, request.source_site_instance(), request.dest_site_instance(), candidate_site_instance, request.common_params().transition, request.state() == NavigationRequest::FAILED, request.restore_type() != RestoreType::NONE, request.is_view_source(), was_server_redirect); return dest_site_instance; }
173,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: static int wanxl_ioctl(struct net_device *dev, struct ifreq *ifr, int cmd) { const size_t size = sizeof(sync_serial_settings); sync_serial_settings line; port_t *port = dev_to_port(dev); if (cmd != SIOCWANDEV) return hdlc_ioctl(dev, ifr, cmd); switch (ifr->ifr_settings.type) { case IF_GET_IFACE: ifr->ifr_settings.type = IF_IFACE_SYNC_SERIAL; if (ifr->ifr_settings.size < size) { ifr->ifr_settings.size = size; /* data size wanted */ return -ENOBUFS; } line.clock_type = get_status(port)->clocking; line.clock_rate = 0; line.loopback = 0; if (copy_to_user(ifr->ifr_settings.ifs_ifsu.sync, &line, size)) return -EFAULT; return 0; case IF_IFACE_SYNC_SERIAL: if (!capable(CAP_NET_ADMIN)) return -EPERM; if (dev->flags & IFF_UP) return -EBUSY; if (copy_from_user(&line, ifr->ifr_settings.ifs_ifsu.sync, size)) return -EFAULT; if (line.clock_type != CLOCK_EXT && line.clock_type != CLOCK_TXFROMRX) return -EINVAL; /* No such clock setting */ if (line.loopback != 0) return -EINVAL; get_status(port)->clocking = line.clock_type; return 0; default: return hdlc_ioctl(dev, ifr, cmd); } } Commit Message: wanxl: fix info leak in ioctl The wanxl_ioctl() code fails to initialize the two padding bytes of struct sync_serial_settings after the ->loopback member. Add an explicit memset(0) before filling the structure to avoid the info leak. Signed-off-by: Salva Peiró <speiro@ai2.upv.es> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID: CWE-399
static int wanxl_ioctl(struct net_device *dev, struct ifreq *ifr, int cmd) { const size_t size = sizeof(sync_serial_settings); sync_serial_settings line; port_t *port = dev_to_port(dev); if (cmd != SIOCWANDEV) return hdlc_ioctl(dev, ifr, cmd); switch (ifr->ifr_settings.type) { case IF_GET_IFACE: ifr->ifr_settings.type = IF_IFACE_SYNC_SERIAL; if (ifr->ifr_settings.size < size) { ifr->ifr_settings.size = size; /* data size wanted */ return -ENOBUFS; } memset(&line, 0, sizeof(line)); line.clock_type = get_status(port)->clocking; line.clock_rate = 0; line.loopback = 0; if (copy_to_user(ifr->ifr_settings.ifs_ifsu.sync, &line, size)) return -EFAULT; return 0; case IF_IFACE_SYNC_SERIAL: if (!capable(CAP_NET_ADMIN)) return -EPERM; if (dev->flags & IFF_UP) return -EBUSY; if (copy_from_user(&line, ifr->ifr_settings.ifs_ifsu.sync, size)) return -EFAULT; if (line.clock_type != CLOCK_EXT && line.clock_type != CLOCK_TXFROMRX) return -EINVAL; /* No such clock setting */ if (line.loopback != 0) return -EINVAL; get_status(port)->clocking = line.clock_type; return 0; default: return hdlc_ioctl(dev, ifr, cmd); } }
166,438
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 sh_op(RAnal *anal, RAnalOp *op, ut64 addr, const ut8 *data, int len) { ut8 op_MSB,op_LSB; int ret; if (!data) return 0; memset (op, '\0', sizeof (RAnalOp)); op->addr = addr; op->type = R_ANAL_OP_TYPE_UNK; op->jump = op->fail = -1; op->ptr = op->val = -1; op->size = 2; op_MSB = anal->big_endian? data[0]: data[1]; op_LSB = anal->big_endian? data[1]: data[0]; ret = first_nibble_decode[(op_MSB>>4) & 0x0F](anal, op, (ut16)(op_MSB<<8 | op_LSB)); return ret; } Commit Message: Fix #9903 - oobread in RAnal.sh CWE ID: CWE-125
static int sh_op(RAnal *anal, RAnalOp *op, ut64 addr, const ut8 *data, int len) { ut8 op_MSB,op_LSB; int ret; if (!data || len < 2) { return 0; } memset (op, '\0', sizeof (RAnalOp)); op->addr = addr; op->type = R_ANAL_OP_TYPE_UNK; op->jump = op->fail = -1; op->ptr = op->val = -1; op->size = 2; op_MSB = anal->big_endian? data[0]: data[1]; op_LSB = anal->big_endian? data[1]: data[0]; ret = first_nibble_decode[(op_MSB>>4) & 0x0F](anal, op, (ut16)(op_MSB<<8 | op_LSB)); return ret; }
169,221
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 parse_csum_name(const char *name, int len) { if (len < 0 && name) len = strlen(name); if (!name || (len == 4 && strncasecmp(name, "auto", 4) == 0)) { if (protocol_version >= 30) return CSUM_MD5; if (protocol_version >= 27) return CSUM_MD4_OLD; if (protocol_version >= 21) return CSUM_MD4_BUSTED; return CSUM_ARCHAIC; } if (len == 3 && strncasecmp(name, "md4", 3) == 0) return CSUM_MD4; if (len == 3 && strncasecmp(name, "md5", 3) == 0) return CSUM_MD5; if (len == 4 && strncasecmp(name, "none", 4) == 0) return CSUM_NONE; rprintf(FERROR, "unknown checksum name: %s\n", name); exit_cleanup(RERR_UNSUPPORTED); } Commit Message: CWE ID: CWE-354
int parse_csum_name(const char *name, int len) { if (len < 0 && name) len = strlen(name); if (!name || (len == 4 && strncasecmp(name, "auto", 4) == 0)) { if (protocol_version >= 30) return CSUM_MD5; if (protocol_version >= 27) return CSUM_MD4_OLD; if (protocol_version >= 21) return CSUM_MD4_BUSTED; return CSUM_MD4_ARCHAIC; } if (len == 3 && strncasecmp(name, "md4", 3) == 0) return CSUM_MD4; if (len == 3 && strncasecmp(name, "md5", 3) == 0) return CSUM_MD5; if (len == 4 && strncasecmp(name, "none", 4) == 0) return CSUM_NONE; rprintf(FERROR, "unknown checksum name: %s\n", name); exit_cleanup(RERR_UNSUPPORTED); }
164,645