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: void file_sb_list_del(struct file *file) { if (!list_empty(&file->f_u.fu_list)) { lg_local_lock_cpu(&files_lglock, file_list_cpu(file)); list_del_init(&file->f_u.fu_list); lg_local_unlock_cpu(&files_lglock, file_list_cpu(file)); } } Commit Message: get rid of s_files and files_lock The only thing we need it for is alt-sysrq-r (emergency remount r/o) and these days we can do just as well without going through the list of files. Signed-off-by: Al Viro <viro@zeniv.linux.org.uk> CWE ID: CWE-17
void file_sb_list_del(struct file *file)
166,799
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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 PageHandler::PrintToPDF(Maybe<bool> landscape, Maybe<bool> display_header_footer, Maybe<bool> print_background, Maybe<double> scale, Maybe<double> paper_width, Maybe<double> paper_height, Maybe<double> margin_top, Maybe<double> margin_bottom, Maybe<double> margin_left, Maybe<double> margin_right, Maybe<String> page_ranges, Maybe<bool> ignore_invalid_page_ranges, std::unique_ptr<PrintToPDFCallback> callback) { callback->sendFailure(Response::Error("PrintToPDF is not implemented")); return; } Commit Message: DevTools: allow styling the page number element when printing over the protocol. Bug: none Change-Id: I13e6afbd86a7c6bcdedbf0645183194b9de7cfb4 Reviewed-on: https://chromium-review.googlesource.com/809759 Commit-Queue: Pavel Feldman <pfeldman@chromium.org> Reviewed-by: Lei Zhang <thestig@chromium.org> Reviewed-by: Tom Sepez <tsepez@chromium.org> Reviewed-by: Jianzhou Feng <jzfeng@chromium.org> Cr-Commit-Position: refs/heads/master@{#523966} CWE ID: CWE-20
void PageHandler::PrintToPDF(Maybe<bool> landscape, Maybe<bool> display_header_footer, Maybe<bool> print_background, Maybe<double> scale, Maybe<double> paper_width, Maybe<double> paper_height, Maybe<double> margin_top, Maybe<double> margin_bottom, Maybe<double> margin_left, Maybe<double> margin_right, Maybe<String> page_ranges, Maybe<bool> ignore_invalid_page_ranges, Maybe<String> header_template, Maybe<String> footer_template, std::unique_ptr<PrintToPDFCallback> callback) { callback->sendFailure(Response::Error("PrintToPDF is not implemented")); return; }
172,900
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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 MagickOffsetType TIFFSeekCustomStream(const MagickOffsetType offset, const int whence,void *user_data) { PhotoshopProfile *profile; profile=(PhotoshopProfile *) user_data; switch (whence) { case SEEK_SET: default: { if (offset < 0) return(-1); profile->offset=offset; break; } case SEEK_CUR: { if ((profile->offset+offset) < 0) return(-1); profile->offset+=offset; break; } case SEEK_END: { if (((MagickOffsetType) profile->length+offset) < 0) return(-1); profile->offset=profile->length+offset; break; } } return(profile->offset); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1602 CWE ID: CWE-190
static MagickOffsetType TIFFSeekCustomStream(const MagickOffsetType offset, const int whence,void *user_data) { PhotoshopProfile *profile; profile=(PhotoshopProfile *) user_data; switch (whence) { case SEEK_SET: default: { if (offset < 0) return(-1); profile->offset=offset; break; } case SEEK_CUR: { if (((offset > 0) && (profile->offset > (SSIZE_MAX-offset))) || ((offset < 0) && (profile->offset < (-SSIZE_MAX-offset)))) { errno=EOVERFLOW; return(-1); } if ((profile->offset+offset) < 0) return(-1); profile->offset+=offset; break; } case SEEK_END: { if (((MagickOffsetType) profile->length+offset) < 0) return(-1); profile->offset=profile->length+offset; break; } } return(profile->offset); }
169,620
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: InspectorPageAgent::ResourceType InspectorPageAgent::CachedResourceType( const Resource& cached_resource) { switch (cached_resource.GetType()) { case Resource::kImage: return InspectorPageAgent::kImageResource; case Resource::kFont: return InspectorPageAgent::kFontResource; case Resource::kMedia: return InspectorPageAgent::kMediaResource; case Resource::kManifest: return InspectorPageAgent::kManifestResource; case Resource::kTextTrack: return InspectorPageAgent::kTextTrackResource; case Resource::kCSSStyleSheet: case Resource::kXSLStyleSheet: return InspectorPageAgent::kStylesheetResource; case Resource::kScript: return InspectorPageAgent::kScriptResource; case Resource::kImportResource: case Resource::kMainResource: return InspectorPageAgent::kDocumentResource; default: break; } return InspectorPageAgent::kOtherResource; } Commit Message: DevTools: send proper resource type in Network.RequestWillBeSent This patch plumbs resoure type into the DispatchWillSendRequest instrumenation. This allows us to report accurate type in Network.RequestWillBeSent event, instead of "Other", that we report today. BUG=765501 R=dgozman Change-Id: I0134c08b841e8dd247fdc8ff208bfd51e462709c Reviewed-on: https://chromium-review.googlesource.com/667504 Reviewed-by: Pavel Feldman <pfeldman@chromium.org> Reviewed-by: Dmitry Gozman <dgozman@chromium.org> Commit-Queue: Andrey Lushnikov <lushnikov@chromium.org> Cr-Commit-Position: refs/heads/master@{#507936} CWE ID: CWE-119
InspectorPageAgent::ResourceType InspectorPageAgent::CachedResourceType( InspectorPageAgent::ResourceType InspectorPageAgent::ToResourceType( const Resource::Type resource_type) { switch (resource_type) { case Resource::kImage: return InspectorPageAgent::kImageResource; case Resource::kFont: return InspectorPageAgent::kFontResource; case Resource::kMedia: return InspectorPageAgent::kMediaResource; case Resource::kManifest: return InspectorPageAgent::kManifestResource; case Resource::kTextTrack: return InspectorPageAgent::kTextTrackResource; case Resource::kCSSStyleSheet: case Resource::kXSLStyleSheet: return InspectorPageAgent::kStylesheetResource; case Resource::kScript: return InspectorPageAgent::kScriptResource; case Resource::kImportResource: case Resource::kMainResource: return InspectorPageAgent::kDocumentResource; default: break; } return InspectorPageAgent::kOtherResource; }
172,469
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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 char *base64decode(const char *buf, size_t *size) { if (!buf || !size) return NULL; size_t len = (*size > 0) ? *size : strlen(buf); if (len <= 0) return NULL; unsigned char *outbuf = (unsigned char*)malloc((len/4)*3+3); const char *ptr = buf; int p = 0; size_t l = 0; do { ptr += strspn(ptr, "\r\n\t "); if (*ptr == '\0' || ptr >= buf+len) { break; } l = strcspn(ptr, "\r\n\t "); if (l > 3 && ptr+l <= buf+len) { p+=base64decode_block(outbuf+p, ptr, l); ptr += l; } else { break; } } while (1); outbuf[p] = 0; *size = p; return outbuf; } Commit Message: base64: Rework base64decode to handle split encoded data correctly CWE ID: CWE-125
unsigned char *base64decode(const char *buf, size_t *size) { if (!buf || !size) return NULL; size_t len = (*size > 0) ? *size : strlen(buf); if (len <= 0) return NULL; unsigned char *outbuf = (unsigned char*)malloc((len/4)*3+3); const char *ptr = buf; int p = 0; int wv, w1, w2, w3, w4; int tmpval[4]; int tmpcnt = 0; do { while (ptr < buf+len && (*ptr == ' ' || *ptr == '\t' || *ptr == '\n' || *ptr == '\r')) { ptr++; } if (*ptr == '\0' || ptr >= buf+len) { break; } if ((wv = base64_table[(int)(unsigned char)*ptr++]) == -1) { continue; } tmpval[tmpcnt++] = wv; if (tmpcnt == 4) { tmpcnt = 0; w1 = tmpval[0]; w2 = tmpval[1]; w3 = tmpval[2]; w4 = tmpval[3]; if (w2 >= 0) { outbuf[p++] = (unsigned char)(((w1 << 2) + (w2 >> 4)) & 0xFF); } if (w3 >= 0) { outbuf[p++] = (unsigned char)(((w2 << 4) + (w3 >> 2)) & 0xFF); } if (w4 >= 0) { outbuf[p++] = (unsigned char)(((w3 << 6) + w4) & 0xFF); } } } while (1); outbuf[p] = 0; *size = p; return outbuf; }
168,416
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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 java_switch_op(RAnal *anal, RAnalOp *op, ut64 addr, const ut8 *data, int len) { ut8 op_byte = data[0]; ut64 offset = addr - java_get_method_start (); ut8 pos = (offset+1)%4 ? 1 + 4 - (offset+1)%4 : 1; if (op_byte == 0xaa) { if (pos + 8 > len) { return op->size; } int min_val = (ut32)(UINT (data, pos + 4)), max_val = (ut32)(UINT (data, pos + 8)); ut32 default_loc = (ut32) (UINT (data, pos)), cur_case = 0; op->switch_op = r_anal_switch_op_new (addr, min_val, default_loc); RAnalCaseOp *caseop = NULL; pos += 12; if (max_val > min_val && ((max_val - min_val)<(UT16_MAX/4))) { for (cur_case = 0; cur_case <= max_val - min_val; pos += 4, cur_case++) { if (pos + 4 >= len) { break; } int offset = (int)(ut32)(R_BIN_JAVA_UINT (data, pos)); caseop = r_anal_switch_op_add_case (op->switch_op, addr + pos, cur_case + min_val, addr + offset); if (caseop) { caseop->bb_ref_to = addr+offset; caseop->bb_ref_from = addr; // TODO figure this one out } } } else { eprintf ("Invalid switch boundaries at 0x%"PFMT64x"\n", addr); } } op->size = pos; return op->size; } Commit Message: Fix #10296 - Heap out of bounds read in java_switch_op() CWE ID: CWE-125
static int java_switch_op(RAnal *anal, RAnalOp *op, ut64 addr, const ut8 *data, int len) { ut8 op_byte = data[0]; ut64 offset = addr - java_get_method_start (); ut8 pos = (offset+1)%4 ? 1 + 4 - (offset+1)%4 : 1; if (op_byte == 0xaa) { if (pos + 8 + 8 > len) { return op->size; } const int min_val = (ut32)(UINT (data, pos + 4)); const int max_val = (ut32)(UINT (data, pos + 8)); ut32 default_loc = (ut32) (UINT (data, pos)), cur_case = 0; op->switch_op = r_anal_switch_op_new (addr, min_val, default_loc); RAnalCaseOp *caseop = NULL; pos += 12; if (max_val > min_val && ((max_val - min_val)<(UT16_MAX/4))) { for (cur_case = 0; cur_case <= max_val - min_val; pos += 4, cur_case++) { if (pos + 4 >= len) { break; } int offset = (int)(ut32)(R_BIN_JAVA_UINT (data, pos)); caseop = r_anal_switch_op_add_case (op->switch_op, addr + pos, cur_case + min_val, addr + offset); if (caseop) { caseop->bb_ref_to = addr+offset; caseop->bb_ref_from = addr; // TODO figure this one out } } } else { eprintf ("Invalid switch boundaries at 0x%"PFMT64x"\n", addr); } } op->size = pos; return op->size; }
169,198
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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 esp_do_dma(ESPState *s) { uint32_t len; int to_device; len = s->dma_left; if (s->do_cmd) { trace_esp_do_dma(s->cmdlen, len); s->dma_memory_read(s->dma_opaque, &s->cmdbuf[s->cmdlen], len); return; } return; } Commit Message: CWE ID: CWE-787
static void esp_do_dma(ESPState *s) { uint32_t len; int to_device; len = s->dma_left; if (s->do_cmd) { trace_esp_do_dma(s->cmdlen, len); assert (s->cmdlen <= sizeof(s->cmdbuf) && len <= sizeof(s->cmdbuf) - s->cmdlen); s->dma_memory_read(s->dma_opaque, &s->cmdbuf[s->cmdlen], len); return; } return; }
164,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: long long VideoTrack::GetHeight() const { return m_height; } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
long long VideoTrack::GetHeight() const
174,327
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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 __u8 *mr_report_fixup(struct hid_device *hdev, __u8 *rdesc, unsigned int *rsize) { if (*rsize >= 30 && rdesc[29] == 0x05 && rdesc[30] == 0x09) { hid_info(hdev, "fixing up button/consumer in HID report descriptor\n"); rdesc[30] = 0x0c; } return rdesc; } Commit Message: HID: fix a couple of off-by-ones There are a few very theoretical off-by-one bugs in report descriptor size checking when performing a pre-parsing fixup. Fix those. Cc: stable@vger.kernel.org Reported-by: Ben Hawkes <hawkes@google.com> Reviewed-by: Benjamin Tissoires <benjamin.tissoires@redhat.com> Signed-off-by: Jiri Kosina <jkosina@suse.cz> CWE ID: CWE-119
static __u8 *mr_report_fixup(struct hid_device *hdev, __u8 *rdesc, unsigned int *rsize) { if (*rsize >= 31 && rdesc[29] == 0x05 && rdesc[30] == 0x09) { hid_info(hdev, "fixing up button/consumer in HID report descriptor\n"); rdesc[30] = 0x0c; } return rdesc; }
166,373
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: long long Cluster::GetPosition() const { const long long pos = m_element_start - m_pSegment->m_start; assert(pos >= 0); return pos; } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
long long Cluster::GetPosition() const long Cluster::GetIndex() const { return m_index; } long long Cluster::GetPosition() const { const long long pos = m_element_start - m_pSegment->m_start; assert(pos >= 0); return pos; }
174,350
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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 ext4_io_end_t *ext4_init_io_end (struct inode *inode) { ext4_io_end_t *io = NULL; io = kmalloc(sizeof(*io), GFP_NOFS); if (io) { igrab(inode); io->inode = inode; io->flag = 0; io->offset = 0; io->size = 0; io->error = 0; INIT_WORK(&io->work, ext4_end_io_work); INIT_LIST_HEAD(&io->list); } return io; } Commit Message: ext4: use ext4_get_block_write in buffer write Allocate uninitialized extent before ext4 buffer write and convert the extent to initialized after io completes. The purpose is to make sure an extent can only be marked initialized after it has been written with new data so we can safely drop the i_mutex lock in ext4 DIO read without exposing stale data. This helps to improve multi-thread DIO read performance on high-speed disks. Skip the nobh and data=journal mount cases to make things simple for now. Signed-off-by: Jiaying Zhang <jiayingz@google.com> Signed-off-by: "Theodore Ts'o" <tytso@mit.edu> CWE ID:
static ext4_io_end_t *ext4_init_io_end (struct inode *inode) static ext4_io_end_t *ext4_init_io_end (struct inode *inode, gfp_t flags) { ext4_io_end_t *io = NULL; io = kmalloc(sizeof(*io), flags); if (io) { igrab(inode); io->inode = inode; io->flag = 0; io->offset = 0; io->size = 0; io->page = NULL; INIT_WORK(&io->work, ext4_end_io_work); INIT_LIST_HEAD(&io->list); } return io; }
167,546
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: virtual void PreEncodeFrameHook(::libvpx_test::VideoSource *video, ::libvpx_test::Encoder *encoder) { if (video->frame() == 1) { encoder->Control(VP8E_SET_CPUUSED, set_cpu_used_); } if (cfg_.ts_number_layers > 1) { if (video->frame() == 1) { encoder->Control(VP9E_SET_SVC, 1); } vpx_svc_layer_id_t layer_id = {0, 0}; layer_id.spatial_layer_id = 0; frame_flags_ = SetFrameFlags(video->frame(), cfg_.ts_number_layers); layer_id.temporal_layer_id = SetLayerId(video->frame(), cfg_.ts_number_layers); if (video->frame() > 0) { encoder->Control(VP9E_SET_SVC_LAYER_ID, &layer_id); } } const vpx_rational_t tb = video->timebase(); timebase_ = static_cast<double>(tb.num) / tb.den; duration_ = 0; } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119
virtual void PreEncodeFrameHook(::libvpx_test::VideoSource *video, ::libvpx_test::Encoder *encoder) { if (video->frame() == 0) encoder->Control(VP8E_SET_CPUUSED, set_cpu_used_); if (denoiser_offon_test_) { ASSERT_GT(denoiser_offon_period_, 0) << "denoiser_offon_period_ is not positive."; if ((video->frame() + 1) % denoiser_offon_period_ == 0) { // Flip denoiser_on_ periodically denoiser_on_ ^= 1; } } encoder->Control(VP9E_SET_NOISE_SENSITIVITY, denoiser_on_); if (cfg_.ts_number_layers > 1) { if (video->frame() == 0) { encoder->Control(VP9E_SET_SVC, 1); } vpx_svc_layer_id_t layer_id; layer_id.spatial_layer_id = 0; frame_flags_ = SetFrameFlags(video->frame(), cfg_.ts_number_layers); layer_id.temporal_layer_id = SetLayerId(video->frame(), cfg_.ts_number_layers); encoder->Control(VP9E_SET_SVC_LAYER_ID, &layer_id); } const vpx_rational_t tb = video->timebase(); timebase_ = static_cast<double>(tb.num) / tb.den; duration_ = 0; }
174,516
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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 MaybeReportDownloadDeepScanningVerdict( Profile* profile, const GURL& url, const std::string& file_name, const std::string& download_digest_sha256, BinaryUploadService::Result result, DeepScanningClientResponse response) { if (response.malware_scan_verdict().verdict() == MalwareDeepScanningVerdict::UWS || response.malware_scan_verdict().verdict() == MalwareDeepScanningVerdict::MALWARE) { extensions::SafeBrowsingPrivateEventRouterFactory::GetForProfile(profile) ->OnDangerousDeepScanningResult(url, file_name, download_digest_sha256); } } Commit Message: Add reporting for DLP deep scanning For each triggered rule in the DLP response, we report the download as violating that rule. This also implements the UnsafeReportingEnabled enterprise policy, which controls whether or not we do any reporting. Bug: 980777 Change-Id: I48100cfb4dd5aa92ed80da1f34e64a6e393be2fa Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1772381 Commit-Queue: Daniel Rubery <drubery@chromium.org> Reviewed-by: Karan Bhatia <karandeepb@chromium.org> Reviewed-by: Roger Tawa <rogerta@chromium.org> Cr-Commit-Position: refs/heads/master@{#691371} CWE ID: CWE-416
void MaybeReportDownloadDeepScanningVerdict( Profile* profile, const GURL& url, const std::string& file_name, const std::string& download_digest_sha256, BinaryUploadService::Result result, DeepScanningClientResponse response) { if (result != BinaryUploadService::Result::SUCCESS) return; if (!g_browser_process->local_state()->GetBoolean( policy::policy_prefs::kUnsafeEventsReportingEnabled)) return; if (response.malware_scan_verdict().verdict() == MalwareDeepScanningVerdict::UWS || response.malware_scan_verdict().verdict() == MalwareDeepScanningVerdict::MALWARE) { extensions::SafeBrowsingPrivateEventRouterFactory::GetForProfile(profile) ->OnDangerousDeepScanningResult(url, file_name, download_digest_sha256); } if (response.dlp_scan_verdict().status() == DlpDeepScanningVerdict::SUCCESS) { if (!response.dlp_scan_verdict().triggered_rules().empty()) { extensions::SafeBrowsingPrivateEventRouterFactory::GetForProfile(profile) ->OnSensitiveDataEvent(response.dlp_scan_verdict(), url, file_name, download_digest_sha256); } } }
172,413
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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 AppCacheDispatcherHost::OnChannelConnected(int32 peer_pid) { if (appcache_service_.get()) { backend_impl_.Initialize( appcache_service_.get(), &frontend_proxy_, process_id_); get_status_callback_ = base::Bind(&AppCacheDispatcherHost::GetStatusCallback, base::Unretained(this)); start_update_callback_ = base::Bind(&AppCacheDispatcherHost::StartUpdateCallback, base::Unretained(this)); swap_cache_callback_ = base::Bind(&AppCacheDispatcherHost::SwapCacheCallback, base::Unretained(this)); } } Commit Message: AppCache: Use WeakPtr<> to fix a potential uaf bug. BUG=554908 Review URL: https://codereview.chromium.org/1441683004 Cr-Commit-Position: refs/heads/master@{#359930} CWE ID:
void AppCacheDispatcherHost::OnChannelConnected(int32 peer_pid) { if (appcache_service_.get()) { backend_impl_.Initialize( appcache_service_.get(), &frontend_proxy_, process_id_); get_status_callback_ = base::Bind(&AppCacheDispatcherHost::GetStatusCallback, weak_factory_.GetWeakPtr()); start_update_callback_ = base::Bind(&AppCacheDispatcherHost::StartUpdateCallback, weak_factory_.GetWeakPtr()); swap_cache_callback_ = base::Bind(&AppCacheDispatcherHost::SwapCacheCallback, weak_factory_.GetWeakPtr()); } }
171,745
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: nfssvc_decode_readdirargs(struct svc_rqst *rqstp, __be32 *p, struct nfsd_readdirargs *args) { p = decode_fh(p, &args->fh); if (!p) return 0; args->cookie = ntohl(*p++); args->count = ntohl(*p++); args->count = min_t(u32, args->count, PAGE_SIZE); args->buffer = page_address(*(rqstp->rq_next_page++)); return xdr_argsize_check(rqstp, p); } Commit Message: Merge tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux Pull nfsd updates from Bruce Fields: "Another RDMA update from Chuck Lever, and a bunch of miscellaneous bugfixes" * tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux: (26 commits) nfsd: Fix up the "supattr_exclcreat" attributes nfsd: encoders mustn't use unitialized values in error cases nfsd: fix undefined behavior in nfsd4_layout_verify lockd: fix lockd shutdown race NFSv4: Fix callback server shutdown SUNRPC: Refactor svc_set_num_threads() NFSv4.x/callback: Create the callback service through svc_create_pooled lockd: remove redundant check on block svcrdma: Clean out old XDR encoders svcrdma: Remove the req_map cache svcrdma: Remove unused RDMA Write completion handler svcrdma: Reduce size of sge array in struct svc_rdma_op_ctxt svcrdma: Clean up RPC-over-RDMA backchannel reply processing svcrdma: Report Write/Reply chunk overruns svcrdma: Clean up RDMA_ERROR path svcrdma: Use rdma_rw API in RPC reply path svcrdma: Introduce local rdma_rw API helpers svcrdma: Clean up svc_rdma_get_inv_rkey() svcrdma: Add helper to save pages under I/O svcrdma: Eliminate RPCRDMA_SQ_DEPTH_MULT ... CWE ID: CWE-404
nfssvc_decode_readdirargs(struct svc_rqst *rqstp, __be32 *p, struct nfsd_readdirargs *args) { p = decode_fh(p, &args->fh); if (!p) return 0; args->cookie = ntohl(*p++); args->count = ntohl(*p++); args->count = min_t(u32, args->count, PAGE_SIZE); if (!xdr_argsize_check(rqstp, p)) return 0; args->buffer = page_address(*(rqstp->rq_next_page++)); return 1; }
168,151
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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 long __media_device_enum_links(struct media_device *mdev, struct media_links_enum *links) { struct media_entity *entity; entity = find_entity(mdev, links->entity); if (entity == NULL) return -EINVAL; if (links->pads) { unsigned int p; for (p = 0; p < entity->num_pads; p++) { struct media_pad_desc pad; media_device_kpad_to_upad(&entity->pads[p], &pad); if (copy_to_user(&links->pads[p], &pad, sizeof(pad))) return -EFAULT; } } if (links->links) { struct media_link_desc __user *ulink; unsigned int l; for (l = 0, ulink = links->links; l < entity->num_links; l++) { struct media_link_desc link; /* Ignore backlinks. */ if (entity->links[l].source->entity != entity) continue; media_device_kpad_to_upad(entity->links[l].source, &link.source); media_device_kpad_to_upad(entity->links[l].sink, &link.sink); link.flags = entity->links[l].flags; if (copy_to_user(ulink, &link, sizeof(*ulink))) return -EFAULT; ulink++; } } return 0; } Commit Message: [media] media: info leak in __media_device_enum_links() These structs have holes and reserved struct members which aren't cleared. I've added a memset() so we don't leak stack information. Signed-off-by: Dan Carpenter <dan.carpenter@oracle.com> Signed-off-by: Laurent Pinchart <laurent.pinchart@ideasonboard.com> Signed-off-by: Mauro Carvalho Chehab <mchehab@redhat.com> CWE ID: CWE-200
static long __media_device_enum_links(struct media_device *mdev, struct media_links_enum *links) { struct media_entity *entity; entity = find_entity(mdev, links->entity); if (entity == NULL) return -EINVAL; if (links->pads) { unsigned int p; for (p = 0; p < entity->num_pads; p++) { struct media_pad_desc pad; memset(&pad, 0, sizeof(pad)); media_device_kpad_to_upad(&entity->pads[p], &pad); if (copy_to_user(&links->pads[p], &pad, sizeof(pad))) return -EFAULT; } } if (links->links) { struct media_link_desc __user *ulink; unsigned int l; for (l = 0, ulink = links->links; l < entity->num_links; l++) { struct media_link_desc link; /* Ignore backlinks. */ if (entity->links[l].source->entity != entity) continue; memset(&link, 0, sizeof(link)); media_device_kpad_to_upad(entity->links[l].source, &link.source); media_device_kpad_to_upad(entity->links[l].sink, &link.sink); link.flags = entity->links[l].flags; if (copy_to_user(ulink, &link, sizeof(*ulink))) return -EFAULT; ulink++; } } return 0; }
167,576
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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_x509_param_set_hosts(X509_VERIFY_PARAM_ID *id, int mode, const char *name, size_t namelen) { char *copy; /* * Refuse names with embedded NUL bytes. * XXX: Do we need to push an error onto the error stack? */ if (name && memchr(name, '\0', namelen)) return 0; if (mode == SET_HOST && id->hosts) { string_stack_free(id->hosts); id->hosts = NULL; } if (name == NULL || namelen == 0) return 1; copy = strndup(name, namelen); if (copy == NULL) return 0; if (id->hosts == NULL && (id->hosts = sk_OPENSSL_STRING_new_null()) == NULL) { free(copy); return 0; } if (!sk_OPENSSL_STRING_push(id->hosts, copy)) { free(copy); if (sk_OPENSSL_STRING_num(id->hosts) == 0) { sk_OPENSSL_STRING_free(id->hosts); id->hosts = NULL; } return 0; } return 1; } Commit Message: Call strlen() if name length provided is 0, like OpenSSL does. Issue notice by Christian Heimes <christian@python.org> ok deraadt@ jsing@ CWE ID: CWE-295
int_x509_param_set_hosts(X509_VERIFY_PARAM_ID *id, int mode, const char *name, size_t namelen) { char *copy; if (name != NULL && namelen == 0) namelen = strlen(name); /* * Refuse names with embedded NUL bytes. * XXX: Do we need to push an error onto the error stack? */ if (name && memchr(name, '\0', namelen)) return 0; if (mode == SET_HOST && id->hosts) { string_stack_free(id->hosts); id->hosts = NULL; } if (name == NULL || namelen == 0) return 1; copy = strndup(name, namelen); if (copy == NULL) return 0; if (id->hosts == NULL && (id->hosts = sk_OPENSSL_STRING_new_null()) == NULL) { free(copy); return 0; } if (!sk_OPENSSL_STRING_push(id->hosts, copy)) { free(copy); if (sk_OPENSSL_STRING_num(id->hosts) == 0) { sk_OPENSSL_STRING_free(id->hosts); id->hosts = NULL; } return 0; } return 1; }
169,269
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static void update_exception_bitmap(struct kvm_vcpu *vcpu) { u32 eb; eb = (1u << PF_VECTOR) | (1u << UD_VECTOR) | (1u << MC_VECTOR) | (1u << NM_VECTOR) | (1u << DB_VECTOR); if ((vcpu->guest_debug & (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP)) == (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP)) eb |= 1u << BP_VECTOR; if (to_vmx(vcpu)->rmode.vm86_active) eb = ~0; if (enable_ept) eb &= ~(1u << PF_VECTOR); /* bypass_guest_pf = 0 */ if (vcpu->fpu_active) eb &= ~(1u << NM_VECTOR); /* When we are running a nested L2 guest and L1 specified for it a * certain exception bitmap, we must trap the same exceptions and pass * them to L1. When running L2, we will only handle the exceptions * specified above if L1 did not want them. */ if (is_guest_mode(vcpu)) eb |= get_vmcs12(vcpu)->exception_bitmap; vmcs_write32(EXCEPTION_BITMAP, eb); } Commit Message: KVM: x86: work around infinite loop in microcode when #AC is delivered It was found that a guest can DoS a host by triggering an infinite stream of "alignment check" (#AC) exceptions. This causes the microcode to enter an infinite loop where the core never receives another interrupt. The host kernel panics pretty quickly due to the effects (CVE-2015-5307). Signed-off-by: Eric Northup <digitaleric@google.com> Cc: stable@vger.kernel.org Signed-off-by: Paolo Bonzini <pbonzini@redhat.com> CWE ID: CWE-399
static void update_exception_bitmap(struct kvm_vcpu *vcpu) { u32 eb; eb = (1u << PF_VECTOR) | (1u << UD_VECTOR) | (1u << MC_VECTOR) | (1u << NM_VECTOR) | (1u << DB_VECTOR) | (1u << AC_VECTOR); if ((vcpu->guest_debug & (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP)) == (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP)) eb |= 1u << BP_VECTOR; if (to_vmx(vcpu)->rmode.vm86_active) eb = ~0; if (enable_ept) eb &= ~(1u << PF_VECTOR); /* bypass_guest_pf = 0 */ if (vcpu->fpu_active) eb &= ~(1u << NM_VECTOR); /* When we are running a nested L2 guest and L1 specified for it a * certain exception bitmap, we must trap the same exceptions and pass * them to L1. When running L2, we will only handle the exceptions * specified above if L1 did not want them. */ if (is_guest_mode(vcpu)) eb |= get_vmcs12(vcpu)->exception_bitmap; vmcs_write32(EXCEPTION_BITMAP, eb); }
166,600
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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 IMFSample* CreateSampleFromInputBuffer( const media::BitstreamBuffer& bitstream_buffer, base::ProcessHandle renderer_process, DWORD stream_size, DWORD alignment) { HANDLE shared_memory_handle = NULL; RETURN_ON_FAILURE(::DuplicateHandle(renderer_process, bitstream_buffer.handle(), base::GetCurrentProcessHandle(), &shared_memory_handle, 0, FALSE, DUPLICATE_SAME_ACCESS), "Duplicate handle failed", NULL); base::SharedMemory shm(shared_memory_handle, true); RETURN_ON_FAILURE(shm.Map(bitstream_buffer.size()), "Failed in base::SharedMemory::Map", NULL); return CreateInputSample(reinterpret_cast<const uint8*>(shm.memory()), bitstream_buffer.size(), stream_size, alignment); } 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:
static IMFSample* CreateSampleFromInputBuffer( const media::BitstreamBuffer& bitstream_buffer, DWORD stream_size, DWORD alignment) { base::SharedMemory shm(bitstream_buffer.handle(), true); RETURN_ON_FAILURE(shm.Map(bitstream_buffer.size()), "Failed in base::SharedMemory::Map", NULL); return CreateInputSample(reinterpret_cast<const uint8*>(shm.memory()), bitstream_buffer.size(), stream_size, alignment); }
170,939
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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 AudioRendererAlgorithm::FillBuffer( uint8* dest, int requested_frames) { DCHECK_NE(bytes_per_frame_, 0); if (playback_rate_ == 0.0f) return 0; int total_frames_rendered = 0; uint8* output_ptr = dest; while (total_frames_rendered < requested_frames) { if (index_into_window_ == window_size_) ResetWindow(); bool rendered_frame = true; if (playback_rate_ > 1.0) rendered_frame = OutputFasterPlayback(output_ptr); else if (playback_rate_ < 1.0) rendered_frame = OutputSlowerPlayback(output_ptr); else rendered_frame = OutputNormalPlayback(output_ptr); if (!rendered_frame) { needs_more_data_ = true; break; } output_ptr += bytes_per_frame_; total_frames_rendered++; } return total_frames_rendered; } Commit Message: Protect AudioRendererAlgorithm from invalid step sizes. BUG=165430 TEST=unittests and asan pass. Review URL: https://codereview.chromium.org/11573023 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@173249 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
int AudioRendererAlgorithm::FillBuffer( uint8* dest, int requested_frames) { DCHECK_NE(bytes_per_frame_, 0); if (playback_rate_ == 0.0f) return 0; int slower_step = ceil(window_size_ * playback_rate_); int faster_step = ceil(window_size_ / playback_rate_); AlignToFrameBoundary(&slower_step); AlignToFrameBoundary(&faster_step); int total_frames_rendered = 0; uint8* output_ptr = dest; while (total_frames_rendered < requested_frames) { if (index_into_window_ == window_size_) ResetWindow(); bool rendered_frame = true; if (window_size_ > faster_step) { rendered_frame = OutputFasterPlayback( output_ptr, window_size_, faster_step); } else if (slower_step < window_size_) { rendered_frame = OutputSlowerPlayback( output_ptr, slower_step, window_size_); } else { rendered_frame = OutputNormalPlayback(output_ptr); } if (!rendered_frame) { needs_more_data_ = true; break; } output_ptr += bytes_per_frame_; total_frames_rendered++; } return total_frames_rendered; }
171,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: ResourceRequestBlockedReason BaseFetchContext::CanRequest( Resource::Type type, const ResourceRequest& resource_request, const KURL& url, const ResourceLoaderOptions& options, SecurityViolationReportingPolicy reporting_policy, FetchParameters::OriginRestriction origin_restriction, ResourceRequest::RedirectStatus redirect_status) const { ResourceRequestBlockedReason blocked_reason = CanRequestInternal(type, resource_request, url, options, reporting_policy, origin_restriction, redirect_status); if (blocked_reason != ResourceRequestBlockedReason::kNone && reporting_policy == SecurityViolationReportingPolicy::kReport) { DispatchDidBlockRequest(resource_request, options.initiator_info, blocked_reason); } return blocked_reason; } Commit Message: DevTools: send proper resource type in Network.RequestWillBeSent This patch plumbs resoure type into the DispatchWillSendRequest instrumenation. This allows us to report accurate type in Network.RequestWillBeSent event, instead of "Other", that we report today. BUG=765501 R=dgozman Change-Id: I0134c08b841e8dd247fdc8ff208bfd51e462709c Reviewed-on: https://chromium-review.googlesource.com/667504 Reviewed-by: Pavel Feldman <pfeldman@chromium.org> Reviewed-by: Dmitry Gozman <dgozman@chromium.org> Commit-Queue: Andrey Lushnikov <lushnikov@chromium.org> Cr-Commit-Position: refs/heads/master@{#507936} CWE ID: CWE-119
ResourceRequestBlockedReason BaseFetchContext::CanRequest( Resource::Type type, const ResourceRequest& resource_request, const KURL& url, const ResourceLoaderOptions& options, SecurityViolationReportingPolicy reporting_policy, FetchParameters::OriginRestriction origin_restriction, ResourceRequest::RedirectStatus redirect_status) const { ResourceRequestBlockedReason blocked_reason = CanRequestInternal(type, resource_request, url, options, reporting_policy, origin_restriction, redirect_status); if (blocked_reason != ResourceRequestBlockedReason::kNone && reporting_policy == SecurityViolationReportingPolicy::kReport) { DispatchDidBlockRequest(resource_request, options.initiator_info, blocked_reason, type); } return blocked_reason; }
172,472
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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 LogErrorEventDescription(Display* dpy, const XErrorEvent& error_event) { char error_str[256]; char request_str[256]; XGetErrorText(dpy, error_event.error_code, error_str, sizeof(error_str)); strncpy(request_str, "Unknown", sizeof(request_str)); if (error_event.request_code < 128) { std::string num = base::UintToString(error_event.request_code); XGetErrorDatabaseText( dpy, "XRequest", num.c_str(), "Unknown", request_str, sizeof(request_str)); } else { int num_ext; char** ext_list = XListExtensions(dpy, &num_ext); for (int i = 0; i < num_ext; i++) { int ext_code, first_event, first_error; XQueryExtension(dpy, ext_list[i], &ext_code, &first_event, &first_error); if (error_event.request_code == ext_code) { std::string msg = StringPrintf( "%s.%d", ext_list[i], error_event.minor_code); XGetErrorDatabaseText( dpy, "XRequest", msg.c_str(), "Unknown", request_str, sizeof(request_str)); break; } } XFreeExtensionList(ext_list); } LOG(ERROR) << "X Error detected: " << "serial " << error_event.serial << ", " << "error_code " << static_cast<int>(error_event.error_code) << " (" << error_str << "), " << "request_code " << static_cast<int>(error_event.request_code) << ", " << "minor_code " << static_cast<int>(error_event.minor_code) << " (" << request_str << ")"; } Commit Message: Make shared memory segments writable only by their rightful owners. BUG=143859 TEST=Chrome's UI still works on Linux and Chrome OS Review URL: https://chromiumcodereview.appspot.com/10854242 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@158289 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264
void LogErrorEventDescription(Display* dpy, const XErrorEvent& error_event) { char error_str[256]; char request_str[256]; XGetErrorText(dpy, error_event.error_code, error_str, sizeof(error_str)); strncpy(request_str, "Unknown", sizeof(request_str)); if (error_event.request_code < 128) { std::string num = base::UintToString(error_event.request_code); XGetErrorDatabaseText( dpy, "XRequest", num.c_str(), "Unknown", request_str, sizeof(request_str)); } else { int num_ext; char** ext_list = XListExtensions(dpy, &num_ext); for (int i = 0; i < num_ext; i++) { int ext_code, first_event, first_error; XQueryExtension(dpy, ext_list[i], &ext_code, &first_event, &first_error); if (error_event.request_code == ext_code) { std::string msg = StringPrintf( "%s.%d", ext_list[i], error_event.minor_code); XGetErrorDatabaseText( dpy, "XRequest", msg.c_str(), "Unknown", request_str, sizeof(request_str)); break; } } XFreeExtensionList(ext_list); } LOG(ERROR) << "X Error detected: " << "serial " << error_event.serial << ", " << "error_code " << static_cast<int>(error_event.error_code) << " (" << error_str << "), " << "request_code " << static_cast<int>(error_event.request_code) << ", " << "minor_code " << static_cast<int>(error_event.minor_code) << " (" << request_str << ")"; }
171,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: MagickExport MagickBooleanType SetQuantumDepth(const Image *image, QuantumInfo *quantum_info,const size_t depth) { size_t extent, quantum; /* Allocate the quantum pixel buffer. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(quantum_info != (QuantumInfo *) NULL); assert(quantum_info->signature == MagickCoreSignature); quantum_info->depth=depth; if (quantum_info->format == FloatingPointQuantumFormat) { if (quantum_info->depth > 32) quantum_info->depth=64; else if (quantum_info->depth > 16) quantum_info->depth=32; else quantum_info->depth=16; } if (quantum_info->pixels != (unsigned char **) NULL) DestroyQuantumPixels(quantum_info); quantum=(quantum_info->pad+6)*(quantum_info->depth+7)/8; extent=image->columns*quantum; if ((image->columns != 0) && (quantum != (extent/image->columns))) return(MagickFalse); return(AcquireQuantumPixels(quantum_info,extent)); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/105 CWE ID: CWE-369
MagickExport MagickBooleanType SetQuantumDepth(const Image *image, QuantumInfo *quantum_info,const size_t depth) { size_t extent, quantum; /* Allocate the quantum pixel buffer. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(quantum_info != (QuantumInfo *) NULL); assert(quantum_info->signature == MagickCoreSignature); quantum_info->depth=depth; if (quantum_info->format == FloatingPointQuantumFormat) { if (quantum_info->depth > 32) quantum_info->depth=64; else if (quantum_info->depth > 16) quantum_info->depth=32; else quantum_info->depth=16; } if (quantum_info->pixels != (unsigned char **) NULL) DestroyQuantumPixels(quantum_info); quantum=(quantum_info->pad+6)*(quantum_info->depth+7)/8; extent=MagickMax(image->columns,image->rows)*quantum; if ((MagickMax(image->columns,image->rows) != 0) && (quantum != (extent/MagickMax(image->columns,image->rows)))) return(MagickFalse); return(AcquireQuantumPixels(quantum_info,extent)); }
168,799
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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 jp2_pclr_getdata(jp2_box_t *box, jas_stream_t *in) { jp2_pclr_t *pclr = &box->data.pclr; int lutsize; unsigned int i; unsigned int j; int_fast32_t x; pclr->lutdata = 0; if (jp2_getuint16(in, &pclr->numlutents) || jp2_getuint8(in, &pclr->numchans)) { return -1; } lutsize = pclr->numlutents * pclr->numchans; if (!(pclr->lutdata = jas_alloc2(lutsize, sizeof(int_fast32_t)))) { return -1; } if (!(pclr->bpc = jas_alloc2(pclr->numchans, sizeof(uint_fast8_t)))) { return -1; } for (i = 0; i < pclr->numchans; ++i) { if (jp2_getuint8(in, &pclr->bpc[i])) { return -1; } } for (i = 0; i < pclr->numlutents; ++i) { for (j = 0; j < pclr->numchans; ++j) { if (jp2_getint(in, (pclr->bpc[j] & 0x80) != 0, (pclr->bpc[j] & 0x7f) + 1, &x)) { return -1; } pclr->lutdata[i * pclr->numchans + j] = x; } } return 0; } Commit Message: Fixed bugs due to uninitialized data in the JP2 decoder. Also, added some comments marking I/O stream interfaces that probably need to be changed (in the long term) to fix integer overflow problems. CWE ID: CWE-476
static int jp2_pclr_getdata(jp2_box_t *box, jas_stream_t *in) { jp2_pclr_t *pclr = &box->data.pclr; int lutsize; unsigned int i; unsigned int j; int_fast32_t x; pclr->lutdata = 0; pclr->bpc = 0; if (jp2_getuint16(in, &pclr->numlutents) || jp2_getuint8(in, &pclr->numchans)) { return -1; } lutsize = pclr->numlutents * pclr->numchans; if (!(pclr->lutdata = jas_alloc2(lutsize, sizeof(int_fast32_t)))) { return -1; } if (!(pclr->bpc = jas_alloc2(pclr->numchans, sizeof(uint_fast8_t)))) { return -1; } for (i = 0; i < pclr->numchans; ++i) { if (jp2_getuint8(in, &pclr->bpc[i])) { return -1; } } for (i = 0; i < pclr->numlutents; ++i) { for (j = 0; j < pclr->numchans; ++j) { if (jp2_getint(in, (pclr->bpc[j] & 0x80) != 0, (pclr->bpc[j] & 0x7f) + 1, &x)) { return -1; } pclr->lutdata[i * pclr->numchans + j] = x; } } return 0; }
168,323
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void XMLHttpRequest::networkError() { genericError(); if (!m_uploadComplete) { m_uploadComplete = true; if (m_upload && m_uploadEventsAllowed) m_upload->dispatchEventAndLoadEnd(XMLHttpRequestProgressEvent::create(eventNames().errorEvent)); } m_progressEventThrottle.dispatchEventAndLoadEnd(XMLHttpRequestProgressEvent::create(eventNames().errorEvent)); internalAbort(); } Commit Message: Don't dispatch events when XHR is set to sync mode Any of readystatechange, progress, abort, error, timeout and loadend event are not specified to be dispatched in sync mode in the latest spec. Just an exception corresponding to the failure is thrown. Clean up for readability done in this CL - factor out dispatchEventAndLoadEnd calling code - make didTimeout() private - give error handling methods more descriptive names - set m_exceptionCode in failure type specific methods -- Note that for didFailRedirectCheck, m_exceptionCode was not set in networkError(), but was set at the end of createRequest() This CL is prep for fixing crbug.com/292422 BUG=292422 Review URL: https://chromiumcodereview.appspot.com/24225002 git-svn-id: svn://svn.chromium.org/blink/trunk@158046 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399
void XMLHttpRequest::networkError() void XMLHttpRequest::dispatchEventAndLoadEnd(const AtomicString& type) { if (!m_uploadComplete) { m_uploadComplete = true; if (m_upload && m_uploadEventsAllowed) m_upload->dispatchEventAndLoadEnd(XMLHttpRequestProgressEvent::create(type)); } m_progressEventThrottle.dispatchEventAndLoadEnd(XMLHttpRequestProgressEvent::create(type)); } void XMLHttpRequest::handleNetworkError() { m_exceptionCode = NetworkError; handleDidFailGeneric(); if (m_async) { changeState(DONE); dispatchEventAndLoadEnd(eventNames().errorEvent); } else { m_state = DONE; } internalAbort(); }
171,169
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: size_t mptsas_config_ioc_0(MPTSASState *s, uint8_t **data, int address) { PCIDeviceClass *pcic = PCI_DEVICE_GET_CLASS(s); return MPTSAS_CONFIG_PACK(0, MPI_CONFIG_PAGETYPE_IOC, 0x01, "*l*lwwb*b*b*blww", pcic->vendor_id, pcic->device_id, pcic->revision, pcic->subsystem_vendor_id, pcic->subsystem_id); } Commit Message: CWE ID: CWE-20
size_t mptsas_config_ioc_0(MPTSASState *s, uint8_t **data, int address) { PCIDeviceClass *pcic = PCI_DEVICE_GET_CLASS(s); return MPTSAS_CONFIG_PACK(0, MPI_CONFIG_PAGETYPE_IOC, 0x01, "*l*lwwb*b*b*blww", pcic->vendor_id, pcic->device_id, pcic->revision, pcic->class_id, pcic->subsystem_vendor_id, pcic->subsystem_id); }
164,934
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: size_t calculate_camera_metadata_entry_data_size(uint8_t type, size_t data_count) { if (type >= NUM_TYPES) return 0; size_t data_bytes = data_count * camera_metadata_type_size[type]; return data_bytes <= 4 ? 0 : ALIGN_TO(data_bytes, DATA_ALIGNMENT); } Commit Message: Camera: Prevent data size overflow Add a function to check overflow when calculating metadata data size. Bug: 30741779 Change-Id: I6405fe608567a4f4113674050f826f305ecae030 CWE ID: CWE-119
size_t calculate_camera_metadata_entry_data_size(uint8_t type,
173,394
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: fpDiff(TIFF* tif, uint8* cp0, tmsize_t cc) { tmsize_t stride = PredictorState(tif)->stride; uint32 bps = tif->tif_dir.td_bitspersample / 8; tmsize_t wc = cc / bps; tmsize_t count; uint8 *cp = (uint8 *) cp0; uint8 *tmp = (uint8 *)_TIFFmalloc(cc); assert((cc%(bps*stride))==0); if (!tmp) return; _TIFFmemcpy(tmp, cp0, cc); for (count = 0; count < wc; count++) { uint32 byte; for (byte = 0; byte < bps; byte++) { #if WORDS_BIGENDIAN cp[byte * wc + count] = tmp[bps * count + byte]; #else cp[(bps - byte - 1) * wc + count] = tmp[bps * count + byte]; #endif } } _TIFFfree(tmp); cp = (uint8 *) cp0; cp += cc - stride - 1; for (count = cc; count > stride; count -= stride) REPEAT4(stride, cp[stride] = (unsigned char)((cp[stride] - cp[0])&0xff); cp--) } Commit Message: * libtiff/tif_predict.h, libtiff/tif_predict.c: Replace assertions by runtime checks to avoid assertions in debug mode, or buffer overflows in release mode. Can happen when dealing with unusual tile size like YCbCr with subsampling. Reported as MSVR 35105 by Axel Souchet & Vishal Chauhan from the MSRC Vulnerabilities & Mitigations team. CWE ID: CWE-119
fpDiff(TIFF* tif, uint8* cp0, tmsize_t cc) { tmsize_t stride = PredictorState(tif)->stride; uint32 bps = tif->tif_dir.td_bitspersample / 8; tmsize_t wc = cc / bps; tmsize_t count; uint8 *cp = (uint8 *) cp0; uint8 *tmp = (uint8 *)_TIFFmalloc(cc); if((cc%(bps*stride))!=0) { TIFFErrorExt(tif->tif_clientdata, "fpDiff", "%s", "(cc%(bps*stride))!=0"); return 0; } if (!tmp) return 0; _TIFFmemcpy(tmp, cp0, cc); for (count = 0; count < wc; count++) { uint32 byte; for (byte = 0; byte < bps; byte++) { #if WORDS_BIGENDIAN cp[byte * wc + count] = tmp[bps * count + byte]; #else cp[(bps - byte - 1) * wc + count] = tmp[bps * count + byte]; #endif } } _TIFFfree(tmp); cp = (uint8 *) cp0; cp += cc - stride - 1; for (count = cc; count > stride; count -= stride) REPEAT4(stride, cp[stride] = (unsigned char)((cp[stride] - cp[0])&0xff); cp--) return 1; }
166,881
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: pipe_iov_copy_to_user(struct iovec *iov, const void *from, unsigned long len, int atomic) { unsigned long copy; while (len > 0) { while (!iov->iov_len) iov++; copy = min_t(unsigned long, len, iov->iov_len); if (atomic) { if (__copy_to_user_inatomic(iov->iov_base, from, copy)) return -EFAULT; } else { if (copy_to_user(iov->iov_base, from, copy)) return -EFAULT; } from += copy; len -= copy; iov->iov_base += copy; iov->iov_len -= copy; } return 0; } Commit Message: switch pipe_read() to copy_page_to_iter() Signed-off-by: Al Viro <viro@zeniv.linux.org.uk> CWE ID: CWE-17
pipe_iov_copy_to_user(struct iovec *iov, const void *from, unsigned long len,
169,928
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: SPL_METHOD(SplFileInfo, getPath) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); char *path; int path_len; if (zend_parse_parameters_none() == FAILURE) { return; } path = spl_filesystem_object_get_path(intern, &path_len TSRMLS_CC); RETURN_STRINGL(path, path_len, 1); } Commit Message: Fix bug #72262 - do not overflow int CWE ID: CWE-190
SPL_METHOD(SplFileInfo, getPath) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); char *path; int path_len; if (zend_parse_parameters_none() == FAILURE) { return; } path = spl_filesystem_object_get_path(intern, &path_len TSRMLS_CC); RETURN_STRINGL(path, path_len, 1); }
167,031
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: asmlinkage void bad_mode(struct pt_regs *regs, int reason, unsigned int esr) { console_verbose(); pr_crit("Bad mode in %s handler detected, code 0x%08x\n", handler[reason], esr); die("Oops - bad mode", regs, 0); local_irq_disable(); panic("bad mode"); } Commit Message: arm64: don't kill the kernel on a bad esr from el0 Rather than completely killing the kernel if we receive an esr value we can't deal with in the el0 handlers, send the process a SIGILL and log the esr value in the hope that we can debug it. If we receive a bad esr from el1, we'll die() as before. Signed-off-by: Mark Rutland <mark.rutland@arm.com> Signed-off-by: Catalin Marinas <catalin.marinas@arm.com> Cc: stable@vger.kernel.org CWE ID:
asmlinkage void bad_mode(struct pt_regs *regs, int reason, unsigned int esr) { siginfo_t info; void __user *pc = (void __user *)instruction_pointer(regs); console_verbose(); pr_crit("Bad mode in %s handler detected, code 0x%08x\n", handler[reason], esr); __show_regs(regs); info.si_signo = SIGILL; info.si_errno = 0; info.si_code = ILL_ILLOPC; info.si_addr = pc; arm64_notify_die("Oops - bad mode", regs, &info, 0); }
166,012
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: gnutls_session_get_data (gnutls_session_t session, void *session_data, size_t * session_data_size) { gnutls_datum_t psession; int ret; if (session->internals.resumable == RESUME_FALSE) return GNUTLS_E_INVALID_SESSION; psession.data = session_data; ret = _gnutls_session_pack (session, &psession); if (ret < 0) { gnutls_assert (); return ret; } *session_data_size = psession.size; if (psession.size > *session_data_size) { ret = GNUTLS_E_SHORT_MEMORY_BUFFER; goto error; } if (session_data != NULL) memcpy (session_data, psession.data, psession.size); ret = 0; error: _gnutls_free_datum (&psession); return ret; } Commit Message: CWE ID: CWE-119
gnutls_session_get_data (gnutls_session_t session, void *session_data, size_t * session_data_size) { gnutls_datum_t psession; int ret; if (session->internals.resumable == RESUME_FALSE) return GNUTLS_E_INVALID_SESSION; psession.data = session_data; ret = _gnutls_session_pack (session, &psession); if (ret < 0) { gnutls_assert (); return ret; } if (psession.size > *session_data_size) { ret = GNUTLS_E_SHORT_MEMORY_BUFFER; goto error; } *session_data_size = psession.size; if (session_data != NULL) memcpy (session_data, psession.data, psession.size); ret = 0; error: _gnutls_free_datum (&psession); return ret; }
164,569
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static int store_icy(URLContext *h, int size) { HTTPContext *s = h->priv_data; /* until next metadata packet */ int remaining = s->icy_metaint - s->icy_data_read; if (remaining < 0) return AVERROR_INVALIDDATA; if (!remaining) { /* The metadata packet is variable sized. It has a 1 byte header * which sets the length of the packet (divided by 16). If it's 0, * the metadata doesn't change. After the packet, icy_metaint bytes * of normal data follows. */ uint8_t ch; int len = http_read_stream_all(h, &ch, 1); if (len < 0) return len; if (ch > 0) { char data[255 * 16 + 1]; int ret; len = ch * 16; ret = http_read_stream_all(h, data, len); if (ret < 0) return ret; data[len + 1] = 0; if ((ret = av_opt_set(s, "icy_metadata_packet", data, 0)) < 0) return ret; update_metadata(s, data); } s->icy_data_read = 0; remaining = s->icy_metaint; } return FFMIN(size, remaining); } Commit Message: http: make length/offset-related variables unsigned. Fixes #5992, reported and found by Paul Cher <paulcher@icloud.com>. CWE ID: CWE-119
static int store_icy(URLContext *h, int size) { HTTPContext *s = h->priv_data; /* until next metadata packet */ uint64_t remaining; if (s->icy_metaint < s->icy_data_read) return AVERROR_INVALIDDATA; remaining = s->icy_metaint - s->icy_data_read; if (!remaining) { /* The metadata packet is variable sized. It has a 1 byte header * which sets the length of the packet (divided by 16). If it's 0, * the metadata doesn't change. After the packet, icy_metaint bytes * of normal data follows. */ uint8_t ch; int len = http_read_stream_all(h, &ch, 1); if (len < 0) return len; if (ch > 0) { char data[255 * 16 + 1]; int ret; len = ch * 16; ret = http_read_stream_all(h, data, len); if (ret < 0) return ret; data[len + 1] = 0; if ((ret = av_opt_set(s, "icy_metadata_packet", data, 0)) < 0) return ret; update_metadata(s, data); } s->icy_data_read = 0; remaining = s->icy_metaint; } return FFMIN(size, remaining); }
168,505
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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 DecrementUntilZero(int* count) { (*count)--; if (!(*count)) base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::RunLoop::QuitCurrentWhenIdleClosureDeprecated()); } 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 <wez@chromium.org> Reviewed-by: Avi Drissman <avi@chromium.org> Cr-Commit-Position: refs/heads/master@{#573131} CWE ID: CWE-94
static void DecrementUntilZero(int* count) { { base::RunLoop run_loop; cloud_print_proxy->GetCloudPrintProxyInfo( base::BindOnce([](base::OnceClosure done, bool, const std::string&, const std::string&) { std::move(done).Run(); }, run_loop.QuitClosure())); run_loop.Run(); } }
172,049
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static ssize_t stellaris_enet_receive(NetClientState *nc, const uint8_t *buf, size_t size) { stellaris_enet_state *s = qemu_get_nic_opaque(nc); int n; uint8_t *p; uint32_t crc; if ((s->rctl & SE_RCTL_RXEN) == 0) return -1; if (s->np >= 31) { return 0; } DPRINTF("Received packet len=%zu\n", size); n = s->next_packet + s->np; if (n >= 31) n -= 31; s->np++; s->rx[n].len = size + 6; p = s->rx[n].data; *(p++) = (size + 6); memset(p, 0, (6 - size) & 3); } Commit Message: CWE ID: CWE-20
static ssize_t stellaris_enet_receive(NetClientState *nc, const uint8_t *buf, size_t size) { stellaris_enet_state *s = qemu_get_nic_opaque(nc); int n; uint8_t *p; uint32_t crc; if ((s->rctl & SE_RCTL_RXEN) == 0) return -1; if (s->np >= 31) { return 0; } DPRINTF("Received packet len=%zu\n", size); n = s->next_packet + s->np; if (n >= 31) n -= 31; if (size >= sizeof(s->rx[n].data) - 6) { /* If the packet won't fit into the * emulated 2K RAM, this is reported * as a FIFO overrun error. */ s->ris |= SE_INT_FOV; stellaris_enet_update(s); return -1; } s->np++; s->rx[n].len = size + 6; p = s->rx[n].data; *(p++) = (size + 6); memset(p, 0, (6 - size) & 3); }
165,078
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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* H264SwDecMalloc(u32 size) { return malloc(size); } Commit Message: h264dec: check for overflows when calculating allocation size. Bug: 27855419 Change-Id: Idabedca52913ec31ea5cb6a6109ab94e3fb2badd CWE ID: CWE-119
void* H264SwDecMalloc(u32 size) { void* H264SwDecMalloc(u32 size, u32 num) { if (size > UINT32_MAX / num) { ALOGE("can't allocate %u * %u bytes", size, num); android_errorWriteLog(0x534e4554, "27855419"); return NULL; } return malloc(size * num); }
173,875
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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 nfs4_close_sync(struct path *path, struct nfs4_state *state, mode_t mode) { __nfs4_close(path, state, mode, 1); } Commit Message: NFSv4: Convert the open and close ops to use fmode Signed-off-by: Trond Myklebust <Trond.Myklebust@netapp.com> CWE ID:
void nfs4_close_sync(struct path *path, struct nfs4_state *state, mode_t mode) void nfs4_close_sync(struct path *path, struct nfs4_state *state, fmode_t fmode) { __nfs4_close(path, state, fmode, 1); }
165,711
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void MessageService::OpenChannelToExtension( int source_process_id, int source_routing_id, int receiver_port_id, const std::string& source_extension_id, const std::string& target_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()); MessagePort* receiver = new ExtensionMessagePort( GetExtensionProcess(profile, target_extension_id), MSG_ROUTING_CONTROL, target_extension_id); 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); } OpenChannelParams* params = new OpenChannelParams(source, tab_json, receiver, receiver_port_id, source_extension_id, target_extension_id, channel_name); if (MaybeAddPendingOpenChannelTask(profile, params)) { return; } OpenChannelImpl(scoped_ptr<OpenChannelParams>(params)); } 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::OpenChannelToExtension( int source_process_id, int source_routing_id, int receiver_port_id, const std::string& source_extension_id, const std::string& target_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()); MessagePort* receiver = new ExtensionMessagePort( GetExtensionProcess(profile, target_extension_id), MSG_ROUTING_CONTROL, target_extension_id); 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); } OpenChannelParams* params = new OpenChannelParams(source, tab_json, receiver, receiver_port_id, source_extension_id, target_extension_id, channel_name); if (MaybeAddPendingOpenChannelTask(profile, params)) { return; } OpenChannelImpl(scoped_ptr<OpenChannelParams>(params)); }
171,446
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void ElementsUploadDataStreamTest::FileChangedHelper( const base::FilePath& file_path, const base::Time& time, bool error_expected) { std::vector<std::unique_ptr<UploadElementReader>> element_readers; element_readers.push_back(base::MakeUnique<UploadFileElementReader>( base::ThreadTaskRunnerHandle::Get().get(), file_path, 1, 2, time)); TestCompletionCallback init_callback; std::unique_ptr<UploadDataStream> stream( new ElementsUploadDataStream(std::move(element_readers), 0)); ASSERT_THAT(stream->Init(init_callback.callback(), NetLogWithSource()), IsError(ERR_IO_PENDING)); int error_code = init_callback.WaitForResult(); if (error_expected) ASSERT_THAT(error_code, IsError(ERR_UPLOAD_FILE_CHANGED)); else ASSERT_THAT(error_code, IsOk()); } Commit Message: Replace base::MakeUnique with std::make_unique in net/. base/memory/ptr_util.h includes will be cleaned up later. Bug: 755727 Change-Id: Ibaf46f05c9b02b76f9a91e819984b087a8c0d434 Reviewed-on: https://chromium-review.googlesource.com/627300 Commit-Queue: Jeremy Roman <jbroman@chromium.org> Reviewed-by: Daniel Cheng <dcheng@chromium.org> Reviewed-by: Bence Béky <bnc@chromium.org> Cr-Commit-Position: refs/heads/master@{#498123} CWE ID: CWE-311
void ElementsUploadDataStreamTest::FileChangedHelper( const base::FilePath& file_path, const base::Time& time, bool error_expected) { std::vector<std::unique_ptr<UploadElementReader>> element_readers; element_readers.push_back(std::make_unique<UploadFileElementReader>( base::ThreadTaskRunnerHandle::Get().get(), file_path, 1, 2, time)); TestCompletionCallback init_callback; std::unique_ptr<UploadDataStream> stream( new ElementsUploadDataStream(std::move(element_readers), 0)); ASSERT_THAT(stream->Init(init_callback.callback(), NetLogWithSource()), IsError(ERR_IO_PENDING)); int error_code = init_callback.WaitForResult(); if (error_expected) ASSERT_THAT(error_code, IsError(ERR_UPLOAD_FILE_CHANGED)); else ASSERT_THAT(error_code, IsOk()); }
173,261
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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 inet6_csk_xmit(struct sock *sk, struct sk_buff *skb, struct flowi *fl_unused) { struct ipv6_pinfo *np = inet6_sk(sk); struct flowi6 fl6; struct dst_entry *dst; int res; dst = inet6_csk_route_socket(sk, &fl6); if (IS_ERR(dst)) { sk->sk_err_soft = -PTR_ERR(dst); sk->sk_route_caps = 0; kfree_skb(skb); return PTR_ERR(dst); } rcu_read_lock(); skb_dst_set_noref(skb, dst); /* Restore final destination back after routing done */ fl6.daddr = sk->sk_v6_daddr; res = ip6_xmit(sk, skb, &fl6, np->opt, np->tclass); rcu_read_unlock(); return res; } Commit Message: ipv6: add complete rcu protection around np->opt This patch addresses multiple problems : UDP/RAW sendmsg() need to get a stable struct ipv6_txoptions while socket is not locked : Other threads can change np->opt concurrently. Dmitry posted a syzkaller (http://github.com/google/syzkaller) program desmonstrating use-after-free. Starting with TCP/DCCP lockless listeners, tcp_v6_syn_recv_sock() and dccp_v6_request_recv_sock() also need to use RCU protection to dereference np->opt once (before calling ipv6_dup_options()) This patch adds full RCU protection to np->opt Reported-by: Dmitry Vyukov <dvyukov@google.com> Signed-off-by: Eric Dumazet <edumazet@google.com> Acked-by: Hannes Frederic Sowa <hannes@stressinduktion.org> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID: CWE-416
int inet6_csk_xmit(struct sock *sk, struct sk_buff *skb, struct flowi *fl_unused) { struct ipv6_pinfo *np = inet6_sk(sk); struct flowi6 fl6; struct dst_entry *dst; int res; dst = inet6_csk_route_socket(sk, &fl6); if (IS_ERR(dst)) { sk->sk_err_soft = -PTR_ERR(dst); sk->sk_route_caps = 0; kfree_skb(skb); return PTR_ERR(dst); } rcu_read_lock(); skb_dst_set_noref(skb, dst); /* Restore final destination back after routing done */ fl6.daddr = sk->sk_v6_daddr; res = ip6_xmit(sk, skb, &fl6, rcu_dereference(np->opt), np->tclass); rcu_read_unlock(); return res; }
167,334
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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_expand_16_mod(PNG_CONST image_transform *this, image_pixel *that, png_const_structp pp, PNG_CONST transform_display *display) { /* Expect expand_16 to expand everything to 16 bits as a result of also * causing 'expand' to happen. */ if (that->colour_type == PNG_COLOR_TYPE_PALETTE) image_pixel_convert_PLTE(that); if (that->have_tRNS) image_pixel_add_alpha(that, &display->this); if (that->bit_depth < 16) that->sample_depth = that->bit_depth = 16; this->next->mod(this->next, that, pp, display); } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
image_transform_png_set_expand_16_mod(PNG_CONST image_transform *this, image_transform_png_set_expand_16_mod(const image_transform *this, image_pixel *that, png_const_structp pp, const transform_display *display) { /* Expect expand_16 to expand everything to 16 bits as a result of also * causing 'expand' to happen. */ if (that->colour_type == PNG_COLOR_TYPE_PALETTE) image_pixel_convert_PLTE(that); if (that->have_tRNS) image_pixel_add_alpha(that, &display->this, 0/*!for background*/); if (that->bit_depth < 16) that->sample_depth = that->bit_depth = 16; this->next->mod(this->next, that, pp, display); }
173,627
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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 RecordResourceCompletionUMA(bool image_complete, bool css_complete, bool xhr_complete) { base::UmaHistogramBoolean("OfflinePages.Background.ResourceCompletion.Image", image_complete); base::UmaHistogramBoolean("OfflinePages.Background.ResourceCompletion.Css", css_complete); base::UmaHistogramBoolean("OfflinePages.Background.ResourceCompletion.Xhr", xhr_complete); } Commit Message: Remove unused histograms from the background loader offliner. Bug: 975512 Change-Id: I87b0a91bed60e3a9e8a1fd9ae9b18cac27a0859f Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1683361 Reviewed-by: Cathy Li <chili@chromium.org> Reviewed-by: Steven Holte <holte@chromium.org> Commit-Queue: Peter Williamson <petewil@chromium.org> Cr-Commit-Position: refs/heads/master@{#675332} CWE ID: CWE-119
void RecordResourceCompletionUMA(bool image_complete,
172,483
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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 SiteInstanceImpl::ShouldLockToOrigin(BrowserContext* browser_context, GURL site_url) { if (RenderProcessHost::run_renderer_in_process()) return false; if (!DoesSiteRequireDedicatedProcess(browser_context, site_url)) return false; if (site_url.SchemeIs(content::kGuestScheme)) return false; if (site_url.SchemeIs(content::kChromeUIScheme)) return false; if (!GetContentClient()->browser()->ShouldLockToOrigin(browser_context, site_url)) { return false; } return true; } Commit Message: Allow origin lock for WebUI pages. Returning true for WebUI pages in DoesSiteRequireDedicatedProcess helps to keep enforcing a SiteInstance swap during chrome://foo -> chrome://bar navigation, even after relaxing BrowsingInstance::GetSiteInstanceForURL to consider RPH::IsSuitableHost (see https://crrev.com/c/783470 for that fixes process sharing in isolated(b(c),d(c)) scenario). I've manually tested this CL by visiting the following URLs: - chrome://welcome/ - chrome://settings - chrome://extensions - chrome://history - chrome://help and chrome://chrome (both redirect to chrome://settings/help) Bug: 510588, 847127 Change-Id: I55073bce00f32cb8bc5c1c91034438ff9a3f8971 Reviewed-on: https://chromium-review.googlesource.com/1237392 Commit-Queue: Łukasz Anforowicz <lukasza@chromium.org> Reviewed-by: François Doray <fdoray@chromium.org> Reviewed-by: Nasko Oskov <nasko@chromium.org> Reviewed-by: Avi Drissman <avi@chromium.org> Cr-Commit-Position: refs/heads/master@{#595259} CWE ID: CWE-119
bool SiteInstanceImpl::ShouldLockToOrigin(BrowserContext* browser_context, GURL site_url) { if (RenderProcessHost::run_renderer_in_process()) return false; if (!DoesSiteRequireDedicatedProcess(browser_context, site_url)) return false; if (site_url.SchemeIs(content::kGuestScheme)) return false; if (!GetContentClient()->browser()->ShouldLockToOrigin(browser_context, site_url)) { return false; } return true; }
173,282
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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 PrintPreviewDataService::SetDataEntry( const std::string& preview_ui_addr_str, int index, const base::RefCountedBytes* data_bytes) { PreviewDataStoreMap::iterator it = data_store_map_.find(preview_ui_addr_str); if (it == data_store_map_.end()) data_store_map_[preview_ui_addr_str] = new PrintPreviewDataStore(); data_store_map_[preview_ui_addr_str]->SetPreviewDataForIndex(index, data_bytes); } 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 PrintPreviewDataService::SetDataEntry( int32 preview_ui_id, int index, const base::RefCountedBytes* data_bytes) { if (!ContainsKey(data_store_map_, preview_ui_id)) data_store_map_[preview_ui_id] = new PrintPreviewDataStore(); data_store_map_[preview_ui_id]->SetPreviewDataForIndex(index, data_bytes); }
170,824
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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 OMXNodeInstance::invalidateBufferID(OMX::buffer_id buffer __unused) { } Commit Message: IOMX: Enable buffer ptr to buffer id translation for arm32 Bug: 20634516 Change-Id: Iac9eac3cb251eccd9bbad5df7421a07edc21da0c (cherry picked from commit 2d6b6601743c3c6960c6511a2cb774ef902759f4) CWE ID: CWE-119
void OMXNodeInstance::invalidateBufferID(OMX::buffer_id buffer __unused) {
173,359
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: newkeys_to_blob(struct sshbuf *m, struct ssh *ssh, int mode) { struct sshbuf *b; struct sshcipher_ctx *cc; struct sshcomp *comp; struct sshenc *enc; struct sshmac *mac; struct newkeys *newkey; int r; if ((newkey = ssh->state->newkeys[mode]) == NULL) return SSH_ERR_INTERNAL_ERROR; enc = &newkey->enc; mac = &newkey->mac; comp = &newkey->comp; cc = (mode == MODE_OUT) ? ssh->state->send_context : ssh->state->receive_context; if ((r = cipher_get_keyiv(cc, enc->iv, enc->iv_len)) != 0) return r; if ((b = sshbuf_new()) == NULL) return SSH_ERR_ALLOC_FAIL; /* The cipher struct is constant and shared, you export pointer */ if ((r = sshbuf_put_cstring(b, enc->name)) != 0 || (r = sshbuf_put(b, &enc->cipher, sizeof(enc->cipher))) != 0 || (r = sshbuf_put_u32(b, enc->enabled)) != 0 || (r = sshbuf_put_u32(b, enc->block_size)) != 0 || (r = sshbuf_put_string(b, enc->key, enc->key_len)) != 0 || (r = sshbuf_put_string(b, enc->iv, enc->iv_len)) != 0) goto out; if (cipher_authlen(enc->cipher) == 0) { if ((r = sshbuf_put_cstring(b, mac->name)) != 0 || (r = sshbuf_put_u32(b, mac->enabled)) != 0 || (r = sshbuf_put_string(b, mac->key, mac->key_len)) != 0) goto out; } if ((r = sshbuf_put_u32(b, comp->type)) != 0 || (r = sshbuf_put_u32(b, comp->enabled)) != 0 || (r = sshbuf_put_cstring(b, comp->name)) != 0) goto out; r = sshbuf_put_stringb(m, b); out: sshbuf_free(b); return r; } Commit Message: Remove support for pre-authentication compression. Doing compression early in the protocol probably seemed reasonable in the 1990s, but today it's clearly a bad idea in terms of both cryptography (cf. multiple compression oracle attacks in TLS) and attack surface. Moreover, to support it across privilege-separation zlib needed the assistance of a complex shared-memory manager that made the required attack surface considerably larger. Prompted by Guido Vranken pointing out a compiler-elided security check in the shared memory manager found by Stack (http://css.csail.mit.edu/stack/); ok deraadt@ markus@ NB. pre-auth authentication has been disabled by default in sshd for >10 years. CWE ID: CWE-119
newkeys_to_blob(struct sshbuf *m, struct ssh *ssh, int mode) { struct sshbuf *b; struct sshcipher_ctx *cc; struct sshcomp *comp; struct sshenc *enc; struct sshmac *mac; struct newkeys *newkey; int r; if ((newkey = ssh->state->newkeys[mode]) == NULL) return SSH_ERR_INTERNAL_ERROR; enc = &newkey->enc; mac = &newkey->mac; comp = &newkey->comp; cc = (mode == MODE_OUT) ? ssh->state->send_context : ssh->state->receive_context; if ((r = cipher_get_keyiv(cc, enc->iv, enc->iv_len)) != 0) return r; if ((b = sshbuf_new()) == NULL) return SSH_ERR_ALLOC_FAIL; /* The cipher struct is constant and shared, you export pointer */ if ((r = sshbuf_put_cstring(b, enc->name)) != 0 || (r = sshbuf_put(b, &enc->cipher, sizeof(enc->cipher))) != 0 || (r = sshbuf_put_u32(b, enc->enabled)) != 0 || (r = sshbuf_put_u32(b, enc->block_size)) != 0 || (r = sshbuf_put_string(b, enc->key, enc->key_len)) != 0 || (r = sshbuf_put_string(b, enc->iv, enc->iv_len)) != 0) goto out; if (cipher_authlen(enc->cipher) == 0) { if ((r = sshbuf_put_cstring(b, mac->name)) != 0 || (r = sshbuf_put_u32(b, mac->enabled)) != 0 || (r = sshbuf_put_string(b, mac->key, mac->key_len)) != 0) goto out; } if ((r = sshbuf_put_u32(b, comp->type)) != 0 || (r = sshbuf_put_cstring(b, comp->name)) != 0) goto out; r = sshbuf_put_stringb(m, b); out: sshbuf_free(b); return r; }
168,651
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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 amd_gpio_remove(struct platform_device *pdev) { struct amd_gpio *gpio_dev; gpio_dev = platform_get_drvdata(pdev); gpiochip_remove(&gpio_dev->gc); pinctrl_unregister(gpio_dev->pctrl); return 0; } Commit Message: pinctrl/amd: Drop pinctrl_unregister for devm_ registered device It's not necessary to unregister pin controller device registered with devm_pinctrl_register() and using pinctrl_unregister() leads to a double free. Fixes: 3bfd44306c65 ("pinctrl: amd: Add support for additional GPIO") Signed-off-by: Wei Yongjun <weiyongjun1@huawei.com> Signed-off-by: Linus Walleij <linus.walleij@linaro.org> CWE ID: CWE-415
static int amd_gpio_remove(struct platform_device *pdev) { struct amd_gpio *gpio_dev; gpio_dev = platform_get_drvdata(pdev); gpiochip_remove(&gpio_dev->gc); return 0; }
169,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: SynchronousCompositorOutputSurface::DemandDrawHw( gfx::Size surface_size, const gfx::Transform& transform, gfx::Rect viewport, gfx::Rect clip, gfx::Rect viewport_rect_for_tile_priority, const gfx::Transform& transform_for_tile_priority) { DCHECK(CalledOnValidThread()); DCHECK(HasClient()); DCHECK(context_provider_.get()); surface_size_ = surface_size; InvokeComposite(transform, viewport, clip, viewport_rect_for_tile_priority, transform_for_tile_priority, true); return frame_holder_.Pass(); } Commit Message: sync compositor: pass simple gfx types by const ref See bug for reasoning BUG=159273 Review URL: https://codereview.chromium.org/1417893006 Cr-Commit-Position: refs/heads/master@{#356653} CWE ID: CWE-399
SynchronousCompositorOutputSurface::DemandDrawHw( const gfx::Size& surface_size, const gfx::Transform& transform, const gfx::Rect& viewport, const gfx::Rect& clip, const gfx::Rect& viewport_rect_for_tile_priority, const gfx::Transform& transform_for_tile_priority) { DCHECK(CalledOnValidThread()); DCHECK(HasClient()); DCHECK(context_provider_.get()); surface_size_ = surface_size; InvokeComposite(transform, viewport, clip, viewport_rect_for_tile_priority, transform_for_tile_priority, true); return frame_holder_.Pass(); }
171,621
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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::SetNetworkConditions( network::mojom::NetworkConditionsPtr conditions) { if (!process_) return; StoragePartition* partition = process_->GetStoragePartition(); network::mojom::NetworkContext* context = partition->GetNetworkContext(); context->SetNetworkConditions(host_id_, std::move(conditions)); } Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable This keeps BrowserContext* and StoragePartition* instead of RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost upon closure of DevTools front-end. Bug: 801117, 783067, 780694 Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b Reviewed-on: https://chromium-review.googlesource.com/876657 Commit-Queue: Andrey Kosyakov <caseq@chromium.org> Reviewed-by: Dmitry Gozman <dgozman@chromium.org> Cr-Commit-Position: refs/heads/master@{#531157} CWE ID: CWE-20
void NetworkHandler::SetNetworkConditions( network::mojom::NetworkConditionsPtr conditions) { if (!storage_partition_) return; network::mojom::NetworkContext* context = storage_partition_->GetNetworkContext(); context->SetNetworkConditions(host_id_, std::move(conditions)); }
172,762
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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 PluginModule::InstanceDeleted(PluginInstance* instance) { if (out_of_process_proxy_.get()) out_of_process_proxy_->RemoveInstance(instance->pp_instance()); instances_.erase(instance); if (nacl_ipc_proxy_) { out_of_process_proxy_.reset(); reserve_instance_id_ = NULL; } } Commit Message: Revert 143656 - Add an IPC channel between the NaCl loader process and the renderer. BUG=116317 TEST=ppapi, nacl tests, manual testing for experimental IPC proxy. Review URL: https://chromiumcodereview.appspot.com/10641016 TBR=bbudge@chromium.org Review URL: https://chromiumcodereview.appspot.com/10625007 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143665 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void PluginModule::InstanceDeleted(PluginInstance* instance) { if (out_of_process_proxy_.get()) out_of_process_proxy_->RemoveInstance(instance->pp_instance()); instances_.erase(instance); }
170,746
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: pim_print(netdissect_options *ndo, register const u_char *bp, register u_int len, const u_char *bp2) { register const u_char *ep; register const struct pim *pim = (const struct pim *)bp; ep = (const u_char *)ndo->ndo_snapend; if (bp >= ep) return; #ifdef notyet /* currently we see only version and type */ ND_TCHECK(pim->pim_rsv); #endif switch (PIM_VER(pim->pim_typever)) { case 2: if (!ndo->ndo_vflag) { ND_PRINT((ndo, "PIMv%u, %s, length %u", PIM_VER(pim->pim_typever), tok2str(pimv2_type_values,"Unknown Type",PIM_TYPE(pim->pim_typever)), len)); return; } else { ND_PRINT((ndo, "PIMv%u, length %u\n\t%s", PIM_VER(pim->pim_typever), len, tok2str(pimv2_type_values,"Unknown Type",PIM_TYPE(pim->pim_typever)))); pimv2_print(ndo, bp, len, bp2); } break; default: ND_PRINT((ndo, "PIMv%u, length %u", PIM_VER(pim->pim_typever), len)); break; } return; } Commit Message: CVE-2017-13030/PIM: Redo bounds checks and add length checks. Use ND_TCHECK macros to do bounds checking, and add length checks before the bounds checks. Add a bounds check that the review process found was missing. This fixes a buffer over-read discovered by Bhargava Shastry, SecT/TU Berlin. Add a test using the capture file supplied by the reporter(s), modified so the capture file won't be rejected as an invalid capture. Update one test output file to reflect the changes. CWE ID: CWE-125
pim_print(netdissect_options *ndo, register const u_char *bp, register u_int len, const u_char *bp2) { register const struct pim *pim = (const struct pim *)bp; #ifdef notyet /* currently we see only version and type */ ND_TCHECK(pim->pim_rsv); #endif ND_TCHECK(pim->pim_typever); switch (PIM_VER(pim->pim_typever)) { case 2: if (!ndo->ndo_vflag) { ND_PRINT((ndo, "PIMv%u, %s, length %u", PIM_VER(pim->pim_typever), tok2str(pimv2_type_values,"Unknown Type",PIM_TYPE(pim->pim_typever)), len)); return; } else { ND_PRINT((ndo, "PIMv%u, length %u\n\t%s", PIM_VER(pim->pim_typever), len, tok2str(pimv2_type_values,"Unknown Type",PIM_TYPE(pim->pim_typever)))); pimv2_print(ndo, bp, len, bp2); } break; default: ND_PRINT((ndo, "PIMv%u, length %u", PIM_VER(pim->pim_typever), len)); break; } return; trunc: ND_PRINT((ndo, "[|pim]")); return; }
167,854
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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 vfio_msi_enable(struct vfio_pci_device *vdev, int nvec, bool msix) { struct pci_dev *pdev = vdev->pdev; unsigned int flag = msix ? PCI_IRQ_MSIX : PCI_IRQ_MSI; int ret; if (!is_irq_none(vdev)) return -EINVAL; vdev->ctx = kzalloc(nvec * sizeof(struct vfio_pci_irq_ctx), GFP_KERNEL); if (!vdev->ctx) return -ENOMEM; /* return the number of supported vectors if we can't get all: */ ret = pci_alloc_irq_vectors(pdev, 1, nvec, flag); if (ret < nvec) { if (ret > 0) pci_free_irq_vectors(pdev); kfree(vdev->ctx); return ret; } vdev->num_ctx = nvec; vdev->irq_type = msix ? VFIO_PCI_MSIX_IRQ_INDEX : VFIO_PCI_MSI_IRQ_INDEX; if (!msix) { /* * Compute the virtual hardware field for max msi vectors - * it is the log base 2 of the number of vectors. */ vdev->msi_qmax = fls(nvec * 2 - 1) - 1; } return 0; } Commit Message: vfio/pci: Fix integer overflows, bitmask check The VFIO_DEVICE_SET_IRQS ioctl did not sufficiently sanitize user-supplied integers, potentially allowing memory corruption. This patch adds appropriate integer overflow checks, checks the range bounds for VFIO_IRQ_SET_DATA_NONE, and also verifies that only single element in the VFIO_IRQ_SET_DATA_TYPE_MASK bitmask is set. VFIO_IRQ_SET_ACTION_TYPE_MASK is already correctly checked later in vfio_pci_set_irqs_ioctl(). Furthermore, a kzalloc is changed to a kcalloc because the use of a kzalloc with an integer multiplication allowed an integer overflow condition to be reached without this patch. kcalloc checks for overflow and should prevent a similar occurrence. Signed-off-by: Vlad Tsyrklevich <vlad@tsyrklevich.net> Signed-off-by: Alex Williamson <alex.williamson@redhat.com> CWE ID: CWE-190
static int vfio_msi_enable(struct vfio_pci_device *vdev, int nvec, bool msix) { struct pci_dev *pdev = vdev->pdev; unsigned int flag = msix ? PCI_IRQ_MSIX : PCI_IRQ_MSI; int ret; if (!is_irq_none(vdev)) return -EINVAL; vdev->ctx = kcalloc(nvec, sizeof(struct vfio_pci_irq_ctx), GFP_KERNEL); if (!vdev->ctx) return -ENOMEM; /* return the number of supported vectors if we can't get all: */ ret = pci_alloc_irq_vectors(pdev, 1, nvec, flag); if (ret < nvec) { if (ret > 0) pci_free_irq_vectors(pdev); kfree(vdev->ctx); return ret; } vdev->num_ctx = nvec; vdev->irq_type = msix ? VFIO_PCI_MSIX_IRQ_INDEX : VFIO_PCI_MSI_IRQ_INDEX; if (!msix) { /* * Compute the virtual hardware field for max msi vectors - * it is the log base 2 of the number of vectors. */ vdev->msi_qmax = fls(nvec * 2 - 1) - 1; } return 0; }
166,901
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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 lookup1_values(int entries, int dim) { int r = (int) floor(exp((float) log((float) entries) / dim)); if ((int) floor(pow((float) r+1, dim)) <= entries) // (int) cast for MinGW warning; ++r; // floor() to avoid _ftol() when non-CRT assert(pow((float) r+1, dim) > entries); assert((int) floor(pow((float) r, dim)) <= entries); // (int),floor() as above return r; } Commit Message: Fix seven bugs discovered and fixed by ForAllSecure: CVE-2019-13217: heap buffer overflow in start_decoder() CVE-2019-13218: stack buffer overflow in compute_codewords() CVE-2019-13219: uninitialized memory in vorbis_decode_packet_rest() CVE-2019-13220: out-of-range read in draw_line() CVE-2019-13221: issue with large 1D codebooks in lookup1_values() CVE-2019-13222: unchecked NULL returned by get_window() CVE-2019-13223: division by zero in predict_point() CWE ID: CWE-20
static int lookup1_values(int entries, int dim) { int r = (int) floor(exp((float) log((float) entries) / dim)); if ((int) floor(pow((float) r+1, dim)) <= entries) // (int) cast for MinGW warning; ++r; // floor() to avoid _ftol() when non-CRT if (pow((float) r+1, dim) <= entries) return -1; if ((int) floor(pow((float) r, dim)) > entries) return -1; return r; }
169,616
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: MagickExport const char *GetMagickFeatures(void) { return "DPC" #if defined(MAGICKCORE_BUILD_MODULES) || defined(_DLL) " Modules" #endif #if defined(MAGICKCORE_HDRI_SUPPORT) " HDRI" #endif #if defined(MAGICKCORE_OPENCL_SUPPORT) " OpenCL" #endif #if defined(MAGICKCORE_OPENMP_SUPPORT) " OpenMP" #endif ; } Commit Message: CWE ID: CWE-189
MagickExport const char *GetMagickFeatures(void) { return "DPC" #if defined(MAGICKCORE_WINDOWS_SUPPORT) && defined(_DEBUG) " Debug" #endif #if defined(MAGICKCORE_CIPHER_SUPPORT) " Cipher" #endif #if defined(MAGICKCORE_HDRI_SUPPORT) " HDRI" #endif #if defined(MAGICKCORE_BUILD_MODULES) || defined(_DLL) " Modules" #endif #if defined(MAGICKCORE_OPENCL_SUPPORT) " OpenCL" #endif #if defined(MAGICKCORE_OPENMP_SUPPORT) " OpenMP" #endif #if defined(ZERO_CONFIGURATION_SUPPORT) " Zero-configuration" #endif ; }
168,861
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: virtual InputMethodDescriptor current_input_method() const { if (current_input_method_.id.empty()) { return input_method::GetFallbackInputMethodDescriptor(); } return current_input_method_; } Commit Message: Remove use of libcros from InputMethodLibrary. BUG=chromium-os:16238 TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before. Review URL: http://codereview.chromium.org/7003086 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
virtual InputMethodDescriptor current_input_method() const { virtual input_method::InputMethodDescriptor current_input_method() const { if (current_input_method_.id.empty()) { return input_method::GetFallbackInputMethodDescriptor(); } return current_input_method_; }
170,512
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: set_text_distance(gs_point *pdist, double dx, double dy, const gs_matrix *pmat) { int code = gs_distance_transform_inverse(dx, dy, pmat, pdist); double rounded; if (code == gs_error_undefinedresult) { /* The CTM is degenerate. Can't know the distance in user space. } else if (code < 0) return code; /* If the distance is very close to integers, round it. */ if (fabs(pdist->x - (rounded = floor(pdist->x + 0.5))) < 0.0005) pdist->x = rounded; if (fabs(pdist->y - (rounded = floor(pdist->y + 0.5))) < 0.0005) pdist->y = rounded; return 0; } Commit Message: CWE ID: CWE-119
set_text_distance(gs_point *pdist, double dx, double dy, const gs_matrix *pmat) { int code; double rounded; if (dx > 1e38 || dy > 1e38) code = gs_error_undefinedresult; else code = gs_distance_transform_inverse(dx, dy, pmat, pdist); if (code == gs_error_undefinedresult) { /* The CTM is degenerate. Can't know the distance in user space. } else if (code < 0) return code; /* If the distance is very close to integers, round it. */ if (fabs(pdist->x - (rounded = floor(pdist->x + 0.5))) < 0.0005) pdist->x = rounded; if (fabs(pdist->y - (rounded = floor(pdist->y + 0.5))) < 0.0005) pdist->y = rounded; return 0; }
164,898
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: plan_a (char const *filename) { char const *s; char const *lim; char const **ptr; char *buffer; lin iline; size_t size = instat.st_size; /* Fail if the file size doesn't fit in a size_t, or if storage isn't available. */ if (! (size == instat.st_size && (buffer = malloc (size ? size : (size_t) 1)))) return false; /* Read the input file, but don't bother reading it if it's empty. When creating files, the files do not actually exist. */ if (size) { if (S_ISREG (instat.st_mode)) { int ifd = safe_open (filename, O_RDONLY|binary_transput, 0); size_t buffered = 0, n; if (ifd < 0) pfatal ("can't open file %s", quotearg (filename)); /* Some non-POSIX hosts exaggerate st_size in text mode; or the file may have shrunk! */ size = buffered; break; } if (n == (size_t) -1) { /* Perhaps size is too large for this host. */ close (ifd); free (buffer); return false; } buffered += n; } if (close (ifd) != 0) read_fatal (); } Commit Message: CWE ID: CWE-59
plan_a (char const *filename) { char const *s; char const *lim; char const **ptr; char *buffer; lin iline; size_t size = instat.st_size; /* Fail if the file size doesn't fit in a size_t, or if storage isn't available. */ if (! (size == instat.st_size && (buffer = malloc (size ? size : (size_t) 1)))) return false; /* Read the input file, but don't bother reading it if it's empty. When creating files, the files do not actually exist. */ if (size) { if (S_ISREG (instat.st_mode)) { int flags = O_RDONLY | binary_transput; size_t buffered = 0, n; int ifd; if (! follow_symlinks) flags |= O_NOFOLLOW; ifd = safe_open (filename, flags, 0); if (ifd < 0) pfatal ("can't open file %s", quotearg (filename)); /* Some non-POSIX hosts exaggerate st_size in text mode; or the file may have shrunk! */ size = buffered; break; } if (n == (size_t) -1) { /* Perhaps size is too large for this host. */ close (ifd); free (buffer); return false; } buffered += n; } if (close (ifd) != 0) read_fatal (); }
164,685
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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 AXListBoxOption::isEnabled() const { if (!getNode()) return false; if (equalIgnoringCase(getAttribute(aria_disabledAttr), "true")) return false; if (toElement(getNode())->hasAttribute(disabledAttr)) return false; return true; } Commit Message: Switch to equalIgnoringASCIICase throughout modules/accessibility BUG=627682 Review-Url: https://codereview.chromium.org/2793913007 Cr-Commit-Position: refs/heads/master@{#461858} CWE ID: CWE-254
bool AXListBoxOption::isEnabled() const { if (!getNode()) return false; if (equalIgnoringASCIICase(getAttribute(aria_disabledAttr), "true")) return false; if (toElement(getNode())->hasAttribute(disabledAttr)) return false; return true; }
171,907
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: pdf_dict_put(fz_context *ctx, pdf_obj *obj, pdf_obj *key, pdf_obj *val) { int i; RESOLVE(obj); if (!OBJ_IS_DICT(obj)) fz_throw(ctx, FZ_ERROR_GENERIC, "not a dict (%s)", pdf_objkindstr(obj)); if (!val) val = PDF_OBJ_NULL; if (DICT(obj)->len > 100 && !(obj->flags & PDF_FLAGS_SORTED)) pdf_sort_dict(ctx, obj); if (key < PDF_OBJ_NAME__LIMIT) i = pdf_dict_find(ctx, obj, key); else i = pdf_dict_finds(ctx, obj, pdf_to_name(ctx, key)); prepare_object_for_alteration(ctx, obj, val); if (i >= 0 && i < DICT(obj)->len) { if (DICT(obj)->items[i].v != val) { pdf_obj *d = DICT(obj)->items[i].v; DICT(obj)->items[i].v = pdf_keep_obj(ctx, val); { pdf_obj *d = DICT(obj)->items[i].v; DICT(obj)->items[i].v = pdf_keep_obj(ctx, val); pdf_drop_obj(ctx, d); } } else memmove(&DICT(obj)->items[i + 1], &DICT(obj)->items[i], (DICT(obj)->len - i) * sizeof(struct keyval)); DICT(obj)->items[i].k = pdf_keep_obj(ctx, key); DICT(obj)->items[i].v = pdf_keep_obj(ctx, val); DICT(obj)->len ++; } } Commit Message: CWE ID: CWE-416
pdf_dict_put(fz_context *ctx, pdf_obj *obj, pdf_obj *key, pdf_obj *val) static void pdf_dict_get_put(fz_context *ctx, pdf_obj *obj, pdf_obj *key, pdf_obj *val, pdf_obj **old_val) { int i; if (old_val) *old_val = NULL; RESOLVE(obj); if (!OBJ_IS_DICT(obj)) fz_throw(ctx, FZ_ERROR_GENERIC, "not a dict (%s)", pdf_objkindstr(obj)); if (!val) val = PDF_OBJ_NULL; if (DICT(obj)->len > 100 && !(obj->flags & PDF_FLAGS_SORTED)) pdf_sort_dict(ctx, obj); if (key < PDF_OBJ_NAME__LIMIT) i = pdf_dict_find(ctx, obj, key); else i = pdf_dict_finds(ctx, obj, pdf_to_name(ctx, key)); prepare_object_for_alteration(ctx, obj, val); if (i >= 0 && i < DICT(obj)->len) { if (DICT(obj)->items[i].v != val) { pdf_obj *d = DICT(obj)->items[i].v; DICT(obj)->items[i].v = pdf_keep_obj(ctx, val); { pdf_obj *d = DICT(obj)->items[i].v; DICT(obj)->items[i].v = pdf_keep_obj(ctx, val); if (old_val) *old_val = d; else pdf_drop_obj(ctx, d); } } else memmove(&DICT(obj)->items[i + 1], &DICT(obj)->items[i], (DICT(obj)->len - i) * sizeof(struct keyval)); DICT(obj)->items[i].k = pdf_keep_obj(ctx, key); DICT(obj)->items[i].v = pdf_keep_obj(ctx, val); DICT(obj)->len ++; } }
165,260
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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 cJSON_AddItemToArray( cJSON *array, cJSON *item ) { cJSON *c = array->child; if ( ! item ) return; if ( ! c ) { array->child = item; } else { while ( c && c->next ) c = c->next; suffix_object( c, item ); } } Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a malformed JSON string was passed on the control channel. This issue, present in the cJSON library, was already fixed upstream, so was addressed here in iperf3 by importing a newer version of cJSON (plus local ESnet modifications). Discovered and reported by Dave McDaniel, Cisco Talos. Based on a patch by @dopheide-esnet, with input from @DaveGamble. Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001, CVE-2016-4303 (cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40) Signed-off-by: Bruce A. Mah <bmah@es.net> CWE ID: CWE-119
void cJSON_AddItemToArray( cJSON *array, cJSON *item )
167,267
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: xps_begin_opacity(xps_document *doc, const fz_matrix *ctm, const fz_rect *area, char *base_uri, xps_resource *dict, char *opacity_att, fz_xml *opacity_mask_tag) { float opacity; if (!opacity_att && !opacity_mask_tag) return; opacity = 1; if (opacity_att) opacity = fz_atof(opacity_att); if (opacity_mask_tag && !strcmp(fz_xml_tag(opacity_mask_tag), "SolidColorBrush")) { char *scb_opacity_att = fz_xml_att(opacity_mask_tag, "Opacity"); char *scb_color_att = fz_xml_att(opacity_mask_tag, "Color"); if (scb_opacity_att) opacity = opacity * fz_atof(scb_opacity_att); if (scb_color_att) { fz_colorspace *colorspace; float samples[32]; xps_parse_color(doc, base_uri, scb_color_att, &colorspace, samples); opacity = opacity * samples[0]; } opacity_mask_tag = NULL; } if (doc->opacity_top + 1 < nelem(doc->opacity)) { doc->opacity[doc->opacity_top + 1] = doc->opacity[doc->opacity_top] * opacity; doc->opacity_top++; } if (opacity_mask_tag) { fz_begin_mask(doc->dev, area, 0, NULL, NULL); xps_parse_brush(doc, ctm, area, base_uri, dict, opacity_mask_tag); fz_end_mask(doc->dev); } } Commit Message: CWE ID: CWE-119
xps_begin_opacity(xps_document *doc, const fz_matrix *ctm, const fz_rect *area, char *base_uri, xps_resource *dict, char *opacity_att, fz_xml *opacity_mask_tag) { float opacity; if (!opacity_att && !opacity_mask_tag) return; opacity = 1; if (opacity_att) opacity = fz_atof(opacity_att); if (opacity_mask_tag && !strcmp(fz_xml_tag(opacity_mask_tag), "SolidColorBrush")) { char *scb_opacity_att = fz_xml_att(opacity_mask_tag, "Opacity"); char *scb_color_att = fz_xml_att(opacity_mask_tag, "Color"); if (scb_opacity_att) opacity = opacity * fz_atof(scb_opacity_att); if (scb_color_att) { fz_colorspace *colorspace; float samples[FZ_MAX_COLORS]; xps_parse_color(doc, base_uri, scb_color_att, &colorspace, samples); opacity = opacity * samples[0]; } opacity_mask_tag = NULL; } if (doc->opacity_top + 1 < nelem(doc->opacity)) { doc->opacity[doc->opacity_top + 1] = doc->opacity[doc->opacity_top] * opacity; doc->opacity_top++; } if (opacity_mask_tag) { fz_begin_mask(doc->dev, area, 0, NULL, NULL); xps_parse_brush(doc, ctm, area, base_uri, dict, opacity_mask_tag); fz_end_mask(doc->dev); } }
165,227
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: flatpak_proxy_client_init (FlatpakProxyClient *client) { init_side (client, &client->client_side); init_side (client, &client->bus_side); client->auth_end_offset = AUTH_END_INIT_OFFSET; client->rewrite_reply = g_hash_table_new_full (g_direct_hash, g_direct_equal, NULL, g_object_unref); client->get_owner_reply = g_hash_table_new_full (g_direct_hash, g_direct_equal, NULL, g_free); client->unique_id_policy = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL); } Commit Message: Fix vulnerability in dbus proxy During the authentication all client data is directly forwarded to the dbus daemon as is, until we detect the BEGIN command after which we start filtering the binary dbus protocol. Unfortunately the detection of the BEGIN command in the proxy did not exactly match the detection in the dbus daemon. A BEGIN followed by a space or tab was considered ok in the daemon but not by the proxy. This could be exploited to send arbitrary dbus messages to the host, which can be used to break out of the sandbox. This was noticed by Gabriel Campana of The Google Security Team. This fix makes the detection of the authentication phase end match the dbus code. In addition we duplicate the authentication line validation from dbus, which includes ensuring all data is ASCII, and limiting the size of a line to 16k. In fact, we add some extra stringent checks, disallowing ASCII control chars and requiring that auth lines start with a capital letter. CWE ID: CWE-436
flatpak_proxy_client_init (FlatpakProxyClient *client) { init_side (client, &client->client_side); init_side (client, &client->bus_side); client->auth_buffer = g_byte_array_new (); client->rewrite_reply = g_hash_table_new_full (g_direct_hash, g_direct_equal, NULL, g_object_unref); client->get_owner_reply = g_hash_table_new_full (g_direct_hash, g_direct_equal, NULL, g_free); client->unique_id_policy = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL); }
169,342
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static bool CheckMov(const uint8* buffer, int buffer_size) { RCHECK(buffer_size > 8); int offset = 0; while (offset + 8 < buffer_size) { int atomsize = Read32(buffer + offset); uint32 atomtype = Read32(buffer + offset + 4); switch (atomtype) { case TAG('f','t','y','p'): case TAG('p','d','i','n'): case TAG('m','o','o','v'): case TAG('m','o','o','f'): case TAG('m','f','r','a'): case TAG('m','d','a','t'): case TAG('f','r','e','e'): case TAG('s','k','i','p'): case TAG('m','e','t','a'): case TAG('m','e','c','o'): case TAG('s','t','y','p'): case TAG('s','i','d','x'): case TAG('s','s','i','x'): case TAG('p','r','f','t'): case TAG('b','l','o','c'): break; default: return false; } if (atomsize == 1) { if (offset + 16 > buffer_size) break; if (Read32(buffer + offset + 8) != 0) break; // Offset is way past buffer size. atomsize = Read32(buffer + offset + 12); } if (atomsize <= 0) break; // Indicates the last atom or length too big. offset += atomsize; } return true; } Commit Message: Add extra checks to avoid integer overflow. BUG=425980 TEST=no crash with ASAN Review URL: https://codereview.chromium.org/659743004 Cr-Commit-Position: refs/heads/master@{#301249} CWE ID: CWE-189
static bool CheckMov(const uint8* buffer, int buffer_size) { RCHECK(buffer_size > 8); int offset = 0; while (offset + 8 < buffer_size) { uint32 atomsize = Read32(buffer + offset); uint32 atomtype = Read32(buffer + offset + 4); switch (atomtype) { case TAG('f','t','y','p'): case TAG('p','d','i','n'): case TAG('m','o','o','v'): case TAG('m','o','o','f'): case TAG('m','f','r','a'): case TAG('m','d','a','t'): case TAG('f','r','e','e'): case TAG('s','k','i','p'): case TAG('m','e','t','a'): case TAG('m','e','c','o'): case TAG('s','t','y','p'): case TAG('s','i','d','x'): case TAG('s','s','i','x'): case TAG('p','r','f','t'): case TAG('b','l','o','c'): break; default: return false; } if (atomsize == 1) { if (offset + 16 > buffer_size) break; if (Read32(buffer + offset + 8) != 0) break; // Offset is way past buffer size. atomsize = Read32(buffer + offset + 12); } if (atomsize == 0 || atomsize > static_cast<size_t>(buffer_size)) break; // Indicates the last atom or length too big. offset += atomsize; } return true; }
171,611
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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 ChromeContentRendererClient::RenderViewCreated(RenderView* render_view) { ContentSettingsObserver* content_settings = new ContentSettingsObserver(render_view); new DevToolsAgent(render_view); new ExtensionHelper(render_view, extension_dispatcher_.get()); new PageLoadHistograms(render_view, histogram_snapshots_.get()); new PrintWebViewHelper(render_view); new SearchBox(render_view); new SpellCheckProvider(render_view, spellcheck_.get()); #if defined(ENABLE_SAFE_BROWSING) safe_browsing::MalwareDOMDetails::Create(render_view); #endif #if defined(OS_MACOSX) new TextInputClientObserver(render_view); #endif // defined(OS_MACOSX) PasswordAutofillManager* password_autofill_manager = new PasswordAutofillManager(render_view); AutofillAgent* autofill_agent = new AutofillAgent(render_view, password_autofill_manager); PageClickTracker* page_click_tracker = new PageClickTracker(render_view); page_click_tracker->AddListener(password_autofill_manager); page_click_tracker->AddListener(autofill_agent); TranslateHelper* translate = new TranslateHelper(render_view, autofill_agent); new ChromeRenderViewObserver( render_view, content_settings, extension_dispatcher_.get(), translate); if (CommandLine::ForCurrentProcess()->HasSwitch( switches::kDomAutomationController)) { new AutomationRendererHelper(render_view); } } Commit Message: DevTools: move DevToolsAgent/Client into content. BUG=84078 TEST= Review URL: http://codereview.chromium.org/7461019 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@93596 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
void ChromeContentRendererClient::RenderViewCreated(RenderView* render_view) { ContentSettingsObserver* content_settings = new ContentSettingsObserver(render_view); new ExtensionHelper(render_view, extension_dispatcher_.get()); new PageLoadHistograms(render_view, histogram_snapshots_.get()); new PrintWebViewHelper(render_view); new SearchBox(render_view); new SpellCheckProvider(render_view, spellcheck_.get()); #if defined(ENABLE_SAFE_BROWSING) safe_browsing::MalwareDOMDetails::Create(render_view); #endif #if defined(OS_MACOSX) new TextInputClientObserver(render_view); #endif // defined(OS_MACOSX) PasswordAutofillManager* password_autofill_manager = new PasswordAutofillManager(render_view); AutofillAgent* autofill_agent = new AutofillAgent(render_view, password_autofill_manager); PageClickTracker* page_click_tracker = new PageClickTracker(render_view); page_click_tracker->AddListener(password_autofill_manager); page_click_tracker->AddListener(autofill_agent); TranslateHelper* translate = new TranslateHelper(render_view, autofill_agent); new ChromeRenderViewObserver( render_view, content_settings, extension_dispatcher_.get(), translate); if (CommandLine::ForCurrentProcess()->HasSwitch( switches::kDomAutomationController)) { new AutomationRendererHelper(render_view); } }
170,324
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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 get_frame_stats(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, vpx_fixed_buf_t *stats) { 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 get frame stats."); while ((pkt = vpx_codec_get_cx_data(ctx, &iter)) != NULL) { if (pkt->kind == VPX_CODEC_STATS_PKT) { const uint8_t *const pkt_buf = pkt->data.twopass_stats.buf; const size_t pkt_size = pkt->data.twopass_stats.sz; stats->buf = realloc(stats->buf, stats->sz + pkt_size); memcpy((uint8_t *)stats->buf + stats->sz, pkt_buf, pkt_size); stats->sz += pkt_size; } } } 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 get_frame_stats(vpx_codec_ctx_t *ctx, static int get_frame_stats(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, vpx_fixed_buf_t *stats) { 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 get frame stats."); while ((pkt = vpx_codec_get_cx_data(ctx, &iter)) != NULL) { got_pkts = 1; if (pkt->kind == VPX_CODEC_STATS_PKT) { const uint8_t *const pkt_buf = pkt->data.twopass_stats.buf; const size_t pkt_size = pkt->data.twopass_stats.sz; stats->buf = realloc(stats->buf, stats->sz + pkt_size); memcpy((uint8_t *)stats->buf + stats->sz, pkt_buf, pkt_size); stats->sz += pkt_size; } } return got_pkts; }
174,492
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void RenderFrameObserverNatives::OnDocumentElementCreated( const v8::FunctionCallbackInfo<v8::Value>& args) { CHECK(args.Length() == 2); CHECK(args[0]->IsInt32()); CHECK(args[1]->IsFunction()); int frame_id = args[0]->Int32Value(); content::RenderFrame* frame = content::RenderFrame::FromRoutingID(frame_id); if (!frame) { LOG(WARNING) << "No render frame found to register LoadWatcher."; return; } new LoadWatcher(context(), frame, args[1].As<v8::Function>()); args.GetReturnValue().Set(true); } Commit Message: Fix re-entrancy and lifetime issue in RenderFrameObserverNatives::OnDocumentElementCreated BUG=585268,568130 Review URL: https://codereview.chromium.org/1684953002 Cr-Commit-Position: refs/heads/master@{#374758} CWE ID:
void RenderFrameObserverNatives::OnDocumentElementCreated( const v8::FunctionCallbackInfo<v8::Value>& args) { CHECK(args.Length() == 2); CHECK(args[0]->IsInt32()); CHECK(args[1]->IsFunction()); int frame_id = args[0]->Int32Value(); content::RenderFrame* frame = content::RenderFrame::FromRoutingID(frame_id); if (!frame) { LOG(WARNING) << "No render frame found to register LoadWatcher."; return; } v8::Global<v8::Function> v8_callback(context()->isolate(), args[1].As<v8::Function>()); base::Callback<void(bool)> callback( base::Bind(&RenderFrameObserverNatives::InvokeCallback, weak_ptr_factory_.GetWeakPtr(), base::Passed(&v8_callback))); if (ExtensionFrameHelper::Get(frame)->did_create_current_document_element()) { // If the document element is already created, then we can call the callback // immediately (though use PostTask to ensure that the callback is called // asynchronously). base::MessageLoop::current()->PostTask(FROM_HERE, base::Bind(callback, true)); } else { new LoadWatcher(frame, callback); } args.GetReturnValue().Set(true); }
172,146
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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 gup_huge_pmd(pmd_t orig, pmd_t *pmdp, unsigned long addr, unsigned long end, int write, struct page **pages, int *nr) { struct page *head, *page; int refs; if (!pmd_access_permitted(orig, write)) return 0; if (pmd_devmap(orig)) return __gup_device_huge_pmd(orig, pmdp, addr, end, pages, nr); refs = 0; page = pmd_page(orig) + ((addr & ~PMD_MASK) >> PAGE_SHIFT); do { pages[*nr] = page; (*nr)++; page++; refs++; } while (addr += PAGE_SIZE, addr != end); head = compound_head(pmd_page(orig)); if (!page_cache_add_speculative(head, refs)) { *nr -= refs; return 0; } if (unlikely(pmd_val(orig) != pmd_val(*pmdp))) { *nr -= refs; while (refs--) put_page(head); return 0; } SetPageReferenced(head); return 1; } Commit Message: Merge branch 'page-refs' (page ref overflow) Merge page ref overflow branch. Jann Horn reported that he can overflow the page ref count with sufficient memory (and a filesystem that is intentionally extremely slow). Admittedly it's not exactly easy. To have more than four billion references to a page requires a minimum of 32GB of kernel memory just for the pointers to the pages, much less any metadata to keep track of those pointers. Jann needed a total of 140GB of memory and a specially crafted filesystem that leaves all reads pending (in order to not ever free the page references and just keep adding more). Still, we have a fairly straightforward way to limit the two obvious user-controllable sources of page references: direct-IO like page references gotten through get_user_pages(), and the splice pipe page duplication. So let's just do that. * branch page-refs: fs: prevent page refcount overflow in pipe_buf_get mm: prevent get_user_pages() from overflowing page refcount mm: add 'try_get_page()' helper function mm: make page ref count overflow check tighter and more explicit CWE ID: CWE-416
static int gup_huge_pmd(pmd_t orig, pmd_t *pmdp, unsigned long addr, unsigned long end, int write, struct page **pages, int *nr) { struct page *head, *page; int refs; if (!pmd_access_permitted(orig, write)) return 0; if (pmd_devmap(orig)) return __gup_device_huge_pmd(orig, pmdp, addr, end, pages, nr); refs = 0; page = pmd_page(orig) + ((addr & ~PMD_MASK) >> PAGE_SHIFT); do { pages[*nr] = page; (*nr)++; page++; refs++; } while (addr += PAGE_SIZE, addr != end); head = try_get_compound_head(pmd_page(orig), refs); if (!head) { *nr -= refs; return 0; } if (unlikely(pmd_val(orig) != pmd_val(*pmdp))) { *nr -= refs; while (refs--) put_page(head); return 0; } SetPageReferenced(head); return 1; }
170,226
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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 mct_u232_port_probe(struct usb_serial_port *port) { struct mct_u232_private *priv; priv = kzalloc(sizeof(*priv), GFP_KERNEL); if (!priv) return -ENOMEM; /* Use second interrupt-in endpoint for reading. */ priv->read_urb = port->serial->port[1]->interrupt_in_urb; priv->read_urb->context = port; spin_lock_init(&priv->lock); usb_set_serial_port_data(port, priv); return 0; } Commit Message: USB: mct_u232: add sanity checking in probe An attack using the lack of sanity checking in probe is known. This patch checks for the existence of a second port. CVE-2016-3136 Signed-off-by: Oliver Neukum <ONeukum@suse.com> CC: stable@vger.kernel.org [johan: add error message ] Signed-off-by: Johan Hovold <johan@kernel.org> Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org> CWE ID:
static int mct_u232_port_probe(struct usb_serial_port *port) { struct usb_serial *serial = port->serial; struct mct_u232_private *priv; /* check first to simplify error handling */ if (!serial->port[1] || !serial->port[1]->interrupt_in_urb) { dev_err(&port->dev, "expected endpoint missing\n"); return -ENODEV; } priv = kzalloc(sizeof(*priv), GFP_KERNEL); if (!priv) return -ENOMEM; /* Use second interrupt-in endpoint for reading. */ priv->read_urb = serial->port[1]->interrupt_in_urb; priv->read_urb->context = port; spin_lock_init(&priv->lock); usb_set_serial_port_data(port, priv); return 0; }
167,361
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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 AcceleratedSurfaceBuffersSwappedCompleted(int host_id, int route_id, int surface_id, bool alive, base::TimeTicks timebase, base::TimeDelta interval) { AcceleratedSurfaceBuffersSwappedCompletedForGPU(host_id, route_id, alive, true /* presented */); AcceleratedSurfaceBuffersSwappedCompletedForRenderer(surface_id, timebase, interval); } Commit Message: Implement TextureImageTransportSurface using texture mailbox This has a couple of advantages: - allow tearing down and recreating the UI parent context without losing the renderer contexts - do not require a context to be able to generate textures when creating the GLSurfaceHandle - clearer ownership semantics that potentially allows for more robust and easier lost context handling/thumbnailing/etc., since a texture is at any given time owned by either: UI parent, mailbox, or TextureImageTransportSurface - simplify frontbuffer protection logic; the frontbuffer textures are now owned by RWHV where they are refcounted The TextureImageTransportSurface informs RenderWidgetHostView of the mailbox names for the front- and backbuffer textures by associating them with a surface_handle (1 or 2) in the AcceleratedSurfaceNew message. During SwapBuffers() or PostSubBuffer() cycles, it then uses produceTextureCHROMIUM() and consumeTextureCHROMIUM() to transfer ownership between renderer and browser compositor. RWHV sends back the surface_handle of the buffer being returned with the Swap ACK (or 0 if no buffer is being returned in which case TextureImageTransportSurface will allocate a new texture - note that this could be used to simply keep textures for thumbnailing). BUG=154815,139616 TBR=sky@chromium.org Review URL: https://chromiumcodereview.appspot.com/11194042 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171569 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
void AcceleratedSurfaceBuffersSwappedCompleted(int host_id, int route_id, int surface_id, uint64 surface_handle, bool alive, base::TimeTicks timebase, base::TimeDelta interval) { AcceleratedSurfaceBuffersSwappedCompletedForGPU(host_id, route_id, alive, surface_handle); AcceleratedSurfaceBuffersSwappedCompletedForRenderer(surface_id, timebase, interval); }
171,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: setup_server_realm(krb5_principal sprinc) { krb5_error_code kret; kdc_realm_t *newrealm; kret = 0; if (kdc_numrealms > 1) { if (!(newrealm = find_realm_data(sprinc->realm.data, (krb5_ui_4) sprinc->realm.length))) kret = ENOENT; else kdc_active_realm = newrealm; } else kdc_active_realm = kdc_realmlist[0]; return(kret); } Commit Message: Multi-realm KDC null deref [CVE-2013-1418] If a KDC serves multiple realms, certain requests can cause setup_server_realm() to dereference a null pointer, crashing the KDC. CVSSv2: AV:N/AC:M/Au:N/C:N/I:N/A:P/E:POC/RL:OF/RC:C A related but more minor vulnerability requires authentication to exploit, and is only present if a third-party KDC database module can dereference a null pointer under certain conditions. (back ported from commit 5d2d9a1abe46a2c1a8614d4672d08d9d30a5f8bf) ticket: 7757 (new) version_fixed: 1.10.7 status: resolved CWE ID:
setup_server_realm(krb5_principal sprinc) { krb5_error_code kret; kdc_realm_t *newrealm; kret = 0; if (sprinc == NULL) return NULL; if (kdc_numrealms > 1) { if (!(newrealm = find_realm_data(sprinc->realm.data, (krb5_ui_4) sprinc->realm.length))) kret = ENOENT; else kdc_active_realm = newrealm; } else kdc_active_realm = kdc_realmlist[0]; return(kret); }
165,933
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: Chapters::Edition::Edition() { } 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
Chapters::Edition::Edition() const int size = (m_atoms_size == 0) ? 1 : 2 * m_atoms_size; Atom* const atoms = new (std::nothrow) Atom[size]; if (atoms == NULL) return false; for (int idx = 0; idx < m_atoms_count; ++idx) { m_atoms[idx].ShallowCopy(atoms[idx]); } delete[] m_atoms; m_atoms = atoms; m_atoms_size = size; return true; }
174,273
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void RenderWidgetHostViewAura::CreateDelegatedFrameHostClient() { if (IsMus()) return; cc::FrameSinkId frame_sink_id = host_->AllocateFrameSinkId(is_guest_view_hack_); if (!delegated_frame_host_client_) { delegated_frame_host_client_ = base::MakeUnique<DelegatedFrameHostClientAura>(this); } delegated_frame_host_ = base::MakeUnique<DelegatedFrameHost>( frame_sink_id, delegated_frame_host_client_.get()); if (renderer_compositor_frame_sink_) { delegated_frame_host_->DidCreateNewRendererCompositorFrameSink( renderer_compositor_frame_sink_); } UpdateNeedsBeginFramesInternal(); if (host_->delegate() && host_->delegate()->GetInputEventRouter()) { host_->delegate()->GetInputEventRouter()->AddFrameSinkIdOwner( GetFrameSinkId(), this); } } Commit Message: Allocate a FrameSinkId for RenderWidgetHostViewAura in mus+ash RenderWidgetHostViewChildFrame expects its parent to have a valid FrameSinkId. Make sure RenderWidgetHostViewAura has a FrameSinkId even if DelegatedFrameHost is not used (in mus+ash). BUG=706553 TBR=jam@chromium.org Review-Url: https://codereview.chromium.org/2847253003 Cr-Commit-Position: refs/heads/master@{#468179} CWE ID: CWE-254
void RenderWidgetHostViewAura::CreateDelegatedFrameHostClient() { if (IsMus()) return; if (!delegated_frame_host_client_) { delegated_frame_host_client_ = base::MakeUnique<DelegatedFrameHostClientAura>(this); } delegated_frame_host_ = base::MakeUnique<DelegatedFrameHost>( frame_sink_id_, delegated_frame_host_client_.get()); if (renderer_compositor_frame_sink_) { delegated_frame_host_->DidCreateNewRendererCompositorFrameSink( renderer_compositor_frame_sink_); } UpdateNeedsBeginFramesInternal(); if (host_->delegate() && host_->delegate()->GetInputEventRouter()) { host_->delegate()->GetInputEventRouter()->AddFrameSinkIdOwner( GetFrameSinkId(), this); } }
172,233
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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 SimpleSoftOMXComponent::internalGetParameter( OMX_INDEXTYPE index, OMX_PTR params) { switch (index) { case OMX_IndexParamPortDefinition: { OMX_PARAM_PORTDEFINITIONTYPE *defParams = (OMX_PARAM_PORTDEFINITIONTYPE *)params; if (defParams->nPortIndex >= mPorts.size() || defParams->nSize != sizeof(OMX_PARAM_PORTDEFINITIONTYPE)) { return OMX_ErrorUndefined; } const PortInfo *port = &mPorts.itemAt(defParams->nPortIndex); memcpy(defParams, &port->mDef, sizeof(port->mDef)); return OMX_ErrorNone; } default: return OMX_ErrorUnsupportedIndex; } } Commit Message: DO NOT MERGE Verify OMX buffer sizes prior to access Bug: 27207275 Change-Id: I4412825d1ee233d993af0a67708bea54304ff62d CWE ID: CWE-119
OMX_ERRORTYPE SimpleSoftOMXComponent::internalGetParameter( OMX_INDEXTYPE index, OMX_PTR params) { switch (index) { case OMX_IndexParamPortDefinition: { OMX_PARAM_PORTDEFINITIONTYPE *defParams = (OMX_PARAM_PORTDEFINITIONTYPE *)params; if (!isValidOMXParam(defParams)) { return OMX_ErrorBadParameter; } if (defParams->nPortIndex >= mPorts.size() || defParams->nSize != sizeof(OMX_PARAM_PORTDEFINITIONTYPE)) { return OMX_ErrorUndefined; } const PortInfo *port = &mPorts.itemAt(defParams->nPortIndex); memcpy(defParams, &port->mDef, sizeof(port->mDef)); return OMX_ErrorNone; } default: return OMX_ErrorUnsupportedIndex; } }
174,222
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: LocalSiteCharacteristicsWebContentsObserverTest() { scoped_feature_list_.InitAndEnableFeature( features::kSiteCharacteristicsDatabase); } Commit Message: Connect the LocalDB to TabManager. Bug: 773382 Change-Id: Iec8fe5226ee175105d51f300f30b4865478ac099 Reviewed-on: https://chromium-review.googlesource.com/1118611 Commit-Queue: Sébastien Marchand <sebmarchand@chromium.org> Reviewed-by: François Doray <fdoray@chromium.org> Cr-Commit-Position: refs/heads/master@{#572871} CWE ID:
LocalSiteCharacteristicsWebContentsObserverTest() {
172,217
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: ParseNameValue(const char * buffer, int bufsize, struct NameValueParserData * data) { struct xmlparser parser; data->l_head = NULL; data->portListing = NULL; data->portListingLength = 0; /* init xmlparser object */ parser.xmlstart = buffer; parser.xmlsize = bufsize; parser.data = data; parser.starteltfunc = NameValueParserStartElt; parser.endeltfunc = NameValueParserEndElt; parser.datafunc = NameValueParserGetData; parser.attfunc = 0; parsexml(&parser); } Commit Message: properly initialize data structure for SOAP parsing in ParseNameValue() topelt field was not properly initialized. should fix #268 CWE ID: CWE-119
ParseNameValue(const char * buffer, int bufsize, struct NameValueParserData * data) { struct xmlparser parser; memset(data, 0, sizeof(struct NameValueParserData)); /* init xmlparser object */ parser.xmlstart = buffer; parser.xmlsize = bufsize; parser.data = data; parser.starteltfunc = NameValueParserStartElt; parser.endeltfunc = NameValueParserEndElt; parser.datafunc = NameValueParserGetData; parser.attfunc = 0; parsexml(&parser); }
169,368
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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 CrosLibrary::TestApi::SetKeyboardLibrary( KeyboardLibrary* library, bool own) { library_->keyboard_lib_.SetImpl(library, own); } 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
void CrosLibrary::TestApi::SetKeyboardLibrary(
170,639
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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 SampleTable::isValid() const { return mChunkOffsetOffset >= 0 && mSampleToChunkOffset >= 0 && mSampleSizeOffset >= 0 && mTimeToSample != NULL; } Commit Message: Resolve merge conflict when cp'ing ag/931301 to mnc-mr1-release Change-Id: I079d1db2d30d126f8aed348bd62451acf741037d CWE ID: CWE-20
bool SampleTable::isValid() const { return mChunkOffsetOffset >= 0 && mSampleToChunkOffset >= 0 && mSampleSizeOffset >= 0 && !mTimeToSample.empty(); }
174,172
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: image_transform_png_set_gray_to_rgb_mod(PNG_CONST image_transform *this, image_pixel *that, png_const_structp pp, PNG_CONST transform_display *display) { /* NOTE: we can actually pend the tRNS processing at this point because we * can correctly recognize the original pixel value even though we have * mapped the one gray channel to the three RGB ones, but in fact libpng * doesn't do this, so we don't either. */ if ((that->colour_type & PNG_COLOR_MASK_COLOR) == 0 && that->have_tRNS) image_pixel_add_alpha(that, &display->this); /* Simply expand the bit depth and alter the colour type as required. */ if (that->colour_type == PNG_COLOR_TYPE_GRAY) { /* RGB images have a bit depth at least equal to '8' */ if (that->bit_depth < 8) that->sample_depth = that->bit_depth = 8; /* And just changing the colour type works here because the green and blue * channels are being maintained in lock-step with the red/gray: */ that->colour_type = PNG_COLOR_TYPE_RGB; } else if (that->colour_type == PNG_COLOR_TYPE_GRAY_ALPHA) that->colour_type = PNG_COLOR_TYPE_RGB_ALPHA; this->next->mod(this->next, that, pp, display); } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
image_transform_png_set_gray_to_rgb_mod(PNG_CONST image_transform *this, image_transform_png_set_gray_to_rgb_mod(const image_transform *this, image_pixel *that, png_const_structp pp, const transform_display *display) { /* NOTE: we can actually pend the tRNS processing at this point because we * can correctly recognize the original pixel value even though we have * mapped the one gray channel to the three RGB ones, but in fact libpng * doesn't do this, so we don't either. */ if ((that->colour_type & PNG_COLOR_MASK_COLOR) == 0 && that->have_tRNS) image_pixel_add_alpha(that, &display->this, 0/*!for background*/); /* Simply expand the bit depth and alter the colour type as required. */ if (that->colour_type == PNG_COLOR_TYPE_GRAY) { /* RGB images have a bit depth at least equal to '8' */ if (that->bit_depth < 8) that->sample_depth = that->bit_depth = 8; /* And just changing the colour type works here because the green and blue * channels are being maintained in lock-step with the red/gray: */ that->colour_type = PNG_COLOR_TYPE_RGB; } else if (that->colour_type == PNG_COLOR_TYPE_GRAY_ALPHA) that->colour_type = PNG_COLOR_TYPE_RGB_ALPHA; this->next->mod(this->next, that, pp, display); }
173,636
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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 ipv4_pktinfo_prepare(const struct sock *sk, struct sk_buff *skb) { struct in_pktinfo *pktinfo = PKTINFO_SKB_CB(skb); bool prepare = (inet_sk(sk)->cmsg_flags & IP_CMSG_PKTINFO) || ipv6_sk_rxinfo(sk); if (prepare && skb_rtable(skb)) { /* skb->cb is overloaded: prior to this point it is IP{6}CB * which has interface index (iif) as the first member of the * underlying inet{6}_skb_parm struct. This code then overlays * PKTINFO_SKB_CB and in_pktinfo also has iif as the first * element so the iif is picked up from the prior IPCB. If iif * is the loopback interface, then return the sending interface * (e.g., process binds socket to eth0 for Tx which is * redirected to loopback in the rtable/dst). */ if (pktinfo->ipi_ifindex == LOOPBACK_IFINDEX) pktinfo->ipi_ifindex = inet_iif(skb); pktinfo->ipi_spec_dst.s_addr = fib_compute_spec_dst(skb); } else { pktinfo->ipi_ifindex = 0; pktinfo->ipi_spec_dst.s_addr = 0; } skb_dst_drop(skb); } Commit Message: ipv4: keep skb->dst around in presence of IP options Andrey Konovalov got crashes in __ip_options_echo() when a NULL skb->dst is accessed. ipv4_pktinfo_prepare() should not drop the dst if (evil) IP options are present. We could refine the test to the presence of ts_needtime or srr, but IP options are not often used, so let's be conservative. Thanks to syzkaller team for finding this bug. Fixes: d826eb14ecef ("ipv4: PKTINFO doesnt need dst reference") Signed-off-by: Eric Dumazet <edumazet@google.com> Reported-by: Andrey Konovalov <andreyknvl@google.com> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID: CWE-476
void ipv4_pktinfo_prepare(const struct sock *sk, struct sk_buff *skb) { struct in_pktinfo *pktinfo = PKTINFO_SKB_CB(skb); bool prepare = (inet_sk(sk)->cmsg_flags & IP_CMSG_PKTINFO) || ipv6_sk_rxinfo(sk); if (prepare && skb_rtable(skb)) { /* skb->cb is overloaded: prior to this point it is IP{6}CB * which has interface index (iif) as the first member of the * underlying inet{6}_skb_parm struct. This code then overlays * PKTINFO_SKB_CB and in_pktinfo also has iif as the first * element so the iif is picked up from the prior IPCB. If iif * is the loopback interface, then return the sending interface * (e.g., process binds socket to eth0 for Tx which is * redirected to loopback in the rtable/dst). */ if (pktinfo->ipi_ifindex == LOOPBACK_IFINDEX) pktinfo->ipi_ifindex = inet_iif(skb); pktinfo->ipi_spec_dst.s_addr = fib_compute_spec_dst(skb); } else { pktinfo->ipi_ifindex = 0; pktinfo->ipi_spec_dst.s_addr = 0; } /* We need to keep the dst for __ip_options_echo() * We could restrict the test to opt.ts_needtime || opt.srr, * but the following is good enough as IP options are not often used. */ if (unlikely(IPCB(skb)->opt.optlen)) skb_dst_force(skb); else skb_dst_drop(skb); }
168,370
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: asmlinkage long sys_oabi_semtimedop(int semid, struct oabi_sembuf __user *tsops, unsigned nsops, const struct timespec __user *timeout) { struct sembuf *sops; struct timespec local_timeout; long err; int i; if (nsops < 1) return -EINVAL; sops = kmalloc(sizeof(*sops) * nsops, GFP_KERNEL); if (!sops) return -ENOMEM; err = 0; for (i = 0; i < nsops; i++) { __get_user_error(sops[i].sem_num, &tsops->sem_num, err); __get_user_error(sops[i].sem_op, &tsops->sem_op, err); __get_user_error(sops[i].sem_flg, &tsops->sem_flg, err); tsops++; } if (timeout) { /* copy this as well before changing domain protection */ err |= copy_from_user(&local_timeout, timeout, sizeof(*timeout)); timeout = &local_timeout; } if (err) { err = -EFAULT; } else { mm_segment_t fs = get_fs(); set_fs(KERNEL_DS); err = sys_semtimedop(semid, sops, nsops, timeout); set_fs(fs); } kfree(sops); return err; } Commit Message: ARM: 6891/1: prevent heap corruption in OABI semtimedop When CONFIG_OABI_COMPAT is set, the wrapper for semtimedop does not bound the nsops argument. A sufficiently large value will cause an integer overflow in allocation size, followed by copying too much data into the allocated buffer. Fix this by restricting nsops to SEMOPM. Untested. Cc: stable@kernel.org Signed-off-by: Dan Rosenberg <drosenberg@vsecurity.com> Signed-off-by: Russell King <rmk+kernel@arm.linux.org.uk> CWE ID: CWE-189
asmlinkage long sys_oabi_semtimedop(int semid, struct oabi_sembuf __user *tsops, unsigned nsops, const struct timespec __user *timeout) { struct sembuf *sops; struct timespec local_timeout; long err; int i; if (nsops < 1 || nsops > SEMOPM) return -EINVAL; sops = kmalloc(sizeof(*sops) * nsops, GFP_KERNEL); if (!sops) return -ENOMEM; err = 0; for (i = 0; i < nsops; i++) { __get_user_error(sops[i].sem_num, &tsops->sem_num, err); __get_user_error(sops[i].sem_op, &tsops->sem_op, err); __get_user_error(sops[i].sem_flg, &tsops->sem_flg, err); tsops++; } if (timeout) { /* copy this as well before changing domain protection */ err |= copy_from_user(&local_timeout, timeout, sizeof(*timeout)); timeout = &local_timeout; } if (err) { err = -EFAULT; } else { mm_segment_t fs = get_fs(); set_fs(KERNEL_DS); err = sys_semtimedop(semid, sops, nsops, timeout); set_fs(fs); } kfree(sops); return err; }
165,885
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: Chapters::Chapters( Segment* pSegment, long long payload_start, long long payload_size, long long element_start, long long element_size) : m_pSegment(pSegment), m_start(payload_start), m_size(payload_size), m_element_start(element_start), m_element_size(element_size), m_editions(NULL), m_editions_size(0), m_editions_count(0) { } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
Chapters::Chapters(
174,243
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: tbGetBuffer(unsigned size) { char *rtrn; if (size >= BUFFER_SIZE) return NULL; if ((BUFFER_SIZE - tbNext) <= size) tbNext = 0; rtrn = &textBuffer[tbNext]; tbNext += size; return rtrn; } Commit Message: CWE ID: CWE-119
tbGetBuffer(unsigned size) { struct textBuffer *tb; tb = &textBuffer[textBufferIndex]; textBufferIndex = (textBufferIndex + 1) % NUM_BUFFER; if (size > tb->size) { free(tb->buffer); tb->buffer = xnfalloc(size); tb->size = size; } return tb->buffer; }
164,692
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: int wvlan_set_station_nickname(struct net_device *dev, struct iw_request_info *info, union iwreq_data *wrqu, char *extra) { struct wl_private *lp = wl_priv(dev); unsigned long flags; int ret = 0; /*------------------------------------------------------------------------*/ DBG_FUNC("wvlan_set_station_nickname"); DBG_ENTER(DbgInfo); wl_lock(lp, &flags); memset(lp->StationName, 0, sizeof(lp->StationName)); memcpy(lp->StationName, extra, wrqu->data.length); /* Commit the adapter parameters */ wl_apply(lp); wl_unlock(lp, &flags); DBG_LEAVE(DbgInfo); return ret; } /* wvlan_set_station_nickname */ Commit Message: staging: wlags49_h2: buffer overflow setting station name We need to check the length parameter before doing the memcpy(). I've actually changed it to strlcpy() as well so that it's NUL terminated. You need CAP_NET_ADMIN to trigger these so it's not the end of the world. Reported-by: Nico Golde <nico@ngolde.de> Reported-by: Fabian Yamaguchi <fabs@goesec.de> Signed-off-by: Dan Carpenter <dan.carpenter@oracle.com> Cc: stable@kernel.org Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org> CWE ID: CWE-119
int wvlan_set_station_nickname(struct net_device *dev, struct iw_request_info *info, union iwreq_data *wrqu, char *extra) { struct wl_private *lp = wl_priv(dev); unsigned long flags; size_t len; int ret = 0; /*------------------------------------------------------------------------*/ DBG_FUNC("wvlan_set_station_nickname"); DBG_ENTER(DbgInfo); wl_lock(lp, &flags); memset(lp->StationName, 0, sizeof(lp->StationName)); len = min_t(size_t, wrqu->data.length, sizeof(lp->StationName)); strlcpy(lp->StationName, extra, len); /* Commit the adapter parameters */ wl_apply(lp); wl_unlock(lp, &flags); DBG_LEAVE(DbgInfo); return ret; } /* wvlan_set_station_nickname */
165,963
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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 remove_bond(const bt_bdaddr_t *bd_addr) { /* sanity check */ if (interface_ready() == FALSE) return BT_STATUS_NOT_READY; return btif_dm_remove_bond(bd_addr); } Commit Message: Add guest mode functionality (2/3) Add a flag to enable() to start Bluetooth in restricted mode. In restricted mode, all devices that are paired during restricted mode are deleted upon leaving restricted mode. Right now restricted mode is only entered while a guest user is active. Bug: 27410683 Change-Id: I8f23d28ef0aa3a8df13d469c73005c8e1b894d19 CWE ID: CWE-20
static int remove_bond(const bt_bdaddr_t *bd_addr) { if (is_restricted_mode() && !btif_storage_is_restricted_device(bd_addr)) return BT_STATUS_SUCCESS; /* sanity check */ if (interface_ready() == FALSE) return BT_STATUS_NOT_READY; return btif_dm_remove_bond(bd_addr); }
173,552
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: process_open(u_int32_t id) { u_int32_t pflags; Attrib a; char *name; int r, handle, fd, flags, mode, status = SSH2_FX_FAILURE; if ((r = sshbuf_get_cstring(iqueue, &name, NULL)) != 0 || (r = sshbuf_get_u32(iqueue, &pflags)) != 0 || /* portable flags */ (r = decode_attrib(iqueue, &a)) != 0) fatal("%s: buffer error: %s", __func__, ssh_err(r)); debug3("request %u: open flags %d", id, pflags); flags = flags_from_portable(pflags); mode = (a.flags & SSH2_FILEXFER_ATTR_PERMISSIONS) ? a.perm : 0666; logit("open \"%s\" flags %s mode 0%o", name, string_from_portable(pflags), mode); if (readonly && ((flags & O_ACCMODE) == O_WRONLY || (flags & O_ACCMODE) == O_RDWR)) { verbose("Refusing open request in read-only mode"); status = SSH2_FX_PERMISSION_DENIED; } else { fd = open(name, flags, mode); if (fd < 0) { status = errno_to_portable(errno); } else { handle = handle_new(HANDLE_FILE, name, fd, flags, NULL); if (handle < 0) { close(fd); } else { send_handle(id, handle); status = SSH2_FX_OK; } } } if (status != SSH2_FX_OK) send_status(id, status); free(name); } Commit Message: disallow creation (of empty files) in read-only mode; reported by Michal Zalewski, feedback & ok deraadt@ CWE ID: CWE-269
process_open(u_int32_t id) { u_int32_t pflags; Attrib a; char *name; int r, handle, fd, flags, mode, status = SSH2_FX_FAILURE; if ((r = sshbuf_get_cstring(iqueue, &name, NULL)) != 0 || (r = sshbuf_get_u32(iqueue, &pflags)) != 0 || /* portable flags */ (r = decode_attrib(iqueue, &a)) != 0) fatal("%s: buffer error: %s", __func__, ssh_err(r)); debug3("request %u: open flags %d", id, pflags); flags = flags_from_portable(pflags); mode = (a.flags & SSH2_FILEXFER_ATTR_PERMISSIONS) ? a.perm : 0666; logit("open \"%s\" flags %s mode 0%o", name, string_from_portable(pflags), mode); if (readonly && ((flags & O_ACCMODE) != O_RDONLY || (flags & (O_CREAT|O_TRUNC)) != 0)) { verbose("Refusing open request in read-only mode"); status = SSH2_FX_PERMISSION_DENIED; } else { fd = open(name, flags, mode); if (fd < 0) { status = errno_to_portable(errno); } else { handle = handle_new(HANDLE_FILE, name, fd, flags, NULL); if (handle < 0) { close(fd); } else { send_handle(id, handle); status = SSH2_FX_OK; } } } if (status != SSH2_FX_OK) send_status(id, status); free(name); }
167,715
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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 do_session_handshake (lua_State *L, int status, lua_KContext ctx) { int rc; struct ssh_userdata *sshu = NULL; assert(lua_gettop(L) == 4); sshu = (struct ssh_userdata *) nseU_checkudata(L, 3, SSH2_UDATA, "ssh2"); while ((rc = libssh2_session_handshake(sshu->session, sshu->sp[0])) == LIBSSH2_ERROR_EAGAIN) { luaL_getmetafield(L, 3, "filter"); lua_pushvalue(L, 3); assert(lua_status(L) == LUA_OK); lua_callk(L, 1, 0, 0, do_session_handshake); } if (rc) { libssh2_session_free(sshu->session); return luaL_error(L, "Unable to complete libssh2 handshake."); } lua_settop(L, 3); return 1; } Commit Message: Avoid a crash (double-free) when SSH connection fails CWE ID: CWE-415
static int do_session_handshake (lua_State *L, int status, lua_KContext ctx) { int rc; struct ssh_userdata *sshu = NULL; assert(lua_gettop(L) == 4); sshu = (struct ssh_userdata *) nseU_checkudata(L, 3, SSH2_UDATA, "ssh2"); while ((rc = libssh2_session_handshake(sshu->session, sshu->sp[0])) == LIBSSH2_ERROR_EAGAIN) { luaL_getmetafield(L, 3, "filter"); lua_pushvalue(L, 3); assert(lua_status(L) == LUA_OK); lua_callk(L, 1, 0, 0, do_session_handshake); } if (rc) { libssh2_session_free(sshu->session); sshu->session = NULL; return luaL_error(L, "Unable to complete libssh2 handshake."); } lua_settop(L, 3); return 1; }
169,856
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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 MagickPixelPacket **AcquirePixelThreadSet(const Image *image) { MagickPixelPacket **pixels; register ssize_t i, j; size_t number_threads; number_threads=(size_t) GetMagickResourceLimit(ThreadResource); pixels=(MagickPixelPacket **) AcquireQuantumMemory(number_threads, sizeof(*pixels)); if (pixels == (MagickPixelPacket **) NULL) return((MagickPixelPacket **) NULL); (void) memset(pixels,0,number_threads*sizeof(*pixels)); for (i=0; i < (ssize_t) number_threads; i++) { pixels[i]=(MagickPixelPacket *) AcquireQuantumMemory(image->columns, sizeof(**pixels)); if (pixels[i] == (MagickPixelPacket *) NULL) return(DestroyPixelThreadSet(pixels)); for (j=0; j < (ssize_t) image->columns; j++) GetMagickPixelPacket(image,&pixels[i][j]); } return(pixels); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1586 CWE ID: CWE-119
static MagickPixelPacket **AcquirePixelThreadSet(const Image *image) static MagickPixelPacket **AcquirePixelThreadSet(const Image *images) { const Image *next; MagickPixelPacket **pixels; register ssize_t i, j; size_t columns, number_threads; number_threads=(size_t) GetMagickResourceLimit(ThreadResource); pixels=(MagickPixelPacket **) AcquireQuantumMemory(number_threads, sizeof(*pixels)); if (pixels == (MagickPixelPacket **) NULL) return((MagickPixelPacket **) NULL); (void) memset(pixels,0,number_threads*sizeof(*pixels)); columns=images->columns; for (next=images; next != (Image *) NULL; next=next->next) columns=MagickMax(next->columns,columns); for (i=0; i < (ssize_t) number_threads; i++) { pixels[i]=(MagickPixelPacket *) AcquireQuantumMemory(columns, sizeof(**pixels)); if (pixels[i] == (MagickPixelPacket *) NULL) return(DestroyPixelThreadSet(pixels)); for (j=0; j < (ssize_t) columns; j++) GetMagickPixelPacket(images,&pixels[i][j]); } return(pixels); }
169,601
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void BluetoothOptionsHandler::RequestPasskey( chromeos::BluetoothDevice* device) { } Commit Message: Implement methods for pairing of bluetooth devices. BUG=chromium:100392,chromium:102139 TEST= Review URL: http://codereview.chromium.org/8495018 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@109094 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
void BluetoothOptionsHandler::RequestPasskey( chromeos::BluetoothDevice* device) { DictionaryValue params; params.SetString("pairing", "bluetoothEnterPasskey"); SendDeviceNotification(device, &params); }
170,972
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: status_t CameraDeviceClient::dump(int fd, const Vector<String16>& args) { String8 result; result.appendFormat("CameraDeviceClient[%d] (%p) PID: %d, dump:\n", mCameraId, getRemoteCallback()->asBinder().get(), mClientPid); result.append(" State: "); mFrameProcessor->dump(fd, args); return dumpDevice(fd, args); } Commit Message: Camera: Disallow dumping clients directly Camera service dumps should only be initiated through ICameraService::dump. Bug: 26265403 Change-Id: If3ca4718ed74bf33ad8a416192689203029e2803 CWE ID: CWE-264
status_t CameraDeviceClient::dump(int fd, const Vector<String16>& args) { return BasicClient::dump(fd, args); } status_t CameraDeviceClient::dumpClient(int fd, const Vector<String16>& args) { String8 result; result.appendFormat("CameraDeviceClient[%d] (%p) PID: %d, dump:\n", mCameraId, getRemoteCallback()->asBinder().get(), mClientPid); result.append(" State: "); mFrameProcessor->dump(fd, args); return dumpDevice(fd, args); }
173,939
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void PepperRendererConnection::OnMsgDidDeleteInProcessInstance( PP_Instance instance) { in_process_host_->DeleteInstance(instance); } Commit Message: Validate in-process plugin instance messages. Bug: 733548, 733549 Cq-Include-Trybots: master.tryserver.chromium.linux:linux_site_isolation Change-Id: Ie5572c7bcafa05399b09c44425ddd5ce9b9e4cba Reviewed-on: https://chromium-review.googlesource.com/538908 Commit-Queue: Bill Budge <bbudge@chromium.org> Reviewed-by: Raymes Khoury <raymes@chromium.org> Cr-Commit-Position: refs/heads/master@{#480696} CWE ID: CWE-20
void PepperRendererConnection::OnMsgDidDeleteInProcessInstance( PP_Instance instance) { // 'instance' is possibly invalid. The host must be careful not to trust it. in_process_host_->DeleteInstance(instance); }
172,312
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: ExprResolveLhs(struct xkb_context *ctx, const ExprDef *expr, const char **elem_rtrn, const char **field_rtrn, ExprDef **index_rtrn) { switch (expr->expr.op) { case EXPR_IDENT: *elem_rtrn = NULL; *field_rtrn = xkb_atom_text(ctx, expr->ident.ident); *index_rtrn = NULL; return true; case EXPR_FIELD_REF: *elem_rtrn = xkb_atom_text(ctx, expr->field_ref.element); *field_rtrn = xkb_atom_text(ctx, expr->field_ref.field); *index_rtrn = NULL; return true; case EXPR_ARRAY_REF: *elem_rtrn = xkb_atom_text(ctx, expr->array_ref.element); *field_rtrn = xkb_atom_text(ctx, expr->array_ref.field); *index_rtrn = expr->array_ref.entry; return true; default: break; } log_wsgo(ctx, "Unexpected operator %d in ResolveLhs\n", expr->expr.op); return false; } Commit Message: xkbcomp: Don't falsely promise from ExprResolveLhs Every user of ExprReturnLhs goes on to unconditionally dereference the field return, which can be NULL if xkb_intern_atom fails. Return false if this is the case, so we fail safely. testcase: splice geometry data into interp Signed-off-by: Daniel Stone <daniels@collabora.com> CWE ID: CWE-476
ExprResolveLhs(struct xkb_context *ctx, const ExprDef *expr, const char **elem_rtrn, const char **field_rtrn, ExprDef **index_rtrn) { switch (expr->expr.op) { case EXPR_IDENT: *elem_rtrn = NULL; *field_rtrn = xkb_atom_text(ctx, expr->ident.ident); *index_rtrn = NULL; return (*field_rtrn != NULL); case EXPR_FIELD_REF: *elem_rtrn = xkb_atom_text(ctx, expr->field_ref.element); *field_rtrn = xkb_atom_text(ctx, expr->field_ref.field); *index_rtrn = NULL; return true; case EXPR_ARRAY_REF: *elem_rtrn = xkb_atom_text(ctx, expr->array_ref.element); *field_rtrn = xkb_atom_text(ctx, expr->array_ref.field); *index_rtrn = expr->array_ref.entry; return true; default: break; } log_wsgo(ctx, "Unexpected operator %d in ResolveLhs\n", expr->expr.op); return false; }
169,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: ut64 MACH0_(get_baddr)(struct MACH0_(obj_t)* bin) { int i; if (bin->hdr.filetype != MH_EXECUTE && bin->hdr.filetype != MH_DYLINKER) return 0; for (i = 0; i < bin->nsegs; ++i) if (bin->segs[i].fileoff == 0 && bin->segs[i].filesize != 0) return bin->segs[i].vmaddr; return 0; } Commit Message: Fix null deref and uaf in mach0 parser CWE ID: CWE-416
ut64 MACH0_(get_baddr)(struct MACH0_(obj_t)* bin) { int i; if (bin->hdr.filetype != MH_EXECUTE && bin->hdr.filetype != MH_DYLINKER) { return 0; } for (i = 0; i < bin->nsegs; ++i) { if (bin->segs[i].fileoff == 0 && bin->segs[i].filesize != 0) { return bin->segs[i].vmaddr; } } return 0; }
168,232
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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 read_sequence_header(decoder_info_t *decoder_info, stream_t *stream) { decoder_info->width = get_flc(16, stream); decoder_info->height = get_flc(16, stream); decoder_info->log2_sb_size = get_flc(3, stream); decoder_info->pb_split = get_flc(1, stream); decoder_info->tb_split_enable = get_flc(1, stream); decoder_info->max_num_ref = get_flc(2, stream) + 1; decoder_info->interp_ref = get_flc(2, stream); decoder_info->max_delta_qp = get_flc(1, stream); decoder_info->deblocking = get_flc(1, stream); decoder_info->clpf = get_flc(1, stream); decoder_info->use_block_contexts = get_flc(1, stream); decoder_info->bipred = get_flc(2, stream); decoder_info->qmtx = get_flc(1, stream); if (decoder_info->qmtx) { decoder_info->qmtx_offset = get_flc(6, stream) - 32; } decoder_info->subsample = get_flc(2, stream); decoder_info->subsample = // 0: 400 1: 420 2: 422 3: 444 (decoder_info->subsample & 1) * 20 + (decoder_info->subsample & 2) * 22 + ((decoder_info->subsample & 3) == 3) * 2 + 400; decoder_info->num_reorder_pics = get_flc(4, stream); if (decoder_info->subsample != 400) { decoder_info->cfl_intra = get_flc(1, stream); decoder_info->cfl_inter = get_flc(1, stream); } decoder_info->bitdepth = get_flc(1, stream) ? 10 : 8; if (decoder_info->bitdepth == 10) decoder_info->bitdepth += 2 * get_flc(1, stream); decoder_info->input_bitdepth = get_flc(1, stream) ? 10 : 8; if (decoder_info->input_bitdepth == 10) decoder_info->input_bitdepth += 2 * get_flc(1, stream); } Commit Message: Fix possible stack overflows in decoder for illegal bit streams Fixes CVE-2018-0429 A vulnerability in the Thor decoder (available at: https://github.com/cisco/thor) could allow an authenticated, local attacker to cause segmentation faults and stack overflows when using a non-conformant Thor bitstream as input. The vulnerability is due to lack of input validation when parsing the bitstream. A successful exploit could allow the attacker to cause a stack overflow and potentially inject and execute arbitrary code. CWE ID: CWE-119
void read_sequence_header(decoder_info_t *decoder_info, stream_t *stream) { decoder_info->width = get_flc(16, stream); decoder_info->height = get_flc(16, stream); decoder_info->log2_sb_size = get_flc(3, stream); decoder_info->log2_sb_size = clip(decoder_info->log2_sb_size, log2i(MIN_BLOCK_SIZE), log2i(MAX_SB_SIZE)); decoder_info->pb_split = get_flc(1, stream); decoder_info->tb_split_enable = get_flc(1, stream); decoder_info->max_num_ref = get_flc(2, stream) + 1; decoder_info->interp_ref = get_flc(2, stream); decoder_info->max_delta_qp = get_flc(1, stream); decoder_info->deblocking = get_flc(1, stream); decoder_info->clpf = get_flc(1, stream); decoder_info->use_block_contexts = get_flc(1, stream); decoder_info->bipred = get_flc(2, stream); decoder_info->qmtx = get_flc(1, stream); if (decoder_info->qmtx) { decoder_info->qmtx_offset = get_flc(6, stream) - 32; } decoder_info->subsample = get_flc(2, stream); decoder_info->subsample = // 0: 400 1: 420 2: 422 3: 444 (decoder_info->subsample & 1) * 20 + (decoder_info->subsample & 2) * 22 + ((decoder_info->subsample & 3) == 3) * 2 + 400; decoder_info->num_reorder_pics = get_flc(4, stream); if (decoder_info->subsample != 400) { decoder_info->cfl_intra = get_flc(1, stream); decoder_info->cfl_inter = get_flc(1, stream); } decoder_info->bitdepth = get_flc(1, stream) ? 10 : 8; if (decoder_info->bitdepth == 10) decoder_info->bitdepth += 2 * get_flc(1, stream); decoder_info->input_bitdepth = get_flc(1, stream) ? 10 : 8; if (decoder_info->input_bitdepth == 10) decoder_info->input_bitdepth += 2 * get_flc(1, stream); }
169,367
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: CStarter::removeDeferredJobs() { bool ret = true; if ( this->deferral_tid == -1 ) { return ( ret ); } m_deferred_job_update = true; if ( daemonCore->Cancel_Timer( this->deferral_tid ) >= 0 ) { dprintf( D_FULLDEBUG, "Cancelled time deferred execution for " "Job %d.%d\n", this->jic->jobCluster(), this->jic->jobProc() ); this->deferral_tid = -1; } else { MyString error = "Failed to cancel deferred execution timer for Job "; error += this->jic->jobCluster(); error += "."; error += this->jic->jobProc(); EXCEPT( error.Value() ); ret = false; } return ( ret ); } Commit Message: CWE ID: CWE-134
CStarter::removeDeferredJobs() { bool ret = true; if ( this->deferral_tid == -1 ) { return ( ret ); } m_deferred_job_update = true; if ( daemonCore->Cancel_Timer( this->deferral_tid ) >= 0 ) { dprintf( D_FULLDEBUG, "Cancelled time deferred execution for " "Job %d.%d\n", this->jic->jobCluster(), this->jic->jobProc() ); this->deferral_tid = -1; } else { MyString error = "Failed to cancel deferred execution timer for Job "; error += this->jic->jobCluster(); error += "."; error += this->jic->jobProc(); EXCEPT( "%s", error.Value() ); ret = false; } return ( ret ); }
165,379
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: TestFlashMessageLoop::TestFlashMessageLoop(TestingInstance* instance) : TestCase(instance), message_loop_(NULL), callback_factory_(this) { } Commit Message: Fix PPB_Flash_MessageLoop. This CL suspends script callbacks and resource loads while running nested message loop using PPB_Flash_MessageLoop. BUG=569496 Review URL: https://codereview.chromium.org/1559113002 Cr-Commit-Position: refs/heads/master@{#374529} CWE ID: CWE-264
TestFlashMessageLoop::TestFlashMessageLoop(TestingInstance* instance) : TestCase(instance),
172,127
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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 OPJ_BOOL opj_tcd_code_block_enc_allocate_data(opj_tcd_cblk_enc_t * p_code_block) { OPJ_UINT32 l_data_size; /* The +1 is needed for https://github.com/uclouvain/openjpeg/issues/835 */ l_data_size = 1 + (OPJ_UINT32)((p_code_block->x1 - p_code_block->x0) * (p_code_block->y1 - p_code_block->y0) * (OPJ_INT32)sizeof(OPJ_UINT32)); if (l_data_size > p_code_block->data_size) { if (p_code_block->data) { /* We refer to data - 1 since below we incremented it */ opj_free(p_code_block->data - 1); } p_code_block->data = (OPJ_BYTE*) opj_malloc(l_data_size + 1); if (! p_code_block->data) { p_code_block->data_size = 0U; return OPJ_FALSE; } p_code_block->data_size = l_data_size; /* We reserve the initial byte as a fake byte to a non-FF value */ /* and increment the data pointer, so that opj_mqc_init_enc() */ /* can do bp = data - 1, and opj_mqc_byteout() can safely dereference */ /* it. */ p_code_block->data[0] = 0; p_code_block->data += 1; /*why +1 ?*/ } return OPJ_TRUE; } Commit Message: Encoder: grow buffer size in opj_tcd_code_block_enc_allocate_data() to avoid write heap buffer overflow in opj_mqc_flush (#982) CWE ID: CWE-119
static OPJ_BOOL opj_tcd_code_block_enc_allocate_data(opj_tcd_cblk_enc_t * p_code_block) { OPJ_UINT32 l_data_size; /* +1 is needed for https://github.com/uclouvain/openjpeg/issues/835 */ /* and actually +2 required for https://github.com/uclouvain/openjpeg/issues/982 */ /* TODO: is there a theoretical upper-bound for the compressed code */ /* block size ? */ l_data_size = 2 + (OPJ_UINT32)((p_code_block->x1 - p_code_block->x0) * (p_code_block->y1 - p_code_block->y0) * (OPJ_INT32)sizeof(OPJ_UINT32)); if (l_data_size > p_code_block->data_size) { if (p_code_block->data) { /* We refer to data - 1 since below we incremented it */ opj_free(p_code_block->data - 1); } p_code_block->data = (OPJ_BYTE*) opj_malloc(l_data_size + 1); if (! p_code_block->data) { p_code_block->data_size = 0U; return OPJ_FALSE; } p_code_block->data_size = l_data_size; /* We reserve the initial byte as a fake byte to a non-FF value */ /* and increment the data pointer, so that opj_mqc_init_enc() */ /* can do bp = data - 1, and opj_mqc_byteout() can safely dereference */ /* it. */ p_code_block->data[0] = 0; p_code_block->data += 1; /*why +1 ?*/ } return OPJ_TRUE; }
167,769
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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 xen_netbk_idx_release(struct xen_netbk *netbk, u16 pending_idx) { struct xenvif *vif; struct pending_tx_info *pending_tx_info; pending_ring_idx_t index; /* Already complete? */ if (netbk->mmap_pages[pending_idx] == NULL) return; pending_tx_info = &netbk->pending_tx_info[pending_idx]; vif = pending_tx_info->vif; make_tx_response(vif, &pending_tx_info->req, XEN_NETIF_RSP_OKAY); index = pending_index(netbk->pending_prod++); netbk->pending_ring[index] = pending_idx; xenvif_put(vif); netbk->mmap_pages[pending_idx]->mapping = 0; put_page(netbk->mmap_pages[pending_idx]); netbk->mmap_pages[pending_idx] = NULL; } Commit Message: xen/netback: don't leak pages on failure in xen_netbk_tx_check_gop. Signed-off-by: Matthew Daley <mattjd@gmail.com> Reviewed-by: Konrad Rzeszutek Wilk <konrad.wilk@oracle.com> Acked-by: Ian Campbell <ian.campbell@citrix.com> Acked-by: Jan Beulich <JBeulich@suse.com> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID: CWE-399
static void xen_netbk_idx_release(struct xen_netbk *netbk, u16 pending_idx) static void xen_netbk_idx_release(struct xen_netbk *netbk, u16 pending_idx, u8 status) { struct xenvif *vif; struct pending_tx_info *pending_tx_info; pending_ring_idx_t index; /* Already complete? */ if (netbk->mmap_pages[pending_idx] == NULL) return; pending_tx_info = &netbk->pending_tx_info[pending_idx]; vif = pending_tx_info->vif; make_tx_response(vif, &pending_tx_info->req, status); index = pending_index(netbk->pending_prod++); netbk->pending_ring[index] = pending_idx; xenvif_put(vif); netbk->mmap_pages[pending_idx]->mapping = 0; put_page(netbk->mmap_pages[pending_idx]); netbk->mmap_pages[pending_idx] = NULL; }
166,168
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: int cJSON_GetArraySize( cJSON *array ) { cJSON *c = array->child; int i = 0; while ( c ) { ++i; c = c->next; } return i; } Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a malformed JSON string was passed on the control channel. This issue, present in the cJSON library, was already fixed upstream, so was addressed here in iperf3 by importing a newer version of cJSON (plus local ESnet modifications). Discovered and reported by Dave McDaniel, Cisco Talos. Based on a patch by @dopheide-esnet, with input from @DaveGamble. Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001, CVE-2016-4303 (cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40) Signed-off-by: Bruce A. Mah <bmah@es.net> CWE ID: CWE-119
int cJSON_GetArraySize( cJSON *array )
167,287
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void VarianceTest<VarianceFunctionType>::OneQuarterTest() { memset(src_, 255, block_size_); const int half = block_size_ / 2; memset(ref_, 255, half); memset(ref_ + half, 0, half); unsigned int sse; unsigned int var; REGISTER_STATE_CHECK(var = variance_(src_, width_, ref_, width_, &sse)); const unsigned int expected = block_size_ * 255 * 255 / 4; EXPECT_EQ(expected, var); } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119
void VarianceTest<VarianceFunctionType>::OneQuarterTest() { const int half = block_size_ / 2; if (!use_high_bit_depth_) { memset(src_, 255, block_size_); memset(ref_, 255, half); memset(ref_ + half, 0, half); #if CONFIG_VP9_HIGHBITDEPTH } else { vpx_memset16(CONVERT_TO_SHORTPTR(src_), 255 << (bit_depth_ - 8), block_size_); vpx_memset16(CONVERT_TO_SHORTPTR(ref_), 255 << (bit_depth_ - 8), half); vpx_memset16(CONVERT_TO_SHORTPTR(ref_) + half, 0, half); #endif // CONFIG_VP9_HIGHBITDEPTH } unsigned int sse; unsigned int var; ASM_REGISTER_STATE_CHECK(var = variance_(src_, width_, ref_, width_, &sse)); const unsigned int expected = block_size_ * 255 * 255 / 4; EXPECT_EQ(expected, var); }
174,585
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the 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 IsIDNComponentSafe(base::StringPiece16 label) { return g_idn_spoof_checker.Get().Check(label); } Commit Message: Block domain labels made of Cyrillic letters that look alike Latin Block a label made entirely of Latin-look-alike Cyrillic letters when the TLD is not an IDN (i.e. this check is ON only for TLDs like 'com', 'net', 'uk', but not applied for IDN TLDs like рф. BUG=683314 TEST=components_unittests --gtest_filter=U*IDN* Review-Url: https://codereview.chromium.org/2683793010 Cr-Commit-Position: refs/heads/master@{#459226} CWE ID: CWE-20
bool IsIDNComponentSafe(base::StringPiece16 label) { bool IsIDNComponentSafe(base::StringPiece16 label, bool is_tld_ascii) { return g_idn_spoof_checker.Get().Check(label, is_tld_ascii); }
172,392