instruction
stringclasses 1
value | input
stringlengths 93
3.53k
| output
stringlengths 16
15.4k
| __index_level_0__
int64 165k
175k
|
|---|---|---|---|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: HeadlessPrintManager::GetPrintParamsFromSettings(
const HeadlessPrintSettings& settings) {
printing::PrintSettings print_settings;
print_settings.set_dpi(printing::kPointsPerInch);
print_settings.set_should_print_backgrounds(
settings.should_print_backgrounds);
print_settings.set_scale_factor(settings.scale);
print_settings.SetOrientation(settings.landscape);
print_settings.set_display_header_footer(settings.display_header_footer);
if (print_settings.display_header_footer()) {
url::Replacements<char> url_sanitizer;
url_sanitizer.ClearUsername();
url_sanitizer.ClearPassword();
std::string url = printing_rfh_->GetLastCommittedURL()
.ReplaceComponents(url_sanitizer)
.spec();
print_settings.set_url(base::UTF8ToUTF16(url));
}
print_settings.set_margin_type(printing::CUSTOM_MARGINS);
print_settings.SetCustomMargins(settings.margins_in_points);
gfx::Rect printable_area_device_units(settings.paper_size_in_points);
print_settings.SetPrinterPrintableArea(settings.paper_size_in_points,
printable_area_device_units, true);
auto print_params = std::make_unique<PrintMsg_PrintPages_Params>();
printing::RenderParamsFromPrintSettings(print_settings,
&print_params->params);
print_params->params.document_cookie = printing::PrintSettings::NewCookie();
return print_params;
}
Commit Message: DevTools: allow styling the page number element when printing over the protocol.
Bug: none
Change-Id: I13e6afbd86a7c6bcdedbf0645183194b9de7cfb4
Reviewed-on: https://chromium-review.googlesource.com/809759
Commit-Queue: Pavel Feldman <pfeldman@chromium.org>
Reviewed-by: Lei Zhang <thestig@chromium.org>
Reviewed-by: Tom Sepez <tsepez@chromium.org>
Reviewed-by: Jianzhou Feng <jzfeng@chromium.org>
Cr-Commit-Position: refs/heads/master@{#523966}
CWE ID: CWE-20
|
HeadlessPrintManager::GetPrintParamsFromSettings(
const HeadlessPrintSettings& settings) {
printing::PrintSettings print_settings;
print_settings.set_dpi(printing::kPointsPerInch);
print_settings.set_should_print_backgrounds(
settings.should_print_backgrounds);
print_settings.set_scale_factor(settings.scale);
print_settings.SetOrientation(settings.landscape);
print_settings.set_display_header_footer(settings.display_header_footer);
if (print_settings.display_header_footer()) {
url::Replacements<char> url_sanitizer;
url_sanitizer.ClearUsername();
url_sanitizer.ClearPassword();
std::string url = printing_rfh_->GetLastCommittedURL()
.ReplaceComponents(url_sanitizer)
.spec();
print_settings.set_url(base::UTF8ToUTF16(url));
}
print_settings.set_margin_type(printing::CUSTOM_MARGINS);
print_settings.SetCustomMargins(settings.margins_in_points);
gfx::Rect printable_area_device_units(settings.paper_size_in_points);
print_settings.SetPrinterPrintableArea(settings.paper_size_in_points,
printable_area_device_units, true);
auto print_params = std::make_unique<PrintMsg_PrintPages_Params>();
printing::RenderParamsFromPrintSettings(print_settings,
&print_params->params);
print_params->params.document_cookie = printing::PrintSettings::NewCookie();
print_params->params.header_template =
base::UTF8ToUTF16(settings.header_template);
print_params->params.footer_template =
base::UTF8ToUTF16(settings.footer_template);
return print_params;
}
| 172,902
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void CloseTabsAndExpectNotifications(
TabStripModel* tab_strip_model,
std::vector<LifecycleUnit*> lifecycle_units) {
std::vector<std::unique_ptr<testing::StrictMock<MockLifecycleUnitObserver>>>
observers;
for (LifecycleUnit* lifecycle_unit : lifecycle_units) {
observers.emplace_back(
std::make_unique<testing::StrictMock<MockLifecycleUnitObserver>>());
lifecycle_unit->AddObserver(observers.back().get());
EXPECT_CALL(*observers.back().get(),
OnLifecycleUnitDestroyed(lifecycle_unit));
}
tab_strip_model->CloseAllTabs();
}
Commit Message: Connect the LocalDB to TabManager.
Bug: 773382
Change-Id: Iec8fe5226ee175105d51f300f30b4865478ac099
Reviewed-on: https://chromium-review.googlesource.com/1118611
Commit-Queue: Sébastien Marchand <sebmarchand@chromium.org>
Reviewed-by: François Doray <fdoray@chromium.org>
Cr-Commit-Position: refs/heads/master@{#572871}
CWE ID:
|
void CloseTabsAndExpectNotifications(
TabStripModel* tab_strip_model,
std::vector<LifecycleUnit*> lifecycle_units) {
std::vector<
std::unique_ptr<::testing::StrictMock<MockLifecycleUnitObserver>>>
observers;
for (LifecycleUnit* lifecycle_unit : lifecycle_units) {
observers.emplace_back(
std::make_unique<::testing::StrictMock<MockLifecycleUnitObserver>>());
lifecycle_unit->AddObserver(observers.back().get());
EXPECT_CALL(*observers.back().get(),
OnLifecycleUnitDestroyed(lifecycle_unit));
}
tab_strip_model->CloseAllTabs();
}
| 172,221
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: error::Error GLES2DecoderPassthroughImpl::DoLinkProgram(GLuint program) {
TRACE_EVENT0("gpu", "GLES2DecoderPassthroughImpl::DoLinkProgram");
SCOPED_UMA_HISTOGRAM_TIMER("GPU.PassthroughDoLinkProgramTime");
api()->glLinkProgramFn(GetProgramServiceID(program, resources_));
ExitCommandProcessingEarly();
return error::kNoError;
}
Commit Message: Add GL_PROGRAM_COMPLETION_QUERY_CHROMIUM
This makes the query of GL_COMPLETION_STATUS_KHR to programs much
cheaper by minimizing the round-trip to the GPU thread.
Bug: 881152, 957001
Change-Id: Iadfa798af29225e752c710ca5c25f50b3dd3101a
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1586630
Commit-Queue: Kenneth Russell <kbr@chromium.org>
Reviewed-by: Kentaro Hara <haraken@chromium.org>
Reviewed-by: Geoff Lang <geofflang@chromium.org>
Reviewed-by: Kenneth Russell <kbr@chromium.org>
Cr-Commit-Position: refs/heads/master@{#657568}
CWE ID: CWE-416
|
error::Error GLES2DecoderPassthroughImpl::DoLinkProgram(GLuint program) {
TRACE_EVENT0("gpu", "GLES2DecoderPassthroughImpl::DoLinkProgram");
SCOPED_UMA_HISTOGRAM_TIMER("GPU.PassthroughDoLinkProgramTime");
GLuint program_service_id = GetProgramServiceID(program, resources_);
api()->glLinkProgramFn(program_service_id);
ExitCommandProcessingEarly();
linking_program_service_id_ = program_service_id;
return error::kNoError;
}
| 172,534
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: XOpenDevice(
register Display *dpy,
register XID id)
{
register long rlen; /* raw length */
xOpenDeviceReq *req;
xOpenDeviceReply rep;
XDevice *dev;
XExtDisplayInfo *info = XInput_find_display(dpy);
LockDisplay(dpy);
if (_XiCheckExtInit(dpy, XInput_Initial_Release, info) == -1)
return NULL;
GetReq(OpenDevice, req);
req->reqType = info->codes->major_opcode;
req->ReqType = X_OpenDevice;
req->deviceid = id;
if (!_XReply(dpy, (xReply *) & rep, 0, xFalse)) {
UnlockDisplay(dpy);
SyncHandle();
return (XDevice *) NULL;
return (XDevice *) NULL;
}
rlen = rep.length << 2;
dev = (XDevice *) Xmalloc(sizeof(XDevice) + rep.num_classes *
sizeof(XInputClassInfo));
if (dev) {
int dlen; /* data length */
_XEatData(dpy, (unsigned long)rlen - dlen);
} else
_XEatDataWords(dpy, rep.length);
UnlockDisplay(dpy);
SyncHandle();
return (dev);
}
Commit Message:
CWE ID: CWE-284
|
XOpenDevice(
register Display *dpy,
register XID id)
{
register long rlen; /* raw length */
xOpenDeviceReq *req;
xOpenDeviceReply rep;
XDevice *dev;
XExtDisplayInfo *info = XInput_find_display(dpy);
LockDisplay(dpy);
if (_XiCheckExtInit(dpy, XInput_Initial_Release, info) == -1)
return NULL;
GetReq(OpenDevice, req);
req->reqType = info->codes->major_opcode;
req->ReqType = X_OpenDevice;
req->deviceid = id;
if (!_XReply(dpy, (xReply *) & rep, 0, xFalse)) {
UnlockDisplay(dpy);
SyncHandle();
return (XDevice *) NULL;
return (XDevice *) NULL;
}
if (rep.length < INT_MAX >> 2 &&
(rep.length << 2) >= rep.num_classes * sizeof(xInputClassInfo)) {
rlen = rep.length << 2;
dev = (XDevice *) Xmalloc(sizeof(XDevice) + rep.num_classes *
sizeof(XInputClassInfo));
} else {
rlen = 0;
dev = NULL;
}
if (dev) {
int dlen; /* data length */
_XEatData(dpy, (unsigned long)rlen - dlen);
} else
_XEatDataWords(dpy, rep.length);
UnlockDisplay(dpy);
SyncHandle();
return (dev);
}
| 164,921
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void TestFlashMessageLoop::DestroyMessageLoopResourceTask(int32_t unused) {
if (message_loop_) {
delete message_loop_;
message_loop_ = NULL;
} else {
PP_NOTREACHED();
}
}
Commit Message: Fix PPB_Flash_MessageLoop.
This CL suspends script callbacks and resource loads while running nested message loop using PPB_Flash_MessageLoop.
BUG=569496
Review URL: https://codereview.chromium.org/1559113002
Cr-Commit-Position: refs/heads/master@{#374529}
CWE ID: CWE-264
|
void TestFlashMessageLoop::DestroyMessageLoopResourceTask(int32_t unused) {
if (message_loop_) {
delete message_loop_;
message_loop_ = nullptr;
} else {
PP_NOTREACHED();
}
}
| 172,124
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: int simple_set_acl(struct inode *inode, struct posix_acl *acl, int type)
{
int error;
if (type == ACL_TYPE_ACCESS) {
error = posix_acl_equiv_mode(acl, &inode->i_mode);
if (error < 0)
return 0;
if (error == 0)
acl = NULL;
}
inode->i_ctime = current_time(inode);
set_cached_acl(inode, type, acl);
return 0;
}
Commit Message: tmpfs: clear S_ISGID when setting posix ACLs
This change was missed the tmpfs modification in In CVE-2016-7097
commit 073931017b49 ("posix_acl: Clear SGID bit when setting
file permissions")
It can test by xfstest generic/375, which failed to clear
setgid bit in the following test case on tmpfs:
touch $testfile
chown 100:100 $testfile
chmod 2755 $testfile
_runas -u 100 -g 101 -- setfacl -m u::rwx,g::rwx,o::rwx $testfile
Signed-off-by: Gu Zheng <guzheng1@huawei.com>
Signed-off-by: Al Viro <viro@zeniv.linux.org.uk>
CWE ID:
|
int simple_set_acl(struct inode *inode, struct posix_acl *acl, int type)
{
int error;
if (type == ACL_TYPE_ACCESS) {
error = posix_acl_update_mode(inode,
&inode->i_mode, &acl);
if (error)
return error;
}
inode->i_ctime = current_time(inode);
set_cached_acl(inode, type, acl);
return 0;
}
| 168,386
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: token_continue(i_ctx_t *i_ctx_p, scanner_state * pstate, bool save)
{
os_ptr op = osp;
int code;
ref token;
/* Note that gs_scan_token may change osp! */
pop(1); /* remove the file or scanner state */
again:
gs_scanner_error_object(i_ctx_p, pstate, &i_ctx_p->error_object);
break;
case scan_BOS:
code = 0;
case 0: /* read a token */
push(2);
ref_assign(op - 1, &token);
make_true(op);
break;
case scan_EOF: /* no tokens */
push(1);
make_false(op);
code = 0;
break;
case scan_Refill: /* need more data */
code = gs_scan_handle_refill(i_ctx_p, pstate, save,
ztoken_continue);
switch (code) {
case 0: /* state is not copied to the heap */
goto again;
case o_push_estack:
return code;
}
break; /* error */
}
Commit Message:
CWE ID: CWE-125
|
token_continue(i_ctx_t *i_ctx_p, scanner_state * pstate, bool save)
{
os_ptr op = osp;
int code;
ref token;
/* Since we might free pstate below, and we're dealing with
* gc memory referenced by the stack, we need to explicitly
* remove the reference to pstate from the stack, otherwise
* the garbager will fall over
*/
make_null(osp);
/* Note that gs_scan_token may change osp! */
pop(1); /* remove the file or scanner state */
again:
gs_scanner_error_object(i_ctx_p, pstate, &i_ctx_p->error_object);
break;
case scan_BOS:
code = 0;
case 0: /* read a token */
push(2);
ref_assign(op - 1, &token);
make_true(op);
break;
case scan_EOF: /* no tokens */
push(1);
make_false(op);
code = 0;
break;
case scan_Refill: /* need more data */
code = gs_scan_handle_refill(i_ctx_p, pstate, save,
ztoken_continue);
switch (code) {
case 0: /* state is not copied to the heap */
goto again;
case o_push_estack:
return code;
}
break; /* error */
}
| 164,738
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: pvscsi_ring_pop_req_descr(PVSCSIRingInfo *mgr)
{
uint32_t ready_ptr = RS_GET_FIELD(mgr, reqProdIdx);
if (ready_ptr != mgr->consumed_ptr) {
uint32_t next_ready_ptr =
mgr->consumed_ptr++ & mgr->txr_len_mask;
uint32_t next_ready_page =
return mgr->req_ring_pages_pa[next_ready_page] +
inpage_idx * sizeof(PVSCSIRingReqDesc);
} else {
return 0;
}
}
Commit Message:
CWE ID: CWE-399
|
pvscsi_ring_pop_req_descr(PVSCSIRingInfo *mgr)
{
uint32_t ready_ptr = RS_GET_FIELD(mgr, reqProdIdx);
uint32_t ring_size = PVSCSI_MAX_NUM_PAGES_REQ_RING
* PVSCSI_MAX_NUM_REQ_ENTRIES_PER_PAGE;
if (ready_ptr != mgr->consumed_ptr
&& ready_ptr - mgr->consumed_ptr < ring_size) {
uint32_t next_ready_ptr =
mgr->consumed_ptr++ & mgr->txr_len_mask;
uint32_t next_ready_page =
return mgr->req_ring_pages_pa[next_ready_page] +
inpage_idx * sizeof(PVSCSIRingReqDesc);
} else {
return 0;
}
}
| 164,929
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void PrintJobWorker::GetSettingsWithUI(
int document_page_count,
bool has_selection,
bool is_scripted) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
#if defined(OS_ANDROID)
if (is_scripted) {
PrintingContextDelegate* printing_context_delegate =
static_cast<PrintingContextDelegate*>(printing_context_delegate_.get());
content::WebContents* web_contents =
printing_context_delegate->GetWebContents();
TabAndroid* tab =
web_contents ? TabAndroid::FromWebContents(web_contents) : nullptr;
if (tab)
tab->SetPendingPrint();
}
#endif
printing_context_->AskUserForSettings(
document_page_count, has_selection, is_scripted,
base::Bind(&PostOnOwnerThread, make_scoped_refptr(owner_),
base::Bind(&PrintJobWorker::GetSettingsDone,
weak_factory_.GetWeakPtr())));
}
Commit Message: If JavaScript shows a dialog, cause the page to lose fullscreen.
BUG=670135, 550017, 726761, 728276
Review-Url: https://codereview.chromium.org/2906133004
Cr-Commit-Position: refs/heads/master@{#478884}
CWE ID: CWE-20
|
void PrintJobWorker::GetSettingsWithUI(
int document_page_count,
bool has_selection,
bool is_scripted) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
PrintingContextDelegate* printing_context_delegate =
static_cast<PrintingContextDelegate*>(printing_context_delegate_.get());
content::WebContents* web_contents =
printing_context_delegate->GetWebContents();
#if defined(OS_ANDROID)
if (is_scripted) {
TabAndroid* tab =
web_contents ? TabAndroid::FromWebContents(web_contents) : nullptr;
if (tab)
tab->SetPendingPrint();
}
#endif
// Running a dialog causes an exit to webpage-initiated fullscreen.
// http://crbug.com/728276
if (web_contents->IsFullscreenForCurrentTab())
web_contents->ExitFullscreen(true);
printing_context_->AskUserForSettings(
document_page_count, has_selection, is_scripted,
base::Bind(&PostOnOwnerThread, make_scoped_refptr(owner_),
base::Bind(&PrintJobWorker::GetSettingsDone,
weak_factory_.GetWeakPtr())));
}
| 172,313
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: process_demand_active(STREAM s)
{
uint8 type;
uint16 len_src_descriptor, len_combined_caps;
/* at this point we need to ensure that we have ui created */
rd_create_ui();
in_uint32_le(s, g_rdp_shareid);
in_uint16_le(s, len_src_descriptor);
in_uint16_le(s, len_combined_caps);
in_uint8s(s, len_src_descriptor);
logger(Protocol, Debug, "process_demand_active(), shareid=0x%x", g_rdp_shareid);
rdp_process_server_caps(s, len_combined_caps);
rdp_send_confirm_active();
rdp_send_synchronise();
rdp_send_control(RDP_CTL_COOPERATE);
rdp_send_control(RDP_CTL_REQUEST_CONTROL);
rdp_recv(&type); /* RDP_PDU_SYNCHRONIZE */
rdp_recv(&type); /* RDP_CTL_COOPERATE */
rdp_recv(&type); /* RDP_CTL_GRANT_CONTROL */
rdp_send_input(0, RDP_INPUT_SYNCHRONIZE, 0,
g_numlock_sync ? ui_get_numlock_state(read_keyboard_state()) : 0, 0);
if (g_rdp_version >= RDP_V5)
{
rdp_enum_bmpcache2();
rdp_send_fonts(3);
}
else
{
rdp_send_fonts(1);
rdp_send_fonts(2);
}
rdp_recv(&type); /* RDP_PDU_UNKNOWN 0x28 (Fonts?) */
reset_order_state();
}
Commit Message: Malicious RDP server security fixes
This commit includes fixes for a set of 21 vulnerabilities in
rdesktop when a malicious RDP server is used.
All vulnerabilities was identified and reported by Eyal Itkin.
* Add rdp_protocol_error function that is used in several fixes
* Refactor of process_bitmap_updates
* Fix possible integer overflow in s_check_rem() on 32bit arch
* Fix memory corruption in process_bitmap_data - CVE-2018-8794
* Fix remote code execution in process_bitmap_data - CVE-2018-8795
* Fix remote code execution in process_plane - CVE-2018-8797
* Fix Denial of Service in mcs_recv_connect_response - CVE-2018-20175
* Fix Denial of Service in mcs_parse_domain_params - CVE-2018-20175
* Fix Denial of Service in sec_parse_crypt_info - CVE-2018-20176
* Fix Denial of Service in sec_recv - CVE-2018-20176
* Fix minor information leak in rdpdr_process - CVE-2018-8791
* Fix Denial of Service in cssp_read_tsrequest - CVE-2018-8792
* Fix remote code execution in cssp_read_tsrequest - CVE-2018-8793
* Fix Denial of Service in process_bitmap_data - CVE-2018-8796
* Fix minor information leak in rdpsnd_process_ping - CVE-2018-8798
* Fix Denial of Service in process_secondary_order - CVE-2018-8799
* Fix remote code execution in in ui_clip_handle_data - CVE-2018-8800
* Fix major information leak in ui_clip_handle_data - CVE-2018-20174
* Fix memory corruption in rdp_in_unistr - CVE-2018-20177
* Fix Denial of Service in process_demand_active - CVE-2018-20178
* Fix remote code execution in lspci_process - CVE-2018-20179
* Fix remote code execution in rdpsnddbg_process - CVE-2018-20180
* Fix remote code execution in seamless_process - CVE-2018-20181
* Fix remote code execution in seamless_process_line - CVE-2018-20182
CWE ID: CWE-119
|
process_demand_active(STREAM s)
{
uint8 type;
uint16 len_src_descriptor, len_combined_caps;
struct stream packet = *s;
/* at this point we need to ensure that we have ui created */
rd_create_ui();
in_uint32_le(s, g_rdp_shareid);
in_uint16_le(s, len_src_descriptor);
in_uint16_le(s, len_combined_caps);
if (!s_check_rem(s, len_src_descriptor))
{
rdp_protocol_error("rdp_demand_active(), consume of source descriptor from stream would overrun", &packet);
}
in_uint8s(s, len_src_descriptor);
logger(Protocol, Debug, "process_demand_active(), shareid=0x%x", g_rdp_shareid);
rdp_process_server_caps(s, len_combined_caps);
rdp_send_confirm_active();
rdp_send_synchronise();
rdp_send_control(RDP_CTL_COOPERATE);
rdp_send_control(RDP_CTL_REQUEST_CONTROL);
rdp_recv(&type); /* RDP_PDU_SYNCHRONIZE */
rdp_recv(&type); /* RDP_CTL_COOPERATE */
rdp_recv(&type); /* RDP_CTL_GRANT_CONTROL */
rdp_send_input(0, RDP_INPUT_SYNCHRONIZE, 0,
g_numlock_sync ? ui_get_numlock_state(read_keyboard_state()) : 0, 0);
if (g_rdp_version >= RDP_V5)
{
rdp_enum_bmpcache2();
rdp_send_fonts(3);
}
else
{
rdp_send_fonts(1);
rdp_send_fonts(2);
}
rdp_recv(&type); /* RDP_PDU_UNKNOWN 0x28 (Fonts?) */
reset_order_state();
}
| 169,803
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: SPL_METHOD(DirectoryIterator, key)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
if (zend_parse_parameters_none() == FAILURE) {
return;
}
if (intern->u.dir.dirp) {
RETURN_LONG(intern->u.dir.index);
} else {
RETURN_FALSE;
}
}
Commit Message: Fix bug #72262 - do not overflow int
CWE ID: CWE-190
|
SPL_METHOD(DirectoryIterator, key)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
if (zend_parse_parameters_none() == FAILURE) {
return;
}
if (intern->u.dir.dirp) {
RETURN_LONG(intern->u.dir.index);
} else {
RETURN_FALSE;
}
}
| 167,028
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: bt_status_t btif_dm_pin_reply( const bt_bdaddr_t *bd_addr, uint8_t accept,
uint8_t pin_len, bt_pin_code_t *pin_code)
{
BTIF_TRACE_EVENT("%s: accept=%d", __FUNCTION__, accept);
if (pin_code == NULL)
return BT_STATUS_FAIL;
#if (defined(BLE_INCLUDED) && (BLE_INCLUDED == TRUE))
if (pairing_cb.is_le_only)
{
int i;
UINT32 passkey = 0;
int multi[] = {100000, 10000, 1000, 100, 10,1};
BD_ADDR remote_bd_addr;
bdcpy(remote_bd_addr, bd_addr->address);
for (i = 0; i < 6; i++)
{
passkey += (multi[i] * (pin_code->pin[i] - '0'));
}
BTIF_TRACE_DEBUG("btif_dm_pin_reply: passkey: %d", passkey);
BTA_DmBlePasskeyReply(remote_bd_addr, accept, passkey);
}
else
{
BTA_DmPinReply( (UINT8 *)bd_addr->address, accept, pin_len, pin_code->pin);
if (accept)
pairing_cb.pin_code_len = pin_len;
}
#else
BTA_DmPinReply( (UINT8 *)bd_addr->address, accept, pin_len, pin_code->pin);
if (accept)
pairing_cb.pin_code_len = pin_len;
#endif
return BT_STATUS_SUCCESS;
}
Commit Message: DO NOT MERGE Check size of pin before replying
If a malicious client set a pin that was too long it would overflow
the pin code memory.
Bug: 27411268
Change-Id: I9197ac6fdaa92a4799dacb6364e04671a39450cc
CWE ID: CWE-119
|
bt_status_t btif_dm_pin_reply( const bt_bdaddr_t *bd_addr, uint8_t accept,
uint8_t pin_len, bt_pin_code_t *pin_code)
{
BTIF_TRACE_EVENT("%s: accept=%d", __FUNCTION__, accept);
if (pin_code == NULL || pin_len > PIN_CODE_LEN)
return BT_STATUS_FAIL;
#if (defined(BLE_INCLUDED) && (BLE_INCLUDED == TRUE))
if (pairing_cb.is_le_only)
{
int i;
UINT32 passkey = 0;
int multi[] = {100000, 10000, 1000, 100, 10,1};
BD_ADDR remote_bd_addr;
bdcpy(remote_bd_addr, bd_addr->address);
for (i = 0; i < 6; i++)
{
passkey += (multi[i] * (pin_code->pin[i] - '0'));
}
BTIF_TRACE_DEBUG("btif_dm_pin_reply: passkey: %d", passkey);
BTA_DmBlePasskeyReply(remote_bd_addr, accept, passkey);
}
else
{
BTA_DmPinReply( (UINT8 *)bd_addr->address, accept, pin_len, pin_code->pin);
if (accept)
pairing_cb.pin_code_len = pin_len;
}
#else
BTA_DmPinReply( (UINT8 *)bd_addr->address, accept, pin_len, pin_code->pin);
if (accept)
pairing_cb.pin_code_len = pin_len;
#endif
return BT_STATUS_SUCCESS;
}
| 173,886
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void BluetoothOptionsHandler::DeviceFound(const std::string& adapter_id,
chromeos::BluetoothDevice* device) {
VLOG(2) << "Device found on " << adapter_id;
DCHECK(device);
web_ui_->CallJavascriptFunction(
"options.SystemOptions.addBluetoothDevice", device->AsDictionary());
}
Commit Message: Implement methods for pairing of bluetooth devices.
BUG=chromium:100392,chromium:102139
TEST=
Review URL: http://codereview.chromium.org/8495018
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@109094 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119
|
void BluetoothOptionsHandler::DeviceFound(const std::string& adapter_id,
chromeos::BluetoothDevice* device) {
VLOG(2) << "Device found on " << adapter_id;
DCHECK(device);
SendDeviceNotification(device, NULL);
}
| 170,965
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: my_object_str_hash_len (MyObject *obj, GHashTable *table, guint *len, GError **error)
{
*len = 0;
g_hash_table_foreach (table, hash_foreach, len);
return TRUE;
}
Commit Message:
CWE ID: CWE-264
|
my_object_str_hash_len (MyObject *obj, GHashTable *table, guint *len, GError **error)
| 165,121
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: bool BaseSessionService::RestoreUpdateTabNavigationCommand(
const SessionCommand& command,
TabNavigation* navigation,
SessionID::id_type* tab_id) {
scoped_ptr<Pickle> pickle(command.PayloadAsPickle());
if (!pickle.get())
return false;
void* iterator = NULL;
std::string url_spec;
if (!pickle->ReadInt(&iterator, tab_id) ||
!pickle->ReadInt(&iterator, &(navigation->index_)) ||
!pickle->ReadString(&iterator, &url_spec) ||
!pickle->ReadString16(&iterator, &(navigation->title_)) ||
!pickle->ReadString(&iterator, &(navigation->state_)) ||
!pickle->ReadInt(&iterator,
reinterpret_cast<int*>(&(navigation->transition_))))
return false;
bool has_type_mask = pickle->ReadInt(&iterator, &(navigation->type_mask_));
if (has_type_mask) {
std::string referrer_spec;
pickle->ReadString(&iterator, &referrer_spec);
int policy_int;
WebReferrerPolicy policy;
if (pickle->ReadInt(&iterator, &policy_int))
policy = static_cast<WebReferrerPolicy>(policy_int);
else
policy = WebKit::WebReferrerPolicyDefault;
navigation->referrer_ = content::Referrer(
referrer_spec.empty() ? GURL() : GURL(referrer_spec),
policy);
std::string content_state;
if (CompressDataHelper::ReadAndDecompressStringFromPickle(
*pickle.get(), &iterator, &content_state) &&
!content_state.empty()) {
navigation->state_ = content_state;
}
}
navigation->virtual_url_ = GURL(url_spec);
return true;
}
Commit Message: Metrics for measuring how much overhead reading compressed content states adds.
BUG=104293
TEST=NONE
Review URL: https://chromiumcodereview.appspot.com/9426039
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@123733 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20
|
bool BaseSessionService::RestoreUpdateTabNavigationCommand(
const SessionCommand& command,
TabNavigation* navigation,
SessionID::id_type* tab_id) {
scoped_ptr<Pickle> pickle(command.PayloadAsPickle());
if (!pickle.get())
return false;
void* iterator = NULL;
std::string url_spec;
if (!pickle->ReadInt(&iterator, tab_id) ||
!pickle->ReadInt(&iterator, &(navigation->index_)) ||
!pickle->ReadString(&iterator, &url_spec) ||
!pickle->ReadString16(&iterator, &(navigation->title_)) ||
!pickle->ReadString(&iterator, &(navigation->state_)) ||
!pickle->ReadInt(&iterator,
reinterpret_cast<int*>(&(navigation->transition_))))
return false;
bool has_type_mask = pickle->ReadInt(&iterator, &(navigation->type_mask_));
if (has_type_mask) {
std::string referrer_spec;
pickle->ReadString(&iterator, &referrer_spec);
int policy_int;
WebReferrerPolicy policy;
if (pickle->ReadInt(&iterator, &policy_int))
policy = static_cast<WebReferrerPolicy>(policy_int);
else
policy = WebKit::WebReferrerPolicyDefault;
navigation->referrer_ = content::Referrer(
referrer_spec.empty() ? GURL() : GURL(referrer_spec),
policy);
base::TimeTicks start_time_ = base::TimeTicks::Now();
std::string content_state;
if (CompressDataHelper::ReadAndDecompressStringFromPickle(
*pickle.get(), &iterator, &content_state) &&
!content_state.empty()) {
navigation->state_ = content_state;
}
base::TimeDelta total_time = base::TimeTicks::Now() - start_time_;
time_spent_reading_compressed_content_states += total_time;
}
navigation->virtual_url_ = GURL(url_spec);
return true;
}
| 171,050
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: PHP_METHOD(Phar, addFile)
{
char *fname, *localname = NULL;
size_t fname_len, localname_len = 0;
php_stream *resource;
zval zresource;
PHAR_ARCHIVE_OBJECT();
if (zend_parse_parameters(ZEND_NUM_ARGS(), "s|s", &fname, &fname_len, &localname, &localname_len) == FAILURE) {
return;
}
#if PHP_API_VERSION < 20100412
if (PG(safe_mode) && (!php_checkuid(fname, NULL, CHECKUID_ALLOW_ONLY_FILE))) {
zend_throw_exception_ex(spl_ce_RuntimeException, 0, "phar error: unable to open file \"%s\" to add to phar archive, safe_mode restrictions prevent this", fname);
return;
}
#endif
if (!strstr(fname, "://") && php_check_open_basedir(fname)) {
zend_throw_exception_ex(spl_ce_RuntimeException, 0, "phar error: unable to open file \"%s\" to add to phar archive, open_basedir restrictions prevent this", fname);
return;
}
if (!(resource = php_stream_open_wrapper(fname, "rb", 0, NULL))) {
zend_throw_exception_ex(spl_ce_RuntimeException, 0, "phar error: unable to open file \"%s\" to add to phar archive", fname);
return;
}
if (localname) {
fname = localname;
fname_len = localname_len;
}
php_stream_to_zval(resource, &zresource);
phar_add_file(&(phar_obj->archive), fname, fname_len, NULL, 0, &zresource);
zval_ptr_dtor(&zresource);
}
Commit Message:
CWE ID: CWE-20
|
PHP_METHOD(Phar, addFile)
{
char *fname, *localname = NULL;
size_t fname_len, localname_len = 0;
php_stream *resource;
zval zresource;
PHAR_ARCHIVE_OBJECT();
if (zend_parse_parameters(ZEND_NUM_ARGS(), "p|s", &fname, &fname_len, &localname, &localname_len) == FAILURE) {
return;
}
#if PHP_API_VERSION < 20100412
if (PG(safe_mode) && (!php_checkuid(fname, NULL, CHECKUID_ALLOW_ONLY_FILE))) {
zend_throw_exception_ex(spl_ce_RuntimeException, 0, "phar error: unable to open file \"%s\" to add to phar archive, safe_mode restrictions prevent this", fname);
return;
}
#endif
if (!strstr(fname, "://") && php_check_open_basedir(fname)) {
zend_throw_exception_ex(spl_ce_RuntimeException, 0, "phar error: unable to open file \"%s\" to add to phar archive, open_basedir restrictions prevent this", fname);
return;
}
if (!(resource = php_stream_open_wrapper(fname, "rb", 0, NULL))) {
zend_throw_exception_ex(spl_ce_RuntimeException, 0, "phar error: unable to open file \"%s\" to add to phar archive", fname);
return;
}
if (localname) {
fname = localname;
fname_len = localname_len;
}
php_stream_to_zval(resource, &zresource);
phar_add_file(&(phar_obj->archive), fname, fname_len, NULL, 0, &zresource);
zval_ptr_dtor(&zresource);
}
| 165,070
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: bool nodeHasRole(Node* node, const String& role) {
if (!node || !node->isElementNode())
return false;
return equalIgnoringCase(toElement(node)->getAttribute(roleAttr), role);
}
Commit Message: Switch to equalIgnoringASCIICase throughout modules/accessibility
BUG=627682
Review-Url: https://codereview.chromium.org/2793913007
Cr-Commit-Position: refs/heads/master@{#461858}
CWE ID: CWE-254
|
bool nodeHasRole(Node* node, const String& role) {
if (!node || !node->isElementNode())
return false;
return equalIgnoringASCIICase(toElement(node)->getAttribute(roleAttr), role);
}
| 171,930
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static char* getPreferredTag(const char* gf_tag)
{
char* result = NULL;
int grOffset = 0;
grOffset = findOffset( LOC_GRANDFATHERED ,gf_tag);
if(grOffset < 0) {
return NULL;
}
if( grOffset < LOC_PREFERRED_GRANDFATHERED_LEN ){
/* return preferred tag */
result = estrdup( LOC_PREFERRED_GRANDFATHERED[grOffset] );
} else {
/* Return correct grandfathered language tag */
result = estrdup( LOC_GRANDFATHERED[grOffset] );
}
return result;
}
Commit Message: Fix bug #72241: get_icu_value_internal out-of-bounds read
CWE ID: CWE-125
|
static char* getPreferredTag(const char* gf_tag)
{
char* result = NULL;
int grOffset = 0;
grOffset = findOffset( LOC_GRANDFATHERED ,gf_tag);
if(grOffset < 0) {
return NULL;
}
if( grOffset < LOC_PREFERRED_GRANDFATHERED_LEN ){
/* return preferred tag */
result = estrdup( LOC_PREFERRED_GRANDFATHERED[grOffset] );
} else {
/* Return correct grandfathered language tag */
result = estrdup( LOC_GRANDFATHERED[grOffset] );
}
return result;
}
| 167,201
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static noinline void key_gc_unused_keys(struct list_head *keys)
{
while (!list_empty(keys)) {
struct key *key =
list_entry(keys->next, struct key, graveyard_link);
list_del(&key->graveyard_link);
kdebug("- %u", key->serial);
key_check(key);
security_key_free(key);
/* deal with the user's key tracking and quota */
if (test_bit(KEY_FLAG_IN_QUOTA, &key->flags)) {
spin_lock(&key->user->lock);
key->user->qnkeys--;
key->user->qnbytes -= key->quotalen;
spin_unlock(&key->user->lock);
}
atomic_dec(&key->user->nkeys);
if (test_bit(KEY_FLAG_INSTANTIATED, &key->flags))
atomic_dec(&key->user->nikeys);
key_user_put(key->user);
/* now throw away the key memory */
if (key->type->destroy)
key->type->destroy(key);
kfree(key->description);
#ifdef KEY_DEBUGGING
key->magic = KEY_DEBUG_MAGIC_X;
#endif
kmem_cache_free(key_jar, key);
}
}
Commit Message: KEYS: close race between key lookup and freeing
When a key is being garbage collected, it's key->user would get put before
the ->destroy() callback is called, where the key is removed from it's
respective tracking structures.
This leaves a key hanging in a semi-invalid state which leaves a window open
for a different task to try an access key->user. An example is
find_keyring_by_name() which would dereference key->user for a key that is
in the process of being garbage collected (where key->user was freed but
->destroy() wasn't called yet - so it's still present in the linked list).
This would cause either a panic, or corrupt memory.
Fixes CVE-2014-9529.
Signed-off-by: Sasha Levin <sasha.levin@oracle.com>
Signed-off-by: David Howells <dhowells@redhat.com>
CWE ID: CWE-362
|
static noinline void key_gc_unused_keys(struct list_head *keys)
{
while (!list_empty(keys)) {
struct key *key =
list_entry(keys->next, struct key, graveyard_link);
list_del(&key->graveyard_link);
kdebug("- %u", key->serial);
key_check(key);
security_key_free(key);
/* deal with the user's key tracking and quota */
if (test_bit(KEY_FLAG_IN_QUOTA, &key->flags)) {
spin_lock(&key->user->lock);
key->user->qnkeys--;
key->user->qnbytes -= key->quotalen;
spin_unlock(&key->user->lock);
}
atomic_dec(&key->user->nkeys);
if (test_bit(KEY_FLAG_INSTANTIATED, &key->flags))
atomic_dec(&key->user->nikeys);
/* now throw away the key memory */
if (key->type->destroy)
key->type->destroy(key);
key_user_put(key->user);
kfree(key->description);
#ifdef KEY_DEBUGGING
key->magic = KEY_DEBUG_MAGIC_X;
#endif
kmem_cache_free(key_jar, key);
}
}
| 166,783
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: INST_HANDLER (lds) { // LDS Rd, k
int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x1) << 4);
int k = (buf[3] << 8) | buf[2];
op->ptr = k;
__generic_ld_st (op, "ram", 0, 1, 0, k, 0);
ESIL_A ("r%d,=,", d);
}
Commit Message: Fix crash in anal.avr
CWE ID: CWE-125
|
INST_HANDLER (lds) { // LDS Rd, k
if (len < 4) {
return;
}
int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x1) << 4);
int k = (buf[3] << 8) | buf[2];
op->ptr = k;
__generic_ld_st (op, "ram", 0, 1, 0, k, 0);
ESIL_A ("r%d,=,", d);
}
| 169,234
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: PromoResourceService::PromoResourceService(Profile* profile)
: WebResourceService(profile->GetPrefs(),
GetPromoResourceURL(),
true, // append locale to URL
prefs::kNtpPromoResourceCacheUpdate,
kStartResourceFetchDelay,
GetCacheUpdateDelay()),
profile_(profile),
ALLOW_THIS_IN_INITIALIZER_LIST(
weak_ptr_factory_(this)),
web_resource_update_scheduled_(false) {
ScheduleNotificationOnInit();
}
Commit Message: Refresh promo notifications as they're fetched
The "guard" existed for notification scheduling was preventing
"turn-off a promo" and "update a promo" scenarios.
Yet I do not believe it was adding any actual safety: if things
on a server backend go wrong, the clients will be affected one
way or the other, and it is better to have an option to shut
the malformed promo down "as quickly as possible" (~in 12-24 hours).
BUG=
TEST=
Review URL: https://chromiumcodereview.appspot.com/10696204
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@146462 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID:
|
PromoResourceService::PromoResourceService(Profile* profile)
: WebResourceService(profile->GetPrefs(),
GetPromoResourceURL(),
true, // append locale to URL
prefs::kNtpPromoResourceCacheUpdate,
kStartResourceFetchDelay,
GetCacheUpdateDelay()),
profile_(profile),
ALLOW_THIS_IN_INITIALIZER_LIST(
weak_ptr_factory_(this)) {
ScheduleNotificationOnInit();
}
| 170,782
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static int is_rndis(USBNetState *s)
{
return s->dev.config->bConfigurationValue == DEV_RNDIS_CONFIG_VALUE;
}
Commit Message:
CWE ID:
|
static int is_rndis(USBNetState *s)
{
return s->dev.config ?
s->dev.config->bConfigurationValue == DEV_RNDIS_CONFIG_VALUE : 0;
}
| 165,187
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: status_t NuPlayer::GenericSource::setBuffers(
bool audio, Vector<MediaBuffer *> &buffers) {
if (mIsWidevine && !audio && mVideoTrack.mSource != NULL) {
return mVideoTrack.mSource->setBuffers(buffers);
}
return INVALID_OPERATION;
}
Commit Message: Resolve a merge issue between lmp and lmp-mr1+
Change-Id: I336cb003fb7f50fd7d95c30ca47e45530a7ad503
(cherry picked from commit 33f6da1092834f1e4be199cfa3b6310d66b521c0)
(cherry picked from commit bb3a0338b58fafb01ac5b34efc450b80747e71e4)
CWE ID: CWE-119
|
status_t NuPlayer::GenericSource::setBuffers(
bool audio, Vector<MediaBuffer *> &buffers) {
if (mIsSecure && !audio && mVideoTrack.mSource != NULL) {
return mVideoTrack.mSource->setBuffers(buffers);
}
return INVALID_OPERATION;
}
| 174,166
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: string DecodeFile(const string& filename, int num_threads) {
libvpx_test::WebMVideoSource video(filename);
video.Init();
vpx_codec_dec_cfg_t cfg = {0};
cfg.threads = num_threads;
libvpx_test::VP9Decoder decoder(cfg, 0);
libvpx_test::MD5 md5;
for (video.Begin(); video.cxdata(); video.Next()) {
const vpx_codec_err_t res =
decoder.DecodeFrame(video.cxdata(), video.frame_size());
if (res != VPX_CODEC_OK) {
EXPECT_EQ(VPX_CODEC_OK, res) << decoder.DecodeError();
break;
}
libvpx_test::DxDataIterator dec_iter = decoder.GetDxData();
const vpx_image_t *img = NULL;
while ((img = dec_iter.Next())) {
md5.Add(img);
}
}
return string(md5.Get());
}
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
|
string DecodeFile(const string& filename, int num_threads) {
libvpx_test::WebMVideoSource video(filename);
video.Init();
vpx_codec_dec_cfg_t cfg = vpx_codec_dec_cfg_t();
cfg.threads = num_threads;
libvpx_test::VP9Decoder decoder(cfg, 0);
libvpx_test::MD5 md5;
for (video.Begin(); video.cxdata(); video.Next()) {
const vpx_codec_err_t res =
decoder.DecodeFrame(video.cxdata(), video.frame_size());
if (res != VPX_CODEC_OK) {
EXPECT_EQ(VPX_CODEC_OK, res) << decoder.DecodeError();
break;
}
libvpx_test::DxDataIterator dec_iter = decoder.GetDxData();
const vpx_image_t *img = NULL;
while ((img = dec_iter.Next())) {
md5.Add(img);
}
}
return string(md5.Get());
}
| 174,598
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void RendererSchedulerImpl::OnShutdownTaskQueue(
const scoped_refptr<MainThreadTaskQueue>& task_queue) {
if (main_thread_only().was_shutdown)
return;
if (task_queue_throttler_)
task_queue_throttler_->ShutdownTaskQueue(task_queue.get());
if (task_runners_.erase(task_queue)) {
switch (task_queue->queue_class()) {
case MainThreadTaskQueue::QueueClass::kTimer:
task_queue->RemoveTaskObserver(
&main_thread_only().timer_task_cost_estimator);
case MainThreadTaskQueue::QueueClass::kLoading:
task_queue->RemoveTaskObserver(
&main_thread_only().loading_task_cost_estimator);
default:
break;
}
}
}
Commit Message: [scheduler] Remove implicit fallthrough in switch
Bail out early when a condition in the switch is fulfilled.
This does not change behaviour due to RemoveTaskObserver being no-op when
the task observer is not present in the list.
R=thakis@chromium.org
Bug: 177475
Change-Id: Ibc7772c79f8a8c8a1d63a997dabe1efda5d3a7bd
Reviewed-on: https://chromium-review.googlesource.com/891187
Reviewed-by: Nico Weber <thakis@chromium.org>
Commit-Queue: Alexander Timin <altimin@chromium.org>
Cr-Commit-Position: refs/heads/master@{#532649}
CWE ID: CWE-119
|
void RendererSchedulerImpl::OnShutdownTaskQueue(
const scoped_refptr<MainThreadTaskQueue>& task_queue) {
if (main_thread_only().was_shutdown)
return;
if (task_queue_throttler_)
task_queue_throttler_->ShutdownTaskQueue(task_queue.get());
if (task_runners_.erase(task_queue)) {
switch (task_queue->queue_class()) {
case MainThreadTaskQueue::QueueClass::kTimer:
task_queue->RemoveTaskObserver(
&main_thread_only().timer_task_cost_estimator);
break;
case MainThreadTaskQueue::QueueClass::kLoading:
task_queue->RemoveTaskObserver(
&main_thread_only().loading_task_cost_estimator);
break;
default:
break;
}
}
}
| 172,603
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static PassRefPtr<Uint8Array> copySkImageData(SkImage* input,
const SkImageInfo& info) {
size_t width = static_cast<size_t>(input->width());
RefPtr<ArrayBuffer> dstBuffer =
ArrayBuffer::createOrNull(width * input->height(), info.bytesPerPixel());
if (!dstBuffer)
return nullptr;
RefPtr<Uint8Array> dstPixels =
Uint8Array::create(dstBuffer, 0, dstBuffer->byteLength());
input->readPixels(info, dstPixels->data(), width * info.bytesPerPixel(), 0,
0);
return dstPixels;
}
Commit Message: Prevent bad casting in ImageBitmap when calling ArrayBuffer::createOrNull
Currently when ImageBitmap's constructor is invoked, we check whether
dstSize will overflow size_t or not. The problem comes when we call
ArrayBuffer::createOrNull some times in the code.
Both parameters of ArrayBuffer::createOrNull are unsigned. In ImageBitmap
when we call this method, the first parameter is usually width * height.
This could overflow unsigned even if it has been checked safe with size_t,
the reason is that unsigned is a 32-bit value on 64-bit systems, while
size_t is a 64-bit value.
This CL makes a change such that we check whether the dstSize will overflow
unsigned or not. In this case, we can guarantee that createOrNull will not have
any crash.
BUG=664139
Review-Url: https://codereview.chromium.org/2500493002
Cr-Commit-Position: refs/heads/master@{#431936}
CWE ID: CWE-787
|
static PassRefPtr<Uint8Array> copySkImageData(SkImage* input,
const SkImageInfo& info) {
// width * height * bytesPerPixel will never overflow unsigned.
unsigned width = static_cast<unsigned>(input->width());
RefPtr<ArrayBuffer> dstBuffer =
ArrayBuffer::createOrNull(width * input->height(), info.bytesPerPixel());
if (!dstBuffer)
return nullptr;
RefPtr<Uint8Array> dstPixels =
Uint8Array::create(dstBuffer, 0, dstBuffer->byteLength());
input->readPixels(info, dstPixels->data(), width * info.bytesPerPixel(), 0,
0);
return dstPixels;
}
| 172,499
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: SProcXResQueryResourceBytes (ClientPtr client)
{
REQUEST(xXResQueryResourceBytesReq);
int c;
xXResResourceIdSpec *specs = (void*) ((char*) stuff + sizeof(*stuff));
int c;
xXResResourceIdSpec *specs = (void*) ((char*) stuff + sizeof(*stuff));
swapl(&stuff->numSpecs);
REQUEST_AT_LEAST_SIZE(xXResQueryResourceBytesReq);
REQUEST_FIXED_SIZE(xXResQueryResourceBytesReq,
stuff->numSpecs * sizeof(specs[0]));
}
Commit Message:
CWE ID: CWE-20
|
SProcXResQueryResourceBytes (ClientPtr client)
{
REQUEST(xXResQueryResourceBytesReq);
int c;
xXResResourceIdSpec *specs = (void*) ((char*) stuff + sizeof(*stuff));
int c;
xXResResourceIdSpec *specs = (void*) ((char*) stuff + sizeof(*stuff));
REQUEST_AT_LEAST_SIZE(xXResQueryResourceBytesReq);
swapl(&stuff->numSpecs);
REQUEST_FIXED_SIZE(xXResQueryResourceBytesReq,
stuff->numSpecs * sizeof(specs[0]));
}
| 165,435
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: unsigned long lh_char_hash(const void *k)
{
unsigned int h = 0;
const char* data = (const char*)k;
while( *data!=0 ) h = h*129 + (unsigned int)(*data++) + LH_PRIME;
return h;
}
Commit Message: Patch to address the following issues:
* CVE-2013-6371: hash collision denial of service
* CVE-2013-6370: buffer overflow if size_t is larger than int
CWE ID: CWE-310
|
unsigned long lh_char_hash(const void *k)
{
static volatile int random_seed = -1;
if (random_seed == -1) {
int seed;
/* we can't use -1 as it is the unitialized sentinel */
while ((seed = json_c_get_random_seed()) == -1);
#if defined __GNUC__
__sync_val_compare_and_swap(&random_seed, -1, seed);
#elif defined _MSC_VER
InterlockedCompareExchange(&random_seed, seed, -1);
#else
#warning "racy random seed initializtion if used by multiple threads"
random_seed = seed; /* potentially racy */
#endif
}
return hashlittle((const char*)k, strlen((const char*)k), random_seed);
}
| 166,540
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void CoordinatorImpl::FinalizeGlobalMemoryDumpIfAllManagersReplied() {
TRACE_EVENT0(base::trace_event::MemoryDumpManager::kTraceCategory,
"GlobalMemoryDump.Computation");
DCHECK(!queued_memory_dump_requests_.empty());
QueuedRequest* request = &queued_memory_dump_requests_.front();
if (!request->dump_in_progress || request->pending_responses.size() > 0 ||
request->heap_dump_in_progress) {
return;
}
QueuedRequestDispatcher::Finalize(request, tracing_observer_.get());
queued_memory_dump_requests_.pop_front();
request = nullptr;
if (!queued_memory_dump_requests_.empty()) {
base::SequencedTaskRunnerHandle::Get()->PostTask(
FROM_HERE,
base::BindOnce(&CoordinatorImpl::PerformNextQueuedGlobalMemoryDump,
base::Unretained(this)));
}
}
Commit Message: Fix heap-use-after-free by using weak factory instead of Unretained
Bug: 856578
Change-Id: Ifb2a1b7e6c22e1af36e12eedba72427f51d925b9
Reviewed-on: https://chromium-review.googlesource.com/1114617
Reviewed-by: Hector Dearman <hjd@chromium.org>
Commit-Queue: Hector Dearman <hjd@chromium.org>
Cr-Commit-Position: refs/heads/master@{#571528}
CWE ID: CWE-416
|
void CoordinatorImpl::FinalizeGlobalMemoryDumpIfAllManagersReplied() {
TRACE_EVENT0(base::trace_event::MemoryDumpManager::kTraceCategory,
"GlobalMemoryDump.Computation");
DCHECK(!queued_memory_dump_requests_.empty());
QueuedRequest* request = &queued_memory_dump_requests_.front();
if (!request->dump_in_progress || request->pending_responses.size() > 0 ||
request->heap_dump_in_progress) {
return;
}
QueuedRequestDispatcher::Finalize(request, tracing_observer_.get());
queued_memory_dump_requests_.pop_front();
request = nullptr;
if (!queued_memory_dump_requests_.empty()) {
base::SequencedTaskRunnerHandle::Get()->PostTask(
FROM_HERE,
base::BindOnce(&CoordinatorImpl::PerformNextQueuedGlobalMemoryDump,
weak_ptr_factory_.GetWeakPtr()));
}
}
| 173,212
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: AppCacheDispatcherHost::AppCacheDispatcherHost(
ChromeAppCacheService* appcache_service,
int process_id)
: BrowserMessageFilter(AppCacheMsgStart),
appcache_service_(appcache_service),
frontend_proxy_(this),
process_id_(process_id) {
}
Commit Message: AppCache: Use WeakPtr<> to fix a potential uaf bug.
BUG=554908
Review URL: https://codereview.chromium.org/1441683004
Cr-Commit-Position: refs/heads/master@{#359930}
CWE ID:
|
AppCacheDispatcherHost::AppCacheDispatcherHost(
ChromeAppCacheService* appcache_service,
int process_id)
: BrowserMessageFilter(AppCacheMsgStart),
appcache_service_(appcache_service),
frontend_proxy_(this),
process_id_(process_id),
weak_factory_(this) {
}
| 171,744
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: OMX_ERRORTYPE omx_video::fill_this_buffer(OMX_IN OMX_HANDLETYPE hComp,
OMX_IN OMX_BUFFERHEADERTYPE* buffer)
{
DEBUG_PRINT_LOW("FTB: buffer->pBuffer[%p]", buffer->pBuffer);
if (m_state == OMX_StateInvalid) {
DEBUG_PRINT_ERROR("ERROR: FTB in Invalid State");
return OMX_ErrorInvalidState;
}
if (buffer == NULL ||(buffer->nSize != sizeof(OMX_BUFFERHEADERTYPE))) {
DEBUG_PRINT_ERROR("ERROR: omx_video::ftb-->Invalid buffer or size");
return OMX_ErrorBadParameter;
}
if (buffer->nVersion.nVersion != OMX_SPEC_VERSION) {
DEBUG_PRINT_ERROR("ERROR: omx_video::ftb-->OMX Version Invalid");
return OMX_ErrorVersionMismatch;
}
if (buffer->nOutputPortIndex != (OMX_U32)PORT_INDEX_OUT) {
DEBUG_PRINT_ERROR("ERROR: omx_video::ftb-->Bad port index");
return OMX_ErrorBadPortIndex;
}
if (!m_sOutPortDef.bEnabled) {
DEBUG_PRINT_ERROR("ERROR: omx_video::ftb-->port is disabled");
return OMX_ErrorIncorrectStateOperation;
}
post_event((unsigned long) hComp, (unsigned long)buffer,OMX_COMPONENT_GENERATE_FTB);
return OMX_ErrorNone;
}
Commit Message: DO NOT MERGE mm-video-v4l2: venc: Avoid processing ETBs/FTBs in invalid states
(per the spec) ETB/FTB should not be handled in states other than
Executing, Paused and Idle. This avoids accessing invalid buffers.
Also add a lock to protect the private-buffers from being deleted
while accessing from another thread.
Bug: 27903498
Security Vulnerability - Heap Use-After-Free and Possible LPE in
MediaServer (libOmxVenc problem #3)
CRs-Fixed: 1010088
Change-Id: I898b42034c0add621d4f9d8e02ca0ed4403d4fd3
CWE ID:
|
OMX_ERRORTYPE omx_video::fill_this_buffer(OMX_IN OMX_HANDLETYPE hComp,
OMX_IN OMX_BUFFERHEADERTYPE* buffer)
{
DEBUG_PRINT_LOW("FTB: buffer->pBuffer[%p]", buffer->pBuffer);
if (m_state != OMX_StateExecuting &&
m_state != OMX_StatePause &&
m_state != OMX_StateIdle) {
DEBUG_PRINT_ERROR("ERROR: FTB in Invalid State");
return OMX_ErrorInvalidState;
}
if (buffer == NULL ||(buffer->nSize != sizeof(OMX_BUFFERHEADERTYPE))) {
DEBUG_PRINT_ERROR("ERROR: omx_video::ftb-->Invalid buffer or size");
return OMX_ErrorBadParameter;
}
if (buffer->nVersion.nVersion != OMX_SPEC_VERSION) {
DEBUG_PRINT_ERROR("ERROR: omx_video::ftb-->OMX Version Invalid");
return OMX_ErrorVersionMismatch;
}
if (buffer->nOutputPortIndex != (OMX_U32)PORT_INDEX_OUT) {
DEBUG_PRINT_ERROR("ERROR: omx_video::ftb-->Bad port index");
return OMX_ErrorBadPortIndex;
}
if (!m_sOutPortDef.bEnabled) {
DEBUG_PRINT_ERROR("ERROR: omx_video::ftb-->port is disabled");
return OMX_ErrorIncorrectStateOperation;
}
post_event((unsigned long) hComp, (unsigned long)buffer,OMX_COMPONENT_GENERATE_FTB);
return OMX_ErrorNone;
}
| 173,747
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: bool AXNodeObject::isPressed() const {
if (!isButton())
return false;
Node* node = this->getNode();
if (!node)
return false;
if (ariaRoleAttribute() == ToggleButtonRole) {
if (equalIgnoringCase(getAttribute(aria_pressedAttr), "true") ||
equalIgnoringCase(getAttribute(aria_pressedAttr), "mixed"))
return true;
return false;
}
return node->isActive();
}
Commit Message: Switch to equalIgnoringASCIICase throughout modules/accessibility
BUG=627682
Review-Url: https://codereview.chromium.org/2793913007
Cr-Commit-Position: refs/heads/master@{#461858}
CWE ID: CWE-254
|
bool AXNodeObject::isPressed() const {
if (!isButton())
return false;
Node* node = this->getNode();
if (!node)
return false;
if (ariaRoleAttribute() == ToggleButtonRole) {
if (equalIgnoringASCIICase(getAttribute(aria_pressedAttr), "true") ||
equalIgnoringASCIICase(getAttribute(aria_pressedAttr), "mixed"))
return true;
return false;
}
return node->isActive();
}
| 171,918
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: int ssl3_send_alert(SSL *s, int level, int desc)
{
/* Map tls/ssl alert value to correct one */
desc = s->method->ssl3_enc->alert_value(desc);
if (s->version == SSL3_VERSION && desc == SSL_AD_PROTOCOL_VERSION)
desc = SSL_AD_HANDSHAKE_FAILURE; /* SSL 3.0 does not have
* protocol_version alerts */
* protocol_version alerts */
if (desc < 0)
return -1;
/* If a fatal one, remove from cache */
if ((level == 2) && (s->session != NULL))
SSL_CTX_remove_session(s->session_ctx, s->session);
s->s3->alert_dispatch = 1;
s->s3->send_alert[0] = level;
* else data is still being written out, we will get written some time in
* the future
*/
return -1;
}
Commit Message:
CWE ID: CWE-200
|
int ssl3_send_alert(SSL *s, int level, int desc)
{
/* Map tls/ssl alert value to correct one */
desc = s->method->ssl3_enc->alert_value(desc);
if (s->version == SSL3_VERSION && desc == SSL_AD_PROTOCOL_VERSION)
desc = SSL_AD_HANDSHAKE_FAILURE; /* SSL 3.0 does not have
* protocol_version alerts */
* protocol_version alerts */
if (desc < 0)
return -1;
/* If a fatal one, remove from cache and go into the error state */
if (level == SSL3_AL_FATAL) {
if (s->session != NULL)
SSL_CTX_remove_session(s->session_ctx, s->session);
s->state = SSL_ST_ERR;
}
s->s3->alert_dispatch = 1;
s->s3->send_alert[0] = level;
* else data is still being written out, we will get written some time in
* the future
*/
return -1;
}
| 165,141
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void DownloadController::CreateGETDownload(
const content::ResourceRequestInfo::WebContentsGetter& wc_getter,
bool must_download,
const DownloadInfo& info) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
base::Bind(&DownloadController::StartAndroidDownload,
base::Unretained(this),
wc_getter, must_download, info));
}
Commit Message: Clean up Android DownloadManager code as most download now go through Chrome Network stack
The only exception is OMA DRM download.
And it only applies to context menu download interception.
Clean up the remaining unused code now.
BUG=647755
Review-Url: https://codereview.chromium.org/2371773003
Cr-Commit-Position: refs/heads/master@{#421332}
CWE ID: CWE-254
|
void DownloadController::CreateGETDownload(
| 171,881
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void OmniboxEditModel::RestoreState(const State* state) {
controller_->GetToolbarModel()->set_url_replacement_enabled(
!state || state->url_replacement_enabled);
permanent_text_ = controller_->GetToolbarModel()->GetText();
view_->RevertWithoutResettingSearchTermReplacement();
input_ = state ? state->autocomplete_input : AutocompleteInput();
if (!state)
return;
SetFocusState(state->focus_state, OMNIBOX_FOCUS_CHANGE_TAB_SWITCH);
focus_source_ = state->focus_source;
if (state->user_input_in_progress) {
keyword_ = state->keyword;
is_keyword_hint_ = state->is_keyword_hint;
view_->SetUserText(state->user_text,
DisplayTextFromUserText(state->user_text), false);
view_->SetGrayTextAutocompletion(state->gray_text);
}
}
Commit Message: [OriginChip] Re-enable the chip as necessary when switching tabs.
BUG=369500
Review URL: https://codereview.chromium.org/292493003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@271161 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-362
|
void OmniboxEditModel::RestoreState(const State* state) {
bool url_replacement_enabled = !state || state->url_replacement_enabled;
controller_->GetToolbarModel()->set_url_replacement_enabled(
url_replacement_enabled);
controller_->GetToolbarModel()->set_origin_chip_enabled(
url_replacement_enabled);
permanent_text_ = controller_->GetToolbarModel()->GetText();
view_->RevertWithoutResettingSearchTermReplacement();
input_ = state ? state->autocomplete_input : AutocompleteInput();
if (!state)
return;
SetFocusState(state->focus_state, OMNIBOX_FOCUS_CHANGE_TAB_SWITCH);
focus_source_ = state->focus_source;
if (state->user_input_in_progress) {
keyword_ = state->keyword;
is_keyword_hint_ = state->is_keyword_hint;
view_->SetUserText(state->user_text,
DisplayTextFromUserText(state->user_text), false);
view_->SetGrayTextAutocompletion(state->gray_text);
}
}
| 171,175
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void ResourceDispatcherHostImpl::OnSSLCertificateError(
net::URLRequest* request,
const net::SSLInfo& ssl_info,
bool is_hsts_host) {
DCHECK(request);
ResourceRequestInfoImpl* info = ResourceRequestInfoImpl::ForRequest(request);
DCHECK(info);
GlobalRequestID request_id(info->GetChildID(), info->GetRequestID());
int render_process_id;
int render_view_id;
if(!info->GetAssociatedRenderView(&render_process_id, &render_view_id))
NOTREACHED();
SSLManager::OnSSLCertificateError(ssl_delegate_weak_factory_.GetWeakPtr(),
request_id, info->GetResourceType(), request->url(), render_process_id,
render_view_id, ssl_info, is_hsts_host);
}
Commit Message: Inherits SupportsWeakPtr<T> instead of having WeakPtrFactory<T>
This change refines r137676.
BUG=122654
TEST=browser_test
Review URL: https://chromiumcodereview.appspot.com/10332233
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@139771 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119
|
void ResourceDispatcherHostImpl::OnSSLCertificateError(
net::URLRequest* request,
const net::SSLInfo& ssl_info,
bool is_hsts_host) {
DCHECK(request);
ResourceRequestInfoImpl* info = ResourceRequestInfoImpl::ForRequest(request);
DCHECK(info);
GlobalRequestID request_id(info->GetChildID(), info->GetRequestID());
int render_process_id;
int render_view_id;
if(!info->GetAssociatedRenderView(&render_process_id, &render_view_id))
NOTREACHED();
SSLManager::OnSSLCertificateError(
AsWeakPtr(), request_id, info->GetResourceType(), request->url(),
render_process_id, render_view_id, ssl_info, is_hsts_host);
}
| 170,989
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: swabHorDiff16(TIFF* tif, uint8* cp0, tmsize_t cc)
{
uint16* wp = (uint16*) cp0;
tmsize_t wc = cc / 2;
horDiff16(tif, cp0, cc);
TIFFSwabArrayOfShort(wp, wc);
}
Commit Message: * libtiff/tif_predict.h, libtiff/tif_predict.c:
Replace assertions by runtime checks to avoid assertions in debug mode,
or buffer overflows in release mode. Can happen when dealing with
unusual tile size like YCbCr with subsampling. Reported as MSVR 35105
by Axel Souchet & Vishal Chauhan from the MSRC Vulnerabilities & Mitigations
team.
CWE ID: CWE-119
|
swabHorDiff16(TIFF* tif, uint8* cp0, tmsize_t cc)
{
uint16* wp = (uint16*) cp0;
tmsize_t wc = cc / 2;
if( !horDiff16(tif, cp0, cc) )
return 0;
TIFFSwabArrayOfShort(wp, wc);
return 1;
}
| 166,890
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void ntlm_print_negotiate_flags(UINT32 flags)
{
int i;
const char* str;
WLog_INFO(TAG, "negotiateFlags \"0x%08"PRIX32"\"", flags);
for (i = 31; i >= 0; i--)
{
if ((flags >> i) & 1)
{
str = NTLM_NEGOTIATE_STRINGS[(31 - i)];
WLog_INFO(TAG, "\t%s (%d),", str, (31 - i));
}
}
}
Commit Message: Fixed CVE-2018-8789
Thanks to Eyal Itkin from Check Point Software Technologies.
CWE ID: CWE-125
|
void ntlm_print_negotiate_flags(UINT32 flags)
static void ntlm_print_negotiate_flags(UINT32 flags)
{
int i;
const char* str;
WLog_INFO(TAG, "negotiateFlags \"0x%08"PRIX32"\"", flags);
for (i = 31; i >= 0; i--)
{
if ((flags >> i) & 1)
{
str = NTLM_NEGOTIATE_STRINGS[(31 - i)];
WLog_INFO(TAG, "\t%s (%d),", str, (31 - i));
}
}
}
| 169,275
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: ikev1_cert_print(netdissect_options *ndo, u_char tpay _U_,
const struct isakmp_gen *ext, u_int item_len,
const u_char *ep _U_, uint32_t phase _U_,
uint32_t doi0 _U_,
uint32_t proto0 _U_, int depth _U_)
{
const struct ikev1_pl_cert *p;
struct ikev1_pl_cert cert;
static const char *certstr[] = {
"none", "pkcs7", "pgp", "dns",
"x509sign", "x509ke", "kerberos", "crl",
"arl", "spki", "x509attr",
};
ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_CERT)));
p = (const struct ikev1_pl_cert *)ext;
ND_TCHECK(*p);
UNALIGNED_MEMCPY(&cert, ext, sizeof(cert));
ND_PRINT((ndo," len=%d", item_len - 4));
ND_PRINT((ndo," type=%s", STR_OR_ID((cert.encode), certstr)));
if (2 < ndo->ndo_vflag && 4 < item_len) {
ND_PRINT((ndo," "));
if (!rawprint(ndo, (const uint8_t *)(ext + 1), item_len - 4))
goto trunc;
}
return (const u_char *)ext + item_len;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_CERT)));
return NULL;
}
Commit Message: CVE-2017-13690/IKEv2: Fix some bounds checks.
Use a pointer of the correct type in ND_TCHECK(), or use ND_TCHECK2()
and provide the correct length.
While we're at it, remove the blank line between some checks and the
UNALIGNED_MEMCPY()s they protect.
Also, note the places where we print the entire payload.
This fixes a buffer over-read discovered by Bhargava Shastry,
SecT/TU Berlin.
Add a test using the capture file supplied by the reporter(s).
CWE ID: CWE-125
|
ikev1_cert_print(netdissect_options *ndo, u_char tpay _U_,
const struct isakmp_gen *ext, u_int item_len,
const u_char *ep _U_, uint32_t phase _U_,
uint32_t doi0 _U_,
uint32_t proto0 _U_, int depth _U_)
{
const struct ikev1_pl_cert *p;
struct ikev1_pl_cert cert;
static const char *certstr[] = {
"none", "pkcs7", "pgp", "dns",
"x509sign", "x509ke", "kerberos", "crl",
"arl", "spki", "x509attr",
};
ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_CERT)));
p = (const struct ikev1_pl_cert *)ext;
ND_TCHECK(*p);
UNALIGNED_MEMCPY(&cert, ext, sizeof(cert));
ND_PRINT((ndo," len=%d", item_len - 4));
ND_PRINT((ndo," type=%s", STR_OR_ID((cert.encode), certstr)));
if (2 < ndo->ndo_vflag && 4 < item_len) {
/* Print the entire payload in hex */
ND_PRINT((ndo," "));
if (!rawprint(ndo, (const uint8_t *)(ext + 1), item_len - 4))
goto trunc;
}
return (const u_char *)ext + item_len;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_CERT)));
return NULL;
}
| 167,789
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static uint64_t pci_read(void *opaque, hwaddr addr, unsigned int size)
{
AcpiPciHpState *s = opaque;
uint32_t val = 0;
int bsel = s->hotplug_select;
if (bsel < 0 || bsel > ACPI_PCIHP_MAX_HOTPLUG_BUS) {
return 0;
}
switch (addr) {
case PCI_UP_BASE:
val = s->acpi_pcihp_pci_status[bsel].up;
if (!s->legacy_piix) {
s->acpi_pcihp_pci_status[bsel].up = 0;
}
ACPI_PCIHP_DPRINTF("pci_up_read %" PRIu32 "\n", val);
break;
case PCI_DOWN_BASE:
val = s->acpi_pcihp_pci_status[bsel].down;
ACPI_PCIHP_DPRINTF("pci_down_read %" PRIu32 "\n", val);
break;
case PCI_EJ_BASE:
/* No feature defined yet */
ACPI_PCIHP_DPRINTF("pci_features_read %" PRIu32 "\n", val);
break;
case PCI_RMV_BASE:
val = s->acpi_pcihp_pci_status[bsel].hotplug_enable;
ACPI_PCIHP_DPRINTF("pci_rmv_read %" PRIu32 "\n", val);
break;
case PCI_SEL_BASE:
val = s->hotplug_select;
ACPI_PCIHP_DPRINTF("pci_sel_read %" PRIu32 "\n", val);
default:
break;
}
return val;
}
Commit Message:
CWE ID: CWE-119
|
static uint64_t pci_read(void *opaque, hwaddr addr, unsigned int size)
{
AcpiPciHpState *s = opaque;
uint32_t val = 0;
int bsel = s->hotplug_select;
if (bsel < 0 || bsel >= ACPI_PCIHP_MAX_HOTPLUG_BUS) {
return 0;
}
switch (addr) {
case PCI_UP_BASE:
val = s->acpi_pcihp_pci_status[bsel].up;
if (!s->legacy_piix) {
s->acpi_pcihp_pci_status[bsel].up = 0;
}
ACPI_PCIHP_DPRINTF("pci_up_read %" PRIu32 "\n", val);
break;
case PCI_DOWN_BASE:
val = s->acpi_pcihp_pci_status[bsel].down;
ACPI_PCIHP_DPRINTF("pci_down_read %" PRIu32 "\n", val);
break;
case PCI_EJ_BASE:
/* No feature defined yet */
ACPI_PCIHP_DPRINTF("pci_features_read %" PRIu32 "\n", val);
break;
case PCI_RMV_BASE:
val = s->acpi_pcihp_pci_status[bsel].hotplug_enable;
ACPI_PCIHP_DPRINTF("pci_rmv_read %" PRIu32 "\n", val);
break;
case PCI_SEL_BASE:
val = s->hotplug_select;
ACPI_PCIHP_DPRINTF("pci_sel_read %" PRIu32 "\n", val);
default:
break;
}
return val;
}
| 165,019
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static void jpc_undo_roi(jas_matrix_t *x, int roishift, int bgshift, int numbps)
{
int i;
int j;
int thresh;
jpc_fix_t val;
jpc_fix_t mag;
bool warn;
uint_fast32_t mask;
if (roishift == 0 && bgshift == 0) {
return;
}
thresh = 1 << roishift;
warn = false;
for (i = 0; i < jas_matrix_numrows(x); ++i) {
for (j = 0; j < jas_matrix_numcols(x); ++j) {
val = jas_matrix_get(x, i, j);
mag = JAS_ABS(val);
if (mag >= thresh) {
/* We are dealing with ROI data. */
mag >>= roishift;
val = (val < 0) ? (-mag) : mag;
jas_matrix_set(x, i, j, val);
} else {
/* We are dealing with non-ROI (i.e., background) data. */
mag <<= bgshift;
mask = (1 << numbps) - 1;
/* Perform a basic sanity check on the sample value. */
/* Some implementations write garbage in the unused
most-significant bit planes introduced by ROI shifting.
Here we ensure that any such bits are masked off. */
if (mag & (~mask)) {
if (!warn) {
jas_eprintf("warning: possibly corrupt code stream\n");
warn = true;
}
mag &= mask;
}
val = (val < 0) ? (-mag) : mag;
jas_matrix_set(x, i, j, val);
}
}
}
}
Commit Message: Fixed an integral type promotion problem by adding a JAS_CAST.
Modified the jpc_tsfb_synthesize function so that it will be a noop for
an empty sequence (in order to avoid dereferencing a null pointer).
CWE ID: CWE-476
|
static void jpc_undo_roi(jas_matrix_t *x, int roishift, int bgshift, int numbps)
{
int i;
int j;
int thresh;
jpc_fix_t val;
jpc_fix_t mag;
bool warn;
uint_fast32_t mask;
if (roishift < 0) {
/* We could instead return an error here. */
/* I do not think it matters much. */
jas_eprintf("warning: forcing negative ROI shift to zero "
"(bitstream is probably corrupt)\n");
roishift = 0;
}
if (roishift == 0 && bgshift == 0) {
return;
}
thresh = 1 << roishift;
warn = false;
for (i = 0; i < jas_matrix_numrows(x); ++i) {
for (j = 0; j < jas_matrix_numcols(x); ++j) {
val = jas_matrix_get(x, i, j);
mag = JAS_ABS(val);
if (mag >= thresh) {
/* We are dealing with ROI data. */
mag >>= roishift;
val = (val < 0) ? (-mag) : mag;
jas_matrix_set(x, i, j, val);
} else {
/* We are dealing with non-ROI (i.e., background) data. */
mag <<= bgshift;
mask = (JAS_CAST(uint_fast32_t, 1) << numbps) - 1;
/* Perform a basic sanity check on the sample value. */
/* Some implementations write garbage in the unused
most-significant bit planes introduced by ROI shifting.
Here we ensure that any such bits are masked off. */
if (mag & (~mask)) {
if (!warn) {
jas_eprintf("warning: possibly corrupt code stream\n");
warn = true;
}
mag &= mask;
}
val = (val < 0) ? (-mag) : mag;
jas_matrix_set(x, i, j, val);
}
}
}
}
| 168,477
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: SPL_METHOD(SplFileInfo, getRealPath)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
char buff[MAXPATHLEN];
char *filename;
zend_error_handling error_handling;
if (zend_parse_parameters_none() == FAILURE) {
return;
}
zend_replace_error_handling(EH_THROW, spl_ce_RuntimeException, &error_handling TSRMLS_CC);
if (intern->type == SPL_FS_DIR && !intern->file_name && intern->u.dir.entry.d_name[0]) {
spl_filesystem_object_get_file_name(intern TSRMLS_CC);
}
if (intern->orig_path) {
filename = intern->orig_path;
} else {
filename = intern->file_name;
}
if (filename && VCWD_REALPATH(filename, buff)) {
#ifdef ZTS
if (VCWD_ACCESS(buff, F_OK)) {
RETVAL_FALSE;
} else
#endif
RETVAL_STRING(buff, 1);
} else {
RETVAL_FALSE;
}
zend_restore_error_handling(&error_handling TSRMLS_CC);
}
Commit Message: Fix bug #72262 - do not overflow int
CWE ID: CWE-190
|
SPL_METHOD(SplFileInfo, getRealPath)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
char buff[MAXPATHLEN];
char *filename;
zend_error_handling error_handling;
if (zend_parse_parameters_none() == FAILURE) {
return;
}
zend_replace_error_handling(EH_THROW, spl_ce_RuntimeException, &error_handling TSRMLS_CC);
if (intern->type == SPL_FS_DIR && !intern->file_name && intern->u.dir.entry.d_name[0]) {
spl_filesystem_object_get_file_name(intern TSRMLS_CC);
}
if (intern->orig_path) {
filename = intern->orig_path;
} else {
filename = intern->file_name;
}
if (filename && VCWD_REALPATH(filename, buff)) {
#ifdef ZTS
if (VCWD_ACCESS(buff, F_OK)) {
RETVAL_FALSE;
} else
#endif
RETVAL_STRING(buff, 1);
} else {
RETVAL_FALSE;
}
zend_restore_error_handling(&error_handling TSRMLS_CC);
}
| 167,039
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: XSharedMemoryId AttachSharedMemory(Display* display, int shared_memory_key) {
DCHECK(QuerySharedMemorySupport(display));
XShmSegmentInfo shminfo;
memset(&shminfo, 0, sizeof(shminfo));
shminfo.shmid = shared_memory_key;
if (!XShmAttach(display, &shminfo))
NOTREACHED();
return shminfo.shmseg;
}
Commit Message: Make shared memory segments writable only by their rightful owners.
BUG=143859
TEST=Chrome's UI still works on Linux and Chrome OS
Review URL: https://chromiumcodereview.appspot.com/10854242
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@158289 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-264
|
XSharedMemoryId AttachSharedMemory(Display* display, int shared_memory_key) {
DCHECK(QuerySharedMemorySupport(display));
XShmSegmentInfo shminfo;
memset(&shminfo, 0, sizeof(shminfo));
shminfo.shmid = shared_memory_key;
if (!XShmAttach(display, &shminfo)) {
LOG(WARNING) << "X failed to attach to shared memory segment "
<< shminfo.shmid;
NOTREACHED();
} else {
VLOG(1) << "X attached to shared memory segment " << shminfo.shmid;
}
return shminfo.shmseg;
}
| 171,593
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: SyncType GetSyncType(const Extension* extension) {
if (!IsSyncable(extension)) {
return SYNC_TYPE_NONE;
}
if (!ManifestURL::GetUpdateURL(extension).is_empty() &&
!ManifestURL::UpdatesFromGallery(extension)) {
return SYNC_TYPE_NONE;
}
if (PluginInfo::HasPlugins(extension))
return SYNC_TYPE_NONE;
switch (extension->GetType()) {
case Manifest::TYPE_EXTENSION:
return SYNC_TYPE_EXTENSION;
case Manifest::TYPE_USER_SCRIPT:
if (ManifestURL::UpdatesFromGallery(extension))
return SYNC_TYPE_EXTENSION;
return SYNC_TYPE_NONE;
case Manifest::TYPE_HOSTED_APP:
case Manifest::TYPE_LEGACY_PACKAGED_APP:
case Manifest::TYPE_PLATFORM_APP:
return SYNC_TYPE_APP;
case Manifest::TYPE_UNKNOWN:
case Manifest::TYPE_THEME:
case Manifest::TYPE_SHARED_MODULE:
return SYNC_TYPE_NONE;
}
NOTREACHED();
return SYNC_TYPE_NONE;
}
Commit Message: Fix syncing of NPAPI plugins.
This fix adds a check for |plugin| permission
while syncing NPAPI plugins.
BUG=252034
Review URL: https://chromiumcodereview.appspot.com/16816024
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@207830 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID:
|
SyncType GetSyncType(const Extension* extension) {
if (!IsSyncable(extension)) {
return SYNC_TYPE_NONE;
}
if (!ManifestURL::GetUpdateURL(extension).is_empty() &&
!ManifestURL::UpdatesFromGallery(extension)) {
return SYNC_TYPE_NONE;
}
if (PluginInfo::HasPlugins(extension) ||
extension->HasAPIPermission(APIPermission::kPlugin)) {
return SYNC_TYPE_NONE;
}
switch (extension->GetType()) {
case Manifest::TYPE_EXTENSION:
return SYNC_TYPE_EXTENSION;
case Manifest::TYPE_USER_SCRIPT:
if (ManifestURL::UpdatesFromGallery(extension))
return SYNC_TYPE_EXTENSION;
return SYNC_TYPE_NONE;
case Manifest::TYPE_HOSTED_APP:
case Manifest::TYPE_LEGACY_PACKAGED_APP:
case Manifest::TYPE_PLATFORM_APP:
return SYNC_TYPE_APP;
case Manifest::TYPE_UNKNOWN:
case Manifest::TYPE_THEME:
case Manifest::TYPE_SHARED_MODULE:
return SYNC_TYPE_NONE;
}
NOTREACHED();
return SYNC_TYPE_NONE;
}
| 171,248
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static int adjust_insn_aux_data(struct bpf_verifier_env *env, u32 prog_len,
u32 off, u32 cnt)
{
struct bpf_insn_aux_data *new_data, *old_data = env->insn_aux_data;
if (cnt == 1)
return 0;
new_data = vzalloc(sizeof(struct bpf_insn_aux_data) * prog_len);
if (!new_data)
return -ENOMEM;
memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
memcpy(new_data + off + cnt - 1, old_data + off,
sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
env->insn_aux_data = new_data;
vfree(old_data);
return 0;
}
Commit Message: bpf: fix branch pruning logic
when the verifier detects that register contains a runtime constant
and it's compared with another constant it will prune exploration
of the branch that is guaranteed not to be taken at runtime.
This is all correct, but malicious program may be constructed
in such a way that it always has a constant comparison and
the other branch is never taken under any conditions.
In this case such path through the program will not be explored
by the verifier. It won't be taken at run-time either, but since
all instructions are JITed the malicious program may cause JITs
to complain about using reserved fields, etc.
To fix the issue we have to track the instructions explored by
the verifier and sanitize instructions that are dead at run time
with NOPs. We cannot reject such dead code, since llvm generates
it for valid C code, since it doesn't do as much data flow
analysis as the verifier does.
Fixes: 17a5267067f3 ("bpf: verifier (add verifier core)")
Signed-off-by: Alexei Starovoitov <ast@kernel.org>
Acked-by: Daniel Borkmann <daniel@iogearbox.net>
Signed-off-by: Daniel Borkmann <daniel@iogearbox.net>
CWE ID: CWE-20
|
static int adjust_insn_aux_data(struct bpf_verifier_env *env, u32 prog_len,
u32 off, u32 cnt)
{
struct bpf_insn_aux_data *new_data, *old_data = env->insn_aux_data;
int i;
if (cnt == 1)
return 0;
new_data = vzalloc(sizeof(struct bpf_insn_aux_data) * prog_len);
if (!new_data)
return -ENOMEM;
memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
memcpy(new_data + off + cnt - 1, old_data + off,
sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
for (i = off; i < off + cnt - 1; i++)
new_data[i].seen = true;
env->insn_aux_data = new_data;
vfree(old_data);
return 0;
}
| 167,637
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: const Cluster* Segment::FindOrPreloadCluster(long long requested_pos) {
if (requested_pos < 0)
return 0;
Cluster** const ii = m_clusters;
Cluster** i = ii;
const long count = m_clusterCount + m_clusterPreloadCount;
Cluster** const jj = ii + count;
Cluster** j = jj;
while (i < j) {
Cluster** const k = i + (j - i) / 2;
assert(k < jj);
Cluster* const pCluster = *k;
assert(pCluster);
const long long pos = pCluster->GetPosition();
assert(pos >= 0);
if (pos < requested_pos)
i = k + 1;
else if (pos > requested_pos)
j = k;
else
return pCluster;
}
assert(i == j);
Cluster* const pCluster = Cluster::Create(this, -1, requested_pos);
assert(pCluster);
const ptrdiff_t idx = i - m_clusters;
PreloadCluster(pCluster, idx);
assert(m_clusters);
assert(m_clusterPreloadCount > 0);
assert(m_clusters[idx] == pCluster);
return pCluster;
}
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
|
const Cluster* Segment::FindOrPreloadCluster(long long requested_pos) {
if (requested_pos < 0)
return 0;
Cluster** const ii = m_clusters;
Cluster** i = ii;
const long count = m_clusterCount + m_clusterPreloadCount;
Cluster** const jj = ii + count;
Cluster** j = jj;
while (i < j) {
Cluster** const k = i + (j - i) / 2;
assert(k < jj);
Cluster* const pCluster = *k;
assert(pCluster);
const long long pos = pCluster->GetPosition();
assert(pos >= 0);
if (pos < requested_pos)
i = k + 1;
else if (pos > requested_pos)
j = k;
else
return pCluster;
}
assert(i == j);
Cluster* const pCluster = Cluster::Create(this, -1, requested_pos);
if (pCluster == NULL)
return NULL;
const ptrdiff_t idx = i - m_clusters;
if (!PreloadCluster(pCluster, idx)) {
delete pCluster;
return NULL;
}
assert(m_clusters);
assert(m_clusterPreloadCount > 0);
assert(m_clusters[idx] == pCluster);
return pCluster;
}
| 173,812
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: ext4_xattr_cache_insert(struct mb_cache *ext4_mb_cache, struct buffer_head *bh)
{
__u32 hash = le32_to_cpu(BHDR(bh)->h_hash);
struct mb_cache_entry *ce;
int error;
ce = mb_cache_entry_alloc(ext4_mb_cache, GFP_NOFS);
if (!ce) {
ea_bdebug(bh, "out of memory");
return;
}
error = mb_cache_entry_insert(ce, bh->b_bdev, bh->b_blocknr, hash);
if (error) {
mb_cache_entry_free(ce);
if (error == -EBUSY) {
ea_bdebug(bh, "already in cache");
error = 0;
}
} else {
ea_bdebug(bh, "inserting [%x]", (int)hash);
mb_cache_entry_release(ce);
}
}
Commit Message: ext4: convert to mbcache2
The conversion is generally straightforward. The only tricky part is
that xattr block corresponding to found mbcache entry can get freed
before we get buffer lock for that block. So we have to check whether
the entry is still valid after getting buffer lock.
Signed-off-by: Jan Kara <jack@suse.cz>
Signed-off-by: Theodore Ts'o <tytso@mit.edu>
CWE ID: CWE-19
|
ext4_xattr_cache_insert(struct mb_cache *ext4_mb_cache, struct buffer_head *bh)
ext4_xattr_cache_insert(struct mb2_cache *ext4_mb_cache, struct buffer_head *bh)
{
__u32 hash = le32_to_cpu(BHDR(bh)->h_hash);
int error;
error = mb2_cache_entry_create(ext4_mb_cache, GFP_NOFS, hash,
bh->b_blocknr);
if (error) {
if (error == -EBUSY)
ea_bdebug(bh, "already in cache");
} else
ea_bdebug(bh, "inserting [%x]", (int)hash);
}
| 169,992
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: bool VideoTrack::VetEntry(const BlockEntry* pBlockEntry) const
{
return Track::VetEntry(pBlockEntry) && pBlockEntry->GetBlock()->IsKey();
}
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
|
bool VideoTrack::VetEntry(const BlockEntry* pBlockEntry) const
| 174,452
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void OomInterventionImpl::Check(TimerBase*) {
DCHECK(host_);
OomInterventionMetrics current_memory = GetCurrentMemoryMetrics();
bool oom_detected = false;
oom_detected |= detection_args_->blink_workload_threshold > 0 &&
current_memory.current_blink_usage_kb * 1024 >
detection_args_->blink_workload_threshold;
oom_detected |= detection_args_->private_footprint_threshold > 0 &&
current_memory.current_private_footprint_kb * 1024 >
detection_args_->private_footprint_threshold;
oom_detected |=
detection_args_->swap_threshold > 0 &&
current_memory.current_swap_kb * 1024 > detection_args_->swap_threshold;
oom_detected |= detection_args_->virtual_memory_thresold > 0 &&
current_memory.current_vm_size_kb * 1024 >
detection_args_->virtual_memory_thresold;
ReportMemoryStats(current_memory);
if (oom_detected) {
if (navigate_ads_enabled_) {
for (const auto& page : Page::OrdinaryPages()) {
if (page->MainFrame()->IsLocalFrame()) {
ToLocalFrame(page->MainFrame())
->GetDocument()
->NavigateLocalAdsFrames();
}
}
}
if (renderer_pause_enabled_) {
pauser_.reset(new ScopedPagePauser);
}
host_->OnHighMemoryUsage();
timer_.Stop();
V8GCForContextDispose::Instance().SetForcePageNavigationGC();
}
}
Commit Message: OomIntervention opt-out should work properly with 'show original'
OomIntervention should not be re-triggered on the same page if the user declines the intervention once.
This CL fixes the bug.
Bug: 889131, 887119
Change-Id: Idb9eebb2bb9f79756b63f0e010fe018ba5c490e8
Reviewed-on: https://chromium-review.googlesource.com/1245019
Commit-Queue: Yuzu Saijo <yuzus@chromium.org>
Reviewed-by: Kentaro Hara <haraken@chromium.org>
Cr-Commit-Position: refs/heads/master@{#594574}
CWE ID: CWE-119
|
void OomInterventionImpl::Check(TimerBase*) {
DCHECK(host_);
DCHECK(renderer_pause_enabled_ || navigate_ads_enabled_);
OomInterventionMetrics current_memory = GetCurrentMemoryMetrics();
bool oom_detected = false;
oom_detected |= detection_args_->blink_workload_threshold > 0 &&
current_memory.current_blink_usage_kb * 1024 >
detection_args_->blink_workload_threshold;
oom_detected |= detection_args_->private_footprint_threshold > 0 &&
current_memory.current_private_footprint_kb * 1024 >
detection_args_->private_footprint_threshold;
oom_detected |=
detection_args_->swap_threshold > 0 &&
current_memory.current_swap_kb * 1024 > detection_args_->swap_threshold;
oom_detected |= detection_args_->virtual_memory_thresold > 0 &&
current_memory.current_vm_size_kb * 1024 >
detection_args_->virtual_memory_thresold;
ReportMemoryStats(current_memory);
if (oom_detected) {
if (navigate_ads_enabled_) {
for (const auto& page : Page::OrdinaryPages()) {
if (page->MainFrame()->IsLocalFrame()) {
ToLocalFrame(page->MainFrame())
->GetDocument()
->NavigateLocalAdsFrames();
}
}
}
if (renderer_pause_enabled_) {
pauser_.reset(new ScopedPagePauser);
}
host_->OnHighMemoryUsage();
timer_.Stop();
V8GCForContextDispose::Instance().SetForcePageNavigationGC();
}
}
| 172,115
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: cdf_count_chain(const cdf_sat_t *sat, cdf_secid_t sid, size_t size)
{
size_t i, j;
cdf_secid_t maxsector = (cdf_secid_t)(sat->sat_len * size);
DPRINTF(("Chain:"));
for (j = i = 0; sid >= 0; i++, j++) {
DPRINTF((" %d", sid));
if (j >= CDF_LOOP_LIMIT) {
DPRINTF(("Counting chain loop limit"));
errno = EFTYPE;
return (size_t)-1;
}
if (sid > maxsector) {
DPRINTF(("Sector %d > %d\n", sid, maxsector));
errno = EFTYPE;
return (size_t)-1;
}
sid = CDF_TOLE4((uint32_t)sat->sat_tab[sid]);
}
if (i == 0) {
DPRINTF((" none, sid: %d\n", sid));
return (size_t)-1;
}
DPRINTF(("\n"));
return i;
}
Commit Message: Fix incorrect bounds check for sector count. (Francisco Alonso and Jan Kaluza
at RedHat)
CWE ID: CWE-20
|
cdf_count_chain(const cdf_sat_t *sat, cdf_secid_t sid, size_t size)
{
size_t i, j;
cdf_secid_t maxsector = (cdf_secid_t)((sat->sat_len * size)
/ sizeof(maxsector));
DPRINTF(("Chain:"));
for (j = i = 0; sid >= 0; i++, j++) {
DPRINTF((" %d", sid));
if (j >= CDF_LOOP_LIMIT) {
DPRINTF(("Counting chain loop limit"));
errno = EFTYPE;
return (size_t)-1;
}
if (sid >= maxsector) {
DPRINTF(("Sector %d >= %d\n", sid, maxsector));
errno = EFTYPE;
return (size_t)-1;
}
sid = CDF_TOLE4((uint32_t)sat->sat_tab[sid]);
}
if (i == 0) {
DPRINTF((" none, sid: %d\n", sid));
return (size_t)-1;
}
DPRINTF(("\n"));
return i;
}
| 166,365
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void _xml_endElementHandler(void *userData, const XML_Char *name)
{
xml_parser *parser = (xml_parser *)userData;
char *tag_name;
if (parser) {
zval *retval, *args[2];
tag_name = _xml_decode_tag(parser, name);
if (parser->endElementHandler) {
args[0] = _xml_resource_zval(parser->index);
args[1] = _xml_string_zval(((char *) tag_name) + parser->toffset);
if ((retval = xml_call_handler(parser, parser->endElementHandler, parser->endElementPtr, 2, args))) {
zval_ptr_dtor(&retval);
}
}
if (parser->data) {
zval *tag;
if (parser->lastwasopen) {
add_assoc_string(*(parser->ctag),"type","complete",1);
} else {
MAKE_STD_ZVAL(tag);
array_init(tag);
_xml_add_to_info(parser,((char *) tag_name) + parser->toffset);
add_assoc_string(tag,"tag",((char *) tag_name) + parser->toffset,1); /* cast to avoid gcc-warning */
add_assoc_string(tag,"type","close",1);
add_assoc_long(tag,"level",parser->level);
zend_hash_next_index_insert(Z_ARRVAL_P(parser->data),&tag,sizeof(zval*),NULL);
}
parser->lastwasopen = 0;
}
efree(tag_name);
if ((parser->ltags) && (parser->level <= XML_MAXLEVEL)) {
efree(parser->ltags[parser->level-1]);
}
parser->level--;
}
}
Commit Message:
CWE ID: CWE-119
|
void _xml_endElementHandler(void *userData, const XML_Char *name)
{
xml_parser *parser = (xml_parser *)userData;
char *tag_name;
if (parser) {
zval *retval, *args[2];
tag_name = _xml_decode_tag(parser, name);
if (parser->endElementHandler) {
args[0] = _xml_resource_zval(parser->index);
args[1] = _xml_string_zval(((char *) tag_name) + parser->toffset);
if ((retval = xml_call_handler(parser, parser->endElementHandler, parser->endElementPtr, 2, args))) {
zval_ptr_dtor(&retval);
}
}
if (parser->data) {
zval *tag;
if (parser->lastwasopen) {
add_assoc_string(*(parser->ctag),"type","complete",1);
} else {
MAKE_STD_ZVAL(tag);
array_init(tag);
_xml_add_to_info(parser,((char *) tag_name) + parser->toffset);
add_assoc_string(tag,"tag",((char *) tag_name) + parser->toffset,1); /* cast to avoid gcc-warning */
add_assoc_string(tag,"type","close",1);
add_assoc_long(tag,"level",parser->level);
zend_hash_next_index_insert(Z_ARRVAL_P(parser->data),&tag,sizeof(zval*),NULL);
}
parser->lastwasopen = 0;
}
efree(tag_name);
if ((parser->ltags) && (parser->level <= XML_MAXLEVEL)) {
efree(parser->ltags[parser->level-1]);
}
parser->level--;
}
}
| 165,041
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static int parallels_open(BlockDriverState *bs, QDict *options, int flags,
Error **errp)
{
BDRVParallelsState *s = bs->opaque;
int i;
struct parallels_header ph;
int ret;
bs->read_only = 1; // no write support yet
ret = bdrv_pread(bs->file, 0, &ph, sizeof(ph));
if (ret < 0) {
goto fail;
}
if (memcmp(ph.magic, HEADER_MAGIC, 16) ||
(le32_to_cpu(ph.version) != HEADER_VERSION)) {
error_setg(errp, "Image not in Parallels format");
ret = -EINVAL;
goto fail;
}
bs->total_sectors = le32_to_cpu(ph.nb_sectors);
s->tracks = le32_to_cpu(ph.tracks);
s->catalog_size = le32_to_cpu(ph.catalog_entries);
s->catalog_bitmap = g_malloc(s->catalog_size * 4);
ret = bdrv_pread(bs->file, 64, s->catalog_bitmap, s->catalog_size * 4);
le32_to_cpus(&s->catalog_bitmap[i]);
qemu_co_mutex_init(&s->lock);
return 0;
fail:
g_free(s->catalog_bitmap);
return ret;
}
Commit Message:
CWE ID: CWE-190
|
static int parallels_open(BlockDriverState *bs, QDict *options, int flags,
Error **errp)
{
BDRVParallelsState *s = bs->opaque;
int i;
struct parallels_header ph;
int ret;
bs->read_only = 1; // no write support yet
ret = bdrv_pread(bs->file, 0, &ph, sizeof(ph));
if (ret < 0) {
goto fail;
}
if (memcmp(ph.magic, HEADER_MAGIC, 16) ||
(le32_to_cpu(ph.version) != HEADER_VERSION)) {
error_setg(errp, "Image not in Parallels format");
ret = -EINVAL;
goto fail;
}
bs->total_sectors = le32_to_cpu(ph.nb_sectors);
s->tracks = le32_to_cpu(ph.tracks);
s->catalog_size = le32_to_cpu(ph.catalog_entries);
if (s->catalog_size > INT_MAX / 4) {
error_setg(errp, "Catalog too large");
ret = -EFBIG;
goto fail;
}
s->catalog_bitmap = g_malloc(s->catalog_size * 4);
ret = bdrv_pread(bs->file, 64, s->catalog_bitmap, s->catalog_size * 4);
le32_to_cpus(&s->catalog_bitmap[i]);
qemu_co_mutex_init(&s->lock);
return 0;
fail:
g_free(s->catalog_bitmap);
return ret;
}
| 165,410
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: bool GesturePoint::IsOverMinFlickSpeed() {
return velocity_calculator_.VelocitySquared() > kMinFlickSpeedSquared;
}
Commit Message: Add setters for the aura gesture recognizer constants.
BUG=113227
TEST=none
Review URL: http://codereview.chromium.org/9372040
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@122586 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20
|
bool GesturePoint::IsOverMinFlickSpeed() {
return velocity_calculator_.VelocitySquared() >
GestureConfiguration::min_flick_speed_squared();
}
| 171,045
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: bool TextureManager::TextureInfo::ValidForTexture(
GLint face,
GLint level,
GLint xoffset,
GLint yoffset,
GLsizei width,
GLsizei height,
GLenum format,
GLenum type) const {
size_t face_index = GLTargetToFaceIndex(face);
if (level >= 0 && face_index < level_infos_.size() &&
static_cast<size_t>(level) < level_infos_[face_index].size()) {
const LevelInfo& info = level_infos_[GLTargetToFaceIndex(face)][level];
GLint right;
GLint top;
return SafeAdd(xoffset, width, &right) &&
SafeAdd(yoffset, height, &top) &&
xoffset >= 0 &&
yoffset >= 0 &&
right <= info.width &&
top <= info.height &&
format == info.internal_format &&
type == info.type;
}
return false;
}
Commit Message: Fix SafeAdd and SafeMultiply
BUG=145648,145544
Review URL: https://chromiumcodereview.appspot.com/10916165
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@155478 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-189
|
bool TextureManager::TextureInfo::ValidForTexture(
GLint face,
GLint level,
GLint xoffset,
GLint yoffset,
GLsizei width,
GLsizei height,
GLenum format,
GLenum type) const {
size_t face_index = GLTargetToFaceIndex(face);
if (level >= 0 && face_index < level_infos_.size() &&
static_cast<size_t>(level) < level_infos_[face_index].size()) {
const LevelInfo& info = level_infos_[GLTargetToFaceIndex(face)][level];
int32 right;
int32 top;
return SafeAddInt32(xoffset, width, &right) &&
SafeAddInt32(yoffset, height, &top) &&
xoffset >= 0 &&
yoffset >= 0 &&
right <= info.width &&
top <= info.height &&
format == info.internal_format &&
type == info.type;
}
return false;
}
| 170,752
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: frag6_print(netdissect_options *ndo, register const u_char *bp, register const u_char *bp2)
{
register const struct ip6_frag *dp;
register const struct ip6_hdr *ip6;
dp = (const struct ip6_frag *)bp;
ip6 = (const struct ip6_hdr *)bp2;
ND_TCHECK(dp->ip6f_offlg);
if (ndo->ndo_vflag) {
ND_PRINT((ndo, "frag (0x%08x:%d|%ld)",
EXTRACT_32BITS(&dp->ip6f_ident),
EXTRACT_16BITS(&dp->ip6f_offlg) & IP6F_OFF_MASK,
sizeof(struct ip6_hdr) + EXTRACT_16BITS(&ip6->ip6_plen) -
(long)(bp - bp2) - sizeof(struct ip6_frag)));
} else {
ND_PRINT((ndo, "frag (%d|%ld)",
EXTRACT_16BITS(&dp->ip6f_offlg) & IP6F_OFF_MASK,
sizeof(struct ip6_hdr) + EXTRACT_16BITS(&ip6->ip6_plen) -
(long)(bp - bp2) - sizeof(struct ip6_frag)));
}
/* it is meaningless to decode non-first fragment */
if ((EXTRACT_16BITS(&dp->ip6f_offlg) & IP6F_OFF_MASK) != 0)
return -1;
else
{
ND_PRINT((ndo, " "));
return sizeof(struct ip6_frag);
}
trunc:
ND_PRINT((ndo, "[|frag]"));
return -1;
}
Commit Message: CVE-2017-13031/Check for the presence of the entire IPv6 fragment header.
This fixes a buffer over-read discovered by Bhargava Shastry,
SecT/TU Berlin.
Add a test using the capture file supplied by the reporter(s), modified
so the capture file won't be rejected as an invalid capture.
Clean up some whitespace in tests/TESTLIST while we're at it.
CWE ID: CWE-125
|
frag6_print(netdissect_options *ndo, register const u_char *bp, register const u_char *bp2)
{
register const struct ip6_frag *dp;
register const struct ip6_hdr *ip6;
dp = (const struct ip6_frag *)bp;
ip6 = (const struct ip6_hdr *)bp2;
ND_TCHECK(*dp);
if (ndo->ndo_vflag) {
ND_PRINT((ndo, "frag (0x%08x:%d|%ld)",
EXTRACT_32BITS(&dp->ip6f_ident),
EXTRACT_16BITS(&dp->ip6f_offlg) & IP6F_OFF_MASK,
sizeof(struct ip6_hdr) + EXTRACT_16BITS(&ip6->ip6_plen) -
(long)(bp - bp2) - sizeof(struct ip6_frag)));
} else {
ND_PRINT((ndo, "frag (%d|%ld)",
EXTRACT_16BITS(&dp->ip6f_offlg) & IP6F_OFF_MASK,
sizeof(struct ip6_hdr) + EXTRACT_16BITS(&ip6->ip6_plen) -
(long)(bp - bp2) - sizeof(struct ip6_frag)));
}
/* it is meaningless to decode non-first fragment */
if ((EXTRACT_16BITS(&dp->ip6f_offlg) & IP6F_OFF_MASK) != 0)
return -1;
else
{
ND_PRINT((ndo, " "));
return sizeof(struct ip6_frag);
}
trunc:
ND_PRINT((ndo, "[|frag]"));
return -1;
}
| 167,852
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: long SimpleBlock::Parse()
{
return m_block.Parse(m_pCluster);
}
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 SimpleBlock::Parse()
| 174,410
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void DocumentLoader::DetachFromFrame() {
DCHECK(frame_);
fetcher_->StopFetching();
if (frame_ && !SentDidFinishLoad())
LoadFailed(ResourceError::CancelledError(Url()));
fetcher_->ClearContext();
if (!frame_)
return;
application_cache_host_->DetachFromDocumentLoader();
application_cache_host_.Clear();
service_worker_network_provider_ = nullptr;
WeakIdentifierMap<DocumentLoader>::NotifyObjectDestroyed(this);
ClearResource();
frame_ = nullptr;
}
Commit Message: Fix detach with open()ed document leaving parent loading indefinitely
Change-Id: I26c2a054b9f1e5eb076acd677e1223058825f6d6
Bug: 803416
Test: fast/loader/document-open-iframe-then-detach.html
Change-Id: I26c2a054b9f1e5eb076acd677e1223058825f6d6
Reviewed-on: https://chromium-review.googlesource.com/887298
Reviewed-by: Mike West <mkwst@chromium.org>
Commit-Queue: Nate Chapin <japhet@chromium.org>
Cr-Commit-Position: refs/heads/master@{#532967}
CWE ID: CWE-362
|
void DocumentLoader::DetachFromFrame() {
void DocumentLoader::StopLoading() {
fetcher_->StopFetching();
if (frame_ && !SentDidFinishLoad())
LoadFailed(ResourceError::CancelledError(Url()));
}
void DocumentLoader::DetachFromFrame() {
DCHECK(frame_);
StopLoading();
fetcher_->ClearContext();
if (!frame_)
return;
application_cache_host_->DetachFromDocumentLoader();
application_cache_host_.Clear();
service_worker_network_provider_ = nullptr;
WeakIdentifierMap<DocumentLoader>::NotifyObjectDestroyed(this);
ClearResource();
frame_ = nullptr;
}
| 171,851
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: PHP_FUNCTION(snmp_set_enum_print)
{
long a1;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &a1) == FAILURE) {
RETURN_FALSE;
}
netsnmp_ds_set_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_PRINT_NUMERIC_ENUM, (int) a1);
RETURN_TRUE;
}
Commit Message:
CWE ID: CWE-416
|
PHP_FUNCTION(snmp_set_enum_print)
{
long a1;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &a1) == FAILURE) {
RETURN_FALSE;
}
netsnmp_ds_set_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_PRINT_NUMERIC_ENUM, (int) a1);
RETURN_TRUE;
| 164,970
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: cib_timeout_handler(gpointer data)
{
struct timer_rec_s *timer = data;
timer_expired = TRUE;
crm_err("Call %d timed out after %ds", timer->call_id, timer->timeout);
/* Always return TRUE, never remove the handler
* We do that after the while-loop in cib_native_perform_op()
*/
return TRUE;
}
Commit Message: High: core: Internal tls api improvements for reuse with future LRMD tls backend.
CWE ID: CWE-399
|
cib_timeout_handler(gpointer data)
| 166,154
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: GpuChannelHost::GpuChannelHost(
GpuChannelHostFactory* factory, int gpu_process_id, int client_id)
: factory_(factory),
gpu_process_id_(gpu_process_id),
client_id_(client_id),
state_(kUnconnected) {
}
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:
|
GpuChannelHost::GpuChannelHost(
GpuChannelHostFactory* factory, int gpu_host_id, int client_id)
: factory_(factory),
client_id_(client_id),
gpu_host_id_(gpu_host_id),
state_(kUnconnected) {
}
| 170,929
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static inline realpath_cache_bucket* realpath_cache_find(const char *path, int path_len, time_t t TSRMLS_DC) /* {{{ */
{
#ifdef PHP_WIN32
unsigned long key = realpath_cache_key(path, path_len TSRMLS_CC);
#else
unsigned long key = realpath_cache_key(path, path_len);
#endif
unsigned long n = key % (sizeof(CWDG(realpath_cache)) / sizeof(CWDG(realpath_cache)[0]));
realpath_cache_bucket **bucket = &CWDG(realpath_cache)[n];
while (*bucket != NULL) {
if (CWDG(realpath_cache_ttl) && (*bucket)->expires < t) {
realpath_cache_bucket *r = *bucket;
*bucket = (*bucket)->next;
/* if the pointers match then only subtract the length of the path */
if(r->path == r->realpath) {
CWDG(realpath_cache_size) -= sizeof(realpath_cache_bucket) + r->path_len + 1;
} else {
CWDG(realpath_cache_size) -= sizeof(realpath_cache_bucket) + r->path_len + 1 + r->realpath_len + 1;
}
free(r);
} else if (key == (*bucket)->key && path_len == (*bucket)->path_len &&
memcmp(path, (*bucket)->path, path_len) == 0) {
return *bucket;
} else {
bucket = &(*bucket)->next;
}
}
return NULL;
}
/* }}} */
Commit Message:
CWE ID: CWE-190
|
static inline realpath_cache_bucket* realpath_cache_find(const char *path, int path_len, time_t t TSRMLS_DC) /* {{{ */
{
#ifdef PHP_WIN32
unsigned long key = realpath_cache_key(path, path_len TSRMLS_CC);
#else
unsigned long key = realpath_cache_key(path, path_len);
#endif
unsigned long n = key % (sizeof(CWDG(realpath_cache)) / sizeof(CWDG(realpath_cache)[0]));
realpath_cache_bucket **bucket = &CWDG(realpath_cache)[n];
while (*bucket != NULL) {
if (CWDG(realpath_cache_ttl) && (*bucket)->expires < t) {
realpath_cache_bucket *r = *bucket;
*bucket = (*bucket)->next;
/* if the pointers match then only subtract the length of the path */
if(r->path == r->realpath) {
CWDG(realpath_cache_size) -= sizeof(realpath_cache_bucket) + r->path_len + 1;
} else {
CWDG(realpath_cache_size) -= sizeof(realpath_cache_bucket) + r->path_len + 1 + r->realpath_len + 1;
}
free(r);
} else if (key == (*bucket)->key && path_len == (*bucket)->path_len &&
memcmp(path, (*bucket)->path, path_len) == 0) {
return *bucket;
} else {
bucket = &(*bucket)->next;
}
}
return NULL;
}
/* }}} */
| 164,983
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static bool dump_fd_info(const char *dest_filename, char *source_filename, int source_base_ofs, uid_t uid, gid_t gid)
{
FILE *fp = fopen(dest_filename, "w");
if (!fp)
return false;
unsigned fd = 0;
while (fd <= 99999) /* paranoia check */
{
sprintf(source_filename + source_base_ofs, "fd/%u", fd);
char *name = malloc_readlink(source_filename);
if (!name)
break;
fprintf(fp, "%u:%s\n", fd, name);
free(name);
sprintf(source_filename + source_base_ofs, "fdinfo/%u", fd);
fd++;
FILE *in = fopen(source_filename, "r");
if (!in)
continue;
char buf[128];
while (fgets(buf, sizeof(buf)-1, in))
{
/* in case the line is not terminated, terminate it */
char *eol = strchrnul(buf, '\n');
eol[0] = '\n';
eol[1] = '\0';
fputs(buf, fp);
}
fclose(in);
}
const int dest_fd = fileno(fp);
if (fchown(dest_fd, uid, gid) < 0)
{
perror_msg("Can't change '%s' ownership to %lu:%lu", dest_filename, (long)uid, (long)gid);
fclose(fp);
unlink(dest_filename);
return false;
}
fclose(fp);
return true;
}
Commit Message: ccpp: open file for dump_fd_info with O_EXCL
To avoid possible races.
Related: #1211835
Signed-off-by: Jakub Filak <jfilak@redhat.com>
CWE ID: CWE-59
|
static bool dump_fd_info(const char *dest_filename, char *source_filename, int source_base_ofs, uid_t uid, gid_t gid)
{
FILE *fp = fopen(dest_filename, "wx");
if (!fp)
return false;
unsigned fd = 0;
while (fd <= 99999) /* paranoia check */
{
sprintf(source_filename + source_base_ofs, "fd/%u", fd);
char *name = malloc_readlink(source_filename);
if (!name)
break;
fprintf(fp, "%u:%s\n", fd, name);
free(name);
sprintf(source_filename + source_base_ofs, "fdinfo/%u", fd);
fd++;
FILE *in = fopen(source_filename, "r");
if (!in)
continue;
char buf[128];
while (fgets(buf, sizeof(buf)-1, in))
{
/* in case the line is not terminated, terminate it */
char *eol = strchrnul(buf, '\n');
eol[0] = '\n';
eol[1] = '\0';
fputs(buf, fp);
}
fclose(in);
}
const int dest_fd = fileno(fp);
if (fchown(dest_fd, uid, gid) < 0)
{
perror_msg("Can't change '%s' ownership to %lu:%lu", dest_filename, (long)uid, (long)gid);
fclose(fp);
unlink(dest_filename);
return false;
}
fclose(fp);
return true;
}
| 170,138
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void close_all_sockets(atransport* t) {
asocket* s;
/* this is a little gross, but since s->close() *will* modify
** the list out from under you, your options are limited.
*/
std::lock_guard<std::recursive_mutex> lock(local_socket_list_lock);
restart:
for (s = local_socket_list.next; s != &local_socket_list; s = s->next) {
if (s->transport == t || (s->peer && s->peer->transport == t)) {
local_socket_close(s);
goto restart;
}
}
}
Commit Message: adb: use asocket's close function when closing.
close_all_sockets was assuming that all registered local sockets used
local_socket_close as their close function. However, this is not true
for JDWP sockets.
Bug: http://b/28347842
Change-Id: I40a1174845cd33f15f30ce70828a7081cd5a087e
(cherry picked from commit 53eb31d87cb84a4212f4850bf745646e1fb12814)
CWE ID: CWE-264
|
void close_all_sockets(atransport* t) {
asocket* s;
/* this is a little gross, but since s->close() *will* modify
** the list out from under you, your options are limited.
*/
std::lock_guard<std::recursive_mutex> lock(local_socket_list_lock);
restart:
for (s = local_socket_list.next; s != &local_socket_list; s = s->next) {
if (s->transport == t || (s->peer && s->peer->transport == t)) {
s->close(s);
goto restart;
}
}
}
| 173,405
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void ntlm_populate_message_header(NTLM_MESSAGE_HEADER* header, UINT32 MessageType)
{
CopyMemory(header->Signature, NTLM_SIGNATURE, sizeof(NTLM_SIGNATURE));
header->MessageType = MessageType;
}
Commit Message: Fixed CVE-2018-8789
Thanks to Eyal Itkin from Check Point Software Technologies.
CWE ID: CWE-125
|
void ntlm_populate_message_header(NTLM_MESSAGE_HEADER* header, UINT32 MessageType)
static void ntlm_populate_message_header(NTLM_MESSAGE_HEADER* header, UINT32 MessageType)
{
CopyMemory(header->Signature, NTLM_SIGNATURE, sizeof(NTLM_SIGNATURE));
header->MessageType = MessageType;
}
| 169,273
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: bool Performance::PassesTimingAllowCheck(
const ResourceResponse& response,
const SecurityOrigin& initiator_security_origin,
const AtomicString& original_timing_allow_origin,
ExecutionContext* context) {
scoped_refptr<const SecurityOrigin> resource_origin =
SecurityOrigin::Create(response.Url());
if (resource_origin->IsSameSchemeHostPort(&initiator_security_origin))
return true;
const AtomicString& timing_allow_origin_string =
original_timing_allow_origin.IsEmpty()
? response.HttpHeaderField(HTTPNames::Timing_Allow_Origin)
: original_timing_allow_origin;
if (timing_allow_origin_string.IsEmpty() ||
EqualIgnoringASCIICase(timing_allow_origin_string, "null"))
return false;
if (timing_allow_origin_string == "*") {
UseCounter::Count(context, WebFeature::kStarInTimingAllowOrigin);
return true;
}
const String& security_origin = initiator_security_origin.ToString();
Vector<String> timing_allow_origins;
timing_allow_origin_string.GetString().Split(',', timing_allow_origins);
if (timing_allow_origins.size() > 1) {
UseCounter::Count(context, WebFeature::kMultipleOriginsInTimingAllowOrigin);
} else if (timing_allow_origins.size() == 1 &&
timing_allow_origin_string != "*") {
UseCounter::Count(context, WebFeature::kSingleOriginInTimingAllowOrigin);
}
for (const String& allow_origin : timing_allow_origins) {
const String allow_origin_stripped = allow_origin.StripWhiteSpace();
if (allow_origin_stripped == security_origin ||
allow_origin_stripped == "*") {
return true;
}
}
return false;
}
Commit Message: Fix timing allow check algorithm for service workers
This CL uses the OriginalURLViaServiceWorker() in the timing allow check
algorithm if the response WasFetchedViaServiceWorker(). This way, if a
service worker changes a same origin request to become cross origin,
then the timing allow check algorithm will still fail.
resource-timing-worker.js is changed so it avoids an empty Response,
which is an odd case in terms of same origin checks.
Bug: 837275
Change-Id: I7e497a6fcc2ee14244121b915ca5f5cceded417a
Reviewed-on: https://chromium-review.googlesource.com/1038229
Commit-Queue: Nicolás Peña Moreno <npm@chromium.org>
Reviewed-by: Yoav Weiss <yoav@yoav.ws>
Reviewed-by: Timothy Dresser <tdresser@chromium.org>
Cr-Commit-Position: refs/heads/master@{#555476}
CWE ID: CWE-200
|
bool Performance::PassesTimingAllowCheck(
const ResourceResponse& response,
const SecurityOrigin& initiator_security_origin,
const AtomicString& original_timing_allow_origin,
ExecutionContext* context) {
const KURL& response_url = response.WasFetchedViaServiceWorker()
? response.OriginalURLViaServiceWorker()
: response.Url();
scoped_refptr<const SecurityOrigin> resource_origin =
SecurityOrigin::Create(response_url);
if (resource_origin->IsSameSchemeHostPort(&initiator_security_origin))
return true;
const AtomicString& timing_allow_origin_string =
original_timing_allow_origin.IsEmpty()
? response.HttpHeaderField(HTTPNames::Timing_Allow_Origin)
: original_timing_allow_origin;
if (timing_allow_origin_string.IsEmpty() ||
EqualIgnoringASCIICase(timing_allow_origin_string, "null"))
return false;
if (timing_allow_origin_string == "*") {
UseCounter::Count(context, WebFeature::kStarInTimingAllowOrigin);
return true;
}
const String& security_origin = initiator_security_origin.ToString();
Vector<String> timing_allow_origins;
timing_allow_origin_string.GetString().Split(',', timing_allow_origins);
if (timing_allow_origins.size() > 1) {
UseCounter::Count(context, WebFeature::kMultipleOriginsInTimingAllowOrigin);
} else if (timing_allow_origins.size() == 1 &&
timing_allow_origin_string != "*") {
UseCounter::Count(context, WebFeature::kSingleOriginInTimingAllowOrigin);
}
for (const String& allow_origin : timing_allow_origins) {
const String allow_origin_stripped = allow_origin.StripWhiteSpace();
if (allow_origin_stripped == security_origin ||
allow_origin_stripped == "*") {
return true;
}
}
return false;
}
| 173,143
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static size_t exif_convert_any_to_int(void *value, int format, int motorola_intel TSRMLS_DC)
{
int s_den;
unsigned u_den;
switch(format) {
case TAG_FMT_SBYTE: return *(signed char *)value;
case TAG_FMT_BYTE: return *(uchar *)value;
case TAG_FMT_USHORT: return php_ifd_get16u(value, motorola_intel);
case TAG_FMT_ULONG: return php_ifd_get32u(value, motorola_intel);
case TAG_FMT_URATIONAL:
u_den = php_ifd_get32u(4+(char *)value, motorola_intel);
if (u_den == 0) {
return 0;
} else {
return php_ifd_get32u(value, motorola_intel) / u_den;
}
case TAG_FMT_SRATIONAL:
s_den = php_ifd_get32s(4+(char *)value, motorola_intel);
if (s_den == 0) {
return 0;
} else {
return php_ifd_get32s(value, motorola_intel) / s_den;
}
case TAG_FMT_SSHORT: return php_ifd_get16u(value, motorola_intel);
case TAG_FMT_SLONG: return php_ifd_get32s(value, motorola_intel);
/* Not sure if this is correct (never seen float used in Exif format) */
case TAG_FMT_SINGLE:
#ifdef EXIF_DEBUG
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Found value of type single");
#endif
return (size_t)*(float *)value;
case TAG_FMT_DOUBLE:
#ifdef EXIF_DEBUG
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Found value of type double");
#endif
return (size_t)*(double *)value;
}
return 0;
}
Commit Message: Fix bug #73737 FPE when parsing a tag format
CWE ID: CWE-189
|
static size_t exif_convert_any_to_int(void *value, int format, int motorola_intel TSRMLS_DC)
{
int s_den;
unsigned u_den;
switch(format) {
case TAG_FMT_SBYTE: return *(signed char *)value;
case TAG_FMT_BYTE: return *(uchar *)value;
case TAG_FMT_USHORT: return php_ifd_get16u(value, motorola_intel);
case TAG_FMT_ULONG: return php_ifd_get32u(value, motorola_intel);
case TAG_FMT_URATIONAL:
u_den = php_ifd_get32u(4+(char *)value, motorola_intel);
if (u_den == 0) {
return 0;
} else {
return php_ifd_get32u(value, motorola_intel) / u_den;
}
case TAG_FMT_SRATIONAL:
s_den = php_ifd_get32s(4+(char *)value, motorola_intel);
if (s_den == 0) {
return 0;
} else {
return (size_t)((double)php_ifd_get32s(value, motorola_intel) / s_den);
}
case TAG_FMT_SSHORT: return php_ifd_get16u(value, motorola_intel);
case TAG_FMT_SLONG: return php_ifd_get32s(value, motorola_intel);
/* Not sure if this is correct (never seen float used in Exif format) */
case TAG_FMT_SINGLE:
#ifdef EXIF_DEBUG
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Found value of type single");
#endif
return (size_t)*(float *)value;
case TAG_FMT_DOUBLE:
#ifdef EXIF_DEBUG
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Found value of type double");
#endif
return (size_t)*(double *)value;
}
return 0;
}
| 168,516
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static void *bpf_any_get(void *raw, enum bpf_type type)
{
switch (type) {
case BPF_TYPE_PROG:
atomic_inc(&((struct bpf_prog *)raw)->aux->refcnt);
break;
case BPF_TYPE_MAP:
bpf_map_inc(raw, true);
break;
default:
WARN_ON_ONCE(1);
break;
}
return raw;
}
Commit Message: bpf: fix refcnt overflow
On a system with >32Gbyte of phyiscal memory and infinite RLIMIT_MEMLOCK,
the malicious application may overflow 32-bit bpf program refcnt.
It's also possible to overflow map refcnt on 1Tb system.
Impose 32k hard limit which means that the same bpf program or
map cannot be shared by more than 32k processes.
Fixes: 1be7f75d1668 ("bpf: enable non-root eBPF programs")
Reported-by: Jann Horn <jannh@google.com>
Signed-off-by: Alexei Starovoitov <ast@kernel.org>
Acked-by: Daniel Borkmann <daniel@iogearbox.net>
Signed-off-by: David S. Miller <davem@davemloft.net>
CWE ID:
|
static void *bpf_any_get(void *raw, enum bpf_type type)
{
switch (type) {
case BPF_TYPE_PROG:
raw = bpf_prog_inc(raw);
break;
case BPF_TYPE_MAP:
raw = bpf_map_inc(raw, true);
break;
default:
WARN_ON_ONCE(1);
break;
}
return raw;
}
| 167,250
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static void copyStereo24(
short *dst,
const int *const *src,
unsigned nSamples,
unsigned /* nChannels */) {
for (unsigned i = 0; i < nSamples; ++i) {
*dst++ = src[0][i] >> 8;
*dst++ = src[1][i] >> 8;
}
}
Commit Message: FLACExtractor: copy protect mWriteBuffer
Bug: 30895578
Change-Id: I4cba36bbe3502678210e5925181683df9726b431
CWE ID: CWE-119
|
static void copyStereo24(
short *dst,
const int * src[FLACParser::kMaxChannels],
unsigned nSamples,
unsigned /* nChannels */) {
for (unsigned i = 0; i < nSamples; ++i) {
*dst++ = src[0][i] >> 8;
*dst++ = src[1][i] >> 8;
}
}
| 174,022
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: status_t OMXNodeInstance::sendCommand(
OMX_COMMANDTYPE cmd, OMX_S32 param) {
const sp<GraphicBufferSource>& bufferSource(getGraphicBufferSource());
if (bufferSource != NULL && cmd == OMX_CommandStateSet) {
if (param == OMX_StateIdle) {
bufferSource->omxIdle();
} else if (param == OMX_StateLoaded) {
bufferSource->omxLoaded();
setGraphicBufferSource(NULL);
}
}
Mutex::Autolock autoLock(mLock);
{
Mutex::Autolock _l(mDebugLock);
bumpDebugLevel_l(2 /* numInputBuffers */, 2 /* numOutputBuffers */);
}
const char *paramString =
cmd == OMX_CommandStateSet ? asString((OMX_STATETYPE)param) : portString(param);
CLOG_STATE(sendCommand, "%s(%d), %s(%d)", asString(cmd), cmd, paramString, param);
OMX_ERRORTYPE err = OMX_SendCommand(mHandle, cmd, param, NULL);
CLOG_IF_ERROR(sendCommand, err, "%s(%d), %s(%d)", asString(cmd), cmd, paramString, param);
return StatusFromOMXError(err);
}
Commit Message: DO NOT MERGE: IOMX: work against metadata buffer spoofing
- Prohibit direct set/getParam/Settings for extensions meant for
OMXNodeInstance alone. This disallows enabling metadata mode
without the knowledge of OMXNodeInstance.
- Use a backup buffer for metadata mode buffers and do not directly
share with clients.
- Disallow setting up metadata mode/tunneling/input surface
after first sendCommand.
- Disallow store-meta for input cross process.
- Disallow emptyBuffer for surface input (via IOMX).
- Fix checking for input surface.
Bug: 29422020
Change-Id: I801c77b80e703903f62e42d76fd2e76a34e4bc8e
(cherry picked from commit 7c3c2fa3e233c656fc8c2fc2a6634b3ecf8a23e8)
CWE ID: CWE-200
|
status_t OMXNodeInstance::sendCommand(
OMX_COMMANDTYPE cmd, OMX_S32 param) {
if (cmd == OMX_CommandStateSet) {
// We do not support returning from unloaded state, so there are no configurations past
// first StateSet command.
mSailed = true;
}
const sp<GraphicBufferSource> bufferSource(getGraphicBufferSource());
if (bufferSource != NULL && cmd == OMX_CommandStateSet) {
if (param == OMX_StateIdle) {
bufferSource->omxIdle();
} else if (param == OMX_StateLoaded) {
bufferSource->omxLoaded();
setGraphicBufferSource(NULL);
}
}
Mutex::Autolock autoLock(mLock);
{
Mutex::Autolock _l(mDebugLock);
bumpDebugLevel_l(2 /* numInputBuffers */, 2 /* numOutputBuffers */);
}
const char *paramString =
cmd == OMX_CommandStateSet ? asString((OMX_STATETYPE)param) : portString(param);
CLOG_STATE(sendCommand, "%s(%d), %s(%d)", asString(cmd), cmd, paramString, param);
OMX_ERRORTYPE err = OMX_SendCommand(mHandle, cmd, param, NULL);
CLOG_IF_ERROR(sendCommand, err, "%s(%d), %s(%d)", asString(cmd), cmd, paramString, param);
return StatusFromOMXError(err);
}
| 174,137
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: cfm_network_addr_print(netdissect_options *ndo,
register const u_char *tptr)
{
u_int network_addr_type;
u_int hexdump = FALSE;
/*
* Altough AFIs are tpically 2 octects wide,
* 802.1ab specifies that this field width
* is only once octet
*/
network_addr_type = *tptr;
ND_PRINT((ndo, "\n\t Network Address Type %s (%u)",
tok2str(af_values, "Unknown", network_addr_type),
network_addr_type));
/*
* Resolve the passed in Address.
*/
switch(network_addr_type) {
case AFNUM_INET:
ND_PRINT((ndo, ", %s", ipaddr_string(ndo, tptr + 1)));
break;
case AFNUM_INET6:
ND_PRINT((ndo, ", %s", ip6addr_string(ndo, tptr + 1)));
break;
default:
hexdump = TRUE;
break;
}
return hexdump;
}
Commit Message: CVE-2017-13052/CFM: refine decoding of the Sender ID TLV
In cfm_network_addr_print() add a length argument and use it to validate
the input buffer.
In cfm_print() add a length check for MAC address chassis ID. Supply
cfm_network_addr_print() with the length of its buffer and a correct
pointer to the buffer (it was off-by-one before). Change some error
handling blocks to skip to the next TLV in the current PDU rather than to
stop decoding the PDU. Print the management domain and address contents,
although in hex only so far.
Add some comments to clarify the code flow and to tell exact sections in
IEEE standard documents. Add new error messages and make some existing
messages more specific.
This fixes a buffer over-read discovered by Bhargava Shastry,
SecT/TU Berlin.
Add a test using the capture file supplied by the reporter(s).
CWE ID: CWE-125
|
cfm_network_addr_print(netdissect_options *ndo,
register const u_char *tptr, const u_int length)
{
u_int network_addr_type;
u_int hexdump = FALSE;
/*
* Altough AFIs are tpically 2 octects wide,
* 802.1ab specifies that this field width
* is only once octet
*/
if (length < 1) {
ND_PRINT((ndo, "\n\t Network Address Type (invalid, no data"));
return hexdump;
}
/* The calling function must make any due ND_TCHECK calls. */
network_addr_type = *tptr;
ND_PRINT((ndo, "\n\t Network Address Type %s (%u)",
tok2str(af_values, "Unknown", network_addr_type),
network_addr_type));
/*
* Resolve the passed in Address.
*/
switch(network_addr_type) {
case AFNUM_INET:
if (length != 1 + 4) {
ND_PRINT((ndo, "(invalid IPv4 address length %u)", length - 1));
hexdump = TRUE;
break;
}
ND_PRINT((ndo, ", %s", ipaddr_string(ndo, tptr + 1)));
break;
case AFNUM_INET6:
if (length != 1 + 16) {
ND_PRINT((ndo, "(invalid IPv6 address length %u)", length - 1));
hexdump = TRUE;
break;
}
ND_PRINT((ndo, ", %s", ip6addr_string(ndo, tptr + 1)));
break;
default:
hexdump = TRUE;
break;
}
return hexdump;
}
| 167,821
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void SetManualFallbacksForFilling(bool enabled) {
if (enabled) {
scoped_feature_list_.InitAndEnableFeature(
password_manager::features::kEnableManualFallbacksFilling);
} else {
scoped_feature_list_.InitAndDisableFeature(
password_manager::features::kEnableManualFallbacksFilling);
}
}
Commit Message: Fixing names of password_manager kEnableManualFallbacksFilling feature.
Fixing names of password_manager kEnableManualFallbacksFilling feature
as per the naming convention.
Bug: 785953
Change-Id: I4a4baa1649fe9f02c3783a5e4c40bc75e717cc03
Reviewed-on: https://chromium-review.googlesource.com/900566
Reviewed-by: Vaclav Brozek <vabr@chromium.org>
Commit-Queue: NIKHIL SAHNI <nikhil.sahni@samsung.com>
Cr-Commit-Position: refs/heads/master@{#534923}
CWE ID: CWE-264
|
void SetManualFallbacksForFilling(bool enabled) {
if (enabled) {
scoped_feature_list_.InitAndEnableFeature(
password_manager::features::kManualFallbacksFilling);
} else {
scoped_feature_list_.InitAndDisableFeature(
password_manager::features::kManualFallbacksFilling);
}
}
| 171,750
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: int ntlm_read_message_header(wStream* s, NTLM_MESSAGE_HEADER* header)
{
if (Stream_GetRemainingLength(s) < 12)
return -1;
Stream_Read(s, header->Signature, 8);
Stream_Read_UINT32(s, header->MessageType);
if (strncmp((char*) header->Signature, NTLM_SIGNATURE, 8) != 0)
return -1;
return 1;
}
Commit Message: Fixed CVE-2018-8789
Thanks to Eyal Itkin from Check Point Software Technologies.
CWE ID: CWE-125
|
int ntlm_read_message_header(wStream* s, NTLM_MESSAGE_HEADER* header)
static int ntlm_read_message_header(wStream* s, NTLM_MESSAGE_HEADER* header)
{
if (Stream_GetRemainingLength(s) < 12)
return -1;
Stream_Read(s, header->Signature, 8);
Stream_Read_UINT32(s, header->MessageType);
if (strncmp((char*) header->Signature, NTLM_SIGNATURE, 8) != 0)
return -1;
return 1;
}
| 169,278
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void ChromeClientImpl::Focus() {
if (web_view_->Client())
web_view_->Client()->DidFocus();
}
Commit Message: If a page calls |window.focus()|, kick it out of fullscreen.
BUG=776418, 800056
Change-Id: I1880fe600e4814c073f247c43b1c1ac80c8fc017
Reviewed-on: https://chromium-review.googlesource.com/852378
Reviewed-by: Nasko Oskov <nasko@chromium.org>
Reviewed-by: Philip Jägenstedt <foolip@chromium.org>
Commit-Queue: Avi Drissman <avi@chromium.org>
Cr-Commit-Position: refs/heads/master@{#533790}
CWE ID:
|
void ChromeClientImpl::Focus() {
void ChromeClientImpl::Focus(LocalFrame* calling_frame) {
if (web_view_->Client()) {
web_view_->Client()->DidFocus(
calling_frame ? WebLocalFrameImpl::FromFrame(calling_frame) : nullptr);
}
}
| 172,724
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void IndexedDBCursor::RemoveCursorFromTransaction() {
if (transaction_)
transaction_->UnregisterOpenCursor(this);
}
Commit Message: [IndexedDB] Fix Cursor UAF
If the connection is closed before we return a cursor, it dies in
IndexedDBCallbacks::IOThreadHelper::SendSuccessCursor. It's deleted on
the correct thread, but we also need to makes sure to remove it from its
transaction.
To make things simpler, we have the cursor remove itself from its
transaction on destruction.
R: pwnall@chromium.org
Bug: 728887
Change-Id: I8c76e6195c2490137a05213e47c635d12f4d3dd2
Reviewed-on: https://chromium-review.googlesource.com/526284
Commit-Queue: Daniel Murphy <dmurph@chromium.org>
Reviewed-by: Victor Costan <pwnall@chromium.org>
Cr-Commit-Position: refs/heads/master@{#477504}
CWE ID: CWE-416
|
void IndexedDBCursor::RemoveCursorFromTransaction() {
| 172,307
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void EVP_EncodeUpdate(EVP_ENCODE_CTX *ctx, unsigned char *out, int *outl,
const unsigned char *in, int inl)
{
int i, j;
unsigned int total = 0;
*outl = 0;
if (inl <= 0)
return;
OPENSSL_assert(ctx->length <= (int)sizeof(ctx->enc_data));
if ((ctx->num + inl) < ctx->length) {
memcpy(&(ctx->enc_data[ctx->num]), in, inl);
ctx->num += inl;
return;
}
if (ctx->num != 0) {
i = ctx->length - ctx->num;
memcpy(&(ctx->enc_data[ctx->num]), in, i);
in += i;
inl -= i;
j = EVP_EncodeBlock(out, ctx->enc_data, ctx->length);
ctx->num = 0;
out += j;
*(out++) = '\n';
*out = '\0';
total = j + 1;
}
while (inl >= ctx->length) {
j = EVP_EncodeBlock(out, in, ctx->length);
in += ctx->length;
inl -= ctx->length;
out += j;
*(out++) = '\n';
*out = '\0';
total += j + 1;
}
if (inl != 0)
memcpy(&(ctx->enc_data[0]), in, inl);
ctx->num = inl;
*outl = total;
}
Commit Message:
CWE ID: CWE-189
|
void EVP_EncodeUpdate(EVP_ENCODE_CTX *ctx, unsigned char *out, int *outl,
const unsigned char *in, int inl)
{
int i, j;
unsigned int total = 0;
*outl = 0;
if (inl <= 0)
return;
OPENSSL_assert(ctx->length <= (int)sizeof(ctx->enc_data));
if (ctx->length - ctx->num > inl) {
memcpy(&(ctx->enc_data[ctx->num]), in, inl);
ctx->num += inl;
return;
}
if (ctx->num != 0) {
i = ctx->length - ctx->num;
memcpy(&(ctx->enc_data[ctx->num]), in, i);
in += i;
inl -= i;
j = EVP_EncodeBlock(out, ctx->enc_data, ctx->length);
ctx->num = 0;
out += j;
*(out++) = '\n';
*out = '\0';
total = j + 1;
}
while (inl >= ctx->length) {
j = EVP_EncodeBlock(out, in, ctx->length);
in += ctx->length;
inl -= ctx->length;
out += j;
*(out++) = '\n';
*out = '\0';
total += j + 1;
}
if (inl != 0)
memcpy(&(ctx->enc_data[0]), in, inl);
ctx->num = inl;
*outl = total;
}
| 165,217
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static void t1_check_unusual_charstring(void)
{
char *p = strstr(t1_line_array, charstringname) + strlen(charstringname);
int i;
/*tex If no number follows |/CharStrings|, let's read the next line. */
if (sscanf(p, "%i", &i) != 1) {
strcpy(t1_buf_array, t1_line_array);
t1_getline();
strcat(t1_buf_array, t1_line_array);
strcpy(t1_line_array, t1_buf_array);
t1_line_ptr = eol(t1_line_array);
}
}
Commit Message: writet1 protection against buffer overflow
git-svn-id: svn://tug.org/texlive/trunk/Build/source@48697 c570f23f-e606-0410-a88d-b1316a301751
CWE ID: CWE-119
|
static void t1_check_unusual_charstring(void)
{
char *p = strstr(t1_line_array, charstringname) + strlen(charstringname);
int i;
/*tex If no number follows |/CharStrings|, let's read the next line. */
if (sscanf(p, "%i", &i) != 1) {
strcpy(t1_buf_array, t1_line_array);
t1_getline();
alloc_array(t1_buf, strlen(t1_line_array) + strlen(t1_buf_array) + 1, T1_BUF_SIZE);
strcat(t1_buf_array, t1_line_array);
alloc_array(t1_line, strlen(t1_buf_array) + 1, T1_BUF_SIZE);
strcpy(t1_line_array, t1_buf_array);
t1_line_ptr = eol(t1_line_array);
}
}
| 169,021
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: QString IRCView::closeToTagString(TextHtmlData* data, const QString& _tag)
{
QString ret;
QString tag;
int i = data->openHtmlTags.count() - 1;
for ( ; i >= 0 ; --i)
{
tag = data->openHtmlTags.at(i);
ret += QLatin1String("</") + tag + QLatin1Char('>');
if (tag == _tag)
{
data->openHtmlTags.removeAt(i);
break;
}
}
ret += openTags(data, i);
return ret;
}
Commit Message:
CWE ID:
|
QString IRCView::closeToTagString(TextHtmlData* data, const QString& _tag)
{
QString ret;
QString tag;
int i = data->openHtmlTags.count() - 1;
for ( ; i >= 0 ; --i)
{
tag = data->openHtmlTags.at(i);
ret += QLatin1String("</") + tag + QLatin1Char('>');
if (tag == _tag)
{
data->openHtmlTags.removeAt(i);
break;
}
}
if (i > -1)
ret += openTags(data, i);
return ret;
}
| 164,648
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: image_transform_png_set_palette_to_rgb_mod(PNG_CONST image_transform *this,
image_pixel *that, png_const_structp pp,
PNG_CONST transform_display *display)
{
if (that->colour_type == PNG_COLOR_TYPE_PALETTE)
image_pixel_convert_PLTE(that);
this->next->mod(this->next, that, pp, display);
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID:
|
image_transform_png_set_palette_to_rgb_mod(PNG_CONST image_transform *this,
image_transform_png_set_palette_to_rgb_mod(const image_transform *this,
image_pixel *that, png_const_structp pp,
const transform_display *display)
{
if (that->colour_type == PNG_COLOR_TYPE_PALETTE)
image_pixel_convert_PLTE(that);
this->next->mod(this->next, that, pp, display);
}
| 173,639
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: xfs_set_acl(struct inode *inode, struct posix_acl *acl, int type)
{
int error = 0;
if (!acl)
goto set_acl;
error = -E2BIG;
if (acl->a_count > XFS_ACL_MAX_ENTRIES(XFS_M(inode->i_sb)))
return error;
if (type == ACL_TYPE_ACCESS) {
umode_t mode = inode->i_mode;
error = posix_acl_equiv_mode(acl, &mode);
if (error <= 0) {
acl = NULL;
if (error < 0)
return error;
}
error = xfs_set_mode(inode, mode);
if (error)
return error;
}
set_acl:
return __xfs_set_acl(inode, type, acl);
}
Commit Message: posix_acl: Clear SGID bit when setting file permissions
When file permissions are modified via chmod(2) and the user is not in
the owning group or capable of CAP_FSETID, the setgid bit is cleared in
inode_change_ok(). Setting a POSIX ACL via setxattr(2) sets the file
permissions as well as the new ACL, but doesn't clear the setgid bit in
a similar way; this allows to bypass the check in chmod(2). Fix that.
References: CVE-2016-7097
Reviewed-by: Christoph Hellwig <hch@lst.de>
Reviewed-by: Jeff Layton <jlayton@redhat.com>
Signed-off-by: Jan Kara <jack@suse.cz>
Signed-off-by: Andreas Gruenbacher <agruenba@redhat.com>
CWE ID: CWE-285
|
xfs_set_acl(struct inode *inode, struct posix_acl *acl, int type)
{
int error = 0;
if (!acl)
goto set_acl;
error = -E2BIG;
if (acl->a_count > XFS_ACL_MAX_ENTRIES(XFS_M(inode->i_sb)))
return error;
if (type == ACL_TYPE_ACCESS) {
umode_t mode;
error = posix_acl_update_mode(inode, &mode, &acl);
if (error)
return error;
error = xfs_set_mode(inode, mode);
if (error)
return error;
}
set_acl:
return __xfs_set_acl(inode, type, acl);
}
| 166,979
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void CameraSource::signalBufferReturned(MediaBuffer *buffer) {
ALOGV("signalBufferReturned: %p", buffer->data());
Mutex::Autolock autoLock(mLock);
for (List<sp<IMemory> >::iterator it = mFramesBeingEncoded.begin();
it != mFramesBeingEncoded.end(); ++it) {
if ((*it)->pointer() == buffer->data()) {
releaseOneRecordingFrame((*it));
mFramesBeingEncoded.erase(it);
++mNumFramesEncoded;
buffer->setObserver(0);
buffer->release();
mFrameCompleteCondition.signal();
return;
}
}
CHECK(!"signalBufferReturned: bogus buffer");
}
Commit Message: DO NOT MERGE: Camera: Adjust pointers to ANW buffers to avoid infoleak
Subtract address of a random static object from pointers being routed
through app process.
Bug: 28466701
Change-Id: Idcbfe81e9507433769672f3dc6d67db5eeed4e04
CWE ID: CWE-200
|
void CameraSource::signalBufferReturned(MediaBuffer *buffer) {
ALOGV("signalBufferReturned: %p", buffer->data());
Mutex::Autolock autoLock(mLock);
for (List<sp<IMemory> >::iterator it = mFramesBeingEncoded.begin();
it != mFramesBeingEncoded.end(); ++it) {
if ((*it)->pointer() == buffer->data()) {
// b/28466701
adjustOutgoingANWBuffer(it->get());
releaseOneRecordingFrame((*it));
mFramesBeingEncoded.erase(it);
++mNumFramesEncoded;
buffer->setObserver(0);
buffer->release();
mFrameCompleteCondition.signal();
return;
}
}
CHECK(!"signalBufferReturned: bogus buffer");
}
| 173,510
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: virtual InputMethodDescriptor current_input_method() const {
return current_input_method_;
}
Commit Message: Remove use of libcros from InputMethodLibrary.
BUG=chromium-os:16238
TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before.
Review URL: http://codereview.chromium.org/7003086
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
|
virtual InputMethodDescriptor current_input_method() const {
virtual input_method::InputMethodDescriptor current_input_method() const {
return current_input_method_;
}
| 170,513
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void RunAccuracyCheck() {
ACMRandom rnd(ACMRandom::DeterministicSeed());
uint32_t max_error = 0;
int64_t total_error = 0;
const int count_test_block = 10000;
for (int i = 0; i < count_test_block; ++i) {
DECLARE_ALIGNED_ARRAY(16, int16_t, test_input_block, kNumCoeffs);
DECLARE_ALIGNED_ARRAY(16, int16_t, test_temp_block, kNumCoeffs);
DECLARE_ALIGNED_ARRAY(16, uint8_t, dst, kNumCoeffs);
DECLARE_ALIGNED_ARRAY(16, uint8_t, src, kNumCoeffs);
for (int j = 0; j < kNumCoeffs; ++j) {
src[j] = rnd.Rand8();
dst[j] = rnd.Rand8();
test_input_block[j] = src[j] - dst[j];
}
REGISTER_STATE_CHECK(RunFwdTxfm(test_input_block,
test_temp_block, pitch_));
REGISTER_STATE_CHECK(RunInvTxfm(test_temp_block, dst, pitch_));
for (int j = 0; j < kNumCoeffs; ++j) {
const uint32_t diff = dst[j] - src[j];
const uint32_t error = diff * diff;
if (max_error < error)
max_error = error;
total_error += error;
}
}
EXPECT_GE(1u, max_error)
<< "Error: 4x4 FHT/IHT has an individual round trip error > 1";
EXPECT_GE(count_test_block , total_error)
<< "Error: 4x4 FHT/IHT has average round trip error > 1 per block";
}
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 RunAccuracyCheck() {
void RunAccuracyCheck(int limit) {
ACMRandom rnd(ACMRandom::DeterministicSeed());
uint32_t max_error = 0;
int64_t total_error = 0;
const int count_test_block = 10000;
for (int i = 0; i < count_test_block; ++i) {
DECLARE_ALIGNED(16, int16_t, test_input_block[kNumCoeffs]);
DECLARE_ALIGNED(16, tran_low_t, test_temp_block[kNumCoeffs]);
DECLARE_ALIGNED(16, uint8_t, dst[kNumCoeffs]);
DECLARE_ALIGNED(16, uint8_t, src[kNumCoeffs]);
#if CONFIG_VP9_HIGHBITDEPTH
DECLARE_ALIGNED(16, uint16_t, dst16[kNumCoeffs]);
DECLARE_ALIGNED(16, uint16_t, src16[kNumCoeffs]);
#endif
for (int j = 0; j < kNumCoeffs; ++j) {
if (bit_depth_ == VPX_BITS_8) {
src[j] = rnd.Rand8();
dst[j] = rnd.Rand8();
test_input_block[j] = src[j] - dst[j];
#if CONFIG_VP9_HIGHBITDEPTH
} else {
src16[j] = rnd.Rand16() & mask_;
dst16[j] = rnd.Rand16() & mask_;
test_input_block[j] = src16[j] - dst16[j];
#endif
}
}
ASM_REGISTER_STATE_CHECK(RunFwdTxfm(test_input_block,
test_temp_block, pitch_));
if (bit_depth_ == VPX_BITS_8) {
ASM_REGISTER_STATE_CHECK(RunInvTxfm(test_temp_block, dst, pitch_));
#if CONFIG_VP9_HIGHBITDEPTH
} else {
ASM_REGISTER_STATE_CHECK(RunInvTxfm(test_temp_block,
CONVERT_TO_BYTEPTR(dst16), pitch_));
#endif
}
for (int j = 0; j < kNumCoeffs; ++j) {
#if CONFIG_VP9_HIGHBITDEPTH
const uint32_t diff =
bit_depth_ == VPX_BITS_8 ? dst[j] - src[j] : dst16[j] - src16[j];
#else
ASSERT_EQ(VPX_BITS_8, bit_depth_);
const uint32_t diff = dst[j] - src[j];
#endif
const uint32_t error = diff * diff;
if (max_error < error)
max_error = error;
total_error += error;
}
}
EXPECT_GE(static_cast<uint32_t>(limit), max_error)
<< "Error: 4x4 FHT/IHT has an individual round trip error > "
<< limit;
EXPECT_GE(count_test_block * limit, total_error)
<< "Error: 4x4 FHT/IHT has average round trip error > " << limit
<< " per block";
}
| 174,547
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void OneClickSigninSyncStarter::UntrustedSigninConfirmed(
StartSyncMode response) {
if (response == UNDO_SYNC) {
CancelSigninAndDelete();
} else {
if (response == CONFIGURE_SYNC_FIRST)
start_mode_ = response;
SigninManager* signin = SigninManagerFactory::GetForProfile(profile_);
signin->CompletePendingSignin();
}
}
Commit Message: Display confirmation dialog for untrusted signins
BUG=252062
Review URL: https://chromiumcodereview.appspot.com/17482002
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@208520 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-200
|
void OneClickSigninSyncStarter::UntrustedSigninConfirmed(
StartSyncMode response) {
if (response == UNDO_SYNC) {
CancelSigninAndDelete();
// If this was not an interstitial signin, (i.e. it was a SAML signin)
// then the browser page is now blank and should redirect to the NTP.
if (source_ != SyncPromoUI::SOURCE_UNKNOWN) {
EnsureBrowser();
chrome::NavigateParams params(browser_, GURL(chrome::kChromeUINewTabURL),
content::PAGE_TRANSITION_AUTO_TOPLEVEL);
params.disposition = CURRENT_TAB;
params.window_action = chrome::NavigateParams::SHOW_WINDOW;
chrome::Navigate(¶ms);
}
} else {
if (response == CONFIGURE_SYNC_FIRST)
start_mode_ = response;
SigninManager* signin = SigninManagerFactory::GetForProfile(profile_);
signin->CompletePendingSignin();
}
}
| 171,246
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static int wddx_stack_destroy(wddx_stack *stack)
{
register int i;
if (stack->elements) {
for (i = 0; i < stack->top; i++) {
if (((st_entry *)stack->elements[i])->data) {
zval_ptr_dtor(&((st_entry *)stack->elements[i])->data);
}
if (((st_entry *)stack->elements[i])->varname) {
efree(((st_entry *)stack->elements[i])->varname);
}
efree(stack->elements[i]);
}
efree(stack->elements);
}
return SUCCESS;
}
Commit Message: Fix bug #72860: wddx_deserialize use-after-free
CWE ID: CWE-416
|
static int wddx_stack_destroy(wddx_stack *stack)
{
register int i;
if (stack->elements) {
for (i = 0; i < stack->top; i++) {
if (((st_entry *)stack->elements[i])->data
&& ((st_entry *)stack->elements[i])->type != ST_FIELD) {
zval_ptr_dtor(&((st_entry *)stack->elements[i])->data);
}
if (((st_entry *)stack->elements[i])->varname) {
efree(((st_entry *)stack->elements[i])->varname);
}
efree(stack->elements[i]);
}
efree(stack->elements);
}
return SUCCESS;
}
| 166,936
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: swabHorDiff32(TIFF* tif, uint8* cp0, tmsize_t cc)
{
uint32* wp = (uint32*) cp0;
tmsize_t wc = cc / 4;
horDiff32(tif, cp0, cc);
TIFFSwabArrayOfLong(wp, wc);
}
Commit Message: * libtiff/tif_predict.h, libtiff/tif_predict.c:
Replace assertions by runtime checks to avoid assertions in debug mode,
or buffer overflows in release mode. Can happen when dealing with
unusual tile size like YCbCr with subsampling. Reported as MSVR 35105
by Axel Souchet & Vishal Chauhan from the MSRC Vulnerabilities & Mitigations
team.
CWE ID: CWE-119
|
swabHorDiff32(TIFF* tif, uint8* cp0, tmsize_t cc)
{
uint32* wp = (uint32*) cp0;
tmsize_t wc = cc / 4;
if( !horDiff32(tif, cp0, cc) )
return 0;
TIFFSwabArrayOfLong(wp, wc);
return 1;
}
| 166,891
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: l2tp_result_code_print(netdissect_options *ndo, const u_char *dat, u_int length)
{
const uint16_t *ptr = (const uint16_t *)dat;
ND_PRINT((ndo, "%u", EXTRACT_16BITS(ptr))); ptr++; /* Result Code */
if (length > 2) { /* Error Code (opt) */
ND_PRINT((ndo, "/%u", EXTRACT_16BITS(ptr))); ptr++;
}
if (length > 4) { /* Error Message (opt) */
ND_PRINT((ndo, " "));
print_string(ndo, (const u_char *)ptr, length - 4);
}
}
Commit Message: CVE-2017-13006/L2TP: Check whether an AVP's content exceeds the AVP length.
It's not good enough to check whether all the data specified by the AVP
length was captured - you also have to check whether that length is
large enough for all the required data in the AVP.
This fixes a buffer over-read discovered by Yannick Formaggio.
Add a test using the capture file supplied by the reporter(s).
CWE ID: CWE-125
|
l2tp_result_code_print(netdissect_options *ndo, const u_char *dat, u_int length)
{
const uint16_t *ptr = (const uint16_t *)dat;
/* Result Code */
if (length < 2) {
ND_PRINT((ndo, "AVP too short"));
return;
}
ND_PRINT((ndo, "%u", EXTRACT_16BITS(ptr)));
ptr++;
length -= 2;
/* Error Code (opt) */
if (length == 0)
return;
if (length < 2) {
ND_PRINT((ndo, " AVP too short"));
return;
}
ND_PRINT((ndo, "/%u", EXTRACT_16BITS(ptr)));
ptr++;
length -= 2;
/* Error Message (opt) */
if (length == 0)
return;
ND_PRINT((ndo, " "));
print_string(ndo, (const u_char *)ptr, length);
}
| 167,902
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static bool glfs_check_config(const char *cfgstring, char **reason)
{
char *path;
glfs_t *fs = NULL;
glfs_fd_t *gfd = NULL;
gluster_server *hosts = NULL; /* gluster server defination */
bool result = true;
path = strchr(cfgstring, '/');
if (!path) {
if (asprintf(reason, "No path found") == -1)
*reason = NULL;
result = false;
goto done;
}
path += 1; /* get past '/' */
fs = tcmu_create_glfs_object(path, &hosts);
if (!fs) {
tcmu_err("tcmu_create_glfs_object failed\n");
goto done;
}
gfd = glfs_open(fs, hosts->path, ALLOWED_BSOFLAGS);
if (!gfd) {
if (asprintf(reason, "glfs_open failed: %m") == -1)
*reason = NULL;
result = false;
goto unref;
}
if (glfs_access(fs, hosts->path, R_OK|W_OK) == -1) {
if (asprintf(reason, "glfs_access file not present, or not writable") == -1)
*reason = NULL;
result = false;
goto unref;
}
goto done;
unref:
gluster_cache_refresh(fs, path);
done:
if (gfd)
glfs_close(gfd);
gluster_free_server(&hosts);
return result;
}
Commit Message: glfs: discard glfs_check_config
Signed-off-by: Prasanna Kumar Kalever <prasanna.kalever@redhat.com>
CWE ID: CWE-119
|
static bool glfs_check_config(const char *cfgstring, char **reason)
| 167,635
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: bool BrokerDuplicateHandle(HANDLE source_handle,
DWORD target_process_id,
HANDLE* target_handle,
DWORD desired_access,
DWORD options) {
if (!g_target_services) {
base::win::ScopedHandle target_process(::OpenProcess(PROCESS_DUP_HANDLE,
FALSE,
target_process_id));
if (!target_process.IsValid())
return false;
if (!::DuplicateHandle(::GetCurrentProcess(), source_handle,
target_process, target_handle,
desired_access, FALSE,
options)) {
return false;
}
return true;
}
ResultCode result = g_target_services->DuplicateHandle(source_handle,
target_process_id,
target_handle,
desired_access,
options);
return SBOX_ALL_OK == result;
}
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:
|
bool BrokerDuplicateHandle(HANDLE source_handle,
DWORD target_process_id,
HANDLE* target_handle,
DWORD desired_access,
DWORD options) {
// If our process is the target just duplicate the handle.
if (::GetCurrentProcessId() == target_process_id) {
return !!::DuplicateHandle(::GetCurrentProcess(), source_handle,
::GetCurrentProcess(), target_handle,
desired_access, FALSE, options);
}
// Try the broker next
if (g_target_services &&
g_target_services->DuplicateHandle(source_handle, target_process_id,
target_handle, desired_access,
options) == SBOX_ALL_OK) {
return true;
}
// Finally, see if we already have access to the process.
base::win::ScopedHandle target_process;
target_process.Set(::OpenProcess(PROCESS_DUP_HANDLE, FALSE,
target_process_id));
if (target_process.IsValid()) {
return !!::DuplicateHandle(::GetCurrentProcess(), source_handle,
target_process, target_handle,
desired_access, FALSE, options);
}
return false;
}
| 170,946
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: PowerPopupView() {
SetHorizontalAlignment(ALIGN_RIGHT);
UpdateText();
}
Commit Message: ash: Fix right-alignment of power-status text.
It turns out setting ALING_RIGHT on a Label isn't enough to get proper
right-aligned text. Label has to be explicitly told that it is multi-lined.
BUG=none
TEST=none
Review URL: https://chromiumcodereview.appspot.com/9918026
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@129898 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
|
PowerPopupView() {
SetHorizontalAlignment(ALIGN_RIGHT);
SetMultiLine(true);
UpdateText();
}
| 170,908
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void DataReductionProxySettings::InitPrefMembers() {
DCHECK(thread_checker_.CalledOnValidThread());
spdy_proxy_auth_enabled_.Init(
prefs::kDataSaverEnabled, GetOriginalProfilePrefs(),
base::Bind(&DataReductionProxySettings::OnProxyEnabledPrefChange,
base::Unretained(this)));
}
Commit Message: Move IsDataSaverEnabledByUser to be a static method and use it
This method now officially becomes the source of truth that
everything in the code base eventually calls into to determine whether
or not DataSaver is enabled.
Bug: 934399
Change-Id: Iae837b710ace8cc3101188f79d02cbc2d4f0fd93
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1537242
Reviewed-by: Joshua Pawlicki <waffles@chromium.org>
Reviewed-by: Tarun Bansal <tbansal@chromium.org>
Commit-Queue: Robert Ogden <robertogden@chromium.org>
Cr-Commit-Position: refs/heads/master@{#643948}
CWE ID: CWE-119
|
void DataReductionProxySettings::InitPrefMembers() {
| 172,553
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void GaiaOAuthClient::Core::FetchUserInfoAndInvokeCallback() {
request_.reset(new UrlFetcher(
GURL(provider_info_.user_info_url), UrlFetcher::GET));
request_->SetRequestContext(request_context_getter_);
request_->SetHeader("Authorization", "Bearer " + access_token_);
request_->Start(
base::Bind(&GaiaOAuthClient::Core::OnUserInfoFetchComplete, this));
}
Commit Message: Remove UrlFetcher from remoting and use the one in net instead.
BUG=133790
TEST=Stop and restart the Me2Me host. It should still work.
Review URL: https://chromiumcodereview.appspot.com/10637008
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143798 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
|
void GaiaOAuthClient::Core::FetchUserInfoAndInvokeCallback() {
request_.reset(net::URLFetcher::Create(
GURL(provider_info_.user_info_url), net::URLFetcher::GET, this));
request_->SetRequestContext(request_context_getter_);
request_->AddExtraRequestHeader("Authorization: Bearer " + access_token_);
url_fetcher_type_ = URL_FETCHER_GET_USER_INFO;
request_->Start();
}
| 170,806
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: int php_wddx_deserialize_ex(char *value, int vallen, zval *return_value)
{
wddx_stack stack;
XML_Parser parser;
st_entry *ent;
int retval;
wddx_stack_init(&stack);
parser = XML_ParserCreate("UTF-8");
XML_SetUserData(parser, &stack);
XML_SetElementHandler(parser, php_wddx_push_element, php_wddx_pop_element);
XML_SetCharacterDataHandler(parser, php_wddx_process_data);
XML_Parse(parser, value, vallen, 1);
XML_ParserFree(parser);
if (stack.top == 1) {
wddx_stack_top(&stack, (void**)&ent);
*return_value = *(ent->data);
zval_copy_ctor(return_value);
retval = SUCCESS;
} else {
retval = FAILURE;
}
wddx_stack_destroy(&stack);
return retval;
}
Commit Message: Fix for bug #72790 and bug #72799
CWE ID: CWE-476
|
int php_wddx_deserialize_ex(char *value, int vallen, zval *return_value)
{
wddx_stack stack;
XML_Parser parser;
st_entry *ent;
int retval;
wddx_stack_init(&stack);
parser = XML_ParserCreate("UTF-8");
XML_SetUserData(parser, &stack);
XML_SetElementHandler(parser, php_wddx_push_element, php_wddx_pop_element);
XML_SetCharacterDataHandler(parser, php_wddx_process_data);
XML_Parse(parser, value, vallen, 1);
XML_ParserFree(parser);
if (stack.top == 1) {
wddx_stack_top(&stack, (void**)&ent);
if(ent->data == NULL) {
retval = FAILURE;
} else {
*return_value = *(ent->data);
zval_copy_ctor(return_value);
retval = SUCCESS;
}
} else {
retval = FAILURE;
}
wddx_stack_destroy(&stack);
return retval;
}
| 166,948
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static int getnum (lua_State *L, const char **fmt, int df) {
if (!isdigit(**fmt)) /* no number? */
return df; /* return default value */
else {
int a = 0;
do {
if (a > (INT_MAX / 10) || a * 10 > (INT_MAX - (**fmt - '0')))
luaL_error(L, "integral size overflow");
a = a*10 + *((*fmt)++) - '0';
} while (isdigit(**fmt));
return a;
}
}
Commit Message: Security: update Lua struct package for security.
During an auditing Apple found that the "struct" Lua package
we ship with Redis (http://www.inf.puc-rio.br/~roberto/struct/) contains
a security problem. A bound-checking statement fails because of integer
overflow. The bug exists since we initially integrated this package with
Lua, when scripting was introduced, so every version of Redis with
EVAL/EVALSHA capabilities exposed is affected.
Instead of just fixing the bug, the library was updated to the latest
version shipped by the author.
CWE ID: CWE-190
|
static int getnum (lua_State *L, const char **fmt, int df) {
static int getnum (const char **fmt, int df) {
if (!isdigit(**fmt)) /* no number? */
return df; /* return default value */
else {
int a = 0;
do {
a = a*10 + *((*fmt)++) - '0';
} while (isdigit(**fmt));
return a;
}
}
| 170,165
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: RenderWidgetHostViewAndroid::RenderWidgetHostViewAndroid(
RenderWidgetHostImpl* widget_host,
ContentViewCoreImpl* content_view_core)
: host_(widget_host),
is_layer_attached_(true),
content_view_core_(NULL),
ime_adapter_android_(ALLOW_THIS_IN_INITIALIZER_LIST(this)),
cached_background_color_(SK_ColorWHITE),
texture_id_in_layer_(0) {
if (CompositorImpl::UsesDirectGL()) {
surface_texture_transport_.reset(new SurfaceTextureTransportClient());
layer_ = surface_texture_transport_->Initialize();
} else {
texture_layer_ = cc::TextureLayer::create(0);
layer_ = texture_layer_;
}
layer_->setContentsOpaque(true);
layer_->setIsDrawable(true);
host_->SetView(this);
SetContentViewCore(content_view_core);
}
Commit Message: Implement TextureImageTransportSurface using texture mailbox
This has a couple of advantages:
- allow tearing down and recreating the UI parent context without
losing the renderer contexts
- do not require a context to be able to generate textures when
creating the GLSurfaceHandle
- clearer ownership semantics that potentially allows for more
robust and easier lost context handling/thumbnailing/etc., since a texture is at
any given time owned by either: UI parent, mailbox, or
TextureImageTransportSurface
- simplify frontbuffer protection logic;
the frontbuffer textures are now owned by RWHV where they are refcounted
The TextureImageTransportSurface informs RenderWidgetHostView of the
mailbox names for the front- and backbuffer textures by
associating them with a surface_handle (1 or 2) in the AcceleratedSurfaceNew message.
During SwapBuffers() or PostSubBuffer() cycles, it then uses
produceTextureCHROMIUM() and consumeTextureCHROMIUM()
to transfer ownership between renderer and browser compositor.
RWHV sends back the surface_handle of the buffer being returned with the Swap ACK
(or 0 if no buffer is being returned in which case TextureImageTransportSurface will
allocate a new texture - note that this could be used to
simply keep textures for thumbnailing).
BUG=154815,139616
TBR=sky@chromium.org
Review URL: https://chromiumcodereview.appspot.com/11194042
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171569 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID:
|
RenderWidgetHostViewAndroid::RenderWidgetHostViewAndroid(
RenderWidgetHostImpl* widget_host,
ContentViewCoreImpl* content_view_core)
: host_(widget_host),
is_layer_attached_(true),
content_view_core_(NULL),
ime_adapter_android_(ALLOW_THIS_IN_INITIALIZER_LIST(this)),
cached_background_color_(SK_ColorWHITE),
texture_id_in_layer_(0),
current_buffer_id_(0) {
if (CompositorImpl::UsesDirectGL()) {
surface_texture_transport_.reset(new SurfaceTextureTransportClient());
layer_ = surface_texture_transport_->Initialize();
} else {
texture_layer_ = cc::TextureLayer::create(0);
layer_ = texture_layer_;
}
layer_->setContentsOpaque(true);
layer_->setIsDrawable(true);
host_->SetView(this);
SetContentViewCore(content_view_core);
}
| 171,370
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static void r_bin_dwarf_dump_debug_info(FILE *f, const RBinDwarfDebugInfo *inf) {
size_t i, j, k;
RBinDwarfDIE *dies;
RBinDwarfAttrValue *values;
if (!inf || !f) {
return;
}
for (i = 0; i < inf->length; i++) {
fprintf (f, " Compilation Unit @ offset 0x%"PFMT64x":\n", inf->comp_units [i].offset);
fprintf (f, " Length: 0x%x\n", inf->comp_units [i].hdr.length);
fprintf (f, " Version: %d\n", inf->comp_units [i].hdr.version);
fprintf (f, " Abbrev Offset: 0x%x\n", inf->comp_units [i].hdr.abbrev_offset);
fprintf (f, " Pointer Size: %d\n", inf->comp_units [i].hdr.pointer_size);
dies = inf->comp_units[i].dies;
for (j = 0; j < inf->comp_units[i].length; j++) {
fprintf (f, " Abbrev Number: %"PFMT64u" ", dies[j].abbrev_code);
if (dies[j].tag && dies[j].tag <= DW_TAG_volatile_type &&
dwarf_tag_name_encodings[dies[j].tag]) {
fprintf (f, "(%s)\n", dwarf_tag_name_encodings[dies[j].tag]);
} else {
fprintf (f, "(Unknown abbrev tag)\n");
}
if (!dies[j].abbrev_code) {
continue;
}
values = dies[j].attr_values;
for (k = 0; k < dies[j].length; k++) {
if (!values[k].name)
continue;
if (values[k].name < DW_AT_vtable_elem_location &&
dwarf_attr_encodings[values[k].name]) {
fprintf (f, " %-18s : ", dwarf_attr_encodings[values[k].name]);
} else {
fprintf (f, " TODO\t");
}
r_bin_dwarf_dump_attr_value (&values[k], f);
fprintf (f, "\n");
}
}
}
}
Commit Message: Fix #8813 - segfault in dwarf parser
CWE ID: CWE-125
|
static void r_bin_dwarf_dump_debug_info(FILE *f, const RBinDwarfDebugInfo *inf) {
size_t i, j, k;
RBinDwarfDIE *dies;
RBinDwarfAttrValue *values;
if (!inf || !f) {
return;
}
for (i = 0; i < inf->length; i++) {
fprintf (f, " Compilation Unit @ offset 0x%"PFMT64x":\n", inf->comp_units [i].offset);
fprintf (f, " Length: 0x%x\n", inf->comp_units [i].hdr.length);
fprintf (f, " Version: %d\n", inf->comp_units [i].hdr.version);
fprintf (f, " Abbrev Offset: 0x%x\n", inf->comp_units [i].hdr.abbrev_offset);
fprintf (f, " Pointer Size: %d\n", inf->comp_units [i].hdr.pointer_size);
dies = inf->comp_units[i].dies;
for (j = 0; j < inf->comp_units[i].length; j++) {
fprintf (f, " Abbrev Number: %"PFMT64u" ", dies[j].abbrev_code);
if (dies[j].tag && dies[j].tag <= DW_TAG_volatile_type &&
dwarf_tag_name_encodings[dies[j].tag]) {
fprintf (f, "(%s)\n", dwarf_tag_name_encodings[dies[j].tag]);
} else {
fprintf (f, "(Unknown abbrev tag)\n");
}
if (!dies[j].abbrev_code) {
continue;
}
values = dies[j].attr_values;
for (k = 0; k < dies[j].length; k++) {
if (!values[k].name) {
continue;
}
if (values[k].name < DW_AT_vtable_elem_location &&
dwarf_attr_encodings[values[k].name]) {
fprintf (f, " %-18s : ", dwarf_attr_encodings[values[k].name]);
} else {
fprintf (f, " TODO\t");
}
r_bin_dwarf_dump_attr_value (&values[k], f);
fprintf (f, "\n");
}
}
}
}
| 167,668
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void CtcpHandler::handleVersion(CtcpType ctcptype, const QString &prefix, const QString &target, const QString ¶m) {
Q_UNUSED(target)
if(ctcptype == CtcpQuery) {
if(_ignoreListManager->ctcpMatch(prefix, network()->networkName(), "VERSION"))
return;
reply(nickFromMask(prefix), "VERSION", QString("Quassel IRC %1 (built on %2) -- http://www.quassel-irc.org")
.arg(Quassel::buildInfo().plainVersionString)
.arg(Quassel::buildInfo().buildDate));
emit displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Received CTCP VERSION request by %1").arg(prefix));
} else {
str.append(tr(" with arguments: %1").arg(param));
emit displayMsg(Message::Error, BufferInfo::StatusBuffer, "", str);
}
}
Commit Message:
CWE ID: CWE-399
|
void CtcpHandler::handleVersion(CtcpType ctcptype, const QString &prefix, const QString &target, const QString ¶m) {
void CtcpHandler::handleVersion(CtcpType ctcptype, const QString &prefix, const QString &target, const QString ¶m, QString &reply) {
Q_UNUSED(target)
if(ctcptype == CtcpQuery) {
reply = QString("Quassel IRC %1 (built on %2) -- http://www.quassel-irc.org").arg(Quassel::buildInfo().plainVersionString).arg(Quassel::buildInfo().buildDate);
emit displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Received CTCP VERSION request by %1").arg(prefix));
} else {
str.append(tr(" with arguments: %1").arg(param));
emit displayMsg(Message::Error, BufferInfo::StatusBuffer, "", str);
}
}
| 164,880
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static inline void set_socket_blocking(int s, int blocking)
{
int opts;
opts = fcntl(s, F_GETFL);
if (opts<0) APPL_TRACE_ERROR("set blocking (%s)", strerror(errno));
if(blocking)
opts &= ~O_NONBLOCK;
else opts |= O_NONBLOCK;
if (fcntl(s, F_SETFL, opts) < 0)
APPL_TRACE_ERROR("set blocking (%s)", strerror(errno));
}
Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process
Bug: 28885210
Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360
Conflicts:
btif/co/bta_hh_co.c
btif/src/btif_core.c
Merge conflict resolution of ag/1161415 (referencing ag/1164670)
- Directly into mnc-mr2-release
CWE ID: CWE-284
|
static inline void set_socket_blocking(int s, int blocking)
{
int opts;
opts = TEMP_FAILURE_RETRY(fcntl(s, F_GETFL));
if (opts<0) APPL_TRACE_ERROR("set blocking (%s)", strerror(errno));
if(blocking)
opts &= ~O_NONBLOCK;
else opts |= O_NONBLOCK;
if (TEMP_FAILURE_RETRY(fcntl(s, F_SETFL, opts)) < 0)
APPL_TRACE_ERROR("set blocking (%s)", strerror(errno));
}
| 173,466
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static void coroutine_fn v9fs_xattrcreate(void *opaque)
{
int flags;
int32_t fid;
int64_t size;
ssize_t err = 0;
V9fsString name;
size_t offset = 7;
V9fsFidState *file_fidp;
V9fsFidState *xattr_fidp;
V9fsPDU *pdu = opaque;
v9fs_string_init(&name);
err = pdu_unmarshal(pdu, offset, "dsqd", &fid, &name, &size, &flags);
if (err < 0) {
goto out_nofid;
}
trace_v9fs_xattrcreate(pdu->tag, pdu->id, fid, name.data, size, flags);
file_fidp = get_fid(pdu, fid);
if (file_fidp == NULL) {
err = -EINVAL;
goto out_nofid;
}
/* Make the file fid point to xattr */
xattr_fidp = file_fidp;
xattr_fidp->fid_type = P9_FID_XATTR;
xattr_fidp->fs.xattr.copied_len = 0;
xattr_fidp->fs.xattr.len = size;
xattr_fidp->fs.xattr.flags = flags;
v9fs_string_init(&xattr_fidp->fs.xattr.name);
v9fs_string_copy(&xattr_fidp->fs.xattr.name, &name);
xattr_fidp->fs.xattr.value = g_malloc(size);
err = offset;
put_fid(pdu, file_fidp);
out_nofid:
pdu_complete(pdu, err);
v9fs_string_free(&name);
}
Commit Message:
CWE ID: CWE-119
|
static void coroutine_fn v9fs_xattrcreate(void *opaque)
{
int flags;
int32_t fid;
int64_t size;
ssize_t err = 0;
V9fsString name;
size_t offset = 7;
V9fsFidState *file_fidp;
V9fsFidState *xattr_fidp;
V9fsPDU *pdu = opaque;
v9fs_string_init(&name);
err = pdu_unmarshal(pdu, offset, "dsqd", &fid, &name, &size, &flags);
if (err < 0) {
goto out_nofid;
}
trace_v9fs_xattrcreate(pdu->tag, pdu->id, fid, name.data, size, flags);
file_fidp = get_fid(pdu, fid);
if (file_fidp == NULL) {
err = -EINVAL;
goto out_nofid;
}
/* Make the file fid point to xattr */
xattr_fidp = file_fidp;
xattr_fidp->fid_type = P9_FID_XATTR;
xattr_fidp->fs.xattr.copied_len = 0;
xattr_fidp->fs.xattr.len = size;
xattr_fidp->fs.xattr.flags = flags;
v9fs_string_init(&xattr_fidp->fs.xattr.name);
v9fs_string_copy(&xattr_fidp->fs.xattr.name, &name);
xattr_fidp->fs.xattr.value = g_malloc0(size);
err = offset;
put_fid(pdu, file_fidp);
out_nofid:
pdu_complete(pdu, err);
v9fs_string_free(&name);
}
| 164,908
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static void copyStereo16(
short *dst,
const int *const *src,
unsigned nSamples,
unsigned /* nChannels */) {
for (unsigned i = 0; i < nSamples; ++i) {
*dst++ = src[0][i];
*dst++ = src[1][i];
}
}
Commit Message: FLACExtractor: copy protect mWriteBuffer
Bug: 30895578
Change-Id: I4cba36bbe3502678210e5925181683df9726b431
CWE ID: CWE-119
|
static void copyStereo16(
short *dst,
const int * src[FLACParser::kMaxChannels],
unsigned nSamples,
unsigned /* nChannels */) {
for (unsigned i = 0; i < nSamples; ++i) {
*dst++ = src[0][i];
*dst++ = src[1][i];
}
}
| 174,021
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void PluginChannel::OnChannelConnected(int32 peer_pid) {
base::ProcessHandle handle;
if (!base::OpenProcessHandle(peer_pid, &handle)) {
NOTREACHED();
}
renderer_handle_ = handle;
NPChannelBase::OnChannelConnected(peer_pid);
}
Commit Message: Convert plugin and GPU process to brokered handle duplication.
BUG=119250
Review URL: https://chromiumcodereview.appspot.com/9958034
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132303 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID:
|
void PluginChannel::OnChannelConnected(int32 peer_pid) {
| 170,948
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.