instruction
stringclasses
1 value
input
stringlengths
93
3.53k
output
stringlengths
16
15.4k
__index_level_0__
int64
165k
175k
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static int udf_symlink_filler(struct file *file, struct page *page) { struct inode *inode = page->mapping->host; struct buffer_head *bh = NULL; unsigned char *symlink; int err = -EIO; unsigned char *p = kmap(page); struct udf_inode_info *iinfo; uint32_t pos; iinfo = UDF_I(inode); pos = udf_block_map(inode, 0); down_read(&iinfo->i_data_sem); if (iinfo->i_alloc_type == ICBTAG_FLAG_AD_IN_ICB) { symlink = iinfo->i_ext.i_data + iinfo->i_lenEAttr; } else { bh = sb_bread(inode->i_sb, pos); if (!bh) goto out; symlink = bh->b_data; } udf_pc_to_char(inode->i_sb, symlink, inode->i_size, p); brelse(bh); up_read(&iinfo->i_data_sem); SetPageUptodate(page); kunmap(page); unlock_page(page); return 0; out: up_read(&iinfo->i_data_sem); SetPageError(page); kunmap(page); unlock_page(page); return err; } Commit Message: udf: Verify symlink size before loading it UDF specification allows arbitrarily large symlinks. However we support only symlinks at most one block large. Check the length of the symlink so that we don't access memory beyond end of the symlink block. CC: [email protected] Reported-by: Carl Henrik Lunde <[email protected]> Signed-off-by: Jan Kara <[email protected]> CWE ID: CWE-119
static int udf_symlink_filler(struct file *file, struct page *page) { struct inode *inode = page->mapping->host; struct buffer_head *bh = NULL; unsigned char *symlink; int err; unsigned char *p = kmap(page); struct udf_inode_info *iinfo; uint32_t pos; /* We don't support symlinks longer than one block */ if (inode->i_size > inode->i_sb->s_blocksize) { err = -ENAMETOOLONG; goto out_unmap; } iinfo = UDF_I(inode); pos = udf_block_map(inode, 0); down_read(&iinfo->i_data_sem); if (iinfo->i_alloc_type == ICBTAG_FLAG_AD_IN_ICB) { symlink = iinfo->i_ext.i_data + iinfo->i_lenEAttr; } else { bh = sb_bread(inode->i_sb, pos); if (!bh) { err = -EIO; goto out_unlock_inode; } symlink = bh->b_data; } udf_pc_to_char(inode->i_sb, symlink, inode->i_size, p); brelse(bh); up_read(&iinfo->i_data_sem); SetPageUptodate(page); kunmap(page); unlock_page(page); return 0; out_unlock_inode: up_read(&iinfo->i_data_sem); SetPageError(page); out_unmap: kunmap(page); unlock_page(page); return err; }
169,930
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void FillRandom(uint8_t *data, int stride) { for (int h = 0; h < height_; ++h) { for (int w = 0; w < width_; ++w) { data[h * stride + w] = rnd_.Rand8(); } } } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119
void FillRandom(uint8_t *data, int stride) { uint8_t *data8 = data; #if CONFIG_VP9_HIGHBITDEPTH uint16_t *data16 = CONVERT_TO_SHORTPTR(data); #endif // CONFIG_VP9_HIGHBITDEPTH for (int h = 0; h < height_; ++h) { for (int w = 0; w < width_; ++w) { if (!use_high_bit_depth_) { data8[h * stride + w] = rnd_.Rand8(); #if CONFIG_VP9_HIGHBITDEPTH } else { data16[h * stride + w] = rnd_.Rand16() & mask_; #endif // CONFIG_VP9_HIGHBITDEPTH } } } }
174,572
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static double ipow( double n, int exp ) { double r; if ( exp < 0 ) return 1.0 / ipow( n, -exp ); r = 1; while ( exp > 0 ) { if ( exp & 1 ) r *= n; exp >>= 1; n *= n; } return r; } Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a malformed JSON string was passed on the control channel. This issue, present in the cJSON library, was already fixed upstream, so was addressed here in iperf3 by importing a newer version of cJSON (plus local ESnet modifications). Discovered and reported by Dave McDaniel, Cisco Talos. Based on a patch by @dopheide-esnet, with input from @DaveGamble. Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001, CVE-2016-4303 (cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40) Signed-off-by: Bruce A. Mah <[email protected]> CWE ID: CWE-119
static double ipow( double n, int exp ) /* Parse the input text to generate a number, and populate the result into item. */ static const char *parse_number(cJSON *item,const char *num) { double n=0,sign=1,scale=0;int subscale=0,signsubscale=1; if (*num=='-') sign=-1,num++; /* Has sign? */ if (*num=='0') num++; /* is zero */ if (*num>='1' && *num<='9') do n=(n*10.0)+(*num++ -'0'); while (*num>='0' && *num<='9'); /* Number? */ if (*num=='.' && num[1]>='0' && num[1]<='9') {num++; do n=(n*10.0)+(*num++ -'0'),scale--; while (*num>='0' && *num<='9');} /* Fractional part? */ if (*num=='e' || *num=='E') /* Exponent? */ { num++;if (*num=='+') num++; else if (*num=='-') signsubscale=-1,num++; /* With sign? */ while (*num>='0' && *num<='9') subscale=(subscale*10)+(*num++ - '0'); /* Number? */ }
167,300
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: header_put_le_3byte (SF_PRIVATE *psf, int x) { if (psf->headindex < SIGNED_SIZEOF (psf->header) - 3) { psf->header [psf->headindex++] = x ; psf->header [psf->headindex++] = (x >> 8) ; psf->header [psf->headindex++] = (x >> 16) ; } ; } /* header_put_le_3byte */ Commit Message: src/ : Move to a variable length header buffer Previously, the `psf->header` buffer was a fixed length specified by `SF_HEADER_LEN` which was set to `12292`. This was problematic for two reasons; this value was un-necessarily large for the majority of files and too small for some others. Now the size of the header buffer starts at 256 bytes and grows as necessary up to a maximum of 100k. CWE ID: CWE-119
header_put_le_3byte (SF_PRIVATE *psf, int x) { psf->header.ptr [psf->header.indx++] = x ; psf->header.ptr [psf->header.indx++] = (x >> 8) ; psf->header.ptr [psf->header.indx++] = (x >> 16) ; } /* header_put_le_3byte */
170,054
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: int WebContentsImpl::DownloadImage( const GURL& url, bool is_favicon, uint32_t max_bitmap_size, bool bypass_cache, const WebContents::ImageDownloadCallback& callback) { DCHECK_CURRENTLY_ON(BrowserThread::UI); static int next_image_download_id = 0; const image_downloader::ImageDownloaderPtr& mojo_image_downloader = GetMainFrame()->GetMojoImageDownloader(); const int download_id = ++next_image_download_id; if (!mojo_image_downloader) { BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind(&WebContents::ImageDownloadCallback::Run, base::Owned(new ImageDownloadCallback(callback)), download_id, 400, url, std::vector<SkBitmap>(), std::vector<gfx::Size>())); return download_id; } image_downloader::DownloadRequestPtr req = image_downloader::DownloadRequest::New(); req->url = mojo::String::From(url); req->is_favicon = is_favicon; req->max_bitmap_size = max_bitmap_size; req->bypass_cache = bypass_cache; mojo_image_downloader->DownloadImage( std::move(req), base::Bind(&DidDownloadImage, callback, download_id, url)); return download_id; } Commit Message: Don't call WebContents::DownloadImage() callback if the WebContents were deleted BUG=583718 Review URL: https://codereview.chromium.org/1685343004 Cr-Commit-Position: refs/heads/master@{#375700} CWE ID:
int WebContentsImpl::DownloadImage( const GURL& url, bool is_favicon, uint32_t max_bitmap_size, bool bypass_cache, const WebContents::ImageDownloadCallback& callback) { DCHECK_CURRENTLY_ON(BrowserThread::UI); static int next_image_download_id = 0; const image_downloader::ImageDownloaderPtr& mojo_image_downloader = GetMainFrame()->GetMojoImageDownloader(); const int download_id = ++next_image_download_id; if (!mojo_image_downloader) { image_downloader::DownloadResultPtr result = image_downloader::DownloadResult::New(); result->http_status_code = 400; BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind(&WebContentsImpl::OnDidDownloadImage, weak_factory_.GetWeakPtr(), callback, download_id, url, base::Passed(&result))); return download_id; } image_downloader::DownloadRequestPtr req = image_downloader::DownloadRequest::New(); req->url = mojo::String::From(url); req->is_favicon = is_favicon; req->max_bitmap_size = max_bitmap_size; req->bypass_cache = bypass_cache; mojo_image_downloader->DownloadImage( std::move(req), base::Bind(&WebContentsImpl::OnDidDownloadImage, weak_factory_.GetWeakPtr(), callback, download_id, url)); return download_id; }
172,210
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void WebResourceService::StartFetch() { ScheduleFetch(cache_update_delay_ms_); prefs_->SetString(last_update_time_pref_name_, base::DoubleToString(base::Time::Now().ToDoubleT())); if (in_fetch_) return; in_fetch_ = true; GURL web_resource_server = application_locale_.empty() ? web_resource_server_ : google_util::AppendGoogleLocaleParam(web_resource_server_, application_locale_); DVLOG(1) << "WebResourceService StartFetch " << web_resource_server; url_fetcher_ = net::URLFetcher::Create(web_resource_server, net::URLFetcher::GET, this); url_fetcher_->SetLoadFlags(net::LOAD_DISABLE_CACHE | net::LOAD_DO_NOT_SEND_COOKIES | net::LOAD_DO_NOT_SAVE_COOKIES); url_fetcher_->SetRequestContext(request_context_.get()); url_fetcher_->Start(); } Commit Message: Add data usage tracking for chrome services Add data usage tracking for captive portal, web resource and signin services BUG=655749 Review-Url: https://codereview.chromium.org/2643013004 Cr-Commit-Position: refs/heads/master@{#445810} CWE ID: CWE-190
void WebResourceService::StartFetch() { ScheduleFetch(cache_update_delay_ms_); prefs_->SetString(last_update_time_pref_name_, base::DoubleToString(base::Time::Now().ToDoubleT())); if (in_fetch_) return; in_fetch_ = true; GURL web_resource_server = application_locale_.empty() ? web_resource_server_ : google_util::AppendGoogleLocaleParam(web_resource_server_, application_locale_); DVLOG(1) << "WebResourceService StartFetch " << web_resource_server; url_fetcher_ = net::URLFetcher::Create(web_resource_server, net::URLFetcher::GET, this); data_use_measurement::DataUseUserData::AttachToFetcher( url_fetcher_.get(), data_use_measurement::DataUseUserData::WEB_RESOURCE_SERVICE); url_fetcher_->SetLoadFlags(net::LOAD_DISABLE_CACHE | net::LOAD_DO_NOT_SEND_COOKIES | net::LOAD_DO_NOT_SAVE_COOKIES); url_fetcher_->SetRequestContext(request_context_.get()); url_fetcher_->Start(); }
172,020
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: const char* Track::GetCodecId() const { return m_info.codecId; } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
const char* Track::GetCodecId() const
174,293
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void CheckSad(unsigned int max_sad) { unsigned int reference_sad, exp_sad; reference_sad = ReferenceSAD(max_sad); exp_sad = SAD(max_sad); if (reference_sad <= max_sad) { ASSERT_EQ(exp_sad, reference_sad); } else { ASSERT_GE(exp_sad, reference_sad); } } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119
void CheckSad(unsigned int max_sad) {
174,570
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static void __update_open_stateid(struct nfs4_state *state, nfs4_stateid *open_stateid, const nfs4_stateid *deleg_stateid, int open_flags) { /* * Protect the call to nfs4_state_set_mode_locked and * serialise the stateid update */ write_seqlock(&state->seqlock); if (deleg_stateid != NULL) { memcpy(state->stateid.data, deleg_stateid->data, sizeof(state->stateid.data)); set_bit(NFS_DELEGATED_STATE, &state->flags); } if (open_stateid != NULL) nfs_set_open_stateid_locked(state, open_stateid, open_flags); write_sequnlock(&state->seqlock); spin_lock(&state->owner->so_lock); update_open_stateflags(state, open_flags); spin_unlock(&state->owner->so_lock); } Commit Message: NFSv4: Convert the open and close ops to use fmode Signed-off-by: Trond Myklebust <[email protected]> CWE ID:
static void __update_open_stateid(struct nfs4_state *state, nfs4_stateid *open_stateid, const nfs4_stateid *deleg_stateid, int open_flags) static void __update_open_stateid(struct nfs4_state *state, nfs4_stateid *open_stateid, const nfs4_stateid *deleg_stateid, fmode_t fmode) { /* * Protect the call to nfs4_state_set_mode_locked and * serialise the stateid update */ write_seqlock(&state->seqlock); if (deleg_stateid != NULL) { memcpy(state->stateid.data, deleg_stateid->data, sizeof(state->stateid.data)); set_bit(NFS_DELEGATED_STATE, &state->flags); } if (open_stateid != NULL) nfs_set_open_stateid_locked(state, open_stateid, fmode); write_sequnlock(&state->seqlock); spin_lock(&state->owner->so_lock); update_open_stateflags(state, fmode); spin_unlock(&state->owner->so_lock); }
165,683
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void ImageInputType::ensurePrimaryContent() { if (!m_useFallbackContent) return; m_useFallbackContent = false; reattachFallbackContent(); } Commit Message: ImageInputType::ensurePrimaryContent should recreate UA shadow tree. Once the fallback shadow tree was created, it was never recreated even if ensurePrimaryContent was called. Such situation happens by updating |src| attribute. BUG=589838 Review URL: https://codereview.chromium.org/1732753004 Cr-Commit-Position: refs/heads/master@{#377804} CWE ID: CWE-361
void ImageInputType::ensurePrimaryContent() { if (!m_useFallbackContent) return; m_useFallbackContent = false; if (ShadowRoot* root = element().userAgentShadowRoot()) root->removeChildren(); createShadowSubtree(); reattachFallbackContent(); }
172,285
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static void iwl_sta_ucode_activate(struct iwl_priv *priv, u8 sta_id) { if (!(priv->stations[sta_id].used & IWL_STA_DRIVER_ACTIVE)) IWL_ERR(priv, "ACTIVATE a non DRIVER active station id %u " "addr %pM\n", sta_id, priv->stations[sta_id].sta.sta.addr); if (priv->stations[sta_id].used & IWL_STA_UCODE_ACTIVE) { IWL_DEBUG_ASSOC(priv, "STA id %u addr %pM already present in uCode " "(according to driver)\n", sta_id, priv->stations[sta_id].sta.sta.addr); } else { priv->stations[sta_id].used |= IWL_STA_UCODE_ACTIVE; IWL_DEBUG_ASSOC(priv, "Added STA id %u addr %pM to uCode\n", sta_id, priv->stations[sta_id].sta.sta.addr); } } Commit Message: iwlwifi: Sanity check for sta_id On my testing, I saw some strange behavior [ 421.739708] iwlwifi 0000:01:00.0: ACTIVATE a non DRIVER active station id 148 addr 00:00:00:00:00:00 [ 421.739719] iwlwifi 0000:01:00.0: iwl_sta_ucode_activate Added STA id 148 addr 00:00:00:00:00:00 to uCode not sure how it happen, but adding the sanity check to prevent memory corruption Signed-off-by: Wey-Yi Guy <[email protected]> Signed-off-by: John W. Linville <[email protected]> CWE ID: CWE-119
static void iwl_sta_ucode_activate(struct iwl_priv *priv, u8 sta_id) static int iwl_sta_ucode_activate(struct iwl_priv *priv, u8 sta_id) { if (sta_id >= IWLAGN_STATION_COUNT) { IWL_ERR(priv, "invalid sta_id %u", sta_id); return -EINVAL; } if (!(priv->stations[sta_id].used & IWL_STA_DRIVER_ACTIVE)) IWL_ERR(priv, "ACTIVATE a non DRIVER active station id %u " "addr %pM\n", sta_id, priv->stations[sta_id].sta.sta.addr); if (priv->stations[sta_id].used & IWL_STA_UCODE_ACTIVE) { IWL_DEBUG_ASSOC(priv, "STA id %u addr %pM already present in uCode " "(according to driver)\n", sta_id, priv->stations[sta_id].sta.sta.addr); } else { priv->stations[sta_id].used |= IWL_STA_UCODE_ACTIVE; IWL_DEBUG_ASSOC(priv, "Added STA id %u addr %pM to uCode\n", sta_id, priv->stations[sta_id].sta.sta.addr); } return 0; }
169,869
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void DirectoryEntrySync::removeRecursively(ExceptionState& exceptionState) { RefPtr<VoidSyncCallbackHelper> helper = VoidSyncCallbackHelper::create(); m_fileSystem->removeRecursively(this, helper->successCallback(), helper->errorCallback(), DOMFileSystemBase::Synchronous); helper->getResult(exceptionState); } 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
void DirectoryEntrySync::removeRecursively(ExceptionState& exceptionState) { VoidSyncCallbackHelper* helper = VoidSyncCallbackHelper::create(); m_fileSystem->removeRecursively(this, helper->successCallback(), helper->errorCallback(), DOMFileSystemBase::Synchronous); helper->getResult(exceptionState); }
171,419
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: rpl_dio_printopt(netdissect_options *ndo, const struct rpl_dio_genoption *opt, u_int length) { if(length < RPL_DIO_GENOPTION_LEN) return; length -= RPL_DIO_GENOPTION_LEN; ND_TCHECK(opt->rpl_dio_len); while((opt->rpl_dio_type == RPL_OPT_PAD0 && (const u_char *)opt < ndo->ndo_snapend) || ND_TTEST2(*opt,(opt->rpl_dio_len+2))) { unsigned int optlen = opt->rpl_dio_len+2; if(opt->rpl_dio_type == RPL_OPT_PAD0) { optlen = 1; ND_PRINT((ndo, " opt:pad0")); } else { ND_PRINT((ndo, " opt:%s len:%u ", tok2str(rpl_subopt_values, "subopt:%u", opt->rpl_dio_type), optlen)); if(ndo->ndo_vflag > 2) { unsigned int paylen = opt->rpl_dio_len; if(paylen > length) paylen = length; hex_print(ndo, " ", ((const uint8_t *)opt) + RPL_DIO_GENOPTION_LEN, /* content of DIO option */ paylen); } } opt = (const struct rpl_dio_genoption *)(((const char *)opt) + optlen); length -= optlen; } return; trunc: ND_PRINT((ndo," [|truncated]")); return; } Commit Message: (for 4.9.3) CVE-2018-14882/ICMP6 RPL: Add a missing bounds check Moreover: Add and use *_tstr[] strings. Update four tests outputs accordingly. Fix a space. Wang Junjie of 360 ESG Codesafe Team had independently identified this vulnerability in 2018 by means of fuzzing and provided the packet capture file for the test. CWE ID: CWE-125
rpl_dio_printopt(netdissect_options *ndo, const struct rpl_dio_genoption *opt, u_int length) { if(length < RPL_DIO_GENOPTION_LEN) return; length -= RPL_DIO_GENOPTION_LEN; ND_TCHECK(opt->rpl_dio_len); while((opt->rpl_dio_type == RPL_OPT_PAD0 && (const u_char *)opt < ndo->ndo_snapend) || ND_TTEST2(*opt,(opt->rpl_dio_len+2))) { unsigned int optlen = opt->rpl_dio_len+2; if(opt->rpl_dio_type == RPL_OPT_PAD0) { optlen = 1; ND_PRINT((ndo, " opt:pad0")); } else { ND_PRINT((ndo, " opt:%s len:%u ", tok2str(rpl_subopt_values, "subopt:%u", opt->rpl_dio_type), optlen)); if(ndo->ndo_vflag > 2) { unsigned int paylen = opt->rpl_dio_len; if(paylen > length) paylen = length; hex_print(ndo, " ", ((const uint8_t *)opt) + RPL_DIO_GENOPTION_LEN, /* content of DIO option */ paylen); } } opt = (const struct rpl_dio_genoption *)(((const char *)opt) + optlen); length -= optlen; ND_TCHECK(opt->rpl_dio_len); } return; trunc: ND_PRINT((ndo, "%s", rpl_tstr)); return; }
169,831
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static void encode_frame(vpx_codec_ctx_t *ctx, const vpx_image_t *img, vpx_codec_pts_t pts, unsigned int duration, vpx_enc_frame_flags_t flags, unsigned int deadline, VpxVideoWriter *writer) { vpx_codec_iter_t iter = NULL; const vpx_codec_cx_pkt_t *pkt = NULL; const vpx_codec_err_t res = vpx_codec_encode(ctx, img, pts, duration, flags, deadline); if (res != VPX_CODEC_OK) die_codec(ctx, "Failed to encode frame."); while ((pkt = vpx_codec_get_cx_data(ctx, &iter)) != NULL) { if (pkt->kind == VPX_CODEC_CX_FRAME_PKT) { const int keyframe = (pkt->data.frame.flags & VPX_FRAME_IS_KEY) != 0; if (!vpx_video_writer_write_frame(writer, pkt->data.frame.buf, pkt->data.frame.sz, pkt->data.frame.pts)) die_codec(ctx, "Failed to write compressed frame."); printf(keyframe ? "K" : "."); fflush(stdout); } } } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119
static void encode_frame(vpx_codec_ctx_t *ctx, static int encode_frame(vpx_codec_ctx_t *ctx, const vpx_image_t *img, vpx_codec_pts_t pts, unsigned int duration, vpx_enc_frame_flags_t flags, unsigned int deadline, VpxVideoWriter *writer) { int got_pkts = 0; vpx_codec_iter_t iter = NULL; const vpx_codec_cx_pkt_t *pkt = NULL; const vpx_codec_err_t res = vpx_codec_encode(ctx, img, pts, duration, flags, deadline); if (res != VPX_CODEC_OK) die_codec(ctx, "Failed to encode frame."); while ((pkt = vpx_codec_get_cx_data(ctx, &iter)) != NULL) { got_pkts = 1; if (pkt->kind == VPX_CODEC_CX_FRAME_PKT) { const int keyframe = (pkt->data.frame.flags & VPX_FRAME_IS_KEY) != 0; if (!vpx_video_writer_write_frame(writer, pkt->data.frame.buf, pkt->data.frame.sz, pkt->data.frame.pts)) die_codec(ctx, "Failed to write compressed frame."); printf(keyframe ? "K" : "."); fflush(stdout); } } return got_pkts; } static vpx_fixed_buf_t pass0(vpx_image_t *raw, FILE *infile, const VpxInterface *encoder, const vpx_codec_enc_cfg_t *cfg) { vpx_codec_ctx_t codec; int frame_count = 0; vpx_fixed_buf_t stats = {NULL, 0}; if (vpx_codec_enc_init(&codec, encoder->codec_interface(), cfg, 0)) die_codec(&codec, "Failed to initialize encoder"); // Calculate frame statistics. while (vpx_img_read(raw, infile)) { ++frame_count; get_frame_stats(&codec, raw, frame_count, 1, 0, VPX_DL_GOOD_QUALITY, &stats); } // Flush encoder. while (get_frame_stats(&codec, NULL, frame_count, 1, 0, VPX_DL_GOOD_QUALITY, &stats)) {} printf("Pass 0 complete. Processed %d frames.\n", frame_count); if (vpx_codec_destroy(&codec)) die_codec(&codec, "Failed to destroy codec."); return stats; } static void pass1(vpx_image_t *raw, FILE *infile, const char *outfile_name, const VpxInterface *encoder, const vpx_codec_enc_cfg_t *cfg) { VpxVideoInfo info = { encoder->fourcc, cfg->g_w, cfg->g_h, {cfg->g_timebase.num, cfg->g_timebase.den} }; VpxVideoWriter *writer = NULL; vpx_codec_ctx_t codec; int frame_count = 0; writer = vpx_video_writer_open(outfile_name, kContainerIVF, &info); if (!writer) die("Failed to open %s for writing", outfile_name); if (vpx_codec_enc_init(&codec, encoder->codec_interface(), cfg, 0)) die_codec(&codec, "Failed to initialize encoder"); // Encode frames. while (vpx_img_read(raw, infile)) { ++frame_count; encode_frame(&codec, raw, frame_count, 1, 0, VPX_DL_GOOD_QUALITY, writer); } // Flush encoder. while (encode_frame(&codec, NULL, -1, 1, 0, VPX_DL_GOOD_QUALITY, writer)) {} printf("\n"); if (vpx_codec_destroy(&codec)) die_codec(&codec, "Failed to destroy codec."); vpx_video_writer_close(writer); printf("Pass 1 complete. Processed %d frames.\n", frame_count); }
174,491
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: perform_gamma_threshold_tests(png_modifier *pm) { png_byte colour_type = 0; png_byte bit_depth = 0; unsigned int palette_number = 0; /* Don't test more than one instance of each palette - it's pointless, in * fact this test is somewhat excessive since libpng doesn't make this * decision based on colour type or bit depth! */ while (next_format(&colour_type, &bit_depth, &palette_number, 1/*gamma*/)) if (palette_number == 0) { double test_gamma = 1.0; while (test_gamma >= .4) { /* There's little point testing the interlacing vs non-interlacing, * but this can be set from the command line. */ gamma_threshold_test(pm, colour_type, bit_depth, pm->interlace_type, test_gamma, 1/test_gamma); test_gamma *= .95; } /* And a special test for sRGB */ gamma_threshold_test(pm, colour_type, bit_depth, pm->interlace_type, .45455, 2.2); if (fail(pm)) return; } } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
perform_gamma_threshold_tests(png_modifier *pm) { png_byte colour_type = 0; png_byte bit_depth = 0; unsigned int palette_number = 0; /* Don't test more than one instance of each palette - it's pointless, in * fact this test is somewhat excessive since libpng doesn't make this * decision based on colour type or bit depth! * * CHANGED: now test two palettes and, as a side effect, images with and * without tRNS. */ while (next_format(&colour_type, &bit_depth, &palette_number, pm->test_lbg_gamma_threshold, pm->test_tRNS)) if (palette_number < 2) { double test_gamma = 1.0; while (test_gamma >= .4) { /* There's little point testing the interlacing vs non-interlacing, * but this can be set from the command line. */ gamma_threshold_test(pm, colour_type, bit_depth, pm->interlace_type, test_gamma, 1/test_gamma); test_gamma *= .95; } /* And a special test for sRGB */ gamma_threshold_test(pm, colour_type, bit_depth, pm->interlace_type, .45455, 2.2); if (fail(pm)) return; } }
173,682
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: PrintViewManagerBase::PrintViewManagerBase(content::WebContents* web_contents) : PrintManager(web_contents), printing_rfh_(nullptr), printing_succeeded_(false), inside_inner_message_loop_(false), #if !defined(OS_MACOSX) expecting_first_page_(true), #endif queue_(g_browser_process->print_job_manager()->queue()) { DCHECK(queue_.get()); Profile* profile = Profile::FromBrowserContext(web_contents->GetBrowserContext()); printing_enabled_.Init( prefs::kPrintingEnabled, profile->GetPrefs(), base::Bind(&PrintViewManagerBase::UpdatePrintingEnabled, base::Unretained(this))); } Commit Message: Use pdf compositor service for printing when OOPIF is enabled When OOPIF is enabled (by site-per-process flag or top-document-isolation feature), use the pdf compositor service for converting PaintRecord to PDF on renderers. In the future, this will make compositing PDF from multiple renderers possible. [email protected] BUG=455764 Change-Id: I3c28f03f4358e4228239fe1a33384f85e7716e8f Reviewed-on: https://chromium-review.googlesource.com/699765 Commit-Queue: Wei Li <[email protected]> Reviewed-by: Daniel Cheng <[email protected]> Reviewed-by: Lei Zhang <[email protected]> Cr-Commit-Position: refs/heads/master@{#511616} CWE ID: CWE-254
PrintViewManagerBase::PrintViewManagerBase(content::WebContents* web_contents) : PrintManager(web_contents), printing_rfh_(nullptr), printing_succeeded_(false), inside_inner_message_loop_(false), #if !defined(OS_MACOSX) expecting_first_page_(true), #endif queue_(g_browser_process->print_job_manager()->queue()), weak_ptr_factory_(this) { DCHECK(queue_.get()); Profile* profile = Profile::FromBrowserContext(web_contents->GetBrowserContext()); printing_enabled_.Init( prefs::kPrintingEnabled, profile->GetPrefs(), base::Bind(&PrintViewManagerBase::UpdatePrintingEnabled, base::Unretained(this))); }
171,893
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void NetworkHandler::SetCookies( std::unique_ptr<protocol::Array<Network::CookieParam>> cookies, std::unique_ptr<SetCookiesCallback> callback) { if (!process_) { callback->sendFailure(Response::InternalError()); return; } BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::BindOnce( &SetCookiesOnIO, base::Unretained( process_->GetStoragePartition()->GetURLRequestContext()), std::move(cookies), base::BindOnce(&CookiesSetOnIO, std::move(callback)))); } Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable This keeps BrowserContext* and StoragePartition* instead of RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost upon closure of DevTools front-end. Bug: 801117, 783067, 780694 Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b Reviewed-on: https://chromium-review.googlesource.com/876657 Commit-Queue: Andrey Kosyakov <[email protected]> Reviewed-by: Dmitry Gozman <[email protected]> Cr-Commit-Position: refs/heads/master@{#531157} CWE ID: CWE-20
void NetworkHandler::SetCookies( std::unique_ptr<protocol::Array<Network::CookieParam>> cookies, std::unique_ptr<SetCookiesCallback> callback) { if (!storage_partition_) { callback->sendFailure(Response::InternalError()); return; } BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::BindOnce( &SetCookiesOnIO, base::Unretained(storage_partition_->GetURLRequestContext()), std::move(cookies), base::BindOnce(&CookiesSetOnIO, std::move(callback)))); }
172,761
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: PHP_FUNCTION(mcrypt_module_is_block_mode) { MCRYPT_GET_MODE_DIR_ARGS(modes_dir) if (mcrypt_module_is_block_mode(module, dir) == 1) { RETURN_TRUE; } else { RETURN_FALSE; } } Commit Message: Fix bug #72455: Heap Overflow due to integer overflows CWE ID: CWE-190
PHP_FUNCTION(mcrypt_module_is_block_mode) { MCRYPT_GET_MODE_DIR_ARGS(modes_dir) if (mcrypt_module_is_block_mode(module, dir) == 1) { RETURN_TRUE; } else { RETURN_FALSE; } }
167,098
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: ResourceDispatcherHostImpl::ResourceDispatcherHostImpl() : download_file_manager_(new DownloadFileManager(NULL)), save_file_manager_(new SaveFileManager()), request_id_(-1), ALLOW_THIS_IN_INITIALIZER_LIST(weak_factory_(this)), ALLOW_THIS_IN_INITIALIZER_LIST(ssl_delegate_weak_factory_(this)), is_shutdown_(false), max_outstanding_requests_cost_per_process_( kMaxOutstandingRequestsCostPerProcess), filter_(NULL), delegate_(NULL), allow_cross_origin_auth_prompt_(false) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); DCHECK(!g_resource_dispatcher_host); g_resource_dispatcher_host = this; GetContentClient()->browser()->ResourceDispatcherHostCreated(); ANNOTATE_BENIGN_RACE( &last_user_gesture_time_, "We don't care about the precise value, see http://crbug.com/92889"); BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::Bind(&appcache::AppCacheInterceptor::EnsureRegistered)); update_load_states_timer_.reset( new base::RepeatingTimer<ResourceDispatcherHostImpl>()); } Commit Message: Inherits SupportsWeakPtr<T> instead of having WeakPtrFactory<T> This change refines r137676. BUG=122654 TEST=browser_test Review URL: https://chromiumcodereview.appspot.com/10332233 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@139771 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
ResourceDispatcherHostImpl::ResourceDispatcherHostImpl() : download_file_manager_(new DownloadFileManager(NULL)), save_file_manager_(new SaveFileManager()), request_id_(-1), is_shutdown_(false), max_outstanding_requests_cost_per_process_( kMaxOutstandingRequestsCostPerProcess), filter_(NULL), delegate_(NULL), allow_cross_origin_auth_prompt_(false) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); DCHECK(!g_resource_dispatcher_host); g_resource_dispatcher_host = this; GetContentClient()->browser()->ResourceDispatcherHostCreated(); ANNOTATE_BENIGN_RACE( &last_user_gesture_time_, "We don't care about the precise value, see http://crbug.com/92889"); BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::Bind(&appcache::AppCacheInterceptor::EnsureRegistered)); update_load_states_timer_.reset( new base::RepeatingTimer<ResourceDispatcherHostImpl>()); }
170,991
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: int vt_reset_keyboard(int fd) { int kb; /* If we can't read the default, then default to unicode. It's 2017 after all. */ kb = vt_default_utf8() != 0 ? K_UNICODE : K_XLATE; if (ioctl(fd, KDSKBMODE, kb) < 0) return -errno; return 0; } Commit Message: Merge pull request #12378 from rbalint/vt-kbd-reset-check VT kbd reset check CWE ID: CWE-255
int vt_reset_keyboard(int fd) { int kb, r; /* If we can't read the default, then default to unicode. It's 2017 after all. */ kb = vt_default_utf8() != 0 ? K_UNICODE : K_XLATE; r = vt_verify_kbmode(fd); if (r == -EBUSY) { log_debug_errno(r, "Keyboard is not in XLATE or UNICODE mode, not resetting: %m"); return 0; } else if (r < 0) return r; if (ioctl(fd, KDSKBMODE, kb) < 0) return -errno; return 0; }
169,776
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void PrintPreviewUI::OnDidPreviewPage(int page_number, int preview_request_id) { DCHECK_GE(page_number, 0); base::FundamentalValue number(page_number); StringValue ui_identifier(preview_ui_addr_str_); base::FundamentalValue request_id(preview_request_id); web_ui()->CallJavascriptFunction( "onDidPreviewPage", number, ui_identifier, request_id); } Commit Message: Print preview: Use an ID instead of memory pointer string in WebUI. BUG=144051 Review URL: https://chromiumcodereview.appspot.com/10870003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@153342 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-200
void PrintPreviewUI::OnDidPreviewPage(int page_number, int preview_request_id) { DCHECK_GE(page_number, 0); base::FundamentalValue number(page_number); base::FundamentalValue ui_identifier(id_); base::FundamentalValue request_id(preview_request_id); web_ui()->CallJavascriptFunction( "onDidPreviewPage", number, ui_identifier, request_id); }
170,837
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: xmlParseMisc(xmlParserCtxtPtr ctxt) { while (((RAW == '<') && (NXT(1) == '?')) || (CMP4(CUR_PTR, '<', '!', '-', '-')) || IS_BLANK_CH(CUR)) { if ((RAW == '<') && (NXT(1) == '?')) { xmlParsePI(ctxt); } else if (IS_BLANK_CH(CUR)) { NEXT; } else xmlParseComment(ctxt); } } Commit Message: libxml: XML_PARSER_EOF checks from upstream BUG=229019 TBR=cpu Review URL: https://chromiumcodereview.appspot.com/14053009 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@196804 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
xmlParseMisc(xmlParserCtxtPtr ctxt) { while ((ctxt->instate != XML_PARSER_EOF) && (((RAW == '<') && (NXT(1) == '?')) || (CMP4(CUR_PTR, '<', '!', '-', '-')) || IS_BLANK_CH(CUR))) { if ((RAW == '<') && (NXT(1) == '?')) { xmlParsePI(ctxt); } else if (IS_BLANK_CH(CUR)) { NEXT; } else xmlParseComment(ctxt); } }
171,294
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: videobuf_vm_open(struct vm_area_struct *vma) { struct videobuf_mapping *map = vma->vm_private_data; dprintk(2,"vm_open %p [count=%d,vma=%08lx-%08lx]\n",map, map->count,vma->vm_start,vma->vm_end); map->count++; } Commit Message: V4L/DVB (6751): V4L: Memory leak! Fix count in videobuf-vmalloc mmap This is pretty serious bug. map->count is never initialized after the call to kmalloc making the count start at some random trash value. The end result is leaking videobufs. Also, fix up the debug statements to print unsigned values. Pushed to http://ifup.org/hg/v4l-dvb too Signed-off-by: Brandon Philips <[email protected]> Signed-off-by: Mauro Carvalho Chehab <[email protected]> CWE ID: CWE-119
videobuf_vm_open(struct vm_area_struct *vma) { struct videobuf_mapping *map = vma->vm_private_data; dprintk(2,"vm_open %p [count=%u,vma=%08lx-%08lx]\n",map, map->count,vma->vm_start,vma->vm_end); map->count++; }
168,919
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static int rose_parse_ccitt(unsigned char *p, struct rose_facilities_struct *facilities, int len) { unsigned char l, n = 0; char callsign[11]; do { switch (*p & 0xC0) { case 0x00: p += 2; n += 2; len -= 2; break; case 0x40: p += 3; n += 3; len -= 3; break; case 0x80: p += 4; n += 4; len -= 4; break; case 0xC0: l = p[1]; if (*p == FAC_CCITT_DEST_NSAP) { memcpy(&facilities->source_addr, p + 7, ROSE_ADDR_LEN); memcpy(callsign, p + 12, l - 10); callsign[l - 10] = '\0'; asc2ax(&facilities->source_call, callsign); } if (*p == FAC_CCITT_SRC_NSAP) { memcpy(&facilities->dest_addr, p + 7, ROSE_ADDR_LEN); memcpy(callsign, p + 12, l - 10); callsign[l - 10] = '\0'; asc2ax(&facilities->dest_call, callsign); } p += l + 2; n += l + 2; len -= l + 2; break; } } while (*p != 0x00 && len > 0); return n; } Commit Message: ROSE: prevent heap corruption with bad facilities When parsing the FAC_NATIONAL_DIGIS facilities field, it's possible for a remote host to provide more digipeaters than expected, resulting in heap corruption. Check against ROSE_MAX_DIGIS to prevent overflows, and abort facilities parsing on failure. Additionally, when parsing the FAC_CCITT_DEST_NSAP and FAC_CCITT_SRC_NSAP facilities fields, a remote host can provide a length of less than 10, resulting in an underflow in a memcpy size, causing a kernel panic due to massive heap corruption. A length of greater than 20 results in a stack overflow of the callsign array. Abort facilities parsing on these invalid length values. Signed-off-by: Dan Rosenberg <[email protected]> Cc: [email protected] Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-20
static int rose_parse_ccitt(unsigned char *p, struct rose_facilities_struct *facilities, int len) { unsigned char l, n = 0; char callsign[11]; do { switch (*p & 0xC0) { case 0x00: p += 2; n += 2; len -= 2; break; case 0x40: p += 3; n += 3; len -= 3; break; case 0x80: p += 4; n += 4; len -= 4; break; case 0xC0: l = p[1]; /* Prevent overflows*/ if (l < 10 || l > 20) return -1; if (*p == FAC_CCITT_DEST_NSAP) { memcpy(&facilities->source_addr, p + 7, ROSE_ADDR_LEN); memcpy(callsign, p + 12, l - 10); callsign[l - 10] = '\0'; asc2ax(&facilities->source_call, callsign); } if (*p == FAC_CCITT_SRC_NSAP) { memcpy(&facilities->dest_addr, p + 7, ROSE_ADDR_LEN); memcpy(callsign, p + 12, l - 10); callsign[l - 10] = '\0'; asc2ax(&facilities->dest_call, callsign); } p += l + 2; n += l + 2; len -= l + 2; break; } } while (*p != 0x00 && len > 0); return n; }
165,671
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: PageHandler::PageHandler(EmulationHandler* emulation_handler) : DevToolsDomainHandler(Page::Metainfo::domainName), enabled_(false), screencast_enabled_(false), screencast_quality_(kDefaultScreenshotQuality), screencast_max_width_(-1), screencast_max_height_(-1), capture_every_nth_frame_(1), capture_retry_count_(0), has_compositor_frame_metadata_(false), session_id_(0), frame_counter_(0), frames_in_flight_(0), video_consumer_(nullptr), last_surface_size_(gfx::Size()), host_(nullptr), emulation_handler_(emulation_handler), observer_(this), weak_factory_(this) { bool create_video_consumer = true; #ifdef OS_ANDROID if (!CompositorImpl::IsInitialized()) create_video_consumer = false; #endif if (create_video_consumer) { video_consumer_ = std::make_unique<DevToolsVideoConsumer>( base::BindRepeating(&PageHandler::OnFrameFromVideoConsumer, weak_factory_.GetWeakPtr())); } DCHECK(emulation_handler_); } Commit Message: [DevTools] Do not allow Page.setDownloadBehavior for extensions Bug: 866426 Change-Id: I71b672978e1a8ec779ede49da16b21198567d3a4 Reviewed-on: https://chromium-review.googlesource.com/c/1270007 Commit-Queue: Dmitry Gozman <[email protected]> Reviewed-by: Devlin <[email protected]> Cr-Commit-Position: refs/heads/master@{#598004} CWE ID: CWE-20
PageHandler::PageHandler(EmulationHandler* emulation_handler) PageHandler::PageHandler(EmulationHandler* emulation_handler, bool allow_set_download_behavior) : DevToolsDomainHandler(Page::Metainfo::domainName), enabled_(false), screencast_enabled_(false), screencast_quality_(kDefaultScreenshotQuality), screencast_max_width_(-1), screencast_max_height_(-1), capture_every_nth_frame_(1), capture_retry_count_(0), has_compositor_frame_metadata_(false), session_id_(0), frame_counter_(0), frames_in_flight_(0), video_consumer_(nullptr), last_surface_size_(gfx::Size()), host_(nullptr), emulation_handler_(emulation_handler), allow_set_download_behavior_(allow_set_download_behavior), observer_(this), weak_factory_(this) { bool create_video_consumer = true; #ifdef OS_ANDROID if (!CompositorImpl::IsInitialized()) create_video_consumer = false; #endif if (create_video_consumer) { video_consumer_ = std::make_unique<DevToolsVideoConsumer>( base::BindRepeating(&PageHandler::OnFrameFromVideoConsumer, weak_factory_.GetWeakPtr())); } DCHECK(emulation_handler_); }
172,607
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: TaskService::TaskService() : next_instance_id_(0), bound_instance_id_(kInvalidInstanceId) {} Commit Message: Change ReadWriteLock to Lock+ConditionVariable in TaskService There are non-trivial performance implications of using shared SRWLocking on Windows as more state has to be checked. Since there are only two uses of the ReadWriteLock in Chromium after over 1 year, the decision is to remove it. BUG=758721 Change-Id: I84d1987d7b624a89e896eb37184ee50845c39d80 Reviewed-on: https://chromium-review.googlesource.com/634423 Commit-Queue: Robert Liao <[email protected]> Reviewed-by: Takashi Toyoshima <[email protected]> Reviewed-by: Francois Doray <[email protected]> Cr-Commit-Position: refs/heads/master@{#497632} CWE ID: CWE-20
TaskService::TaskService()
172,213
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: ExprAppendMultiKeysymList(ExprDef *expr, ExprDef *append) { unsigned nSyms = darray_size(expr->keysym_list.syms); unsigned numEntries = darray_size(append->keysym_list.syms); darray_append(expr->keysym_list.symsMapIndex, nSyms); darray_append(expr->keysym_list.symsNumEntries, numEntries); darray_concat(expr->keysym_list.syms, append->keysym_list.syms); FreeStmt((ParseCommon *) &append); return expr; } Commit Message: xkbcomp: fix pointer value for FreeStmt Signed-off-by: Peter Hutterer <[email protected]> CWE ID: CWE-416
ExprAppendMultiKeysymList(ExprDef *expr, ExprDef *append) { unsigned nSyms = darray_size(expr->keysym_list.syms); unsigned numEntries = darray_size(append->keysym_list.syms); darray_append(expr->keysym_list.symsMapIndex, nSyms); darray_append(expr->keysym_list.symsNumEntries, numEntries); darray_concat(expr->keysym_list.syms, append->keysym_list.syms); FreeStmt((ParseCommon *) append); return expr; }
169,093
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void LinkChangeSerializerMarkupAccumulator::appendElement(StringBuilder& result, Element& element, Namespaces* namespaces) { if (element.hasTagName(HTMLNames::htmlTag)) { result.append('\n'); MarkupFormatter::appendComment(result, String::format(" saved from url=(%04d)%s ", static_cast<int>(document().url().string().utf8().length()), document().url().string().utf8().data())); result.append('\n'); } if (element.hasTagName(HTMLNames::baseTag)) { result.appendLiteral("<base href=\".\""); if (!document().baseTarget().isEmpty()) { result.appendLiteral(" target=\""); MarkupFormatter::appendAttributeValue(result, document().baseTarget(), document().isHTMLDocument()); result.append('"'); } if (document().isXHTMLDocument()) result.appendLiteral(" />"); else result.appendLiteral(">"); } else { SerializerMarkupAccumulator::appendElement(result, element, namespaces); } } Commit Message: Escape "--" in the page URL at page serialization This patch makes page serializer to escape the page URL embed into a HTML comment of result HTML[1] to avoid inserting text as HTML from URL by introducing a static member function |PageSerialzier::markOfTheWebDeclaration()| for sharing it between |PageSerialzier| and |WebPageSerialzier| classes. [1] We use following format for serialized HTML: saved from url=(${lengthOfURL})${URL} BUG=503217 TEST=webkit_unit_tests --gtest_filter=PageSerializerTest.markOfTheWebDeclaration TEST=webkit_unit_tests --gtest_filter=WebPageSerializerTest.fromUrlWithMinusMinu Review URL: https://codereview.chromium.org/1371323003 Cr-Commit-Position: refs/heads/master@{#351736} CWE ID: CWE-20
void LinkChangeSerializerMarkupAccumulator::appendElement(StringBuilder& result, Element& element, Namespaces* namespaces) { if (element.hasTagName(HTMLNames::htmlTag)) { result.append('\n'); MarkupFormatter::appendComment(result, PageSerializer::markOfTheWebDeclaration(document().url())); result.append('\n'); } if (element.hasTagName(HTMLNames::baseTag)) { result.appendLiteral("<base href=\".\""); if (!document().baseTarget().isEmpty()) { result.appendLiteral(" target=\""); MarkupFormatter::appendAttributeValue(result, document().baseTarget(), document().isHTMLDocument()); result.append('"'); } if (document().isXHTMLDocument()) result.appendLiteral(" />"); else result.appendLiteral(">"); } else { SerializerMarkupAccumulator::appendElement(result, element, namespaces); } }
171,785
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: OMX_BUFFERHEADERTYPE *OMXNodeInstance::findBufferHeader(OMX::buffer_id buffer) { if (buffer == 0) { return NULL; } Mutex::Autolock autoLock(mBufferIDLock); ssize_t index = mBufferIDToBufferHeader.indexOfKey(buffer); if (index < 0) { CLOGW("findBufferHeader: buffer %u not found", buffer); return NULL; } return mBufferIDToBufferHeader.valueAt(index); } Commit Message: DO NOT MERGE omx: check buffer port before using Bug: 28816827 Change-Id: I3d5bad4a1ef96dec544b05bb31cc6f7109aae0a5 CWE ID: CWE-119
OMX_BUFFERHEADERTYPE *OMXNodeInstance::findBufferHeader(OMX::buffer_id buffer) { OMX_BUFFERHEADERTYPE *OMXNodeInstance::findBufferHeader( OMX::buffer_id buffer, OMX_U32 portIndex) { if (buffer == 0) { return NULL; } Mutex::Autolock autoLock(mBufferIDLock); ssize_t index = mBufferIDToBufferHeader.indexOfKey(buffer); if (index < 0) { CLOGW("findBufferHeader: buffer %u not found", buffer); return NULL; } OMX_BUFFERHEADERTYPE *header = mBufferIDToBufferHeader.valueAt(index); BufferMeta *buffer_meta = static_cast<BufferMeta *>(header->pAppPrivate); if (buffer_meta->getPortIndex() != portIndex) { CLOGW("findBufferHeader: buffer %u found but with incorrect port index.", buffer); android_errorWriteLog(0x534e4554, "28816827"); return NULL; } return header; }
173,528
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void RenderFrameImpl::DidAddMessageToConsole( const blink::WebConsoleMessage& message, const blink::WebString& source_name, unsigned source_line, const blink::WebString& stack_trace) { logging::LogSeverity log_severity = logging::LOG_VERBOSE; switch (message.level) { case blink::mojom::ConsoleMessageLevel::kVerbose: log_severity = logging::LOG_VERBOSE; break; case blink::mojom::ConsoleMessageLevel::kInfo: log_severity = logging::LOG_INFO; break; case blink::mojom::ConsoleMessageLevel::kWarning: log_severity = logging::LOG_WARNING; break; case blink::mojom::ConsoleMessageLevel::kError: log_severity = logging::LOG_ERROR; break; default: log_severity = logging::LOG_VERBOSE; } if (ShouldReportDetailedMessageForSource(source_name)) { for (auto& observer : observers_) { observer.DetailedConsoleMessageAdded( message.text.Utf16(), source_name.Utf16(), stack_trace.Utf16(), source_line, static_cast<uint32_t>(log_severity)); } } Send(new FrameHostMsg_DidAddMessageToConsole( routing_id_, static_cast<int32_t>(log_severity), message.text.Utf16(), static_cast<int32_t>(source_line), source_name.Utf16())); } Commit Message: Convert FrameHostMsg_DidAddMessageToConsole to Mojo. Note: Since this required changing the test RenderViewImplTest.DispatchBeforeUnloadCanDetachFrame, I manually re-introduced https://crbug.com/666714 locally (the bug the test was added for), and reran the test to confirm that it still covers the bug. Bug: 786836 Change-Id: I110668fa6f0f261fd2ac36bb91a8d8b31c99f4f1 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1526270 Commit-Queue: Lowell Manners <[email protected]> Reviewed-by: Daniel Cheng <[email protected]> Reviewed-by: Camille Lamy <[email protected]> Cr-Commit-Position: refs/heads/master@{#653137} CWE ID: CWE-416
void RenderFrameImpl::DidAddMessageToConsole( const blink::WebConsoleMessage& message, const blink::WebString& source_name, unsigned source_line, const blink::WebString& stack_trace) { logging::LogSeverity log_severity = logging::LOG_VERBOSE; switch (message.level) { case blink::mojom::ConsoleMessageLevel::kVerbose: log_severity = logging::LOG_VERBOSE; break; case blink::mojom::ConsoleMessageLevel::kInfo: log_severity = logging::LOG_INFO; break; case blink::mojom::ConsoleMessageLevel::kWarning: log_severity = logging::LOG_WARNING; break; case blink::mojom::ConsoleMessageLevel::kError: log_severity = logging::LOG_ERROR; break; default: log_severity = logging::LOG_VERBOSE; } if (ShouldReportDetailedMessageForSource(source_name)) { for (auto& observer : observers_) { observer.DetailedConsoleMessageAdded( message.text.Utf16(), source_name.Utf16(), stack_trace.Utf16(), source_line, static_cast<uint32_t>(log_severity)); } } GetFrameHost()->DidAddMessageToConsole(message.level, message.text.Utf16(), static_cast<int32_t>(source_line), source_name.Utf16()); }
172,488
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static void registerStreamURLTask(void* context) { OwnPtr<BlobRegistryContext> blobRegistryContext = adoptPtr(static_cast<BlobRegistryContext*>(context)); blobRegistry().registerStreamURL(blobRegistryContext->url, blobRegistryContext->type); } Commit Message: Remove BlobRegistry indirection since there is only one implementation. BUG= Review URL: https://chromiumcodereview.appspot.com/15851008 git-svn-id: svn://svn.chromium.org/blink/trunk@152746 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID:
static void registerStreamURLTask(void* context) { OwnPtr<BlobRegistryContext> blobRegistryContext = adoptPtr(static_cast<BlobRegistryContext*>(context)); if (WebBlobRegistry* registry = blobRegistry()) registry->registerStreamURL(blobRegistryContext->url, blobRegistryContext->type); }
170,689
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: BufferMeta(const sp<IMemory> &mem, OMX_U32 portIndex, bool is_backup = false) : mMem(mem), mIsBackup(is_backup), mPortIndex(portIndex) { } Commit Message: DO NOT MERGE: IOMX: work against metadata buffer spoofing - Prohibit direct set/getParam/Settings for extensions meant for OMXNodeInstance alone. This disallows enabling metadata mode without the knowledge of OMXNodeInstance. - Use a backup buffer for metadata mode buffers and do not directly share with clients. - Disallow setting up metadata mode/tunneling/input surface after first sendCommand. - Disallow store-meta for input cross process. - Disallow emptyBuffer for surface input (via IOMX). - Fix checking for input surface. Bug: 29422020 Change-Id: I801c77b80e703903f62e42d76fd2e76a34e4bc8e (cherry picked from commit 7c3c2fa3e233c656fc8c2fc2a6634b3ecf8a23e8) CWE ID: CWE-200
BufferMeta(const sp<IMemory> &mem, OMX_U32 portIndex, bool is_backup = false) BufferMeta( const sp<IMemory> &mem, OMX_U32 portIndex, bool copyToOmx, bool copyFromOmx, OMX_U8 *backup) : mMem(mem), mCopyFromOmx(copyFromOmx), mCopyToOmx(copyToOmx), mPortIndex(portIndex), mBackup(backup) { }
174,124
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void PushMessagingServiceImpl::DidHandleMessage( const std::string& app_id, const base::Closure& message_handled_closure) { auto in_flight_iterator = in_flight_message_deliveries_.find(app_id); DCHECK(in_flight_iterator != in_flight_message_deliveries_.end()); in_flight_message_deliveries_.erase(in_flight_iterator); #if BUILDFLAG(ENABLE_BACKGROUND) if (in_flight_message_deliveries_.empty()) in_flight_keep_alive_.reset(); #endif message_handled_closure.Run(); if (push_messaging_service_observer_) push_messaging_service_observer_->OnMessageHandled(); } Commit Message: Remove some senseless indirection from the Push API code Four files to call one Java function. Let's just call it directly. BUG= Change-Id: I6e988e9a000051dd7e3dd2b517a33a09afc2fff6 Reviewed-on: https://chromium-review.googlesource.com/749147 Reviewed-by: Anita Woodruff <[email protected]> Commit-Queue: Peter Beverloo <[email protected]> Cr-Commit-Position: refs/heads/master@{#513464} CWE ID: CWE-119
void PushMessagingServiceImpl::DidHandleMessage( const std::string& app_id, const base::Closure& message_handled_closure) { auto in_flight_iterator = in_flight_message_deliveries_.find(app_id); DCHECK(in_flight_iterator != in_flight_message_deliveries_.end()); in_flight_message_deliveries_.erase(in_flight_iterator); #if BUILDFLAG(ENABLE_BACKGROUND) if (in_flight_message_deliveries_.empty()) in_flight_keep_alive_.reset(); #endif message_handled_closure.Run(); #if defined(OS_ANDROID) chrome::android::Java_PushMessagingServiceObserver_onMessageHandled( base::android::AttachCurrentThread()); #endif }
172,941
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void FillConstant(uint8_t *data, int stride, uint8_t fill_constant) { for (int h = 0; h < height_; ++h) { for (int w = 0; w < width_; ++w) { data[h * stride + w] = fill_constant; } } } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119
void FillConstant(uint8_t *data, int stride, uint8_t fill_constant) { // Sum of Absolute Differences Average. Given two blocks, and a prediction // calculate the absolute difference between one pixel and average of the // corresponding and predicted pixels; accumulate. unsigned int ReferenceSADavg(int block_idx) { unsigned int sad = 0; const uint8_t *const reference8 = GetReference(block_idx); const uint8_t *const source8 = source_data_; const uint8_t *const second_pred8 = second_pred_; #if CONFIG_VP9_HIGHBITDEPTH const uint16_t *const reference16 = CONVERT_TO_SHORTPTR(GetReference(block_idx)); const uint16_t *const source16 = CONVERT_TO_SHORTPTR(source_data_); const uint16_t *const second_pred16 = CONVERT_TO_SHORTPTR(second_pred_); #endif // CONFIG_VP9_HIGHBITDEPTH for (int h = 0; h < height_; ++h) { for (int w = 0; w < width_; ++w) { if (!use_high_bit_depth_) { const int tmp = second_pred8[h * width_ + w] + reference8[h * reference_stride_ + w]; const uint8_t comp_pred = ROUND_POWER_OF_TWO(tmp, 1); sad += abs(source8[h * source_stride_ + w] - comp_pred); #if CONFIG_VP9_HIGHBITDEPTH } else { const int tmp = second_pred16[h * width_ + w] + reference16[h * reference_stride_ + w]; const uint16_t comp_pred = ROUND_POWER_OF_TWO(tmp, 1); sad += abs(source16[h * source_stride_ + w] - comp_pred); #endif // CONFIG_VP9_HIGHBITDEPTH } } } return sad; } void FillConstant(uint8_t *data, int stride, uint16_t fill_constant) { uint8_t *data8 = data; #if CONFIG_VP9_HIGHBITDEPTH uint16_t *data16 = CONVERT_TO_SHORTPTR(data); #endif // CONFIG_VP9_HIGHBITDEPTH for (int h = 0; h < height_; ++h) { for (int w = 0; w < width_; ++w) { if (!use_high_bit_depth_) { data8[h * stride + w] = static_cast<uint8_t>(fill_constant); #if CONFIG_VP9_HIGHBITDEPTH } else { data16[h * stride + w] = fill_constant; #endif // CONFIG_VP9_HIGHBITDEPTH } } } }
174,571
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: my_object_objpath (MyObject *obj, const char *incoming, const char **outgoing, GError **error) { if (strcmp (incoming, "/org/freedesktop/DBus/GLib/Tests/MyTestObject")) { g_set_error (error, MY_OBJECT_ERROR, MY_OBJECT_ERROR_FOO, "invalid incoming object"); return FALSE; } *outgoing = "/org/freedesktop/DBus/GLib/Tests/MyTestObject2"; return TRUE; } Commit Message: CWE ID: CWE-264
my_object_objpath (MyObject *obj, const char *incoming, const char **outgoing, GError **error)
165,114
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: GURL DecorateFrontendURL(const GURL& base_url) { std::string frontend_url = base_url.spec(); std::string url_string( frontend_url + ((frontend_url.find("?") == std::string::npos) ? "?" : "&") + "dockSide=undocked"); // TODO(dgozman): remove this support in M38. base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); if (command_line->HasSwitch(switches::kEnableDevToolsExperiments)) url_string += "&experiments=true"; if (command_line->HasSwitch(switches::kDevToolsFlags)) { std::string flags = command_line->GetSwitchValueASCII( switches::kDevToolsFlags); flags = net::EscapeQueryParamValue(flags, false); url_string += "&flags=" + flags; } #if defined(DEBUG_DEVTOOLS) url_string += "&debugFrontend=true"; #endif // defined(DEBUG_DEVTOOLS) return GURL(url_string); } Commit Message: [DevTools] Move sanitize url to devtools_ui.cc. Compatibility script is not reliable enough. BUG=653134 Review-Url: https://codereview.chromium.org/2403633002 Cr-Commit-Position: refs/heads/master@{#425814} CWE ID: CWE-200
GURL DecorateFrontendURL(const GURL& base_url) { std::string frontend_url = base_url.spec(); std::string url_string( frontend_url + ((frontend_url.find("?") == std::string::npos) ? "?" : "&") + "dockSide=undocked"); // TODO(dgozman): remove this support in M38. base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); if (command_line->HasSwitch(switches::kEnableDevToolsExperiments)) url_string += "&experiments=true"; if (command_line->HasSwitch(switches::kDevToolsFlags)) { url_string += "&" + command_line->GetSwitchValueASCII( switches::kDevToolsFlags); } #if defined(DEBUG_DEVTOOLS) url_string += "&debugFrontend=true"; #endif // defined(DEBUG_DEVTOOLS) return GURL(url_string); }
172,508
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void AXTree::PopulateOrderedSetItems(const AXNode* ordered_set, const AXNode* local_parent, std::vector<const AXNode*>& items, bool node_is_radio_button) const { if (!(ordered_set == local_parent)) { if (local_parent->data().role == ordered_set->data().role) return; } for (int i = 0; i < local_parent->child_count(); ++i) { const AXNode* child = local_parent->GetUnignoredChildAtIndex(i); if (node_is_radio_button && child->data().role == ax::mojom::Role::kRadioButton) items.push_back(child); if (!node_is_radio_button && child->SetRoleMatchesItemRole(ordered_set)) items.push_back(child); if (child->data().role == ax::mojom::Role::kGenericContainer || child->data().role == ax::mojom::Role::kIgnored) { PopulateOrderedSetItems(ordered_set, child, items, node_is_radio_button); } } } Commit Message: Position info (item n of m) incorrect if hidden focusable items in list Bug: 836997 Change-Id: I971fa7076f72d51829b36af8e379260d48ca25ec Reviewed-on: https://chromium-review.googlesource.com/c/1450235 Commit-Queue: Aaron Leventhal <[email protected]> Reviewed-by: Nektarios Paisios <[email protected]> Cr-Commit-Position: refs/heads/master@{#628890} CWE ID: CWE-190
void AXTree::PopulateOrderedSetItems(const AXNode* ordered_set, const AXNode* local_parent, std::vector<const AXNode*>& items, bool node_is_radio_button) const { if (!(ordered_set == local_parent)) { if (local_parent->data().role == ordered_set->data().role) return; } for (int i = 0; i < local_parent->child_count(); ++i) { const AXNode* child = local_parent->GetUnignoredChildAtIndex(i); // Invisible children should not be counted. // However, in the collapsed container case (e.g. a combobox), items can // still be chosen/navigated. However, the options in these collapsed // containers are historically marked invisible. Therefore, in that case, // count the invisible items. Only check 2 levels up, as combobox containers // are never higher. if (child->data().HasState(ax::mojom::State::kInvisible) && !IsCollapsed(local_parent) && !IsCollapsed(local_parent->parent())) { continue; } if (node_is_radio_button && child->data().role == ax::mojom::Role::kRadioButton) items.push_back(child); if (!node_is_radio_button && child->SetRoleMatchesItemRole(ordered_set)) items.push_back(child); if (child->data().role == ax::mojom::Role::kGenericContainer || child->data().role == ax::mojom::Role::kIgnored) { PopulateOrderedSetItems(ordered_set, child, items, node_is_radio_button); } } }
172,061
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: BGD_DECLARE(void) gdImageWebp (gdImagePtr im, FILE * outFile) { gdIOCtx *out = gdNewFileCtx(outFile); if (out == NULL) { return; } gdImageWebpCtx(im, out, -1); out->gd_free(out); } Commit Message: Fix double-free in gdImageWebPtr() The issue is that gdImageWebpCtx() (which is called by gdImageWebpPtr() and the other WebP output functions to do the real work) does not return whether it succeeded or failed, so this is not checked in gdImageWebpPtr() and the function wrongly assumes everything is okay, which is not, in this case, because there is a size limitation for WebP, namely that the width and height must by less than 16383. We can't change the signature of gdImageWebpCtx() for API compatibility reasons, so we introduce the static helper _gdImageWebpCtx() which returns success respective failure, so gdImageWebpPtr() and gdImageWebpPtrEx() can check the return value. We leave it solely to libwebp for now to report warnings regarding the failing write. This issue had been reported by Ibrahim El-Sayed to [email protected]. CVE-2016-6912 CWE ID: CWE-415
BGD_DECLARE(void) gdImageWebp (gdImagePtr im, FILE * outFile) { gdIOCtx *out = gdNewFileCtx(outFile); if (out == NULL) { return; } _gdImageWebpCtx(im, out, -1); out->gd_free(out); }
168,816
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: CoordinatorImpl::CoordinatorImpl(service_manager::Connector* connector) : next_dump_id_(0), client_process_timeout_(base::TimeDelta::FromSeconds(15)) { process_map_ = std::make_unique<ProcessMap>(connector); DCHECK(!g_coordinator_impl); g_coordinator_impl = this; base::trace_event::MemoryDumpManager::GetInstance()->set_tracing_process_id( mojom::kServiceTracingProcessId); tracing_observer_ = std::make_unique<TracingObserver>( base::trace_event::TraceLog::GetInstance(), nullptr); } Commit Message: Fix heap-use-after-free by using weak factory instead of Unretained Bug: 856578 Change-Id: Ifb2a1b7e6c22e1af36e12eedba72427f51d925b9 Reviewed-on: https://chromium-review.googlesource.com/1114617 Reviewed-by: Hector Dearman <[email protected]> Commit-Queue: Hector Dearman <[email protected]> Cr-Commit-Position: refs/heads/master@{#571528} CWE ID: CWE-416
CoordinatorImpl::CoordinatorImpl(service_manager::Connector* connector) : next_dump_id_(0), client_process_timeout_(base::TimeDelta::FromSeconds(15)), weak_ptr_factory_(this) { process_map_ = std::make_unique<ProcessMap>(connector); DCHECK(!g_coordinator_impl); g_coordinator_impl = this; base::trace_event::MemoryDumpManager::GetInstance()->set_tracing_process_id( mojom::kServiceTracingProcessId); tracing_observer_ = std::make_unique<TracingObserver>( base::trace_event::TraceLog::GetInstance(), nullptr); }
173,211
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: PlatformFileForTransit GetFileHandleForProcess(base::PlatformFile handle, base::ProcessHandle process, bool close_source_handle) { IPC::PlatformFileForTransit out_handle; #if defined(OS_WIN) DWORD options = DUPLICATE_SAME_ACCESS; if (close_source_handle) options |= DUPLICATE_CLOSE_SOURCE; if (!::DuplicateHandle(::GetCurrentProcess(), handle, process, &out_handle, 0, FALSE, options)) { out_handle = IPC::InvalidPlatformFileForTransit(); } #elif defined(OS_POSIX) int fd = close_source_handle ? handle : ::dup(handle); out_handle = base::FileDescriptor(fd, true); #else #error Not implemented. #endif return out_handle; } Commit Message: GetFileHandleForProcess should check for INVALID_HANDLE_VALUE BUG=243339 [email protected] Review URL: https://codereview.chromium.org/16020004 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@202207 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
PlatformFileForTransit GetFileHandleForProcess(base::PlatformFile handle, base::ProcessHandle process, bool close_source_handle) { IPC::PlatformFileForTransit out_handle; #if defined(OS_WIN) DWORD options = DUPLICATE_SAME_ACCESS; if (close_source_handle) options |= DUPLICATE_CLOSE_SOURCE; if (handle == INVALID_HANDLE_VALUE || !::DuplicateHandle(::GetCurrentProcess(), handle, process, &out_handle, 0, FALSE, options)) { out_handle = IPC::InvalidPlatformFileForTransit(); } #elif defined(OS_POSIX) int fd = close_source_handle ? handle : ::dup(handle); out_handle = base::FileDescriptor(fd, true); #else #error Not implemented. #endif return out_handle; }
171,314
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: OMX_ERRORTYPE SoftFlacEncoder::internalGetParameter( OMX_INDEXTYPE index, OMX_PTR params) { ALOGV("SoftFlacEncoder::internalGetParameter(index=0x%x)", index); switch (index) { 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->nChannels = mNumChannels; pcmParams->nSamplingRate = mSampleRate; return OMX_ErrorNone; } case OMX_IndexParamAudioFlac: { OMX_AUDIO_PARAM_FLACTYPE *flacParams = (OMX_AUDIO_PARAM_FLACTYPE *)params; flacParams->nCompressionLevel = mCompressionLevel; flacParams->nChannels = mNumChannels; flacParams->nSampleRate = 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 SoftFlacEncoder::internalGetParameter( OMX_INDEXTYPE index, OMX_PTR params) { ALOGV("SoftFlacEncoder::internalGetParameter(index=0x%x)", index); switch (index) { 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->nChannels = mNumChannels; pcmParams->nSamplingRate = mSampleRate; return OMX_ErrorNone; } case OMX_IndexParamAudioFlac: { OMX_AUDIO_PARAM_FLACTYPE *flacParams = (OMX_AUDIO_PARAM_FLACTYPE *)params; if (!isValidOMXParam(flacParams)) { return OMX_ErrorBadParameter; } flacParams->nCompressionLevel = mCompressionLevel; flacParams->nChannels = mNumChannels; flacParams->nSampleRate = mSampleRate; return OMX_ErrorNone; } default: return SimpleSoftOMXComponent::internalGetParameter(index, params); } }
174,203
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: php_stream *php_stream_zip_open(char *filename, char *path, char *mode STREAMS_DC TSRMLS_DC) { struct zip_file *zf = NULL; int err = 0; php_stream *stream = NULL; struct php_zip_stream_data_t *self; struct zip *stream_za; if (strncmp(mode,"r", strlen("r")) != 0) { return NULL; } if (filename) { if (ZIP_OPENBASEDIR_CHECKPATH(filename)) { return NULL; } /* duplicate to make the stream za independent (esp. for MSHUTDOWN) */ stream_za = zip_open(filename, ZIP_CREATE, &err); if (!stream_za) { return NULL; } zf = zip_fopen(stream_za, path, 0); if (zf) { self = emalloc(sizeof(*self)); self->za = stream_za; self->zf = zf; self->stream = NULL; self->cursor = 0; stream = php_stream_alloc(&php_stream_zipio_ops, self, NULL, mode); stream->orig_path = estrdup(path); } else { zip_close(stream_za); } } if (!stream) { return NULL; } else { return stream; } } Commit Message: CWE ID: CWE-119
php_stream *php_stream_zip_open(char *filename, char *path, char *mode STREAMS_DC TSRMLS_DC) { struct zip_file *zf = NULL; int err = 0; php_stream *stream = NULL; struct php_zip_stream_data_t *self; struct zip *stream_za; if (strncmp(mode,"r", strlen("r")) != 0) { return NULL; } if (filename) { if (ZIP_OPENBASEDIR_CHECKPATH(filename)) { return NULL; } /* duplicate to make the stream za independent (esp. for MSHUTDOWN) */ stream_za = zip_open(filename, ZIP_CREATE, &err); if (!stream_za) { return NULL; } zf = zip_fopen(stream_za, path, 0); if (zf) { self = emalloc(sizeof(*self)); self->za = stream_za; self->zf = zf; self->stream = NULL; self->cursor = 0; stream = php_stream_alloc(&php_stream_zipio_ops, self, NULL, mode); stream->orig_path = estrdup(path); } else { zip_close(stream_za); } } if (!stream) { return NULL; } else { return stream; } }
164,968
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static unsigned int subpel_variance_ref(const uint8_t *ref, const uint8_t *src, int l2w, int l2h, int xoff, int yoff, unsigned int *sse_ptr) { int se = 0; unsigned int sse = 0; const int w = 1 << l2w, h = 1 << l2h; for (int y = 0; y < h; y++) { for (int x = 0; x < w; x++) { const int a1 = ref[(w + 1) * (y + 0) + x + 0]; const int a2 = ref[(w + 1) * (y + 0) + x + 1]; const int b1 = ref[(w + 1) * (y + 1) + x + 0]; const int b2 = ref[(w + 1) * (y + 1) + x + 1]; const int a = a1 + (((a2 - a1) * xoff + 8) >> 4); const int b = b1 + (((b2 - b1) * xoff + 8) >> 4); const int r = a + (((b - a) * yoff + 8) >> 4); int diff = r - src[w * y + x]; se += diff; sse += diff * diff; } } *sse_ptr = sse; return sse - (((int64_t) se * se) >> (l2w + l2h)); } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119
static unsigned int subpel_variance_ref(const uint8_t *ref, const uint8_t *src, static unsigned int mb_ss_ref(const int16_t *src) { unsigned int res = 0; for (int i = 0; i < 256; ++i) { res += src[i] * src[i]; } return res; } static uint32_t variance_ref(const uint8_t *src, const uint8_t *ref, int l2w, int l2h, int src_stride_coeff, int ref_stride_coeff, uint32_t *sse_ptr, bool use_high_bit_depth_, vpx_bit_depth_t bit_depth) { int64_t se = 0; uint64_t sse = 0; const int w = 1 << l2w; const int h = 1 << l2h; for (int y = 0; y < h; y++) { for (int x = 0; x < w; x++) { int diff; if (!use_high_bit_depth_) { diff = ref[w * y * ref_stride_coeff + x] - src[w * y * src_stride_coeff + x]; se += diff; sse += diff * diff; #if CONFIG_VP9_HIGHBITDEPTH } else { diff = CONVERT_TO_SHORTPTR(ref)[w * y * ref_stride_coeff + x] - CONVERT_TO_SHORTPTR(src)[w * y * src_stride_coeff + x]; se += diff; sse += diff * diff; #endif // CONFIG_VP9_HIGHBITDEPTH } } } RoundHighBitDepth(bit_depth, &se, &sse); *sse_ptr = static_cast<uint32_t>(sse); return static_cast<uint32_t>(sse - ((static_cast<int64_t>(se) * se) >> (l2w + l2h))); } /* The subpel reference functions differ from the codec version in one aspect: * they calculate the bilinear factors directly instead of using a lookup table * and therefore upshift xoff and yoff by 1. Only every other calculated value * is used so the codec version shrinks the table to save space and maintain * compatibility with vp8. */ static uint32_t subpel_variance_ref(const uint8_t *ref, const uint8_t *src, int l2w, int l2h, int xoff, int yoff, uint32_t *sse_ptr, bool use_high_bit_depth_, vpx_bit_depth_t bit_depth) { int64_t se = 0; uint64_t sse = 0; const int w = 1 << l2w; const int h = 1 << l2h; xoff <<= 1; yoff <<= 1; for (int y = 0; y < h; y++) { for (int x = 0; x < w; x++) { // Bilinear interpolation at a 16th pel step. if (!use_high_bit_depth_) { const int a1 = ref[(w + 1) * (y + 0) + x + 0]; const int a2 = ref[(w + 1) * (y + 0) + x + 1]; const int b1 = ref[(w + 1) * (y + 1) + x + 0]; const int b2 = ref[(w + 1) * (y + 1) + x + 1]; const int a = a1 + (((a2 - a1) * xoff + 8) >> 4); const int b = b1 + (((b2 - b1) * xoff + 8) >> 4); const int r = a + (((b - a) * yoff + 8) >> 4); const int diff = r - src[w * y + x]; se += diff; sse += diff * diff; #if CONFIG_VP9_HIGHBITDEPTH } else { uint16_t *ref16 = CONVERT_TO_SHORTPTR(ref); uint16_t *src16 = CONVERT_TO_SHORTPTR(src); const int a1 = ref16[(w + 1) * (y + 0) + x + 0]; const int a2 = ref16[(w + 1) * (y + 0) + x + 1]; const int b1 = ref16[(w + 1) * (y + 1) + x + 0]; const int b2 = ref16[(w + 1) * (y + 1) + x + 1]; const int a = a1 + (((a2 - a1) * xoff + 8) >> 4); const int b = b1 + (((b2 - b1) * xoff + 8) >> 4); const int r = a + (((b - a) * yoff + 8) >> 4); const int diff = r - src16[w * y + x]; se += diff; sse += diff * diff; #endif // CONFIG_VP9_HIGHBITDEPTH } } } RoundHighBitDepth(bit_depth, &se, &sse); *sse_ptr = static_cast<uint32_t>(sse); return static_cast<uint32_t>(sse - ((static_cast<int64_t>(se) * se) >> (l2w + l2h))); } class SumOfSquaresTest : public ::testing::TestWithParam<SumOfSquaresFunction> { public: SumOfSquaresTest() : func_(GetParam()) {} virtual ~SumOfSquaresTest() { libvpx_test::ClearSystemState(); } protected: void ConstTest(); void RefTest(); SumOfSquaresFunction func_; ACMRandom rnd_; }; void SumOfSquaresTest::ConstTest() { int16_t mem[256]; unsigned int res; for (int v = 0; v < 256; ++v) { for (int i = 0; i < 256; ++i) { mem[i] = v; } ASM_REGISTER_STATE_CHECK(res = func_(mem)); EXPECT_EQ(256u * (v * v), res); } } void SumOfSquaresTest::RefTest() { int16_t mem[256]; for (int i = 0; i < 100; ++i) { for (int j = 0; j < 256; ++j) { mem[j] = rnd_.Rand8() - rnd_.Rand8(); } const unsigned int expected = mb_ss_ref(mem); unsigned int res; ASM_REGISTER_STATE_CHECK(res = func_(mem)); EXPECT_EQ(expected, res); } }
174,595
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: NavigateParams::NavigateParams( Browser* a_browser, const GURL& a_url, content::PageTransition a_transition) : url(a_url), target_contents(NULL), source_contents(NULL), disposition(CURRENT_TAB), transition(a_transition), tabstrip_index(-1), tabstrip_add_types(TabStripModel::ADD_ACTIVE), window_action(NO_ACTION), user_gesture(true), path_behavior(RESPECT), ref_behavior(IGNORE_REF), browser(a_browser), profile(NULL) { } Commit Message: Fix memory error in previous CL. BUG=100315 BUG=99016 TEST=Memory bots go green Review URL: http://codereview.chromium.org/8302001 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@105577 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
NavigateParams::NavigateParams( Browser* a_browser, const GURL& a_url, content::PageTransition a_transition) : url(a_url), target_contents(NULL), source_contents(NULL), disposition(CURRENT_TAB), transition(a_transition), is_renderer_initiated(false), tabstrip_index(-1), tabstrip_add_types(TabStripModel::ADD_ACTIVE), window_action(NO_ACTION), user_gesture(true), path_behavior(RESPECT), ref_behavior(IGNORE_REF), browser(a_browser), profile(NULL) { }
170,249
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static Image *ReadTILEImage(const ImageInfo *image_info, ExceptionInfo *exception) { Image *image, *tile_image; ImageInfo *read_info; /* Initialize Image structure. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); read_info=CloneImageInfo(image_info); SetImageInfoBlob(read_info,(void *) NULL,0); *read_info->magick='\0'; tile_image=ReadImage(read_info,exception); read_info=DestroyImageInfo(read_info); if (tile_image == (Image *) NULL) return((Image *) NULL); image=AcquireImage(image_info); if ((image->columns == 0) || (image->rows == 0)) ThrowReaderException(OptionError,"MustSpecifyImageSize"); if (*image_info->filename == '\0') ThrowReaderException(OptionError,"MustSpecifyAnImageName"); image->colorspace=tile_image->colorspace; image->matte=tile_image->matte; if (image->matte != MagickFalse) (void) SetImageBackgroundColor(image); (void) CopyMagickString(image->filename,image_info->filename,MaxTextExtent); if (LocaleCompare(tile_image->magick,"PATTERN") == 0) { tile_image->tile_offset.x=0; tile_image->tile_offset.y=0; } (void) TextureImage(image,tile_image); tile_image=DestroyImage(tile_image); if (image->colorspace == GRAYColorspace) image->type=GrayscaleType; return(GetFirstImageInList(image)); } Commit Message: CWE ID: CWE-119
static Image *ReadTILEImage(const ImageInfo *image_info, ExceptionInfo *exception) { Image *image, *tile_image; ImageInfo *read_info; MagickBooleanType status; /* Initialize Image structure. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); read_info=CloneImageInfo(image_info); SetImageInfoBlob(read_info,(void *) NULL,0); *read_info->magick='\0'; tile_image=ReadImage(read_info,exception); read_info=DestroyImageInfo(read_info); if (tile_image == (Image *) NULL) return((Image *) NULL); image=AcquireImage(image_info); if ((image->columns == 0) || (image->rows == 0)) ThrowReaderException(OptionError,"MustSpecifyImageSize"); status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } if (*image_info->filename == '\0') ThrowReaderException(OptionError,"MustSpecifyAnImageName"); image->colorspace=tile_image->colorspace; image->matte=tile_image->matte; if (image->matte != MagickFalse) (void) SetImageBackgroundColor(image); (void) CopyMagickString(image->filename,image_info->filename,MaxTextExtent); if (LocaleCompare(tile_image->magick,"PATTERN") == 0) { tile_image->tile_offset.x=0; tile_image->tile_offset.y=0; } (void) TextureImage(image,tile_image); tile_image=DestroyImage(tile_image); if (image->colorspace == GRAYColorspace) image->type=GrayscaleType; return(GetFirstImageInList(image)); }
168,610
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: png_get_mmx_rowbytes_threshold (png_structp png_ptr) { /* Obsolete, to be removed from libpng-1.4.0 */ return (png_ptr? 0L: 0L); } Commit Message: third_party/libpng: update to 1.2.54 [email protected] BUG=560291 Review URL: https://codereview.chromium.org/1467263003 Cr-Commit-Position: refs/heads/master@{#362298} CWE ID: CWE-119
png_get_mmx_rowbytes_threshold (png_structp png_ptr) { /* Obsolete, to be removed from libpng-1.4.0 */ PNG_UNUSED(png_ptr) return 0L; }
172,167
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static base::Callback<void(const gfx::Image&)> Wrap( const base::Callback<void(const SkBitmap&)>& image_decoded_callback) { auto* handler = new ImageDecodedHandlerWithTimeout(image_decoded_callback); base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( FROM_HERE, base::Bind(&ImageDecodedHandlerWithTimeout::OnImageDecoded, handler->weak_ptr_factory_.GetWeakPtr(), gfx::Image()), base::TimeDelta::FromSeconds(kDecodeLogoTimeoutSeconds)); return base::Bind(&ImageDecodedHandlerWithTimeout::OnImageDecoded, handler->weak_ptr_factory_.GetWeakPtr()); } Commit Message: Local NTP: add smoke tests for doodles Split LogoService into LogoService interface and LogoServiceImpl to make it easier to provide fake data to the test. Bug: 768419 Cq-Include-Trybots: master.tryserver.chromium.linux:closure_compilation Change-Id: I84639189d2db1b24a2e139936c99369352bab587 Reviewed-on: https://chromium-review.googlesource.com/690198 Reviewed-by: Sylvain Defresne <[email protected]> Reviewed-by: Marc Treib <[email protected]> Commit-Queue: Chris Pickel <[email protected]> Cr-Commit-Position: refs/heads/master@{#505374} CWE ID: CWE-119
static base::Callback<void(const gfx::Image&)> Wrap(
171,961
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: png_get_int_32(png_bytep buf) { png_int_32 i = ((png_int_32)(*buf) << 24) + ((png_int_32)(*(buf + 1)) << 16) + ((png_int_32)(*(buf + 2)) << 8) + (png_int_32)(*(buf + 3)); return (i); } Commit Message: third_party/libpng: update to 1.2.54 [email protected] BUG=560291 Review URL: https://codereview.chromium.org/1467263003 Cr-Commit-Position: refs/heads/master@{#362298} CWE ID: CWE-119
png_get_int_32(png_bytep buf) { png_int_32 i = ((png_int_32)((*(buf )) & 0xff) << 24) + ((png_int_32)((*(buf + 1)) & 0xff) << 16) + ((png_int_32)((*(buf + 2)) & 0xff) << 8) + ((png_int_32)((*(buf + 3)) & 0xff) ); return (i); }
172,173
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: PepperMediaDeviceManager* PepperPlatformAudioInput::GetMediaDeviceManager() { DCHECK(main_message_loop_proxy_->BelongsToCurrentThread()); RenderFrameImpl* const render_frame = RenderFrameImpl::FromRoutingID(render_frame_id_); return render_frame ? PepperMediaDeviceManager::GetForRenderFrame(render_frame) : NULL; } Commit Message: Pepper: Access PepperMediaDeviceManager through a WeakPtr Its lifetime is scoped to the RenderFrame, and it might go away before the hosts that refer to it. BUG=423030 Review URL: https://codereview.chromium.org/653243003 Cr-Commit-Position: refs/heads/master@{#299897} CWE ID: CWE-399
PepperMediaDeviceManager* PepperPlatformAudioInput::GetMediaDeviceManager() { DCHECK(main_message_loop_proxy_->BelongsToCurrentThread()); RenderFrameImpl* const render_frame = RenderFrameImpl::FromRoutingID(render_frame_id_); return render_frame ? PepperMediaDeviceManager::GetForRenderFrame(render_frame).get() : NULL; }
171,609
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: const Cues* Segment::GetCues() const { return m_pCues; } 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 Cues* Segment::GetCues() const
174,301
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static BOOLEAN flush_incoming_que_on_wr_signal_l(l2cap_socket *sock) { uint8_t *buf; uint32_t len; while (packet_get_head_l(sock, &buf, &len)) { int sent = send(sock->our_fd, buf, len, MSG_DONTWAIT); if (sent == (signed)len) osi_free(buf); else if (sent >= 0) { packet_put_head_l(sock, buf + sent, len - sent); osi_free(buf); if (!sent) /* special case if other end not keeping up */ return TRUE; } else { packet_put_head_l(sock, buf, len); osi_free(buf); return errno == EINTR || errno == EWOULDBLOCK || errno == EAGAIN; } } return FALSE; } Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process Bug: 28885210 Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360 Conflicts: btif/co/bta_hh_co.c btif/src/btif_core.c Merge conflict resolution of ag/1161415 (referencing ag/1164670) - Directly into mnc-mr2-release CWE ID: CWE-284
static BOOLEAN flush_incoming_que_on_wr_signal_l(l2cap_socket *sock) { uint8_t *buf; uint32_t len; while (packet_get_head_l(sock, &buf, &len)) { int sent = TEMP_FAILURE_RETRY(send(sock->our_fd, buf, len, MSG_DONTWAIT)); if (sent == (signed)len) osi_free(buf); else if (sent >= 0) { packet_put_head_l(sock, buf + sent, len - sent); osi_free(buf); if (!sent) /* special case if other end not keeping up */ return TRUE; } else { packet_put_head_l(sock, buf, len); osi_free(buf); return errno == EINTR || errno == EWOULDBLOCK || errno == EAGAIN; } } return FALSE; }
173,454
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void KioskNextHomeInterfaceBrokerImpl::GetAppController( mojom::AppControllerRequest request) { app_controller_->BindRequest(std::move(request)); } Commit Message: Refactor the AppController implementation into a KeyedService. This is necessary to guarantee that the AppController will not outlive the AppServiceProxy, which could happen before during Profile destruction. Bug: 945427 Change-Id: I9e2089799e38d5a70a4a9aa66df5319113e7809e Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1542336 Reviewed-by: Michael Giuffrida <[email protected]> Commit-Queue: Lucas Tenório <[email protected]> Cr-Commit-Position: refs/heads/master@{#645122} CWE ID: CWE-416
void KioskNextHomeInterfaceBrokerImpl::GetAppController( mojom::AppControllerRequest request) { AppControllerService::Get(context_)->BindRequest(std::move(request)); }
172,090
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static void die_codec(vpx_codec_ctx_t *ctx, const char *s) { const char *detail = vpx_codec_error_detail(ctx); printf("%s: %s\n", s, vpx_codec_error(ctx)); if(detail) printf(" %s\n",detail); exit(EXIT_FAILURE); } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119
static void die_codec(vpx_codec_ctx_t *ctx, const char *s) {
174,496
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static char *__filterQuotedShell(const char *arg) { r_return_val_if_fail (arg, NULL); char *a = malloc (strlen (arg) + 1); if (!a) { return NULL; } char *b = a; while (*arg) { switch (*arg) { case ' ': case '=': case '\r': case '\n': break; default: *b++ = *arg; break; } arg++; } *b = 0; return a; } Commit Message: More fixes for the CVE-2019-14745 CWE ID: CWE-78
static char *__filterQuotedShell(const char *arg) { r_return_val_if_fail (arg, NULL); char *a = malloc (strlen (arg) + 1); if (!a) { return NULL; } char *b = a; while (*arg) { switch (*arg) { case ' ': case '=': case '"': case '\\': case '\r': case '\n': break; default: *b++ = *arg; break; } arg++; } *b = 0; return a; }
170,184
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: Gfx::Gfx(XRef *xrefA, OutputDev *outA, Dict *resDict, Catalog *catalogA, PDFRectangle *box, PDFRectangle *cropBox, GBool (*abortCheckCbkA)(void *data), void *abortCheckCbkDataA) #ifdef USE_CMS : iccColorSpaceCache(5) #endif { int i; xref = xrefA; catalog = catalogA; subPage = gTrue; printCommands = globalParams->getPrintCommands(); profileCommands = globalParams->getProfileCommands(); textHaveCSPattern = gFalse; drawText = gFalse; drawText = gFalse; maskHaveCSPattern = gFalse; mcStack = NULL; res = new GfxResources(xref, resDict, NULL); out = outA; state = new GfxState(72, 72, box, 0, gFalse); stackHeight = 1; pushStateGuard(); fontChanged = gFalse; clip = clipNone; ignoreUndef = 0; for (i = 0; i < 6; ++i) { baseMatrix[i] = state->getCTM()[i]; } formDepth = 0; abortCheckCbk = abortCheckCbkA; abortCheckCbkData = abortCheckCbkDataA; if (cropBox) { state->moveTo(cropBox->x1, cropBox->y1); state->lineTo(cropBox->x2, cropBox->y1); state->lineTo(cropBox->x2, cropBox->y2); state->lineTo(cropBox->x1, cropBox->y2); state->closePath(); state->clip(); out->clip(state); state->clearPath(); } } Commit Message: CWE ID: CWE-20
Gfx::Gfx(XRef *xrefA, OutputDev *outA, Dict *resDict, Catalog *catalogA, PDFRectangle *box, PDFRectangle *cropBox, GBool (*abortCheckCbkA)(void *data), void *abortCheckCbkDataA) #ifdef USE_CMS : iccColorSpaceCache(5) #endif { int i; xref = xrefA; catalog = catalogA; subPage = gTrue; printCommands = globalParams->getPrintCommands(); profileCommands = globalParams->getProfileCommands(); textHaveCSPattern = gFalse; drawText = gFalse; drawText = gFalse; maskHaveCSPattern = gFalse; mcStack = NULL; parser = NULL; res = new GfxResources(xref, resDict, NULL); out = outA; state = new GfxState(72, 72, box, 0, gFalse); stackHeight = 1; pushStateGuard(); fontChanged = gFalse; clip = clipNone; ignoreUndef = 0; for (i = 0; i < 6; ++i) { baseMatrix[i] = state->getCTM()[i]; } formDepth = 0; abortCheckCbk = abortCheckCbkA; abortCheckCbkData = abortCheckCbkDataA; if (cropBox) { state->moveTo(cropBox->x1, cropBox->y1); state->lineTo(cropBox->x2, cropBox->y1); state->lineTo(cropBox->x2, cropBox->y2); state->lineTo(cropBox->x1, cropBox->y2); state->closePath(); state->clip(); out->clip(state); state->clearPath(); } }
164,905
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void hashtable_clear(hashtable_t *hashtable) { size_t i; hashtable_do_clear(hashtable); for(i = 0; i < num_buckets(hashtable); i++) { hashtable->buckets[i].first = hashtable->buckets[i].last = &hashtable->list; } list_init(&hashtable->list); hashtable->size = 0; } Commit Message: CVE-2013-6401: Change hash function, randomize hashes Thanks to Florian Weimer and Eric Sesterhenn for reporting, reviewing and testing. CWE ID: CWE-310
void hashtable_clear(hashtable_t *hashtable) { size_t i; hashtable_do_clear(hashtable); for(i = 0; i < hashsize(hashtable->order); i++) { hashtable->buckets[i].first = hashtable->buckets[i].last = &hashtable->list; } list_init(&hashtable->list); hashtable->size = 0; }
166,527
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static int handle_emulation_failure(struct kvm_vcpu *vcpu) { int r = EMULATE_DONE; ++vcpu->stat.insn_emulation_fail; trace_kvm_emulate_insn_failed(vcpu); if (!is_guest_mode(vcpu)) { vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR; vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION; vcpu->run->internal.ndata = 0; r = EMULATE_FAIL; } kvm_queue_exception(vcpu, UD_VECTOR); return r; } Commit Message: KVM: x86: Don't report guest userspace emulation error to userspace Commit fc3a9157d314 ("KVM: X86: Don't report L2 emulation failures to user-space") disabled the reporting of L2 (nested guest) emulation failures to userspace due to race-condition between a vmexit and the instruction emulator. The same rational applies also to userspace applications that are permitted by the guest OS to access MMIO area or perform PIO. This patch extends the current behavior - of injecting a #UD instead of reporting it to userspace - also for guest userspace code. Signed-off-by: Nadav Amit <[email protected]> Signed-off-by: Paolo Bonzini <[email protected]> CWE ID: CWE-362
static int handle_emulation_failure(struct kvm_vcpu *vcpu) { int r = EMULATE_DONE; ++vcpu->stat.insn_emulation_fail; trace_kvm_emulate_insn_failed(vcpu); if (!is_guest_mode(vcpu) && kvm_x86_ops->get_cpl(vcpu) == 0) { vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR; vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION; vcpu->run->internal.ndata = 0; r = EMULATE_FAIL; } kvm_queue_exception(vcpu, UD_VECTOR); return r; }
166,252
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void MessageService::OpenChannelToTab( int source_process_id, int source_routing_id, int receiver_port_id, int tab_id, const std::string& extension_id, const std::string& channel_name) { content::RenderProcessHost* source = content::RenderProcessHost::FromID(source_process_id); if (!source) return; Profile* profile = Profile::FromBrowserContext(source->GetBrowserContext()); WebContents* contents = NULL; scoped_ptr<MessagePort> receiver; if (ExtensionTabUtil::GetTabById(tab_id, profile, true, NULL, NULL, &contents, NULL)) { receiver.reset(new ExtensionMessagePort( contents->GetRenderProcessHost(), contents->GetRenderViewHost()->GetRoutingID(), extension_id)); } if (contents && contents->GetController().NeedsReload()) { ExtensionMessagePort port(source, MSG_ROUTING_CONTROL, extension_id); port.DispatchOnDisconnect(GET_OPPOSITE_PORT_ID(receiver_port_id), true); return; } WebContents* source_contents = tab_util::GetWebContentsByID( source_process_id, source_routing_id); std::string tab_json = "null"; if (source_contents) { scoped_ptr<DictionaryValue> tab_value(ExtensionTabUtil::CreateTabValue( source_contents, ExtensionTabUtil::INCLUDE_PRIVACY_SENSITIVE_FIELDS)); base::JSONWriter::Write(tab_value.get(), &tab_json); } scoped_ptr<OpenChannelParams> params(new OpenChannelParams(source, tab_json, receiver.release(), receiver_port_id, extension_id, extension_id, channel_name)); OpenChannelImpl(params.Pass()); } Commit Message: Do not pass URLs in onUpdated events to extensions unless they have the "tabs" permission. BUG=168442 Review URL: https://chromiumcodereview.appspot.com/11824004 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@176406 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264
void MessageService::OpenChannelToTab( int source_process_id, int source_routing_id, int receiver_port_id, int tab_id, const std::string& extension_id, const std::string& channel_name) { content::RenderProcessHost* source = content::RenderProcessHost::FromID(source_process_id); if (!source) return; Profile* profile = Profile::FromBrowserContext(source->GetBrowserContext()); WebContents* contents = NULL; scoped_ptr<MessagePort> receiver; if (ExtensionTabUtil::GetTabById(tab_id, profile, true, NULL, NULL, &contents, NULL)) { receiver.reset(new ExtensionMessagePort( contents->GetRenderProcessHost(), contents->GetRenderViewHost()->GetRoutingID(), extension_id)); } if (contents && contents->GetController().NeedsReload()) { ExtensionMessagePort port(source, MSG_ROUTING_CONTROL, extension_id); port.DispatchOnDisconnect(GET_OPPOSITE_PORT_ID(receiver_port_id), true); return; } WebContents* source_contents = tab_util::GetWebContentsByID( source_process_id, source_routing_id); std::string tab_json = "null"; if (source_contents) { scoped_ptr<DictionaryValue> tab_value(ExtensionTabUtil::CreateTabValue( source_contents)); base::JSONWriter::Write(tab_value.get(), &tab_json); } scoped_ptr<OpenChannelParams> params(new OpenChannelParams(source, tab_json, receiver.release(), receiver_port_id, extension_id, extension_id, channel_name)); OpenChannelImpl(params.Pass()); }
171,448
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: cdf_read_sector(const cdf_info_t *info, void *buf, size_t offs, size_t len, const cdf_header_t *h, cdf_secid_t id) { assert((size_t)CDF_SEC_SIZE(h) == len); return cdf_read(info, (off_t)CDF_SEC_POS(h, id), ((char *)buf) + offs, len); } Commit Message: add more check found by cert's fuzzer. CWE ID: CWE-119
cdf_read_sector(const cdf_info_t *info, void *buf, size_t offs, size_t len, const cdf_header_t *h, cdf_secid_t id) { size_t ss = CDF_SEC_SIZE(h); size_t pos = CDF_SEC_POS(h, id); assert(ss == len); return cdf_read(info, (off_t)pos, ((char *)buf) + offs, len); }
169,883
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: ber_parse_header(STREAM s, int tagval, int *length) { int tag, len; if (tagval > 0xff) { in_uint16_be(s, tag); } else { in_uint8(s, tag); } if (tag != tagval) { logger(Core, Error, "ber_parse_header(), expected tag %d, got %d", tagval, tag); return False; } in_uint8(s, len); if (len & 0x80) { len &= ~0x80; *length = 0; while (len--) next_be(s, *length); } else *length = len; return s_check(s); } Commit Message: Malicious RDP server security fixes This commit includes fixes for a set of 21 vulnerabilities in rdesktop when a malicious RDP server is used. All vulnerabilities was identified and reported by Eyal Itkin. * Add rdp_protocol_error function that is used in several fixes * Refactor of process_bitmap_updates * Fix possible integer overflow in s_check_rem() on 32bit arch * Fix memory corruption in process_bitmap_data - CVE-2018-8794 * Fix remote code execution in process_bitmap_data - CVE-2018-8795 * Fix remote code execution in process_plane - CVE-2018-8797 * Fix Denial of Service in mcs_recv_connect_response - CVE-2018-20175 * Fix Denial of Service in mcs_parse_domain_params - CVE-2018-20175 * Fix Denial of Service in sec_parse_crypt_info - CVE-2018-20176 * Fix Denial of Service in sec_recv - CVE-2018-20176 * Fix minor information leak in rdpdr_process - CVE-2018-8791 * Fix Denial of Service in cssp_read_tsrequest - CVE-2018-8792 * Fix remote code execution in cssp_read_tsrequest - CVE-2018-8793 * Fix Denial of Service in process_bitmap_data - CVE-2018-8796 * Fix minor information leak in rdpsnd_process_ping - CVE-2018-8798 * Fix Denial of Service in process_secondary_order - CVE-2018-8799 * Fix remote code execution in in ui_clip_handle_data - CVE-2018-8800 * Fix major information leak in ui_clip_handle_data - CVE-2018-20174 * Fix memory corruption in rdp_in_unistr - CVE-2018-20177 * Fix Denial of Service in process_demand_active - CVE-2018-20178 * Fix remote code execution in lspci_process - CVE-2018-20179 * Fix remote code execution in rdpsnddbg_process - CVE-2018-20180 * Fix remote code execution in seamless_process - CVE-2018-20181 * Fix remote code execution in seamless_process_line - CVE-2018-20182 CWE ID: CWE-119
ber_parse_header(STREAM s, int tagval, int *length) ber_parse_header(STREAM s, int tagval, uint32 *length) { int tag, len; if (tagval > 0xff) { in_uint16_be(s, tag); } else { in_uint8(s, tag); } if (tag != tagval) { logger(Core, Error, "ber_parse_header(), expected tag %d, got %d", tagval, tag); return False; } in_uint8(s, len); if (len & 0x80) { len &= ~0x80; *length = 0; while (len--) next_be(s, *length); } else *length = len; return s_check(s); }
169,794
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void ChromeMockRenderThread::OnMsgOpenChannelToExtension( int routing_id, const std::string& source_extension_id, const std::string& target_extension_id, const std::string& channel_name, int* port_id) { *port_id = 0; } Commit Message: Print preview: Use an ID instead of memory pointer string in WebUI. BUG=144051 Review URL: https://chromiumcodereview.appspot.com/10870003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@153342 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-200
void ChromeMockRenderThread::OnMsgOpenChannelToExtension( int routing_id, const std::string& source_extension_id, const std::string& target_extension_id, const std::string& channel_name, int* port_id) { *port_id = 0; }
170,852
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: pvscsi_ring_init_data(PVSCSIRingInfo *m, PVSCSICmdDescSetupRings *ri) { int i; uint32_t txr_len_log2, rxr_len_log2; uint32_t req_ring_size, cmp_ring_size; m->rs_pa = ri->ringsStatePPN << VMW_PAGE_SHIFT; if ((ri->reqRingNumPages > PVSCSI_SETUP_RINGS_MAX_NUM_PAGES) || (ri->cmpRingNumPages > PVSCSI_SETUP_RINGS_MAX_NUM_PAGES)) { return -1; } req_ring_size = ri->reqRingNumPages * PVSCSI_MAX_NUM_REQ_ENTRIES_PER_PAGE; cmp_ring_size = ri->cmpRingNumPages * PVSCSI_MAX_NUM_CMP_ENTRIES_PER_PAGE; txr_len_log2 = pvscsi_log2(req_ring_size - 1); } Commit Message: CWE ID: CWE-125
pvscsi_ring_init_data(PVSCSIRingInfo *m, PVSCSICmdDescSetupRings *ri) { int i; uint32_t txr_len_log2, rxr_len_log2; uint32_t req_ring_size, cmp_ring_size; m->rs_pa = ri->ringsStatePPN << VMW_PAGE_SHIFT; req_ring_size = ri->reqRingNumPages * PVSCSI_MAX_NUM_REQ_ENTRIES_PER_PAGE; cmp_ring_size = ri->cmpRingNumPages * PVSCSI_MAX_NUM_CMP_ENTRIES_PER_PAGE; txr_len_log2 = pvscsi_log2(req_ring_size - 1); }
164,937
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: bool SyncManager::ReceivedExperiment(browser_sync::Experiments* experiments) const { ReadTransaction trans(FROM_HERE, GetUserShare()); ReadNode node(&trans); if (node.InitByTagLookup(kNigoriTag) != sync_api::BaseNode::INIT_OK) { DVLOG(1) << "Couldn't find Nigori node."; return false; } bool found_experiment = false; if (node.GetNigoriSpecifics().sync_tabs()) { experiments->sync_tabs = true; found_experiment = true; } if (node.GetNigoriSpecifics().sync_tab_favicons()) { experiments->sync_tab_favicons = true; found_experiment = true; } return found_experiment; } 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
bool SyncManager::ReceivedExperiment(browser_sync::Experiments* experiments) const { ReadTransaction trans(FROM_HERE, GetUserShare()); ReadNode node(&trans); if (node.InitByTagLookup(kNigoriTag) != sync_api::BaseNode::INIT_OK) { DVLOG(1) << "Couldn't find Nigori node."; return false; } bool found_experiment = false; if (node.GetNigoriSpecifics().sync_tab_favicons()) { experiments->sync_tab_favicons = true; found_experiment = true; } return found_experiment; }
170,796
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: CryptohomeLibrary* CrosLibrary::GetCryptohomeLibrary() { return crypto_lib_.GetDefaultImpl(use_stub_impl_); } Commit Message: chromeos: Replace copy-and-pasted code with macros. This replaces a bunch of duplicated-per-library cros function definitions and comments. BUG=none TEST=built it Review URL: http://codereview.chromium.org/6086007 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@70070 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-189
CryptohomeLibrary* CrosLibrary::GetCryptohomeLibrary() {
170,622
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void StopInputMethodDaemon() { if (!initialized_successfully_) return; should_launch_ime_ = false; if (ibus_daemon_process_handle_ != base::kNullProcessHandle) { const base::ProcessId pid = base::GetProcId(ibus_daemon_process_handle_); if (!chromeos::StopInputMethodProcess(input_method_status_connection_)) { LOG(ERROR) << "StopInputMethodProcess IPC failed. Sending SIGTERM to " << "PID " << pid; base::KillProcess(ibus_daemon_process_handle_, -1, false /* wait */); } VLOG(1) << "ibus-daemon (PID=" << pid << ") is terminated"; ibus_daemon_process_handle_ = base::kNullProcessHandle; } } 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 StopInputMethodDaemon() { if (!initialized_successfully_) return; should_launch_ime_ = false; if (ibus_daemon_process_handle_ != base::kNullProcessHandle) { const base::ProcessId pid = base::GetProcId(ibus_daemon_process_handle_); if (!ibus_controller_->StopInputMethodProcess()) { LOG(ERROR) << "StopInputMethodProcess IPC failed. Sending SIGTERM to " << "PID " << pid; base::KillProcess(ibus_daemon_process_handle_, -1, false /* wait */); } VLOG(1) << "ibus-daemon (PID=" << pid << ") is terminated"; ibus_daemon_process_handle_ = base::kNullProcessHandle; } }
170,508
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void __detach_mounts(struct dentry *dentry) { struct mountpoint *mp; struct mount *mnt; namespace_lock(); mp = lookup_mountpoint(dentry); if (!mp) goto out_unlock; lock_mount_hash(); while (!hlist_empty(&mp->m_list)) { mnt = hlist_entry(mp->m_list.first, struct mount, mnt_mp_list); umount_tree(mnt, 0); } unlock_mount_hash(); put_mountpoint(mp); out_unlock: namespace_unlock(); } Commit Message: mnt: Honor MNT_LOCKED when detaching mounts Modify umount(MNT_DETACH) to keep mounts in the hash table that are locked to their parent mounts, when the parent is lazily unmounted. In mntput_no_expire detach the children from the hash table, depending on mnt_pin_kill in cleanup_mnt to decrement the mnt_count of the children. In __detach_mounts if there are any mounts that have been unmounted but still are on the list of mounts of a mountpoint, remove their children from the mount hash table and those children to the unmounted list so they won't linger potentially indefinitely waiting for their final mntput, now that the mounts serve no purpose. Cc: [email protected] Signed-off-by: "Eric W. Biederman" <[email protected]> CWE ID: CWE-284
void __detach_mounts(struct dentry *dentry) { struct mountpoint *mp; struct mount *mnt; namespace_lock(); mp = lookup_mountpoint(dentry); if (!mp) goto out_unlock; lock_mount_hash(); while (!hlist_empty(&mp->m_list)) { mnt = hlist_entry(mp->m_list.first, struct mount, mnt_mp_list); if (mnt->mnt.mnt_flags & MNT_UMOUNT) { struct mount *p, *tmp; list_for_each_entry_safe(p, tmp, &mnt->mnt_mounts, mnt_child) { hlist_add_head(&p->mnt_umount.s_list, &unmounted); umount_mnt(p); } } else umount_tree(mnt, 0); } unlock_mount_hash(); put_mountpoint(mp); out_unlock: namespace_unlock(); }
167,588
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: vcard_apdu_new(unsigned char *raw_apdu, int len, vcard_7816_status_t *status) { VCardAPDU *new_apdu; *status = VCARD7816_STATUS_EXC_ERROR_MEMORY_FAILURE; if (len < 4) { *status = VCARD7816_STATUS_ERROR_WRONG_LENGTH; return NULL; } new_apdu = g_new(VCardAPDU, 1); new_apdu->a_data = g_memdup(raw_apdu, len); new_apdu->a_len = len; *status = vcard_apdu_set_class(new_apdu); if (*status != VCARD7816_STATUS_SUCCESS) { g_free(new_apdu); return NULL; } *status = vcard_apdu_set_length(new_apdu); if (*status != VCARD7816_STATUS_SUCCESS) { g_free(new_apdu); new_apdu = NULL; } return new_apdu; } Commit Message: CWE ID: CWE-772
vcard_apdu_new(unsigned char *raw_apdu, int len, vcard_7816_status_t *status) { VCardAPDU *new_apdu; *status = VCARD7816_STATUS_EXC_ERROR_MEMORY_FAILURE; if (len < 4) { *status = VCARD7816_STATUS_ERROR_WRONG_LENGTH; return NULL; } new_apdu = g_new(VCardAPDU, 1); new_apdu->a_data = g_memdup(raw_apdu, len); new_apdu->a_len = len; *status = vcard_apdu_set_class(new_apdu); if (*status != VCARD7816_STATUS_SUCCESS) { vcard_apdu_delete(new_apdu); return NULL; } *status = vcard_apdu_set_length(new_apdu); if (*status != VCARD7816_STATUS_SUCCESS) { vcard_apdu_delete(new_apdu); new_apdu = NULL; } return new_apdu; }
164,941
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static void coroutine_fn v9fs_wstat(void *opaque) { int32_t fid; int err = 0; int16_t unused; V9fsStat v9stat; size_t offset = 7; struct stat stbuf; V9fsFidState *fidp; V9fsPDU *pdu = opaque; v9fs_stat_init(&v9stat); err = pdu_unmarshal(pdu, offset, "dwS", &fid, &unused, &v9stat); goto out_nofid; } Commit Message: CWE ID: CWE-362
static void coroutine_fn v9fs_wstat(void *opaque) { int32_t fid; int err = 0; int16_t unused; V9fsStat v9stat; size_t offset = 7; struct stat stbuf; V9fsFidState *fidp; V9fsPDU *pdu = opaque; V9fsState *s = pdu->s; v9fs_stat_init(&v9stat); err = pdu_unmarshal(pdu, offset, "dwS", &fid, &unused, &v9stat); goto out_nofid; }
164,633
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static int nbd_negotiate_write(QIOChannel *ioc, const void *buffer, size_t size) { ssize_t ret; guint watch; assert(qemu_in_coroutine()); /* Negotiation are always in main loop. */ watch = qio_channel_add_watch(ioc, G_IO_OUT, nbd_negotiate_continue, qemu_coroutine_self(), NULL); ret = nbd_write(ioc, buffer, size, NULL); g_source_remove(watch); return ret; } Commit Message: CWE ID: CWE-20
static int nbd_negotiate_write(QIOChannel *ioc, const void *buffer, size_t size)
165,455
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static inline int btif_hl_select_close_connected(void){ char sig_on = btif_hl_signal_select_close_connected; BTIF_TRACE_DEBUG("btif_hl_select_close_connected"); return send(signal_fds[1], &sig_on, sizeof(sig_on), 0); } Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process Bug: 28885210 Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360 Conflicts: btif/co/bta_hh_co.c btif/src/btif_core.c Merge conflict resolution of ag/1161415 (referencing ag/1164670) - Directly into mnc-mr2-release CWE ID: CWE-284
static inline int btif_hl_select_close_connected(void){ char sig_on = btif_hl_signal_select_close_connected; BTIF_TRACE_DEBUG("btif_hl_select_close_connected"); return TEMP_FAILURE_RETRY(send(signal_fds[1], &sig_on, sizeof(sig_on), 0)); }
173,440
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: PHP_FUNCTION(readlink) { char *link; int link_len; char buff[MAXPATHLEN]; int ret; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &link, &link_len) == FAILURE) { return; } if (php_check_open_basedir(link TSRMLS_CC)) { RETURN_FALSE; } ret = php_sys_readlink(link, buff, MAXPATHLEN-1); if (ret == -1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s", strerror(errno)); RETURN_FALSE; } /* Append NULL to the end of the string */ buff[ret] = '\0'; RETURN_STRING(buff, 1); } Commit Message: CWE ID: CWE-254
PHP_FUNCTION(readlink) { char *link; int link_len; char buff[MAXPATHLEN]; int ret; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "p", &link, &link_len) == FAILURE) { return; } if (php_check_open_basedir(link TSRMLS_CC)) { RETURN_FALSE; } ret = php_sys_readlink(link, buff, MAXPATHLEN-1); if (ret == -1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s", strerror(errno)); RETURN_FALSE; } /* Append NULL to the end of the string */ buff[ret] = '\0'; RETURN_STRING(buff, 1); }
165,316
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static u_int mp_dss_len(const struct mp_dss *m, int csum) { u_int len; len = 4; if (m->flags & MP_DSS_A) { /* Ack present - 4 or 8 octets */ len += (m->flags & MP_DSS_a) ? 8 : 4; } if (m->flags & MP_DSS_M) { /* * Data Sequence Number (DSN), Subflow Sequence Number (SSN), * Data-Level Length present, and Checksum possibly present. * All but the Checksum are 10 bytes if the m flag is * clear (4-byte DSN) and 14 bytes if the m flag is set * (8-byte DSN). */ len += (m->flags & MP_DSS_m) ? 14 : 10; /* * The Checksum is present only if negotiated. */ if (csum) len += 2; } return len; } Commit Message: CVE-2017-13040/MPTCP: Clean up printing DSS suboption. Do the length checking inline; that means we print stuff up to the point at which we run out of option data. First check to make sure we have at least 4 bytes of option, so we have flags to check. This fixes a buffer over-read discovered by Kim Gwan Yeong. Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-125
static u_int mp_dss_len(const struct mp_dss *m, int csum)
167,836
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void ImageBitmapFactories::ImageBitmapLoader::RejectPromise( ImageBitmapRejectionReason reason) { switch (reason) { case kUndecodableImageBitmapRejectionReason: resolver_->Reject( DOMException::Create(DOMExceptionCode::kInvalidStateError, "The source image could not be decoded.")); break; case kAllocationFailureImageBitmapRejectionReason: resolver_->Reject( DOMException::Create(DOMExceptionCode::kInvalidStateError, "The ImageBitmap could not be allocated.")); break; default: NOTREACHED(); } factory_->DidFinishLoading(this); } Commit Message: Fix UAP in ImageBitmapLoader/FileReaderLoader FileReaderLoader stores its client as a raw pointer, so in cases like ImageBitmapLoader where the FileReaderLoaderClient really is garbage collected we have to make sure to destroy the FileReaderLoader when the ExecutionContext that owns it is destroyed. Bug: 913970 Change-Id: I40b02115367cf7bf5bbbbb8e9b57874d2510f861 Reviewed-on: https://chromium-review.googlesource.com/c/1374511 Reviewed-by: Jeremy Roman <[email protected]> Commit-Queue: Marijn Kruisselbrink <[email protected]> Cr-Commit-Position: refs/heads/master@{#616342} CWE ID: CWE-416
void ImageBitmapFactories::ImageBitmapLoader::RejectPromise( ImageBitmapRejectionReason reason) { switch (reason) { case kUndecodableImageBitmapRejectionReason: resolver_->Reject( DOMException::Create(DOMExceptionCode::kInvalidStateError, "The source image could not be decoded.")); break; case kAllocationFailureImageBitmapRejectionReason: resolver_->Reject( DOMException::Create(DOMExceptionCode::kInvalidStateError, "The ImageBitmap could not be allocated.")); break; default: NOTREACHED(); } loader_.reset(); factory_->DidFinishLoading(this); }
173,069
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void DownloadController::StartAndroidDownload( const content::ResourceRequestInfo::WebContentsGetter& wc_getter, bool must_download, const DownloadInfo& info) { DCHECK_CURRENTLY_ON(BrowserThread::UI); WebContents* web_contents = wc_getter.Run(); if (!web_contents) { LOG(ERROR) << "Download failed on URL:" << info.url.spec(); return; } AcquireFileAccessPermission( web_contents, base::Bind(&DownloadController::StartAndroidDownloadInternal, base::Unretained(this), wc_getter, must_download, info)); } Commit Message: Clean up Android DownloadManager code as most download now go through Chrome Network stack The only exception is OMA DRM download. And it only applies to context menu download interception. Clean up the remaining unused code now. BUG=647755 Review-Url: https://codereview.chromium.org/2371773003 Cr-Commit-Position: refs/heads/master@{#421332} CWE ID: CWE-254
void DownloadController::StartAndroidDownload(
171,883
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: image_transform_png_set_palette_to_rgb_add(image_transform *this, PNG_CONST image_transform **that, png_byte colour_type, png_byte bit_depth) { UNUSED(bit_depth) this->next = *that; *that = this; return colour_type == PNG_COLOR_TYPE_PALETTE; } 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_palette_to_rgb_add(image_transform *this, const image_transform **that, png_byte colour_type, png_byte bit_depth) { UNUSED(bit_depth) this->next = *that; *that = this; return colour_type == PNG_COLOR_TYPE_PALETTE; }
173,638
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void RenderFrameImpl::OnSelectPopupMenuItem(int selected_index) { if (external_popup_menu_ == NULL) return; blink::WebScopedUserGesture gesture(frame_); external_popup_menu_->DidSelectItem(selected_index); external_popup_menu_.reset(); } Commit Message: Fix crashes in RenderFrameImpl::OnSelectPopupMenuItem(s) ExternalPopupMenu::DidSelectItem(s) can delete the RenderFrameImpl. We need to reset external_popup_menu_ before calling it. Bug: 912211 Change-Id: Ia9a628e144464a2ebb14ab77d3a693fd5cead6fc Reviewed-on: https://chromium-review.googlesource.com/c/1381325 Commit-Queue: Kent Tamura <[email protected]> Reviewed-by: Avi Drissman <[email protected]> Cr-Commit-Position: refs/heads/master@{#618026} CWE ID: CWE-416
void RenderFrameImpl::OnSelectPopupMenuItem(int selected_index) { if (external_popup_menu_ == NULL) return; blink::WebScopedUserGesture gesture(frame_); // We need to reset |external_popup_menu_| before calling DidSelectItem(), // which might delete |this|. // See ExternalPopupMenuRemoveTest.RemoveFrameOnChange std::unique_ptr<ExternalPopupMenu> popup; popup.swap(external_popup_menu_); popup->DidSelectItem(selected_index); }
173,072
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static inline int object_common2(UNSERIALIZE_PARAMETER, long elements) { zval *retval_ptr = NULL; zval fname; if (Z_TYPE_PP(rval) != IS_OBJECT) { return 0; } if (!process_nested_data(UNSERIALIZE_PASSTHRU, Z_OBJPROP_PP(rval), elements, 1)) { /* We've got partially constructed object on our hands here. Wipe it. */ if(Z_TYPE_PP(rval) == IS_OBJECT) { zend_hash_clean(Z_OBJPROP_PP(rval)); } ZVAL_NULL(*rval); return 0; } if (Z_TYPE_PP(rval) != IS_OBJECT) { return 0; } if (Z_OBJCE_PP(rval) != PHP_IC_ENTRY && zend_hash_exists(&Z_OBJCE_PP(rval)->function_table, "__wakeup", sizeof("__wakeup"))) { INIT_PZVAL(&fname); ZVAL_STRINGL(&fname, "__wakeup", sizeof("__wakeup") - 1, 0); BG(serialize_lock)++; call_user_function_ex(CG(function_table), rval, &fname, &retval_ptr, 0, 0, 1, NULL TSRMLS_CC); BG(serialize_lock)--; } if (retval_ptr) { zval_ptr_dtor(&retval_ptr); } if (EG(exception)) { return 0; } return finish_nested_data(UNSERIALIZE_PASSTHRU); } Commit Message: Fix bug #73052 - Memory Corruption in During Deserialized-object Destruction CWE ID: CWE-119
static inline int object_common2(UNSERIALIZE_PARAMETER, long elements) { zval *retval_ptr = NULL; zval fname; if (Z_TYPE_PP(rval) != IS_OBJECT) { return 0; } if (!process_nested_data(UNSERIALIZE_PASSTHRU, Z_OBJPROP_PP(rval), elements, 1)) { /* We've got partially constructed object on our hands here. Wipe it. */ if(Z_TYPE_PP(rval) == IS_OBJECT) { zend_hash_clean(Z_OBJPROP_PP(rval)); zend_object_store_ctor_failed(*rval TSRMLS_CC); } ZVAL_NULL(*rval); return 0; } if (Z_TYPE_PP(rval) != IS_OBJECT) { return 0; } if (Z_OBJCE_PP(rval) != PHP_IC_ENTRY && zend_hash_exists(&Z_OBJCE_PP(rval)->function_table, "__wakeup", sizeof("__wakeup"))) { INIT_PZVAL(&fname); ZVAL_STRINGL(&fname, "__wakeup", sizeof("__wakeup") - 1, 0); BG(serialize_lock)++; call_user_function_ex(CG(function_table), rval, &fname, &retval_ptr, 0, 0, 1, NULL TSRMLS_CC); BG(serialize_lock)--; } if (retval_ptr) { zval_ptr_dtor(&retval_ptr); } if (EG(exception)) { return 0; } return finish_nested_data(UNSERIALIZE_PASSTHRU); }
166,940
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: nfs_printfh(netdissect_options *ndo, register const uint32_t *dp, const u_int len) { my_fsid fsid; uint32_t ino; const char *sfsname = NULL; char *spacep; if (ndo->ndo_uflag) { u_int i; char const *sep = ""; ND_PRINT((ndo, " fh[")); for (i=0; i<len; i++) { ND_PRINT((ndo, "%s%x", sep, dp[i])); sep = ":"; } ND_PRINT((ndo, "]")); return; } Parse_fh((const u_char *)dp, len, &fsid, &ino, NULL, &sfsname, 0); if (sfsname) { /* file system ID is ASCII, not numeric, for this server OS */ static char temp[NFSX_V3FHMAX+1]; /* Make sure string is null-terminated */ strncpy(temp, sfsname, NFSX_V3FHMAX); temp[sizeof(temp) - 1] = '\0'; /* Remove trailing spaces */ spacep = strchr(temp, ' '); if (spacep) *spacep = '\0'; ND_PRINT((ndo, " fh %s/", temp)); } else { ND_PRINT((ndo, " fh %d,%d/", fsid.Fsid_dev.Major, fsid.Fsid_dev.Minor)); } if(fsid.Fsid_dev.Minor == 257) /* Print the undecoded handle */ ND_PRINT((ndo, "%s", fsid.Opaque_Handle)); else ND_PRINT((ndo, "%ld", (long) ino)); } Commit Message: CVE-2017-13001/NFS: Don't copy more data than is in the file handle. Also, put the buffer on the stack; no reason to make it static. (65 bytes isn't a lot.) This fixes a buffer over-read discovered by Kamil Frankowicz. Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-125
nfs_printfh(netdissect_options *ndo, register const uint32_t *dp, const u_int len) { my_fsid fsid; uint32_t ino; const char *sfsname = NULL; char *spacep; if (ndo->ndo_uflag) { u_int i; char const *sep = ""; ND_PRINT((ndo, " fh[")); for (i=0; i<len; i++) { ND_PRINT((ndo, "%s%x", sep, dp[i])); sep = ":"; } ND_PRINT((ndo, "]")); return; } Parse_fh((const u_char *)dp, len, &fsid, &ino, NULL, &sfsname, 0); if (sfsname) { /* file system ID is ASCII, not numeric, for this server OS */ char temp[NFSX_V3FHMAX+1]; u_int stringlen; /* Make sure string is null-terminated */ stringlen = len; if (stringlen > NFSX_V3FHMAX) stringlen = NFSX_V3FHMAX; strncpy(temp, sfsname, stringlen); temp[stringlen] = '\0'; /* Remove trailing spaces */ spacep = strchr(temp, ' '); if (spacep) *spacep = '\0'; ND_PRINT((ndo, " fh %s/", temp)); } else { ND_PRINT((ndo, " fh %d,%d/", fsid.Fsid_dev.Major, fsid.Fsid_dev.Minor)); } if(fsid.Fsid_dev.Minor == 257) /* Print the undecoded handle */ ND_PRINT((ndo, "%s", fsid.Opaque_Handle)); else ND_PRINT((ndo, "%ld", (long) ino)); }
167,906
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: Curves16Data* CurvesAlloc(cmsContext ContextID, int nCurves, int nElements, cmsToneCurve** G) { int i, j; Curves16Data* c16; c16 = _cmsMallocZero(ContextID, sizeof(Curves16Data)); if (c16 == NULL) return NULL; c16 ->nCurves = nCurves; c16 ->nElements = nElements; c16 ->Curves = _cmsCalloc(ContextID, nCurves, sizeof(cmsUInt16Number*)); if (c16 ->Curves == NULL) return NULL; for (i=0; i < nCurves; i++) { c16->Curves[i] = _cmsCalloc(ContextID, nElements, sizeof(cmsUInt16Number)); if (nElements == 256) { for (j=0; j < nElements; j++) { c16 ->Curves[i][j] = cmsEvalToneCurve16(G[i], FROM_8_TO_16(j)); } } else { for (j=0; j < nElements; j++) { c16 ->Curves[i][j] = cmsEvalToneCurve16(G[i], (cmsUInt16Number) j); } } } return c16; } Commit Message: Non happy-path fixes CWE ID:
Curves16Data* CurvesAlloc(cmsContext ContextID, int nCurves, int nElements, cmsToneCurve** G) { int i, j; Curves16Data* c16; c16 = _cmsMallocZero(ContextID, sizeof(Curves16Data)); if (c16 == NULL) return NULL; c16 ->nCurves = nCurves; c16 ->nElements = nElements; c16 ->Curves = _cmsCalloc(ContextID, nCurves, sizeof(cmsUInt16Number*)); if (c16 ->Curves == NULL) return NULL; for (i=0; i < nCurves; i++) { c16->Curves[i] = _cmsCalloc(ContextID, nElements, sizeof(cmsUInt16Number)); if (c16->Curves[i] == NULL) { for (j=0; j < i; j++) { _cmsFree(ContextID, c16->Curves[j]); } _cmsFree(ContextID, c16->Curves); _cmsFree(ContextID, c16); return NULL; } if (nElements == 256) { for (j=0; j < nElements; j++) { c16 ->Curves[i][j] = cmsEvalToneCurve16(G[i], FROM_8_TO_16(j)); } } else { for (j=0; j < nElements; j++) { c16 ->Curves[i][j] = cmsEvalToneCurve16(G[i], (cmsUInt16Number) j); } } } return c16; }
166,544
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: PHP_FUNCTION(mcrypt_enc_is_block_algorithm) { MCRYPT_GET_TD_ARG if (mcrypt_enc_is_block_algorithm(pm->td) == 1) { RETURN_TRUE } else { RETURN_FALSE } } Commit Message: Fix bug #72455: Heap Overflow due to integer overflows CWE ID: CWE-190
PHP_FUNCTION(mcrypt_enc_is_block_algorithm) { MCRYPT_GET_TD_ARG if (mcrypt_enc_is_block_algorithm(pm->td) == 1) { RETURN_TRUE } else { RETURN_FALSE } }
167,094
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static void locationWithCallWithAttributeSetter(v8::Local<v8::Value> jsValue, const v8::PropertyCallbackInfo<void>& info) { TestObjectPython* proxyImp = V8TestObjectPython::toNative(info.Holder()); TestNode* imp = WTF::getPtr(proxyImp->locationWithCallWith()); if (!imp) return; V8TRYCATCH_FOR_V8STRINGRESOURCE_VOID(V8StringResource<>, cppValue, jsValue); imp->setHrefCallWith(callingDOMWindow(info.GetIsolate()), enteredDOMWindow(info.GetIsolate()), cppValue); } Commit Message: document.location bindings fix BUG=352374 [email protected] 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 locationWithCallWithAttributeSetter(v8::Local<v8::Value> jsValue, const v8::PropertyCallbackInfo<void>& info) { TestObjectPython* proxyImp = V8TestObjectPython::toNative(info.Holder()); RefPtr<TestNode> imp = WTF::getPtr(proxyImp->locationWithCallWith()); if (!imp) return; V8TRYCATCH_FOR_V8STRINGRESOURCE_VOID(V8StringResource<>, cppValue, jsValue); imp->setHrefCallWith(callingDOMWindow(info.GetIsolate()), enteredDOMWindow(info.GetIsolate()), cppValue); }
171,687
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void HistoryController::UpdateForCommit(RenderFrameImpl* frame, const WebHistoryItem& item, WebHistoryCommitType commit_type, bool navigation_within_page) { switch (commit_type) { case blink::WebBackForwardCommit: if (!provisional_entry_) return; current_entry_.reset(provisional_entry_.release()); if (HistoryEntry::HistoryNode* node = current_entry_->GetHistoryNodeForFrame(frame)) { node->set_item(item); } break; case blink::WebStandardCommit: CreateNewBackForwardItem(frame, item, navigation_within_page); break; case blink::WebInitialCommitInChildFrame: UpdateForInitialLoadInChildFrame(frame, item); break; case blink::WebHistoryInertCommit: if (current_entry_) { if (HistoryEntry::HistoryNode* node = current_entry_->GetHistoryNodeForFrame(frame)) { if (!navigation_within_page) node->RemoveChildren(); node->set_item(item); } } break; default: NOTREACHED() << "Invalid commit type: " << commit_type; } } Commit Message: Fix HistoryEntry corruption when commit isn't for provisional entry. BUG=597322 TEST=See bug for repro steps. Review URL: https://codereview.chromium.org/1848103004 Cr-Commit-Position: refs/heads/master@{#384659} CWE ID: CWE-254
void HistoryController::UpdateForCommit(RenderFrameImpl* frame, const WebHistoryItem& item, WebHistoryCommitType commit_type, bool navigation_within_page) { switch (commit_type) { case blink::WebBackForwardCommit: if (!provisional_entry_) return; // Commit the provisional entry, but only if this back/forward item // matches it. Otherwise it could be a commit from an earlier attempt to // go back/forward, and we should leave the provisional entry in place. if (HistoryEntry::HistoryNode* node = provisional_entry_->GetHistoryNodeForFrame(frame)) { if (node->item().itemSequenceNumber() == item.itemSequenceNumber()) current_entry_.reset(provisional_entry_.release()); } if (HistoryEntry::HistoryNode* node = current_entry_->GetHistoryNodeForFrame(frame)) { node->set_item(item); } break; case blink::WebStandardCommit: CreateNewBackForwardItem(frame, item, navigation_within_page); break; case blink::WebInitialCommitInChildFrame: UpdateForInitialLoadInChildFrame(frame, item); break; case blink::WebHistoryInertCommit: if (current_entry_) { if (HistoryEntry::HistoryNode* node = current_entry_->GetHistoryNodeForFrame(frame)) { if (!navigation_within_page) node->RemoveChildren(); node->set_item(item); } } break; default: NOTREACHED() << "Invalid commit type: " << commit_type; } }
172,565
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void HistogramsCallback() { MockHistogramsCallback(); QuitMessageLoop(); } Commit Message: Migrate ServiceProcessControl tests off of QuitCurrent*Deprecated(). Bug: 844016 Change-Id: I9403b850456c8ee06cd2539f7cec9599302e81a0 Reviewed-on: https://chromium-review.googlesource.com/1126576 Commit-Queue: Wez <[email protected]> Reviewed-by: Avi Drissman <[email protected]> Cr-Commit-Position: refs/heads/master@{#573131} CWE ID: CWE-94
void HistogramsCallback() { void HistogramsCallback(base::RepeatingClosure on_done) { MockHistogramsCallback(); on_done.Run(); }
172,050
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void set_cfg_option(char *opt_string) { char *sep, *sep2, szSec[1024], szKey[1024], szVal[1024]; sep = strchr(opt_string, ':'); if (!sep) { fprintf(stderr, "Badly formatted option %s - expected Section:Name=Value\n", opt_string); return; } { const size_t sepIdx = sep - opt_string; strncpy(szSec, opt_string, sepIdx); szSec[sepIdx] = 0; } sep ++; sep2 = strchr(sep, '='); if (!sep2) { fprintf(stderr, "Badly formatted option %s - expected Section:Name=Value\n", opt_string); return; } { const size_t sepIdx = sep2 - sep; strncpy(szKey, sep, sepIdx); szKey[sepIdx] = 0; strcpy(szVal, sep2+1); } if (!stricmp(szKey, "*")) { if (stricmp(szVal, "null")) { fprintf(stderr, "Badly formatted option %s - expected Section:*=null\n", opt_string); return; } gf_cfg_del_section(cfg_file, szSec); return; } if (!stricmp(szVal, "null")) { szVal[0]=0; } gf_cfg_set_key(cfg_file, szSec, szKey, szVal[0] ? szVal : NULL); } Commit Message: fix some overflows due to strcpy fixes #1184, #1186, #1187 among other things CWE ID: CWE-119
void set_cfg_option(char *opt_string) { char *sep, *sep2, szSec[1024], szKey[1024], szVal[1024]; sep = strchr(opt_string, ':'); if (!sep) { fprintf(stderr, "Badly formatted option %s - expected Section:Name=Value\n", opt_string); return; } { const size_t sepIdx = sep - opt_string; if (sepIdx >= sizeof(szSec)) { fprintf(stderr, "Badly formatted option %s - Section name is too long\n", opt_string); return; } strncpy(szSec, opt_string, sepIdx); szSec[sepIdx] = 0; } sep ++; sep2 = strchr(sep, '='); if (!sep2) { fprintf(stderr, "Badly formatted option %s - expected Section:Name=Value\n", opt_string); return; } { const size_t sepIdx = sep2 - sep; if (sepIdx >= sizeof(szKey)) { fprintf(stderr, "Badly formatted option %s - key name is too long\n", opt_string); return; } strncpy(szKey, sep, sepIdx); szKey[sepIdx] = 0; if (strlen(sep2 + 1) >= sizeof(szVal)) { fprintf(stderr, "Badly formatted option %s - value is too long\n", opt_string); return; } strcpy(szVal, sep2+1); } if (!stricmp(szKey, "*")) { if (stricmp(szVal, "null")) { fprintf(stderr, "Badly formatted option %s - expected Section:*=null\n", opt_string); return; } gf_cfg_del_section(cfg_file, szSec); return; } if (!stricmp(szVal, "null")) { szVal[0]=0; } gf_cfg_set_key(cfg_file, szSec, szKey, szVal[0] ? szVal : NULL); }
169,791
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: std::string GetDMToken() { std::string dm_token = *GetTestingDMToken(); #if !defined(OS_CHROMEOS) if (dm_token.empty() && policy::ChromeBrowserCloudManagementController::IsEnabled()) { dm_token = policy::BrowserDMTokenStorage::Get()->RetrieveDMToken(); } #endif return dm_token; } Commit Message: Migrate download_protection code to new DM token class. Migrates RetrieveDMToken calls to use the new BrowserDMToken class. Bug: 1020296 Change-Id: Icef580e243430d73b6c1c42b273a8540277481d9 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1904234 Commit-Queue: Dominique Fauteux-Chapleau <[email protected]> Reviewed-by: Tien Mai <[email protected]> Reviewed-by: Daniel Rubery <[email protected]> Cr-Commit-Position: refs/heads/master@{#714196} CWE ID: CWE-20
std::string GetDMToken() { BrowserDMToken GetTestingDMToken() { const char* dm_token = *GetTestingDMTokenStorage(); return dm_token && dm_token[0] ? BrowserDMToken::CreateValidToken(dm_token) : BrowserDMToken::CreateEmptyToken(); } policy::BrowserDMTokenStorage::BrowserDMToken GetDMToken() { auto dm_token = GetTestingDMToken(); #if !defined(OS_CHROMEOS) if (dm_token.is_empty() && policy::ChromeBrowserCloudManagementController::IsEnabled()) { dm_token = policy::BrowserDMTokenStorage::Get()->RetrieveBrowserDMToken(); } #endif return dm_token; }
172,353
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void * CAPSTONE_API cs_winkernel_malloc(size_t size) { NT_ASSERT(size); #pragma prefast(suppress : 30030) // Allocating executable POOL_TYPE memory CS_WINKERNEL_MEMBLOCK *block = (CS_WINKERNEL_MEMBLOCK *)ExAllocatePoolWithTag( NonPagedPool, size + sizeof(CS_WINKERNEL_MEMBLOCK), CS_WINKERNEL_POOL_TAG); if (!block) { return NULL; } block->size = size; return block->data; } Commit Message: provide a validity check to prevent against Integer overflow conditions (#870) * provide a validity check to prevent against Integer overflow conditions * fix some style issues. CWE ID: CWE-190
void * CAPSTONE_API cs_winkernel_malloc(size_t size) { NT_ASSERT(size); #pragma prefast(suppress : 30030) // Allocating executable POOL_TYPE memory size_t number_of_bytes = 0; CS_WINKERNEL_MEMBLOCK *block = NULL; // A specially crafted size value can trigger the overflow. // If the sum in a value that overflows or underflows the capacity of the type, // the function returns NULL. if (!NT_SUCCESS(RtlSizeTAdd(size, sizeof(CS_WINKERNEL_MEMBLOCK), &number_of_bytes))) { return NULL; } block = (CS_WINKERNEL_MEMBLOCK *)ExAllocatePoolWithTag( NonPagedPool, number_of_bytes, CS_WINKERNEL_POOL_TAG); if (!block) { return NULL; } block->size = size; return block->data; }
168,311
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static BT_HDR *create_pbuf(UINT16 len, UINT8 *data) { BT_HDR* p_buf = GKI_getbuf((UINT16) (len + BTA_HH_MIN_OFFSET + sizeof(BT_HDR))); if (p_buf) { UINT8* pbuf_data; p_buf->len = len; p_buf->offset = BTA_HH_MIN_OFFSET; pbuf_data = (UINT8*) (p_buf + 1) + p_buf->offset; memcpy(pbuf_data, data, len); } return p_buf; } Commit Message: DO NOT MERGE btif: check overflow on create_pbuf size Bug: 27930580 Change-Id: Ieb1f23f9a8a937b21f7c5eca92da3b0b821400e6 CWE ID: CWE-119
static BT_HDR *create_pbuf(UINT16 len, UINT8 *data) { UINT16 buflen = (UINT16) (len + BTA_HH_MIN_OFFSET + sizeof(BT_HDR)); if (buflen < len) { android_errorWriteWithInfoLog(0x534e4554, "28672558", -1, NULL, 0); return NULL; } BT_HDR* p_buf = GKI_getbuf(buflen); if (p_buf) { UINT8* pbuf_data; p_buf->len = len; p_buf->offset = BTA_HH_MIN_OFFSET; pbuf_data = (UINT8*) (p_buf + 1) + p_buf->offset; memcpy(pbuf_data, data, len); } return p_buf; }
173,757
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: GF_Err dinf_Read(GF_Box *s, GF_BitStream *bs) { GF_Err e = gf_isom_box_array_read(s, bs, dinf_AddBox); if (e) { return e; } if (!((GF_DataInformationBox *)s)->dref) { GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[iso file] Missing dref box in dinf\n")); ((GF_DataInformationBox *)s)->dref = (GF_DataReferenceBox *)gf_isom_box_new(GF_ISOM_BOX_TYPE_DREF); } return GF_OK; } Commit Message: prevent dref memleak on invalid input (#1183) CWE ID: CWE-400
GF_Err dinf_Read(GF_Box *s, GF_BitStream *bs) { GF_Err e = gf_isom_box_array_read(s, bs, dinf_AddBox); if (e) { return e; } if (!((GF_DataInformationBox *)s)->dref) { GF_Box* dref; GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[iso file] Missing dref box in dinf\n")); dref = gf_isom_box_new(GF_ISOM_BOX_TYPE_DREF); ((GF_DataInformationBox *)s)->dref = (GF_DataReferenceBox *)dref; gf_isom_box_add_for_dump_mode(s, dref); } return GF_OK; }
169,759
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static int picolcd_raw_event(struct hid_device *hdev, struct hid_report *report, u8 *raw_data, int size) { struct picolcd_data *data = hid_get_drvdata(hdev); unsigned long flags; int ret = 0; if (!data) return 1; if (report->id == REPORT_KEY_STATE) { if (data->input_keys) ret = picolcd_raw_keypad(data, report, raw_data+1, size-1); } else if (report->id == REPORT_IR_DATA) { ret = picolcd_raw_cir(data, report, raw_data+1, size-1); } else { spin_lock_irqsave(&data->lock, flags); /* * We let the caller of picolcd_send_and_wait() check if the * report we got is one of the expected ones or not. */ if (data->pending) { memcpy(data->pending->raw_data, raw_data+1, size-1); data->pending->raw_size = size-1; data->pending->in_report = report; complete(&data->pending->ready); } spin_unlock_irqrestore(&data->lock, flags); } picolcd_debug_raw_event(data, hdev, report, raw_data, size); return 1; } Commit Message: HID: picolcd: sanity check report size in raw_event() callback The report passed to us from transport driver could potentially be arbitrarily large, therefore we better sanity-check it so that raw_data that we hold in picolcd_pending structure are always kept within proper bounds. Cc: [email protected] Reported-by: Steven Vittitoe <[email protected]> Signed-off-by: Jiri Kosina <[email protected]> CWE ID: CWE-119
static int picolcd_raw_event(struct hid_device *hdev, struct hid_report *report, u8 *raw_data, int size) { struct picolcd_data *data = hid_get_drvdata(hdev); unsigned long flags; int ret = 0; if (!data) return 1; if (size > 64) { hid_warn(hdev, "invalid size value (%d) for picolcd raw event\n", size); return 0; } if (report->id == REPORT_KEY_STATE) { if (data->input_keys) ret = picolcd_raw_keypad(data, report, raw_data+1, size-1); } else if (report->id == REPORT_IR_DATA) { ret = picolcd_raw_cir(data, report, raw_data+1, size-1); } else { spin_lock_irqsave(&data->lock, flags); /* * We let the caller of picolcd_send_and_wait() check if the * report we got is one of the expected ones or not. */ if (data->pending) { memcpy(data->pending->raw_data, raw_data+1, size-1); data->pending->raw_size = size-1; data->pending->in_report = report; complete(&data->pending->ready); } spin_unlock_irqrestore(&data->lock, flags); } picolcd_debug_raw_event(data, hdev, report, raw_data, size); return 1; }
166,368
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void ChromeOSSetImePropertyActivated( InputMethodStatusConnection* connection, const char* key, bool activated) { DLOG(INFO) << "SetImePropertyeActivated: " << key << ": " << activated; DCHECK(key); g_return_if_fail(connection); connection->SetImePropertyActivated(key, activated); } 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 ChromeOSSetImePropertyActivated(
170,527
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: RenderProcessHost* SharedWorkerDevToolsAgentHost::GetProcess() { return worker_host_ ? RenderProcessHost::FromID(worker_host_->process_id()) : nullptr; } Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable This keeps BrowserContext* and StoragePartition* instead of RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost upon closure of DevTools front-end. Bug: 801117, 783067, 780694 Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b Reviewed-on: https://chromium-review.googlesource.com/876657 Commit-Queue: Andrey Kosyakov <[email protected]> Reviewed-by: Dmitry Gozman <[email protected]> Cr-Commit-Position: refs/heads/master@{#531157} CWE ID: CWE-20
RenderProcessHost* SharedWorkerDevToolsAgentHost::GetProcess() {
172,789
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void DXVAVideoDecodeAccelerator::Decode( const media::BitstreamBuffer& bitstream_buffer) { DCHECK(CalledOnValidThread()); RETURN_AND_NOTIFY_ON_FAILURE((state_ == kNormal || state_ == kStopped), "Invalid state: " << state_, ILLEGAL_STATE,); base::win::ScopedComPtr<IMFSample> sample; sample.Attach(CreateSampleFromInputBuffer(bitstream_buffer, renderer_process_, input_stream_info_.cbSize, input_stream_info_.cbAlignment)); RETURN_AND_NOTIFY_ON_FAILURE(sample, "Failed to create input sample", PLATFORM_FAILURE,); if (!inputs_before_decode_) { TRACE_EVENT_BEGIN_ETW("DXVAVideoDecodeAccelerator.Decoding", this, ""); } inputs_before_decode_++; RETURN_AND_NOTIFY_ON_FAILURE( SendMFTMessage(MFT_MESSAGE_NOTIFY_START_OF_STREAM, 0), "Failed to create input sample", PLATFORM_FAILURE,); HRESULT hr = decoder_->ProcessInput(0, sample, 0); RETURN_AND_NOTIFY_ON_HR_FAILURE(hr, "Failed to process input sample", PLATFORM_FAILURE,); RETURN_AND_NOTIFY_ON_FAILURE( SendMFTMessage(MFT_MESSAGE_NOTIFY_END_OF_STREAM, 0), "Failed to send eos message to MFT", PLATFORM_FAILURE,); state_ = kEosDrain; last_input_buffer_id_ = bitstream_buffer.id(); DoDecode(); RETURN_AND_NOTIFY_ON_FAILURE((state_ == kStopped || state_ == kNormal), "Failed to process output. Unexpected decoder state: " << state_, ILLEGAL_STATE,); MessageLoop::current()->PostTask(FROM_HERE, base::Bind( &DXVAVideoDecodeAccelerator::NotifyInputBufferRead, this, bitstream_buffer.id())); } 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 DXVAVideoDecodeAccelerator::Decode( const media::BitstreamBuffer& bitstream_buffer) { DCHECK(CalledOnValidThread()); RETURN_AND_NOTIFY_ON_FAILURE((state_ == kNormal || state_ == kStopped), "Invalid state: " << state_, ILLEGAL_STATE,); base::win::ScopedComPtr<IMFSample> sample; sample.Attach(CreateSampleFromInputBuffer(bitstream_buffer, input_stream_info_.cbSize, input_stream_info_.cbAlignment)); RETURN_AND_NOTIFY_ON_FAILURE(sample, "Failed to create input sample", PLATFORM_FAILURE,); if (!inputs_before_decode_) { TRACE_EVENT_BEGIN_ETW("DXVAVideoDecodeAccelerator.Decoding", this, ""); } inputs_before_decode_++; RETURN_AND_NOTIFY_ON_FAILURE( SendMFTMessage(MFT_MESSAGE_NOTIFY_START_OF_STREAM, 0), "Failed to create input sample", PLATFORM_FAILURE,); HRESULT hr = decoder_->ProcessInput(0, sample, 0); RETURN_AND_NOTIFY_ON_HR_FAILURE(hr, "Failed to process input sample", PLATFORM_FAILURE,); RETURN_AND_NOTIFY_ON_FAILURE( SendMFTMessage(MFT_MESSAGE_NOTIFY_END_OF_STREAM, 0), "Failed to send eos message to MFT", PLATFORM_FAILURE,); state_ = kEosDrain; last_input_buffer_id_ = bitstream_buffer.id(); DoDecode(); RETURN_AND_NOTIFY_ON_FAILURE((state_ == kStopped || state_ == kNormal), "Failed to process output. Unexpected decoder state: " << state_, ILLEGAL_STATE,); MessageLoop::current()->PostTask(FROM_HERE, base::Bind( &DXVAVideoDecodeAccelerator::NotifyInputBufferRead, this, bitstream_buffer.id())); }
170,941
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static void *bpf_obj_do_get(const struct filename *pathname, enum bpf_type *type) { struct inode *inode; struct path path; void *raw; int ret; ret = kern_path(pathname->name, LOOKUP_FOLLOW, &path); if (ret) return ERR_PTR(ret); inode = d_backing_inode(path.dentry); ret = inode_permission(inode, MAY_WRITE); if (ret) goto out; ret = bpf_inode_type(inode, type); if (ret) goto out; raw = bpf_any_get(inode->i_private, *type); touch_atime(&path); path_put(&path); return raw; out: path_put(&path); return ERR_PTR(ret); } Commit Message: bpf: fix refcnt overflow On a system with >32Gbyte of phyiscal memory and infinite RLIMIT_MEMLOCK, the malicious application may overflow 32-bit bpf program refcnt. It's also possible to overflow map refcnt on 1Tb system. Impose 32k hard limit which means that the same bpf program or map cannot be shared by more than 32k processes. Fixes: 1be7f75d1668 ("bpf: enable non-root eBPF programs") Reported-by: Jann Horn <[email protected]> Signed-off-by: Alexei Starovoitov <[email protected]> Acked-by: Daniel Borkmann <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID:
static void *bpf_obj_do_get(const struct filename *pathname, enum bpf_type *type) { struct inode *inode; struct path path; void *raw; int ret; ret = kern_path(pathname->name, LOOKUP_FOLLOW, &path); if (ret) return ERR_PTR(ret); inode = d_backing_inode(path.dentry); ret = inode_permission(inode, MAY_WRITE); if (ret) goto out; ret = bpf_inode_type(inode, type); if (ret) goto out; raw = bpf_any_get(inode->i_private, *type); if (!IS_ERR(raw)) touch_atime(&path); path_put(&path); return raw; out: path_put(&path); return ERR_PTR(ret); }
167,251
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static int get_refcount(BlockDriverState *bs, int64_t cluster_index) { BDRVQcowState *s = bs->opaque; int refcount_table_index, block_index; int64_t refcount_block_offset; int ret; uint16_t *refcount_block; uint16_t refcount; refcount_table_index = cluster_index >> (s->cluster_bits - REFCOUNT_SHIFT); if (refcount_table_index >= s->refcount_table_size) return 0; refcount_block_offset = s->refcount_table[refcount_table_index] & REFT_OFFSET_MASK; if (!refcount_block_offset) return 0; ret = qcow2_cache_get(bs, s->refcount_block_cache, refcount_block_offset, (void**) &refcount_block); if (ret < 0) { return ret; } block_index = cluster_index & ((1 << (s->cluster_bits - REFCOUNT_SHIFT)) - 1); refcount = be16_to_cpu(refcount_block[block_index]); ret = qcow2_cache_put(bs, s->refcount_block_cache, (void**) &refcount_block); if (ret < 0) { return ret; } return refcount; } Commit Message: CWE ID: CWE-190
static int get_refcount(BlockDriverState *bs, int64_t cluster_index) { BDRVQcowState *s = bs->opaque; uint64_t refcount_table_index, block_index; int64_t refcount_block_offset; int ret; uint16_t *refcount_block; uint16_t refcount; refcount_table_index = cluster_index >> (s->cluster_bits - REFCOUNT_SHIFT); if (refcount_table_index >= s->refcount_table_size) return 0; refcount_block_offset = s->refcount_table[refcount_table_index] & REFT_OFFSET_MASK; if (!refcount_block_offset) return 0; ret = qcow2_cache_get(bs, s->refcount_block_cache, refcount_block_offset, (void**) &refcount_block); if (ret < 0) { return ret; } block_index = cluster_index & ((1 << (s->cluster_bits - REFCOUNT_SHIFT)) - 1); refcount = be16_to_cpu(refcount_block[block_index]); ret = qcow2_cache_put(bs, s->refcount_block_cache, (void**) &refcount_block); if (ret < 0) { return ret; } return refcount; }
165,405
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: unsigned int svc_rdma_xdr_get_reply_hdr_len(__be32 *rdma_resp) { unsigned int nsegs; __be32 *p; p = rdma_resp; /* RPC-over-RDMA V1 replies never have a Read list. */ p += rpcrdma_fixed_maxsz + 1; /* Skip Write list. */ while (*p++ != xdr_zero) { nsegs = be32_to_cpup(p++); p += nsegs * rpcrdma_segment_maxsz; } /* Skip Reply chunk. */ if (*p++ != xdr_zero) { nsegs = be32_to_cpup(p++); p += nsegs * rpcrdma_segment_maxsz; } return (unsigned long)p - (unsigned long)rdma_resp; } 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
unsigned int svc_rdma_xdr_get_reply_hdr_len(__be32 *rdma_resp)
168,163
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static struct desc_struct *get_desc(unsigned short sel) { struct desc_ptr gdt_desc = {0, 0}; unsigned long desc_base; #ifdef CONFIG_MODIFY_LDT_SYSCALL if ((sel & SEGMENT_TI_MASK) == SEGMENT_LDT) { struct desc_struct *desc = NULL; struct ldt_struct *ldt; /* Bits [15:3] contain the index of the desired entry. */ sel >>= 3; mutex_lock(&current->active_mm->context.lock); ldt = current->active_mm->context.ldt; if (ldt && sel < ldt->nr_entries) desc = &ldt->entries[sel]; mutex_unlock(&current->active_mm->context.lock); return desc; } #endif native_store_gdt(&gdt_desc); /* * Segment descriptors have a size of 8 bytes. Thus, the index is * multiplied by 8 to obtain the memory offset of the desired descriptor * from the base of the GDT. As bits [15:3] of the segment selector * contain the index, it can be regarded as multiplied by 8 already. * All that remains is to clear bits [2:0]. */ desc_base = sel & ~(SEGMENT_RPL_MASK | SEGMENT_TI_MASK); if (desc_base > gdt_desc.size) return NULL; return (struct desc_struct *)(gdt_desc.address + desc_base); } Commit Message: x86/insn-eval: Fix use-after-free access to LDT entry get_desc() computes a pointer into the LDT while holding a lock that protects the LDT from being freed, but then drops the lock and returns the (now potentially dangling) pointer to its caller. Fix it by giving the caller a copy of the LDT entry instead. Fixes: 670f928ba09b ("x86/insn-eval: Add utility function to get segment descriptor") Cc: [email protected] Signed-off-by: Jann Horn <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-362
static struct desc_struct *get_desc(unsigned short sel) static bool get_desc(struct desc_struct *out, unsigned short sel) { struct desc_ptr gdt_desc = {0, 0}; unsigned long desc_base; #ifdef CONFIG_MODIFY_LDT_SYSCALL if ((sel & SEGMENT_TI_MASK) == SEGMENT_LDT) { bool success = false; struct ldt_struct *ldt; /* Bits [15:3] contain the index of the desired entry. */ sel >>= 3; mutex_lock(&current->active_mm->context.lock); ldt = current->active_mm->context.ldt; if (ldt && sel < ldt->nr_entries) { *out = ldt->entries[sel]; success = true; } mutex_unlock(&current->active_mm->context.lock); return success; } #endif native_store_gdt(&gdt_desc); /* * Segment descriptors have a size of 8 bytes. Thus, the index is * multiplied by 8 to obtain the memory offset of the desired descriptor * from the base of the GDT. As bits [15:3] of the segment selector * contain the index, it can be regarded as multiplied by 8 already. * All that remains is to clear bits [2:0]. */ desc_base = sel & ~(SEGMENT_RPL_MASK | SEGMENT_TI_MASK); if (desc_base > gdt_desc.size) return false; *out = *(struct desc_struct *)(gdt_desc.address + desc_base); return true; }
169,607
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static void gamma_transform_test(png_modifier *pm, PNG_CONST png_byte colour_type, PNG_CONST png_byte bit_depth, PNG_CONST int palette_number, PNG_CONST int interlace_type, PNG_CONST double file_gamma, PNG_CONST double screen_gamma, PNG_CONST png_byte sbit, PNG_CONST int use_input_precision, PNG_CONST int scale16) { size_t pos = 0; char name[64]; if (sbit != bit_depth && sbit != 0) { pos = safecat(name, sizeof name, pos, "sbit("); pos = safecatn(name, sizeof name, pos, sbit); pos = safecat(name, sizeof name, pos, ") "); } else pos = safecat(name, sizeof name, pos, "gamma "); if (scale16) pos = safecat(name, sizeof name, pos, "16to8 "); pos = safecatd(name, sizeof name, pos, file_gamma, 3); pos = safecat(name, sizeof name, pos, "->"); pos = safecatd(name, sizeof name, pos, screen_gamma, 3); gamma_test(pm, colour_type, bit_depth, palette_number, interlace_type, file_gamma, screen_gamma, sbit, 0, name, use_input_precision, scale16, pm->test_gamma_expand16, 0 , 0, 0); } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
static void gamma_transform_test(png_modifier *pm, const png_byte colour_type, const png_byte bit_depth, const int palette_number, const int interlace_type, const double file_gamma, const double screen_gamma, const png_byte sbit, const int use_input_precision, const int scale16) { size_t pos = 0; char name[64]; if (sbit != bit_depth && sbit != 0) { pos = safecat(name, sizeof name, pos, "sbit("); pos = safecatn(name, sizeof name, pos, sbit); pos = safecat(name, sizeof name, pos, ") "); } else pos = safecat(name, sizeof name, pos, "gamma "); if (scale16) pos = safecat(name, sizeof name, pos, "16to8 "); pos = safecatd(name, sizeof name, pos, file_gamma, 3); pos = safecat(name, sizeof name, pos, "->"); pos = safecatd(name, sizeof name, pos, screen_gamma, 3); gamma_test(pm, colour_type, bit_depth, palette_number, interlace_type, file_gamma, screen_gamma, sbit, 0, name, use_input_precision, scale16, pm->test_gamma_expand16, 0 , 0, 0); }
173,615
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: SocketStreamDispatcherHost::SocketStreamDispatcherHost( int render_process_id, ResourceMessageFilter::URLRequestContextSelector* selector, content::ResourceContext* resource_context) : ALLOW_THIS_IN_INITIALIZER_LIST(ssl_delegate_weak_factory_(this)), render_process_id_(render_process_id), url_request_context_selector_(selector), resource_context_(resource_context) { DCHECK(selector); net::WebSocketJob::EnsureInit(); } Commit Message: Inherits SupportsWeakPtr<T> instead of having WeakPtrFactory<T> This change refines r137676. BUG=122654 TEST=browser_test Review URL: https://chromiumcodereview.appspot.com/10332233 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@139771 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
SocketStreamDispatcherHost::SocketStreamDispatcherHost( int render_process_id, ResourceMessageFilter::URLRequestContextSelector* selector, content::ResourceContext* resource_context) : render_process_id_(render_process_id), url_request_context_selector_(selector), resource_context_(resource_context) { DCHECK(selector); net::WebSocketJob::EnsureInit(); }
170,993
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void BeginInstallWithManifestFunction::OnParseSuccess( const SkBitmap& icon, DictionaryValue* parsed_manifest) { CHECK(parsed_manifest); icon_ = icon; parsed_manifest_.reset(parsed_manifest); std::string init_errors; dummy_extension_ = Extension::Create( FilePath(), Extension::INTERNAL, *static_cast<DictionaryValue*>(parsed_manifest_.get()), Extension::NO_FLAGS, &init_errors); if (!dummy_extension_.get()) { OnParseFailure(MANIFEST_ERROR, std::string(kInvalidManifestError)); return; } if (icon_.empty()) icon_ = Extension::GetDefaultIcon(dummy_extension_->is_app()); ShowExtensionInstallDialog(profile(), this, dummy_extension_.get(), &icon_, dummy_extension_->GetPermissionMessageStrings(), ExtensionInstallUI::INSTALL_PROMPT); } Commit Message: Adding tests for new webstore beginInstallWithManifest method. BUG=75821 TEST=none Review URL: http://codereview.chromium.org/6900059 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@83080 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
void BeginInstallWithManifestFunction::OnParseSuccess( const SkBitmap& icon, DictionaryValue* parsed_manifest) { CHECK(parsed_manifest); icon_ = icon; parsed_manifest_.reset(parsed_manifest); std::string init_errors; dummy_extension_ = Extension::Create( FilePath(), Extension::INTERNAL, *static_cast<DictionaryValue*>(parsed_manifest_.get()), Extension::NO_FLAGS, &init_errors); if (!dummy_extension_.get()) { OnParseFailure(MANIFEST_ERROR, std::string(kInvalidManifestError)); return; } if (icon_.empty()) icon_ = Extension::GetDefaultIcon(dummy_extension_->is_app()); // In tests, we may have setup to proceed or abort without putting up the real // confirmation dialog. if (auto_confirm_for_tests != DO_NOT_SKIP) { if (auto_confirm_for_tests == PROCEED) this->InstallUIProceed(); else this->InstallUIAbort(); return; } ShowExtensionInstallDialog(profile(), this, dummy_extension_.get(), &icon_, dummy_extension_->GetPermissionMessageStrings(), ExtensionInstallUI::INSTALL_PROMPT); }
170,405
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void AppLauncherHandler::FillAppDictionary(base::DictionaryValue* dictionary) { base::AutoReset<bool> auto_reset(&ignore_changes_, true); base::ListValue* list = new base::ListValue(); Profile* profile = Profile::FromWebUI(web_ui()); PrefService* prefs = profile->GetPrefs(); for (std::set<std::string>::iterator it = visible_apps_.begin(); it != visible_apps_.end(); ++it) { const Extension* extension = extension_service_->GetInstalledExtension(*it); if (extension && extensions::ui_util::ShouldDisplayInNewTabPage( extension, profile)) { base::DictionaryValue* app_info = GetAppInfo(extension); list->Append(app_info); } } dictionary->Set("apps", list); #if defined(OS_MACOSX) dictionary->SetBoolean("disableAppWindowLaunch", true); dictionary->SetBoolean("disableCreateAppShortcut", true); #endif #if defined(OS_CHROMEOS) dictionary->SetBoolean("disableCreateAppShortcut", true); #endif const base::ListValue* app_page_names = prefs->GetList(prefs::kNtpAppPageNames); if (!app_page_names || !app_page_names->GetSize()) { ListPrefUpdate update(prefs, prefs::kNtpAppPageNames); base::ListValue* list = update.Get(); list->Set(0, new base::StringValue( l10n_util::GetStringUTF16(IDS_APP_DEFAULT_PAGE_NAME))); dictionary->Set("appPageNames", static_cast<base::ListValue*>(list->DeepCopy())); } else { dictionary->Set("appPageNames", static_cast<base::ListValue*>(app_page_names->DeepCopy())); } } Commit Message: Remove --disable-app-shims. App shims have been enabled by default for 3 milestones (since r242711). BUG=350161 Review URL: https://codereview.chromium.org/298953002 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@272786 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void AppLauncherHandler::FillAppDictionary(base::DictionaryValue* dictionary) { base::AutoReset<bool> auto_reset(&ignore_changes_, true); base::ListValue* list = new base::ListValue(); Profile* profile = Profile::FromWebUI(web_ui()); PrefService* prefs = profile->GetPrefs(); for (std::set<std::string>::iterator it = visible_apps_.begin(); it != visible_apps_.end(); ++it) { const Extension* extension = extension_service_->GetInstalledExtension(*it); if (extension && extensions::ui_util::ShouldDisplayInNewTabPage( extension, profile)) { base::DictionaryValue* app_info = GetAppInfo(extension); list->Append(app_info); } } dictionary->Set("apps", list); const base::ListValue* app_page_names = prefs->GetList(prefs::kNtpAppPageNames); if (!app_page_names || !app_page_names->GetSize()) { ListPrefUpdate update(prefs, prefs::kNtpAppPageNames); base::ListValue* list = update.Get(); list->Set(0, new base::StringValue( l10n_util::GetStringUTF16(IDS_APP_DEFAULT_PAGE_NAME))); dictionary->Set("appPageNames", static_cast<base::ListValue*>(list->DeepCopy())); } else { dictionary->Set("appPageNames", static_cast<base::ListValue*>(app_page_names->DeepCopy())); } }
171,147