instruction
stringclasses
1 value
input
stringlengths
90
139k
output
stringlengths
16
138k
__index_level_0__
int64
165k
175k
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: status_t SampleTable::setCompositionTimeToSampleParams( off64_t data_offset, size_t data_size) { ALOGI("There are reordered frames present."); if (mCompositionTimeDeltaEntries != NULL || data_size < 8) { return ERROR_MALFORMED; } uint8_t header[8]; if (mDataSource->readAt( data_offset, header, sizeof(header)) < (ssize_t)sizeof(header)) { return ERROR_IO; } if (U32_AT(header) != 0) { return ERROR_MALFORMED; } size_t numEntries = U32_AT(&header[4]); if (data_size != (numEntries + 1) * 8) { return ERROR_MALFORMED; } mNumCompositionTimeDeltaEntries = numEntries; uint64_t allocSize = numEntries * 2 * sizeof(uint32_t); if (allocSize > SIZE_MAX) { return ERROR_OUT_OF_RANGE; } mCompositionTimeDeltaEntries = new uint32_t[2 * numEntries]; if (mDataSource->readAt( data_offset + 8, mCompositionTimeDeltaEntries, numEntries * 8) < (ssize_t)numEntries * 8) { delete[] mCompositionTimeDeltaEntries; mCompositionTimeDeltaEntries = NULL; return ERROR_IO; } for (size_t i = 0; i < 2 * numEntries; ++i) { mCompositionTimeDeltaEntries[i] = ntohl(mCompositionTimeDeltaEntries[i]); } mCompositionDeltaLookup->setEntries( mCompositionTimeDeltaEntries, mNumCompositionTimeDeltaEntries); return OK; } Commit Message: Fix several ineffective integer overflow checks Commit edd4a76 (which addressed bugs 15328708, 15342615, 15342751) added several integer overflow checks. Unfortunately, those checks fail to take into account integer promotion rules and are thus themselves subject to an integer overflow. Cast the sizeof() operator to a uint64_t to force promotion while multiplying. Bug: 20139950 (cherry picked from commit e2e812e58e8d2716b00d7d82db99b08d3afb4b32) Change-Id: I080eb3fa147601f18cedab86e0360406c3963d7b CWE ID: CWE-189
status_t SampleTable::setCompositionTimeToSampleParams( off64_t data_offset, size_t data_size) { ALOGI("There are reordered frames present."); if (mCompositionTimeDeltaEntries != NULL || data_size < 8) { return ERROR_MALFORMED; } uint8_t header[8]; if (mDataSource->readAt( data_offset, header, sizeof(header)) < (ssize_t)sizeof(header)) { return ERROR_IO; } if (U32_AT(header) != 0) { return ERROR_MALFORMED; } size_t numEntries = U32_AT(&header[4]); if (data_size != (numEntries + 1) * 8) { return ERROR_MALFORMED; } mNumCompositionTimeDeltaEntries = numEntries; uint64_t allocSize = numEntries * 2 * (uint64_t)sizeof(uint32_t); if (allocSize > SIZE_MAX) { return ERROR_OUT_OF_RANGE; } mCompositionTimeDeltaEntries = new uint32_t[2 * numEntries]; if (mDataSource->readAt( data_offset + 8, mCompositionTimeDeltaEntries, numEntries * 8) < (ssize_t)numEntries * 8) { delete[] mCompositionTimeDeltaEntries; mCompositionTimeDeltaEntries = NULL; return ERROR_IO; } for (size_t i = 0; i < 2 * numEntries; ++i) { mCompositionTimeDeltaEntries[i] = ntohl(mCompositionTimeDeltaEntries[i]); } mCompositionDeltaLookup->setEntries( mCompositionTimeDeltaEntries, mNumCompositionTimeDeltaEntries); return OK; }
173,337
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void vhost_net_ubuf_put_and_wait(struct vhost_net_ubuf_ref *ubufs) { kref_put(&ubufs->kref, vhost_net_zerocopy_done_signal); wait_event(ubufs->wait, !atomic_read(&ubufs->kref.refcount)); kfree(ubufs); } Commit Message: vhost-net: fix use-after-free in vhost_net_flush vhost_net_ubuf_put_and_wait has a confusing name: it will actually also free it's argument. Thus since commit 1280c27f8e29acf4af2da914e80ec27c3dbd5c01 "vhost-net: flush outstanding DMAs on memory change" vhost_net_flush tries to use the argument after passing it to vhost_net_ubuf_put_and_wait, this results in use after free. To fix, don't free the argument in vhost_net_ubuf_put_and_wait, add an new API for callers that want to free ubufs. Acked-by: Asias He <[email protected]> Acked-by: Jason Wang <[email protected]> Signed-off-by: Michael S. Tsirkin <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-399
static void vhost_net_ubuf_put_and_wait(struct vhost_net_ubuf_ref *ubufs) { kref_put(&ubufs->kref, vhost_net_zerocopy_done_signal); wait_event(ubufs->wait, !atomic_read(&ubufs->kref.refcount)); } static void vhost_net_ubuf_put_wait_and_free(struct vhost_net_ubuf_ref *ubufs) { vhost_net_ubuf_put_and_wait(ubufs); kfree(ubufs); }
166,021
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: enum nss_status _nss_mymachines_getpwnam_r( const char *name, struct passwd *pwd, char *buffer, size_t buflen, int *errnop) { _cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL; _cleanup_bus_message_unref_ sd_bus_message* reply = NULL; _cleanup_bus_flush_close_unref_ sd_bus *bus = NULL; const char *p, *e, *machine; uint32_t mapped; uid_t uid; size_t l; int r; assert(name); assert(pwd); p = startswith(name, "vu-"); if (!p) goto not_found; e = strrchr(p, '-'); if (!e || e == p) goto not_found; r = parse_uid(e + 1, &uid); if (r < 0) goto not_found; machine = strndupa(p, e - p); if (!machine_name_is_valid(machine)) goto not_found; r = sd_bus_open_system(&bus); if (r < 0) goto fail; r = sd_bus_call_method(bus, "org.freedesktop.machine1", "/org/freedesktop/machine1", "org.freedesktop.machine1.Manager", "MapFromMachineUser", &error, &reply, "su", machine, (uint32_t) uid); if (r < 0) { if (sd_bus_error_has_name(&error, BUS_ERROR_NO_SUCH_USER_MAPPING)) goto not_found; goto fail; } r = sd_bus_message_read(reply, "u", &mapped); if (r < 0) goto fail; l = strlen(name); if (buflen < l+1) { *errnop = ENOMEM; return NSS_STATUS_TRYAGAIN; } memcpy(buffer, name, l+1); pwd->pw_name = buffer; pwd->pw_uid = mapped; pwd->pw_gid = 65534; /* nobody */ pwd->pw_gecos = buffer; pwd->pw_passwd = (char*) "*"; /* locked */ pwd->pw_dir = (char*) "/"; pwd->pw_shell = (char*) "/sbin/nologin"; *errnop = 0; return NSS_STATUS_SUCCESS; not_found: *errnop = 0; return NSS_STATUS_NOTFOUND; fail: *errnop = -r; return NSS_STATUS_UNAVAIL; } Commit Message: nss-mymachines: do not allow overlong machine names https://github.com/systemd/systemd/issues/2002 CWE ID: CWE-119
enum nss_status _nss_mymachines_getpwnam_r( const char *name, struct passwd *pwd, char *buffer, size_t buflen, int *errnop) { _cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL; _cleanup_bus_message_unref_ sd_bus_message* reply = NULL; _cleanup_bus_flush_close_unref_ sd_bus *bus = NULL; const char *p, *e, *machine; uint32_t mapped; uid_t uid; size_t l; int r; assert(name); assert(pwd); p = startswith(name, "vu-"); if (!p) goto not_found; e = strrchr(p, '-'); if (!e || e == p) goto not_found; if (e - p > HOST_NAME_MAX - 1) /* -1 for the last dash */ goto not_found; r = parse_uid(e + 1, &uid); if (r < 0) goto not_found; machine = strndupa(p, e - p); if (!machine_name_is_valid(machine)) goto not_found; r = sd_bus_open_system(&bus); if (r < 0) goto fail; r = sd_bus_call_method(bus, "org.freedesktop.machine1", "/org/freedesktop/machine1", "org.freedesktop.machine1.Manager", "MapFromMachineUser", &error, &reply, "su", machine, (uint32_t) uid); if (r < 0) { if (sd_bus_error_has_name(&error, BUS_ERROR_NO_SUCH_USER_MAPPING)) goto not_found; goto fail; } r = sd_bus_message_read(reply, "u", &mapped); if (r < 0) goto fail; l = strlen(name); if (buflen < l+1) { *errnop = ENOMEM; return NSS_STATUS_TRYAGAIN; } memcpy(buffer, name, l+1); pwd->pw_name = buffer; pwd->pw_uid = mapped; pwd->pw_gid = 65534; /* nobody */ pwd->pw_gecos = buffer; pwd->pw_passwd = (char*) "*"; /* locked */ pwd->pw_dir = (char*) "/"; pwd->pw_shell = (char*) "/sbin/nologin"; *errnop = 0; return NSS_STATUS_SUCCESS; not_found: *errnop = 0; return NSS_STATUS_NOTFOUND; fail: *errnop = -r; return NSS_STATUS_UNAVAIL; }
168,870
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void PrintViewManagerBase::OnDidPrintPage( const PrintHostMsg_DidPrintPage_Params& params) { if (!OpportunisticallyCreatePrintJob(params.document_cookie)) return; PrintedDocument* document = print_job_->document(); if (!document || params.document_cookie != document->cookie()) { return; } #if defined(OS_MACOSX) const bool metafile_must_be_valid = true; #else const bool metafile_must_be_valid = expecting_first_page_; expecting_first_page_ = false; #endif std::unique_ptr<base::SharedMemory> shared_buf; if (metafile_must_be_valid) { if (!base::SharedMemory::IsHandleValid(params.metafile_data_handle)) { NOTREACHED() << "invalid memory handle"; web_contents()->Stop(); return; } shared_buf = base::MakeUnique<base::SharedMemory>(params.metafile_data_handle, true); if (!shared_buf->Map(params.data_size)) { NOTREACHED() << "couldn't map"; web_contents()->Stop(); return; } } else { if (base::SharedMemory::IsHandleValid(params.metafile_data_handle)) { NOTREACHED() << "unexpected valid memory handle"; web_contents()->Stop(); base::SharedMemory::CloseHandle(params.metafile_data_handle); return; } } std::unique_ptr<PdfMetafileSkia> metafile( new PdfMetafileSkia(SkiaDocumentType::PDF)); if (metafile_must_be_valid) { if (!metafile->InitFromData(shared_buf->memory(), params.data_size)) { NOTREACHED() << "Invalid metafile header"; web_contents()->Stop(); return; } } #if defined(OS_WIN) print_job_->AppendPrintedPage(params.page_number); if (metafile_must_be_valid) { scoped_refptr<base::RefCountedBytes> bytes = new base::RefCountedBytes( reinterpret_cast<const unsigned char*>(shared_buf->memory()), params.data_size); document->DebugDumpData(bytes.get(), FILE_PATH_LITERAL(".pdf")); const auto& settings = document->settings(); if (settings.printer_is_textonly()) { print_job_->StartPdfToTextConversion(bytes, params.page_size); } else if ((settings.printer_is_ps2() || settings.printer_is_ps3()) && !base::FeatureList::IsEnabled( features::kDisablePostScriptPrinting)) { print_job_->StartPdfToPostScriptConversion(bytes, params.content_area, params.physical_offsets, settings.printer_is_ps2()); } else { bool print_text_with_gdi = settings.print_text_with_gdi() && !settings.printer_is_xps() && base::FeatureList::IsEnabled( features::kGdiTextPrinting); print_job_->StartPdfToEmfConversion( bytes, params.page_size, params.content_area, print_text_with_gdi); } } #else document->SetPage(params.page_number, std::move(metafile), #if defined(OS_WIN) 0.0f /* dummy shrink_factor */, #endif params.page_size, params.content_area); ShouldQuitFromInnerMessageLoop(); #endif } Commit Message: Use pdf compositor service for printing when OOPIF is enabled When OOPIF is enabled (by site-per-process flag or top-document-isolation feature), use the pdf compositor service for converting PaintRecord to PDF on renderers. In the future, this will make compositing PDF from multiple renderers possible. [email protected] BUG=455764 Change-Id: I3c28f03f4358e4228239fe1a33384f85e7716e8f Reviewed-on: https://chromium-review.googlesource.com/699765 Commit-Queue: Wei Li <[email protected]> Reviewed-by: Daniel Cheng <[email protected]> Reviewed-by: Lei Zhang <[email protected]> Cr-Commit-Position: refs/heads/master@{#511616} CWE ID: CWE-254
void PrintViewManagerBase::OnDidPrintPage( const PrintHostMsg_DidPrintPage_Params& params) { // Ready to composite. Starting a print job. if (!OpportunisticallyCreatePrintJob(params.document_cookie)) return; PrintedDocument* document = print_job_->document(); if (!document || params.document_cookie != document->cookie()) { return; } #if defined(OS_MACOSX) const bool metafile_must_be_valid = true; #else const bool metafile_must_be_valid = expecting_first_page_; expecting_first_page_ = false; #endif std::unique_ptr<base::SharedMemory> shared_buf; if (metafile_must_be_valid) { if (!base::SharedMemory::IsHandleValid(params.metafile_data_handle)) { NOTREACHED() << "invalid memory handle"; web_contents()->Stop(); return; } auto* client = PrintCompositeClient::FromWebContents(web_contents()); if (IsOopifEnabled() && !client->for_preview() && !document->settings().is_modifiable()) { client->DoComposite( params.metafile_data_handle, params.data_size, base::BindOnce(&PrintViewManagerBase::OnComposePdfDone, weak_ptr_factory_.GetWeakPtr(), params)); return; } shared_buf = std::make_unique<base::SharedMemory>(params.metafile_data_handle, true); if (!shared_buf->Map(params.data_size)) { NOTREACHED() << "couldn't map"; web_contents()->Stop(); return; } } else { if (base::SharedMemory::IsHandleValid(params.metafile_data_handle)) { NOTREACHED() << "unexpected valid memory handle"; web_contents()->Stop(); base::SharedMemory::CloseHandle(params.metafile_data_handle); return; } } UpdateForPrintedPage(params, metafile_must_be_valid, std::move(shared_buf)); } void PrintViewManagerBase::UpdateForPrintedPage( const PrintHostMsg_DidPrintPage_Params& params, bool has_valid_page_data, std::unique_ptr<base::SharedMemory> shared_buf) { PrintedDocument* document = print_job_->document(); if (!document) return; #if defined(OS_WIN) print_job_->AppendPrintedPage(params.page_number); if (has_valid_page_data) { scoped_refptr<base::RefCountedBytes> bytes(new base::RefCountedBytes( reinterpret_cast<const unsigned char*>(shared_buf->memory()), shared_buf->mapped_size())); document->DebugDumpData(bytes.get(), FILE_PATH_LITERAL(".pdf")); const auto& settings = document->settings(); if (settings.printer_is_textonly()) { print_job_->StartPdfToTextConversion(bytes, params.page_size); } else if ((settings.printer_is_ps2() || settings.printer_is_ps3()) && !base::FeatureList::IsEnabled( features::kDisablePostScriptPrinting)) { print_job_->StartPdfToPostScriptConversion(bytes, params.content_area, params.physical_offsets, settings.printer_is_ps2()); } else { bool print_text_with_gdi = settings.print_text_with_gdi() && !settings.printer_is_xps() && base::FeatureList::IsEnabled(features::kGdiTextPrinting); print_job_->StartPdfToEmfConversion( bytes, params.page_size, params.content_area, print_text_with_gdi); } } #else std::unique_ptr<PdfMetafileSkia> metafile = std::make_unique<PdfMetafileSkia>(SkiaDocumentType::PDF); if (has_valid_page_data) { if (!metafile->InitFromData(shared_buf->memory(), shared_buf->mapped_size())) { NOTREACHED() << "Invalid metafile header"; web_contents()->Stop(); return; } } document->SetPage(params.page_number, std::move(metafile), params.page_size, params.content_area); ShouldQuitFromInnerMessageLoop(); #endif }
171,892
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: PanelSettingsMenuModel::PanelSettingsMenuModel(Panel* panel) : ALLOW_THIS_IN_INITIALIZER_LIST(ui::SimpleMenuModel(this)), panel_(panel) { const Extension* extension = panel_->GetExtension(); DCHECK(extension); AddItem(COMMAND_NAME, UTF8ToUTF16(extension->name())); AddSeparator(); AddItem(COMMAND_CONFIGURE, l10n_util::GetStringUTF16(IDS_EXTENSIONS_OPTIONS)); AddItem(COMMAND_DISABLE, l10n_util::GetStringUTF16(IDS_EXTENSIONS_DISABLE)); AddItem(COMMAND_UNINSTALL, l10n_util::GetStringFUTF16(IDS_EXTENSIONS_UNINSTALL, l10n_util::GetStringUTF16(IDS_SHORT_PRODUCT_NAME))); AddSeparator(); AddItem(COMMAND_MANAGE, l10n_util::GetStringUTF16(IDS_MANAGE_EXTENSIONS)); } Commit Message: [i18n-fixlet] Make strings branding specific in extension code. IDS_EXTENSIONS_UNINSTALL IDS_EXTENSIONS_INCOGNITO_WARNING IDS_EXTENSION_INSTALLED_HEADING IDS_EXTENSION_ALERT_ITEM_EXTERNAL And fix a $1 $1 bug. IDS_EXTENSION_INLINE_INSTALL_PROMPT_TITLE BUG=NONE TEST=NONE Review URL: http://codereview.chromium.org/9107061 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@118018 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
PanelSettingsMenuModel::PanelSettingsMenuModel(Panel* panel) : ALLOW_THIS_IN_INITIALIZER_LIST(ui::SimpleMenuModel(this)), panel_(panel) { const Extension* extension = panel_->GetExtension(); DCHECK(extension); AddItem(COMMAND_NAME, UTF8ToUTF16(extension->name())); AddSeparator(); AddItem(COMMAND_CONFIGURE, l10n_util::GetStringUTF16(IDS_EXTENSIONS_OPTIONS)); AddItem(COMMAND_DISABLE, l10n_util::GetStringUTF16(IDS_EXTENSIONS_DISABLE)); AddItem(COMMAND_UNINSTALL, l10n_util::GetStringUTF16(IDS_EXTENSIONS_UNINSTALL)); AddSeparator(); AddItem(COMMAND_MANAGE, l10n_util::GetStringUTF16(IDS_MANAGE_EXTENSIONS)); }
170,983
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static noinline int hiddev_ioctl_usage(struct hiddev *hiddev, unsigned int cmd, void __user *user_arg) { struct hid_device *hid = hiddev->hid; struct hiddev_report_info rinfo; struct hiddev_usage_ref_multi *uref_multi = NULL; struct hiddev_usage_ref *uref; struct hid_report *report; struct hid_field *field; int i; uref_multi = kmalloc(sizeof(struct hiddev_usage_ref_multi), GFP_KERNEL); if (!uref_multi) return -ENOMEM; uref = &uref_multi->uref; if (cmd == HIDIOCGUSAGES || cmd == HIDIOCSUSAGES) { if (copy_from_user(uref_multi, user_arg, sizeof(*uref_multi))) goto fault; } else { if (copy_from_user(uref, user_arg, sizeof(*uref))) goto fault; } switch (cmd) { case HIDIOCGUCODE: rinfo.report_type = uref->report_type; rinfo.report_id = uref->report_id; if ((report = hiddev_lookup_report(hid, &rinfo)) == NULL) goto inval; if (uref->field_index >= report->maxfield) goto inval; field = report->field[uref->field_index]; if (uref->usage_index >= field->maxusage) goto inval; uref->usage_code = field->usage[uref->usage_index].hid; if (copy_to_user(user_arg, uref, sizeof(*uref))) goto fault; goto goodreturn; default: if (cmd != HIDIOCGUSAGE && cmd != HIDIOCGUSAGES && uref->report_type == HID_REPORT_TYPE_INPUT) goto inval; if (uref->report_id == HID_REPORT_ID_UNKNOWN) { field = hiddev_lookup_usage(hid, uref); if (field == NULL) goto inval; } else { rinfo.report_type = uref->report_type; rinfo.report_id = uref->report_id; if ((report = hiddev_lookup_report(hid, &rinfo)) == NULL) goto inval; if (uref->field_index >= report->maxfield) goto inval; field = report->field[uref->field_index]; if (cmd == HIDIOCGCOLLECTIONINDEX) { if (uref->usage_index >= field->maxusage) goto inval; } else if (uref->usage_index >= field->report_count) goto inval; else if ((cmd == HIDIOCGUSAGES || cmd == HIDIOCSUSAGES) && (uref_multi->num_values > HID_MAX_MULTI_USAGES || uref->usage_index + uref_multi->num_values > field->report_count)) goto inval; } switch (cmd) { case HIDIOCGUSAGE: uref->value = field->value[uref->usage_index]; if (copy_to_user(user_arg, uref, sizeof(*uref))) goto fault; goto goodreturn; case HIDIOCSUSAGE: field->value[uref->usage_index] = uref->value; goto goodreturn; case HIDIOCGCOLLECTIONINDEX: i = field->usage[uref->usage_index].collection_index; kfree(uref_multi); return i; case HIDIOCGUSAGES: for (i = 0; i < uref_multi->num_values; i++) uref_multi->values[i] = field->value[uref->usage_index + i]; if (copy_to_user(user_arg, uref_multi, sizeof(*uref_multi))) goto fault; goto goodreturn; case HIDIOCSUSAGES: for (i = 0; i < uref_multi->num_values; i++) field->value[uref->usage_index + i] = uref_multi->values[i]; goto goodreturn; } goodreturn: kfree(uref_multi); return 0; fault: kfree(uref_multi); return -EFAULT; inval: kfree(uref_multi); return -EINVAL; } } Commit Message: HID: hiddev: validate num_values for HIDIOCGUSAGES, HIDIOCSUSAGES commands This patch validates the num_values parameter from userland during the HIDIOCGUSAGES and HIDIOCSUSAGES commands. Previously, if the report id was set to HID_REPORT_ID_UNKNOWN, we would fail to validate the num_values parameter leading to a heap overflow. Cc: [email protected] Signed-off-by: Scott Bauer <[email protected]> Signed-off-by: Jiri Kosina <[email protected]> CWE ID: CWE-119
static noinline int hiddev_ioctl_usage(struct hiddev *hiddev, unsigned int cmd, void __user *user_arg) { struct hid_device *hid = hiddev->hid; struct hiddev_report_info rinfo; struct hiddev_usage_ref_multi *uref_multi = NULL; struct hiddev_usage_ref *uref; struct hid_report *report; struct hid_field *field; int i; uref_multi = kmalloc(sizeof(struct hiddev_usage_ref_multi), GFP_KERNEL); if (!uref_multi) return -ENOMEM; uref = &uref_multi->uref; if (cmd == HIDIOCGUSAGES || cmd == HIDIOCSUSAGES) { if (copy_from_user(uref_multi, user_arg, sizeof(*uref_multi))) goto fault; } else { if (copy_from_user(uref, user_arg, sizeof(*uref))) goto fault; } switch (cmd) { case HIDIOCGUCODE: rinfo.report_type = uref->report_type; rinfo.report_id = uref->report_id; if ((report = hiddev_lookup_report(hid, &rinfo)) == NULL) goto inval; if (uref->field_index >= report->maxfield) goto inval; field = report->field[uref->field_index]; if (uref->usage_index >= field->maxusage) goto inval; uref->usage_code = field->usage[uref->usage_index].hid; if (copy_to_user(user_arg, uref, sizeof(*uref))) goto fault; goto goodreturn; default: if (cmd != HIDIOCGUSAGE && cmd != HIDIOCGUSAGES && uref->report_type == HID_REPORT_TYPE_INPUT) goto inval; if (uref->report_id == HID_REPORT_ID_UNKNOWN) { field = hiddev_lookup_usage(hid, uref); if (field == NULL) goto inval; } else { rinfo.report_type = uref->report_type; rinfo.report_id = uref->report_id; if ((report = hiddev_lookup_report(hid, &rinfo)) == NULL) goto inval; if (uref->field_index >= report->maxfield) goto inval; field = report->field[uref->field_index]; if (cmd == HIDIOCGCOLLECTIONINDEX) { if (uref->usage_index >= field->maxusage) goto inval; } else if (uref->usage_index >= field->report_count) goto inval; } if ((cmd == HIDIOCGUSAGES || cmd == HIDIOCSUSAGES) && (uref_multi->num_values > HID_MAX_MULTI_USAGES || uref->usage_index + uref_multi->num_values > field->report_count)) goto inval; switch (cmd) { case HIDIOCGUSAGE: uref->value = field->value[uref->usage_index]; if (copy_to_user(user_arg, uref, sizeof(*uref))) goto fault; goto goodreturn; case HIDIOCSUSAGE: field->value[uref->usage_index] = uref->value; goto goodreturn; case HIDIOCGCOLLECTIONINDEX: i = field->usage[uref->usage_index].collection_index; kfree(uref_multi); return i; case HIDIOCGUSAGES: for (i = 0; i < uref_multi->num_values; i++) uref_multi->values[i] = field->value[uref->usage_index + i]; if (copy_to_user(user_arg, uref_multi, sizeof(*uref_multi))) goto fault; goto goodreturn; case HIDIOCSUSAGES: for (i = 0; i < uref_multi->num_values; i++) field->value[uref->usage_index + i] = uref_multi->values[i]; goto goodreturn; } goodreturn: kfree(uref_multi); return 0; fault: kfree(uref_multi); return -EFAULT; inval: kfree(uref_multi); return -EINVAL; } }
167,022
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void SocketStream::DoLoop(int result) { if (!context_.get()) next_state_ = STATE_CLOSE; if (next_state_ == STATE_NONE) return; do { State state = next_state_; next_state_ = STATE_NONE; switch (state) { case STATE_BEFORE_CONNECT: DCHECK_EQ(OK, result); result = DoBeforeConnect(); break; case STATE_BEFORE_CONNECT_COMPLETE: result = DoBeforeConnectComplete(result); break; case STATE_RESOLVE_PROXY: DCHECK_EQ(OK, result); result = DoResolveProxy(); break; case STATE_RESOLVE_PROXY_COMPLETE: result = DoResolveProxyComplete(result); break; case STATE_RESOLVE_HOST: DCHECK_EQ(OK, result); result = DoResolveHost(); break; case STATE_RESOLVE_HOST_COMPLETE: result = DoResolveHostComplete(result); break; case STATE_RESOLVE_PROTOCOL: result = DoResolveProtocol(result); break; case STATE_RESOLVE_PROTOCOL_COMPLETE: result = DoResolveProtocolComplete(result); break; case STATE_TCP_CONNECT: result = DoTcpConnect(result); break; case STATE_TCP_CONNECT_COMPLETE: result = DoTcpConnectComplete(result); break; case STATE_GENERATE_PROXY_AUTH_TOKEN: result = DoGenerateProxyAuthToken(); break; case STATE_GENERATE_PROXY_AUTH_TOKEN_COMPLETE: result = DoGenerateProxyAuthTokenComplete(result); break; case STATE_WRITE_TUNNEL_HEADERS: DCHECK_EQ(OK, result); result = DoWriteTunnelHeaders(); break; case STATE_WRITE_TUNNEL_HEADERS_COMPLETE: result = DoWriteTunnelHeadersComplete(result); break; case STATE_READ_TUNNEL_HEADERS: DCHECK_EQ(OK, result); result = DoReadTunnelHeaders(); break; case STATE_READ_TUNNEL_HEADERS_COMPLETE: result = DoReadTunnelHeadersComplete(result); break; case STATE_SOCKS_CONNECT: DCHECK_EQ(OK, result); result = DoSOCKSConnect(); break; case STATE_SOCKS_CONNECT_COMPLETE: result = DoSOCKSConnectComplete(result); break; case STATE_SECURE_PROXY_CONNECT: DCHECK_EQ(OK, result); result = DoSecureProxyConnect(); break; case STATE_SECURE_PROXY_CONNECT_COMPLETE: result = DoSecureProxyConnectComplete(result); break; case STATE_SECURE_PROXY_HANDLE_CERT_ERROR: result = DoSecureProxyHandleCertError(result); break; case STATE_SECURE_PROXY_HANDLE_CERT_ERROR_COMPLETE: result = DoSecureProxyHandleCertErrorComplete(result); break; case STATE_SSL_CONNECT: DCHECK_EQ(OK, result); result = DoSSLConnect(); break; case STATE_SSL_CONNECT_COMPLETE: result = DoSSLConnectComplete(result); break; case STATE_SSL_HANDLE_CERT_ERROR: result = DoSSLHandleCertError(result); break; case STATE_SSL_HANDLE_CERT_ERROR_COMPLETE: result = DoSSLHandleCertErrorComplete(result); break; case STATE_READ_WRITE: result = DoReadWrite(result); break; case STATE_AUTH_REQUIRED: Finish(result); return; case STATE_CLOSE: DCHECK_LE(result, OK); Finish(result); return; default: NOTREACHED() << "bad state " << state; Finish(result); return; } if (state == STATE_RESOLVE_PROTOCOL && result == ERR_PROTOCOL_SWITCHED) continue; if (state != STATE_READ_WRITE && result < ERR_IO_PENDING) { net_log_.EndEventWithNetErrorCode( NetLog::TYPE_SOCKET_STREAM_CONNECT, result); } } while (result != ERR_IO_PENDING); } Commit Message: Revert a workaround commit for a Use-After-Free crash. Revert a workaround commit r20158 for a Use-After-Free issue (http://crbug.com/244746) because a cleaner CL r207218 is landed. URLRequestContext does not inherit SupportsWeakPtr now. R=mmenke BUG=244746 Review URL: https://chromiumcodereview.appspot.com/16870008 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@207811 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void SocketStream::DoLoop(int result) { if (!context_) next_state_ = STATE_CLOSE; if (next_state_ == STATE_NONE) return; do { State state = next_state_; next_state_ = STATE_NONE; switch (state) { case STATE_BEFORE_CONNECT: DCHECK_EQ(OK, result); result = DoBeforeConnect(); break; case STATE_BEFORE_CONNECT_COMPLETE: result = DoBeforeConnectComplete(result); break; case STATE_RESOLVE_PROXY: DCHECK_EQ(OK, result); result = DoResolveProxy(); break; case STATE_RESOLVE_PROXY_COMPLETE: result = DoResolveProxyComplete(result); break; case STATE_RESOLVE_HOST: DCHECK_EQ(OK, result); result = DoResolveHost(); break; case STATE_RESOLVE_HOST_COMPLETE: result = DoResolveHostComplete(result); break; case STATE_RESOLVE_PROTOCOL: result = DoResolveProtocol(result); break; case STATE_RESOLVE_PROTOCOL_COMPLETE: result = DoResolveProtocolComplete(result); break; case STATE_TCP_CONNECT: result = DoTcpConnect(result); break; case STATE_TCP_CONNECT_COMPLETE: result = DoTcpConnectComplete(result); break; case STATE_GENERATE_PROXY_AUTH_TOKEN: result = DoGenerateProxyAuthToken(); break; case STATE_GENERATE_PROXY_AUTH_TOKEN_COMPLETE: result = DoGenerateProxyAuthTokenComplete(result); break; case STATE_WRITE_TUNNEL_HEADERS: DCHECK_EQ(OK, result); result = DoWriteTunnelHeaders(); break; case STATE_WRITE_TUNNEL_HEADERS_COMPLETE: result = DoWriteTunnelHeadersComplete(result); break; case STATE_READ_TUNNEL_HEADERS: DCHECK_EQ(OK, result); result = DoReadTunnelHeaders(); break; case STATE_READ_TUNNEL_HEADERS_COMPLETE: result = DoReadTunnelHeadersComplete(result); break; case STATE_SOCKS_CONNECT: DCHECK_EQ(OK, result); result = DoSOCKSConnect(); break; case STATE_SOCKS_CONNECT_COMPLETE: result = DoSOCKSConnectComplete(result); break; case STATE_SECURE_PROXY_CONNECT: DCHECK_EQ(OK, result); result = DoSecureProxyConnect(); break; case STATE_SECURE_PROXY_CONNECT_COMPLETE: result = DoSecureProxyConnectComplete(result); break; case STATE_SECURE_PROXY_HANDLE_CERT_ERROR: result = DoSecureProxyHandleCertError(result); break; case STATE_SECURE_PROXY_HANDLE_CERT_ERROR_COMPLETE: result = DoSecureProxyHandleCertErrorComplete(result); break; case STATE_SSL_CONNECT: DCHECK_EQ(OK, result); result = DoSSLConnect(); break; case STATE_SSL_CONNECT_COMPLETE: result = DoSSLConnectComplete(result); break; case STATE_SSL_HANDLE_CERT_ERROR: result = DoSSLHandleCertError(result); break; case STATE_SSL_HANDLE_CERT_ERROR_COMPLETE: result = DoSSLHandleCertErrorComplete(result); break; case STATE_READ_WRITE: result = DoReadWrite(result); break; case STATE_AUTH_REQUIRED: Finish(result); return; case STATE_CLOSE: DCHECK_LE(result, OK); Finish(result); return; default: NOTREACHED() << "bad state " << state; Finish(result); return; } if (state == STATE_RESOLVE_PROTOCOL && result == ERR_PROTOCOL_SWITCHED) continue; if (state != STATE_READ_WRITE && result < ERR_IO_PENDING) { net_log_.EndEventWithNetErrorCode( NetLog::TYPE_SOCKET_STREAM_CONNECT, result); } } while (result != ERR_IO_PENDING); }
171,254
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: main (int argc _GL_UNUSED, char **argv) { struct timespec result; struct timespec result2; struct timespec expected; struct timespec now; const char *p; int i; long gmtoff; time_t ref_time = 1304250918; /* Set the time zone to US Eastern time with the 2012 rules. This should disable any leap second support. Otherwise, there will be a problem with glibc on sites that default to leap seconds; see <http://bugs.gnu.org/12206>. */ setenv ("TZ", "EST5EDT,M3.2.0,M11.1.0", 1); gmtoff = gmt_offset (ref_time); /* ISO 8601 extended date and time of day representation, 'T' separator, local time zone */ p = "2011-05-01T11:55:18"; expected.tv_sec = ref_time - gmtoff; expected.tv_nsec = 0; ASSERT (parse_datetime (&result, p, 0)); LOG (p, expected, result); ASSERT (expected.tv_sec == result.tv_sec && expected.tv_nsec == result.tv_nsec); /* ISO 8601 extended date and time of day representation, ' ' separator, local time zone */ p = "2011-05-01 11:55:18"; expected.tv_sec = ref_time - gmtoff; expected.tv_nsec = 0; ASSERT (parse_datetime (&result, p, 0)); LOG (p, expected, result); ASSERT (expected.tv_sec == result.tv_sec && expected.tv_nsec == result.tv_nsec); /* ISO 8601, extended date and time of day representation, 'T' separator, UTC */ p = "2011-05-01T11:55:18Z"; expected.tv_sec = ref_time; expected.tv_nsec = 0; ASSERT (parse_datetime (&result, p, 0)); LOG (p, expected, result); ASSERT (expected.tv_sec == result.tv_sec && expected.tv_nsec == result.tv_nsec); /* ISO 8601, extended date and time of day representation, ' ' separator, UTC */ p = "2011-05-01 11:55:18Z"; expected.tv_sec = ref_time; expected.tv_nsec = 0; ASSERT (parse_datetime (&result, p, 0)); LOG (p, expected, result); ASSERT (expected.tv_sec == result.tv_sec && expected.tv_nsec == result.tv_nsec); /* ISO 8601 extended date and time of day representation, 'T' separator, w/UTC offset */ p = "2011-05-01T11:55:18-07:00"; expected.tv_sec = 1304276118; expected.tv_nsec = 0; ASSERT (parse_datetime (&result, p, 0)); LOG (p, expected, result); ASSERT (expected.tv_sec == result.tv_sec && expected.tv_nsec == result.tv_nsec); /* ISO 8601 extended date and time of day representation, ' ' separator, w/UTC offset */ p = "2011-05-01 11:55:18-07:00"; expected.tv_sec = 1304276118; expected.tv_nsec = 0; ASSERT (parse_datetime (&result, p, 0)); LOG (p, expected, result); ASSERT (expected.tv_sec == result.tv_sec && expected.tv_nsec == result.tv_nsec); /* ISO 8601 extended date and time of day representation, 'T' separator, w/hour only UTC offset */ p = "2011-05-01T11:55:18-07"; expected.tv_sec = 1304276118; expected.tv_nsec = 0; ASSERT (parse_datetime (&result, p, 0)); LOG (p, expected, result); ASSERT (expected.tv_sec == result.tv_sec && expected.tv_nsec == result.tv_nsec); /* ISO 8601 extended date and time of day representation, ' ' separator, w/hour only UTC offset */ p = "2011-05-01 11:55:18-07"; expected.tv_sec = 1304276118; expected.tv_nsec = 0; ASSERT (parse_datetime (&result, p, 0)); LOG (p, expected, result); ASSERT (expected.tv_sec == result.tv_sec && expected.tv_nsec == result.tv_nsec); now.tv_sec = 4711; now.tv_nsec = 1267; p = "now"; ASSERT (parse_datetime (&result, p, &now)); LOG (p, now, result); ASSERT (now.tv_sec == result.tv_sec && now.tv_nsec == result.tv_nsec); now.tv_sec = 4711; now.tv_nsec = 1267; p = "tomorrow"; ASSERT (parse_datetime (&result, p, &now)); LOG (p, now, result); ASSERT (now.tv_sec + 24 * 60 * 60 == result.tv_sec && now.tv_nsec == result.tv_nsec); now.tv_sec = 4711; now.tv_nsec = 1267; p = "yesterday"; ASSERT (parse_datetime (&result, p, &now)); LOG (p, now, result); ASSERT (now.tv_sec - 24 * 60 * 60 == result.tv_sec && now.tv_nsec == result.tv_nsec); now.tv_sec = 4711; now.tv_nsec = 1267; p = "4 hours"; ASSERT (parse_datetime (&result, p, &now)); LOG (p, now, result); ASSERT (now.tv_sec + 4 * 60 * 60 == result.tv_sec && now.tv_nsec == result.tv_nsec); /* test if timezone is not being ignored for day offset */ now.tv_sec = 4711; now.tv_nsec = 1267; p = "UTC+400 +24 hours"; ASSERT (parse_datetime (&result, p, &now)); LOG (p, now, result); p = "UTC+400 +1 day"; ASSERT (parse_datetime (&result2, p, &now)); LOG (p, now, result2); ASSERT (result.tv_sec == result2.tv_sec && result.tv_nsec == result2.tv_nsec); /* test if several time zones formats are handled same way */ now.tv_sec = 4711; now.tv_nsec = 1267; p = "UTC+14:00"; ASSERT (parse_datetime (&result, p, &now)); LOG (p, now, result); p = "UTC+14"; ASSERT (parse_datetime (&result2, p, &now)); LOG (p, now, result2); ASSERT (result.tv_sec == result2.tv_sec && result.tv_nsec == result2.tv_nsec); p = "UTC+1400"; ASSERT (parse_datetime (&result2, p, &now)); LOG (p, now, result2); ASSERT (result.tv_sec == result2.tv_sec && result.tv_nsec == result2.tv_nsec); now.tv_sec = 4711; now.tv_nsec = 1267; p = "UTC-14:00"; ASSERT (parse_datetime (&result, p, &now)); LOG (p, now, result); p = "UTC-14"; ASSERT (parse_datetime (&result2, p, &now)); LOG (p, now, result2); ASSERT (result.tv_sec == result2.tv_sec && result.tv_nsec == result2.tv_nsec); p = "UTC-1400"; ASSERT (parse_datetime (&result2, p, &now)); LOG (p, now, result2); ASSERT (result.tv_sec == result2.tv_sec && result.tv_nsec == result2.tv_nsec); now.tv_sec = 4711; now.tv_nsec = 1267; p = "UTC+0:15"; ASSERT (parse_datetime (&result, p, &now)); LOG (p, now, result); p = "UTC+0015"; ASSERT (parse_datetime (&result2, p, &now)); LOG (p, now, result2); ASSERT (result.tv_sec == result2.tv_sec && result.tv_nsec == result2.tv_nsec); now.tv_sec = 4711; now.tv_nsec = 1267; p = "UTC-1:30"; ASSERT (parse_datetime (&result, p, &now)); LOG (p, now, result); p = "UTC-130"; ASSERT (parse_datetime (&result2, p, &now)); LOG (p, now, result2); ASSERT (result.tv_sec == result2.tv_sec && result.tv_nsec == result2.tv_nsec); /* TZ out of range should cause parse_datetime failure */ now.tv_sec = 4711; now.tv_nsec = 1267; p = "UTC+25:00"; ASSERT (!parse_datetime (&result, p, &now)); /* Check for several invalid countable dayshifts */ now.tv_sec = 4711; now.tv_nsec = 1267; p = "UTC+4:00 +40 yesterday"; ASSERT (!parse_datetime (&result, p, &now)); p = "UTC+4:00 next yesterday"; ASSERT (!parse_datetime (&result, p, &now)); p = "UTC+4:00 tomorrow ago"; ASSERT (!parse_datetime (&result, p, &now)); p = "UTC+4:00 tomorrow hence"; ASSERT (!parse_datetime (&result, p, &now)); p = "UTC+4:00 40 now ago"; ASSERT (!parse_datetime (&result, p, &now)); p = "UTC+4:00 last tomorrow"; ASSERT (!parse_datetime (&result, p, &now)); p = "UTC+4:00 -4 today"; ASSERT (!parse_datetime (&result, p, &now)); /* And check correct usage of dayshifts */ now.tv_sec = 4711; now.tv_nsec = 1267; p = "UTC+400 tomorrow"; ASSERT (parse_datetime (&result, p, &now)); LOG (p, now, result); p = "UTC+400 +1 day"; ASSERT (parse_datetime (&result2, p, &now)); LOG (p, now, result2); ASSERT (result.tv_sec == result2.tv_sec && result.tv_nsec == result2.tv_nsec); p = "UTC+400 1 day hence"; ASSERT (parse_datetime (&result2, p, &now)); LOG (p, now, result2); ASSERT (result.tv_sec == result2.tv_sec && result.tv_nsec == result2.tv_nsec); now.tv_sec = 4711; now.tv_nsec = 1267; p = "UTC+400 yesterday"; ASSERT (parse_datetime (&result, p, &now)); LOG (p, now, result); p = "UTC+400 1 day ago"; ASSERT (parse_datetime (&result2, p, &now)); LOG (p, now, result2); ASSERT (result.tv_sec == result2.tv_sec && result.tv_nsec == result2.tv_nsec); now.tv_sec = 4711; now.tv_nsec = 1267; p = "UTC+400 now"; ASSERT (parse_datetime (&result, p, &now)); LOG (p, now, result); p = "UTC+400 +0 minutes"; /* silly, but simple "UTC+400" is different*/ ASSERT (parse_datetime (&result2, p, &now)); LOG (p, now, result2); ASSERT (result.tv_sec == result2.tv_sec && result.tv_nsec == result2.tv_nsec); /* Check that some "next Monday", "last Wednesday", etc. are correct. */ setenv ("TZ", "UTC0", 1); for (i = 0; day_table[i]; i++) { unsigned int thur2 = 7 * 24 * 3600; /* 2nd thursday */ char tmp[32]; sprintf (tmp, "NEXT %s", day_table[i]); now.tv_sec = thur2 + 4711; now.tv_nsec = 1267; ASSERT (parse_datetime (&result, tmp, &now)); LOG (tmp, now, result); ASSERT (result.tv_nsec == 0); ASSERT (result.tv_sec == thur2 + (i == 4 ? 7 : (i + 3) % 7) * 24 * 3600); sprintf (tmp, "LAST %s", day_table[i]); now.tv_sec = thur2 + 4711; now.tv_nsec = 1267; ASSERT (parse_datetime (&result, tmp, &now)); LOG (tmp, now, result); ASSERT (result.tv_nsec == 0); ASSERT (result.tv_sec == thur2 + ((i + 3) % 7 - 7) * 24 * 3600); } p = "THURSDAY UTC+00"; /* The epoch was on Thursday. */ now.tv_sec = 0; now.tv_nsec = 0; ASSERT (parse_datetime (&result, p, &now)); LOG (p, now, result); ASSERT (result.tv_sec == now.tv_sec && result.tv_nsec == now.tv_nsec); p = "FRIDAY UTC+00"; now.tv_sec = 0; now.tv_nsec = 0; ASSERT (parse_datetime (&result, p, &now)); LOG (p, now, result); ASSERT (result.tv_sec == 24 * 3600 && result.tv_nsec == now.tv_nsec); /* Exercise a sign-extension bug. Before July 2012, an input starting with a high-bit-set byte would be treated like "0". */ ASSERT ( ! parse_datetime (&result, "\xb0", &now)); /* Exercise TZ="" parsing code. */ /* These two would infloop or segfault before Feb 2014. */ ASSERT ( ! parse_datetime (&result, "TZ=\"\"\"", &now)); ASSERT ( ! parse_datetime (&result, "TZ=\"\" \"", &now)); /* Exercise invalid patterns. */ ASSERT ( ! parse_datetime (&result, "TZ=\"", &now)); ASSERT ( ! parse_datetime (&result, "TZ=\"\\\"", &now)); ASSERT ( ! parse_datetime (&result, "TZ=\"\\n", &now)); ASSERT ( ! parse_datetime (&result, "TZ=\"\\n\"", &now)); /* Exercise valid patterns. */ ASSERT ( parse_datetime (&result, "TZ=\"\"", &now)); ASSERT ( parse_datetime (&result, "TZ=\"\" ", &now)); ASSERT ( parse_datetime (&result, " TZ=\"\"", &now)); ASSERT ( parse_datetime (&result, "TZ=\"\\\\\"", &now)); ASSERT ( parse_datetime (&result, "TZ=\"\\\"\"", &now)); return 0; } Commit Message: CWE ID: CWE-119
main (int argc _GL_UNUSED, char **argv) { struct timespec result; struct timespec result2; struct timespec expected; struct timespec now; const char *p; int i; long gmtoff; time_t ref_time = 1304250918; /* Set the time zone to US Eastern time with the 2012 rules. This should disable any leap second support. Otherwise, there will be a problem with glibc on sites that default to leap seconds; see <http://bugs.gnu.org/12206>. */ setenv ("TZ", "EST5EDT,M3.2.0,M11.1.0", 1); gmtoff = gmt_offset (ref_time); /* ISO 8601 extended date and time of day representation, 'T' separator, local time zone */ p = "2011-05-01T11:55:18"; expected.tv_sec = ref_time - gmtoff; expected.tv_nsec = 0; ASSERT (parse_datetime (&result, p, 0)); LOG (p, expected, result); ASSERT (expected.tv_sec == result.tv_sec && expected.tv_nsec == result.tv_nsec); /* ISO 8601 extended date and time of day representation, ' ' separator, local time zone */ p = "2011-05-01 11:55:18"; expected.tv_sec = ref_time - gmtoff; expected.tv_nsec = 0; ASSERT (parse_datetime (&result, p, 0)); LOG (p, expected, result); ASSERT (expected.tv_sec == result.tv_sec && expected.tv_nsec == result.tv_nsec); /* ISO 8601, extended date and time of day representation, 'T' separator, UTC */ p = "2011-05-01T11:55:18Z"; expected.tv_sec = ref_time; expected.tv_nsec = 0; ASSERT (parse_datetime (&result, p, 0)); LOG (p, expected, result); ASSERT (expected.tv_sec == result.tv_sec && expected.tv_nsec == result.tv_nsec); /* ISO 8601, extended date and time of day representation, ' ' separator, UTC */ p = "2011-05-01 11:55:18Z"; expected.tv_sec = ref_time; expected.tv_nsec = 0; ASSERT (parse_datetime (&result, p, 0)); LOG (p, expected, result); ASSERT (expected.tv_sec == result.tv_sec && expected.tv_nsec == result.tv_nsec); /* ISO 8601 extended date and time of day representation, 'T' separator, w/UTC offset */ p = "2011-05-01T11:55:18-07:00"; expected.tv_sec = 1304276118; expected.tv_nsec = 0; ASSERT (parse_datetime (&result, p, 0)); LOG (p, expected, result); ASSERT (expected.tv_sec == result.tv_sec && expected.tv_nsec == result.tv_nsec); /* ISO 8601 extended date and time of day representation, ' ' separator, w/UTC offset */ p = "2011-05-01 11:55:18-07:00"; expected.tv_sec = 1304276118; expected.tv_nsec = 0; ASSERT (parse_datetime (&result, p, 0)); LOG (p, expected, result); ASSERT (expected.tv_sec == result.tv_sec && expected.tv_nsec == result.tv_nsec); /* ISO 8601 extended date and time of day representation, 'T' separator, w/hour only UTC offset */ p = "2011-05-01T11:55:18-07"; expected.tv_sec = 1304276118; expected.tv_nsec = 0; ASSERT (parse_datetime (&result, p, 0)); LOG (p, expected, result); ASSERT (expected.tv_sec == result.tv_sec && expected.tv_nsec == result.tv_nsec); /* ISO 8601 extended date and time of day representation, ' ' separator, w/hour only UTC offset */ p = "2011-05-01 11:55:18-07"; expected.tv_sec = 1304276118; expected.tv_nsec = 0; ASSERT (parse_datetime (&result, p, 0)); LOG (p, expected, result); ASSERT (expected.tv_sec == result.tv_sec && expected.tv_nsec == result.tv_nsec); now.tv_sec = 4711; now.tv_nsec = 1267; p = "now"; ASSERT (parse_datetime (&result, p, &now)); LOG (p, now, result); ASSERT (now.tv_sec == result.tv_sec && now.tv_nsec == result.tv_nsec); now.tv_sec = 4711; now.tv_nsec = 1267; p = "tomorrow"; ASSERT (parse_datetime (&result, p, &now)); LOG (p, now, result); ASSERT (now.tv_sec + 24 * 60 * 60 == result.tv_sec && now.tv_nsec == result.tv_nsec); now.tv_sec = 4711; now.tv_nsec = 1267; p = "yesterday"; ASSERT (parse_datetime (&result, p, &now)); LOG (p, now, result); ASSERT (now.tv_sec - 24 * 60 * 60 == result.tv_sec && now.tv_nsec == result.tv_nsec); now.tv_sec = 4711; now.tv_nsec = 1267; p = "4 hours"; ASSERT (parse_datetime (&result, p, &now)); LOG (p, now, result); ASSERT (now.tv_sec + 4 * 60 * 60 == result.tv_sec && now.tv_nsec == result.tv_nsec); /* test if timezone is not being ignored for day offset */ now.tv_sec = 4711; now.tv_nsec = 1267; p = "UTC+400 +24 hours"; ASSERT (parse_datetime (&result, p, &now)); LOG (p, now, result); p = "UTC+400 +1 day"; ASSERT (parse_datetime (&result2, p, &now)); LOG (p, now, result2); ASSERT (result.tv_sec == result2.tv_sec && result.tv_nsec == result2.tv_nsec); /* test if several time zones formats are handled same way */ now.tv_sec = 4711; now.tv_nsec = 1267; p = "UTC+14:00"; ASSERT (parse_datetime (&result, p, &now)); LOG (p, now, result); p = "UTC+14"; ASSERT (parse_datetime (&result2, p, &now)); LOG (p, now, result2); ASSERT (result.tv_sec == result2.tv_sec && result.tv_nsec == result2.tv_nsec); p = "UTC+1400"; ASSERT (parse_datetime (&result2, p, &now)); LOG (p, now, result2); ASSERT (result.tv_sec == result2.tv_sec && result.tv_nsec == result2.tv_nsec); now.tv_sec = 4711; now.tv_nsec = 1267; p = "UTC-14:00"; ASSERT (parse_datetime (&result, p, &now)); LOG (p, now, result); p = "UTC-14"; ASSERT (parse_datetime (&result2, p, &now)); LOG (p, now, result2); ASSERT (result.tv_sec == result2.tv_sec && result.tv_nsec == result2.tv_nsec); p = "UTC-1400"; ASSERT (parse_datetime (&result2, p, &now)); LOG (p, now, result2); ASSERT (result.tv_sec == result2.tv_sec && result.tv_nsec == result2.tv_nsec); now.tv_sec = 4711; now.tv_nsec = 1267; p = "UTC+0:15"; ASSERT (parse_datetime (&result, p, &now)); LOG (p, now, result); p = "UTC+0015"; ASSERT (parse_datetime (&result2, p, &now)); LOG (p, now, result2); ASSERT (result.tv_sec == result2.tv_sec && result.tv_nsec == result2.tv_nsec); now.tv_sec = 4711; now.tv_nsec = 1267; p = "UTC-1:30"; ASSERT (parse_datetime (&result, p, &now)); LOG (p, now, result); p = "UTC-130"; ASSERT (parse_datetime (&result2, p, &now)); LOG (p, now, result2); ASSERT (result.tv_sec == result2.tv_sec && result.tv_nsec == result2.tv_nsec); /* TZ out of range should cause parse_datetime failure */ now.tv_sec = 4711; now.tv_nsec = 1267; p = "UTC+25:00"; ASSERT (!parse_datetime (&result, p, &now)); /* Check for several invalid countable dayshifts */ now.tv_sec = 4711; now.tv_nsec = 1267; p = "UTC+4:00 +40 yesterday"; ASSERT (!parse_datetime (&result, p, &now)); p = "UTC+4:00 next yesterday"; ASSERT (!parse_datetime (&result, p, &now)); p = "UTC+4:00 tomorrow ago"; ASSERT (!parse_datetime (&result, p, &now)); p = "UTC+4:00 tomorrow hence"; ASSERT (!parse_datetime (&result, p, &now)); p = "UTC+4:00 40 now ago"; ASSERT (!parse_datetime (&result, p, &now)); p = "UTC+4:00 last tomorrow"; ASSERT (!parse_datetime (&result, p, &now)); p = "UTC+4:00 -4 today"; ASSERT (!parse_datetime (&result, p, &now)); /* And check correct usage of dayshifts */ now.tv_sec = 4711; now.tv_nsec = 1267; p = "UTC+400 tomorrow"; ASSERT (parse_datetime (&result, p, &now)); LOG (p, now, result); p = "UTC+400 +1 day"; ASSERT (parse_datetime (&result2, p, &now)); LOG (p, now, result2); ASSERT (result.tv_sec == result2.tv_sec && result.tv_nsec == result2.tv_nsec); p = "UTC+400 1 day hence"; ASSERT (parse_datetime (&result2, p, &now)); LOG (p, now, result2); ASSERT (result.tv_sec == result2.tv_sec && result.tv_nsec == result2.tv_nsec); now.tv_sec = 4711; now.tv_nsec = 1267; p = "UTC+400 yesterday"; ASSERT (parse_datetime (&result, p, &now)); LOG (p, now, result); p = "UTC+400 1 day ago"; ASSERT (parse_datetime (&result2, p, &now)); LOG (p, now, result2); ASSERT (result.tv_sec == result2.tv_sec && result.tv_nsec == result2.tv_nsec); now.tv_sec = 4711; now.tv_nsec = 1267; p = "UTC+400 now"; ASSERT (parse_datetime (&result, p, &now)); LOG (p, now, result); p = "UTC+400 +0 minutes"; /* silly, but simple "UTC+400" is different*/ ASSERT (parse_datetime (&result2, p, &now)); LOG (p, now, result2); ASSERT (result.tv_sec == result2.tv_sec && result.tv_nsec == result2.tv_nsec); /* Check that some "next Monday", "last Wednesday", etc. are correct. */ setenv ("TZ", "UTC0", 1); for (i = 0; day_table[i]; i++) { unsigned int thur2 = 7 * 24 * 3600; /* 2nd thursday */ char tmp[32]; sprintf (tmp, "NEXT %s", day_table[i]); now.tv_sec = thur2 + 4711; now.tv_nsec = 1267; ASSERT (parse_datetime (&result, tmp, &now)); LOG (tmp, now, result); ASSERT (result.tv_nsec == 0); ASSERT (result.tv_sec == thur2 + (i == 4 ? 7 : (i + 3) % 7) * 24 * 3600); sprintf (tmp, "LAST %s", day_table[i]); now.tv_sec = thur2 + 4711; now.tv_nsec = 1267; ASSERT (parse_datetime (&result, tmp, &now)); LOG (tmp, now, result); ASSERT (result.tv_nsec == 0); ASSERT (result.tv_sec == thur2 + ((i + 3) % 7 - 7) * 24 * 3600); } p = "THURSDAY UTC+00"; /* The epoch was on Thursday. */ now.tv_sec = 0; now.tv_nsec = 0; ASSERT (parse_datetime (&result, p, &now)); LOG (p, now, result); ASSERT (result.tv_sec == now.tv_sec && result.tv_nsec == now.tv_nsec); p = "FRIDAY UTC+00"; now.tv_sec = 0; now.tv_nsec = 0; ASSERT (parse_datetime (&result, p, &now)); LOG (p, now, result); ASSERT (result.tv_sec == 24 * 3600 && result.tv_nsec == now.tv_nsec); /* Exercise a sign-extension bug. Before July 2012, an input starting with a high-bit-set byte would be treated like "0". */ ASSERT ( ! parse_datetime (&result, "\xb0", &now)); /* Exercise TZ="" parsing code. */ /* These two would infloop or segfault before Feb 2014. */ ASSERT ( ! parse_datetime (&result, "TZ=\"\"\"", &now)); ASSERT ( ! parse_datetime (&result, "TZ=\"\" \"", &now)); /* Exercise invalid patterns. */ ASSERT ( ! parse_datetime (&result, "TZ=\"", &now)); ASSERT ( ! parse_datetime (&result, "TZ=\"\\\"", &now)); ASSERT ( ! parse_datetime (&result, "TZ=\"\\n", &now)); ASSERT ( ! parse_datetime (&result, "TZ=\"\\n\"", &now)); /* Exercise valid patterns. */ ASSERT ( parse_datetime (&result, "TZ=\"\"", &now)); ASSERT ( parse_datetime (&result, "TZ=\"\" ", &now)); ASSERT ( parse_datetime (&result, " TZ=\"\"", &now)); ASSERT ( parse_datetime (&result, "TZ=\"\\\\\"", &now)); ASSERT ( parse_datetime (&result, "TZ=\"\\\"\"", &now)); /* Outlandishly-long time zone abbreviations should not cause problems. */ { static char const bufprefix[] = "TZ=\""; enum { tzname_len = 2000 }; static char const bufsuffix[] = "0\" 1970-01-01 01:02:03.123456789"; enum { bufsize = sizeof bufprefix - 1 + tzname_len + sizeof bufsuffix }; char buf[bufsize]; memcpy (buf, bufprefix, sizeof bufprefix - 1); memset (buf + sizeof bufprefix - 1, 'X', tzname_len); strcpy (buf + bufsize - sizeof bufsuffix, bufsuffix); ASSERT (parse_datetime (&result, buf, &now)); LOG (buf, now, result); ASSERT (result.tv_sec == 1 * 60 * 60 + 2 * 60 + 3 && result.tv_nsec == 123456789); } return 0; }
164,891
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int usb_console_setup(struct console *co, char *options) { struct usbcons_info *info = &usbcons_info; int baud = 9600; int bits = 8; int parity = 'n'; int doflow = 0; int cflag = CREAD | HUPCL | CLOCAL; char *s; struct usb_serial *serial; struct usb_serial_port *port; int retval; struct tty_struct *tty = NULL; struct ktermios dummy; if (options) { baud = simple_strtoul(options, NULL, 10); s = options; while (*s >= '0' && *s <= '9') s++; if (*s) parity = *s++; if (*s) bits = *s++ - '0'; if (*s) doflow = (*s++ == 'r'); } /* Sane default */ if (baud == 0) baud = 9600; switch (bits) { case 7: cflag |= CS7; break; default: case 8: cflag |= CS8; break; } switch (parity) { case 'o': case 'O': cflag |= PARODD; break; case 'e': case 'E': cflag |= PARENB; break; } co->cflag = cflag; /* * no need to check the index here: if the index is wrong, console * code won't call us */ port = usb_serial_port_get_by_minor(co->index); if (port == NULL) { /* no device is connected yet, sorry :( */ pr_err("No USB device connected to ttyUSB%i\n", co->index); return -ENODEV; } serial = port->serial; retval = usb_autopm_get_interface(serial->interface); if (retval) goto error_get_interface; tty_port_tty_set(&port->port, NULL); info->port = port; ++port->port.count; if (!tty_port_initialized(&port->port)) { if (serial->type->set_termios) { /* * allocate a fake tty so the driver can initialize * the termios structure, then later call set_termios to * configure according to command line arguments */ tty = kzalloc(sizeof(*tty), GFP_KERNEL); if (!tty) { retval = -ENOMEM; goto reset_open_count; } kref_init(&tty->kref); tty->driver = usb_serial_tty_driver; tty->index = co->index; init_ldsem(&tty->ldisc_sem); spin_lock_init(&tty->files_lock); INIT_LIST_HEAD(&tty->tty_files); kref_get(&tty->driver->kref); __module_get(tty->driver->owner); tty->ops = &usb_console_fake_tty_ops; tty_init_termios(tty); tty_port_tty_set(&port->port, tty); } /* only call the device specific open if this * is the first time the port is opened */ retval = serial->type->open(NULL, port); if (retval) { dev_err(&port->dev, "could not open USB console port\n"); goto fail; } if (serial->type->set_termios) { tty->termios.c_cflag = cflag; tty_termios_encode_baud_rate(&tty->termios, baud, baud); memset(&dummy, 0, sizeof(struct ktermios)); serial->type->set_termios(tty, port, &dummy); tty_port_tty_set(&port->port, NULL); tty_kref_put(tty); } tty_port_set_initialized(&port->port, 1); } /* Now that any required fake tty operations are completed restore * the tty port count */ --port->port.count; /* The console is special in terms of closing the device so * indicate this port is now acting as a system console. */ port->port.console = 1; mutex_unlock(&serial->disc_mutex); return retval; fail: tty_port_tty_set(&port->port, NULL); tty_kref_put(tty); reset_open_count: port->port.count = 0; usb_autopm_put_interface(serial->interface); error_get_interface: usb_serial_put(serial); mutex_unlock(&serial->disc_mutex); return retval; } Commit Message: USB: serial: console: fix use-after-free after failed setup Make sure to reset the USB-console port pointer when console setup fails in order to avoid having the struct usb_serial be prematurely freed by the console code when the device is later disconnected. Fixes: 73e487fdb75f ("[PATCH] USB console: fix disconnection issues") Cc: stable <[email protected]> # 2.6.18 Acked-by: Greg Kroah-Hartman <[email protected]> Signed-off-by: Johan Hovold <[email protected]> CWE ID: CWE-416
static int usb_console_setup(struct console *co, char *options) { struct usbcons_info *info = &usbcons_info; int baud = 9600; int bits = 8; int parity = 'n'; int doflow = 0; int cflag = CREAD | HUPCL | CLOCAL; char *s; struct usb_serial *serial; struct usb_serial_port *port; int retval; struct tty_struct *tty = NULL; struct ktermios dummy; if (options) { baud = simple_strtoul(options, NULL, 10); s = options; while (*s >= '0' && *s <= '9') s++; if (*s) parity = *s++; if (*s) bits = *s++ - '0'; if (*s) doflow = (*s++ == 'r'); } /* Sane default */ if (baud == 0) baud = 9600; switch (bits) { case 7: cflag |= CS7; break; default: case 8: cflag |= CS8; break; } switch (parity) { case 'o': case 'O': cflag |= PARODD; break; case 'e': case 'E': cflag |= PARENB; break; } co->cflag = cflag; /* * no need to check the index here: if the index is wrong, console * code won't call us */ port = usb_serial_port_get_by_minor(co->index); if (port == NULL) { /* no device is connected yet, sorry :( */ pr_err("No USB device connected to ttyUSB%i\n", co->index); return -ENODEV; } serial = port->serial; retval = usb_autopm_get_interface(serial->interface); if (retval) goto error_get_interface; tty_port_tty_set(&port->port, NULL); info->port = port; ++port->port.count; if (!tty_port_initialized(&port->port)) { if (serial->type->set_termios) { /* * allocate a fake tty so the driver can initialize * the termios structure, then later call set_termios to * configure according to command line arguments */ tty = kzalloc(sizeof(*tty), GFP_KERNEL); if (!tty) { retval = -ENOMEM; goto reset_open_count; } kref_init(&tty->kref); tty->driver = usb_serial_tty_driver; tty->index = co->index; init_ldsem(&tty->ldisc_sem); spin_lock_init(&tty->files_lock); INIT_LIST_HEAD(&tty->tty_files); kref_get(&tty->driver->kref); __module_get(tty->driver->owner); tty->ops = &usb_console_fake_tty_ops; tty_init_termios(tty); tty_port_tty_set(&port->port, tty); } /* only call the device specific open if this * is the first time the port is opened */ retval = serial->type->open(NULL, port); if (retval) { dev_err(&port->dev, "could not open USB console port\n"); goto fail; } if (serial->type->set_termios) { tty->termios.c_cflag = cflag; tty_termios_encode_baud_rate(&tty->termios, baud, baud); memset(&dummy, 0, sizeof(struct ktermios)); serial->type->set_termios(tty, port, &dummy); tty_port_tty_set(&port->port, NULL); tty_kref_put(tty); } tty_port_set_initialized(&port->port, 1); } /* Now that any required fake tty operations are completed restore * the tty port count */ --port->port.count; /* The console is special in terms of closing the device so * indicate this port is now acting as a system console. */ port->port.console = 1; mutex_unlock(&serial->disc_mutex); return retval; fail: tty_port_tty_set(&port->port, NULL); tty_kref_put(tty); reset_open_count: port->port.count = 0; info->port = NULL; usb_autopm_put_interface(serial->interface); error_get_interface: usb_serial_put(serial); mutex_unlock(&serial->disc_mutex); return retval; }
167,687
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: RenderProcessHost* SharedWorkerDevToolsAgentHost::GetProcess() { return worker_host_ ? RenderProcessHost::FromID(worker_host_->process_id()) : nullptr; } Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable This keeps BrowserContext* and StoragePartition* instead of RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost upon closure of DevTools front-end. Bug: 801117, 783067, 780694 Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b Reviewed-on: https://chromium-review.googlesource.com/876657 Commit-Queue: Andrey Kosyakov <[email protected]> Reviewed-by: Dmitry Gozman <[email protected]> Cr-Commit-Position: refs/heads/master@{#531157} CWE ID: CWE-20
RenderProcessHost* SharedWorkerDevToolsAgentHost::GetProcess() {
172,789
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: v8::Local<v8::Value> PrivateScriptRunner::runDOMAttributeGetter(ScriptState* scriptState, ScriptState* scriptStateInUserScript, const char* className, const char* attributeName, v8::Local<v8::Value> holder) { v8::Isolate* isolate = scriptState->isolate(); v8::Local<v8::Object> classObject = classObjectOfPrivateScript(scriptState, className); v8::Local<v8::Value> descriptor; if (!classObject->GetOwnPropertyDescriptor(scriptState->context(), v8String(isolate, attributeName)).ToLocal(&descriptor) || !descriptor->IsObject()) { fprintf(stderr, "Private script error: Target DOM attribute getter was not found. (Class name = %s, Attribute name = %s)\n", className, attributeName); RELEASE_NOTREACHED(); } v8::Local<v8::Value> getter; if (!v8::Local<v8::Object>::Cast(descriptor)->Get(scriptState->context(), v8String(isolate, "get")).ToLocal(&getter) || !getter->IsFunction()) { fprintf(stderr, "Private script error: Target DOM attribute getter was not found. (Class name = %s, Attribute name = %s)\n", className, attributeName); RELEASE_NOTREACHED(); } initializeHolderIfNeeded(scriptState, classObject, holder); v8::TryCatch block(isolate); v8::Local<v8::Value> result; if (!V8ScriptRunner::callFunction(v8::Local<v8::Function>::Cast(getter), scriptState->getExecutionContext(), holder, 0, 0, isolate).ToLocal(&result)) { rethrowExceptionInPrivateScript(isolate, block, scriptStateInUserScript, ExceptionState::GetterContext, attributeName, className); block.ReThrow(); return v8::Local<v8::Value>(); } return result; } Commit Message: Blink-in-JS should not run micro tasks If Blink-in-JS runs micro tasks, there's a risk of causing a UXSS bug (see 645211 for concrete steps). This CL makes Blink-in-JS use callInternalFunction (instead of callFunction) to avoid running micro tasks after Blink-in-JS' callbacks. BUG=645211 Review-Url: https://codereview.chromium.org/2330843002 Cr-Commit-Position: refs/heads/master@{#417874} CWE ID: CWE-79
v8::Local<v8::Value> PrivateScriptRunner::runDOMAttributeGetter(ScriptState* scriptState, ScriptState* scriptStateInUserScript, const char* className, const char* attributeName, v8::Local<v8::Value> holder) { v8::Isolate* isolate = scriptState->isolate(); v8::Local<v8::Object> classObject = classObjectOfPrivateScript(scriptState, className); v8::Local<v8::Value> descriptor; if (!classObject->GetOwnPropertyDescriptor(scriptState->context(), v8String(isolate, attributeName)).ToLocal(&descriptor) || !descriptor->IsObject()) { fprintf(stderr, "Private script error: Target DOM attribute getter was not found. (Class name = %s, Attribute name = %s)\n", className, attributeName); RELEASE_NOTREACHED(); } v8::Local<v8::Value> getter; if (!v8::Local<v8::Object>::Cast(descriptor)->Get(scriptState->context(), v8String(isolate, "get")).ToLocal(&getter) || !getter->IsFunction()) { fprintf(stderr, "Private script error: Target DOM attribute getter was not found. (Class name = %s, Attribute name = %s)\n", className, attributeName); RELEASE_NOTREACHED(); } initializeHolderIfNeeded(scriptState, classObject, holder); v8::TryCatch block(isolate); v8::Local<v8::Value> result; if (!V8ScriptRunner::callInternalFunction(v8::Local<v8::Function>::Cast(getter), holder, 0, 0, isolate).ToLocal(&result)) { rethrowExceptionInPrivateScript(isolate, block, scriptStateInUserScript, ExceptionState::GetterContext, attributeName, className); block.ReThrow(); return v8::Local<v8::Value>(); } return result; }
172,075
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int rawsock_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t len, int flags) { int noblock = flags & MSG_DONTWAIT; struct sock *sk = sock->sk; struct sk_buff *skb; int copied; int rc; pr_debug("sock=%p sk=%p len=%zu flags=%d\n", sock, sk, len, flags); skb = skb_recv_datagram(sk, flags, noblock, &rc); if (!skb) return rc; msg->msg_namelen = 0; copied = skb->len; if (len < copied) { msg->msg_flags |= MSG_TRUNC; copied = len; } rc = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied); skb_free_datagram(sk, skb); return rc ? : copied; } Commit Message: net: rework recvmsg handler msg_name and msg_namelen logic This patch now always passes msg->msg_namelen as 0. recvmsg handlers must set msg_namelen to the proper size <= sizeof(struct sockaddr_storage) to return msg_name to the user. This prevents numerous uninitialized memory leaks we had in the recvmsg handlers and makes it harder for new code to accidentally leak uninitialized memory. Optimize for the case recvfrom is called with NULL as address. We don't need to copy the address at all, so set it to NULL before invoking the recvmsg handler. We can do so, because all the recvmsg handlers must cope with the case a plain read() is called on them. read() also sets msg_name to NULL. Also document these changes in include/linux/net.h as suggested by David Miller. Changes since RFC: Set msg->msg_name = NULL if user specified a NULL in msg_name but had a non-null msg_namelen in verify_iovec/verify_compat_iovec. This doesn't affect sendto as it would bail out earlier while trying to copy-in the address. It also more naturally reflects the logic by the callers of verify_iovec. With this change in place I could remove " if (!uaddr || msg_sys->msg_namelen == 0) msg->msg_name = NULL ". This change does not alter the user visible error logic as we ignore msg_namelen as long as msg_name is NULL. Also remove two unnecessary curly brackets in ___sys_recvmsg and change comments to netdev style. Cc: David Miller <[email protected]> Suggested-by: Eric Dumazet <[email protected]> Signed-off-by: Hannes Frederic Sowa <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-20
static int rawsock_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t len, int flags) { int noblock = flags & MSG_DONTWAIT; struct sock *sk = sock->sk; struct sk_buff *skb; int copied; int rc; pr_debug("sock=%p sk=%p len=%zu flags=%d\n", sock, sk, len, flags); skb = skb_recv_datagram(sk, flags, noblock, &rc); if (!skb) return rc; copied = skb->len; if (len < copied) { msg->msg_flags |= MSG_TRUNC; copied = len; } rc = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied); skb_free_datagram(sk, skb); return rc ? : copied; }
166,510
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void handle_ld_nf(u32 insn, struct pt_regs *regs) { int rd = ((insn >> 25) & 0x1f); int from_kernel = (regs->tstate & TSTATE_PRIV) != 0; unsigned long *reg; perf_sw_event(PERF_COUNT_SW_EMULATION_FAULTS, 1, 0, regs, 0); maybe_flush_windows(0, 0, rd, from_kernel); reg = fetch_reg_addr(rd, regs); if (from_kernel || rd < 16) { reg[0] = 0; if ((insn & 0x780000) == 0x180000) reg[1] = 0; } else if (test_thread_flag(TIF_32BIT)) { put_user(0, (int __user *) reg); if ((insn & 0x780000) == 0x180000) put_user(0, ((int __user *) reg) + 1); } else { put_user(0, (unsigned long __user *) reg); if ((insn & 0x780000) == 0x180000) put_user(0, (unsigned long __user *) reg + 1); } advance(regs); } Commit Message: perf: Remove the nmi parameter from the swevent and overflow interface The nmi parameter indicated if we could do wakeups from the current context, if not, we would set some state and self-IPI and let the resulting interrupt do the wakeup. For the various event classes: - hardware: nmi=0; PMI is in fact an NMI or we run irq_work_run from the PMI-tail (ARM etc.) - tracepoint: nmi=0; since tracepoint could be from NMI context. - software: nmi=[0,1]; some, like the schedule thing cannot perform wakeups, and hence need 0. As one can see, there is very little nmi=1 usage, and the down-side of not using it is that on some platforms some software events can have a jiffy delay in wakeup (when arch_irq_work_raise isn't implemented). The up-side however is that we can remove the nmi parameter and save a bunch of conditionals in fast paths. Signed-off-by: Peter Zijlstra <[email protected]> Cc: Michael Cree <[email protected]> Cc: Will Deacon <[email protected]> Cc: Deng-Cheng Zhu <[email protected]> Cc: Anton Blanchard <[email protected]> Cc: Eric B Munson <[email protected]> Cc: Heiko Carstens <[email protected]> Cc: Paul Mundt <[email protected]> Cc: David S. Miller <[email protected]> Cc: Frederic Weisbecker <[email protected]> Cc: Jason Wessel <[email protected]> Cc: Don Zickus <[email protected]> Link: http://lkml.kernel.org/n/[email protected] Signed-off-by: Ingo Molnar <[email protected]> CWE ID: CWE-399
void handle_ld_nf(u32 insn, struct pt_regs *regs) { int rd = ((insn >> 25) & 0x1f); int from_kernel = (regs->tstate & TSTATE_PRIV) != 0; unsigned long *reg; perf_sw_event(PERF_COUNT_SW_EMULATION_FAULTS, 1, regs, 0); maybe_flush_windows(0, 0, rd, from_kernel); reg = fetch_reg_addr(rd, regs); if (from_kernel || rd < 16) { reg[0] = 0; if ((insn & 0x780000) == 0x180000) reg[1] = 0; } else if (test_thread_flag(TIF_32BIT)) { put_user(0, (int __user *) reg); if ((insn & 0x780000) == 0x180000) put_user(0, ((int __user *) reg) + 1); } else { put_user(0, (unsigned long __user *) reg); if ((insn & 0x780000) == 0x180000) put_user(0, (unsigned long __user *) reg + 1); } advance(regs); }
165,807
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: RunLoop::RunLoop() : delegate_(tls_delegate.Get().Get()), origin_task_runner_(ThreadTaskRunnerHandle::Get()), weak_factory_(this) { DCHECK(delegate_) << "A RunLoop::Delegate must be bound to this thread prior " "to using RunLoop."; DCHECK(origin_task_runner_); } Commit Message: Introduce RunLoop::Type::NESTABLE_TASKS_ALLOWED to replace MessageLoop::ScopedNestableTaskAllower. (as well as MessageLoop::SetNestableTasksAllowed()) Surveying usage: the scoped object is always instantiated right before RunLoop().Run(). The intent is really to allow nestable tasks in that RunLoop so it's better to explicitly label that RunLoop as such and it allows us to break the last dependency that forced some RunLoop users to use MessageLoop APIs. There's also the odd case of allowing nestable tasks for loops that are reentrant from a native task (without going through RunLoop), these are the minority but will have to be handled (after cleaning up the majority of cases that are RunLoop induced). As highlighted by robliao@ in https://chromium-review.googlesource.com/c/600517 (which was merged in this CL). [email protected] Bug: 750779 Change-Id: I43d122c93ec903cff3a6fe7b77ec461ea0656448 Reviewed-on: https://chromium-review.googlesource.com/594713 Commit-Queue: Gabriel Charette <[email protected]> Reviewed-by: Robert Liao <[email protected]> Reviewed-by: danakj <[email protected]> Cr-Commit-Position: refs/heads/master@{#492263} CWE ID:
RunLoop::RunLoop() RunLoop::RunLoop(Type type) : delegate_(tls_delegate.Get().Get()), type_(type), origin_task_runner_(ThreadTaskRunnerHandle::Get()), weak_factory_(this) { DCHECK(delegate_) << "A RunLoop::Delegate must be bound to this thread prior " "to using RunLoop."; DCHECK(origin_task_runner_); DCHECK(IsNestingAllowedOnCurrentThread() || type_ != Type::kNestableTasksAllowed); }
171,869
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: find_insert(png_const_charp what, png_charp param) { png_uint_32 chunk = 0; png_charp parameter_list[1024]; int i, nparams; /* Assemble the chunk name */ for (i=0; i<4; ++i) { char ch = what[i]; if ((ch >= 65 && ch <= 90) || (ch >= 97 && ch <= 122)) chunk = (chunk << 8) + what[i]; else break; } if (i < 4 || what[4] != 0) { fprintf(stderr, "makepng --insert \"%s\": invalid chunk name\n", what); exit(1); } /* Assemble the parameter list. */ nparams = find_parameters(what, param, parameter_list, 1024); # define CHUNK(a,b,c,d) (((a)<<24)+((b)<<16)+((c)<<8)+(d)) switch (chunk) { case CHUNK(105,67,67,80): /* iCCP */ if (nparams == 2) return make_insert(what, insert_iCCP, nparams, parameter_list); break; case CHUNK(116,69,88,116): /* tEXt */ if (nparams == 2) return make_insert(what, insert_tEXt, nparams, parameter_list); break; case CHUNK(122,84,88,116): /* zTXt */ if (nparams == 2) return make_insert(what, insert_zTXt, nparams, parameter_list); break; case CHUNK(105,84,88,116): /* iTXt */ if (nparams == 4) return make_insert(what, insert_iTXt, nparams, parameter_list); break; case CHUNK(104,73,83,84): /* hIST */ if (nparams <= 256) return make_insert(what, insert_hIST, nparams, parameter_list); break; #if 0 case CHUNK(115,80,76,84): /* sPLT */ return make_insert(what, insert_sPLT, nparams, parameter_list); #endif default: fprintf(stderr, "makepng --insert \"%s\": unrecognized chunk name\n", what); exit(1); } bad_parameter_count(what, nparams); return NULL; } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
find_insert(png_const_charp what, png_charp param) { png_uint_32 chunk = 0; png_charp parameter_list[1024]; int i, nparams; /* Assemble the chunk name */ for (i=0; i<4; ++i) { char ch = what[i]; if ((ch >= 65 && ch <= 90) || (ch >= 97 && ch <= 122)) chunk = (chunk << 8) + what[i]; else break; } if (i < 4 || what[4] != 0) { fprintf(stderr, "makepng --insert \"%s\": invalid chunk name\n", what); exit(1); } /* Assemble the parameter list. */ nparams = find_parameters(what, param, parameter_list, 1024); # define CHUNK(a,b,c,d) (((a)<<24)+((b)<<16)+((c)<<8)+(d)) switch (chunk) { case CHUNK(105,67,67,80): /* iCCP */ if (nparams == 2) return make_insert(what, insert_iCCP, nparams, parameter_list); break; case CHUNK(116,69,88,116): /* tEXt */ if (nparams == 2) return make_insert(what, insert_tEXt, nparams, parameter_list); break; case CHUNK(122,84,88,116): /* zTXt */ if (nparams == 2) return make_insert(what, insert_zTXt, nparams, parameter_list); break; case CHUNK(105,84,88,116): /* iTXt */ if (nparams == 4) return make_insert(what, insert_iTXt, nparams, parameter_list); break; case CHUNK(104,73,83,84): /* hIST */ if (nparams <= 256) return make_insert(what, insert_hIST, nparams, parameter_list); break; case CHUNK(115,66,73,84): /* sBIT */ if (nparams <= 4) return make_insert(what, insert_sBIT, nparams, parameter_list); break; #if 0 case CHUNK(115,80,76,84): /* sPLT */ return make_insert(what, insert_sPLT, nparams, parameter_list); #endif default: fprintf(stderr, "makepng --insert \"%s\": unrecognized chunk name\n", what); exit(1); } bad_parameter_count(what, nparams); return NULL; }
173,578
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: SYSCALL_DEFINE6(recvfrom, int, fd, void __user *, ubuf, size_t, size, unsigned int, flags, struct sockaddr __user *, addr, int __user *, addr_len) { struct socket *sock; struct iovec iov; struct msghdr msg; struct sockaddr_storage address; int err, err2; int fput_needed; if (size > INT_MAX) size = INT_MAX; sock = sockfd_lookup_light(fd, &err, &fput_needed); if (!sock) goto out; msg.msg_control = NULL; msg.msg_controllen = 0; msg.msg_iovlen = 1; msg.msg_iov = &iov; iov.iov_len = size; iov.iov_base = ubuf; msg.msg_name = (struct sockaddr *)&address; msg.msg_namelen = sizeof(address); if (sock->file->f_flags & O_NONBLOCK) flags |= MSG_DONTWAIT; err = sock_recvmsg(sock, &msg, size, flags); if (err >= 0 && addr != NULL) { err2 = move_addr_to_user(&address, msg.msg_namelen, addr, addr_len); if (err2 < 0) err = err2; } fput_light(sock->file, fput_needed); out: return err; } Commit Message: net: rework recvmsg handler msg_name and msg_namelen logic This patch now always passes msg->msg_namelen as 0. recvmsg handlers must set msg_namelen to the proper size <= sizeof(struct sockaddr_storage) to return msg_name to the user. This prevents numerous uninitialized memory leaks we had in the recvmsg handlers and makes it harder for new code to accidentally leak uninitialized memory. Optimize for the case recvfrom is called with NULL as address. We don't need to copy the address at all, so set it to NULL before invoking the recvmsg handler. We can do so, because all the recvmsg handlers must cope with the case a plain read() is called on them. read() also sets msg_name to NULL. Also document these changes in include/linux/net.h as suggested by David Miller. Changes since RFC: Set msg->msg_name = NULL if user specified a NULL in msg_name but had a non-null msg_namelen in verify_iovec/verify_compat_iovec. This doesn't affect sendto as it would bail out earlier while trying to copy-in the address. It also more naturally reflects the logic by the callers of verify_iovec. With this change in place I could remove " if (!uaddr || msg_sys->msg_namelen == 0) msg->msg_name = NULL ". This change does not alter the user visible error logic as we ignore msg_namelen as long as msg_name is NULL. Also remove two unnecessary curly brackets in ___sys_recvmsg and change comments to netdev style. Cc: David Miller <[email protected]> Suggested-by: Eric Dumazet <[email protected]> Signed-off-by: Hannes Frederic Sowa <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-20
SYSCALL_DEFINE6(recvfrom, int, fd, void __user *, ubuf, size_t, size, unsigned int, flags, struct sockaddr __user *, addr, int __user *, addr_len) { struct socket *sock; struct iovec iov; struct msghdr msg; struct sockaddr_storage address; int err, err2; int fput_needed; if (size > INT_MAX) size = INT_MAX; sock = sockfd_lookup_light(fd, &err, &fput_needed); if (!sock) goto out; msg.msg_control = NULL; msg.msg_controllen = 0; msg.msg_iovlen = 1; msg.msg_iov = &iov; iov.iov_len = size; iov.iov_base = ubuf; /* Save some cycles and don't copy the address if not needed */ msg.msg_name = addr ? (struct sockaddr *)&address : NULL; /* We assume all kernel code knows the size of sockaddr_storage */ msg.msg_namelen = 0; if (sock->file->f_flags & O_NONBLOCK) flags |= MSG_DONTWAIT; err = sock_recvmsg(sock, &msg, size, flags); if (err >= 0 && addr != NULL) { err2 = move_addr_to_user(&address, msg.msg_namelen, addr, addr_len); if (err2 < 0) err = err2; } fput_light(sock->file, fput_needed); out: return err; }
166,515
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: fm_mgr_config_mgr_connect ( fm_config_conx_hdl *hdl, fm_mgr_type_t mgr ) { char s_path[256]; char c_path[256]; char *mgr_prefix; p_hsm_com_client_hdl_t *mgr_hdl; pid_t pid; memset(s_path,0,sizeof(s_path)); memset(c_path,0,sizeof(c_path)); pid = getpid(); switch ( mgr ) { case FM_MGR_SM: mgr_prefix = HSM_FM_SCK_SM; mgr_hdl = &hdl->sm_hdl; break; case FM_MGR_PM: mgr_prefix = HSM_FM_SCK_PM; mgr_hdl = &hdl->pm_hdl; break; case FM_MGR_FE: mgr_prefix = HSM_FM_SCK_FE; mgr_hdl = &hdl->fe_hdl; break; default: return FM_CONF_INIT_ERR; } sprintf(s_path,"%s%s%d",HSM_FM_SCK_PREFIX,mgr_prefix,hdl->instance); sprintf(c_path,"%s%s%d_C_%lu",HSM_FM_SCK_PREFIX,mgr_prefix, hdl->instance, (long unsigned)pid); if ( *mgr_hdl == NULL ) { if ( hcom_client_init(mgr_hdl,s_path,c_path,32768) != HSM_COM_OK ) { return FM_CONF_INIT_ERR; } } if ( hcom_client_connect(*mgr_hdl) == HSM_COM_OK ) { hdl->conx_mask |= mgr; return FM_CONF_OK; } return FM_CONF_CONX_ERR; } Commit Message: Fix scripts and code that use well-known tmp files. CWE ID: CWE-362
fm_mgr_config_mgr_connect ( fm_config_conx_hdl *hdl, fm_mgr_type_t mgr ) { char s_path[256]; char c_path[256]; char *mgr_prefix; p_hsm_com_client_hdl_t *mgr_hdl; memset(s_path,0,sizeof(s_path)); memset(c_path,0,sizeof(c_path)); switch ( mgr ) { case FM_MGR_SM: mgr_prefix = HSM_FM_SCK_SM; mgr_hdl = &hdl->sm_hdl; break; case FM_MGR_PM: mgr_prefix = HSM_FM_SCK_PM; mgr_hdl = &hdl->pm_hdl; break; case FM_MGR_FE: mgr_prefix = HSM_FM_SCK_FE; mgr_hdl = &hdl->fe_hdl; break; default: return FM_CONF_INIT_ERR; } sprintf(s_path,"%s%s%d",HSM_FM_SCK_PREFIX,mgr_prefix,hdl->instance); sprintf(c_path,"%s%s%d_C_XXXXXX",HSM_FM_SCK_PREFIX,mgr_prefix,hdl->instance); if ( *mgr_hdl == NULL ) { if ( hcom_client_init(mgr_hdl,s_path,c_path,32768) != HSM_COM_OK ) { return FM_CONF_INIT_ERR; } } if ( hcom_client_connect(*mgr_hdl) == HSM_COM_OK ) { hdl->conx_mask |= mgr; return FM_CONF_OK; } return FM_CONF_CONX_ERR; }
170,131
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static MagickBooleanType TraceBezier(MVGInfo *mvg_info, const size_t number_coordinates) { double alpha, *coefficients, weight; PointInfo end, point, *points; PrimitiveInfo *primitive_info; register PrimitiveInfo *p; register ssize_t i, j; size_t control_points, quantum; /* Allocate coefficients. */ primitive_info=(*mvg_info->primitive_info)+mvg_info->offset; quantum=number_coordinates; for (i=0; i < (ssize_t) number_coordinates; i++) { for (j=i+1; j < (ssize_t) number_coordinates; j++) { alpha=fabs(primitive_info[j].point.x-primitive_info[i].point.x); if (alpha > (double) SSIZE_MAX) { (void) ThrowMagickException(mvg_info->exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",""); return(MagickFalse); } if (alpha > (double) quantum) quantum=(size_t) alpha; alpha=fabs(primitive_info[j].point.y-primitive_info[i].point.y); if (alpha > (double) SSIZE_MAX) { (void) ThrowMagickException(mvg_info->exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",""); return(MagickFalse); } if (alpha > (double) quantum) quantum=(size_t) alpha; } } quantum=MagickMin(quantum/number_coordinates,BezierQuantum); primitive_info=(*mvg_info->primitive_info)+mvg_info->offset; coefficients=(double *) AcquireQuantumMemory(number_coordinates, sizeof(*coefficients)); points=(PointInfo *) AcquireQuantumMemory(quantum,number_coordinates* sizeof(*points)); if ((coefficients == (double *) NULL) || (points == (PointInfo *) NULL)) { if (points != (PointInfo *) NULL) points=(PointInfo *) RelinquishMagickMemory(points); if (coefficients != (double *) NULL) coefficients=(double *) RelinquishMagickMemory(coefficients); (void) ThrowMagickException(mvg_info->exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",""); return(MagickFalse); } control_points=quantum*number_coordinates; if (CheckPrimitiveExtent(mvg_info,control_points+1) == MagickFalse) { points=(PointInfo *) RelinquishMagickMemory(points); coefficients=(double *) RelinquishMagickMemory(coefficients); return(MagickFalse); } /* Compute bezier points. */ end=primitive_info[number_coordinates-1].point; for (i=0; i < (ssize_t) number_coordinates; i++) coefficients[i]=Permutate((ssize_t) number_coordinates-1,i); weight=0.0; for (i=0; i < (ssize_t) control_points; i++) { p=primitive_info; point.x=0.0; point.y=0.0; alpha=pow((double) (1.0-weight),(double) number_coordinates-1.0); for (j=0; j < (ssize_t) number_coordinates; j++) { point.x+=alpha*coefficients[j]*p->point.x; point.y+=alpha*coefficients[j]*p->point.y; alpha*=weight/(1.0-weight); p++; } points[i]=point; weight+=1.0/control_points; } /* Bezier curves are just short segmented polys. */ p=primitive_info; for (i=0; i < (ssize_t) control_points; i++) { if (TracePoint(p,points[i]) == MagickFalse) { points=(PointInfo *) RelinquishMagickMemory(points); coefficients=(double *) RelinquishMagickMemory(coefficients); return(MagickFalse); } p+=p->coordinates; } if (TracePoint(p,end) == MagickFalse) { points=(PointInfo *) RelinquishMagickMemory(points); coefficients=(double *) RelinquishMagickMemory(coefficients); return(MagickFalse); } p+=p->coordinates; primitive_info->coordinates=(size_t) (p-primitive_info); primitive_info->closed_subpath=MagickFalse; for (i=0; i < (ssize_t) primitive_info->coordinates; i++) { p->primitive=primitive_info->primitive; p--; } points=(PointInfo *) RelinquishMagickMemory(points); coefficients=(double *) RelinquishMagickMemory(coefficients); return(MagickTrue); } Commit Message: ... CWE ID:
static MagickBooleanType TraceBezier(MVGInfo *mvg_info, const size_t number_coordinates) { double alpha, *coefficients, weight; PointInfo end, point, *points; PrimitiveInfo *primitive_info; register PrimitiveInfo *p; register ssize_t i, j; size_t control_points, quantum; /* Allocate coefficients. */ primitive_info=(*mvg_info->primitive_info)+mvg_info->offset; quantum=number_coordinates; for (i=0; i < (ssize_t) number_coordinates; i++) { for (j=i+1; j < (ssize_t) number_coordinates; j++) { alpha=fabs(primitive_info[j].point.x-primitive_info[i].point.x); if (alpha > (double) SSIZE_MAX) { (void) ThrowMagickException(mvg_info->exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",""); return(MagickFalse); } if (alpha > (double) quantum) quantum=(size_t) alpha; alpha=fabs(primitive_info[j].point.y-primitive_info[i].point.y); if (alpha > (double) SSIZE_MAX) { (void) ThrowMagickException(mvg_info->exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",""); return(MagickFalse); } if (alpha > (double) quantum) quantum=(size_t) alpha; } } primitive_info=(*mvg_info->primitive_info)+mvg_info->offset; quantum=MagickMin(quantum/number_coordinates,BezierQuantum); coefficients=(double *) AcquireQuantumMemory(number_coordinates, sizeof(*coefficients)); points=(PointInfo *) AcquireQuantumMemory(quantum,number_coordinates* sizeof(*points)); if ((coefficients == (double *) NULL) || (points == (PointInfo *) NULL)) { if (points != (PointInfo *) NULL) points=(PointInfo *) RelinquishMagickMemory(points); if (coefficients != (double *) NULL) coefficients=(double *) RelinquishMagickMemory(coefficients); (void) ThrowMagickException(mvg_info->exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",""); return(MagickFalse); } control_points=quantum*number_coordinates; if (CheckPrimitiveExtent(mvg_info,control_points+1) == MagickFalse) { points=(PointInfo *) RelinquishMagickMemory(points); coefficients=(double *) RelinquishMagickMemory(coefficients); return(MagickFalse); } primitive_info=(*mvg_info->primitive_info)+mvg_info->offset; /* Compute bezier points. */ end=primitive_info[number_coordinates-1].point; for (i=0; i < (ssize_t) number_coordinates; i++) coefficients[i]=Permutate((ssize_t) number_coordinates-1,i); weight=0.0; for (i=0; i < (ssize_t) control_points; i++) { p=primitive_info; point.x=0.0; point.y=0.0; alpha=pow((double) (1.0-weight),(double) number_coordinates-1.0); for (j=0; j < (ssize_t) number_coordinates; j++) { point.x+=alpha*coefficients[j]*p->point.x; point.y+=alpha*coefficients[j]*p->point.y; alpha*=weight/(1.0-weight); p++; } points[i]=point; weight+=1.0/control_points; } /* Bezier curves are just short segmented polys. */ p=primitive_info; for (i=0; i < (ssize_t) control_points; i++) { if (TracePoint(p,points[i]) == MagickFalse) { points=(PointInfo *) RelinquishMagickMemory(points); coefficients=(double *) RelinquishMagickMemory(coefficients); return(MagickFalse); } p+=p->coordinates; } if (TracePoint(p,end) == MagickFalse) { points=(PointInfo *) RelinquishMagickMemory(points); coefficients=(double *) RelinquishMagickMemory(coefficients); return(MagickFalse); } p+=p->coordinates; primitive_info->coordinates=(size_t) (p-primitive_info); primitive_info->closed_subpath=MagickFalse; for (i=0; i < (ssize_t) primitive_info->coordinates; i++) { p->primitive=primitive_info->primitive; p--; } points=(PointInfo *) RelinquishMagickMemory(points); coefficients=(double *) RelinquishMagickMemory(coefficients); return(MagickTrue); }
169,485
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void MarkingVisitor::ConservativelyMarkHeader(HeapObjectHeader* header) { const GCInfo* gc_info = ThreadHeap::GcInfo(header->GcInfoIndex()); if (gc_info->HasVTable() && !VTableInitialized(header->Payload())) { MarkHeaderNoTracing(header); #if DCHECK_IS_ON() DCHECK(IsUninitializedMemory(header->Payload(), header->PayloadSize())); #endif } else { MarkHeader(header, gc_info->trace_); } } Commit Message: [oilpan] Fix GCInfoTable for multiple threads Previously, grow and access from different threads could lead to a race on the table backing; see bug. - Rework the table to work on an existing reservation. - Commit upon growing, avoiding any copies. Drive-by: Fix over-allocation of table. Bug: chromium:841280 Change-Id: I329cb6f40091e14e8c05334ba1104a9440c31d43 Reviewed-on: https://chromium-review.googlesource.com/1061525 Commit-Queue: Michael Lippautz <[email protected]> Reviewed-by: Kentaro Hara <[email protected]> Cr-Commit-Position: refs/heads/master@{#560434} CWE ID: CWE-362
void MarkingVisitor::ConservativelyMarkHeader(HeapObjectHeader* header) { const GCInfo* gc_info = GCInfoTable::Get().GCInfoFromIndex(header->GcInfoIndex()); if (gc_info->HasVTable() && !VTableInitialized(header->Payload())) { MarkHeaderNoTracing(header); #if DCHECK_IS_ON() DCHECK(IsUninitializedMemory(header->Payload(), header->PayloadSize())); #endif } else { MarkHeader(header, gc_info->trace_); } }
173,141
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int lock_flags) __releases(RCU) { struct inode *inode = VFS_I(ip); struct xfs_mount *mp = ip->i_mount; int error; /* * check for re-use of an inode within an RCU grace period due to the * radix tree nodes not being updated yet. We monitor for this by * setting the inode number to zero before freeing the inode structure. * If the inode has been reallocated and set up, then the inode number * will not match, so check for that, too. */ spin_lock(&ip->i_flags_lock); if (ip->i_ino != ino) { trace_xfs_iget_skip(ip); XFS_STATS_INC(mp, xs_ig_frecycle); error = -EAGAIN; goto out_error; } /* * If we are racing with another cache hit that is currently * instantiating this inode or currently recycling it out of * reclaimabe state, wait for the initialisation to complete * before continuing. * * XXX(hch): eventually we should do something equivalent to * wait_on_inode to wait for these flags to be cleared * instead of polling for it. */ if (ip->i_flags & (XFS_INEW|XFS_IRECLAIM)) { trace_xfs_iget_skip(ip); XFS_STATS_INC(mp, xs_ig_frecycle); error = -EAGAIN; goto out_error; } /* * If lookup is racing with unlink return an error immediately. */ if (VFS_I(ip)->i_mode == 0 && !(flags & XFS_IGET_CREATE)) { error = -ENOENT; goto out_error; } /* * If IRECLAIMABLE is set, we've torn down the VFS inode already. * Need to carefully get it back into useable state. */ if (ip->i_flags & XFS_IRECLAIMABLE) { trace_xfs_iget_reclaim(ip); if (flags & XFS_IGET_INCORE) { error = -EAGAIN; goto out_error; } /* * We need to set XFS_IRECLAIM to prevent xfs_reclaim_inode * from stomping over us while we recycle the inode. We can't * clear the radix tree reclaimable tag yet as it requires * pag_ici_lock to be held exclusive. */ ip->i_flags |= XFS_IRECLAIM; spin_unlock(&ip->i_flags_lock); rcu_read_unlock(); error = xfs_reinit_inode(mp, inode); if (error) { bool wake; /* * Re-initializing the inode failed, and we are in deep * trouble. Try to re-add it to the reclaim list. */ rcu_read_lock(); spin_lock(&ip->i_flags_lock); wake = !!__xfs_iflags_test(ip, XFS_INEW); ip->i_flags &= ~(XFS_INEW | XFS_IRECLAIM); if (wake) wake_up_bit(&ip->i_flags, __XFS_INEW_BIT); ASSERT(ip->i_flags & XFS_IRECLAIMABLE); trace_xfs_iget_reclaim_fail(ip); goto out_error; } spin_lock(&pag->pag_ici_lock); spin_lock(&ip->i_flags_lock); /* * Clear the per-lifetime state in the inode as we are now * effectively a new inode and need to return to the initial * state before reuse occurs. */ ip->i_flags &= ~XFS_IRECLAIM_RESET_FLAGS; ip->i_flags |= XFS_INEW; xfs_inode_clear_reclaim_tag(pag, ip->i_ino); inode->i_state = I_NEW; ASSERT(!rwsem_is_locked(&inode->i_rwsem)); init_rwsem(&inode->i_rwsem); spin_unlock(&ip->i_flags_lock); spin_unlock(&pag->pag_ici_lock); } else { /* If the VFS inode is being torn down, pause and try again. */ if (!igrab(inode)) { trace_xfs_iget_skip(ip); error = -EAGAIN; goto out_error; } /* We've got a live one. */ spin_unlock(&ip->i_flags_lock); rcu_read_unlock(); trace_xfs_iget_hit(ip); } if (lock_flags != 0) xfs_ilock(ip, lock_flags); if (!(flags & XFS_IGET_INCORE)) xfs_iflags_clear(ip, XFS_ISTALE | XFS_IDONTCACHE); XFS_STATS_INC(mp, xs_ig_found); return 0; out_error: spin_unlock(&ip->i_flags_lock); rcu_read_unlock(); return error; } Commit Message: xfs: validate cached inodes are free when allocated A recent fuzzed filesystem image cached random dcache corruption when the reproducer was run. This often showed up as panics in lookup_slow() on a null inode->i_ops pointer when doing pathwalks. BUG: unable to handle kernel NULL pointer dereference at 0000000000000000 .... Call Trace: lookup_slow+0x44/0x60 walk_component+0x3dd/0x9f0 link_path_walk+0x4a7/0x830 path_lookupat+0xc1/0x470 filename_lookup+0x129/0x270 user_path_at_empty+0x36/0x40 path_listxattr+0x98/0x110 SyS_listxattr+0x13/0x20 do_syscall_64+0xf5/0x280 entry_SYSCALL_64_after_hwframe+0x42/0xb7 but had many different failure modes including deadlocks trying to lock the inode that was just allocated or KASAN reports of use-after-free violations. The cause of the problem was a corrupt INOBT on a v4 fs where the root inode was marked as free in the inobt record. Hence when we allocated an inode, it chose the root inode to allocate, found it in the cache and re-initialised it. We recently fixed a similar inode allocation issue caused by inobt record corruption problem in xfs_iget_cache_miss() in commit ee457001ed6c ("xfs: catch inode allocation state mismatch corruption"). This change adds similar checks to the cache-hit path to catch it, and turns the reproducer into a corruption shutdown situation. Reported-by: Wen Xu <[email protected]> Signed-Off-By: Dave Chinner <[email protected]> Reviewed-by: Christoph Hellwig <[email protected]> Reviewed-by: Carlos Maiolino <[email protected]> Reviewed-by: Darrick J. Wong <[email protected]> [darrick: fix typos in comment] Signed-off-by: Darrick J. Wong <[email protected]> CWE ID: CWE-476
int lock_flags) __releases(RCU) { struct inode *inode = VFS_I(ip); struct xfs_mount *mp = ip->i_mount; int error; /* * check for re-use of an inode within an RCU grace period due to the * radix tree nodes not being updated yet. We monitor for this by * setting the inode number to zero before freeing the inode structure. * If the inode has been reallocated and set up, then the inode number * will not match, so check for that, too. */ spin_lock(&ip->i_flags_lock); if (ip->i_ino != ino) { trace_xfs_iget_skip(ip); XFS_STATS_INC(mp, xs_ig_frecycle); error = -EAGAIN; goto out_error; } /* * If we are racing with another cache hit that is currently * instantiating this inode or currently recycling it out of * reclaimabe state, wait for the initialisation to complete * before continuing. * * XXX(hch): eventually we should do something equivalent to * wait_on_inode to wait for these flags to be cleared * instead of polling for it. */ if (ip->i_flags & (XFS_INEW|XFS_IRECLAIM)) { trace_xfs_iget_skip(ip); XFS_STATS_INC(mp, xs_ig_frecycle); error = -EAGAIN; goto out_error; } /* * Check the inode free state is valid. This also detects lookup * racing with unlinks. */ error = xfs_iget_check_free_state(ip, flags); if (error) goto out_error; /* * If IRECLAIMABLE is set, we've torn down the VFS inode already. * Need to carefully get it back into useable state. */ if (ip->i_flags & XFS_IRECLAIMABLE) { trace_xfs_iget_reclaim(ip); if (flags & XFS_IGET_INCORE) { error = -EAGAIN; goto out_error; } /* * We need to set XFS_IRECLAIM to prevent xfs_reclaim_inode * from stomping over us while we recycle the inode. We can't * clear the radix tree reclaimable tag yet as it requires * pag_ici_lock to be held exclusive. */ ip->i_flags |= XFS_IRECLAIM; spin_unlock(&ip->i_flags_lock); rcu_read_unlock(); error = xfs_reinit_inode(mp, inode); if (error) { bool wake; /* * Re-initializing the inode failed, and we are in deep * trouble. Try to re-add it to the reclaim list. */ rcu_read_lock(); spin_lock(&ip->i_flags_lock); wake = !!__xfs_iflags_test(ip, XFS_INEW); ip->i_flags &= ~(XFS_INEW | XFS_IRECLAIM); if (wake) wake_up_bit(&ip->i_flags, __XFS_INEW_BIT); ASSERT(ip->i_flags & XFS_IRECLAIMABLE); trace_xfs_iget_reclaim_fail(ip); goto out_error; } spin_lock(&pag->pag_ici_lock); spin_lock(&ip->i_flags_lock); /* * Clear the per-lifetime state in the inode as we are now * effectively a new inode and need to return to the initial * state before reuse occurs. */ ip->i_flags &= ~XFS_IRECLAIM_RESET_FLAGS; ip->i_flags |= XFS_INEW; xfs_inode_clear_reclaim_tag(pag, ip->i_ino); inode->i_state = I_NEW; ASSERT(!rwsem_is_locked(&inode->i_rwsem)); init_rwsem(&inode->i_rwsem); spin_unlock(&ip->i_flags_lock); spin_unlock(&pag->pag_ici_lock); } else { /* If the VFS inode is being torn down, pause and try again. */ if (!igrab(inode)) { trace_xfs_iget_skip(ip); error = -EAGAIN; goto out_error; } /* We've got a live one. */ spin_unlock(&ip->i_flags_lock); rcu_read_unlock(); trace_xfs_iget_hit(ip); } if (lock_flags != 0) xfs_ilock(ip, lock_flags); if (!(flags & XFS_IGET_INCORE)) xfs_iflags_clear(ip, XFS_ISTALE | XFS_IDONTCACHE); XFS_STATS_INC(mp, xs_ig_found); return 0; out_error: spin_unlock(&ip->i_flags_lock); rcu_read_unlock(); return error; }
169,165
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static PHP_FUNCTION(gzopen) { char *filename; char *mode; int filename_len, mode_len; int flags = REPORT_ERRORS; php_stream *stream; long use_include_path = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss|l", &filename, &filename_len, &mode, &mode_len, &use_include_path) == FAILURE) { return; } if (use_include_path) { flags |= USE_PATH; } stream = php_stream_gzopen(NULL, filename, mode, flags, NULL, NULL STREAMS_CC TSRMLS_CC); if (!stream) { RETURN_FALSE; } php_stream_to_zval(stream, return_value); } Commit Message: CWE ID: CWE-254
static PHP_FUNCTION(gzopen) { char *filename; char *mode; int filename_len, mode_len; int flags = REPORT_ERRORS; php_stream *stream; long use_include_path = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ps|l", &filename, &filename_len, &mode, &mode_len, &use_include_path) == FAILURE) { return; } if (use_include_path) { flags |= USE_PATH; } stream = php_stream_gzopen(NULL, filename, mode, flags, NULL, NULL STREAMS_CC TSRMLS_CC); if (!stream) { RETURN_FALSE; } php_stream_to_zval(stream, return_value); }
165,319
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: HostCache::HostCache(size_t max_entries) : max_entries_(max_entries), network_changes_(0) {} Commit Message: Add PersistenceDelegate to HostCache PersistenceDelegate is a new interface for persisting the contents of the HostCache. This commit includes the interface itself, the logic in HostCache for interacting with it, and a mock implementation of the interface for testing. It does not include support for immediate data removal since that won't be needed for the currently planned use case. BUG=605149 Review-Url: https://codereview.chromium.org/2943143002 Cr-Commit-Position: refs/heads/master@{#481015} CWE ID:
HostCache::HostCache(size_t max_entries)
172,007
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: PaintArtifactCompositor::PendingLayer::PendingLayer( const PaintChunk& first_paint_chunk, size_t chunk_index, bool chunk_requires_own_layer) : bounds(first_paint_chunk.bounds), rect_known_to_be_opaque( first_paint_chunk.known_to_be_opaque ? bounds : FloatRect()), property_tree_state(first_paint_chunk.properties.GetPropertyTreeState()), requires_own_layer(chunk_requires_own_layer) { paint_chunk_indices.push_back(chunk_index); } Commit Message: Reland "[CI] Make paint property nodes non-ref-counted" This reverts commit 887383b30842d9d9006e11bb6932660a3cb5b1b7. Reason for revert: Retry in M69. Original change's description: > Revert "[CI] Make paint property nodes non-ref-counted" > > This reverts commit 70fc0b018c9517558b7aa2be00edf2debb449123. > > Reason for revert: Caused bugs found by clusterfuzz > > Original change's description: > > [CI] Make paint property nodes non-ref-counted > > > > Now all paint property nodes are owned by ObjectPaintProperties > > (and LocalFrameView temporarily before removing non-RLS mode). > > Others just use raw pointers or references. > > > > Bug: 833496 > > Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2 > > Change-Id: I2d544fe153bb94698623248748df63c8aa2081ae > > Reviewed-on: https://chromium-review.googlesource.com/1031101 > > Reviewed-by: Tien-Ren Chen <[email protected]> > > Commit-Queue: Xianzhu Wang <[email protected]> > > Cr-Commit-Position: refs/heads/master@{#554626} > > [email protected],[email protected],[email protected] > > Change-Id: I02bb50d6744cb81a797246a0116b677e80a3c69f > No-Presubmit: true > No-Tree-Checks: true > No-Try: true > Bug: 833496,837932,837943 > Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2 > Reviewed-on: https://chromium-review.googlesource.com/1034292 > Reviewed-by: Xianzhu Wang <[email protected]> > Commit-Queue: Xianzhu Wang <[email protected]> > Cr-Commit-Position: refs/heads/master@{#554653} [email protected],[email protected],[email protected] # Not skipping CQ checks because original CL landed > 1 day ago. Bug: 833496, 837932, 837943 Change-Id: I0b4ef70db1f1f211ba97c30d617225355c750992 Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2 Reviewed-on: https://chromium-review.googlesource.com/1083491 Commit-Queue: Xianzhu Wang <[email protected]> Reviewed-by: Xianzhu Wang <[email protected]> Cr-Commit-Position: refs/heads/master@{#563930} CWE ID:
PaintArtifactCompositor::PendingLayer::PendingLayer( const PaintChunk& first_paint_chunk, size_t chunk_index, bool chunk_requires_own_layer) : bounds(first_paint_chunk.bounds), rect_known_to_be_opaque( first_paint_chunk.known_to_be_opaque ? bounds : FloatRect()), property_tree_state(first_paint_chunk.properties), requires_own_layer(chunk_requires_own_layer) { paint_chunk_indices.push_back(chunk_index); }
171,815
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: jbig2_immediate_generic_region(Jbig2Ctx *ctx, Jbig2Segment *segment, const byte *segment_data) { Jbig2RegionSegmentInfo rsi; byte seg_flags; int8_t gbat[8]; int offset; int gbat_bytes = 0; Jbig2GenericRegionParams params; int code = 0; Jbig2Image *image = NULL; Jbig2WordStream *ws = NULL; Jbig2ArithState *as = NULL; Jbig2ArithCx *GB_stats = NULL; /* 7.4.6 */ if (segment->data_length < 18) return jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, "Segment too short"); jbig2_get_region_segment_info(&rsi, segment_data); jbig2_error(ctx, JBIG2_SEVERITY_INFO, segment->number, "generic region: %d x %d @ (%d, %d), flags = %02x", rsi.width, rsi.height, rsi.x, rsi.y, rsi.flags); /* 7.4.6.2 */ seg_flags = segment_data[17]; jbig2_error(ctx, JBIG2_SEVERITY_INFO, segment->number, "segment flags = %02x", seg_flags); if ((seg_flags & 1) && (seg_flags & 6)) jbig2_error(ctx, JBIG2_SEVERITY_WARNING, segment->number, "MMR is 1, but GBTEMPLATE is not 0"); /* 7.4.6.3 */ if (!(seg_flags & 1)) { gbat_bytes = (seg_flags & 6) ? 2 : 8; if (18 + gbat_bytes > segment->data_length) return jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, "Segment too short"); memcpy(gbat, segment_data + 18, gbat_bytes); jbig2_error(ctx, JBIG2_SEVERITY_INFO, segment->number, "gbat: %d, %d", gbat[0], gbat[1]); } offset = 18 + gbat_bytes; /* Table 34 */ params.MMR = seg_flags & 1; params.GBTEMPLATE = (seg_flags & 6) >> 1; params.TPGDON = (seg_flags & 8) >> 3; params.USESKIP = 0; memcpy(params.gbat, gbat, gbat_bytes); image = jbig2_image_new(ctx, rsi.width, rsi.height); if (image == NULL) return jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, "unable to allocate generic image"); jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, segment->number, "allocated %d x %d image buffer for region decode results", rsi.width, rsi.height); if (params.MMR) { code = jbig2_decode_generic_mmr(ctx, segment, &params, segment_data + offset, segment->data_length - offset, image); } else { int stats_size = jbig2_generic_stats_size(ctx, params.GBTEMPLATE); GB_stats = jbig2_new(ctx, Jbig2ArithCx, stats_size); if (GB_stats == NULL) { code = jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, "unable to allocate GB_stats in jbig2_immediate_generic_region"); goto cleanup; } memset(GB_stats, 0, stats_size); ws = jbig2_word_stream_buf_new(ctx, segment_data + offset, segment->data_length - offset); if (ws == NULL) { code = jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, "unable to allocate ws in jbig2_immediate_generic_region"); goto cleanup; } as = jbig2_arith_new(ctx, ws); if (as == NULL) { code = jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, "unable to allocate as in jbig2_immediate_generic_region"); goto cleanup; } code = jbig2_decode_generic_region(ctx, segment, &params, as, image, GB_stats); } if (code >= 0) jbig2_page_add_result(ctx, &ctx->pages[ctx->current_page], image, rsi.x, rsi.y, rsi.op); else jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, "error while decoding immediate_generic_region"); cleanup: jbig2_free(ctx->allocator, as); jbig2_word_stream_buf_free(ctx, ws); jbig2_free(ctx->allocator, GB_stats); jbig2_image_release(ctx, image); return code; } Commit Message: CWE ID: CWE-119
jbig2_immediate_generic_region(Jbig2Ctx *ctx, Jbig2Segment *segment, const byte *segment_data) { Jbig2RegionSegmentInfo rsi; byte seg_flags; int8_t gbat[8]; int offset; uint32_t gbat_bytes = 0; Jbig2GenericRegionParams params; int code = 0; Jbig2Image *image = NULL; Jbig2WordStream *ws = NULL; Jbig2ArithState *as = NULL; Jbig2ArithCx *GB_stats = NULL; /* 7.4.6 */ if (segment->data_length < 18) return jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, "Segment too short"); jbig2_get_region_segment_info(&rsi, segment_data); jbig2_error(ctx, JBIG2_SEVERITY_INFO, segment->number, "generic region: %d x %d @ (%d, %d), flags = %02x", rsi.width, rsi.height, rsi.x, rsi.y, rsi.flags); /* 7.4.6.2 */ seg_flags = segment_data[17]; jbig2_error(ctx, JBIG2_SEVERITY_INFO, segment->number, "segment flags = %02x", seg_flags); if ((seg_flags & 1) && (seg_flags & 6)) jbig2_error(ctx, JBIG2_SEVERITY_WARNING, segment->number, "MMR is 1, but GBTEMPLATE is not 0"); /* 7.4.6.3 */ if (!(seg_flags & 1)) { gbat_bytes = (seg_flags & 6) ? 2 : 8; if (18 + gbat_bytes > segment->data_length) return jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, "Segment too short"); memcpy(gbat, segment_data + 18, gbat_bytes); jbig2_error(ctx, JBIG2_SEVERITY_INFO, segment->number, "gbat: %d, %d", gbat[0], gbat[1]); } offset = 18 + gbat_bytes; /* Table 34 */ params.MMR = seg_flags & 1; params.GBTEMPLATE = (seg_flags & 6) >> 1; params.TPGDON = (seg_flags & 8) >> 3; params.USESKIP = 0; memcpy(params.gbat, gbat, gbat_bytes); image = jbig2_image_new(ctx, rsi.width, rsi.height); if (image == NULL) return jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, "unable to allocate generic image"); jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, segment->number, "allocated %d x %d image buffer for region decode results", rsi.width, rsi.height); if (params.MMR) { code = jbig2_decode_generic_mmr(ctx, segment, &params, segment_data + offset, segment->data_length - offset, image); } else { int stats_size = jbig2_generic_stats_size(ctx, params.GBTEMPLATE); GB_stats = jbig2_new(ctx, Jbig2ArithCx, stats_size); if (GB_stats == NULL) { code = jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, "unable to allocate GB_stats in jbig2_immediate_generic_region"); goto cleanup; } memset(GB_stats, 0, stats_size); ws = jbig2_word_stream_buf_new(ctx, segment_data + offset, segment->data_length - offset); if (ws == NULL) { code = jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, "unable to allocate ws in jbig2_immediate_generic_region"); goto cleanup; } as = jbig2_arith_new(ctx, ws); if (as == NULL) { code = jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, "unable to allocate as in jbig2_immediate_generic_region"); goto cleanup; } code = jbig2_decode_generic_region(ctx, segment, &params, as, image, GB_stats); } if (code >= 0) jbig2_page_add_result(ctx, &ctx->pages[ctx->current_page], image, rsi.x, rsi.y, rsi.op); else jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, "error while decoding immediate_generic_region"); cleanup: jbig2_free(ctx->allocator, as); jbig2_word_stream_buf_free(ctx, ws); jbig2_free(ctx->allocator, GB_stats); jbig2_image_release(ctx, image); return code; }
165,486
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void ExtensionTtsController::CheckSpeechStatus() { if (!current_utterance_) return; if (!current_utterance_->extension_id().empty()) return; if (GetPlatformImpl()->IsSpeaking() == false) { FinishCurrentUtterance(); SpeakNextUtterance(); } if (current_utterance_ && current_utterance_->extension_id().empty()) { MessageLoop::current()->PostDelayedTask( FROM_HERE, method_factory_.NewRunnableMethod( &ExtensionTtsController::CheckSpeechStatus), kSpeechCheckDelayIntervalMs); } } Commit Message: Extend TTS extension API to support richer events returned from the engine to the client. Previously we just had a completed event; this adds start, word boundary, sentence boundary, and marker boundary. In addition, interrupted and canceled, which were previously errors, now become events. Mac and Windows implementations extended to support as many of these events as possible. BUG=67713 BUG=70198 BUG=75106 BUG=83404 TEST=Updates all TTS API tests to be event-based, and adds new tests. Review URL: http://codereview.chromium.org/6792014 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@91665 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
void ExtensionTtsController::CheckSpeechStatus() { std::set<std::string> desired_event_types; if (options->HasKey(constants::kDesiredEventTypesKey)) { ListValue* list; EXTENSION_FUNCTION_VALIDATE( options->GetList(constants::kDesiredEventTypesKey, &list)); for (size_t i = 0; i < list->GetSize(); i++) { std::string event_type; if (!list->GetString(i, &event_type)) desired_event_types.insert(event_type); } } std::string voice_extension_id; if (options->HasKey(constants::kExtensionIdKey)) { EXTENSION_FUNCTION_VALIDATE( options->GetString(constants::kExtensionIdKey, &voice_extension_id)); }
170,374
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void NavigationControllerImpl::Reload(ReloadType reload_type, bool check_for_repost) { DCHECK_NE(ReloadType::NONE, reload_type); if (transient_entry_index_ != -1) { NavigationEntryImpl* transient_entry = GetTransientEntry(); if (!transient_entry) return; LoadURL(transient_entry->GetURL(), Referrer(), ui::PAGE_TRANSITION_RELOAD, transient_entry->extra_headers()); return; } NavigationEntryImpl* entry = nullptr; int current_index = -1; if (IsInitialNavigation() && pending_entry_) { entry = pending_entry_; current_index = pending_entry_index_; } else { DiscardNonCommittedEntriesInternal(); current_index = GetCurrentEntryIndex(); if (current_index != -1) { entry = GetEntryAtIndex(current_index); } } if (!entry) return; if (last_committed_reload_type_ != ReloadType::NONE) { DCHECK(!last_committed_reload_time_.is_null()); base::Time now = time_smoother_.GetSmoothedTime(get_timestamp_callback_.Run()); DCHECK_GT(now, last_committed_reload_time_); if (!last_committed_reload_time_.is_null() && now > last_committed_reload_time_) { base::TimeDelta delta = now - last_committed_reload_time_; UMA_HISTOGRAM_MEDIUM_TIMES("Navigation.Reload.ReloadToReloadDuration", delta); if (last_committed_reload_type_ == ReloadType::NORMAL) { UMA_HISTOGRAM_MEDIUM_TIMES( "Navigation.Reload.ReloadMainResourceToReloadDuration", delta); } } } entry->set_reload_type(reload_type); if (g_check_for_repost && check_for_repost && entry->GetHasPostData()) { delegate_->NotifyBeforeFormRepostWarningShow(); pending_reload_ = reload_type; delegate_->ActivateAndShowRepostFormWarningDialog(); } else { if (!IsInitialNavigation()) DiscardNonCommittedEntriesInternal(); SiteInstanceImpl* site_instance = entry->site_instance(); bool is_for_guests_only = site_instance && site_instance->HasProcess() && site_instance->GetProcess()->IsForGuestsOnly(); if (!is_for_guests_only && site_instance && site_instance->HasWrongProcessForURL(entry->GetURL())) { NavigationEntryImpl* nav_entry = NavigationEntryImpl::FromNavigationEntry( CreateNavigationEntry(entry->GetURL(), entry->GetReferrer(), entry->GetTransitionType(), false, entry->extra_headers(), browser_context_, nullptr /* blob_url_loader_factory */) .release()); reload_type = ReloadType::NONE; nav_entry->set_should_replace_entry(true); pending_entry_ = nav_entry; DCHECK_EQ(-1, pending_entry_index_); } else { pending_entry_ = entry; pending_entry_index_ = current_index; pending_entry_->SetTransitionType(ui::PAGE_TRANSITION_RELOAD); } NavigateToPendingEntry(reload_type, nullptr /* navigation_ui_data */); } } Commit Message: Preserve renderer-initiated bit when reloading in a new process. BUG=847718 TEST=See bug for repro steps. Change-Id: I6c3461793fbb23f1a4d731dc27b4e77312f29227 Reviewed-on: https://chromium-review.googlesource.com/1080235 Commit-Queue: Charlie Reis <[email protected]> Reviewed-by: Nasko Oskov <[email protected]> Cr-Commit-Position: refs/heads/master@{#563312} CWE ID:
void NavigationControllerImpl::Reload(ReloadType reload_type, bool check_for_repost) { DCHECK_NE(ReloadType::NONE, reload_type); if (transient_entry_index_ != -1) { NavigationEntryImpl* transient_entry = GetTransientEntry(); if (!transient_entry) return; LoadURL(transient_entry->GetURL(), Referrer(), ui::PAGE_TRANSITION_RELOAD, transient_entry->extra_headers()); return; } NavigationEntryImpl* entry = nullptr; int current_index = -1; if (IsInitialNavigation() && pending_entry_) { entry = pending_entry_; current_index = pending_entry_index_; } else { DiscardNonCommittedEntriesInternal(); current_index = GetCurrentEntryIndex(); if (current_index != -1) { entry = GetEntryAtIndex(current_index); } } if (!entry) return; if (last_committed_reload_type_ != ReloadType::NONE) { DCHECK(!last_committed_reload_time_.is_null()); base::Time now = time_smoother_.GetSmoothedTime(get_timestamp_callback_.Run()); DCHECK_GT(now, last_committed_reload_time_); if (!last_committed_reload_time_.is_null() && now > last_committed_reload_time_) { base::TimeDelta delta = now - last_committed_reload_time_; UMA_HISTOGRAM_MEDIUM_TIMES("Navigation.Reload.ReloadToReloadDuration", delta); if (last_committed_reload_type_ == ReloadType::NORMAL) { UMA_HISTOGRAM_MEDIUM_TIMES( "Navigation.Reload.ReloadMainResourceToReloadDuration", delta); } } } entry->set_reload_type(reload_type); if (g_check_for_repost && check_for_repost && entry->GetHasPostData()) { delegate_->NotifyBeforeFormRepostWarningShow(); pending_reload_ = reload_type; delegate_->ActivateAndShowRepostFormWarningDialog(); } else { if (!IsInitialNavigation()) DiscardNonCommittedEntriesInternal(); SiteInstanceImpl* site_instance = entry->site_instance(); bool is_for_guests_only = site_instance && site_instance->HasProcess() && site_instance->GetProcess()->IsForGuestsOnly(); if (!is_for_guests_only && site_instance && site_instance->HasWrongProcessForURL(entry->GetURL())) { NavigationEntryImpl* nav_entry = NavigationEntryImpl::FromNavigationEntry( CreateNavigationEntry(entry->GetURL(), entry->GetReferrer(), entry->GetTransitionType(), false, entry->extra_headers(), browser_context_, nullptr /* blob_url_loader_factory */) .release()); reload_type = ReloadType::NONE; nav_entry->set_should_replace_entry(true); nav_entry->set_is_renderer_initiated(entry->is_renderer_initiated()); pending_entry_ = nav_entry; DCHECK_EQ(-1, pending_entry_index_); } else { pending_entry_ = entry; pending_entry_index_ = current_index; pending_entry_->SetTransitionType(ui::PAGE_TRANSITION_RELOAD); } NavigateToPendingEntry(reload_type, nullptr /* navigation_ui_data */); } }
173,155
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void SubpelVarianceTest<SubpelVarianceFunctionType>::RefTest() { for (int x = 0; x < 16; ++x) { for (int y = 0; y < 16; ++y) { for (int j = 0; j < block_size_; j++) { src_[j] = rnd.Rand8(); } for (int j = 0; j < block_size_ + width_ + height_ + 1; j++) { ref_[j] = rnd.Rand8(); } unsigned int sse1, sse2; unsigned int var1; REGISTER_STATE_CHECK(var1 = subpel_variance_(ref_, width_ + 1, x, y, src_, width_, &sse1)); const unsigned int var2 = subpel_variance_ref(ref_, src_, log2width_, log2height_, x, y, &sse2); EXPECT_EQ(sse1, sse2) << "at position " << x << ", " << y; EXPECT_EQ(var1, var2) << "at position " << x << ", " << y; } } } 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 SubpelVarianceTest<SubpelVarianceFunctionType>::RefTest() { for (int x = 0; x < 8; ++x) { for (int y = 0; y < 8; ++y) { if (!use_high_bit_depth_) { for (int j = 0; j < block_size_; j++) { src_[j] = rnd_.Rand8(); } for (int j = 0; j < block_size_ + width_ + height_ + 1; j++) { ref_[j] = rnd_.Rand8(); } #if CONFIG_VP9_HIGHBITDEPTH } else { for (int j = 0; j < block_size_; j++) { CONVERT_TO_SHORTPTR(src_)[j] = rnd_.Rand16() & mask_; } for (int j = 0; j < block_size_ + width_ + height_ + 1; j++) { CONVERT_TO_SHORTPTR(ref_)[j] = rnd_.Rand16() & mask_; } #endif // CONFIG_VP9_HIGHBITDEPTH } unsigned int sse1, sse2; unsigned int var1; ASM_REGISTER_STATE_CHECK(var1 = subpel_variance_(ref_, width_ + 1, x, y, src_, width_, &sse1)); const unsigned int var2 = subpel_variance_ref(ref_, src_, log2width_, log2height_, x, y, &sse2, use_high_bit_depth_, bit_depth_); EXPECT_EQ(sse1, sse2) << "at position " << x << ", " << y; EXPECT_EQ(var1, var2) << "at position " << x << ", " << y; } } }
174,587
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void TabStripModelObserver::TabDetachedAt(TabContents* contents, int index) { } Commit Message: Remove TabContents from TabStripModelObserver::TabDetachedAt. BUG=107201 TEST=no visible change Review URL: https://chromiumcodereview.appspot.com/11293205 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@167122 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
void TabStripModelObserver::TabDetachedAt(TabContents* contents, void TabStripModelObserver::TabDetachedAt(WebContents* contents, int index) { }
171,518
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: OMX_ERRORTYPE SoftAACEncoder::internalGetParameter( OMX_INDEXTYPE index, OMX_PTR params) { switch (index) { case OMX_IndexParamAudioPortFormat: { OMX_AUDIO_PARAM_PORTFORMATTYPE *formatParams = (OMX_AUDIO_PARAM_PORTFORMATTYPE *)params; if (formatParams->nPortIndex > 1) { return OMX_ErrorUndefined; } if (formatParams->nIndex > 0) { return OMX_ErrorNoMore; } formatParams->eEncoding = (formatParams->nPortIndex == 0) ? OMX_AUDIO_CodingPCM : OMX_AUDIO_CodingAAC; return OMX_ErrorNone; } case OMX_IndexParamAudioAac: { OMX_AUDIO_PARAM_AACPROFILETYPE *aacParams = (OMX_AUDIO_PARAM_AACPROFILETYPE *)params; if (aacParams->nPortIndex != 1) { return OMX_ErrorUndefined; } aacParams->nBitRate = mBitRate; aacParams->nAudioBandWidth = 0; aacParams->nAACtools = 0; aacParams->nAACERtools = 0; aacParams->eAACProfile = OMX_AUDIO_AACObjectMain; aacParams->eAACStreamFormat = OMX_AUDIO_AACStreamFormatMP4FF; aacParams->eChannelMode = OMX_AUDIO_ChannelModeStereo; aacParams->nChannels = mNumChannels; aacParams->nSampleRate = mSampleRate; aacParams->nFrameLength = 0; return OMX_ErrorNone; } case OMX_IndexParamAudioPcm: { OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams = (OMX_AUDIO_PARAM_PCMMODETYPE *)params; if (pcmParams->nPortIndex != 0) { return OMX_ErrorUndefined; } pcmParams->eNumData = OMX_NumericalDataSigned; pcmParams->eEndian = OMX_EndianBig; pcmParams->bInterleaved = OMX_TRUE; pcmParams->nBitPerSample = 16; pcmParams->ePCMMode = OMX_AUDIO_PCMModeLinear; pcmParams->eChannelMapping[0] = OMX_AUDIO_ChannelLF; pcmParams->eChannelMapping[1] = OMX_AUDIO_ChannelRF; pcmParams->nChannels = mNumChannels; pcmParams->nSamplingRate = mSampleRate; return OMX_ErrorNone; } default: return SimpleSoftOMXComponent::internalGetParameter(index, params); } } Commit Message: DO NOT MERGE Verify OMX buffer sizes prior to access Bug: 27207275 Change-Id: I4412825d1ee233d993af0a67708bea54304ff62d CWE ID: CWE-119
OMX_ERRORTYPE SoftAACEncoder::internalGetParameter( OMX_INDEXTYPE index, OMX_PTR params) { switch (index) { case OMX_IndexParamAudioPortFormat: { OMX_AUDIO_PARAM_PORTFORMATTYPE *formatParams = (OMX_AUDIO_PARAM_PORTFORMATTYPE *)params; if (!isValidOMXParam(formatParams)) { return OMX_ErrorBadParameter; } if (formatParams->nPortIndex > 1) { return OMX_ErrorUndefined; } if (formatParams->nIndex > 0) { return OMX_ErrorNoMore; } formatParams->eEncoding = (formatParams->nPortIndex == 0) ? OMX_AUDIO_CodingPCM : OMX_AUDIO_CodingAAC; return OMX_ErrorNone; } case OMX_IndexParamAudioAac: { OMX_AUDIO_PARAM_AACPROFILETYPE *aacParams = (OMX_AUDIO_PARAM_AACPROFILETYPE *)params; if (!isValidOMXParam(aacParams)) { return OMX_ErrorBadParameter; } if (aacParams->nPortIndex != 1) { return OMX_ErrorUndefined; } aacParams->nBitRate = mBitRate; aacParams->nAudioBandWidth = 0; aacParams->nAACtools = 0; aacParams->nAACERtools = 0; aacParams->eAACProfile = OMX_AUDIO_AACObjectMain; aacParams->eAACStreamFormat = OMX_AUDIO_AACStreamFormatMP4FF; aacParams->eChannelMode = OMX_AUDIO_ChannelModeStereo; aacParams->nChannels = mNumChannels; aacParams->nSampleRate = mSampleRate; aacParams->nFrameLength = 0; return OMX_ErrorNone; } case OMX_IndexParamAudioPcm: { OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams = (OMX_AUDIO_PARAM_PCMMODETYPE *)params; if (!isValidOMXParam(pcmParams)) { return OMX_ErrorBadParameter; } if (pcmParams->nPortIndex != 0) { return OMX_ErrorUndefined; } pcmParams->eNumData = OMX_NumericalDataSigned; pcmParams->eEndian = OMX_EndianBig; pcmParams->bInterleaved = OMX_TRUE; pcmParams->nBitPerSample = 16; pcmParams->ePCMMode = OMX_AUDIO_PCMModeLinear; pcmParams->eChannelMapping[0] = OMX_AUDIO_ChannelLF; pcmParams->eChannelMapping[1] = OMX_AUDIO_ChannelRF; pcmParams->nChannels = mNumChannels; pcmParams->nSamplingRate = mSampleRate; return OMX_ErrorNone; } default: return SimpleSoftOMXComponent::internalGetParameter(index, params); } }
174,188
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int rpc_type_of_NPPVariable(int variable) { int type; switch (variable) { case NPPVpluginNameString: case NPPVpluginDescriptionString: case NPPVformValue: // byte values of 0 does not appear in the UTF-8 encoding but for U+0000 type = RPC_TYPE_STRING; break; case NPPVpluginWindowSize: case NPPVpluginTimerInterval: type = RPC_TYPE_INT32; break; case NPPVpluginNeedsXEmbed: case NPPVpluginWindowBool: case NPPVpluginTransparentBool: case NPPVjavascriptPushCallerBool: case NPPVpluginKeepLibraryInMemory: type = RPC_TYPE_BOOLEAN; break; case NPPVpluginScriptableNPObject: type = RPC_TYPE_NP_OBJECT; break; default: type = RPC_ERROR_GENERIC; break; } return type; } Commit Message: Support all the new variables added CWE ID: CWE-264
int rpc_type_of_NPPVariable(int variable) { int type; switch (variable) { case NPPVpluginNameString: case NPPVpluginDescriptionString: case NPPVformValue: // byte values of 0 does not appear in the UTF-8 encoding but for U+0000 case NPPVpluginNativeAccessibleAtkPlugId: type = RPC_TYPE_STRING; break; case NPPVpluginWindowSize: case NPPVpluginTimerInterval: type = RPC_TYPE_INT32; break; case NPPVpluginNeedsXEmbed: case NPPVpluginWindowBool: case NPPVpluginTransparentBool: case NPPVjavascriptPushCallerBool: case NPPVpluginKeepLibraryInMemory: case NPPVpluginUrlRequestsDisplayedBool: case NPPVpluginWantsAllNetworkStreams: case NPPVpluginCancelSrcStream: case NPPVSupportsAdvancedKeyHandling: type = RPC_TYPE_BOOLEAN; break; case NPPVpluginScriptableNPObject: type = RPC_TYPE_NP_OBJECT; break; default: type = RPC_ERROR_GENERIC; break; } return type; }
165,863
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void PageFormAnalyserLogger::Flush() { std::string text; for (ConsoleLevel level : {kError, kWarning, kVerbose}) { for (LogEntry& entry : node_buffer_[level]) { text.clear(); text += "[DOM] "; text += entry.message; for (unsigned i = 0; i < entry.nodes.size(); ++i) text += " %o"; blink::WebConsoleMessage message(level, blink::WebString::FromUTF8(text)); message.nodes = std::move(entry.nodes); // avoids copying node vectors. frame_->AddMessageToConsole(message); } } node_buffer_.clear(); } Commit Message: [AF] Prevent Logging Password Values to Console Before sending over to be logged by DevTools, filter out DOM nodes that have a type attribute equal to "password", and that are not empty. Bug: 934609 Change-Id: I147ad0c2bad13cc50394f4b5ff2f4bfb7293114b Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1506498 Commit-Queue: Sebastien Lalancette <[email protected]> Reviewed-by: Vadym Doroshenko <[email protected]> Reviewed-by: Mathieu Perreault <[email protected]> Cr-Commit-Position: refs/heads/master@{#638615} CWE ID: CWE-119
void PageFormAnalyserLogger::Flush() { std::string text; for (ConsoleLevel level : {kError, kWarning, kVerbose}) { for (LogEntry& entry : node_buffer_[level]) { text.clear(); text += "[DOM] "; text += entry.message; std::vector<blink::WebNode> nodesToLog; for (unsigned i = 0; i < entry.nodes.size(); ++i) { if (entry.nodes[i].IsElementNode()) { const blink::WebElement element = entry.nodes[i].ToConst<blink::WebElement>(); const blink::WebInputElement* webInputElement = blink::ToWebInputElement(&element); // Filter out password inputs with values from being logged, as their // values are also logged. const bool shouldObfuscate = webInputElement && webInputElement->IsPasswordFieldForAutofill() && !webInputElement->Value().IsEmpty(); if (!shouldObfuscate) { text += " %o"; nodesToLog.push_back(element); } } } blink::WebConsoleMessage message(level, blink::WebString::FromUTF8(text)); message.nodes = std::move(nodesToLog); // avoids copying node vectors. frame_->AddMessageToConsole(message); } } node_buffer_.clear(); }
172,078
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: add_range(fz_context *ctx, pdf_cmap *cmap, unsigned int low, unsigned int high, unsigned int out, int check_for_overlap, int many) { int current; cmap_splay *tree; if (low > high) { fz_warn(ctx, "range limits out of range in cmap %s", cmap->cmap_name); return; } tree = cmap->tree; if (cmap->tlen) { unsigned int move = cmap->ttop; unsigned int gt = EMPTY; unsigned int lt = EMPTY; if (check_for_overlap) { /* Check for collision with the current node */ do { current = move; /* Cases we might meet: * tree[i]: <-----> * case 0: <-> * case 1: <-------> * case 2: <-------------> * case 3: <-> * case 4: <-------> * case 5: <-> */ if (low <= tree[current].low && tree[current].low <= high) { /* case 1, reduces to case 0 */ /* or case 2, deleting the node */ tree[current].out += high + 1 - tree[current].low; tree[current].low = high + 1; if (tree[current].low > tree[current].high) { move = delete_node(cmap, current); current = EMPTY; continue; } } else if (low <= tree[current].high && tree[current].high <= high) { /* case 4, reduces to case 5 */ tree[current].high = low - 1; assert(tree[current].low <= tree[current].high); } else if (tree[current].low < low && high < tree[current].high) { /* case 3, reduces to case 5 */ int new_high = tree[current].high; tree[current].high = low-1; add_range(ctx, cmap, high+1, new_high, tree[current].out + high + 1 - tree[current].low, 0, tree[current].many); } /* Now look for where to move to next (left for case 0, right for case 5) */ if (tree[current].low > high) { gt = current; } else { move = tree[current].right; lt = current; } } while (move != EMPTY); } else { do { current = move; if (tree[current].low > high) { move = tree[current].left; gt = current; } else { move = tree[current].right; lt = current; } } while (move != EMPTY); } /* current is now the node to which we would be adding the new node */ /* lt is the last node we traversed which is lt the new node. */ /* gt is the last node we traversed which is gt the new node. */ if (!many) { /* Check for the 'merge' cases. */ if (lt != EMPTY && !tree[lt].many && tree[lt].high == low-1 && tree[lt].out - tree[lt].low == out - low) { tree[lt].high = high; if (gt != EMPTY && !tree[gt].many && tree[gt].low == high+1 && tree[gt].out - tree[gt].low == out - low) { tree[lt].high = tree[gt].high; delete_node(cmap, gt); } goto exit; } if (gt != EMPTY && !tree[gt].many && tree[gt].low == high+1 && tree[gt].out - tree[gt].low == out - low) { tree[gt].low = low; tree[gt].out = out; goto exit; } } } else current = EMPTY; if (cmap->tlen == cmap->tcap) { int new_cap = cmap->tcap ? cmap->tcap * 2 : 256; tree = cmap->tree = fz_resize_array(ctx, cmap->tree, new_cap, sizeof *cmap->tree); cmap->tcap = new_cap; } tree[cmap->tlen].low = low; tree[cmap->tlen].high = high; tree[cmap->tlen].out = out; tree[cmap->tlen].parent = current; tree[cmap->tlen].left = EMPTY; tree[cmap->tlen].right = EMPTY; tree[cmap->tlen].many = many; cmap->tlen++; if (current == EMPTY) cmap->ttop = 0; else if (tree[current].low > high) tree[current].left = cmap->tlen-1; else { assert(tree[current].high < low); tree[current].right = cmap->tlen-1; } move_to_root(tree, cmap->tlen-1); cmap->ttop = cmap->tlen-1; exit: {} #ifdef CHECK_SPLAY check_splay(cmap->tree, cmap->ttop, 0); #endif #ifdef DUMP_SPLAY dump_splay(cmap->tree, cmap->ttop, 0, ""); #endif } Commit Message: CWE ID: CWE-416
add_range(fz_context *ctx, pdf_cmap *cmap, unsigned int low, unsigned int high, unsigned int out, int check_for_overlap, int many) { int current; cmap_splay *tree; if (low > high) { fz_warn(ctx, "range limits out of range in cmap %s", cmap->cmap_name); return; } tree = cmap->tree; if (cmap->tlen) { unsigned int move = cmap->ttop; unsigned int gt = EMPTY; unsigned int lt = EMPTY; if (check_for_overlap) { /* Check for collision with the current node */ do { current = move; /* Cases we might meet: * tree[i]: <-----> * case 0: <-> * case 1: <-------> * case 2: <-------------> * case 3: <-> * case 4: <-------> * case 5: <-> */ if (low <= tree[current].low && tree[current].low <= high) { /* case 1, reduces to case 0 */ /* or case 2, deleting the node */ tree[current].out += high + 1 - tree[current].low; tree[current].low = high + 1; if (tree[current].low > tree[current].high) { move = delete_node(cmap, current); current = EMPTY; continue; } } else if (low <= tree[current].high && tree[current].high <= high) { /* case 4, reduces to case 5 */ tree[current].high = low - 1; assert(tree[current].low <= tree[current].high); } else if (tree[current].low < low && high < tree[current].high) { /* case 3, reduces to case 5 */ int new_high = tree[current].high; tree[current].high = low-1; add_range(ctx, cmap, high+1, new_high, tree[current].out + high + 1 - tree[current].low, 0, tree[current].many); tree = cmap->tree; } /* Now look for where to move to next (left for case 0, right for case 5) */ if (tree[current].low > high) { gt = current; } else { move = tree[current].right; lt = current; } } while (move != EMPTY); } else { do { current = move; if (tree[current].low > high) { move = tree[current].left; gt = current; } else { move = tree[current].right; lt = current; } } while (move != EMPTY); } /* current is now the node to which we would be adding the new node */ /* lt is the last node we traversed which is lt the new node. */ /* gt is the last node we traversed which is gt the new node. */ if (!many) { /* Check for the 'merge' cases. */ if (lt != EMPTY && !tree[lt].many && tree[lt].high == low-1 && tree[lt].out - tree[lt].low == out - low) { tree[lt].high = high; if (gt != EMPTY && !tree[gt].many && tree[gt].low == high+1 && tree[gt].out - tree[gt].low == out - low) { tree[lt].high = tree[gt].high; delete_node(cmap, gt); } goto exit; } if (gt != EMPTY && !tree[gt].many && tree[gt].low == high+1 && tree[gt].out - tree[gt].low == out - low) { tree[gt].low = low; tree[gt].out = out; goto exit; } } } else current = EMPTY; if (cmap->tlen == cmap->tcap) { int new_cap = cmap->tcap ? cmap->tcap * 2 : 256; tree = cmap->tree = fz_resize_array(ctx, cmap->tree, new_cap, sizeof *cmap->tree); cmap->tcap = new_cap; } tree[cmap->tlen].low = low; tree[cmap->tlen].high = high; tree[cmap->tlen].out = out; tree[cmap->tlen].parent = current; tree[cmap->tlen].left = EMPTY; tree[cmap->tlen].right = EMPTY; tree[cmap->tlen].many = many; cmap->tlen++; if (current == EMPTY) cmap->ttop = 0; else if (tree[current].low > high) tree[current].left = cmap->tlen-1; else { assert(tree[current].high < low); tree[current].right = cmap->tlen-1; } move_to_root(tree, cmap->tlen-1); cmap->ttop = cmap->tlen-1; exit: {} #ifdef CHECK_SPLAY check_splay(cmap->tree, cmap->ttop, 0); #endif #ifdef DUMP_SPLAY dump_splay(cmap->tree, cmap->ttop, 0, ""); #endif }
164,577
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool asn1_write_GeneralString(struct asn1_data *data, const char *s) { asn1_push_tag(data, ASN1_GENERAL_STRING); asn1_write_LDAPString(data, s); asn1_pop_tag(data); return !data->has_error; } Commit Message: CWE ID: CWE-399
bool asn1_write_GeneralString(struct asn1_data *data, const char *s) { if (!asn1_push_tag(data, ASN1_GENERAL_STRING)) return false; if (!asn1_write_LDAPString(data, s)) return false; return asn1_pop_tag(data); }
164,589
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int php_var_unserialize_internal(UNSERIALIZE_PARAMETER) { const unsigned char *cursor, *limit, *marker, *start; zval *rval_ref; limit = max; cursor = *p; if (YYCURSOR >= YYLIMIT) { return 0; } if (var_hash && (*p)[0] != 'R') { var_push(var_hash, rval); } start = cursor; #line 585 "ext/standard/var_unserializer.c" { YYCTYPE yych; static const unsigned char yybm[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; if ((YYLIMIT - YYCURSOR) < 7) YYFILL(7); yych = *YYCURSOR; switch (yych) { case 'C': case 'O': goto yy13; case 'N': goto yy5; case 'R': goto yy2; case 'S': goto yy10; case 'a': goto yy11; case 'b': goto yy6; case 'd': goto yy8; case 'i': goto yy7; case 'o': goto yy12; case 'r': goto yy4; case 's': goto yy9; case '}': goto yy14; default: goto yy16; } yy2: yych = *(YYMARKER = ++YYCURSOR); if (yych == ':') goto yy95; yy3: #line 962 "ext/standard/var_unserializer.re" { return 0; } #line 646 "ext/standard/var_unserializer.c" yy4: yych = *(YYMARKER = ++YYCURSOR); if (yych == ':') goto yy89; goto yy3; yy5: yych = *++YYCURSOR; if (yych == ';') goto yy87; goto yy3; yy6: yych = *(YYMARKER = ++YYCURSOR); if (yych == ':') goto yy83; goto yy3; yy7: yych = *(YYMARKER = ++YYCURSOR); if (yych == ':') goto yy77; goto yy3; yy8: yych = *(YYMARKER = ++YYCURSOR); if (yych == ':') goto yy53; goto yy3; yy9: yych = *(YYMARKER = ++YYCURSOR); if (yych == ':') goto yy46; goto yy3; yy10: yych = *(YYMARKER = ++YYCURSOR); if (yych == ':') goto yy39; goto yy3; yy11: yych = *(YYMARKER = ++YYCURSOR); if (yych == ':') goto yy32; goto yy3; yy12: yych = *(YYMARKER = ++YYCURSOR); if (yych == ':') goto yy25; goto yy3; yy13: yych = *(YYMARKER = ++YYCURSOR); if (yych == ':') goto yy17; goto yy3; yy14: ++YYCURSOR; #line 956 "ext/standard/var_unserializer.re" { /* this is the case where we have less data than planned */ php_error_docref(NULL, E_NOTICE, "Unexpected end of serialized data"); return 0; /* not sure if it should be 0 or 1 here? */ } #line 695 "ext/standard/var_unserializer.c" yy16: yych = *++YYCURSOR; goto yy3; yy17: yych = *++YYCURSOR; if (yybm[0+yych] & 128) { goto yy20; } if (yych == '+') goto yy19; yy18: YYCURSOR = YYMARKER; goto yy3; yy19: yych = *++YYCURSOR; if (yybm[0+yych] & 128) { goto yy20; } goto yy18; yy20: ++YYCURSOR; if ((YYLIMIT - YYCURSOR) < 2) YYFILL(2); yych = *YYCURSOR; if (yybm[0+yych] & 128) { goto yy20; } if (yych <= '/') goto yy18; if (yych >= ';') goto yy18; yych = *++YYCURSOR; if (yych != '"') goto yy18; ++YYCURSOR; #line 804 "ext/standard/var_unserializer.re" { size_t len, len2, len3, maxlen; zend_long elements; char *str; zend_string *class_name; zend_class_entry *ce; int incomplete_class = 0; int custom_object = 0; zval user_func; zval retval; zval args[1]; if (!var_hash) return 0; if (*start == 'C') { custom_object = 1; } len2 = len = parse_uiv(start + 2); maxlen = max - YYCURSOR; if (maxlen < len || len == 0) { *p = start + 2; return 0; } str = (char*)YYCURSOR; YYCURSOR += len; if (*(YYCURSOR) != '"') { *p = YYCURSOR; return 0; } if (*(YYCURSOR+1) != ':') { *p = YYCURSOR+1; return 0; } len3 = strspn(str, "0123456789_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\177\200\201\202\203\204\205\206\207\210\211\212\213\214\215\216\217\220\221\222\223\224\225\226\227\230\231\232\233\234\235\236\237\240\241\242\243\244\245\246\247\250\251\252\253\254\255\256\257\260\261\262\263\264\265\266\267\270\271\272\273\274\275\276\277\300\301\302\303\304\305\306\307\310\311\312\313\314\315\316\317\320\321\322\323\324\325\326\327\330\331\332\333\334\335\336\337\340\341\342\343\344\345\346\347\350\351\352\353\354\355\356\357\360\361\362\363\364\365\366\367\370\371\372\373\374\375\376\377\\"); if (len3 != len) { *p = YYCURSOR + len3 - len; return 0; } class_name = zend_string_init(str, len, 0); do { if(!unserialize_allowed_class(class_name, classes)) { incomplete_class = 1; ce = PHP_IC_ENTRY; break; } /* Try to find class directly */ BG(serialize_lock)++; ce = zend_lookup_class(class_name); if (ce) { BG(serialize_lock)--; if (EG(exception)) { zend_string_release(class_name); return 0; } break; } BG(serialize_lock)--; if (EG(exception)) { zend_string_release(class_name); return 0; } /* Check for unserialize callback */ if ((PG(unserialize_callback_func) == NULL) || (PG(unserialize_callback_func)[0] == '\0')) { incomplete_class = 1; ce = PHP_IC_ENTRY; break; } /* Call unserialize callback */ ZVAL_STRING(&user_func, PG(unserialize_callback_func)); ZVAL_STR_COPY(&args[0], class_name); BG(serialize_lock)++; if (call_user_function_ex(CG(function_table), NULL, &user_func, &retval, 1, args, 0, NULL) != SUCCESS) { BG(serialize_lock)--; if (EG(exception)) { zend_string_release(class_name); zval_ptr_dtor(&user_func); zval_ptr_dtor(&args[0]); return 0; } php_error_docref(NULL, E_WARNING, "defined (%s) but not found", Z_STRVAL(user_func)); incomplete_class = 1; ce = PHP_IC_ENTRY; zval_ptr_dtor(&user_func); zval_ptr_dtor(&args[0]); break; } BG(serialize_lock)--; zval_ptr_dtor(&retval); if (EG(exception)) { zend_string_release(class_name); zval_ptr_dtor(&user_func); zval_ptr_dtor(&args[0]); return 0; } /* The callback function may have defined the class */ BG(serialize_lock)++; if ((ce = zend_lookup_class(class_name)) == NULL) { php_error_docref(NULL, E_WARNING, "Function %s() hasn't defined the class it was called for", Z_STRVAL(user_func)); incomplete_class = 1; ce = PHP_IC_ENTRY; } BG(serialize_lock)--; zval_ptr_dtor(&user_func); zval_ptr_dtor(&args[0]); break; } while (1); *p = YYCURSOR; if (custom_object) { int ret; ret = object_custom(UNSERIALIZE_PASSTHRU, ce); if (ret && incomplete_class) { php_store_class_name(rval, ZSTR_VAL(class_name), len2); } zend_string_release(class_name); return ret; } elements = object_common1(UNSERIALIZE_PASSTHRU, ce); if (elements < 0) { zend_string_release(class_name); return 0; } if (incomplete_class) { php_store_class_name(rval, ZSTR_VAL(class_name), len2); } zend_string_release(class_name); return object_common2(UNSERIALIZE_PASSTHRU, elements); } #line 878 "ext/standard/var_unserializer.c" yy25: yych = *++YYCURSOR; if (yych <= ',') { if (yych != '+') goto yy18; } else { if (yych <= '-') goto yy26; if (yych <= '/') goto yy18; if (yych <= '9') goto yy27; goto yy18; } yy26: yych = *++YYCURSOR; if (yych <= '/') goto yy18; if (yych >= ':') goto yy18; yy27: ++YYCURSOR; if ((YYLIMIT - YYCURSOR) < 2) YYFILL(2); yych = *YYCURSOR; if (yych <= '/') goto yy18; if (yych <= '9') goto yy27; if (yych >= ';') goto yy18; yych = *++YYCURSOR; if (yych != '"') goto yy18; ++YYCURSOR; #line 793 "ext/standard/var_unserializer.re" { zend_long elements; if (!var_hash) return 0; elements = object_common1(UNSERIALIZE_PASSTHRU, ZEND_STANDARD_CLASS_DEF_PTR); if (elements < 0 || elements >= HT_MAX_SIZE) { return 0; } return object_common2(UNSERIALIZE_PASSTHRU, elements); } #line 914 "ext/standard/var_unserializer.c" yy32: yych = *++YYCURSOR; if (yych == '+') goto yy33; if (yych <= '/') goto yy18; if (yych <= '9') goto yy34; goto yy18; yy33: yych = *++YYCURSOR; if (yych <= '/') goto yy18; if (yych >= ':') goto yy18; yy34: ++YYCURSOR; if ((YYLIMIT - YYCURSOR) < 2) YYFILL(2); yych = *YYCURSOR; if (yych <= '/') goto yy18; if (yych <= '9') goto yy34; if (yych >= ';') goto yy18; yych = *++YYCURSOR; if (yych != '{') goto yy18; ++YYCURSOR; #line 769 "ext/standard/var_unserializer.re" { zend_long elements = parse_iv(start + 2); /* use iv() not uiv() in order to check data range */ *p = YYCURSOR; if (!var_hash) return 0; if (elements < 0 || elements >= HT_MAX_SIZE) { return 0; } array_init_size(rval, elements); if (elements) { /* we can't convert from packed to hash during unserialization, because reference to some zvals might be keept in var_hash (to support references) */ zend_hash_real_init(Z_ARRVAL_P(rval), 0); } if (!process_nested_data(UNSERIALIZE_PASSTHRU, Z_ARRVAL_P(rval), elements, 0)) { return 0; } return finish_nested_data(UNSERIALIZE_PASSTHRU); } #line 959 "ext/standard/var_unserializer.c" yy39: yych = *++YYCURSOR; if (yych == '+') goto yy40; if (yych <= '/') goto yy18; if (yych <= '9') goto yy41; goto yy18; yy40: yych = *++YYCURSOR; if (yych <= '/') goto yy18; if (yych >= ':') goto yy18; yy41: ++YYCURSOR; if ((YYLIMIT - YYCURSOR) < 2) YYFILL(2); yych = *YYCURSOR; if (yych <= '/') goto yy18; if (yych <= '9') goto yy41; if (yych >= ';') goto yy18; yych = *++YYCURSOR; if (yych != '"') goto yy18; ++YYCURSOR; #line 735 "ext/standard/var_unserializer.re" { size_t len, maxlen; zend_string *str; len = parse_uiv(start + 2); maxlen = max - YYCURSOR; if (maxlen < len) { *p = start + 2; return 0; } if ((str = unserialize_str(&YYCURSOR, len, maxlen)) == NULL) { return 0; } if (*(YYCURSOR) != '"') { zend_string_free(str); *p = YYCURSOR; return 0; } if (*(YYCURSOR + 1) != ';') { efree(str); *p = YYCURSOR + 1; return 0; } YYCURSOR += 2; *p = YYCURSOR; ZVAL_STR(rval, str); return 1; } #line 1014 "ext/standard/var_unserializer.c" yy46: yych = *++YYCURSOR; if (yych == '+') goto yy47; if (yych <= '/') goto yy18; if (yych <= '9') goto yy48; goto yy18; yy47: yych = *++YYCURSOR; if (yych <= '/') goto yy18; if (yych >= ':') goto yy18; yy48: ++YYCURSOR; if ((YYLIMIT - YYCURSOR) < 2) YYFILL(2); yych = *YYCURSOR; if (yych <= '/') goto yy18; if (yych <= '9') goto yy48; if (yych >= ';') goto yy18; yych = *++YYCURSOR; if (yych != '"') goto yy18; ++YYCURSOR; #line 703 "ext/standard/var_unserializer.re" { size_t len, maxlen; char *str; len = parse_uiv(start + 2); maxlen = max - YYCURSOR; if (maxlen < len) { *p = start + 2; return 0; } str = (char*)YYCURSOR; YYCURSOR += len; if (*(YYCURSOR) != '"') { *p = YYCURSOR; return 0; } if (*(YYCURSOR + 1) != ';') { *p = YYCURSOR + 1; return 0; } YYCURSOR += 2; *p = YYCURSOR; ZVAL_STRINGL(rval, str, len); return 1; } #line 1067 "ext/standard/var_unserializer.c" yy53: yych = *++YYCURSOR; if (yych <= '/') { if (yych <= ',') { if (yych == '+') goto yy57; goto yy18; } else { if (yych <= '-') goto yy55; if (yych <= '.') goto yy60; goto yy18; } } else { if (yych <= 'I') { if (yych <= '9') goto yy58; if (yych <= 'H') goto yy18; goto yy56; } else { if (yych != 'N') goto yy18; } } yych = *++YYCURSOR; if (yych == 'A') goto yy76; goto yy18; yy55: yych = *++YYCURSOR; if (yych <= '/') { if (yych == '.') goto yy60; goto yy18; } else { if (yych <= '9') goto yy58; if (yych != 'I') goto yy18; } yy56: yych = *++YYCURSOR; if (yych == 'N') goto yy72; goto yy18; yy57: yych = *++YYCURSOR; if (yych == '.') goto yy60; if (yych <= '/') goto yy18; if (yych >= ':') goto yy18; yy58: ++YYCURSOR; if ((YYLIMIT - YYCURSOR) < 4) YYFILL(4); yych = *YYCURSOR; if (yych <= ':') { if (yych <= '.') { if (yych <= '-') goto yy18; goto yy70; } else { if (yych <= '/') goto yy18; if (yych <= '9') goto yy58; goto yy18; } } else { if (yych <= 'E') { if (yych <= ';') goto yy63; if (yych <= 'D') goto yy18; goto yy65; } else { if (yych == 'e') goto yy65; goto yy18; } } yy60: yych = *++YYCURSOR; if (yych <= '/') goto yy18; if (yych >= ':') goto yy18; yy61: ++YYCURSOR; if ((YYLIMIT - YYCURSOR) < 4) YYFILL(4); yych = *YYCURSOR; if (yych <= ';') { if (yych <= '/') goto yy18; if (yych <= '9') goto yy61; if (yych <= ':') goto yy18; } else { if (yych <= 'E') { if (yych <= 'D') goto yy18; goto yy65; } else { if (yych == 'e') goto yy65; goto yy18; } } yy63: ++YYCURSOR; #line 694 "ext/standard/var_unserializer.re" { #if SIZEOF_ZEND_LONG == 4 use_double: #endif *p = YYCURSOR; ZVAL_DOUBLE(rval, zend_strtod((const char *)start + 2, NULL)); return 1; } #line 1164 "ext/standard/var_unserializer.c" yy65: yych = *++YYCURSOR; if (yych <= ',') { if (yych != '+') goto yy18; } else { if (yych <= '-') goto yy66; if (yych <= '/') goto yy18; if (yych <= '9') goto yy67; goto yy18; } yy66: yych = *++YYCURSOR; if (yych <= ',') { if (yych == '+') goto yy69; goto yy18; } else { if (yych <= '-') goto yy69; if (yych <= '/') goto yy18; if (yych >= ':') goto yy18; } yy67: ++YYCURSOR; if (YYLIMIT <= YYCURSOR) YYFILL(1); yych = *YYCURSOR; if (yych <= '/') goto yy18; if (yych <= '9') goto yy67; if (yych == ';') goto yy63; goto yy18; yy69: yych = *++YYCURSOR; if (yych <= '/') goto yy18; if (yych <= '9') goto yy67; goto yy18; yy70: ++YYCURSOR; if ((YYLIMIT - YYCURSOR) < 4) YYFILL(4); yych = *YYCURSOR; if (yych <= ';') { if (yych <= '/') goto yy18; if (yych <= '9') goto yy70; if (yych <= ':') goto yy18; goto yy63; } else { if (yych <= 'E') { if (yych <= 'D') goto yy18; goto yy65; } else { if (yych == 'e') goto yy65; goto yy18; } } yy72: yych = *++YYCURSOR; if (yych != 'F') goto yy18; yy73: yych = *++YYCURSOR; if (yych != ';') goto yy18; ++YYCURSOR; #line 678 "ext/standard/var_unserializer.re" { *p = YYCURSOR; if (!strncmp((char*)start + 2, "NAN", 3)) { ZVAL_DOUBLE(rval, php_get_nan()); } else if (!strncmp((char*)start + 2, "INF", 3)) { ZVAL_DOUBLE(rval, php_get_inf()); } else if (!strncmp((char*)start + 2, "-INF", 4)) { ZVAL_DOUBLE(rval, -php_get_inf()); } else { ZVAL_NULL(rval); } return 1; } #line 1239 "ext/standard/var_unserializer.c" yy76: yych = *++YYCURSOR; if (yych == 'N') goto yy73; goto yy18; yy77: yych = *++YYCURSOR; if (yych <= ',') { if (yych != '+') goto yy18; } else { if (yych <= '-') goto yy78; if (yych <= '/') goto yy18; if (yych <= '9') goto yy79; goto yy18; } yy78: yych = *++YYCURSOR; if (yych <= '/') goto yy18; if (yych >= ':') goto yy18; yy79: ++YYCURSOR; if (YYLIMIT <= YYCURSOR) YYFILL(1); yych = *YYCURSOR; if (yych <= '/') goto yy18; if (yych <= '9') goto yy79; if (yych != ';') goto yy18; ++YYCURSOR; #line 652 "ext/standard/var_unserializer.re" { #if SIZEOF_ZEND_LONG == 4 int digits = YYCURSOR - start - 3; if (start[2] == '-' || start[2] == '+') { digits--; } /* Use double for large zend_long values that were serialized on a 64-bit system */ if (digits >= MAX_LENGTH_OF_LONG - 1) { if (digits == MAX_LENGTH_OF_LONG - 1) { int cmp = strncmp((char*)YYCURSOR - MAX_LENGTH_OF_LONG, long_min_digits, MAX_LENGTH_OF_LONG - 1); if (!(cmp < 0 || (cmp == 0 && start[2] == '-'))) { goto use_double; } } else { goto use_double; } } #endif *p = YYCURSOR; ZVAL_LONG(rval, parse_iv(start + 2)); return 1; } #line 1292 "ext/standard/var_unserializer.c" yy83: yych = *++YYCURSOR; if (yych <= '/') goto yy18; if (yych >= '2') goto yy18; yych = *++YYCURSOR; if (yych != ';') goto yy18; ++YYCURSOR; #line 646 "ext/standard/var_unserializer.re" { *p = YYCURSOR; ZVAL_BOOL(rval, parse_iv(start + 2)); return 1; } #line 1306 "ext/standard/var_unserializer.c" yy87: ++YYCURSOR; #line 640 "ext/standard/var_unserializer.re" { *p = YYCURSOR; ZVAL_NULL(rval); return 1; } #line 1315 "ext/standard/var_unserializer.c" yy89: yych = *++YYCURSOR; if (yych <= ',') { if (yych != '+') goto yy18; } else { if (yych <= '-') goto yy90; if (yych <= '/') goto yy18; if (yych <= '9') goto yy91; goto yy18; } yy90: yych = *++YYCURSOR; if (yych <= '/') goto yy18; if (yych >= ':') goto yy18; yy91: ++YYCURSOR; if (YYLIMIT <= YYCURSOR) YYFILL(1); yych = *YYCURSOR; if (yych <= '/') goto yy18; if (yych <= '9') goto yy91; if (yych != ';') goto yy18; ++YYCURSOR; #line 615 "ext/standard/var_unserializer.re" { zend_long id; *p = YYCURSOR; if (!var_hash) return 0; id = parse_iv(start + 2) - 1; if (id == -1 || (rval_ref = var_access(var_hash, id)) == NULL) { return 0; } if (rval_ref == rval) { return 0; } if (Z_ISUNDEF_P(rval_ref) || (Z_ISREF_P(rval_ref) && Z_ISUNDEF_P(Z_REFVAL_P(rval_ref)))) { ZVAL_UNDEF(rval); return 1; } ZVAL_COPY(rval, rval_ref); return 1; } #line 1363 "ext/standard/var_unserializer.c" yy95: yych = *++YYCURSOR; if (yych <= ',') { if (yych != '+') goto yy18; } else { if (yych <= '-') goto yy96; if (yych <= '/') goto yy18; if (yych <= '9') goto yy97; goto yy18; } yy96: yych = *++YYCURSOR; if (yych <= '/') goto yy18; if (yych >= ':') goto yy18; yy97: ++YYCURSOR; if (YYLIMIT <= YYCURSOR) YYFILL(1); yych = *YYCURSOR; if (yych <= '/') goto yy18; if (yych <= '9') goto yy97; if (yych != ';') goto yy18; ++YYCURSOR; #line 589 "ext/standard/var_unserializer.re" { zend_long id; *p = YYCURSOR; if (!var_hash) return 0; id = parse_iv(start + 2) - 1; if (id == -1 || (rval_ref = var_access(var_hash, id)) == NULL) { return 0; } zval_ptr_dtor(rval); if (Z_ISUNDEF_P(rval_ref) || (Z_ISREF_P(rval_ref) && Z_ISUNDEF_P(Z_REFVAL_P(rval_ref)))) { ZVAL_UNDEF(rval); return 1; } if (Z_ISREF_P(rval_ref)) { ZVAL_COPY(rval, rval_ref); } else { ZVAL_NEW_REF(rval_ref, rval_ref); ZVAL_COPY(rval, rval_ref); } return 1; } #line 1412 "ext/standard/var_unserializer.c" } #line 964 "ext/standard/var_unserializer.re" return 0; } Commit Message: Fixed bug #74103 and bug #75054 Directly fail unserialization when trying to acquire an r/R reference to an UNDEF HT slot. Previously this left an UNDEF and later deleted the index/key from the HT. What actually caused the issue here is a combination of two factors: First, the key deletion was performed using the hash API, rather than the symtable API, such that the element was not actually removed if it used an integral string key. Second, a subsequent deletion operation, while collecting trailing UNDEF ranges, would mark the element as available for reuse (leaving a corrupted HT state with nNumOfElemnts > nNumUsed). Fix this by failing early and dropping the deletion code. CWE ID: CWE-416
static int php_var_unserialize_internal(UNSERIALIZE_PARAMETER) { const unsigned char *cursor, *limit, *marker, *start; zval *rval_ref; limit = max; cursor = *p; if (YYCURSOR >= YYLIMIT) { return 0; } if (var_hash && (*p)[0] != 'R') { var_push(var_hash, rval); } start = cursor; #line 576 "ext/standard/var_unserializer.c" { YYCTYPE yych; static const unsigned char yybm[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; if ((YYLIMIT - YYCURSOR) < 7) YYFILL(7); yych = *YYCURSOR; switch (yych) { case 'C': case 'O': goto yy4; case 'N': goto yy5; case 'R': goto yy6; case 'S': goto yy7; case 'a': goto yy8; case 'b': goto yy9; case 'd': goto yy10; case 'i': goto yy11; case 'o': goto yy12; case 'r': goto yy13; case 's': goto yy14; case '}': goto yy15; default: goto yy2; } yy2: ++YYCURSOR; yy3: #line 951 "ext/standard/var_unserializer.re" { return 0; } #line 636 "ext/standard/var_unserializer.c" yy4: yych = *(YYMARKER = ++YYCURSOR); if (yych == ':') goto yy17; goto yy3; yy5: yych = *++YYCURSOR; if (yych == ';') goto yy19; goto yy3; yy6: yych = *(YYMARKER = ++YYCURSOR); if (yych == ':') goto yy21; goto yy3; yy7: yych = *(YYMARKER = ++YYCURSOR); if (yych == ':') goto yy22; goto yy3; yy8: yych = *(YYMARKER = ++YYCURSOR); if (yych == ':') goto yy23; goto yy3; yy9: yych = *(YYMARKER = ++YYCURSOR); if (yych == ':') goto yy24; goto yy3; yy10: yych = *(YYMARKER = ++YYCURSOR); if (yych == ':') goto yy25; goto yy3; yy11: yych = *(YYMARKER = ++YYCURSOR); if (yych == ':') goto yy26; goto yy3; yy12: yych = *(YYMARKER = ++YYCURSOR); if (yych == ':') goto yy27; goto yy3; yy13: yych = *(YYMARKER = ++YYCURSOR); if (yych == ':') goto yy28; goto yy3; yy14: yych = *(YYMARKER = ++YYCURSOR); if (yych == ':') goto yy29; goto yy3; yy15: ++YYCURSOR; #line 945 "ext/standard/var_unserializer.re" { /* this is the case where we have less data than planned */ php_error_docref(NULL, E_NOTICE, "Unexpected end of serialized data"); return 0; /* not sure if it should be 0 or 1 here? */ } #line 689 "ext/standard/var_unserializer.c" yy17: yych = *++YYCURSOR; if (yybm[0+yych] & 128) { goto yy31; } if (yych == '+') goto yy30; yy18: YYCURSOR = YYMARKER; goto yy3; yy19: ++YYCURSOR; #line 629 "ext/standard/var_unserializer.re" { *p = YYCURSOR; ZVAL_NULL(rval); return 1; } #line 707 "ext/standard/var_unserializer.c" yy21: yych = *++YYCURSOR; if (yych <= ',') { if (yych == '+') goto yy33; goto yy18; } else { if (yych <= '-') goto yy33; if (yych <= '/') goto yy18; if (yych <= '9') goto yy34; goto yy18; } yy22: yych = *++YYCURSOR; if (yych == '+') goto yy36; if (yych <= '/') goto yy18; if (yych <= '9') goto yy37; goto yy18; yy23: yych = *++YYCURSOR; if (yych == '+') goto yy39; if (yych <= '/') goto yy18; if (yych <= '9') goto yy40; goto yy18; yy24: yych = *++YYCURSOR; if (yych <= '/') goto yy18; if (yych <= '1') goto yy42; goto yy18; yy25: yych = *++YYCURSOR; if (yych <= '/') { if (yych <= ',') { if (yych == '+') goto yy43; goto yy18; } else { if (yych <= '-') goto yy44; if (yych <= '.') goto yy45; goto yy18; } } else { if (yych <= 'I') { if (yych <= '9') goto yy46; if (yych <= 'H') goto yy18; goto yy48; } else { if (yych == 'N') goto yy49; goto yy18; } } yy26: yych = *++YYCURSOR; if (yych <= ',') { if (yych == '+') goto yy50; goto yy18; } else { if (yych <= '-') goto yy50; if (yych <= '/') goto yy18; if (yych <= '9') goto yy51; goto yy18; } yy27: yych = *++YYCURSOR; if (yych <= ',') { if (yych == '+') goto yy53; goto yy18; } else { if (yych <= '-') goto yy53; if (yych <= '/') goto yy18; if (yych <= '9') goto yy54; goto yy18; } yy28: yych = *++YYCURSOR; if (yych <= ',') { if (yych == '+') goto yy56; goto yy18; } else { if (yych <= '-') goto yy56; if (yych <= '/') goto yy18; if (yych <= '9') goto yy57; goto yy18; } yy29: yych = *++YYCURSOR; if (yych == '+') goto yy59; if (yych <= '/') goto yy18; if (yych <= '9') goto yy60; goto yy18; yy30: yych = *++YYCURSOR; if (yybm[0+yych] & 128) { goto yy31; } goto yy18; yy31: ++YYCURSOR; if ((YYLIMIT - YYCURSOR) < 2) YYFILL(2); yych = *YYCURSOR; if (yybm[0+yych] & 128) { goto yy31; } if (yych <= '/') goto yy18; if (yych <= ':') goto yy62; goto yy18; yy33: yych = *++YYCURSOR; if (yych <= '/') goto yy18; if (yych >= ':') goto yy18; yy34: ++YYCURSOR; if (YYLIMIT <= YYCURSOR) YYFILL(1); yych = *YYCURSOR; if (yych <= '/') goto yy18; if (yych <= '9') goto yy34; if (yych == ';') goto yy63; goto yy18; yy36: yych = *++YYCURSOR; if (yych <= '/') goto yy18; if (yych >= ':') goto yy18; yy37: ++YYCURSOR; if ((YYLIMIT - YYCURSOR) < 2) YYFILL(2); yych = *YYCURSOR; if (yych <= '/') goto yy18; if (yych <= '9') goto yy37; if (yych <= ':') goto yy65; goto yy18; yy39: yych = *++YYCURSOR; if (yych <= '/') goto yy18; if (yych >= ':') goto yy18; yy40: ++YYCURSOR; if ((YYLIMIT - YYCURSOR) < 2) YYFILL(2); yych = *YYCURSOR; if (yych <= '/') goto yy18; if (yych <= '9') goto yy40; if (yych <= ':') goto yy66; goto yy18; yy42: yych = *++YYCURSOR; if (yych == ';') goto yy67; goto yy18; yy43: yych = *++YYCURSOR; if (yych == '.') goto yy45; if (yych <= '/') goto yy18; if (yych <= '9') goto yy46; goto yy18; yy44: yych = *++YYCURSOR; if (yych <= '/') { if (yych != '.') goto yy18; } else { if (yych <= '9') goto yy46; if (yych == 'I') goto yy48; goto yy18; } yy45: yych = *++YYCURSOR; if (yych <= '/') goto yy18; if (yych <= '9') goto yy69; goto yy18; yy46: ++YYCURSOR; if ((YYLIMIT - YYCURSOR) < 4) YYFILL(4); yych = *YYCURSOR; if (yych <= ':') { if (yych <= '.') { if (yych <= '-') goto yy18; goto yy69; } else { if (yych <= '/') goto yy18; if (yych <= '9') goto yy46; goto yy18; } } else { if (yych <= 'E') { if (yych <= ';') goto yy71; if (yych <= 'D') goto yy18; goto yy73; } else { if (yych == 'e') goto yy73; goto yy18; } } yy48: yych = *++YYCURSOR; if (yych == 'N') goto yy74; goto yy18; yy49: yych = *++YYCURSOR; if (yych == 'A') goto yy75; goto yy18; yy50: yych = *++YYCURSOR; if (yych <= '/') goto yy18; if (yych >= ':') goto yy18; yy51: ++YYCURSOR; if (YYLIMIT <= YYCURSOR) YYFILL(1); yych = *YYCURSOR; if (yych <= '/') goto yy18; if (yych <= '9') goto yy51; if (yych == ';') goto yy76; goto yy18; yy53: yych = *++YYCURSOR; if (yych <= '/') goto yy18; if (yych >= ':') goto yy18; yy54: ++YYCURSOR; if ((YYLIMIT - YYCURSOR) < 2) YYFILL(2); yych = *YYCURSOR; if (yych <= '/') goto yy18; if (yych <= '9') goto yy54; if (yych <= ':') goto yy78; goto yy18; yy56: yych = *++YYCURSOR; if (yych <= '/') goto yy18; if (yych >= ':') goto yy18; yy57: ++YYCURSOR; if (YYLIMIT <= YYCURSOR) YYFILL(1); yych = *YYCURSOR; if (yych <= '/') goto yy18; if (yych <= '9') goto yy57; if (yych == ';') goto yy79; goto yy18; yy59: yych = *++YYCURSOR; if (yych <= '/') goto yy18; if (yych >= ':') goto yy18; yy60: ++YYCURSOR; if ((YYLIMIT - YYCURSOR) < 2) YYFILL(2); yych = *YYCURSOR; if (yych <= '/') goto yy18; if (yych <= '9') goto yy60; if (yych <= ':') goto yy81; goto yy18; yy62: yych = *++YYCURSOR; if (yych == '"') goto yy82; goto yy18; yy63: ++YYCURSOR; #line 580 "ext/standard/var_unserializer.re" { zend_long id; *p = YYCURSOR; if (!var_hash) return 0; id = parse_iv(start + 2) - 1; if (id == -1 || (rval_ref = var_access(var_hash, id)) == NULL) { return 0; } if (Z_ISUNDEF_P(rval_ref) || (Z_ISREF_P(rval_ref) && Z_ISUNDEF_P(Z_REFVAL_P(rval_ref)))) { return 0; } if (Z_ISREF_P(rval_ref)) { ZVAL_COPY(rval, rval_ref); } else { ZVAL_NEW_REF(rval_ref, rval_ref); ZVAL_COPY(rval, rval_ref); } return 1; } #line 982 "ext/standard/var_unserializer.c" yy65: yych = *++YYCURSOR; if (yych == '"') goto yy84; goto yy18; yy66: yych = *++YYCURSOR; if (yych == '{') goto yy86; goto yy18; yy67: ++YYCURSOR; #line 635 "ext/standard/var_unserializer.re" { *p = YYCURSOR; ZVAL_BOOL(rval, parse_iv(start + 2)); return 1; } #line 999 "ext/standard/var_unserializer.c" yy69: ++YYCURSOR; if ((YYLIMIT - YYCURSOR) < 4) YYFILL(4); yych = *YYCURSOR; if (yych <= ';') { if (yych <= '/') goto yy18; if (yych <= '9') goto yy69; if (yych <= ':') goto yy18; } else { if (yych <= 'E') { if (yych <= 'D') goto yy18; goto yy73; } else { if (yych == 'e') goto yy73; goto yy18; } } yy71: ++YYCURSOR; #line 683 "ext/standard/var_unserializer.re" { #if SIZEOF_ZEND_LONG == 4 use_double: #endif *p = YYCURSOR; ZVAL_DOUBLE(rval, zend_strtod((const char *)start + 2, NULL)); return 1; } #line 1028 "ext/standard/var_unserializer.c" yy73: yych = *++YYCURSOR; if (yych <= ',') { if (yych == '+') goto yy88; goto yy18; } else { if (yych <= '-') goto yy88; if (yych <= '/') goto yy18; if (yych <= '9') goto yy89; goto yy18; } yy74: yych = *++YYCURSOR; if (yych == 'F') goto yy91; goto yy18; yy75: yych = *++YYCURSOR; if (yych == 'N') goto yy91; goto yy18; yy76: ++YYCURSOR; #line 641 "ext/standard/var_unserializer.re" { #if SIZEOF_ZEND_LONG == 4 int digits = YYCURSOR - start - 3; if (start[2] == '-' || start[2] == '+') { digits--; } /* Use double for large zend_long values that were serialized on a 64-bit system */ if (digits >= MAX_LENGTH_OF_LONG - 1) { if (digits == MAX_LENGTH_OF_LONG - 1) { int cmp = strncmp((char*)YYCURSOR - MAX_LENGTH_OF_LONG, long_min_digits, MAX_LENGTH_OF_LONG - 1); if (!(cmp < 0 || (cmp == 0 && start[2] == '-'))) { goto use_double; } } else { goto use_double; } } #endif *p = YYCURSOR; ZVAL_LONG(rval, parse_iv(start + 2)); return 1; } #line 1076 "ext/standard/var_unserializer.c" yy78: yych = *++YYCURSOR; if (yych == '"') goto yy92; goto yy18; yy79: ++YYCURSOR; #line 605 "ext/standard/var_unserializer.re" { zend_long id; *p = YYCURSOR; if (!var_hash) return 0; id = parse_iv(start + 2) - 1; if (id == -1 || (rval_ref = var_access(var_hash, id)) == NULL) { return 0; } if (rval_ref == rval) { return 0; } if (Z_ISUNDEF_P(rval_ref) || (Z_ISREF_P(rval_ref) && Z_ISUNDEF_P(Z_REFVAL_P(rval_ref)))) { return 0; } ZVAL_COPY(rval, rval_ref); return 1; } #line 1107 "ext/standard/var_unserializer.c" yy81: yych = *++YYCURSOR; if (yych == '"') goto yy94; goto yy18; yy82: ++YYCURSOR; #line 793 "ext/standard/var_unserializer.re" { size_t len, len2, len3, maxlen; zend_long elements; char *str; zend_string *class_name; zend_class_entry *ce; int incomplete_class = 0; int custom_object = 0; zval user_func; zval retval; zval args[1]; if (!var_hash) return 0; if (*start == 'C') { custom_object = 1; } len2 = len = parse_uiv(start + 2); maxlen = max - YYCURSOR; if (maxlen < len || len == 0) { *p = start + 2; return 0; } str = (char*)YYCURSOR; YYCURSOR += len; if (*(YYCURSOR) != '"') { *p = YYCURSOR; return 0; } if (*(YYCURSOR+1) != ':') { *p = YYCURSOR+1; return 0; } len3 = strspn(str, "0123456789_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\177\200\201\202\203\204\205\206\207\210\211\212\213\214\215\216\217\220\221\222\223\224\225\226\227\230\231\232\233\234\235\236\237\240\241\242\243\244\245\246\247\250\251\252\253\254\255\256\257\260\261\262\263\264\265\266\267\270\271\272\273\274\275\276\277\300\301\302\303\304\305\306\307\310\311\312\313\314\315\316\317\320\321\322\323\324\325\326\327\330\331\332\333\334\335\336\337\340\341\342\343\344\345\346\347\350\351\352\353\354\355\356\357\360\361\362\363\364\365\366\367\370\371\372\373\374\375\376\377\\"); if (len3 != len) { *p = YYCURSOR + len3 - len; return 0; } class_name = zend_string_init(str, len, 0); do { if(!unserialize_allowed_class(class_name, classes)) { incomplete_class = 1; ce = PHP_IC_ENTRY; break; } /* Try to find class directly */ BG(serialize_lock)++; ce = zend_lookup_class(class_name); if (ce) { BG(serialize_lock)--; if (EG(exception)) { zend_string_release(class_name); return 0; } break; } BG(serialize_lock)--; if (EG(exception)) { zend_string_release(class_name); return 0; } /* Check for unserialize callback */ if ((PG(unserialize_callback_func) == NULL) || (PG(unserialize_callback_func)[0] == '\0')) { incomplete_class = 1; ce = PHP_IC_ENTRY; break; } /* Call unserialize callback */ ZVAL_STRING(&user_func, PG(unserialize_callback_func)); ZVAL_STR_COPY(&args[0], class_name); BG(serialize_lock)++; if (call_user_function_ex(CG(function_table), NULL, &user_func, &retval, 1, args, 0, NULL) != SUCCESS) { BG(serialize_lock)--; if (EG(exception)) { zend_string_release(class_name); zval_ptr_dtor(&user_func); zval_ptr_dtor(&args[0]); return 0; } php_error_docref(NULL, E_WARNING, "defined (%s) but not found", Z_STRVAL(user_func)); incomplete_class = 1; ce = PHP_IC_ENTRY; zval_ptr_dtor(&user_func); zval_ptr_dtor(&args[0]); break; } BG(serialize_lock)--; zval_ptr_dtor(&retval); if (EG(exception)) { zend_string_release(class_name); zval_ptr_dtor(&user_func); zval_ptr_dtor(&args[0]); return 0; } /* The callback function may have defined the class */ BG(serialize_lock)++; if ((ce = zend_lookup_class(class_name)) == NULL) { php_error_docref(NULL, E_WARNING, "Function %s() hasn't defined the class it was called for", Z_STRVAL(user_func)); incomplete_class = 1; ce = PHP_IC_ENTRY; } BG(serialize_lock)--; zval_ptr_dtor(&user_func); zval_ptr_dtor(&args[0]); break; } while (1); *p = YYCURSOR; if (custom_object) { int ret; ret = object_custom(UNSERIALIZE_PASSTHRU, ce); if (ret && incomplete_class) { php_store_class_name(rval, ZSTR_VAL(class_name), len2); } zend_string_release(class_name); return ret; } elements = object_common1(UNSERIALIZE_PASSTHRU, ce); if (elements < 0) { zend_string_release(class_name); return 0; } if (incomplete_class) { php_store_class_name(rval, ZSTR_VAL(class_name), len2); } zend_string_release(class_name); return object_common2(UNSERIALIZE_PASSTHRU, elements); } #line 1266 "ext/standard/var_unserializer.c" yy84: ++YYCURSOR; #line 724 "ext/standard/var_unserializer.re" { size_t len, maxlen; zend_string *str; len = parse_uiv(start + 2); maxlen = max - YYCURSOR; if (maxlen < len) { *p = start + 2; return 0; } if ((str = unserialize_str(&YYCURSOR, len, maxlen)) == NULL) { return 0; } if (*(YYCURSOR) != '"') { zend_string_free(str); *p = YYCURSOR; return 0; } if (*(YYCURSOR + 1) != ';') { efree(str); *p = YYCURSOR + 1; return 0; } YYCURSOR += 2; *p = YYCURSOR; ZVAL_STR(rval, str); return 1; } #line 1303 "ext/standard/var_unserializer.c" yy86: ++YYCURSOR; #line 758 "ext/standard/var_unserializer.re" { zend_long elements = parse_iv(start + 2); /* use iv() not uiv() in order to check data range */ *p = YYCURSOR; if (!var_hash) return 0; if (elements < 0 || elements >= HT_MAX_SIZE) { return 0; } array_init_size(rval, elements); if (elements) { /* we can't convert from packed to hash during unserialization, because reference to some zvals might be keept in var_hash (to support references) */ zend_hash_real_init(Z_ARRVAL_P(rval), 0); } if (!process_nested_data(UNSERIALIZE_PASSTHRU, Z_ARRVAL_P(rval), elements, 0)) { return 0; } return finish_nested_data(UNSERIALIZE_PASSTHRU); } #line 1330 "ext/standard/var_unserializer.c" yy88: yych = *++YYCURSOR; if (yych <= ',') { if (yych == '+') goto yy96; goto yy18; } else { if (yych <= '-') goto yy96; if (yych <= '/') goto yy18; if (yych >= ':') goto yy18; } yy89: ++YYCURSOR; if (YYLIMIT <= YYCURSOR) YYFILL(1); yych = *YYCURSOR; if (yych <= '/') goto yy18; if (yych <= '9') goto yy89; if (yych == ';') goto yy71; goto yy18; yy91: yych = *++YYCURSOR; if (yych == ';') goto yy97; goto yy18; yy92: ++YYCURSOR; #line 782 "ext/standard/var_unserializer.re" { zend_long elements; if (!var_hash) return 0; elements = object_common1(UNSERIALIZE_PASSTHRU, ZEND_STANDARD_CLASS_DEF_PTR); if (elements < 0 || elements >= HT_MAX_SIZE) { return 0; } return object_common2(UNSERIALIZE_PASSTHRU, elements); } #line 1366 "ext/standard/var_unserializer.c" yy94: ++YYCURSOR; #line 692 "ext/standard/var_unserializer.re" { size_t len, maxlen; char *str; len = parse_uiv(start + 2); maxlen = max - YYCURSOR; if (maxlen < len) { *p = start + 2; return 0; } str = (char*)YYCURSOR; YYCURSOR += len; if (*(YYCURSOR) != '"') { *p = YYCURSOR; return 0; } if (*(YYCURSOR + 1) != ';') { *p = YYCURSOR + 1; return 0; } YYCURSOR += 2; *p = YYCURSOR; ZVAL_STRINGL(rval, str, len); return 1; } #line 1401 "ext/standard/var_unserializer.c" yy96: yych = *++YYCURSOR; if (yych <= '/') goto yy18; if (yych <= '9') goto yy89; goto yy18; yy97: ++YYCURSOR; #line 667 "ext/standard/var_unserializer.re" { *p = YYCURSOR; if (!strncmp((char*)start + 2, "NAN", 3)) { ZVAL_DOUBLE(rval, php_get_nan()); } else if (!strncmp((char*)start + 2, "INF", 3)) { ZVAL_DOUBLE(rval, php_get_inf()); } else if (!strncmp((char*)start + 2, "-INF", 4)) { ZVAL_DOUBLE(rval, -php_get_inf()); } else { ZVAL_NULL(rval); } return 1; } #line 1425 "ext/standard/var_unserializer.c" } #line 953 "ext/standard/var_unserializer.re" return 0; }
167,933
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: bgp_attr_parse_ret_t bgp_attr_parse(struct peer *peer, struct attr *attr, bgp_size_t size, struct bgp_nlri *mp_update, struct bgp_nlri *mp_withdraw) { bgp_attr_parse_ret_t ret; uint8_t flag = 0; uint8_t type = 0; bgp_size_t length; uint8_t *startp, *endp; uint8_t *attr_endp; uint8_t seen[BGP_ATTR_BITMAP_SIZE]; /* we need the as4_path only until we have synthesized the as_path with * it */ /* same goes for as4_aggregator */ struct aspath *as4_path = NULL; as_t as4_aggregator = 0; struct in_addr as4_aggregator_addr = {.s_addr = 0}; /* Initialize bitmap. */ memset(seen, 0, BGP_ATTR_BITMAP_SIZE); /* End pointer of BGP attribute. */ endp = BGP_INPUT_PNT(peer) + size; /* Get attributes to the end of attribute length. */ while (BGP_INPUT_PNT(peer) < endp) { /* Check remaining length check.*/ if (endp - BGP_INPUT_PNT(peer) < BGP_ATTR_MIN_LEN) { /* XXX warning: long int format, int arg (arg 5) */ flog_warn( EC_BGP_ATTRIBUTE_TOO_SMALL, "%s: error BGP attribute length %lu is smaller than min len", peer->host, (unsigned long)(endp - stream_pnt(BGP_INPUT(peer)))); bgp_notify_send(peer, BGP_NOTIFY_UPDATE_ERR, BGP_NOTIFY_UPDATE_ATTR_LENG_ERR); return BGP_ATTR_PARSE_ERROR; } /* Fetch attribute flag and type. */ startp = BGP_INPUT_PNT(peer); /* "The lower-order four bits of the Attribute Flags octet are unused. They MUST be zero when sent and MUST be ignored when received." */ flag = 0xF0 & stream_getc(BGP_INPUT(peer)); type = stream_getc(BGP_INPUT(peer)); /* Check whether Extended-Length applies and is in bounds */ if (CHECK_FLAG(flag, BGP_ATTR_FLAG_EXTLEN) && ((endp - startp) < (BGP_ATTR_MIN_LEN + 1))) { flog_warn( EC_BGP_EXT_ATTRIBUTE_TOO_SMALL, "%s: Extended length set, but just %lu bytes of attr header", peer->host, (unsigned long)(endp - stream_pnt(BGP_INPUT(peer)))); bgp_notify_send(peer, BGP_NOTIFY_UPDATE_ERR, BGP_NOTIFY_UPDATE_ATTR_LENG_ERR); return BGP_ATTR_PARSE_ERROR; } /* Check extended attribue length bit. */ if (CHECK_FLAG(flag, BGP_ATTR_FLAG_EXTLEN)) length = stream_getw(BGP_INPUT(peer)); else length = stream_getc(BGP_INPUT(peer)); /* If any attribute appears more than once in the UPDATE message, then the Error Subcode is set to Malformed Attribute List. */ if (CHECK_BITMAP(seen, type)) { flog_warn( EC_BGP_ATTRIBUTE_REPEATED, "%s: error BGP attribute type %d appears twice in a message", peer->host, type); bgp_notify_send(peer, BGP_NOTIFY_UPDATE_ERR, BGP_NOTIFY_UPDATE_MAL_ATTR); return BGP_ATTR_PARSE_ERROR; } /* Set type to bitmap to check duplicate attribute. `type' is unsigned char so it never overflow bitmap range. */ SET_BITMAP(seen, type); /* Overflow check. */ attr_endp = BGP_INPUT_PNT(peer) + length; if (attr_endp > endp) { flog_warn( EC_BGP_ATTRIBUTE_TOO_LARGE, "%s: BGP type %d length %d is too large, attribute total length is %d. attr_endp is %p. endp is %p", peer->host, type, length, size, attr_endp, endp); /* * RFC 4271 6.3 * If any recognized attribute has an Attribute * Length that conflicts with the expected length * (based on the attribute type code), then the * Error Subcode MUST be set to Attribute Length * Error. The Data field MUST contain the erroneous * attribute (type, length, and value). * ---------- * We do not currently have a good way to determine the * length of the attribute independent of the length * received in the message. Instead we send the * minimum between the amount of data we have and the * amount specified by the attribute length field. * * Instead of directly passing in the packet buffer and * offset we use the stream_get* functions to read into * a stack buffer, since they perform bounds checking * and we are working with untrusted data. */ unsigned char ndata[BGP_MAX_PACKET_SIZE]; memset(ndata, 0x00, sizeof(ndata)); size_t lfl = CHECK_FLAG(flag, BGP_ATTR_FLAG_EXTLEN) ? 2 : 1; /* Rewind to end of flag field */ stream_forward_getp(BGP_INPUT(peer), -(1 + lfl)); /* Type */ stream_get(&ndata[0], BGP_INPUT(peer), 1); /* Length */ stream_get(&ndata[1], BGP_INPUT(peer), lfl); /* Value */ size_t atl = attr_endp - startp; size_t ndl = MIN(atl, STREAM_READABLE(BGP_INPUT(peer))); stream_get(&ndata[lfl + 1], BGP_INPUT(peer), ndl); bgp_notify_send_with_data( peer, BGP_NOTIFY_UPDATE_ERR, BGP_NOTIFY_UPDATE_ATTR_LENG_ERR, ndata, ndl + lfl + 1); return BGP_ATTR_PARSE_ERROR; } struct bgp_attr_parser_args attr_args = { .peer = peer, .length = length, .attr = attr, .type = type, .flags = flag, .startp = startp, .total = attr_endp - startp, }; /* If any recognized attribute has Attribute Flags that conflict with the Attribute Type Code, then the Error Subcode is set to Attribute Flags Error. The Data field contains the erroneous attribute (type, length and value). */ if (bgp_attr_flag_invalid(&attr_args)) { ret = bgp_attr_malformed( &attr_args, BGP_NOTIFY_UPDATE_ATTR_FLAG_ERR, attr_args.total); if (ret == BGP_ATTR_PARSE_PROCEED) continue; return ret; } /* OK check attribute and store it's value. */ switch (type) { case BGP_ATTR_ORIGIN: ret = bgp_attr_origin(&attr_args); break; case BGP_ATTR_AS_PATH: ret = bgp_attr_aspath(&attr_args); break; case BGP_ATTR_AS4_PATH: ret = bgp_attr_as4_path(&attr_args, &as4_path); break; case BGP_ATTR_NEXT_HOP: ret = bgp_attr_nexthop(&attr_args); break; case BGP_ATTR_MULTI_EXIT_DISC: ret = bgp_attr_med(&attr_args); break; case BGP_ATTR_LOCAL_PREF: ret = bgp_attr_local_pref(&attr_args); break; case BGP_ATTR_ATOMIC_AGGREGATE: ret = bgp_attr_atomic(&attr_args); break; case BGP_ATTR_AGGREGATOR: ret = bgp_attr_aggregator(&attr_args); break; case BGP_ATTR_AS4_AGGREGATOR: ret = bgp_attr_as4_aggregator(&attr_args, &as4_aggregator, &as4_aggregator_addr); break; case BGP_ATTR_COMMUNITIES: ret = bgp_attr_community(&attr_args); break; case BGP_ATTR_LARGE_COMMUNITIES: ret = bgp_attr_large_community(&attr_args); break; case BGP_ATTR_ORIGINATOR_ID: ret = bgp_attr_originator_id(&attr_args); break; case BGP_ATTR_CLUSTER_LIST: ret = bgp_attr_cluster_list(&attr_args); break; case BGP_ATTR_MP_REACH_NLRI: ret = bgp_mp_reach_parse(&attr_args, mp_update); break; case BGP_ATTR_MP_UNREACH_NLRI: ret = bgp_mp_unreach_parse(&attr_args, mp_withdraw); break; case BGP_ATTR_EXT_COMMUNITIES: ret = bgp_attr_ext_communities(&attr_args); break; #if ENABLE_BGP_VNC case BGP_ATTR_VNC: #endif case BGP_ATTR_ENCAP: ret = bgp_attr_encap(type, peer, length, attr, flag, startp); break; case BGP_ATTR_PREFIX_SID: ret = bgp_attr_prefix_sid(length, &attr_args, mp_update); break; case BGP_ATTR_PMSI_TUNNEL: ret = bgp_attr_pmsi_tunnel(&attr_args); break; default: ret = bgp_attr_unknown(&attr_args); break; } if (ret == BGP_ATTR_PARSE_ERROR_NOTIFYPLS) { bgp_notify_send(peer, BGP_NOTIFY_UPDATE_ERR, BGP_NOTIFY_UPDATE_MAL_ATTR); ret = BGP_ATTR_PARSE_ERROR; } if (ret == BGP_ATTR_PARSE_EOR) { if (as4_path) aspath_unintern(&as4_path); return ret; } /* If hard error occurred immediately return to the caller. */ if (ret == BGP_ATTR_PARSE_ERROR) { flog_warn(EC_BGP_ATTRIBUTE_PARSE_ERROR, "%s: Attribute %s, parse error", peer->host, lookup_msg(attr_str, type, NULL)); if (as4_path) aspath_unintern(&as4_path); return ret; } if (ret == BGP_ATTR_PARSE_WITHDRAW) { flog_warn( EC_BGP_ATTRIBUTE_PARSE_WITHDRAW, "%s: Attribute %s, parse error - treating as withdrawal", peer->host, lookup_msg(attr_str, type, NULL)); if (as4_path) aspath_unintern(&as4_path); return ret; } /* Check the fetched length. */ if (BGP_INPUT_PNT(peer) != attr_endp) { flog_warn(EC_BGP_ATTRIBUTE_FETCH_ERROR, "%s: BGP attribute %s, fetch error", peer->host, lookup_msg(attr_str, type, NULL)); bgp_notify_send(peer, BGP_NOTIFY_UPDATE_ERR, BGP_NOTIFY_UPDATE_ATTR_LENG_ERR); if (as4_path) aspath_unintern(&as4_path); return BGP_ATTR_PARSE_ERROR; } } /* Check final read pointer is same as end pointer. */ if (BGP_INPUT_PNT(peer) != endp) { flog_warn(EC_BGP_ATTRIBUTES_MISMATCH, "%s: BGP attribute %s, length mismatch", peer->host, lookup_msg(attr_str, type, NULL)); bgp_notify_send(peer, BGP_NOTIFY_UPDATE_ERR, BGP_NOTIFY_UPDATE_ATTR_LENG_ERR); if (as4_path) aspath_unintern(&as4_path); return BGP_ATTR_PARSE_ERROR; } /* Check all mandatory well-known attributes are present */ if ((ret = bgp_attr_check(peer, attr)) < 0) { if (as4_path) aspath_unintern(&as4_path); return ret; } /* * At this place we can see whether we got AS4_PATH and/or * AS4_AGGREGATOR from a 16Bit peer and act accordingly. * We can not do this before we've read all attributes because * the as4 handling does not say whether AS4_PATH has to be sent * after AS_PATH or not - and when AS4_AGGREGATOR will be send * in relationship to AGGREGATOR. * So, to be defensive, we are not relying on any order and read * all attributes first, including these 32bit ones, and now, * afterwards, we look what and if something is to be done for as4. * * It is possible to not have AS_PATH, e.g. GR EoR and sole * MP_UNREACH_NLRI. */ /* actually... this doesn't ever return failure currently, but * better safe than sorry */ if (CHECK_FLAG(attr->flag, ATTR_FLAG_BIT(BGP_ATTR_AS_PATH)) && bgp_attr_munge_as4_attrs(peer, attr, as4_path, as4_aggregator, &as4_aggregator_addr)) { bgp_notify_send(peer, BGP_NOTIFY_UPDATE_ERR, BGP_NOTIFY_UPDATE_MAL_ATTR); if (as4_path) aspath_unintern(&as4_path); return BGP_ATTR_PARSE_ERROR; } /* At this stage, we have done all fiddling with as4, and the * resulting info is in attr->aggregator resp. attr->aspath * so we can chuck as4_aggregator and as4_path alltogether in * order to save memory */ if (as4_path) { aspath_unintern(&as4_path); /* unintern - it is in the hash */ /* The flag that we got this is still there, but that does not * do any trouble */ } /* * The "rest" of the code does nothing with as4_aggregator. * there is no memory attached specifically which is not part * of the attr. * so ignoring just means do nothing. */ /* * Finally do the checks on the aspath we did not do yet * because we waited for a potentially synthesized aspath. */ if (attr->flag & (ATTR_FLAG_BIT(BGP_ATTR_AS_PATH))) { ret = bgp_attr_aspath_check(peer, attr); if (ret != BGP_ATTR_PARSE_PROCEED) return ret; } /* Finally intern unknown attribute. */ if (attr->transit) attr->transit = transit_intern(attr->transit); if (attr->encap_subtlvs) attr->encap_subtlvs = encap_intern(attr->encap_subtlvs, ENCAP_SUBTLV_TYPE); #if ENABLE_BGP_VNC if (attr->vnc_subtlvs) attr->vnc_subtlvs = encap_intern(attr->vnc_subtlvs, VNC_SUBTLV_TYPE); #endif return BGP_ATTR_PARSE_PROCEED; } Commit Message: bgpd: don't use BGP_ATTR_VNC(255) unless ENABLE_BGP_VNC_ATTR is defined Signed-off-by: Lou Berger <[email protected]> CWE ID:
bgp_attr_parse_ret_t bgp_attr_parse(struct peer *peer, struct attr *attr, bgp_size_t size, struct bgp_nlri *mp_update, struct bgp_nlri *mp_withdraw) { bgp_attr_parse_ret_t ret; uint8_t flag = 0; uint8_t type = 0; bgp_size_t length; uint8_t *startp, *endp; uint8_t *attr_endp; uint8_t seen[BGP_ATTR_BITMAP_SIZE]; /* we need the as4_path only until we have synthesized the as_path with * it */ /* same goes for as4_aggregator */ struct aspath *as4_path = NULL; as_t as4_aggregator = 0; struct in_addr as4_aggregator_addr = {.s_addr = 0}; /* Initialize bitmap. */ memset(seen, 0, BGP_ATTR_BITMAP_SIZE); /* End pointer of BGP attribute. */ endp = BGP_INPUT_PNT(peer) + size; /* Get attributes to the end of attribute length. */ while (BGP_INPUT_PNT(peer) < endp) { /* Check remaining length check.*/ if (endp - BGP_INPUT_PNT(peer) < BGP_ATTR_MIN_LEN) { /* XXX warning: long int format, int arg (arg 5) */ flog_warn( EC_BGP_ATTRIBUTE_TOO_SMALL, "%s: error BGP attribute length %lu is smaller than min len", peer->host, (unsigned long)(endp - stream_pnt(BGP_INPUT(peer)))); bgp_notify_send(peer, BGP_NOTIFY_UPDATE_ERR, BGP_NOTIFY_UPDATE_ATTR_LENG_ERR); return BGP_ATTR_PARSE_ERROR; } /* Fetch attribute flag and type. */ startp = BGP_INPUT_PNT(peer); /* "The lower-order four bits of the Attribute Flags octet are unused. They MUST be zero when sent and MUST be ignored when received." */ flag = 0xF0 & stream_getc(BGP_INPUT(peer)); type = stream_getc(BGP_INPUT(peer)); /* Check whether Extended-Length applies and is in bounds */ if (CHECK_FLAG(flag, BGP_ATTR_FLAG_EXTLEN) && ((endp - startp) < (BGP_ATTR_MIN_LEN + 1))) { flog_warn( EC_BGP_EXT_ATTRIBUTE_TOO_SMALL, "%s: Extended length set, but just %lu bytes of attr header", peer->host, (unsigned long)(endp - stream_pnt(BGP_INPUT(peer)))); bgp_notify_send(peer, BGP_NOTIFY_UPDATE_ERR, BGP_NOTIFY_UPDATE_ATTR_LENG_ERR); return BGP_ATTR_PARSE_ERROR; } /* Check extended attribue length bit. */ if (CHECK_FLAG(flag, BGP_ATTR_FLAG_EXTLEN)) length = stream_getw(BGP_INPUT(peer)); else length = stream_getc(BGP_INPUT(peer)); /* If any attribute appears more than once in the UPDATE message, then the Error Subcode is set to Malformed Attribute List. */ if (CHECK_BITMAP(seen, type)) { flog_warn( EC_BGP_ATTRIBUTE_REPEATED, "%s: error BGP attribute type %d appears twice in a message", peer->host, type); bgp_notify_send(peer, BGP_NOTIFY_UPDATE_ERR, BGP_NOTIFY_UPDATE_MAL_ATTR); return BGP_ATTR_PARSE_ERROR; } /* Set type to bitmap to check duplicate attribute. `type' is unsigned char so it never overflow bitmap range. */ SET_BITMAP(seen, type); /* Overflow check. */ attr_endp = BGP_INPUT_PNT(peer) + length; if (attr_endp > endp) { flog_warn( EC_BGP_ATTRIBUTE_TOO_LARGE, "%s: BGP type %d length %d is too large, attribute total length is %d. attr_endp is %p. endp is %p", peer->host, type, length, size, attr_endp, endp); /* * RFC 4271 6.3 * If any recognized attribute has an Attribute * Length that conflicts with the expected length * (based on the attribute type code), then the * Error Subcode MUST be set to Attribute Length * Error. The Data field MUST contain the erroneous * attribute (type, length, and value). * ---------- * We do not currently have a good way to determine the * length of the attribute independent of the length * received in the message. Instead we send the * minimum between the amount of data we have and the * amount specified by the attribute length field. * * Instead of directly passing in the packet buffer and * offset we use the stream_get* functions to read into * a stack buffer, since they perform bounds checking * and we are working with untrusted data. */ unsigned char ndata[BGP_MAX_PACKET_SIZE]; memset(ndata, 0x00, sizeof(ndata)); size_t lfl = CHECK_FLAG(flag, BGP_ATTR_FLAG_EXTLEN) ? 2 : 1; /* Rewind to end of flag field */ stream_forward_getp(BGP_INPUT(peer), -(1 + lfl)); /* Type */ stream_get(&ndata[0], BGP_INPUT(peer), 1); /* Length */ stream_get(&ndata[1], BGP_INPUT(peer), lfl); /* Value */ size_t atl = attr_endp - startp; size_t ndl = MIN(atl, STREAM_READABLE(BGP_INPUT(peer))); stream_get(&ndata[lfl + 1], BGP_INPUT(peer), ndl); bgp_notify_send_with_data( peer, BGP_NOTIFY_UPDATE_ERR, BGP_NOTIFY_UPDATE_ATTR_LENG_ERR, ndata, ndl + lfl + 1); return BGP_ATTR_PARSE_ERROR; } struct bgp_attr_parser_args attr_args = { .peer = peer, .length = length, .attr = attr, .type = type, .flags = flag, .startp = startp, .total = attr_endp - startp, }; /* If any recognized attribute has Attribute Flags that conflict with the Attribute Type Code, then the Error Subcode is set to Attribute Flags Error. The Data field contains the erroneous attribute (type, length and value). */ if (bgp_attr_flag_invalid(&attr_args)) { ret = bgp_attr_malformed( &attr_args, BGP_NOTIFY_UPDATE_ATTR_FLAG_ERR, attr_args.total); if (ret == BGP_ATTR_PARSE_PROCEED) continue; return ret; } /* OK check attribute and store it's value. */ switch (type) { case BGP_ATTR_ORIGIN: ret = bgp_attr_origin(&attr_args); break; case BGP_ATTR_AS_PATH: ret = bgp_attr_aspath(&attr_args); break; case BGP_ATTR_AS4_PATH: ret = bgp_attr_as4_path(&attr_args, &as4_path); break; case BGP_ATTR_NEXT_HOP: ret = bgp_attr_nexthop(&attr_args); break; case BGP_ATTR_MULTI_EXIT_DISC: ret = bgp_attr_med(&attr_args); break; case BGP_ATTR_LOCAL_PREF: ret = bgp_attr_local_pref(&attr_args); break; case BGP_ATTR_ATOMIC_AGGREGATE: ret = bgp_attr_atomic(&attr_args); break; case BGP_ATTR_AGGREGATOR: ret = bgp_attr_aggregator(&attr_args); break; case BGP_ATTR_AS4_AGGREGATOR: ret = bgp_attr_as4_aggregator(&attr_args, &as4_aggregator, &as4_aggregator_addr); break; case BGP_ATTR_COMMUNITIES: ret = bgp_attr_community(&attr_args); break; case BGP_ATTR_LARGE_COMMUNITIES: ret = bgp_attr_large_community(&attr_args); break; case BGP_ATTR_ORIGINATOR_ID: ret = bgp_attr_originator_id(&attr_args); break; case BGP_ATTR_CLUSTER_LIST: ret = bgp_attr_cluster_list(&attr_args); break; case BGP_ATTR_MP_REACH_NLRI: ret = bgp_mp_reach_parse(&attr_args, mp_update); break; case BGP_ATTR_MP_UNREACH_NLRI: ret = bgp_mp_unreach_parse(&attr_args, mp_withdraw); break; case BGP_ATTR_EXT_COMMUNITIES: ret = bgp_attr_ext_communities(&attr_args); break; #if ENABLE_BGP_VNC_ATTR case BGP_ATTR_VNC: #endif case BGP_ATTR_ENCAP: ret = bgp_attr_encap(type, peer, length, attr, flag, startp); break; case BGP_ATTR_PREFIX_SID: ret = bgp_attr_prefix_sid(length, &attr_args, mp_update); break; case BGP_ATTR_PMSI_TUNNEL: ret = bgp_attr_pmsi_tunnel(&attr_args); break; default: ret = bgp_attr_unknown(&attr_args); break; } if (ret == BGP_ATTR_PARSE_ERROR_NOTIFYPLS) { bgp_notify_send(peer, BGP_NOTIFY_UPDATE_ERR, BGP_NOTIFY_UPDATE_MAL_ATTR); ret = BGP_ATTR_PARSE_ERROR; } if (ret == BGP_ATTR_PARSE_EOR) { if (as4_path) aspath_unintern(&as4_path); return ret; } /* If hard error occurred immediately return to the caller. */ if (ret == BGP_ATTR_PARSE_ERROR) { flog_warn(EC_BGP_ATTRIBUTE_PARSE_ERROR, "%s: Attribute %s, parse error", peer->host, lookup_msg(attr_str, type, NULL)); if (as4_path) aspath_unintern(&as4_path); return ret; } if (ret == BGP_ATTR_PARSE_WITHDRAW) { flog_warn( EC_BGP_ATTRIBUTE_PARSE_WITHDRAW, "%s: Attribute %s, parse error - treating as withdrawal", peer->host, lookup_msg(attr_str, type, NULL)); if (as4_path) aspath_unintern(&as4_path); return ret; } /* Check the fetched length. */ if (BGP_INPUT_PNT(peer) != attr_endp) { flog_warn(EC_BGP_ATTRIBUTE_FETCH_ERROR, "%s: BGP attribute %s, fetch error", peer->host, lookup_msg(attr_str, type, NULL)); bgp_notify_send(peer, BGP_NOTIFY_UPDATE_ERR, BGP_NOTIFY_UPDATE_ATTR_LENG_ERR); if (as4_path) aspath_unintern(&as4_path); return BGP_ATTR_PARSE_ERROR; } } /* Check final read pointer is same as end pointer. */ if (BGP_INPUT_PNT(peer) != endp) { flog_warn(EC_BGP_ATTRIBUTES_MISMATCH, "%s: BGP attribute %s, length mismatch", peer->host, lookup_msg(attr_str, type, NULL)); bgp_notify_send(peer, BGP_NOTIFY_UPDATE_ERR, BGP_NOTIFY_UPDATE_ATTR_LENG_ERR); if (as4_path) aspath_unintern(&as4_path); return BGP_ATTR_PARSE_ERROR; } /* Check all mandatory well-known attributes are present */ if ((ret = bgp_attr_check(peer, attr)) < 0) { if (as4_path) aspath_unintern(&as4_path); return ret; } /* * At this place we can see whether we got AS4_PATH and/or * AS4_AGGREGATOR from a 16Bit peer and act accordingly. * We can not do this before we've read all attributes because * the as4 handling does not say whether AS4_PATH has to be sent * after AS_PATH or not - and when AS4_AGGREGATOR will be send * in relationship to AGGREGATOR. * So, to be defensive, we are not relying on any order and read * all attributes first, including these 32bit ones, and now, * afterwards, we look what and if something is to be done for as4. * * It is possible to not have AS_PATH, e.g. GR EoR and sole * MP_UNREACH_NLRI. */ /* actually... this doesn't ever return failure currently, but * better safe than sorry */ if (CHECK_FLAG(attr->flag, ATTR_FLAG_BIT(BGP_ATTR_AS_PATH)) && bgp_attr_munge_as4_attrs(peer, attr, as4_path, as4_aggregator, &as4_aggregator_addr)) { bgp_notify_send(peer, BGP_NOTIFY_UPDATE_ERR, BGP_NOTIFY_UPDATE_MAL_ATTR); if (as4_path) aspath_unintern(&as4_path); return BGP_ATTR_PARSE_ERROR; } /* At this stage, we have done all fiddling with as4, and the * resulting info is in attr->aggregator resp. attr->aspath * so we can chuck as4_aggregator and as4_path alltogether in * order to save memory */ if (as4_path) { aspath_unintern(&as4_path); /* unintern - it is in the hash */ /* The flag that we got this is still there, but that does not * do any trouble */ } /* * The "rest" of the code does nothing with as4_aggregator. * there is no memory attached specifically which is not part * of the attr. * so ignoring just means do nothing. */ /* * Finally do the checks on the aspath we did not do yet * because we waited for a potentially synthesized aspath. */ if (attr->flag & (ATTR_FLAG_BIT(BGP_ATTR_AS_PATH))) { ret = bgp_attr_aspath_check(peer, attr); if (ret != BGP_ATTR_PARSE_PROCEED) return ret; } /* Finally intern unknown attribute. */ if (attr->transit) attr->transit = transit_intern(attr->transit); if (attr->encap_subtlvs) attr->encap_subtlvs = encap_intern(attr->encap_subtlvs, ENCAP_SUBTLV_TYPE); #if ENABLE_BGP_VNC if (attr->vnc_subtlvs) attr->vnc_subtlvs = encap_intern(attr->vnc_subtlvs, VNC_SUBTLV_TYPE); #endif return BGP_ATTR_PARSE_PROCEED; }
169,742
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int hfsplus_rename_cat(u32 cnid, struct inode *src_dir, struct qstr *src_name, struct inode *dst_dir, struct qstr *dst_name) { struct super_block *sb = src_dir->i_sb; struct hfs_find_data src_fd, dst_fd; hfsplus_cat_entry entry; int entry_size, type; int err; dprint(DBG_CAT_MOD, "rename_cat: %u - %lu,%s - %lu,%s\n", cnid, src_dir->i_ino, src_name->name, dst_dir->i_ino, dst_name->name); err = hfs_find_init(HFSPLUS_SB(sb)->cat_tree, &src_fd); if (err) return err; dst_fd = src_fd; /* find the old dir entry and read the data */ hfsplus_cat_build_key(sb, src_fd.search_key, src_dir->i_ino, src_name); err = hfs_brec_find(&src_fd); if (err) goto out; hfs_bnode_read(src_fd.bnode, &entry, src_fd.entryoffset, src_fd.entrylength); /* create new dir entry with the data from the old entry */ hfsplus_cat_build_key(sb, dst_fd.search_key, dst_dir->i_ino, dst_name); err = hfs_brec_find(&dst_fd); if (err != -ENOENT) { if (!err) err = -EEXIST; goto out; } err = hfs_brec_insert(&dst_fd, &entry, src_fd.entrylength); if (err) goto out; dst_dir->i_size++; dst_dir->i_mtime = dst_dir->i_ctime = CURRENT_TIME_SEC; /* finally remove the old entry */ hfsplus_cat_build_key(sb, src_fd.search_key, src_dir->i_ino, src_name); err = hfs_brec_find(&src_fd); if (err) goto out; err = hfs_brec_remove(&src_fd); if (err) goto out; src_dir->i_size--; src_dir->i_mtime = src_dir->i_ctime = CURRENT_TIME_SEC; /* remove old thread entry */ hfsplus_cat_build_key(sb, src_fd.search_key, cnid, NULL); err = hfs_brec_find(&src_fd); if (err) goto out; type = hfs_bnode_read_u16(src_fd.bnode, src_fd.entryoffset); err = hfs_brec_remove(&src_fd); if (err) goto out; /* create new thread entry */ hfsplus_cat_build_key(sb, dst_fd.search_key, cnid, NULL); entry_size = hfsplus_fill_cat_thread(sb, &entry, type, dst_dir->i_ino, dst_name); err = hfs_brec_find(&dst_fd); if (err != -ENOENT) { if (!err) err = -EEXIST; goto out; } err = hfs_brec_insert(&dst_fd, &entry, entry_size); hfsplus_mark_inode_dirty(dst_dir, HFSPLUS_I_CAT_DIRTY); hfsplus_mark_inode_dirty(src_dir, HFSPLUS_I_CAT_DIRTY); out: hfs_bnode_put(dst_fd.bnode); hfs_find_exit(&src_fd); return err; } Commit Message: hfsplus: Fix potential buffer overflows Commit ec81aecb2966 ("hfs: fix a potential buffer overflow") fixed a few potential buffer overflows in the hfs filesystem. But as Timo Warns pointed out, these changes also need to be made on the hfsplus filesystem as well. Reported-by: Timo Warns <[email protected]> Acked-by: WANG Cong <[email protected]> Cc: Alexey Khoroshilov <[email protected]> Cc: Miklos Szeredi <[email protected]> Cc: Sage Weil <[email protected]> Cc: Eugene Teo <[email protected]> Cc: Roman Zippel <[email protected]> Cc: Al Viro <[email protected]> Cc: Christoph Hellwig <[email protected]> Cc: Alexey Dobriyan <[email protected]> Cc: Dave Anderson <[email protected]> Cc: stable <[email protected]> Cc: Andrew Morton <[email protected]> Signed-off-by: Greg Kroah-Hartman <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-264
int hfsplus_rename_cat(u32 cnid, struct inode *src_dir, struct qstr *src_name, struct inode *dst_dir, struct qstr *dst_name) { struct super_block *sb = src_dir->i_sb; struct hfs_find_data src_fd, dst_fd; hfsplus_cat_entry entry; int entry_size, type; int err; dprint(DBG_CAT_MOD, "rename_cat: %u - %lu,%s - %lu,%s\n", cnid, src_dir->i_ino, src_name->name, dst_dir->i_ino, dst_name->name); err = hfs_find_init(HFSPLUS_SB(sb)->cat_tree, &src_fd); if (err) return err; dst_fd = src_fd; /* find the old dir entry and read the data */ hfsplus_cat_build_key(sb, src_fd.search_key, src_dir->i_ino, src_name); err = hfs_brec_find(&src_fd); if (err) goto out; if (src_fd.entrylength > sizeof(entry) || src_fd.entrylength < 0) { err = -EIO; goto out; } hfs_bnode_read(src_fd.bnode, &entry, src_fd.entryoffset, src_fd.entrylength); /* create new dir entry with the data from the old entry */ hfsplus_cat_build_key(sb, dst_fd.search_key, dst_dir->i_ino, dst_name); err = hfs_brec_find(&dst_fd); if (err != -ENOENT) { if (!err) err = -EEXIST; goto out; } err = hfs_brec_insert(&dst_fd, &entry, src_fd.entrylength); if (err) goto out; dst_dir->i_size++; dst_dir->i_mtime = dst_dir->i_ctime = CURRENT_TIME_SEC; /* finally remove the old entry */ hfsplus_cat_build_key(sb, src_fd.search_key, src_dir->i_ino, src_name); err = hfs_brec_find(&src_fd); if (err) goto out; err = hfs_brec_remove(&src_fd); if (err) goto out; src_dir->i_size--; src_dir->i_mtime = src_dir->i_ctime = CURRENT_TIME_SEC; /* remove old thread entry */ hfsplus_cat_build_key(sb, src_fd.search_key, cnid, NULL); err = hfs_brec_find(&src_fd); if (err) goto out; type = hfs_bnode_read_u16(src_fd.bnode, src_fd.entryoffset); err = hfs_brec_remove(&src_fd); if (err) goto out; /* create new thread entry */ hfsplus_cat_build_key(sb, dst_fd.search_key, cnid, NULL); entry_size = hfsplus_fill_cat_thread(sb, &entry, type, dst_dir->i_ino, dst_name); err = hfs_brec_find(&dst_fd); if (err != -ENOENT) { if (!err) err = -EEXIST; goto out; } err = hfs_brec_insert(&dst_fd, &entry, entry_size); hfsplus_mark_inode_dirty(dst_dir, HFSPLUS_I_CAT_DIRTY); hfsplus_mark_inode_dirty(src_dir, HFSPLUS_I_CAT_DIRTY); out: hfs_bnode_put(dst_fd.bnode); hfs_find_exit(&src_fd); return err; }
165,599
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: SplashPath *Splash::makeDashedPath(SplashPath *path) { SplashPath *dPath; SplashCoord lineDashTotal; SplashCoord lineDashStartPhase, lineDashDist, segLen; SplashCoord x0, y0, x1, y1, xa, ya; GBool lineDashStartOn, lineDashOn, newPath; int lineDashStartIdx, lineDashIdx; int i, j, k; lineDashTotal = 0; for (i = 0; i < state->lineDashLength; ++i) { lineDashTotal += state->lineDash[i]; } if (lineDashTotal == 0) { return new SplashPath(); } lineDashStartPhase = state->lineDashPhase; i = splashFloor(lineDashStartPhase / lineDashTotal); lineDashStartPhase -= (SplashCoord)i * lineDashTotal; lineDashStartOn = gTrue; lineDashStartIdx = 0; if (lineDashStartPhase > 0) { while (lineDashStartPhase >= state->lineDash[lineDashStartIdx]) { lineDashStartOn = !lineDashStartOn; lineDashStartPhase -= state->lineDash[lineDashStartIdx]; ++lineDashStartIdx; } } dPath = new SplashPath(); while (i < path->length) { for (j = i; j < path->length - 1 && !(path->flags[j] & splashPathLast); ++j) ; lineDashOn = lineDashStartOn; lineDashIdx = lineDashStartIdx; lineDashDist = state->lineDash[lineDashIdx] - lineDashStartPhase; newPath = gTrue; for (k = i; k < j; ++k) { x0 = path->pts[k].x; y0 = path->pts[k].y; x1 = path->pts[k+1].x; y1 = path->pts[k+1].y; segLen = splashDist(x0, y0, x1, y1); while (segLen > 0) { if (lineDashDist >= segLen) { if (lineDashOn) { if (newPath) { dPath->moveTo(x0, y0); newPath = gFalse; } dPath->lineTo(x1, y1); } lineDashDist -= segLen; segLen = 0; } else { xa = x0 + (lineDashDist / segLen) * (x1 - x0); ya = y0 + (lineDashDist / segLen) * (y1 - y0); if (lineDashOn) { if (newPath) { dPath->moveTo(x0, y0); newPath = gFalse; } dPath->lineTo(xa, ya); } x0 = xa; y0 = ya; segLen -= lineDashDist; lineDashDist = 0; } if (lineDashDist <= 0) { lineDashOn = !lineDashOn; if (++lineDashIdx == state->lineDashLength) { lineDashIdx = 0; } lineDashDist = state->lineDash[lineDashIdx]; newPath = gTrue; } } } i = j + 1; } if (dPath->length == 0) { GBool allSame = gTrue; for (int i = 0; allSame && i < path->length - 1; ++i) { allSame = path->pts[i].x == path->pts[i + 1].x && path->pts[i].y == path->pts[i + 1].y; } if (allSame) { x0 = path->pts[0].x; y0 = path->pts[0].y; dPath->moveTo(x0, y0); dPath->lineTo(x0, y0); } } return dPath; } Commit Message: CWE ID: CWE-119
SplashPath *Splash::makeDashedPath(SplashPath *path) { SplashPath *dPath; SplashCoord lineDashTotal; SplashCoord lineDashStartPhase, lineDashDist, segLen; SplashCoord x0, y0, x1, y1, xa, ya; GBool lineDashStartOn, lineDashOn, newPath; int lineDashStartIdx, lineDashIdx; int i, j, k; lineDashTotal = 0; for (i = 0; i < state->lineDashLength; ++i) { lineDashTotal += state->lineDash[i]; } if (lineDashTotal == 0) { return new SplashPath(); } lineDashStartPhase = state->lineDashPhase; i = splashFloor(lineDashStartPhase / lineDashTotal); lineDashStartPhase -= (SplashCoord)i * lineDashTotal; lineDashStartOn = gTrue; lineDashStartIdx = 0; if (lineDashStartPhase > 0) { while (lineDashStartIdx < state->lineDashLength && lineDashStartPhase >= state->lineDash[lineDashStartIdx]) { lineDashStartOn = !lineDashStartOn; lineDashStartPhase -= state->lineDash[lineDashStartIdx]; ++lineDashStartIdx; } if (unlikely(lineDashStartIdx == state->lineDashLength)) { return new SplashPath(); } } dPath = new SplashPath(); while (i < path->length) { for (j = i; j < path->length - 1 && !(path->flags[j] & splashPathLast); ++j) ; lineDashOn = lineDashStartOn; lineDashIdx = lineDashStartIdx; lineDashDist = state->lineDash[lineDashIdx] - lineDashStartPhase; newPath = gTrue; for (k = i; k < j; ++k) { x0 = path->pts[k].x; y0 = path->pts[k].y; x1 = path->pts[k+1].x; y1 = path->pts[k+1].y; segLen = splashDist(x0, y0, x1, y1); while (segLen > 0) { if (lineDashDist >= segLen) { if (lineDashOn) { if (newPath) { dPath->moveTo(x0, y0); newPath = gFalse; } dPath->lineTo(x1, y1); } lineDashDist -= segLen; segLen = 0; } else { xa = x0 + (lineDashDist / segLen) * (x1 - x0); ya = y0 + (lineDashDist / segLen) * (y1 - y0); if (lineDashOn) { if (newPath) { dPath->moveTo(x0, y0); newPath = gFalse; } dPath->lineTo(xa, ya); } x0 = xa; y0 = ya; segLen -= lineDashDist; lineDashDist = 0; } if (lineDashDist <= 0) { lineDashOn = !lineDashOn; if (++lineDashIdx == state->lineDashLength) { lineDashIdx = 0; } lineDashDist = state->lineDash[lineDashIdx]; newPath = gTrue; } } } i = j + 1; } if (dPath->length == 0) { GBool allSame = gTrue; for (int i = 0; allSame && i < path->length - 1; ++i) { allSame = path->pts[i].x == path->pts[i + 1].x && path->pts[i].y == path->pts[i + 1].y; } if (allSame) { x0 = path->pts[0].x; y0 = path->pts[0].y; dPath->moveTo(x0, y0); dPath->lineTo(x0, y0); } } return dPath; }
164,734
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: Packet *PacketTunnelPktSetup(ThreadVars *tv, DecodeThreadVars *dtv, Packet *parent, uint8_t *pkt, uint32_t len, enum DecodeTunnelProto proto, PacketQueue *pq) { int ret; SCEnter(); /* get us a packet */ Packet *p = PacketGetFromQueueOrAlloc(); if (unlikely(p == NULL)) { SCReturnPtr(NULL, "Packet"); } /* copy packet and set lenght, proto */ PacketCopyData(p, pkt, len); p->recursion_level = parent->recursion_level + 1; p->ts.tv_sec = parent->ts.tv_sec; p->ts.tv_usec = parent->ts.tv_usec; p->datalink = DLT_RAW; p->tenant_id = parent->tenant_id; /* set the root ptr to the lowest layer */ if (parent->root != NULL) p->root = parent->root; else p->root = parent; /* tell new packet it's part of a tunnel */ SET_TUNNEL_PKT(p); ret = DecodeTunnel(tv, dtv, p, GET_PKT_DATA(p), GET_PKT_LEN(p), pq, proto); if (unlikely(ret != TM_ECODE_OK)) { /* Not a tunnel packet, just a pseudo packet */ p->root = NULL; UNSET_TUNNEL_PKT(p); TmqhOutputPacketpool(tv, p); SCReturnPtr(NULL, "Packet"); } /* tell parent packet it's part of a tunnel */ SET_TUNNEL_PKT(parent); /* increment tunnel packet refcnt in the root packet */ TUNNEL_INCR_PKT_TPR(p); /* disable payload (not packet) inspection on the parent, as the payload * is the packet we will now run through the system separately. We do * check it against the ip/port/other header checks though */ DecodeSetNoPayloadInspectionFlag(parent); SCReturnPtr(p, "Packet"); } Commit Message: teredo: be stricter on what to consider valid teredo Invalid Teredo can lead to valid DNS traffic (or other UDP traffic) being misdetected as Teredo. This leads to false negatives in the UDP payload inspection. Make the teredo code only consider a packet teredo if the encapsulated data was decoded without any 'invalid' events being set. Bug #2736. CWE ID: CWE-20
Packet *PacketTunnelPktSetup(ThreadVars *tv, DecodeThreadVars *dtv, Packet *parent, uint8_t *pkt, uint32_t len, enum DecodeTunnelProto proto, PacketQueue *pq) { int ret; SCEnter(); /* get us a packet */ Packet *p = PacketGetFromQueueOrAlloc(); if (unlikely(p == NULL)) { SCReturnPtr(NULL, "Packet"); } /* copy packet and set lenght, proto */ PacketCopyData(p, pkt, len); p->recursion_level = parent->recursion_level + 1; p->ts.tv_sec = parent->ts.tv_sec; p->ts.tv_usec = parent->ts.tv_usec; p->datalink = DLT_RAW; p->tenant_id = parent->tenant_id; /* set the root ptr to the lowest layer */ if (parent->root != NULL) p->root = parent->root; else p->root = parent; /* tell new packet it's part of a tunnel */ SET_TUNNEL_PKT(p); ret = DecodeTunnel(tv, dtv, p, GET_PKT_DATA(p), GET_PKT_LEN(p), pq, proto); if (unlikely(ret != TM_ECODE_OK) || (proto == DECODE_TUNNEL_IPV6_TEREDO && (p->flags & PKT_IS_INVALID))) { /* Not a (valid) tunnel packet */ SCLogDebug("tunnel packet is invalid"); p->root = NULL; UNSET_TUNNEL_PKT(p); TmqhOutputPacketpool(tv, p); SCReturnPtr(NULL, "Packet"); } /* tell parent packet it's part of a tunnel */ SET_TUNNEL_PKT(parent); /* increment tunnel packet refcnt in the root packet */ TUNNEL_INCR_PKT_TPR(p); /* disable payload (not packet) inspection on the parent, as the payload * is the packet we will now run through the system separately. We do * check it against the ip/port/other header checks though */ DecodeSetNoPayloadInspectionFlag(parent); SCReturnPtr(p, "Packet"); }
169,479
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void nfnetlink_rcv_batch(struct sk_buff *skb, struct nlmsghdr *nlh, u_int16_t subsys_id) { struct sk_buff *oskb = skb; struct net *net = sock_net(skb->sk); const struct nfnetlink_subsystem *ss; const struct nfnl_callback *nc; static LIST_HEAD(err_list); u32 status; int err; if (subsys_id >= NFNL_SUBSYS_COUNT) return netlink_ack(skb, nlh, -EINVAL); replay: status = 0; skb = netlink_skb_clone(oskb, GFP_KERNEL); if (!skb) return netlink_ack(oskb, nlh, -ENOMEM); nfnl_lock(subsys_id); ss = nfnl_dereference_protected(subsys_id); if (!ss) { #ifdef CONFIG_MODULES nfnl_unlock(subsys_id); request_module("nfnetlink-subsys-%d", subsys_id); nfnl_lock(subsys_id); ss = nfnl_dereference_protected(subsys_id); if (!ss) #endif { nfnl_unlock(subsys_id); netlink_ack(oskb, nlh, -EOPNOTSUPP); return kfree_skb(skb); } } if (!ss->commit || !ss->abort) { nfnl_unlock(subsys_id); netlink_ack(oskb, nlh, -EOPNOTSUPP); return kfree_skb(skb); } while (skb->len >= nlmsg_total_size(0)) { int msglen, type; nlh = nlmsg_hdr(skb); err = 0; if (nlmsg_len(nlh) < sizeof(struct nfgenmsg) || skb->len < nlh->nlmsg_len) { err = -EINVAL; goto ack; } /* Only requests are handled by the kernel */ if (!(nlh->nlmsg_flags & NLM_F_REQUEST)) { err = -EINVAL; goto ack; } type = nlh->nlmsg_type; if (type == NFNL_MSG_BATCH_BEGIN) { /* Malformed: Batch begin twice */ nfnl_err_reset(&err_list); status |= NFNL_BATCH_FAILURE; goto done; } else if (type == NFNL_MSG_BATCH_END) { status |= NFNL_BATCH_DONE; goto done; } else if (type < NLMSG_MIN_TYPE) { err = -EINVAL; goto ack; } /* We only accept a batch with messages for the same * subsystem. */ if (NFNL_SUBSYS_ID(type) != subsys_id) { err = -EINVAL; goto ack; } nc = nfnetlink_find_client(type, ss); if (!nc) { err = -EINVAL; goto ack; } { int min_len = nlmsg_total_size(sizeof(struct nfgenmsg)); u_int8_t cb_id = NFNL_MSG_TYPE(nlh->nlmsg_type); struct nlattr *cda[ss->cb[cb_id].attr_count + 1]; struct nlattr *attr = (void *)nlh + min_len; int attrlen = nlh->nlmsg_len - min_len; err = nla_parse(cda, ss->cb[cb_id].attr_count, attr, attrlen, ss->cb[cb_id].policy); if (err < 0) goto ack; if (nc->call_batch) { err = nc->call_batch(net, net->nfnl, skb, nlh, (const struct nlattr **)cda); } /* The lock was released to autoload some module, we * have to abort and start from scratch using the * original skb. */ if (err == -EAGAIN) { status |= NFNL_BATCH_REPLAY; goto next; } } ack: if (nlh->nlmsg_flags & NLM_F_ACK || err) { /* Errors are delivered once the full batch has been * processed, this avoids that the same error is * reported several times when replaying the batch. */ if (nfnl_err_add(&err_list, nlh, err) < 0) { /* We failed to enqueue an error, reset the * list of errors and send OOM to userspace * pointing to the batch header. */ nfnl_err_reset(&err_list); netlink_ack(oskb, nlmsg_hdr(oskb), -ENOMEM); status |= NFNL_BATCH_FAILURE; goto done; } /* We don't stop processing the batch on errors, thus, * userspace gets all the errors that the batch * triggers. */ if (err) status |= NFNL_BATCH_FAILURE; } next: msglen = NLMSG_ALIGN(nlh->nlmsg_len); if (msglen > skb->len) msglen = skb->len; skb_pull(skb, msglen); } done: if (status & NFNL_BATCH_REPLAY) { ss->abort(net, oskb); nfnl_err_reset(&err_list); nfnl_unlock(subsys_id); kfree_skb(skb); goto replay; } else if (status == NFNL_BATCH_DONE) { ss->commit(net, oskb); } else { ss->abort(net, oskb); } nfnl_err_deliver(&err_list, oskb); nfnl_unlock(subsys_id); kfree_skb(skb); } Commit Message: netfilter: nfnetlink: correctly validate length of batch messages If nlh->nlmsg_len is zero then an infinite loop is triggered because 'skb_pull(skb, msglen);' pulls zero bytes. The calculation in nlmsg_len() underflows if 'nlh->nlmsg_len < NLMSG_HDRLEN' which bypasses the length validation and will later trigger an out-of-bound read. If the length validation does fail then the malformed batch message is copied back to userspace. However, we cannot do this because the nlh->nlmsg_len can be invalid. This leads to an out-of-bounds read in netlink_ack: [ 41.455421] ================================================================== [ 41.456431] BUG: KASAN: slab-out-of-bounds in memcpy+0x1d/0x40 at addr ffff880119e79340 [ 41.456431] Read of size 4294967280 by task a.out/987 [ 41.456431] ============================================================================= [ 41.456431] BUG kmalloc-512 (Not tainted): kasan: bad access detected [ 41.456431] ----------------------------------------------------------------------------- ... [ 41.456431] Bytes b4 ffff880119e79310: 00 00 00 00 d5 03 00 00 b0 fb fe ff 00 00 00 00 ................ [ 41.456431] Object ffff880119e79320: 20 00 00 00 10 00 05 00 00 00 00 00 00 00 00 00 ............... [ 41.456431] Object ffff880119e79330: 14 00 0a 00 01 03 fc 40 45 56 11 22 33 10 00 05 .......@EV."3... [ 41.456431] Object ffff880119e79340: f0 ff ff ff 88 99 aa bb 00 14 00 0a 00 06 fe fb ................ ^^ start of batch nlmsg with nlmsg_len=4294967280 ... [ 41.456431] Memory state around the buggy address: [ 41.456431] ffff880119e79400: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 [ 41.456431] ffff880119e79480: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 [ 41.456431] >ffff880119e79500: 00 00 00 00 fc fc fc fc fc fc fc fc fc fc fc fc [ 41.456431] ^ [ 41.456431] ffff880119e79580: fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc [ 41.456431] ffff880119e79600: fc fc fc fc fc fc fc fc fc fc fb fb fb fb fb fb [ 41.456431] ================================================================== Fix this with better validation of nlh->nlmsg_len and by setting NFNL_BATCH_FAILURE if any batch message fails length validation. CAP_NET_ADMIN is required to trigger the bugs. Fixes: 9ea2aa8b7dba ("netfilter: nfnetlink: validate nfnetlink header from batch") Signed-off-by: Phil Turnbull <[email protected]> Signed-off-by: Pablo Neira Ayuso <[email protected]> CWE ID: CWE-125
static void nfnetlink_rcv_batch(struct sk_buff *skb, struct nlmsghdr *nlh, u_int16_t subsys_id) { struct sk_buff *oskb = skb; struct net *net = sock_net(skb->sk); const struct nfnetlink_subsystem *ss; const struct nfnl_callback *nc; static LIST_HEAD(err_list); u32 status; int err; if (subsys_id >= NFNL_SUBSYS_COUNT) return netlink_ack(skb, nlh, -EINVAL); replay: status = 0; skb = netlink_skb_clone(oskb, GFP_KERNEL); if (!skb) return netlink_ack(oskb, nlh, -ENOMEM); nfnl_lock(subsys_id); ss = nfnl_dereference_protected(subsys_id); if (!ss) { #ifdef CONFIG_MODULES nfnl_unlock(subsys_id); request_module("nfnetlink-subsys-%d", subsys_id); nfnl_lock(subsys_id); ss = nfnl_dereference_protected(subsys_id); if (!ss) #endif { nfnl_unlock(subsys_id); netlink_ack(oskb, nlh, -EOPNOTSUPP); return kfree_skb(skb); } } if (!ss->commit || !ss->abort) { nfnl_unlock(subsys_id); netlink_ack(oskb, nlh, -EOPNOTSUPP); return kfree_skb(skb); } while (skb->len >= nlmsg_total_size(0)) { int msglen, type; nlh = nlmsg_hdr(skb); err = 0; if (nlh->nlmsg_len < NLMSG_HDRLEN || skb->len < nlh->nlmsg_len || nlmsg_len(nlh) < sizeof(struct nfgenmsg)) { nfnl_err_reset(&err_list); status |= NFNL_BATCH_FAILURE; goto done; } /* Only requests are handled by the kernel */ if (!(nlh->nlmsg_flags & NLM_F_REQUEST)) { err = -EINVAL; goto ack; } type = nlh->nlmsg_type; if (type == NFNL_MSG_BATCH_BEGIN) { /* Malformed: Batch begin twice */ nfnl_err_reset(&err_list); status |= NFNL_BATCH_FAILURE; goto done; } else if (type == NFNL_MSG_BATCH_END) { status |= NFNL_BATCH_DONE; goto done; } else if (type < NLMSG_MIN_TYPE) { err = -EINVAL; goto ack; } /* We only accept a batch with messages for the same * subsystem. */ if (NFNL_SUBSYS_ID(type) != subsys_id) { err = -EINVAL; goto ack; } nc = nfnetlink_find_client(type, ss); if (!nc) { err = -EINVAL; goto ack; } { int min_len = nlmsg_total_size(sizeof(struct nfgenmsg)); u_int8_t cb_id = NFNL_MSG_TYPE(nlh->nlmsg_type); struct nlattr *cda[ss->cb[cb_id].attr_count + 1]; struct nlattr *attr = (void *)nlh + min_len; int attrlen = nlh->nlmsg_len - min_len; err = nla_parse(cda, ss->cb[cb_id].attr_count, attr, attrlen, ss->cb[cb_id].policy); if (err < 0) goto ack; if (nc->call_batch) { err = nc->call_batch(net, net->nfnl, skb, nlh, (const struct nlattr **)cda); } /* The lock was released to autoload some module, we * have to abort and start from scratch using the * original skb. */ if (err == -EAGAIN) { status |= NFNL_BATCH_REPLAY; goto next; } } ack: if (nlh->nlmsg_flags & NLM_F_ACK || err) { /* Errors are delivered once the full batch has been * processed, this avoids that the same error is * reported several times when replaying the batch. */ if (nfnl_err_add(&err_list, nlh, err) < 0) { /* We failed to enqueue an error, reset the * list of errors and send OOM to userspace * pointing to the batch header. */ nfnl_err_reset(&err_list); netlink_ack(oskb, nlmsg_hdr(oskb), -ENOMEM); status |= NFNL_BATCH_FAILURE; goto done; } /* We don't stop processing the batch on errors, thus, * userspace gets all the errors that the batch * triggers. */ if (err) status |= NFNL_BATCH_FAILURE; } next: msglen = NLMSG_ALIGN(nlh->nlmsg_len); if (msglen > skb->len) msglen = skb->len; skb_pull(skb, msglen); } done: if (status & NFNL_BATCH_REPLAY) { ss->abort(net, oskb); nfnl_err_reset(&err_list); nfnl_unlock(subsys_id); kfree_skb(skb); goto replay; } else if (status == NFNL_BATCH_DONE) { ss->commit(net, oskb); } else { ss->abort(net, oskb); } nfnl_err_deliver(&err_list, oskb); nfnl_unlock(subsys_id); kfree_skb(skb); }
166,919
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void fpm_child_init(struct fpm_worker_pool_s *wp) /* {{{ */ { fpm_globals.max_requests = wp->config->pm_max_requests; if (0 > fpm_stdio_init_child(wp) || 0 > fpm_log_init_child(wp) || 0 > fpm_status_init_child(wp) || 0 > fpm_unix_init_child(wp) || 0 > fpm_signals_init_child() || 0 > fpm_env_init_child(wp) || 0 > fpm_php_init_child(wp)) { zlog(ZLOG_ERROR, "[pool %s] child failed to initialize", wp->config->name); exit(FPM_EXIT_SOFTWARE); } } /* }}} */ Commit Message: Fixed bug #73342 Directly listen on socket, instead of duping it to STDIN and listening on that. CWE ID: CWE-400
static void fpm_child_init(struct fpm_worker_pool_s *wp) /* {{{ */ { fpm_globals.max_requests = wp->config->pm_max_requests; fpm_globals.listening_socket = dup(wp->listening_socket); if (0 > fpm_stdio_init_child(wp) || 0 > fpm_log_init_child(wp) || 0 > fpm_status_init_child(wp) || 0 > fpm_unix_init_child(wp) || 0 > fpm_signals_init_child() || 0 > fpm_env_init_child(wp) || 0 > fpm_php_init_child(wp)) { zlog(ZLOG_ERROR, "[pool %s] child failed to initialize", wp->config->name); exit(FPM_EXIT_SOFTWARE); } } /* }}} */
169,451
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int sock_setsockopt(struct socket *sock, int level, int optname, char __user *optval, unsigned int optlen) { struct sock *sk = sock->sk; int val; int valbool; struct linger ling; int ret = 0; /* * Options without arguments */ if (optname == SO_BINDTODEVICE) return sock_bindtodevice(sk, optval, optlen); if (optlen < sizeof(int)) return -EINVAL; if (get_user(val, (int __user *)optval)) return -EFAULT; valbool = val ? 1 : 0; lock_sock(sk); switch (optname) { case SO_DEBUG: if (val && !capable(CAP_NET_ADMIN)) ret = -EACCES; else sock_valbool_flag(sk, SOCK_DBG, valbool); break; case SO_REUSEADDR: sk->sk_reuse = (valbool ? SK_CAN_REUSE : SK_NO_REUSE); break; case SO_TYPE: case SO_PROTOCOL: case SO_DOMAIN: case SO_ERROR: ret = -ENOPROTOOPT; break; case SO_DONTROUTE: sock_valbool_flag(sk, SOCK_LOCALROUTE, valbool); break; case SO_BROADCAST: sock_valbool_flag(sk, SOCK_BROADCAST, valbool); break; case SO_SNDBUF: /* Don't error on this BSD doesn't and if you think about it this is right. Otherwise apps have to play 'guess the biggest size' games. RCVBUF/SNDBUF are treated in BSD as hints */ if (val > sysctl_wmem_max) val = sysctl_wmem_max; set_sndbuf: sk->sk_userlocks |= SOCK_SNDBUF_LOCK; if ((val * 2) < SOCK_MIN_SNDBUF) sk->sk_sndbuf = SOCK_MIN_SNDBUF; else sk->sk_sndbuf = val * 2; /* * Wake up sending tasks if we * upped the value. */ sk->sk_write_space(sk); break; case SO_SNDBUFFORCE: if (!capable(CAP_NET_ADMIN)) { ret = -EPERM; break; } goto set_sndbuf; case SO_RCVBUF: /* Don't error on this BSD doesn't and if you think about it this is right. Otherwise apps have to play 'guess the biggest size' games. RCVBUF/SNDBUF are treated in BSD as hints */ if (val > sysctl_rmem_max) val = sysctl_rmem_max; set_rcvbuf: sk->sk_userlocks |= SOCK_RCVBUF_LOCK; /* * We double it on the way in to account for * "struct sk_buff" etc. overhead. Applications * assume that the SO_RCVBUF setting they make will * allow that much actual data to be received on that * socket. * * Applications are unaware that "struct sk_buff" and * other overheads allocate from the receive buffer * during socket buffer allocation. * * And after considering the possible alternatives, * returning the value we actually used in getsockopt * is the most desirable behavior. */ if ((val * 2) < SOCK_MIN_RCVBUF) sk->sk_rcvbuf = SOCK_MIN_RCVBUF; else sk->sk_rcvbuf = val * 2; break; case SO_RCVBUFFORCE: if (!capable(CAP_NET_ADMIN)) { ret = -EPERM; break; } goto set_rcvbuf; case SO_KEEPALIVE: #ifdef CONFIG_INET if (sk->sk_protocol == IPPROTO_TCP) tcp_set_keepalive(sk, valbool); #endif sock_valbool_flag(sk, SOCK_KEEPOPEN, valbool); break; case SO_OOBINLINE: sock_valbool_flag(sk, SOCK_URGINLINE, valbool); break; case SO_NO_CHECK: sk->sk_no_check = valbool; break; case SO_PRIORITY: if ((val >= 0 && val <= 6) || capable(CAP_NET_ADMIN)) sk->sk_priority = val; else ret = -EPERM; break; case SO_LINGER: if (optlen < sizeof(ling)) { ret = -EINVAL; /* 1003.1g */ break; } if (copy_from_user(&ling, optval, sizeof(ling))) { ret = -EFAULT; break; } if (!ling.l_onoff) sock_reset_flag(sk, SOCK_LINGER); else { #if (BITS_PER_LONG == 32) if ((unsigned int)ling.l_linger >= MAX_SCHEDULE_TIMEOUT/HZ) sk->sk_lingertime = MAX_SCHEDULE_TIMEOUT; else #endif sk->sk_lingertime = (unsigned int)ling.l_linger * HZ; sock_set_flag(sk, SOCK_LINGER); } break; case SO_BSDCOMPAT: sock_warn_obsolete_bsdism("setsockopt"); break; case SO_PASSCRED: if (valbool) set_bit(SOCK_PASSCRED, &sock->flags); else clear_bit(SOCK_PASSCRED, &sock->flags); break; case SO_TIMESTAMP: case SO_TIMESTAMPNS: if (valbool) { if (optname == SO_TIMESTAMP) sock_reset_flag(sk, SOCK_RCVTSTAMPNS); else sock_set_flag(sk, SOCK_RCVTSTAMPNS); sock_set_flag(sk, SOCK_RCVTSTAMP); sock_enable_timestamp(sk, SOCK_TIMESTAMP); } else { sock_reset_flag(sk, SOCK_RCVTSTAMP); sock_reset_flag(sk, SOCK_RCVTSTAMPNS); } break; case SO_TIMESTAMPING: if (val & ~SOF_TIMESTAMPING_MASK) { ret = -EINVAL; break; } sock_valbool_flag(sk, SOCK_TIMESTAMPING_TX_HARDWARE, val & SOF_TIMESTAMPING_TX_HARDWARE); sock_valbool_flag(sk, SOCK_TIMESTAMPING_TX_SOFTWARE, val & SOF_TIMESTAMPING_TX_SOFTWARE); sock_valbool_flag(sk, SOCK_TIMESTAMPING_RX_HARDWARE, val & SOF_TIMESTAMPING_RX_HARDWARE); if (val & SOF_TIMESTAMPING_RX_SOFTWARE) sock_enable_timestamp(sk, SOCK_TIMESTAMPING_RX_SOFTWARE); else sock_disable_timestamp(sk, (1UL << SOCK_TIMESTAMPING_RX_SOFTWARE)); sock_valbool_flag(sk, SOCK_TIMESTAMPING_SOFTWARE, val & SOF_TIMESTAMPING_SOFTWARE); sock_valbool_flag(sk, SOCK_TIMESTAMPING_SYS_HARDWARE, val & SOF_TIMESTAMPING_SYS_HARDWARE); sock_valbool_flag(sk, SOCK_TIMESTAMPING_RAW_HARDWARE, val & SOF_TIMESTAMPING_RAW_HARDWARE); break; case SO_RCVLOWAT: if (val < 0) val = INT_MAX; sk->sk_rcvlowat = val ? : 1; break; case SO_RCVTIMEO: ret = sock_set_timeout(&sk->sk_rcvtimeo, optval, optlen); break; case SO_SNDTIMEO: ret = sock_set_timeout(&sk->sk_sndtimeo, optval, optlen); break; case SO_ATTACH_FILTER: ret = -EINVAL; if (optlen == sizeof(struct sock_fprog)) { struct sock_fprog fprog; ret = -EFAULT; if (copy_from_user(&fprog, optval, sizeof(fprog))) break; ret = sk_attach_filter(&fprog, sk); } break; case SO_DETACH_FILTER: ret = sk_detach_filter(sk); break; case SO_PASSSEC: if (valbool) set_bit(SOCK_PASSSEC, &sock->flags); else clear_bit(SOCK_PASSSEC, &sock->flags); break; case SO_MARK: if (!capable(CAP_NET_ADMIN)) ret = -EPERM; else sk->sk_mark = val; break; /* We implement the SO_SNDLOWAT etc to not be settable (1003.1g 5.3) */ case SO_RXQ_OVFL: sock_valbool_flag(sk, SOCK_RXQ_OVFL, valbool); break; case SO_WIFI_STATUS: sock_valbool_flag(sk, SOCK_WIFI_STATUS, valbool); break; case SO_PEEK_OFF: if (sock->ops->set_peek_off) sock->ops->set_peek_off(sk, val); else ret = -EOPNOTSUPP; break; case SO_NOFCS: sock_valbool_flag(sk, SOCK_NOFCS, valbool); break; default: ret = -ENOPROTOOPT; break; } release_sock(sk); return ret; } Commit Message: net: cleanups in sock_setsockopt() Use min_t()/max_t() macros, reformat two comments, use !!test_bit() to match !!sock_flag() Signed-off-by: Eric Dumazet <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-119
int sock_setsockopt(struct socket *sock, int level, int optname, char __user *optval, unsigned int optlen) { struct sock *sk = sock->sk; int val; int valbool; struct linger ling; int ret = 0; /* * Options without arguments */ if (optname == SO_BINDTODEVICE) return sock_bindtodevice(sk, optval, optlen); if (optlen < sizeof(int)) return -EINVAL; if (get_user(val, (int __user *)optval)) return -EFAULT; valbool = val ? 1 : 0; lock_sock(sk); switch (optname) { case SO_DEBUG: if (val && !capable(CAP_NET_ADMIN)) ret = -EACCES; else sock_valbool_flag(sk, SOCK_DBG, valbool); break; case SO_REUSEADDR: sk->sk_reuse = (valbool ? SK_CAN_REUSE : SK_NO_REUSE); break; case SO_TYPE: case SO_PROTOCOL: case SO_DOMAIN: case SO_ERROR: ret = -ENOPROTOOPT; break; case SO_DONTROUTE: sock_valbool_flag(sk, SOCK_LOCALROUTE, valbool); break; case SO_BROADCAST: sock_valbool_flag(sk, SOCK_BROADCAST, valbool); break; case SO_SNDBUF: /* Don't error on this BSD doesn't and if you think * about it this is right. Otherwise apps have to * play 'guess the biggest size' games. RCVBUF/SNDBUF * are treated in BSD as hints */ val = min_t(u32, val, sysctl_wmem_max); set_sndbuf: sk->sk_userlocks |= SOCK_SNDBUF_LOCK; sk->sk_sndbuf = max_t(u32, val * 2, SOCK_MIN_SNDBUF); /* Wake up sending tasks if we upped the value. */ sk->sk_write_space(sk); break; case SO_SNDBUFFORCE: if (!capable(CAP_NET_ADMIN)) { ret = -EPERM; break; } goto set_sndbuf; case SO_RCVBUF: /* Don't error on this BSD doesn't and if you think * about it this is right. Otherwise apps have to * play 'guess the biggest size' games. RCVBUF/SNDBUF * are treated in BSD as hints */ val = min_t(u32, val, sysctl_rmem_max); set_rcvbuf: sk->sk_userlocks |= SOCK_RCVBUF_LOCK; /* * We double it on the way in to account for * "struct sk_buff" etc. overhead. Applications * assume that the SO_RCVBUF setting they make will * allow that much actual data to be received on that * socket. * * Applications are unaware that "struct sk_buff" and * other overheads allocate from the receive buffer * during socket buffer allocation. * * And after considering the possible alternatives, * returning the value we actually used in getsockopt * is the most desirable behavior. */ sk->sk_rcvbuf = max_t(u32, val * 2, SOCK_MIN_RCVBUF); break; case SO_RCVBUFFORCE: if (!capable(CAP_NET_ADMIN)) { ret = -EPERM; break; } goto set_rcvbuf; case SO_KEEPALIVE: #ifdef CONFIG_INET if (sk->sk_protocol == IPPROTO_TCP) tcp_set_keepalive(sk, valbool); #endif sock_valbool_flag(sk, SOCK_KEEPOPEN, valbool); break; case SO_OOBINLINE: sock_valbool_flag(sk, SOCK_URGINLINE, valbool); break; case SO_NO_CHECK: sk->sk_no_check = valbool; break; case SO_PRIORITY: if ((val >= 0 && val <= 6) || capable(CAP_NET_ADMIN)) sk->sk_priority = val; else ret = -EPERM; break; case SO_LINGER: if (optlen < sizeof(ling)) { ret = -EINVAL; /* 1003.1g */ break; } if (copy_from_user(&ling, optval, sizeof(ling))) { ret = -EFAULT; break; } if (!ling.l_onoff) sock_reset_flag(sk, SOCK_LINGER); else { #if (BITS_PER_LONG == 32) if ((unsigned int)ling.l_linger >= MAX_SCHEDULE_TIMEOUT/HZ) sk->sk_lingertime = MAX_SCHEDULE_TIMEOUT; else #endif sk->sk_lingertime = (unsigned int)ling.l_linger * HZ; sock_set_flag(sk, SOCK_LINGER); } break; case SO_BSDCOMPAT: sock_warn_obsolete_bsdism("setsockopt"); break; case SO_PASSCRED: if (valbool) set_bit(SOCK_PASSCRED, &sock->flags); else clear_bit(SOCK_PASSCRED, &sock->flags); break; case SO_TIMESTAMP: case SO_TIMESTAMPNS: if (valbool) { if (optname == SO_TIMESTAMP) sock_reset_flag(sk, SOCK_RCVTSTAMPNS); else sock_set_flag(sk, SOCK_RCVTSTAMPNS); sock_set_flag(sk, SOCK_RCVTSTAMP); sock_enable_timestamp(sk, SOCK_TIMESTAMP); } else { sock_reset_flag(sk, SOCK_RCVTSTAMP); sock_reset_flag(sk, SOCK_RCVTSTAMPNS); } break; case SO_TIMESTAMPING: if (val & ~SOF_TIMESTAMPING_MASK) { ret = -EINVAL; break; } sock_valbool_flag(sk, SOCK_TIMESTAMPING_TX_HARDWARE, val & SOF_TIMESTAMPING_TX_HARDWARE); sock_valbool_flag(sk, SOCK_TIMESTAMPING_TX_SOFTWARE, val & SOF_TIMESTAMPING_TX_SOFTWARE); sock_valbool_flag(sk, SOCK_TIMESTAMPING_RX_HARDWARE, val & SOF_TIMESTAMPING_RX_HARDWARE); if (val & SOF_TIMESTAMPING_RX_SOFTWARE) sock_enable_timestamp(sk, SOCK_TIMESTAMPING_RX_SOFTWARE); else sock_disable_timestamp(sk, (1UL << SOCK_TIMESTAMPING_RX_SOFTWARE)); sock_valbool_flag(sk, SOCK_TIMESTAMPING_SOFTWARE, val & SOF_TIMESTAMPING_SOFTWARE); sock_valbool_flag(sk, SOCK_TIMESTAMPING_SYS_HARDWARE, val & SOF_TIMESTAMPING_SYS_HARDWARE); sock_valbool_flag(sk, SOCK_TIMESTAMPING_RAW_HARDWARE, val & SOF_TIMESTAMPING_RAW_HARDWARE); break; case SO_RCVLOWAT: if (val < 0) val = INT_MAX; sk->sk_rcvlowat = val ? : 1; break; case SO_RCVTIMEO: ret = sock_set_timeout(&sk->sk_rcvtimeo, optval, optlen); break; case SO_SNDTIMEO: ret = sock_set_timeout(&sk->sk_sndtimeo, optval, optlen); break; case SO_ATTACH_FILTER: ret = -EINVAL; if (optlen == sizeof(struct sock_fprog)) { struct sock_fprog fprog; ret = -EFAULT; if (copy_from_user(&fprog, optval, sizeof(fprog))) break; ret = sk_attach_filter(&fprog, sk); } break; case SO_DETACH_FILTER: ret = sk_detach_filter(sk); break; case SO_PASSSEC: if (valbool) set_bit(SOCK_PASSSEC, &sock->flags); else clear_bit(SOCK_PASSSEC, &sock->flags); break; case SO_MARK: if (!capable(CAP_NET_ADMIN)) ret = -EPERM; else sk->sk_mark = val; break; /* We implement the SO_SNDLOWAT etc to not be settable (1003.1g 5.3) */ case SO_RXQ_OVFL: sock_valbool_flag(sk, SOCK_RXQ_OVFL, valbool); break; case SO_WIFI_STATUS: sock_valbool_flag(sk, SOCK_WIFI_STATUS, valbool); break; case SO_PEEK_OFF: if (sock->ops->set_peek_off) sock->ops->set_peek_off(sk, val); else ret = -EOPNOTSUPP; break; case SO_NOFCS: sock_valbool_flag(sk, SOCK_NOFCS, valbool); break; default: ret = -ENOPROTOOPT; break; } release_sock(sk); return ret; }
167,609
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: PersistentHistogramAllocator::GetCreateHistogramResultHistogram() { constexpr subtle::AtomicWord kHistogramUnderConstruction = 1; static subtle::AtomicWord atomic_histogram_pointer = 0; subtle::AtomicWord histogram_value = subtle::Acquire_Load(&atomic_histogram_pointer); if (histogram_value == kHistogramUnderConstruction) return nullptr; if (histogram_value) return reinterpret_cast<HistogramBase*>(histogram_value); if (subtle::NoBarrier_CompareAndSwap(&atomic_histogram_pointer, 0, kHistogramUnderConstruction) != 0) { return nullptr; } if (GlobalHistogramAllocator::Get()) { DVLOG(1) << "Creating the results-histogram inside persistent" << " memory can cause future allocations to crash if" << " that memory is ever released (for testing)."; } HistogramBase* histogram_pointer = LinearHistogram::FactoryGet( kResultHistogram, 1, CREATE_HISTOGRAM_MAX, CREATE_HISTOGRAM_MAX + 1, HistogramBase::kUmaTargetedHistogramFlag); subtle::Release_Store( &atomic_histogram_pointer, reinterpret_cast<subtle::AtomicWord>(histogram_pointer)); return histogram_pointer; } Commit Message: Remove UMA.CreatePersistentHistogram.Result This histogram isn't showing anything meaningful and the problems it could show are better observed by looking at the allocators directly. Bug: 831013 Change-Id: Ibe968597758230192e53a7675e7390e968c9e5b9 Reviewed-on: https://chromium-review.googlesource.com/1008047 Commit-Queue: Brian White <[email protected]> Reviewed-by: Alexei Svitkine <[email protected]> Cr-Commit-Position: refs/heads/master@{#549986} CWE ID: CWE-264
PersistentHistogramAllocator::GetCreateHistogramResultHistogram() {
172,133
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: const PPB_NaCl_Private* GetNaclInterface() { pp::Module *module = pp::Module::Get(); CHECK(module); return static_cast<const PPB_NaCl_Private*>( module->GetBrowserInterface(PPB_NACL_PRIVATE_INTERFACE)); } Commit Message: Revert 143656 - Add an IPC channel between the NaCl loader process and the renderer. BUG=116317 TEST=ppapi, nacl tests, manual testing for experimental IPC proxy. Review URL: https://chromiumcodereview.appspot.com/10641016 [email protected] Review URL: https://chromiumcodereview.appspot.com/10625007 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143665 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
const PPB_NaCl_Private* GetNaclInterface() {
170,741
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: png_get_uint_32(png_bytep buf) { png_uint_32 i = ((png_uint_32)(*buf) << 24) + ((png_uint_32)(*(buf + 1)) << 16) + ((png_uint_32)(*(buf + 2)) << 8) + (png_uint_32)(*(buf + 3)); return (i); } Commit Message: third_party/libpng: update to 1.2.54 [email protected] BUG=560291 Review URL: https://codereview.chromium.org/1467263003 Cr-Commit-Position: refs/heads/master@{#362298} CWE ID: CWE-119
png_get_uint_32(png_bytep buf) { png_uint_32 i = ((png_uint_32)((*(buf )) & 0xff) << 24) + ((png_uint_32)((*(buf + 1)) & 0xff) << 16) + ((png_uint_32)((*(buf + 2)) & 0xff) << 8) + ((png_uint_32)((*(buf + 3)) & 0xff) ); return (i); }
172,176
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static struct net_device *_init_airo_card( unsigned short irq, int port, int is_pcmcia, struct pci_dev *pci, struct device *dmdev ) { struct net_device *dev; struct airo_info *ai; int i, rc; CapabilityRid cap_rid; /* Create the network device object. */ dev = alloc_netdev(sizeof(*ai), "", ether_setup); if (!dev) { airo_print_err("", "Couldn't alloc_etherdev"); return NULL; } ai = dev->ml_priv = netdev_priv(dev); ai->wifidev = NULL; ai->flags = 1 << FLAG_RADIO_DOWN; ai->jobs = 0; ai->dev = dev; if (pci && (pci->device == 0x5000 || pci->device == 0xa504)) { airo_print_dbg("", "Found an MPI350 card"); set_bit(FLAG_MPI, &ai->flags); } spin_lock_init(&ai->aux_lock); sema_init(&ai->sem, 1); ai->config.len = 0; ai->pci = pci; init_waitqueue_head (&ai->thr_wait); ai->tfm = NULL; add_airo_dev(ai); if (airo_networks_allocate (ai)) goto err_out_free; airo_networks_initialize (ai); skb_queue_head_init (&ai->txq); /* The Airo-specific entries in the device structure. */ if (test_bit(FLAG_MPI,&ai->flags)) dev->netdev_ops = &mpi_netdev_ops; else dev->netdev_ops = &airo_netdev_ops; dev->wireless_handlers = &airo_handler_def; ai->wireless_data.spy_data = &ai->spy_data; dev->wireless_data = &ai->wireless_data; dev->irq = irq; dev->base_addr = port; SET_NETDEV_DEV(dev, dmdev); reset_card (dev, 1); msleep(400); if (!is_pcmcia) { if (!request_region(dev->base_addr, 64, DRV_NAME)) { rc = -EBUSY; airo_print_err(dev->name, "Couldn't request region"); goto err_out_nets; } } if (test_bit(FLAG_MPI,&ai->flags)) { if (mpi_map_card(ai, pci)) { airo_print_err("", "Could not map memory"); goto err_out_res; } } if (probe) { if (setup_card(ai, dev->dev_addr, 1) != SUCCESS) { airo_print_err(dev->name, "MAC could not be enabled" ); rc = -EIO; goto err_out_map; } } else if (!test_bit(FLAG_MPI,&ai->flags)) { ai->bap_read = fast_bap_read; set_bit(FLAG_FLASHING, &ai->flags); } strcpy(dev->name, "eth%d"); rc = register_netdev(dev); if (rc) { airo_print_err(dev->name, "Couldn't register_netdev"); goto err_out_map; } ai->wifidev = init_wifidev(ai, dev); if (!ai->wifidev) goto err_out_reg; rc = readCapabilityRid(ai, &cap_rid, 1); if (rc != SUCCESS) { rc = -EIO; goto err_out_wifi; } /* WEP capability discovery */ ai->wep_capable = (cap_rid.softCap & cpu_to_le16(0x02)) ? 1 : 0; ai->max_wep_idx = (cap_rid.softCap & cpu_to_le16(0x80)) ? 3 : 0; airo_print_info(dev->name, "Firmware version %x.%x.%02d", ((le16_to_cpu(cap_rid.softVer) >> 8) & 0xF), (le16_to_cpu(cap_rid.softVer) & 0xFF), le16_to_cpu(cap_rid.softSubVer)); /* Test for WPA support */ /* Only firmware versions 5.30.17 or better can do WPA */ if (le16_to_cpu(cap_rid.softVer) > 0x530 || (le16_to_cpu(cap_rid.softVer) == 0x530 && le16_to_cpu(cap_rid.softSubVer) >= 17)) { airo_print_info(ai->dev->name, "WPA supported."); set_bit(FLAG_WPA_CAPABLE, &ai->flags); ai->bssListFirst = RID_WPA_BSSLISTFIRST; ai->bssListNext = RID_WPA_BSSLISTNEXT; ai->bssListRidLen = sizeof(BSSListRid); } else { airo_print_info(ai->dev->name, "WPA unsupported with firmware " "versions older than 5.30.17."); ai->bssListFirst = RID_BSSLISTFIRST; ai->bssListNext = RID_BSSLISTNEXT; ai->bssListRidLen = sizeof(BSSListRid) - sizeof(BSSListRidExtra); } set_bit(FLAG_REGISTERED,&ai->flags); airo_print_info(dev->name, "MAC enabled %pM", dev->dev_addr); /* Allocate the transmit buffers */ if (probe && !test_bit(FLAG_MPI,&ai->flags)) for( i = 0; i < MAX_FIDS; i++ ) ai->fids[i] = transmit_allocate(ai,AIRO_DEF_MTU,i>=MAX_FIDS/2); if (setup_proc_entry(dev, dev->ml_priv) < 0) goto err_out_wifi; return dev; err_out_wifi: unregister_netdev(ai->wifidev); free_netdev(ai->wifidev); err_out_reg: unregister_netdev(dev); err_out_map: if (test_bit(FLAG_MPI,&ai->flags) && pci) { pci_free_consistent(pci, PCI_SHARED_LEN, ai->shared, ai->shared_dma); iounmap(ai->pciaux); iounmap(ai->pcimem); mpi_unmap_card(ai->pci); } err_out_res: if (!is_pcmcia) release_region( dev->base_addr, 64 ); err_out_nets: airo_networks_free(ai); err_out_free: del_airo_dev(ai); free_netdev(dev); return NULL; } Commit Message: net: Audit drivers to identify those needing IFF_TX_SKB_SHARING cleared After the last patch, We are left in a state in which only drivers calling ether_setup have IFF_TX_SKB_SHARING set (we assume that drivers touching real hardware call ether_setup for their net_devices and don't hold any state in their skbs. There are a handful of drivers that violate this assumption of course, and need to be fixed up. This patch identifies those drivers, and marks them as not being able to support the safe transmission of skbs by clearning the IFF_TX_SKB_SHARING flag in priv_flags Signed-off-by: Neil Horman <[email protected]> CC: Karsten Keil <[email protected]> CC: "David S. Miller" <[email protected]> CC: Jay Vosburgh <[email protected]> CC: Andy Gospodarek <[email protected]> CC: Patrick McHardy <[email protected]> CC: Krzysztof Halasa <[email protected]> CC: "John W. Linville" <[email protected]> CC: Greg Kroah-Hartman <[email protected]> CC: Marcel Holtmann <[email protected]> CC: Johannes Berg <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-264
static struct net_device *_init_airo_card( unsigned short irq, int port, int is_pcmcia, struct pci_dev *pci, struct device *dmdev ) { struct net_device *dev; struct airo_info *ai; int i, rc; CapabilityRid cap_rid; /* Create the network device object. */ dev = alloc_netdev(sizeof(*ai), "", ether_setup); if (!dev) { airo_print_err("", "Couldn't alloc_etherdev"); return NULL; } ai = dev->ml_priv = netdev_priv(dev); ai->wifidev = NULL; ai->flags = 1 << FLAG_RADIO_DOWN; ai->jobs = 0; ai->dev = dev; if (pci && (pci->device == 0x5000 || pci->device == 0xa504)) { airo_print_dbg("", "Found an MPI350 card"); set_bit(FLAG_MPI, &ai->flags); } spin_lock_init(&ai->aux_lock); sema_init(&ai->sem, 1); ai->config.len = 0; ai->pci = pci; init_waitqueue_head (&ai->thr_wait); ai->tfm = NULL; add_airo_dev(ai); if (airo_networks_allocate (ai)) goto err_out_free; airo_networks_initialize (ai); skb_queue_head_init (&ai->txq); /* The Airo-specific entries in the device structure. */ if (test_bit(FLAG_MPI,&ai->flags)) dev->netdev_ops = &mpi_netdev_ops; else dev->netdev_ops = &airo_netdev_ops; dev->wireless_handlers = &airo_handler_def; ai->wireless_data.spy_data = &ai->spy_data; dev->wireless_data = &ai->wireless_data; dev->irq = irq; dev->base_addr = port; dev->priv_flags &= ~IFF_TX_SKB_SHARING; SET_NETDEV_DEV(dev, dmdev); reset_card (dev, 1); msleep(400); if (!is_pcmcia) { if (!request_region(dev->base_addr, 64, DRV_NAME)) { rc = -EBUSY; airo_print_err(dev->name, "Couldn't request region"); goto err_out_nets; } } if (test_bit(FLAG_MPI,&ai->flags)) { if (mpi_map_card(ai, pci)) { airo_print_err("", "Could not map memory"); goto err_out_res; } } if (probe) { if (setup_card(ai, dev->dev_addr, 1) != SUCCESS) { airo_print_err(dev->name, "MAC could not be enabled" ); rc = -EIO; goto err_out_map; } } else if (!test_bit(FLAG_MPI,&ai->flags)) { ai->bap_read = fast_bap_read; set_bit(FLAG_FLASHING, &ai->flags); } strcpy(dev->name, "eth%d"); rc = register_netdev(dev); if (rc) { airo_print_err(dev->name, "Couldn't register_netdev"); goto err_out_map; } ai->wifidev = init_wifidev(ai, dev); if (!ai->wifidev) goto err_out_reg; rc = readCapabilityRid(ai, &cap_rid, 1); if (rc != SUCCESS) { rc = -EIO; goto err_out_wifi; } /* WEP capability discovery */ ai->wep_capable = (cap_rid.softCap & cpu_to_le16(0x02)) ? 1 : 0; ai->max_wep_idx = (cap_rid.softCap & cpu_to_le16(0x80)) ? 3 : 0; airo_print_info(dev->name, "Firmware version %x.%x.%02d", ((le16_to_cpu(cap_rid.softVer) >> 8) & 0xF), (le16_to_cpu(cap_rid.softVer) & 0xFF), le16_to_cpu(cap_rid.softSubVer)); /* Test for WPA support */ /* Only firmware versions 5.30.17 or better can do WPA */ if (le16_to_cpu(cap_rid.softVer) > 0x530 || (le16_to_cpu(cap_rid.softVer) == 0x530 && le16_to_cpu(cap_rid.softSubVer) >= 17)) { airo_print_info(ai->dev->name, "WPA supported."); set_bit(FLAG_WPA_CAPABLE, &ai->flags); ai->bssListFirst = RID_WPA_BSSLISTFIRST; ai->bssListNext = RID_WPA_BSSLISTNEXT; ai->bssListRidLen = sizeof(BSSListRid); } else { airo_print_info(ai->dev->name, "WPA unsupported with firmware " "versions older than 5.30.17."); ai->bssListFirst = RID_BSSLISTFIRST; ai->bssListNext = RID_BSSLISTNEXT; ai->bssListRidLen = sizeof(BSSListRid) - sizeof(BSSListRidExtra); } set_bit(FLAG_REGISTERED,&ai->flags); airo_print_info(dev->name, "MAC enabled %pM", dev->dev_addr); /* Allocate the transmit buffers */ if (probe && !test_bit(FLAG_MPI,&ai->flags)) for( i = 0; i < MAX_FIDS; i++ ) ai->fids[i] = transmit_allocate(ai,AIRO_DEF_MTU,i>=MAX_FIDS/2); if (setup_proc_entry(dev, dev->ml_priv) < 0) goto err_out_wifi; return dev; err_out_wifi: unregister_netdev(ai->wifidev); free_netdev(ai->wifidev); err_out_reg: unregister_netdev(dev); err_out_map: if (test_bit(FLAG_MPI,&ai->flags) && pci) { pci_free_consistent(pci, PCI_SHARED_LEN, ai->shared, ai->shared_dma); iounmap(ai->pciaux); iounmap(ai->pcimem); mpi_unmap_card(ai->pci); } err_out_res: if (!is_pcmcia) release_region( dev->base_addr, 64 ); err_out_nets: airo_networks_free(ai); err_out_free: del_airo_dev(ai); free_netdev(dev); return NULL; }
165,733
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int find_high_bit(unsigned int x) { int i; for(i=31;i>=0;i--) { if(x&(1<<i)) return i; } return 0; } Commit Message: Trying to fix some invalid left shift operations Fixes issue #16 CWE ID: CWE-682
static int find_high_bit(unsigned int x) { int i; for(i=31;i>=0;i--) { if(x&(1U<<(unsigned int)i)) return i; } return 0; }
168,194
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool GLES2DecoderImpl::CheckFramebufferValid( Framebuffer* framebuffer, GLenum target, const char* func_name) { if (!framebuffer) { if (backbuffer_needs_clear_bits_) { glClearColor(0, 0, 0, (GLES2Util::GetChannelsForFormat( offscreen_target_color_format_) & 0x0008) != 0 ? 0 : 1); state_.SetDeviceColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); glClearStencil(0); state_.SetDeviceStencilMaskSeparate(GL_FRONT, -1); state_.SetDeviceStencilMaskSeparate(GL_BACK, -1); glClearDepth(1.0f); state_.SetDeviceDepthMask(GL_TRUE); state_.SetDeviceCapabilityState(GL_SCISSOR_TEST, false); glClear(backbuffer_needs_clear_bits_); backbuffer_needs_clear_bits_ = 0; RestoreClearState(); } return true; } if (framebuffer_manager()->IsComplete(framebuffer)) { return true; } GLenum completeness = framebuffer->IsPossiblyComplete(); if (completeness != GL_FRAMEBUFFER_COMPLETE) { LOCAL_SET_GL_ERROR( GL_INVALID_FRAMEBUFFER_OPERATION, func_name, "framebuffer incomplete"); return false; } if (renderbuffer_manager()->HaveUnclearedRenderbuffers() || texture_manager()->HaveUnclearedMips()) { if (!framebuffer->IsCleared()) { if (framebuffer->GetStatus(texture_manager(), target) != GL_FRAMEBUFFER_COMPLETE) { LOCAL_SET_GL_ERROR( GL_INVALID_FRAMEBUFFER_OPERATION, func_name, "framebuffer incomplete (clear)"); return false; } ClearUnclearedAttachments(target, framebuffer); } } if (!framebuffer_manager()->IsComplete(framebuffer)) { if (framebuffer->GetStatus(texture_manager(), target) != GL_FRAMEBUFFER_COMPLETE) { LOCAL_SET_GL_ERROR( GL_INVALID_FRAMEBUFFER_OPERATION, func_name, "framebuffer incomplete (check)"); return false; } framebuffer_manager()->MarkAsComplete(framebuffer); } return true; } Commit Message: Framebuffer clear() needs to consider the situation some draw buffers are disabled. This is when we expose DrawBuffers extension. BUG=376951 TEST=the attached test case, webgl conformance [email protected],[email protected] Review URL: https://codereview.chromium.org/315283002 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@275338 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
bool GLES2DecoderImpl::CheckFramebufferValid( Framebuffer* framebuffer, GLenum target, const char* func_name) { if (!framebuffer) { if (backbuffer_needs_clear_bits_) { glClearColor(0, 0, 0, (GLES2Util::GetChannelsForFormat( offscreen_target_color_format_) & 0x0008) != 0 ? 0 : 1); state_.SetDeviceColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); glClearStencil(0); state_.SetDeviceStencilMaskSeparate(GL_FRONT, -1); state_.SetDeviceStencilMaskSeparate(GL_BACK, -1); glClearDepth(1.0f); state_.SetDeviceDepthMask(GL_TRUE); state_.SetDeviceCapabilityState(GL_SCISSOR_TEST, false); bool reset_draw_buffer = false; if ((backbuffer_needs_clear_bits_ | GL_COLOR_BUFFER_BIT) != 0 && group_->draw_buffer() == GL_NONE) { reset_draw_buffer = true; GLenum buf = GL_BACK; if (GetBackbufferServiceId() != 0) // emulated backbuffer buf = GL_COLOR_ATTACHMENT0; glDrawBuffersARB(1, &buf); } glClear(backbuffer_needs_clear_bits_); if (reset_draw_buffer) { GLenum buf = GL_NONE; glDrawBuffersARB(1, &buf); } backbuffer_needs_clear_bits_ = 0; RestoreClearState(); } return true; } if (framebuffer_manager()->IsComplete(framebuffer)) { return true; } GLenum completeness = framebuffer->IsPossiblyComplete(); if (completeness != GL_FRAMEBUFFER_COMPLETE) { LOCAL_SET_GL_ERROR( GL_INVALID_FRAMEBUFFER_OPERATION, func_name, "framebuffer incomplete"); return false; } if (renderbuffer_manager()->HaveUnclearedRenderbuffers() || texture_manager()->HaveUnclearedMips()) { if (!framebuffer->IsCleared()) { if (framebuffer->GetStatus(texture_manager(), target) != GL_FRAMEBUFFER_COMPLETE) { LOCAL_SET_GL_ERROR( GL_INVALID_FRAMEBUFFER_OPERATION, func_name, "framebuffer incomplete (clear)"); return false; } ClearUnclearedAttachments(target, framebuffer); } } if (!framebuffer_manager()->IsComplete(framebuffer)) { if (framebuffer->GetStatus(texture_manager(), target) != GL_FRAMEBUFFER_COMPLETE) { LOCAL_SET_GL_ERROR( GL_INVALID_FRAMEBUFFER_OPERATION, func_name, "framebuffer incomplete (check)"); return false; } framebuffer_manager()->MarkAsComplete(framebuffer); } return true; }
171,657
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void CheckValueType(const Value::ValueType expected, const Value* const actual) { DCHECK(actual != NULL) << "Expected value to be non-NULL"; DCHECK(expected == actual->GetType()) << "Expected " << print_valuetype(expected) << ", but was " << print_valuetype(actual->GetType()); } Commit Message: In chromedriver, add /log url to get the contents of the chromedriver log remotely. Also add a 'chrome.verbose' boolean startup option. Remove usage of VLOG(1) in chromedriver. We do not need as complicated logging as in Chrome. BUG=85241 TEST=none Review URL: http://codereview.chromium.org/7104085 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@88591 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void CheckValueType(const Value::ValueType expected,
170,465
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void PrintWebViewHelper::OnPrintForPrintPreview( const base::DictionaryValue& job_settings) { if (prep_frame_view_) return; if (!render_view()->GetWebView()) return; blink::WebFrame* main_frame = render_view()->GetWebView()->mainFrame(); if (!main_frame) return; blink::WebDocument document = main_frame->document(); blink::WebElement pdf_element = document.getElementById("pdf-viewer"); if (pdf_element.isNull()) { NOTREACHED(); return; } blink::WebLocalFrame* plugin_frame = pdf_element.document().frame(); blink::WebElement plugin_element = pdf_element; if (pdf_element.hasHTMLTagName("iframe")) { plugin_frame = blink::WebLocalFrame::fromFrameOwnerElement(pdf_element); plugin_element = delegate_->GetPdfElement(plugin_frame); if (plugin_element.isNull()) { NOTREACHED(); return; } } base::AutoReset<bool> set_printing_flag(&print_for_preview_, true); if (!UpdatePrintSettings(plugin_frame, plugin_element, job_settings)) { LOG(ERROR) << "UpdatePrintSettings failed"; DidFinishPrinting(FAIL_PRINT); return; } PrintMsg_Print_Params& print_params = print_pages_params_->params; print_params.printable_area = gfx::Rect(print_params.page_size); if (!RenderPagesForPrint(plugin_frame, plugin_element)) { LOG(ERROR) << "RenderPagesForPrint failed"; DidFinishPrinting(FAIL_PRINT); } } Commit Message: Crash on nested IPC handlers in PrintWebViewHelper Class is not designed to handle nested IPC. Regular flows also does not expect them. Still during printing of plugging them may show message boxes and start nested message loops. For now we are going just crash. If stats show us that this case is frequent we will have to do something more complicated. BUG=502562 Review URL: https://codereview.chromium.org/1228693002 Cr-Commit-Position: refs/heads/master@{#338100} CWE ID:
void PrintWebViewHelper::OnPrintForPrintPreview( const base::DictionaryValue& job_settings) { CHECK_LE(ipc_nesting_level_, 1); if (prep_frame_view_) return; if (!render_view()->GetWebView()) return; blink::WebFrame* main_frame = render_view()->GetWebView()->mainFrame(); if (!main_frame) return; blink::WebDocument document = main_frame->document(); blink::WebElement pdf_element = document.getElementById("pdf-viewer"); if (pdf_element.isNull()) { NOTREACHED(); return; } blink::WebLocalFrame* plugin_frame = pdf_element.document().frame(); blink::WebElement plugin_element = pdf_element; if (pdf_element.hasHTMLTagName("iframe")) { plugin_frame = blink::WebLocalFrame::fromFrameOwnerElement(pdf_element); plugin_element = delegate_->GetPdfElement(plugin_frame); if (plugin_element.isNull()) { NOTREACHED(); return; } } base::AutoReset<bool> set_printing_flag(&print_for_preview_, true); if (!UpdatePrintSettings(plugin_frame, plugin_element, job_settings)) { LOG(ERROR) << "UpdatePrintSettings failed"; DidFinishPrinting(FAIL_PRINT); return; } PrintMsg_Print_Params& print_params = print_pages_params_->params; print_params.printable_area = gfx::Rect(print_params.page_size); if (!RenderPagesForPrint(plugin_frame, plugin_element)) { LOG(ERROR) << "RenderPagesForPrint failed"; DidFinishPrinting(FAIL_PRINT); } }
171,873
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int fsck_gitmodules_fn(const char *var, const char *value, void *vdata) { struct fsck_gitmodules_data *data = vdata; const char *subsection, *key; int subsection_len; char *name; if (parse_config_key(var, "submodule", &subsection, &subsection_len, &key) < 0 || !subsection) return 0; name = xmemdupz(subsection, subsection_len); if (check_submodule_name(name) < 0) data->ret |= report(data->options, data->obj, FSCK_MSG_GITMODULES_NAME, "disallowed submodule name: %s", name); free(name); return 0; } Commit Message: fsck: detect submodule urls starting with dash Urls with leading dashes can cause mischief on older versions of Git. We should detect them so that they can be rejected by receive.fsckObjects, preventing modern versions of git from being a vector by which attacks can spread. Signed-off-by: Jeff King <[email protected]> Signed-off-by: Junio C Hamano <[email protected]> CWE ID: CWE-20
static int fsck_gitmodules_fn(const char *var, const char *value, void *vdata) { struct fsck_gitmodules_data *data = vdata; const char *subsection, *key; int subsection_len; char *name; if (parse_config_key(var, "submodule", &subsection, &subsection_len, &key) < 0 || !subsection) return 0; name = xmemdupz(subsection, subsection_len); if (check_submodule_name(name) < 0) data->ret |= report(data->options, data->obj, FSCK_MSG_GITMODULES_NAME, "disallowed submodule name: %s", name); if (!strcmp(key, "url") && value && looks_like_command_line_option(value)) data->ret |= report(data->options, data->obj, FSCK_MSG_GITMODULES_URL, "disallowed submodule url: %s", value); free(name); return 0; }
169,019
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void ChromeMockRenderThread::OnDidPrintPage( const PrintHostMsg_DidPrintPage_Params& params) { if (printer_.get()) printer_->PrintPage(params); } Commit Message: Print preview: Use an ID instead of memory pointer string in WebUI. BUG=144051 Review URL: https://chromiumcodereview.appspot.com/10870003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@153342 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-200
void ChromeMockRenderThread::OnDidPrintPage( const PrintHostMsg_DidPrintPage_Params& params) { printer_->PrintPage(params); }
170,850
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void UserSelectionScreen::FillUserDictionary( user_manager::User* user, bool is_owner, bool is_signin_to_add, proximity_auth::mojom::AuthType auth_type, const std::vector<std::string>* public_session_recommended_locales, base::DictionaryValue* user_dict) { const bool is_public_session = user->GetType() == user_manager::USER_TYPE_PUBLIC_ACCOUNT; const bool is_legacy_supervised_user = user->GetType() == user_manager::USER_TYPE_SUPERVISED; const bool is_child_user = user->GetType() == user_manager::USER_TYPE_CHILD; user_dict->SetString(kKeyUsername, user->GetAccountId().Serialize()); user_dict->SetString(kKeyEmailAddress, user->display_email()); user_dict->SetString(kKeyDisplayName, user->GetDisplayName()); user_dict->SetBoolean(kKeyPublicAccount, is_public_session); user_dict->SetBoolean(kKeyLegacySupervisedUser, is_legacy_supervised_user); user_dict->SetBoolean(kKeyChildUser, is_child_user); user_dict->SetBoolean(kKeyDesktopUser, false); user_dict->SetInteger(kKeyInitialAuthType, static_cast<int>(auth_type)); user_dict->SetBoolean(kKeySignedIn, user->is_logged_in()); user_dict->SetBoolean(kKeyIsOwner, is_owner); user_dict->SetBoolean(kKeyIsActiveDirectory, user->IsActiveDirectoryUser()); user_dict->SetBoolean(kKeyAllowFingerprint, AllowFingerprintForUser(user)); FillMultiProfileUserPrefs(user, user_dict, is_signin_to_add); if (is_public_session) { AddPublicSessionDetailsToUserDictionaryEntry( user_dict, public_session_recommended_locales); } } Commit Message: cros: Check initial auth type when showing views login. Bug: 859611 Change-Id: I0298db9bbf4aed6bd40600aef2e1c5794e8cd058 Reviewed-on: https://chromium-review.googlesource.com/1123056 Reviewed-by: Xiaoyin Hu <[email protected]> Commit-Queue: Jacob Dufault <[email protected]> Cr-Commit-Position: refs/heads/master@{#572224} CWE ID:
void UserSelectionScreen::FillUserDictionary( const user_manager::User* user, bool is_owner, bool is_signin_to_add, proximity_auth::mojom::AuthType auth_type, const std::vector<std::string>* public_session_recommended_locales, base::DictionaryValue* user_dict) { const bool is_public_session = user->GetType() == user_manager::USER_TYPE_PUBLIC_ACCOUNT; const bool is_legacy_supervised_user = user->GetType() == user_manager::USER_TYPE_SUPERVISED; const bool is_child_user = user->GetType() == user_manager::USER_TYPE_CHILD; user_dict->SetString(kKeyUsername, user->GetAccountId().Serialize()); user_dict->SetString(kKeyEmailAddress, user->display_email()); user_dict->SetString(kKeyDisplayName, user->GetDisplayName()); user_dict->SetBoolean(kKeyPublicAccount, is_public_session); user_dict->SetBoolean(kKeyLegacySupervisedUser, is_legacy_supervised_user); user_dict->SetBoolean(kKeyChildUser, is_child_user); user_dict->SetBoolean(kKeyDesktopUser, false); user_dict->SetInteger(kKeyInitialAuthType, static_cast<int>(auth_type)); user_dict->SetBoolean(kKeySignedIn, user->is_logged_in()); user_dict->SetBoolean(kKeyIsOwner, is_owner); user_dict->SetBoolean(kKeyIsActiveDirectory, user->IsActiveDirectoryUser()); user_dict->SetBoolean(kKeyAllowFingerprint, AllowFingerprintForUser(user)); FillMultiProfileUserPrefs(user, user_dict, is_signin_to_add); if (is_public_session) { AddPublicSessionDetailsToUserDictionaryEntry( user_dict, public_session_recommended_locales); } }
172,200
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void set_task_cpu(struct task_struct *p, unsigned int new_cpu) { #ifdef CONFIG_SCHED_DEBUG /* * We should never call set_task_cpu() on a blocked task, * ttwu() will sort out the placement. */ WARN_ON_ONCE(p->state != TASK_RUNNING && p->state != TASK_WAKING && !(task_thread_info(p)->preempt_count & PREEMPT_ACTIVE)); #ifdef CONFIG_LOCKDEP /* * The caller should hold either p->pi_lock or rq->lock, when changing * a task's CPU. ->pi_lock for waking tasks, rq->lock for runnable tasks. * * sched_move_task() holds both and thus holding either pins the cgroup, * see set_task_rq(). * * Furthermore, all task_rq users should acquire both locks, see * task_rq_lock(). */ WARN_ON_ONCE(debug_locks && !(lockdep_is_held(&p->pi_lock) || lockdep_is_held(&task_rq(p)->lock))); #endif #endif trace_sched_migrate_task(p, new_cpu); if (task_cpu(p) != new_cpu) { p->se.nr_migrations++; perf_sw_event(PERF_COUNT_SW_CPU_MIGRATIONS, 1, 1, NULL, 0); } __set_task_cpu(p, new_cpu); } Commit Message: perf: Remove the nmi parameter from the swevent and overflow interface The nmi parameter indicated if we could do wakeups from the current context, if not, we would set some state and self-IPI and let the resulting interrupt do the wakeup. For the various event classes: - hardware: nmi=0; PMI is in fact an NMI or we run irq_work_run from the PMI-tail (ARM etc.) - tracepoint: nmi=0; since tracepoint could be from NMI context. - software: nmi=[0,1]; some, like the schedule thing cannot perform wakeups, and hence need 0. As one can see, there is very little nmi=1 usage, and the down-side of not using it is that on some platforms some software events can have a jiffy delay in wakeup (when arch_irq_work_raise isn't implemented). The up-side however is that we can remove the nmi parameter and save a bunch of conditionals in fast paths. Signed-off-by: Peter Zijlstra <[email protected]> Cc: Michael Cree <[email protected]> Cc: Will Deacon <[email protected]> Cc: Deng-Cheng Zhu <[email protected]> Cc: Anton Blanchard <[email protected]> Cc: Eric B Munson <[email protected]> Cc: Heiko Carstens <[email protected]> Cc: Paul Mundt <[email protected]> Cc: David S. Miller <[email protected]> Cc: Frederic Weisbecker <[email protected]> Cc: Jason Wessel <[email protected]> Cc: Don Zickus <[email protected]> Link: http://lkml.kernel.org/n/[email protected] Signed-off-by: Ingo Molnar <[email protected]> CWE ID: CWE-399
void set_task_cpu(struct task_struct *p, unsigned int new_cpu) { #ifdef CONFIG_SCHED_DEBUG /* * We should never call set_task_cpu() on a blocked task, * ttwu() will sort out the placement. */ WARN_ON_ONCE(p->state != TASK_RUNNING && p->state != TASK_WAKING && !(task_thread_info(p)->preempt_count & PREEMPT_ACTIVE)); #ifdef CONFIG_LOCKDEP /* * The caller should hold either p->pi_lock or rq->lock, when changing * a task's CPU. ->pi_lock for waking tasks, rq->lock for runnable tasks. * * sched_move_task() holds both and thus holding either pins the cgroup, * see set_task_rq(). * * Furthermore, all task_rq users should acquire both locks, see * task_rq_lock(). */ WARN_ON_ONCE(debug_locks && !(lockdep_is_held(&p->pi_lock) || lockdep_is_held(&task_rq(p)->lock))); #endif #endif trace_sched_migrate_task(p, new_cpu); if (task_cpu(p) != new_cpu) { p->se.nr_migrations++; perf_sw_event(PERF_COUNT_SW_CPU_MIGRATIONS, 1, NULL, 0); } __set_task_cpu(p, new_cpu); }
165,843
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: accept_xsmp_connection (SmsConn sms_conn, GsmXsmpServer *server, unsigned long *mask_ret, SmsCallbacks *callbacks_ret, char **failure_reason_ret) { IceConn ice_conn; GsmXSMPClient *client; /* FIXME: what about during shutdown but before gsm_xsmp_shutdown? */ if (server->priv->xsmp_sockets == NULL) { g_debug ("GsmXsmpServer: In shutdown, rejecting new client"); *failure_reason_ret = strdup (_("Refusing new client connection because the session is currently being shut down\n")); return FALSE; } ice_conn = SmsGetIceConnection (sms_conn); client = ice_conn->context; g_return_val_if_fail (client != NULL, TRUE); gsm_xsmp_client_connect (client, sms_conn, mask_ret, callbacks_ret); return TRUE; } Commit Message: [gsm] Delay the creation of the GsmXSMPClient until it really exists We used to create the GsmXSMPClient before the XSMP connection is really accepted. This can lead to some issues, though. An example is: https://bugzilla.gnome.org/show_bug.cgi?id=598211#c19. Quoting: "What is happening is that a new client (probably metacity in your case) is opening an ICE connection in the GSM_MANAGER_PHASE_END_SESSION phase, which causes a new GsmXSMPClient to be added to the client store. The GSM_MANAGER_PHASE_EXIT phase then begins before the client has had a chance to establish a xsmp connection, which means that client->priv->conn will not be initialized at the point that xsmp_stop is called on the new unregistered client." The fix is to create the GsmXSMPClient object when there's a real XSMP connection. This implies moving the timeout that makes sure we don't have an empty client to the XSMP server. https://bugzilla.gnome.org/show_bug.cgi?id=598211 CWE ID: CWE-835
accept_xsmp_connection (SmsConn sms_conn, GsmXsmpServer *server, unsigned long *mask_ret, SmsCallbacks *callbacks_ret, char **failure_reason_ret) { IceConn ice_conn; GsmClient *client; GsmIceConnectionWatch *data; /* FIXME: what about during shutdown but before gsm_xsmp_shutdown? */ if (server->priv->xsmp_sockets == NULL) { g_debug ("GsmXsmpServer: In shutdown, rejecting new client"); *failure_reason_ret = strdup (_("Refusing new client connection because the session is currently being shut down\n")); return FALSE; } ice_conn = SmsGetIceConnection (sms_conn); data = ice_conn->context; /* Each GsmXSMPClient has its own IceConn watcher */ free_ice_connection_watch (data); client = gsm_xsmp_client_new (ice_conn); gsm_store_add (server->priv->client_store, gsm_client_peek_id (client), G_OBJECT (client)); /* the store will own the ref */ g_object_unref (client); gsm_xsmp_client_connect (GSM_XSMP_CLIENT (client), sms_conn, mask_ret, callbacks_ret); return TRUE; }
168,053
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: Ins_GETVARIATION( TT_ExecContext exc, FT_Long* args ) { FT_UInt num_axes = exc->face->blend->num_axis; FT_Fixed* coords = exc->face->blend->normalizedcoords; FT_UInt i; if ( BOUNDS( num_axes, exc->stackSize + 1 - exc->top ) ) { exc->error = FT_THROW( Stack_Overflow ); return; } for ( i = 0; i < num_axes; i++ ) args[i] = coords[i] >> 2; /* convert 16.16 to 2.14 format */ } Commit Message: CWE ID: CWE-476
Ins_GETVARIATION( TT_ExecContext exc, FT_Long* args ) { FT_UInt num_axes = exc->face->blend->num_axis; FT_Fixed* coords = exc->face->blend->normalizedcoords; FT_UInt i; if ( BOUNDS( num_axes, exc->stackSize + 1 - exc->top ) ) { exc->error = FT_THROW( Stack_Overflow ); return; } if ( coords ) { for ( i = 0; i < num_axes; i++ ) args[i] = coords[i] >> 2; /* convert 16.16 to 2.14 format */ } else { for ( i = 0; i < num_axes; i++ ) args[i] = 0; } }
165,021
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void P2PQuicStreamImpl::Finish() { DCHECK(!fin_sent()); quic::QuicStream::WriteOrBufferData("", /*fin=*/true, nullptr); } Commit Message: P2PQuicStream write functionality. This adds the P2PQuicStream::WriteData function and adds tests. It also adds the concept of a write buffered amount, enforcing this at the P2PQuicStreamImpl. Bug: 874296 Change-Id: Id02c8aa8d5368a87bb24a2e50dab5ef94bcae131 Reviewed-on: https://chromium-review.googlesource.com/c/1315534 Commit-Queue: Seth Hampson <[email protected]> Reviewed-by: Henrik Boström <[email protected]> Cr-Commit-Position: refs/heads/master@{#605766} CWE ID: CWE-284
void P2PQuicStreamImpl::Finish() { void P2PQuicStreamImpl::WriteData(std::vector<uint8_t> data, bool fin) { // It is up to the delegate to not write more data than the // |write_buffer_size_|. DCHECK_GE(write_buffer_size_, data.size() + write_buffered_amount_); write_buffered_amount_ += data.size(); QuicStream::WriteOrBufferData( quic::QuicStringPiece(reinterpret_cast<const char*>(data.data()), data.size()), fin, nullptr); }
172,261
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: AvailableSpaceQueryTask( QuotaManager* manager, const AvailableSpaceCallback& callback) : QuotaThreadTask(manager, manager->db_thread_), profile_path_(manager->profile_path_), space_(-1), get_disk_space_fn_(manager->get_disk_space_fn_), callback_(callback) { DCHECK(get_disk_space_fn_); } Commit Message: Wipe out QuotaThreadTask. This is a one of a series of refactoring patches for QuotaManager. http://codereview.chromium.org/10872054/ http://codereview.chromium.org/10917060/ BUG=139270 Review URL: https://chromiumcodereview.appspot.com/10919070 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@154987 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
AvailableSpaceQueryTask(
170,668
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void BrowserContextDestroyer::FinishDestroyContext() { DCHECK_EQ(pending_hosts_, 0U); delete context_; context_ = nullptr; delete this; } Commit Message: CWE ID: CWE-20
void BrowserContextDestroyer::FinishDestroyContext() { DCHECK(finish_destroy_scheduled_); CHECK_EQ(GetHostsForContext(context_.get()).size(), 0U) << "One or more RenderProcessHosts exist whilst its BrowserContext is " << "being deleted!"; g_contexts_pending_deletion.Get().remove(this); if (context_->IsOffTheRecord()) { // If this is an OTR context and its owner BrowserContext has been scheduled // for deletion, update the owner's BrowserContextDestroyer BrowserContextDestroyer* orig_destroyer = GetForContext(context_->GetOriginalContext()); if (orig_destroyer) { DCHECK_GT(orig_destroyer->otr_contexts_pending_deletion_, 0U); DCHECK(!orig_destroyer->finish_destroy_scheduled_); --orig_destroyer->otr_contexts_pending_deletion_; orig_destroyer->MaybeScheduleFinishDestroyContext(); } } delete this; }
165,420
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: OMX_ERRORTYPE SoftMPEG4Encoder::internalSetParameter( OMX_INDEXTYPE index, const OMX_PTR params) { int32_t indexFull = index; switch (indexFull) { case OMX_IndexParamVideoBitrate: { OMX_VIDEO_PARAM_BITRATETYPE *bitRate = (OMX_VIDEO_PARAM_BITRATETYPE *) params; if (bitRate->nPortIndex != 1 || bitRate->eControlRate != OMX_Video_ControlRateVariable) { return OMX_ErrorUndefined; } mBitrate = bitRate->nTargetBitrate; return OMX_ErrorNone; } case OMX_IndexParamVideoH263: { OMX_VIDEO_PARAM_H263TYPE *h263type = (OMX_VIDEO_PARAM_H263TYPE *)params; if (h263type->nPortIndex != 1) { return OMX_ErrorUndefined; } if (h263type->eProfile != OMX_VIDEO_H263ProfileBaseline || h263type->eLevel != OMX_VIDEO_H263Level45 || (h263type->nAllowedPictureTypes & OMX_VIDEO_PictureTypeB) || h263type->bPLUSPTYPEAllowed != OMX_FALSE || h263type->bForceRoundingTypeToZero != OMX_FALSE || h263type->nPictureHeaderRepetition != 0 || h263type->nGOBHeaderInterval != 0) { return OMX_ErrorUndefined; } return OMX_ErrorNone; } case OMX_IndexParamVideoMpeg4: { OMX_VIDEO_PARAM_MPEG4TYPE *mpeg4type = (OMX_VIDEO_PARAM_MPEG4TYPE *)params; if (mpeg4type->nPortIndex != 1) { return OMX_ErrorUndefined; } if (mpeg4type->eProfile != OMX_VIDEO_MPEG4ProfileCore || mpeg4type->eLevel != OMX_VIDEO_MPEG4Level2 || (mpeg4type->nAllowedPictureTypes & OMX_VIDEO_PictureTypeB) || mpeg4type->nBFrames != 0 || mpeg4type->nIDCVLCThreshold != 0 || mpeg4type->bACPred != OMX_TRUE || mpeg4type->nMaxPacketSize != 256 || mpeg4type->nTimeIncRes != 1000 || mpeg4type->nHeaderExtension != 0 || mpeg4type->bReversibleVLC != OMX_FALSE) { return OMX_ErrorUndefined; } return OMX_ErrorNone; } default: return SoftVideoEncoderOMXComponent::internalSetParameter(index, params); } } Commit Message: DO NOT MERGE Verify OMX buffer sizes prior to access Bug: 27207275 Change-Id: I4412825d1ee233d993af0a67708bea54304ff62d CWE ID: CWE-119
OMX_ERRORTYPE SoftMPEG4Encoder::internalSetParameter( OMX_INDEXTYPE index, const OMX_PTR params) { int32_t indexFull = index; switch (indexFull) { case OMX_IndexParamVideoBitrate: { OMX_VIDEO_PARAM_BITRATETYPE *bitRate = (OMX_VIDEO_PARAM_BITRATETYPE *) params; if (!isValidOMXParam(bitRate)) { return OMX_ErrorBadParameter; } if (bitRate->nPortIndex != 1 || bitRate->eControlRate != OMX_Video_ControlRateVariable) { return OMX_ErrorUndefined; } mBitrate = bitRate->nTargetBitrate; return OMX_ErrorNone; } case OMX_IndexParamVideoH263: { OMX_VIDEO_PARAM_H263TYPE *h263type = (OMX_VIDEO_PARAM_H263TYPE *)params; if (!isValidOMXParam(h263type)) { return OMX_ErrorBadParameter; } if (h263type->nPortIndex != 1) { return OMX_ErrorUndefined; } if (h263type->eProfile != OMX_VIDEO_H263ProfileBaseline || h263type->eLevel != OMX_VIDEO_H263Level45 || (h263type->nAllowedPictureTypes & OMX_VIDEO_PictureTypeB) || h263type->bPLUSPTYPEAllowed != OMX_FALSE || h263type->bForceRoundingTypeToZero != OMX_FALSE || h263type->nPictureHeaderRepetition != 0 || h263type->nGOBHeaderInterval != 0) { return OMX_ErrorUndefined; } return OMX_ErrorNone; } case OMX_IndexParamVideoMpeg4: { OMX_VIDEO_PARAM_MPEG4TYPE *mpeg4type = (OMX_VIDEO_PARAM_MPEG4TYPE *)params; if (!isValidOMXParam(mpeg4type)) { return OMX_ErrorBadParameter; } if (mpeg4type->nPortIndex != 1) { return OMX_ErrorUndefined; } if (mpeg4type->eProfile != OMX_VIDEO_MPEG4ProfileCore || mpeg4type->eLevel != OMX_VIDEO_MPEG4Level2 || (mpeg4type->nAllowedPictureTypes & OMX_VIDEO_PictureTypeB) || mpeg4type->nBFrames != 0 || mpeg4type->nIDCVLCThreshold != 0 || mpeg4type->bACPred != OMX_TRUE || mpeg4type->nMaxPacketSize != 256 || mpeg4type->nTimeIncRes != 1000 || mpeg4type->nHeaderExtension != 0 || mpeg4type->bReversibleVLC != OMX_FALSE) { return OMX_ErrorUndefined; } return OMX_ErrorNone; } default: return SoftVideoEncoderOMXComponent::internalSetParameter(index, params); } }
174,210
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int venc_dev::venc_input_log_buffers(OMX_BUFFERHEADERTYPE *pbuffer, int fd, int plane_offset) { if (!m_debug.infile) { int size = snprintf(m_debug.infile_name, PROPERTY_VALUE_MAX, "%s/input_enc_%lu_%lu_%p.yuv", m_debug.log_loc, m_sVenc_cfg.input_width, m_sVenc_cfg.input_height, this); if ((size > PROPERTY_VALUE_MAX) && (size < 0)) { DEBUG_PRINT_ERROR("Failed to open output file: %s for logging size:%d", m_debug.infile_name, size); } m_debug.infile = fopen (m_debug.infile_name, "ab"); if (!m_debug.infile) { DEBUG_PRINT_HIGH("Failed to open input file: %s for logging", m_debug.infile_name); m_debug.infile_name[0] = '\0'; return -1; } } if (m_debug.infile && pbuffer && pbuffer->nFilledLen) { unsigned long i, msize; int stride = VENUS_Y_STRIDE(COLOR_FMT_NV12, m_sVenc_cfg.input_width); int scanlines = VENUS_Y_SCANLINES(COLOR_FMT_NV12, m_sVenc_cfg.input_height); unsigned char *pvirt,*ptemp; char *temp = (char *)pbuffer->pBuffer; msize = VENUS_BUFFER_SIZE(COLOR_FMT_NV12, m_sVenc_cfg.input_width, m_sVenc_cfg.input_height); if (metadatamode == 1) { pvirt= (unsigned char *)mmap(NULL, msize, PROT_READ|PROT_WRITE,MAP_SHARED, fd, plane_offset); if (pvirt) { ptemp = pvirt; for (i = 0; i < m_sVenc_cfg.input_height; i++) { fwrite(ptemp, m_sVenc_cfg.input_width, 1, m_debug.infile); ptemp += stride; } ptemp = pvirt + (stride * scanlines); for(i = 0; i < m_sVenc_cfg.input_height/2; i++) { fwrite(ptemp, m_sVenc_cfg.input_width, 1, m_debug.infile); ptemp += stride; } munmap(pvirt, msize); } else if (pvirt == MAP_FAILED) { DEBUG_PRINT_ERROR("%s mmap failed", __func__); return -1; } } else { for (i = 0; i < m_sVenc_cfg.input_height; i++) { fwrite(temp, m_sVenc_cfg.input_width, 1, m_debug.infile); temp += stride; } temp = (char *)pbuffer->pBuffer + (stride * scanlines); for(i = 0; i < m_sVenc_cfg.input_height/2; i++) { fwrite(temp, m_sVenc_cfg.input_width, 1, m_debug.infile); temp += stride; } } } return 0; } Commit Message: DO NOT MERGE mm-video-v4l2: venc: add checks before accessing heap pointers Heap pointers do not point to user virtual addresses in case of secure session. Set them to NULL and add checks to avoid accesing them Bug: 28815329 Bug: 28920116 Change-Id: I94fd5808e753b58654d65e175d3857ef46ffba26 CWE ID: CWE-200
int venc_dev::venc_input_log_buffers(OMX_BUFFERHEADERTYPE *pbuffer, int fd, int plane_offset) { if (venc_handle->is_secure_session()) { DEBUG_PRINT_ERROR("logging secure input buffers is not allowed!"); return -1; } if (!m_debug.infile) { int size = snprintf(m_debug.infile_name, PROPERTY_VALUE_MAX, "%s/input_enc_%lu_%lu_%p.yuv", m_debug.log_loc, m_sVenc_cfg.input_width, m_sVenc_cfg.input_height, this); if ((size > PROPERTY_VALUE_MAX) && (size < 0)) { DEBUG_PRINT_ERROR("Failed to open output file: %s for logging size:%d", m_debug.infile_name, size); } m_debug.infile = fopen (m_debug.infile_name, "ab"); if (!m_debug.infile) { DEBUG_PRINT_HIGH("Failed to open input file: %s for logging", m_debug.infile_name); m_debug.infile_name[0] = '\0'; return -1; } } if (m_debug.infile && pbuffer && pbuffer->nFilledLen) { unsigned long i, msize; int stride = VENUS_Y_STRIDE(COLOR_FMT_NV12, m_sVenc_cfg.input_width); int scanlines = VENUS_Y_SCANLINES(COLOR_FMT_NV12, m_sVenc_cfg.input_height); unsigned char *pvirt,*ptemp; char *temp = (char *)pbuffer->pBuffer; msize = VENUS_BUFFER_SIZE(COLOR_FMT_NV12, m_sVenc_cfg.input_width, m_sVenc_cfg.input_height); if (metadatamode == 1) { pvirt= (unsigned char *)mmap(NULL, msize, PROT_READ|PROT_WRITE,MAP_SHARED, fd, plane_offset); if (pvirt) { ptemp = pvirt; for (i = 0; i < m_sVenc_cfg.input_height; i++) { fwrite(ptemp, m_sVenc_cfg.input_width, 1, m_debug.infile); ptemp += stride; } ptemp = pvirt + (stride * scanlines); for(i = 0; i < m_sVenc_cfg.input_height/2; i++) { fwrite(ptemp, m_sVenc_cfg.input_width, 1, m_debug.infile); ptemp += stride; } munmap(pvirt, msize); } else if (pvirt == MAP_FAILED) { DEBUG_PRINT_ERROR("%s mmap failed", __func__); return -1; } } else { for (i = 0; i < m_sVenc_cfg.input_height; i++) { fwrite(temp, m_sVenc_cfg.input_width, 1, m_debug.infile); temp += stride; } temp = (char *)pbuffer->pBuffer + (stride * scanlines); for(i = 0; i < m_sVenc_cfg.input_height/2; i++) { fwrite(temp, m_sVenc_cfg.input_width, 1, m_debug.infile); temp += stride; } } } return 0; }
173,506
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static inline int mk_vhost_fdt_close(struct session_request *sr) { int id; unsigned int hash; struct vhost_fdt_hash_table *ht = NULL; struct vhost_fdt_hash_chain *hc; if (config->fdt == MK_FALSE) { return close(sr->fd_file); } id = sr->vhost_fdt_id; hash = sr->vhost_fdt_hash; ht = mk_vhost_fdt_table_lookup(id, sr->host_conf); if (mk_unlikely(!ht)) { return close(sr->fd_file); } /* We got the hash table, now look around the chains array */ hc = mk_vhost_fdt_chain_lookup(hash, ht); if (hc) { /* Increment the readers and check if we should close */ hc->readers--; if (hc->readers == 0) { hc->fd = -1; hc->hash = 0; ht->av_slots++; return close(sr->fd_file); } else { return 0; } } return close(sr->fd_file); } Commit Message: Request: new request session flag to mark those files opened by FDT This patch aims to fix a potential DDoS problem that can be caused in the server quering repetitive non-existent resources. When serving a static file, the core use Vhost FDT mechanism, but if it sends a static error page it does a direct open(2). When closing the resources for the same request it was just calling mk_vhost_close() which did not clear properly the file descriptor. This patch adds a new field on the struct session_request called 'fd_is_fdt', which contains MK_TRUE or MK_FALSE depending of how fd_file was opened. Thanks to Matthew Daley <[email protected]> for report and troubleshoot this problem. Signed-off-by: Eduardo Silva <[email protected]> CWE ID: CWE-20
static inline int mk_vhost_fdt_close(struct session_request *sr) { int id; unsigned int hash; struct vhost_fdt_hash_table *ht = NULL; struct vhost_fdt_hash_chain *hc; if (config->fdt == MK_FALSE) { return close(sr->fd_file); } id = sr->vhost_fdt_id; hash = sr->vhost_fdt_hash; ht = mk_vhost_fdt_table_lookup(id, sr->host_conf); if (mk_unlikely(!ht)) { return close(sr->fd_file); } /* We got the hash table, now look around the chains array */ hc = mk_vhost_fdt_chain_lookup(hash, ht); if (hc) { /* Increment the readers and check if we should close */ hc->readers--; if (hc->readers == 0) { hc->fd = -1; hc->hash = 0; ht->av_slots++; return close(sr->fd_file); } else { return 0; } } return close(sr->fd_file); }
166,278
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static NTSTATUS do_connect(TALLOC_CTX *ctx, const char *server, const char *share, const struct user_auth_info *auth_info, bool show_sessetup, bool force_encrypt, int max_protocol, int port, int name_type, struct cli_state **pcli) { struct cli_state *c = NULL; char *servicename; char *sharename; char *newserver, *newshare; const char *username; const char *password; const char *domain; NTSTATUS status; int flags = 0; /* make a copy so we don't modify the global string 'service' */ servicename = talloc_strdup(ctx,share); sharename += 2; if (server == NULL) { server = sharename; } sharename = strchr_m(sharename,'\\'); if (!sharename) { return NT_STATUS_NO_MEMORY; } *sharename = 0; sharename++; } Commit Message: CWE ID: CWE-20
static NTSTATUS do_connect(TALLOC_CTX *ctx, const char *server, const char *share, const struct user_auth_info *auth_info, bool show_sessetup, bool force_encrypt, int max_protocol, int port, int name_type, struct cli_state **pcli) { struct cli_state *c = NULL; char *servicename; char *sharename; char *newserver, *newshare; const char *username; const char *password; const char *domain; NTSTATUS status; int flags = 0; int signing_state = get_cmdline_auth_info_signing_state(auth_info); if (force_encrypt) { signing_state = SMB_SIGNING_REQUIRED; } /* make a copy so we don't modify the global string 'service' */ servicename = talloc_strdup(ctx,share); sharename += 2; if (server == NULL) { server = sharename; } sharename = strchr_m(sharename,'\\'); if (!sharename) { return NT_STATUS_NO_MEMORY; } *sharename = 0; sharename++; }
164,676
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: StorageHandler::IndexedDBObserver* StorageHandler::GetIndexedDBObserver() { DCHECK_CURRENTLY_ON(BrowserThread::UI); if (!indexed_db_observer_) { indexed_db_observer_ = std::make_unique<IndexedDBObserver>( weak_ptr_factory_.GetWeakPtr(), static_cast<IndexedDBContextImpl*>( process_->GetStoragePartition()->GetIndexedDBContext())); } return indexed_db_observer_.get(); } Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable This keeps BrowserContext* and StoragePartition* instead of RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost upon closure of DevTools front-end. Bug: 801117, 783067, 780694 Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b Reviewed-on: https://chromium-review.googlesource.com/876657 Commit-Queue: Andrey Kosyakov <[email protected]> Reviewed-by: Dmitry Gozman <[email protected]> Cr-Commit-Position: refs/heads/master@{#531157} CWE ID: CWE-20
StorageHandler::IndexedDBObserver* StorageHandler::GetIndexedDBObserver() { DCHECK_CURRENTLY_ON(BrowserThread::UI); if (!indexed_db_observer_) { indexed_db_observer_ = std::make_unique<IndexedDBObserver>( weak_ptr_factory_.GetWeakPtr(), static_cast<IndexedDBContextImpl*>( storage_partition_->GetIndexedDBContext())); } return indexed_db_observer_.get(); }
172,772
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static v8::Handle<v8::Value> vertexAttribAndUniformHelperf(const v8::Arguments& args, FunctionToCall functionToCall) { if (args.Length() != 2) return V8Proxy::throwNotEnoughArgumentsError(); bool ok = false; int index = -1; WebGLUniformLocation* location = 0; if (isFunctionToCallForAttribute(functionToCall)) index = toInt32(args[0]); else { if (args.Length() > 0 && !isUndefinedOrNull(args[0]) && !V8WebGLUniformLocation::HasInstance(args[0])) { V8Proxy::throwTypeError(); return notHandledByInterceptor(); } location = toWebGLUniformLocation(args[0], ok); } WebGLRenderingContext* context = V8WebGLRenderingContext::toNative(args.Holder()); if (V8Float32Array::HasInstance(args[1])) { Float32Array* array = V8Float32Array::toNative(args[1]->ToObject()); ASSERT(array != NULL); ExceptionCode ec = 0; switch (functionToCall) { case kUniform1v: context->uniform1fv(location, array, ec); break; case kUniform2v: context->uniform2fv(location, array, ec); break; case kUniform3v: context->uniform3fv(location, array, ec); break; case kUniform4v: context->uniform4fv(location, array, ec); break; case kVertexAttrib1v: context->vertexAttrib1fv(index, array); break; case kVertexAttrib2v: context->vertexAttrib2fv(index, array); break; case kVertexAttrib3v: context->vertexAttrib3fv(index, array); break; case kVertexAttrib4v: context->vertexAttrib4fv(index, array); break; default: ASSERT_NOT_REACHED(); break; } if (ec) V8Proxy::setDOMException(ec, args.GetIsolate()); return v8::Undefined(); } if (args[1].IsEmpty() || !args[1]->IsArray()) { V8Proxy::throwTypeError(); return notHandledByInterceptor(); } v8::Handle<v8::Array> array = v8::Local<v8::Array>::Cast(args[1]); uint32_t len = array->Length(); float* data = jsArrayToFloatArray(array, len); if (!data) { V8Proxy::setDOMException(SYNTAX_ERR, args.GetIsolate()); return notHandledByInterceptor(); } ExceptionCode ec = 0; switch (functionToCall) { case kUniform1v: context->uniform1fv(location, data, len, ec); break; case kUniform2v: context->uniform2fv(location, data, len, ec); break; case kUniform3v: context->uniform3fv(location, data, len, ec); break; case kUniform4v: context->uniform4fv(location, data, len, ec); break; case kVertexAttrib1v: context->vertexAttrib1fv(index, data, len); break; case kVertexAttrib2v: context->vertexAttrib2fv(index, data, len); break; case kVertexAttrib3v: context->vertexAttrib3fv(index, data, len); break; case kVertexAttrib4v: context->vertexAttrib4fv(index, data, len); break; default: ASSERT_NOT_REACHED(); break; } fastFree(data); if (ec) V8Proxy::setDOMException(ec, args.GetIsolate()); return v8::Undefined(); } Commit Message: [V8] Pass Isolate to throwNotEnoughArgumentsError() https://bugs.webkit.org/show_bug.cgi?id=86983 Reviewed by Adam Barth. The objective is to pass Isolate around in V8 bindings. This patch passes Isolate to throwNotEnoughArgumentsError(). No tests. No change in behavior. * bindings/scripts/CodeGeneratorV8.pm: (GenerateArgumentsCountCheck): (GenerateEventConstructorCallback): * bindings/scripts/test/V8/V8Float64Array.cpp: (WebCore::Float64ArrayV8Internal::fooCallback): * bindings/scripts/test/V8/V8TestActiveDOMObject.cpp: (WebCore::TestActiveDOMObjectV8Internal::excitingFunctionCallback): (WebCore::TestActiveDOMObjectV8Internal::postMessageCallback): * bindings/scripts/test/V8/V8TestCustomNamedGetter.cpp: (WebCore::TestCustomNamedGetterV8Internal::anotherFunctionCallback): * bindings/scripts/test/V8/V8TestEventConstructor.cpp: (WebCore::V8TestEventConstructor::constructorCallback): * bindings/scripts/test/V8/V8TestEventTarget.cpp: (WebCore::TestEventTargetV8Internal::itemCallback): (WebCore::TestEventTargetV8Internal::dispatchEventCallback): * bindings/scripts/test/V8/V8TestInterface.cpp: (WebCore::TestInterfaceV8Internal::supplementalMethod2Callback): (WebCore::V8TestInterface::constructorCallback): * bindings/scripts/test/V8/V8TestMediaQueryListListener.cpp: (WebCore::TestMediaQueryListListenerV8Internal::methodCallback): * bindings/scripts/test/V8/V8TestNamedConstructor.cpp: (WebCore::V8TestNamedConstructorConstructorCallback): * bindings/scripts/test/V8/V8TestObj.cpp: (WebCore::TestObjV8Internal::voidMethodWithArgsCallback): (WebCore::TestObjV8Internal::intMethodWithArgsCallback): (WebCore::TestObjV8Internal::objMethodWithArgsCallback): (WebCore::TestObjV8Internal::methodWithSequenceArgCallback): (WebCore::TestObjV8Internal::methodReturningSequenceCallback): (WebCore::TestObjV8Internal::methodThatRequiresAllArgsAndThrowsCallback): (WebCore::TestObjV8Internal::serializedValueCallback): (WebCore::TestObjV8Internal::idbKeyCallback): (WebCore::TestObjV8Internal::optionsObjectCallback): (WebCore::TestObjV8Internal::methodWithNonOptionalArgAndOptionalArgCallback): (WebCore::TestObjV8Internal::methodWithNonOptionalArgAndTwoOptionalArgsCallback): (WebCore::TestObjV8Internal::methodWithCallbackArgCallback): (WebCore::TestObjV8Internal::methodWithNonCallbackArgAndCallbackArgCallback): (WebCore::TestObjV8Internal::overloadedMethod1Callback): (WebCore::TestObjV8Internal::overloadedMethod2Callback): (WebCore::TestObjV8Internal::overloadedMethod3Callback): (WebCore::TestObjV8Internal::overloadedMethod4Callback): (WebCore::TestObjV8Internal::overloadedMethod5Callback): (WebCore::TestObjV8Internal::overloadedMethod6Callback): (WebCore::TestObjV8Internal::overloadedMethod7Callback): (WebCore::TestObjV8Internal::overloadedMethod11Callback): (WebCore::TestObjV8Internal::overloadedMethod12Callback): (WebCore::TestObjV8Internal::enabledAtRuntimeMethod1Callback): (WebCore::TestObjV8Internal::enabledAtRuntimeMethod2Callback): (WebCore::TestObjV8Internal::convert1Callback): (WebCore::TestObjV8Internal::convert2Callback): (WebCore::TestObjV8Internal::convert3Callback): (WebCore::TestObjV8Internal::convert4Callback): (WebCore::TestObjV8Internal::convert5Callback): (WebCore::TestObjV8Internal::strictFunctionCallback): (WebCore::V8TestObj::constructorCallback): * bindings/scripts/test/V8/V8TestSerializedScriptValueInterface.cpp: (WebCore::TestSerializedScriptValueInterfaceV8Internal::acceptTransferListCallback): (WebCore::V8TestSerializedScriptValueInterface::constructorCallback): * bindings/v8/ScriptController.cpp: (WebCore::setValueAndClosePopupCallback): * bindings/v8/V8Proxy.cpp: (WebCore::V8Proxy::throwNotEnoughArgumentsError): * bindings/v8/V8Proxy.h: (V8Proxy): * bindings/v8/custom/V8AudioContextCustom.cpp: (WebCore::V8AudioContext::constructorCallback): * bindings/v8/custom/V8DataViewCustom.cpp: (WebCore::V8DataView::getInt8Callback): (WebCore::V8DataView::getUint8Callback): (WebCore::V8DataView::setInt8Callback): (WebCore::V8DataView::setUint8Callback): * bindings/v8/custom/V8DirectoryEntryCustom.cpp: (WebCore::V8DirectoryEntry::getDirectoryCallback): (WebCore::V8DirectoryEntry::getFileCallback): * bindings/v8/custom/V8IntentConstructor.cpp: (WebCore::V8Intent::constructorCallback): * bindings/v8/custom/V8SVGLengthCustom.cpp: (WebCore::V8SVGLength::convertToSpecifiedUnitsCallback): * bindings/v8/custom/V8WebGLRenderingContextCustom.cpp: (WebCore::getObjectParameter): (WebCore::V8WebGLRenderingContext::getAttachedShadersCallback): (WebCore::V8WebGLRenderingContext::getExtensionCallback): (WebCore::V8WebGLRenderingContext::getFramebufferAttachmentParameterCallback): (WebCore::V8WebGLRenderingContext::getParameterCallback): (WebCore::V8WebGLRenderingContext::getProgramParameterCallback): (WebCore::V8WebGLRenderingContext::getShaderParameterCallback): (WebCore::V8WebGLRenderingContext::getUniformCallback): (WebCore::vertexAttribAndUniformHelperf): (WebCore::uniformHelperi): (WebCore::uniformMatrixHelper): * bindings/v8/custom/V8WebKitMutationObserverCustom.cpp: (WebCore::V8WebKitMutationObserver::constructorCallback): (WebCore::V8WebKitMutationObserver::observeCallback): * bindings/v8/custom/V8WebSocketCustom.cpp: (WebCore::V8WebSocket::constructorCallback): (WebCore::V8WebSocket::sendCallback): * bindings/v8/custom/V8XMLHttpRequestCustom.cpp: (WebCore::V8XMLHttpRequest::openCallback): git-svn-id: svn://svn.chromium.org/blink/trunk@117736 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID:
static v8::Handle<v8::Value> vertexAttribAndUniformHelperf(const v8::Arguments& args, FunctionToCall functionToCall) { if (args.Length() != 2) return V8Proxy::throwNotEnoughArgumentsError(args.GetIsolate()); bool ok = false; int index = -1; WebGLUniformLocation* location = 0; if (isFunctionToCallForAttribute(functionToCall)) index = toInt32(args[0]); else { if (args.Length() > 0 && !isUndefinedOrNull(args[0]) && !V8WebGLUniformLocation::HasInstance(args[0])) { V8Proxy::throwTypeError(); return notHandledByInterceptor(); } location = toWebGLUniformLocation(args[0], ok); } WebGLRenderingContext* context = V8WebGLRenderingContext::toNative(args.Holder()); if (V8Float32Array::HasInstance(args[1])) { Float32Array* array = V8Float32Array::toNative(args[1]->ToObject()); ASSERT(array != NULL); ExceptionCode ec = 0; switch (functionToCall) { case kUniform1v: context->uniform1fv(location, array, ec); break; case kUniform2v: context->uniform2fv(location, array, ec); break; case kUniform3v: context->uniform3fv(location, array, ec); break; case kUniform4v: context->uniform4fv(location, array, ec); break; case kVertexAttrib1v: context->vertexAttrib1fv(index, array); break; case kVertexAttrib2v: context->vertexAttrib2fv(index, array); break; case kVertexAttrib3v: context->vertexAttrib3fv(index, array); break; case kVertexAttrib4v: context->vertexAttrib4fv(index, array); break; default: ASSERT_NOT_REACHED(); break; } if (ec) V8Proxy::setDOMException(ec, args.GetIsolate()); return v8::Undefined(); } if (args[1].IsEmpty() || !args[1]->IsArray()) { V8Proxy::throwTypeError(); return notHandledByInterceptor(); } v8::Handle<v8::Array> array = v8::Local<v8::Array>::Cast(args[1]); uint32_t len = array->Length(); float* data = jsArrayToFloatArray(array, len); if (!data) { V8Proxy::setDOMException(SYNTAX_ERR, args.GetIsolate()); return notHandledByInterceptor(); } ExceptionCode ec = 0; switch (functionToCall) { case kUniform1v: context->uniform1fv(location, data, len, ec); break; case kUniform2v: context->uniform2fv(location, data, len, ec); break; case kUniform3v: context->uniform3fv(location, data, len, ec); break; case kUniform4v: context->uniform4fv(location, data, len, ec); break; case kVertexAttrib1v: context->vertexAttrib1fv(index, data, len); break; case kVertexAttrib2v: context->vertexAttrib2fv(index, data, len); break; case kVertexAttrib3v: context->vertexAttrib3fv(index, data, len); break; case kVertexAttrib4v: context->vertexAttrib4fv(index, data, len); break; default: ASSERT_NOT_REACHED(); break; } fastFree(data); if (ec) V8Proxy::setDOMException(ec, args.GetIsolate()); return v8::Undefined(); }
171,130
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int ecdsa_sign_restartable( mbedtls_ecp_group *grp, mbedtls_mpi *r, mbedtls_mpi *s, const mbedtls_mpi *d, const unsigned char *buf, size_t blen, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng, mbedtls_ecdsa_restart_ctx *rs_ctx ) { int ret, key_tries, sign_tries; int *p_sign_tries = &sign_tries, *p_key_tries = &key_tries; mbedtls_ecp_point R; mbedtls_mpi k, e, t; mbedtls_mpi *pk = &k, *pr = r; /* Fail cleanly on curves such as Curve25519 that can't be used for ECDSA */ if( grp->N.p == NULL ) return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA ); /* Make sure d is in range 1..n-1 */ if( mbedtls_mpi_cmp_int( d, 1 ) < 0 || mbedtls_mpi_cmp_mpi( d, &grp->N ) >= 0 ) return( MBEDTLS_ERR_ECP_INVALID_KEY ); mbedtls_ecp_point_init( &R ); mbedtls_mpi_init( &k ); mbedtls_mpi_init( &e ); mbedtls_mpi_init( &t ); ECDSA_RS_ENTER( sig ); #if defined(MBEDTLS_ECP_RESTARTABLE) if( rs_ctx != NULL && rs_ctx->sig != NULL ) { /* redirect to our context */ p_sign_tries = &rs_ctx->sig->sign_tries; p_key_tries = &rs_ctx->sig->key_tries; pk = &rs_ctx->sig->k; pr = &rs_ctx->sig->r; /* jump to current step */ if( rs_ctx->sig->state == ecdsa_sig_mul ) goto mul; if( rs_ctx->sig->state == ecdsa_sig_modn ) goto modn; } #endif /* MBEDTLS_ECP_RESTARTABLE */ *p_sign_tries = 0; do { if( *p_sign_tries++ > 10 ) { ret = MBEDTLS_ERR_ECP_RANDOM_FAILED; goto cleanup; } /* * Steps 1-3: generate a suitable ephemeral keypair * and set r = xR mod n */ *p_key_tries = 0; do { if( *p_key_tries++ > 10 ) { ret = MBEDTLS_ERR_ECP_RANDOM_FAILED; goto cleanup; } MBEDTLS_MPI_CHK( mbedtls_ecp_gen_privkey( grp, pk, f_rng, p_rng ) ); #if defined(MBEDTLS_ECP_RESTARTABLE) if( rs_ctx != NULL && rs_ctx->sig != NULL ) rs_ctx->sig->state = ecdsa_sig_mul; mul: #endif MBEDTLS_MPI_CHK( mbedtls_ecp_mul_restartable( grp, &R, pk, &grp->G, f_rng, p_rng, ECDSA_RS_ECP ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( pr, &R.X, &grp->N ) ); } while( mbedtls_mpi_cmp_int( pr, 0 ) == 0 ); #if defined(MBEDTLS_ECP_RESTARTABLE) if( rs_ctx != NULL && rs_ctx->sig != NULL ) rs_ctx->sig->state = ecdsa_sig_modn; modn: #endif /* * Accounting for everything up to the end of the loop * (step 6, but checking now avoids saving e and t) */ ECDSA_BUDGET( MBEDTLS_ECP_OPS_INV + 4 ); /* * Step 5: derive MPI from hashed message */ MBEDTLS_MPI_CHK( derive_mpi( grp, &e, buf, blen ) ); /* * Generate a random value to blind inv_mod in next step, * avoiding a potential timing leak. */ MBEDTLS_MPI_CHK( mbedtls_ecp_gen_privkey( grp, &t, f_rng, p_rng ) ); /* * Step 6: compute s = (e + r * d) / k = t (e + rd) / (kt) mod n */ MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( s, pr, d ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( &e, &e, s ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &e, &e, &t ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( pk, pk, &t ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_inv_mod( s, pk, &grp->N ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( s, s, &e ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( s, s, &grp->N ) ); } while( mbedtls_mpi_cmp_int( s, 0 ) == 0 ); #if defined(MBEDTLS_ECP_RESTARTABLE) if( rs_ctx != NULL && rs_ctx->sig != NULL ) mbedtls_mpi_copy( r, pr ); #endif cleanup: mbedtls_ecp_point_free( &R ); mbedtls_mpi_free( &k ); mbedtls_mpi_free( &e ); mbedtls_mpi_free( &t ); ECDSA_RS_LEAVE( sig ); return( ret ); } Commit Message: Merge remote-tracking branch 'upstream-restricted/pr/556' into mbedtls-2.16-restricted CWE ID: CWE-200
static int ecdsa_sign_restartable( mbedtls_ecp_group *grp, mbedtls_mpi *r, mbedtls_mpi *s, const mbedtls_mpi *d, const unsigned char *buf, size_t blen, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng, int (*f_rng_blind)(void *, unsigned char *, size_t), void *p_rng_blind, mbedtls_ecdsa_restart_ctx *rs_ctx ) { int ret, key_tries, sign_tries; int *p_sign_tries = &sign_tries, *p_key_tries = &key_tries; mbedtls_ecp_point R; mbedtls_mpi k, e, t; mbedtls_mpi *pk = &k, *pr = r; /* Fail cleanly on curves such as Curve25519 that can't be used for ECDSA */ if( grp->N.p == NULL ) return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA ); /* Make sure d is in range 1..n-1 */ if( mbedtls_mpi_cmp_int( d, 1 ) < 0 || mbedtls_mpi_cmp_mpi( d, &grp->N ) >= 0 ) return( MBEDTLS_ERR_ECP_INVALID_KEY ); mbedtls_ecp_point_init( &R ); mbedtls_mpi_init( &k ); mbedtls_mpi_init( &e ); mbedtls_mpi_init( &t ); ECDSA_RS_ENTER( sig ); #if defined(MBEDTLS_ECP_RESTARTABLE) if( rs_ctx != NULL && rs_ctx->sig != NULL ) { /* redirect to our context */ p_sign_tries = &rs_ctx->sig->sign_tries; p_key_tries = &rs_ctx->sig->key_tries; pk = &rs_ctx->sig->k; pr = &rs_ctx->sig->r; /* jump to current step */ if( rs_ctx->sig->state == ecdsa_sig_mul ) goto mul; if( rs_ctx->sig->state == ecdsa_sig_modn ) goto modn; } #endif /* MBEDTLS_ECP_RESTARTABLE */ *p_sign_tries = 0; do { if( *p_sign_tries++ > 10 ) { ret = MBEDTLS_ERR_ECP_RANDOM_FAILED; goto cleanup; } /* * Steps 1-3: generate a suitable ephemeral keypair * and set r = xR mod n */ *p_key_tries = 0; do { if( *p_key_tries++ > 10 ) { ret = MBEDTLS_ERR_ECP_RANDOM_FAILED; goto cleanup; } MBEDTLS_MPI_CHK( mbedtls_ecp_gen_privkey( grp, pk, f_rng, p_rng ) ); #if defined(MBEDTLS_ECP_RESTARTABLE) if( rs_ctx != NULL && rs_ctx->sig != NULL ) rs_ctx->sig->state = ecdsa_sig_mul; mul: #endif MBEDTLS_MPI_CHK( mbedtls_ecp_mul_restartable( grp, &R, pk, &grp->G, f_rng_blind, p_rng_blind, ECDSA_RS_ECP ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( pr, &R.X, &grp->N ) ); } while( mbedtls_mpi_cmp_int( pr, 0 ) == 0 ); #if defined(MBEDTLS_ECP_RESTARTABLE) if( rs_ctx != NULL && rs_ctx->sig != NULL ) rs_ctx->sig->state = ecdsa_sig_modn; modn: #endif /* * Accounting for everything up to the end of the loop * (step 6, but checking now avoids saving e and t) */ ECDSA_BUDGET( MBEDTLS_ECP_OPS_INV + 4 ); /* * Step 5: derive MPI from hashed message */ MBEDTLS_MPI_CHK( derive_mpi( grp, &e, buf, blen ) ); /* * Generate a random value to blind inv_mod in next step, * avoiding a potential timing leak. */ MBEDTLS_MPI_CHK( mbedtls_ecp_gen_privkey( grp, &t, f_rng_blind, p_rng_blind ) ); /* * Step 6: compute s = (e + r * d) / k = t (e + rd) / (kt) mod n */ MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( s, pr, d ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( &e, &e, s ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &e, &e, &t ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( pk, pk, &t ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_inv_mod( s, pk, &grp->N ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( s, s, &e ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( s, s, &grp->N ) ); } while( mbedtls_mpi_cmp_int( s, 0 ) == 0 ); #if defined(MBEDTLS_ECP_RESTARTABLE) if( rs_ctx != NULL && rs_ctx->sig != NULL ) mbedtls_mpi_copy( r, pr ); #endif cleanup: mbedtls_ecp_point_free( &R ); mbedtls_mpi_free( &k ); mbedtls_mpi_free( &e ); mbedtls_mpi_free( &t ); ECDSA_RS_LEAVE( sig ); return( ret ); }
169,506
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void* ipc_rcu_alloc(int size) { void* out; /* * We prepend the allocation with the rcu struct, and * workqueue if necessary (for vmalloc). */ if (rcu_use_vmalloc(size)) { out = vmalloc(HDRLEN_VMALLOC + size); if (out) { out += HDRLEN_VMALLOC; container_of(out, struct ipc_rcu_hdr, data)->is_vmalloc = 1; container_of(out, struct ipc_rcu_hdr, data)->refcount = 1; } } else { out = kmalloc(HDRLEN_KMALLOC + size, GFP_KERNEL); if (out) { out += HDRLEN_KMALLOC; container_of(out, struct ipc_rcu_hdr, data)->is_vmalloc = 0; container_of(out, struct ipc_rcu_hdr, data)->refcount = 1; } } return out; } Commit Message: ipc,sem: fine grained locking for semtimedop Introduce finer grained locking for semtimedop, to handle the common case of a program wanting to manipulate one semaphore from an array with multiple semaphores. If the call is a semop manipulating just one semaphore in an array with multiple semaphores, only take the lock for that semaphore itself. If the call needs to manipulate multiple semaphores, or another caller is in a transaction that manipulates multiple semaphores, the sem_array lock is taken, as well as all the locks for the individual semaphores. On a 24 CPU system, performance numbers with the semop-multi test with N threads and N semaphores, look like this: vanilla Davidlohr's Davidlohr's + Davidlohr's + threads patches rwlock patches v3 patches 10 610652 726325 1783589 2142206 20 341570 365699 1520453 1977878 30 288102 307037 1498167 2037995 40 290714 305955 1612665 2256484 50 288620 312890 1733453 2650292 60 289987 306043 1649360 2388008 70 291298 306347 1723167 2717486 80 290948 305662 1729545 2763582 90 290996 306680 1736021 2757524 100 292243 306700 1773700 3059159 [[email protected]: do not call sem_lock when bogus sma] [[email protected]: make refcounter atomic] Signed-off-by: Rik van Riel <[email protected]> Suggested-by: Linus Torvalds <[email protected]> Acked-by: Davidlohr Bueso <[email protected]> Cc: Chegu Vinod <[email protected]> Cc: Jason Low <[email protected]> Reviewed-by: Michel Lespinasse <[email protected]> Cc: Peter Hurley <[email protected]> Cc: Stanislav Kinsbursky <[email protected]> Tested-by: Emmanuel Benisty <[email protected]> Tested-by: Sedat Dilek <[email protected]> Signed-off-by: Andrew Morton <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-189
void* ipc_rcu_alloc(int size) void *ipc_rcu_alloc(int size) { void *out; /* * We prepend the allocation with the rcu struct, and * workqueue if necessary (for vmalloc). */ if (rcu_use_vmalloc(size)) { out = vmalloc(HDRLEN_VMALLOC + size); if (!out) goto done; out += HDRLEN_VMALLOC; container_of(out, struct ipc_rcu_hdr, data)->is_vmalloc = 1; } else { out = kmalloc(HDRLEN_KMALLOC + size, GFP_KERNEL); if (!out) goto done; out += HDRLEN_KMALLOC; container_of(out, struct ipc_rcu_hdr, data)->is_vmalloc = 0; } /* set reference counter no matter what kind of allocation was done */ atomic_set(&container_of(out, struct ipc_rcu_hdr, data)->refcount, 1); done: return out; }
165,983
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: ExtensionInstallDialogView::ExtensionInstallDialogView( Profile* profile, content::PageNavigator* navigator, const ExtensionInstallPrompt::DoneCallback& done_callback, std::unique_ptr<ExtensionInstallPrompt::Prompt> prompt) : profile_(profile), navigator_(navigator), done_callback_(done_callback), prompt_(std::move(prompt)), container_(NULL), scroll_view_(NULL), handled_result_(false) { InitView(); } Commit Message: [Extensions UI] Initially disabled OK button for extension install prompts and enable them after a 500 ms time period. BUG=394518 Review-Url: https://codereview.chromium.org/2716353003 Cr-Commit-Position: refs/heads/master@{#461933} CWE ID: CWE-20
ExtensionInstallDialogView::ExtensionInstallDialogView( Profile* profile, content::PageNavigator* navigator, const ExtensionInstallPrompt::DoneCallback& done_callback, std::unique_ptr<ExtensionInstallPrompt::Prompt> prompt) : profile_(profile), navigator_(navigator), done_callback_(done_callback), prompt_(std::move(prompt)), container_(NULL), scroll_view_(NULL), handled_result_(false), install_button_enabled_(false) { InitView(); }
173,159
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void MediaElementAudioSourceHandler::Process(size_t number_of_frames) { AudioBus* output_bus = Output(0).Bus(); MutexTryLocker try_locker(process_lock_); if (try_locker.Locked()) { if (!MediaElement() || !source_sample_rate_) { output_bus->Zero(); return; } if (source_number_of_channels_ != output_bus->NumberOfChannels()) { output_bus->Zero(); return; } AudioSourceProvider& provider = MediaElement()->GetAudioSourceProvider(); if (multi_channel_resampler_.get()) { DCHECK_NE(source_sample_rate_, Context()->sampleRate()); multi_channel_resampler_->Process(&provider, output_bus, number_of_frames); } else { DCHECK_EQ(source_sample_rate_, Context()->sampleRate()); provider.ProvideInput(output_bus, number_of_frames); } if (!PassesCORSAccessCheck()) { if (maybe_print_cors_message_) { maybe_print_cors_message_ = false; PostCrossThreadTask( *task_runner_, FROM_HERE, CrossThreadBind(&MediaElementAudioSourceHandler::PrintCORSMessage, WrapRefCounted(this), current_src_string_)); } output_bus->Zero(); } } else { output_bus->Zero(); } } Commit Message: Redirect should not circumvent same-origin restrictions Check whether we have access to the audio data when the format is set. At this point we have enough information to determine this. The old approach based on when the src was changed was incorrect because at the point, we only know the new src; none of the response headers have been read yet. This new approach also removes the incorrect message reported in 619114. Bug: 826552, 619114 Change-Id: I95119b3a1e399c05d0fbd2da71f87967978efff6 Reviewed-on: https://chromium-review.googlesource.com/1069540 Commit-Queue: Raymond Toy <[email protected]> Reviewed-by: Yutaka Hirano <[email protected]> Reviewed-by: Hongchan Choi <[email protected]> Cr-Commit-Position: refs/heads/master@{#564313} CWE ID: CWE-20
void MediaElementAudioSourceHandler::Process(size_t number_of_frames) { AudioBus* output_bus = Output(0).Bus(); MutexTryLocker try_locker(process_lock_); if (try_locker.Locked()) { if (!MediaElement() || !source_sample_rate_) { output_bus->Zero(); return; } if (source_number_of_channels_ != output_bus->NumberOfChannels()) { output_bus->Zero(); return; } AudioSourceProvider& provider = MediaElement()->GetAudioSourceProvider(); if (multi_channel_resampler_.get()) { DCHECK_NE(source_sample_rate_, Context()->sampleRate()); multi_channel_resampler_->Process(&provider, output_bus, number_of_frames); } else { DCHECK_EQ(source_sample_rate_, Context()->sampleRate()); provider.ProvideInput(output_bus, number_of_frames); } if (is_origin_tainted_) { output_bus->Zero(); } } else { output_bus->Zero(); } }
173,149
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: NavigateParams::NavigateParams( Browser* a_browser, const GURL& a_url, content::PageTransition a_transition) : url(a_url), target_contents(NULL), source_contents(NULL), disposition(CURRENT_TAB), transition(a_transition), tabstrip_index(-1), tabstrip_add_types(TabStripModel::ADD_ACTIVE), window_action(NO_ACTION), user_gesture(true), path_behavior(RESPECT), ref_behavior(IGNORE_REF), browser(a_browser), profile(NULL) { } Commit Message: Fix memory error in previous CL. BUG=100315 BUG=99016 TEST=Memory bots go green Review URL: http://codereview.chromium.org/8302001 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@105577 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
NavigateParams::NavigateParams( Browser* a_browser, const GURL& a_url, content::PageTransition a_transition) : url(a_url), target_contents(NULL), source_contents(NULL), disposition(CURRENT_TAB), transition(a_transition), is_renderer_initiated(false), tabstrip_index(-1), tabstrip_add_types(TabStripModel::ADD_ACTIVE), window_action(NO_ACTION), user_gesture(true), path_behavior(RESPECT), ref_behavior(IGNORE_REF), browser(a_browser), profile(NULL) { }
170,249
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: Node::InsertionNotificationRequest SVGStyleElement::InsertedInto( ContainerNode* insertion_point) { SVGElement::InsertedInto(insertion_point); return kInsertionShouldCallDidNotifySubtreeInsertions; } Commit Message: Do not crash while reentrantly appending to style element. When a node is inserted into a container, it is notified via ::InsertedInto. However, a node may request a second notification via DidNotifySubtreeInsertionsToDocument, which occurs after all the children have been notified as well. *StyleElement is currently using this second notification. This causes a problem, because *ScriptElement is using the same mechanism, which in turn means that scripts can execute before the state of *StyleElements are properly updated. This patch avoids ::DidNotifySubtreeInsertionsToDocument, and instead processes the stylesheet in ::InsertedInto. The original reason for using ::DidNotifySubtreeInsertionsToDocument in the first place appears to be invalid now, as the test case is still passing. [email protected], [email protected] Bug: 853709, 847570 Cq-Include-Trybots: luci.chromium.try:linux_layout_tests_slimming_paint_v2;master.tryserver.blink:linux_trusty_blink_rel Change-Id: Ic0b5fa611044c78c5745cf26870a747f88920a14 Reviewed-on: https://chromium-review.googlesource.com/1104347 Commit-Queue: Anders Ruud <[email protected]> Reviewed-by: Rune Lillesveen <[email protected]> Cr-Commit-Position: refs/heads/master@{#568368} CWE ID: CWE-416
Node::InsertionNotificationRequest SVGStyleElement::InsertedInto( ContainerNode* insertion_point) { SVGElement::InsertedInto(insertion_point);
173,174
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: DefragVlanTest(void) { Packet *p1 = NULL, *p2 = NULL, *r = NULL; int ret = 0; DefragInit(); p1 = BuildTestPacket(1, 0, 1, 'A', 8); if (p1 == NULL) goto end; p2 = BuildTestPacket(1, 1, 0, 'B', 8); if (p2 == NULL) goto end; /* With no VLAN IDs set, packets should re-assemble. */ if ((r = Defrag(NULL, NULL, p1, NULL)) != NULL) goto end; if ((r = Defrag(NULL, NULL, p2, NULL)) == NULL) goto end; SCFree(r); /* With mismatched VLANs, packets should not re-assemble. */ p1->vlan_id[0] = 1; p2->vlan_id[0] = 2; if ((r = Defrag(NULL, NULL, p1, NULL)) != NULL) goto end; if ((r = Defrag(NULL, NULL, p2, NULL)) != NULL) goto end; /* Pass. */ ret = 1; end: if (p1 != NULL) SCFree(p1); if (p2 != NULL) SCFree(p2); DefragDestroy(); return ret; } Commit Message: defrag - take protocol into account during re-assembly The IP protocol was not being used to match fragments with their packets allowing a carefully constructed packet with a different protocol to be matched, allowing re-assembly to complete, creating a packet that would not be re-assembled by the destination host. CWE ID: CWE-358
DefragVlanTest(void) { Packet *p1 = NULL, *p2 = NULL, *r = NULL; int ret = 0; DefragInit(); p1 = BuildTestPacket(IPPROTO_ICMP, 1, 0, 1, 'A', 8); if (p1 == NULL) goto end; p2 = BuildTestPacket(IPPROTO_ICMP, 1, 1, 0, 'B', 8); if (p2 == NULL) goto end; /* With no VLAN IDs set, packets should re-assemble. */ if ((r = Defrag(NULL, NULL, p1, NULL)) != NULL) goto end; if ((r = Defrag(NULL, NULL, p2, NULL)) == NULL) goto end; SCFree(r); /* With mismatched VLANs, packets should not re-assemble. */ p1->vlan_id[0] = 1; p2->vlan_id[0] = 2; if ((r = Defrag(NULL, NULL, p1, NULL)) != NULL) goto end; if ((r = Defrag(NULL, NULL, p2, NULL)) != NULL) goto end; /* Pass. */ ret = 1; end: if (p1 != NULL) SCFree(p1); if (p2 != NULL) SCFree(p2); DefragDestroy(); return ret; }
168,306
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void fe_netjoin_init(void) { settings_add_bool("misc", "hide_netsplit_quits", TRUE); settings_add_int("misc", "netjoin_max_nicks", 10); join_tag = -1; printing_joins = FALSE; read_settings(); signal_add("setup changed", (SIGNAL_FUNC) read_settings); } Commit Message: Merge branch 'netjoin-timeout' into 'master' fe-netjoin: remove irc servers on "server disconnected" signal Closes #7 See merge request !10 CWE ID: CWE-416
void fe_netjoin_init(void) { settings_add_bool("misc", "hide_netsplit_quits", TRUE); settings_add_int("misc", "netjoin_max_nicks", 10); join_tag = -1; printing_joins = FALSE; read_settings(); signal_add("setup changed", (SIGNAL_FUNC) read_settings); signal_add("server disconnected", (SIGNAL_FUNC) sig_server_disconnected); }
168,291
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static ssize_t out_write(struct audio_stream_out *stream, const void* buffer, size_t bytes) { struct a2dp_stream_out *out = (struct a2dp_stream_out *)stream; int sent; DEBUG("write %zu bytes (fd %d)", bytes, out->common.audio_fd); pthread_mutex_lock(&out->common.lock); if (out->common.state == AUDIO_A2DP_STATE_SUSPENDED) { DEBUG("stream suspended"); pthread_mutex_unlock(&out->common.lock); return -1; } /* only allow autostarting if we are in stopped or standby */ if ((out->common.state == AUDIO_A2DP_STATE_STOPPED) || (out->common.state == AUDIO_A2DP_STATE_STANDBY)) { if (start_audio_datapath(&out->common) < 0) { /* emulate time this write represents to avoid very fast write failures during transition periods or remote suspend */ int us_delay = calc_audiotime(out->common.cfg, bytes); DEBUG("emulate a2dp write delay (%d us)", us_delay); usleep(us_delay); pthread_mutex_unlock(&out->common.lock); return -1; } } else if (out->common.state != AUDIO_A2DP_STATE_STARTED) { ERROR("stream not in stopped or standby"); pthread_mutex_unlock(&out->common.lock); return -1; } pthread_mutex_unlock(&out->common.lock); sent = skt_write(out->common.audio_fd, buffer, bytes); if (sent == -1) { skt_disconnect(out->common.audio_fd); out->common.audio_fd = AUDIO_SKT_DISCONNECTED; if (out->common.state != AUDIO_A2DP_STATE_SUSPENDED) out->common.state = AUDIO_A2DP_STATE_STOPPED; else ERROR("write failed : stream suspended, avoid resetting state"); } else { const size_t frames = bytes / audio_stream_out_frame_size(stream); out->frames_rendered += frames; out->frames_presented += frames; } DEBUG("wrote %d bytes out of %zu bytes", sent, bytes); return sent; } Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process Bug: 28885210 Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360 Conflicts: btif/co/bta_hh_co.c btif/src/btif_core.c Merge conflict resolution of ag/1161415 (referencing ag/1164670) - Directly into mnc-mr2-release CWE ID: CWE-284
static ssize_t out_write(struct audio_stream_out *stream, const void* buffer, size_t bytes) { struct a2dp_stream_out *out = (struct a2dp_stream_out *)stream; int sent; DEBUG("write %zu bytes (fd %d)", bytes, out->common.audio_fd); pthread_mutex_lock(&out->common.lock); if (out->common.state == AUDIO_A2DP_STATE_SUSPENDED) { DEBUG("stream suspended"); pthread_mutex_unlock(&out->common.lock); return -1; } /* only allow autostarting if we are in stopped or standby */ if ((out->common.state == AUDIO_A2DP_STATE_STOPPED) || (out->common.state == AUDIO_A2DP_STATE_STANDBY)) { if (start_audio_datapath(&out->common) < 0) { /* emulate time this write represents to avoid very fast write failures during transition periods or remote suspend */ int us_delay = calc_audiotime(out->common.cfg, bytes); DEBUG("emulate a2dp write delay (%d us)", us_delay); TEMP_FAILURE_RETRY(usleep(us_delay)); pthread_mutex_unlock(&out->common.lock); return -1; } } else if (out->common.state != AUDIO_A2DP_STATE_STARTED) { ERROR("stream not in stopped or standby"); pthread_mutex_unlock(&out->common.lock); return -1; } pthread_mutex_unlock(&out->common.lock); sent = skt_write(out->common.audio_fd, buffer, bytes); if (sent == -1) { skt_disconnect(out->common.audio_fd); out->common.audio_fd = AUDIO_SKT_DISCONNECTED; if (out->common.state != AUDIO_A2DP_STATE_SUSPENDED) out->common.state = AUDIO_A2DP_STATE_STOPPED; else ERROR("write failed : stream suspended, avoid resetting state"); } else { const size_t frames = bytes / audio_stream_out_frame_size(stream); out->frames_rendered += frames; out->frames_presented += frames; } DEBUG("wrote %d bytes out of %zu bytes", sent, bytes); return sent; }
173,427
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int vol_prc_lib_release(effect_handle_t handle) { struct listnode *node, *temp_node_next; vol_listener_context_t *context = NULL; vol_listener_context_t *recv_contex = (vol_listener_context_t *)handle; int status = -1; bool recompute_flag = false; int active_stream_count = 0; ALOGV("%s context %p", __func__, handle); pthread_mutex_lock(&vol_listner_init_lock); list_for_each_safe(node, temp_node_next, &vol_effect_list) { context = node_to_item(node, struct vol_listener_context_s, effect_list_node); if ((memcmp(&(context->desc->uuid), &(recv_contex->desc->uuid), sizeof(effect_uuid_t)) == 0) && (context->session_id == recv_contex->session_id) && (context->stream_type == recv_contex->stream_type)) { ALOGV("--- Found something to remove ---"); list_remove(&context->effect_list_node); PRINT_STREAM_TYPE(context->stream_type); if (context->dev_id && AUDIO_DEVICE_OUT_SPEAKER) { recompute_flag = true; } free(context); status = 0; } else { ++active_stream_count; } } if (status != 0) { ALOGE("something wrong ... <<<--- Found NOTHING to remove ... ???? --->>>>>"); } if (active_stream_count == 0) { current_gain_dep_cal_level = -1; current_vol = 0.0; } if (recompute_flag) { check_and_set_gain_dep_cal(); } if (dumping_enabled) { dump_list_l(); } pthread_mutex_unlock(&vol_listner_init_lock); return status; } Commit Message: post proc : volume listener : fix effect release crash Fix access to deleted effect context in vol_prc_lib_release() Bug: 25753245. Change-Id: I64ca99e4d5d09667be4c8c605f66700b9ae67949 (cherry picked from commit 93ab6fdda7b7557ccb34372670c30fa6178f8426) CWE ID: CWE-119
static int vol_prc_lib_release(effect_handle_t handle) { struct listnode *node, *temp_node_next; vol_listener_context_t *context = NULL; vol_listener_context_t *recv_contex = (vol_listener_context_t *)handle; int status = -EINVAL; bool recompute_flag = false; int active_stream_count = 0; uint32_t session_id; uint32_t stream_type; effect_uuid_t uuid; ALOGV("%s context %p", __func__, handle); if (recv_contex == NULL) { return status; } pthread_mutex_lock(&vol_listner_init_lock); session_id = recv_contex->session_id; stream_type = recv_contex->stream_type; uuid = recv_contex->desc->uuid; list_for_each_safe(node, temp_node_next, &vol_effect_list) { context = node_to_item(node, struct vol_listener_context_s, effect_list_node); if ((memcmp(&(context->desc->uuid), &uuid, sizeof(effect_uuid_t)) == 0) && (context->session_id == session_id) && (context->stream_type == stream_type)) { ALOGV("--- Found something to remove ---"); list_remove(node); PRINT_STREAM_TYPE(context->stream_type); if (context->dev_id && AUDIO_DEVICE_OUT_SPEAKER) { recompute_flag = true; } free(context); status = 0; } else { ++active_stream_count; } } if (status != 0) { ALOGE("something wrong ... <<<--- Found NOTHING to remove ... ???? --->>>>>"); pthread_mutex_unlock(&vol_listner_init_lock); return status; } if (active_stream_count == 0) { current_gain_dep_cal_level = -1; current_vol = 0.0; } if (recompute_flag) { check_and_set_gain_dep_cal(); } if (dumping_enabled) { dump_list_l(); } pthread_mutex_unlock(&vol_listner_init_lock); return status; }
173,916
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed 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. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: smb_fdata(netdissect_options *ndo, const u_char *buf, const char *fmt, const u_char *maxbuf, int unicodestr) { static int depth = 0; char s[128]; char *p; while (*fmt) { switch (*fmt) { case '*': fmt++; while (buf < maxbuf) { const u_char *buf2; depth++; buf2 = smb_fdata(ndo, buf, fmt, maxbuf, unicodestr); depth--; if (buf2 == NULL) return(NULL); if (buf2 == buf) return(buf); buf = buf2; } return(buf); case '|': fmt++; if (buf >= maxbuf) return(buf); break; case '%': fmt++; buf = maxbuf; break; case '#': fmt++; return(buf); break; case '[': fmt++; if (buf >= maxbuf) return(buf); memset(s, 0, sizeof(s)); p = strchr(fmt, ']'); if ((size_t)(p - fmt + 1) > sizeof(s)) { /* overrun */ return(buf); } strncpy(s, fmt, p - fmt); s[p - fmt] = '\0'; fmt = p + 1; buf = smb_fdata1(ndo, buf, s, maxbuf, unicodestr); if (buf == NULL) return(NULL); break; default: ND_PRINT((ndo, "%c", *fmt)); fmt++; break; } } if (!depth && buf < maxbuf) { size_t len = PTR_DIFF(maxbuf, buf); ND_PRINT((ndo, "Data: (%lu bytes)\n", (unsigned long)len)); smb_print_data(ndo, buf, len); return(buf + len); } return(buf); } Commit Message: (for 4.9.3) CVE-2018-16452/SMB: prevent stack exhaustion Enforce a limit on how many times smb_fdata() can recurse. This fixes a stack exhaustion discovered by Include Security working under the Mozilla SOS program in 2018 by means of code audit. CWE ID: CWE-674
smb_fdata(netdissect_options *ndo, const u_char *buf, const char *fmt, const u_char *maxbuf, int unicodestr) { static int depth = 0; char s[128]; char *p; while (*fmt) { switch (*fmt) { case '*': fmt++; while (buf < maxbuf) { const u_char *buf2; depth++; /* Not sure how this relates with the protocol specification, * but in order to avoid stack exhaustion recurse at most that * many levels. */ if (depth == 10) ND_PRINT((ndo, "(too many nested levels, not recursing)")); else buf2 = smb_fdata(ndo, buf, fmt, maxbuf, unicodestr); depth--; if (buf2 == NULL) return(NULL); if (buf2 == buf) return(buf); buf = buf2; } return(buf); case '|': fmt++; if (buf >= maxbuf) return(buf); break; case '%': fmt++; buf = maxbuf; break; case '#': fmt++; return(buf); break; case '[': fmt++; if (buf >= maxbuf) return(buf); memset(s, 0, sizeof(s)); p = strchr(fmt, ']'); if ((size_t)(p - fmt + 1) > sizeof(s)) { /* overrun */ return(buf); } strncpy(s, fmt, p - fmt); s[p - fmt] = '\0'; fmt = p + 1; buf = smb_fdata1(ndo, buf, s, maxbuf, unicodestr); if (buf == NULL) return(NULL); break; default: ND_PRINT((ndo, "%c", *fmt)); fmt++; break; } } if (!depth && buf < maxbuf) { size_t len = PTR_DIFF(maxbuf, buf); ND_PRINT((ndo, "Data: (%lu bytes)\n", (unsigned long)len)); smb_print_data(ndo, buf, len); return(buf + len); } return(buf); }
169,814
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static char *print_value( cJSON *item, int depth, int fmt ) { char *out = 0; if ( ! item ) return 0; switch ( ( item->type ) & 255 ) { case cJSON_NULL: out = cJSON_strdup( "null" ); break; case cJSON_False: out = cJSON_strdup( "false" ); break; case cJSON_True: out = cJSON_strdup( "true" ); break; case cJSON_Number: out = print_number( item ); break; case cJSON_String: out = print_string( item ); break; case cJSON_Array: out = print_array( item, depth, fmt ); break; case cJSON_Object: out = print_object( item, depth, fmt ); break; } return out; } Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a malformed JSON string was passed on the control channel. This issue, present in the cJSON library, was already fixed upstream, so was addressed here in iperf3 by importing a newer version of cJSON (plus local ESnet modifications). Discovered and reported by Dave McDaniel, Cisco Talos. Based on a patch by @dopheide-esnet, with input from @DaveGamble. Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001, CVE-2016-4303 (cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40) Signed-off-by: Bruce A. Mah <[email protected]> CWE ID: CWE-119
static char *print_value( cJSON *item, int depth, int fmt ) static char *print_value(cJSON *item,int depth,int fmt,printbuffer *p) { char *out=0; if (!item) return 0; if (p) { switch ((item->type)&255) { case cJSON_NULL: {out=ensure(p,5); if (out) strcpy(out,"null"); break;} case cJSON_False: {out=ensure(p,6); if (out) strcpy(out,"false"); break;} case cJSON_True: {out=ensure(p,5); if (out) strcpy(out,"true"); break;} case cJSON_Number: out=print_number(item,p);break; case cJSON_String: out=print_string(item,p);break; case cJSON_Array: out=print_array(item,depth,fmt,p);break; case cJSON_Object: out=print_object(item,depth,fmt,p);break; } } else { switch ((item->type)&255) { case cJSON_NULL: out=cJSON_strdup("null"); break; case cJSON_False: out=cJSON_strdup("false");break; case cJSON_True: out=cJSON_strdup("true"); break; case cJSON_Number: out=print_number(item,0);break; case cJSON_String: out=print_string(item,0);break; case cJSON_Array: out=print_array(item,depth,fmt,0);break; case cJSON_Object: out=print_object(item,depth,fmt,0);break; } } return out; }
167,311
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: long long Cluster::GetLastTime() const { const BlockEntry* pEntry; const long status = GetLast(pEntry); if (status < 0) //error return status; if (pEntry == NULL) //empty cluster return GetTime(); const Block* const pBlock = pEntry->GetBlock(); assert(pBlock); return pBlock->GetTime(this); } 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::GetLastTime() const
174,341
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: NavigateParams::NavigateParams(Browser* a_browser, TabContentsWrapper* a_target_contents) : target_contents(a_target_contents), source_contents(NULL), disposition(CURRENT_TAB), transition(content::PAGE_TRANSITION_LINK), tabstrip_index(-1), tabstrip_add_types(TabStripModel::ADD_ACTIVE), window_action(NO_ACTION), user_gesture(true), path_behavior(RESPECT), ref_behavior(IGNORE_REF), browser(a_browser), profile(NULL) { } Commit Message: Fix memory error in previous CL. BUG=100315 BUG=99016 TEST=Memory bots go green Review URL: http://codereview.chromium.org/8302001 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@105577 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
NavigateParams::NavigateParams(Browser* a_browser, TabContentsWrapper* a_target_contents) : target_contents(a_target_contents), source_contents(NULL), disposition(CURRENT_TAB), transition(content::PAGE_TRANSITION_LINK), is_renderer_initiated(false), tabstrip_index(-1), tabstrip_add_types(TabStripModel::ADD_ACTIVE), window_action(NO_ACTION), user_gesture(true), path_behavior(RESPECT), ref_behavior(IGNORE_REF), browser(a_browser), profile(NULL) { }
170,250
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void Cues::Init() const { if (m_cue_points) return; assert(m_count == 0); assert(m_preload_count == 0); IMkvReader* const pReader = m_pSegment->m_pReader; const long long stop = m_start + m_size; long long pos = m_start; long cue_points_size = 0; while (pos < stop) { const long long idpos = pos; long len; const long long id = ReadUInt(pReader, pos, len); assert(id >= 0); // TODO assert((pos + len) <= stop); pos += len; // consume ID const long long size = ReadUInt(pReader, pos, len); assert(size >= 0); assert((pos + len) <= stop); pos += len; // consume Size field assert((pos + size) <= stop); if (id == 0x3B) // CuePoint ID PreloadCuePoint(cue_points_size, idpos); pos += size; // consume payload assert(pos <= stop); } } Commit Message: external/libvpx/libwebm: Update snapshot Update libwebm snapshot. This update contains security fixes from upstream. Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b BUG=23167726 Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207 (cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a) CWE ID: CWE-20
void Cues::Init() const { bool Cues::Init() const { if (m_cue_points) return true; if (m_count != 0 || m_preload_count != 0) return false; IMkvReader* const pReader = m_pSegment->m_pReader; const long long stop = m_start + m_size; long long pos = m_start; long cue_points_size = 0; while (pos < stop) { const long long idpos = pos; long len; const long long id = ReadID(pReader, pos, len); if (id < 0 || (pos + len) > stop) { return false; } pos += len; // consume ID const long long size = ReadUInt(pReader, pos, len); if (size < 0 || (pos + len > stop)) { return false; } pos += len; // consume Size field if (pos + size > stop) { return false; } if (id == 0x3B) { // CuePoint ID if (!PreloadCuePoint(cue_points_size, idpos)) return false; } pos += size; // skip payload } return true; }
173,827
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: BOOL pnm2png (FILE *pnm_file, FILE *png_file, FILE *alpha_file, BOOL interlace, BOOL alpha) { png_struct *png_ptr = NULL; png_info *info_ptr = NULL; png_byte *png_pixels = NULL; png_byte **row_pointers = NULL; png_byte *pix_ptr = NULL; png_uint_32 row_bytes; char type_token[16]; char width_token[16]; char height_token[16]; char maxval_token[16]; int color_type; unsigned long ul_width=0, ul_alpha_width=0; unsigned long ul_height=0, ul_alpha_height=0; unsigned long ul_maxval=0; png_uint_32 width, alpha_width; png_uint_32 height, alpha_height; png_uint_32 maxval; int bit_depth = 0; int channels; int alpha_depth = 0; int alpha_present; int row, col; BOOL raw, alpha_raw = FALSE; #if defined(PNG_WRITE_INVERT_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED) BOOL packed_bitmap = FALSE; #endif png_uint_32 tmp16; int i; /* read header of PNM file */ get_token(pnm_file, type_token); if (type_token[0] != 'P') { return FALSE; } else if ((type_token[1] == '1') || (type_token[1] == '4')) { #if defined(PNG_WRITE_INVERT_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED) raw = (type_token[1] == '4'); color_type = PNG_COLOR_TYPE_GRAY; get_token(pnm_file, width_token); sscanf (width_token, "%lu", &ul_width); width = (png_uint_32) ul_width; get_token(pnm_file, height_token); sscanf (height_token, "%lu", &ul_height); height = (png_uint_32) ul_height; bit_depth = 1; packed_bitmap = TRUE; #else fprintf (stderr, "PNM2PNG built without PNG_WRITE_INVERT_SUPPORTED and \n"); fprintf (stderr, "PNG_WRITE_PACK_SUPPORTED can't read PBM (P1,P4) files\n"); #endif } else if ((type_token[1] == '2') || (type_token[1] == '5')) { raw = (type_token[1] == '5'); color_type = PNG_COLOR_TYPE_GRAY; get_token(pnm_file, width_token); sscanf (width_token, "%lu", &ul_width); width = (png_uint_32) ul_width; get_token(pnm_file, height_token); sscanf (height_token, "%lu", &ul_height); height = (png_uint_32) ul_height; get_token(pnm_file, maxval_token); sscanf (maxval_token, "%lu", &ul_maxval); maxval = (png_uint_32) ul_maxval; if (maxval <= 1) bit_depth = 1; else if (maxval <= 3) bit_depth = 2; else if (maxval <= 15) bit_depth = 4; else if (maxval <= 255) bit_depth = 8; else /* if (maxval <= 65535) */ bit_depth = 16; } else if ((type_token[1] == '3') || (type_token[1] == '6')) { raw = (type_token[1] == '6'); color_type = PNG_COLOR_TYPE_RGB; get_token(pnm_file, width_token); sscanf (width_token, "%lu", &ul_width); width = (png_uint_32) ul_width; get_token(pnm_file, height_token); sscanf (height_token, "%lu", &ul_height); height = (png_uint_32) ul_height; get_token(pnm_file, maxval_token); sscanf (maxval_token, "%lu", &ul_maxval); maxval = (png_uint_32) ul_maxval; if (maxval <= 1) bit_depth = 1; else if (maxval <= 3) bit_depth = 2; else if (maxval <= 15) bit_depth = 4; else if (maxval <= 255) bit_depth = 8; else /* if (maxval <= 65535) */ bit_depth = 16; } else { return FALSE; } /* read header of PGM file with alpha channel */ if (alpha) { if (color_type == PNG_COLOR_TYPE_GRAY) color_type = PNG_COLOR_TYPE_GRAY_ALPHA; if (color_type == PNG_COLOR_TYPE_RGB) color_type = PNG_COLOR_TYPE_RGB_ALPHA; get_token(alpha_file, type_token); if (type_token[0] != 'P') { return FALSE; } else if ((type_token[1] == '2') || (type_token[1] == '5')) { alpha_raw = (type_token[1] == '5'); get_token(alpha_file, width_token); sscanf (width_token, "%lu", &ul_alpha_width); alpha_width=(png_uint_32) ul_alpha_width; if (alpha_width != width) return FALSE; get_token(alpha_file, height_token); sscanf (height_token, "%lu", &ul_alpha_height); alpha_height = (png_uint_32) ul_alpha_height; if (alpha_height != height) return FALSE; get_token(alpha_file, maxval_token); sscanf (maxval_token, "%lu", &ul_maxval); maxval = (png_uint_32) ul_maxval; if (maxval <= 1) alpha_depth = 1; else if (maxval <= 3) alpha_depth = 2; else if (maxval <= 15) alpha_depth = 4; else if (maxval <= 255) alpha_depth = 8; else /* if (maxval <= 65535) */ alpha_depth = 16; if (alpha_depth != bit_depth) return FALSE; } else { return FALSE; } } /* end if alpha */ /* calculate the number of channels and store alpha-presence */ if (color_type == PNG_COLOR_TYPE_GRAY) channels = 1; else if (color_type == PNG_COLOR_TYPE_GRAY_ALPHA) channels = 2; else if (color_type == PNG_COLOR_TYPE_RGB) channels = 3; else if (color_type == PNG_COLOR_TYPE_RGB_ALPHA) channels = 4; else channels = 0; /* should not happen */ alpha_present = (channels - 1) % 2; #if defined(PNG_WRITE_INVERT_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED) if (packed_bitmap) /* row data is as many bytes as can fit width x channels x bit_depth */ row_bytes = (width * channels * bit_depth + 7) / 8; else #endif /* row_bytes is the width x number of channels x (bit-depth / 8) */ row_bytes = width * channels * ((bit_depth <= 8) ? 1 : 2); if ((png_pixels = (png_byte *) malloc (row_bytes * height * sizeof (png_byte))) == NULL) return FALSE; /* read data from PNM file */ pix_ptr = png_pixels; for (row = 0; row < height; row++) { #if defined(PNG_WRITE_INVERT_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED) if (packed_bitmap) { for (i = 0; i < row_bytes; i++) /* png supports this format natively so no conversion is needed */ *pix_ptr++ = get_data (pnm_file, 8); } else #endif { for (col = 0; col < width; col++) { for (i = 0; i < (channels - alpha_present); i++) { if (raw) *pix_ptr++ = get_data (pnm_file, bit_depth); else if (bit_depth <= 8) *pix_ptr++ = get_value (pnm_file, bit_depth); else { tmp16 = get_value (pnm_file, bit_depth); *pix_ptr = (png_byte) ((tmp16 >> 8) & 0xFF); pix_ptr++; *pix_ptr = (png_byte) (tmp16 & 0xFF); pix_ptr++; } } if (alpha) /* read alpha-channel from pgm file */ { if (alpha_raw) *pix_ptr++ = get_data (alpha_file, alpha_depth); else if (alpha_depth <= 8) *pix_ptr++ = get_value (alpha_file, bit_depth); else { tmp16 = get_value (alpha_file, bit_depth); *pix_ptr++ = (png_byte) ((tmp16 >> 8) & 0xFF); *pix_ptr++ = (png_byte) (tmp16 & 0xFF); } } /* if alpha */ } /* if packed_bitmap */ } /* end for col */ } /* end for row */ /* prepare the standard PNG structures */ png_ptr = png_create_write_struct (PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); if (!png_ptr) { return FALSE; } info_ptr = png_create_info_struct (png_ptr); if (!info_ptr) { png_destroy_write_struct (&png_ptr, (png_infopp) NULL); return FALSE; } #if defined(PNG_WRITE_INVERT_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED) if (packed_bitmap == TRUE) { png_set_packing (png_ptr); png_set_invert_mono (png_ptr); } #endif /* setjmp() must be called in every function that calls a PNG-reading libpng function */ if (setjmp (png_jmpbuf(png_ptr))) { png_destroy_write_struct (&png_ptr, (png_infopp) NULL); return FALSE; } /* initialize the png structure */ png_init_io (png_ptr, png_file); /* we're going to write more or less the same PNG as the input file */ png_set_IHDR (png_ptr, info_ptr, width, height, bit_depth, color_type, (!interlace) ? PNG_INTERLACE_NONE : PNG_INTERLACE_ADAM7, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE); /* write the file header information */ png_write_info (png_ptr, info_ptr); /* if needed we will allocate memory for an new array of row-pointers */ if (row_pointers == (unsigned char**) NULL) { if ((row_pointers = (png_byte **) malloc (height * sizeof (png_bytep))) == NULL) { png_destroy_write_struct (&png_ptr, (png_infopp) NULL); return FALSE; } } /* set the individual row_pointers to point at the correct offsets */ for (i = 0; i < (height); i++) row_pointers[i] = png_pixels + i * row_bytes; /* write out the entire image data in one call */ png_write_image (png_ptr, row_pointers); /* write the additional chuncks to the PNG file (not really needed) */ png_write_end (png_ptr, info_ptr); /* clean up after the write, and free any memory allocated */ png_destroy_write_struct (&png_ptr, (png_infopp) NULL); if (row_pointers != (unsigned char**) NULL) free (row_pointers); if (png_pixels != (unsigned char*) NULL) free (png_pixels); return TRUE; } /* end of pnm2png */ Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
BOOL pnm2png (FILE *pnm_file, FILE *png_file, FILE *alpha_file, BOOL interlace, BOOL alpha) BOOL pnm2png (FILE *pnm_file, FILE *png_file, FILE *alpha_file, BOOL interlace, BOOL alpha) { png_struct *png_ptr = NULL; png_info *info_ptr = NULL; png_byte *png_pixels = NULL; png_byte **row_pointers = NULL; png_byte *pix_ptr = NULL; volatile png_uint_32 row_bytes; char type_token[16]; char width_token[16]; char height_token[16]; char maxval_token[16]; volatile int color_type=1; unsigned long ul_width=0, ul_alpha_width=0; unsigned long ul_height=0, ul_alpha_height=0; unsigned long ul_maxval=0; volatile png_uint_32 width=0, height=0; volatile png_uint_32 alpha_width=0, alpha_height=0; png_uint_32 maxval; volatile int bit_depth = 0; int channels=0; int alpha_depth = 0; int alpha_present=0; int row, col; BOOL raw, alpha_raw = FALSE; #if defined(PNG_WRITE_INVERT_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED) BOOL packed_bitmap = FALSE; #endif png_uint_32 tmp16; int i; /* read header of PNM file */ get_token(pnm_file, type_token); if (type_token[0] != 'P') { return FALSE; } else if ((type_token[1] == '1') || (type_token[1] == '4')) { #if defined(PNG_WRITE_INVERT_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED) raw = (type_token[1] == '4'); color_type = PNG_COLOR_TYPE_GRAY; get_token(pnm_file, width_token); sscanf (width_token, "%lu", &ul_width); width = (png_uint_32) ul_width; get_token(pnm_file, height_token); sscanf (height_token, "%lu", &ul_height); height = (png_uint_32) ul_height; bit_depth = 1; packed_bitmap = TRUE; #else fprintf (stderr, "PNM2PNG built without PNG_WRITE_INVERT_SUPPORTED and \n"); fprintf (stderr, "PNG_WRITE_PACK_SUPPORTED can't read PBM (P1,P4) files\n"); #endif } else if ((type_token[1] == '2') || (type_token[1] == '5')) { raw = (type_token[1] == '5'); color_type = PNG_COLOR_TYPE_GRAY; get_token(pnm_file, width_token); sscanf (width_token, "%lu", &ul_width); width = (png_uint_32) ul_width; get_token(pnm_file, height_token); sscanf (height_token, "%lu", &ul_height); height = (png_uint_32) ul_height; get_token(pnm_file, maxval_token); sscanf (maxval_token, "%lu", &ul_maxval); maxval = (png_uint_32) ul_maxval; if (maxval <= 1) bit_depth = 1; else if (maxval <= 3) bit_depth = 2; else if (maxval <= 15) bit_depth = 4; else if (maxval <= 255) bit_depth = 8; else /* if (maxval <= 65535) */ bit_depth = 16; } else if ((type_token[1] == '3') || (type_token[1] == '6')) { raw = (type_token[1] == '6'); color_type = PNG_COLOR_TYPE_RGB; get_token(pnm_file, width_token); sscanf (width_token, "%lu", &ul_width); width = (png_uint_32) ul_width; get_token(pnm_file, height_token); sscanf (height_token, "%lu", &ul_height); height = (png_uint_32) ul_height; get_token(pnm_file, maxval_token); sscanf (maxval_token, "%lu", &ul_maxval); maxval = (png_uint_32) ul_maxval; if (maxval <= 1) bit_depth = 1; else if (maxval <= 3) bit_depth = 2; else if (maxval <= 15) bit_depth = 4; else if (maxval <= 255) bit_depth = 8; else /* if (maxval <= 65535) */ bit_depth = 16; } else { return FALSE; } /* read header of PGM file with alpha channel */ if (alpha) { if (color_type == PNG_COLOR_TYPE_GRAY) color_type = PNG_COLOR_TYPE_GRAY_ALPHA; if (color_type == PNG_COLOR_TYPE_RGB) color_type = PNG_COLOR_TYPE_RGB_ALPHA; get_token(alpha_file, type_token); if (type_token[0] != 'P') { return FALSE; } else if ((type_token[1] == '2') || (type_token[1] == '5')) { alpha_raw = (type_token[1] == '5'); get_token(alpha_file, width_token); sscanf (width_token, "%lu", &ul_alpha_width); alpha_width=(png_uint_32) ul_alpha_width; if (alpha_width != width) return FALSE; get_token(alpha_file, height_token); sscanf (height_token, "%lu", &ul_alpha_height); alpha_height = (png_uint_32) ul_alpha_height; if (alpha_height != height) return FALSE; get_token(alpha_file, maxval_token); sscanf (maxval_token, "%lu", &ul_maxval); maxval = (png_uint_32) ul_maxval; if (maxval <= 1) alpha_depth = 1; else if (maxval <= 3) alpha_depth = 2; else if (maxval <= 15) alpha_depth = 4; else if (maxval <= 255) alpha_depth = 8; else /* if (maxval <= 65535) */ alpha_depth = 16; if (alpha_depth != bit_depth) return FALSE; } else { return FALSE; } } /* end if alpha */ /* calculate the number of channels and store alpha-presence */ if (color_type == PNG_COLOR_TYPE_GRAY) channels = 1; else if (color_type == PNG_COLOR_TYPE_GRAY_ALPHA) channels = 2; else if (color_type == PNG_COLOR_TYPE_RGB) channels = 3; else if (color_type == PNG_COLOR_TYPE_RGB_ALPHA) channels = 4; #if 0 else channels = 0; /* cannot happen */ #endif alpha_present = (channels - 1) % 2; #if defined(PNG_WRITE_INVERT_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED) if (packed_bitmap) /* row data is as many bytes as can fit width x channels x bit_depth */ row_bytes = (width * channels * bit_depth + 7) / 8; else #endif /* row_bytes is the width x number of channels x (bit-depth / 8) */ row_bytes = width * channels * ((bit_depth <= 8) ? 1 : 2); if ((png_pixels = (png_byte *) malloc (row_bytes * height * sizeof (png_byte))) == NULL) return FALSE; /* read data from PNM file */ pix_ptr = png_pixels; for (row = 0; row < (int) height; row++) { #if defined(PNG_WRITE_INVERT_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED) if (packed_bitmap) { for (i = 0; i < (int) row_bytes; i++) /* png supports this format natively so no conversion is needed */ *pix_ptr++ = get_data (pnm_file, 8); } else #endif { for (col = 0; col < (int) width; col++) { for (i = 0; i < (channels - alpha_present); i++) { if (raw) *pix_ptr++ = get_data (pnm_file, bit_depth); else if (bit_depth <= 8) *pix_ptr++ = get_value (pnm_file, bit_depth); else { tmp16 = get_value (pnm_file, bit_depth); *pix_ptr = (png_byte) ((tmp16 >> 8) & 0xFF); pix_ptr++; *pix_ptr = (png_byte) (tmp16 & 0xFF); pix_ptr++; } } if (alpha) /* read alpha-channel from pgm file */ { if (alpha_raw) *pix_ptr++ = get_data (alpha_file, alpha_depth); else if (alpha_depth <= 8) *pix_ptr++ = get_value (alpha_file, bit_depth); else { tmp16 = get_value (alpha_file, bit_depth); *pix_ptr++ = (png_byte) ((tmp16 >> 8) & 0xFF); *pix_ptr++ = (png_byte) (tmp16 & 0xFF); } } /* if alpha */ } /* if packed_bitmap */ } /* end for col */ } /* end for row */ /* prepare the standard PNG structures */ png_ptr = png_create_write_struct (png_get_libpng_ver(NULL), NULL, NULL, NULL); if (!png_ptr) { free (png_pixels); png_pixels = NULL; return FALSE; } info_ptr = png_create_info_struct (png_ptr); if (!info_ptr) { png_destroy_write_struct (&png_ptr, (png_infopp) NULL); free (png_pixels); png_pixels = NULL; return FALSE; } #if defined(PNG_WRITE_INVERT_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED) if (packed_bitmap == TRUE) { png_set_packing (png_ptr); png_set_invert_mono (png_ptr); } #endif /* setjmp() must be called in every function that calls a PNG-reading libpng function */ if (setjmp (png_jmpbuf(png_ptr))) { png_destroy_write_struct (&png_ptr, &info_ptr); free (png_pixels); png_pixels = NULL; return FALSE; } /* initialize the png structure */ png_init_io (png_ptr, png_file); /* we're going to write more or less the same PNG as the input file */ png_set_IHDR (png_ptr, info_ptr, width, height, bit_depth, color_type, (!interlace) ? PNG_INTERLACE_NONE : PNG_INTERLACE_ADAM7, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE); /* write the file header information */ png_write_info (png_ptr, info_ptr); /* if needed we will allocate memory for an new array of row-pointers */ if (row_pointers == (unsigned char**) NULL) { if ((row_pointers = (png_byte **) malloc (height * sizeof (png_bytep))) == NULL) { png_destroy_write_struct (&png_ptr, &info_ptr); free (png_pixels); png_pixels = NULL; return FALSE; } } /* set the individual row_pointers to point at the correct offsets */ for (i = 0; i < (int) height; i++) row_pointers[i] = png_pixels + i * row_bytes; /* write out the entire image data in one call */ png_write_image (png_ptr, row_pointers); /* write the additional chunks to the PNG file (not really needed) */ png_write_end (png_ptr, info_ptr); /* clean up after the write, and free any memory allocated */ png_destroy_write_struct (&png_ptr, &info_ptr); if (row_pointers != (unsigned char**) NULL) free (row_pointers); if (png_pixels != (unsigned char*) NULL) free (png_pixels); return TRUE; } /* end of pnm2png */
173,725
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void Compositor::OnFirstSurfaceActivation( const viz::SurfaceInfo& surface_info) { } Commit Message: Don't report OnFirstSurfaceActivation for ui::Compositor Bug: 893850 Change-Id: Iee754cefbd083d0a21a2b672fb8e837eaab81c43 Reviewed-on: https://chromium-review.googlesource.com/c/1293712 Reviewed-by: Antoine Labour <[email protected]> Commit-Queue: Saman Sami <[email protected]> Cr-Commit-Position: refs/heads/master@{#601629} CWE ID: CWE-20
void Compositor::OnFirstSurfaceActivation( const viz::SurfaceInfo& surface_info) { NOTREACHED(); }
172,563
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: gsicc_open_search(const char* pname, int namelen, gs_memory_t *mem_gc, const char* dirname, int dirlen, stream**strp) { char *buffer; stream* str; /* Check if we need to prepend the file name */ if ( dirname != NULL) { /* If this fails, we will still try the file by itself and with %rom% since someone may have left a space some of the spaces as our defaults, even if they defined the directory to use. This will occur only after searching the defined directory. A warning is noted. */ buffer = (char *) gs_alloc_bytes(mem_gc, namelen + dirlen + 1, "gsicc_open_search"); if (buffer == NULL) return_error(gs_error_VMerror); strcpy(buffer, dirname); strcat(buffer, pname); /* Just to make sure we were null terminated */ buffer[namelen + dirlen] = '\0'; str = sfopen(buffer, "r", mem_gc); gs_free_object(mem_gc, buffer, "gsicc_open_search"); if (str != NULL) { *strp = str; return 0; } } /* First just try it like it is */ str = sfopen(pname, "r", mem_gc); if (str != NULL) { *strp = str; return 0; } /* If that fails, try %rom% */ /* FIXME: Not sure this is needed or correct */ strlen(DEFAULT_DIR_ICC),"gsicc_open_search"); if (buffer == NULL) return_error(gs_error_VMerror); strcpy(buffer, DEFAULT_DIR_ICC); strcat(buffer, pname); /* Just to make sure we were null terminated */ buffer[namelen + strlen(DEFAULT_DIR_ICC)] = '\0'; str = sfopen(buffer, "r", mem_gc); gs_free_object(mem_gc, buffer, "gsicc_open_search"); if (str == NULL) { gs_warn1("Could not find %s ",pname); } *strp = str; return 0; } Commit Message: CWE ID: CWE-20
gsicc_open_search(const char* pname, int namelen, gs_memory_t *mem_gc, const char* dirname, int dirlen, stream**strp) { char *buffer; stream* str; /* Check if we need to prepend the file name */ if ( dirname != NULL) { /* If this fails, we will still try the file by itself and with %rom% since someone may have left a space some of the spaces as our defaults, even if they defined the directory to use. This will occur only after searching the defined directory. A warning is noted. */ buffer = (char *) gs_alloc_bytes(mem_gc, namelen + dirlen + 1, "gsicc_open_search"); if (buffer == NULL) return_error(gs_error_VMerror); strcpy(buffer, dirname); strcat(buffer, pname); /* Just to make sure we were null terminated */ buffer[namelen + dirlen] = '\0'; str = sfopen(buffer, "r", mem_gc); gs_free_object(mem_gc, buffer, "gsicc_open_search"); if (str != NULL) { *strp = str; return 0; } } /* First just try it like it is */ if (gs_check_file_permission(mem_gc, pname, namelen, "r") >= 0) { str = sfopen(pname, "r", mem_gc); if (str != NULL) { *strp = str; return 0; } } /* If that fails, try %rom% */ /* FIXME: Not sure this is needed or correct */ strlen(DEFAULT_DIR_ICC),"gsicc_open_search"); if (buffer == NULL) return_error(gs_error_VMerror); strcpy(buffer, DEFAULT_DIR_ICC); strcat(buffer, pname); /* Just to make sure we were null terminated */ buffer[namelen + strlen(DEFAULT_DIR_ICC)] = '\0'; str = sfopen(buffer, "r", mem_gc); gs_free_object(mem_gc, buffer, "gsicc_open_search"); if (str == NULL) { gs_warn1("Could not find %s ",pname); } *strp = str; return 0; }
165,265
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static Image *ReadPCXImage(const ImageInfo *image_info,ExceptionInfo *exception) { #define ThrowPCXException(severity,tag) \ { \ scanline=(unsigned char *) RelinquishMagickMemory(scanline); \ pixel_info=RelinquishVirtualMemory(pixel_info); \ ThrowReaderException(severity,tag); \ } Image *image; int bits, id, mask; MagickBooleanType status; MagickOffsetType offset, *page_table; MemoryInfo *pixel_info; PCXInfo pcx_info; register IndexPacket *indexes; register ssize_t x; register PixelPacket *q; register ssize_t i; register unsigned char *p, *r; size_t one, pcx_packets; ssize_t count, y; unsigned char packet, pcx_colormap[768], *pixels, *scanline; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Determine if this a PCX file. */ page_table=(MagickOffsetType *) NULL; if (LocaleCompare(image_info->magick,"DCX") == 0) { size_t magic; /* Read the DCX page table. */ magic=ReadBlobLSBLong(image); if (magic != 987654321) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); page_table=(MagickOffsetType *) AcquireQuantumMemory(1024UL, sizeof(*page_table)); if (page_table == (MagickOffsetType *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); for (id=0; id < 1024; id++) { page_table[id]=(MagickOffsetType) ReadBlobLSBLong(image); if (page_table[id] == 0) break; } } if (page_table != (MagickOffsetType *) NULL) { offset=SeekBlob(image,(MagickOffsetType) page_table[0],SEEK_SET); if (offset < 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } count=ReadBlob(image,1,&pcx_info.identifier); for (id=1; id < 1024; id++) { int bits_per_pixel; /* Verify PCX identifier. */ pcx_info.version=(unsigned char) ReadBlobByte(image); if ((count == 0) || (pcx_info.identifier != 0x0a)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); pcx_info.encoding=(unsigned char) ReadBlobByte(image); bits_per_pixel=ReadBlobByte(image); if (bits_per_pixel == -1) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); pcx_info.bits_per_pixel=(unsigned char) bits_per_pixel; pcx_info.left=ReadBlobLSBShort(image); pcx_info.top=ReadBlobLSBShort(image); pcx_info.right=ReadBlobLSBShort(image); pcx_info.bottom=ReadBlobLSBShort(image); pcx_info.horizontal_resolution=ReadBlobLSBShort(image); pcx_info.vertical_resolution=ReadBlobLSBShort(image); /* Read PCX raster colormap. */ image->columns=(size_t) MagickAbsoluteValue((ssize_t) pcx_info.right- pcx_info.left)+1UL; image->rows=(size_t) MagickAbsoluteValue((ssize_t) pcx_info.bottom- pcx_info.top)+1UL; if ((image->columns == 0) || (image->rows == 0) || (pcx_info.bits_per_pixel == 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); image->depth=pcx_info.bits_per_pixel <= 8 ? 8U : MAGICKCORE_QUANTUM_DEPTH; image->units=PixelsPerInchResolution; image->x_resolution=(double) pcx_info.horizontal_resolution; image->y_resolution=(double) pcx_info.vertical_resolution; image->colors=16; count=ReadBlob(image,3*image->colors,pcx_colormap); pcx_info.reserved=(unsigned char) ReadBlobByte(image); pcx_info.planes=(unsigned char) ReadBlobByte(image); if ((pcx_info.bits_per_pixel*pcx_info.planes) >= 64) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); one=1; if ((pcx_info.bits_per_pixel != 8) || (pcx_info.planes == 1)) if ((pcx_info.version == 3) || (pcx_info.version == 5) || ((pcx_info.bits_per_pixel*pcx_info.planes) == 1)) image->colors=(size_t) MagickMin(one << (1UL* (pcx_info.bits_per_pixel*pcx_info.planes)),256UL); if (AcquireImageColormap(image,image->colors) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); if ((pcx_info.bits_per_pixel >= 8) && (pcx_info.planes != 1)) image->storage_class=DirectClass; p=pcx_colormap; for (i=0; i < (ssize_t) image->colors; i++) { image->colormap[i].red=ScaleCharToQuantum(*p++); image->colormap[i].green=ScaleCharToQuantum(*p++); image->colormap[i].blue=ScaleCharToQuantum(*p++); } pcx_info.bytes_per_line=ReadBlobLSBShort(image); pcx_info.palette_info=ReadBlobLSBShort(image); for (i=0; i < 58; i++) (void) ReadBlobByte(image); if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; /* Read image data. */ pcx_packets=(size_t) image->rows*pcx_info.bytes_per_line*pcx_info.planes; if ((size_t) (pcx_info.bits_per_pixel*pcx_info.planes*image->columns) > (pcx_packets*8U)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); scanline=(unsigned char *) AcquireQuantumMemory(MagickMax(image->columns, pcx_info.bytes_per_line),MagickMax(8,pcx_info.planes)*sizeof(*scanline)); pixel_info=AcquireVirtualMemory(pcx_packets,2*sizeof(*pixels)); if ((scanline == (unsigned char *) NULL) || (pixel_info == (MemoryInfo *) NULL)) { if (scanline != (unsigned char *) NULL) scanline=(unsigned char *) RelinquishMagickMemory(scanline); if (pixel_info != (MemoryInfo *) NULL) pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); /* Uncompress image data. */ p=pixels; if (pcx_info.encoding == 0) while (pcx_packets != 0) { packet=(unsigned char) ReadBlobByte(image); if (EOFBlob(image) != MagickFalse) ThrowPCXException(CorruptImageError,"UnexpectedEndOfFile"); *p++=packet; pcx_packets--; } else while (pcx_packets != 0) { packet=(unsigned char) ReadBlobByte(image); if (EOFBlob(image) != MagickFalse) ThrowPCXException(CorruptImageError,"UnexpectedEndOfFile"); if ((packet & 0xc0) != 0xc0) { *p++=packet; pcx_packets--; continue; } count=(ssize_t) (packet & 0x3f); packet=(unsigned char) ReadBlobByte(image); if (EOFBlob(image) != MagickFalse) ThrowPCXException(CorruptImageError,"UnexpectedEndOfFile"); for ( ; count != 0; count--) { *p++=packet; pcx_packets--; if (pcx_packets == 0) break; } } if (image->storage_class == DirectClass) image->matte=pcx_info.planes > 3 ? MagickTrue : MagickFalse; else if ((pcx_info.version == 5) || ((pcx_info.bits_per_pixel*pcx_info.planes) == 1)) { /* Initialize image colormap. */ if (image->colors > 256) ThrowPCXException(CorruptImageError,"ColormapExceeds256Colors"); if ((pcx_info.bits_per_pixel*pcx_info.planes) == 1) { /* Monochrome colormap. */ image->colormap[0].red=(Quantum) 0; image->colormap[0].green=(Quantum) 0; image->colormap[0].blue=(Quantum) 0; image->colormap[1].red=QuantumRange; image->colormap[1].green=QuantumRange; image->colormap[1].blue=QuantumRange; } else if (image->colors > 16) { /* 256 color images have their color map at the end of the file. */ pcx_info.colormap_signature=(unsigned char) ReadBlobByte(image); count=ReadBlob(image,3*image->colors,pcx_colormap); p=pcx_colormap; for (i=0; i < (ssize_t) image->colors; i++) { image->colormap[i].red=ScaleCharToQuantum(*p++); image->colormap[i].green=ScaleCharToQuantum(*p++); image->colormap[i].blue=ScaleCharToQuantum(*p++); } } } /* Convert PCX raster image to pixel packets. */ for (y=0; y < (ssize_t) image->rows; y++) { p=pixels+(y*pcx_info.bytes_per_line*pcx_info.planes); q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); r=scanline; if (image->storage_class == DirectClass) for (i=0; i < pcx_info.planes; i++) { r=scanline+i; for (x=0; x < (ssize_t) pcx_info.bytes_per_line; x++) { switch (i) { case 0: { *r=(*p++); break; } case 1: { *r=(*p++); break; } case 2: { *r=(*p++); break; } case 3: default: { *r=(*p++); break; } } r+=pcx_info.planes; } } else if (pcx_info.planes > 1) { for (x=0; x < (ssize_t) image->columns; x++) *r++=0; for (i=0; i < pcx_info.planes; i++) { r=scanline; for (x=0; x < (ssize_t) pcx_info.bytes_per_line; x++) { bits=(*p++); for (mask=0x80; mask != 0; mask>>=1) { if (bits & mask) *r|=1 << i; r++; } } } } else switch (pcx_info.bits_per_pixel) { case 1: { register ssize_t bit; for (x=0; x < ((ssize_t) image->columns-7); x+=8) { for (bit=7; bit >= 0; bit--) *r++=(unsigned char) ((*p) & (0x01 << bit) ? 0x01 : 0x00); p++; } if ((image->columns % 8) != 0) { for (bit=7; bit >= (ssize_t) (8-(image->columns % 8)); bit--) *r++=(unsigned char) ((*p) & (0x01 << bit) ? 0x01 : 0x00); p++; } break; } case 2: { for (x=0; x < ((ssize_t) image->columns-3); x+=4) { *r++=(*p >> 6) & 0x3; *r++=(*p >> 4) & 0x3; *r++=(*p >> 2) & 0x3; *r++=(*p) & 0x3; p++; } if ((image->columns % 4) != 0) { for (i=3; i >= (ssize_t) (4-(image->columns % 4)); i--) *r++=(unsigned char) ((*p >> (i*2)) & 0x03); p++; } break; } case 4: { for (x=0; x < ((ssize_t) image->columns-1); x+=2) { *r++=(*p >> 4) & 0xf; *r++=(*p) & 0xf; p++; } if ((image->columns % 2) != 0) *r++=(*p++ >> 4) & 0xf; break; } case 8: { (void) CopyMagickMemory(r,p,image->columns); break; } default: break; } /* Transfer image scanline. */ r=scanline; for (x=0; x < (ssize_t) image->columns; x++) { if (image->storage_class == PseudoClass) SetPixelIndex(indexes+x,*r++) else { SetPixelRed(q,ScaleCharToQuantum(*r++)); SetPixelGreen(q,ScaleCharToQuantum(*r++)); SetPixelBlue(q,ScaleCharToQuantum(*r++)); if (image->matte != MagickFalse) SetPixelAlpha(q,ScaleCharToQuantum(*r++)); } q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } if (image->storage_class == PseudoClass) (void) SyncImage(image); scanline=(unsigned char *) RelinquishMagickMemory(scanline); pixel_info=RelinquishVirtualMemory(pixel_info); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; if (page_table == (MagickOffsetType *) NULL) break; if (page_table[id] == 0) break; offset=SeekBlob(image,(MagickOffsetType) page_table[id],SEEK_SET); if (offset < 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); count=ReadBlob(image,1,&pcx_info.identifier); if ((count != 0) && (pcx_info.identifier == 0x0a)) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } if (page_table != (MagickOffsetType *) NULL) page_table=(MagickOffsetType *) RelinquishMagickMemory(page_table); (void) CloseBlob(image); return(GetFirstImageInList(image)); } Commit Message: CWE ID: CWE-119
static Image *ReadPCXImage(const ImageInfo *image_info,ExceptionInfo *exception) { #define ThrowPCXException(severity,tag) \ { \ scanline=(unsigned char *) RelinquishMagickMemory(scanline); \ pixel_info=RelinquishVirtualMemory(pixel_info); \ ThrowReaderException(severity,tag); \ } Image *image; int bits, id, mask; MagickBooleanType status; MagickOffsetType offset, *page_table; MemoryInfo *pixel_info; PCXInfo pcx_info; register IndexPacket *indexes; register ssize_t x; register PixelPacket *q; register ssize_t i; register unsigned char *p, *r; size_t one, pcx_packets; ssize_t count, y; unsigned char packet, pcx_colormap[768], *pixels, *scanline; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Determine if this a PCX file. */ page_table=(MagickOffsetType *) NULL; if (LocaleCompare(image_info->magick,"DCX") == 0) { size_t magic; /* Read the DCX page table. */ magic=ReadBlobLSBLong(image); if (magic != 987654321) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); page_table=(MagickOffsetType *) AcquireQuantumMemory(1024UL, sizeof(*page_table)); if (page_table == (MagickOffsetType *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); for (id=0; id < 1024; id++) { page_table[id]=(MagickOffsetType) ReadBlobLSBLong(image); if (page_table[id] == 0) break; } } if (page_table != (MagickOffsetType *) NULL) { offset=SeekBlob(image,(MagickOffsetType) page_table[0],SEEK_SET); if (offset < 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } count=ReadBlob(image,1,&pcx_info.identifier); for (id=1; id < 1024; id++) { int bits_per_pixel; /* Verify PCX identifier. */ pcx_info.version=(unsigned char) ReadBlobByte(image); if ((count == 0) || (pcx_info.identifier != 0x0a)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); pcx_info.encoding=(unsigned char) ReadBlobByte(image); bits_per_pixel=ReadBlobByte(image); if (bits_per_pixel == -1) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); pcx_info.bits_per_pixel=(unsigned char) bits_per_pixel; pcx_info.left=ReadBlobLSBShort(image); pcx_info.top=ReadBlobLSBShort(image); pcx_info.right=ReadBlobLSBShort(image); pcx_info.bottom=ReadBlobLSBShort(image); pcx_info.horizontal_resolution=ReadBlobLSBShort(image); pcx_info.vertical_resolution=ReadBlobLSBShort(image); /* Read PCX raster colormap. */ image->columns=(size_t) MagickAbsoluteValue((ssize_t) pcx_info.right- pcx_info.left)+1UL; image->rows=(size_t) MagickAbsoluteValue((ssize_t) pcx_info.bottom- pcx_info.top)+1UL; if ((image->columns == 0) || (image->rows == 0) || (pcx_info.bits_per_pixel == 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); image->depth=pcx_info.bits_per_pixel <= 8 ? 8U : MAGICKCORE_QUANTUM_DEPTH; image->units=PixelsPerInchResolution; image->x_resolution=(double) pcx_info.horizontal_resolution; image->y_resolution=(double) pcx_info.vertical_resolution; image->colors=16; count=ReadBlob(image,3*image->colors,pcx_colormap); pcx_info.reserved=(unsigned char) ReadBlobByte(image); pcx_info.planes=(unsigned char) ReadBlobByte(image); if ((pcx_info.bits_per_pixel*pcx_info.planes) >= 64) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); one=1; if ((pcx_info.bits_per_pixel != 8) || (pcx_info.planes == 1)) if ((pcx_info.version == 3) || (pcx_info.version == 5) || ((pcx_info.bits_per_pixel*pcx_info.planes) == 1)) image->colors=(size_t) MagickMin(one << (1UL* (pcx_info.bits_per_pixel*pcx_info.planes)),256UL); if (AcquireImageColormap(image,image->colors) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); if ((pcx_info.bits_per_pixel >= 8) && (pcx_info.planes != 1)) image->storage_class=DirectClass; p=pcx_colormap; for (i=0; i < (ssize_t) image->colors; i++) { image->colormap[i].red=ScaleCharToQuantum(*p++); image->colormap[i].green=ScaleCharToQuantum(*p++); image->colormap[i].blue=ScaleCharToQuantum(*p++); } pcx_info.bytes_per_line=ReadBlobLSBShort(image); pcx_info.palette_info=ReadBlobLSBShort(image); for (i=0; i < 58; i++) (void) ReadBlobByte(image); if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } /* Read image data. */ pcx_packets=(size_t) image->rows*pcx_info.bytes_per_line*pcx_info.planes; if ((size_t) (pcx_info.bits_per_pixel*pcx_info.planes*image->columns) > (pcx_packets*8U)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); scanline=(unsigned char *) AcquireQuantumMemory(MagickMax(image->columns, pcx_info.bytes_per_line),MagickMax(8,pcx_info.planes)*sizeof(*scanline)); pixel_info=AcquireVirtualMemory(pcx_packets,2*sizeof(*pixels)); if ((scanline == (unsigned char *) NULL) || (pixel_info == (MemoryInfo *) NULL)) { if (scanline != (unsigned char *) NULL) scanline=(unsigned char *) RelinquishMagickMemory(scanline); if (pixel_info != (MemoryInfo *) NULL) pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); /* Uncompress image data. */ p=pixels; if (pcx_info.encoding == 0) while (pcx_packets != 0) { packet=(unsigned char) ReadBlobByte(image); if (EOFBlob(image) != MagickFalse) ThrowPCXException(CorruptImageError,"UnexpectedEndOfFile"); *p++=packet; pcx_packets--; } else while (pcx_packets != 0) { packet=(unsigned char) ReadBlobByte(image); if (EOFBlob(image) != MagickFalse) ThrowPCXException(CorruptImageError,"UnexpectedEndOfFile"); if ((packet & 0xc0) != 0xc0) { *p++=packet; pcx_packets--; continue; } count=(ssize_t) (packet & 0x3f); packet=(unsigned char) ReadBlobByte(image); if (EOFBlob(image) != MagickFalse) ThrowPCXException(CorruptImageError,"UnexpectedEndOfFile"); for ( ; count != 0; count--) { *p++=packet; pcx_packets--; if (pcx_packets == 0) break; } } if (image->storage_class == DirectClass) image->matte=pcx_info.planes > 3 ? MagickTrue : MagickFalse; else if ((pcx_info.version == 5) || ((pcx_info.bits_per_pixel*pcx_info.planes) == 1)) { /* Initialize image colormap. */ if (image->colors > 256) ThrowPCXException(CorruptImageError,"ColormapExceeds256Colors"); if ((pcx_info.bits_per_pixel*pcx_info.planes) == 1) { /* Monochrome colormap. */ image->colormap[0].red=(Quantum) 0; image->colormap[0].green=(Quantum) 0; image->colormap[0].blue=(Quantum) 0; image->colormap[1].red=QuantumRange; image->colormap[1].green=QuantumRange; image->colormap[1].blue=QuantumRange; } else if (image->colors > 16) { /* 256 color images have their color map at the end of the file. */ pcx_info.colormap_signature=(unsigned char) ReadBlobByte(image); count=ReadBlob(image,3*image->colors,pcx_colormap); p=pcx_colormap; for (i=0; i < (ssize_t) image->colors; i++) { image->colormap[i].red=ScaleCharToQuantum(*p++); image->colormap[i].green=ScaleCharToQuantum(*p++); image->colormap[i].blue=ScaleCharToQuantum(*p++); } } } /* Convert PCX raster image to pixel packets. */ for (y=0; y < (ssize_t) image->rows; y++) { p=pixels+(y*pcx_info.bytes_per_line*pcx_info.planes); q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); r=scanline; if (image->storage_class == DirectClass) for (i=0; i < pcx_info.planes; i++) { r=scanline+i; for (x=0; x < (ssize_t) pcx_info.bytes_per_line; x++) { switch (i) { case 0: { *r=(*p++); break; } case 1: { *r=(*p++); break; } case 2: { *r=(*p++); break; } case 3: default: { *r=(*p++); break; } } r+=pcx_info.planes; } } else if (pcx_info.planes > 1) { for (x=0; x < (ssize_t) image->columns; x++) *r++=0; for (i=0; i < pcx_info.planes; i++) { r=scanline; for (x=0; x < (ssize_t) pcx_info.bytes_per_line; x++) { bits=(*p++); for (mask=0x80; mask != 0; mask>>=1) { if (bits & mask) *r|=1 << i; r++; } } } } else switch (pcx_info.bits_per_pixel) { case 1: { register ssize_t bit; for (x=0; x < ((ssize_t) image->columns-7); x+=8) { for (bit=7; bit >= 0; bit--) *r++=(unsigned char) ((*p) & (0x01 << bit) ? 0x01 : 0x00); p++; } if ((image->columns % 8) != 0) { for (bit=7; bit >= (ssize_t) (8-(image->columns % 8)); bit--) *r++=(unsigned char) ((*p) & (0x01 << bit) ? 0x01 : 0x00); p++; } break; } case 2: { for (x=0; x < ((ssize_t) image->columns-3); x+=4) { *r++=(*p >> 6) & 0x3; *r++=(*p >> 4) & 0x3; *r++=(*p >> 2) & 0x3; *r++=(*p) & 0x3; p++; } if ((image->columns % 4) != 0) { for (i=3; i >= (ssize_t) (4-(image->columns % 4)); i--) *r++=(unsigned char) ((*p >> (i*2)) & 0x03); p++; } break; } case 4: { for (x=0; x < ((ssize_t) image->columns-1); x+=2) { *r++=(*p >> 4) & 0xf; *r++=(*p) & 0xf; p++; } if ((image->columns % 2) != 0) *r++=(*p++ >> 4) & 0xf; break; } case 8: { (void) CopyMagickMemory(r,p,image->columns); break; } default: break; } /* Transfer image scanline. */ r=scanline; for (x=0; x < (ssize_t) image->columns; x++) { if (image->storage_class == PseudoClass) SetPixelIndex(indexes+x,*r++) else { SetPixelRed(q,ScaleCharToQuantum(*r++)); SetPixelGreen(q,ScaleCharToQuantum(*r++)); SetPixelBlue(q,ScaleCharToQuantum(*r++)); if (image->matte != MagickFalse) SetPixelAlpha(q,ScaleCharToQuantum(*r++)); } q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } if (image->storage_class == PseudoClass) (void) SyncImage(image); scanline=(unsigned char *) RelinquishMagickMemory(scanline); pixel_info=RelinquishVirtualMemory(pixel_info); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; if (page_table == (MagickOffsetType *) NULL) break; if (page_table[id] == 0) break; offset=SeekBlob(image,(MagickOffsetType) page_table[id],SEEK_SET); if (offset < 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); count=ReadBlob(image,1,&pcx_info.identifier); if ((count != 0) && (pcx_info.identifier == 0x0a)) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } if (page_table != (MagickOffsetType *) NULL) page_table=(MagickOffsetType *) RelinquishMagickMemory(page_table); (void) CloseBlob(image); return(GetFirstImageInList(image)); }
168,591
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void bond_setup(struct net_device *bond_dev) { struct bonding *bond = netdev_priv(bond_dev); /* initialize rwlocks */ rwlock_init(&bond->lock); rwlock_init(&bond->curr_slave_lock); bond->params = bonding_defaults; /* Initialize pointers */ bond->dev = bond_dev; INIT_LIST_HEAD(&bond->vlan_list); /* Initialize the device entry points */ ether_setup(bond_dev); bond_dev->netdev_ops = &bond_netdev_ops; bond_dev->ethtool_ops = &bond_ethtool_ops; bond_set_mode_ops(bond, bond->params.mode); bond_dev->destructor = bond_destructor; /* Initialize the device options */ bond_dev->tx_queue_len = 0; bond_dev->flags |= IFF_MASTER|IFF_MULTICAST; bond_dev->priv_flags |= IFF_BONDING; bond_dev->priv_flags &= ~IFF_XMIT_DST_RELEASE; /* At first, we block adding VLANs. That's the only way to * prevent problems that occur when adding VLANs over an * empty bond. The block will be removed once non-challenged * slaves are enslaved. */ bond_dev->features |= NETIF_F_VLAN_CHALLENGED; /* don't acquire bond device's netif_tx_lock when * transmitting */ bond_dev->features |= NETIF_F_LLTX; /* By default, we declare the bond to be fully * VLAN hardware accelerated capable. Special * care is taken in the various xmit functions * when there are slaves that are not hw accel * capable */ bond_dev->hw_features = BOND_VLAN_FEATURES | NETIF_F_HW_VLAN_TX | NETIF_F_HW_VLAN_RX | NETIF_F_HW_VLAN_FILTER; bond_dev->hw_features &= ~(NETIF_F_ALL_CSUM & ~NETIF_F_NO_CSUM); bond_dev->features |= bond_dev->hw_features; } Commit Message: net: Audit drivers to identify those needing IFF_TX_SKB_SHARING cleared After the last patch, We are left in a state in which only drivers calling ether_setup have IFF_TX_SKB_SHARING set (we assume that drivers touching real hardware call ether_setup for their net_devices and don't hold any state in their skbs. There are a handful of drivers that violate this assumption of course, and need to be fixed up. This patch identifies those drivers, and marks them as not being able to support the safe transmission of skbs by clearning the IFF_TX_SKB_SHARING flag in priv_flags Signed-off-by: Neil Horman <[email protected]> CC: Karsten Keil <[email protected]> CC: "David S. Miller" <[email protected]> CC: Jay Vosburgh <[email protected]> CC: Andy Gospodarek <[email protected]> CC: Patrick McHardy <[email protected]> CC: Krzysztof Halasa <[email protected]> CC: "John W. Linville" <[email protected]> CC: Greg Kroah-Hartman <[email protected]> CC: Marcel Holtmann <[email protected]> CC: Johannes Berg <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-264
static void bond_setup(struct net_device *bond_dev) { struct bonding *bond = netdev_priv(bond_dev); /* initialize rwlocks */ rwlock_init(&bond->lock); rwlock_init(&bond->curr_slave_lock); bond->params = bonding_defaults; /* Initialize pointers */ bond->dev = bond_dev; INIT_LIST_HEAD(&bond->vlan_list); /* Initialize the device entry points */ ether_setup(bond_dev); bond_dev->netdev_ops = &bond_netdev_ops; bond_dev->ethtool_ops = &bond_ethtool_ops; bond_set_mode_ops(bond, bond->params.mode); bond_dev->destructor = bond_destructor; /* Initialize the device options */ bond_dev->tx_queue_len = 0; bond_dev->flags |= IFF_MASTER|IFF_MULTICAST; bond_dev->priv_flags |= IFF_BONDING; bond_dev->priv_flags &= ~(IFF_XMIT_DST_RELEASE | IFF_TX_SKB_SHARING); /* At first, we block adding VLANs. That's the only way to * prevent problems that occur when adding VLANs over an * empty bond. The block will be removed once non-challenged * slaves are enslaved. */ bond_dev->features |= NETIF_F_VLAN_CHALLENGED; /* don't acquire bond device's netif_tx_lock when * transmitting */ bond_dev->features |= NETIF_F_LLTX; /* By default, we declare the bond to be fully * VLAN hardware accelerated capable. Special * care is taken in the various xmit functions * when there are slaves that are not hw accel * capable */ bond_dev->hw_features = BOND_VLAN_FEATURES | NETIF_F_HW_VLAN_TX | NETIF_F_HW_VLAN_RX | NETIF_F_HW_VLAN_FILTER; bond_dev->hw_features &= ~(NETIF_F_ALL_CSUM & ~NETIF_F_NO_CSUM); bond_dev->features |= bond_dev->hw_features; }
165,727
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void VaapiVideoDecodeAccelerator::VaapiH264Accelerator::FillVAPicture( VAPictureH264* va_pic, scoped_refptr<H264Picture> pic) { VASurfaceID va_surface_id = VA_INVALID_SURFACE; if (!pic->nonexisting) { scoped_refptr<VaapiDecodeSurface> dec_surface = H264PictureToVaapiDecodeSurface(pic); va_surface_id = dec_surface->va_surface()->id(); } va_pic->picture_id = va_surface_id; va_pic->frame_idx = pic->frame_num; va_pic->flags = 0; switch (pic->field) { case H264Picture::FIELD_NONE: break; case H264Picture::FIELD_TOP: va_pic->flags |= VA_PICTURE_H264_TOP_FIELD; break; case H264Picture::FIELD_BOTTOM: va_pic->flags |= VA_PICTURE_H264_BOTTOM_FIELD; break; } if (pic->ref) { va_pic->flags |= pic->long_term ? VA_PICTURE_H264_LONG_TERM_REFERENCE : VA_PICTURE_H264_SHORT_TERM_REFERENCE; } va_pic->TopFieldOrderCnt = pic->top_field_order_cnt; va_pic->BottomFieldOrderCnt = pic->bottom_field_order_cnt; } Commit Message: vaapi vda: Delete owned objects on worker thread in Cleanup() This CL adds a SEQUENCE_CHECKER to Vaapi*Accelerator classes, and posts the destruction of those objects to the appropriate thread on Cleanup(). Also makes {H264,VP8,VP9}Picture RefCountedThreadSafe, see miu@ comment in https://chromium-review.googlesource.com/c/chromium/src/+/794091#message-a64bed985cfaf8a19499a517bb110a7ce581dc0f TEST=play back VP9/VP8/H264 w/ simplechrome on soraka, Release build unstripped, let video play for a few seconds then navigate back; no crashes. Unittests as before: video_decode_accelerator_unittest --test_video_data=test-25fps.vp9:320:240:250:250:35:150:12 video_decode_accelerator_unittest --test_video_data=test-25fps.vp8:320:240:250:250:35:150:11 video_decode_accelerator_unittest --test_video_data=test-25fps.h264:320:240:250:258:35:150:1 Bug: 789160 Cq-Include-Trybots: master.tryserver.chromium.android:android_optional_gpu_tests_rel;master.tryserver.chromium.linux:linux_optional_gpu_tests_rel;master.tryserver.chromium.mac:mac_optional_gpu_tests_rel;master.tryserver.chromium.win:win_optional_gpu_tests_rel Change-Id: I7d96aaf89c92bf46f00c8b8b36798e057a842ed2 Reviewed-on: https://chromium-review.googlesource.com/794091 Reviewed-by: Pawel Osciak <[email protected]> Commit-Queue: Miguel Casas <[email protected]> Cr-Commit-Position: refs/heads/master@{#523372} CWE ID: CWE-362
void VaapiVideoDecodeAccelerator::VaapiH264Accelerator::FillVAPicture( VAPictureH264* va_pic, scoped_refptr<H264Picture> pic) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); VASurfaceID va_surface_id = VA_INVALID_SURFACE; if (!pic->nonexisting) { scoped_refptr<VaapiDecodeSurface> dec_surface = H264PictureToVaapiDecodeSurface(pic); va_surface_id = dec_surface->va_surface()->id(); } va_pic->picture_id = va_surface_id; va_pic->frame_idx = pic->frame_num; va_pic->flags = 0; switch (pic->field) { case H264Picture::FIELD_NONE: break; case H264Picture::FIELD_TOP: va_pic->flags |= VA_PICTURE_H264_TOP_FIELD; break; case H264Picture::FIELD_BOTTOM: va_pic->flags |= VA_PICTURE_H264_BOTTOM_FIELD; break; } if (pic->ref) { va_pic->flags |= pic->long_term ? VA_PICTURE_H264_LONG_TERM_REFERENCE : VA_PICTURE_H264_SHORT_TERM_REFERENCE; } va_pic->TopFieldOrderCnt = pic->top_field_order_cnt; va_pic->BottomFieldOrderCnt = pic->bottom_field_order_cnt; }
172,800
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void RunSignBiasCheck() { ACMRandom rnd(ACMRandom::DeterministicSeed()); DECLARE_ALIGNED_ARRAY(16, int16_t, test_input_block, 64); DECLARE_ALIGNED_ARRAY(16, int16_t, test_output_block, 64); int count_sign_block[64][2]; const int count_test_block = 100000; memset(count_sign_block, 0, sizeof(count_sign_block)); for (int i = 0; i < count_test_block; ++i) { for (int j = 0; j < 64; ++j) test_input_block[j] = rnd.Rand8() - rnd.Rand8(); REGISTER_STATE_CHECK( RunFwdTxfm(test_input_block, test_output_block, pitch_)); for (int j = 0; j < 64; ++j) { if (test_output_block[j] < 0) ++count_sign_block[j][0]; else if (test_output_block[j] > 0) ++count_sign_block[j][1]; } } for (int j = 0; j < 64; ++j) { const int diff = abs(count_sign_block[j][0] - count_sign_block[j][1]); const int max_diff = 1125; EXPECT_LT(diff, max_diff) << "Error: 8x8 FDCT/FHT has a sign bias > " << 1. * max_diff / count_test_block * 100 << "%" << " for input range [-255, 255] at index " << j << " count0: " << count_sign_block[j][0] << " count1: " << count_sign_block[j][1] << " diff: " << diff; } memset(count_sign_block, 0, sizeof(count_sign_block)); for (int i = 0; i < count_test_block; ++i) { for (int j = 0; j < 64; ++j) test_input_block[j] = (rnd.Rand8() >> 4) - (rnd.Rand8() >> 4); REGISTER_STATE_CHECK( RunFwdTxfm(test_input_block, test_output_block, pitch_)); for (int j = 0; j < 64; ++j) { if (test_output_block[j] < 0) ++count_sign_block[j][0]; else if (test_output_block[j] > 0) ++count_sign_block[j][1]; } } for (int j = 0; j < 64; ++j) { const int diff = abs(count_sign_block[j][0] - count_sign_block[j][1]); const int max_diff = 10000; EXPECT_LT(diff, max_diff) << "Error: 4x4 FDCT/FHT has a sign bias > " << 1. * max_diff / count_test_block * 100 << "%" << " for input range [-15, 15] at index " << j << " count0: " << count_sign_block[j][0] << " count1: " << count_sign_block[j][1] << " diff: " << diff; } } 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 RunSignBiasCheck() { ACMRandom rnd(ACMRandom::DeterministicSeed()); DECLARE_ALIGNED(16, int16_t, test_input_block[64]); DECLARE_ALIGNED(16, tran_low_t, test_output_block[64]); int count_sign_block[64][2]; const int count_test_block = 100000; memset(count_sign_block, 0, sizeof(count_sign_block)); for (int i = 0; i < count_test_block; ++i) { for (int j = 0; j < 64; ++j) test_input_block[j] = ((rnd.Rand16() >> (16 - bit_depth_)) & mask_) - ((rnd.Rand16() >> (16 - bit_depth_)) & mask_); ASM_REGISTER_STATE_CHECK( RunFwdTxfm(test_input_block, test_output_block, pitch_)); for (int j = 0; j < 64; ++j) { if (test_output_block[j] < 0) ++count_sign_block[j][0]; else if (test_output_block[j] > 0) ++count_sign_block[j][1]; } } for (int j = 0; j < 64; ++j) { const int diff = abs(count_sign_block[j][0] - count_sign_block[j][1]); const int max_diff = kSignBiasMaxDiff255; EXPECT_LT(diff, max_diff << (bit_depth_ - 8)) << "Error: 8x8 FDCT/FHT has a sign bias > " << 1. * max_diff / count_test_block * 100 << "%" << " for input range [-255, 255] at index " << j << " count0: " << count_sign_block[j][0] << " count1: " << count_sign_block[j][1] << " diff: " << diff; } memset(count_sign_block, 0, sizeof(count_sign_block)); for (int i = 0; i < count_test_block; ++i) { // Initialize a test block with input range [-mask_ / 16, mask_ / 16]. for (int j = 0; j < 64; ++j) test_input_block[j] = ((rnd.Rand16() & mask_) >> 4) - ((rnd.Rand16() & mask_) >> 4); ASM_REGISTER_STATE_CHECK( RunFwdTxfm(test_input_block, test_output_block, pitch_)); for (int j = 0; j < 64; ++j) { if (test_output_block[j] < 0) ++count_sign_block[j][0]; else if (test_output_block[j] > 0) ++count_sign_block[j][1]; } } for (int j = 0; j < 64; ++j) { const int diff = abs(count_sign_block[j][0] - count_sign_block[j][1]); const int max_diff = kSignBiasMaxDiff15; EXPECT_LT(diff, max_diff << (bit_depth_ - 8)) << "Error: 8x8 FDCT/FHT has a sign bias > " << 1. * max_diff / count_test_block * 100 << "%" << " for input range [-15, 15] at index " << j << " count0: " << count_sign_block[j][0] << " count1: " << count_sign_block[j][1] << " diff: " << diff; } }
174,561
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void DevToolsAgentHostImpl::InnerAttachClient(DevToolsAgentHostClient* client) { scoped_refptr<DevToolsAgentHostImpl> protect(this); DevToolsSession* session = new DevToolsSession(this, client); sessions_.insert(session); session_by_client_[client].reset(session); AttachSession(session); if (sessions_.size() == 1) NotifyAttached(); DevToolsManager* manager = DevToolsManager::GetInstance(); if (manager->delegate()) manager->delegate()->ClientAttached(this, client); } Commit Message: [DevTools] Do not allow chrome.debugger to attach to web ui pages If the page navigates to web ui, we force detach the debugger extension. [email protected] Bug: 798222 Change-Id: Idb46c2f59e839388397a8dfa6ce2e2a897698df3 Reviewed-on: https://chromium-review.googlesource.com/935961 Commit-Queue: Dmitry Gozman <[email protected]> Reviewed-by: Devlin <[email protected]> Reviewed-by: Pavel Feldman <[email protected]> Reviewed-by: Nasko Oskov <[email protected]> Cr-Commit-Position: refs/heads/master@{#540916} CWE ID: CWE-20
void DevToolsAgentHostImpl::InnerAttachClient(DevToolsAgentHostClient* client) { bool DevToolsAgentHostImpl::InnerAttachClient(DevToolsAgentHostClient* client, bool restricted) { scoped_refptr<DevToolsAgentHostImpl> protect(this); DevToolsSession* session = new DevToolsSession(this, client, restricted); sessions_.insert(session); session_by_client_[client].reset(session); if (!AttachSession(session)) { sessions_.erase(session); session_by_client_.erase(client); return false; } if (sessions_.size() == 1) NotifyAttached(); DevToolsManager* manager = DevToolsManager::GetInstance(); if (manager->delegate()) manager->delegate()->ClientAttached(this, client); return true; }
173,246
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: TPM_RC tpm_kdfa(TSS2_SYS_CONTEXT *sapi_context, TPMI_ALG_HASH hashAlg, TPM2B *key, char *label, TPM2B *contextU, TPM2B *contextV, UINT16 bits, TPM2B_MAX_BUFFER *resultKey ) { TPM2B_DIGEST tmpResult; TPM2B_DIGEST tpm2bLabel, tpm2bBits, tpm2b_i_2; UINT8 *tpm2bBitsPtr = &tpm2bBits.t.buffer[0]; UINT8 *tpm2b_i_2Ptr = &tpm2b_i_2.t.buffer[0]; TPM2B_DIGEST *bufferList[8]; UINT32 bitsSwizzled, i_Swizzled; TPM_RC rval; int i, j; UINT16 bytes = bits / 8; resultKey->t .size = 0; tpm2b_i_2.t.size = 4; tpm2bBits.t.size = 4; bitsSwizzled = string_bytes_endian_convert_32( bits ); *(UINT32 *)tpm2bBitsPtr = bitsSwizzled; for(i = 0; label[i] != 0 ;i++ ); tpm2bLabel.t.size = i+1; for( i = 0; i < tpm2bLabel.t.size; i++ ) { tpm2bLabel.t.buffer[i] = label[i]; } resultKey->t.size = 0; i = 1; while( resultKey->t.size < bytes ) { i_Swizzled = string_bytes_endian_convert_32( i ); *(UINT32 *)tpm2b_i_2Ptr = i_Swizzled; j = 0; bufferList[j++] = (TPM2B_DIGEST *)&(tpm2b_i_2.b); bufferList[j++] = (TPM2B_DIGEST *)&(tpm2bLabel.b); bufferList[j++] = (TPM2B_DIGEST *)contextU; bufferList[j++] = (TPM2B_DIGEST *)contextV; bufferList[j++] = (TPM2B_DIGEST *)&(tpm2bBits.b); bufferList[j++] = (TPM2B_DIGEST *)0; rval = tpm_hmac(sapi_context, hashAlg, key, (TPM2B **)&( bufferList[0] ), &tmpResult ); if( rval != TPM_RC_SUCCESS ) { return( rval ); } bool res = string_bytes_concat_buffer(resultKey, &(tmpResult.b)); if (!res) { return TSS2_SYS_RC_BAD_VALUE; } } resultKey->t.size = bytes; return TPM_RC_SUCCESS; } Commit Message: kdfa: use openssl for hmac not tpm While not reachable in the current code base tools, a potential security bug lurked in tpm_kdfa(). If using that routine for an hmac authorization, the hmac was calculated using the tpm. A user of an object wishing to authenticate via hmac, would expect that the password is never sent to the tpm. However, since the hmac calculation relies on password, and is performed by the tpm, the password ends up being sent in plain text to the tpm. The fix is to use openssl to generate the hmac on the host. Fixes: CVE-2017-7524 Signed-off-by: William Roberts <[email protected]> CWE ID: CWE-522
TPM_RC tpm_kdfa(TSS2_SYS_CONTEXT *sapi_context, TPMI_ALG_HASH hashAlg, TPM_RC tpm_kdfa(TPMI_ALG_HASH hashAlg, TPM2B *key, char *label, TPM2B *contextU, TPM2B *contextV, UINT16 bits, TPM2B_MAX_BUFFER *resultKey ) { TPM2B_DIGEST tpm2bLabel, tpm2bBits, tpm2b_i_2; UINT8 *tpm2bBitsPtr = &tpm2bBits.t.buffer[0]; UINT8 *tpm2b_i_2Ptr = &tpm2b_i_2.t.buffer[0]; TPM2B_DIGEST *bufferList[8]; UINT32 bitsSwizzled, i_Swizzled; TPM_RC rval = TPM_RC_SUCCESS; int i, j; UINT16 bytes = bits / 8; resultKey->t .size = 0; tpm2b_i_2.t.size = 4; tpm2bBits.t.size = 4; bitsSwizzled = string_bytes_endian_convert_32( bits ); *(UINT32 *)tpm2bBitsPtr = bitsSwizzled; for(i = 0; label[i] != 0 ;i++ ); tpm2bLabel.t.size = i+1; for( i = 0; i < tpm2bLabel.t.size; i++ ) { tpm2bLabel.t.buffer[i] = label[i]; } resultKey->t.size = 0; i = 1; const EVP_MD *md = tpm_algorithm_to_openssl_digest(hashAlg); if (!md) { LOG_ERR("Algorithm not supported for hmac: %x", hashAlg); return TPM_RC_HASH; } HMAC_CTX ctx; HMAC_CTX_init(&ctx); int rc = HMAC_Init_ex(&ctx, key->buffer, key->size, md, NULL); if (!rc) { LOG_ERR("HMAC Init failed: %s", ERR_error_string(rc, NULL)); return TPM_RC_MEMORY; } // TODO Why is this a loop? It appears to only execute once. while( resultKey->t.size < bytes ) { TPM2B_DIGEST tmpResult; i_Swizzled = string_bytes_endian_convert_32( i ); *(UINT32 *)tpm2b_i_2Ptr = i_Swizzled; j = 0; bufferList[j++] = (TPM2B_DIGEST *)&(tpm2b_i_2.b); bufferList[j++] = (TPM2B_DIGEST *)&(tpm2bLabel.b); bufferList[j++] = (TPM2B_DIGEST *)contextU; bufferList[j++] = (TPM2B_DIGEST *)contextV; bufferList[j++] = (TPM2B_DIGEST *)&(tpm2bBits.b); bufferList[j] = (TPM2B_DIGEST *)0; int c; for(c=0; c < j; c++) { TPM2B_DIGEST *digest = bufferList[c]; int rc = HMAC_Update(&ctx, digest->b.buffer, digest->b.size); if (!rc) { LOG_ERR("HMAC Update failed: %s", ERR_error_string(rc, NULL)); rval = TPM_RC_MEMORY; goto err; } } unsigned size = sizeof(tmpResult.t.buffer); int rc = HMAC_Final(&ctx, tmpResult.t.buffer, &size); if (!rc) { LOG_ERR("HMAC Final failed: %s", ERR_error_string(rc, NULL)); rval = TPM_RC_MEMORY; goto err; } tmpResult.t.size = size; bool res = string_bytes_concat_buffer(resultKey, &(tmpResult.b)); if (!res) { rval = TSS2_SYS_RC_BAD_VALUE; goto err; } } resultKey->t.size = bytes; err: HMAC_CTX_cleanup(&ctx); return rval; }
168,265
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int unmap_ref_private(struct mm_struct *mm, struct vm_area_struct *vma, struct page *page, unsigned long address) { struct hstate *h = hstate_vma(vma); struct vm_area_struct *iter_vma; struct address_space *mapping; struct prio_tree_iter iter; pgoff_t pgoff; /* * vm_pgoff is in PAGE_SIZE units, hence the different calculation * from page cache lookup which is in HPAGE_SIZE units. */ address = address & huge_page_mask(h); pgoff = vma_hugecache_offset(h, vma, address); mapping = (struct address_space *)page_private(page); /* * Take the mapping lock for the duration of the table walk. As * this mapping should be shared between all the VMAs, * __unmap_hugepage_range() is called as the lock is already held */ mutex_lock(&mapping->i_mmap_mutex); vma_prio_tree_foreach(iter_vma, &iter, &mapping->i_mmap, pgoff, pgoff) { /* Do not unmap the current VMA */ if (iter_vma == vma) continue; /* * Unmap the page from other VMAs without their own reserves. * They get marked to be SIGKILLed if they fault in these * areas. This is because a future no-page fault on this VMA * could insert a zeroed page instead of the data existing * from the time of fork. This would look like data corruption */ if (!is_vma_resv_set(iter_vma, HPAGE_RESV_OWNER)) __unmap_hugepage_range(iter_vma, address, address + huge_page_size(h), page); } mutex_unlock(&mapping->i_mmap_mutex); return 1; } Commit Message: hugepages: fix use after free bug in "quota" handling hugetlbfs_{get,put}_quota() are badly named. They don't interact with the general quota handling code, and they don't much resemble its behaviour. Rather than being about maintaining limits on on-disk block usage by particular users, they are instead about maintaining limits on in-memory page usage (including anonymous MAP_PRIVATE copied-on-write pages) associated with a particular hugetlbfs filesystem instance. Worse, they work by having callbacks to the hugetlbfs filesystem code from the low-level page handling code, in particular from free_huge_page(). This is a layering violation of itself, but more importantly, if the kernel does a get_user_pages() on hugepages (which can happen from KVM amongst others), then the free_huge_page() can be delayed until after the associated inode has already been freed. If an unmount occurs at the wrong time, even the hugetlbfs superblock where the "quota" limits are stored may have been freed. Andrew Barry proposed a patch to fix this by having hugepages, instead of storing a pointer to their address_space and reaching the superblock from there, had the hugepages store pointers directly to the superblock, bumping the reference count as appropriate to avoid it being freed. Andrew Morton rejected that version, however, on the grounds that it made the existing layering violation worse. This is a reworked version of Andrew's patch, which removes the extra, and some of the existing, layering violation. It works by introducing the concept of a hugepage "subpool" at the lower hugepage mm layer - that is a finite logical pool of hugepages to allocate from. hugetlbfs now creates a subpool for each filesystem instance with a page limit set, and a pointer to the subpool gets added to each allocated hugepage, instead of the address_space pointer used now. The subpool has its own lifetime and is only freed once all pages in it _and_ all other references to it (i.e. superblocks) are gone. subpools are optional - a NULL subpool pointer is taken by the code to mean that no subpool limits are in effect. Previous discussion of this bug found in: "Fix refcounting in hugetlbfs quota handling.". See: https://lkml.org/lkml/2011/8/11/28 or http://marc.info/?l=linux-mm&m=126928970510627&w=1 v2: Fixed a bug spotted by Hillf Danton, and removed the extra parameter to alloc_huge_page() - since it already takes the vma, it is not necessary. Signed-off-by: Andrew Barry <[email protected]> Signed-off-by: David Gibson <[email protected]> Cc: Hugh Dickins <[email protected]> Cc: Mel Gorman <[email protected]> Cc: Minchan Kim <[email protected]> Cc: Hillf Danton <[email protected]> Cc: Paul Mackerras <[email protected]> Signed-off-by: Andrew Morton <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-399
static int unmap_ref_private(struct mm_struct *mm, struct vm_area_struct *vma, struct page *page, unsigned long address) { struct hstate *h = hstate_vma(vma); struct vm_area_struct *iter_vma; struct address_space *mapping; struct prio_tree_iter iter; pgoff_t pgoff; /* * vm_pgoff is in PAGE_SIZE units, hence the different calculation * from page cache lookup which is in HPAGE_SIZE units. */ address = address & huge_page_mask(h); pgoff = vma_hugecache_offset(h, vma, address); mapping = vma->vm_file->f_dentry->d_inode->i_mapping; /* * Take the mapping lock for the duration of the table walk. As * this mapping should be shared between all the VMAs, * __unmap_hugepage_range() is called as the lock is already held */ mutex_lock(&mapping->i_mmap_mutex); vma_prio_tree_foreach(iter_vma, &iter, &mapping->i_mmap, pgoff, pgoff) { /* Do not unmap the current VMA */ if (iter_vma == vma) continue; /* * Unmap the page from other VMAs without their own reserves. * They get marked to be SIGKILLed if they fault in these * areas. This is because a future no-page fault on this VMA * could insert a zeroed page instead of the data existing * from the time of fork. This would look like data corruption */ if (!is_vma_resv_set(iter_vma, HPAGE_RESV_OWNER)) __unmap_hugepage_range(iter_vma, address, address + huge_page_size(h), page); } mutex_unlock(&mapping->i_mmap_mutex); return 1; }
165,613
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: kg_unseal_iov(OM_uint32 *minor_status, gss_ctx_id_t context_handle, int *conf_state, gss_qop_t *qop_state, gss_iov_buffer_desc *iov, int iov_count, int toktype) { krb5_gss_ctx_id_rec *ctx; OM_uint32 code; ctx = (krb5_gss_ctx_id_rec *)context_handle; if (!ctx->established) { *minor_status = KG_CTX_INCOMPLETE; return GSS_S_NO_CONTEXT; } if (kg_locate_iov(iov, iov_count, GSS_IOV_BUFFER_TYPE_STREAM) != NULL) { code = kg_unseal_stream_iov(minor_status, ctx, conf_state, qop_state, iov, iov_count, toktype); } else { code = kg_unseal_iov_token(minor_status, ctx, conf_state, qop_state, iov, iov_count, toktype); } return code; } Commit Message: Fix gss_process_context_token() [CVE-2014-5352] [MITKRB5-SA-2015-001] The krb5 gss_process_context_token() should not actually delete the context; that leaves the caller with a dangling pointer and no way to know that it is invalid. Instead, mark the context as terminated, and check for terminated contexts in the GSS functions which expect established contexts. Also add checks in export_sec_context and pseudo_random, and adjust t_prf.c for the pseudo_random check. ticket: 8055 (new) target_version: 1.13.1 tags: pullup CWE ID:
kg_unseal_iov(OM_uint32 *minor_status, gss_ctx_id_t context_handle, int *conf_state, gss_qop_t *qop_state, gss_iov_buffer_desc *iov, int iov_count, int toktype) { krb5_gss_ctx_id_rec *ctx; OM_uint32 code; ctx = (krb5_gss_ctx_id_rec *)context_handle; if (ctx->terminated || !ctx->established) { *minor_status = KG_CTX_INCOMPLETE; return GSS_S_NO_CONTEXT; } if (kg_locate_iov(iov, iov_count, GSS_IOV_BUFFER_TYPE_STREAM) != NULL) { code = kg_unseal_stream_iov(minor_status, ctx, conf_state, qop_state, iov, iov_count, toktype); } else { code = kg_unseal_iov_token(minor_status, ctx, conf_state, qop_state, iov, iov_count, toktype); } return code; }
166,820
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void MemoryInstrumentation::GetVmRegionsForHeapProfiler( RequestGlobalDumpCallback callback) { const auto& coordinator = GetCoordinatorBindingForCurrentThread(); coordinator->GetVmRegionsForHeapProfiler(callback); } Commit Message: memory-infra: split up memory-infra coordinator service into two This allows for heap profiler to use its own service with correct capabilities and all other instances to use the existing coordinator service. Bug: 792028 Change-Id: I84e4ec71f5f1d00991c0516b1424ce7334bcd3cd Reviewed-on: https://chromium-review.googlesource.com/836896 Commit-Queue: Lalit Maganti <[email protected]> Reviewed-by: Daniel Cheng <[email protected]> Reviewed-by: oysteine <[email protected]> Reviewed-by: Albert J. Wong <[email protected]> Reviewed-by: Hector Dearman <[email protected]> Cr-Commit-Position: refs/heads/master@{#529059} CWE ID: CWE-269
void MemoryInstrumentation::GetVmRegionsForHeapProfiler(
172,918
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void AppCacheHost::SelectCache(const GURL& document_url, const int64 cache_document_was_loaded_from, const GURL& manifest_url) { DCHECK(pending_start_update_callback_.is_null() && pending_swap_cache_callback_.is_null() && pending_get_status_callback_.is_null() && !is_selection_pending() && !was_select_cache_called_); was_select_cache_called_ = true; if (!is_cache_selection_enabled_) { FinishCacheSelection(NULL, NULL); return; } origin_in_use_ = document_url.GetOrigin(); if (service()->quota_manager_proxy() && !origin_in_use_.is_empty()) service()->quota_manager_proxy()->NotifyOriginInUse(origin_in_use_); if (main_resource_blocked_) frontend_->OnContentBlocked(host_id_, blocked_manifest_url_); if (cache_document_was_loaded_from != kAppCacheNoCacheId) { LoadSelectedCache(cache_document_was_loaded_from); return; } if (!manifest_url.is_empty() && (manifest_url.GetOrigin() == document_url.GetOrigin())) { DCHECK(!first_party_url_.is_empty()); AppCachePolicy* policy = service()->appcache_policy(); if (policy && !policy->CanCreateAppCache(manifest_url, first_party_url_)) { FinishCacheSelection(NULL, NULL); std::vector<int> host_ids(1, host_id_); frontend_->OnEventRaised(host_ids, APPCACHE_CHECKING_EVENT); frontend_->OnErrorEventRaised( host_ids, AppCacheErrorDetails( "Cache creation was blocked by the content policy", APPCACHE_POLICY_ERROR, GURL(), 0, false /*is_cross_origin*/)); frontend_->OnContentBlocked(host_id_, manifest_url); return; } set_preferred_manifest_url(manifest_url); new_master_entry_url_ = document_url; LoadOrCreateGroup(manifest_url); return; } FinishCacheSelection(NULL, NULL); } Commit Message: Fix possible map::end() dereference in AppCacheUpdateJob triggered by a compromised renderer. BUG=551044 Review URL: https://codereview.chromium.org/1418783005 Cr-Commit-Position: refs/heads/master@{#358815} CWE ID:
void AppCacheHost::SelectCache(const GURL& document_url, bool AppCacheHost::SelectCache(const GURL& document_url, const int64 cache_document_was_loaded_from, const GURL& manifest_url) { if (was_select_cache_called_) return false; DCHECK(pending_start_update_callback_.is_null() && pending_swap_cache_callback_.is_null() && pending_get_status_callback_.is_null() && !is_selection_pending()); was_select_cache_called_ = true; if (!is_cache_selection_enabled_) { FinishCacheSelection(NULL, NULL); return true; } origin_in_use_ = document_url.GetOrigin(); if (service()->quota_manager_proxy() && !origin_in_use_.is_empty()) service()->quota_manager_proxy()->NotifyOriginInUse(origin_in_use_); if (main_resource_blocked_) frontend_->OnContentBlocked(host_id_, blocked_manifest_url_); if (cache_document_was_loaded_from != kAppCacheNoCacheId) { LoadSelectedCache(cache_document_was_loaded_from); return true; } if (!manifest_url.is_empty() && (manifest_url.GetOrigin() == document_url.GetOrigin())) { DCHECK(!first_party_url_.is_empty()); AppCachePolicy* policy = service()->appcache_policy(); if (policy && !policy->CanCreateAppCache(manifest_url, first_party_url_)) { FinishCacheSelection(NULL, NULL); std::vector<int> host_ids(1, host_id_); frontend_->OnEventRaised(host_ids, APPCACHE_CHECKING_EVENT); frontend_->OnErrorEventRaised( host_ids, AppCacheErrorDetails( "Cache creation was blocked by the content policy", APPCACHE_POLICY_ERROR, GURL(), 0, false /*is_cross_origin*/)); frontend_->OnContentBlocked(host_id_, manifest_url); return true; } set_preferred_manifest_url(manifest_url); new_master_entry_url_ = document_url; LoadOrCreateGroup(manifest_url); return true; } FinishCacheSelection(NULL, NULL); return true; }
171,740
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: bgp_nlri_parse_vpnv4 (struct peer *peer, struct attr *attr, struct bgp_nlri *packet) { u_char *pnt; u_char *lim; struct prefix p; int psize; int prefixlen; u_int16_t type; struct rd_as rd_as; struct rd_ip rd_ip; struct prefix_rd prd; u_char *tagpnt; /* Check peer status. */ if (peer->status != Established) return 0; /* Make prefix_rd */ prd.family = AF_UNSPEC; prd.prefixlen = 64; pnt = packet->nlri; lim = pnt + packet->length; for (; pnt < lim; pnt += psize) { /* Clear prefix structure. */ /* Fetch prefix length. */ prefixlen = *pnt++; p.family = AF_INET; psize = PSIZE (prefixlen); if (prefixlen < 88) { zlog_err ("prefix length is less than 88: %d", prefixlen); return -1; } /* Copyr label to prefix. */ tagpnt = pnt;; /* Copy routing distinguisher to rd. */ memcpy (&prd.val, pnt + 3, 8); else if (type == RD_TYPE_IP) zlog_info ("prefix %ld:%s:%ld:%s/%d", label, inet_ntoa (rd_ip.ip), rd_ip.val, inet_ntoa (p.u.prefix4), p.prefixlen); #endif /* 0 */ if (pnt + psize > lim) return -1; if (attr) bgp_update (peer, &p, attr, AFI_IP, SAFI_MPLS_VPN, ZEBRA_ROUTE_BGP, BGP_ROUTE_NORMAL, &prd, tagpnt, 0); else return -1; } p.prefixlen = prefixlen - 88; memcpy (&p.u.prefix, pnt + 11, psize - 11); #if 0 if (type == RD_TYPE_AS) } Commit Message: CWE ID: CWE-119
bgp_nlri_parse_vpnv4 (struct peer *peer, struct attr *attr, struct bgp_nlri *packet) { u_char *pnt; u_char *lim; struct prefix p; int psize; int prefixlen; u_int16_t type; struct rd_as rd_as; struct rd_ip rd_ip; struct prefix_rd prd; u_char *tagpnt; /* Check peer status. */ if (peer->status != Established) return 0; /* Make prefix_rd */ prd.family = AF_UNSPEC; prd.prefixlen = 64; pnt = packet->nlri; lim = pnt + packet->length; #define VPN_PREFIXLEN_MIN_BYTES (3 + 8) /* label + RD */ for (; pnt < lim; pnt += psize) { /* Clear prefix structure. */ /* Fetch prefix length. */ prefixlen = *pnt++; p.family = afi2family (packet->afi); psize = PSIZE (prefixlen); /* sanity check against packet data */ if (prefixlen < VPN_PREFIXLEN_MIN_BYTES*8 || (pnt + psize) > lim) { zlog_err ("prefix length (%d) is less than 88" " or larger than received (%u)", prefixlen, (uint)(lim-pnt)); return -1; } /* sanity check against storage for the IP address portion */ if ((psize - VPN_PREFIXLEN_MIN_BYTES) > (ssize_t) sizeof(p.u)) { zlog_err ("prefix length (%d) exceeds prefix storage (%zu)", prefixlen - VPN_PREFIXLEN_MIN_BYTES*8, sizeof(p.u)); return -1; } /* Sanity check against max bitlen of the address family */ if ((psize - VPN_PREFIXLEN_MIN_BYTES) > prefix_blen (&p)) { zlog_err ("prefix length (%d) exceeds family (%u) max byte length (%u)", prefixlen - VPN_PREFIXLEN_MIN_BYTES*8, p.family, prefix_blen (&p)); return -1; } /* Copyr label to prefix. */ tagpnt = pnt; /* Copy routing distinguisher to rd. */ memcpy (&prd.val, pnt + 3, 8); else if (type == RD_TYPE_IP) zlog_info ("prefix %ld:%s:%ld:%s/%d", label, inet_ntoa (rd_ip.ip), rd_ip.val, inet_ntoa (p.u.prefix4), p.prefixlen); #endif /* 0 */ if (pnt + psize > lim) return -1; if (attr) bgp_update (peer, &p, attr, AFI_IP, SAFI_MPLS_VPN, ZEBRA_ROUTE_BGP, BGP_ROUTE_NORMAL, &prd, tagpnt, 0); else return -1; } p.prefixlen = prefixlen - VPN_PREFIXLEN_MIN_BYTES*8; memcpy (&p.u.prefix, pnt + VPN_PREFIXLEN_MIN_BYTES, psize - VPN_PREFIXLEN_MIN_BYTES); #if 0 if (type == RD_TYPE_AS) }
165,189
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int rtnl_fill_ifinfo(struct sk_buff *skb, struct net_device *dev, int type, u32 pid, u32 seq, u32 change, unsigned int flags, u32 ext_filter_mask) { struct ifinfomsg *ifm; struct nlmsghdr *nlh; struct rtnl_link_stats64 temp; const struct rtnl_link_stats64 *stats; struct nlattr *attr, *af_spec; struct rtnl_af_ops *af_ops; struct net_device *upper_dev = netdev_master_upper_dev_get(dev); ASSERT_RTNL(); nlh = nlmsg_put(skb, pid, seq, type, sizeof(*ifm), flags); if (nlh == NULL) return -EMSGSIZE; ifm = nlmsg_data(nlh); ifm->ifi_family = AF_UNSPEC; ifm->__ifi_pad = 0; ifm->ifi_type = dev->type; ifm->ifi_index = dev->ifindex; ifm->ifi_flags = dev_get_flags(dev); ifm->ifi_change = change; if (nla_put_string(skb, IFLA_IFNAME, dev->name) || nla_put_u32(skb, IFLA_TXQLEN, dev->tx_queue_len) || nla_put_u8(skb, IFLA_OPERSTATE, netif_running(dev) ? dev->operstate : IF_OPER_DOWN) || nla_put_u8(skb, IFLA_LINKMODE, dev->link_mode) || nla_put_u32(skb, IFLA_MTU, dev->mtu) || nla_put_u32(skb, IFLA_GROUP, dev->group) || nla_put_u32(skb, IFLA_PROMISCUITY, dev->promiscuity) || nla_put_u32(skb, IFLA_NUM_TX_QUEUES, dev->num_tx_queues) || #ifdef CONFIG_RPS nla_put_u32(skb, IFLA_NUM_RX_QUEUES, dev->num_rx_queues) || #endif (dev->ifindex != dev->iflink && nla_put_u32(skb, IFLA_LINK, dev->iflink)) || (upper_dev && nla_put_u32(skb, IFLA_MASTER, upper_dev->ifindex)) || nla_put_u8(skb, IFLA_CARRIER, netif_carrier_ok(dev)) || (dev->qdisc && nla_put_string(skb, IFLA_QDISC, dev->qdisc->ops->id)) || (dev->ifalias && nla_put_string(skb, IFLA_IFALIAS, dev->ifalias))) goto nla_put_failure; if (1) { struct rtnl_link_ifmap map = { .mem_start = dev->mem_start, .mem_end = dev->mem_end, .base_addr = dev->base_addr, .irq = dev->irq, .dma = dev->dma, .port = dev->if_port, }; if (nla_put(skb, IFLA_MAP, sizeof(map), &map)) goto nla_put_failure; } if (dev->addr_len) { if (nla_put(skb, IFLA_ADDRESS, dev->addr_len, dev->dev_addr) || nla_put(skb, IFLA_BROADCAST, dev->addr_len, dev->broadcast)) goto nla_put_failure; } attr = nla_reserve(skb, IFLA_STATS, sizeof(struct rtnl_link_stats)); if (attr == NULL) goto nla_put_failure; stats = dev_get_stats(dev, &temp); copy_rtnl_link_stats(nla_data(attr), stats); attr = nla_reserve(skb, IFLA_STATS64, sizeof(struct rtnl_link_stats64)); if (attr == NULL) goto nla_put_failure; copy_rtnl_link_stats64(nla_data(attr), stats); if (dev->dev.parent && (ext_filter_mask & RTEXT_FILTER_VF) && nla_put_u32(skb, IFLA_NUM_VF, dev_num_vf(dev->dev.parent))) goto nla_put_failure; if (dev->netdev_ops->ndo_get_vf_config && dev->dev.parent && (ext_filter_mask & RTEXT_FILTER_VF)) { int i; struct nlattr *vfinfo, *vf; int num_vfs = dev_num_vf(dev->dev.parent); vfinfo = nla_nest_start(skb, IFLA_VFINFO_LIST); if (!vfinfo) goto nla_put_failure; for (i = 0; i < num_vfs; i++) { struct ifla_vf_info ivi; struct ifla_vf_mac vf_mac; struct ifla_vf_vlan vf_vlan; struct ifla_vf_tx_rate vf_tx_rate; struct ifla_vf_spoofchk vf_spoofchk; /* * Not all SR-IOV capable drivers support the * spoofcheck query. Preset to -1 so the user * space tool can detect that the driver didn't * report anything. */ ivi.spoofchk = -1; if (dev->netdev_ops->ndo_get_vf_config(dev, i, &ivi)) break; vf_mac.vf = vf_vlan.vf = vf_tx_rate.vf = vf_spoofchk.vf = ivi.vf; memcpy(vf_mac.mac, ivi.mac, sizeof(ivi.mac)); vf_vlan.vlan = ivi.vlan; vf_vlan.qos = ivi.qos; vf_tx_rate.rate = ivi.tx_rate; vf_spoofchk.setting = ivi.spoofchk; vf = nla_nest_start(skb, IFLA_VF_INFO); if (!vf) { nla_nest_cancel(skb, vfinfo); goto nla_put_failure; } if (nla_put(skb, IFLA_VF_MAC, sizeof(vf_mac), &vf_mac) || nla_put(skb, IFLA_VF_VLAN, sizeof(vf_vlan), &vf_vlan) || nla_put(skb, IFLA_VF_TX_RATE, sizeof(vf_tx_rate), &vf_tx_rate) || nla_put(skb, IFLA_VF_SPOOFCHK, sizeof(vf_spoofchk), &vf_spoofchk)) goto nla_put_failure; nla_nest_end(skb, vf); } nla_nest_end(skb, vfinfo); } if (rtnl_port_fill(skb, dev)) goto nla_put_failure; if (dev->rtnl_link_ops) { if (rtnl_link_fill(skb, dev) < 0) goto nla_put_failure; } if (!(af_spec = nla_nest_start(skb, IFLA_AF_SPEC))) goto nla_put_failure; list_for_each_entry(af_ops, &rtnl_af_ops, list) { if (af_ops->fill_link_af) { struct nlattr *af; int err; if (!(af = nla_nest_start(skb, af_ops->family))) goto nla_put_failure; err = af_ops->fill_link_af(skb, dev); /* * Caller may return ENODATA to indicate that there * was no data to be dumped. This is not an error, it * means we should trim the attribute header and * continue. */ if (err == -ENODATA) nla_nest_cancel(skb, af); else if (err < 0) goto nla_put_failure; nla_nest_end(skb, af); } } nla_nest_end(skb, af_spec); return nlmsg_end(skb, nlh); nla_put_failure: nlmsg_cancel(skb, nlh); return -EMSGSIZE; } Commit Message: rtnl: fix info leak on RTM_GETLINK request for VF devices Initialize the mac address buffer with 0 as the driver specific function will probably not fill the whole buffer. In fact, all in-kernel drivers fill only ETH_ALEN of the MAX_ADDR_LEN bytes, i.e. 6 of the 32 possible bytes. Therefore we currently leak 26 bytes of stack memory to userland via the netlink interface. Signed-off-by: Mathias Krause <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-399
static int rtnl_fill_ifinfo(struct sk_buff *skb, struct net_device *dev, int type, u32 pid, u32 seq, u32 change, unsigned int flags, u32 ext_filter_mask) { struct ifinfomsg *ifm; struct nlmsghdr *nlh; struct rtnl_link_stats64 temp; const struct rtnl_link_stats64 *stats; struct nlattr *attr, *af_spec; struct rtnl_af_ops *af_ops; struct net_device *upper_dev = netdev_master_upper_dev_get(dev); ASSERT_RTNL(); nlh = nlmsg_put(skb, pid, seq, type, sizeof(*ifm), flags); if (nlh == NULL) return -EMSGSIZE; ifm = nlmsg_data(nlh); ifm->ifi_family = AF_UNSPEC; ifm->__ifi_pad = 0; ifm->ifi_type = dev->type; ifm->ifi_index = dev->ifindex; ifm->ifi_flags = dev_get_flags(dev); ifm->ifi_change = change; if (nla_put_string(skb, IFLA_IFNAME, dev->name) || nla_put_u32(skb, IFLA_TXQLEN, dev->tx_queue_len) || nla_put_u8(skb, IFLA_OPERSTATE, netif_running(dev) ? dev->operstate : IF_OPER_DOWN) || nla_put_u8(skb, IFLA_LINKMODE, dev->link_mode) || nla_put_u32(skb, IFLA_MTU, dev->mtu) || nla_put_u32(skb, IFLA_GROUP, dev->group) || nla_put_u32(skb, IFLA_PROMISCUITY, dev->promiscuity) || nla_put_u32(skb, IFLA_NUM_TX_QUEUES, dev->num_tx_queues) || #ifdef CONFIG_RPS nla_put_u32(skb, IFLA_NUM_RX_QUEUES, dev->num_rx_queues) || #endif (dev->ifindex != dev->iflink && nla_put_u32(skb, IFLA_LINK, dev->iflink)) || (upper_dev && nla_put_u32(skb, IFLA_MASTER, upper_dev->ifindex)) || nla_put_u8(skb, IFLA_CARRIER, netif_carrier_ok(dev)) || (dev->qdisc && nla_put_string(skb, IFLA_QDISC, dev->qdisc->ops->id)) || (dev->ifalias && nla_put_string(skb, IFLA_IFALIAS, dev->ifalias))) goto nla_put_failure; if (1) { struct rtnl_link_ifmap map = { .mem_start = dev->mem_start, .mem_end = dev->mem_end, .base_addr = dev->base_addr, .irq = dev->irq, .dma = dev->dma, .port = dev->if_port, }; if (nla_put(skb, IFLA_MAP, sizeof(map), &map)) goto nla_put_failure; } if (dev->addr_len) { if (nla_put(skb, IFLA_ADDRESS, dev->addr_len, dev->dev_addr) || nla_put(skb, IFLA_BROADCAST, dev->addr_len, dev->broadcast)) goto nla_put_failure; } attr = nla_reserve(skb, IFLA_STATS, sizeof(struct rtnl_link_stats)); if (attr == NULL) goto nla_put_failure; stats = dev_get_stats(dev, &temp); copy_rtnl_link_stats(nla_data(attr), stats); attr = nla_reserve(skb, IFLA_STATS64, sizeof(struct rtnl_link_stats64)); if (attr == NULL) goto nla_put_failure; copy_rtnl_link_stats64(nla_data(attr), stats); if (dev->dev.parent && (ext_filter_mask & RTEXT_FILTER_VF) && nla_put_u32(skb, IFLA_NUM_VF, dev_num_vf(dev->dev.parent))) goto nla_put_failure; if (dev->netdev_ops->ndo_get_vf_config && dev->dev.parent && (ext_filter_mask & RTEXT_FILTER_VF)) { int i; struct nlattr *vfinfo, *vf; int num_vfs = dev_num_vf(dev->dev.parent); vfinfo = nla_nest_start(skb, IFLA_VFINFO_LIST); if (!vfinfo) goto nla_put_failure; for (i = 0; i < num_vfs; i++) { struct ifla_vf_info ivi; struct ifla_vf_mac vf_mac; struct ifla_vf_vlan vf_vlan; struct ifla_vf_tx_rate vf_tx_rate; struct ifla_vf_spoofchk vf_spoofchk; /* * Not all SR-IOV capable drivers support the * spoofcheck query. Preset to -1 so the user * space tool can detect that the driver didn't * report anything. */ ivi.spoofchk = -1; memset(ivi.mac, 0, sizeof(ivi.mac)); if (dev->netdev_ops->ndo_get_vf_config(dev, i, &ivi)) break; vf_mac.vf = vf_vlan.vf = vf_tx_rate.vf = vf_spoofchk.vf = ivi.vf; memcpy(vf_mac.mac, ivi.mac, sizeof(ivi.mac)); vf_vlan.vlan = ivi.vlan; vf_vlan.qos = ivi.qos; vf_tx_rate.rate = ivi.tx_rate; vf_spoofchk.setting = ivi.spoofchk; vf = nla_nest_start(skb, IFLA_VF_INFO); if (!vf) { nla_nest_cancel(skb, vfinfo); goto nla_put_failure; } if (nla_put(skb, IFLA_VF_MAC, sizeof(vf_mac), &vf_mac) || nla_put(skb, IFLA_VF_VLAN, sizeof(vf_vlan), &vf_vlan) || nla_put(skb, IFLA_VF_TX_RATE, sizeof(vf_tx_rate), &vf_tx_rate) || nla_put(skb, IFLA_VF_SPOOFCHK, sizeof(vf_spoofchk), &vf_spoofchk)) goto nla_put_failure; nla_nest_end(skb, vf); } nla_nest_end(skb, vfinfo); } if (rtnl_port_fill(skb, dev)) goto nla_put_failure; if (dev->rtnl_link_ops) { if (rtnl_link_fill(skb, dev) < 0) goto nla_put_failure; } if (!(af_spec = nla_nest_start(skb, IFLA_AF_SPEC))) goto nla_put_failure; list_for_each_entry(af_ops, &rtnl_af_ops, list) { if (af_ops->fill_link_af) { struct nlattr *af; int err; if (!(af = nla_nest_start(skb, af_ops->family))) goto nla_put_failure; err = af_ops->fill_link_af(skb, dev); /* * Caller may return ENODATA to indicate that there * was no data to be dumped. This is not an error, it * means we should trim the attribute header and * continue. */ if (err == -ENODATA) nla_nest_cancel(skb, af); else if (err < 0) goto nla_put_failure; nla_nest_end(skb, af); } } nla_nest_end(skb, af_spec); return nlmsg_end(skb, nlh); nla_put_failure: nlmsg_cancel(skb, nlh); return -EMSGSIZE; }
166,056
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed 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: [email protected] Reported-by: Ben Hawkes <[email protected]> Reviewed-by: Benjamin Tissoires <[email protected]> Signed-off-by: Jiri Kosina <[email protected]> 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. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static boolean parse_identifier( const char **pcur, char *ret ) { const char *cur = *pcur; int i = 0; if (is_alpha_underscore( cur )) { ret[i++] = *cur++; while (is_alpha_underscore( cur ) || is_digit( cur )) ret[i++] = *cur++; ret[i++] = '\0'; *pcur = cur; return TRUE; /* Parse floating point. */ static boolean parse_float( const char **pcur, float *val ) { const char *cur = *pcur; boolean integral_part = FALSE; boolean fractional_part = FALSE; if (*cur == '0' && *(cur + 1) == 'x') { union fi fi; fi.ui = strtoul(cur, NULL, 16); *val = fi.f; cur += 10; goto out; } *val = (float) atof( cur ); if (*cur == '-' || *cur == '+') cur++; if (is_digit( cur )) { cur++; integral_part = TRUE; while (is_digit( cur )) cur++; } if (*cur == '.') { cur++; if (is_digit( cur )) { cur++; fractional_part = TRUE; while (is_digit( cur )) cur++; } } if (!integral_part && !fractional_part) return FALSE; if (uprcase( *cur ) == 'E') { cur++; if (*cur == '-' || *cur == '+') cur++; if (is_digit( cur )) { cur++; while (is_digit( cur )) cur++; } else return FALSE; } out: *pcur = cur; return TRUE; } static boolean parse_double( const char **pcur, uint32_t *val0, uint32_t *val1) { const char *cur = *pcur; union { double dval; uint32_t uval[2]; } v; v.dval = strtod(cur, (char**)pcur); if (*pcur == cur) return FALSE; *val0 = v.uval[0]; *val1 = v.uval[1]; return TRUE; } struct translate_ctx { const char *text; const char *cur; struct tgsi_token *tokens; struct tgsi_token *tokens_cur; struct tgsi_token *tokens_end; struct tgsi_header *header; unsigned processor : 4; unsigned implied_array_size : 6; unsigned num_immediates; }; static void report_error(struct translate_ctx *ctx, const char *format, ...) { va_list args; int line = 1; int column = 1; const char *itr = ctx->text; debug_printf("\nTGSI asm error: "); va_start(args, format); _debug_vprintf(format, args); va_end(args); while (itr != ctx->cur) { if (*itr == '\n') { column = 1; ++line; } ++column; ++itr; } debug_printf(" [%d : %d] \n", line, column); } /* Parse shader header. * Return TRUE for one of the following headers. * FRAG * GEOM * VERT */ static boolean parse_header( struct translate_ctx *ctx ) { uint processor; if (str_match_nocase_whole( &ctx->cur, "FRAG" )) processor = TGSI_PROCESSOR_FRAGMENT; else if (str_match_nocase_whole( &ctx->cur, "VERT" )) processor = TGSI_PROCESSOR_VERTEX; else if (str_match_nocase_whole( &ctx->cur, "GEOM" )) processor = TGSI_PROCESSOR_GEOMETRY; else if (str_match_nocase_whole( &ctx->cur, "TESS_CTRL" )) processor = TGSI_PROCESSOR_TESS_CTRL; else if (str_match_nocase_whole( &ctx->cur, "TESS_EVAL" )) processor = TGSI_PROCESSOR_TESS_EVAL; else if (str_match_nocase_whole( &ctx->cur, "COMP" )) processor = TGSI_PROCESSOR_COMPUTE; else { report_error( ctx, "Unknown header" ); return FALSE; } if (ctx->tokens_cur >= ctx->tokens_end) return FALSE; ctx->header = (struct tgsi_header *) ctx->tokens_cur++; *ctx->header = tgsi_build_header(); if (ctx->tokens_cur >= ctx->tokens_end) return FALSE; *(struct tgsi_processor *) ctx->tokens_cur++ = tgsi_build_processor( processor, ctx->header ); ctx->processor = processor; return TRUE; } static boolean parse_label( struct translate_ctx *ctx, uint *val ) { const char *cur = ctx->cur; if (parse_uint( &cur, val )) { eat_opt_white( &cur ); if (*cur == ':') { cur++; ctx->cur = cur; return TRUE; } } return FALSE; } static boolean parse_file( const char **pcur, uint *file ) { uint i; for (i = 0; i < TGSI_FILE_COUNT; i++) { const char *cur = *pcur; if (str_match_nocase_whole( &cur, tgsi_file_name(i) )) { *pcur = cur; *file = i; return TRUE; } } return FALSE; } static boolean parse_opt_writemask( struct translate_ctx *ctx, uint *writemask ) { const char *cur; cur = ctx->cur; eat_opt_white( &cur ); if (*cur == '.') { cur++; *writemask = TGSI_WRITEMASK_NONE; eat_opt_white( &cur ); if (uprcase( *cur ) == 'X') { cur++; *writemask |= TGSI_WRITEMASK_X; } if (uprcase( *cur ) == 'Y') { cur++; *writemask |= TGSI_WRITEMASK_Y; } if (uprcase( *cur ) == 'Z') { cur++; *writemask |= TGSI_WRITEMASK_Z; } if (uprcase( *cur ) == 'W') { cur++; *writemask |= TGSI_WRITEMASK_W; } if (*writemask == TGSI_WRITEMASK_NONE) { report_error( ctx, "Writemask expected" ); return FALSE; } ctx->cur = cur; } else { *writemask = TGSI_WRITEMASK_XYZW; } return TRUE; } /* <register_file_bracket> ::= <file> `[' */ static boolean parse_register_file_bracket( struct translate_ctx *ctx, uint *file ) { if (!parse_file( &ctx->cur, file )) { report_error( ctx, "Unknown register file" ); return FALSE; } eat_opt_white( &ctx->cur ); if (*ctx->cur != '[') { report_error( ctx, "Expected `['" ); return FALSE; } ctx->cur++; return TRUE; } /* <register_file_bracket_index> ::= <register_file_bracket> <uint> */ static boolean parse_register_file_bracket_index( struct translate_ctx *ctx, uint *file, int *index ) { uint uindex; if (!parse_register_file_bracket( ctx, file )) return FALSE; eat_opt_white( &ctx->cur ); if (!parse_uint( &ctx->cur, &uindex )) { report_error( ctx, "Expected literal unsigned integer" ); return FALSE; } *index = (int) uindex; return TRUE; } /* Parse simple 1d register operand. * <register_dst> ::= <register_file_bracket_index> `]' */ static boolean parse_register_1d(struct translate_ctx *ctx, uint *file, int *index ) { if (!parse_register_file_bracket_index( ctx, file, index )) return FALSE; eat_opt_white( &ctx->cur ); if (*ctx->cur != ']') { report_error( ctx, "Expected `]'" ); return FALSE; } ctx->cur++; return TRUE; } struct parsed_bracket { int index; uint ind_file; int ind_index; uint ind_comp; uint ind_array; }; static boolean parse_register_bracket( struct translate_ctx *ctx, struct parsed_bracket *brackets) { const char *cur; uint uindex; memset(brackets, 0, sizeof(struct parsed_bracket)); eat_opt_white( &ctx->cur ); cur = ctx->cur; if (parse_file( &cur, &brackets->ind_file )) { if (!parse_register_1d( ctx, &brackets->ind_file, &brackets->ind_index )) return FALSE; eat_opt_white( &ctx->cur ); if (*ctx->cur == '.') { ctx->cur++; eat_opt_white(&ctx->cur); switch (uprcase(*ctx->cur)) { case 'X': brackets->ind_comp = TGSI_SWIZZLE_X; break; case 'Y': brackets->ind_comp = TGSI_SWIZZLE_Y; break; case 'Z': brackets->ind_comp = TGSI_SWIZZLE_Z; break; case 'W': brackets->ind_comp = TGSI_SWIZZLE_W; break; default: report_error(ctx, "Expected indirect register swizzle component `x', `y', `z' or `w'"); return FALSE; } ctx->cur++; eat_opt_white(&ctx->cur); } if (*ctx->cur == '+' || *ctx->cur == '-') parse_int( &ctx->cur, &brackets->index ); else brackets->index = 0; } else { if (!parse_uint( &ctx->cur, &uindex )) { report_error( ctx, "Expected literal unsigned integer" ); return FALSE; } brackets->index = (int) uindex; brackets->ind_file = TGSI_FILE_NULL; brackets->ind_index = 0; } eat_opt_white( &ctx->cur ); if (*ctx->cur != ']') { report_error( ctx, "Expected `]'" ); return FALSE; } ctx->cur++; if (*ctx->cur == '(') { ctx->cur++; eat_opt_white( &ctx->cur ); if (!parse_uint( &ctx->cur, &brackets->ind_array )) { report_error( ctx, "Expected literal unsigned integer" ); return FALSE; } eat_opt_white( &ctx->cur ); if (*ctx->cur != ')') { report_error( ctx, "Expected `)'" ); return FALSE; } ctx->cur++; } return TRUE; } static boolean parse_opt_register_src_bracket( struct translate_ctx *ctx, struct parsed_bracket *brackets, int *parsed_brackets) { const char *cur = ctx->cur; *parsed_brackets = 0; eat_opt_white( &cur ); if (cur[0] == '[') { ++cur; ctx->cur = cur; if (!parse_register_bracket(ctx, brackets)) return FALSE; *parsed_brackets = 1; } return TRUE; } /* Parse source register operand. * <register_src> ::= <register_file_bracket_index> `]' | * <register_file_bracket> <register_dst> [`.' (`x' | `y' | `z' | `w')] `]' | * <register_file_bracket> <register_dst> [`.' (`x' | `y' | `z' | `w')] `+' <uint> `]' | * <register_file_bracket> <register_dst> [`.' (`x' | `y' | `z' | `w')] `-' <uint> `]' */ static boolean parse_register_src( struct translate_ctx *ctx, uint *file, struct parsed_bracket *brackets) { brackets->ind_comp = TGSI_SWIZZLE_X; if (!parse_register_file_bracket( ctx, file )) return FALSE; if (!parse_register_bracket( ctx, brackets )) return FALSE; return TRUE; } struct parsed_dcl_bracket { uint first; uint last; }; static boolean parse_register_dcl_bracket( struct translate_ctx *ctx, struct parsed_dcl_bracket *bracket) { uint uindex; memset(bracket, 0, sizeof(struct parsed_dcl_bracket)); eat_opt_white( &ctx->cur ); if (!parse_uint( &ctx->cur, &uindex )) { /* it can be an empty bracket [] which means its range * is from 0 to some implied size */ if (ctx->cur[0] == ']' && ctx->implied_array_size != 0) { bracket->first = 0; bracket->last = ctx->implied_array_size - 1; goto cleanup; } report_error( ctx, "Expected literal unsigned integer" ); return FALSE; } bracket->first = uindex; eat_opt_white( &ctx->cur ); if (ctx->cur[0] == '.' && ctx->cur[1] == '.') { uint uindex; ctx->cur += 2; eat_opt_white( &ctx->cur ); if (!parse_uint( &ctx->cur, &uindex )) { report_error( ctx, "Expected literal integer" ); return FALSE; } bracket->last = (int) uindex; eat_opt_white( &ctx->cur ); } else { bracket->last = bracket->first; } cleanup: if (*ctx->cur != ']') { report_error( ctx, "Expected `]' or `..'" ); return FALSE; } ctx->cur++; return TRUE; } /* Parse register declaration. * <register_dcl> ::= <register_file_bracket_index> `]' | * <register_file_bracket_index> `..' <index> `]' */ static boolean parse_register_dcl( struct translate_ctx *ctx, uint *file, struct parsed_dcl_bracket *brackets, int *num_brackets) { const char *cur; *num_brackets = 0; if (!parse_register_file_bracket( ctx, file )) return FALSE; if (!parse_register_dcl_bracket( ctx, &brackets[0] )) return FALSE; *num_brackets = 1; cur = ctx->cur; eat_opt_white( &cur ); if (cur[0] == '[') { bool is_in = *file == TGSI_FILE_INPUT; bool is_out = *file == TGSI_FILE_OUTPUT; ++cur; ctx->cur = cur; if (!parse_register_dcl_bracket( ctx, &brackets[1] )) return FALSE; /* for geometry shader we don't really care about * the first brackets it's always the size of the * input primitive. so we want to declare just * the index relevant to the semantics which is in * the second bracket */ /* tessellation has similar constraints to geometry shader */ if ((ctx->processor == TGSI_PROCESSOR_GEOMETRY && is_in) || (ctx->processor == TGSI_PROCESSOR_TESS_EVAL && is_in) || (ctx->processor == TGSI_PROCESSOR_TESS_CTRL && (is_in || is_out))) { brackets[0] = brackets[1]; *num_brackets = 1; } else { *num_brackets = 2; } } return TRUE; } /* Parse destination register operand.*/ static boolean parse_register_dst( struct translate_ctx *ctx, uint *file, struct parsed_bracket *brackets) { brackets->ind_comp = TGSI_SWIZZLE_X; if (!parse_register_file_bracket( ctx, file )) return FALSE; if (!parse_register_bracket( ctx, brackets )) return FALSE; return TRUE; } static boolean parse_dst_operand( struct translate_ctx *ctx, struct tgsi_full_dst_register *dst ) { uint file; uint writemask; const char *cur; struct parsed_bracket bracket[2]; int parsed_opt_brackets; if (!parse_register_dst( ctx, &file, &bracket[0] )) return FALSE; if (!parse_opt_register_src_bracket(ctx, &bracket[1], &parsed_opt_brackets)) return FALSE; cur = ctx->cur; eat_opt_white( &cur ); if (!parse_opt_writemask( ctx, &writemask )) return FALSE; dst->Register.File = file; if (parsed_opt_brackets) { dst->Register.Dimension = 1; dst->Dimension.Indirect = 0; dst->Dimension.Dimension = 0; dst->Dimension.Index = bracket[0].index; if (bracket[0].ind_file != TGSI_FILE_NULL) { dst->Dimension.Indirect = 1; dst->DimIndirect.File = bracket[0].ind_file; dst->DimIndirect.Index = bracket[0].ind_index; dst->DimIndirect.Swizzle = bracket[0].ind_comp; dst->DimIndirect.ArrayID = bracket[0].ind_array; } bracket[0] = bracket[1]; } dst->Register.Index = bracket[0].index; dst->Register.WriteMask = writemask; if (bracket[0].ind_file != TGSI_FILE_NULL) { dst->Register.Indirect = 1; dst->Indirect.File = bracket[0].ind_file; dst->Indirect.Index = bracket[0].ind_index; dst->Indirect.Swizzle = bracket[0].ind_comp; dst->Indirect.ArrayID = bracket[0].ind_array; } return TRUE; } static boolean parse_optional_swizzle( struct translate_ctx *ctx, uint *swizzle, boolean *parsed_swizzle, int components) { const char *cur = ctx->cur; *parsed_swizzle = FALSE; eat_opt_white( &cur ); if (*cur == '.') { uint i; cur++; eat_opt_white( &cur ); for (i = 0; i < components; i++) { if (uprcase( *cur ) == 'X') swizzle[i] = TGSI_SWIZZLE_X; else if (uprcase( *cur ) == 'Y') swizzle[i] = TGSI_SWIZZLE_Y; else if (uprcase( *cur ) == 'Z') swizzle[i] = TGSI_SWIZZLE_Z; else if (uprcase( *cur ) == 'W') swizzle[i] = TGSI_SWIZZLE_W; else { report_error( ctx, "Expected register swizzle component `x', `y', `z' or `w'" ); return FALSE; } cur++; } *parsed_swizzle = TRUE; ctx->cur = cur; } return TRUE; } static boolean parse_src_operand( struct translate_ctx *ctx, struct tgsi_full_src_register *src ) { uint file; uint swizzle[4]; boolean parsed_swizzle; struct parsed_bracket bracket[2]; int parsed_opt_brackets; if (*ctx->cur == '-') { ctx->cur++; eat_opt_white( &ctx->cur ); src->Register.Negate = 1; } if (*ctx->cur == '|') { ctx->cur++; eat_opt_white( &ctx->cur ); src->Register.Absolute = 1; } if (!parse_register_src(ctx, &file, &bracket[0])) return FALSE; if (!parse_opt_register_src_bracket(ctx, &bracket[1], &parsed_opt_brackets)) return FALSE; src->Register.File = file; if (parsed_opt_brackets) { src->Register.Dimension = 1; src->Dimension.Indirect = 0; src->Dimension.Dimension = 0; src->Dimension.Index = bracket[0].index; if (bracket[0].ind_file != TGSI_FILE_NULL) { src->Dimension.Indirect = 1; src->DimIndirect.File = bracket[0].ind_file; src->DimIndirect.Index = bracket[0].ind_index; src->DimIndirect.Swizzle = bracket[0].ind_comp; src->DimIndirect.ArrayID = bracket[0].ind_array; } bracket[0] = bracket[1]; } src->Register.Index = bracket[0].index; if (bracket[0].ind_file != TGSI_FILE_NULL) { src->Register.Indirect = 1; src->Indirect.File = bracket[0].ind_file; src->Indirect.Index = bracket[0].ind_index; src->Indirect.Swizzle = bracket[0].ind_comp; src->Indirect.ArrayID = bracket[0].ind_array; } /* Parse optional swizzle. */ if (parse_optional_swizzle( ctx, swizzle, &parsed_swizzle, 4 )) { if (parsed_swizzle) { src->Register.SwizzleX = swizzle[0]; src->Register.SwizzleY = swizzle[1]; src->Register.SwizzleZ = swizzle[2]; src->Register.SwizzleW = swizzle[3]; } } if (src->Register.Absolute) { eat_opt_white( &ctx->cur ); if (*ctx->cur != '|') { report_error( ctx, "Expected `|'" ); return FALSE; } ctx->cur++; } return TRUE; } static boolean parse_texoffset_operand( struct translate_ctx *ctx, struct tgsi_texture_offset *src ) { uint file; uint swizzle[3]; boolean parsed_swizzle; struct parsed_bracket bracket; if (!parse_register_src(ctx, &file, &bracket)) return FALSE; src->File = file; src->Index = bracket.index; /* Parse optional swizzle. */ if (parse_optional_swizzle( ctx, swizzle, &parsed_swizzle, 3 )) { if (parsed_swizzle) { src->SwizzleX = swizzle[0]; src->SwizzleY = swizzle[1]; src->SwizzleZ = swizzle[2]; } } return TRUE; } static boolean match_inst(const char **pcur, unsigned *saturate, const struct tgsi_opcode_info *info) { const char *cur = *pcur; /* simple case: the whole string matches the instruction name */ if (str_match_nocase_whole(&cur, info->mnemonic)) { *pcur = cur; *saturate = 0; return TRUE; } if (str_match_no_case(&cur, info->mnemonic)) { /* the instruction has a suffix, figure it out */ if (str_match_nocase_whole(&cur, "_SAT")) { *pcur = cur; *saturate = 1; return TRUE; } } return FALSE; } static boolean parse_instruction( struct translate_ctx *ctx, boolean has_label ) { uint i; uint saturate = 0; const struct tgsi_opcode_info *info; struct tgsi_full_instruction inst; const char *cur; uint advance; inst = tgsi_default_full_instruction(); /* Parse predicate. */ eat_opt_white( &ctx->cur ); if (*ctx->cur == '(') { uint file; int index; uint swizzle[4]; boolean parsed_swizzle; inst.Instruction.Predicate = 1; ctx->cur++; if (*ctx->cur == '!') { ctx->cur++; inst.Predicate.Negate = 1; } if (!parse_register_1d( ctx, &file, &index )) return FALSE; if (parse_optional_swizzle( ctx, swizzle, &parsed_swizzle, 4 )) { if (parsed_swizzle) { inst.Predicate.SwizzleX = swizzle[0]; inst.Predicate.SwizzleY = swizzle[1]; inst.Predicate.SwizzleZ = swizzle[2]; inst.Predicate.SwizzleW = swizzle[3]; } } if (*ctx->cur != ')') { report_error( ctx, "Expected `)'" ); return FALSE; } ctx->cur++; } /* Parse instruction name. */ eat_opt_white( &ctx->cur ); for (i = 0; i < TGSI_OPCODE_LAST; i++) { cur = ctx->cur; info = tgsi_get_opcode_info( i ); if (match_inst(&cur, &saturate, info)) { if (info->num_dst + info->num_src + info->is_tex == 0) { ctx->cur = cur; break; } else if (*cur == '\0' || eat_white( &cur )) { ctx->cur = cur; break; } } } if (i == TGSI_OPCODE_LAST) { if (has_label) report_error( ctx, "Unknown opcode" ); else report_error( ctx, "Expected `DCL', `IMM' or a label" ); return FALSE; } inst.Instruction.Opcode = i; inst.Instruction.Saturate = saturate; inst.Instruction.NumDstRegs = info->num_dst; inst.Instruction.NumSrcRegs = info->num_src; if (i >= TGSI_OPCODE_SAMPLE && i <= TGSI_OPCODE_GATHER4) { /* * These are not considered tex opcodes here (no additional * target argument) however we're required to set the Texture * bit so we can set the number of tex offsets. */ inst.Instruction.Texture = 1; inst.Texture.Texture = TGSI_TEXTURE_UNKNOWN; } /* Parse instruction operands. */ for (i = 0; i < info->num_dst + info->num_src + info->is_tex; i++) { if (i > 0) { eat_opt_white( &ctx->cur ); if (*ctx->cur != ',') { report_error( ctx, "Expected `,'" ); return FALSE; } ctx->cur++; eat_opt_white( &ctx->cur ); } if (i < info->num_dst) { if (!parse_dst_operand( ctx, &inst.Dst[i] )) return FALSE; } else if (i < info->num_dst + info->num_src) { if (!parse_src_operand( ctx, &inst.Src[i - info->num_dst] )) return FALSE; } else { uint j; for (j = 0; j < TGSI_TEXTURE_COUNT; j++) { if (str_match_nocase_whole( &ctx->cur, tgsi_texture_names[j] )) { inst.Instruction.Texture = 1; inst.Texture.Texture = j; break; } } if (j == TGSI_TEXTURE_COUNT) { report_error( ctx, "Expected texture target" ); return FALSE; } } } cur = ctx->cur; eat_opt_white( &cur ); for (i = 0; inst.Instruction.Texture && *cur == ','; i++) { cur++; eat_opt_white( &cur ); ctx->cur = cur; if (!parse_texoffset_operand( ctx, &inst.TexOffsets[i] )) return FALSE; cur = ctx->cur; eat_opt_white( &cur ); } inst.Texture.NumOffsets = i; cur = ctx->cur; eat_opt_white( &cur ); if (info->is_branch && *cur == ':') { uint target; cur++; eat_opt_white( &cur ); if (!parse_uint( &cur, &target )) { report_error( ctx, "Expected a label" ); return FALSE; } inst.Instruction.Label = 1; inst.Label.Label = target; ctx->cur = cur; } advance = tgsi_build_full_instruction( &inst, ctx->tokens_cur, ctx->header, (uint) (ctx->tokens_end - ctx->tokens_cur) ); if (advance == 0) return FALSE; ctx->tokens_cur += advance; return TRUE; } /* parses a 4-touple of the form {x, y, z, w} * where x, y, z, w are numbers */ static boolean parse_immediate_data(struct translate_ctx *ctx, unsigned type, union tgsi_immediate_data *values) { unsigned i; int ret; eat_opt_white( &ctx->cur ); if (*ctx->cur != '{') { report_error( ctx, "Expected `{'" ); return FALSE; } ctx->cur++; for (i = 0; i < 4; i++) { eat_opt_white( &ctx->cur ); if (i > 0) { if (*ctx->cur != ',') { report_error( ctx, "Expected `,'" ); return FALSE; } ctx->cur++; eat_opt_white( &ctx->cur ); } switch (type) { case TGSI_IMM_FLOAT64: ret = parse_double(&ctx->cur, &values[i].Uint, &values[i+1].Uint); i++; break; case TGSI_IMM_FLOAT32: ret = parse_float(&ctx->cur, &values[i].Float); break; case TGSI_IMM_UINT32: ret = parse_uint(&ctx->cur, &values[i].Uint); break; case TGSI_IMM_INT32: ret = parse_int(&ctx->cur, &values[i].Int); break; default: assert(0); ret = FALSE; break; } if (!ret) { report_error( ctx, "Expected immediate constant" ); return FALSE; } } eat_opt_white( &ctx->cur ); if (*ctx->cur != '}') { report_error( ctx, "Expected `}'" ); return FALSE; } ctx->cur++; return TRUE; } static boolean parse_declaration( struct translate_ctx *ctx ) { struct tgsi_full_declaration decl; uint file; struct parsed_dcl_bracket brackets[2]; int num_brackets; uint writemask; const char *cur, *cur2; uint advance; boolean is_vs_input; if (!eat_white( &ctx->cur )) { report_error( ctx, "Syntax error" ); return FALSE; } if (!parse_register_dcl( ctx, &file, brackets, &num_brackets)) return FALSE; if (!parse_opt_writemask( ctx, &writemask )) return FALSE; decl = tgsi_default_full_declaration(); decl.Declaration.File = file; decl.Declaration.UsageMask = writemask; if (num_brackets == 1) { decl.Range.First = brackets[0].first; decl.Range.Last = brackets[0].last; } else { decl.Range.First = brackets[1].first; decl.Range.Last = brackets[1].last; decl.Declaration.Dimension = 1; decl.Dim.Index2D = brackets[0].first; } is_vs_input = (file == TGSI_FILE_INPUT && ctx->processor == TGSI_PROCESSOR_VERTEX); cur = ctx->cur; eat_opt_white( &cur ); if (*cur == ',') { cur2 = cur; cur2++; eat_opt_white( &cur2 ); if (str_match_nocase_whole( &cur2, "ARRAY" )) { int arrayid; if (*cur2 != '(') { report_error( ctx, "Expected `('" ); return FALSE; } cur2++; eat_opt_white( &cur2 ); if (!parse_int( &cur2, &arrayid )) { report_error( ctx, "Expected `,'" ); return FALSE; } eat_opt_white( &cur2 ); if (*cur2 != ')') { report_error( ctx, "Expected `)'" ); return FALSE; } cur2++; decl.Declaration.Array = 1; decl.Array.ArrayID = arrayid; ctx->cur = cur = cur2; } } if (*cur == ',' && !is_vs_input) { uint i, j; cur++; eat_opt_white( &cur ); if (file == TGSI_FILE_RESOURCE) { for (i = 0; i < TGSI_TEXTURE_COUNT; i++) { if (str_match_nocase_whole(&cur, tgsi_texture_names[i])) { decl.Resource.Resource = i; break; } } if (i == TGSI_TEXTURE_COUNT) { report_error(ctx, "Expected texture target"); return FALSE; } cur2 = cur; eat_opt_white(&cur2); while (*cur2 == ',') { cur2++; eat_opt_white(&cur2); if (str_match_nocase_whole(&cur2, "RAW")) { decl.Resource.Raw = 1; } else if (str_match_nocase_whole(&cur2, "WR")) { decl.Resource.Writable = 1; } else { break; } cur = cur2; eat_opt_white(&cur2); } ctx->cur = cur; } else if (file == TGSI_FILE_SAMPLER_VIEW) { for (i = 0; i < TGSI_TEXTURE_COUNT; i++) { if (str_match_nocase_whole(&cur, tgsi_texture_names[i])) { decl.SamplerView.Resource = i; break; } } if (i == TGSI_TEXTURE_COUNT) { report_error(ctx, "Expected texture target"); return FALSE; } eat_opt_white( &cur ); if (*cur != ',') { report_error( ctx, "Expected `,'" ); return FALSE; } ++cur; eat_opt_white( &cur ); for (j = 0; j < 4; ++j) { for (i = 0; i < TGSI_RETURN_TYPE_COUNT; ++i) { if (str_match_nocase_whole(&cur, tgsi_return_type_names[i])) { switch (j) { case 0: decl.SamplerView.ReturnTypeX = i; break; case 1: decl.SamplerView.ReturnTypeY = i; break; case 2: decl.SamplerView.ReturnTypeZ = i; break; case 3: decl.SamplerView.ReturnTypeW = i; break; default: assert(0); } break; } } if (i == TGSI_RETURN_TYPE_COUNT) { if (j == 0 || j > 2) { report_error(ctx, "Expected type name"); return FALSE; } break; } else { cur2 = cur; eat_opt_white( &cur2 ); if (*cur2 == ',') { cur2++; eat_opt_white( &cur2 ); cur = cur2; continue; } else break; } } if (j < 4) { decl.SamplerView.ReturnTypeY = decl.SamplerView.ReturnTypeZ = decl.SamplerView.ReturnTypeW = decl.SamplerView.ReturnTypeX; } ctx->cur = cur; } else { if (str_match_nocase_whole(&cur, "LOCAL")) { decl.Declaration.Local = 1; ctx->cur = cur; } cur = ctx->cur; eat_opt_white( &cur ); if (*cur == ',') { cur++; eat_opt_white( &cur ); for (i = 0; i < TGSI_SEMANTIC_COUNT; i++) { if (str_match_nocase_whole(&cur, tgsi_semantic_names[i])) { uint index; cur2 = cur; eat_opt_white( &cur2 ); if (*cur2 == '[') { cur2++; eat_opt_white( &cur2 ); if (!parse_uint( &cur2, &index )) { report_error( ctx, "Expected literal integer" ); return FALSE; } eat_opt_white( &cur2 ); if (*cur2 != ']') { report_error( ctx, "Expected `]'" ); return FALSE; } cur2++; decl.Semantic.Index = index; cur = cur2; } decl.Declaration.Semantic = 1; decl.Semantic.Name = i; ctx->cur = cur; break; } } } } } cur = ctx->cur; eat_opt_white( &cur ); if (*cur == ',' && !is_vs_input) { uint i; cur++; eat_opt_white( &cur ); for (i = 0; i < TGSI_INTERPOLATE_COUNT; i++) { if (str_match_nocase_whole( &cur, tgsi_interpolate_names[i] )) { decl.Declaration.Interpolate = 1; decl.Interp.Interpolate = i; ctx->cur = cur; break; } } if (i == TGSI_INTERPOLATE_COUNT) { report_error( ctx, "Expected semantic or interpolate attribute" ); return FALSE; } } cur = ctx->cur; eat_opt_white( &cur ); if (*cur == ',' && !is_vs_input) { uint i; cur++; eat_opt_white( &cur ); for (i = 0; i < TGSI_INTERPOLATE_LOC_COUNT; i++) { if (str_match_nocase_whole( &cur, tgsi_interpolate_locations[i] )) { decl.Interp.Location = i; ctx->cur = cur; break; } } } advance = tgsi_build_full_declaration( &decl, ctx->tokens_cur, ctx->header, (uint) (ctx->tokens_end - ctx->tokens_cur) ); if (advance == 0) return FALSE; ctx->tokens_cur += advance; return TRUE; } static boolean parse_immediate( struct translate_ctx *ctx ) { struct tgsi_full_immediate imm; uint advance; int type; if (*ctx->cur == '[') { uint uindex; ++ctx->cur; eat_opt_white( &ctx->cur ); if (!parse_uint( &ctx->cur, &uindex )) { report_error( ctx, "Expected literal unsigned integer" ); return FALSE; } if (uindex != ctx->num_immediates) { report_error( ctx, "Immediates must be sorted" ); return FALSE; } eat_opt_white( &ctx->cur ); if (*ctx->cur != ']') { report_error( ctx, "Expected `]'" ); return FALSE; } ctx->cur++; } if (!eat_white( &ctx->cur )) { report_error( ctx, "Syntax error" ); return FALSE; } for (type = 0; type < Elements(tgsi_immediate_type_names); ++type) { if (str_match_nocase_whole(&ctx->cur, tgsi_immediate_type_names[type])) break; } if (type == Elements(tgsi_immediate_type_names)) { report_error( ctx, "Expected immediate type" ); return FALSE; } imm = tgsi_default_full_immediate(); imm.Immediate.NrTokens += 4; imm.Immediate.DataType = type; parse_immediate_data(ctx, type, imm.u); advance = tgsi_build_full_immediate( &imm, ctx->tokens_cur, ctx->header, (uint) (ctx->tokens_end - ctx->tokens_cur) ); if (advance == 0) return FALSE; ctx->tokens_cur += advance; ctx->num_immediates++; return TRUE; } static boolean parse_primitive( const char **pcur, uint *primitive ) { uint i; for (i = 0; i < PIPE_PRIM_MAX; i++) { const char *cur = *pcur; if (str_match_nocase_whole( &cur, tgsi_primitive_names[i])) { *primitive = i; *pcur = cur; return TRUE; } } return FALSE; } static boolean parse_fs_coord_origin( const char **pcur, uint *fs_coord_origin ) { uint i; for (i = 0; i < Elements(tgsi_fs_coord_origin_names); i++) { const char *cur = *pcur; if (str_match_nocase_whole( &cur, tgsi_fs_coord_origin_names[i])) { *fs_coord_origin = i; *pcur = cur; return TRUE; } } return FALSE; } static boolean parse_fs_coord_pixel_center( const char **pcur, uint *fs_coord_pixel_center ) { uint i; for (i = 0; i < Elements(tgsi_fs_coord_pixel_center_names); i++) { const char *cur = *pcur; if (str_match_nocase_whole( &cur, tgsi_fs_coord_pixel_center_names[i])) { *fs_coord_pixel_center = i; *pcur = cur; return TRUE; } } return FALSE; } static boolean parse_property( struct translate_ctx *ctx ) { struct tgsi_full_property prop; uint property_name; uint values[8]; uint advance; char id[64]; if (!eat_white( &ctx->cur )) { report_error( ctx, "Syntax error" ); return FALSE; } report_error( ctx, "Syntax error" ); return FALSE; } if (!parse_identifier( &ctx->cur, id )) { report_error( ctx, "Syntax error" ); return FALSE; } break; } } Commit Message: CWE ID: CWE-119
static boolean parse_identifier( const char **pcur, char *ret ) static boolean parse_identifier( const char **pcur, char *ret, size_t len ) { const char *cur = *pcur; int i = 0; if (is_alpha_underscore( cur )) { ret[i++] = *cur++; while (is_alpha_underscore( cur ) || is_digit( cur )) { if (i == len - 1) return FALSE; ret[i++] = *cur++; } ret[i++] = '\0'; *pcur = cur; return TRUE; /* Parse floating point. */ static boolean parse_float( const char **pcur, float *val ) { const char *cur = *pcur; boolean integral_part = FALSE; boolean fractional_part = FALSE; if (*cur == '0' && *(cur + 1) == 'x') { union fi fi; fi.ui = strtoul(cur, NULL, 16); *val = fi.f; cur += 10; goto out; } *val = (float) atof( cur ); if (*cur == '-' || *cur == '+') cur++; if (is_digit( cur )) { cur++; integral_part = TRUE; while (is_digit( cur )) cur++; } if (*cur == '.') { cur++; if (is_digit( cur )) { cur++; fractional_part = TRUE; while (is_digit( cur )) cur++; } } if (!integral_part && !fractional_part) return FALSE; if (uprcase( *cur ) == 'E') { cur++; if (*cur == '-' || *cur == '+') cur++; if (is_digit( cur )) { cur++; while (is_digit( cur )) cur++; } else return FALSE; } out: *pcur = cur; return TRUE; } static boolean parse_double( const char **pcur, uint32_t *val0, uint32_t *val1) { const char *cur = *pcur; union { double dval; uint32_t uval[2]; } v; v.dval = strtod(cur, (char**)pcur); if (*pcur == cur) return FALSE; *val0 = v.uval[0]; *val1 = v.uval[1]; return TRUE; } struct translate_ctx { const char *text; const char *cur; struct tgsi_token *tokens; struct tgsi_token *tokens_cur; struct tgsi_token *tokens_end; struct tgsi_header *header; unsigned processor : 4; unsigned implied_array_size : 6; unsigned num_immediates; }; static void report_error(struct translate_ctx *ctx, const char *format, ...) { va_list args; int line = 1; int column = 1; const char *itr = ctx->text; debug_printf("\nTGSI asm error: "); va_start(args, format); _debug_vprintf(format, args); va_end(args); while (itr != ctx->cur) { if (*itr == '\n') { column = 1; ++line; } ++column; ++itr; } debug_printf(" [%d : %d] \n", line, column); } /* Parse shader header. * Return TRUE for one of the following headers. * FRAG * GEOM * VERT */ static boolean parse_header( struct translate_ctx *ctx ) { uint processor; if (str_match_nocase_whole( &ctx->cur, "FRAG" )) processor = TGSI_PROCESSOR_FRAGMENT; else if (str_match_nocase_whole( &ctx->cur, "VERT" )) processor = TGSI_PROCESSOR_VERTEX; else if (str_match_nocase_whole( &ctx->cur, "GEOM" )) processor = TGSI_PROCESSOR_GEOMETRY; else if (str_match_nocase_whole( &ctx->cur, "TESS_CTRL" )) processor = TGSI_PROCESSOR_TESS_CTRL; else if (str_match_nocase_whole( &ctx->cur, "TESS_EVAL" )) processor = TGSI_PROCESSOR_TESS_EVAL; else if (str_match_nocase_whole( &ctx->cur, "COMP" )) processor = TGSI_PROCESSOR_COMPUTE; else { report_error( ctx, "Unknown header" ); return FALSE; } if (ctx->tokens_cur >= ctx->tokens_end) return FALSE; ctx->header = (struct tgsi_header *) ctx->tokens_cur++; *ctx->header = tgsi_build_header(); if (ctx->tokens_cur >= ctx->tokens_end) return FALSE; *(struct tgsi_processor *) ctx->tokens_cur++ = tgsi_build_processor( processor, ctx->header ); ctx->processor = processor; return TRUE; } static boolean parse_label( struct translate_ctx *ctx, uint *val ) { const char *cur = ctx->cur; if (parse_uint( &cur, val )) { eat_opt_white( &cur ); if (*cur == ':') { cur++; ctx->cur = cur; return TRUE; } } return FALSE; } static boolean parse_file( const char **pcur, uint *file ) { uint i; for (i = 0; i < TGSI_FILE_COUNT; i++) { const char *cur = *pcur; if (str_match_nocase_whole( &cur, tgsi_file_name(i) )) { *pcur = cur; *file = i; return TRUE; } } return FALSE; } static boolean parse_opt_writemask( struct translate_ctx *ctx, uint *writemask ) { const char *cur; cur = ctx->cur; eat_opt_white( &cur ); if (*cur == '.') { cur++; *writemask = TGSI_WRITEMASK_NONE; eat_opt_white( &cur ); if (uprcase( *cur ) == 'X') { cur++; *writemask |= TGSI_WRITEMASK_X; } if (uprcase( *cur ) == 'Y') { cur++; *writemask |= TGSI_WRITEMASK_Y; } if (uprcase( *cur ) == 'Z') { cur++; *writemask |= TGSI_WRITEMASK_Z; } if (uprcase( *cur ) == 'W') { cur++; *writemask |= TGSI_WRITEMASK_W; } if (*writemask == TGSI_WRITEMASK_NONE) { report_error( ctx, "Writemask expected" ); return FALSE; } ctx->cur = cur; } else { *writemask = TGSI_WRITEMASK_XYZW; } return TRUE; } /* <register_file_bracket> ::= <file> `[' */ static boolean parse_register_file_bracket( struct translate_ctx *ctx, uint *file ) { if (!parse_file( &ctx->cur, file )) { report_error( ctx, "Unknown register file" ); return FALSE; } eat_opt_white( &ctx->cur ); if (*ctx->cur != '[') { report_error( ctx, "Expected `['" ); return FALSE; } ctx->cur++; return TRUE; } /* <register_file_bracket_index> ::= <register_file_bracket> <uint> */ static boolean parse_register_file_bracket_index( struct translate_ctx *ctx, uint *file, int *index ) { uint uindex; if (!parse_register_file_bracket( ctx, file )) return FALSE; eat_opt_white( &ctx->cur ); if (!parse_uint( &ctx->cur, &uindex )) { report_error( ctx, "Expected literal unsigned integer" ); return FALSE; } *index = (int) uindex; return TRUE; } /* Parse simple 1d register operand. * <register_dst> ::= <register_file_bracket_index> `]' */ static boolean parse_register_1d(struct translate_ctx *ctx, uint *file, int *index ) { if (!parse_register_file_bracket_index( ctx, file, index )) return FALSE; eat_opt_white( &ctx->cur ); if (*ctx->cur != ']') { report_error( ctx, "Expected `]'" ); return FALSE; } ctx->cur++; return TRUE; } struct parsed_bracket { int index; uint ind_file; int ind_index; uint ind_comp; uint ind_array; }; static boolean parse_register_bracket( struct translate_ctx *ctx, struct parsed_bracket *brackets) { const char *cur; uint uindex; memset(brackets, 0, sizeof(struct parsed_bracket)); eat_opt_white( &ctx->cur ); cur = ctx->cur; if (parse_file( &cur, &brackets->ind_file )) { if (!parse_register_1d( ctx, &brackets->ind_file, &brackets->ind_index )) return FALSE; eat_opt_white( &ctx->cur ); if (*ctx->cur == '.') { ctx->cur++; eat_opt_white(&ctx->cur); switch (uprcase(*ctx->cur)) { case 'X': brackets->ind_comp = TGSI_SWIZZLE_X; break; case 'Y': brackets->ind_comp = TGSI_SWIZZLE_Y; break; case 'Z': brackets->ind_comp = TGSI_SWIZZLE_Z; break; case 'W': brackets->ind_comp = TGSI_SWIZZLE_W; break; default: report_error(ctx, "Expected indirect register swizzle component `x', `y', `z' or `w'"); return FALSE; } ctx->cur++; eat_opt_white(&ctx->cur); } if (*ctx->cur == '+' || *ctx->cur == '-') parse_int( &ctx->cur, &brackets->index ); else brackets->index = 0; } else { if (!parse_uint( &ctx->cur, &uindex )) { report_error( ctx, "Expected literal unsigned integer" ); return FALSE; } brackets->index = (int) uindex; brackets->ind_file = TGSI_FILE_NULL; brackets->ind_index = 0; } eat_opt_white( &ctx->cur ); if (*ctx->cur != ']') { report_error( ctx, "Expected `]'" ); return FALSE; } ctx->cur++; if (*ctx->cur == '(') { ctx->cur++; eat_opt_white( &ctx->cur ); if (!parse_uint( &ctx->cur, &brackets->ind_array )) { report_error( ctx, "Expected literal unsigned integer" ); return FALSE; } eat_opt_white( &ctx->cur ); if (*ctx->cur != ')') { report_error( ctx, "Expected `)'" ); return FALSE; } ctx->cur++; } return TRUE; } static boolean parse_opt_register_src_bracket( struct translate_ctx *ctx, struct parsed_bracket *brackets, int *parsed_brackets) { const char *cur = ctx->cur; *parsed_brackets = 0; eat_opt_white( &cur ); if (cur[0] == '[') { ++cur; ctx->cur = cur; if (!parse_register_bracket(ctx, brackets)) return FALSE; *parsed_brackets = 1; } return TRUE; } /* Parse source register operand. * <register_src> ::= <register_file_bracket_index> `]' | * <register_file_bracket> <register_dst> [`.' (`x' | `y' | `z' | `w')] `]' | * <register_file_bracket> <register_dst> [`.' (`x' | `y' | `z' | `w')] `+' <uint> `]' | * <register_file_bracket> <register_dst> [`.' (`x' | `y' | `z' | `w')] `-' <uint> `]' */ static boolean parse_register_src( struct translate_ctx *ctx, uint *file, struct parsed_bracket *brackets) { brackets->ind_comp = TGSI_SWIZZLE_X; if (!parse_register_file_bracket( ctx, file )) return FALSE; if (!parse_register_bracket( ctx, brackets )) return FALSE; return TRUE; } struct parsed_dcl_bracket { uint first; uint last; }; static boolean parse_register_dcl_bracket( struct translate_ctx *ctx, struct parsed_dcl_bracket *bracket) { uint uindex; memset(bracket, 0, sizeof(struct parsed_dcl_bracket)); eat_opt_white( &ctx->cur ); if (!parse_uint( &ctx->cur, &uindex )) { /* it can be an empty bracket [] which means its range * is from 0 to some implied size */ if (ctx->cur[0] == ']' && ctx->implied_array_size != 0) { bracket->first = 0; bracket->last = ctx->implied_array_size - 1; goto cleanup; } report_error( ctx, "Expected literal unsigned integer" ); return FALSE; } bracket->first = uindex; eat_opt_white( &ctx->cur ); if (ctx->cur[0] == '.' && ctx->cur[1] == '.') { uint uindex; ctx->cur += 2; eat_opt_white( &ctx->cur ); if (!parse_uint( &ctx->cur, &uindex )) { report_error( ctx, "Expected literal integer" ); return FALSE; } bracket->last = (int) uindex; eat_opt_white( &ctx->cur ); } else { bracket->last = bracket->first; } cleanup: if (*ctx->cur != ']') { report_error( ctx, "Expected `]' or `..'" ); return FALSE; } ctx->cur++; return TRUE; } /* Parse register declaration. * <register_dcl> ::= <register_file_bracket_index> `]' | * <register_file_bracket_index> `..' <index> `]' */ static boolean parse_register_dcl( struct translate_ctx *ctx, uint *file, struct parsed_dcl_bracket *brackets, int *num_brackets) { const char *cur; *num_brackets = 0; if (!parse_register_file_bracket( ctx, file )) return FALSE; if (!parse_register_dcl_bracket( ctx, &brackets[0] )) return FALSE; *num_brackets = 1; cur = ctx->cur; eat_opt_white( &cur ); if (cur[0] == '[') { bool is_in = *file == TGSI_FILE_INPUT; bool is_out = *file == TGSI_FILE_OUTPUT; ++cur; ctx->cur = cur; if (!parse_register_dcl_bracket( ctx, &brackets[1] )) return FALSE; /* for geometry shader we don't really care about * the first brackets it's always the size of the * input primitive. so we want to declare just * the index relevant to the semantics which is in * the second bracket */ /* tessellation has similar constraints to geometry shader */ if ((ctx->processor == TGSI_PROCESSOR_GEOMETRY && is_in) || (ctx->processor == TGSI_PROCESSOR_TESS_EVAL && is_in) || (ctx->processor == TGSI_PROCESSOR_TESS_CTRL && (is_in || is_out))) { brackets[0] = brackets[1]; *num_brackets = 1; } else { *num_brackets = 2; } } return TRUE; } /* Parse destination register operand.*/ static boolean parse_register_dst( struct translate_ctx *ctx, uint *file, struct parsed_bracket *brackets) { brackets->ind_comp = TGSI_SWIZZLE_X; if (!parse_register_file_bracket( ctx, file )) return FALSE; if (!parse_register_bracket( ctx, brackets )) return FALSE; return TRUE; } static boolean parse_dst_operand( struct translate_ctx *ctx, struct tgsi_full_dst_register *dst ) { uint file; uint writemask; const char *cur; struct parsed_bracket bracket[2]; int parsed_opt_brackets; if (!parse_register_dst( ctx, &file, &bracket[0] )) return FALSE; if (!parse_opt_register_src_bracket(ctx, &bracket[1], &parsed_opt_brackets)) return FALSE; cur = ctx->cur; eat_opt_white( &cur ); if (!parse_opt_writemask( ctx, &writemask )) return FALSE; dst->Register.File = file; if (parsed_opt_brackets) { dst->Register.Dimension = 1; dst->Dimension.Indirect = 0; dst->Dimension.Dimension = 0; dst->Dimension.Index = bracket[0].index; if (bracket[0].ind_file != TGSI_FILE_NULL) { dst->Dimension.Indirect = 1; dst->DimIndirect.File = bracket[0].ind_file; dst->DimIndirect.Index = bracket[0].ind_index; dst->DimIndirect.Swizzle = bracket[0].ind_comp; dst->DimIndirect.ArrayID = bracket[0].ind_array; } bracket[0] = bracket[1]; } dst->Register.Index = bracket[0].index; dst->Register.WriteMask = writemask; if (bracket[0].ind_file != TGSI_FILE_NULL) { dst->Register.Indirect = 1; dst->Indirect.File = bracket[0].ind_file; dst->Indirect.Index = bracket[0].ind_index; dst->Indirect.Swizzle = bracket[0].ind_comp; dst->Indirect.ArrayID = bracket[0].ind_array; } return TRUE; } static boolean parse_optional_swizzle( struct translate_ctx *ctx, uint *swizzle, boolean *parsed_swizzle, int components) { const char *cur = ctx->cur; *parsed_swizzle = FALSE; eat_opt_white( &cur ); if (*cur == '.') { uint i; cur++; eat_opt_white( &cur ); for (i = 0; i < components; i++) { if (uprcase( *cur ) == 'X') swizzle[i] = TGSI_SWIZZLE_X; else if (uprcase( *cur ) == 'Y') swizzle[i] = TGSI_SWIZZLE_Y; else if (uprcase( *cur ) == 'Z') swizzle[i] = TGSI_SWIZZLE_Z; else if (uprcase( *cur ) == 'W') swizzle[i] = TGSI_SWIZZLE_W; else { report_error( ctx, "Expected register swizzle component `x', `y', `z' or `w'" ); return FALSE; } cur++; } *parsed_swizzle = TRUE; ctx->cur = cur; } return TRUE; } static boolean parse_src_operand( struct translate_ctx *ctx, struct tgsi_full_src_register *src ) { uint file; uint swizzle[4]; boolean parsed_swizzle; struct parsed_bracket bracket[2]; int parsed_opt_brackets; if (*ctx->cur == '-') { ctx->cur++; eat_opt_white( &ctx->cur ); src->Register.Negate = 1; } if (*ctx->cur == '|') { ctx->cur++; eat_opt_white( &ctx->cur ); src->Register.Absolute = 1; } if (!parse_register_src(ctx, &file, &bracket[0])) return FALSE; if (!parse_opt_register_src_bracket(ctx, &bracket[1], &parsed_opt_brackets)) return FALSE; src->Register.File = file; if (parsed_opt_brackets) { src->Register.Dimension = 1; src->Dimension.Indirect = 0; src->Dimension.Dimension = 0; src->Dimension.Index = bracket[0].index; if (bracket[0].ind_file != TGSI_FILE_NULL) { src->Dimension.Indirect = 1; src->DimIndirect.File = bracket[0].ind_file; src->DimIndirect.Index = bracket[0].ind_index; src->DimIndirect.Swizzle = bracket[0].ind_comp; src->DimIndirect.ArrayID = bracket[0].ind_array; } bracket[0] = bracket[1]; } src->Register.Index = bracket[0].index; if (bracket[0].ind_file != TGSI_FILE_NULL) { src->Register.Indirect = 1; src->Indirect.File = bracket[0].ind_file; src->Indirect.Index = bracket[0].ind_index; src->Indirect.Swizzle = bracket[0].ind_comp; src->Indirect.ArrayID = bracket[0].ind_array; } /* Parse optional swizzle. */ if (parse_optional_swizzle( ctx, swizzle, &parsed_swizzle, 4 )) { if (parsed_swizzle) { src->Register.SwizzleX = swizzle[0]; src->Register.SwizzleY = swizzle[1]; src->Register.SwizzleZ = swizzle[2]; src->Register.SwizzleW = swizzle[3]; } } if (src->Register.Absolute) { eat_opt_white( &ctx->cur ); if (*ctx->cur != '|') { report_error( ctx, "Expected `|'" ); return FALSE; } ctx->cur++; } return TRUE; } static boolean parse_texoffset_operand( struct translate_ctx *ctx, struct tgsi_texture_offset *src ) { uint file; uint swizzle[3]; boolean parsed_swizzle; struct parsed_bracket bracket; if (!parse_register_src(ctx, &file, &bracket)) return FALSE; src->File = file; src->Index = bracket.index; /* Parse optional swizzle. */ if (parse_optional_swizzle( ctx, swizzle, &parsed_swizzle, 3 )) { if (parsed_swizzle) { src->SwizzleX = swizzle[0]; src->SwizzleY = swizzle[1]; src->SwizzleZ = swizzle[2]; } } return TRUE; } static boolean match_inst(const char **pcur, unsigned *saturate, const struct tgsi_opcode_info *info) { const char *cur = *pcur; /* simple case: the whole string matches the instruction name */ if (str_match_nocase_whole(&cur, info->mnemonic)) { *pcur = cur; *saturate = 0; return TRUE; } if (str_match_no_case(&cur, info->mnemonic)) { /* the instruction has a suffix, figure it out */ if (str_match_nocase_whole(&cur, "_SAT")) { *pcur = cur; *saturate = 1; return TRUE; } } return FALSE; } static boolean parse_instruction( struct translate_ctx *ctx, boolean has_label ) { uint i; uint saturate = 0; const struct tgsi_opcode_info *info; struct tgsi_full_instruction inst; const char *cur; uint advance; inst = tgsi_default_full_instruction(); /* Parse predicate. */ eat_opt_white( &ctx->cur ); if (*ctx->cur == '(') { uint file; int index; uint swizzle[4]; boolean parsed_swizzle; inst.Instruction.Predicate = 1; ctx->cur++; if (*ctx->cur == '!') { ctx->cur++; inst.Predicate.Negate = 1; } if (!parse_register_1d( ctx, &file, &index )) return FALSE; if (parse_optional_swizzle( ctx, swizzle, &parsed_swizzle, 4 )) { if (parsed_swizzle) { inst.Predicate.SwizzleX = swizzle[0]; inst.Predicate.SwizzleY = swizzle[1]; inst.Predicate.SwizzleZ = swizzle[2]; inst.Predicate.SwizzleW = swizzle[3]; } } if (*ctx->cur != ')') { report_error( ctx, "Expected `)'" ); return FALSE; } ctx->cur++; } /* Parse instruction name. */ eat_opt_white( &ctx->cur ); for (i = 0; i < TGSI_OPCODE_LAST; i++) { cur = ctx->cur; info = tgsi_get_opcode_info( i ); if (match_inst(&cur, &saturate, info)) { if (info->num_dst + info->num_src + info->is_tex == 0) { ctx->cur = cur; break; } else if (*cur == '\0' || eat_white( &cur )) { ctx->cur = cur; break; } } } if (i == TGSI_OPCODE_LAST) { if (has_label) report_error( ctx, "Unknown opcode" ); else report_error( ctx, "Expected `DCL', `IMM' or a label" ); return FALSE; } inst.Instruction.Opcode = i; inst.Instruction.Saturate = saturate; inst.Instruction.NumDstRegs = info->num_dst; inst.Instruction.NumSrcRegs = info->num_src; if (i >= TGSI_OPCODE_SAMPLE && i <= TGSI_OPCODE_GATHER4) { /* * These are not considered tex opcodes here (no additional * target argument) however we're required to set the Texture * bit so we can set the number of tex offsets. */ inst.Instruction.Texture = 1; inst.Texture.Texture = TGSI_TEXTURE_UNKNOWN; } /* Parse instruction operands. */ for (i = 0; i < info->num_dst + info->num_src + info->is_tex; i++) { if (i > 0) { eat_opt_white( &ctx->cur ); if (*ctx->cur != ',') { report_error( ctx, "Expected `,'" ); return FALSE; } ctx->cur++; eat_opt_white( &ctx->cur ); } if (i < info->num_dst) { if (!parse_dst_operand( ctx, &inst.Dst[i] )) return FALSE; } else if (i < info->num_dst + info->num_src) { if (!parse_src_operand( ctx, &inst.Src[i - info->num_dst] )) return FALSE; } else { uint j; for (j = 0; j < TGSI_TEXTURE_COUNT; j++) { if (str_match_nocase_whole( &ctx->cur, tgsi_texture_names[j] )) { inst.Instruction.Texture = 1; inst.Texture.Texture = j; break; } } if (j == TGSI_TEXTURE_COUNT) { report_error( ctx, "Expected texture target" ); return FALSE; } } } cur = ctx->cur; eat_opt_white( &cur ); for (i = 0; inst.Instruction.Texture && *cur == ','; i++) { cur++; eat_opt_white( &cur ); ctx->cur = cur; if (!parse_texoffset_operand( ctx, &inst.TexOffsets[i] )) return FALSE; cur = ctx->cur; eat_opt_white( &cur ); } inst.Texture.NumOffsets = i; cur = ctx->cur; eat_opt_white( &cur ); if (info->is_branch && *cur == ':') { uint target; cur++; eat_opt_white( &cur ); if (!parse_uint( &cur, &target )) { report_error( ctx, "Expected a label" ); return FALSE; } inst.Instruction.Label = 1; inst.Label.Label = target; ctx->cur = cur; } advance = tgsi_build_full_instruction( &inst, ctx->tokens_cur, ctx->header, (uint) (ctx->tokens_end - ctx->tokens_cur) ); if (advance == 0) return FALSE; ctx->tokens_cur += advance; return TRUE; } /* parses a 4-touple of the form {x, y, z, w} * where x, y, z, w are numbers */ static boolean parse_immediate_data(struct translate_ctx *ctx, unsigned type, union tgsi_immediate_data *values) { unsigned i; int ret; eat_opt_white( &ctx->cur ); if (*ctx->cur != '{') { report_error( ctx, "Expected `{'" ); return FALSE; } ctx->cur++; for (i = 0; i < 4; i++) { eat_opt_white( &ctx->cur ); if (i > 0) { if (*ctx->cur != ',') { report_error( ctx, "Expected `,'" ); return FALSE; } ctx->cur++; eat_opt_white( &ctx->cur ); } switch (type) { case TGSI_IMM_FLOAT64: ret = parse_double(&ctx->cur, &values[i].Uint, &values[i+1].Uint); i++; break; case TGSI_IMM_FLOAT32: ret = parse_float(&ctx->cur, &values[i].Float); break; case TGSI_IMM_UINT32: ret = parse_uint(&ctx->cur, &values[i].Uint); break; case TGSI_IMM_INT32: ret = parse_int(&ctx->cur, &values[i].Int); break; default: assert(0); ret = FALSE; break; } if (!ret) { report_error( ctx, "Expected immediate constant" ); return FALSE; } } eat_opt_white( &ctx->cur ); if (*ctx->cur != '}') { report_error( ctx, "Expected `}'" ); return FALSE; } ctx->cur++; return TRUE; } static boolean parse_declaration( struct translate_ctx *ctx ) { struct tgsi_full_declaration decl; uint file; struct parsed_dcl_bracket brackets[2]; int num_brackets; uint writemask; const char *cur, *cur2; uint advance; boolean is_vs_input; if (!eat_white( &ctx->cur )) { report_error( ctx, "Syntax error" ); return FALSE; } if (!parse_register_dcl( ctx, &file, brackets, &num_brackets)) return FALSE; if (!parse_opt_writemask( ctx, &writemask )) return FALSE; decl = tgsi_default_full_declaration(); decl.Declaration.File = file; decl.Declaration.UsageMask = writemask; if (num_brackets == 1) { decl.Range.First = brackets[0].first; decl.Range.Last = brackets[0].last; } else { decl.Range.First = brackets[1].first; decl.Range.Last = brackets[1].last; decl.Declaration.Dimension = 1; decl.Dim.Index2D = brackets[0].first; } is_vs_input = (file == TGSI_FILE_INPUT && ctx->processor == TGSI_PROCESSOR_VERTEX); cur = ctx->cur; eat_opt_white( &cur ); if (*cur == ',') { cur2 = cur; cur2++; eat_opt_white( &cur2 ); if (str_match_nocase_whole( &cur2, "ARRAY" )) { int arrayid; if (*cur2 != '(') { report_error( ctx, "Expected `('" ); return FALSE; } cur2++; eat_opt_white( &cur2 ); if (!parse_int( &cur2, &arrayid )) { report_error( ctx, "Expected `,'" ); return FALSE; } eat_opt_white( &cur2 ); if (*cur2 != ')') { report_error( ctx, "Expected `)'" ); return FALSE; } cur2++; decl.Declaration.Array = 1; decl.Array.ArrayID = arrayid; ctx->cur = cur = cur2; } } if (*cur == ',' && !is_vs_input) { uint i, j; cur++; eat_opt_white( &cur ); if (file == TGSI_FILE_RESOURCE) { for (i = 0; i < TGSI_TEXTURE_COUNT; i++) { if (str_match_nocase_whole(&cur, tgsi_texture_names[i])) { decl.Resource.Resource = i; break; } } if (i == TGSI_TEXTURE_COUNT) { report_error(ctx, "Expected texture target"); return FALSE; } cur2 = cur; eat_opt_white(&cur2); while (*cur2 == ',') { cur2++; eat_opt_white(&cur2); if (str_match_nocase_whole(&cur2, "RAW")) { decl.Resource.Raw = 1; } else if (str_match_nocase_whole(&cur2, "WR")) { decl.Resource.Writable = 1; } else { break; } cur = cur2; eat_opt_white(&cur2); } ctx->cur = cur; } else if (file == TGSI_FILE_SAMPLER_VIEW) { for (i = 0; i < TGSI_TEXTURE_COUNT; i++) { if (str_match_nocase_whole(&cur, tgsi_texture_names[i])) { decl.SamplerView.Resource = i; break; } } if (i == TGSI_TEXTURE_COUNT) { report_error(ctx, "Expected texture target"); return FALSE; } eat_opt_white( &cur ); if (*cur != ',') { report_error( ctx, "Expected `,'" ); return FALSE; } ++cur; eat_opt_white( &cur ); for (j = 0; j < 4; ++j) { for (i = 0; i < TGSI_RETURN_TYPE_COUNT; ++i) { if (str_match_nocase_whole(&cur, tgsi_return_type_names[i])) { switch (j) { case 0: decl.SamplerView.ReturnTypeX = i; break; case 1: decl.SamplerView.ReturnTypeY = i; break; case 2: decl.SamplerView.ReturnTypeZ = i; break; case 3: decl.SamplerView.ReturnTypeW = i; break; default: assert(0); } break; } } if (i == TGSI_RETURN_TYPE_COUNT) { if (j == 0 || j > 2) { report_error(ctx, "Expected type name"); return FALSE; } break; } else { cur2 = cur; eat_opt_white( &cur2 ); if (*cur2 == ',') { cur2++; eat_opt_white( &cur2 ); cur = cur2; continue; } else break; } } if (j < 4) { decl.SamplerView.ReturnTypeY = decl.SamplerView.ReturnTypeZ = decl.SamplerView.ReturnTypeW = decl.SamplerView.ReturnTypeX; } ctx->cur = cur; } else { if (str_match_nocase_whole(&cur, "LOCAL")) { decl.Declaration.Local = 1; ctx->cur = cur; } cur = ctx->cur; eat_opt_white( &cur ); if (*cur == ',') { cur++; eat_opt_white( &cur ); for (i = 0; i < TGSI_SEMANTIC_COUNT; i++) { if (str_match_nocase_whole(&cur, tgsi_semantic_names[i])) { uint index; cur2 = cur; eat_opt_white( &cur2 ); if (*cur2 == '[') { cur2++; eat_opt_white( &cur2 ); if (!parse_uint( &cur2, &index )) { report_error( ctx, "Expected literal integer" ); return FALSE; } eat_opt_white( &cur2 ); if (*cur2 != ']') { report_error( ctx, "Expected `]'" ); return FALSE; } cur2++; decl.Semantic.Index = index; cur = cur2; } decl.Declaration.Semantic = 1; decl.Semantic.Name = i; ctx->cur = cur; break; } } } } } cur = ctx->cur; eat_opt_white( &cur ); if (*cur == ',' && !is_vs_input) { uint i; cur++; eat_opt_white( &cur ); for (i = 0; i < TGSI_INTERPOLATE_COUNT; i++) { if (str_match_nocase_whole( &cur, tgsi_interpolate_names[i] )) { decl.Declaration.Interpolate = 1; decl.Interp.Interpolate = i; ctx->cur = cur; break; } } if (i == TGSI_INTERPOLATE_COUNT) { report_error( ctx, "Expected semantic or interpolate attribute" ); return FALSE; } } cur = ctx->cur; eat_opt_white( &cur ); if (*cur == ',' && !is_vs_input) { uint i; cur++; eat_opt_white( &cur ); for (i = 0; i < TGSI_INTERPOLATE_LOC_COUNT; i++) { if (str_match_nocase_whole( &cur, tgsi_interpolate_locations[i] )) { decl.Interp.Location = i; ctx->cur = cur; break; } } } advance = tgsi_build_full_declaration( &decl, ctx->tokens_cur, ctx->header, (uint) (ctx->tokens_end - ctx->tokens_cur) ); if (advance == 0) return FALSE; ctx->tokens_cur += advance; return TRUE; } static boolean parse_immediate( struct translate_ctx *ctx ) { struct tgsi_full_immediate imm; uint advance; int type; if (*ctx->cur == '[') { uint uindex; ++ctx->cur; eat_opt_white( &ctx->cur ); if (!parse_uint( &ctx->cur, &uindex )) { report_error( ctx, "Expected literal unsigned integer" ); return FALSE; } if (uindex != ctx->num_immediates) { report_error( ctx, "Immediates must be sorted" ); return FALSE; } eat_opt_white( &ctx->cur ); if (*ctx->cur != ']') { report_error( ctx, "Expected `]'" ); return FALSE; } ctx->cur++; } if (!eat_white( &ctx->cur )) { report_error( ctx, "Syntax error" ); return FALSE; } for (type = 0; type < Elements(tgsi_immediate_type_names); ++type) { if (str_match_nocase_whole(&ctx->cur, tgsi_immediate_type_names[type])) break; } if (type == Elements(tgsi_immediate_type_names)) { report_error( ctx, "Expected immediate type" ); return FALSE; } imm = tgsi_default_full_immediate(); imm.Immediate.NrTokens += 4; imm.Immediate.DataType = type; parse_immediate_data(ctx, type, imm.u); advance = tgsi_build_full_immediate( &imm, ctx->tokens_cur, ctx->header, (uint) (ctx->tokens_end - ctx->tokens_cur) ); if (advance == 0) return FALSE; ctx->tokens_cur += advance; ctx->num_immediates++; return TRUE; } static boolean parse_primitive( const char **pcur, uint *primitive ) { uint i; for (i = 0; i < PIPE_PRIM_MAX; i++) { const char *cur = *pcur; if (str_match_nocase_whole( &cur, tgsi_primitive_names[i])) { *primitive = i; *pcur = cur; return TRUE; } } return FALSE; } static boolean parse_fs_coord_origin( const char **pcur, uint *fs_coord_origin ) { uint i; for (i = 0; i < Elements(tgsi_fs_coord_origin_names); i++) { const char *cur = *pcur; if (str_match_nocase_whole( &cur, tgsi_fs_coord_origin_names[i])) { *fs_coord_origin = i; *pcur = cur; return TRUE; } } return FALSE; } static boolean parse_fs_coord_pixel_center( const char **pcur, uint *fs_coord_pixel_center ) { uint i; for (i = 0; i < Elements(tgsi_fs_coord_pixel_center_names); i++) { const char *cur = *pcur; if (str_match_nocase_whole( &cur, tgsi_fs_coord_pixel_center_names[i])) { *fs_coord_pixel_center = i; *pcur = cur; return TRUE; } } return FALSE; } static boolean parse_property( struct translate_ctx *ctx ) { struct tgsi_full_property prop; uint property_name; uint values[8]; uint advance; char id[64]; if (!eat_white( &ctx->cur )) { report_error( ctx, "Syntax error" ); return FALSE; } report_error( ctx, "Syntax error" ); return FALSE; } if (!parse_identifier( &ctx->cur, id, sizeof(id) )) { report_error( ctx, "Syntax error" ); return FALSE; } break; } }
164,951
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: ft_smooth_render_generic( FT_Renderer render, FT_GlyphSlot slot, FT_Render_Mode mode, const FT_Vector* origin, FT_Render_Mode required_mode ) { FT_Error error; FT_Outline* outline = NULL; FT_BBox cbox; FT_UInt width, height, height_org, width_org, pitch; FT_Bitmap* bitmap; FT_Memory memory; FT_Int hmul = mode == FT_RENDER_MODE_LCD; FT_Int vmul = mode == FT_RENDER_MODE_LCD_V; FT_Pos x_shift, y_shift, x_left, y_top; FT_Raster_Params params; /* check glyph image format */ if ( slot->format != render->glyph_format ) { error = Smooth_Err_Invalid_Argument; goto Exit; } /* check mode */ if ( mode != required_mode ) return Smooth_Err_Cannot_Render_Glyph; outline = &slot->outline; /* translate the outline to the new origin if needed */ if ( origin ) FT_Outline_Translate( outline, origin->x, origin->y ); /* compute the control box, and grid fit it */ FT_Outline_Get_CBox( outline, &cbox ); cbox.xMin = FT_PIX_FLOOR( cbox.xMin ); cbox.yMin = FT_PIX_FLOOR( cbox.yMin ); cbox.xMax = FT_PIX_CEIL( cbox.xMax ); cbox.yMax = FT_PIX_CEIL( cbox.yMax ); width = (FT_UInt)( ( cbox.xMax - cbox.xMin ) >> 6 ); height = (FT_UInt)( ( cbox.yMax - cbox.yMin ) >> 6 ); bitmap = &slot->bitmap; memory = render->root.memory; width_org = width; height_org = height; /* release old bitmap buffer */ if ( slot->internal->flags & FT_GLYPH_OWN_BITMAP ) { FT_FREE( bitmap->buffer ); slot->internal->flags &= ~FT_GLYPH_OWN_BITMAP; } /* allocate new one, depends on pixel format */ pitch = width; if ( hmul ) { width = width * 3; pitch = FT_PAD_CEIL( width, 4 ); } if ( vmul ) height *= 3; x_shift = (FT_Int) cbox.xMin; y_shift = (FT_Int) cbox.yMin; x_left = (FT_Int)( cbox.xMin >> 6 ); y_top = (FT_Int)( cbox.yMax >> 6 ); #ifdef FT_CONFIG_OPTION_SUBPIXEL_RENDERING if ( slot->library->lcd_filter_func ) { FT_Int extra = slot->library->lcd_extra; if ( hmul ) { x_shift -= 64 * ( extra >> 1 ); width += 3 * extra; pitch = FT_PAD_CEIL( width, 4 ); x_left -= extra >> 1; } if ( vmul ) { y_shift -= 64 * ( extra >> 1 ); height += 3 * extra; y_top += extra >> 1; } } #endif bitmap->pixel_mode = FT_PIXEL_MODE_GRAY; bitmap->num_grays = 256; bitmap->width = width; goto Exit; slot->internal->flags |= FT_GLYPH_OWN_BITMAP; /* set up parameters */ params.target = bitmap; params.source = outline; params.flags = FT_RASTER_FLAG_AA; #ifdef FT_CONFIG_OPTION_SUBPIXEL_RENDERING /* implode outline if needed */ { FT_Vector* points = outline->points; FT_Vector* points_end = points + outline->n_points; FT_Vector* vec; if ( hmul ) for ( vec = points; vec < points_end; vec++ ) vec->x *= 3; if ( vmul ) for ( vec = points; vec < points_end; vec++ ) vec->y *= 3; } /* render outline into the bitmap */ error = render->raster_render( render->raster, &params ); /* deflate outline if needed */ { FT_Vector* points = outline->points; FT_Vector* points_end = points + outline->n_points; FT_Vector* vec; if ( hmul ) for ( vec = points; vec < points_end; vec++ ) vec->x /= 3; if ( vmul ) for ( vec = points; vec < points_end; vec++ ) vec->y /= 3; } if ( slot->library->lcd_filter_func ) slot->library->lcd_filter_func( bitmap, mode, slot->library ); #else /* !FT_CONFIG_OPTION_SUBPIXEL_RENDERING */ /* render outline into bitmap */ error = render->raster_render( render->raster, &params ); /* expand it horizontally */ if ( hmul ) { FT_Byte* line = bitmap->buffer; FT_UInt hh; for ( hh = height_org; hh > 0; hh--, line += pitch ) { FT_UInt xx; FT_Byte* end = line + width; for ( xx = width_org; xx > 0; xx-- ) { FT_UInt pixel = line[xx-1]; end[-3] = (FT_Byte)pixel; end[-2] = (FT_Byte)pixel; end[-1] = (FT_Byte)pixel; end -= 3; } } } /* expand it vertically */ if ( vmul ) { FT_Byte* read = bitmap->buffer + ( height - height_org ) * pitch; FT_Byte* write = bitmap->buffer; FT_UInt hh; for ( hh = height_org; hh > 0; hh-- ) { ft_memcpy( write, read, pitch ); write += pitch; ft_memcpy( write, read, pitch ); write += pitch; ft_memcpy( write, read, pitch ); write += pitch; read += pitch; } } #endif /* !FT_CONFIG_OPTION_SUBPIXEL_RENDERING */ FT_Outline_Translate( outline, x_shift, y_shift ); if ( error ) goto Exit; slot->format = FT_GLYPH_FORMAT_BITMAP; slot->bitmap_left = x_left; slot->bitmap_top = y_top; Exit: if ( outline && origin ) FT_Outline_Translate( outline, -origin->x, -origin->y ); return error; } Commit Message: CWE ID: CWE-189
ft_smooth_render_generic( FT_Renderer render, FT_GlyphSlot slot, FT_Render_Mode mode, const FT_Vector* origin, FT_Render_Mode required_mode ) { FT_Error error; FT_Outline* outline = NULL; FT_BBox cbox; FT_UInt width, height, height_org, width_org, pitch; FT_Bitmap* bitmap; FT_Memory memory; FT_Int hmul = mode == FT_RENDER_MODE_LCD; FT_Int vmul = mode == FT_RENDER_MODE_LCD_V; FT_Pos x_shift, y_shift, x_left, y_top; FT_Raster_Params params; /* check glyph image format */ if ( slot->format != render->glyph_format ) { error = Smooth_Err_Invalid_Argument; goto Exit; } /* check mode */ if ( mode != required_mode ) return Smooth_Err_Cannot_Render_Glyph; outline = &slot->outline; /* translate the outline to the new origin if needed */ if ( origin ) FT_Outline_Translate( outline, origin->x, origin->y ); /* compute the control box, and grid fit it */ FT_Outline_Get_CBox( outline, &cbox ); cbox.xMin = FT_PIX_FLOOR( cbox.xMin ); cbox.yMin = FT_PIX_FLOOR( cbox.yMin ); cbox.xMax = FT_PIX_CEIL( cbox.xMax ); cbox.yMax = FT_PIX_CEIL( cbox.yMax ); width = (FT_UInt)( ( cbox.xMax - cbox.xMin ) >> 6 ); height = (FT_UInt)( ( cbox.yMax - cbox.yMin ) >> 6 ); bitmap = &slot->bitmap; memory = render->root.memory; width_org = width; height_org = height; /* release old bitmap buffer */ if ( slot->internal->flags & FT_GLYPH_OWN_BITMAP ) { FT_FREE( bitmap->buffer ); slot->internal->flags &= ~FT_GLYPH_OWN_BITMAP; } /* allocate new one */ pitch = width; if ( hmul ) { width = width * 3; pitch = FT_PAD_CEIL( width, 4 ); } if ( vmul ) height *= 3; x_shift = (FT_Int) cbox.xMin; y_shift = (FT_Int) cbox.yMin; x_left = (FT_Int)( cbox.xMin >> 6 ); y_top = (FT_Int)( cbox.yMax >> 6 ); #ifdef FT_CONFIG_OPTION_SUBPIXEL_RENDERING if ( slot->library->lcd_filter_func ) { FT_Int extra = slot->library->lcd_extra; if ( hmul ) { x_shift -= 64 * ( extra >> 1 ); width += 3 * extra; pitch = FT_PAD_CEIL( width, 4 ); x_left -= extra >> 1; } if ( vmul ) { y_shift -= 64 * ( extra >> 1 ); height += 3 * extra; y_top += extra >> 1; } } #endif if ( pitch > 0xFFFF || height > 0xFFFF ) { FT_ERROR(( "ft_smooth_render_generic: glyph too large: %d x %d\n", width, height )); return Smooth_Err_Raster_Overflow; } bitmap->pixel_mode = FT_PIXEL_MODE_GRAY; bitmap->num_grays = 256; bitmap->width = width; goto Exit; slot->internal->flags |= FT_GLYPH_OWN_BITMAP; /* set up parameters */ params.target = bitmap; params.source = outline; params.flags = FT_RASTER_FLAG_AA; #ifdef FT_CONFIG_OPTION_SUBPIXEL_RENDERING /* implode outline if needed */ { FT_Vector* points = outline->points; FT_Vector* points_end = points + outline->n_points; FT_Vector* vec; if ( hmul ) for ( vec = points; vec < points_end; vec++ ) vec->x *= 3; if ( vmul ) for ( vec = points; vec < points_end; vec++ ) vec->y *= 3; } /* render outline into the bitmap */ error = render->raster_render( render->raster, &params ); /* deflate outline if needed */ { FT_Vector* points = outline->points; FT_Vector* points_end = points + outline->n_points; FT_Vector* vec; if ( hmul ) for ( vec = points; vec < points_end; vec++ ) vec->x /= 3; if ( vmul ) for ( vec = points; vec < points_end; vec++ ) vec->y /= 3; } if ( slot->library->lcd_filter_func ) slot->library->lcd_filter_func( bitmap, mode, slot->library ); #else /* !FT_CONFIG_OPTION_SUBPIXEL_RENDERING */ /* render outline into bitmap */ error = render->raster_render( render->raster, &params ); /* expand it horizontally */ if ( hmul ) { FT_Byte* line = bitmap->buffer; FT_UInt hh; for ( hh = height_org; hh > 0; hh--, line += pitch ) { FT_UInt xx; FT_Byte* end = line + width; for ( xx = width_org; xx > 0; xx-- ) { FT_UInt pixel = line[xx-1]; end[-3] = (FT_Byte)pixel; end[-2] = (FT_Byte)pixel; end[-1] = (FT_Byte)pixel; end -= 3; } } } /* expand it vertically */ if ( vmul ) { FT_Byte* read = bitmap->buffer + ( height - height_org ) * pitch; FT_Byte* write = bitmap->buffer; FT_UInt hh; for ( hh = height_org; hh > 0; hh-- ) { ft_memcpy( write, read, pitch ); write += pitch; ft_memcpy( write, read, pitch ); write += pitch; ft_memcpy( write, read, pitch ); write += pitch; read += pitch; } } #endif /* !FT_CONFIG_OPTION_SUBPIXEL_RENDERING */ FT_Outline_Translate( outline, x_shift, y_shift ); if ( error ) goto Exit; slot->format = FT_GLYPH_FORMAT_BITMAP; slot->bitmap_left = x_left; slot->bitmap_top = y_top; Exit: if ( outline && origin ) FT_Outline_Translate( outline, -origin->x, -origin->y ); return error; }
164,742
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int userns_install(struct nsproxy *nsproxy, void *ns) { struct user_namespace *user_ns = ns; struct cred *cred; /* Don't allow gaining capabilities by reentering * the same user namespace. */ if (user_ns == current_user_ns()) return -EINVAL; /* Threaded processes may not enter a different user namespace */ if (atomic_read(&current->mm->mm_users) > 1) return -EINVAL; if (!ns_capable(user_ns, CAP_SYS_ADMIN)) return -EPERM; cred = prepare_creds(); if (!cred) return -ENOMEM; put_user_ns(cred->user_ns); set_cred_user_ns(cred, get_user_ns(user_ns)); return commit_creds(cred); } Commit Message: userns: Don't allow CLONE_NEWUSER | CLONE_FS Don't allowing sharing the root directory with processes in a different user namespace. There doesn't seem to be any point, and to allow it would require the overhead of putting a user namespace reference in fs_struct (for permission checks) and incrementing that reference count on practically every call to fork. So just perform the inexpensive test of forbidding sharing fs_struct acrosss processes in different user namespaces. We already disallow other forms of threading when unsharing a user namespace so this should be no real burden in practice. This updates setns, clone, and unshare to disallow multiple user namespaces sharing an fs_struct. Cc: [email protected] Signed-off-by: "Eric W. Biederman" <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-264
static int userns_install(struct nsproxy *nsproxy, void *ns) { struct user_namespace *user_ns = ns; struct cred *cred; /* Don't allow gaining capabilities by reentering * the same user namespace. */ if (user_ns == current_user_ns()) return -EINVAL; /* Threaded processes may not enter a different user namespace */ if (atomic_read(&current->mm->mm_users) > 1) return -EINVAL; if (current->fs->users != 1) return -EINVAL; if (!ns_capable(user_ns, CAP_SYS_ADMIN)) return -EPERM; cred = prepare_creds(); if (!cred) return -ENOMEM; put_user_ns(cred->user_ns); set_cred_user_ns(cred, get_user_ns(user_ns)); return commit_creds(cred); }
166,108
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int add_push_report_sideband_pkt(git_push *push, git_pkt_data *data_pkt, git_buf *data_pkt_buf) { git_pkt *pkt; const char *line, *line_end; size_t line_len; int error; int reading_from_buf = data_pkt_buf->size > 0; if (reading_from_buf) { /* We had an existing partial packet, so add the new * packet to the buffer and parse the whole thing */ git_buf_put(data_pkt_buf, data_pkt->data, data_pkt->len); line = data_pkt_buf->ptr; line_len = data_pkt_buf->size; } else { line = data_pkt->data; line_len = data_pkt->len; } while (line_len > 0) { error = git_pkt_parse_line(&pkt, line, &line_end, line_len); if (error == GIT_EBUFS) { /* Buffer the data when the inner packet is split * across multiple sideband packets */ if (!reading_from_buf) git_buf_put(data_pkt_buf, line, line_len); error = 0; goto done; } else if (error < 0) goto done; /* Advance in the buffer */ line_len -= (line_end - line); line = line_end; /* When a valid packet with no content has been * read, git_pkt_parse_line does not report an * error, but the pkt pointer has not been set. * Handle this by skipping over empty packets. */ if (pkt == NULL) continue; error = add_push_report_pkt(push, pkt); git_pkt_free(pkt); if (error < 0 && error != GIT_ITEROVER) goto done; } error = 0; done: if (reading_from_buf) git_buf_consume(data_pkt_buf, line_end); return error; } Commit Message: smart_pkt: treat empty packet lines as error The Git protocol does not specify what should happen in the case of an empty packet line (that is a packet line "0004"). We currently indicate success, but do not return a packet in the case where we hit an empty line. The smart protocol was not prepared to handle such packets in all cases, though, resulting in a `NULL` pointer dereference. Fix the issue by returning an error instead. As such kind of packets is not even specified by upstream, this is the right thing to do. CWE ID: CWE-476
static int add_push_report_sideband_pkt(git_push *push, git_pkt_data *data_pkt, git_buf *data_pkt_buf) { git_pkt *pkt; const char *line, *line_end; size_t line_len; int error; int reading_from_buf = data_pkt_buf->size > 0; if (reading_from_buf) { /* We had an existing partial packet, so add the new * packet to the buffer and parse the whole thing */ git_buf_put(data_pkt_buf, data_pkt->data, data_pkt->len); line = data_pkt_buf->ptr; line_len = data_pkt_buf->size; } else { line = data_pkt->data; line_len = data_pkt->len; } while (line_len > 0) { error = git_pkt_parse_line(&pkt, line, &line_end, line_len); if (error == GIT_EBUFS) { /* Buffer the data when the inner packet is split * across multiple sideband packets */ if (!reading_from_buf) git_buf_put(data_pkt_buf, line, line_len); error = 0; goto done; } else if (error < 0) goto done; /* Advance in the buffer */ line_len -= (line_end - line); line = line_end; error = add_push_report_pkt(push, pkt); git_pkt_free(pkt); if (error < 0 && error != GIT_ITEROVER) goto done; } error = 0; done: if (reading_from_buf) git_buf_consume(data_pkt_buf, line_end); return error; }
170,110