instruction
stringclasses
1 value
input
stringlengths
90
9.3k
output
stringlengths
16
15.4k
__index_level_0__
int64
165k
175k
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: make_size(png_store* PNG_CONST ps, png_byte PNG_CONST colour_type, int bdlo, int PNG_CONST bdhi) { for (; bdlo <= bdhi; ++bdlo) { png_uint_32 width; for (width = 1; width <= 16; ++width) { png_uint_32 height; for (height = 1; height <= 16; ++height) { /* The four combinations of DIY interlace and interlace or not - * no interlace + DIY should be identical to no interlace with * libpng doing it. */ make_size_image(ps, colour_type, DEPTH(bdlo), PNG_INTERLACE_NONE, width, height, 0); make_size_image(ps, colour_type, DEPTH(bdlo), PNG_INTERLACE_NONE, width, height, 1); # ifdef PNG_WRITE_INTERLACING_SUPPORTED make_size_image(ps, colour_type, DEPTH(bdlo), PNG_INTERLACE_ADAM7, width, height, 0); make_size_image(ps, colour_type, DEPTH(bdlo), PNG_INTERLACE_ADAM7, width, height, 1); # endif } } } } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
make_size(png_store* PNG_CONST ps, png_byte PNG_CONST colour_type, int bdlo, make_size(png_store* const ps, png_byte const colour_type, int bdlo, int const bdhi) { for (; bdlo <= bdhi; ++bdlo) { png_uint_32 width; for (width = 1; width <= 16; ++width) { png_uint_32 height; for (height = 1; height <= 16; ++height) { /* The four combinations of DIY interlace and interlace or not - * no interlace + DIY should be identical to no interlace with * libpng doing it. */ make_size_image(ps, colour_type, DEPTH(bdlo), PNG_INTERLACE_NONE, width, height, 0); make_size_image(ps, colour_type, DEPTH(bdlo), PNG_INTERLACE_NONE, width, height, 1); # ifdef PNG_WRITE_INTERLACING_SUPPORTED make_size_image(ps, colour_type, DEPTH(bdlo), PNG_INTERLACE_ADAM7, width, height, 0); # endif # if CAN_WRITE_INTERLACE /* 1.7.0 removes the hack that prevented app write of an interlaced * image if WRITE_INTERLACE was not supported */ make_size_image(ps, colour_type, DEPTH(bdlo), PNG_INTERLACE_ADAM7, width, height, 1); # endif } } } }
173,663
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int dtls1_retrieve_buffered_fragment(SSL *s, int *ok) { /*- * (0) check whether the desired fragment is available * if so: * (1) copy over the fragment to s->init_buf->data[] * (2) update s->init_num */ pitem *item; hm_fragment *frag; int al; *ok = 0; item = pqueue_peek(s->d1->buffered_messages); if (item == NULL) return 0; frag = (hm_fragment *)item->data; /* Don't return if reassembly still in progress */ if (frag->reassembly != NULL) frag->msg_header.frag_len); } Commit Message: CWE ID: CWE-399
static int dtls1_retrieve_buffered_fragment(SSL *s, int *ok) { /*- * (0) check whether the desired fragment is available * if so: * (1) copy over the fragment to s->init_buf->data[] * (2) update s->init_num */ pitem *item; hm_fragment *frag; int al; *ok = 0; do { item = pqueue_peek(s->d1->buffered_messages); if (item == NULL) return 0; frag = (hm_fragment *)item->data; if (frag->msg_header.seq < s->d1->handshake_read_seq) { /* This is a stale message that has been buffered so clear it */ pqueue_pop(s->d1->buffered_messages); dtls1_hm_fragment_free(frag); pitem_free(item); item = NULL; frag = NULL; } } while (item == NULL); /* Don't return if reassembly still in progress */ if (frag->reassembly != NULL) frag->msg_header.frag_len); }
165,197
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool mkvparser::Match(IMkvReader* pReader, long long& pos, unsigned long id_, unsigned char*& buf, size_t& buflen) { assert(pReader); assert(pos >= 0); long long total, available; long status = pReader->Length(&total, &available); assert(status >= 0); assert((total < 0) || (available <= total)); if (status < 0) return false; long len; const long long id = ReadUInt(pReader, pos, len); assert(id >= 0); assert(len > 0); assert(len <= 8); assert((pos + len) <= available); if ((unsigned long)id != id_) return false; pos += len; // consume id const long long size_ = ReadUInt(pReader, pos, len); assert(size_ >= 0); assert(len > 0); assert(len <= 8); assert((pos + len) <= available); pos += len; // consume length of size of payload assert((pos + size_) <= available); const long buflen_ = static_cast<long>(size_); buf = new (std::nothrow) unsigned char[buflen_]; assert(buf); // TODO status = pReader->Read(pos, buflen_, buf); assert(status == 0); // TODO buflen = buflen_; pos += size_; // consume size of payload return true; } Commit Message: external/libvpx/libwebm: Update snapshot Update libwebm snapshot. This update contains security fixes from upstream. Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b BUG=23167726 Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207 (cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a) CWE ID: CWE-20
bool mkvparser::Match(IMkvReader* pReader, long long& pos, unsigned long id_, bool Match(IMkvReader* pReader, long long& pos, unsigned long expected_id, unsigned char*& buf, size_t& buflen) { if (!pReader || pos < 0) return false; long long total = 0; long long available = 0; long status = pReader->Length(&total, &available); if (status < 0 || (total >= 0 && available > total)) return false; long len = 0; const long long id = ReadID(pReader, pos, len); if (id < 0 || (available - pos) > len) return false; if (static_cast<unsigned long>(id) != expected_id) return false; pos += len; // consume id const long long size = ReadUInt(pReader, pos, len); if (size < 0 || len <= 0 || len > 8 || (available - pos) > len) return false; unsigned long long rollover_check = static_cast<unsigned long long>(pos) + len; if (rollover_check > LONG_LONG_MAX) return false; pos += len; // consume length of size of payload rollover_check = static_cast<unsigned long long>(pos) + size; if (rollover_check > LONG_LONG_MAX) return false; if ((pos + size) > available) return false; if (size >= LONG_MAX) return false; const long buflen_ = static_cast<long>(size); buf = SafeArrayAlloc<unsigned char>(1, buflen_); if (!buf) return false; status = pReader->Read(pos, buflen_, buf); if (status != 0) return false; buflen = buflen_; pos += size; // consume size of payload return true; }
173,833
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: MagickExport MemoryInfo *AcquireVirtualMemory(const size_t count, const size_t quantum) { MemoryInfo *memory_info; size_t extent; if (CheckMemoryOverflow(count,quantum) != MagickFalse) return((MemoryInfo *) NULL); memory_info=(MemoryInfo *) MagickAssumeAligned(AcquireAlignedMemory(1, sizeof(*memory_info))); if (memory_info == (MemoryInfo *) NULL) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); (void) ResetMagickMemory(memory_info,0,sizeof(*memory_info)); extent=count*quantum; memory_info->length=extent; memory_info->signature=MagickSignature; if (AcquireMagickResource(MemoryResource,extent) != MagickFalse) { memory_info->blob=AcquireAlignedMemory(1,extent); if (memory_info->blob != NULL) { memory_info->type=AlignedVirtualMemory; return(memory_info); } } RelinquishMagickResource(MemoryResource,extent); if (AcquireMagickResource(MapResource,extent) != MagickFalse) { /* Heap memory failed, try anonymous memory mapping. */ memory_info->blob=MapBlob(-1,IOMode,0,extent); if (memory_info->blob != NULL) { memory_info->type=MapVirtualMemory; return(memory_info); } if (AcquireMagickResource(DiskResource,extent) != MagickFalse) { int file; /* Anonymous memory mapping failed, try file-backed memory mapping. If the MapResource request failed, there is no point in trying file-backed memory mapping. */ file=AcquireUniqueFileResource(memory_info->filename); if (file != -1) { MagickOffsetType offset; offset=(MagickOffsetType) lseek(file,extent-1,SEEK_SET); if ((offset == (MagickOffsetType) (extent-1)) && (write(file,"",1) == 1)) { memory_info->blob=MapBlob(file,IOMode,0,extent); if (memory_info->blob != NULL) { (void) close(file); memory_info->type=MapVirtualMemory; return(memory_info); } } /* File-backed memory mapping failed, delete the temporary file. */ (void) close(file); (void) RelinquishUniqueFileResource(memory_info->filename); *memory_info->filename='\0'; } } RelinquishMagickResource(DiskResource,extent); } RelinquishMagickResource(MapResource,extent); if (memory_info->blob == NULL) { memory_info->blob=AcquireMagickMemory(extent); if (memory_info->blob != NULL) memory_info->type=UnalignedVirtualMemory; } if (memory_info->blob == NULL) memory_info=RelinquishVirtualMemory(memory_info); return(memory_info); } Commit Message: Suspend exception processing if there are too many exceptions CWE ID: CWE-119
MagickExport MemoryInfo *AcquireVirtualMemory(const size_t count, const size_t quantum) { MemoryInfo *memory_info; size_t extent; if (HeapOverflowSanityCheck(count,quantum) != MagickFalse) return((MemoryInfo *) NULL); memory_info=(MemoryInfo *) MagickAssumeAligned(AcquireAlignedMemory(1, sizeof(*memory_info))); if (memory_info == (MemoryInfo *) NULL) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); (void) ResetMagickMemory(memory_info,0,sizeof(*memory_info)); extent=count*quantum; memory_info->length=extent; memory_info->signature=MagickSignature; if (AcquireMagickResource(MemoryResource,extent) != MagickFalse) { memory_info->blob=AcquireAlignedMemory(1,extent); if (memory_info->blob != NULL) { memory_info->type=AlignedVirtualMemory; return(memory_info); } } RelinquishMagickResource(MemoryResource,extent); if (AcquireMagickResource(MapResource,extent) != MagickFalse) { /* Heap memory failed, try anonymous memory mapping. */ memory_info->blob=MapBlob(-1,IOMode,0,extent); if (memory_info->blob != NULL) { memory_info->type=MapVirtualMemory; return(memory_info); } if (AcquireMagickResource(DiskResource,extent) != MagickFalse) { int file; /* Anonymous memory mapping failed, try file-backed memory mapping. If the MapResource request failed, there is no point in trying file-backed memory mapping. */ file=AcquireUniqueFileResource(memory_info->filename); if (file != -1) { MagickOffsetType offset; offset=(MagickOffsetType) lseek(file,extent-1,SEEK_SET); if ((offset == (MagickOffsetType) (extent-1)) && (write(file,"",1) == 1)) { memory_info->blob=MapBlob(file,IOMode,0,extent); if (memory_info->blob != NULL) { (void) close(file); memory_info->type=MapVirtualMemory; return(memory_info); } } /* File-backed memory mapping failed, delete the temporary file. */ (void) close(file); (void) RelinquishUniqueFileResource(memory_info->filename); *memory_info->filename='\0'; } } RelinquishMagickResource(DiskResource,extent); } RelinquishMagickResource(MapResource,extent); if (memory_info->blob == NULL) { memory_info->blob=AcquireMagickMemory(extent); if (memory_info->blob != NULL) memory_info->type=UnalignedVirtualMemory; } if (memory_info->blob == NULL) memory_info=RelinquishVirtualMemory(memory_info); return(memory_info); }
168,544
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void nfs4_open_release(void *calldata) { struct nfs4_opendata *data = calldata; struct nfs4_state *state = NULL; /* If this request hasn't been cancelled, do nothing */ if (data->cancelled == 0) goto out_free; /* In case of error, no cleanup! */ if (data->rpc_status != 0 || !data->rpc_done) goto out_free; /* In case we need an open_confirm, no cleanup! */ if (data->o_res.rflags & NFS4_OPEN_RESULT_CONFIRM) goto out_free; state = nfs4_opendata_to_nfs4_state(data); if (!IS_ERR(state)) nfs4_close_state(&data->path, state, data->o_arg.open_flags); out_free: nfs4_opendata_put(data); } Commit Message: NFSv4: Convert the open and close ops to use fmode Signed-off-by: Trond Myklebust <Trond.Myklebust@netapp.com> CWE ID:
static void nfs4_open_release(void *calldata) { struct nfs4_opendata *data = calldata; struct nfs4_state *state = NULL; /* If this request hasn't been cancelled, do nothing */ if (data->cancelled == 0) goto out_free; /* In case of error, no cleanup! */ if (data->rpc_status != 0 || !data->rpc_done) goto out_free; /* In case we need an open_confirm, no cleanup! */ if (data->o_res.rflags & NFS4_OPEN_RESULT_CONFIRM) goto out_free; state = nfs4_opendata_to_nfs4_state(data); if (!IS_ERR(state)) nfs4_close_state(&data->path, state, data->o_arg.fmode); out_free: nfs4_opendata_put(data); }
165,698
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: http_rxchunk(struct http *hp) { char *q; int l, i; l = hp->prxbuf; do (void)http_rxchar(hp, 1, 0); while (hp->rxbuf[hp->prxbuf - 1] != '\n'); vtc_dump(hp->vl, 4, "len", hp->rxbuf + l, -1); i = strtoul(hp->rxbuf + l, &q, 16); bprintf(hp->chunklen, "%d", i); if ((q == hp->rxbuf + l) || (*q != '\0' && !vct_islws(*q))) { vtc_log(hp->vl, hp->fatal, "chunked fail %02x @ %d", *q, q - (hp->rxbuf + l)); } assert(q != hp->rxbuf + l); assert(*q == '\0' || vct_islws(*q)); hp->prxbuf = l; if (i > 0) { (void)http_rxchar(hp, i, 0); vtc_dump(hp->vl, 4, "chunk", hp->rxbuf + l, i); } l = hp->prxbuf; (void)http_rxchar(hp, 2, 0); if(!vct_iscrlf(hp->rxbuf[l])) vtc_log(hp->vl, hp->fatal, "Wrong chunk tail[0] = %02x", hp->rxbuf[l] & 0xff); if(!vct_iscrlf(hp->rxbuf[l + 1])) vtc_log(hp->vl, hp->fatal, "Wrong chunk tail[1] = %02x", hp->rxbuf[l + 1] & 0xff); hp->prxbuf = l; hp->rxbuf[l] = '\0'; return (i); } Commit Message: Do not consider a CR by itself as a valid line terminator Varnish (prior to version 4.0) was not following the standard with regard to line separator. Spotted and analyzed by: Régis Leroy [regilero] regis.leroy@makina-corpus.com CWE ID:
http_rxchunk(struct http *hp) { char *q; int l, i; l = hp->prxbuf; do (void)http_rxchar(hp, 1, 0); while (hp->rxbuf[hp->prxbuf - 1] != '\n'); vtc_dump(hp->vl, 4, "len", hp->rxbuf + l, -1); i = strtoul(hp->rxbuf + l, &q, 16); bprintf(hp->chunklen, "%d", i); if ((q == hp->rxbuf + l) || (*q != '\0' && !vct_islws(*q))) { vtc_log(hp->vl, hp->fatal, "chunked fail %02x @ %d", *q, q - (hp->rxbuf + l)); } assert(q != hp->rxbuf + l); assert(*q == '\0' || vct_islws(*q)); hp->prxbuf = l; if (i > 0) { (void)http_rxchar(hp, i, 0); vtc_dump(hp->vl, 4, "chunk", hp->rxbuf + l, i); } l = hp->prxbuf; (void)http_rxchar(hp, 2, 0); if(!vct_iscrlf(&hp->rxbuf[l])) vtc_log(hp->vl, hp->fatal, "Wrong chunk tail[0] = %02x", hp->rxbuf[l] & 0xff); if(!vct_iscrlf(&hp->rxbuf[l + 1])) vtc_log(hp->vl, hp->fatal, "Wrong chunk tail[1] = %02x", hp->rxbuf[l + 1] & 0xff); hp->prxbuf = l; hp->rxbuf[l] = '\0'; return (i); }
169,999
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: ExtensionTtsController::~ExtensionTtsController() { FinishCurrentUtterance(); ClearUtteranceQueue(); } Commit Message: Extend TTS extension API to support richer events returned from the engine to the client. Previously we just had a completed event; this adds start, word boundary, sentence boundary, and marker boundary. In addition, interrupted and canceled, which were previously errors, now become events. Mac and Windows implementations extended to support as many of these events as possible. BUG=67713 BUG=70198 BUG=75106 BUG=83404 TEST=Updates all TTS API tests to be event-based, and adds new tests. Review URL: http://codereview.chromium.org/6792014 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@91665 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
ExtensionTtsController::~ExtensionTtsController() {
170,396
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void OneClickSigninSyncStarter::UntrustedSigninConfirmed( StartSyncMode response) { if (response == UNDO_SYNC) { CancelSigninAndDelete(); } else { if (response == CONFIGURE_SYNC_FIRST) start_mode_ = response; SigninManager* signin = SigninManagerFactory::GetForProfile(profile_); signin->CompletePendingSignin(); } } Commit Message: Display confirmation dialog for untrusted signins BUG=252062 Review URL: https://chromiumcodereview.appspot.com/17482002 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@208520 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-200
void OneClickSigninSyncStarter::UntrustedSigninConfirmed( StartSyncMode response) { if (response == UNDO_SYNC) { CancelSigninAndDelete(); // If this was not an interstitial signin, (i.e. it was a SAML signin) // then the browser page is now blank and should redirect to the NTP. if (source_ != SyncPromoUI::SOURCE_UNKNOWN) { EnsureBrowser(); chrome::NavigateParams params(browser_, GURL(chrome::kChromeUINewTabURL), content::PAGE_TRANSITION_AUTO_TOPLEVEL); params.disposition = CURRENT_TAB; params.window_action = chrome::NavigateParams::SHOW_WINDOW; chrome::Navigate(&params); } } else { if (response == CONFIGURE_SYNC_FIRST) start_mode_ = response; SigninManager* signin = SigninManagerFactory::GetForProfile(profile_); signin->CompletePendingSignin(); } }
171,246
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: MagickExport MagickBooleanType SetQuantumDepth(const Image *image, QuantumInfo *quantum_info,const size_t depth) { size_t extent, quantum; /* Allocate the quantum pixel buffer. */ assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(quantum_info != (QuantumInfo *) NULL); assert(quantum_info->signature == MagickSignature); quantum_info->depth=depth; if (quantum_info->format == FloatingPointQuantumFormat) { if (quantum_info->depth > 32) quantum_info->depth=64; else if (quantum_info->depth > 16) quantum_info->depth=32; else quantum_info->depth=16; } if (quantum_info->pixels != (unsigned char **) NULL) DestroyQuantumPixels(quantum_info); quantum=(quantum_info->pad+6)*(quantum_info->depth+7)/8; extent=image->columns*quantum; if (quantum != (extent/image->columns)) return(MagickFalse); return(AcquireQuantumPixels(quantum_info,extent)); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/110 CWE ID: CWE-369
MagickExport MagickBooleanType SetQuantumDepth(const Image *image, QuantumInfo *quantum_info,const size_t depth) { size_t extent, quantum; /* Allocate the quantum pixel buffer. */ assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(quantum_info != (QuantumInfo *) NULL); assert(quantum_info->signature == MagickSignature); quantum_info->depth=depth; if (quantum_info->format == FloatingPointQuantumFormat) { if (quantum_info->depth > 32) quantum_info->depth=64; else if (quantum_info->depth > 16) quantum_info->depth=32; else quantum_info->depth=16; } if (quantum_info->pixels != (unsigned char **) NULL) DestroyQuantumPixels(quantum_info); quantum=(quantum_info->pad+6)*(quantum_info->depth+7)/8; extent=image->columns*quantum; if ((image->columns != 0) && (quantum != (extent/image->columns))) return(MagickFalse); return(AcquireQuantumPixels(quantum_info,extent)); }
170,113
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: cdf_check_stream_offset(const cdf_stream_t *sst, const cdf_header_t *h, const void *p, size_t tail, int line) { const char *b = (const char *)sst->sst_tab; const char *e = ((const char *)p) + tail; (void)&line; if (e >= b && (size_t)(e - b) <= CDF_SEC_SIZE(h) * sst->sst_len) return 0; DPRINTF(("%d: offset begin %p < end %p || %" SIZE_T_FORMAT "u" " > %" SIZE_T_FORMAT "u [%" SIZE_T_FORMAT "u %" SIZE_T_FORMAT "u]\n", line, b, e, (size_t)(e - b), CDF_SEC_SIZE(h) * sst->sst_len, CDF_SEC_SIZE(h), sst->sst_len)); errno = EFTYPE; return -1; } Commit Message: Use the proper sector size when checking stream offsets (Francisco Alonso and Jan Kaluza at RedHat) CWE ID: CWE-189
cdf_check_stream_offset(const cdf_stream_t *sst, const cdf_header_t *h, const void *p, size_t tail, int line) { const char *b = (const char *)sst->sst_tab; const char *e = ((const char *)p) + tail; size_t ss = sst->sst_dirlen < h->h_min_size_standard_stream ? CDF_SHORT_SEC_SIZE(h) : CDF_SEC_SIZE(h); (void)&line; if (e >= b && (size_t)(e - b) <= ss * sst->sst_len) return 0; DPRINTF(("%d: offset begin %p < end %p || %" SIZE_T_FORMAT "u" " > %" SIZE_T_FORMAT "u [%" SIZE_T_FORMAT "u %" SIZE_T_FORMAT "u]\n", line, b, e, (size_t)(e - b), ss * sst->sst_len, ss, sst->sst_len)); errno = EFTYPE; return -1; }
166,366
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void ChromeClientImpl::Focus() { if (web_view_->Client()) web_view_->Client()->DidFocus(); } Commit Message: If a page calls |window.focus()|, kick it out of fullscreen. BUG=776418, 800056 Change-Id: I1880fe600e4814c073f247c43b1c1ac80c8fc017 Reviewed-on: https://chromium-review.googlesource.com/852378 Reviewed-by: Nasko Oskov <nasko@chromium.org> Reviewed-by: Philip Jägenstedt <foolip@chromium.org> Commit-Queue: Avi Drissman <avi@chromium.org> Cr-Commit-Position: refs/heads/master@{#533790} CWE ID:
void ChromeClientImpl::Focus() { void ChromeClientImpl::Focus(LocalFrame* calling_frame) { if (web_view_->Client()) { web_view_->Client()->DidFocus( calling_frame ? WebLocalFrameImpl::FromFrame(calling_frame) : nullptr); } }
172,724
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool ChangeInputMethodViaIBus(const std::string& input_method_id) { if (!initialized_successfully_) return false; std::string input_method_id_to_switch = input_method_id; if (!InputMethodIsActivated(input_method_id)) { scoped_ptr<InputMethodDescriptors> input_methods(GetActiveInputMethods()); DCHECK(!input_methods->empty()); if (!input_methods->empty()) { input_method_id_to_switch = input_methods->at(0).id; LOG(INFO) << "Can't change the current input method to " << input_method_id << " since the engine is not preloaded. " << "Switch to " << input_method_id_to_switch << " instead."; } } if (chromeos::ChangeInputMethod(input_method_status_connection_, input_method_id_to_switch.c_str())) { return true; } LOG(ERROR) << "Can't switch input method to " << input_method_id_to_switch; return false; } Commit Message: Remove use of libcros from InputMethodLibrary. BUG=chromium-os:16238 TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before. Review URL: http://codereview.chromium.org/7003086 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
bool ChangeInputMethodViaIBus(const std::string& input_method_id) { if (!initialized_successfully_) return false; std::string input_method_id_to_switch = input_method_id; if (!InputMethodIsActivated(input_method_id)) { scoped_ptr<input_method::InputMethodDescriptors> input_methods( GetActiveInputMethods()); DCHECK(!input_methods->empty()); if (!input_methods->empty()) { input_method_id_to_switch = input_methods->at(0).id; LOG(INFO) << "Can't change the current input method to " << input_method_id << " since the engine is not preloaded. " << "Switch to " << input_method_id_to_switch << " instead."; } } if (ibus_controller_->ChangeInputMethod(input_method_id_to_switch)) { return true; } LOG(ERROR) << "Can't switch input method to " << input_method_id_to_switch; return false; }
170,481
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: check_compat_entry_size_and_hooks(struct compat_ip6t_entry *e, struct xt_table_info *newinfo, unsigned int *size, const unsigned char *base, const unsigned char *limit, const unsigned int *hook_entries, const unsigned int *underflows, const char *name) { struct xt_entry_match *ematch; struct xt_entry_target *t; struct xt_target *target; unsigned int entry_offset; unsigned int j; int ret, off, h; duprintf("check_compat_entry_size_and_hooks %p\n", e); if ((unsigned long)e % __alignof__(struct compat_ip6t_entry) != 0 || (unsigned char *)e + sizeof(struct compat_ip6t_entry) >= limit || (unsigned char *)e + e->next_offset > limit) { duprintf("Bad offset %p, limit = %p\n", e, limit); return -EINVAL; } if (e->next_offset < sizeof(struct compat_ip6t_entry) + sizeof(struct compat_xt_entry_target)) { duprintf("checking: element %p size %u\n", e, e->next_offset); return -EINVAL; } if (!ip6_checkentry(&e->ipv6)) return -EINVAL; ret = xt_compat_check_entry_offsets(e, e->target_offset, e->next_offset); if (ret) return ret; off = sizeof(struct ip6t_entry) - sizeof(struct compat_ip6t_entry); entry_offset = (void *)e - (void *)base; j = 0; xt_ematch_foreach(ematch, e) { ret = compat_find_calc_match(ematch, name, &e->ipv6, &off); if (ret != 0) goto release_matches; ++j; } t = compat_ip6t_get_target(e); target = xt_request_find_target(NFPROTO_IPV6, t->u.user.name, t->u.user.revision); if (IS_ERR(target)) { duprintf("check_compat_entry_size_and_hooks: `%s' not found\n", t->u.user.name); ret = PTR_ERR(target); goto release_matches; } t->u.kernel.target = target; off += xt_compat_target_offset(target); *size += off; ret = xt_compat_add_offset(AF_INET6, entry_offset, off); if (ret) goto out; /* Check hooks & underflows */ for (h = 0; h < NF_INET_NUMHOOKS; h++) { if ((unsigned char *)e - base == hook_entries[h]) newinfo->hook_entry[h] = hook_entries[h]; if ((unsigned char *)e - base == underflows[h]) newinfo->underflow[h] = underflows[h]; } /* Clear counters and comefrom */ memset(&e->counters, 0, sizeof(e->counters)); e->comefrom = 0; return 0; out: module_put(t->u.kernel.target->me); release_matches: xt_ematch_foreach(ematch, e) { if (j-- == 0) break; module_put(ematch->u.kernel.match->me); } return ret; } Commit Message: netfilter: x_tables: check for bogus target offset We're currently asserting that targetoff + targetsize <= nextoff. Extend it to also check that targetoff is >= sizeof(xt_entry). Since this is generic code, add an argument pointing to the start of the match/target, we can then derive the base structure size from the delta. We also need the e->elems pointer in a followup change to validate matches. Signed-off-by: Florian Westphal <fw@strlen.de> Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org> CWE ID: CWE-264
check_compat_entry_size_and_hooks(struct compat_ip6t_entry *e, struct xt_table_info *newinfo, unsigned int *size, const unsigned char *base, const unsigned char *limit, const unsigned int *hook_entries, const unsigned int *underflows, const char *name) { struct xt_entry_match *ematch; struct xt_entry_target *t; struct xt_target *target; unsigned int entry_offset; unsigned int j; int ret, off, h; duprintf("check_compat_entry_size_and_hooks %p\n", e); if ((unsigned long)e % __alignof__(struct compat_ip6t_entry) != 0 || (unsigned char *)e + sizeof(struct compat_ip6t_entry) >= limit || (unsigned char *)e + e->next_offset > limit) { duprintf("Bad offset %p, limit = %p\n", e, limit); return -EINVAL; } if (e->next_offset < sizeof(struct compat_ip6t_entry) + sizeof(struct compat_xt_entry_target)) { duprintf("checking: element %p size %u\n", e, e->next_offset); return -EINVAL; } if (!ip6_checkentry(&e->ipv6)) return -EINVAL; ret = xt_compat_check_entry_offsets(e, e->elems, e->target_offset, e->next_offset); if (ret) return ret; off = sizeof(struct ip6t_entry) - sizeof(struct compat_ip6t_entry); entry_offset = (void *)e - (void *)base; j = 0; xt_ematch_foreach(ematch, e) { ret = compat_find_calc_match(ematch, name, &e->ipv6, &off); if (ret != 0) goto release_matches; ++j; } t = compat_ip6t_get_target(e); target = xt_request_find_target(NFPROTO_IPV6, t->u.user.name, t->u.user.revision); if (IS_ERR(target)) { duprintf("check_compat_entry_size_and_hooks: `%s' not found\n", t->u.user.name); ret = PTR_ERR(target); goto release_matches; } t->u.kernel.target = target; off += xt_compat_target_offset(target); *size += off; ret = xt_compat_add_offset(AF_INET6, entry_offset, off); if (ret) goto out; /* Check hooks & underflows */ for (h = 0; h < NF_INET_NUMHOOKS; h++) { if ((unsigned char *)e - base == hook_entries[h]) newinfo->hook_entry[h] = hook_entries[h]; if ((unsigned char *)e - base == underflows[h]) newinfo->underflow[h] = underflows[h]; } /* Clear counters and comefrom */ memset(&e->counters, 0, sizeof(e->counters)); e->comefrom = 0; return 0; out: module_put(t->u.kernel.target->me); release_matches: xt_ematch_foreach(ematch, e) { if (j-- == 0) break; module_put(ematch->u.kernel.match->me); } return ret; }
167,219
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static PassRefPtrWillBeRawPtr<CreateFileResult> create() { return adoptRefWillBeNoop(new CreateFileResult()); } Commit Message: Oilpan: Ship Oilpan for SyncCallbackHelper, CreateFileResult and CallbackWrapper in filesystem/ These are leftovers when we shipped Oilpan for filesystem/ once. BUG=340522 Review URL: https://codereview.chromium.org/501263003 git-svn-id: svn://svn.chromium.org/blink/trunk@180909 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-119
static PassRefPtrWillBeRawPtr<CreateFileResult> create() static CreateFileResult* create() { return new CreateFileResult(); }
171,413
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool FrameworkListener::onDataAvailable(SocketClient *c) { char buffer[CMD_BUF_SIZE]; int len; len = TEMP_FAILURE_RETRY(read(c->getSocket(), buffer, sizeof(buffer))); if (len < 0) { SLOGE("read() failed (%s)", strerror(errno)); return false; } else if (!len) return false; if(buffer[len-1] != '\0') SLOGW("String is not zero-terminated"); int offset = 0; int i; for (i = 0; i < len; i++) { if (buffer[i] == '\0') { /* IMPORTANT: dispatchCommand() expects a zero-terminated string */ dispatchCommand(c, buffer + offset); offset = i + 1; } } return true; } Commit Message: Fix vold vulnerability in FrameworkListener Modify FrameworkListener to ignore commands that exceed the maximum buffer length and send an error message. Bug: 29831647 Change-Id: I9e57d1648d55af2ca0191bb47868e375ecc26950 Signed-off-by: Connor O'Brien <connoro@google.com> (cherry picked from commit baa126dc158a40bc83c17c6d428c760e5b93fb1a) (cherry picked from commit 470484d2a25ad432190a01d1c763b4b36db33c7e) CWE ID: CWE-264
bool FrameworkListener::onDataAvailable(SocketClient *c) { char buffer[CMD_BUF_SIZE]; int len; len = TEMP_FAILURE_RETRY(read(c->getSocket(), buffer, sizeof(buffer))); if (len < 0) { SLOGE("read() failed (%s)", strerror(errno)); return false; } else if (!len) { return false; } else if (buffer[len-1] != '\0') { SLOGW("String is not zero-terminated"); android_errorWriteLog(0x534e4554, "29831647"); c->sendMsg(500, "Command too large for buffer", false); mSkipToNextNullByte = true; return false; } int offset = 0; int i; for (i = 0; i < len; i++) { if (buffer[i] == '\0') { /* IMPORTANT: dispatchCommand() expects a zero-terminated string */ if (mSkipToNextNullByte) { mSkipToNextNullByte = false; } else { dispatchCommand(c, buffer + offset); } offset = i + 1; } } mSkipToNextNullByte = false; return true; }
173,391
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: Response ServiceWorkerHandler::DeliverPushMessage( const std::string& origin, const std::string& registration_id, const std::string& data) { if (!enabled_) return CreateDomainNotEnabledErrorResponse(); if (!process_) return CreateContextErrorResponse(); int64_t id = 0; if (!base::StringToInt64(registration_id, &id)) return CreateInvalidVersionIdErrorResponse(); PushEventPayload payload; if (data.size() > 0) payload.setData(data); BrowserContext::DeliverPushMessage(process_->GetBrowserContext(), GURL(origin), id, payload, base::Bind(&PushDeliveryNoOp)); return Response::OK(); } Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable This keeps BrowserContext* and StoragePartition* instead of RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost upon closure of DevTools front-end. Bug: 801117, 783067, 780694 Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b Reviewed-on: https://chromium-review.googlesource.com/876657 Commit-Queue: Andrey Kosyakov <caseq@chromium.org> Reviewed-by: Dmitry Gozman <dgozman@chromium.org> Cr-Commit-Position: refs/heads/master@{#531157} CWE ID: CWE-20
Response ServiceWorkerHandler::DeliverPushMessage( const std::string& origin, const std::string& registration_id, const std::string& data) { if (!enabled_) return CreateDomainNotEnabledErrorResponse(); if (!browser_context_) return CreateContextErrorResponse(); int64_t id = 0; if (!base::StringToInt64(registration_id, &id)) return CreateInvalidVersionIdErrorResponse(); PushEventPayload payload; if (data.size() > 0) payload.setData(data); BrowserContext::DeliverPushMessage( browser_context_, GURL(origin), id, payload, base::BindRepeating([](mojom::PushDeliveryStatus status) {})); return Response::OK(); }
172,766
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: unsigned long Tracks::GetTracksCount() const { const ptrdiff_t result = m_trackEntriesEnd - m_trackEntries; assert(result >= 0); return static_cast<unsigned long>(result); } 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
unsigned long Tracks::GetTracksCount() const
174,374
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: ParseNameValue(const char * buffer, int bufsize, struct NameValueParserData * data) { struct xmlparser parser; data->l_head = NULL; data->portListing = NULL; data->portListingLength = 0; /* init xmlparser object */ parser.xmlstart = buffer; parser.xmlsize = bufsize; parser.data = data; parser.starteltfunc = NameValueParserStartElt; parser.endeltfunc = NameValueParserEndElt; parser.datafunc = NameValueParserGetData; parser.attfunc = 0; parsexml(&parser); } Commit Message: properly initialize data structure for SOAP parsing in ParseNameValue() topelt field was not properly initialized. should fix #268 CWE ID: CWE-119
ParseNameValue(const char * buffer, int bufsize, struct NameValueParserData * data) { struct xmlparser parser; memset(data, 0, sizeof(struct NameValueParserData)); /* init xmlparser object */ parser.xmlstart = buffer; parser.xmlsize = bufsize; parser.data = data; parser.starteltfunc = NameValueParserStartElt; parser.endeltfunc = NameValueParserEndElt; parser.datafunc = NameValueParserGetData; parser.attfunc = 0; parsexml(&parser); }
169,368
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int wddx_stack_destroy(wddx_stack *stack) { register int i; if (stack->elements) { for (i = 0; i < stack->top; i++) { if (((st_entry *)stack->elements[i])->data) { zval_ptr_dtor(&((st_entry *)stack->elements[i])->data); } if (((st_entry *)stack->elements[i])->varname) { efree(((st_entry *)stack->elements[i])->varname); } efree(stack->elements[i]); } efree(stack->elements); } return SUCCESS; } Commit Message: Fix bug #72860: wddx_deserialize use-after-free CWE ID: CWE-416
static int wddx_stack_destroy(wddx_stack *stack) { register int i; if (stack->elements) { for (i = 0; i < stack->top; i++) { if (((st_entry *)stack->elements[i])->data && ((st_entry *)stack->elements[i])->type != ST_FIELD) { zval_ptr_dtor(&((st_entry *)stack->elements[i])->data); } if (((st_entry *)stack->elements[i])->varname) { efree(((st_entry *)stack->elements[i])->varname); } efree(stack->elements[i]); } efree(stack->elements); } return SUCCESS; }
166,936
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void AppCacheHost::SelectCacheForSharedWorker(int64 appcache_id) { DCHECK(pending_start_update_callback_.is_null() && pending_swap_cache_callback_.is_null() && pending_get_status_callback_.is_null() && !is_selection_pending() && !was_select_cache_called_); was_select_cache_called_ = true; if (appcache_id != kAppCacheNoCacheId) { LoadSelectedCache(appcache_id); return; } FinishCacheSelection(NULL, NULL); } Commit Message: Fix possible map::end() dereference in AppCacheUpdateJob triggered by a compromised renderer. BUG=551044 Review URL: https://codereview.chromium.org/1418783005 Cr-Commit-Position: refs/heads/master@{#358815} CWE ID:
void AppCacheHost::SelectCacheForSharedWorker(int64 appcache_id) { bool AppCacheHost::SelectCacheForSharedWorker(int64 appcache_id) { if (was_select_cache_called_) return false; DCHECK(pending_start_update_callback_.is_null() && pending_swap_cache_callback_.is_null() && pending_get_status_callback_.is_null() && !is_selection_pending()); was_select_cache_called_ = true; if (appcache_id != kAppCacheNoCacheId) { LoadSelectedCache(appcache_id); return true; } FinishCacheSelection(NULL, NULL); return true; }
171,741
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void FaviconWebUIHandler::HandleGetFaviconDominantColor(const ListValue* args) { std::string path; CHECK(args->GetString(0, &path)); DCHECK(StartsWithASCII(path, "chrome://favicon/", false)) << "path is " << path; path = path.substr(arraysize("chrome://favicon/") - 1); double id; CHECK(args->GetDouble(1, &id)); FaviconService* favicon_service = web_ui_->GetProfile()->GetFaviconService(Profile::EXPLICIT_ACCESS); if (!favicon_service || path.empty()) return; FaviconService::Handle handle = favicon_service->GetFaviconForURL( GURL(path), history::FAVICON, &consumer_, NewCallback(this, &FaviconWebUIHandler::OnFaviconDataAvailable)); consumer_.SetClientData(favicon_service, handle, static_cast<int>(id)); } Commit Message: ntp4: show larger favicons in most visited page extend favicon source to provide larger icons. For now, larger means at most 32x32. Also, the only icon we actually support at this resolution is the default (globe). BUG=none TEST=manual Review URL: http://codereview.chromium.org/7300017 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@91517 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
void FaviconWebUIHandler::HandleGetFaviconDominantColor(const ListValue* args) { std::string path; CHECK(args->GetString(0, &path)); DCHECK(StartsWithASCII(path, "chrome://favicon/size/32/", false)) << "path is " << path; path = path.substr(arraysize("chrome://favicon/size/32/") - 1); double id; CHECK(args->GetDouble(1, &id)); FaviconService* favicon_service = web_ui_->GetProfile()->GetFaviconService(Profile::EXPLICIT_ACCESS); if (!favicon_service || path.empty()) return; FaviconService::Handle handle = favicon_service->GetFaviconForURL( GURL(path), history::FAVICON, &consumer_, NewCallback(this, &FaviconWebUIHandler::OnFaviconDataAvailable)); consumer_.SetClientData(favicon_service, handle, static_cast<int>(id)); }
170,369
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: OMX_ERRORTYPE SoftOpus::internalGetParameter( OMX_INDEXTYPE index, OMX_PTR params) { switch ((int)index) { case OMX_IndexParamAudioAndroidOpus: { OMX_AUDIO_PARAM_ANDROID_OPUSTYPE *opusParams = (OMX_AUDIO_PARAM_ANDROID_OPUSTYPE *)params; if (opusParams->nPortIndex != 0) { return OMX_ErrorUndefined; } opusParams->nAudioBandWidth = 0; opusParams->nSampleRate = kRate; opusParams->nBitRate = 0; if (!isConfigured()) { opusParams->nChannels = 1; } else { opusParams->nChannels = mHeader->channels; } return OMX_ErrorNone; } case OMX_IndexParamAudioPcm: { OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams = (OMX_AUDIO_PARAM_PCMMODETYPE *)params; if (pcmParams->nPortIndex != 1) { return OMX_ErrorUndefined; } pcmParams->eNumData = OMX_NumericalDataSigned; pcmParams->eEndian = OMX_EndianBig; pcmParams->bInterleaved = OMX_TRUE; pcmParams->nBitPerSample = 16; pcmParams->ePCMMode = OMX_AUDIO_PCMModeLinear; pcmParams->eChannelMapping[0] = OMX_AUDIO_ChannelLF; pcmParams->eChannelMapping[1] = OMX_AUDIO_ChannelRF; pcmParams->nSamplingRate = kRate; if (!isConfigured()) { pcmParams->nChannels = 1; } else { pcmParams->nChannels = mHeader->channels; } return OMX_ErrorNone; } default: return SimpleSoftOMXComponent::internalGetParameter(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::internalGetParameter( OMX_INDEXTYPE index, OMX_PTR params) { switch ((int)index) { case OMX_IndexParamAudioAndroidOpus: { OMX_AUDIO_PARAM_ANDROID_OPUSTYPE *opusParams = (OMX_AUDIO_PARAM_ANDROID_OPUSTYPE *)params; if (!isValidOMXParam(opusParams)) { return OMX_ErrorBadParameter; } if (opusParams->nPortIndex != 0) { return OMX_ErrorUndefined; } opusParams->nAudioBandWidth = 0; opusParams->nSampleRate = kRate; opusParams->nBitRate = 0; if (!isConfigured()) { opusParams->nChannels = 1; } else { opusParams->nChannels = mHeader->channels; } return OMX_ErrorNone; } case OMX_IndexParamAudioPcm: { OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams = (OMX_AUDIO_PARAM_PCMMODETYPE *)params; if (!isValidOMXParam(pcmParams)) { return OMX_ErrorBadParameter; } if (pcmParams->nPortIndex != 1) { return OMX_ErrorUndefined; } pcmParams->eNumData = OMX_NumericalDataSigned; pcmParams->eEndian = OMX_EndianBig; pcmParams->bInterleaved = OMX_TRUE; pcmParams->nBitPerSample = 16; pcmParams->ePCMMode = OMX_AUDIO_PCMModeLinear; pcmParams->eChannelMapping[0] = OMX_AUDIO_ChannelLF; pcmParams->eChannelMapping[1] = OMX_AUDIO_ChannelRF; pcmParams->nSamplingRate = kRate; if (!isConfigured()) { pcmParams->nChannels = 1; } else { pcmParams->nChannels = mHeader->channels; } return OMX_ErrorNone; } default: return SimpleSoftOMXComponent::internalGetParameter(index, params); } }
174,216
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool DebuggerFunction::InitTabContents() { Value* debuggee; EXTENSION_FUNCTION_VALIDATE(args_->Get(0, &debuggee)); DictionaryValue* dict = static_cast<DictionaryValue*>(debuggee); EXTENSION_FUNCTION_VALIDATE(dict->GetInteger(keys::kTabIdKey, &tab_id_)); contents_ = NULL; TabContentsWrapper* wrapper = NULL; bool result = ExtensionTabUtil::GetTabById( tab_id_, profile(), include_incognito(), NULL, NULL, &wrapper, NULL); if (!result || !wrapper) { error_ = ExtensionErrorUtils::FormatErrorMessage( keys::kNoTabError, base::IntToString(tab_id_)); return false; } contents_ = wrapper->web_contents(); if (ChromeWebUIControllerFactory::GetInstance()->HasWebUIScheme( contents_->GetURL())) { error_ = ExtensionErrorUtils::FormatErrorMessage( keys::kAttachToWebUIError, contents_->GetURL().scheme()); return false; } return true; } Commit Message: Allow browser to handle all WebUI navigations. BUG=113496 TEST="Google Dashboard" link in Sync settings loads in new process. Review URL: http://codereview.chromium.org/9663045 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@126949 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264
bool DebuggerFunction::InitTabContents() { Value* debuggee; EXTENSION_FUNCTION_VALIDATE(args_->Get(0, &debuggee)); DictionaryValue* dict = static_cast<DictionaryValue*>(debuggee); EXTENSION_FUNCTION_VALIDATE(dict->GetInteger(keys::kTabIdKey, &tab_id_)); contents_ = NULL; TabContentsWrapper* wrapper = NULL; bool result = ExtensionTabUtil::GetTabById( tab_id_, profile(), include_incognito(), NULL, NULL, &wrapper, NULL); if (!result || !wrapper) { error_ = ExtensionErrorUtils::FormatErrorMessage( keys::kNoTabError, base::IntToString(tab_id_)); return false; } contents_ = wrapper->web_contents(); if (content::GetContentClient()->HasWebUIScheme( contents_->GetURL())) { error_ = ExtensionErrorUtils::FormatErrorMessage( keys::kAttachToWebUIError, contents_->GetURL().scheme()); return false; } return true; }
171,006
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: MagickExport MagickBooleanType SetQuantumDepth(const Image *image, QuantumInfo *quantum_info,const size_t depth) { size_t extent, quantum; /* Allocate the quantum pixel buffer. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(quantum_info != (QuantumInfo *) NULL); assert(quantum_info->signature == MagickCoreSignature); quantum_info->depth=depth; if (quantum_info->format == FloatingPointQuantumFormat) { if (quantum_info->depth > 32) quantum_info->depth=64; else if (quantum_info->depth > 16) quantum_info->depth=32; else quantum_info->depth=16; } if (quantum_info->pixels != (unsigned char **) NULL) DestroyQuantumPixels(quantum_info); quantum=(quantum_info->pad+6)*(quantum_info->depth+7)/8; extent=image->columns*quantum; if ((image->columns != 0) && (quantum != (extent/image->columns))) return(MagickFalse); return(AcquireQuantumPixels(quantum_info,extent)); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/105 CWE ID: CWE-369
MagickExport MagickBooleanType SetQuantumDepth(const Image *image, QuantumInfo *quantum_info,const size_t depth) { size_t extent, quantum; /* Allocate the quantum pixel buffer. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(quantum_info != (QuantumInfo *) NULL); assert(quantum_info->signature == MagickCoreSignature); quantum_info->depth=depth; if (quantum_info->format == FloatingPointQuantumFormat) { if (quantum_info->depth > 32) quantum_info->depth=64; else if (quantum_info->depth > 16) quantum_info->depth=32; else quantum_info->depth=16; } if (quantum_info->pixels != (unsigned char **) NULL) DestroyQuantumPixels(quantum_info); quantum=(quantum_info->pad+6)*(quantum_info->depth+7)/8; extent=MagickMax(image->columns,image->rows)*quantum; if ((MagickMax(image->columns,image->rows) != 0) && (quantum != (extent/MagickMax(image->columns,image->rows)))) return(MagickFalse); return(AcquireQuantumPixels(quantum_info,extent)); }
168,799
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: long FS_FOpenFileRead(const char *filename, fileHandle_t *file, qboolean uniqueFILE) { searchpath_t *search; long len; if(!fs_searchpaths) Com_Error(ERR_FATAL, "Filesystem call made without initialization"); for(search = fs_searchpaths; search; search = search->next) { len = FS_FOpenFileReadDir(filename, search, file, uniqueFILE, qfalse); if(file == NULL) { if(len > 0) return len; } else { if(len >= 0 && *file) return len; } } #ifdef FS_MISSING if(missingFiles) fprintf(missingFiles, "%s\n", filename); #endif if(file) { *file = 0; return -1; } else { return 0; } } Commit Message: All: Don't load .pk3s as .dlls, and don't load user config files from .pk3s CWE ID: CWE-269
long FS_FOpenFileRead(const char *filename, fileHandle_t *file, qboolean uniqueFILE) { searchpath_t *search; long len; qboolean isLocalConfig; if(!fs_searchpaths) Com_Error(ERR_FATAL, "Filesystem call made without initialization"); isLocalConfig = !strcmp(filename, "autoexec.cfg") || !strcmp(filename, Q3CONFIG_CFG); for(search = fs_searchpaths; search; search = search->next) { // autoexec.cfg and wolfconfig_mp.cfg can only be loaded outside of pk3 files. if (isLocalConfig && search->pack) continue; len = FS_FOpenFileReadDir(filename, search, file, uniqueFILE, qfalse); if(file == NULL) { if(len > 0) return len; } else { if(len >= 0 && *file) return len; } } #ifdef FS_MISSING if(missingFiles) fprintf(missingFiles, "%s\n", filename); #endif if(file) { *file = 0; return -1; } else { return 0; } }
170,083
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: std::string TestFlashMessageLoop::TestBasics() { message_loop_ = new pp::flash::MessageLoop(instance_); pp::CompletionCallback callback = callback_factory_.NewCallback( &TestFlashMessageLoop::QuitMessageLoopTask); pp::Module::Get()->core()->CallOnMainThread(0, callback); int32_t result = message_loop_->Run(); ASSERT_TRUE(message_loop_); delete message_loop_; message_loop_ = NULL; ASSERT_EQ(PP_OK, result); PASS(); } Commit Message: Fix PPB_Flash_MessageLoop. This CL suspends script callbacks and resource loads while running nested message loop using PPB_Flash_MessageLoop. BUG=569496 Review URL: https://codereview.chromium.org/1559113002 Cr-Commit-Position: refs/heads/master@{#374529} CWE ID: CWE-264
std::string TestFlashMessageLoop::TestBasics() { message_loop_ = new pp::flash::MessageLoop(instance_); pp::CompletionCallback callback = callback_factory_.NewCallback( &TestFlashMessageLoop::QuitMessageLoopTask); pp::Module::Get()->core()->CallOnMainThread(0, callback); int32_t result = message_loop_->Run(); ASSERT_TRUE(message_loop_); delete message_loop_; message_loop_ = nullptr; ASSERT_EQ(PP_OK, result); PASS(); }
172,126
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: __be32 ipv6_select_ident(struct net *net, const struct in6_addr *daddr, const struct in6_addr *saddr) { static u32 ip6_idents_hashrnd __read_mostly; u32 id; net_get_random_once(&ip6_idents_hashrnd, sizeof(ip6_idents_hashrnd)); id = __ipv6_select_ident(net, ip6_idents_hashrnd, daddr, saddr); return htonl(id); } Commit Message: inet: switch IP ID generator to siphash According to Amit Klein and Benny Pinkas, IP ID generation is too weak and might be used by attackers. Even with recent net_hash_mix() fix (netns: provide pure entropy for net_hash_mix()) having 64bit key and Jenkins hash is risky. It is time to switch to siphash and its 128bit keys. Signed-off-by: Eric Dumazet <edumazet@google.com> Reported-by: Amit Klein <aksecurity@gmail.com> Reported-by: Benny Pinkas <benny@pinkas.net> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID: CWE-200
__be32 ipv6_select_ident(struct net *net, const struct in6_addr *daddr, const struct in6_addr *saddr) { u32 id; id = __ipv6_select_ident(net, daddr, saddr); return htonl(id); }
169,719
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: const BlockEntry* Segment::GetBlock( const CuePoint& cp, const CuePoint::TrackPosition& tp) { Cluster** const ii = m_clusters; Cluster** i = ii; const long count = m_clusterCount + m_clusterPreloadCount; Cluster** const jj = ii + count; Cluster** j = jj; while (i < j) { Cluster** const k = i + (j - i) / 2; assert(k < jj); Cluster* const pCluster = *k; assert(pCluster); const long long pos = pCluster->GetPosition(); assert(pos >= 0); if (pos < tp.m_pos) i = k + 1; else if (pos > tp.m_pos) j = k; else return pCluster->GetEntry(cp, tp); } assert(i == j); Cluster* const pCluster = Cluster::Create(this, -1, tp.m_pos); //, -1); assert(pCluster); const ptrdiff_t idx = i - m_clusters; PreloadCluster(pCluster, idx); assert(m_clusters); assert(m_clusterPreloadCount > 0); assert(m_clusters[idx] == pCluster); return pCluster->GetEntry(cp, tp); } 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 BlockEntry* Segment::GetBlock( const long count = m_clusterCount + m_clusterPreloadCount; Cluster** const jj = ii + count; Cluster** j = jj; while (i < j) { // INVARIANT: //[ii, i) < pTP->m_pos //[i, j) ? //[j, jj) > pTP->m_pos Cluster** const k = i + (j - i) / 2; assert(k < jj); Cluster* const pCluster = *k; assert(pCluster); // const long long pos_ = pCluster->m_pos; // assert(pos_); // const long long pos = pos_ * ((pos_ < 0) ? -1 : 1); const long long pos = pCluster->GetPosition(); assert(pos >= 0); if (pos < tp.m_pos) i = k + 1; else if (pos > tp.m_pos) j = k; else return pCluster->GetEntry(cp, tp); } assert(i == j); // assert(Cluster::HasBlockEntries(this, tp.m_pos)); Cluster* const pCluster = Cluster::Create(this, -1, tp.m_pos); //, -1); assert(pCluster); const ptrdiff_t idx = i - m_clusters; PreloadCluster(pCluster, idx); assert(m_clusters); assert(m_clusterPreloadCount > 0); assert(m_clusters[idx] == pCluster); return pCluster->GetEntry(cp, tp); }
174,288
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int skcipher_setkey(void *private, const u8 *key, unsigned int keylen) { return crypto_skcipher_setkey(private, key, keylen); } Commit Message: crypto: algif_skcipher - Require setkey before accept(2) Some cipher implementations will crash if you try to use them without calling setkey first. This patch adds a check so that the accept(2) call will fail with -ENOKEY if setkey hasn't been done on the socket yet. Cc: stable@vger.kernel.org Reported-by: Dmitry Vyukov <dvyukov@google.com> Signed-off-by: Herbert Xu <herbert@gondor.apana.org.au> Tested-by: Dmitry Vyukov <dvyukov@google.com> CWE ID: CWE-476
static int skcipher_setkey(void *private, const u8 *key, unsigned int keylen) { struct skcipher_tfm *tfm = private; int err; err = crypto_skcipher_setkey(tfm->skcipher, key, keylen); tfm->has_key = !err; return err; }
167,457
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: DWORD WtsSessionProcessDelegate::Core::GetExitCode() { DCHECK(main_task_runner_->BelongsToCurrentThread()); DWORD exit_code = CONTROL_C_EXIT; if (worker_process_.IsValid()) { if (!::GetExitCodeProcess(worker_process_, &exit_code)) { LOG_GETLASTERROR(INFO) << "Failed to query the exit code of the worker process"; exit_code = CONTROL_C_EXIT; } } return exit_code; } Commit Message: Validate and report peer's PID to WorkerProcessIpcDelegate so it will be able to duplicate handles to and from the worker process. As a side effect WorkerProcessLauncher::Delegate is now responsible for retrieving the client's PID and deciding whether a launch failed due to a permanent error condition. BUG=134694 Review URL: https://chromiumcodereview.appspot.com/11143025 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@162778 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
DWORD WtsSessionProcessDelegate::Core::GetExitCode() { DWORD WtsSessionProcessDelegate::Core::GetProcessId() const { DWORD pid = 0; if (pipe_.IsValid() && get_named_pipe_client_pid_(pipe_, &pid)) { return pid; } else { return 0; } } bool WtsSessionProcessDelegate::Core::IsPermanentError( int failure_count) const { // Get exit code of the worker process if it is available. DWORD exit_code = CONTROL_C_EXIT; if (worker_process_.IsValid()) { if (!::GetExitCodeProcess(worker_process_, &exit_code)) { LOG_GETLASTERROR(INFO) << "Failed to query the exit code of the worker process"; exit_code = CONTROL_C_EXIT; } } // Stop trying to restart the worker process if it exited due to // misconfiguration. return (kMinPermanentErrorExitCode <= exit_code && exit_code <= kMaxPermanentErrorExitCode); }
171,556
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: jbig2_end_of_stripe(Jbig2Ctx *ctx, Jbig2Segment *segment, const uint8_t *segment_data) { Jbig2Page page = ctx->pages[ctx->current_page]; int end_row; end_row = jbig2_get_int32(segment_data); if (end_row < page.end_row) { jbig2_error(ctx, JBIG2_SEVERITY_WARNING, segment->number, "end of stripe segment with non-positive end row advance" " (new end row %d vs current end row %d)", end_row, page.end_row); } else { jbig2_error(ctx, JBIG2_SEVERITY_INFO, segment->number, "end of stripe: advancing end row to %d", end_row); } page.end_row = end_row; return 0; } Commit Message: CWE ID: CWE-119
jbig2_end_of_stripe(Jbig2Ctx *ctx, Jbig2Segment *segment, const uint8_t *segment_data) { Jbig2Page page = ctx->pages[ctx->current_page]; uint32_t end_row; end_row = jbig2_get_uint32(segment_data); if (end_row < page.end_row) { jbig2_error(ctx, JBIG2_SEVERITY_WARNING, segment->number, "end of stripe segment with non-positive end row advance" " (new end row %d vs current end row %d)", end_row, page.end_row); } else { jbig2_error(ctx, JBIG2_SEVERITY_INFO, segment->number, "end of stripe: advancing end row to %d", end_row); } page.end_row = end_row; return 0; }
165,495
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void InspectorNetworkAgent::DidReceiveResourceResponse( unsigned long identifier, DocumentLoader* loader, const ResourceResponse& response, Resource* cached_resource) { String request_id = IdentifiersFactory::RequestId(identifier); bool is_not_modified = response.HttpStatusCode() == 304; bool resource_is_empty = true; std::unique_ptr<protocol::Network::Response> resource_response = BuildObjectForResourceResponse(response, cached_resource, &resource_is_empty); InspectorPageAgent::ResourceType type = cached_resource ? InspectorPageAgent::CachedResourceType(*cached_resource) : InspectorPageAgent::kOtherResource; InspectorPageAgent::ResourceType saved_type = resources_data_->GetResourceType(request_id); if (saved_type == InspectorPageAgent::kScriptResource || saved_type == InspectorPageAgent::kXHRResource || saved_type == InspectorPageAgent::kDocumentResource || saved_type == InspectorPageAgent::kFetchResource || saved_type == InspectorPageAgent::kEventSourceResource) { type = saved_type; } if (type == InspectorPageAgent::kDocumentResource && loader && loader->GetSubstituteData().IsValid()) return; if (cached_resource) resources_data_->AddResource(request_id, cached_resource); String frame_id = loader && loader->GetFrame() ? IdentifiersFactory::FrameId(loader->GetFrame()) : ""; String loader_id = loader ? IdentifiersFactory::LoaderId(loader) : ""; resources_data_->ResponseReceived(request_id, frame_id, response); resources_data_->SetResourceType(request_id, type); if (response.GetSecurityStyle() != ResourceResponse::kSecurityStyleUnknown && response.GetSecurityStyle() != ResourceResponse::kSecurityStyleUnauthenticated) { const ResourceResponse::SecurityDetails* response_security_details = response.GetSecurityDetails(); resources_data_->SetCertificate(request_id, response_security_details->certificate); } if (resource_response && !resource_is_empty) { Maybe<String> maybe_frame_id; if (!frame_id.IsEmpty()) maybe_frame_id = frame_id; GetFrontend()->responseReceived( request_id, loader_id, MonotonicallyIncreasingTime(), InspectorPageAgent::ResourceTypeJson(type), std::move(resource_response), std::move(maybe_frame_id)); } if (is_not_modified && cached_resource && cached_resource->EncodedSize()) DidReceiveData(identifier, loader, 0, cached_resource->EncodedSize()); } 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 InspectorNetworkAgent::DidReceiveResourceResponse( unsigned long identifier, DocumentLoader* loader, const ResourceResponse& response, Resource* cached_resource) { String request_id = IdentifiersFactory::RequestId(identifier); bool is_not_modified = response.HttpStatusCode() == 304; bool resource_is_empty = true; std::unique_ptr<protocol::Network::Response> resource_response = BuildObjectForResourceResponse(response, cached_resource, &resource_is_empty); InspectorPageAgent::ResourceType type = cached_resource ? InspectorPageAgent::ToResourceType(cached_resource->GetType()) : InspectorPageAgent::kOtherResource; InspectorPageAgent::ResourceType saved_type = resources_data_->GetResourceType(request_id); if (saved_type == InspectorPageAgent::kScriptResource || saved_type == InspectorPageAgent::kXHRResource || saved_type == InspectorPageAgent::kDocumentResource || saved_type == InspectorPageAgent::kFetchResource || saved_type == InspectorPageAgent::kEventSourceResource) { type = saved_type; } if (type == InspectorPageAgent::kDocumentResource && loader && loader->GetSubstituteData().IsValid()) return; if (cached_resource) resources_data_->AddResource(request_id, cached_resource); String frame_id = loader && loader->GetFrame() ? IdentifiersFactory::FrameId(loader->GetFrame()) : ""; String loader_id = loader ? IdentifiersFactory::LoaderId(loader) : ""; resources_data_->ResponseReceived(request_id, frame_id, response); resources_data_->SetResourceType(request_id, type); if (response.GetSecurityStyle() != ResourceResponse::kSecurityStyleUnknown && response.GetSecurityStyle() != ResourceResponse::kSecurityStyleUnauthenticated) { const ResourceResponse::SecurityDetails* response_security_details = response.GetSecurityDetails(); resources_data_->SetCertificate(request_id, response_security_details->certificate); } if (resource_response && !resource_is_empty) { Maybe<String> maybe_frame_id; if (!frame_id.IsEmpty()) maybe_frame_id = frame_id; GetFrontend()->responseReceived( request_id, loader_id, MonotonicallyIncreasingTime(), InspectorPageAgent::ResourceTypeJson(type), std::move(resource_response), std::move(maybe_frame_id)); } if (is_not_modified && cached_resource && cached_resource->EncodedSize()) DidReceiveData(identifier, loader, 0, cached_resource->EncodedSize()); }
172,466
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static uint32_t scsi_init_iovec(SCSIDiskReq *r) { r->iov.iov_len = MIN(r->sector_count * 512, SCSI_DMA_BUF_SIZE); qemu_iovec_init_external(&r->qiov, &r->iov, 1); return r->qiov.size / 512; } Commit Message: scsi-disk: lazily allocate bounce buffer It will not be needed for reads and writes if the HBA provides a sglist. In addition, this lets scsi-disk refuse commands with an excessive allocation length, as well as limit memory on usual well-behaved guests. Signed-off-by: Paolo Bonzini <pbonzini@redhat.com> Signed-off-by: Kevin Wolf <kwolf@redhat.com> CWE ID: CWE-119
static uint32_t scsi_init_iovec(SCSIDiskReq *r) { SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev); if (!r->iov.iov_base) { r->buflen = SCSI_DMA_BUF_SIZE; r->iov.iov_base = qemu_blockalign(s->bs, r->buflen); } r->iov.iov_len = MIN(r->sector_count * 512, r->buflen); qemu_iovec_init_external(&r->qiov, &r->iov, 1); return r->qiov.size / 512; }
166,554
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: image_transform_png_set_expand_gray_1_2_4_to_8_set( PNG_CONST image_transform *this, transform_display *that, png_structp pp, png_infop pi) { png_set_expand_gray_1_2_4_to_8(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_expand_gray_1_2_4_to_8_set( const image_transform *this, transform_display *that, png_structp pp, png_infop pi) { png_set_expand_gray_1_2_4_to_8(pp); /* NOTE: don't expect this to expand tRNS */ this->next->set(this->next, that, pp, pi); }
173,632
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void Com_WriteConfig_f( void ) { char filename[MAX_QPATH]; if ( Cmd_Argc() != 2 ) { Com_Printf( "Usage: writeconfig <filename>\n" ); return; } Q_strncpyz( filename, Cmd_Argv(1), sizeof( filename ) ); COM_DefaultExtension( filename, sizeof( filename ), ".cfg" ); Com_Printf( "Writing %s.\n", filename ); Com_WriteConfigToFile( filename ); } Commit Message: Merge some file writing extension checks from OpenJK. Thanks Ensiform. https://github.com/JACoders/OpenJK/commit/05928a57f9e4aae15a3bd0 https://github.com/JACoders/OpenJK/commit/ef124fd0fc48af164581176 CWE ID: CWE-269
void Com_WriteConfig_f( void ) { char filename[MAX_QPATH]; if ( Cmd_Argc() != 2 ) { Com_Printf( "Usage: writeconfig <filename>\n" ); return; } if (!COM_CompareExtension(filename, ".cfg")) { Com_Printf("Com_WriteConfig_f: Only the \".cfg\" extension is supported by this command!\n"); return; } Q_strncpyz( filename, Cmd_Argv(1), sizeof( filename ) ); COM_DefaultExtension( filename, sizeof( filename ), ".cfg" ); Com_Printf( "Writing %s.\n", filename ); Com_WriteConfigToFile( filename ); }
170,077
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static MagickBooleanType load_tile(Image *image,Image *tile_image, XCFDocInfo *inDocInfo,XCFLayerInfo *inLayerInfo,size_t data_length, ExceptionInfo *exception) { ssize_t y; register ssize_t x; register Quantum *q; ssize_t count; unsigned char *graydata; XCFPixelInfo *xcfdata, *xcfodata; xcfdata=(XCFPixelInfo *) AcquireQuantumMemory(data_length,sizeof(*xcfdata)); if (xcfdata == (XCFPixelInfo *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); xcfodata=xcfdata; graydata=(unsigned char *) xcfdata; /* used by gray and indexed */ count=ReadBlob(image,data_length,(unsigned char *) xcfdata); if (count != (ssize_t) data_length) ThrowBinaryException(CorruptImageError,"NotEnoughPixelData", image->filename); for (y=0; y < (ssize_t) tile_image->rows; y++) { q=GetAuthenticPixels(tile_image,0,y,tile_image->columns,1,exception); if (q == (Quantum *) NULL) break; if (inDocInfo->image_type == GIMP_GRAY) { for (x=0; x < (ssize_t) tile_image->columns; x++) { SetPixelGray(tile_image,ScaleCharToQuantum(*graydata),q); SetPixelAlpha(tile_image,ScaleCharToQuantum((unsigned char) inLayerInfo->alpha),q); graydata++; q+=GetPixelChannels(tile_image); } } else if (inDocInfo->image_type == GIMP_RGB) { for (x=0; x < (ssize_t) tile_image->columns; x++) { SetPixelRed(tile_image,ScaleCharToQuantum(xcfdata->red),q); SetPixelGreen(tile_image,ScaleCharToQuantum(xcfdata->green),q); SetPixelBlue(tile_image,ScaleCharToQuantum(xcfdata->blue),q); SetPixelAlpha(tile_image,xcfdata->alpha == 255U ? TransparentAlpha : ScaleCharToQuantum((unsigned char) inLayerInfo->alpha),q); xcfdata++; q+=GetPixelChannels(tile_image); } } if (SyncAuthenticPixels(tile_image,exception) == MagickFalse) break; } xcfodata=(XCFPixelInfo *) RelinquishMagickMemory(xcfodata); return MagickTrue; } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/104 CWE ID: CWE-125
static MagickBooleanType load_tile(Image *image,Image *tile_image, XCFDocInfo *inDocInfo,XCFLayerInfo *inLayerInfo,size_t data_length, ExceptionInfo *exception) { ssize_t y; register ssize_t x; register Quantum *q; ssize_t count; unsigned char *graydata; XCFPixelInfo *xcfdata, *xcfodata; xcfdata=(XCFPixelInfo *) AcquireQuantumMemory(MagickMax(data_length, tile_image->columns*tile_image->rows),sizeof(*xcfdata)); if (xcfdata == (XCFPixelInfo *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); xcfodata=xcfdata; graydata=(unsigned char *) xcfdata; /* used by gray and indexed */ count=ReadBlob(image,data_length,(unsigned char *) xcfdata); if (count != (ssize_t) data_length) ThrowBinaryException(CorruptImageError,"NotEnoughPixelData", image->filename); for (y=0; y < (ssize_t) tile_image->rows; y++) { q=GetAuthenticPixels(tile_image,0,y,tile_image->columns,1,exception); if (q == (Quantum *) NULL) break; if (inDocInfo->image_type == GIMP_GRAY) { for (x=0; x < (ssize_t) tile_image->columns; x++) { SetPixelGray(tile_image,ScaleCharToQuantum(*graydata),q); SetPixelAlpha(tile_image,ScaleCharToQuantum((unsigned char) inLayerInfo->alpha),q); graydata++; q+=GetPixelChannels(tile_image); } } else if (inDocInfo->image_type == GIMP_RGB) { for (x=0; x < (ssize_t) tile_image->columns; x++) { SetPixelRed(tile_image,ScaleCharToQuantum(xcfdata->red),q); SetPixelGreen(tile_image,ScaleCharToQuantum(xcfdata->green),q); SetPixelBlue(tile_image,ScaleCharToQuantum(xcfdata->blue),q); SetPixelAlpha(tile_image,xcfdata->alpha == 255U ? TransparentAlpha : ScaleCharToQuantum((unsigned char) inLayerInfo->alpha),q); xcfdata++; q+=GetPixelChannels(tile_image); } } if (SyncAuthenticPixels(tile_image,exception) == MagickFalse) break; } xcfodata=(XCFPixelInfo *) RelinquishMagickMemory(xcfodata); return MagickTrue; }
168,800
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int btsock_thread_add_fd(int h, int fd, int type, int flags, uint32_t user_id) { if(h < 0 || h >= MAX_THREAD) { APPL_TRACE_ERROR("invalid bt thread handle:%d", h); return FALSE; } if(ts[h].cmd_fdw == -1) { APPL_TRACE_ERROR("cmd socket is not created. socket thread may not initialized"); return FALSE; } if(flags & SOCK_THREAD_ADD_FD_SYNC) { if(ts[h].thread_id == pthread_self()) { flags &= ~SOCK_THREAD_ADD_FD_SYNC; add_poll(h, fd, type, flags, user_id); return TRUE; } APPL_TRACE_DEBUG("THREAD_ADD_FD_SYNC is not called in poll thread, fallback to async"); } sock_cmd_t cmd = {CMD_ADD_FD, fd, type, flags, user_id}; APPL_TRACE_DEBUG("adding fd:%d, flags:0x%x", fd, flags); return send(ts[h].cmd_fdw, &cmd, sizeof(cmd), 0) == sizeof(cmd); } Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process Bug: 28885210 Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360 Conflicts: btif/co/bta_hh_co.c btif/src/btif_core.c Merge conflict resolution of ag/1161415 (referencing ag/1164670) - Directly into mnc-mr2-release CWE ID: CWE-284
int btsock_thread_add_fd(int h, int fd, int type, int flags, uint32_t user_id) { if(h < 0 || h >= MAX_THREAD) { APPL_TRACE_ERROR("invalid bt thread handle:%d", h); return FALSE; } if(ts[h].cmd_fdw == -1) { APPL_TRACE_ERROR("cmd socket is not created. socket thread may not initialized"); return FALSE; } if(flags & SOCK_THREAD_ADD_FD_SYNC) { if(ts[h].thread_id == pthread_self()) { flags &= ~SOCK_THREAD_ADD_FD_SYNC; add_poll(h, fd, type, flags, user_id); return TRUE; } APPL_TRACE_DEBUG("THREAD_ADD_FD_SYNC is not called in poll thread, fallback to async"); } sock_cmd_t cmd = {CMD_ADD_FD, fd, type, flags, user_id}; APPL_TRACE_DEBUG("adding fd:%d, flags:0x%x", fd, flags); return TEMP_FAILURE_RETRY(send(ts[h].cmd_fdw, &cmd, sizeof(cmd), 0)) == sizeof(cmd); }
173,460
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int raw_cmd_copyin(int cmd, void __user *param, struct floppy_raw_cmd **rcmd) { struct floppy_raw_cmd *ptr; int ret; int i; *rcmd = NULL; loop: ptr = kmalloc(sizeof(struct floppy_raw_cmd), GFP_USER); if (!ptr) return -ENOMEM; *rcmd = ptr; ret = copy_from_user(ptr, param, sizeof(*ptr)); if (ret) return -EFAULT; ptr->next = NULL; ptr->buffer_length = 0; param += sizeof(struct floppy_raw_cmd); if (ptr->cmd_count > 33) /* the command may now also take up the space * initially intended for the reply & the * reply count. Needed for long 82078 commands * such as RESTORE, which takes ... 17 command * bytes. Murphy's law #137: When you reserve * 16 bytes for a structure, you'll one day * discover that you really need 17... */ return -EINVAL; for (i = 0; i < 16; i++) ptr->reply[i] = 0; ptr->resultcode = 0; ptr->kernel_data = NULL; if (ptr->flags & (FD_RAW_READ | FD_RAW_WRITE)) { if (ptr->length <= 0) return -EINVAL; ptr->kernel_data = (char *)fd_dma_mem_alloc(ptr->length); fallback_on_nodma_alloc(&ptr->kernel_data, ptr->length); if (!ptr->kernel_data) return -ENOMEM; ptr->buffer_length = ptr->length; } if (ptr->flags & FD_RAW_WRITE) { ret = fd_copyin(ptr->data, ptr->kernel_data, ptr->length); if (ret) return ret; } if (ptr->flags & FD_RAW_MORE) { rcmd = &(ptr->next); ptr->rate &= 0x43; goto loop; } return 0; } Commit Message: floppy: ignore kernel-only members in FDRAWCMD ioctl input Always clear out these floppy_raw_cmd struct members after copying the entire structure from userspace so that the in-kernel version is always valid and never left in an interdeterminate state. Signed-off-by: Matthew Daley <mattd@bugfuzz.com> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org> CWE ID: CWE-264
static int raw_cmd_copyin(int cmd, void __user *param, struct floppy_raw_cmd **rcmd) { struct floppy_raw_cmd *ptr; int ret; int i; *rcmd = NULL; loop: ptr = kmalloc(sizeof(struct floppy_raw_cmd), GFP_USER); if (!ptr) return -ENOMEM; *rcmd = ptr; ret = copy_from_user(ptr, param, sizeof(*ptr)); ptr->next = NULL; ptr->buffer_length = 0; ptr->kernel_data = NULL; if (ret) return -EFAULT; param += sizeof(struct floppy_raw_cmd); if (ptr->cmd_count > 33) /* the command may now also take up the space * initially intended for the reply & the * reply count. Needed for long 82078 commands * such as RESTORE, which takes ... 17 command * bytes. Murphy's law #137: When you reserve * 16 bytes for a structure, you'll one day * discover that you really need 17... */ return -EINVAL; for (i = 0; i < 16; i++) ptr->reply[i] = 0; ptr->resultcode = 0; if (ptr->flags & (FD_RAW_READ | FD_RAW_WRITE)) { if (ptr->length <= 0) return -EINVAL; ptr->kernel_data = (char *)fd_dma_mem_alloc(ptr->length); fallback_on_nodma_alloc(&ptr->kernel_data, ptr->length); if (!ptr->kernel_data) return -ENOMEM; ptr->buffer_length = ptr->length; } if (ptr->flags & FD_RAW_WRITE) { ret = fd_copyin(ptr->data, ptr->kernel_data, ptr->length); if (ret) return ret; } if (ptr->flags & FD_RAW_MORE) { rcmd = &(ptr->next); ptr->rate &= 0x43; goto loop; } return 0; }
166,435
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static bool tailmatch(const char *little, const char *bigone) { size_t littlelen = strlen(little); size_t biglen = strlen(bigone); if(littlelen > biglen) return FALSE; return Curl_raw_equal(little, bigone+biglen-littlelen) ? TRUE : FALSE; } Commit Message: cookie: fix tailmatching to prevent cross-domain leakage Cookies set for 'example.com' could accidentaly also be sent by libcurl to the 'bexample.com' (ie with a prefix to the first domain name). This is a security vulnerabilty, CVE-2013-1944. Bug: http://curl.haxx.se/docs/adv_20130412.html CWE ID: CWE-200
static bool tailmatch(const char *little, const char *bigone) static bool tailmatch(const char *cooke_domain, const char *hostname) { size_t cookie_domain_len = strlen(cooke_domain); size_t hostname_len = strlen(hostname); if(hostname_len < cookie_domain_len) return FALSE; if(!Curl_raw_equal(cooke_domain, hostname+hostname_len-cookie_domain_len)) return FALSE; /* A lead char of cookie_domain is not '.'. RFC6265 4.1.2.3. The Domain Attribute says: For example, if the value of the Domain attribute is "example.com", the user agent will include the cookie in the Cookie header when making HTTP requests to example.com, www.example.com, and www.corp.example.com. */ if(hostname_len == cookie_domain_len) return TRUE; if('.' == *(hostname + hostname_len - cookie_domain_len - 1)) return TRUE; return FALSE; }
166,098
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void GpuProcessHostUIShim::OnAcceleratedSurfaceBuffersSwapped( const GpuHostMsg_AcceleratedSurfaceBuffersSwapped_Params& params) { TRACE_EVENT0("renderer", "GpuProcessHostUIShim::OnAcceleratedSurfaceBuffersSwapped"); ScopedSendOnIOThread delayed_send( host_id_, new AcceleratedSurfaceMsg_BufferPresented(params.route_id, false, 0)); RenderWidgetHostViewPort* view = GetRenderWidgetHostViewFromSurfaceID( params.surface_id); if (!view) return; delayed_send.Cancel(); static const base::TimeDelta swap_delay = GetSwapDelay(); if (swap_delay.ToInternalValue()) base::PlatformThread::Sleep(swap_delay); view->AcceleratedSurfaceBuffersSwapped(params, host_id_); } 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 GpuProcessHostUIShim::OnAcceleratedSurfaceBuffersSwapped( const GpuHostMsg_AcceleratedSurfaceBuffersSwapped_Params& params) { TRACE_EVENT0("renderer", "GpuProcessHostUIShim::OnAcceleratedSurfaceBuffersSwapped"); ScopedSendOnIOThread delayed_send( host_id_, new AcceleratedSurfaceMsg_BufferPresented(params.route_id, params.surface_handle, 0)); RenderWidgetHostViewPort* view = GetRenderWidgetHostViewFromSurfaceID( params.surface_id); if (!view) return; delayed_send.Cancel(); static const base::TimeDelta swap_delay = GetSwapDelay(); if (swap_delay.ToInternalValue()) base::PlatformThread::Sleep(swap_delay); view->AcceleratedSurfaceBuffersSwapped(params, host_id_); }
171,357
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int jffs2_set_acl(struct inode *inode, struct posix_acl *acl, int type) { int rc, xprefix; switch (type) { case ACL_TYPE_ACCESS: xprefix = JFFS2_XPREFIX_ACL_ACCESS; if (acl) { umode_t mode = inode->i_mode; rc = posix_acl_equiv_mode(acl, &mode); if (rc < 0) return rc; if (inode->i_mode != mode) { struct iattr attr; attr.ia_valid = ATTR_MODE | ATTR_CTIME; attr.ia_mode = mode; attr.ia_ctime = CURRENT_TIME_SEC; rc = jffs2_do_setattr(inode, &attr); if (rc < 0) return rc; } if (rc == 0) acl = NULL; } break; case ACL_TYPE_DEFAULT: xprefix = JFFS2_XPREFIX_ACL_DEFAULT; if (!S_ISDIR(inode->i_mode)) return acl ? -EACCES : 0; break; default: return -EINVAL; } rc = __jffs2_set_acl(inode, xprefix, acl); if (!rc) set_cached_acl(inode, type, acl); return rc; } Commit Message: posix_acl: Clear SGID bit when setting file permissions When file permissions are modified via chmod(2) and the user is not in the owning group or capable of CAP_FSETID, the setgid bit is cleared in inode_change_ok(). Setting a POSIX ACL via setxattr(2) sets the file permissions as well as the new ACL, but doesn't clear the setgid bit in a similar way; this allows to bypass the check in chmod(2). Fix that. References: CVE-2016-7097 Reviewed-by: Christoph Hellwig <hch@lst.de> Reviewed-by: Jeff Layton <jlayton@redhat.com> Signed-off-by: Jan Kara <jack@suse.cz> Signed-off-by: Andreas Gruenbacher <agruenba@redhat.com> CWE ID: CWE-285
int jffs2_set_acl(struct inode *inode, struct posix_acl *acl, int type) { int rc, xprefix; switch (type) { case ACL_TYPE_ACCESS: xprefix = JFFS2_XPREFIX_ACL_ACCESS; if (acl) { umode_t mode; rc = posix_acl_update_mode(inode, &mode, &acl); if (rc) return rc; if (inode->i_mode != mode) { struct iattr attr; attr.ia_valid = ATTR_MODE | ATTR_CTIME; attr.ia_mode = mode; attr.ia_ctime = CURRENT_TIME_SEC; rc = jffs2_do_setattr(inode, &attr); if (rc < 0) return rc; } } break; case ACL_TYPE_DEFAULT: xprefix = JFFS2_XPREFIX_ACL_DEFAULT; if (!S_ISDIR(inode->i_mode)) return acl ? -EACCES : 0; break; default: return -EINVAL; } rc = __jffs2_set_acl(inode, xprefix, acl); if (!rc) set_cached_acl(inode, type, acl); return rc; }
166,974
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: validate_entries( bool ignore_invalid_entry ) { HASHITER it = hash_iter_begin( ConfigTab, TABLESIZE ); unsigned int invalid_entries = 0; MyString tmp; MyString output = "The following configuration macros appear to contain default values that must be changed before Condor will run. These macros are:\n"; while( ! hash_iter_done(it) ) { char * val = hash_iter_value(it); if( strstr(val, FORBIDDEN_CONFIG_VAL) ) { char * name = hash_iter_key(it); MyString filename; int line_number; param_get_location(name, filename, line_number); tmp.sprintf(" %s (found on line %d of %s)\n", name, line_number, filename.Value()); output += tmp; invalid_entries++; } hash_iter_next(it); } hash_iter_delete(&it); if(invalid_entries > 0) { if(ignore_invalid_entry) { dprintf(D_ALWAYS, "%s", output.Value()); } else { EXCEPT(output.Value()); } } } Commit Message: CWE ID: CWE-134
validate_entries( bool ignore_invalid_entry ) { HASHITER it = hash_iter_begin( ConfigTab, TABLESIZE ); unsigned int invalid_entries = 0; MyString tmp; MyString output = "The following configuration macros appear to contain default values that must be changed before Condor will run. These macros are:\n"; while( ! hash_iter_done(it) ) { char * val = hash_iter_value(it); if( strstr(val, FORBIDDEN_CONFIG_VAL) ) { char * name = hash_iter_key(it); MyString filename; int line_number; param_get_location(name, filename, line_number); tmp.sprintf(" %s (found on line %d of %s)\n", name, line_number, filename.Value()); output += tmp; invalid_entries++; } hash_iter_next(it); } hash_iter_delete(&it); if(invalid_entries > 0) { if(ignore_invalid_entry) { dprintf(D_ALWAYS, "%s", output.Value()); } else { EXCEPT("%s", output.Value()); } } }
165,382
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int jpc_tsfb_synthesize(jpc_tsfb_t *tsfb, jas_seq2d_t *a) { return (tsfb->numlvls > 0) ? jpc_tsfb_synthesize2(tsfb, jas_seq2d_getref(a, jas_seq2d_xstart(a), jas_seq2d_ystart(a)), jas_seq2d_xstart(a), jas_seq2d_ystart(a), jas_seq2d_width(a), jas_seq2d_height(a), jas_seq2d_rowstep(a), tsfb->numlvls - 1) : 0; } Commit Message: Fixed an integral type promotion problem by adding a JAS_CAST. Modified the jpc_tsfb_synthesize function so that it will be a noop for an empty sequence (in order to avoid dereferencing a null pointer). CWE ID: CWE-476
int jpc_tsfb_synthesize(jpc_tsfb_t *tsfb, jas_seq2d_t *a) { return (tsfb->numlvls > 0 && jas_seq2d_size(a)) ? jpc_tsfb_synthesize2(tsfb, jas_seq2d_getref(a, jas_seq2d_xstart(a), jas_seq2d_ystart(a)), jas_seq2d_xstart(a), jas_seq2d_ystart(a), jas_seq2d_width(a), jas_seq2d_height(a), jas_seq2d_rowstep(a), tsfb->numlvls - 1) : 0; }
168,478
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: nfssvc_decode_readlinkargs(struct svc_rqst *rqstp, __be32 *p, struct nfsd_readlinkargs *args) { p = decode_fh(p, &args->fh); if (!p) return 0; args->buffer = page_address(*(rqstp->rq_next_page++)); return xdr_argsize_check(rqstp, p); } Commit Message: Merge tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux Pull nfsd updates from Bruce Fields: "Another RDMA update from Chuck Lever, and a bunch of miscellaneous bugfixes" * tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux: (26 commits) nfsd: Fix up the "supattr_exclcreat" attributes nfsd: encoders mustn't use unitialized values in error cases nfsd: fix undefined behavior in nfsd4_layout_verify lockd: fix lockd shutdown race NFSv4: Fix callback server shutdown SUNRPC: Refactor svc_set_num_threads() NFSv4.x/callback: Create the callback service through svc_create_pooled lockd: remove redundant check on block svcrdma: Clean out old XDR encoders svcrdma: Remove the req_map cache svcrdma: Remove unused RDMA Write completion handler svcrdma: Reduce size of sge array in struct svc_rdma_op_ctxt svcrdma: Clean up RPC-over-RDMA backchannel reply processing svcrdma: Report Write/Reply chunk overruns svcrdma: Clean up RDMA_ERROR path svcrdma: Use rdma_rw API in RPC reply path svcrdma: Introduce local rdma_rw API helpers svcrdma: Clean up svc_rdma_get_inv_rkey() svcrdma: Add helper to save pages under I/O svcrdma: Eliminate RPCRDMA_SQ_DEPTH_MULT ... CWE ID: CWE-404
nfssvc_decode_readlinkargs(struct svc_rqst *rqstp, __be32 *p, struct nfsd_readlinkargs *args) { p = decode_fh(p, &args->fh); if (!p) return 0; if (!xdr_argsize_check(rqstp, p)) return 0; args->buffer = page_address(*(rqstp->rq_next_page++)); return 1; }
168,152
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool GLES2DecoderImpl::SimulateFixedAttribs( GLuint max_vertex_accessed, bool* simulated) { DCHECK(simulated); *simulated = false; if (gfx::GetGLImplementation() == gfx::kGLImplementationEGLGLES2) return true; if (!vertex_attrib_manager_.HaveFixedAttribs()) { return true; } int num_vertices = max_vertex_accessed + 1; int elements_needed = 0; const VertexAttribManager::VertexAttribInfoList& infos = vertex_attrib_manager_.GetEnabledVertexAttribInfos(); for (VertexAttribManager::VertexAttribInfoList::const_iterator it = infos.begin(); it != infos.end(); ++it) { const VertexAttribManager::VertexAttribInfo* info = *it; const ProgramManager::ProgramInfo::VertexAttribInfo* attrib_info = current_program_->GetAttribInfoByLocation(info->index()); if (attrib_info && info->CanAccess(max_vertex_accessed) && info->type() == GL_FIXED) { int elements_used = 0; if (!SafeMultiply( static_cast<int>(num_vertices), info->size(), &elements_used) || !SafeAdd(elements_needed, elements_used, &elements_needed)) { SetGLError(GL_OUT_OF_MEMORY, "glDrawXXX: simulating GL_FIXED attribs"); return false; } } } const int kSizeOfFloat = sizeof(float); // NOLINT int size_needed = 0; if (!SafeMultiply(elements_needed, kSizeOfFloat, &size_needed)) { SetGLError(GL_OUT_OF_MEMORY, "glDrawXXX: simulating GL_FIXED attribs"); return false; } glBindBuffer(GL_ARRAY_BUFFER, fixed_attrib_buffer_id_); if (size_needed > fixed_attrib_buffer_size_) { glBufferData(GL_ARRAY_BUFFER, size_needed, NULL, GL_DYNAMIC_DRAW); } GLintptr offset = 0; for (VertexAttribManager::VertexAttribInfoList::const_iterator it = infos.begin(); it != infos.end(); ++it) { const VertexAttribManager::VertexAttribInfo* info = *it; const ProgramManager::ProgramInfo::VertexAttribInfo* attrib_info = current_program_->GetAttribInfoByLocation(info->index()); if (attrib_info && info->CanAccess(max_vertex_accessed) && info->type() == GL_FIXED) { int num_elements = info->size() * kSizeOfFloat; int size = num_elements * num_vertices; scoped_array<float> data(new float[size]); const int32* src = reinterpret_cast<const int32 *>( info->buffer()->GetRange(info->offset(), size)); const int32* end = src + num_elements; float* dst = data.get(); while (src != end) { *dst++ = static_cast<float>(*src++) / 65536.0f; } glBufferSubData(GL_ARRAY_BUFFER, offset, size, data.get()); glVertexAttribPointer( info->index(), info->size(), GL_FLOAT, false, 0, reinterpret_cast<GLvoid*>(offset)); offset += size; } } *simulated = true; return true; } Commit Message: Revert "Revert 100494 - Fix bug in SimulateAttrib0.""" TEST=none BUG=95625 TBR=apatrick@chromium.org Review URL: http://codereview.chromium.org/7796016 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@100507 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
bool GLES2DecoderImpl::SimulateFixedAttribs( GLuint max_vertex_accessed, bool* simulated) { DCHECK(simulated); *simulated = false; if (gfx::GetGLImplementation() == gfx::kGLImplementationEGLGLES2) return true; if (!vertex_attrib_manager_.HaveFixedAttribs()) { return true; } GLuint num_vertices = max_vertex_accessed + 1; if (num_vertices == 0) { SetGLError(GL_OUT_OF_MEMORY, "glDrawXXX: Simulating attrib 0"); return false; } GLuint elements_needed = 0; const VertexAttribManager::VertexAttribInfoList& infos = vertex_attrib_manager_.GetEnabledVertexAttribInfos(); for (VertexAttribManager::VertexAttribInfoList::const_iterator it = infos.begin(); it != infos.end(); ++it) { const VertexAttribManager::VertexAttribInfo* info = *it; const ProgramManager::ProgramInfo::VertexAttribInfo* attrib_info = current_program_->GetAttribInfoByLocation(info->index()); if (attrib_info && info->CanAccess(max_vertex_accessed) && info->type() == GL_FIXED) { GLuint elements_used = 0; if (!SafeMultiply(num_vertices, static_cast<GLuint>(info->size()), &elements_used) || !SafeAdd(elements_needed, elements_used, &elements_needed)) { SetGLError(GL_OUT_OF_MEMORY, "glDrawXXX: simulating GL_FIXED attribs"); return false; } } } const GLuint kSizeOfFloat = sizeof(float); // NOLINT GLuint size_needed = 0; if (!SafeMultiply(elements_needed, kSizeOfFloat, &size_needed) || size_needed > 0x7FFFFFFFU) { SetGLError(GL_OUT_OF_MEMORY, "glDrawXXX: simulating GL_FIXED attribs"); return false; } CopyRealGLErrorsToWrapper(); glBindBuffer(GL_ARRAY_BUFFER, fixed_attrib_buffer_id_); if (static_cast<GLsizei>(size_needed) > fixed_attrib_buffer_size_) { glBufferData(GL_ARRAY_BUFFER, size_needed, NULL, GL_DYNAMIC_DRAW); GLenum error = glGetError(); if (error != GL_NO_ERROR) { SetGLError(GL_OUT_OF_MEMORY, "glDrawXXX: simulating GL_FIXED attribs"); return false; } } GLintptr offset = 0; for (VertexAttribManager::VertexAttribInfoList::const_iterator it = infos.begin(); it != infos.end(); ++it) { const VertexAttribManager::VertexAttribInfo* info = *it; const ProgramManager::ProgramInfo::VertexAttribInfo* attrib_info = current_program_->GetAttribInfoByLocation(info->index()); if (attrib_info && info->CanAccess(max_vertex_accessed) && info->type() == GL_FIXED) { int num_elements = info->size() * kSizeOfFloat; int size = num_elements * num_vertices; scoped_array<float> data(new float[size]); const int32* src = reinterpret_cast<const int32 *>( info->buffer()->GetRange(info->offset(), size)); const int32* end = src + num_elements; float* dst = data.get(); while (src != end) { *dst++ = static_cast<float>(*src++) / 65536.0f; } glBufferSubData(GL_ARRAY_BUFFER, offset, size, data.get()); glVertexAttribPointer( info->index(), info->size(), GL_FLOAT, false, 0, reinterpret_cast<GLvoid*>(offset)); offset += size; } } *simulated = true; return true; }
170,333
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void ntlm_free_message_fields_buffer(NTLM_MESSAGE_FIELDS* fields) { if (fields) { if (fields->Buffer) { free(fields->Buffer); fields->Len = 0; fields->MaxLen = 0; fields->Buffer = NULL; fields->BufferOffset = 0; } } } Commit Message: Fixed CVE-2018-8789 Thanks to Eyal Itkin from Check Point Software Technologies. CWE ID: CWE-125
void ntlm_free_message_fields_buffer(NTLM_MESSAGE_FIELDS* fields) static void ntlm_free_message_fields_buffer(NTLM_MESSAGE_FIELDS* fields) { if (fields) { if (fields->Buffer) { free(fields->Buffer); fields->Len = 0; fields->MaxLen = 0; fields->Buffer = NULL; fields->BufferOffset = 0; } } }
169,272
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void reflectUrlStringAttributeAttributeSetter(v8::Local<v8::Value> v8Value, const v8::FunctionCallbackInfo<v8::Value>& info) { v8::Local<v8::Object> holder = info.Holder(); Element* impl = V8Element::toImpl(holder); V8StringResource<> cppValue = v8Value; if (!cppValue.prepare()) return; impl->setAttribute(HTMLNames::reflecturlstringattributeAttr, cppValue); } Commit Message: binding: Removes unused code in templates/attributes.cpp. Faking {{cpp_class}} and {{c8_class}} doesn't make sense. Probably it made sense before the introduction of virtual ScriptWrappable::wrap(). Checking the existence of window->document() doesn't seem making sense to me, and CQ tests seem passing without the check. BUG= Review-Url: https://codereview.chromium.org/2268433002 Cr-Commit-Position: refs/heads/master@{#413375} CWE ID: CWE-189
static void reflectUrlStringAttributeAttributeSetter(v8::Local<v8::Value> v8Value, const v8::FunctionCallbackInfo<v8::Value>& info) { v8::Local<v8::Object> holder = info.Holder(); TestInterfaceNode* impl = V8TestInterfaceNode::toImpl(holder); V8StringResource<> cppValue = v8Value; if (!cppValue.prepare()) return; impl->setAttribute(HTMLNames::reflecturlstringattributeAttr, cppValue); }
171,599
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: GF_Err gf_bin128_parse(const char *string, bin128 value) { u32 len; u32 i=0; if (!strnicmp(string, "0x", 2)) string += 2; len = (u32) strlen(string); if (len >= 32) { u32 j; for (j=0; j<len; j+=2) { u32 v; char szV[5]; while (string[j] && !isalnum(string[j])) j++; if (!string[j]) break; sprintf(szV, "%c%c", string[j], string[j+1]); sscanf(szV, "%x", &v); value[i] = v; i++; } } if (i != 16) { GF_LOG(GF_LOG_ERROR, GF_LOG_CORE, ("[CORE] 128bit blob is not 16-bytes long: %s\n", string)); return GF_BAD_PARAM; } return GF_OK; } Commit Message: fix buffer overrun in gf_bin128_parse closes #1204 closes #1205 CWE ID: CWE-119
GF_Err gf_bin128_parse(const char *string, bin128 value) { u32 len; u32 i=0; if (!strnicmp(string, "0x", 2)) string += 2; len = (u32) strlen(string); if (len >= 32) { u32 j; for (j=0; j<len; j+=2) { u32 v; char szV[5]; while (string[j] && !isalnum(string[j])) j++; if (!string[j]) break; sprintf(szV, "%c%c", string[j], string[j+1]); sscanf(szV, "%x", &v); value[i] = v; i++; if (i > 15) { // force error check below i++; break; } } } if (i != 16) { GF_LOG(GF_LOG_ERROR, GF_LOG_CORE, ("[CORE] 128bit blob is not 16-bytes long: %s\n", string)); return GF_BAD_PARAM; } return GF_OK; }
169,708
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void FrameView::updateLayoutAndStyleForPainting() { RefPtr<FrameView> protector(this); updateLayoutAndStyleIfNeededRecursive(); if (RenderView* view = renderView()) { TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"), "UpdateLayerTree", "frame", m_frame.get()); InspectorInstrumentation::willUpdateLayerTree(m_frame.get()); view->compositor()->updateIfNeededRecursive(); if (view->compositor()->inCompositingMode() && m_frame->isLocalRoot()) m_frame->page()->scrollingCoordinator()->updateAfterCompositingChangeIfNeeded(); updateCompositedSelectionBoundsIfNeeded(); InspectorInstrumentation::didUpdateLayerTree(m_frame.get()); invalidateTreeIfNeededRecursive(); } scrollContentsIfNeededRecursive(); ASSERT(lifecycle().state() == DocumentLifecycle::PaintInvalidationClean); } Commit Message: Defer call to updateWidgetPositions() outside of RenderLayerScrollableArea. updateWidgetPositions() can destroy the render tree, so it should never be called from inside RenderLayerScrollableArea. Leaving it there allows for the potential of use-after-free bugs. BUG=402407 R=vollick@chromium.org Review URL: https://codereview.chromium.org/490473003 git-svn-id: svn://svn.chromium.org/blink/trunk@180681 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-416
void FrameView::updateLayoutAndStyleForPainting() { RefPtr<FrameView> protector(this); updateLayoutAndStyleIfNeededRecursive(); updateWidgetPositionsIfNeeded(); if (RenderView* view = renderView()) { TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"), "UpdateLayerTree", "frame", m_frame.get()); InspectorInstrumentation::willUpdateLayerTree(m_frame.get()); view->compositor()->updateIfNeededRecursive(); if (view->compositor()->inCompositingMode() && m_frame->isLocalRoot()) m_frame->page()->scrollingCoordinator()->updateAfterCompositingChangeIfNeeded(); updateCompositedSelectionBoundsIfNeeded(); InspectorInstrumentation::didUpdateLayerTree(m_frame.get()); invalidateTreeIfNeededRecursive(); } scrollContentsIfNeededRecursive(); ASSERT(lifecycle().state() == DocumentLifecycle::PaintInvalidationClean); }
171,636
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void GpuProcessHost::EstablishChannelError( const EstablishChannelCallback& callback, const IPC::ChannelHandle& channel_handle, base::ProcessHandle renderer_process_for_gpu, const content::GPUInfo& gpu_info) { callback.Run(channel_handle, renderer_process_for_gpu, gpu_info); } Commit Message: Convert plugin and GPU process to brokered handle duplication. BUG=119250 Review URL: https://chromiumcodereview.appspot.com/9958034 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132303 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
void GpuProcessHost::EstablishChannelError( const EstablishChannelCallback& callback, const IPC::ChannelHandle& channel_handle, base::ProcessHandle renderer_process_for_gpu, const content::GPUInfo& gpu_info) { callback.Run(channel_handle, gpu_info); }
170,920
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static NavigationPolicy NavigationPolicyForRequest( const FrameLoadRequest& request) { NavigationPolicy policy = kNavigationPolicyCurrentTab; Event* event = request.TriggeringEvent(); if (!event) return policy; if (request.Form() && event->UnderlyingEvent()) event = event->UnderlyingEvent(); if (event->IsMouseEvent()) { MouseEvent* mouse_event = ToMouseEvent(event); NavigationPolicyFromMouseEvent( mouse_event->button(), mouse_event->ctrlKey(), mouse_event->shiftKey(), mouse_event->altKey(), mouse_event->metaKey(), &policy); } else if (event->IsKeyboardEvent()) { KeyboardEvent* key_event = ToKeyboardEvent(event); NavigationPolicyFromMouseEvent(0, key_event->ctrlKey(), key_event->shiftKey(), key_event->altKey(), key_event->metaKey(), &policy); } else if (event->IsGestureEvent()) { GestureEvent* gesture_event = ToGestureEvent(event); NavigationPolicyFromMouseEvent( 0, gesture_event->ctrlKey(), gesture_event->shiftKey(), gesture_event->altKey(), gesture_event->metaKey(), &policy); } return policy; } Commit Message: Only allow downloading in response to real keyboard modifiers BUG=848531 Change-Id: I97554c8d312243b55647f1376945aee32dbd95bf Reviewed-on: https://chromium-review.googlesource.com/1082216 Reviewed-by: Mike West <mkwst@chromium.org> Commit-Queue: Jochen Eisinger <jochen@chromium.org> Cr-Commit-Position: refs/heads/master@{#564051} CWE ID:
static NavigationPolicy NavigationPolicyForRequest( static NavigationPolicy NavigationPolicyForEvent(Event* event) { NavigationPolicy policy = kNavigationPolicyCurrentTab; if (event->IsMouseEvent()) { MouseEvent* mouse_event = ToMouseEvent(event); NavigationPolicyFromMouseEvent( mouse_event->button(), mouse_event->ctrlKey(), mouse_event->shiftKey(), mouse_event->altKey(), mouse_event->metaKey(), &policy); } else if (event->IsKeyboardEvent()) { KeyboardEvent* key_event = ToKeyboardEvent(event); NavigationPolicyFromMouseEvent(0, key_event->ctrlKey(), key_event->shiftKey(), key_event->altKey(), key_event->metaKey(), &policy); } else if (event->IsGestureEvent()) { GestureEvent* gesture_event = ToGestureEvent(event); NavigationPolicyFromMouseEvent( 0, gesture_event->ctrlKey(), gesture_event->shiftKey(), gesture_event->altKey(), gesture_event->metaKey(), &policy); } return policy; }
173,191
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void patch_instruction(VAPICROMState *s, X86CPU *cpu, target_ulong ip) { CPUState *cs = CPU(cpu); CPUX86State *env = &cpu->env; VAPICHandlers *handlers; uint8_t opcode[2]; uint32_t imm32; target_ulong current_pc = 0; target_ulong current_cs_base = 0; uint32_t current_flags = 0; if (smp_cpus == 1) { handlers = &s->rom_state.up; } else { handlers = &s->rom_state.mp; } if (!kvm_enabled()) { cpu_get_tb_cpu_state(env, &current_pc, &current_cs_base, &current_flags); } pause_all_vcpus(); cpu_memory_rw_debug(cs, ip, opcode, sizeof(opcode), 0); switch (opcode[0]) { case 0x89: /* mov r32 to r/m32 */ patch_byte(cpu, ip, 0x50 + modrm_reg(opcode[1])); /* push reg */ patch_call(s, cpu, ip + 1, handlers->set_tpr); break; case 0x8b: /* mov r/m32 to r32 */ patch_byte(cpu, ip, 0x90); patch_call(s, cpu, ip + 1, handlers->get_tpr[modrm_reg(opcode[1])]); break; case 0xa1: /* mov abs to eax */ patch_call(s, cpu, ip, handlers->get_tpr[0]); break; case 0xa3: /* mov eax to abs */ patch_call(s, cpu, ip, handlers->set_tpr_eax); break; case 0xc7: /* mov imm32, r/m32 (c7/0) */ patch_byte(cpu, ip, 0x68); /* push imm32 */ cpu_memory_rw_debug(cs, ip + 6, (void *)&imm32, sizeof(imm32), 0); cpu_memory_rw_debug(cs, ip + 1, (void *)&imm32, sizeof(imm32), 1); patch_call(s, cpu, ip + 5, handlers->set_tpr); break; case 0xff: /* push r/m32 */ patch_byte(cpu, ip, 0x50); /* push eax */ patch_call(s, cpu, ip + 1, handlers->get_tpr_stack); break; default: abort(); } resume_all_vcpus(); if (!kvm_enabled()) { tb_gen_code(cs, current_pc, current_cs_base, current_flags, 1); cpu_resume_from_signal(cs, NULL); } } Commit Message: CWE ID: CWE-200
static void patch_instruction(VAPICROMState *s, X86CPU *cpu, target_ulong ip) { CPUState *cs = CPU(cpu); CPUX86State *env = &cpu->env; VAPICHandlers *handlers; uint8_t opcode[2]; uint32_t imm32 = 0; target_ulong current_pc = 0; target_ulong current_cs_base = 0; uint32_t current_flags = 0; if (smp_cpus == 1) { handlers = &s->rom_state.up; } else { handlers = &s->rom_state.mp; } if (!kvm_enabled()) { cpu_get_tb_cpu_state(env, &current_pc, &current_cs_base, &current_flags); } pause_all_vcpus(); cpu_memory_rw_debug(cs, ip, opcode, sizeof(opcode), 0); switch (opcode[0]) { case 0x89: /* mov r32 to r/m32 */ patch_byte(cpu, ip, 0x50 + modrm_reg(opcode[1])); /* push reg */ patch_call(s, cpu, ip + 1, handlers->set_tpr); break; case 0x8b: /* mov r/m32 to r32 */ patch_byte(cpu, ip, 0x90); patch_call(s, cpu, ip + 1, handlers->get_tpr[modrm_reg(opcode[1])]); break; case 0xa1: /* mov abs to eax */ patch_call(s, cpu, ip, handlers->get_tpr[0]); break; case 0xa3: /* mov eax to abs */ patch_call(s, cpu, ip, handlers->set_tpr_eax); break; case 0xc7: /* mov imm32, r/m32 (c7/0) */ patch_byte(cpu, ip, 0x68); /* push imm32 */ cpu_memory_rw_debug(cs, ip + 6, (void *)&imm32, sizeof(imm32), 0); cpu_memory_rw_debug(cs, ip + 1, (void *)&imm32, sizeof(imm32), 1); patch_call(s, cpu, ip + 5, handlers->set_tpr); break; case 0xff: /* push r/m32 */ patch_byte(cpu, ip, 0x50); /* push eax */ patch_call(s, cpu, ip + 1, handlers->get_tpr_stack); break; default: abort(); } resume_all_vcpus(); if (!kvm_enabled()) { tb_gen_code(cs, current_pc, current_cs_base, current_flags, 1); cpu_resume_from_signal(cs, NULL); } }
165,076
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: AcceleratedStaticBitmapImage::AcceleratedStaticBitmapImage( sk_sp<SkImage> image, base::WeakPtr<WebGraphicsContext3DProviderWrapper>&& context_provider_wrapper) : paint_image_content_id_(cc::PaintImage::GetNextContentId()) { CHECK(image && image->isTextureBacked()); texture_holder_ = std::make_unique<SkiaTextureHolder>( std::move(image), std::move(context_provider_wrapper)); thread_checker_.DetachFromThread(); } Commit Message: Fix *StaticBitmapImage ThreadChecker and unaccelerated SkImage destroy - AcceleratedStaticBitmapImage was misusing ThreadChecker by having its own detach logic. Using proper DetachThread is simpler, cleaner and correct. - UnacceleratedStaticBitmapImage didn't destroy the SkImage in the proper thread, leading to GrContext/SkSp problems. Bug: 890576 Change-Id: Ic71e7f7322b0b851774628247aa5256664bc0723 Reviewed-on: https://chromium-review.googlesource.com/c/1307775 Reviewed-by: Gabriel Charette <gab@chromium.org> Reviewed-by: Jeremy Roman <jbroman@chromium.org> Commit-Queue: Fernando Serboncini <fserb@chromium.org> Cr-Commit-Position: refs/heads/master@{#604427} CWE ID: CWE-119
AcceleratedStaticBitmapImage::AcceleratedStaticBitmapImage( sk_sp<SkImage> image, base::WeakPtr<WebGraphicsContext3DProviderWrapper>&& context_provider_wrapper) : paint_image_content_id_(cc::PaintImage::GetNextContentId()) { CHECK(image && image->isTextureBacked()); texture_holder_ = std::make_unique<SkiaTextureHolder>( std::move(image), std::move(context_provider_wrapper)); }
172,588
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void SyncBackendHost::Core::DoInitialize(const DoInitializeOptions& options) { DCHECK(!sync_loop_); sync_loop_ = options.sync_loop; DCHECK(sync_loop_); if (options.delete_sync_data_folder) { DeleteSyncDataFolder(); } bool success = file_util::CreateDirectory(sync_data_folder_path_); DCHECK(success); DCHECK(!registrar_); registrar_ = options.registrar; DCHECK(registrar_); sync_manager_.reset(new sync_api::SyncManager(name_)); sync_manager_->AddObserver(this); success = sync_manager_->Init( sync_data_folder_path_, options.event_handler, options.service_url.host() + options.service_url.path(), options.service_url.EffectiveIntPort(), options.service_url.SchemeIsSecure(), BrowserThread::GetBlockingPool(), options.make_http_bridge_factory_fn.Run(), options.registrar /* as ModelSafeWorkerRegistrar */, options.extensions_activity_monitor, options.registrar /* as SyncManager::ChangeDelegate */, MakeUserAgentForSyncApi(), options.credentials, true, new BridgedSyncNotifier( options.chrome_sync_notification_bridge, options.sync_notifier_factory->CreateSyncNotifier()), options.restored_key_for_bootstrapping, options.testing_mode, &encryptor_, options.unrecoverable_error_handler, options.report_unrecoverable_error_function); LOG_IF(ERROR, !success) << "Syncapi initialization failed!"; if (CommandLine::ForCurrentProcess()->HasSwitch( switches::kSyncThrowUnrecoverableError)) { sync_manager_->ThrowUnrecoverableError(); } } Commit Message: [Sync] Cleanup all tab sync enabling logic now that its on by default. BUG=none TEST= Review URL: https://chromiumcodereview.appspot.com/10443046 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@139462 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-362
void SyncBackendHost::Core::DoInitialize(const DoInitializeOptions& options) { DCHECK(!sync_loop_); sync_loop_ = options.sync_loop; DCHECK(sync_loop_); if (options.delete_sync_data_folder) { DeleteSyncDataFolder(); } bool success = file_util::CreateDirectory(sync_data_folder_path_); DCHECK(success); DCHECK(!registrar_); registrar_ = options.registrar; DCHECK(registrar_); sync_manager_.reset(new sync_api::SyncManager(name_)); sync_manager_->AddObserver(this); success = sync_manager_->Init( sync_data_folder_path_, options.event_handler, options.service_url.host() + options.service_url.path(), options.service_url.EffectiveIntPort(), options.service_url.SchemeIsSecure(), BrowserThread::GetBlockingPool(), options.make_http_bridge_factory_fn.Run(), options.registrar /* as ModelSafeWorkerRegistrar */, options.extensions_activity_monitor, options.registrar /* as SyncManager::ChangeDelegate */, MakeUserAgentForSyncApi(), options.credentials, new BridgedSyncNotifier( options.chrome_sync_notification_bridge, options.sync_notifier_factory->CreateSyncNotifier()), options.restored_key_for_bootstrapping, options.testing_mode, &encryptor_, options.unrecoverable_error_handler, options.report_unrecoverable_error_function); LOG_IF(ERROR, !success) << "Syncapi initialization failed!"; if (CommandLine::ForCurrentProcess()->HasSwitch( switches::kSyncThrowUnrecoverableError)) { sync_manager_->ThrowUnrecoverableError(); } }
170,785
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void Compositor::OnFirstSurfaceActivation( const viz::SurfaceInfo& surface_info) { } Commit Message: Don't report OnFirstSurfaceActivation for ui::Compositor Bug: 893850 Change-Id: Iee754cefbd083d0a21a2b672fb8e837eaab81c43 Reviewed-on: https://chromium-review.googlesource.com/c/1293712 Reviewed-by: Antoine Labour <piman@chromium.org> Commit-Queue: Saman Sami <samans@chromium.org> Cr-Commit-Position: refs/heads/master@{#601629} CWE ID: CWE-20
void Compositor::OnFirstSurfaceActivation( const viz::SurfaceInfo& surface_info) { NOTREACHED(); }
172,563
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void CloudPolicySubsystem::StopAutoRetry() { cloud_policy_controller_->StopAutoRetry(); device_token_fetcher_->StopAutoRetry(); data_store_->Reset(); } Commit Message: Reset the device policy machinery upon retrying enrollment. BUG=chromium-os:18208 TEST=See bug description Review URL: http://codereview.chromium.org/7676005 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@97615 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void CloudPolicySubsystem::StopAutoRetry() { void CloudPolicySubsystem::Reset() { data_store_->Reset(); cloud_policy_cache_->Reset(); cloud_policy_controller_->Reset(); device_token_fetcher_->Reset(); }
170,283
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static size_t optsize (lua_State *L, char opt, const char **fmt) { switch (opt) { case 'B': case 'b': return sizeof(char); case 'H': case 'h': return sizeof(short); case 'L': case 'l': return sizeof(long); case 'T': return sizeof(size_t); case 'f': return sizeof(float); case 'd': return sizeof(double); case 'x': return 1; case 'c': return getnum(L, fmt, 1); case 'i': case 'I': { int sz = getnum(L, fmt, sizeof(int)); if (sz > MAXINTSIZE) luaL_error(L, "integral size %d is larger than limit of %d", sz, MAXINTSIZE); return sz; } default: return 0; /* other cases do not need alignment */ } } Commit Message: Security: update Lua struct package for security. During an auditing Apple found that the "struct" Lua package we ship with Redis (http://www.inf.puc-rio.br/~roberto/struct/) contains a security problem. A bound-checking statement fails because of integer overflow. The bug exists since we initially integrated this package with Lua, when scripting was introduced, so every version of Redis with EVAL/EVALSHA capabilities exposed is affected. Instead of just fixing the bug, the library was updated to the latest version shipped by the author. CWE ID: CWE-190
static size_t optsize (lua_State *L, char opt, const char **fmt) { switch (opt) { case 'B': case 'b': return sizeof(char); case 'H': case 'h': return sizeof(short); case 'L': case 'l': return sizeof(long); case 'T': return sizeof(size_t); case 'f': return sizeof(float); case 'd': return sizeof(double); case 'x': return 1; case 'c': return getnum(fmt, 1); case 'i': case 'I': { int sz = getnum(fmt, sizeof(int)); if (sz > MAXINTSIZE) luaL_error(L, "integral size %d is larger than limit of %d", sz, MAXINTSIZE); return sz; } default: return 0; /* other cases do not need alignment */ } }
170,166
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool DownloadManagerImpl::InterceptDownload( const download::DownloadCreateInfo& info) { WebContents* web_contents = WebContentsImpl::FromRenderFrameHostID( info.render_process_id, info.render_frame_id); if (info.is_new_download && info.result == download::DOWNLOAD_INTERRUPT_REASON_SERVER_CROSS_ORIGIN_REDIRECT) { if (web_contents) { std::vector<GURL> url_chain(info.url_chain); GURL url = url_chain.back(); url_chain.pop_back(); NavigationController::LoadURLParams params(url); params.has_user_gesture = info.has_user_gesture; params.referrer = Referrer( info.referrer_url, Referrer::NetReferrerPolicyToBlinkReferrerPolicy( info.referrer_policy)); params.redirect_chain = url_chain; web_contents->GetController().LoadURLWithParams(params); } if (info.request_handle) info.request_handle->CancelRequest(false); return true; } if (!delegate_ || !delegate_->InterceptDownloadIfApplicable( info.url(), info.mime_type, info.request_origin, web_contents)) { return false; } if (info.request_handle) info.request_handle->CancelRequest(false); return true; } Commit Message: When turning a download into a navigation, navigate the right frame Code changes from Nate Chapin <japhet@chromium.org> Bug: 926105 Change-Id: I098599394e6ebe7d2fce5af838014297a337d294 Reviewed-on: https://chromium-review.googlesource.com/c/1454962 Reviewed-by: Camille Lamy <clamy@chromium.org> Commit-Queue: Jochen Eisinger <jochen@chromium.org> Cr-Commit-Position: refs/heads/master@{#629547} CWE ID: CWE-284
bool DownloadManagerImpl::InterceptDownload( const download::DownloadCreateInfo& info) { WebContents* web_contents = WebContentsImpl::FromRenderFrameHostID( info.render_process_id, info.render_frame_id); if (info.is_new_download && info.result == download::DOWNLOAD_INTERRUPT_REASON_SERVER_CROSS_ORIGIN_REDIRECT) { if (web_contents) { std::vector<GURL> url_chain(info.url_chain); GURL url = url_chain.back(); url_chain.pop_back(); NavigationController::LoadURLParams params(url); params.has_user_gesture = info.has_user_gesture; params.referrer = Referrer( info.referrer_url, Referrer::NetReferrerPolicyToBlinkReferrerPolicy( info.referrer_policy)); params.redirect_chain = url_chain; params.frame_tree_node_id = RenderFrameHost::GetFrameTreeNodeIdForRoutingId( info.render_process_id, info.render_frame_id); web_contents->GetController().LoadURLWithParams(params); } if (info.request_handle) info.request_handle->CancelRequest(false); return true; } if (!delegate_ || !delegate_->InterceptDownloadIfApplicable( info.url(), info.mime_type, info.request_origin, web_contents)) { return false; } if (info.request_handle) info.request_handle->CancelRequest(false); return true; }
173,023
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void skel(const char *homedir, uid_t u, gid_t g) { char *fname; if (arg_zsh) { if (asprintf(&fname, "%s/.zshrc", homedir) == -1) errExit("asprintf"); struct stat s; if (stat(fname, &s) == 0) return; if (stat("/etc/skel/.zshrc", &s) == 0) { if (is_link("/etc/skel/.zshrc")) { fprintf(stderr, "Error: invalid /etc/skel/.zshrc file\n"); exit(1); } if (copy_file("/etc/skel/.zshrc", fname) == 0) { if (chown(fname, u, g) == -1) errExit("chown"); fs_logger("clone /etc/skel/.zshrc"); } } else { // FILE *fp = fopen(fname, "w"); if (fp) { fprintf(fp, "\n"); fclose(fp); if (chown(fname, u, g) == -1) errExit("chown"); if (chmod(fname, S_IRUSR | S_IWUSR) < 0) errExit("chown"); fs_logger2("touch", fname); } } free(fname); } else if (arg_csh) { if (asprintf(&fname, "%s/.cshrc", homedir) == -1) errExit("asprintf"); struct stat s; if (stat(fname, &s) == 0) return; if (stat("/etc/skel/.cshrc", &s) == 0) { if (is_link("/etc/skel/.cshrc")) { fprintf(stderr, "Error: invalid /etc/skel/.cshrc file\n"); exit(1); } if (copy_file("/etc/skel/.cshrc", fname) == 0) { if (chown(fname, u, g) == -1) errExit("chown"); fs_logger("clone /etc/skel/.cshrc"); } } else { // /* coverity[toctou] */ FILE *fp = fopen(fname, "w"); if (fp) { fprintf(fp, "\n"); fclose(fp); if (chown(fname, u, g) == -1) errExit("chown"); if (chmod(fname, S_IRUSR | S_IWUSR) < 0) errExit("chown"); fs_logger2("touch", fname); } } free(fname); } else { if (asprintf(&fname, "%s/.bashrc", homedir) == -1) errExit("asprintf"); struct stat s; if (stat(fname, &s) == 0) return; if (stat("/etc/skel/.bashrc", &s) == 0) { if (is_link("/etc/skel/.bashrc")) { fprintf(stderr, "Error: invalid /etc/skel/.bashrc file\n"); exit(1); } if (copy_file("/etc/skel/.bashrc", fname) == 0) { /* coverity[toctou] */ if (chown(fname, u, g) == -1) errExit("chown"); fs_logger("clone /etc/skel/.bashrc"); } } free(fname); } } Commit Message: security fix CWE ID: CWE-269
static void skel(const char *homedir, uid_t u, gid_t g) { char *fname; if (arg_zsh) { if (asprintf(&fname, "%s/.zshrc", homedir) == -1) errExit("asprintf"); struct stat s; if (stat(fname, &s) == 0) return; if (is_link(fname)) { // stat on dangling symlinks fails, try again using lstat fprintf(stderr, "Error: invalid %s file\n", fname); exit(1); } if (stat("/etc/skel/.zshrc", &s) == 0) { copy_file_as_user("/etc/skel/.zshrc", fname, u, g, 0644); // regular user fs_logger("clone /etc/skel/.zshrc"); } else { touch_file_as_user(fname, u, g, 0644); fs_logger2("touch", fname); } free(fname); } else if (arg_csh) { if (asprintf(&fname, "%s/.cshrc", homedir) == -1) errExit("asprintf"); struct stat s; if (stat(fname, &s) == 0) return; if (is_link(fname)) { // stat on dangling symlinks fails, try again using lstat fprintf(stderr, "Error: invalid %s file\n", fname); exit(1); } if (stat("/etc/skel/.cshrc", &s) == 0) { copy_file_as_user("/etc/skel/.cshrc", fname, u, g, 0644); // regular user fs_logger("clone /etc/skel/.cshrc"); } else { touch_file_as_user(fname, u, g, 0644); fs_logger2("touch", fname); } free(fname); } else { if (asprintf(&fname, "%s/.bashrc", homedir) == -1) errExit("asprintf"); struct stat s; if (stat(fname, &s) == 0) return; if (is_link(fname)) { // stat on dangling symlinks fails, try again using lstat fprintf(stderr, "Error: invalid %s file\n", fname); exit(1); } if (stat("/etc/skel/.bashrc", &s) == 0) { copy_file_as_user("/etc/skel/.bashrc", fname, u, g, 0644); // regular user fs_logger("clone /etc/skel/.bashrc"); } free(fname); } }
170,098
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: std::string SanitizeFrontendQueryParam( const std::string& key, const std::string& value) { if (key == "can_dock" || key == "debugFrontend" || key == "experiments" || key == "isSharedWorker" || key == "v8only" || key == "remoteFrontend") return "true"; if (key == "ws" || key == "service-backend") return SanitizeEndpoint(value); if (key == "dockSide" && value == "undocked") return value; if (key == "panel" && (value == "elements" || value == "console")) return value; if (key == "remoteBase") return SanitizeRemoteBase(value); if (key == "remoteFrontendUrl") return SanitizeRemoteFrontendURL(value); return std::string(); } Commit Message: DevTools: move front-end URL handling to DevToolsUIBindingds BUG=662859 Review-Url: https://codereview.chromium.org/2607833002 Cr-Commit-Position: refs/heads/master@{#440926} CWE ID: CWE-200
std::string SanitizeFrontendQueryParam(
172,459
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: rend_service_intro_established(origin_circuit_t *circuit, const uint8_t *request, size_t request_len) { rend_service_t *service; rend_intro_point_t *intro; char serviceid[REND_SERVICE_ID_LEN_BASE32+1]; (void) request; (void) request_len; tor_assert(circuit->rend_data); /* XXX: This is version 2 specific (only supported one for now). */ const char *rend_pk_digest = (char *) rend_data_get_pk_digest(circuit->rend_data, NULL); if (circuit->base_.purpose != CIRCUIT_PURPOSE_S_ESTABLISH_INTRO) { log_warn(LD_PROTOCOL, "received INTRO_ESTABLISHED cell on non-intro circuit."); goto err; } service = rend_service_get_by_pk_digest(rend_pk_digest); if (!service) { log_warn(LD_REND, "Unknown service on introduction circuit %u.", (unsigned)circuit->base_.n_circ_id); goto err; } /* We've just successfully established a intro circuit to one of our * introduction point, account for it. */ intro = find_intro_point(circuit); if (intro == NULL) { log_warn(LD_REND, "Introduction circuit established without a rend_intro_point_t " "object for service %s on circuit %u", safe_str_client(serviceid), (unsigned)circuit->base_.n_circ_id); goto err; } intro->circuit_established = 1; /* We might not have every introduction point ready but at this point we * know that the descriptor needs to be uploaded. */ service->desc_is_dirty = time(NULL); circuit_change_purpose(TO_CIRCUIT(circuit), CIRCUIT_PURPOSE_S_INTRO); base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32 + 1, rend_pk_digest, REND_SERVICE_ID_LEN); log_info(LD_REND, "Received INTRO_ESTABLISHED cell on circuit %u for service %s", (unsigned)circuit->base_.n_circ_id, serviceid); /* Getting a valid INTRODUCE_ESTABLISHED means we've successfully * used the circ */ pathbias_mark_use_success(circuit); return 0; err: circuit_mark_for_close(TO_CIRCUIT(circuit), END_CIRC_REASON_TORPROTOCOL); return -1; } Commit Message: Fix log-uninitialized-stack bug in rend_service_intro_established. Fixes bug 23490; bugfix on 0.2.7.2-alpha. TROVE-2017-008 CVE-2017-0380 CWE ID: CWE-532
rend_service_intro_established(origin_circuit_t *circuit, const uint8_t *request, size_t request_len) { rend_service_t *service; rend_intro_point_t *intro; char serviceid[REND_SERVICE_ID_LEN_BASE32+1]; (void) request; (void) request_len; tor_assert(circuit->rend_data); /* XXX: This is version 2 specific (only supported one for now). */ const char *rend_pk_digest = (char *) rend_data_get_pk_digest(circuit->rend_data, NULL); if (circuit->base_.purpose != CIRCUIT_PURPOSE_S_ESTABLISH_INTRO) { log_warn(LD_PROTOCOL, "received INTRO_ESTABLISHED cell on non-intro circuit."); goto err; } service = rend_service_get_by_pk_digest(rend_pk_digest); if (!service) { log_warn(LD_REND, "Unknown service on introduction circuit %u.", (unsigned)circuit->base_.n_circ_id); goto err; } base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32 + 1, rend_pk_digest, REND_SERVICE_ID_LEN); /* We've just successfully established a intro circuit to one of our * introduction point, account for it. */ intro = find_intro_point(circuit); if (intro == NULL) { log_warn(LD_REND, "Introduction circuit established without a rend_intro_point_t " "object for service %s on circuit %u", safe_str_client(serviceid), (unsigned)circuit->base_.n_circ_id); goto err; } intro->circuit_established = 1; /* We might not have every introduction point ready but at this point we * know that the descriptor needs to be uploaded. */ service->desc_is_dirty = time(NULL); circuit_change_purpose(TO_CIRCUIT(circuit), CIRCUIT_PURPOSE_S_INTRO); log_info(LD_REND, "Received INTRO_ESTABLISHED cell on circuit %u for service %s", (unsigned)circuit->base_.n_circ_id, serviceid); /* Getting a valid INTRODUCE_ESTABLISHED means we've successfully * used the circ */ pathbias_mark_use_success(circuit); return 0; err: circuit_mark_for_close(TO_CIRCUIT(circuit), END_CIRC_REASON_TORPROTOCOL); return -1; }
168,449
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: _fep_open_control_socket (Fep *fep) { struct sockaddr_un sun; char *path; int fd; ssize_t sun_len; fd = socket (AF_UNIX, SOCK_STREAM, 0); if (fd < 0) { perror ("socket"); return -1; } path = create_socket_name ("fep-XXXXXX/control"); if (strlen (path) + 1 >= sizeof(sun.sun_path)) { fep_log (FEP_LOG_LEVEL_WARNING, "unix domain socket path too long: %d + 1 >= %d", strlen (path), sizeof (sun.sun_path)); free (path); return -1; } memset (&sun, 0, sizeof(sun)); sun.sun_family = AF_UNIX; #ifdef __linux__ sun.sun_path[0] = '\0'; memcpy (sun.sun_path + 1, path, strlen (path)); sun_len = offsetof (struct sockaddr_un, sun_path) + strlen (path) + 1; remove_control_socket (path); #else memcpy (sun.sun_path, path, strlen (path)); sun_len = sizeof (struct sockaddr_un); #endif if (bind (fd, (const struct sockaddr *) &sun, sun_len) < 0) { perror ("bind"); free (path); close (fd); return -1; } if (listen (fd, 5) < 0) { perror ("listen"); free (path); close (fd); return -1; } fep->server = fd; fep->control_socket_path = path; return 0; } Commit Message: Don't use abstract Unix domain sockets CWE ID: CWE-264
_fep_open_control_socket (Fep *fep) { struct sockaddr_un sun; char *path; int fd; ssize_t sun_len; fd = socket (AF_UNIX, SOCK_STREAM, 0); if (fd < 0) { perror ("socket"); return -1; } path = create_socket_name ("fep-XXXXXX/control"); if (strlen (path) + 1 >= sizeof(sun.sun_path)) { fep_log (FEP_LOG_LEVEL_WARNING, "unix domain socket path too long: %d + 1 >= %d", strlen (path), sizeof (sun.sun_path)); free (path); return -1; } memset (&sun, 0, sizeof(sun)); sun.sun_family = AF_UNIX; memcpy (sun.sun_path, path, strlen (path)); sun_len = sizeof (struct sockaddr_un); if (bind (fd, (const struct sockaddr *) &sun, sun_len) < 0) { perror ("bind"); free (path); close (fd); return -1; } if (listen (fd, 5) < 0) { perror ("listen"); free (path); close (fd); return -1; } fep->server = fd; fep->control_socket_path = path; return 0; }
166,325
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: OMX_ERRORTYPE omx_vdec::get_config(OMX_IN OMX_HANDLETYPE hComp, OMX_IN OMX_INDEXTYPE configIndex, OMX_INOUT OMX_PTR configData) { (void) hComp; OMX_ERRORTYPE eRet = OMX_ErrorNone; if (m_state == OMX_StateInvalid) { DEBUG_PRINT_ERROR("Get Config in Invalid State"); return OMX_ErrorInvalidState; } switch ((unsigned long)configIndex) { case OMX_QcomIndexConfigInterlaced: { OMX_QCOM_CONFIG_INTERLACETYPE *configFmt = (OMX_QCOM_CONFIG_INTERLACETYPE *) configData; if (configFmt->nPortIndex == 1) { if (configFmt->nIndex == 0) { configFmt->eInterlaceType = OMX_QCOM_InterlaceFrameProgressive; } else if (configFmt->nIndex == 1) { configFmt->eInterlaceType = OMX_QCOM_InterlaceInterleaveFrameTopFieldFirst; } else if (configFmt->nIndex == 2) { configFmt->eInterlaceType = OMX_QCOM_InterlaceInterleaveFrameBottomFieldFirst; } else { DEBUG_PRINT_ERROR("get_config: OMX_QcomIndexConfigInterlaced:" " NoMore Interlaced formats"); eRet = OMX_ErrorNoMore; } } else { DEBUG_PRINT_ERROR("get_config: Bad port index %d queried on only o/p port", (int)configFmt->nPortIndex); eRet = OMX_ErrorBadPortIndex; } break; } case OMX_QcomIndexQueryNumberOfVideoDecInstance: { QOMX_VIDEO_QUERY_DECODER_INSTANCES *decoderinstances = (QOMX_VIDEO_QUERY_DECODER_INSTANCES*)configData; decoderinstances->nNumOfInstances = 16; /*TODO: How to handle this case */ break; } case OMX_QcomIndexConfigVideoFramePackingArrangement: { if (drv_ctx.decoder_format == VDEC_CODECTYPE_H264) { OMX_QCOM_FRAME_PACK_ARRANGEMENT *configFmt = (OMX_QCOM_FRAME_PACK_ARRANGEMENT *) configData; memcpy(configFmt, &m_frame_pack_arrangement, sizeof(OMX_QCOM_FRAME_PACK_ARRANGEMENT)); } else { DEBUG_PRINT_ERROR("get_config: Framepack data not supported for non H264 codecs"); } break; } case OMX_IndexConfigCommonOutputCrop: { OMX_CONFIG_RECTTYPE *rect = (OMX_CONFIG_RECTTYPE *) configData; memcpy(rect, &rectangle, sizeof(OMX_CONFIG_RECTTYPE)); DEBUG_PRINT_HIGH("get_config: crop info: L: %u, T: %u, R: %u, B: %u", rectangle.nLeft, rectangle.nTop, rectangle.nWidth, rectangle.nHeight); break; } case OMX_QcomIndexConfigPerfLevel: { struct v4l2_control control; OMX_QCOM_VIDEO_CONFIG_PERF_LEVEL *perf = (OMX_QCOM_VIDEO_CONFIG_PERF_LEVEL *)configData; control.id = V4L2_CID_MPEG_VIDC_SET_PERF_LEVEL; if (ioctl(drv_ctx.video_driver_fd, VIDIOC_G_CTRL, &control) < 0) { DEBUG_PRINT_ERROR("Failed getting performance level: %d", errno); eRet = OMX_ErrorHardware; } if (eRet == OMX_ErrorNone) { switch (control.value) { case V4L2_CID_MPEG_VIDC_PERF_LEVEL_TURBO: perf->ePerfLevel = OMX_QCOM_PerfLevelTurbo; break; default: DEBUG_PRINT_HIGH("Unknown perf level %d, reporting Nominal instead", control.value); /* Fall through */ case V4L2_CID_MPEG_VIDC_PERF_LEVEL_NOMINAL: perf->ePerfLevel = OMX_QCOM_PerfLevelNominal; break; } } break; } default: { DEBUG_PRINT_ERROR("get_config: unknown param %d",configIndex); eRet = OMX_ErrorBadParameter; } } return eRet; } Commit Message: DO NOT MERGE mm-video-v4l2: vidc: validate omx param/config data Check the sanity of config/param strcuture objects passed to get/set _ config()/parameter() methods. Bug: 27533317 Security Vulnerability in MediaServer omx_vdec::get_config() Can lead to arbitrary write Change-Id: I6c3243afe12055ab94f1a1ecf758c10e88231809 Conflicts: mm-core/inc/OMX_QCOMExtns.h mm-video-v4l2/vidc/vdec/src/omx_vdec_msm8974.cpp mm-video-v4l2/vidc/venc/src/omx_video_base.cpp mm-video-v4l2/vidc/venc/src/omx_video_encoder.cpp CWE ID: CWE-20
OMX_ERRORTYPE omx_vdec::get_config(OMX_IN OMX_HANDLETYPE hComp, OMX_IN OMX_INDEXTYPE configIndex, OMX_INOUT OMX_PTR configData) { (void) hComp; OMX_ERRORTYPE eRet = OMX_ErrorNone; if (m_state == OMX_StateInvalid) { DEBUG_PRINT_ERROR("Get Config in Invalid State"); return OMX_ErrorInvalidState; } switch ((unsigned long)configIndex) { case OMX_QcomIndexConfigInterlaced: { VALIDATE_OMX_PARAM_DATA(configData, OMX_QCOM_CONFIG_INTERLACETYPE); OMX_QCOM_CONFIG_INTERLACETYPE *configFmt = (OMX_QCOM_CONFIG_INTERLACETYPE *) configData; if (configFmt->nPortIndex == 1) { if (configFmt->nIndex == 0) { configFmt->eInterlaceType = OMX_QCOM_InterlaceFrameProgressive; } else if (configFmt->nIndex == 1) { configFmt->eInterlaceType = OMX_QCOM_InterlaceInterleaveFrameTopFieldFirst; } else if (configFmt->nIndex == 2) { configFmt->eInterlaceType = OMX_QCOM_InterlaceInterleaveFrameBottomFieldFirst; } else { DEBUG_PRINT_ERROR("get_config: OMX_QcomIndexConfigInterlaced:" " NoMore Interlaced formats"); eRet = OMX_ErrorNoMore; } } else { DEBUG_PRINT_ERROR("get_config: Bad port index %d queried on only o/p port", (int)configFmt->nPortIndex); eRet = OMX_ErrorBadPortIndex; } break; } case OMX_QcomIndexQueryNumberOfVideoDecInstance: { VALIDATE_OMX_PARAM_DATA(configData, QOMX_VIDEO_QUERY_DECODER_INSTANCES); QOMX_VIDEO_QUERY_DECODER_INSTANCES *decoderinstances = (QOMX_VIDEO_QUERY_DECODER_INSTANCES*)configData; decoderinstances->nNumOfInstances = 16; /*TODO: How to handle this case */ break; } case OMX_QcomIndexConfigVideoFramePackingArrangement: { if (drv_ctx.decoder_format == VDEC_CODECTYPE_H264) { VALIDATE_OMX_PARAM_DATA(configData, OMX_QCOM_FRAME_PACK_ARRANGEMENT); OMX_QCOM_FRAME_PACK_ARRANGEMENT *configFmt = (OMX_QCOM_FRAME_PACK_ARRANGEMENT *) configData; memcpy(configFmt, &m_frame_pack_arrangement, sizeof(OMX_QCOM_FRAME_PACK_ARRANGEMENT)); } else { DEBUG_PRINT_ERROR("get_config: Framepack data not supported for non H264 codecs"); } break; } case OMX_IndexConfigCommonOutputCrop: { VALIDATE_OMX_PARAM_DATA(configData, OMX_CONFIG_RECTTYPE); OMX_CONFIG_RECTTYPE *rect = (OMX_CONFIG_RECTTYPE *) configData; memcpy(rect, &rectangle, sizeof(OMX_CONFIG_RECTTYPE)); DEBUG_PRINT_HIGH("get_config: crop info: L: %u, T: %u, R: %u, B: %u", rectangle.nLeft, rectangle.nTop, rectangle.nWidth, rectangle.nHeight); break; } case OMX_QcomIndexConfigPerfLevel: { VALIDATE_OMX_PARAM_DATA(configData, OMX_QCOM_VIDEO_CONFIG_PERF_LEVEL); struct v4l2_control control; OMX_QCOM_VIDEO_CONFIG_PERF_LEVEL *perf = (OMX_QCOM_VIDEO_CONFIG_PERF_LEVEL *)configData; control.id = V4L2_CID_MPEG_VIDC_SET_PERF_LEVEL; if (ioctl(drv_ctx.video_driver_fd, VIDIOC_G_CTRL, &control) < 0) { DEBUG_PRINT_ERROR("Failed getting performance level: %d", errno); eRet = OMX_ErrorHardware; } if (eRet == OMX_ErrorNone) { switch (control.value) { case V4L2_CID_MPEG_VIDC_PERF_LEVEL_TURBO: perf->ePerfLevel = OMX_QCOM_PerfLevelTurbo; break; default: DEBUG_PRINT_HIGH("Unknown perf level %d, reporting Nominal instead", control.value); /* Fall through */ case V4L2_CID_MPEG_VIDC_PERF_LEVEL_NOMINAL: perf->ePerfLevel = OMX_QCOM_PerfLevelNominal; break; } } break; } default: { DEBUG_PRINT_ERROR("get_config: unknown param %d",configIndex); eRet = OMX_ErrorBadParameter; } } return eRet; }
173,788
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void HTMLMediaElement::ChangeNetworkStateFromLoadingToIdle() { progress_event_timer_.Stop(); if (GetWebMediaPlayer() && GetWebMediaPlayer()->DidLoadingProgress()) ScheduleEvent(EventTypeNames::progress); ScheduleEvent(EventTypeNames::suspend); SetNetworkState(kNetworkIdle); } 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::ChangeNetworkStateFromLoadingToIdle() { progress_event_timer_.Stop(); if (!MediaShouldBeOpaque()) { // Schedule one last progress event so we guarantee that at least one is // fired for files that load very quickly. if (GetWebMediaPlayer() && GetWebMediaPlayer()->DidLoadingProgress()) ScheduleEvent(EventTypeNames::progress); ScheduleEvent(EventTypeNames::suspend); SetNetworkState(kNetworkIdle); } }
173,161
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bgp_capabilities_print(netdissect_options *ndo, const u_char *opt, int caps_len) { int cap_type, cap_len, tcap_len, cap_offset; int i = 0; while (i < caps_len) { ND_TCHECK2(opt[i], BGP_CAP_HEADER_SIZE); cap_type=opt[i]; cap_len=opt[i+1]; tcap_len=cap_len; ND_PRINT((ndo, "\n\t %s (%u), length: %u", tok2str(bgp_capcode_values, "Unknown", cap_type), cap_type, cap_len)); ND_TCHECK2(opt[i+2], cap_len); switch (cap_type) { case BGP_CAPCODE_MP: ND_PRINT((ndo, "\n\t\tAFI %s (%u), SAFI %s (%u)", tok2str(af_values, "Unknown", EXTRACT_16BITS(opt+i+2)), EXTRACT_16BITS(opt+i+2), tok2str(bgp_safi_values, "Unknown", opt[i+5]), opt[i+5])); break; case BGP_CAPCODE_RESTART: /* Restart Flags (4 bits), Restart Time in seconds (12 bits) */ ND_TCHECK_16BITS(opt + i + 2); ND_PRINT((ndo, "\n\t\tRestart Flags: [%s], Restart Time %us", ((opt[i+2])&0x80) ? "R" : "none", EXTRACT_16BITS(opt+i+2)&0xfff)); tcap_len-=2; cap_offset=4; while(tcap_len>=4) { ND_PRINT((ndo, "\n\t\t AFI %s (%u), SAFI %s (%u), Forwarding state preserved: %s", tok2str(af_values,"Unknown", EXTRACT_16BITS(opt+i+cap_offset)), EXTRACT_16BITS(opt+i+cap_offset), tok2str(bgp_safi_values,"Unknown", opt[i+cap_offset+2]), opt[i+cap_offset+2], ((opt[i+cap_offset+3])&0x80) ? "yes" : "no" )); tcap_len-=4; cap_offset+=4; } break; case BGP_CAPCODE_RR: case BGP_CAPCODE_RR_CISCO: break; case BGP_CAPCODE_AS_NEW: /* * Extract the 4 byte AS number encoded. */ if (cap_len == 4) { ND_PRINT((ndo, "\n\t\t 4 Byte AS %s", as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(opt + i + 2)))); } break; case BGP_CAPCODE_ADD_PATH: cap_offset=2; if (tcap_len == 0) { ND_PRINT((ndo, " (bogus)")); /* length */ break; } while (tcap_len > 0) { if (tcap_len < 4) { ND_PRINT((ndo, "\n\t\t(invalid)")); break; } ND_PRINT((ndo, "\n\t\tAFI %s (%u), SAFI %s (%u), Send/Receive: %s", tok2str(af_values,"Unknown",EXTRACT_16BITS(opt+i+cap_offset)), EXTRACT_16BITS(opt+i+cap_offset), tok2str(bgp_safi_values,"Unknown",opt[i+cap_offset+2]), opt[i+cap_offset+2], tok2str(bgp_add_path_recvsend,"Bogus (0x%02x)",opt[i+cap_offset+3]) )); tcap_len-=4; cap_offset+=4; } break; default: ND_PRINT((ndo, "\n\t\tno decoder for Capability %u", cap_type)); if (ndo->ndo_vflag <= 1) print_unknown_data(ndo, &opt[i+2], "\n\t\t", cap_len); break; } if (ndo->ndo_vflag > 1 && cap_len > 0) { print_unknown_data(ndo, &opt[i+2], "\n\t\t", cap_len); } i += BGP_CAP_HEADER_SIZE + cap_len; } return; trunc: ND_PRINT((ndo, "[|BGP]")); } Commit Message: (for 4.9.3) CVE-2018-14467/BGP: Fix BGP_CAPCODE_MP. Add a bounds check and a comment to bgp_capabilities_print(). This fixes a buffer over-read discovered by Bhargava Shastry, SecT/TU Berlin. Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-125
bgp_capabilities_print(netdissect_options *ndo, const u_char *opt, int caps_len) { int cap_type, cap_len, tcap_len, cap_offset; int i = 0; while (i < caps_len) { ND_TCHECK2(opt[i], BGP_CAP_HEADER_SIZE); cap_type=opt[i]; cap_len=opt[i+1]; tcap_len=cap_len; ND_PRINT((ndo, "\n\t %s (%u), length: %u", tok2str(bgp_capcode_values, "Unknown", cap_type), cap_type, cap_len)); ND_TCHECK2(opt[i+2], cap_len); switch (cap_type) { case BGP_CAPCODE_MP: /* AFI (16 bits), Reserved (8 bits), SAFI (8 bits) */ ND_TCHECK_8BITS(opt + i + 5); ND_PRINT((ndo, "\n\t\tAFI %s (%u), SAFI %s (%u)", tok2str(af_values, "Unknown", EXTRACT_16BITS(opt+i+2)), EXTRACT_16BITS(opt+i+2), tok2str(bgp_safi_values, "Unknown", opt[i+5]), opt[i+5])); break; case BGP_CAPCODE_RESTART: /* Restart Flags (4 bits), Restart Time in seconds (12 bits) */ ND_TCHECK_16BITS(opt + i + 2); ND_PRINT((ndo, "\n\t\tRestart Flags: [%s], Restart Time %us", ((opt[i+2])&0x80) ? "R" : "none", EXTRACT_16BITS(opt+i+2)&0xfff)); tcap_len-=2; cap_offset=4; while(tcap_len>=4) { ND_PRINT((ndo, "\n\t\t AFI %s (%u), SAFI %s (%u), Forwarding state preserved: %s", tok2str(af_values,"Unknown", EXTRACT_16BITS(opt+i+cap_offset)), EXTRACT_16BITS(opt+i+cap_offset), tok2str(bgp_safi_values,"Unknown", opt[i+cap_offset+2]), opt[i+cap_offset+2], ((opt[i+cap_offset+3])&0x80) ? "yes" : "no" )); tcap_len-=4; cap_offset+=4; } break; case BGP_CAPCODE_RR: case BGP_CAPCODE_RR_CISCO: break; case BGP_CAPCODE_AS_NEW: /* * Extract the 4 byte AS number encoded. */ if (cap_len == 4) { ND_PRINT((ndo, "\n\t\t 4 Byte AS %s", as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(opt + i + 2)))); } break; case BGP_CAPCODE_ADD_PATH: cap_offset=2; if (tcap_len == 0) { ND_PRINT((ndo, " (bogus)")); /* length */ break; } while (tcap_len > 0) { if (tcap_len < 4) { ND_PRINT((ndo, "\n\t\t(invalid)")); break; } ND_PRINT((ndo, "\n\t\tAFI %s (%u), SAFI %s (%u), Send/Receive: %s", tok2str(af_values,"Unknown",EXTRACT_16BITS(opt+i+cap_offset)), EXTRACT_16BITS(opt+i+cap_offset), tok2str(bgp_safi_values,"Unknown",opt[i+cap_offset+2]), opt[i+cap_offset+2], tok2str(bgp_add_path_recvsend,"Bogus (0x%02x)",opt[i+cap_offset+3]) )); tcap_len-=4; cap_offset+=4; } break; default: ND_PRINT((ndo, "\n\t\tno decoder for Capability %u", cap_type)); if (ndo->ndo_vflag <= 1) print_unknown_data(ndo, &opt[i+2], "\n\t\t", cap_len); break; } if (ndo->ndo_vflag > 1 && cap_len > 0) { print_unknown_data(ndo, &opt[i+2], "\n\t\t", cap_len); } i += BGP_CAP_HEADER_SIZE + cap_len; } return; trunc: ND_PRINT((ndo, "[|BGP]")); }
169,844
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int ntlm_read_message_fields_buffer(wStream* s, NTLM_MESSAGE_FIELDS* fields) { if (fields->Len > 0) { if ((fields->BufferOffset + fields->Len) > Stream_Length(s)) return -1; fields->Buffer = (PBYTE) malloc(fields->Len); if (!fields->Buffer) return -1; Stream_SetPosition(s, fields->BufferOffset); Stream_Read(s, fields->Buffer, fields->Len); } return 1; } Commit Message: Fixed CVE-2018-8789 Thanks to Eyal Itkin from Check Point Software Technologies. CWE ID: CWE-125
int ntlm_read_message_fields_buffer(wStream* s, NTLM_MESSAGE_FIELDS* fields) static int ntlm_read_message_fields_buffer(wStream* s, NTLM_MESSAGE_FIELDS* fields) { if (fields->Len > 0) { const UINT64 offset = (UINT64)fields->BufferOffset + (UINT64)fields->Len; if (offset > Stream_Length(s)) return -1; fields->Buffer = (PBYTE) malloc(fields->Len); if (!fields->Buffer) return -1; Stream_SetPosition(s, fields->BufferOffset); Stream_Read(s, fields->Buffer, fields->Len); } return 1; }
169,277
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void CancelHandwriting(int n_strokes) { IBusInputContext* context = GetInputContext(input_context_path_, ibus_); if (!context) { return; } ibus_input_context_cancel_hand_writing(context, n_strokes); g_object_unref(context); } 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 CancelHandwriting(int n_strokes) { // IBusController override. virtual void CancelHandwriting(int n_strokes) { IBusInputContext* context = GetInputContext(input_context_path_, ibus_); if (!context) { return; } ibus_input_context_cancel_hand_writing(context, n_strokes); g_object_unref(context); }
170,518
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int kwajd_read_headers(struct mspack_system *sys, struct mspack_file *fh, struct mskwajd_header *hdr) { unsigned char buf[16]; int i; /* read in the header */ if (sys->read(fh, &buf[0], kwajh_SIZEOF) != kwajh_SIZEOF) { return MSPACK_ERR_READ; } /* check for "KWAJ" signature */ if (((unsigned int) EndGetI32(&buf[kwajh_Signature1]) != 0x4A41574B) || ((unsigned int) EndGetI32(&buf[kwajh_Signature2]) != 0xD127F088)) { return MSPACK_ERR_SIGNATURE; } /* basic header fields */ hdr->comp_type = EndGetI16(&buf[kwajh_CompMethod]); hdr->data_offset = EndGetI16(&buf[kwajh_DataOffset]); hdr->headers = EndGetI16(&buf[kwajh_Flags]); hdr->length = 0; hdr->filename = NULL; hdr->extra = NULL; hdr->extra_length = 0; /* optional headers */ /* 4 bytes: length of unpacked file */ if (hdr->headers & MSKWAJ_HDR_HASLENGTH) { if (sys->read(fh, &buf[0], 4) != 4) return MSPACK_ERR_READ; hdr->length = EndGetI32(&buf[0]); } /* 2 bytes: unknown purpose */ if (hdr->headers & MSKWAJ_HDR_HASUNKNOWN1) { if (sys->read(fh, &buf[0], 2) != 2) return MSPACK_ERR_READ; } /* 2 bytes: length of section, then [length] bytes: unknown purpose */ if (hdr->headers & MSKWAJ_HDR_HASUNKNOWN2) { if (sys->read(fh, &buf[0], 2) != 2) return MSPACK_ERR_READ; i = EndGetI16(&buf[0]); if (sys->seek(fh, (off_t)i, MSPACK_SYS_SEEK_CUR)) return MSPACK_ERR_SEEK; } /* filename and extension */ if (hdr->headers & (MSKWAJ_HDR_HASFILENAME | MSKWAJ_HDR_HASFILEEXT)) { off_t pos = sys->tell(fh); char *fn = (char *) sys->alloc(sys, (size_t) 13); /* allocate memory for maximum length filename */ if (! fn) return MSPACK_ERR_NOMEMORY; hdr->filename = fn; /* copy filename if present */ if (hdr->headers & MSKWAJ_HDR_HASFILENAME) { if (sys->read(fh, &buf[0], 9) != 9) return MSPACK_ERR_READ; for (i = 0; i < 9; i++, fn++) if (!(*fn = buf[i])) break; pos += (i < 9) ? i+1 : 9; if (sys->seek(fh, pos, MSPACK_SYS_SEEK_START)) return MSPACK_ERR_SEEK; } /* copy extension if present */ if (hdr->headers & MSKWAJ_HDR_HASFILEEXT) { *fn++ = '.'; if (sys->read(fh, &buf[0], 4) != 4) return MSPACK_ERR_READ; for (i = 0; i < 4; i++, fn++) if (!(*fn = buf[i])) break; pos += (i < 4) ? i+1 : 4; if (sys->seek(fh, pos, MSPACK_SYS_SEEK_START)) return MSPACK_ERR_SEEK; } *fn = '\0'; } /* 2 bytes: extra text length then [length] bytes of extra text data */ if (hdr->headers & MSKWAJ_HDR_HASEXTRATEXT) { if (sys->read(fh, &buf[0], 2) != 2) return MSPACK_ERR_READ; i = EndGetI16(&buf[0]); hdr->extra = (char *) sys->alloc(sys, (size_t)i+1); if (! hdr->extra) return MSPACK_ERR_NOMEMORY; if (sys->read(fh, hdr->extra, i) != i) return MSPACK_ERR_READ; hdr->extra[i] = '\0'; hdr->extra_length = i; } return MSPACK_ERR_OK; } Commit Message: kwaj_read_headers(): fix handling of non-terminated strings CWE ID: CWE-787
static int kwajd_read_headers(struct mspack_system *sys, struct mspack_file *fh, struct mskwajd_header *hdr) { unsigned char buf[16]; int i; /* read in the header */ if (sys->read(fh, &buf[0], kwajh_SIZEOF) != kwajh_SIZEOF) { return MSPACK_ERR_READ; } /* check for "KWAJ" signature */ if (((unsigned int) EndGetI32(&buf[kwajh_Signature1]) != 0x4A41574B) || ((unsigned int) EndGetI32(&buf[kwajh_Signature2]) != 0xD127F088)) { return MSPACK_ERR_SIGNATURE; } /* basic header fields */ hdr->comp_type = EndGetI16(&buf[kwajh_CompMethod]); hdr->data_offset = EndGetI16(&buf[kwajh_DataOffset]); hdr->headers = EndGetI16(&buf[kwajh_Flags]); hdr->length = 0; hdr->filename = NULL; hdr->extra = NULL; hdr->extra_length = 0; /* optional headers */ /* 4 bytes: length of unpacked file */ if (hdr->headers & MSKWAJ_HDR_HASLENGTH) { if (sys->read(fh, &buf[0], 4) != 4) return MSPACK_ERR_READ; hdr->length = EndGetI32(&buf[0]); } /* 2 bytes: unknown purpose */ if (hdr->headers & MSKWAJ_HDR_HASUNKNOWN1) { if (sys->read(fh, &buf[0], 2) != 2) return MSPACK_ERR_READ; } /* 2 bytes: length of section, then [length] bytes: unknown purpose */ if (hdr->headers & MSKWAJ_HDR_HASUNKNOWN2) { if (sys->read(fh, &buf[0], 2) != 2) return MSPACK_ERR_READ; i = EndGetI16(&buf[0]); if (sys->seek(fh, (off_t)i, MSPACK_SYS_SEEK_CUR)) return MSPACK_ERR_SEEK; } /* filename and extension */ if (hdr->headers & (MSKWAJ_HDR_HASFILENAME | MSKWAJ_HDR_HASFILEEXT)) { int len; /* allocate memory for maximum length filename */ char *fn = (char *) sys->alloc(sys, (size_t) 13); if (!(hdr->filename = fn)) return MSPACK_ERR_NOMEMORY; /* copy filename if present */ if (hdr->headers & MSKWAJ_HDR_HASFILENAME) { /* read and copy up to 9 bytes of a null terminated string */ if ((len = sys->read(fh, &buf[0], 9)) < 2) return MSPACK_ERR_READ; for (i = 0; i < len; i++) if (!(*fn++ = buf[i])) break; /* if string was 9 bytes with no null terminator, reject it */ if (i == 9 && buf[8] != '\0') return MSPACK_ERR_DATAFORMAT; /* seek to byte after string ended in file */ if (sys->seek(fh, (off_t)(i + 1 - len), MSPACK_SYS_SEEK_CUR)) return MSPACK_ERR_SEEK; fn--; /* remove the null terminator */ } /* copy extension if present */ if (hdr->headers & MSKWAJ_HDR_HASFILEEXT) { *fn++ = '.'; /* read and copy up to 4 bytes of a null terminated string */ if ((len = sys->read(fh, &buf[0], 4)) < 2) return MSPACK_ERR_READ; for (i = 0; i < len; i++) if (!(*fn++ = buf[i])) break; /* if string was 4 bytes with no null terminator, reject it */ if (i == 4 && buf[3] != '\0') return MSPACK_ERR_DATAFORMAT; /* seek to byte after string ended in file */ if (sys->seek(fh, (off_t)(i + 1 - len), MSPACK_SYS_SEEK_CUR)) return MSPACK_ERR_SEEK; fn--; /* remove the null terminator */ } *fn = '\0'; } /* 2 bytes: extra text length then [length] bytes of extra text data */ if (hdr->headers & MSKWAJ_HDR_HASEXTRATEXT) { if (sys->read(fh, &buf[0], 2) != 2) return MSPACK_ERR_READ; i = EndGetI16(&buf[0]); hdr->extra = (char *) sys->alloc(sys, (size_t)i+1); if (! hdr->extra) return MSPACK_ERR_NOMEMORY; if (sys->read(fh, hdr->extra, i) != i) return MSPACK_ERR_READ; hdr->extra[i] = '\0'; hdr->extra_length = i; } return MSPACK_ERR_OK; }
169,111
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void RenderWidgetHostImpl::OnCompositorSurfaceBuffersSwapped( int32 surface_id, uint64 surface_handle, int32 route_id, const gfx::Size& size, int32 gpu_process_host_id) { TRACE_EVENT0("renderer_host", "RenderWidgetHostImpl::OnCompositorSurfaceBuffersSwapped"); if (!view_) { RenderWidgetHostImpl::AcknowledgeBufferPresent(route_id, gpu_process_host_id, false, 0); return; } GpuHostMsg_AcceleratedSurfaceBuffersSwapped_Params gpu_params; gpu_params.surface_id = surface_id; gpu_params.surface_handle = surface_handle; gpu_params.route_id = route_id; gpu_params.size = size; #if defined(OS_MACOSX) gpu_params.window = gfx::kNullPluginWindow; #endif view_->AcceleratedSurfaceBuffersSwapped(gpu_params, gpu_process_host_id); } 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 RenderWidgetHostImpl::OnCompositorSurfaceBuffersSwapped( int32 surface_id, uint64 surface_handle, int32 route_id, const gfx::Size& size, int32 gpu_process_host_id) { TRACE_EVENT0("renderer_host", "RenderWidgetHostImpl::OnCompositorSurfaceBuffersSwapped"); if (!view_) { RenderWidgetHostImpl::AcknowledgeBufferPresent(route_id, gpu_process_host_id, surface_handle, 0); return; } GpuHostMsg_AcceleratedSurfaceBuffersSwapped_Params gpu_params; gpu_params.surface_id = surface_id; gpu_params.surface_handle = surface_handle; gpu_params.route_id = route_id; gpu_params.size = size; #if defined(OS_MACOSX) gpu_params.window = gfx::kNullPluginWindow; #endif view_->AcceleratedSurfaceBuffersSwapped(gpu_params, gpu_process_host_id); }
171,367
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void GpuVideoDecodeAccelerator::Initialize( const media::VideoCodecProfile profile, IPC::Message* init_done_msg, base::ProcessHandle renderer_process) { DCHECK(!video_decode_accelerator_.get()); DCHECK(!init_done_msg_); DCHECK(init_done_msg); init_done_msg_ = init_done_msg; #if (defined(OS_CHROMEOS) && defined(ARCH_CPU_ARMEL)) || defined(OS_WIN) DCHECK(stub_ && stub_->decoder()); #if defined(OS_WIN) if (base::win::GetVersion() < base::win::VERSION_WIN7) { NOTIMPLEMENTED() << "HW video decode acceleration not available."; NotifyError(media::VideoDecodeAccelerator::PLATFORM_FAILURE); return; } DLOG(INFO) << "Initializing DXVA HW decoder for windows."; DXVAVideoDecodeAccelerator* video_decoder = new DXVAVideoDecodeAccelerator(this, renderer_process); #else // OS_WIN OmxVideoDecodeAccelerator* video_decoder = new OmxVideoDecodeAccelerator(this); video_decoder->SetEglState( gfx::GLSurfaceEGL::GetHardwareDisplay(), stub_->decoder()->GetGLContext()->GetHandle()); #endif // OS_WIN video_decode_accelerator_ = video_decoder; if (!video_decode_accelerator_->Initialize(profile)) NotifyError(media::VideoDecodeAccelerator::PLATFORM_FAILURE); #else // Update RenderViewImpl::createMediaPlayer when adding clauses. NOTIMPLEMENTED() << "HW video decode acceleration not available."; NotifyError(media::VideoDecodeAccelerator::PLATFORM_FAILURE); #endif // defined(OS_CHROMEOS) && defined(ARCH_CPU_ARMEL) } Commit Message: Convert plugin and GPU process to brokered handle duplication. BUG=119250 Review URL: https://chromiumcodereview.appspot.com/9958034 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132303 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
void GpuVideoDecodeAccelerator::Initialize( const media::VideoCodecProfile profile, IPC::Message* init_done_msg) { DCHECK(!video_decode_accelerator_.get()); DCHECK(!init_done_msg_); DCHECK(init_done_msg); init_done_msg_ = init_done_msg; #if (defined(OS_CHROMEOS) && defined(ARCH_CPU_ARMEL)) || defined(OS_WIN) DCHECK(stub_ && stub_->decoder()); #if defined(OS_WIN) if (base::win::GetVersion() < base::win::VERSION_WIN7) { NOTIMPLEMENTED() << "HW video decode acceleration not available."; NotifyError(media::VideoDecodeAccelerator::PLATFORM_FAILURE); return; } DLOG(INFO) << "Initializing DXVA HW decoder for windows."; DXVAVideoDecodeAccelerator* video_decoder = new DXVAVideoDecodeAccelerator(this); #else // OS_WIN OmxVideoDecodeAccelerator* video_decoder = new OmxVideoDecodeAccelerator(this); video_decoder->SetEglState( gfx::GLSurfaceEGL::GetHardwareDisplay(), stub_->decoder()->GetGLContext()->GetHandle()); #endif // OS_WIN video_decode_accelerator_ = video_decoder; if (!video_decode_accelerator_->Initialize(profile)) NotifyError(media::VideoDecodeAccelerator::PLATFORM_FAILURE); #else // Update RenderViewImpl::createMediaPlayer when adding clauses. NOTIMPLEMENTED() << "HW video decode acceleration not available."; NotifyError(media::VideoDecodeAccelerator::PLATFORM_FAILURE); #endif // defined(OS_CHROMEOS) && defined(ARCH_CPU_ARMEL) }
170,942
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int snd_timer_user_params(struct file *file, struct snd_timer_params __user *_params) { struct snd_timer_user *tu; struct snd_timer_params params; struct snd_timer *t; struct snd_timer_read *tr; struct snd_timer_tread *ttr; int err; tu = file->private_data; if (!tu->timeri) return -EBADFD; t = tu->timeri->timer; if (!t) return -EBADFD; if (copy_from_user(&params, _params, sizeof(params))) return -EFAULT; if (!(t->hw.flags & SNDRV_TIMER_HW_SLAVE) && params.ticks < 1) { err = -EINVAL; goto _end; } if (params.queue_size > 0 && (params.queue_size < 32 || params.queue_size > 1024)) { err = -EINVAL; goto _end; } if (params.filter & ~((1<<SNDRV_TIMER_EVENT_RESOLUTION)| (1<<SNDRV_TIMER_EVENT_TICK)| (1<<SNDRV_TIMER_EVENT_START)| (1<<SNDRV_TIMER_EVENT_STOP)| (1<<SNDRV_TIMER_EVENT_CONTINUE)| (1<<SNDRV_TIMER_EVENT_PAUSE)| (1<<SNDRV_TIMER_EVENT_SUSPEND)| (1<<SNDRV_TIMER_EVENT_RESUME)| (1<<SNDRV_TIMER_EVENT_MSTART)| (1<<SNDRV_TIMER_EVENT_MSTOP)| (1<<SNDRV_TIMER_EVENT_MCONTINUE)| (1<<SNDRV_TIMER_EVENT_MPAUSE)| (1<<SNDRV_TIMER_EVENT_MSUSPEND)| (1<<SNDRV_TIMER_EVENT_MRESUME))) { err = -EINVAL; goto _end; } snd_timer_stop(tu->timeri); spin_lock_irq(&t->lock); tu->timeri->flags &= ~(SNDRV_TIMER_IFLG_AUTO| SNDRV_TIMER_IFLG_EXCLUSIVE| SNDRV_TIMER_IFLG_EARLY_EVENT); if (params.flags & SNDRV_TIMER_PSFLG_AUTO) tu->timeri->flags |= SNDRV_TIMER_IFLG_AUTO; if (params.flags & SNDRV_TIMER_PSFLG_EXCLUSIVE) tu->timeri->flags |= SNDRV_TIMER_IFLG_EXCLUSIVE; if (params.flags & SNDRV_TIMER_PSFLG_EARLY_EVENT) tu->timeri->flags |= SNDRV_TIMER_IFLG_EARLY_EVENT; spin_unlock_irq(&t->lock); if (params.queue_size > 0 && (unsigned int)tu->queue_size != params.queue_size) { if (tu->tread) { ttr = kmalloc(params.queue_size * sizeof(*ttr), GFP_KERNEL); if (ttr) { kfree(tu->tqueue); tu->queue_size = params.queue_size; tu->tqueue = ttr; } } else { tr = kmalloc(params.queue_size * sizeof(*tr), GFP_KERNEL); if (tr) { kfree(tu->queue); tu->queue_size = params.queue_size; tu->queue = tr; } } } tu->qhead = tu->qtail = tu->qused = 0; if (tu->timeri->flags & SNDRV_TIMER_IFLG_EARLY_EVENT) { if (tu->tread) { struct snd_timer_tread tread; tread.event = SNDRV_TIMER_EVENT_EARLY; tread.tstamp.tv_sec = 0; tread.tstamp.tv_nsec = 0; tread.val = 0; snd_timer_user_append_to_tqueue(tu, &tread); } else { struct snd_timer_read *r = &tu->queue[0]; r->resolution = 0; r->ticks = 0; tu->qused++; tu->qtail++; } } tu->filter = params.filter; tu->ticks = params.ticks; err = 0; _end: if (copy_to_user(_params, &params, sizeof(params))) return -EFAULT; return err; } Commit Message: ALSA: timer: Fix leak in SNDRV_TIMER_IOCTL_PARAMS The stack object “tread” has a total size of 32 bytes. Its field “event” and “val” both contain 4 bytes padding. These 8 bytes padding bytes are sent to user without being initialized. Signed-off-by: Kangjie Lu <kjlu@gatech.edu> Signed-off-by: Takashi Iwai <tiwai@suse.de> CWE ID: CWE-200
static int snd_timer_user_params(struct file *file, struct snd_timer_params __user *_params) { struct snd_timer_user *tu; struct snd_timer_params params; struct snd_timer *t; struct snd_timer_read *tr; struct snd_timer_tread *ttr; int err; tu = file->private_data; if (!tu->timeri) return -EBADFD; t = tu->timeri->timer; if (!t) return -EBADFD; if (copy_from_user(&params, _params, sizeof(params))) return -EFAULT; if (!(t->hw.flags & SNDRV_TIMER_HW_SLAVE) && params.ticks < 1) { err = -EINVAL; goto _end; } if (params.queue_size > 0 && (params.queue_size < 32 || params.queue_size > 1024)) { err = -EINVAL; goto _end; } if (params.filter & ~((1<<SNDRV_TIMER_EVENT_RESOLUTION)| (1<<SNDRV_TIMER_EVENT_TICK)| (1<<SNDRV_TIMER_EVENT_START)| (1<<SNDRV_TIMER_EVENT_STOP)| (1<<SNDRV_TIMER_EVENT_CONTINUE)| (1<<SNDRV_TIMER_EVENT_PAUSE)| (1<<SNDRV_TIMER_EVENT_SUSPEND)| (1<<SNDRV_TIMER_EVENT_RESUME)| (1<<SNDRV_TIMER_EVENT_MSTART)| (1<<SNDRV_TIMER_EVENT_MSTOP)| (1<<SNDRV_TIMER_EVENT_MCONTINUE)| (1<<SNDRV_TIMER_EVENT_MPAUSE)| (1<<SNDRV_TIMER_EVENT_MSUSPEND)| (1<<SNDRV_TIMER_EVENT_MRESUME))) { err = -EINVAL; goto _end; } snd_timer_stop(tu->timeri); spin_lock_irq(&t->lock); tu->timeri->flags &= ~(SNDRV_TIMER_IFLG_AUTO| SNDRV_TIMER_IFLG_EXCLUSIVE| SNDRV_TIMER_IFLG_EARLY_EVENT); if (params.flags & SNDRV_TIMER_PSFLG_AUTO) tu->timeri->flags |= SNDRV_TIMER_IFLG_AUTO; if (params.flags & SNDRV_TIMER_PSFLG_EXCLUSIVE) tu->timeri->flags |= SNDRV_TIMER_IFLG_EXCLUSIVE; if (params.flags & SNDRV_TIMER_PSFLG_EARLY_EVENT) tu->timeri->flags |= SNDRV_TIMER_IFLG_EARLY_EVENT; spin_unlock_irq(&t->lock); if (params.queue_size > 0 && (unsigned int)tu->queue_size != params.queue_size) { if (tu->tread) { ttr = kmalloc(params.queue_size * sizeof(*ttr), GFP_KERNEL); if (ttr) { kfree(tu->tqueue); tu->queue_size = params.queue_size; tu->tqueue = ttr; } } else { tr = kmalloc(params.queue_size * sizeof(*tr), GFP_KERNEL); if (tr) { kfree(tu->queue); tu->queue_size = params.queue_size; tu->queue = tr; } } } tu->qhead = tu->qtail = tu->qused = 0; if (tu->timeri->flags & SNDRV_TIMER_IFLG_EARLY_EVENT) { if (tu->tread) { struct snd_timer_tread tread; memset(&tread, 0, sizeof(tread)); tread.event = SNDRV_TIMER_EVENT_EARLY; tread.tstamp.tv_sec = 0; tread.tstamp.tv_nsec = 0; tread.val = 0; snd_timer_user_append_to_tqueue(tu, &tread); } else { struct snd_timer_read *r = &tu->queue[0]; r->resolution = 0; r->ticks = 0; tu->qused++; tu->qtail++; } } tu->filter = params.filter; tu->ticks = params.ticks; err = 0; _end: if (copy_to_user(_params, &params, sizeof(params))) return -EFAULT; return err; }
167,237
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool WebMediaPlayerImpl::HasSingleSecurityOrigin() const { if (data_source_) return data_source_->HasSingleOrigin(); return true; } Commit Message: Fix HasSingleSecurityOrigin for HLS HLS manifests can request segments from a different origin than the original manifest's origin. We do not inspect HLS manifests within Chromium, and instead delegate to Android's MediaPlayer. This means we need to be conservative, and always assume segments might come from a different origin. HasSingleSecurityOrigin should always return false when decoding HLS. Bug: 864283 Change-Id: Ie16849ac6f29ae7eaa9caf342ad0509a226228ef Reviewed-on: https://chromium-review.googlesource.com/1142691 Reviewed-by: Dale Curtis <dalecurtis@chromium.org> Reviewed-by: Dominick Ng <dominickn@chromium.org> Commit-Queue: Thomas Guilbert <tguilbert@chromium.org> Cr-Commit-Position: refs/heads/master@{#576378} CWE ID: CWE-346
bool WebMediaPlayerImpl::HasSingleSecurityOrigin() const { if (demuxer_found_hls_) { // HLS manifests might pull segments from a different origin. We can't know // for sure, so we conservatively say no here. return false; } if (data_source_) return data_source_->HasSingleOrigin(); return true; }
173,178
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void locationWithPerWorldBindingsAttributeSetter(v8::Local<v8::Value> jsValue, const v8::PropertyCallbackInfo<void>& info) { TestObjectPython* proxyImp = V8TestObjectPython::toNative(info.Holder()); TestNode* imp = WTF::getPtr(proxyImp->locationWithPerWorldBindings()); if (!imp) return; V8TRYCATCH_FOR_V8STRINGRESOURCE_VOID(V8StringResource<>, cppValue, jsValue); imp->setHref(cppValue); } Commit Message: document.location bindings fix BUG=352374 R=jochen@chromium.org Review URL: https://codereview.chromium.org/196343011 git-svn-id: svn://svn.chromium.org/blink/trunk@169176 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399
static void locationWithPerWorldBindingsAttributeSetter(v8::Local<v8::Value> jsValue, const v8::PropertyCallbackInfo<void>& info) { TestObjectPython* proxyImp = V8TestObjectPython::toNative(info.Holder()); RefPtr<TestNode> imp = WTF::getPtr(proxyImp->locationWithPerWorldBindings()); if (!imp) return; V8TRYCATCH_FOR_V8STRINGRESOURCE_VOID(V8StringResource<>, cppValue, jsValue); imp->setHref(cppValue); }
171,689
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: OMX_ERRORTYPE SoftAACEncoder::internalGetParameter( OMX_INDEXTYPE index, OMX_PTR params) { switch (index) { case OMX_IndexParamAudioPortFormat: { OMX_AUDIO_PARAM_PORTFORMATTYPE *formatParams = (OMX_AUDIO_PARAM_PORTFORMATTYPE *)params; if (formatParams->nPortIndex > 1) { return OMX_ErrorUndefined; } if (formatParams->nIndex > 0) { return OMX_ErrorNoMore; } formatParams->eEncoding = (formatParams->nPortIndex == 0) ? OMX_AUDIO_CodingPCM : OMX_AUDIO_CodingAAC; return OMX_ErrorNone; } case OMX_IndexParamAudioAac: { OMX_AUDIO_PARAM_AACPROFILETYPE *aacParams = (OMX_AUDIO_PARAM_AACPROFILETYPE *)params; if (aacParams->nPortIndex != 1) { return OMX_ErrorUndefined; } aacParams->nBitRate = mBitRate; aacParams->nAudioBandWidth = 0; aacParams->nAACtools = 0; aacParams->nAACERtools = 0; aacParams->eAACProfile = OMX_AUDIO_AACObjectMain; aacParams->eAACStreamFormat = OMX_AUDIO_AACStreamFormatMP4FF; aacParams->eChannelMode = OMX_AUDIO_ChannelModeStereo; aacParams->nChannels = mNumChannels; aacParams->nSampleRate = mSampleRate; aacParams->nFrameLength = 0; return OMX_ErrorNone; } case OMX_IndexParamAudioPcm: { OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams = (OMX_AUDIO_PARAM_PCMMODETYPE *)params; if (pcmParams->nPortIndex != 0) { return OMX_ErrorUndefined; } pcmParams->eNumData = OMX_NumericalDataSigned; pcmParams->eEndian = OMX_EndianBig; pcmParams->bInterleaved = OMX_TRUE; pcmParams->nBitPerSample = 16; pcmParams->ePCMMode = OMX_AUDIO_PCMModeLinear; pcmParams->eChannelMapping[0] = OMX_AUDIO_ChannelLF; pcmParams->eChannelMapping[1] = OMX_AUDIO_ChannelRF; pcmParams->nChannels = mNumChannels; pcmParams->nSamplingRate = mSampleRate; return OMX_ErrorNone; } default: return SimpleSoftOMXComponent::internalGetParameter(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 SoftAACEncoder::internalGetParameter( OMX_INDEXTYPE index, OMX_PTR params) { switch (index) { case OMX_IndexParamAudioPortFormat: { OMX_AUDIO_PARAM_PORTFORMATTYPE *formatParams = (OMX_AUDIO_PARAM_PORTFORMATTYPE *)params; if (!isValidOMXParam(formatParams)) { return OMX_ErrorBadParameter; } if (formatParams->nPortIndex > 1) { return OMX_ErrorUndefined; } if (formatParams->nIndex > 0) { return OMX_ErrorNoMore; } formatParams->eEncoding = (formatParams->nPortIndex == 0) ? OMX_AUDIO_CodingPCM : OMX_AUDIO_CodingAAC; return OMX_ErrorNone; } case OMX_IndexParamAudioAac: { OMX_AUDIO_PARAM_AACPROFILETYPE *aacParams = (OMX_AUDIO_PARAM_AACPROFILETYPE *)params; if (!isValidOMXParam(aacParams)) { return OMX_ErrorBadParameter; } if (aacParams->nPortIndex != 1) { return OMX_ErrorUndefined; } aacParams->nBitRate = mBitRate; aacParams->nAudioBandWidth = 0; aacParams->nAACtools = 0; aacParams->nAACERtools = 0; aacParams->eAACProfile = OMX_AUDIO_AACObjectMain; aacParams->eAACStreamFormat = OMX_AUDIO_AACStreamFormatMP4FF; aacParams->eChannelMode = OMX_AUDIO_ChannelModeStereo; aacParams->nChannels = mNumChannels; aacParams->nSampleRate = mSampleRate; aacParams->nFrameLength = 0; return OMX_ErrorNone; } case OMX_IndexParamAudioPcm: { OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams = (OMX_AUDIO_PARAM_PCMMODETYPE *)params; if (!isValidOMXParam(pcmParams)) { return OMX_ErrorBadParameter; } if (pcmParams->nPortIndex != 0) { return OMX_ErrorUndefined; } pcmParams->eNumData = OMX_NumericalDataSigned; pcmParams->eEndian = OMX_EndianBig; pcmParams->bInterleaved = OMX_TRUE; pcmParams->nBitPerSample = 16; pcmParams->ePCMMode = OMX_AUDIO_PCMModeLinear; pcmParams->eChannelMapping[0] = OMX_AUDIO_ChannelLF; pcmParams->eChannelMapping[1] = OMX_AUDIO_ChannelRF; pcmParams->nChannels = mNumChannels; pcmParams->nSamplingRate = mSampleRate; return OMX_ErrorNone; } default: return SimpleSoftOMXComponent::internalGetParameter(index, params); } }
174,188
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void DownloadManagerImpl::CreateNewDownloadItemToStart( std::unique_ptr<download::DownloadCreateInfo> info, const download::DownloadUrlParameters::OnStartedCallback& on_started, download::InProgressDownloadManager::StartDownloadItemCallback callback, uint32_t id) { DCHECK_CURRENTLY_ON(BrowserThread::UI); download::DownloadItemImpl* download = CreateActiveItem(id, *info); std::move(callback).Run(std::move(info), download, should_persist_new_download_); for (auto& observer : observers_) observer.OnDownloadCreated(this, download); OnNewDownloadCreated(download); OnDownloadStarted(download, on_started); } Commit Message: Early return if a download Id is already used when creating a download This is protect against download Id overflow and use-after-free issue. BUG=958533 Change-Id: I2c183493cb09106686df9822b3987bfb95bcf720 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1591485 Reviewed-by: Xing Liu <xingliu@chromium.org> Commit-Queue: Min Qin <qinmin@chromium.org> Cr-Commit-Position: refs/heads/master@{#656910} CWE ID: CWE-416
void DownloadManagerImpl::CreateNewDownloadItemToStart( std::unique_ptr<download::DownloadCreateInfo> info, const download::DownloadUrlParameters::OnStartedCallback& on_started, download::InProgressDownloadManager::StartDownloadItemCallback callback, uint32_t id) { DCHECK_CURRENTLY_ON(BrowserThread::UI); download::DownloadItemImpl* download = CreateActiveItem(id, *info); std::move(callback).Run(std::move(info), download, should_persist_new_download_); if (download) { // For new downloads, we notify here, rather than earlier, so that // the download_file is bound to download and all the usual // setters (e.g. Cancel) work. for (auto& observer : observers_) observer.OnDownloadCreated(this, download); OnNewDownloadCreated(download); } OnDownloadStarted(download, on_started); }
172,966
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: image_transform_png_set_gray_to_rgb_set(PNG_CONST image_transform *this, transform_display *that, png_structp pp, png_infop pi) { png_set_gray_to_rgb(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_gray_to_rgb_set(PNG_CONST image_transform *this, image_transform_png_set_gray_to_rgb_set(const image_transform *this, transform_display *that, png_structp pp, png_infop pi) { png_set_gray_to_rgb(pp); /* NOTE: this doesn't result in tRNS expansion. */ this->next->set(this->next, that, pp, pi); }
173,637
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void snd_timer_interrupt(struct snd_timer * timer, unsigned long ticks_left) { struct snd_timer_instance *ti, *ts, *tmp; unsigned long resolution, ticks; struct list_head *p, *ack_list_head; unsigned long flags; int use_tasklet = 0; if (timer == NULL) return; spin_lock_irqsave(&timer->lock, flags); /* remember the current resolution */ if (timer->hw.c_resolution) resolution = timer->hw.c_resolution(timer); else resolution = timer->hw.resolution; /* loop for all active instances * Here we cannot use list_for_each_entry because the active_list of a * processed instance is relinked to done_list_head before the callback * is called. */ list_for_each_entry_safe(ti, tmp, &timer->active_list_head, active_list) { if (!(ti->flags & SNDRV_TIMER_IFLG_RUNNING)) continue; ti->pticks += ticks_left; ti->resolution = resolution; if (ti->cticks < ticks_left) ti->cticks = 0; else ti->cticks -= ticks_left; if (ti->cticks) /* not expired */ continue; if (ti->flags & SNDRV_TIMER_IFLG_AUTO) { ti->cticks = ti->ticks; } else { ti->flags &= ~SNDRV_TIMER_IFLG_RUNNING; if (--timer->running) list_del(&ti->active_list); } if ((timer->hw.flags & SNDRV_TIMER_HW_TASKLET) || (ti->flags & SNDRV_TIMER_IFLG_FAST)) ack_list_head = &timer->ack_list_head; else ack_list_head = &timer->sack_list_head; if (list_empty(&ti->ack_list)) list_add_tail(&ti->ack_list, ack_list_head); list_for_each_entry(ts, &ti->slave_active_head, active_list) { ts->pticks = ti->pticks; ts->resolution = resolution; if (list_empty(&ts->ack_list)) list_add_tail(&ts->ack_list, ack_list_head); } } if (timer->flags & SNDRV_TIMER_FLG_RESCHED) snd_timer_reschedule(timer, timer->sticks); if (timer->running) { if (timer->hw.flags & SNDRV_TIMER_HW_STOP) { timer->hw.stop(timer); timer->flags |= SNDRV_TIMER_FLG_CHANGE; } if (!(timer->hw.flags & SNDRV_TIMER_HW_AUTO) || (timer->flags & SNDRV_TIMER_FLG_CHANGE)) { /* restart timer */ timer->flags &= ~SNDRV_TIMER_FLG_CHANGE; timer->hw.start(timer); } } else { timer->hw.stop(timer); } /* now process all fast callbacks */ while (!list_empty(&timer->ack_list_head)) { p = timer->ack_list_head.next; /* get first item */ ti = list_entry(p, struct snd_timer_instance, ack_list); /* remove from ack_list and make empty */ list_del_init(p); ticks = ti->pticks; ti->pticks = 0; ti->flags |= SNDRV_TIMER_IFLG_CALLBACK; spin_unlock(&timer->lock); if (ti->callback) ti->callback(ti, resolution, ticks); spin_lock(&timer->lock); ti->flags &= ~SNDRV_TIMER_IFLG_CALLBACK; } /* do we have any slow callbacks? */ use_tasklet = !list_empty(&timer->sack_list_head); spin_unlock_irqrestore(&timer->lock, flags); if (use_tasklet) tasklet_schedule(&timer->task_queue); } Commit Message: ALSA: timer: Fix double unlink of active_list ALSA timer instance object has a couple of linked lists and they are unlinked unconditionally at snd_timer_stop(). Meanwhile snd_timer_interrupt() unlinks it, but it calls list_del() which leaves the element list itself unchanged. This ends up with unlinking twice, and it was caught by syzkaller fuzzer. The fix is to use list_del_init() variant properly there, too. Reported-by: Dmitry Vyukov <dvyukov@google.com> Tested-by: Dmitry Vyukov <dvyukov@google.com> Cc: <stable@vger.kernel.org> Signed-off-by: Takashi Iwai <tiwai@suse.de> CWE ID: CWE-362
void snd_timer_interrupt(struct snd_timer * timer, unsigned long ticks_left) { struct snd_timer_instance *ti, *ts, *tmp; unsigned long resolution, ticks; struct list_head *p, *ack_list_head; unsigned long flags; int use_tasklet = 0; if (timer == NULL) return; spin_lock_irqsave(&timer->lock, flags); /* remember the current resolution */ if (timer->hw.c_resolution) resolution = timer->hw.c_resolution(timer); else resolution = timer->hw.resolution; /* loop for all active instances * Here we cannot use list_for_each_entry because the active_list of a * processed instance is relinked to done_list_head before the callback * is called. */ list_for_each_entry_safe(ti, tmp, &timer->active_list_head, active_list) { if (!(ti->flags & SNDRV_TIMER_IFLG_RUNNING)) continue; ti->pticks += ticks_left; ti->resolution = resolution; if (ti->cticks < ticks_left) ti->cticks = 0; else ti->cticks -= ticks_left; if (ti->cticks) /* not expired */ continue; if (ti->flags & SNDRV_TIMER_IFLG_AUTO) { ti->cticks = ti->ticks; } else { ti->flags &= ~SNDRV_TIMER_IFLG_RUNNING; if (--timer->running) list_del_init(&ti->active_list); } if ((timer->hw.flags & SNDRV_TIMER_HW_TASKLET) || (ti->flags & SNDRV_TIMER_IFLG_FAST)) ack_list_head = &timer->ack_list_head; else ack_list_head = &timer->sack_list_head; if (list_empty(&ti->ack_list)) list_add_tail(&ti->ack_list, ack_list_head); list_for_each_entry(ts, &ti->slave_active_head, active_list) { ts->pticks = ti->pticks; ts->resolution = resolution; if (list_empty(&ts->ack_list)) list_add_tail(&ts->ack_list, ack_list_head); } } if (timer->flags & SNDRV_TIMER_FLG_RESCHED) snd_timer_reschedule(timer, timer->sticks); if (timer->running) { if (timer->hw.flags & SNDRV_TIMER_HW_STOP) { timer->hw.stop(timer); timer->flags |= SNDRV_TIMER_FLG_CHANGE; } if (!(timer->hw.flags & SNDRV_TIMER_HW_AUTO) || (timer->flags & SNDRV_TIMER_FLG_CHANGE)) { /* restart timer */ timer->flags &= ~SNDRV_TIMER_FLG_CHANGE; timer->hw.start(timer); } } else { timer->hw.stop(timer); } /* now process all fast callbacks */ while (!list_empty(&timer->ack_list_head)) { p = timer->ack_list_head.next; /* get first item */ ti = list_entry(p, struct snd_timer_instance, ack_list); /* remove from ack_list and make empty */ list_del_init(p); ticks = ti->pticks; ti->pticks = 0; ti->flags |= SNDRV_TIMER_IFLG_CALLBACK; spin_unlock(&timer->lock); if (ti->callback) ti->callback(ti, resolution, ticks); spin_lock(&timer->lock); ti->flags &= ~SNDRV_TIMER_IFLG_CALLBACK; } /* do we have any slow callbacks? */ use_tasklet = !list_empty(&timer->sack_list_head); spin_unlock_irqrestore(&timer->lock, flags); if (use_tasklet) tasklet_schedule(&timer->task_queue); }
167,408
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: transform_test(png_modifier *pmIn, PNG_CONST png_uint_32 idIn, PNG_CONST image_transform* transform_listIn, PNG_CONST char * volatile name) { transform_display d; context(&pmIn->this, fault); transform_display_init(&d, pmIn, idIn, transform_listIn); Try { size_t pos = 0; png_structp pp; png_infop pi; char full_name[256]; /* Make sure the encoding fields are correct and enter the required * modifications. */ transform_set_encoding(&d); /* Add any modifications required by the transform list. */ d.transform_list->ini(d.transform_list, &d); /* Add the color space information, if any, to the name. */ pos = safecat(full_name, sizeof full_name, pos, name); pos = safecat_current_encoding(full_name, sizeof full_name, pos, d.pm); /* Get a png_struct for reading the image. */ pp = set_modifier_for_read(d.pm, &pi, d.this.id, full_name); standard_palette_init(&d.this); # if 0 /* Logging (debugging only) */ { char buffer[256]; (void)store_message(&d.pm->this, pp, buffer, sizeof buffer, 0, "running test"); fprintf(stderr, "%s\n", buffer); } # endif /* Introduce the correct read function. */ if (d.pm->this.progressive) { /* Share the row function with the standard implementation. */ png_set_progressive_read_fn(pp, &d, transform_info, progressive_row, transform_end); /* Now feed data into the reader until we reach the end: */ modifier_progressive_read(d.pm, pp, pi); } else { /* modifier_read expects a png_modifier* */ png_set_read_fn(pp, d.pm, modifier_read); /* Check the header values: */ png_read_info(pp, pi); /* Process the 'info' requirements. Only one image is generated */ transform_info_imp(&d, pp, pi); sequential_row(&d.this, pp, pi, -1, 0); if (!d.this.speed) transform_image_validate(&d, pp, pi); else d.this.ps->validated = 1; } modifier_reset(d.pm); } Catch(fault) { modifier_reset(voidcast(png_modifier*,(void*)fault)); } } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
transform_test(png_modifier *pmIn, PNG_CONST png_uint_32 idIn, transform_test(png_modifier *pmIn, const png_uint_32 idIn, const image_transform* transform_listIn, const char * const name) { transform_display d; context(&pmIn->this, fault); transform_display_init(&d, pmIn, idIn, transform_listIn); Try { size_t pos = 0; png_structp pp; png_infop pi; char full_name[256]; /* Make sure the encoding fields are correct and enter the required * modifications. */ transform_set_encoding(&d); /* Add any modifications required by the transform list. */ d.transform_list->ini(d.transform_list, &d); /* Add the color space information, if any, to the name. */ pos = safecat(full_name, sizeof full_name, pos, name); pos = safecat_current_encoding(full_name, sizeof full_name, pos, d.pm); /* Get a png_struct for reading the image. */ pp = set_modifier_for_read(d.pm, &pi, d.this.id, full_name); standard_palette_init(&d.this); # if 0 /* Logging (debugging only) */ { char buffer[256]; (void)store_message(&d.pm->this, pp, buffer, sizeof buffer, 0, "running test"); fprintf(stderr, "%s\n", buffer); } # endif /* Introduce the correct read function. */ if (d.pm->this.progressive) { /* Share the row function with the standard implementation. */ png_set_progressive_read_fn(pp, &d, transform_info, progressive_row, transform_end); /* Now feed data into the reader until we reach the end: */ modifier_progressive_read(d.pm, pp, pi); } else { /* modifier_read expects a png_modifier* */ png_set_read_fn(pp, d.pm, modifier_read); /* Check the header values: */ png_read_info(pp, pi); /* Process the 'info' requirements. Only one image is generated */ transform_info_imp(&d, pp, pi); sequential_row(&d.this, pp, pi, -1, 0); if (!d.this.speed) transform_image_validate(&d, pp, pi); else d.this.ps->validated = 1; } modifier_reset(d.pm); } Catch(fault) { modifier_reset(voidcast(png_modifier*,(void*)fault)); } }
173,717
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: init_ext2_xattr(void) { ext2_xattr_cache = mb_cache_create("ext2_xattr", 6); if (!ext2_xattr_cache) return -ENOMEM; return 0; } Commit Message: ext2: convert to mbcache2 The conversion is generally straightforward. We convert filesystem from a global cache to per-fs one. Similarly to ext4 the tricky part is that xattr block corresponding to found mbcache entry can get freed before we get buffer lock for that block. So we have to check whether the entry is still valid after getting the buffer lock. Signed-off-by: Jan Kara <jack@suse.cz> Signed-off-by: Theodore Ts'o <tytso@mit.edu> CWE ID: CWE-19
init_ext2_xattr(void) #define HASH_BUCKET_BITS 10 struct mb2_cache *ext2_xattr_create_cache(void) { return mb2_cache_create(HASH_BUCKET_BITS); }
169,985
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int ovl_remove_upper(struct dentry *dentry, bool is_dir) { struct dentry *upperdir = ovl_dentry_upper(dentry->d_parent); struct inode *dir = upperdir->d_inode; struct dentry *upper = ovl_dentry_upper(dentry); int err; inode_lock_nested(dir, I_MUTEX_PARENT); err = -ESTALE; if (upper->d_parent == upperdir) { /* Don't let d_delete() think it can reset d_inode */ dget(upper); if (is_dir) err = vfs_rmdir(dir, upper); else err = vfs_unlink(dir, upper, NULL); dput(upper); ovl_dentry_version_inc(dentry->d_parent); } /* * Keeping this dentry hashed would mean having to release * upperpath/lowerpath, which could only be done if we are the * sole user of this dentry. Too tricky... Just unhash for * now. */ if (!err) d_drop(dentry); inode_unlock(dir); return err; } Commit Message: ovl: verify upper dentry before unlink and rename Unlink and rename in overlayfs checked the upper dentry for staleness by verifying upper->d_parent against upperdir. However the dentry can go stale also by being unhashed, for example. Expand the verification to actually look up the name again (under parent lock) and check if it matches the upper dentry. This matches what the VFS does before passing the dentry to filesytem's unlink/rename methods, which excludes any inconsistency caused by overlayfs. Signed-off-by: Miklos Szeredi <mszeredi@redhat.com> CWE ID: CWE-20
static int ovl_remove_upper(struct dentry *dentry, bool is_dir) { struct dentry *upperdir = ovl_dentry_upper(dentry->d_parent); struct inode *dir = upperdir->d_inode; struct dentry *upper; int err; inode_lock_nested(dir, I_MUTEX_PARENT); upper = lookup_one_len(dentry->d_name.name, upperdir, dentry->d_name.len); err = PTR_ERR(upper); if (IS_ERR(upper)) goto out_unlock; err = -ESTALE; if (upper == ovl_dentry_upper(dentry)) { if (is_dir) err = vfs_rmdir(dir, upper); else err = vfs_unlink(dir, upper, NULL); ovl_dentry_version_inc(dentry->d_parent); } dput(upper); /* * Keeping this dentry hashed would mean having to release * upperpath/lowerpath, which could only be done if we are the * sole user of this dentry. Too tricky... Just unhash for * now. */ if (!err) d_drop(dentry); out_unlock: inode_unlock(dir); return err; }
167,014
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: safecat_current_encoding(char *buffer, size_t bufsize, size_t pos, PNG_CONST png_modifier *pm) { pos = safecat_color_encoding(buffer, bufsize, pos, pm->current_encoding, pm->current_gamma); if (pm->encoding_ignored) pos = safecat(buffer, bufsize, pos, "[overridden]"); return pos; } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
safecat_current_encoding(char *buffer, size_t bufsize, size_t pos, const png_modifier *pm) { pos = safecat_color_encoding(buffer, bufsize, pos, pm->current_encoding, pm->current_gamma); if (pm->encoding_ignored) pos = safecat(buffer, bufsize, pos, "[overridden]"); return pos; }
173,691
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void DocumentLoader::InstallNewDocument( const KURL& url, Document* owner_document, bool should_reuse_default_view, const AtomicString& mime_type, const AtomicString& encoding, InstallNewDocumentReason reason, ParserSynchronizationPolicy parsing_policy, const KURL& overriding_url) { DCHECK(!frame_->GetDocument() || !frame_->GetDocument()->IsActive()); DCHECK_EQ(frame_->Tree().ChildCount(), 0u); if (GetFrameLoader().StateMachine()->IsDisplayingInitialEmptyDocument()) { GetFrameLoader().StateMachine()->AdvanceTo( FrameLoaderStateMachine::kCommittedFirstRealLoad); } SecurityOrigin* previous_security_origin = nullptr; if (frame_->GetDocument()) previous_security_origin = frame_->GetDocument()->GetSecurityOrigin(); if (!should_reuse_default_view) frame_->SetDOMWindow(LocalDOMWindow::Create(*frame_)); bool user_gesture_bit_set = frame_->HasReceivedUserGesture() || frame_->HasReceivedUserGestureBeforeNavigation(); if (reason == InstallNewDocumentReason::kNavigation) WillCommitNavigation(); Document* document = frame_->DomWindow()->InstallNewDocument( mime_type, DocumentInit::Create() .WithFrame(frame_) .WithURL(url) .WithOwnerDocument(owner_document) .WithNewRegistrationContext(), false); if (user_gesture_bit_set) { frame_->SetDocumentHasReceivedUserGestureBeforeNavigation( ShouldPersistUserGestureValue(previous_security_origin, document->GetSecurityOrigin())); if (frame_->IsMainFrame()) frame_->ClearDocumentHasReceivedUserGesture(); } if (ShouldClearWindowName(*frame_, previous_security_origin, *document)) { frame_->Tree().ExperimentalSetNulledName(); } frame_->GetPage()->GetChromeClient().InstallSupplements(*frame_); if (!overriding_url.IsEmpty()) document->SetBaseURLOverride(overriding_url); DidInstallNewDocument(document); if (reason == InstallNewDocumentReason::kNavigation) DidCommitNavigation(); writer_ = DocumentWriter::Create(document, parsing_policy, mime_type, encoding); document->SetFeaturePolicy( RuntimeEnabledFeatures::FeaturePolicyExperimentalFeaturesEnabled() ? response_.HttpHeaderField(HTTPNames::Feature_Policy) : g_empty_string); GetFrameLoader().DispatchDidClearDocumentOfWindowObject(); } Commit Message: Inherit CSP when we inherit the security origin This prevents attacks that use main window navigation to get out of the existing csp constraints such as the related bug Bug: 747847 Change-Id: I1e57b50da17f65d38088205b0a3c7c49ef2ae4d8 Reviewed-on: https://chromium-review.googlesource.com/592027 Reviewed-by: Mike West <mkwst@chromium.org> Commit-Queue: Andy Paicu <andypaicu@chromium.org> Cr-Commit-Position: refs/heads/master@{#492333} CWE ID: CWE-732
void DocumentLoader::InstallNewDocument( const KURL& url, Document* owner_document, bool should_reuse_default_view, const AtomicString& mime_type, const AtomicString& encoding, InstallNewDocumentReason reason, ParserSynchronizationPolicy parsing_policy, const KURL& overriding_url) { DCHECK(!frame_->GetDocument() || !frame_->GetDocument()->IsActive()); DCHECK_EQ(frame_->Tree().ChildCount(), 0u); if (GetFrameLoader().StateMachine()->IsDisplayingInitialEmptyDocument()) { GetFrameLoader().StateMachine()->AdvanceTo( FrameLoaderStateMachine::kCommittedFirstRealLoad); } SecurityOrigin* previous_security_origin = nullptr; if (frame_->GetDocument()) previous_security_origin = frame_->GetDocument()->GetSecurityOrigin(); if (!should_reuse_default_view) frame_->SetDOMWindow(LocalDOMWindow::Create(*frame_)); bool user_gesture_bit_set = frame_->HasReceivedUserGesture() || frame_->HasReceivedUserGestureBeforeNavigation(); if (reason == InstallNewDocumentReason::kNavigation) WillCommitNavigation(); Document* document = frame_->DomWindow()->InstallNewDocument( mime_type, DocumentInit::Create() .WithFrame(frame_) .WithURL(url) .WithOwnerDocument(owner_document) .WithNewRegistrationContext(), false); if (user_gesture_bit_set) { frame_->SetDocumentHasReceivedUserGestureBeforeNavigation( ShouldPersistUserGestureValue(previous_security_origin, document->GetSecurityOrigin())); if (frame_->IsMainFrame()) frame_->ClearDocumentHasReceivedUserGesture(); } if (ShouldClearWindowName(*frame_, previous_security_origin, *document)) { frame_->Tree().ExperimentalSetNulledName(); } frame_->GetPage()->GetChromeClient().InstallSupplements(*frame_); if (!overriding_url.IsEmpty()) document->SetBaseURLOverride(overriding_url); DidInstallNewDocument(document, reason); if (reason == InstallNewDocumentReason::kNavigation) DidCommitNavigation(); writer_ = DocumentWriter::Create(document, parsing_policy, mime_type, encoding); document->SetFeaturePolicy( RuntimeEnabledFeatures::FeaturePolicyExperimentalFeaturesEnabled() ? response_.HttpHeaderField(HTTPNames::Feature_Policy) : g_empty_string); GetFrameLoader().DispatchDidClearDocumentOfWindowObject(); }
172,303
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void ContainerNode::notifyNodeInsertedInternal(Node& root, NodeVector& postInsertionNotificationTargets) { EventDispatchForbiddenScope assertNoEventDispatch; ScriptForbiddenScope forbidScript; for (Node& node : NodeTraversal::inclusiveDescendantsOf(root)) { if (!inDocument() && !node.isContainerNode()) continue; if (Node::InsertionShouldCallDidNotifySubtreeInsertions == node.insertedInto(this)) postInsertionNotificationTargets.append(&node); for (ShadowRoot* shadowRoot = node.youngestShadowRoot(); shadowRoot; shadowRoot = shadowRoot->olderShadowRoot()) notifyNodeInsertedInternal(*shadowRoot, postInsertionNotificationTargets); } } Commit Message: Fix an optimisation in ContainerNode::notifyNodeInsertedInternal R=tkent@chromium.org BUG=544020 Review URL: https://codereview.chromium.org/1420653003 Cr-Commit-Position: refs/heads/master@{#355240} CWE ID:
void ContainerNode::notifyNodeInsertedInternal(Node& root, NodeVector& postInsertionNotificationTargets) { EventDispatchForbiddenScope assertNoEventDispatch; ScriptForbiddenScope forbidScript; for (Node& node : NodeTraversal::inclusiveDescendantsOf(root)) { // into detached subtrees that are not in a shadow tree. if (!inDocument() && !isInShadowTree() && !node.isContainerNode()) continue; if (Node::InsertionShouldCallDidNotifySubtreeInsertions == node.insertedInto(this)) postInsertionNotificationTargets.append(&node); for (ShadowRoot* shadowRoot = node.youngestShadowRoot(); shadowRoot; shadowRoot = shadowRoot->olderShadowRoot()) notifyNodeInsertedInternal(*shadowRoot, postInsertionNotificationTargets); } }
171,772
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int strdup_if_nonnull(char **target, char *source) { if (source) { *target = kstrdup(source, GFP_KERNEL); if (!*target) return -ENOMEM; } else *target = NULL; return 0; } Commit Message: Merge tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux Pull nfsd updates from Bruce Fields: "Another RDMA update from Chuck Lever, and a bunch of miscellaneous bugfixes" * tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux: (26 commits) nfsd: Fix up the "supattr_exclcreat" attributes nfsd: encoders mustn't use unitialized values in error cases nfsd: fix undefined behavior in nfsd4_layout_verify lockd: fix lockd shutdown race NFSv4: Fix callback server shutdown SUNRPC: Refactor svc_set_num_threads() NFSv4.x/callback: Create the callback service through svc_create_pooled lockd: remove redundant check on block svcrdma: Clean out old XDR encoders svcrdma: Remove the req_map cache svcrdma: Remove unused RDMA Write completion handler svcrdma: Reduce size of sge array in struct svc_rdma_op_ctxt svcrdma: Clean up RPC-over-RDMA backchannel reply processing svcrdma: Report Write/Reply chunk overruns svcrdma: Clean up RDMA_ERROR path svcrdma: Use rdma_rw API in RPC reply path svcrdma: Introduce local rdma_rw API helpers svcrdma: Clean up svc_rdma_get_inv_rkey() svcrdma: Add helper to save pages under I/O svcrdma: Eliminate RPCRDMA_SQ_DEPTH_MULT ... CWE ID: CWE-404
int strdup_if_nonnull(char **target, char *source)
168,146
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: jbig2_sd_new(Jbig2Ctx *ctx, int n_symbols) { Jbig2SymbolDict *new = NULL; if (n_symbols < 0) { jbig2_error(ctx, JBIG2_SEVERITY_FATAL, -1, "Negative number of symbols in symbol dict: %d", n_symbols); return NULL; } new = jbig2_new(ctx, Jbig2SymbolDict, 1); if (new != NULL) { new->glyphs = jbig2_new(ctx, Jbig2Image *, n_symbols); new->n_symbols = n_symbols; } else { jbig2_error(ctx, JBIG2_SEVERITY_FATAL, -1, "unable to allocate new empty symbol dict"); return NULL; } if (new->glyphs != NULL) { memset(new->glyphs, 0, n_symbols * sizeof(Jbig2Image *)); } else { jbig2_error(ctx, JBIG2_SEVERITY_FATAL, -1, "unable to allocate glyphs for new empty symbol dict"); jbig2_free(ctx->allocator, new); return NULL; } return new; } Commit Message: CWE ID: CWE-119
jbig2_sd_new(Jbig2Ctx *ctx, int n_symbols) jbig2_sd_new(Jbig2Ctx *ctx, uint32_t n_symbols) { Jbig2SymbolDict *new_dict = NULL; if (n_symbols < 0) { jbig2_error(ctx, JBIG2_SEVERITY_FATAL, -1, "Negative number of symbols in symbol dict: %d", n_symbols); return NULL; } new_dict = jbig2_new(ctx, Jbig2SymbolDict, 1); if (new_dict != NULL) { new_dict->glyphs = jbig2_new(ctx, Jbig2Image *, n_symbols); new_dict->n_symbols = n_symbols; } else { jbig2_error(ctx, JBIG2_SEVERITY_FATAL, -1, "unable to allocate new empty symbol dict"); return NULL; } if (new_dict->glyphs != NULL) { memset(new_dict->glyphs, 0, n_symbols * sizeof(Jbig2Image *)); } else { jbig2_error(ctx, JBIG2_SEVERITY_FATAL, -1, "unable to allocate glyphs for new empty symbol dict"); jbig2_free(ctx->allocator, new_dict); return NULL; } return new_dict; }
165,502
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: OMX_ERRORTYPE SoftVideoDecoderOMXComponent::internalGetParameter( OMX_INDEXTYPE index, OMX_PTR params) { switch (index) { case OMX_IndexParamVideoPortFormat: { OMX_VIDEO_PARAM_PORTFORMATTYPE *formatParams = (OMX_VIDEO_PARAM_PORTFORMATTYPE *)params; if (formatParams->nPortIndex > kMaxPortIndex) { return OMX_ErrorBadPortIndex; } if (formatParams->nIndex != 0) { return OMX_ErrorNoMore; } if (formatParams->nPortIndex == kInputPortIndex) { formatParams->eCompressionFormat = mCodingType; formatParams->eColorFormat = OMX_COLOR_FormatUnused; formatParams->xFramerate = 0; } else { CHECK_EQ(formatParams->nPortIndex, 1u); formatParams->eCompressionFormat = OMX_VIDEO_CodingUnused; formatParams->eColorFormat = OMX_COLOR_FormatYUV420Planar; formatParams->xFramerate = 0; } return OMX_ErrorNone; } case OMX_IndexParamVideoProfileLevelQuerySupported: { OMX_VIDEO_PARAM_PROFILELEVELTYPE *profileLevel = (OMX_VIDEO_PARAM_PROFILELEVELTYPE *) params; if (profileLevel->nPortIndex != kInputPortIndex) { ALOGE("Invalid port index: %" PRIu32, profileLevel->nPortIndex); return OMX_ErrorUnsupportedIndex; } if (profileLevel->nProfileIndex >= mNumProfileLevels) { return OMX_ErrorNoMore; } profileLevel->eProfile = mProfileLevels[profileLevel->nProfileIndex].mProfile; profileLevel->eLevel = mProfileLevels[profileLevel->nProfileIndex].mLevel; return OMX_ErrorNone; } default: return SimpleSoftOMXComponent::internalGetParameter(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 SoftVideoDecoderOMXComponent::internalGetParameter( OMX_INDEXTYPE index, OMX_PTR params) { switch (index) { case OMX_IndexParamVideoPortFormat: { OMX_VIDEO_PARAM_PORTFORMATTYPE *formatParams = (OMX_VIDEO_PARAM_PORTFORMATTYPE *)params; if (!isValidOMXParam(formatParams)) { return OMX_ErrorBadParameter; } if (formatParams->nPortIndex > kMaxPortIndex) { return OMX_ErrorBadPortIndex; } if (formatParams->nIndex != 0) { return OMX_ErrorNoMore; } if (formatParams->nPortIndex == kInputPortIndex) { formatParams->eCompressionFormat = mCodingType; formatParams->eColorFormat = OMX_COLOR_FormatUnused; formatParams->xFramerate = 0; } else { CHECK_EQ(formatParams->nPortIndex, 1u); formatParams->eCompressionFormat = OMX_VIDEO_CodingUnused; formatParams->eColorFormat = OMX_COLOR_FormatYUV420Planar; formatParams->xFramerate = 0; } return OMX_ErrorNone; } case OMX_IndexParamVideoProfileLevelQuerySupported: { OMX_VIDEO_PARAM_PROFILELEVELTYPE *profileLevel = (OMX_VIDEO_PARAM_PROFILELEVELTYPE *) params; if (!isValidOMXParam(profileLevel)) { return OMX_ErrorBadParameter; } if (profileLevel->nPortIndex != kInputPortIndex) { ALOGE("Invalid port index: %" PRIu32, profileLevel->nPortIndex); return OMX_ErrorUnsupportedIndex; } if (profileLevel->nProfileIndex >= mNumProfileLevels) { return OMX_ErrorNoMore; } profileLevel->eProfile = mProfileLevels[profileLevel->nProfileIndex].mProfile; profileLevel->eLevel = mProfileLevels[profileLevel->nProfileIndex].mLevel; return OMX_ErrorNone; } default: return SimpleSoftOMXComponent::internalGetParameter(index, params); } }
174,225
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int mpeg4_decode_profile_level(MpegEncContext *s, GetBitContext *gb) { s->avctx->profile = get_bits(gb, 4); s->avctx->level = get_bits(gb, 4); if (s->avctx->profile == 0 && s->avctx->level == 8) { s->avctx->level = 0; } return 0; } Commit Message: avcodec/mpeg4videodec: Check read profile before setting it Fixes: null pointer dereference Fixes: ffmpeg_crash_7.avi Found-by: Thuan Pham, Marcel Böhme, Andrew Santosa and Alexandru Razvan Caciulescu with AFLSmart Signed-off-by: Michael Niedermayer <michael@niedermayer.cc> CWE ID: CWE-476
static int mpeg4_decode_profile_level(MpegEncContext *s, GetBitContext *gb) static int mpeg4_decode_profile_level(MpegEncContext *s, GetBitContext *gb, int *profile, int *level) { *profile = get_bits(gb, 4); *level = get_bits(gb, 4); if (*profile == 0 && *level == 8) { *level = 0; } return 0; }
169,161
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: std::string SanitizeEndpoint(const std::string& value) { if (value.find('&') != std::string::npos || value.find('?') != std::string::npos) return std::string(); return value; } 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 SanitizeEndpoint(const std::string& value) {
172,457
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int __gfs2_set_acl(struct inode *inode, struct posix_acl *acl, int type) { int error; int len; char *data; const char *name = gfs2_acl_name(type); if (acl && acl->a_count > GFS2_ACL_MAX_ENTRIES(GFS2_SB(inode))) return -E2BIG; if (type == ACL_TYPE_ACCESS) { umode_t mode = inode->i_mode; error = posix_acl_equiv_mode(acl, &mode); if (error < 0) return error; if (error == 0) acl = NULL; if (mode != inode->i_mode) { inode->i_mode = mode; mark_inode_dirty(inode); } } if (acl) { len = posix_acl_to_xattr(&init_user_ns, acl, NULL, 0); if (len == 0) return 0; data = kmalloc(len, GFP_NOFS); if (data == NULL) return -ENOMEM; error = posix_acl_to_xattr(&init_user_ns, acl, data, len); if (error < 0) goto out; } else { data = NULL; len = 0; } error = __gfs2_xattr_set(inode, name, data, len, 0, GFS2_EATYPE_SYS); if (error) goto out; set_cached_acl(inode, type, acl); out: kfree(data); return error; } Commit Message: posix_acl: Clear SGID bit when setting file permissions When file permissions are modified via chmod(2) and the user is not in the owning group or capable of CAP_FSETID, the setgid bit is cleared in inode_change_ok(). Setting a POSIX ACL via setxattr(2) sets the file permissions as well as the new ACL, but doesn't clear the setgid bit in a similar way; this allows to bypass the check in chmod(2). Fix that. References: CVE-2016-7097 Reviewed-by: Christoph Hellwig <hch@lst.de> Reviewed-by: Jeff Layton <jlayton@redhat.com> Signed-off-by: Jan Kara <jack@suse.cz> Signed-off-by: Andreas Gruenbacher <agruenba@redhat.com> CWE ID: CWE-285
int __gfs2_set_acl(struct inode *inode, struct posix_acl *acl, int type) { int error; int len; char *data; const char *name = gfs2_acl_name(type); if (acl && acl->a_count > GFS2_ACL_MAX_ENTRIES(GFS2_SB(inode))) return -E2BIG; if (type == ACL_TYPE_ACCESS) { umode_t mode = inode->i_mode; error = posix_acl_update_mode(inode, &inode->i_mode, &acl); if (error) return error; if (mode != inode->i_mode) mark_inode_dirty(inode); } if (acl) { len = posix_acl_to_xattr(&init_user_ns, acl, NULL, 0); if (len == 0) return 0; data = kmalloc(len, GFP_NOFS); if (data == NULL) return -ENOMEM; error = posix_acl_to_xattr(&init_user_ns, acl, data, len); if (error < 0) goto out; } else { data = NULL; len = 0; } error = __gfs2_xattr_set(inode, name, data, len, 0, GFS2_EATYPE_SYS); if (error) goto out; set_cached_acl(inode, type, acl); out: kfree(data); return error; }
166,972
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static char *print_number( cJSON *item ) { char *str; double f, f2; int64_t i; str = (char*) cJSON_malloc( 64 ); if ( str ) { f = item->valuefloat; i = f; f2 = i; if ( f2 == f && item->valueint >= LLONG_MIN && item->valueint <= LLONG_MAX ) sprintf( str, "%lld", (long long) item->valueint ); else sprintf( str, "%g", item->valuefloat ); } return str; } Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a malformed JSON string was passed on the control channel. This issue, present in the cJSON library, was already fixed upstream, so was addressed here in iperf3 by importing a newer version of cJSON (plus local ESnet modifications). Discovered and reported by Dave McDaniel, Cisco Talos. Based on a patch by @dopheide-esnet, with input from @DaveGamble. Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001, CVE-2016-4303 (cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40) Signed-off-by: Bruce A. Mah <bmah@es.net> CWE ID: CWE-119
static char *print_number( cJSON *item ) static int update(printbuffer *p) { char *str; if (!p || !p->buffer) return 0; str=p->buffer+p->offset; return p->offset+strlen(str); } /* Render the number nicely from the given item into a string. */ static char *print_number(cJSON *item,printbuffer *p) { char *str=0; double d=item->valuedouble; if (d==0) { if (p) str=ensure(p,2); else str=(char*)cJSON_malloc(2); /* special case for 0. */ if (str) strcpy(str,"0"); } else if (fabs(((double)item->valueint)-d)<=DBL_EPSILON && d<=LLONG_MAX && d>=LLONG_MIN) { if (p) str=ensure(p,64); else str=(char*)cJSON_malloc(64); if (str) sprintf(str,"%lld",(long long) item->valueint); } else { if (p) str=ensure(p,64); else str=(char*)cJSON_malloc(64); /* This is a nice tradeoff. */ if (str) { if (fpclassify(d) != FP_ZERO && !isnormal(d)) sprintf(str,"null"); else if (fabs(floor(d)-d)<=DBL_EPSILON && fabs(d)<1.0e60) sprintf(str,"%.0f",d); else if (fabs(d)<1.0e-6 || fabs(d)>1.0e9) sprintf(str,"%e",d); else sprintf(str,"%f",d); } } return str; }
167,307
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void ExtensionTtsController::SpeakNow(Utterance* utterance) { std::string extension_id = GetMatchingExtensionId(utterance); if (!extension_id.empty()) { current_utterance_ = utterance; utterance->set_extension_id(extension_id); ListValue args; args.Set(0, Value::CreateStringValue(utterance->text())); DictionaryValue* options = static_cast<DictionaryValue*>( utterance->options()->DeepCopy()); if (options->HasKey(util::kEnqueueKey)) options->Remove(util::kEnqueueKey, NULL); args.Set(1, options); args.Set(2, Value::CreateIntegerValue(utterance->id())); std::string json_args; base::JSONWriter::Write(&args, false, &json_args); utterance->profile()->GetExtensionEventRouter()->DispatchEventToExtension( extension_id, events::kOnSpeak, json_args, utterance->profile(), GURL()); return; } GetPlatformImpl()->clear_error(); bool success = GetPlatformImpl()->Speak( utterance->text(), utterance->locale(), utterance->gender(), utterance->rate(), utterance->pitch(), utterance->volume()); if (!success) { utterance->set_error(GetPlatformImpl()->error()); utterance->FinishAndDestroy(); return; } current_utterance_ = utterance; CheckSpeechStatus(); } Commit Message: Extend TTS extension API to support richer events returned from the engine to the client. Previously we just had a completed event; this adds start, word boundary, sentence boundary, and marker boundary. In addition, interrupted and canceled, which were previously errors, now become events. Mac and Windows implementations extended to support as many of these events as possible. BUG=67713 BUG=70198 BUG=75106 BUG=83404 TEST=Updates all TTS API tests to be event-based, and adds new tests. Review URL: http://codereview.chromium.org/6792014 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@91665 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
void ExtensionTtsController::SpeakNow(Utterance* utterance) { } double pitch = 1.0; if (options->HasKey(constants::kPitchKey)) { EXTENSION_FUNCTION_VALIDATE( options->GetDouble(constants::kPitchKey, &pitch)); if (pitch < 0.0 || pitch > 2.0) { error_ = constants::kErrorInvalidPitch; return false; } }
170,388
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: TestCompletionCallback() : callback_(base::Bind(&TestCompletionCallback::SetResult, base::Unretained(this))) {} Commit Message: Update helper classes in usb_device_handle_unittest for OnceCallback Helper classes in usb_device_handle_unittest.cc don't fit to OnceCallback migration, as they are copied and passed to others. This CL updates them to pass new callbacks for each use to avoid the copy of callbacks. Bug: 714018 Change-Id: Ifb70901439ae92b6b049b84534283c39ebc40ee0 Reviewed-on: https://chromium-review.googlesource.com/527549 Reviewed-by: Ken Rockot <rockot@chromium.org> Commit-Queue: Taiju Tsuiki <tzik@chromium.org> Cr-Commit-Position: refs/heads/master@{#478549} CWE ID:
TestCompletionCallback()
171,975
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static ssize_t aio_setup_single_vector(struct kiocb *kiocb) { kiocb->ki_iovec = &kiocb->ki_inline_vec; kiocb->ki_iovec->iov_base = kiocb->ki_buf; kiocb->ki_iovec->iov_len = kiocb->ki_left; kiocb->ki_nr_segs = 1; kiocb->ki_cur_seg = 0; return 0; } Commit Message: vfs: make AIO use the proper rw_verify_area() area helpers We had for some reason overlooked the AIO interface, and it didn't use the proper rw_verify_area() helper function that checks (for example) mandatory locking on the file, and that the size of the access doesn't cause us to overflow the provided offset limits etc. Instead, AIO did just the security_file_permission() thing (that rw_verify_area() also does) directly. This fixes it to do all the proper helper functions, which not only means that now mandatory file locking works with AIO too, we can actually remove lines of code. Reported-by: Manish Honap <manish_honap_vit@yahoo.co.in> Cc: stable@vger.kernel.org Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org> CWE ID:
static ssize_t aio_setup_single_vector(struct kiocb *kiocb) static ssize_t aio_setup_single_vector(int type, struct file * file, struct kiocb *kiocb) { int bytes; bytes = rw_verify_area(type, file, &kiocb->ki_pos, kiocb->ki_left); if (bytes < 0) return bytes; kiocb->ki_iovec = &kiocb->ki_inline_vec; kiocb->ki_iovec->iov_base = kiocb->ki_buf; kiocb->ki_iovec->iov_len = bytes; kiocb->ki_nr_segs = 1; kiocb->ki_cur_seg = 0; return 0; }
167,612
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int cp2112_gpio_direction_input(struct gpio_chip *chip, unsigned offset) { struct cp2112_device *dev = gpiochip_get_data(chip); struct hid_device *hdev = dev->hdev; u8 *buf = dev->in_out_buffer; int ret; mutex_lock(&dev->lock); ret = hid_hw_raw_request(hdev, CP2112_GPIO_CONFIG, buf, CP2112_GPIO_CONFIG_LENGTH, HID_FEATURE_REPORT, HID_REQ_GET_REPORT); if (ret != CP2112_GPIO_CONFIG_LENGTH) { hid_err(hdev, "error requesting GPIO config: %d\n", ret); goto exit; } buf[1] &= ~(1 << offset); buf[2] = gpio_push_pull; ret = hid_hw_raw_request(hdev, CP2112_GPIO_CONFIG, buf, CP2112_GPIO_CONFIG_LENGTH, HID_FEATURE_REPORT, HID_REQ_SET_REPORT); if (ret < 0) { hid_err(hdev, "error setting GPIO config: %d\n", ret); goto exit; } ret = 0; exit: mutex_unlock(&dev->lock); return ret <= 0 ? ret : -EIO; } Commit Message: HID: cp2112: fix gpio-callback error handling In case of a zero-length report, the gpio direction_input callback would currently return success instead of an errno. Fixes: 1ffb3c40ffb5 ("HID: cp2112: make transfer buffers DMA capable") Cc: stable <stable@vger.kernel.org> # 4.9 Signed-off-by: Johan Hovold <johan@kernel.org> Reviewed-by: Benjamin Tissoires <benjamin.tissoires@redhat.com> Signed-off-by: Jiri Kosina <jkosina@suse.cz> CWE ID: CWE-388
static int cp2112_gpio_direction_input(struct gpio_chip *chip, unsigned offset) { struct cp2112_device *dev = gpiochip_get_data(chip); struct hid_device *hdev = dev->hdev; u8 *buf = dev->in_out_buffer; int ret; mutex_lock(&dev->lock); ret = hid_hw_raw_request(hdev, CP2112_GPIO_CONFIG, buf, CP2112_GPIO_CONFIG_LENGTH, HID_FEATURE_REPORT, HID_REQ_GET_REPORT); if (ret != CP2112_GPIO_CONFIG_LENGTH) { hid_err(hdev, "error requesting GPIO config: %d\n", ret); goto exit; } buf[1] &= ~(1 << offset); buf[2] = gpio_push_pull; ret = hid_hw_raw_request(hdev, CP2112_GPIO_CONFIG, buf, CP2112_GPIO_CONFIG_LENGTH, HID_FEATURE_REPORT, HID_REQ_SET_REPORT); if (ret < 0) { hid_err(hdev, "error setting GPIO config: %d\n", ret); goto exit; } ret = 0; exit: mutex_unlock(&dev->lock); return ret < 0 ? ret : -EIO; }
168,207
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: juniper_mlfr_print(netdissect_options *ndo, const struct pcap_pkthdr *h, register const u_char *p) { struct juniper_l2info_t l2info; l2info.pictype = DLT_JUNIPER_MLFR; if (juniper_parse_header(ndo, p, h, &l2info) == 0) return l2info.header_len; p+=l2info.header_len; /* suppress Bundle-ID if frame was captured on a child-link */ if (ndo->ndo_eflag && EXTRACT_32BITS(l2info.cookie) != 1) ND_PRINT((ndo, "Bundle-ID %u, ", l2info.bundle)); switch (l2info.proto) { case (LLC_UI): case (LLC_UI<<8): isoclns_print(ndo, p, l2info.length, l2info.caplen); break; case (LLC_UI<<8 | NLPID_Q933): case (LLC_UI<<8 | NLPID_IP): case (LLC_UI<<8 | NLPID_IP6): /* pass IP{4,6} to the OSI layer for proper link-layer printing */ isoclns_print(ndo, p - 1, l2info.length + 1, l2info.caplen + 1); break; default: ND_PRINT((ndo, "unknown protocol 0x%04x, length %u", l2info.proto, l2info.length)); } return l2info.header_len; } Commit Message: CVE-2017-12897/ISO CLNS: Use ND_TTEST() for the bounds checks in isoclns_print(). This fixes a buffer over-read discovered by Kamil Frankowicz. Don't pass the remaining caplen - that's too hard to get right, and we were getting it wrong in at least one case; just use ND_TTEST(). Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-125
juniper_mlfr_print(netdissect_options *ndo, const struct pcap_pkthdr *h, register const u_char *p) { struct juniper_l2info_t l2info; l2info.pictype = DLT_JUNIPER_MLFR; if (juniper_parse_header(ndo, p, h, &l2info) == 0) return l2info.header_len; p+=l2info.header_len; /* suppress Bundle-ID if frame was captured on a child-link */ if (ndo->ndo_eflag && EXTRACT_32BITS(l2info.cookie) != 1) ND_PRINT((ndo, "Bundle-ID %u, ", l2info.bundle)); switch (l2info.proto) { case (LLC_UI): case (LLC_UI<<8): isoclns_print(ndo, p, l2info.length); break; case (LLC_UI<<8 | NLPID_Q933): case (LLC_UI<<8 | NLPID_IP): case (LLC_UI<<8 | NLPID_IP6): /* pass IP{4,6} to the OSI layer for proper link-layer printing */ isoclns_print(ndo, p - 1, l2info.length + 1); break; default: ND_PRINT((ndo, "unknown protocol 0x%04x, length %u", l2info.proto, l2info.length)); } return l2info.header_len; }
167,951
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void Start() { DVLOG(2) << "Starting SafeBrowsing download check for: " << item_->DebugString(true); DCHECK_CURRENTLY_ON(BrowserThread::UI); DownloadCheckResultReason reason = REASON_MAX; if (!IsSupportedDownload( *item_, item_->GetTargetFilePath(), &reason, &type_)) { switch (reason) { case REASON_EMPTY_URL_CHAIN: case REASON_INVALID_URL: case REASON_UNSUPPORTED_URL_SCHEME: PostFinishTask(UNKNOWN, reason); return; case REASON_NOT_BINARY_FILE: RecordFileExtensionType(item_->GetTargetFilePath()); PostFinishTask(UNKNOWN, reason); return; default: NOTREACHED(); } } RecordFileExtensionType(item_->GetTargetFilePath()); if (item_->GetTargetFilePath().MatchesExtension( FILE_PATH_LITERAL(".zip"))) { StartExtractZipFeatures(); } else { DCHECK(!download_protection_util::IsArchiveFile( item_->GetTargetFilePath())); StartExtractFileFeatures(); } } Commit Message: Add the SandboxedDMGParser and wire it up to the DownloadProtectionService. BUG=496898,464083 R=isherman@chromium.org, kenrb@chromium.org, mattm@chromium.org, thestig@chromium.org Review URL: https://codereview.chromium.org/1299223006 . Cr-Commit-Position: refs/heads/master@{#344876} CWE ID:
void Start() { DVLOG(2) << "Starting SafeBrowsing download check for: " << item_->DebugString(true); DCHECK_CURRENTLY_ON(BrowserThread::UI); DownloadCheckResultReason reason = REASON_MAX; if (!IsSupportedDownload( *item_, item_->GetTargetFilePath(), &reason, &type_)) { switch (reason) { case REASON_EMPTY_URL_CHAIN: case REASON_INVALID_URL: case REASON_UNSUPPORTED_URL_SCHEME: PostFinishTask(UNKNOWN, reason); return; case REASON_NOT_BINARY_FILE: RecordFileExtensionType(item_->GetTargetFilePath()); PostFinishTask(UNKNOWN, reason); return; default: NOTREACHED(); } } RecordFileExtensionType(item_->GetTargetFilePath()); if (item_->GetTargetFilePath().MatchesExtension( FILE_PATH_LITERAL(".zip"))) { StartExtractZipFeatures(); #if defined(OS_MACOSX) } else if (item_->GetTargetFilePath().MatchesExtension( FILE_PATH_LITERAL(".dmg"))) { StartExtractDmgFeatures(); #endif } else { DCHECK(!download_protection_util::IsArchiveFile( item_->GetTargetFilePath())); StartExtractFileFeatures(); } }
171,715
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int bta_co_rfc_data_outgoing_size(void *user_data, int *size) { pthread_mutex_lock(&slot_lock); uint32_t id = (uintptr_t)user_data; int ret = false; *size = 0; rfc_slot_t *slot = find_rfc_slot_by_id(id); if (!slot) goto out; if (ioctl(slot->fd, FIONREAD, size) == 0) { ret = true; } else { LOG_ERROR("%s unable to determine bytes remaining to be read on fd %d: %s", __func__, slot->fd, strerror(errno)); cleanup_rfc_slot(slot); } out:; pthread_mutex_unlock(&slot_lock); return ret; } Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process Bug: 28885210 Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360 Conflicts: btif/co/bta_hh_co.c btif/src/btif_core.c Merge conflict resolution of ag/1161415 (referencing ag/1164670) - Directly into mnc-mr2-release CWE ID: CWE-284
int bta_co_rfc_data_outgoing_size(void *user_data, int *size) { pthread_mutex_lock(&slot_lock); uint32_t id = (uintptr_t)user_data; int ret = false; *size = 0; rfc_slot_t *slot = find_rfc_slot_by_id(id); if (!slot) goto out; if (TEMP_FAILURE_RETRY(ioctl(slot->fd, FIONREAD, size)) == 0) { ret = true; } else { LOG_ERROR("%s unable to determine bytes remaining to be read on fd %d: %s", __func__, slot->fd, strerror(errno)); cleanup_rfc_slot(slot); } out:; pthread_mutex_unlock(&slot_lock); return ret; }
173,456
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: long long mkvparser::GetUIntLength(IMkvReader* pReader, long long pos, long& len) { assert(pReader); assert(pos >= 0); long long total, available; int status = pReader->Length(&total, &available); assert(status >= 0); assert((total < 0) || (available <= total)); len = 1; if (pos >= available) return pos; // too few bytes available unsigned char b; status = pReader->Read(pos, 1, &b); if (status < 0) return status; assert(status == 0); if (b == 0) // we can't handle u-int values larger than 8 bytes return E_FILE_FORMAT_INVALID; unsigned char m = 0x80; while (!(b & m)) { m >>= 1; ++len; } return 0; // success } Commit Message: external/libvpx/libwebm: Update snapshot Update libwebm snapshot. This update contains security fixes from upstream. Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b BUG=23167726 Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207 (cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a) CWE ID: CWE-20
long long mkvparser::GetUIntLength(IMkvReader* pReader, long long pos, long long ReadID(IMkvReader* pReader, long long pos, long& len) { const long long id = ReadUInt(pReader, pos, len); if (id < 0 || len < 1 || len > 4) { // An ID must be at least 1 byte long, and cannot exceed 4. // See EBMLMaxIDLength: http://www.matroska.org/technical/specs/index.html return E_FILE_FORMAT_INVALID; } return id; } long long GetUIntLength(IMkvReader* pReader, long long pos, long& len) { if (!pReader || pos < 0) return E_FILE_FORMAT_INVALID; long long total, available; int status = pReader->Length(&total, &available); if (status < 0 || (total >= 0 && available > total)) return E_FILE_FORMAT_INVALID; len = 1; if (pos >= available) return pos; // too few bytes available unsigned char b; status = pReader->Read(pos, 1, &b); if (status != 0) return status; if (b == 0) // we can't handle u-int values larger than 8 bytes return E_FILE_FORMAT_INVALID; unsigned char m = 0x80; while (!(b & m)) { m >>= 1; ++len; } return 0; // success }
173,824
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed 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. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void RenderWidgetHostViewAura::AcceleratedSurfaceRelease( uint64 surface_handle) { DCHECK(image_transport_clients_.find(surface_handle) != image_transport_clients_.end()); if (current_surface_ == surface_handle) { current_surface_ = 0; UpdateExternalTexture(); } image_transport_clients_.erase(surface_handle); } 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::AcceleratedSurfaceRelease( void RenderWidgetHostViewAura::AcceleratedSurfaceRelease() { // This really tells us to release the frontbuffer. if (current_surface_ && ShouldReleaseFrontSurface()) { ui::Compositor* compositor = GetCompositor(); if (compositor) { // We need to wait for a commit to clear to guarantee that all we // will not issue any more GL referencing the previous surface. can_lock_compositor_ = NO_PENDING_COMMIT; scoped_refptr<ui::Texture> surface_ref = image_transport_clients_[current_surface_]; on_compositing_did_commit_callbacks_.push_back( base::Bind(&RenderWidgetHostViewAura:: SetSurfaceNotInUseByCompositor, AsWeakPtr(), surface_ref)); if (!compositor->HasObserver(this)) compositor->AddObserver(this); } image_transport_clients_.erase(current_surface_); current_surface_ = 0; UpdateExternalTexture(); } }
171,375