instruction
stringclasses
1 value
input
stringlengths
90
139k
output
stringlengths
16
138k
__index_level_0__
int64
165k
175k
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void xen_netbk_tx_submit(struct xen_netbk *netbk) { struct gnttab_copy *gop = netbk->tx_copy_ops; struct sk_buff *skb; while ((skb = __skb_dequeue(&netbk->tx_queue)) != NULL) { struct xen_netif_tx_request *txp; struct xenvif *vif; u16 pending_idx; unsigned data_len; pending_idx = *((u16 *)skb->data); vif = netbk->pending_tx_info[pending_idx].vif; txp = &netbk->pending_tx_info[pending_idx].req; /* Check the remap error code. */ if (unlikely(xen_netbk_tx_check_gop(netbk, skb, &gop))) { netdev_dbg(vif->dev, "netback grant failed.\n"); skb_shinfo(skb)->nr_frags = 0; kfree_skb(skb); continue; } data_len = skb->len; memcpy(skb->data, (void *)(idx_to_kaddr(netbk, pending_idx)|txp->offset), data_len); if (data_len < txp->size) { /* Append the packet payload as a fragment. */ txp->offset += data_len; txp->size -= data_len; } else { /* Schedule a response immediately. */ xen_netbk_idx_release(netbk, pending_idx); } if (txp->flags & XEN_NETTXF_csum_blank) skb->ip_summed = CHECKSUM_PARTIAL; else if (txp->flags & XEN_NETTXF_data_validated) skb->ip_summed = CHECKSUM_UNNECESSARY; xen_netbk_fill_frags(netbk, skb); /* * If the initial fragment was < PKT_PROT_LEN then * pull through some bytes from the other fragments to * increase the linear region to PKT_PROT_LEN bytes. */ if (skb_headlen(skb) < PKT_PROT_LEN && skb_is_nonlinear(skb)) { int target = min_t(int, skb->len, PKT_PROT_LEN); __pskb_pull_tail(skb, target - skb_headlen(skb)); } skb->dev = vif->dev; skb->protocol = eth_type_trans(skb, skb->dev); if (checksum_setup(vif, skb)) { netdev_dbg(vif->dev, "Can't setup checksum in net_tx_action\n"); kfree_skb(skb); continue; } vif->dev->stats.rx_bytes += skb->len; vif->dev->stats.rx_packets++; xenvif_receive_skb(vif, skb); } } Commit Message: xen/netback: don't leak pages on failure in xen_netbk_tx_check_gop. Signed-off-by: Matthew Daley <[email protected]> Reviewed-by: Konrad Rzeszutek Wilk <[email protected]> Acked-by: Ian Campbell <[email protected]> Acked-by: Jan Beulich <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-399
static void xen_netbk_tx_submit(struct xen_netbk *netbk) { struct gnttab_copy *gop = netbk->tx_copy_ops; struct sk_buff *skb; while ((skb = __skb_dequeue(&netbk->tx_queue)) != NULL) { struct xen_netif_tx_request *txp; struct xenvif *vif; u16 pending_idx; unsigned data_len; pending_idx = *((u16 *)skb->data); vif = netbk->pending_tx_info[pending_idx].vif; txp = &netbk->pending_tx_info[pending_idx].req; /* Check the remap error code. */ if (unlikely(xen_netbk_tx_check_gop(netbk, skb, &gop))) { netdev_dbg(vif->dev, "netback grant failed.\n"); skb_shinfo(skb)->nr_frags = 0; kfree_skb(skb); continue; } data_len = skb->len; memcpy(skb->data, (void *)(idx_to_kaddr(netbk, pending_idx)|txp->offset), data_len); if (data_len < txp->size) { /* Append the packet payload as a fragment. */ txp->offset += data_len; txp->size -= data_len; } else { /* Schedule a response immediately. */ xen_netbk_idx_release(netbk, pending_idx, XEN_NETIF_RSP_OKAY); } if (txp->flags & XEN_NETTXF_csum_blank) skb->ip_summed = CHECKSUM_PARTIAL; else if (txp->flags & XEN_NETTXF_data_validated) skb->ip_summed = CHECKSUM_UNNECESSARY; xen_netbk_fill_frags(netbk, skb); /* * If the initial fragment was < PKT_PROT_LEN then * pull through some bytes from the other fragments to * increase the linear region to PKT_PROT_LEN bytes. */ if (skb_headlen(skb) < PKT_PROT_LEN && skb_is_nonlinear(skb)) { int target = min_t(int, skb->len, PKT_PROT_LEN); __pskb_pull_tail(skb, target - skb_headlen(skb)); } skb->dev = vif->dev; skb->protocol = eth_type_trans(skb, skb->dev); if (checksum_setup(vif, skb)) { netdev_dbg(vif->dev, "Can't setup checksum in net_tx_action\n"); kfree_skb(skb); continue; } vif->dev->stats.rx_bytes += skb->len; vif->dev->stats.rx_packets++; xenvif_receive_skb(vif, skb); } }
166,170
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: SQLRETURN SQLSetDescField( SQLHDESC descriptor_handle, SQLSMALLINT rec_number, SQLSMALLINT field_identifier, SQLPOINTER value, SQLINTEGER buffer_length ) { /* * not quite sure how the descriptor can be * allocated to a statement, all the documentation talks * about state transitions on statement states, but the * descriptor may be allocated with more than one statement * at one time. Which one should I check ? */ DMHDESC descriptor = (DMHDESC) descriptor_handle; SQLRETURN ret; SQLCHAR s1[ 100 + LOG_MESSAGE_LEN ]; int isStrField = 0; /* * check descriptor */ if ( !__validate_desc( descriptor )) { dm_log_write( __FILE__, __LINE__, LOG_INFO, LOG_INFO, "Error: SQL_INVALID_HANDLE" ); return SQL_INVALID_HANDLE; } function_entry( descriptor ); if ( log_info.log_flag ) { sprintf( descriptor -> msg, "\n\t\tEntry:\ \n\t\t\tDescriptor = %p\ \n\t\t\tRec Number = %d\ \n\t\t\tField Ident = %s\ \n\t\t\tValue = %p\ \n\t\t\tBuffer Length = %d", descriptor, rec_number, __desc_attr_as_string( s1, field_identifier ), value, (int)buffer_length ); dm_log_write( __FILE__, __LINE__, LOG_INFO, LOG_INFO, descriptor -> msg ); } thread_protect( SQL_HANDLE_DESC, descriptor ); if ( descriptor -> connection -> state < STATE_C4 ) { dm_log_write( __FILE__, __LINE__, LOG_INFO, LOG_INFO, "Error: HY010" ); __post_internal_error( &descriptor -> error, ERROR_HY010, NULL, descriptor -> connection -> environment -> requested_version ); return function_return_nodrv( SQL_HANDLE_DESC, descriptor, SQL_ERROR ); } /* * check status of statements associated with this descriptor */ if( __check_stmt_from_desc( descriptor, STATE_S8 ) || __check_stmt_from_desc( descriptor, STATE_S9 ) || __check_stmt_from_desc( descriptor, STATE_S10 ) || __check_stmt_from_desc( descriptor, STATE_S11 ) || __check_stmt_from_desc( descriptor, STATE_S12 ) || __check_stmt_from_desc( descriptor, STATE_S13 ) || __check_stmt_from_desc( descriptor, STATE_S14 ) || __check_stmt_from_desc( descriptor, STATE_S15 )) { dm_log_write( __FILE__, __LINE__, LOG_INFO, LOG_INFO, "Error: HY010" ); __post_internal_error( &descriptor -> error, ERROR_HY010, NULL, descriptor -> connection -> environment -> requested_version ); return function_return_nodrv( SQL_HANDLE_DESC, descriptor, SQL_ERROR ); } if ( rec_number < 0 ) { __post_internal_error( &descriptor -> error, ERROR_07009, NULL, descriptor -> connection -> environment -> requested_version ); return function_return_nodrv( SQL_HANDLE_DESC, descriptor, SQL_ERROR ); } switch ( field_identifier ) { /* Fixed-length fields: buffer_length is ignored */ case SQL_DESC_ALLOC_TYPE: case SQL_DESC_ARRAY_SIZE: case SQL_DESC_ARRAY_STATUS_PTR: case SQL_DESC_BIND_OFFSET_PTR: case SQL_DESC_BIND_TYPE: case SQL_DESC_COUNT: case SQL_DESC_ROWS_PROCESSED_PTR: case SQL_DESC_AUTO_UNIQUE_VALUE: case SQL_DESC_CASE_SENSITIVE: case SQL_DESC_CONCISE_TYPE: case SQL_DESC_DATA_PTR: case SQL_DESC_DATETIME_INTERVAL_CODE: case SQL_DESC_DATETIME_INTERVAL_PRECISION: case SQL_DESC_DISPLAY_SIZE: case SQL_DESC_FIXED_PREC_SCALE: case SQL_DESC_INDICATOR_PTR: case SQL_DESC_LENGTH: case SQL_DESC_NULLABLE: case SQL_DESC_NUM_PREC_RADIX: case SQL_DESC_OCTET_LENGTH: case SQL_DESC_OCTET_LENGTH_PTR: case SQL_DESC_PARAMETER_TYPE: case SQL_DESC_PRECISION: case SQL_DESC_ROWVER: case SQL_DESC_SCALE: case SQL_DESC_SEARCHABLE: case SQL_DESC_TYPE: case SQL_DESC_UNNAMED: case SQL_DESC_UNSIGNED: case SQL_DESC_UPDATABLE: isStrField = 0; break; /* Pointer to data: buffer_length must be valid */ case SQL_DESC_BASE_COLUMN_NAME: case SQL_DESC_BASE_TABLE_NAME: case SQL_DESC_CATALOG_NAME: case SQL_DESC_LABEL: case SQL_DESC_LITERAL_PREFIX: case SQL_DESC_LITERAL_SUFFIX: case SQL_DESC_LOCAL_TYPE_NAME: case SQL_DESC_NAME: case SQL_DESC_SCHEMA_NAME: case SQL_DESC_TABLE_NAME: case SQL_DESC_TYPE_NAME: isStrField = 1; break; default: isStrField = buffer_length != SQL_IS_POINTER && buffer_length != SQL_IS_INTEGER && buffer_length != SQL_IS_UINTEGER && buffer_length != SQL_IS_SMALLINT && buffer_length != SQL_IS_USMALLINT; } if ( isStrField && buffer_length < 0 && buffer_length != SQL_NTS) { __post_internal_error( &descriptor -> error, ERROR_HY090, NULL, descriptor -> connection -> environment -> requested_version ); return function_return_nodrv( SQL_HANDLE_DESC, descriptor, SQL_ERROR ); } if ( field_identifier == SQL_DESC_COUNT && (SQLINTEGER)value < 0 ) { __post_internal_error( &descriptor -> error, ERROR_07009, NULL, descriptor -> connection -> environment -> requested_version ); return function_return_nodrv( SQL_HANDLE_DESC, descriptor, SQL_ERROR ); } if ( field_identifier == SQL_DESC_PARAMETER_TYPE && value != SQL_PARAM_INPUT && value != SQL_PARAM_OUTPUT && value != SQL_PARAM_INPUT_OUTPUT && value != SQL_PARAM_INPUT_OUTPUT_STREAM && value != SQL_PARAM_OUTPUT_STREAM ) { __post_internal_error( &descriptor -> error, ERROR_HY105, NULL, descriptor -> connection -> environment -> requested_version ); return function_return_nodrv( SQL_HANDLE_DESC, descriptor, SQL_ERROR ); } if ( CHECK_SQLSETDESCFIELD( descriptor -> connection )) { ret = SQLSETDESCFIELD( descriptor -> connection, descriptor -> driver_desc, rec_number, field_identifier, value, buffer_length ); } else if ( CHECK_SQLSETDESCFIELDW( descriptor -> connection )) { SQLWCHAR *s1 = NULL; if (isStrField) { s1 = ansi_to_unicode_alloc( value, buffer_length, descriptor -> connection, NULL ); if (SQL_NTS != buffer_length) { buffer_length *= sizeof(SQLWCHAR); } } else { s1 = value; } ret = SQLSETDESCFIELDW( descriptor -> connection, descriptor -> driver_desc, rec_number, field_identifier, s1, buffer_length ); if (isStrField) { if (s1) free(s1); } } else { dm_log_write( __FILE__, __LINE__, LOG_INFO, LOG_INFO, "Error: IM001" ); __post_internal_error( &descriptor -> error, ERROR_IM001, NULL, descriptor -> connection -> environment -> requested_version ); return function_return_nodrv( SQL_HANDLE_DESC, descriptor, SQL_ERROR ); } if ( log_info.log_flag ) { sprintf( descriptor -> msg, "\n\t\tExit:[%s]", __get_return_status( ret, s1 )); dm_log_write( __FILE__, __LINE__, LOG_INFO, LOG_INFO, descriptor -> msg ); } return function_return( SQL_HANDLE_DESC, descriptor, ret ); } Commit Message: New Pre Source CWE ID: CWE-119
SQLRETURN SQLSetDescField( SQLHDESC descriptor_handle, SQLSMALLINT rec_number, SQLSMALLINT field_identifier, SQLPOINTER value, SQLINTEGER buffer_length ) { /* * not quite sure how the descriptor can be * allocated to a statement, all the documentation talks * about state transitions on statement states, but the * descriptor may be allocated with more than one statement * at one time. Which one should I check ? */ DMHDESC descriptor = (DMHDESC) descriptor_handle; SQLRETURN ret; SQLCHAR s1[ 100 + LOG_MESSAGE_LEN ]; int isStrField = 0; /* * check descriptor */ if ( !__validate_desc( descriptor )) { dm_log_write( __FILE__, __LINE__, LOG_INFO, LOG_INFO, "Error: SQL_INVALID_HANDLE" ); return SQL_INVALID_HANDLE; } function_entry( descriptor ); if ( log_info.log_flag ) { sprintf( descriptor -> msg, "\n\t\tEntry:\ \n\t\t\tDescriptor = %p\ \n\t\t\tRec Number = %d\ \n\t\t\tField Ident = %s\ \n\t\t\tValue = %p\ \n\t\t\tBuffer Length = %d", descriptor, rec_number, __desc_attr_as_string( s1, field_identifier ), value, (int)buffer_length ); dm_log_write( __FILE__, __LINE__, LOG_INFO, LOG_INFO, descriptor -> msg ); } thread_protect( SQL_HANDLE_DESC, descriptor ); if ( descriptor -> connection -> state < STATE_C4 ) { dm_log_write( __FILE__, __LINE__, LOG_INFO, LOG_INFO, "Error: HY010" ); __post_internal_error( &descriptor -> error, ERROR_HY010, NULL, descriptor -> connection -> environment -> requested_version ); return function_return_nodrv( SQL_HANDLE_DESC, descriptor, SQL_ERROR ); } /* * check status of statements associated with this descriptor */ if( __check_stmt_from_desc( descriptor, STATE_S8 ) || __check_stmt_from_desc( descriptor, STATE_S9 ) || __check_stmt_from_desc( descriptor, STATE_S10 ) || __check_stmt_from_desc( descriptor, STATE_S11 ) || __check_stmt_from_desc( descriptor, STATE_S12 ) || __check_stmt_from_desc( descriptor, STATE_S13 ) || __check_stmt_from_desc( descriptor, STATE_S14 ) || __check_stmt_from_desc( descriptor, STATE_S15 )) { dm_log_write( __FILE__, __LINE__, LOG_INFO, LOG_INFO, "Error: HY010" ); __post_internal_error( &descriptor -> error, ERROR_HY010, NULL, descriptor -> connection -> environment -> requested_version ); return function_return_nodrv( SQL_HANDLE_DESC, descriptor, SQL_ERROR ); } if ( rec_number < 0 ) { __post_internal_error( &descriptor -> error, ERROR_07009, NULL, descriptor -> connection -> environment -> requested_version ); return function_return_nodrv( SQL_HANDLE_DESC, descriptor, SQL_ERROR ); } switch ( field_identifier ) { /* Fixed-length fields: buffer_length is ignored */ case SQL_DESC_ALLOC_TYPE: case SQL_DESC_ARRAY_SIZE: case SQL_DESC_ARRAY_STATUS_PTR: case SQL_DESC_BIND_OFFSET_PTR: case SQL_DESC_BIND_TYPE: case SQL_DESC_COUNT: case SQL_DESC_ROWS_PROCESSED_PTR: case SQL_DESC_AUTO_UNIQUE_VALUE: case SQL_DESC_CASE_SENSITIVE: case SQL_DESC_CONCISE_TYPE: case SQL_DESC_DATA_PTR: case SQL_DESC_DATETIME_INTERVAL_CODE: case SQL_DESC_DATETIME_INTERVAL_PRECISION: case SQL_DESC_DISPLAY_SIZE: case SQL_DESC_FIXED_PREC_SCALE: case SQL_DESC_INDICATOR_PTR: case SQL_DESC_LENGTH: case SQL_DESC_NULLABLE: case SQL_DESC_NUM_PREC_RADIX: case SQL_DESC_OCTET_LENGTH: case SQL_DESC_OCTET_LENGTH_PTR: case SQL_DESC_PARAMETER_TYPE: case SQL_DESC_PRECISION: case SQL_DESC_ROWVER: case SQL_DESC_SCALE: case SQL_DESC_SEARCHABLE: case SQL_DESC_TYPE: case SQL_DESC_UNNAMED: case SQL_DESC_UNSIGNED: case SQL_DESC_UPDATABLE: isStrField = 0; break; /* Pointer to data: buffer_length must be valid */ case SQL_DESC_BASE_COLUMN_NAME: case SQL_DESC_BASE_TABLE_NAME: case SQL_DESC_CATALOG_NAME: case SQL_DESC_LABEL: case SQL_DESC_LITERAL_PREFIX: case SQL_DESC_LITERAL_SUFFIX: case SQL_DESC_LOCAL_TYPE_NAME: case SQL_DESC_NAME: case SQL_DESC_SCHEMA_NAME: case SQL_DESC_TABLE_NAME: case SQL_DESC_TYPE_NAME: isStrField = 1; break; default: isStrField = buffer_length != SQL_IS_POINTER && buffer_length != SQL_IS_INTEGER && buffer_length != SQL_IS_UINTEGER && buffer_length != SQL_IS_SMALLINT && buffer_length != SQL_IS_USMALLINT; } if ( isStrField && buffer_length < 0 && buffer_length != SQL_NTS) { __post_internal_error( &descriptor -> error, ERROR_HY090, NULL, descriptor -> connection -> environment -> requested_version ); return function_return_nodrv( SQL_HANDLE_DESC, descriptor, SQL_ERROR ); } if ( field_identifier == SQL_DESC_COUNT && (intptr_t)value < 0 ) { __post_internal_error( &descriptor -> error, ERROR_07009, NULL, descriptor -> connection -> environment -> requested_version ); return function_return_nodrv( SQL_HANDLE_DESC, descriptor, SQL_ERROR ); } if ( field_identifier == SQL_DESC_PARAMETER_TYPE && (intptr_t)value != SQL_PARAM_INPUT && (intptr_t)value != SQL_PARAM_OUTPUT && (intptr_t)value != SQL_PARAM_INPUT_OUTPUT && (intptr_t)value != SQL_PARAM_INPUT_OUTPUT_STREAM && (intptr_t)value != SQL_PARAM_OUTPUT_STREAM ) { __post_internal_error( &descriptor -> error, ERROR_HY105, NULL, descriptor -> connection -> environment -> requested_version ); return function_return_nodrv( SQL_HANDLE_DESC, descriptor, SQL_ERROR ); } if ( CHECK_SQLSETDESCFIELD( descriptor -> connection )) { ret = SQLSETDESCFIELD( descriptor -> connection, descriptor -> driver_desc, rec_number, field_identifier, value, buffer_length ); } else if ( CHECK_SQLSETDESCFIELDW( descriptor -> connection )) { SQLWCHAR *s1 = NULL; if (isStrField) { s1 = ansi_to_unicode_alloc( value, buffer_length, descriptor -> connection, NULL ); if (SQL_NTS != buffer_length) { buffer_length *= sizeof(SQLWCHAR); } } else { s1 = value; } ret = SQLSETDESCFIELDW( descriptor -> connection, descriptor -> driver_desc, rec_number, field_identifier, s1, buffer_length ); if (isStrField) { if (s1) free(s1); } } else { dm_log_write( __FILE__, __LINE__, LOG_INFO, LOG_INFO, "Error: IM001" ); __post_internal_error( &descriptor -> error, ERROR_IM001, NULL, descriptor -> connection -> environment -> requested_version ); return function_return_nodrv( SQL_HANDLE_DESC, descriptor, SQL_ERROR ); } if ( log_info.log_flag ) { sprintf( descriptor -> msg, "\n\t\tExit:[%s]", __get_return_status( ret, s1 )); dm_log_write( __FILE__, __LINE__, LOG_INFO, LOG_INFO, descriptor -> msg ); } return function_return( SQL_HANDLE_DESC, descriptor, ret ); }
169,310
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void RenderFrameDevToolsAgentHost::UpdateFrameHost( RenderFrameHostImpl* frame_host) { if (frame_host == frame_host_) { if (frame_host && !render_frame_alive_) { render_frame_alive_ = true; for (auto* inspector : protocol::InspectorHandler::ForAgentHost(this)) inspector->TargetReloadedAfterCrash(); MaybeReattachToRenderFrame(); } return; } if (frame_host && !ShouldCreateDevToolsForHost(frame_host)) { DestroyOnRenderFrameGone(); return; } if (IsAttached()) RevokePolicy(); frame_host_ = frame_host; agent_ptr_.reset(); if (!render_frame_alive_) { render_frame_alive_ = true; for (auto* inspector : protocol::InspectorHandler::ForAgentHost(this)) inspector->TargetReloadedAfterCrash(); } if (IsAttached()) { GrantPolicy(); for (DevToolsSession* session : sessions()) { session->SetRenderer(frame_host ? frame_host->GetProcess()->GetID() : -1, frame_host); } MaybeReattachToRenderFrame(); } } Commit Message: [DevTools] Do not allow chrome.debugger to attach to web ui pages If the page navigates to web ui, we force detach the debugger extension. [email protected] Bug: 798222 Change-Id: Idb46c2f59e839388397a8dfa6ce2e2a897698df3 Reviewed-on: https://chromium-review.googlesource.com/935961 Commit-Queue: Dmitry Gozman <[email protected]> Reviewed-by: Devlin <[email protected]> Reviewed-by: Pavel Feldman <[email protected]> Reviewed-by: Nasko Oskov <[email protected]> Cr-Commit-Position: refs/heads/master@{#540916} CWE ID: CWE-20
void RenderFrameDevToolsAgentHost::UpdateFrameHost( RenderFrameHostImpl* frame_host) { if (frame_host == frame_host_) { if (frame_host && !render_frame_alive_) { render_frame_alive_ = true; for (auto* inspector : protocol::InspectorHandler::ForAgentHost(this)) inspector->TargetReloadedAfterCrash(); MaybeReattachToRenderFrame(); } return; } if (frame_host && !ShouldCreateDevToolsForHost(frame_host)) { DestroyOnRenderFrameGone(); return; } if (IsAttached()) RevokePolicy(); frame_host_ = frame_host; agent_ptr_.reset(); if (!IsFrameHostAllowedForRestrictedSessions()) ForceDetachRestrictedSessions(); if (!render_frame_alive_) { render_frame_alive_ = true; for (auto* inspector : protocol::InspectorHandler::ForAgentHost(this)) inspector->TargetReloadedAfterCrash(); } if (IsAttached()) { GrantPolicy(); for (DevToolsSession* session : sessions()) { session->SetRenderer(frame_host ? frame_host->GetProcess()->GetID() : -1, frame_host); } MaybeReattachToRenderFrame(); } }
173,250
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void WebPage::touchPointAsMouseEvent(const Platform::TouchPoint& point, unsigned modifiers) { if (d->m_page->defersLoading()) return; if (d->m_fullScreenPluginView.get()) return; d->m_lastUserEventTimestamp = currentTime(); Platform::TouchPoint tPoint = point; tPoint.m_pos = d->mapFromTransformed(tPoint.m_pos); d->m_touchEventHandler->handleTouchPoint(tPoint, modifiers); } Commit Message: [BlackBerry] Adapt to new BlackBerry::Platform::TouchPoint API https://bugs.webkit.org/show_bug.cgi?id=105143 RIM PR 171941 Reviewed by Rob Buis. Internally reviewed by George Staikos. Source/WebCore: TouchPoint instances now provide document coordinates for the viewport and content position of the touch event. The pixel coordinates stored in the TouchPoint should no longer be needed in WebKit. Also adapt to new method names and encapsulation of TouchPoint data members. No change in behavior, no new tests. * platform/blackberry/PlatformTouchPointBlackBerry.cpp: (WebCore::PlatformTouchPoint::PlatformTouchPoint): Source/WebKit/blackberry: TouchPoint instances now provide document coordinates for the viewport and content position of the touch event. The pixel coordinates stored in the TouchPoint should no longer be needed in WebKit. One exception is when passing events to a full screen plugin. Also adapt to new method names and encapsulation of TouchPoint data members. * Api/WebPage.cpp: (BlackBerry::WebKit::WebPage::touchEvent): (BlackBerry::WebKit::WebPage::touchPointAsMouseEvent): (BlackBerry::WebKit::WebPagePrivate::dispatchTouchEventToFullScreenPlugin): (BlackBerry::WebKit::WebPagePrivate::dispatchTouchPointAsMouseEventToFullScreenPlugin): * WebKitSupport/InputHandler.cpp: (BlackBerry::WebKit::InputHandler::shouldRequestSpellCheckingOptionsForPoint): * WebKitSupport/InputHandler.h: (InputHandler): * WebKitSupport/TouchEventHandler.cpp: (BlackBerry::WebKit::TouchEventHandler::doFatFingers): (BlackBerry::WebKit::TouchEventHandler::handleTouchPoint): * WebKitSupport/TouchEventHandler.h: (TouchEventHandler): Tools: Adapt to new method names and encapsulation of TouchPoint data members. * DumpRenderTree/blackberry/EventSender.cpp: (addTouchPointCallback): (updateTouchPointCallback): (touchEndCallback): (releaseTouchPointCallback): (sendTouchEvent): git-svn-id: svn://svn.chromium.org/blink/trunk@137880 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID:
void WebPage::touchPointAsMouseEvent(const Platform::TouchPoint& point, unsigned modifiers) { if (d->m_page->defersLoading()) return; if (d->m_fullScreenPluginView.get()) return; d->m_lastUserEventTimestamp = currentTime(); d->m_touchEventHandler->handleTouchPoint(point, modifiers); }
170,767
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: header_put_be_8byte (SF_PRIVATE *psf, sf_count_t x) { if (psf->headindex < SIGNED_SIZEOF (psf->header) - 8) { psf->header [psf->headindex++] = (x >> 56) ; psf->header [psf->headindex++] = (x >> 48) ; psf->header [psf->headindex++] = (x >> 40) ; psf->header [psf->headindex++] = (x >> 32) ; psf->header [psf->headindex++] = (x >> 24) ; psf->header [psf->headindex++] = (x >> 16) ; psf->header [psf->headindex++] = (x >> 8) ; psf->header [psf->headindex++] = x ; } ; } /* header_put_be_8byte */ Commit Message: src/ : Move to a variable length header buffer Previously, the `psf->header` buffer was a fixed length specified by `SF_HEADER_LEN` which was set to `12292`. This was problematic for two reasons; this value was un-necessarily large for the majority of files and too small for some others. Now the size of the header buffer starts at 256 bytes and grows as necessary up to a maximum of 100k. CWE ID: CWE-119
header_put_be_8byte (SF_PRIVATE *psf, sf_count_t x) { psf->header.ptr [psf->header.indx++] = (x >> 56) ; psf->header.ptr [psf->header.indx++] = (x >> 48) ; psf->header.ptr [psf->header.indx++] = (x >> 40) ; psf->header.ptr [psf->header.indx++] = (x >> 32) ; psf->header.ptr [psf->header.indx++] = (x >> 24) ; psf->header.ptr [psf->header.indx++] = (x >> 16) ; psf->header.ptr [psf->header.indx++] = (x >> 8) ; psf->header.ptr [psf->header.indx++] = x ; } /* header_put_be_8byte */
170,050
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: gss_verify_mic (minor_status, context_handle, message_buffer, token_buffer, qop_state) OM_uint32 * minor_status; gss_ctx_id_t context_handle; gss_buffer_t message_buffer; gss_buffer_t token_buffer; gss_qop_t * qop_state; { OM_uint32 status; gss_union_ctx_id_t ctx; gss_mechanism mech; if (minor_status == NULL) return (GSS_S_CALL_INACCESSIBLE_WRITE); *minor_status = 0; if (context_handle == GSS_C_NO_CONTEXT) return (GSS_S_CALL_INACCESSIBLE_READ | GSS_S_NO_CONTEXT); if ((message_buffer == GSS_C_NO_BUFFER) || GSS_EMPTY_BUFFER(token_buffer)) return (GSS_S_CALL_INACCESSIBLE_READ); /* * select the approprate underlying mechanism routine and * call it. */ ctx = (gss_union_ctx_id_t) context_handle; mech = gssint_get_mechanism (ctx->mech_type); if (mech) { if (mech->gss_verify_mic) { status = mech->gss_verify_mic( minor_status, ctx->internal_ctx_id, message_buffer, token_buffer, qop_state); if (status != GSS_S_COMPLETE) map_error(minor_status, mech); } else status = GSS_S_UNAVAILABLE; return(status); } return (GSS_S_BAD_MECH); } Commit Message: Preserve GSS context on init/accept failure After gss_init_sec_context() or gss_accept_sec_context() has created a context, don't delete the mechglue context on failures from subsequent calls, even if the mechanism deletes the mech-specific context (which is allowed by RFC 2744 but not preferred). Check for union contexts with no mechanism context in each GSS function which accepts a gss_ctx_id_t. CVE-2017-11462: RFC 2744 permits a GSS-API implementation to delete an existing security context on a second or subsequent call to gss_init_sec_context() or gss_accept_sec_context() if the call results in an error. This API behavior has been found to be dangerous, leading to the possibility of memory errors in some callers. For safety, GSS-API implementations should instead preserve existing security contexts on error until the caller deletes them. All versions of MIT krb5 prior to this change may delete acceptor contexts on error. Versions 1.13.4 through 1.13.7, 1.14.1 through 1.14.5, and 1.15 through 1.15.1 may also delete initiator contexts on error. ticket: 8598 (new) target_version: 1.15-next target_version: 1.14-next tags: pullup CWE ID: CWE-415
gss_verify_mic (minor_status, context_handle, message_buffer, token_buffer, qop_state) OM_uint32 * minor_status; gss_ctx_id_t context_handle; gss_buffer_t message_buffer; gss_buffer_t token_buffer; gss_qop_t * qop_state; { OM_uint32 status; gss_union_ctx_id_t ctx; gss_mechanism mech; if (minor_status == NULL) return (GSS_S_CALL_INACCESSIBLE_WRITE); *minor_status = 0; if (context_handle == GSS_C_NO_CONTEXT) return (GSS_S_CALL_INACCESSIBLE_READ | GSS_S_NO_CONTEXT); if ((message_buffer == GSS_C_NO_BUFFER) || GSS_EMPTY_BUFFER(token_buffer)) return (GSS_S_CALL_INACCESSIBLE_READ); /* * select the approprate underlying mechanism routine and * call it. */ ctx = (gss_union_ctx_id_t) context_handle; if (ctx->internal_ctx_id == GSS_C_NO_CONTEXT) return (GSS_S_NO_CONTEXT); mech = gssint_get_mechanism (ctx->mech_type); if (mech) { if (mech->gss_verify_mic) { status = mech->gss_verify_mic( minor_status, ctx->internal_ctx_id, message_buffer, token_buffer, qop_state); if (status != GSS_S_COMPLETE) map_error(minor_status, mech); } else status = GSS_S_UNAVAILABLE; return(status); } return (GSS_S_BAD_MECH); }
168,027
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void __skb_complete_tx_timestamp(struct sk_buff *skb, struct sock *sk, int tstype) { struct sock_exterr_skb *serr; int err; serr = SKB_EXT_ERR(skb); memset(serr, 0, sizeof(*serr)); serr->ee.ee_errno = ENOMSG; serr->ee.ee_origin = SO_EE_ORIGIN_TIMESTAMPING; serr->ee.ee_info = tstype; if (sk->sk_tsflags & SOF_TIMESTAMPING_OPT_ID) { serr->ee.ee_data = skb_shinfo(skb)->tskey; if (sk->sk_protocol == IPPROTO_TCP && sk->sk_type == SOCK_STREAM) serr->ee.ee_data -= sk->sk_tskey; } err = sock_queue_err_skb(sk, skb); if (err) kfree_skb(skb); } Commit Message: tcp: mark skbs with SCM_TIMESTAMPING_OPT_STATS SOF_TIMESTAMPING_OPT_STATS can be enabled and disabled while packets are collected on the error queue. So, checking SOF_TIMESTAMPING_OPT_STATS in sk->sk_tsflags is not enough to safely assume that the skb contains OPT_STATS data. Add a bit in sock_exterr_skb to indicate whether the skb contains opt_stats data. Fixes: 1c885808e456 ("tcp: SOF_TIMESTAMPING_OPT_STATS option for SO_TIMESTAMPING") Reported-by: JongHwan Kim <[email protected]> Signed-off-by: Soheil Hassas Yeganeh <[email protected]> Signed-off-by: Eric Dumazet <[email protected]> Signed-off-by: Willem de Bruijn <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-125
static void __skb_complete_tx_timestamp(struct sk_buff *skb, struct sock *sk, int tstype, bool opt_stats) { struct sock_exterr_skb *serr; int err; BUILD_BUG_ON(sizeof(struct sock_exterr_skb) > sizeof(skb->cb)); serr = SKB_EXT_ERR(skb); memset(serr, 0, sizeof(*serr)); serr->ee.ee_errno = ENOMSG; serr->ee.ee_origin = SO_EE_ORIGIN_TIMESTAMPING; serr->ee.ee_info = tstype; serr->opt_stats = opt_stats; if (sk->sk_tsflags & SOF_TIMESTAMPING_OPT_ID) { serr->ee.ee_data = skb_shinfo(skb)->tskey; if (sk->sk_protocol == IPPROTO_TCP && sk->sk_type == SOCK_STREAM) serr->ee.ee_data -= sk->sk_tskey; } err = sock_queue_err_skb(sk, skb); if (err) kfree_skb(skb); }
170,071
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void ChromeMockRenderThread::OnGetDefaultPrintSettings( PrintMsg_Print_Params* params) { if (printer_.get()) printer_->GetDefaultPrintSettings(params); } Commit Message: Print preview: Use an ID instead of memory pointer string in WebUI. BUG=144051 Review URL: https://chromiumcodereview.appspot.com/10870003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@153342 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-200
void ChromeMockRenderThread::OnGetDefaultPrintSettings( PrintMsg_Print_Params* params) { printer_->GetDefaultPrintSettings(params); }
170,851
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int cdc_parse_cdc_header(struct usb_cdc_parsed_header *hdr, struct usb_interface *intf, u8 *buffer, int buflen) { /* duplicates are ignored */ struct usb_cdc_union_desc *union_header = NULL; /* duplicates are not tolerated */ struct usb_cdc_header_desc *header = NULL; struct usb_cdc_ether_desc *ether = NULL; struct usb_cdc_mdlm_detail_desc *detail = NULL; struct usb_cdc_mdlm_desc *desc = NULL; unsigned int elength; int cnt = 0; memset(hdr, 0x00, sizeof(struct usb_cdc_parsed_header)); hdr->phonet_magic_present = false; while (buflen > 0) { elength = buffer[0]; if (!elength) { dev_err(&intf->dev, "skipping garbage byte\n"); elength = 1; goto next_desc; } if (buffer[1] != USB_DT_CS_INTERFACE) { dev_err(&intf->dev, "skipping garbage\n"); goto next_desc; } switch (buffer[2]) { case USB_CDC_UNION_TYPE: /* we've found it */ if (elength < sizeof(struct usb_cdc_union_desc)) goto next_desc; if (union_header) { dev_err(&intf->dev, "More than one union descriptor, skipping ...\n"); goto next_desc; } union_header = (struct usb_cdc_union_desc *)buffer; break; case USB_CDC_COUNTRY_TYPE: if (elength < sizeof(struct usb_cdc_country_functional_desc)) goto next_desc; hdr->usb_cdc_country_functional_desc = (struct usb_cdc_country_functional_desc *)buffer; break; case USB_CDC_HEADER_TYPE: if (elength != sizeof(struct usb_cdc_header_desc)) goto next_desc; if (header) return -EINVAL; header = (struct usb_cdc_header_desc *)buffer; break; case USB_CDC_ACM_TYPE: if (elength < sizeof(struct usb_cdc_acm_descriptor)) goto next_desc; hdr->usb_cdc_acm_descriptor = (struct usb_cdc_acm_descriptor *)buffer; break; case USB_CDC_ETHERNET_TYPE: if (elength != sizeof(struct usb_cdc_ether_desc)) goto next_desc; if (ether) return -EINVAL; ether = (struct usb_cdc_ether_desc *)buffer; break; case USB_CDC_CALL_MANAGEMENT_TYPE: if (elength < sizeof(struct usb_cdc_call_mgmt_descriptor)) goto next_desc; hdr->usb_cdc_call_mgmt_descriptor = (struct usb_cdc_call_mgmt_descriptor *)buffer; break; case USB_CDC_DMM_TYPE: if (elength < sizeof(struct usb_cdc_dmm_desc)) goto next_desc; hdr->usb_cdc_dmm_desc = (struct usb_cdc_dmm_desc *)buffer; break; case USB_CDC_MDLM_TYPE: if (elength < sizeof(struct usb_cdc_mdlm_desc *)) goto next_desc; if (desc) return -EINVAL; desc = (struct usb_cdc_mdlm_desc *)buffer; break; case USB_CDC_MDLM_DETAIL_TYPE: if (elength < sizeof(struct usb_cdc_mdlm_detail_desc *)) goto next_desc; if (detail) return -EINVAL; detail = (struct usb_cdc_mdlm_detail_desc *)buffer; break; case USB_CDC_NCM_TYPE: if (elength < sizeof(struct usb_cdc_ncm_desc)) goto next_desc; hdr->usb_cdc_ncm_desc = (struct usb_cdc_ncm_desc *)buffer; break; case USB_CDC_MBIM_TYPE: if (elength < sizeof(struct usb_cdc_mbim_desc)) goto next_desc; hdr->usb_cdc_mbim_desc = (struct usb_cdc_mbim_desc *)buffer; break; case USB_CDC_MBIM_EXTENDED_TYPE: if (elength < sizeof(struct usb_cdc_mbim_extended_desc)) break; hdr->usb_cdc_mbim_extended_desc = (struct usb_cdc_mbim_extended_desc *)buffer; break; case CDC_PHONET_MAGIC_NUMBER: hdr->phonet_magic_present = true; break; default: /* * there are LOTS more CDC descriptors that * could legitimately be found here. */ dev_dbg(&intf->dev, "Ignoring descriptor: type %02x, length %ud\n", buffer[2], elength); goto next_desc; } cnt++; next_desc: buflen -= elength; buffer += elength; } hdr->usb_cdc_union_desc = union_header; hdr->usb_cdc_header_desc = header; hdr->usb_cdc_mdlm_detail_desc = detail; hdr->usb_cdc_mdlm_desc = desc; hdr->usb_cdc_ether_desc = ether; return cnt; } Commit Message: USB: core: harden cdc_parse_cdc_header Andrey Konovalov reported a possible out-of-bounds problem for the cdc_parse_cdc_header function. He writes: It looks like cdc_parse_cdc_header() doesn't validate buflen before accessing buffer[1], buffer[2] and so on. The only check present is while (buflen > 0). So fix this issue up by properly validating the buffer length matches what the descriptor says it is. Reported-by: Andrey Konovalov <[email protected]> Tested-by: Andrey Konovalov <[email protected]> Cc: stable <[email protected]> Signed-off-by: Greg Kroah-Hartman <[email protected]> CWE ID: CWE-119
int cdc_parse_cdc_header(struct usb_cdc_parsed_header *hdr, struct usb_interface *intf, u8 *buffer, int buflen) { /* duplicates are ignored */ struct usb_cdc_union_desc *union_header = NULL; /* duplicates are not tolerated */ struct usb_cdc_header_desc *header = NULL; struct usb_cdc_ether_desc *ether = NULL; struct usb_cdc_mdlm_detail_desc *detail = NULL; struct usb_cdc_mdlm_desc *desc = NULL; unsigned int elength; int cnt = 0; memset(hdr, 0x00, sizeof(struct usb_cdc_parsed_header)); hdr->phonet_magic_present = false; while (buflen > 0) { elength = buffer[0]; if (!elength) { dev_err(&intf->dev, "skipping garbage byte\n"); elength = 1; goto next_desc; } if ((buflen < elength) || (elength < 3)) { dev_err(&intf->dev, "invalid descriptor buffer length\n"); break; } if (buffer[1] != USB_DT_CS_INTERFACE) { dev_err(&intf->dev, "skipping garbage\n"); goto next_desc; } switch (buffer[2]) { case USB_CDC_UNION_TYPE: /* we've found it */ if (elength < sizeof(struct usb_cdc_union_desc)) goto next_desc; if (union_header) { dev_err(&intf->dev, "More than one union descriptor, skipping ...\n"); goto next_desc; } union_header = (struct usb_cdc_union_desc *)buffer; break; case USB_CDC_COUNTRY_TYPE: if (elength < sizeof(struct usb_cdc_country_functional_desc)) goto next_desc; hdr->usb_cdc_country_functional_desc = (struct usb_cdc_country_functional_desc *)buffer; break; case USB_CDC_HEADER_TYPE: if (elength != sizeof(struct usb_cdc_header_desc)) goto next_desc; if (header) return -EINVAL; header = (struct usb_cdc_header_desc *)buffer; break; case USB_CDC_ACM_TYPE: if (elength < sizeof(struct usb_cdc_acm_descriptor)) goto next_desc; hdr->usb_cdc_acm_descriptor = (struct usb_cdc_acm_descriptor *)buffer; break; case USB_CDC_ETHERNET_TYPE: if (elength != sizeof(struct usb_cdc_ether_desc)) goto next_desc; if (ether) return -EINVAL; ether = (struct usb_cdc_ether_desc *)buffer; break; case USB_CDC_CALL_MANAGEMENT_TYPE: if (elength < sizeof(struct usb_cdc_call_mgmt_descriptor)) goto next_desc; hdr->usb_cdc_call_mgmt_descriptor = (struct usb_cdc_call_mgmt_descriptor *)buffer; break; case USB_CDC_DMM_TYPE: if (elength < sizeof(struct usb_cdc_dmm_desc)) goto next_desc; hdr->usb_cdc_dmm_desc = (struct usb_cdc_dmm_desc *)buffer; break; case USB_CDC_MDLM_TYPE: if (elength < sizeof(struct usb_cdc_mdlm_desc *)) goto next_desc; if (desc) return -EINVAL; desc = (struct usb_cdc_mdlm_desc *)buffer; break; case USB_CDC_MDLM_DETAIL_TYPE: if (elength < sizeof(struct usb_cdc_mdlm_detail_desc *)) goto next_desc; if (detail) return -EINVAL; detail = (struct usb_cdc_mdlm_detail_desc *)buffer; break; case USB_CDC_NCM_TYPE: if (elength < sizeof(struct usb_cdc_ncm_desc)) goto next_desc; hdr->usb_cdc_ncm_desc = (struct usb_cdc_ncm_desc *)buffer; break; case USB_CDC_MBIM_TYPE: if (elength < sizeof(struct usb_cdc_mbim_desc)) goto next_desc; hdr->usb_cdc_mbim_desc = (struct usb_cdc_mbim_desc *)buffer; break; case USB_CDC_MBIM_EXTENDED_TYPE: if (elength < sizeof(struct usb_cdc_mbim_extended_desc)) break; hdr->usb_cdc_mbim_extended_desc = (struct usb_cdc_mbim_extended_desc *)buffer; break; case CDC_PHONET_MAGIC_NUMBER: hdr->phonet_magic_present = true; break; default: /* * there are LOTS more CDC descriptors that * could legitimately be found here. */ dev_dbg(&intf->dev, "Ignoring descriptor: type %02x, length %ud\n", buffer[2], elength); goto next_desc; } cnt++; next_desc: buflen -= elength; buffer += elength; } hdr->usb_cdc_union_desc = union_header; hdr->usb_cdc_header_desc = header; hdr->usb_cdc_mdlm_detail_desc = detail; hdr->usb_cdc_mdlm_desc = desc; hdr->usb_cdc_ether_desc = ether; return cnt; }
167,676
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: gss_export_sec_context(minor_status, context_handle, interprocess_token) OM_uint32 * minor_status; gss_ctx_id_t * context_handle; gss_buffer_t interprocess_token; { OM_uint32 status; OM_uint32 length; gss_union_ctx_id_t ctx = NULL; gss_mechanism mech; gss_buffer_desc token = GSS_C_EMPTY_BUFFER; char *buf; status = val_exp_sec_ctx_args(minor_status, context_handle, interprocess_token); if (status != GSS_S_COMPLETE) return (status); /* * select the approprate underlying mechanism routine and * call it. */ ctx = (gss_union_ctx_id_t) *context_handle; mech = gssint_get_mechanism (ctx->mech_type); if (!mech) return GSS_S_BAD_MECH; if (!mech->gss_export_sec_context) return (GSS_S_UNAVAILABLE); status = mech->gss_export_sec_context(minor_status, &ctx->internal_ctx_id, &token); if (status != GSS_S_COMPLETE) { map_error(minor_status, mech); goto cleanup; } length = token.length + 4 + ctx->mech_type->length; interprocess_token->length = length; interprocess_token->value = malloc(length); if (interprocess_token->value == 0) { *minor_status = ENOMEM; status = GSS_S_FAILURE; goto cleanup; } buf = interprocess_token->value; length = ctx->mech_type->length; buf[3] = (unsigned char) (length & 0xFF); length >>= 8; buf[2] = (unsigned char) (length & 0xFF); length >>= 8; buf[1] = (unsigned char) (length & 0xFF); length >>= 8; buf[0] = (unsigned char) (length & 0xFF); memcpy(buf+4, ctx->mech_type->elements, (size_t) ctx->mech_type->length); memcpy(buf+4+ctx->mech_type->length, token.value, token.length); status = GSS_S_COMPLETE; cleanup: (void) gss_release_buffer(minor_status, &token); if (ctx != NULL && ctx->internal_ctx_id == GSS_C_NO_CONTEXT) { /* If the mech deleted its context, delete the union context. */ free(ctx->mech_type->elements); free(ctx->mech_type); free(ctx); *context_handle = GSS_C_NO_CONTEXT; } return status; } Commit Message: Preserve GSS context on init/accept failure After gss_init_sec_context() or gss_accept_sec_context() has created a context, don't delete the mechglue context on failures from subsequent calls, even if the mechanism deletes the mech-specific context (which is allowed by RFC 2744 but not preferred). Check for union contexts with no mechanism context in each GSS function which accepts a gss_ctx_id_t. CVE-2017-11462: RFC 2744 permits a GSS-API implementation to delete an existing security context on a second or subsequent call to gss_init_sec_context() or gss_accept_sec_context() if the call results in an error. This API behavior has been found to be dangerous, leading to the possibility of memory errors in some callers. For safety, GSS-API implementations should instead preserve existing security contexts on error until the caller deletes them. All versions of MIT krb5 prior to this change may delete acceptor contexts on error. Versions 1.13.4 through 1.13.7, 1.14.1 through 1.14.5, and 1.15 through 1.15.1 may also delete initiator contexts on error. ticket: 8598 (new) target_version: 1.15-next target_version: 1.14-next tags: pullup CWE ID: CWE-415
gss_export_sec_context(minor_status, context_handle, interprocess_token) OM_uint32 * minor_status; gss_ctx_id_t * context_handle; gss_buffer_t interprocess_token; { OM_uint32 status; OM_uint32 length; gss_union_ctx_id_t ctx = NULL; gss_mechanism mech; gss_buffer_desc token = GSS_C_EMPTY_BUFFER; char *buf; status = val_exp_sec_ctx_args(minor_status, context_handle, interprocess_token); if (status != GSS_S_COMPLETE) return (status); /* * select the approprate underlying mechanism routine and * call it. */ ctx = (gss_union_ctx_id_t) *context_handle; if (ctx->internal_ctx_id == GSS_C_NO_CONTEXT) return (GSS_S_NO_CONTEXT); mech = gssint_get_mechanism (ctx->mech_type); if (!mech) return GSS_S_BAD_MECH; if (!mech->gss_export_sec_context) return (GSS_S_UNAVAILABLE); status = mech->gss_export_sec_context(minor_status, &ctx->internal_ctx_id, &token); if (status != GSS_S_COMPLETE) { map_error(minor_status, mech); goto cleanup; } length = token.length + 4 + ctx->mech_type->length; interprocess_token->length = length; interprocess_token->value = malloc(length); if (interprocess_token->value == 0) { *minor_status = ENOMEM; status = GSS_S_FAILURE; goto cleanup; } buf = interprocess_token->value; length = ctx->mech_type->length; buf[3] = (unsigned char) (length & 0xFF); length >>= 8; buf[2] = (unsigned char) (length & 0xFF); length >>= 8; buf[1] = (unsigned char) (length & 0xFF); length >>= 8; buf[0] = (unsigned char) (length & 0xFF); memcpy(buf+4, ctx->mech_type->elements, (size_t) ctx->mech_type->length); memcpy(buf+4+ctx->mech_type->length, token.value, token.length); status = GSS_S_COMPLETE; cleanup: (void) gss_release_buffer(minor_status, &token); if (ctx != NULL && ctx->internal_ctx_id == GSS_C_NO_CONTEXT) { /* If the mech deleted its context, delete the union context. */ free(ctx->mech_type->elements); free(ctx->mech_type); free(ctx); *context_handle = GSS_C_NO_CONTEXT; } return status; }
168,015
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int ntlm_read_message_fields_buffer(wStream* s, NTLM_MESSAGE_FIELDS* fields) { if (fields->Len > 0) { if ((fields->BufferOffset + fields->Len) > Stream_Length(s)) return -1; fields->Buffer = (PBYTE) malloc(fields->Len); if (!fields->Buffer) return -1; Stream_SetPosition(s, fields->BufferOffset); Stream_Read(s, fields->Buffer, fields->Len); } return 1; } Commit Message: Fixed CVE-2018-8789 Thanks to Eyal Itkin from Check Point Software Technologies. CWE ID: CWE-125
int ntlm_read_message_fields_buffer(wStream* s, NTLM_MESSAGE_FIELDS* fields) static int ntlm_read_message_fields_buffer(wStream* s, NTLM_MESSAGE_FIELDS* fields) { if (fields->Len > 0) { const UINT64 offset = (UINT64)fields->BufferOffset + (UINT64)fields->Len; if (offset > Stream_Length(s)) return -1; fields->Buffer = (PBYTE) malloc(fields->Len); if (!fields->Buffer) return -1; Stream_SetPosition(s, fields->BufferOffset); Stream_Read(s, fields->Buffer, fields->Len); } return 1; }
169,277
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: status_t SampleTable::setTimeToSampleParams( off64_t data_offset, size_t data_size) { if (mTimeToSample != NULL || data_size < 8) { return ERROR_MALFORMED; } uint8_t header[8]; if (mDataSource->readAt( data_offset, header, sizeof(header)) < (ssize_t)sizeof(header)) { return ERROR_IO; } if (U32_AT(header) != 0) { return ERROR_MALFORMED; } mTimeToSampleCount = U32_AT(&header[4]); uint64_t allocSize = (uint64_t)mTimeToSampleCount * 2 * sizeof(uint32_t); if (allocSize > UINT32_MAX) { return ERROR_OUT_OF_RANGE; } mTimeToSample = new (std::nothrow) uint32_t[mTimeToSampleCount * 2]; if (!mTimeToSample) return ERROR_OUT_OF_RANGE; size_t size = sizeof(uint32_t) * mTimeToSampleCount * 2; if (mDataSource->readAt( data_offset + 8, mTimeToSample, size) < (ssize_t)size) { return ERROR_IO; } for (uint32_t i = 0; i < mTimeToSampleCount * 2; ++i) { mTimeToSample[i] = ntohl(mTimeToSample[i]); } return OK; } Commit Message: Resolve merge conflict when cp'ing ag/931301 to mnc-mr1-release Change-Id: I079d1db2d30d126f8aed348bd62451acf741037d CWE ID: CWE-20
status_t SampleTable::setTimeToSampleParams( off64_t data_offset, size_t data_size) { if (!mTimeToSample.empty() || data_size < 8) { return ERROR_MALFORMED; } uint8_t header[8]; if (mDataSource->readAt( data_offset, header, sizeof(header)) < (ssize_t)sizeof(header)) { return ERROR_IO; } if (U32_AT(header) != 0) { return ERROR_MALFORMED; } mTimeToSampleCount = U32_AT(&header[4]); if ((uint64_t)mTimeToSampleCount > (uint64_t)UINT32_MAX / (2 * sizeof(uint32_t))) { // Choose this bound because // 1) 2 * sizeof(uint32_t) is the amount of memory needed for one // time-to-sample entry in the time-to-sample table. // 2) mTimeToSampleCount is the number of entries of the time-to-sample // table. // 3) We hope that the table size does not exceed UINT32_MAX. ALOGE(" Error: Time-to-sample table size too large."); return ERROR_OUT_OF_RANGE; } // Note: At this point, we know that mTimeToSampleCount * 2 will not // overflow because of the above condition. if (!mDataSource->getVector(data_offset + 8, &mTimeToSample, mTimeToSampleCount * 2)) { ALOGE(" Error: Incomplete data read for time-to-sample table."); return ERROR_IO; } for (size_t i = 0; i < mTimeToSample.size(); ++i) { mTimeToSample.editItemAt(i) = ntohl(mTimeToSample[i]); } return OK; }
174,173
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void ResourceDispatcherHostImpl::BlockRequestsForRoute(int child_id, int route_id) { ProcessRouteIDs key(child_id, route_id); DCHECK(blocked_loaders_map_.find(key) == blocked_loaders_map_.end()) << "BlockRequestsForRoute called multiple time for the same RVH"; blocked_loaders_map_[key] = new BlockedLoadersList(); } Commit Message: Make chrome.appWindow.create() provide access to the child window at a predictable time. When you first create a window with chrome.appWindow.create(), it won't have loaded any resources. So, at create time, you are guaranteed that: child_window.location.href == 'about:blank' child_window.document.documentElement.outerHTML == '<html><head></head><body></body></html>' This is in line with the behaviour of window.open(). BUG=131735 TEST=browser_tests:PlatformAppBrowserTest.WindowsApi Committed: http://src.chromium.org/viewvc/chrome?view=rev&revision=144072 Review URL: https://chromiumcodereview.appspot.com/10644006 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@144356 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void ResourceDispatcherHostImpl::BlockRequestsForRoute(int child_id, int route_id) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); ProcessRouteIDs key(child_id, route_id); DCHECK(blocked_loaders_map_.find(key) == blocked_loaders_map_.end()) << "BlockRequestsForRoute called multiple time for the same RVH"; blocked_loaders_map_[key] = new BlockedLoadersList(); }
170,816
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void encode_share_access(struct xdr_stream *xdr, int open_flags) { __be32 *p; RESERVE_SPACE(8); switch (open_flags & (FMODE_READ|FMODE_WRITE)) { case FMODE_READ: WRITE32(NFS4_SHARE_ACCESS_READ); break; case FMODE_WRITE: WRITE32(NFS4_SHARE_ACCESS_WRITE); break; case FMODE_READ|FMODE_WRITE: WRITE32(NFS4_SHARE_ACCESS_BOTH); break; default: BUG(); } WRITE32(0); /* for linux, share_deny = 0 always */ } Commit Message: NFSv4: Convert the open and close ops to use fmode Signed-off-by: Trond Myklebust <[email protected]> CWE ID:
static void encode_share_access(struct xdr_stream *xdr, int open_flags) static void encode_share_access(struct xdr_stream *xdr, fmode_t fmode) { __be32 *p; RESERVE_SPACE(8); switch (fmode & (FMODE_READ|FMODE_WRITE)) { case FMODE_READ: WRITE32(NFS4_SHARE_ACCESS_READ); break; case FMODE_WRITE: WRITE32(NFS4_SHARE_ACCESS_WRITE); break; case FMODE_READ|FMODE_WRITE: WRITE32(NFS4_SHARE_ACCESS_BOTH); break; default: WRITE32(0); } WRITE32(0); /* for linux, share_deny = 0 always */ }
165,715
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env, struct bpf_insn *insn, struct bpf_reg_state *dst_reg, struct bpf_reg_state src_reg) { struct bpf_reg_state *regs = cur_regs(env); u8 opcode = BPF_OP(insn->code); bool src_known, dst_known; s64 smin_val, smax_val; u64 umin_val, umax_val; u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32; smin_val = src_reg.smin_value; smax_val = src_reg.smax_value; umin_val = src_reg.umin_value; umax_val = src_reg.umax_value; src_known = tnum_is_const(src_reg.var_off); dst_known = tnum_is_const(dst_reg->var_off); switch (opcode) { case BPF_ADD: if (signed_add_overflows(dst_reg->smin_value, smin_val) || signed_add_overflows(dst_reg->smax_value, smax_val)) { dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; } else { dst_reg->smin_value += smin_val; dst_reg->smax_value += smax_val; } if (dst_reg->umin_value + umin_val < umin_val || dst_reg->umax_value + umax_val < umax_val) { dst_reg->umin_value = 0; dst_reg->umax_value = U64_MAX; } else { dst_reg->umin_value += umin_val; dst_reg->umax_value += umax_val; } dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off); break; case BPF_SUB: if (signed_sub_overflows(dst_reg->smin_value, smax_val) || signed_sub_overflows(dst_reg->smax_value, smin_val)) { /* Overflow possible, we know nothing */ dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; } else { dst_reg->smin_value -= smax_val; dst_reg->smax_value -= smin_val; } if (dst_reg->umin_value < umax_val) { /* Overflow possible, we know nothing */ dst_reg->umin_value = 0; dst_reg->umax_value = U64_MAX; } else { /* Cannot overflow (as long as bounds are consistent) */ dst_reg->umin_value -= umax_val; dst_reg->umax_value -= umin_val; } dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off); break; case BPF_MUL: dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off); if (smin_val < 0 || dst_reg->smin_value < 0) { /* Ain't nobody got time to multiply that sign */ __mark_reg_unbounded(dst_reg); __update_reg_bounds(dst_reg); break; } /* Both values are positive, so we can work with unsigned and * copy the result to signed (unless it exceeds S64_MAX). */ if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) { /* Potential overflow, we know nothing */ __mark_reg_unbounded(dst_reg); /* (except what we can learn from the var_off) */ __update_reg_bounds(dst_reg); break; } dst_reg->umin_value *= umin_val; dst_reg->umax_value *= umax_val; if (dst_reg->umax_value > S64_MAX) { /* Overflow possible, we know nothing */ dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; } else { dst_reg->smin_value = dst_reg->umin_value; dst_reg->smax_value = dst_reg->umax_value; } break; case BPF_AND: if (src_known && dst_known) { __mark_reg_known(dst_reg, dst_reg->var_off.value & src_reg.var_off.value); break; } /* We get our minimum from the var_off, since that's inherently * bitwise. Our maximum is the minimum of the operands' maxima. */ dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off); dst_reg->umin_value = dst_reg->var_off.value; dst_reg->umax_value = min(dst_reg->umax_value, umax_val); if (dst_reg->smin_value < 0 || smin_val < 0) { /* Lose signed bounds when ANDing negative numbers, * ain't nobody got time for that. */ dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; } else { /* ANDing two positives gives a positive, so safe to * cast result into s64. */ dst_reg->smin_value = dst_reg->umin_value; dst_reg->smax_value = dst_reg->umax_value; } /* We may learn something more from the var_off */ __update_reg_bounds(dst_reg); break; case BPF_OR: if (src_known && dst_known) { __mark_reg_known(dst_reg, dst_reg->var_off.value | src_reg.var_off.value); break; } /* We get our maximum from the var_off, and our minimum is the * maximum of the operands' minima */ dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off); dst_reg->umin_value = max(dst_reg->umin_value, umin_val); dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask; if (dst_reg->smin_value < 0 || smin_val < 0) { /* Lose signed bounds when ORing negative numbers, * ain't nobody got time for that. */ dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; } else { /* ORing two positives gives a positive, so safe to * cast result into s64. */ dst_reg->smin_value = dst_reg->umin_value; dst_reg->smax_value = dst_reg->umax_value; } /* We may learn something more from the var_off */ __update_reg_bounds(dst_reg); break; case BPF_LSH: if (umax_val >= insn_bitness) { /* Shifts greater than 31 or 63 are undefined. * This includes shifts by a negative number. */ mark_reg_unknown(env, regs, insn->dst_reg); break; } /* We lose all sign bit information (except what we can pick * up from var_off) */ dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; /* If we might shift our top bit out, then we know nothing */ if (dst_reg->umax_value > 1ULL << (63 - umax_val)) { dst_reg->umin_value = 0; dst_reg->umax_value = U64_MAX; } else { dst_reg->umin_value <<= umin_val; dst_reg->umax_value <<= umax_val; } if (src_known) dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val); else dst_reg->var_off = tnum_lshift(tnum_unknown, umin_val); /* We may learn something more from the var_off */ __update_reg_bounds(dst_reg); break; case BPF_RSH: if (umax_val >= insn_bitness) { /* Shifts greater than 31 or 63 are undefined. * This includes shifts by a negative number. */ mark_reg_unknown(env, regs, insn->dst_reg); break; } /* BPF_RSH is an unsigned shift. If the value in dst_reg might * be negative, then either: * 1) src_reg might be zero, so the sign bit of the result is * unknown, so we lose our signed bounds * 2) it's known negative, thus the unsigned bounds capture the * signed bounds * 3) the signed bounds cross zero, so they tell us nothing * about the result * If the value in dst_reg is known nonnegative, then again the * unsigned bounts capture the signed bounds. * Thus, in all cases it suffices to blow away our signed bounds * and rely on inferring new ones from the unsigned bounds and * var_off of the result. */ dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; if (src_known) dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val); else dst_reg->var_off = tnum_rshift(tnum_unknown, umin_val); dst_reg->umin_value >>= umax_val; dst_reg->umax_value >>= umin_val; /* We may learn something more from the var_off */ __update_reg_bounds(dst_reg); break; default: mark_reg_unknown(env, regs, insn->dst_reg); break; } if (BPF_CLASS(insn->code) != BPF_ALU64) { /* 32-bit ALU ops are (32,32)->32 */ coerce_reg_to_size(dst_reg, 4); coerce_reg_to_size(&src_reg, 4); } __reg_deduce_bounds(dst_reg); __reg_bound_offset(dst_reg); return 0; } Commit Message: bpf: fix integer overflows There were various issues related to the limited size of integers used in the verifier: - `off + size` overflow in __check_map_access() - `off + reg->off` overflow in check_mem_access() - `off + reg->var_off.value` overflow or 32-bit truncation of `reg->var_off.value` in check_mem_access() - 32-bit truncation in check_stack_boundary() Make sure that any integer math cannot overflow by not allowing pointer math with large values. Also reduce the scope of "scalar op scalar" tracking. Fixes: f1174f77b50c ("bpf/verifier: rework value tracking") Reported-by: Jann Horn <[email protected]> Signed-off-by: Alexei Starovoitov <[email protected]> Signed-off-by: Daniel Borkmann <[email protected]> CWE ID: CWE-190
static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env, struct bpf_insn *insn, struct bpf_reg_state *dst_reg, struct bpf_reg_state src_reg) { struct bpf_reg_state *regs = cur_regs(env); u8 opcode = BPF_OP(insn->code); bool src_known, dst_known; s64 smin_val, smax_val; u64 umin_val, umax_val; u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32; smin_val = src_reg.smin_value; smax_val = src_reg.smax_value; umin_val = src_reg.umin_value; umax_val = src_reg.umax_value; src_known = tnum_is_const(src_reg.var_off); dst_known = tnum_is_const(dst_reg->var_off); if (!src_known && opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) { __mark_reg_unknown(dst_reg); return 0; } switch (opcode) { case BPF_ADD: if (signed_add_overflows(dst_reg->smin_value, smin_val) || signed_add_overflows(dst_reg->smax_value, smax_val)) { dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; } else { dst_reg->smin_value += smin_val; dst_reg->smax_value += smax_val; } if (dst_reg->umin_value + umin_val < umin_val || dst_reg->umax_value + umax_val < umax_val) { dst_reg->umin_value = 0; dst_reg->umax_value = U64_MAX; } else { dst_reg->umin_value += umin_val; dst_reg->umax_value += umax_val; } dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off); break; case BPF_SUB: if (signed_sub_overflows(dst_reg->smin_value, smax_val) || signed_sub_overflows(dst_reg->smax_value, smin_val)) { /* Overflow possible, we know nothing */ dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; } else { dst_reg->smin_value -= smax_val; dst_reg->smax_value -= smin_val; } if (dst_reg->umin_value < umax_val) { /* Overflow possible, we know nothing */ dst_reg->umin_value = 0; dst_reg->umax_value = U64_MAX; } else { /* Cannot overflow (as long as bounds are consistent) */ dst_reg->umin_value -= umax_val; dst_reg->umax_value -= umin_val; } dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off); break; case BPF_MUL: dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off); if (smin_val < 0 || dst_reg->smin_value < 0) { /* Ain't nobody got time to multiply that sign */ __mark_reg_unbounded(dst_reg); __update_reg_bounds(dst_reg); break; } /* Both values are positive, so we can work with unsigned and * copy the result to signed (unless it exceeds S64_MAX). */ if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) { /* Potential overflow, we know nothing */ __mark_reg_unbounded(dst_reg); /* (except what we can learn from the var_off) */ __update_reg_bounds(dst_reg); break; } dst_reg->umin_value *= umin_val; dst_reg->umax_value *= umax_val; if (dst_reg->umax_value > S64_MAX) { /* Overflow possible, we know nothing */ dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; } else { dst_reg->smin_value = dst_reg->umin_value; dst_reg->smax_value = dst_reg->umax_value; } break; case BPF_AND: if (src_known && dst_known) { __mark_reg_known(dst_reg, dst_reg->var_off.value & src_reg.var_off.value); break; } /* We get our minimum from the var_off, since that's inherently * bitwise. Our maximum is the minimum of the operands' maxima. */ dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off); dst_reg->umin_value = dst_reg->var_off.value; dst_reg->umax_value = min(dst_reg->umax_value, umax_val); if (dst_reg->smin_value < 0 || smin_val < 0) { /* Lose signed bounds when ANDing negative numbers, * ain't nobody got time for that. */ dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; } else { /* ANDing two positives gives a positive, so safe to * cast result into s64. */ dst_reg->smin_value = dst_reg->umin_value; dst_reg->smax_value = dst_reg->umax_value; } /* We may learn something more from the var_off */ __update_reg_bounds(dst_reg); break; case BPF_OR: if (src_known && dst_known) { __mark_reg_known(dst_reg, dst_reg->var_off.value | src_reg.var_off.value); break; } /* We get our maximum from the var_off, and our minimum is the * maximum of the operands' minima */ dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off); dst_reg->umin_value = max(dst_reg->umin_value, umin_val); dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask; if (dst_reg->smin_value < 0 || smin_val < 0) { /* Lose signed bounds when ORing negative numbers, * ain't nobody got time for that. */ dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; } else { /* ORing two positives gives a positive, so safe to * cast result into s64. */ dst_reg->smin_value = dst_reg->umin_value; dst_reg->smax_value = dst_reg->umax_value; } /* We may learn something more from the var_off */ __update_reg_bounds(dst_reg); break; case BPF_LSH: if (umax_val >= insn_bitness) { /* Shifts greater than 31 or 63 are undefined. * This includes shifts by a negative number. */ mark_reg_unknown(env, regs, insn->dst_reg); break; } /* We lose all sign bit information (except what we can pick * up from var_off) */ dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; /* If we might shift our top bit out, then we know nothing */ if (dst_reg->umax_value > 1ULL << (63 - umax_val)) { dst_reg->umin_value = 0; dst_reg->umax_value = U64_MAX; } else { dst_reg->umin_value <<= umin_val; dst_reg->umax_value <<= umax_val; } if (src_known) dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val); else dst_reg->var_off = tnum_lshift(tnum_unknown, umin_val); /* We may learn something more from the var_off */ __update_reg_bounds(dst_reg); break; case BPF_RSH: if (umax_val >= insn_bitness) { /* Shifts greater than 31 or 63 are undefined. * This includes shifts by a negative number. */ mark_reg_unknown(env, regs, insn->dst_reg); break; } /* BPF_RSH is an unsigned shift. If the value in dst_reg might * be negative, then either: * 1) src_reg might be zero, so the sign bit of the result is * unknown, so we lose our signed bounds * 2) it's known negative, thus the unsigned bounds capture the * signed bounds * 3) the signed bounds cross zero, so they tell us nothing * about the result * If the value in dst_reg is known nonnegative, then again the * unsigned bounts capture the signed bounds. * Thus, in all cases it suffices to blow away our signed bounds * and rely on inferring new ones from the unsigned bounds and * var_off of the result. */ dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; if (src_known) dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val); else dst_reg->var_off = tnum_rshift(tnum_unknown, umin_val); dst_reg->umin_value >>= umax_val; dst_reg->umax_value >>= umin_val; /* We may learn something more from the var_off */ __update_reg_bounds(dst_reg); break; default: mark_reg_unknown(env, regs, insn->dst_reg); break; } if (BPF_CLASS(insn->code) != BPF_ALU64) { /* 32-bit ALU ops are (32,32)->32 */ coerce_reg_to_size(dst_reg, 4); coerce_reg_to_size(&src_reg, 4); } __reg_deduce_bounds(dst_reg); __reg_bound_offset(dst_reg); return 0; }
167,644
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void ip_cmsg_recv_checksum(struct msghdr *msg, struct sk_buff *skb, int tlen, int offset) { __wsum csum = skb->csum; if (skb->ip_summed != CHECKSUM_COMPLETE) return; if (offset != 0) csum = csum_sub(csum, csum_partial(skb_transport_header(skb) + tlen, offset, 0)); put_cmsg(msg, SOL_IP, IP_CHECKSUM, sizeof(__wsum), &csum); } Commit Message: ip: fix IP_CHECKSUM handling The skbs processed by ip_cmsg_recv() are not guaranteed to be linear e.g. when sending UDP packets over loopback with MSGMORE. Using csum_partial() on [potentially] the whole skb len is dangerous; instead be on the safe side and use skb_checksum(). Thanks to syzkaller team to detect the issue and provide the reproducer. v1 -> v2: - move the variable declaration in a tighter scope Fixes: ad6f939ab193 ("ip: Add offset parameter to ip_cmsg_recv") Reported-by: Andrey Konovalov <[email protected]> Signed-off-by: Paolo Abeni <[email protected]> Acked-by: Eric Dumazet <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-125
static void ip_cmsg_recv_checksum(struct msghdr *msg, struct sk_buff *skb, int tlen, int offset) { __wsum csum = skb->csum; if (skb->ip_summed != CHECKSUM_COMPLETE) return; if (offset != 0) { int tend_off = skb_transport_offset(skb) + tlen; csum = csum_sub(csum, skb_checksum(skb, tend_off, offset, 0)); } put_cmsg(msg, SOL_IP, IP_CHECKSUM, sizeof(__wsum), &csum); }
168,345
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void FileSystemOperation::GetUsageAndQuotaThenRunTask( const GURL& origin, FileSystemType type, const base::Closure& task, const base::Closure& error_callback) { quota::QuotaManagerProxy* quota_manager_proxy = file_system_context()->quota_manager_proxy(); if (!quota_manager_proxy || !file_system_context()->GetQuotaUtil(type)) { operation_context_.set_allowed_bytes_growth(kint64max); task.Run(); return; } TaskParamsForDidGetQuota params; params.origin = origin; params.type = type; params.task = task; params.error_callback = error_callback; DCHECK(quota_manager_proxy); DCHECK(quota_manager_proxy->quota_manager()); quota_manager_proxy->quota_manager()->GetUsageAndQuota( origin, FileSystemTypeToQuotaStorageType(type), base::Bind(&FileSystemOperation::DidGetUsageAndQuotaAndRunTask, base::Unretained(this), params)); } Commit Message: Crash fix in fileapi::FileSystemOperation::DidGetUsageAndQuotaAndRunTask https://chromiumcodereview.appspot.com/10008047 introduced delete-with-inflight-tasks in Write sequence but I failed to convert this callback to use WeakPtr(). BUG=128178 TEST=manual test Review URL: https://chromiumcodereview.appspot.com/10408006 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@137635 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
void FileSystemOperation::GetUsageAndQuotaThenRunTask( const GURL& origin, FileSystemType type, const base::Closure& task, const base::Closure& error_callback) { quota::QuotaManagerProxy* quota_manager_proxy = file_system_context()->quota_manager_proxy(); if (!quota_manager_proxy || !file_system_context()->GetQuotaUtil(type)) { operation_context_.set_allowed_bytes_growth(kint64max); task.Run(); return; } TaskParamsForDidGetQuota params; params.origin = origin; params.type = type; params.task = task; params.error_callback = error_callback; DCHECK(quota_manager_proxy); DCHECK(quota_manager_proxy->quota_manager()); quota_manager_proxy->quota_manager()->GetUsageAndQuota( origin, FileSystemTypeToQuotaStorageType(type), base::Bind(&FileSystemOperation::DidGetUsageAndQuotaAndRunTask, weak_factory_.GetWeakPtr(), params)); }
170,762
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: std::unique_ptr<FakeMediaStreamUIProxy> CreateMockUI(bool expect_started) { std::unique_ptr<MockMediaStreamUIProxy> fake_ui = std::make_unique<MockMediaStreamUIProxy>(); if (expect_started) EXPECT_CALL(*fake_ui, MockOnStarted(_)); return fake_ui; } Commit Message: Make MediaStreamDispatcherHost per-request instead of per-frame. Instead of having RenderFrameHost own a single MSDH to handle all requests from a frame, MSDH objects will be owned by a strong binding. A consequence of this is that an additional requester ID is added to requests to MediaStreamManager, so that an MSDH is able to cancel only requests generated by it. In practice, MSDH will continue to be per frame in most cases since each frame normally makes a single request for an MSDH object. This fixes a lifetime issue caused by the IO thread executing tasks after the RenderFrameHost dies. Drive-by: Fix some minor lint issues. Bug: 912520 Change-Id: I52742ffc98b9fc57ce8e6f5093a61aed86d3e516 Reviewed-on: https://chromium-review.googlesource.com/c/1369799 Reviewed-by: Emircan Uysaler <[email protected]> Reviewed-by: Ken Buchanan <[email protected]> Reviewed-by: Olga Sharonova <[email protected]> Commit-Queue: Guido Urdaneta <[email protected]> Cr-Commit-Position: refs/heads/master@{#616347} CWE ID: CWE-189
std::unique_ptr<FakeMediaStreamUIProxy> CreateMockUI(bool expect_started) { std::unique_ptr<MockMediaStreamUIProxy> fake_ui = std::make_unique<MockMediaStreamUIProxy>(); testing::Mock::AllowLeak(fake_ui.get()); if (expect_started) EXPECT_CALL(*fake_ui, MockOnStarted(_)); return fake_ui; }
173,099
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void VRDisplay::ConnectVSyncProvider() { DVLOG(1) << __FUNCTION__ << ": IsPresentationFocused()=" << IsPresentationFocused() << " vr_v_sync_provider_.is_bound()=" << vr_v_sync_provider_.is_bound(); if (!IsPresentationFocused() || vr_v_sync_provider_.is_bound()) return; display_->GetVRVSyncProvider(mojo::MakeRequest(&vr_v_sync_provider_)); vr_v_sync_provider_.set_connection_error_handler(ConvertToBaseCallback( WTF::Bind(&VRDisplay::OnVSyncConnectionError, WrapWeakPersistent(this)))); if (pending_raf_ && !display_blurred_) { pending_vsync_ = true; vr_v_sync_provider_->GetVSync(ConvertToBaseCallback( WTF::Bind(&VRDisplay::OnVSync, WrapWeakPersistent(this)))); } } Commit Message: WebVR: fix initial vsync Applications sometimes use window.rAF while not presenting, then switch to vrDisplay.rAF after presentation starts. Depending on the animation loop's timing, this can cause a race condition where presentation has been started but there's no vrDisplay.rAF pending yet. Ensure there's at least vsync being processed after presentation starts so that a queued window.rAF can run and schedule a vrDisplay.rAF. BUG=711789 Review-Url: https://codereview.chromium.org/2848483003 Cr-Commit-Position: refs/heads/master@{#468167} CWE ID:
void VRDisplay::ConnectVSyncProvider() { DVLOG(1) << __FUNCTION__ << ": IsPresentationFocused()=" << IsPresentationFocused() << " vr_v_sync_provider_.is_bound()=" << vr_v_sync_provider_.is_bound(); if (!IsPresentationFocused() || vr_v_sync_provider_.is_bound()) return; display_->GetVRVSyncProvider(mojo::MakeRequest(&vr_v_sync_provider_)); vr_v_sync_provider_.set_connection_error_handler(ConvertToBaseCallback( WTF::Bind(&VRDisplay::OnVSyncConnectionError, WrapWeakPersistent(this)))); if (pending_vrdisplay_raf_ && !display_blurred_) { pending_vsync_ = true; vr_v_sync_provider_->GetVSync(ConvertToBaseCallback( WTF::Bind(&VRDisplay::OnVSync, WrapWeakPersistent(this)))); } }
171,992
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int llcp_sock_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t len, int flags) { int noblock = flags & MSG_DONTWAIT; struct sock *sk = sock->sk; unsigned int copied, rlen; struct sk_buff *skb, *cskb; int err = 0; pr_debug("%p %zu\n", sk, len); msg->msg_namelen = 0; lock_sock(sk); if (sk->sk_state == LLCP_CLOSED && skb_queue_empty(&sk->sk_receive_queue)) { release_sock(sk); return 0; } release_sock(sk); if (flags & (MSG_OOB)) return -EOPNOTSUPP; skb = skb_recv_datagram(sk, flags, noblock, &err); if (!skb) { pr_err("Recv datagram failed state %d %d %d", sk->sk_state, err, sock_error(sk)); if (sk->sk_shutdown & RCV_SHUTDOWN) return 0; return err; } rlen = skb->len; /* real length of skb */ copied = min_t(unsigned int, rlen, len); cskb = skb; if (skb_copy_datagram_iovec(cskb, 0, msg->msg_iov, copied)) { if (!(flags & MSG_PEEK)) skb_queue_head(&sk->sk_receive_queue, skb); return -EFAULT; } sock_recv_timestamp(msg, sk, skb); if (sk->sk_type == SOCK_DGRAM && msg->msg_name) { struct nfc_llcp_ui_cb *ui_cb = nfc_llcp_ui_skb_cb(skb); struct sockaddr_nfc_llcp *sockaddr = (struct sockaddr_nfc_llcp *) msg->msg_name; msg->msg_namelen = sizeof(struct sockaddr_nfc_llcp); pr_debug("Datagram socket %d %d\n", ui_cb->dsap, ui_cb->ssap); memset(sockaddr, 0, sizeof(*sockaddr)); sockaddr->sa_family = AF_NFC; sockaddr->nfc_protocol = NFC_PROTO_NFC_DEP; sockaddr->dsap = ui_cb->dsap; sockaddr->ssap = ui_cb->ssap; } /* Mark read part of skb as used */ if (!(flags & MSG_PEEK)) { /* SOCK_STREAM: re-queue skb if it contains unreceived data */ if (sk->sk_type == SOCK_STREAM || sk->sk_type == SOCK_DGRAM || sk->sk_type == SOCK_RAW) { skb_pull(skb, copied); if (skb->len) { skb_queue_head(&sk->sk_receive_queue, skb); goto done; } } kfree_skb(skb); } /* XXX Queue backlogged skbs */ done: /* SOCK_SEQPACKET: return real length if MSG_TRUNC is set */ if (sk->sk_type == SOCK_SEQPACKET && (flags & MSG_TRUNC)) copied = rlen; return copied; } Commit Message: net: rework recvmsg handler msg_name and msg_namelen logic This patch now always passes msg->msg_namelen as 0. recvmsg handlers must set msg_namelen to the proper size <= sizeof(struct sockaddr_storage) to return msg_name to the user. This prevents numerous uninitialized memory leaks we had in the recvmsg handlers and makes it harder for new code to accidentally leak uninitialized memory. Optimize for the case recvfrom is called with NULL as address. We don't need to copy the address at all, so set it to NULL before invoking the recvmsg handler. We can do so, because all the recvmsg handlers must cope with the case a plain read() is called on them. read() also sets msg_name to NULL. Also document these changes in include/linux/net.h as suggested by David Miller. Changes since RFC: Set msg->msg_name = NULL if user specified a NULL in msg_name but had a non-null msg_namelen in verify_iovec/verify_compat_iovec. This doesn't affect sendto as it would bail out earlier while trying to copy-in the address. It also more naturally reflects the logic by the callers of verify_iovec. With this change in place I could remove " if (!uaddr || msg_sys->msg_namelen == 0) msg->msg_name = NULL ". This change does not alter the user visible error logic as we ignore msg_namelen as long as msg_name is NULL. Also remove two unnecessary curly brackets in ___sys_recvmsg and change comments to netdev style. Cc: David Miller <[email protected]> Suggested-by: Eric Dumazet <[email protected]> Signed-off-by: Hannes Frederic Sowa <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-20
static int llcp_sock_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t len, int flags) { int noblock = flags & MSG_DONTWAIT; struct sock *sk = sock->sk; unsigned int copied, rlen; struct sk_buff *skb, *cskb; int err = 0; pr_debug("%p %zu\n", sk, len); lock_sock(sk); if (sk->sk_state == LLCP_CLOSED && skb_queue_empty(&sk->sk_receive_queue)) { release_sock(sk); return 0; } release_sock(sk); if (flags & (MSG_OOB)) return -EOPNOTSUPP; skb = skb_recv_datagram(sk, flags, noblock, &err); if (!skb) { pr_err("Recv datagram failed state %d %d %d", sk->sk_state, err, sock_error(sk)); if (sk->sk_shutdown & RCV_SHUTDOWN) return 0; return err; } rlen = skb->len; /* real length of skb */ copied = min_t(unsigned int, rlen, len); cskb = skb; if (skb_copy_datagram_iovec(cskb, 0, msg->msg_iov, copied)) { if (!(flags & MSG_PEEK)) skb_queue_head(&sk->sk_receive_queue, skb); return -EFAULT; } sock_recv_timestamp(msg, sk, skb); if (sk->sk_type == SOCK_DGRAM && msg->msg_name) { struct nfc_llcp_ui_cb *ui_cb = nfc_llcp_ui_skb_cb(skb); struct sockaddr_nfc_llcp *sockaddr = (struct sockaddr_nfc_llcp *) msg->msg_name; msg->msg_namelen = sizeof(struct sockaddr_nfc_llcp); pr_debug("Datagram socket %d %d\n", ui_cb->dsap, ui_cb->ssap); memset(sockaddr, 0, sizeof(*sockaddr)); sockaddr->sa_family = AF_NFC; sockaddr->nfc_protocol = NFC_PROTO_NFC_DEP; sockaddr->dsap = ui_cb->dsap; sockaddr->ssap = ui_cb->ssap; } /* Mark read part of skb as used */ if (!(flags & MSG_PEEK)) { /* SOCK_STREAM: re-queue skb if it contains unreceived data */ if (sk->sk_type == SOCK_STREAM || sk->sk_type == SOCK_DGRAM || sk->sk_type == SOCK_RAW) { skb_pull(skb, copied); if (skb->len) { skb_queue_head(&sk->sk_receive_queue, skb); goto done; } } kfree_skb(skb); } /* XXX Queue backlogged skbs */ done: /* SOCK_SEQPACKET: return real length if MSG_TRUNC is set */ if (sk->sk_type == SOCK_SEQPACKET && (flags & MSG_TRUNC)) copied = rlen; return copied; }
166,509
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static inline struct old_rng_alg *crypto_old_rng_alg(struct crypto_rng *tfm) { return &crypto_rng_tfm(tfm)->__crt_alg->cra_rng; } Commit Message: crypto: rng - Remove old low-level rng interface Now that all rng implementations have switched over to the new interface, we can remove the old low-level interface. Signed-off-by: Herbert Xu <[email protected]> CWE ID: CWE-476
static inline struct old_rng_alg *crypto_old_rng_alg(struct crypto_rng *tfm)
167,730
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void DocumentLoader::InstallNewDocument( const KURL& url, Document* owner_document, WebGlobalObjectReusePolicy global_object_reuse_policy, const AtomicString& mime_type, const AtomicString& encoding, InstallNewDocumentReason reason, ParserSynchronizationPolicy parsing_policy, const KURL& overriding_url) { DCHECK(!frame_->GetDocument() || !frame_->GetDocument()->IsActive()); DCHECK_EQ(frame_->Tree().ChildCount(), 0u); if (GetFrameLoader().StateMachine()->IsDisplayingInitialEmptyDocument()) { GetFrameLoader().StateMachine()->AdvanceTo( FrameLoaderStateMachine::kCommittedFirstRealLoad); } const SecurityOrigin* previous_security_origin = nullptr; const ContentSecurityPolicy* previous_csp = nullptr; if (frame_->GetDocument()) { previous_security_origin = frame_->GetDocument()->GetSecurityOrigin(); previous_csp = frame_->GetDocument()->GetContentSecurityPolicy(); } if (global_object_reuse_policy != WebGlobalObjectReusePolicy::kUseExisting) frame_->SetDOMWindow(LocalDOMWindow::Create(*frame_)); if (reason == InstallNewDocumentReason::kNavigation) WillCommitNavigation(); Document* document = frame_->DomWindow()->InstallNewDocument( mime_type, DocumentInit::Create() .WithDocumentLoader(this) .WithURL(url) .WithOwnerDocument(owner_document) .WithNewRegistrationContext() .WithPreviousDocumentCSP(previous_csp), false); if (frame_->IsMainFrame()) frame_->ClearActivation(); if (frame_->HasReceivedUserGestureBeforeNavigation() != had_sticky_activation_) { frame_->SetDocumentHasReceivedUserGestureBeforeNavigation( had_sticky_activation_); GetLocalFrameClient().SetHasReceivedUserGestureBeforeNavigation( had_sticky_activation_); } if (ShouldClearWindowName(*frame_, previous_security_origin, *document)) { frame_->Tree().ExperimentalSetNulledName(); } if (!overriding_url.IsEmpty()) document->SetBaseURLOverride(overriding_url); DidInstallNewDocument(document, previous_csp); if (reason == InstallNewDocumentReason::kNavigation) DidCommitNavigation(global_object_reuse_policy); if (GetFrameLoader().StateMachine()->CommittedFirstRealDocumentLoad()) { if (document->GetSettings() ->GetForceTouchEventFeatureDetectionForInspector()) { OriginTrialContext::FromOrCreate(document)->AddFeature( "ForceTouchEventFeatureDetectionForInspector"); } OriginTrialContext::AddTokensFromHeader( document, response_.HttpHeaderField(http_names::kOriginTrial)); } bool stale_while_revalidate_enabled = origin_trials::StaleWhileRevalidateEnabled(document); fetcher_->SetStaleWhileRevalidateEnabled(stale_while_revalidate_enabled); if (stale_while_revalidate_enabled && !RuntimeEnabledFeatures::StaleWhileRevalidateEnabledByRuntimeFlag()) UseCounter::Count(frame_, WebFeature::kStaleWhileRevalidateEnabled); parser_ = document->OpenForNavigation(parsing_policy, mime_type, encoding); ScriptableDocumentParser* scriptable_parser = parser_->AsScriptableDocumentParser(); if (scriptable_parser && GetResource()) { scriptable_parser->SetInlineScriptCacheHandler( ToRawResource(GetResource())->InlineScriptCacheHandler()); } WTF::String feature_policy( response_.HttpHeaderField(http_names::kFeaturePolicy)); MergeFeaturesFromOriginPolicy(feature_policy, request_.GetOriginPolicy()); document->ApplyFeaturePolicyFromHeader(feature_policy); GetFrameLoader().DispatchDidClearDocumentOfWindowObject(); } Commit Message: Inherit the navigation initiator when navigating instead of the parent/opener Spec PR: https://github.com/w3c/webappsec-csp/pull/358 Bug: 905301, 894228, 836148 Change-Id: I43ada2266d42d1cd56dbe3c6dd89d115e878a83a Reviewed-on: https://chromium-review.googlesource.com/c/1314633 Commit-Queue: Andy Paicu <[email protected]> Reviewed-by: Mike West <[email protected]> Cr-Commit-Position: refs/heads/master@{#610850} CWE ID: CWE-20
void DocumentLoader::InstallNewDocument( const KURL& url, Document* owner_document, WebGlobalObjectReusePolicy global_object_reuse_policy, const AtomicString& mime_type, const AtomicString& encoding, InstallNewDocumentReason reason, ParserSynchronizationPolicy parsing_policy, const KURL& overriding_url) { DCHECK(!frame_->GetDocument() || !frame_->GetDocument()->IsActive()); DCHECK_EQ(frame_->Tree().ChildCount(), 0u); if (GetFrameLoader().StateMachine()->IsDisplayingInitialEmptyDocument()) { GetFrameLoader().StateMachine()->AdvanceTo( FrameLoaderStateMachine::kCommittedFirstRealLoad); } const SecurityOrigin* previous_security_origin = nullptr; if (frame_->GetDocument()) { previous_security_origin = frame_->GetDocument()->GetSecurityOrigin(); } if (global_object_reuse_policy != WebGlobalObjectReusePolicy::kUseExisting) frame_->SetDOMWindow(LocalDOMWindow::Create(*frame_)); if (reason == InstallNewDocumentReason::kNavigation) WillCommitNavigation(); Document* document = frame_->DomWindow()->InstallNewDocument( mime_type, DocumentInit::Create() .WithDocumentLoader(this) .WithURL(url) .WithOwnerDocument(owner_document) .WithNewRegistrationContext(), false); if (frame_->IsMainFrame()) frame_->ClearActivation(); if (frame_->HasReceivedUserGestureBeforeNavigation() != had_sticky_activation_) { frame_->SetDocumentHasReceivedUserGestureBeforeNavigation( had_sticky_activation_); GetLocalFrameClient().SetHasReceivedUserGestureBeforeNavigation( had_sticky_activation_); } if (ShouldClearWindowName(*frame_, previous_security_origin, *document)) { frame_->Tree().ExperimentalSetNulledName(); } if (!overriding_url.IsEmpty()) document->SetBaseURLOverride(overriding_url); DidInstallNewDocument(document); if (reason == InstallNewDocumentReason::kNavigation) DidCommitNavigation(global_object_reuse_policy); if (GetFrameLoader().StateMachine()->CommittedFirstRealDocumentLoad()) { if (document->GetSettings() ->GetForceTouchEventFeatureDetectionForInspector()) { OriginTrialContext::FromOrCreate(document)->AddFeature( "ForceTouchEventFeatureDetectionForInspector"); } OriginTrialContext::AddTokensFromHeader( document, response_.HttpHeaderField(http_names::kOriginTrial)); } bool stale_while_revalidate_enabled = origin_trials::StaleWhileRevalidateEnabled(document); fetcher_->SetStaleWhileRevalidateEnabled(stale_while_revalidate_enabled); if (stale_while_revalidate_enabled && !RuntimeEnabledFeatures::StaleWhileRevalidateEnabledByRuntimeFlag()) UseCounter::Count(frame_, WebFeature::kStaleWhileRevalidateEnabled); parser_ = document->OpenForNavigation(parsing_policy, mime_type, encoding); ScriptableDocumentParser* scriptable_parser = parser_->AsScriptableDocumentParser(); if (scriptable_parser && GetResource()) { scriptable_parser->SetInlineScriptCacheHandler( ToRawResource(GetResource())->InlineScriptCacheHandler()); } WTF::String feature_policy( response_.HttpHeaderField(http_names::kFeaturePolicy)); MergeFeaturesFromOriginPolicy(feature_policy, request_.GetOriginPolicy()); document->ApplyFeaturePolicyFromHeader(feature_policy); GetFrameLoader().DispatchDidClearDocumentOfWindowObject(); }
173,057
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static bool decode_openldap_dereference(void *mem_ctx, DATA_BLOB in, void *_out) { void **out = (void **)_out; struct asn1_data *data = asn1_init(mem_ctx); struct dsdb_openldap_dereference_result_control *control; struct dsdb_openldap_dereference_result **r = NULL; int i = 0; if (!data) return false; control = talloc(mem_ctx, struct dsdb_openldap_dereference_result_control); if (!control) return false; if (!asn1_load(data, in)) { return false; } control = talloc(mem_ctx, struct dsdb_openldap_dereference_result_control); if (!control) { return false; } if (!asn1_start_tag(data, ASN1_SEQUENCE(0))) { return false; } while (asn1_tag_remaining(data) > 0) { r = talloc_realloc(control, r, struct dsdb_openldap_dereference_result *, i + 2); if (!r) { return false; } r[i] = talloc_zero(r, struct dsdb_openldap_dereference_result); if (!r[i]) { return false; } if (!asn1_start_tag(data, ASN1_SEQUENCE(0))) { return false; } asn1_read_OctetString_talloc(r[i], data, &r[i]->source_attribute); asn1_read_OctetString_talloc(r[i], data, &r[i]->dereferenced_dn); if (asn1_peek_tag(data, ASN1_CONTEXT(0))) { if (!asn1_start_tag(data, ASN1_CONTEXT(0))) { return false; } ldap_decode_attribs_bare(r, data, &r[i]->attributes, &r[i]->num_attributes); if (!asn1_end_tag(data)) { return false; } } if (!asn1_end_tag(data)) { return false; } i++; r[i] = NULL; } if (!asn1_end_tag(data)) { return false; } control->attributes = r; *out = control; return true; } Commit Message: CWE ID: CWE-399
static bool decode_openldap_dereference(void *mem_ctx, DATA_BLOB in, void *_out) { void **out = (void **)_out; struct asn1_data *data = asn1_init(mem_ctx); struct dsdb_openldap_dereference_result_control *control; struct dsdb_openldap_dereference_result **r = NULL; int i = 0; if (!data) return false; control = talloc(mem_ctx, struct dsdb_openldap_dereference_result_control); if (!control) return false; if (!asn1_load(data, in)) { return false; } control = talloc(mem_ctx, struct dsdb_openldap_dereference_result_control); if (!control) { return false; } if (!asn1_start_tag(data, ASN1_SEQUENCE(0))) { return false; } while (asn1_tag_remaining(data) > 0) { r = talloc_realloc(control, r, struct dsdb_openldap_dereference_result *, i + 2); if (!r) { return false; } r[i] = talloc_zero(r, struct dsdb_openldap_dereference_result); if (!r[i]) { return false; } if (!asn1_start_tag(data, ASN1_SEQUENCE(0))) { return false; } asn1_read_OctetString_talloc(r[i], data, &r[i]->source_attribute); asn1_read_OctetString_talloc(r[i], data, &r[i]->dereferenced_dn); if (asn1_peek_tag(data, ASN1_CONTEXT(0))) { if (!asn1_start_tag(data, ASN1_CONTEXT(0))) { return false; } if (!ldap_decode_attribs_bare(r, data, &r[i]->attributes, &r[i]->num_attributes)) { return false; } if (!asn1_end_tag(data)) { return false; } } if (!asn1_end_tag(data)) { return false; } i++; r[i] = NULL; } if (!asn1_end_tag(data)) { return false; } control->attributes = r; *out = control; return true; }
164,595
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: read_packet(int fd, gss_buffer_t buf, int timeout, int first) { int ret; static uint32_t len = 0; static char len_buf[4]; static int len_buf_pos = 0; static char * tmpbuf = 0; static int tmpbuf_pos = 0; if (first) { len_buf_pos = 0; return -2; } if (len_buf_pos < 4) { ret = timed_read(fd, &len_buf[len_buf_pos], 4 - len_buf_pos, timeout); if (ret == -1) { if (errno == EINTR || errno == EAGAIN) return -2; LOG(LOG_ERR, ("%s", strerror(errno))); return -1; } if (ret == 0) { /* EOF */ /* Failure to read ANY length just means we're done */ if (len_buf_pos == 0) return 0; /* * Otherwise, we got EOF mid-length, and that's * a protocol error. */ LOG(LOG_INFO, ("EOF reading packet len")); return -1; } len_buf_pos += ret; } /* Not done reading the length? */ if (len_buf_pos != 4) return -2; /* We have the complete length */ len = ntohl(*(uint32_t *)len_buf); /* * We make sure recvd length is reasonable, allowing for some * slop in enc overhead, beyond the actual maximum number of * bytes of decrypted payload. */ if (len > GSTD_MAXPACKETCONTENTS + 512) { LOG(LOG_ERR, ("ridiculous length, %ld", len)); return -1; } if (!tmpbuf) { if ((tmpbuf = malloc(len)) == NULL) { LOG(LOG_CRIT, ("malloc failure, %ld bytes", len)); return -1; } } ret = timed_read(fd, tmpbuf + tmpbuf_pos, len - tmpbuf_pos, timeout); if (ret == -1) { if (errno == EINTR || errno == EAGAIN) return -2; LOG(LOG_ERR, ("%s", strerror(errno))); return -1; } if (ret == 0) { LOG(LOG_ERR, ("EOF while reading packet (len=%d)", len)); return -1; } tmpbuf_pos += ret; if (tmpbuf_pos == len) { buf->length = len; buf->value = tmpbuf; len = len_buf_pos = tmpbuf_pos = 0; tmpbuf = NULL; LOG(LOG_DEBUG, ("read packet of length %d", buf->length)); return 1; } return -2; } Commit Message: knc: fix a couple of memory leaks. One of these can be remotely triggered during the authentication phase which leads to a remote DoS possibility. Pointed out by: Imre Rad <[email protected]> CWE ID: CWE-400
read_packet(int fd, gss_buffer_t buf, int timeout, int first) { int ret; static uint32_t len = 0; static char len_buf[4]; static int len_buf_pos = 0; static char * tmpbuf = 0; static int tmpbuf_pos = 0; if (first) { len_buf_pos = 0; return -2; } if (len_buf_pos < 4) { ret = timed_read(fd, &len_buf[len_buf_pos], 4 - len_buf_pos, timeout); if (ret == -1) { if (errno == EINTR || errno == EAGAIN) return -2; LOG(LOG_ERR, ("%s", strerror(errno))); goto bail; } if (ret == 0) { /* EOF */ /* Failure to read ANY length just means we're done */ if (len_buf_pos == 0) return 0; /* * Otherwise, we got EOF mid-length, and that's * a protocol error. */ LOG(LOG_INFO, ("EOF reading packet len")); goto bail; } len_buf_pos += ret; } /* Not done reading the length? */ if (len_buf_pos != 4) return -2; /* We have the complete length */ len = ntohl(*(uint32_t *)len_buf); /* * We make sure recvd length is reasonable, allowing for some * slop in enc overhead, beyond the actual maximum number of * bytes of decrypted payload. */ if (len > GSTD_MAXPACKETCONTENTS + 512) { LOG(LOG_ERR, ("ridiculous length, %ld", len)); goto bail; } if (!tmpbuf) { if ((tmpbuf = malloc(len)) == NULL) { LOG(LOG_CRIT, ("malloc failure, %ld bytes", len)); goto bail; } } ret = timed_read(fd, tmpbuf + tmpbuf_pos, len - tmpbuf_pos, timeout); if (ret == -1) { if (errno == EINTR || errno == EAGAIN) return -2; LOG(LOG_ERR, ("%s", strerror(errno))); goto bail; } if (ret == 0) { LOG(LOG_ERR, ("EOF while reading packet (len=%d)", len)); goto bail; } tmpbuf_pos += ret; if (tmpbuf_pos == len) { buf->length = len; buf->value = tmpbuf; len = len_buf_pos = tmpbuf_pos = 0; tmpbuf = NULL; LOG(LOG_DEBUG, ("read packet of length %d", buf->length)); return 1; } return -2; bail: free(tmpbuf); tmpbuf = NULL; return -1; }
169,433
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int ax25_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t size, int flags) { struct sock *sk = sock->sk; struct sk_buff *skb; int copied; int err = 0; lock_sock(sk); /* * This works for seqpacket too. The receiver has ordered the * queue for us! We do one quick check first though */ if (sk->sk_type == SOCK_SEQPACKET && sk->sk_state != TCP_ESTABLISHED) { err = -ENOTCONN; goto out; } /* Now we can treat all alike */ skb = skb_recv_datagram(sk, flags & ~MSG_DONTWAIT, flags & MSG_DONTWAIT, &err); if (skb == NULL) goto out; if (!ax25_sk(sk)->pidincl) skb_pull(skb, 1); /* Remove PID */ skb_reset_transport_header(skb); copied = skb->len; if (copied > size) { copied = size; msg->msg_flags |= MSG_TRUNC; } skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied); if (msg->msg_namelen != 0) { struct sockaddr_ax25 *sax = (struct sockaddr_ax25 *)msg->msg_name; ax25_digi digi; ax25_address src; const unsigned char *mac = skb_mac_header(skb); ax25_addr_parse(mac + 1, skb->data - mac - 1, &src, NULL, &digi, NULL, NULL); sax->sax25_family = AF_AX25; /* We set this correctly, even though we may not let the application know the digi calls further down (because it did NOT ask to know them). This could get political... **/ sax->sax25_ndigis = digi.ndigi; sax->sax25_call = src; if (sax->sax25_ndigis != 0) { int ct; struct full_sockaddr_ax25 *fsa = (struct full_sockaddr_ax25 *)sax; for (ct = 0; ct < digi.ndigi; ct++) fsa->fsa_digipeater[ct] = digi.calls[ct]; } msg->msg_namelen = sizeof(struct full_sockaddr_ax25); } skb_free_datagram(sk, skb); err = copied; out: release_sock(sk); return err; } Commit Message: ax25: fix info leak via msg_name in ax25_recvmsg() When msg_namelen is non-zero the sockaddr info gets filled out, as requested, but the code fails to initialize the padding bytes of struct sockaddr_ax25 inserted by the compiler for alignment. Additionally the msg_namelen value is updated to sizeof(struct full_sockaddr_ax25) but is not always filled up to this size. Both issues lead to the fact that the code will leak uninitialized kernel stack bytes in net/socket.c. Fix both issues by initializing the memory with memset(0). Cc: Ralf Baechle <[email protected]> Signed-off-by: Mathias Krause <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-200
static int ax25_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t size, int flags) { struct sock *sk = sock->sk; struct sk_buff *skb; int copied; int err = 0; lock_sock(sk); /* * This works for seqpacket too. The receiver has ordered the * queue for us! We do one quick check first though */ if (sk->sk_type == SOCK_SEQPACKET && sk->sk_state != TCP_ESTABLISHED) { err = -ENOTCONN; goto out; } /* Now we can treat all alike */ skb = skb_recv_datagram(sk, flags & ~MSG_DONTWAIT, flags & MSG_DONTWAIT, &err); if (skb == NULL) goto out; if (!ax25_sk(sk)->pidincl) skb_pull(skb, 1); /* Remove PID */ skb_reset_transport_header(skb); copied = skb->len; if (copied > size) { copied = size; msg->msg_flags |= MSG_TRUNC; } skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied); if (msg->msg_namelen != 0) { struct sockaddr_ax25 *sax = (struct sockaddr_ax25 *)msg->msg_name; ax25_digi digi; ax25_address src; const unsigned char *mac = skb_mac_header(skb); memset(sax, 0, sizeof(struct full_sockaddr_ax25)); ax25_addr_parse(mac + 1, skb->data - mac - 1, &src, NULL, &digi, NULL, NULL); sax->sax25_family = AF_AX25; /* We set this correctly, even though we may not let the application know the digi calls further down (because it did NOT ask to know them). This could get political... **/ sax->sax25_ndigis = digi.ndigi; sax->sax25_call = src; if (sax->sax25_ndigis != 0) { int ct; struct full_sockaddr_ax25 *fsa = (struct full_sockaddr_ax25 *)sax; for (ct = 0; ct < digi.ndigi; ct++) fsa->fsa_digipeater[ct] = digi.calls[ct]; } msg->msg_namelen = sizeof(struct full_sockaddr_ax25); } skb_free_datagram(sk, skb); err = copied; out: release_sock(sk); return err; }
166,044
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void AutoFillManager::LogMetricsAboutSubmittedForm( const FormData& form, const FormStructure* submitted_form) { FormStructure* cached_submitted_form; if (!FindCachedForm(form, &cached_submitted_form)) { NOTREACHED(); return; } std::map<std::string, const AutoFillField*> cached_fields; for (size_t i = 0; i < cached_submitted_form->field_count(); ++i) { const AutoFillField* field = cached_submitted_form->field(i); cached_fields[field->FieldSignature()] = field; } for (size_t i = 0; i < submitted_form->field_count(); ++i) { const AutoFillField* field = submitted_form->field(i); FieldTypeSet field_types; personal_data_->GetPossibleFieldTypes(field->value(), &field_types); DCHECK(!field_types.empty()); if (field->form_control_type() == ASCIIToUTF16("select-one")) { continue; } metric_logger_->Log(AutoFillMetrics::FIELD_SUBMITTED); if (field_types.find(EMPTY_TYPE) == field_types.end() && field_types.find(UNKNOWN_TYPE) == field_types.end()) { if (field->is_autofilled()) { metric_logger_->Log(AutoFillMetrics::FIELD_AUTOFILLED); } else { metric_logger_->Log(AutoFillMetrics::FIELD_AUTOFILL_FAILED); AutoFillFieldType heuristic_type = UNKNOWN_TYPE; AutoFillFieldType server_type = NO_SERVER_DATA; std::map<std::string, const AutoFillField*>::const_iterator cached_field = cached_fields.find(field->FieldSignature()); if (cached_field != cached_fields.end()) { heuristic_type = cached_field->second->heuristic_type(); server_type = cached_field->second->server_type(); } if (heuristic_type == UNKNOWN_TYPE) metric_logger_->Log(AutoFillMetrics::FIELD_HEURISTIC_TYPE_UNKNOWN); else if (field_types.count(heuristic_type)) metric_logger_->Log(AutoFillMetrics::FIELD_HEURISTIC_TYPE_MATCH); else metric_logger_->Log(AutoFillMetrics::FIELD_HEURISTIC_TYPE_MISMATCH); if (server_type == NO_SERVER_DATA) metric_logger_->Log(AutoFillMetrics::FIELD_SERVER_TYPE_UNKNOWN); else if (field_types.count(server_type)) metric_logger_->Log(AutoFillMetrics::FIELD_SERVER_TYPE_MATCH); else metric_logger_->Log(AutoFillMetrics::FIELD_SERVER_TYPE_MISMATCH); } } } } Commit Message: Add support for autofill server experiments BUG=none TEST=unit_tests --gtest_filter=AutoFillMetricsTest.QualityMetricsWithExperimentId:AutoFillQueryXmlParserTest.ParseExperimentId Review URL: http://codereview.chromium.org/6260027 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@73216 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void AutoFillManager::LogMetricsAboutSubmittedForm( const FormData& form, const FormStructure* submitted_form) { FormStructure* cached_submitted_form; if (!FindCachedForm(form, &cached_submitted_form)) { NOTREACHED(); return; } std::map<std::string, const AutoFillField*> cached_fields; for (size_t i = 0; i < cached_submitted_form->field_count(); ++i) { const AutoFillField* field = cached_submitted_form->field(i); cached_fields[field->FieldSignature()] = field; } std::string experiment_id = cached_submitted_form->server_experiment_id(); for (size_t i = 0; i < submitted_form->field_count(); ++i) { const AutoFillField* field = submitted_form->field(i); FieldTypeSet field_types; personal_data_->GetPossibleFieldTypes(field->value(), &field_types); DCHECK(!field_types.empty()); if (field->form_control_type() == ASCIIToUTF16("select-one")) { continue; } metric_logger_->Log(AutoFillMetrics::FIELD_SUBMITTED, experiment_id); if (field_types.find(EMPTY_TYPE) == field_types.end() && field_types.find(UNKNOWN_TYPE) == field_types.end()) { if (field->is_autofilled()) { metric_logger_->Log(AutoFillMetrics::FIELD_AUTOFILLED, experiment_id); } else { metric_logger_->Log(AutoFillMetrics::FIELD_AUTOFILL_FAILED, experiment_id); AutoFillFieldType heuristic_type = UNKNOWN_TYPE; AutoFillFieldType server_type = NO_SERVER_DATA; std::map<std::string, const AutoFillField*>::const_iterator cached_field = cached_fields.find(field->FieldSignature()); if (cached_field != cached_fields.end()) { heuristic_type = cached_field->second->heuristic_type(); server_type = cached_field->second->server_type(); } if (heuristic_type == UNKNOWN_TYPE) { metric_logger_->Log(AutoFillMetrics::FIELD_HEURISTIC_TYPE_UNKNOWN, experiment_id); } else if (field_types.count(heuristic_type)) { metric_logger_->Log(AutoFillMetrics::FIELD_HEURISTIC_TYPE_MATCH, experiment_id); } else { metric_logger_->Log(AutoFillMetrics::FIELD_HEURISTIC_TYPE_MISMATCH, experiment_id); } if (server_type == NO_SERVER_DATA) { metric_logger_->Log(AutoFillMetrics::FIELD_SERVER_TYPE_UNKNOWN, experiment_id); } else if (field_types.count(server_type)) { metric_logger_->Log(AutoFillMetrics::FIELD_SERVER_TYPE_MATCH, experiment_id); } else { metric_logger_->Log(AutoFillMetrics::FIELD_SERVER_TYPE_MISMATCH, experiment_id); } } } } }
170,651
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: OMX_ERRORTYPE SoftAAC2::internalGetParameter( OMX_INDEXTYPE index, OMX_PTR params) { switch (index) { case OMX_IndexParamAudioAac: { OMX_AUDIO_PARAM_AACPROFILETYPE *aacParams = (OMX_AUDIO_PARAM_AACPROFILETYPE *)params; if (aacParams->nPortIndex != 0) { return OMX_ErrorUndefined; } aacParams->nBitRate = 0; aacParams->nAudioBandWidth = 0; aacParams->nAACtools = 0; aacParams->nAACERtools = 0; aacParams->eAACProfile = OMX_AUDIO_AACObjectMain; aacParams->eAACStreamFormat = mIsADTS ? OMX_AUDIO_AACStreamFormatMP4ADTS : OMX_AUDIO_AACStreamFormatMP4FF; aacParams->eChannelMode = OMX_AUDIO_ChannelModeStereo; if (!isConfigured()) { aacParams->nChannels = 1; aacParams->nSampleRate = 44100; aacParams->nFrameLength = 0; } else { aacParams->nChannels = mStreamInfo->numChannels; aacParams->nSampleRate = mStreamInfo->sampleRate; aacParams->nFrameLength = mStreamInfo->frameSize; } return OMX_ErrorNone; } case OMX_IndexParamAudioPcm: { OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams = (OMX_AUDIO_PARAM_PCMMODETYPE *)params; if (pcmParams->nPortIndex != 1) { return OMX_ErrorUndefined; } pcmParams->eNumData = OMX_NumericalDataSigned; pcmParams->eEndian = OMX_EndianBig; pcmParams->bInterleaved = OMX_TRUE; pcmParams->nBitPerSample = 16; pcmParams->ePCMMode = OMX_AUDIO_PCMModeLinear; pcmParams->eChannelMapping[0] = OMX_AUDIO_ChannelLF; pcmParams->eChannelMapping[1] = OMX_AUDIO_ChannelRF; pcmParams->eChannelMapping[2] = OMX_AUDIO_ChannelCF; pcmParams->eChannelMapping[3] = OMX_AUDIO_ChannelLFE; pcmParams->eChannelMapping[4] = OMX_AUDIO_ChannelLS; pcmParams->eChannelMapping[5] = OMX_AUDIO_ChannelRS; if (!isConfigured()) { pcmParams->nChannels = 1; pcmParams->nSamplingRate = 44100; } else { pcmParams->nChannels = mStreamInfo->numChannels; pcmParams->nSamplingRate = mStreamInfo->sampleRate; } return OMX_ErrorNone; } default: return SimpleSoftOMXComponent::internalGetParameter(index, params); } } Commit Message: DO NOT MERGE Verify OMX buffer sizes prior to access Bug: 27207275 Change-Id: I4412825d1ee233d993af0a67708bea54304ff62d CWE ID: CWE-119
OMX_ERRORTYPE SoftAAC2::internalGetParameter( OMX_INDEXTYPE index, OMX_PTR params) { switch (index) { case OMX_IndexParamAudioAac: { OMX_AUDIO_PARAM_AACPROFILETYPE *aacParams = (OMX_AUDIO_PARAM_AACPROFILETYPE *)params; if (!isValidOMXParam(aacParams)) { return OMX_ErrorBadParameter; } if (aacParams->nPortIndex != 0) { return OMX_ErrorUndefined; } aacParams->nBitRate = 0; aacParams->nAudioBandWidth = 0; aacParams->nAACtools = 0; aacParams->nAACERtools = 0; aacParams->eAACProfile = OMX_AUDIO_AACObjectMain; aacParams->eAACStreamFormat = mIsADTS ? OMX_AUDIO_AACStreamFormatMP4ADTS : OMX_AUDIO_AACStreamFormatMP4FF; aacParams->eChannelMode = OMX_AUDIO_ChannelModeStereo; if (!isConfigured()) { aacParams->nChannels = 1; aacParams->nSampleRate = 44100; aacParams->nFrameLength = 0; } else { aacParams->nChannels = mStreamInfo->numChannels; aacParams->nSampleRate = mStreamInfo->sampleRate; aacParams->nFrameLength = mStreamInfo->frameSize; } return OMX_ErrorNone; } case OMX_IndexParamAudioPcm: { OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams = (OMX_AUDIO_PARAM_PCMMODETYPE *)params; if (!isValidOMXParam(pcmParams)) { return OMX_ErrorBadParameter; } if (pcmParams->nPortIndex != 1) { return OMX_ErrorUndefined; } pcmParams->eNumData = OMX_NumericalDataSigned; pcmParams->eEndian = OMX_EndianBig; pcmParams->bInterleaved = OMX_TRUE; pcmParams->nBitPerSample = 16; pcmParams->ePCMMode = OMX_AUDIO_PCMModeLinear; pcmParams->eChannelMapping[0] = OMX_AUDIO_ChannelLF; pcmParams->eChannelMapping[1] = OMX_AUDIO_ChannelRF; pcmParams->eChannelMapping[2] = OMX_AUDIO_ChannelCF; pcmParams->eChannelMapping[3] = OMX_AUDIO_ChannelLFE; pcmParams->eChannelMapping[4] = OMX_AUDIO_ChannelLS; pcmParams->eChannelMapping[5] = OMX_AUDIO_ChannelRS; if (!isConfigured()) { pcmParams->nChannels = 1; pcmParams->nSamplingRate = 44100; } else { pcmParams->nChannels = mStreamInfo->numChannels; pcmParams->nSamplingRate = mStreamInfo->sampleRate; } return OMX_ErrorNone; } default: return SimpleSoftOMXComponent::internalGetParameter(index, params); } }
174,186
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int decode_frame(AVCodecContext *avctx, void *data, int *got_frame, AVPacket *avpkt) { PicContext *s = avctx->priv_data; AVFrame *frame = data; uint32_t *palette; int bits_per_plane, bpp, etype, esize, npal, pos_after_pal; int i, x, y, plane, tmp, ret, val; bytestream2_init(&s->g, avpkt->data, avpkt->size); if (bytestream2_get_bytes_left(&s->g) < 11) return AVERROR_INVALIDDATA; if (bytestream2_get_le16u(&s->g) != 0x1234) return AVERROR_INVALIDDATA; s->width = bytestream2_get_le16u(&s->g); s->height = bytestream2_get_le16u(&s->g); bytestream2_skip(&s->g, 4); tmp = bytestream2_get_byteu(&s->g); bits_per_plane = tmp & 0xF; s->nb_planes = (tmp >> 4) + 1; bpp = bits_per_plane * s->nb_planes; if (bits_per_plane > 8 || bpp < 1 || bpp > 32) { avpriv_request_sample(avctx, "Unsupported bit depth"); return AVERROR_PATCHWELCOME; } if (bytestream2_peek_byte(&s->g) == 0xFF || bpp == 1 || bpp == 4 || bpp == 8) { bytestream2_skip(&s->g, 2); etype = bytestream2_get_le16(&s->g); esize = bytestream2_get_le16(&s->g); if (bytestream2_get_bytes_left(&s->g) < esize) return AVERROR_INVALIDDATA; } else { etype = -1; esize = 0; } avctx->pix_fmt = AV_PIX_FMT_PAL8; if (av_image_check_size(s->width, s->height, 0, avctx) < 0) return -1; if (s->width != avctx->width && s->height != avctx->height) { ret = ff_set_dimensions(avctx, s->width, s->height); if (ret < 0) return ret; } if ((ret = ff_get_buffer(avctx, frame, 0)) < 0) return ret; memset(frame->data[0], 0, s->height * frame->linesize[0]); frame->pict_type = AV_PICTURE_TYPE_I; frame->palette_has_changed = 1; pos_after_pal = bytestream2_tell(&s->g) + esize; palette = (uint32_t*)frame->data[1]; if (etype == 1 && esize > 1 && bytestream2_peek_byte(&s->g) < 6) { int idx = bytestream2_get_byte(&s->g); npal = 4; for (i = 0; i < npal; i++) palette[i] = ff_cga_palette[ cga_mode45_index[idx][i] ]; } else if (etype == 2) { npal = FFMIN(esize, 16); for (i = 0; i < npal; i++) { int pal_idx = bytestream2_get_byte(&s->g); palette[i] = ff_cga_palette[FFMIN(pal_idx, 15)]; } } else if (etype == 3) { npal = FFMIN(esize, 16); for (i = 0; i < npal; i++) { int pal_idx = bytestream2_get_byte(&s->g); palette[i] = ff_ega_palette[FFMIN(pal_idx, 63)]; } } else if (etype == 4 || etype == 5) { npal = FFMIN(esize / 3, 256); for (i = 0; i < npal; i++) { palette[i] = bytestream2_get_be24(&s->g) << 2; palette[i] |= 0xFFU << 24 | palette[i] >> 6 & 0x30303; } } else { if (bpp == 1) { npal = 2; palette[0] = 0xFF000000; palette[1] = 0xFFFFFFFF; } else if (bpp == 2) { npal = 4; for (i = 0; i < npal; i++) palette[i] = ff_cga_palette[ cga_mode45_index[0][i] ]; } else { npal = 16; memcpy(palette, ff_cga_palette, npal * 4); } } memset(palette + npal, 0, AVPALETTE_SIZE - npal * 4); bytestream2_seek(&s->g, pos_after_pal, SEEK_SET); val = 0; y = s->height - 1; if (bytestream2_get_le16(&s->g)) { x = 0; plane = 0; while (bytestream2_get_bytes_left(&s->g) >= 6) { int stop_size, marker, t1, t2; t1 = bytestream2_get_bytes_left(&s->g); t2 = bytestream2_get_le16(&s->g); stop_size = t1 - FFMIN(t1, t2); bytestream2_skip(&s->g, 2); marker = bytestream2_get_byte(&s->g); while (plane < s->nb_planes && bytestream2_get_bytes_left(&s->g) > stop_size) { int run = 1; val = bytestream2_get_byte(&s->g); if (val == marker) { run = bytestream2_get_byte(&s->g); if (run == 0) run = bytestream2_get_le16(&s->g); val = bytestream2_get_byte(&s->g); } if (!bytestream2_get_bytes_left(&s->g)) break; if (bits_per_plane == 8) { picmemset_8bpp(s, frame, val, run, &x, &y); if (y < 0) goto finish; } else { picmemset(s, frame, val, run, &x, &y, &plane, bits_per_plane); } } } if (x < avctx->width) { int run = (y + 1) * avctx->width - x; if (bits_per_plane == 8) picmemset_8bpp(s, frame, val, run, &x, &y); else picmemset(s, frame, val, run / (8 / bits_per_plane), &x, &y, &plane, bits_per_plane); } } else { while (y >= 0 && bytestream2_get_bytes_left(&s->g) > 0) { memcpy(frame->data[0] + y * frame->linesize[0], s->g.buffer, FFMIN(avctx->width, bytestream2_get_bytes_left(&s->g))); bytestream2_skip(&s->g, avctx->width); y--; } } finish: *got_frame = 1; return avpkt->size; } Commit Message: avcodec/pictordec: Fix logic error Fixes: 559/clusterfuzz-testcase-6424225917173760 Found-by: continuous fuzzing process https://github.com/google/oss-fuzz/tree/master/targets/ffmpeg Signed-off-by: Michael Niedermayer <[email protected]> CWE ID: CWE-787
static int decode_frame(AVCodecContext *avctx, void *data, int *got_frame, AVPacket *avpkt) { PicContext *s = avctx->priv_data; AVFrame *frame = data; uint32_t *palette; int bits_per_plane, bpp, etype, esize, npal, pos_after_pal; int i, x, y, plane, tmp, ret, val; bytestream2_init(&s->g, avpkt->data, avpkt->size); if (bytestream2_get_bytes_left(&s->g) < 11) return AVERROR_INVALIDDATA; if (bytestream2_get_le16u(&s->g) != 0x1234) return AVERROR_INVALIDDATA; s->width = bytestream2_get_le16u(&s->g); s->height = bytestream2_get_le16u(&s->g); bytestream2_skip(&s->g, 4); tmp = bytestream2_get_byteu(&s->g); bits_per_plane = tmp & 0xF; s->nb_planes = (tmp >> 4) + 1; bpp = bits_per_plane * s->nb_planes; if (bits_per_plane > 8 || bpp < 1 || bpp > 32) { avpriv_request_sample(avctx, "Unsupported bit depth"); return AVERROR_PATCHWELCOME; } if (bytestream2_peek_byte(&s->g) == 0xFF || bpp == 1 || bpp == 4 || bpp == 8) { bytestream2_skip(&s->g, 2); etype = bytestream2_get_le16(&s->g); esize = bytestream2_get_le16(&s->g); if (bytestream2_get_bytes_left(&s->g) < esize) return AVERROR_INVALIDDATA; } else { etype = -1; esize = 0; } avctx->pix_fmt = AV_PIX_FMT_PAL8; if (av_image_check_size(s->width, s->height, 0, avctx) < 0) return -1; if (s->width != avctx->width || s->height != avctx->height) { ret = ff_set_dimensions(avctx, s->width, s->height); if (ret < 0) return ret; } if ((ret = ff_get_buffer(avctx, frame, 0)) < 0) return ret; memset(frame->data[0], 0, s->height * frame->linesize[0]); frame->pict_type = AV_PICTURE_TYPE_I; frame->palette_has_changed = 1; pos_after_pal = bytestream2_tell(&s->g) + esize; palette = (uint32_t*)frame->data[1]; if (etype == 1 && esize > 1 && bytestream2_peek_byte(&s->g) < 6) { int idx = bytestream2_get_byte(&s->g); npal = 4; for (i = 0; i < npal; i++) palette[i] = ff_cga_palette[ cga_mode45_index[idx][i] ]; } else if (etype == 2) { npal = FFMIN(esize, 16); for (i = 0; i < npal; i++) { int pal_idx = bytestream2_get_byte(&s->g); palette[i] = ff_cga_palette[FFMIN(pal_idx, 15)]; } } else if (etype == 3) { npal = FFMIN(esize, 16); for (i = 0; i < npal; i++) { int pal_idx = bytestream2_get_byte(&s->g); palette[i] = ff_ega_palette[FFMIN(pal_idx, 63)]; } } else if (etype == 4 || etype == 5) { npal = FFMIN(esize / 3, 256); for (i = 0; i < npal; i++) { palette[i] = bytestream2_get_be24(&s->g) << 2; palette[i] |= 0xFFU << 24 | palette[i] >> 6 & 0x30303; } } else { if (bpp == 1) { npal = 2; palette[0] = 0xFF000000; palette[1] = 0xFFFFFFFF; } else if (bpp == 2) { npal = 4; for (i = 0; i < npal; i++) palette[i] = ff_cga_palette[ cga_mode45_index[0][i] ]; } else { npal = 16; memcpy(palette, ff_cga_palette, npal * 4); } } memset(palette + npal, 0, AVPALETTE_SIZE - npal * 4); bytestream2_seek(&s->g, pos_after_pal, SEEK_SET); val = 0; y = s->height - 1; if (bytestream2_get_le16(&s->g)) { x = 0; plane = 0; while (bytestream2_get_bytes_left(&s->g) >= 6) { int stop_size, marker, t1, t2; t1 = bytestream2_get_bytes_left(&s->g); t2 = bytestream2_get_le16(&s->g); stop_size = t1 - FFMIN(t1, t2); bytestream2_skip(&s->g, 2); marker = bytestream2_get_byte(&s->g); while (plane < s->nb_planes && bytestream2_get_bytes_left(&s->g) > stop_size) { int run = 1; val = bytestream2_get_byte(&s->g); if (val == marker) { run = bytestream2_get_byte(&s->g); if (run == 0) run = bytestream2_get_le16(&s->g); val = bytestream2_get_byte(&s->g); } if (!bytestream2_get_bytes_left(&s->g)) break; if (bits_per_plane == 8) { picmemset_8bpp(s, frame, val, run, &x, &y); if (y < 0) goto finish; } else { picmemset(s, frame, val, run, &x, &y, &plane, bits_per_plane); } } } if (x < avctx->width) { int run = (y + 1) * avctx->width - x; if (bits_per_plane == 8) picmemset_8bpp(s, frame, val, run, &x, &y); else picmemset(s, frame, val, run / (8 / bits_per_plane), &x, &y, &plane, bits_per_plane); } } else { while (y >= 0 && bytestream2_get_bytes_left(&s->g) > 0) { memcpy(frame->data[0] + y * frame->linesize[0], s->g.buffer, FFMIN(avctx->width, bytestream2_get_bytes_left(&s->g))); bytestream2_skip(&s->g, avctx->width); y--; } } finish: *got_frame = 1; return avpkt->size; }
168,249
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void update_db_bp_intercept(struct kvm_vcpu *vcpu) { struct vcpu_svm *svm = to_svm(vcpu); clr_exception_intercept(svm, DB_VECTOR); clr_exception_intercept(svm, BP_VECTOR); if (svm->nmi_singlestep) set_exception_intercept(svm, DB_VECTOR); if (vcpu->guest_debug & KVM_GUESTDBG_ENABLE) { if (vcpu->guest_debug & (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP)) set_exception_intercept(svm, DB_VECTOR); if (vcpu->guest_debug & KVM_GUESTDBG_USE_SW_BP) set_exception_intercept(svm, BP_VECTOR); } else vcpu->guest_debug = 0; } Commit Message: KVM: svm: unconditionally intercept #DB This is needed to avoid the possibility that the guest triggers an infinite stream of #DB exceptions (CVE-2015-8104). VMX is not affected: because it does not save DR6 in the VMCS, it already intercepts #DB unconditionally. Reported-by: Jan Beulich <[email protected]> Cc: [email protected] Signed-off-by: Paolo Bonzini <[email protected]> CWE ID: CWE-399
static void update_db_bp_intercept(struct kvm_vcpu *vcpu) static void update_bp_intercept(struct kvm_vcpu *vcpu) { struct vcpu_svm *svm = to_svm(vcpu); clr_exception_intercept(svm, BP_VECTOR); if (vcpu->guest_debug & KVM_GUESTDBG_ENABLE) { if (vcpu->guest_debug & KVM_GUESTDBG_USE_SW_BP) set_exception_intercept(svm, BP_VECTOR); } else vcpu->guest_debug = 0; }
166,571
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int cp2112_probe(struct hid_device *hdev, const struct hid_device_id *id) { struct cp2112_device *dev; u8 buf[3]; struct cp2112_smbus_config_report config; int ret; dev = devm_kzalloc(&hdev->dev, sizeof(*dev), GFP_KERNEL); if (!dev) return -ENOMEM; dev->in_out_buffer = devm_kzalloc(&hdev->dev, CP2112_REPORT_MAX_LENGTH, GFP_KERNEL); if (!dev->in_out_buffer) return -ENOMEM; spin_lock_init(&dev->lock); ret = hid_parse(hdev); if (ret) { hid_err(hdev, "parse failed\n"); return ret; } ret = hid_hw_start(hdev, HID_CONNECT_HIDRAW); if (ret) { hid_err(hdev, "hw start failed\n"); return ret; } ret = hid_hw_open(hdev); if (ret) { hid_err(hdev, "hw open failed\n"); goto err_hid_stop; } ret = hid_hw_power(hdev, PM_HINT_FULLON); if (ret < 0) { hid_err(hdev, "power management error: %d\n", ret); goto err_hid_close; } ret = cp2112_hid_get(hdev, CP2112_GET_VERSION_INFO, buf, sizeof(buf), HID_FEATURE_REPORT); if (ret != sizeof(buf)) { hid_err(hdev, "error requesting version\n"); if (ret >= 0) ret = -EIO; goto err_power_normal; } hid_info(hdev, "Part Number: 0x%02X Device Version: 0x%02X\n", buf[1], buf[2]); ret = cp2112_hid_get(hdev, CP2112_SMBUS_CONFIG, (u8 *)&config, sizeof(config), HID_FEATURE_REPORT); if (ret != sizeof(config)) { hid_err(hdev, "error requesting SMBus config\n"); if (ret >= 0) ret = -EIO; goto err_power_normal; } config.retry_time = cpu_to_be16(1); ret = cp2112_hid_output(hdev, (u8 *)&config, sizeof(config), HID_FEATURE_REPORT); if (ret != sizeof(config)) { hid_err(hdev, "error setting SMBus config\n"); if (ret >= 0) ret = -EIO; goto err_power_normal; } hid_set_drvdata(hdev, (void *)dev); dev->hdev = hdev; dev->adap.owner = THIS_MODULE; dev->adap.class = I2C_CLASS_HWMON; dev->adap.algo = &smbus_algorithm; dev->adap.algo_data = dev; dev->adap.dev.parent = &hdev->dev; snprintf(dev->adap.name, sizeof(dev->adap.name), "CP2112 SMBus Bridge on hiddev%d", hdev->minor); dev->hwversion = buf[2]; init_waitqueue_head(&dev->wait); hid_device_io_start(hdev); ret = i2c_add_adapter(&dev->adap); hid_device_io_stop(hdev); if (ret) { hid_err(hdev, "error registering i2c adapter\n"); goto err_power_normal; } hid_dbg(hdev, "adapter registered\n"); dev->gc.label = "cp2112_gpio"; dev->gc.direction_input = cp2112_gpio_direction_input; dev->gc.direction_output = cp2112_gpio_direction_output; dev->gc.set = cp2112_gpio_set; dev->gc.get = cp2112_gpio_get; dev->gc.base = -1; dev->gc.ngpio = 8; dev->gc.can_sleep = 1; dev->gc.parent = &hdev->dev; ret = gpiochip_add_data(&dev->gc, dev); if (ret < 0) { hid_err(hdev, "error registering gpio chip\n"); goto err_free_i2c; } ret = sysfs_create_group(&hdev->dev.kobj, &cp2112_attr_group); if (ret < 0) { hid_err(hdev, "error creating sysfs attrs\n"); goto err_gpiochip_remove; } chmod_sysfs_attrs(hdev); hid_hw_power(hdev, PM_HINT_NORMAL); ret = gpiochip_irqchip_add(&dev->gc, &cp2112_gpio_irqchip, 0, handle_simple_irq, IRQ_TYPE_NONE); if (ret) { dev_err(dev->gc.parent, "failed to add IRQ chip\n"); goto err_sysfs_remove; } return ret; err_sysfs_remove: sysfs_remove_group(&hdev->dev.kobj, &cp2112_attr_group); err_gpiochip_remove: gpiochip_remove(&dev->gc); err_free_i2c: i2c_del_adapter(&dev->adap); err_power_normal: hid_hw_power(hdev, PM_HINT_NORMAL); err_hid_close: hid_hw_close(hdev); err_hid_stop: hid_hw_stop(hdev); return ret; } Commit Message: HID: cp2112: fix sleep-while-atomic A recent commit fixing DMA-buffers on stack added a shared transfer buffer protected by a spinlock. This is broken as the USB HID request callbacks can sleep. Fix this up by replacing the spinlock with a mutex. Fixes: 1ffb3c40ffb5 ("HID: cp2112: make transfer buffers DMA capable") Cc: stable <[email protected]> # 4.9 Signed-off-by: Johan Hovold <[email protected]> Reviewed-by: Benjamin Tissoires <[email protected]> Signed-off-by: Jiri Kosina <[email protected]> CWE ID: CWE-404
static int cp2112_probe(struct hid_device *hdev, const struct hid_device_id *id) { struct cp2112_device *dev; u8 buf[3]; struct cp2112_smbus_config_report config; int ret; dev = devm_kzalloc(&hdev->dev, sizeof(*dev), GFP_KERNEL); if (!dev) return -ENOMEM; dev->in_out_buffer = devm_kzalloc(&hdev->dev, CP2112_REPORT_MAX_LENGTH, GFP_KERNEL); if (!dev->in_out_buffer) return -ENOMEM; mutex_init(&dev->lock); ret = hid_parse(hdev); if (ret) { hid_err(hdev, "parse failed\n"); return ret; } ret = hid_hw_start(hdev, HID_CONNECT_HIDRAW); if (ret) { hid_err(hdev, "hw start failed\n"); return ret; } ret = hid_hw_open(hdev); if (ret) { hid_err(hdev, "hw open failed\n"); goto err_hid_stop; } ret = hid_hw_power(hdev, PM_HINT_FULLON); if (ret < 0) { hid_err(hdev, "power management error: %d\n", ret); goto err_hid_close; } ret = cp2112_hid_get(hdev, CP2112_GET_VERSION_INFO, buf, sizeof(buf), HID_FEATURE_REPORT); if (ret != sizeof(buf)) { hid_err(hdev, "error requesting version\n"); if (ret >= 0) ret = -EIO; goto err_power_normal; } hid_info(hdev, "Part Number: 0x%02X Device Version: 0x%02X\n", buf[1], buf[2]); ret = cp2112_hid_get(hdev, CP2112_SMBUS_CONFIG, (u8 *)&config, sizeof(config), HID_FEATURE_REPORT); if (ret != sizeof(config)) { hid_err(hdev, "error requesting SMBus config\n"); if (ret >= 0) ret = -EIO; goto err_power_normal; } config.retry_time = cpu_to_be16(1); ret = cp2112_hid_output(hdev, (u8 *)&config, sizeof(config), HID_FEATURE_REPORT); if (ret != sizeof(config)) { hid_err(hdev, "error setting SMBus config\n"); if (ret >= 0) ret = -EIO; goto err_power_normal; } hid_set_drvdata(hdev, (void *)dev); dev->hdev = hdev; dev->adap.owner = THIS_MODULE; dev->adap.class = I2C_CLASS_HWMON; dev->adap.algo = &smbus_algorithm; dev->adap.algo_data = dev; dev->adap.dev.parent = &hdev->dev; snprintf(dev->adap.name, sizeof(dev->adap.name), "CP2112 SMBus Bridge on hiddev%d", hdev->minor); dev->hwversion = buf[2]; init_waitqueue_head(&dev->wait); hid_device_io_start(hdev); ret = i2c_add_adapter(&dev->adap); hid_device_io_stop(hdev); if (ret) { hid_err(hdev, "error registering i2c adapter\n"); goto err_power_normal; } hid_dbg(hdev, "adapter registered\n"); dev->gc.label = "cp2112_gpio"; dev->gc.direction_input = cp2112_gpio_direction_input; dev->gc.direction_output = cp2112_gpio_direction_output; dev->gc.set = cp2112_gpio_set; dev->gc.get = cp2112_gpio_get; dev->gc.base = -1; dev->gc.ngpio = 8; dev->gc.can_sleep = 1; dev->gc.parent = &hdev->dev; ret = gpiochip_add_data(&dev->gc, dev); if (ret < 0) { hid_err(hdev, "error registering gpio chip\n"); goto err_free_i2c; } ret = sysfs_create_group(&hdev->dev.kobj, &cp2112_attr_group); if (ret < 0) { hid_err(hdev, "error creating sysfs attrs\n"); goto err_gpiochip_remove; } chmod_sysfs_attrs(hdev); hid_hw_power(hdev, PM_HINT_NORMAL); ret = gpiochip_irqchip_add(&dev->gc, &cp2112_gpio_irqchip, 0, handle_simple_irq, IRQ_TYPE_NONE); if (ret) { dev_err(dev->gc.parent, "failed to add IRQ chip\n"); goto err_sysfs_remove; } return ret; err_sysfs_remove: sysfs_remove_group(&hdev->dev.kobj, &cp2112_attr_group); err_gpiochip_remove: gpiochip_remove(&dev->gc); err_free_i2c: i2c_del_adapter(&dev->adap); err_power_normal: hid_hw_power(hdev, PM_HINT_NORMAL); err_hid_close: hid_hw_close(hdev); err_hid_stop: hid_hw_stop(hdev); return ret; }
168,212
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void EnsureInitializeForAndroidLayoutTests() { CHECK(CommandLine::ForCurrentProcess()->HasSwitch(switches::kDumpRenderTree)); JNIEnv* env = base::android::AttachCurrentThread(); content::NestedMessagePumpAndroid::RegisterJni(env); content::RegisterNativesImpl(env); bool success = base::MessageLoop::InitMessagePumpForUIFactory( &CreateMessagePumpForUI); CHECK(success) << "Unable to initialize the message pump for Android."; base::FilePath files_dir(GetTestFilesDirectory(env)); base::FilePath stdout_fifo(files_dir.Append(FILE_PATH_LITERAL("test.fifo"))); EnsureCreateFIFO(stdout_fifo); base::FilePath stderr_fifo( files_dir.Append(FILE_PATH_LITERAL("stderr.fifo"))); EnsureCreateFIFO(stderr_fifo); base::FilePath stdin_fifo(files_dir.Append(FILE_PATH_LITERAL("stdin.fifo"))); EnsureCreateFIFO(stdin_fifo); success = base::android::RedirectStream(stdout, stdout_fifo, "w") && base::android::RedirectStream(stdin, stdin_fifo, "r") && base::android::RedirectStream(stderr, stderr_fifo, "w"); CHECK(success) << "Unable to initialize the Android FIFOs."; } Commit Message: Content Shell: Move shell_layout_tests_android into layout_tests/. BUG=420994 Review URL: https://codereview.chromium.org/661743002 Cr-Commit-Position: refs/heads/master@{#299892} CWE ID: CWE-119
void EnsureInitializeForAndroidLayoutTests() { JNIEnv* env = base::android::AttachCurrentThread(); content::NestedMessagePumpAndroid::RegisterJni(env); content::RegisterNativesImpl(env); bool success = base::MessageLoop::InitMessagePumpForUIFactory( &CreateMessagePumpForUI); CHECK(success) << "Unable to initialize the message pump for Android."; base::FilePath files_dir(GetTestFilesDirectory(env)); base::FilePath stdout_fifo(files_dir.Append(FILE_PATH_LITERAL("test.fifo"))); EnsureCreateFIFO(stdout_fifo); base::FilePath stderr_fifo( files_dir.Append(FILE_PATH_LITERAL("stderr.fifo"))); EnsureCreateFIFO(stderr_fifo); base::FilePath stdin_fifo(files_dir.Append(FILE_PATH_LITERAL("stdin.fifo"))); EnsureCreateFIFO(stdin_fifo); success = base::android::RedirectStream(stdout, stdout_fifo, "w") && base::android::RedirectStream(stdin, stdin_fifo, "r") && base::android::RedirectStream(stderr, stderr_fifo, "w"); CHECK(success) << "Unable to initialize the Android FIFOs."; }
171,161
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: xmlBufCreateStatic(void *mem, size_t size) { xmlBufPtr ret; if ((mem == NULL) || (size == 0)) return(NULL); ret = (xmlBufPtr) xmlMalloc(sizeof(xmlBuf)); if (ret == NULL) { xmlBufMemoryError(NULL, "creating buffer"); return(NULL); } if (size < INT_MAX) { ret->compat_use = size; ret->compat_size = size; } else { ret->compat_use = INT_MAX; ret->compat_size = INT_MAX; } ret->use = size; ret->size = size; ret->alloc = XML_BUFFER_ALLOC_IMMUTABLE; ret->content = (xmlChar *) mem; ret->error = 0; ret->buffer = NULL; return(ret); } Commit Message: Roll libxml to 3939178e4cb797417ff033b1e04ab4b038e224d9 Removes a few patches fixed upstream: https://git.gnome.org/browse/libxml2/commit/?id=e26630548e7d138d2c560844c43820b6767251e3 https://git.gnome.org/browse/libxml2/commit/?id=94691dc884d1a8ada39f073408b4bb92fe7fe882 Stops using the NOXXE flag which was reverted upstream: https://git.gnome.org/browse/libxml2/commit/?id=030b1f7a27c22f9237eddca49ec5e620b6258d7d Changes the patch to uri.c to not add limits.h, which is included upstream. Bug: 722079 Change-Id: I4b8449ed33f95de23c54c2cde99970c2df2781ac Reviewed-on: https://chromium-review.googlesource.com/535233 Reviewed-by: Scott Graham <[email protected]> Commit-Queue: Dominic Cooney <[email protected]> Cr-Commit-Position: refs/heads/master@{#480755} CWE ID: CWE-787
xmlBufCreateStatic(void *mem, size_t size) { xmlBufPtr ret; if (mem == NULL) return(NULL); ret = (xmlBufPtr) xmlMalloc(sizeof(xmlBuf)); if (ret == NULL) { xmlBufMemoryError(NULL, "creating buffer"); return(NULL); } if (size < INT_MAX) { ret->compat_use = size; ret->compat_size = size; } else { ret->compat_use = INT_MAX; ret->compat_size = INT_MAX; } ret->use = size; ret->size = size; ret->alloc = XML_BUFFER_ALLOC_IMMUTABLE; ret->content = (xmlChar *) mem; ret->error = 0; ret->buffer = NULL; return(ret); }
172,949
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool FileUtilProxy::Read( scoped_refptr<MessageLoopProxy> message_loop_proxy, PlatformFile file, int64 offset, int bytes_to_read, ReadCallback* callback) { if (bytes_to_read < 0) return false; return Start(FROM_HERE, message_loop_proxy, new RelayRead(file, offset, bytes_to_read, callback)); } Commit Message: Fix a small leak in FileUtilProxy BUG=none TEST=green mem bots Review URL: http://codereview.chromium.org/7669046 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@97451 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
bool FileUtilProxy::Read( scoped_refptr<MessageLoopProxy> message_loop_proxy, PlatformFile file, int64 offset, int bytes_to_read, ReadCallback* callback) { if (bytes_to_read < 0) { delete callback; return false; } return Start(FROM_HERE, message_loop_proxy, new RelayRead(file, offset, bytes_to_read, callback)); }
170,273
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: virtual void PreEncodeFrameHook(::libvpx_test::VideoSource *video, ::libvpx_test::Encoder *encoder) { if (video->frame() == 1) { encoder->Control(VP8E_SET_CPUUSED, set_cpu_used_); } if (cfg_.ts_number_layers > 1) { if (video->frame() == 1) { encoder->Control(VP9E_SET_SVC, 1); } vpx_svc_layer_id_t layer_id = {0, 0}; layer_id.spatial_layer_id = 0; frame_flags_ = SetFrameFlags(video->frame(), cfg_.ts_number_layers); layer_id.temporal_layer_id = SetLayerId(video->frame(), cfg_.ts_number_layers); if (video->frame() > 0) { encoder->Control(VP9E_SET_SVC_LAYER_ID, &layer_id); } } const vpx_rational_t tb = video->timebase(); timebase_ = static_cast<double>(tb.num) / tb.den; duration_ = 0; } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119
virtual void PreEncodeFrameHook(::libvpx_test::VideoSource *video, ::libvpx_test::Encoder *encoder) { if (video->frame() == 0) encoder->Control(VP8E_SET_CPUUSED, set_cpu_used_); if (denoiser_offon_test_) { ASSERT_GT(denoiser_offon_period_, 0) << "denoiser_offon_period_ is not positive."; if ((video->frame() + 1) % denoiser_offon_period_ == 0) { // Flip denoiser_on_ periodically denoiser_on_ ^= 1; } } encoder->Control(VP9E_SET_NOISE_SENSITIVITY, denoiser_on_); if (cfg_.ts_number_layers > 1) { if (video->frame() == 0) { encoder->Control(VP9E_SET_SVC, 1); } vpx_svc_layer_id_t layer_id; layer_id.spatial_layer_id = 0; frame_flags_ = SetFrameFlags(video->frame(), cfg_.ts_number_layers); layer_id.temporal_layer_id = SetLayerId(video->frame(), cfg_.ts_number_layers); encoder->Control(VP9E_SET_SVC_LAYER_ID, &layer_id); } const vpx_rational_t tb = video->timebase(); timebase_ = static_cast<double>(tb.num) / tb.den; duration_ = 0; }
174,516
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void usb_ehci_pci_exit(PCIDevice *dev) { EHCIPCIState *i = PCI_EHCI(dev); static void usb_ehci_pci_reset(DeviceState *dev) { PCIDevice *pci_dev = PCI_DEVICE(dev); EHCIPCIState *i = PCI_EHCI(pci_dev); EHCIState *s = &i->ehci; ehci_reset(s); } static void usb_ehci_pci_write_config(PCIDevice *dev, uint32_t addr, uint32_t val, int l) { EHCIPCIState *i = PCI_EHCI(dev); bool busmaster; pci_default_write_config(dev, addr, val, l); if (!range_covers_byte(addr, l, PCI_COMMAND)) { return; } busmaster = pci_get_word(dev->config + PCI_COMMAND) & PCI_COMMAND_MASTER; i->ehci.as = busmaster ? pci_get_address_space(dev) : &address_space_memory; } static Property ehci_pci_properties[] = { DEFINE_PROP_UINT32("maxframes", EHCIPCIState, ehci.maxframes, 128), DEFINE_PROP_END_OF_LIST(), }; static const VMStateDescription vmstate_ehci_pci = { .name = "ehci", .version_id = 2, .minimum_version_id = 1, .fields = (VMStateField[]) { VMSTATE_PCI_DEVICE(pcidev, EHCIPCIState), VMSTATE_STRUCT(ehci, EHCIPCIState, 2, vmstate_ehci, EHCIState), VMSTATE_END_OF_LIST() } }; static void ehci_class_init(ObjectClass *klass, void *data) { DeviceClass *dc = DEVICE_CLASS(klass); PCIDeviceClass *k = PCI_DEVICE_CLASS(klass); k->realize = usb_ehci_pci_realize; k->exit = usb_ehci_pci_exit; k->class_id = PCI_CLASS_SERIAL_USB; k->config_write = usb_ehci_pci_write_config; dc->vmsd = &vmstate_ehci_pci; dc->props = ehci_pci_properties; dc->reset = usb_ehci_pci_reset; } static const TypeInfo ehci_pci_type_info = { .name = TYPE_PCI_EHCI, .parent = TYPE_PCI_DEVICE, .instance_size = sizeof(EHCIPCIState), .instance_init = usb_ehci_pci_init, .abstract = true, .class_init = ehci_class_init, }; static void ehci_data_class_init(ObjectClass *klass, void *data) .parent = TYPE_PCI_DEVICE, .instance_size = sizeof(EHCIPCIState), .instance_init = usb_ehci_pci_init, .abstract = true, .class_init = ehci_class_init, }; Commit Message: CWE ID: CWE-772
static void usb_ehci_pci_exit(PCIDevice *dev) { EHCIPCIState *i = PCI_EHCI(dev); static void usb_ehci_pci_reset(DeviceState *dev) { PCIDevice *pci_dev = PCI_DEVICE(dev); EHCIPCIState *i = PCI_EHCI(pci_dev); EHCIState *s = &i->ehci; ehci_reset(s); } static void usb_ehci_pci_write_config(PCIDevice *dev, uint32_t addr, uint32_t val, int l) { EHCIPCIState *i = PCI_EHCI(dev); bool busmaster; pci_default_write_config(dev, addr, val, l); if (!range_covers_byte(addr, l, PCI_COMMAND)) { return; } busmaster = pci_get_word(dev->config + PCI_COMMAND) & PCI_COMMAND_MASTER; i->ehci.as = busmaster ? pci_get_address_space(dev) : &address_space_memory; } static Property ehci_pci_properties[] = { DEFINE_PROP_UINT32("maxframes", EHCIPCIState, ehci.maxframes, 128), DEFINE_PROP_END_OF_LIST(), }; static const VMStateDescription vmstate_ehci_pci = { .name = "ehci", .version_id = 2, .minimum_version_id = 1, .fields = (VMStateField[]) { VMSTATE_PCI_DEVICE(pcidev, EHCIPCIState), VMSTATE_STRUCT(ehci, EHCIPCIState, 2, vmstate_ehci, EHCIState), VMSTATE_END_OF_LIST() } }; static void ehci_class_init(ObjectClass *klass, void *data) { DeviceClass *dc = DEVICE_CLASS(klass); PCIDeviceClass *k = PCI_DEVICE_CLASS(klass); k->realize = usb_ehci_pci_realize; k->exit = usb_ehci_pci_exit; k->class_id = PCI_CLASS_SERIAL_USB; k->config_write = usb_ehci_pci_write_config; dc->vmsd = &vmstate_ehci_pci; dc->props = ehci_pci_properties; dc->reset = usb_ehci_pci_reset; } static const TypeInfo ehci_pci_type_info = { .name = TYPE_PCI_EHCI, .parent = TYPE_PCI_DEVICE, .instance_size = sizeof(EHCIPCIState), .instance_init = usb_ehci_pci_init, .abstract = true, .class_init = ehci_class_init, }; static void ehci_data_class_init(ObjectClass *klass, void *data) .parent = TYPE_PCI_DEVICE, .instance_size = sizeof(EHCIPCIState), .instance_init = usb_ehci_pci_init, .instance_finalize = usb_ehci_pci_finalize, .abstract = true, .class_init = ehci_class_init, };
164,796
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: my_object_recursive2 (MyObject *obj, guint32 reqlen, GArray **ret, GError **error) { guint32 val; GArray *array; array = g_array_new (FALSE, TRUE, sizeof (guint32)); while (reqlen > 0) { val = 42; g_array_append_val (array, val); val = 26; g_array_append_val (array, val); reqlen--; } val = 2; g_array_append_val (array, val); *ret = array; return TRUE; } Commit Message: CWE ID: CWE-264
my_object_recursive2 (MyObject *obj, guint32 reqlen, GArray **ret, GError **error)
165,118
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: WORD32 ih264d_cavlc_4x4res_block_totalcoeff_2to10(UWORD32 u4_isdc, UWORD32 u4_total_coeff_trail_one, /*!<TotalCoefficients<<16+trailingones*/ dec_bit_stream_t *ps_bitstrm) { UWORD32 u4_total_zeroes; WORD32 i; UWORD32 *pu4_bitstrm_buf = ps_bitstrm->pu4_buffer; UWORD32 u4_bitstream_offset = ps_bitstrm->u4_ofst; UWORD32 u4_trailing_ones = u4_total_coeff_trail_one & 0xFFFF; UWORD32 u4_total_coeff = u4_total_coeff_trail_one >> 16; WORD16 i2_level_arr[16]; tu_sblk4x4_coeff_data_t *ps_tu_4x4; WORD16 *pi2_coeff_data; dec_struct_t *ps_dec = (dec_struct_t *)ps_bitstrm->pv_codec_handle; ps_tu_4x4 = (tu_sblk4x4_coeff_data_t *)ps_dec->pv_parse_tu_coeff_data; ps_tu_4x4->u2_sig_coeff_map = 0; pi2_coeff_data = &ps_tu_4x4->ai2_level[0]; i = u4_total_coeff - 1; if(u4_trailing_ones) { /*********************************************************************/ /* Decode Trailing Ones */ /* read the sign of T1's and put them in level array */ /*********************************************************************/ UWORD32 u4_signs, u4_cnt = u4_trailing_ones; WORD16 (*ppi2_trlone_lkup)[3] = (WORD16 (*)[3])gai2_ih264d_trailing_one_level; WORD16 *pi2_trlone_lkup; GETBITS(u4_signs, u4_bitstream_offset, pu4_bitstrm_buf, u4_cnt); pi2_trlone_lkup = ppi2_trlone_lkup[(1 << u4_cnt) - 2 + u4_signs]; while(u4_cnt--) i2_level_arr[i--] = *pi2_trlone_lkup++; } /****************************************************************/ /* Decoding Levels Begins */ /****************************************************************/ if(i >= 0) { /****************************************************************/ /* First level is decoded outside the loop as it has lot of */ /* special cases. */ /****************************************************************/ UWORD32 u4_lev_suffix, u4_suffix_len, u4_lev_suffix_size; WORD32 u2_lev_code, u2_abs_value; UWORD32 u4_lev_prefix; /***************************************************************/ /* u4_suffix_len = 0, Find leading zeros in next 32 bits */ /***************************************************************/ FIND_ONE_IN_STREAM_32(u4_lev_prefix, u4_bitstream_offset, pu4_bitstrm_buf); /*********************************************************/ /* Special decoding case when trailing ones are 3 */ /*********************************************************/ u2_lev_code = MIN(15, u4_lev_prefix); u2_lev_code += (3 == u4_trailing_ones) ? 0 : 2; if(14 == u4_lev_prefix) u4_lev_suffix_size = 4; else if(15 <= u4_lev_prefix) { u2_lev_code += 15; u4_lev_suffix_size = u4_lev_prefix - 3; } else u4_lev_suffix_size = 0; if(16 <= u4_lev_prefix) { u2_lev_code += ((1 << (u4_lev_prefix - 3)) - 4096); } if(u4_lev_suffix_size) { GETBITS(u4_lev_suffix, u4_bitstream_offset, pu4_bitstrm_buf, u4_lev_suffix_size); u2_lev_code += u4_lev_suffix; } u2_abs_value = (u2_lev_code + 2) >> 1; /*********************************************************/ /* If Level code is odd, level is negative else positive */ /*********************************************************/ i2_level_arr[i--] = (u2_lev_code & 1) ? -u2_abs_value : u2_abs_value; u4_suffix_len = (u2_abs_value > 3) ? 2 : 1; /*********************************************************/ /* Now loop over the remaining levels */ /*********************************************************/ while(i >= 0) { /***************************************************************/ /* Find leading zeros in next 32 bits */ /***************************************************************/ FIND_ONE_IN_STREAM_32(u4_lev_prefix, u4_bitstream_offset, pu4_bitstrm_buf); u4_lev_suffix_size = (15 <= u4_lev_prefix) ? (u4_lev_prefix - 3) : u4_suffix_len; /*********************************************************/ /* Compute level code using prefix and suffix */ /*********************************************************/ GETBITS(u4_lev_suffix, u4_bitstream_offset, pu4_bitstrm_buf, u4_lev_suffix_size); u2_lev_code = (MIN(15,u4_lev_prefix) << u4_suffix_len) + u4_lev_suffix; if(16 <= u4_lev_prefix) { u2_lev_code += ((1 << (u4_lev_prefix - 3)) - 4096); } u2_abs_value = (u2_lev_code + 2) >> 1; /*********************************************************/ /* If Level code is odd, level is negative else positive */ /*********************************************************/ i2_level_arr[i--] = (u2_lev_code & 1) ? -u2_abs_value : u2_abs_value; /*********************************************************/ /* Increment suffix length if required */ /*********************************************************/ u4_suffix_len += (u4_suffix_len < 6) ? (u2_abs_value > (3 << (u4_suffix_len - 1))) : 0; } /****************************************************************/ /* Decoding Levels Ends */ /****************************************************************/ } /****************************************************************/ /* Decoding total zeros as in section 9.2.3, table 9.7 */ /****************************************************************/ { UWORD32 u4_index; const UWORD8 (*ppu1_total_zero_lkup)[64] = (const UWORD8 (*)[64])gau1_ih264d_table_total_zero_2to10; NEXTBITS(u4_index, u4_bitstream_offset, pu4_bitstrm_buf, 6); u4_total_zeroes = ppu1_total_zero_lkup[u4_total_coeff - 2][u4_index]; FLUSHBITS(u4_bitstream_offset, (u4_total_zeroes >> 4)); u4_total_zeroes &= 0xf; } /**************************************************************/ /* Decode the runs and form the coefficient buffer */ /**************************************************************/ { const UWORD8 *pu1_table_runbefore; UWORD32 u4_run; WORD32 k; UWORD32 u4_scan_pos = u4_total_coeff + u4_total_zeroes - 1 + u4_isdc; WORD32 u4_zeroes_left = u4_total_zeroes; k = u4_total_coeff - 1; /**************************************************************/ /* Decoding Runs Begin for zeros left > 6 */ /**************************************************************/ while((u4_zeroes_left > 6) && k) { UWORD32 u4_code; NEXTBITS(u4_code, u4_bitstream_offset, pu4_bitstrm_buf, 3); if(u4_code != 0) { FLUSHBITS(u4_bitstream_offset, 3); u4_run = (7 - u4_code); } else { FIND_ONE_IN_STREAM_LEN(u4_code, u4_bitstream_offset, pu4_bitstrm_buf, 11); u4_run = (4 + u4_code); } SET_BIT(ps_tu_4x4->u2_sig_coeff_map, u4_scan_pos); *pi2_coeff_data++ = i2_level_arr[k--]; u4_zeroes_left -= u4_run; u4_scan_pos -= (u4_run + 1); } /**************************************************************/ /* Decoding Runs for 0 < zeros left <=6 */ /**************************************************************/ pu1_table_runbefore = (UWORD8 *)gau1_ih264d_table_run_before; while((u4_zeroes_left > 0) && k) { UWORD32 u4_code; NEXTBITS(u4_code, u4_bitstream_offset, pu4_bitstrm_buf, 3); u4_code = pu1_table_runbefore[u4_code + (u4_zeroes_left << 3)]; u4_run = u4_code >> 2; FLUSHBITS(u4_bitstream_offset, (u4_code & 0x03)); SET_BIT(ps_tu_4x4->u2_sig_coeff_map, u4_scan_pos); *pi2_coeff_data++ = i2_level_arr[k--]; u4_zeroes_left -= u4_run; u4_scan_pos -= (u4_run + 1); } /**************************************************************/ /* Decoding Runs End */ /**************************************************************/ /**************************************************************/ /* Copy the remaining coefficients */ /**************************************************************/ if(u4_zeroes_left < 0) return -1; while(k >= 0) { SET_BIT(ps_tu_4x4->u2_sig_coeff_map, u4_scan_pos); *pi2_coeff_data++ = i2_level_arr[k--]; u4_scan_pos--; } } { WORD32 offset; offset = (UWORD8 *)pi2_coeff_data - (UWORD8 *)ps_tu_4x4; offset = ALIGN4(offset); ps_dec->pv_parse_tu_coeff_data = (void *)((UWORD8 *)ps_dec->pv_parse_tu_coeff_data + offset); } ps_bitstrm->u4_ofst = u4_bitstream_offset; return 0; } Commit Message: Decoder: Fix stack underflow in CAVLC 4x4 parse functions Bug: 26399350 Change-Id: Id768751672a7b093ab6e53d4fc0b3188d470920e CWE ID: CWE-119
WORD32 ih264d_cavlc_4x4res_block_totalcoeff_2to10(UWORD32 u4_isdc, UWORD32 u4_total_coeff_trail_one, /*!<TotalCoefficients<<16+trailingones*/ dec_bit_stream_t *ps_bitstrm) { UWORD32 u4_total_zeroes; WORD32 i; UWORD32 *pu4_bitstrm_buf = ps_bitstrm->pu4_buffer; UWORD32 u4_bitstream_offset = ps_bitstrm->u4_ofst; UWORD32 u4_trailing_ones = u4_total_coeff_trail_one & 0xFFFF; UWORD32 u4_total_coeff = u4_total_coeff_trail_one >> 16; // To avoid error check at 4x4 level, allocating for 3 extra levels(16+3) // since u4_trailing_ones can at the max be 3. This will be required when // u4_total_coeff is less than u4_trailing_ones WORD16 ai2_level_arr[19]; WORD16 *i2_level_arr = &ai2_level_arr[3]; tu_sblk4x4_coeff_data_t *ps_tu_4x4; WORD16 *pi2_coeff_data; dec_struct_t *ps_dec = (dec_struct_t *)ps_bitstrm->pv_codec_handle; ps_tu_4x4 = (tu_sblk4x4_coeff_data_t *)ps_dec->pv_parse_tu_coeff_data; ps_tu_4x4->u2_sig_coeff_map = 0; pi2_coeff_data = &ps_tu_4x4->ai2_level[0]; i = u4_total_coeff - 1; if(u4_trailing_ones) { /*********************************************************************/ /* Decode Trailing Ones */ /* read the sign of T1's and put them in level array */ /*********************************************************************/ UWORD32 u4_signs, u4_cnt = u4_trailing_ones; WORD16 (*ppi2_trlone_lkup)[3] = (WORD16 (*)[3])gai2_ih264d_trailing_one_level; WORD16 *pi2_trlone_lkup; GETBITS(u4_signs, u4_bitstream_offset, pu4_bitstrm_buf, u4_cnt); pi2_trlone_lkup = ppi2_trlone_lkup[(1 << u4_cnt) - 2 + u4_signs]; while(u4_cnt--) i2_level_arr[i--] = *pi2_trlone_lkup++; } /****************************************************************/ /* Decoding Levels Begins */ /****************************************************************/ if(i >= 0) { /****************************************************************/ /* First level is decoded outside the loop as it has lot of */ /* special cases. */ /****************************************************************/ UWORD32 u4_lev_suffix, u4_suffix_len, u4_lev_suffix_size; WORD32 u2_lev_code, u2_abs_value; UWORD32 u4_lev_prefix; /***************************************************************/ /* u4_suffix_len = 0, Find leading zeros in next 32 bits */ /***************************************************************/ FIND_ONE_IN_STREAM_32(u4_lev_prefix, u4_bitstream_offset, pu4_bitstrm_buf); /*********************************************************/ /* Special decoding case when trailing ones are 3 */ /*********************************************************/ u2_lev_code = MIN(15, u4_lev_prefix); u2_lev_code += (3 == u4_trailing_ones) ? 0 : 2; if(14 == u4_lev_prefix) u4_lev_suffix_size = 4; else if(15 <= u4_lev_prefix) { u2_lev_code += 15; u4_lev_suffix_size = u4_lev_prefix - 3; } else u4_lev_suffix_size = 0; if(16 <= u4_lev_prefix) { u2_lev_code += ((1 << (u4_lev_prefix - 3)) - 4096); } if(u4_lev_suffix_size) { GETBITS(u4_lev_suffix, u4_bitstream_offset, pu4_bitstrm_buf, u4_lev_suffix_size); u2_lev_code += u4_lev_suffix; } u2_abs_value = (u2_lev_code + 2) >> 1; /*********************************************************/ /* If Level code is odd, level is negative else positive */ /*********************************************************/ i2_level_arr[i--] = (u2_lev_code & 1) ? -u2_abs_value : u2_abs_value; u4_suffix_len = (u2_abs_value > 3) ? 2 : 1; /*********************************************************/ /* Now loop over the remaining levels */ /*********************************************************/ while(i >= 0) { /***************************************************************/ /* Find leading zeros in next 32 bits */ /***************************************************************/ FIND_ONE_IN_STREAM_32(u4_lev_prefix, u4_bitstream_offset, pu4_bitstrm_buf); u4_lev_suffix_size = (15 <= u4_lev_prefix) ? (u4_lev_prefix - 3) : u4_suffix_len; /*********************************************************/ /* Compute level code using prefix and suffix */ /*********************************************************/ GETBITS(u4_lev_suffix, u4_bitstream_offset, pu4_bitstrm_buf, u4_lev_suffix_size); u2_lev_code = (MIN(15,u4_lev_prefix) << u4_suffix_len) + u4_lev_suffix; if(16 <= u4_lev_prefix) { u2_lev_code += ((1 << (u4_lev_prefix - 3)) - 4096); } u2_abs_value = (u2_lev_code + 2) >> 1; /*********************************************************/ /* If Level code is odd, level is negative else positive */ /*********************************************************/ i2_level_arr[i--] = (u2_lev_code & 1) ? -u2_abs_value : u2_abs_value; /*********************************************************/ /* Increment suffix length if required */ /*********************************************************/ u4_suffix_len += (u4_suffix_len < 6) ? (u2_abs_value > (3 << (u4_suffix_len - 1))) : 0; } /****************************************************************/ /* Decoding Levels Ends */ /****************************************************************/ } /****************************************************************/ /* Decoding total zeros as in section 9.2.3, table 9.7 */ /****************************************************************/ { UWORD32 u4_index; const UWORD8 (*ppu1_total_zero_lkup)[64] = (const UWORD8 (*)[64])gau1_ih264d_table_total_zero_2to10; NEXTBITS(u4_index, u4_bitstream_offset, pu4_bitstrm_buf, 6); u4_total_zeroes = ppu1_total_zero_lkup[u4_total_coeff - 2][u4_index]; FLUSHBITS(u4_bitstream_offset, (u4_total_zeroes >> 4)); u4_total_zeroes &= 0xf; } /**************************************************************/ /* Decode the runs and form the coefficient buffer */ /**************************************************************/ { const UWORD8 *pu1_table_runbefore; UWORD32 u4_run; WORD32 k; UWORD32 u4_scan_pos = u4_total_coeff + u4_total_zeroes - 1 + u4_isdc; WORD32 u4_zeroes_left = u4_total_zeroes; k = u4_total_coeff - 1; /**************************************************************/ /* Decoding Runs Begin for zeros left > 6 */ /**************************************************************/ while((u4_zeroes_left > 6) && k) { UWORD32 u4_code; NEXTBITS(u4_code, u4_bitstream_offset, pu4_bitstrm_buf, 3); if(u4_code != 0) { FLUSHBITS(u4_bitstream_offset, 3); u4_run = (7 - u4_code); } else { FIND_ONE_IN_STREAM_LEN(u4_code, u4_bitstream_offset, pu4_bitstrm_buf, 11); u4_run = (4 + u4_code); } SET_BIT(ps_tu_4x4->u2_sig_coeff_map, u4_scan_pos); *pi2_coeff_data++ = i2_level_arr[k--]; u4_zeroes_left -= u4_run; u4_scan_pos -= (u4_run + 1); } /**************************************************************/ /* Decoding Runs for 0 < zeros left <=6 */ /**************************************************************/ pu1_table_runbefore = (UWORD8 *)gau1_ih264d_table_run_before; while((u4_zeroes_left > 0) && k) { UWORD32 u4_code; NEXTBITS(u4_code, u4_bitstream_offset, pu4_bitstrm_buf, 3); u4_code = pu1_table_runbefore[u4_code + (u4_zeroes_left << 3)]; u4_run = u4_code >> 2; FLUSHBITS(u4_bitstream_offset, (u4_code & 0x03)); SET_BIT(ps_tu_4x4->u2_sig_coeff_map, u4_scan_pos); *pi2_coeff_data++ = i2_level_arr[k--]; u4_zeroes_left -= u4_run; u4_scan_pos -= (u4_run + 1); } /**************************************************************/ /* Decoding Runs End */ /**************************************************************/ /**************************************************************/ /* Copy the remaining coefficients */ /**************************************************************/ if(u4_zeroes_left < 0) return -1; while(k >= 0) { SET_BIT(ps_tu_4x4->u2_sig_coeff_map, u4_scan_pos); *pi2_coeff_data++ = i2_level_arr[k--]; u4_scan_pos--; } } { WORD32 offset; offset = (UWORD8 *)pi2_coeff_data - (UWORD8 *)ps_tu_4x4; offset = ALIGN4(offset); ps_dec->pv_parse_tu_coeff_data = (void *)((UWORD8 *)ps_dec->pv_parse_tu_coeff_data + offset); } ps_bitstrm->u4_ofst = u4_bitstream_offset; return 0; }
173,914
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: EncodedJSValue JSC_HOST_CALL jsFloat64ArrayPrototypeFunctionFoo(ExecState* exec) { JSValue thisValue = exec->hostThisValue(); if (!thisValue.inherits(&JSFloat64Array::s_info)) return throwVMTypeError(exec); JSFloat64Array* castedThis = jsCast<JSFloat64Array*>(asObject(thisValue)); ASSERT_GC_OBJECT_INHERITS(castedThis, &JSFloat64Array::s_info); Float64Array* impl = static_cast<Float64Array*>(castedThis->impl()); if (exec->argumentCount() < 1) return throwVMError(exec, createTypeError(exec, "Not enough arguments")); Float32Array* array(toFloat32Array(MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined))); if (exec->hadException()) return JSValue::encode(jsUndefined()); JSC::JSValue result = toJS(exec, castedThis->globalObject(), WTF::getPtr(impl->foo(array))); return JSValue::encode(result); } Commit Message: [JSC] Implement a helper method createNotEnoughArgumentsError() https://bugs.webkit.org/show_bug.cgi?id=85102 Reviewed by Geoffrey Garen. In bug 84787, kbr@ requested to avoid hard-coding createTypeError(exec, "Not enough arguments") here and there. This patch implements createNotEnoughArgumentsError(exec) and uses it in JSC bindings. c.f. a corresponding bug for V8 bindings is bug 85097. Source/JavaScriptCore: * runtime/Error.cpp: (JSC::createNotEnoughArgumentsError): (JSC): * runtime/Error.h: (JSC): Source/WebCore: Test: bindings/scripts/test/TestObj.idl * bindings/scripts/CodeGeneratorJS.pm: Modified as described above. (GenerateArgumentsCountCheck): * bindings/js/JSDataViewCustom.cpp: Ditto. (WebCore::getDataViewMember): (WebCore::setDataViewMember): * bindings/js/JSDeprecatedPeerConnectionCustom.cpp: (WebCore::JSDeprecatedPeerConnectionConstructor::constructJSDeprecatedPeerConnection): * bindings/js/JSDirectoryEntryCustom.cpp: (WebCore::JSDirectoryEntry::getFile): (WebCore::JSDirectoryEntry::getDirectory): * bindings/js/JSSharedWorkerCustom.cpp: (WebCore::JSSharedWorkerConstructor::constructJSSharedWorker): * bindings/js/JSWebKitMutationObserverCustom.cpp: (WebCore::JSWebKitMutationObserverConstructor::constructJSWebKitMutationObserver): (WebCore::JSWebKitMutationObserver::observe): * bindings/js/JSWorkerCustom.cpp: (WebCore::JSWorkerConstructor::constructJSWorker): * bindings/scripts/test/JS/JSFloat64Array.cpp: Updated run-bindings-tests. (WebCore::jsFloat64ArrayPrototypeFunctionFoo): * bindings/scripts/test/JS/JSTestActiveDOMObject.cpp: (WebCore::jsTestActiveDOMObjectPrototypeFunctionExcitingFunction): (WebCore::jsTestActiveDOMObjectPrototypeFunctionPostMessage): * bindings/scripts/test/JS/JSTestCustomNamedGetter.cpp: (WebCore::jsTestCustomNamedGetterPrototypeFunctionAnotherFunction): * bindings/scripts/test/JS/JSTestEventTarget.cpp: (WebCore::jsTestEventTargetPrototypeFunctionItem): (WebCore::jsTestEventTargetPrototypeFunctionAddEventListener): (WebCore::jsTestEventTargetPrototypeFunctionRemoveEventListener): (WebCore::jsTestEventTargetPrototypeFunctionDispatchEvent): * bindings/scripts/test/JS/JSTestInterface.cpp: (WebCore::JSTestInterfaceConstructor::constructJSTestInterface): (WebCore::jsTestInterfacePrototypeFunctionSupplementalMethod2): * bindings/scripts/test/JS/JSTestMediaQueryListListener.cpp: (WebCore::jsTestMediaQueryListListenerPrototypeFunctionMethod): * bindings/scripts/test/JS/JSTestNamedConstructor.cpp: (WebCore::JSTestNamedConstructorNamedConstructor::constructJSTestNamedConstructor): * bindings/scripts/test/JS/JSTestObj.cpp: (WebCore::JSTestObjConstructor::constructJSTestObj): (WebCore::jsTestObjPrototypeFunctionVoidMethodWithArgs): (WebCore::jsTestObjPrototypeFunctionIntMethodWithArgs): (WebCore::jsTestObjPrototypeFunctionObjMethodWithArgs): (WebCore::jsTestObjPrototypeFunctionMethodWithSequenceArg): (WebCore::jsTestObjPrototypeFunctionMethodReturningSequence): (WebCore::jsTestObjPrototypeFunctionMethodThatRequiresAllArgsAndThrows): (WebCore::jsTestObjPrototypeFunctionSerializedValue): (WebCore::jsTestObjPrototypeFunctionIdbKey): (WebCore::jsTestObjPrototypeFunctionOptionsObject): (WebCore::jsTestObjPrototypeFunctionAddEventListener): (WebCore::jsTestObjPrototypeFunctionRemoveEventListener): (WebCore::jsTestObjPrototypeFunctionMethodWithNonOptionalArgAndOptionalArg): (WebCore::jsTestObjPrototypeFunctionMethodWithNonOptionalArgAndTwoOptionalArgs): (WebCore::jsTestObjPrototypeFunctionMethodWithCallbackArg): (WebCore::jsTestObjPrototypeFunctionMethodWithNonCallbackArgAndCallbackArg): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod1): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod2): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod3): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod4): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod5): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod6): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod7): (WebCore::jsTestObjConstructorFunctionClassMethod2): (WebCore::jsTestObjConstructorFunctionOverloadedMethod11): (WebCore::jsTestObjConstructorFunctionOverloadedMethod12): (WebCore::jsTestObjPrototypeFunctionMethodWithUnsignedLongArray): (WebCore::jsTestObjPrototypeFunctionConvert1): (WebCore::jsTestObjPrototypeFunctionConvert2): (WebCore::jsTestObjPrototypeFunctionConvert3): (WebCore::jsTestObjPrototypeFunctionConvert4): (WebCore::jsTestObjPrototypeFunctionConvert5): (WebCore::jsTestObjPrototypeFunctionStrictFunction): * bindings/scripts/test/JS/JSTestSerializedScriptValueInterface.cpp: (WebCore::JSTestSerializedScriptValueInterfaceConstructor::constructJSTestSerializedScriptValueInterface): (WebCore::jsTestSerializedScriptValueInterfacePrototypeFunctionAcceptTransferList): git-svn-id: svn://svn.chromium.org/blink/trunk@115536 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-20
EncodedJSValue JSC_HOST_CALL jsFloat64ArrayPrototypeFunctionFoo(ExecState* exec) { JSValue thisValue = exec->hostThisValue(); if (!thisValue.inherits(&JSFloat64Array::s_info)) return throwVMTypeError(exec); JSFloat64Array* castedThis = jsCast<JSFloat64Array*>(asObject(thisValue)); ASSERT_GC_OBJECT_INHERITS(castedThis, &JSFloat64Array::s_info); Float64Array* impl = static_cast<Float64Array*>(castedThis->impl()); if (exec->argumentCount() < 1) return throwVMError(exec, createNotEnoughArgumentsError(exec)); Float32Array* array(toFloat32Array(MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined))); if (exec->hadException()) return JSValue::encode(jsUndefined()); JSC::JSValue result = toJS(exec, castedThis->globalObject(), WTF::getPtr(impl->foo(array))); return JSValue::encode(result); }
170,566
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: SPL_METHOD(RecursiveDirectoryIterator, getSubPath) { 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.sub_path) { RETURN_STRINGL(intern->u.dir.sub_path, intern->u.dir.sub_path_len, 1); } else { RETURN_STRINGL("", 0, 1); } } Commit Message: Fix bug #72262 - do not overflow int CWE ID: CWE-190
SPL_METHOD(RecursiveDirectoryIterator, getSubPath) { 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.sub_path) { RETURN_STRINGL(intern->u.dir.sub_path, intern->u.dir.sub_path_len, 1); } else { RETURN_STRINGL("", 0, 1); } }
167,046
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void QQuickWebViewFlickablePrivate::onComponentComplete() { Q_Q(QQuickWebView); m_viewportHandler.reset(new QtViewportHandler(webPageProxy.get(), q, pageView.data())); pageView->eventHandler()->setViewportHandler(m_viewportHandler.data()); _q_onVisibleChanged(); } Commit Message: [Qt][WK2] There's no way to test the gesture tap on WTR https://bugs.webkit.org/show_bug.cgi?id=92895 Reviewed by Kenneth Rohde Christiansen. Source/WebKit2: Add an instance of QtViewportHandler to QQuickWebViewPrivate, so it's now available on mobile and desktop modes, as a side effect gesture tap events can now be created and sent to WebCore. This is needed to test tap gestures and to get tap gestures working when you have a WebView (in desktop mode) on notebooks equipped with touch screens. * UIProcess/API/qt/qquickwebview.cpp: (QQuickWebViewPrivate::onComponentComplete): (QQuickWebViewFlickablePrivate::onComponentComplete): Implementation moved to QQuickWebViewPrivate::onComponentComplete. * UIProcess/API/qt/qquickwebview_p_p.h: (QQuickWebViewPrivate): (QQuickWebViewFlickablePrivate): Tools: WTR doesn't create the QQuickItem from C++, not from QML, so a call to componentComplete() was added to mimic the QML behaviour. * WebKitTestRunner/qt/PlatformWebViewQt.cpp: (WTR::PlatformWebView::PlatformWebView): git-svn-id: svn://svn.chromium.org/blink/trunk@124625 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID:
void QQuickWebViewFlickablePrivate::onComponentComplete() { QQuickWebViewPrivate::onComponentComplete(); _q_onVisibleChanged(); }
170,997
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: WebsiteSettingsPopupAndroid::WebsiteSettingsPopupAndroid( JNIEnv* env, jobject java_website_settings_pop, content::WebContents* web_contents) { content::NavigationEntry* nav_entry = web_contents->GetController().GetVisibleEntry(); if (nav_entry == NULL) return; url_ = nav_entry->GetURL(); popup_jobject_.Reset(env, java_website_settings_pop); presenter_.reset(new WebsiteSettings( this, Profile::FromBrowserContext(web_contents->GetBrowserContext()), TabSpecificContentSettings::FromWebContents(web_contents), InfoBarService::FromWebContents(web_contents), nav_entry->GetURL(), nav_entry->GetSSL(), content::CertStore::GetInstance())); } Commit Message: Fix UAF in Origin Info Bubble and permission settings UI. In addition to fixing the UAF, will this also fix the problem of the bubble showing over the previous tab (if the bubble is open when the tab it was opened for closes). BUG=490492 TBR=tedchoc Review URL: https://codereview.chromium.org/1317443002 Cr-Commit-Position: refs/heads/master@{#346023} CWE ID:
WebsiteSettingsPopupAndroid::WebsiteSettingsPopupAndroid( JNIEnv* env, jobject java_website_settings_pop, content::WebContents* web_contents) { content::NavigationEntry* nav_entry = web_contents->GetController().GetVisibleEntry(); if (nav_entry == NULL) return; url_ = nav_entry->GetURL(); popup_jobject_.Reset(env, java_website_settings_pop); presenter_.reset(new WebsiteSettings( this, Profile::FromBrowserContext(web_contents->GetBrowserContext()), TabSpecificContentSettings::FromWebContents(web_contents), web_contents, nav_entry->GetURL(), nav_entry->GetSSL(), content::CertStore::GetInstance())); }
171,778
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: v8::Handle<v8::Value> V8DataView::setInt8Callback(const v8::Arguments& args) { INC_STATS("DOM.DataView.setInt8"); if (args.Length() < 2) return V8Proxy::throwNotEnoughArgumentsError(); DataView* imp = V8DataView::toNative(args.Holder()); ExceptionCode ec = 0; EXCEPTION_BLOCK(unsigned, byteOffset, toUInt32(args[0])); EXCEPTION_BLOCK(int, value, toInt32(args[1])); imp->setInt8(byteOffset, static_cast<int8_t>(value), ec); if (UNLIKELY(ec)) V8Proxy::setDOMException(ec, args.GetIsolate()); return v8::Handle<v8::Value>(); } Commit Message: [V8] Pass Isolate to throwNotEnoughArgumentsError() https://bugs.webkit.org/show_bug.cgi?id=86983 Reviewed by Adam Barth. The objective is to pass Isolate around in V8 bindings. This patch passes Isolate to throwNotEnoughArgumentsError(). No tests. No change in behavior. * bindings/scripts/CodeGeneratorV8.pm: (GenerateArgumentsCountCheck): (GenerateEventConstructorCallback): * bindings/scripts/test/V8/V8Float64Array.cpp: (WebCore::Float64ArrayV8Internal::fooCallback): * bindings/scripts/test/V8/V8TestActiveDOMObject.cpp: (WebCore::TestActiveDOMObjectV8Internal::excitingFunctionCallback): (WebCore::TestActiveDOMObjectV8Internal::postMessageCallback): * bindings/scripts/test/V8/V8TestCustomNamedGetter.cpp: (WebCore::TestCustomNamedGetterV8Internal::anotherFunctionCallback): * bindings/scripts/test/V8/V8TestEventConstructor.cpp: (WebCore::V8TestEventConstructor::constructorCallback): * bindings/scripts/test/V8/V8TestEventTarget.cpp: (WebCore::TestEventTargetV8Internal::itemCallback): (WebCore::TestEventTargetV8Internal::dispatchEventCallback): * bindings/scripts/test/V8/V8TestInterface.cpp: (WebCore::TestInterfaceV8Internal::supplementalMethod2Callback): (WebCore::V8TestInterface::constructorCallback): * bindings/scripts/test/V8/V8TestMediaQueryListListener.cpp: (WebCore::TestMediaQueryListListenerV8Internal::methodCallback): * bindings/scripts/test/V8/V8TestNamedConstructor.cpp: (WebCore::V8TestNamedConstructorConstructorCallback): * bindings/scripts/test/V8/V8TestObj.cpp: (WebCore::TestObjV8Internal::voidMethodWithArgsCallback): (WebCore::TestObjV8Internal::intMethodWithArgsCallback): (WebCore::TestObjV8Internal::objMethodWithArgsCallback): (WebCore::TestObjV8Internal::methodWithSequenceArgCallback): (WebCore::TestObjV8Internal::methodReturningSequenceCallback): (WebCore::TestObjV8Internal::methodThatRequiresAllArgsAndThrowsCallback): (WebCore::TestObjV8Internal::serializedValueCallback): (WebCore::TestObjV8Internal::idbKeyCallback): (WebCore::TestObjV8Internal::optionsObjectCallback): (WebCore::TestObjV8Internal::methodWithNonOptionalArgAndOptionalArgCallback): (WebCore::TestObjV8Internal::methodWithNonOptionalArgAndTwoOptionalArgsCallback): (WebCore::TestObjV8Internal::methodWithCallbackArgCallback): (WebCore::TestObjV8Internal::methodWithNonCallbackArgAndCallbackArgCallback): (WebCore::TestObjV8Internal::overloadedMethod1Callback): (WebCore::TestObjV8Internal::overloadedMethod2Callback): (WebCore::TestObjV8Internal::overloadedMethod3Callback): (WebCore::TestObjV8Internal::overloadedMethod4Callback): (WebCore::TestObjV8Internal::overloadedMethod5Callback): (WebCore::TestObjV8Internal::overloadedMethod6Callback): (WebCore::TestObjV8Internal::overloadedMethod7Callback): (WebCore::TestObjV8Internal::overloadedMethod11Callback): (WebCore::TestObjV8Internal::overloadedMethod12Callback): (WebCore::TestObjV8Internal::enabledAtRuntimeMethod1Callback): (WebCore::TestObjV8Internal::enabledAtRuntimeMethod2Callback): (WebCore::TestObjV8Internal::convert1Callback): (WebCore::TestObjV8Internal::convert2Callback): (WebCore::TestObjV8Internal::convert3Callback): (WebCore::TestObjV8Internal::convert4Callback): (WebCore::TestObjV8Internal::convert5Callback): (WebCore::TestObjV8Internal::strictFunctionCallback): (WebCore::V8TestObj::constructorCallback): * bindings/scripts/test/V8/V8TestSerializedScriptValueInterface.cpp: (WebCore::TestSerializedScriptValueInterfaceV8Internal::acceptTransferListCallback): (WebCore::V8TestSerializedScriptValueInterface::constructorCallback): * bindings/v8/ScriptController.cpp: (WebCore::setValueAndClosePopupCallback): * bindings/v8/V8Proxy.cpp: (WebCore::V8Proxy::throwNotEnoughArgumentsError): * bindings/v8/V8Proxy.h: (V8Proxy): * bindings/v8/custom/V8AudioContextCustom.cpp: (WebCore::V8AudioContext::constructorCallback): * bindings/v8/custom/V8DataViewCustom.cpp: (WebCore::V8DataView::getInt8Callback): (WebCore::V8DataView::getUint8Callback): (WebCore::V8DataView::setInt8Callback): (WebCore::V8DataView::setUint8Callback): * bindings/v8/custom/V8DirectoryEntryCustom.cpp: (WebCore::V8DirectoryEntry::getDirectoryCallback): (WebCore::V8DirectoryEntry::getFileCallback): * bindings/v8/custom/V8IntentConstructor.cpp: (WebCore::V8Intent::constructorCallback): * bindings/v8/custom/V8SVGLengthCustom.cpp: (WebCore::V8SVGLength::convertToSpecifiedUnitsCallback): * bindings/v8/custom/V8WebGLRenderingContextCustom.cpp: (WebCore::getObjectParameter): (WebCore::V8WebGLRenderingContext::getAttachedShadersCallback): (WebCore::V8WebGLRenderingContext::getExtensionCallback): (WebCore::V8WebGLRenderingContext::getFramebufferAttachmentParameterCallback): (WebCore::V8WebGLRenderingContext::getParameterCallback): (WebCore::V8WebGLRenderingContext::getProgramParameterCallback): (WebCore::V8WebGLRenderingContext::getShaderParameterCallback): (WebCore::V8WebGLRenderingContext::getUniformCallback): (WebCore::vertexAttribAndUniformHelperf): (WebCore::uniformHelperi): (WebCore::uniformMatrixHelper): * bindings/v8/custom/V8WebKitMutationObserverCustom.cpp: (WebCore::V8WebKitMutationObserver::constructorCallback): (WebCore::V8WebKitMutationObserver::observeCallback): * bindings/v8/custom/V8WebSocketCustom.cpp: (WebCore::V8WebSocket::constructorCallback): (WebCore::V8WebSocket::sendCallback): * bindings/v8/custom/V8XMLHttpRequestCustom.cpp: (WebCore::V8XMLHttpRequest::openCallback): git-svn-id: svn://svn.chromium.org/blink/trunk@117736 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID:
v8::Handle<v8::Value> V8DataView::setInt8Callback(const v8::Arguments& args) { INC_STATS("DOM.DataView.setInt8"); if (args.Length() < 2) return V8Proxy::throwNotEnoughArgumentsError(args.GetIsolate()); DataView* imp = V8DataView::toNative(args.Holder()); ExceptionCode ec = 0; EXCEPTION_BLOCK(unsigned, byteOffset, toUInt32(args[0])); EXCEPTION_BLOCK(int, value, toInt32(args[1])); imp->setInt8(byteOffset, static_cast<int8_t>(value), ec); if (UNLIKELY(ec)) V8Proxy::setDOMException(ec, args.GetIsolate()); return v8::Handle<v8::Value>(); }
171,114
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void ProfilingService::DumpProcessesForTracing( bool keep_small_allocations, bool strip_path_from_mapped_files, DumpProcessesForTracingCallback callback) { memory_instrumentation::MemoryInstrumentation::GetInstance() ->GetVmRegionsForHeapProfiler(base::Bind( &ProfilingService::OnGetVmRegionsCompleteForDumpProcessesForTracing, weak_factory_.GetWeakPtr(), keep_small_allocations, strip_path_from_mapped_files, base::Passed(&callback))); } Commit Message: memory-infra: split up memory-infra coordinator service into two This allows for heap profiler to use its own service with correct capabilities and all other instances to use the existing coordinator service. Bug: 792028 Change-Id: I84e4ec71f5f1d00991c0516b1424ce7334bcd3cd Reviewed-on: https://chromium-review.googlesource.com/836896 Commit-Queue: Lalit Maganti <[email protected]> Reviewed-by: Daniel Cheng <[email protected]> Reviewed-by: oysteine <[email protected]> Reviewed-by: Albert J. Wong <[email protected]> Reviewed-by: Hector Dearman <[email protected]> Cr-Commit-Position: refs/heads/master@{#529059} CWE ID: CWE-269
void ProfilingService::DumpProcessesForTracing( bool keep_small_allocations, bool strip_path_from_mapped_files, DumpProcessesForTracingCallback callback) { if (!helper_) { context()->connector()->BindInterface( resource_coordinator::mojom::kServiceName, &helper_); } helper_->GetVmRegionsForHeapProfiler(base::Bind( &ProfilingService::OnGetVmRegionsCompleteForDumpProcessesForTracing, weak_factory_.GetWeakPtr(), keep_small_allocations, strip_path_from_mapped_files, base::Passed(&callback))); }
172,913
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void BluetoothOptionsHandler::RequestPasskey( chromeos::BluetoothDevice* device) { } Commit Message: Implement methods for pairing of bluetooth devices. BUG=chromium:100392,chromium:102139 TEST= Review URL: http://codereview.chromium.org/8495018 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@109094 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
void BluetoothOptionsHandler::RequestPasskey( chromeos::BluetoothDevice* device) { DictionaryValue params; params.SetString("pairing", "bluetoothEnterPasskey"); SendDeviceNotification(device, &params); }
170,972
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: znumicc_components(i_ctx_t * i_ctx_p) { ref * pnval; ref * pstrmval; stream * s; int ncomps, expected = 0, code; cmm_profile_t *picc_profile; os_ptr op = osp; check_type(*op, t_dictionary); check_dict_read(*op); code = dict_find_string(op, "N", &pnval); if (code < 0) return code; if (code == 0) return code; if (code == 0) return_error(gs_error_undefined); ncomps = pnval->value.intval; /* verify the DataSource entry. Create profile from stream */ if (dict_find_string(op, "DataSource", &pstrmval) <= 0) if (picc_profile == NULL) return gs_throw(gs_error_VMerror, "Creation of ICC profile failed"); picc_profile->num_comps = ncomps; picc_profile->profile_handle = gsicc_get_profile_handle_buffer(picc_profile->buffer, picc_profile->buffer_size, gs_gstate_memory(igs)); if (picc_profile->profile_handle == NULL) { rc_decrement(picc_profile,"znumicc_components"); make_int(op, expected); return 0; } picc_profile->data_cs = gscms_get_profile_data_space(picc_profile->profile_handle, picc_profile->memory); switch (picc_profile->data_cs) { case gsCIEXYZ: case gsCIELAB: case gsRGB: expected = 3; break; case gsGRAY: expected = 1; break; case gsCMYK: expected = 4; break; case gsNCHANNEL: expected = 0; break; case gsNAMED: case gsUNDEFINED: expected = -1; break; } make_int(op, expected); rc_decrement(picc_profile,"zset_outputintent"); return 0; } Commit Message: CWE ID: CWE-704
znumicc_components(i_ctx_t * i_ctx_p) { ref * pnval; ref * pstrmval; stream * s; int ncomps, expected = 0, code; cmm_profile_t *picc_profile; os_ptr op = osp; check_type(*op, t_dictionary); check_dict_read(*op); code = dict_find_string(op, "N", &pnval); if (code < 0) return code; if (code == 0) return code; if (code == 0) return_error(gs_error_undefined); if (r_type(pnval) != t_integer) return gs_note_error(gs_error_typecheck); ncomps = pnval->value.intval; /* verify the DataSource entry. Create profile from stream */ if (dict_find_string(op, "DataSource", &pstrmval) <= 0) if (picc_profile == NULL) return gs_throw(gs_error_VMerror, "Creation of ICC profile failed"); picc_profile->num_comps = ncomps; picc_profile->profile_handle = gsicc_get_profile_handle_buffer(picc_profile->buffer, picc_profile->buffer_size, gs_gstate_memory(igs)); if (picc_profile->profile_handle == NULL) { rc_decrement(picc_profile,"znumicc_components"); make_int(op, expected); return 0; } picc_profile->data_cs = gscms_get_profile_data_space(picc_profile->profile_handle, picc_profile->memory); switch (picc_profile->data_cs) { case gsCIEXYZ: case gsCIELAB: case gsRGB: expected = 3; break; case gsGRAY: expected = 1; break; case gsCMYK: expected = 4; break; case gsNCHANNEL: expected = 0; break; case gsNAMED: case gsUNDEFINED: expected = -1; break; } make_int(op, expected); rc_decrement(picc_profile,"zset_outputintent"); return 0; }
164,635
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void hugetlb_vm_op_close(struct vm_area_struct *vma) { struct hstate *h = hstate_vma(vma); struct resv_map *reservations = vma_resv_map(vma); unsigned long reserve; unsigned long start; unsigned long end; if (reservations) { start = vma_hugecache_offset(h, vma, vma->vm_start); end = vma_hugecache_offset(h, vma, vma->vm_end); reserve = (end - start) - region_count(&reservations->regions, start, end); kref_put(&reservations->refs, resv_map_release); if (reserve) { hugetlb_acct_memory(h, -reserve); hugetlb_put_quota(vma->vm_file->f_mapping, reserve); } } } Commit Message: hugepages: fix use after free bug in "quota" handling hugetlbfs_{get,put}_quota() are badly named. They don't interact with the general quota handling code, and they don't much resemble its behaviour. Rather than being about maintaining limits on on-disk block usage by particular users, they are instead about maintaining limits on in-memory page usage (including anonymous MAP_PRIVATE copied-on-write pages) associated with a particular hugetlbfs filesystem instance. Worse, they work by having callbacks to the hugetlbfs filesystem code from the low-level page handling code, in particular from free_huge_page(). This is a layering violation of itself, but more importantly, if the kernel does a get_user_pages() on hugepages (which can happen from KVM amongst others), then the free_huge_page() can be delayed until after the associated inode has already been freed. If an unmount occurs at the wrong time, even the hugetlbfs superblock where the "quota" limits are stored may have been freed. Andrew Barry proposed a patch to fix this by having hugepages, instead of storing a pointer to their address_space and reaching the superblock from there, had the hugepages store pointers directly to the superblock, bumping the reference count as appropriate to avoid it being freed. Andrew Morton rejected that version, however, on the grounds that it made the existing layering violation worse. This is a reworked version of Andrew's patch, which removes the extra, and some of the existing, layering violation. It works by introducing the concept of a hugepage "subpool" at the lower hugepage mm layer - that is a finite logical pool of hugepages to allocate from. hugetlbfs now creates a subpool for each filesystem instance with a page limit set, and a pointer to the subpool gets added to each allocated hugepage, instead of the address_space pointer used now. The subpool has its own lifetime and is only freed once all pages in it _and_ all other references to it (i.e. superblocks) are gone. subpools are optional - a NULL subpool pointer is taken by the code to mean that no subpool limits are in effect. Previous discussion of this bug found in: "Fix refcounting in hugetlbfs quota handling.". See: https://lkml.org/lkml/2011/8/11/28 or http://marc.info/?l=linux-mm&m=126928970510627&w=1 v2: Fixed a bug spotted by Hillf Danton, and removed the extra parameter to alloc_huge_page() - since it already takes the vma, it is not necessary. Signed-off-by: Andrew Barry <[email protected]> Signed-off-by: David Gibson <[email protected]> Cc: Hugh Dickins <[email protected]> Cc: Mel Gorman <[email protected]> Cc: Minchan Kim <[email protected]> Cc: Hillf Danton <[email protected]> Cc: Paul Mackerras <[email protected]> Signed-off-by: Andrew Morton <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-399
static void hugetlb_vm_op_close(struct vm_area_struct *vma) { struct hstate *h = hstate_vma(vma); struct resv_map *reservations = vma_resv_map(vma); struct hugepage_subpool *spool = subpool_vma(vma); unsigned long reserve; unsigned long start; unsigned long end; if (reservations) { start = vma_hugecache_offset(h, vma, vma->vm_start); end = vma_hugecache_offset(h, vma, vma->vm_end); reserve = (end - start) - region_count(&reservations->regions, start, end); kref_put(&reservations->refs, resv_map_release); if (reserve) { hugetlb_acct_memory(h, -reserve); hugepage_subpool_put_pages(spool, reserve); } } }
165,612
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void ScreenOrientationDispatcherHost::OnLockRequest( RenderFrameHost* render_frame_host, blink::WebScreenOrientationLockType orientation, int request_id) { if (current_lock_) { NotifyLockError(current_lock_->request_id, blink::WebLockOrientationErrorCanceled); } current_lock_ = new LockInformation(request_id, render_frame_host->GetProcess()->GetID(), render_frame_host->GetRoutingID()); if (!provider_) { NotifyLockError(request_id, blink::WebLockOrientationErrorNotAvailable); return; } provider_->LockOrientation(request_id, orientation); } Commit Message: Cleanups in ScreenOrientationDispatcherHost. BUG=None Review URL: https://codereview.chromium.org/408213003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@284786 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-362
void ScreenOrientationDispatcherHost::OnLockRequest( RenderFrameHost* render_frame_host, blink::WebScreenOrientationLockType orientation, int request_id) { if (current_lock_) { NotifyLockError(current_lock_->request_id, blink::WebLockOrientationErrorCanceled); } if (!provider_) { NotifyLockError(request_id, blink::WebLockOrientationErrorNotAvailable); return; } current_lock_ = new LockInformation(request_id, render_frame_host->GetProcess()->GetID(), render_frame_host->GetRoutingID()); provider_->LockOrientation(request_id, orientation); }
171,177
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: PHP_FUNCTION(locale_get_display_language) { get_icu_disp_value_src_php( LOC_LANG_TAG , INTERNAL_FUNCTION_PARAM_PASSTHRU ); } Commit Message: Fix bug #72241: get_icu_value_internal out-of-bounds read CWE ID: CWE-125
PHP_FUNCTION(locale_get_display_language) PHP_FUNCTION(locale_get_display_language) { get_icu_disp_value_src_php( LOC_LANG_TAG , INTERNAL_FUNCTION_PARAM_PASSTHRU ); }
167,186
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void perf_event_task_output(struct perf_event *event, struct perf_task_event *task_event) { struct perf_output_handle handle; struct perf_sample_data sample; struct task_struct *task = task_event->task; int ret, size = task_event->event_id.header.size; perf_event_header__init_id(&task_event->event_id.header, &sample, event); ret = perf_output_begin(&handle, event, task_event->event_id.header.size, 0, 0); if (ret) goto out; task_event->event_id.pid = perf_event_pid(event, task); task_event->event_id.ppid = perf_event_pid(event, current); task_event->event_id.tid = perf_event_tid(event, task); task_event->event_id.ptid = perf_event_tid(event, current); perf_output_put(&handle, task_event->event_id); perf_event__output_id_sample(event, &handle, &sample); perf_output_end(&handle); out: task_event->event_id.header.size = size; } Commit Message: perf: Remove the nmi parameter from the swevent and overflow interface The nmi parameter indicated if we could do wakeups from the current context, if not, we would set some state and self-IPI and let the resulting interrupt do the wakeup. For the various event classes: - hardware: nmi=0; PMI is in fact an NMI or we run irq_work_run from the PMI-tail (ARM etc.) - tracepoint: nmi=0; since tracepoint could be from NMI context. - software: nmi=[0,1]; some, like the schedule thing cannot perform wakeups, and hence need 0. As one can see, there is very little nmi=1 usage, and the down-side of not using it is that on some platforms some software events can have a jiffy delay in wakeup (when arch_irq_work_raise isn't implemented). The up-side however is that we can remove the nmi parameter and save a bunch of conditionals in fast paths. Signed-off-by: Peter Zijlstra <[email protected]> Cc: Michael Cree <[email protected]> Cc: Will Deacon <[email protected]> Cc: Deng-Cheng Zhu <[email protected]> Cc: Anton Blanchard <[email protected]> Cc: Eric B Munson <[email protected]> Cc: Heiko Carstens <[email protected]> Cc: Paul Mundt <[email protected]> Cc: David S. Miller <[email protected]> Cc: Frederic Weisbecker <[email protected]> Cc: Jason Wessel <[email protected]> Cc: Don Zickus <[email protected]> Link: http://lkml.kernel.org/n/[email protected] Signed-off-by: Ingo Molnar <[email protected]> CWE ID: CWE-399
static void perf_event_task_output(struct perf_event *event, struct perf_task_event *task_event) { struct perf_output_handle handle; struct perf_sample_data sample; struct task_struct *task = task_event->task; int ret, size = task_event->event_id.header.size; perf_event_header__init_id(&task_event->event_id.header, &sample, event); ret = perf_output_begin(&handle, event, task_event->event_id.header.size, 0); if (ret) goto out; task_event->event_id.pid = perf_event_pid(event, task); task_event->event_id.ppid = perf_event_pid(event, current); task_event->event_id.tid = perf_event_tid(event, task); task_event->event_id.ptid = perf_event_tid(event, current); perf_output_put(&handle, task_event->event_id); perf_event__output_id_sample(event, &handle, &sample); perf_output_end(&handle); out: task_event->event_id.header.size = size; }
165,835
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: set_store_for_write(png_store *ps, png_infopp ppi, PNG_CONST char * volatile name) { anon_context(ps); Try { if (ps->pwrite != NULL) png_error(ps->pwrite, "write store already in use"); store_write_reset(ps); safecat(ps->wname, sizeof ps->wname, 0, name); /* Don't do the slow memory checks if doing a speed test, also if user * memory is not supported we can't do it anyway. */ # ifdef PNG_USER_MEM_SUPPORTED if (!ps->speed) ps->pwrite = png_create_write_struct_2(PNG_LIBPNG_VER_STRING, ps, store_error, store_warning, &ps->write_memory_pool, store_malloc, store_free); else # endif ps->pwrite = png_create_write_struct(PNG_LIBPNG_VER_STRING, ps, store_error, store_warning); png_set_write_fn(ps->pwrite, ps, store_write, store_flush); # ifdef PNG_SET_OPTION_SUPPORTED { int opt; for (opt=0; opt<ps->noptions; ++opt) if (png_set_option(ps->pwrite, ps->options[opt].option, ps->options[opt].setting) == PNG_OPTION_INVALID) png_error(ps->pwrite, "png option invalid"); } # endif if (ppi != NULL) *ppi = ps->piwrite = png_create_info_struct(ps->pwrite); } Catch_anonymous return NULL; return ps->pwrite; } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
set_store_for_write(png_store *ps, png_infopp ppi, set_store_for_write(png_store *ps, png_infopp ppi, const char *name) { anon_context(ps); Try { if (ps->pwrite != NULL) png_error(ps->pwrite, "write store already in use"); store_write_reset(ps); safecat(ps->wname, sizeof ps->wname, 0, name); /* Don't do the slow memory checks if doing a speed test, also if user * memory is not supported we can't do it anyway. */ # ifdef PNG_USER_MEM_SUPPORTED if (!ps->speed) ps->pwrite = png_create_write_struct_2(PNG_LIBPNG_VER_STRING, ps, store_error, store_warning, &ps->write_memory_pool, store_malloc, store_free); else # endif ps->pwrite = png_create_write_struct(PNG_LIBPNG_VER_STRING, ps, store_error, store_warning); png_set_write_fn(ps->pwrite, ps, store_write, store_flush); # ifdef PNG_SET_OPTION_SUPPORTED { int opt; for (opt=0; opt<ps->noptions; ++opt) if (png_set_option(ps->pwrite, ps->options[opt].option, ps->options[opt].setting) == PNG_OPTION_INVALID) png_error(ps->pwrite, "png option invalid"); } # endif if (ppi != NULL) *ppi = ps->piwrite = png_create_info_struct(ps->pwrite); } Catch_anonymous return NULL; return ps->pwrite; }
173,696
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: GC_API void * GC_CALL GC_generic_malloc(size_t lb, int k) { void * result; DCL_LOCK_STATE; if (EXPECT(GC_have_errors, FALSE)) GC_print_all_errors(); GC_INVOKE_FINALIZERS(); if (SMALL_OBJ(lb)) { LOCK(); result = GC_generic_malloc_inner((word)lb, k); UNLOCK(); } else { size_t lg; size_t lb_rounded; word n_blocks; GC_bool init; lg = ROUNDED_UP_GRANULES(lb); lb_rounded = GRANULES_TO_BYTES(lg); n_blocks = OBJ_SZ_TO_BLOCKS(lb_rounded); init = GC_obj_kinds[k].ok_init; LOCK(); result = (ptr_t)GC_alloc_large(lb_rounded, k, 0); if (0 != result) { if (GC_debugging_started) { BZERO(result, n_blocks * HBLKSIZE); } else { # ifdef THREADS /* Clear any memory that might be used for GC descriptors */ /* before we release the lock. */ ((word *)result)[0] = 0; ((word *)result)[1] = 0; ((word *)result)[GRANULES_TO_WORDS(lg)-1] = 0; ((word *)result)[GRANULES_TO_WORDS(lg)-2] = 0; # endif } } GC_bytes_allocd += lb_rounded; UNLOCK(); if (init && !GC_debugging_started && 0 != result) { BZERO(result, n_blocks * HBLKSIZE); } } if (0 == result) { return((*GC_get_oom_fn())(lb)); } else { return(result); } } Commit Message: Fix allocation size overflows due to rounding. * malloc.c (GC_generic_malloc): Check if the allocation size is rounded to a smaller value. * mallocx.c (GC_generic_malloc_ignore_off_page): Likewise. CWE ID: CWE-189
GC_API void * GC_CALL GC_generic_malloc(size_t lb, int k) { void * result; DCL_LOCK_STATE; if (EXPECT(GC_have_errors, FALSE)) GC_print_all_errors(); GC_INVOKE_FINALIZERS(); if (SMALL_OBJ(lb)) { LOCK(); result = GC_generic_malloc_inner((word)lb, k); UNLOCK(); } else { size_t lg; size_t lb_rounded; word n_blocks; GC_bool init; lg = ROUNDED_UP_GRANULES(lb); lb_rounded = GRANULES_TO_BYTES(lg); if (lb_rounded < lb) return((*GC_get_oom_fn())(lb)); n_blocks = OBJ_SZ_TO_BLOCKS(lb_rounded); init = GC_obj_kinds[k].ok_init; LOCK(); result = (ptr_t)GC_alloc_large(lb_rounded, k, 0); if (0 != result) { if (GC_debugging_started) { BZERO(result, n_blocks * HBLKSIZE); } else { # ifdef THREADS /* Clear any memory that might be used for GC descriptors */ /* before we release the lock. */ ((word *)result)[0] = 0; ((word *)result)[1] = 0; ((word *)result)[GRANULES_TO_WORDS(lg)-1] = 0; ((word *)result)[GRANULES_TO_WORDS(lg)-2] = 0; # endif } } GC_bytes_allocd += lb_rounded; UNLOCK(); if (init && !GC_debugging_started && 0 != result) { BZERO(result, n_blocks * HBLKSIZE); } } if (0 == result) { return((*GC_get_oom_fn())(lb)); } else { return(result); } }
169,878
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: EncodedJSValue JSC_HOST_CALL JSWebKitMutationObserverConstructor::constructJSWebKitMutationObserver(ExecState* exec) { if (exec->argumentCount() < 1) return throwVMError(exec, createTypeError(exec, "Not enough arguments")); JSObject* object = exec->argument(0).getObject(); if (!object) { setDOMException(exec, TYPE_MISMATCH_ERR); return JSValue::encode(jsUndefined()); } JSWebKitMutationObserverConstructor* jsConstructor = jsCast<JSWebKitMutationObserverConstructor*>(exec->callee()); RefPtr<MutationCallback> callback = JSMutationCallback::create(object, jsConstructor->globalObject()); return JSValue::encode(asObject(toJS(exec, jsConstructor->globalObject(), WebKitMutationObserver::create(callback.release())))); } Commit Message: [JSC] Implement a helper method createNotEnoughArgumentsError() https://bugs.webkit.org/show_bug.cgi?id=85102 Reviewed by Geoffrey Garen. In bug 84787, kbr@ requested to avoid hard-coding createTypeError(exec, "Not enough arguments") here and there. This patch implements createNotEnoughArgumentsError(exec) and uses it in JSC bindings. c.f. a corresponding bug for V8 bindings is bug 85097. Source/JavaScriptCore: * runtime/Error.cpp: (JSC::createNotEnoughArgumentsError): (JSC): * runtime/Error.h: (JSC): Source/WebCore: Test: bindings/scripts/test/TestObj.idl * bindings/scripts/CodeGeneratorJS.pm: Modified as described above. (GenerateArgumentsCountCheck): * bindings/js/JSDataViewCustom.cpp: Ditto. (WebCore::getDataViewMember): (WebCore::setDataViewMember): * bindings/js/JSDeprecatedPeerConnectionCustom.cpp: (WebCore::JSDeprecatedPeerConnectionConstructor::constructJSDeprecatedPeerConnection): * bindings/js/JSDirectoryEntryCustom.cpp: (WebCore::JSDirectoryEntry::getFile): (WebCore::JSDirectoryEntry::getDirectory): * bindings/js/JSSharedWorkerCustom.cpp: (WebCore::JSSharedWorkerConstructor::constructJSSharedWorker): * bindings/js/JSWebKitMutationObserverCustom.cpp: (WebCore::JSWebKitMutationObserverConstructor::constructJSWebKitMutationObserver): (WebCore::JSWebKitMutationObserver::observe): * bindings/js/JSWorkerCustom.cpp: (WebCore::JSWorkerConstructor::constructJSWorker): * bindings/scripts/test/JS/JSFloat64Array.cpp: Updated run-bindings-tests. (WebCore::jsFloat64ArrayPrototypeFunctionFoo): * bindings/scripts/test/JS/JSTestActiveDOMObject.cpp: (WebCore::jsTestActiveDOMObjectPrototypeFunctionExcitingFunction): (WebCore::jsTestActiveDOMObjectPrototypeFunctionPostMessage): * bindings/scripts/test/JS/JSTestCustomNamedGetter.cpp: (WebCore::jsTestCustomNamedGetterPrototypeFunctionAnotherFunction): * bindings/scripts/test/JS/JSTestEventTarget.cpp: (WebCore::jsTestEventTargetPrototypeFunctionItem): (WebCore::jsTestEventTargetPrototypeFunctionAddEventListener): (WebCore::jsTestEventTargetPrototypeFunctionRemoveEventListener): (WebCore::jsTestEventTargetPrototypeFunctionDispatchEvent): * bindings/scripts/test/JS/JSTestInterface.cpp: (WebCore::JSTestInterfaceConstructor::constructJSTestInterface): (WebCore::jsTestInterfacePrototypeFunctionSupplementalMethod2): * bindings/scripts/test/JS/JSTestMediaQueryListListener.cpp: (WebCore::jsTestMediaQueryListListenerPrototypeFunctionMethod): * bindings/scripts/test/JS/JSTestNamedConstructor.cpp: (WebCore::JSTestNamedConstructorNamedConstructor::constructJSTestNamedConstructor): * bindings/scripts/test/JS/JSTestObj.cpp: (WebCore::JSTestObjConstructor::constructJSTestObj): (WebCore::jsTestObjPrototypeFunctionVoidMethodWithArgs): (WebCore::jsTestObjPrototypeFunctionIntMethodWithArgs): (WebCore::jsTestObjPrototypeFunctionObjMethodWithArgs): (WebCore::jsTestObjPrototypeFunctionMethodWithSequenceArg): (WebCore::jsTestObjPrototypeFunctionMethodReturningSequence): (WebCore::jsTestObjPrototypeFunctionMethodThatRequiresAllArgsAndThrows): (WebCore::jsTestObjPrototypeFunctionSerializedValue): (WebCore::jsTestObjPrototypeFunctionIdbKey): (WebCore::jsTestObjPrototypeFunctionOptionsObject): (WebCore::jsTestObjPrototypeFunctionAddEventListener): (WebCore::jsTestObjPrototypeFunctionRemoveEventListener): (WebCore::jsTestObjPrototypeFunctionMethodWithNonOptionalArgAndOptionalArg): (WebCore::jsTestObjPrototypeFunctionMethodWithNonOptionalArgAndTwoOptionalArgs): (WebCore::jsTestObjPrototypeFunctionMethodWithCallbackArg): (WebCore::jsTestObjPrototypeFunctionMethodWithNonCallbackArgAndCallbackArg): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod1): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod2): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod3): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod4): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod5): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod6): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod7): (WebCore::jsTestObjConstructorFunctionClassMethod2): (WebCore::jsTestObjConstructorFunctionOverloadedMethod11): (WebCore::jsTestObjConstructorFunctionOverloadedMethod12): (WebCore::jsTestObjPrototypeFunctionMethodWithUnsignedLongArray): (WebCore::jsTestObjPrototypeFunctionConvert1): (WebCore::jsTestObjPrototypeFunctionConvert2): (WebCore::jsTestObjPrototypeFunctionConvert3): (WebCore::jsTestObjPrototypeFunctionConvert4): (WebCore::jsTestObjPrototypeFunctionConvert5): (WebCore::jsTestObjPrototypeFunctionStrictFunction): * bindings/scripts/test/JS/JSTestSerializedScriptValueInterface.cpp: (WebCore::JSTestSerializedScriptValueInterfaceConstructor::constructJSTestSerializedScriptValueInterface): (WebCore::jsTestSerializedScriptValueInterfacePrototypeFunctionAcceptTransferList): git-svn-id: svn://svn.chromium.org/blink/trunk@115536 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-20
EncodedJSValue JSC_HOST_CALL JSWebKitMutationObserverConstructor::constructJSWebKitMutationObserver(ExecState* exec) { if (exec->argumentCount() < 1) return throwVMError(exec, createNotEnoughArgumentsError(exec)); JSObject* object = exec->argument(0).getObject(); if (!object) { setDOMException(exec, TYPE_MISMATCH_ERR); return JSValue::encode(jsUndefined()); } JSWebKitMutationObserverConstructor* jsConstructor = jsCast<JSWebKitMutationObserverConstructor*>(exec->callee()); RefPtr<MutationCallback> callback = JSMutationCallback::create(object, jsConstructor->globalObject()); return JSValue::encode(asObject(toJS(exec, jsConstructor->globalObject(), WebKitMutationObserver::create(callback.release())))); }
170,563
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int msg_parse_fetch(struct ImapHeader *h, char *s) { char tmp[SHORT_STRING]; char *ptmp = NULL; if (!s) return -1; while (*s) { SKIPWS(s); if (mutt_str_strncasecmp("FLAGS", s, 5) == 0) { s = msg_parse_flags(h, s); if (!s) return -1; } else if (mutt_str_strncasecmp("UID", s, 3) == 0) { s += 3; SKIPWS(s); if (mutt_str_atoui(s, &h->data->uid) < 0) return -1; s = imap_next_word(s); } else if (mutt_str_strncasecmp("INTERNALDATE", s, 12) == 0) { s += 12; SKIPWS(s); if (*s != '\"') { mutt_debug(1, "bogus INTERNALDATE entry: %s\n", s); return -1; } s++; ptmp = tmp; while (*s && *s != '\"') *ptmp++ = *s++; if (*s != '\"') return -1; s++; /* skip past the trailing " */ *ptmp = '\0'; h->received = mutt_date_parse_imap(tmp); } else if (mutt_str_strncasecmp("RFC822.SIZE", s, 11) == 0) { s += 11; SKIPWS(s); ptmp = tmp; while (isdigit((unsigned char) *s)) *ptmp++ = *s++; *ptmp = '\0'; if (mutt_str_atol(tmp, &h->content_length) < 0) return -1; } else if ((mutt_str_strncasecmp("BODY", s, 4) == 0) || (mutt_str_strncasecmp("RFC822.HEADER", s, 13) == 0)) { /* handle above, in msg_fetch_header */ return -2; } else if (*s == ')') s++; /* end of request */ else if (*s) { /* got something i don't understand */ imap_error("msg_parse_fetch", s); return -1; } } return 0; } Commit Message: Don't overflow stack buffer in msg_parse_fetch CWE ID: CWE-119
static int msg_parse_fetch(struct ImapHeader *h, char *s) { char tmp[SHORT_STRING]; char *ptmp = NULL; if (!s) return -1; while (*s) { SKIPWS(s); if (mutt_str_strncasecmp("FLAGS", s, 5) == 0) { s = msg_parse_flags(h, s); if (!s) return -1; } else if (mutt_str_strncasecmp("UID", s, 3) == 0) { s += 3; SKIPWS(s); if (mutt_str_atoui(s, &h->data->uid) < 0) return -1; s = imap_next_word(s); } else if (mutt_str_strncasecmp("INTERNALDATE", s, 12) == 0) { s += 12; SKIPWS(s); if (*s != '\"') { mutt_debug(1, "bogus INTERNALDATE entry: %s\n", s); return -1; } s++; ptmp = tmp; while (*s && (*s != '\"') && (ptmp != (tmp + sizeof(tmp) - 1))) *ptmp++ = *s++; if (*s != '\"') return -1; s++; /* skip past the trailing " */ *ptmp = '\0'; h->received = mutt_date_parse_imap(tmp); } else if (mutt_str_strncasecmp("RFC822.SIZE", s, 11) == 0) { s += 11; SKIPWS(s); ptmp = tmp; while (isdigit((unsigned char) *s) && (ptmp != (tmp + sizeof(tmp) - 1))) *ptmp++ = *s++; *ptmp = '\0'; if (mutt_str_atol(tmp, &h->content_length) < 0) return -1; } else if ((mutt_str_strncasecmp("BODY", s, 4) == 0) || (mutt_str_strncasecmp("RFC822.HEADER", s, 13) == 0)) { /* handle above, in msg_fetch_header */ return -2; } else if (*s == ')') s++; /* end of request */ else if (*s) { /* got something i don't understand */ imap_error("msg_parse_fetch", s); return -1; } } return 0; }
169,132
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void FragmentPaintPropertyTreeBuilder::UpdateEffect() { DCHECK(properties_); const ComputedStyle& style = object_.StyleRef(); if (NeedsPaintPropertyUpdate()) { const auto* output_clip = object_.IsSVGChild() ? context_.current.clip : nullptr; if (NeedsEffect(object_)) { base::Optional<IntRect> mask_clip = CSSMaskPainter::MaskBoundingBox( object_, context_.current.paint_offset); bool has_clip_path = style.ClipPath() && fragment_data_.ClipPathBoundingBox(); bool has_spv1_composited_clip_path = has_clip_path && object_.HasLayer() && ToLayoutBoxModelObject(object_).Layer()->GetCompositedLayerMapping(); bool has_mask_based_clip_path = has_clip_path && !fragment_data_.ClipPathPath(); base::Optional<IntRect> clip_path_clip; if (has_spv1_composited_clip_path || has_mask_based_clip_path) { clip_path_clip = fragment_data_.ClipPathBoundingBox(); } if ((mask_clip || clip_path_clip) && RuntimeEnabledFeatures::SlimmingPaintV175Enabled()) { IntRect combined_clip = mask_clip ? *mask_clip : *clip_path_clip; if (mask_clip && clip_path_clip) combined_clip.Intersect(*clip_path_clip); OnUpdateClip(properties_->UpdateMaskClip( context_.current.clip, ClipPaintPropertyNode::State{context_.current.transform, FloatRoundedRect(combined_clip)})); output_clip = properties_->MaskClip(); } else { OnClearClip(properties_->ClearMaskClip()); } EffectPaintPropertyNode::State state; state.local_transform_space = context_.current.transform; state.output_clip = output_clip; state.opacity = style.Opacity(); if (object_.IsBlendingAllowed()) { state.blend_mode = WebCoreCompositeToSkiaComposite( kCompositeSourceOver, style.GetBlendMode()); } if (RuntimeEnabledFeatures::SlimmingPaintV2Enabled() || RuntimeEnabledFeatures::BlinkGenPropertyTreesEnabled()) { if (CompositingReasonFinder::RequiresCompositingForOpacityAnimation( style)) { state.direct_compositing_reasons = CompositingReason::kActiveOpacityAnimation; } state.compositor_element_id = CompositorElementIdFromUniqueObjectId( object_.UniqueId(), CompositorElementIdNamespace::kPrimary); } OnUpdate( properties_->UpdateEffect(context_.current_effect, std::move(state))); if (mask_clip || has_spv1_composited_clip_path) { EffectPaintPropertyNode::State mask_state; mask_state.local_transform_space = context_.current.transform; mask_state.output_clip = output_clip; mask_state.color_filter = CSSMaskPainter::MaskColorFilter(object_); mask_state.blend_mode = SkBlendMode::kDstIn; if (RuntimeEnabledFeatures::SlimmingPaintV2Enabled() || RuntimeEnabledFeatures::BlinkGenPropertyTreesEnabled()) { mask_state.compositor_element_id = CompositorElementIdFromUniqueObjectId( object_.UniqueId(), CompositorElementIdNamespace::kEffectMask); } OnUpdate(properties_->UpdateMask(properties_->Effect(), std::move(mask_state))); } else { OnClear(properties_->ClearMask()); } if (has_mask_based_clip_path) { const EffectPaintPropertyNode* parent = has_spv1_composited_clip_path ? properties_->Mask() : properties_->Effect(); EffectPaintPropertyNode::State clip_path_state; clip_path_state.local_transform_space = context_.current.transform; clip_path_state.output_clip = output_clip; clip_path_state.blend_mode = SkBlendMode::kDstIn; if (RuntimeEnabledFeatures::SlimmingPaintV2Enabled() || RuntimeEnabledFeatures::BlinkGenPropertyTreesEnabled()) { clip_path_state.compositor_element_id = CompositorElementIdFromUniqueObjectId( object_.UniqueId(), CompositorElementIdNamespace::kEffectClipPath); } OnUpdate( properties_->UpdateClipPath(parent, std::move(clip_path_state))); } else { OnClear(properties_->ClearClipPath()); } } else { OnClear(properties_->ClearEffect()); OnClear(properties_->ClearMask()); OnClear(properties_->ClearClipPath()); OnClearClip(properties_->ClearMaskClip()); } } if (properties_->Effect()) { context_.current_effect = properties_->Effect(); if (properties_->MaskClip()) { context_.current.clip = context_.absolute_position.clip = context_.fixed_position.clip = properties_->MaskClip(); } } } Commit Message: Reland "[CI] Make paint property nodes non-ref-counted" This reverts commit 887383b30842d9d9006e11bb6932660a3cb5b1b7. Reason for revert: Retry in M69. Original change's description: > Revert "[CI] Make paint property nodes non-ref-counted" > > This reverts commit 70fc0b018c9517558b7aa2be00edf2debb449123. > > Reason for revert: Caused bugs found by clusterfuzz > > Original change's description: > > [CI] Make paint property nodes non-ref-counted > > > > Now all paint property nodes are owned by ObjectPaintProperties > > (and LocalFrameView temporarily before removing non-RLS mode). > > Others just use raw pointers or references. > > > > Bug: 833496 > > Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2 > > Change-Id: I2d544fe153bb94698623248748df63c8aa2081ae > > Reviewed-on: https://chromium-review.googlesource.com/1031101 > > Reviewed-by: Tien-Ren Chen <[email protected]> > > Commit-Queue: Xianzhu Wang <[email protected]> > > Cr-Commit-Position: refs/heads/master@{#554626} > > [email protected],[email protected],[email protected] > > Change-Id: I02bb50d6744cb81a797246a0116b677e80a3c69f > No-Presubmit: true > No-Tree-Checks: true > No-Try: true > Bug: 833496,837932,837943 > Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2 > Reviewed-on: https://chromium-review.googlesource.com/1034292 > Reviewed-by: Xianzhu Wang <[email protected]> > Commit-Queue: Xianzhu Wang <[email protected]> > Cr-Commit-Position: refs/heads/master@{#554653} [email protected],[email protected],[email protected] # Not skipping CQ checks because original CL landed > 1 day ago. Bug: 833496, 837932, 837943 Change-Id: I0b4ef70db1f1f211ba97c30d617225355c750992 Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2 Reviewed-on: https://chromium-review.googlesource.com/1083491 Commit-Queue: Xianzhu Wang <[email protected]> Reviewed-by: Xianzhu Wang <[email protected]> Cr-Commit-Position: refs/heads/master@{#563930} CWE ID:
void FragmentPaintPropertyTreeBuilder::UpdateEffect() { DCHECK(properties_); const ComputedStyle& style = object_.StyleRef(); if (NeedsPaintPropertyUpdate()) { const auto* output_clip = object_.IsSVGChild() ? context_.current.clip : nullptr; if (NeedsEffect(object_)) { base::Optional<IntRect> mask_clip = CSSMaskPainter::MaskBoundingBox( object_, context_.current.paint_offset); bool has_clip_path = style.ClipPath() && fragment_data_.ClipPathBoundingBox(); bool has_spv1_composited_clip_path = has_clip_path && object_.HasLayer() && ToLayoutBoxModelObject(object_).Layer()->GetCompositedLayerMapping(); bool has_mask_based_clip_path = has_clip_path && !fragment_data_.ClipPathPath(); base::Optional<IntRect> clip_path_clip; if (has_spv1_composited_clip_path || has_mask_based_clip_path) { clip_path_clip = fragment_data_.ClipPathBoundingBox(); } if ((mask_clip || clip_path_clip) && RuntimeEnabledFeatures::SlimmingPaintV175Enabled()) { IntRect combined_clip = mask_clip ? *mask_clip : *clip_path_clip; if (mask_clip && clip_path_clip) combined_clip.Intersect(*clip_path_clip); OnUpdateClip(properties_->UpdateMaskClip( *context_.current.clip, ClipPaintPropertyNode::State{context_.current.transform, FloatRoundedRect(combined_clip)})); output_clip = properties_->MaskClip(); } else { OnClearClip(properties_->ClearMaskClip()); } EffectPaintPropertyNode::State state; state.local_transform_space = context_.current.transform; state.output_clip = output_clip; state.opacity = style.Opacity(); if (object_.IsBlendingAllowed()) { state.blend_mode = WebCoreCompositeToSkiaComposite( kCompositeSourceOver, style.GetBlendMode()); } if (RuntimeEnabledFeatures::SlimmingPaintV2Enabled() || RuntimeEnabledFeatures::BlinkGenPropertyTreesEnabled()) { if (CompositingReasonFinder::RequiresCompositingForOpacityAnimation( style)) { state.direct_compositing_reasons = CompositingReason::kActiveOpacityAnimation; } state.compositor_element_id = CompositorElementIdFromUniqueObjectId( object_.UniqueId(), CompositorElementIdNamespace::kPrimary); } OnUpdate(properties_->UpdateEffect(*context_.current_effect, std::move(state))); if (mask_clip || has_spv1_composited_clip_path) { EffectPaintPropertyNode::State mask_state; mask_state.local_transform_space = context_.current.transform; mask_state.output_clip = output_clip; mask_state.color_filter = CSSMaskPainter::MaskColorFilter(object_); mask_state.blend_mode = SkBlendMode::kDstIn; if (RuntimeEnabledFeatures::SlimmingPaintV2Enabled() || RuntimeEnabledFeatures::BlinkGenPropertyTreesEnabled()) { mask_state.compositor_element_id = CompositorElementIdFromUniqueObjectId( object_.UniqueId(), CompositorElementIdNamespace::kEffectMask); } OnUpdate(properties_->UpdateMask(*properties_->Effect(), std::move(mask_state))); } else { OnClear(properties_->ClearMask()); } if (has_mask_based_clip_path) { const EffectPaintPropertyNode& parent = has_spv1_composited_clip_path ? *properties_->Mask() : *properties_->Effect(); EffectPaintPropertyNode::State clip_path_state; clip_path_state.local_transform_space = context_.current.transform; clip_path_state.output_clip = output_clip; clip_path_state.blend_mode = SkBlendMode::kDstIn; if (RuntimeEnabledFeatures::SlimmingPaintV2Enabled() || RuntimeEnabledFeatures::BlinkGenPropertyTreesEnabled()) { clip_path_state.compositor_element_id = CompositorElementIdFromUniqueObjectId( object_.UniqueId(), CompositorElementIdNamespace::kEffectClipPath); } OnUpdate( properties_->UpdateClipPath(parent, std::move(clip_path_state))); } else { OnClear(properties_->ClearClipPath()); } } else { OnClear(properties_->ClearEffect()); OnClear(properties_->ClearMask()); OnClear(properties_->ClearClipPath()); OnClearClip(properties_->ClearMaskClip()); } } if (properties_->Effect()) { context_.current_effect = properties_->Effect(); if (properties_->MaskClip()) { context_.current.clip = context_.absolute_position.clip = context_.fixed_position.clip = properties_->MaskClip(); } } }
171,795
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: IMPEG2D_ERROR_CODES_T impeg2d_dec_d_slice(dec_state_t *ps_dec) { UWORD32 i; yuv_buf_t *ps_cur_frm_buf = &ps_dec->s_cur_frm_buf; stream_t *ps_stream = &ps_dec->s_bit_stream; UWORD8 *pu1_vld_buf; WORD16 i2_dc_diff; UWORD32 u4_frame_width = ps_dec->u2_frame_width; UWORD32 u4_frm_offset = 0; if(ps_dec->u2_picture_structure != FRAME_PICTURE) { u4_frame_width <<= 1; if(ps_dec->u2_picture_structure == BOTTOM_FIELD) { u4_frm_offset = ps_dec->u2_frame_width; } } do { UWORD32 u4_x_offset, u4_y_offset; UWORD32 u4_blk_pos; WORD16 i2_dc_val; UWORD32 u4_dst_x_offset = u4_frm_offset + (ps_dec->u2_mb_x << 4); UWORD32 u4_dst_y_offset = (ps_dec->u2_mb_y << 4) * u4_frame_width; UWORD8 *pu1_vld_buf8 = ps_cur_frm_buf->pu1_y + u4_dst_x_offset + u4_dst_y_offset; UWORD32 u4_dst_wd = u4_frame_width; /*------------------------------------------------------------------*/ /* Discard the Macroblock stuffing in case of MPEG-1 stream */ /*------------------------------------------------------------------*/ while(impeg2d_bit_stream_nxt(ps_stream,MB_STUFFING_CODE_LEN) == MB_STUFFING_CODE) impeg2d_bit_stream_flush(ps_stream,MB_STUFFING_CODE_LEN); /*------------------------------------------------------------------*/ /* Flush 2 bits from bitstream [MB_Type and MacroBlockAddrIncrement]*/ /*------------------------------------------------------------------*/ impeg2d_bit_stream_flush(ps_stream,1); if(impeg2d_bit_stream_get(ps_stream, 1) != 0x01) { /* Ignore and continue decoding. */ } /* Process LUMA blocks of the MB */ for(i = 0; i < NUM_LUMA_BLKS; ++i) { u4_x_offset = gai2_impeg2_blk_x_off[i]; u4_y_offset = gai2_impeg2_blk_y_off_frm[i] ; u4_blk_pos = (u4_y_offset * u4_dst_wd) + u4_x_offset; pu1_vld_buf = pu1_vld_buf8 + u4_blk_pos; i2_dc_diff = impeg2d_get_luma_dc_diff(ps_stream); i2_dc_val = ps_dec->u2_def_dc_pred[Y_LUMA] + i2_dc_diff; ps_dec->u2_def_dc_pred[Y_LUMA] = i2_dc_val; i2_dc_val = CLIP_U8(i2_dc_val); ps_dec->pf_memset_8bit_8x8_block(pu1_vld_buf, i2_dc_val, u4_dst_wd); } /* Process U block of the MB */ u4_dst_x_offset >>= 1; u4_dst_y_offset >>= 2; u4_dst_wd >>= 1; pu1_vld_buf = ps_cur_frm_buf->pu1_u + u4_dst_x_offset + u4_dst_y_offset; i2_dc_diff = impeg2d_get_chroma_dc_diff(ps_stream); i2_dc_val = ps_dec->u2_def_dc_pred[U_CHROMA] + i2_dc_diff; ps_dec->u2_def_dc_pred[U_CHROMA] = i2_dc_val; i2_dc_val = CLIP_U8(i2_dc_val); ps_dec->pf_memset_8bit_8x8_block(pu1_vld_buf, i2_dc_val, u4_dst_wd); /* Process V block of the MB */ pu1_vld_buf = ps_cur_frm_buf->pu1_v + u4_dst_x_offset + u4_dst_y_offset; i2_dc_diff = impeg2d_get_chroma_dc_diff(ps_stream); i2_dc_val = ps_dec->u2_def_dc_pred[V_CHROMA] + i2_dc_diff; ps_dec->u2_def_dc_pred[V_CHROMA] = i2_dc_val; i2_dc_val = CLIP_U8(i2_dc_val); ps_dec->pf_memset_8bit_8x8_block(pu1_vld_buf, i2_dc_val, u4_dst_wd); /* Common MB processing Steps */ ps_dec->u2_num_mbs_left--; ps_dec->u2_mb_x++; if(ps_dec->s_bit_stream.u4_offset > ps_dec->s_bit_stream.u4_max_offset) { return IMPEG2D_BITSTREAM_BUFF_EXCEEDED_ERR; } else if (ps_dec->u2_mb_x == ps_dec->u2_num_horiz_mb) { ps_dec->u2_mb_x = 0; ps_dec->u2_mb_y++; } /* Flush end of macro block */ impeg2d_bit_stream_flush(ps_stream,1); } while(ps_dec->u2_num_mbs_left != 0 && impeg2d_bit_stream_nxt(&ps_dec->s_bit_stream,23) != 0x0); return (IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE; }/* End of impeg2d_dec_d_slice() */ Commit Message: Fixed bit stream access to make sure that it is not read beyond the allocated size. Bug: 25765591 Change-Id: I98c23a3c3f84f6710f29bffe5ed73adcf51d47f6 CWE ID: CWE-254
IMPEG2D_ERROR_CODES_T impeg2d_dec_d_slice(dec_state_t *ps_dec) { UWORD32 i; yuv_buf_t *ps_cur_frm_buf = &ps_dec->s_cur_frm_buf; stream_t *ps_stream = &ps_dec->s_bit_stream; UWORD8 *pu1_vld_buf; WORD16 i2_dc_diff; UWORD32 u4_frame_width = ps_dec->u2_frame_width; UWORD32 u4_frm_offset = 0; if(ps_dec->u2_picture_structure != FRAME_PICTURE) { u4_frame_width <<= 1; if(ps_dec->u2_picture_structure == BOTTOM_FIELD) { u4_frm_offset = ps_dec->u2_frame_width; } } do { UWORD32 u4_x_offset, u4_y_offset; UWORD32 u4_blk_pos; WORD16 i2_dc_val; UWORD32 u4_dst_x_offset = u4_frm_offset + (ps_dec->u2_mb_x << 4); UWORD32 u4_dst_y_offset = (ps_dec->u2_mb_y << 4) * u4_frame_width; UWORD8 *pu1_vld_buf8 = ps_cur_frm_buf->pu1_y + u4_dst_x_offset + u4_dst_y_offset; UWORD32 u4_dst_wd = u4_frame_width; /*------------------------------------------------------------------*/ /* Discard the Macroblock stuffing in case of MPEG-1 stream */ /*------------------------------------------------------------------*/ while(impeg2d_bit_stream_nxt(ps_stream,MB_STUFFING_CODE_LEN) == MB_STUFFING_CODE && ps_stream->u4_offset < ps_stream->u4_max_offset) impeg2d_bit_stream_flush(ps_stream,MB_STUFFING_CODE_LEN); /*------------------------------------------------------------------*/ /* Flush 2 bits from bitstream [MB_Type and MacroBlockAddrIncrement]*/ /*------------------------------------------------------------------*/ impeg2d_bit_stream_flush(ps_stream,1); if(impeg2d_bit_stream_get(ps_stream, 1) != 0x01) { /* Ignore and continue decoding. */ } /* Process LUMA blocks of the MB */ for(i = 0; i < NUM_LUMA_BLKS; ++i) { u4_x_offset = gai2_impeg2_blk_x_off[i]; u4_y_offset = gai2_impeg2_blk_y_off_frm[i] ; u4_blk_pos = (u4_y_offset * u4_dst_wd) + u4_x_offset; pu1_vld_buf = pu1_vld_buf8 + u4_blk_pos; i2_dc_diff = impeg2d_get_luma_dc_diff(ps_stream); i2_dc_val = ps_dec->u2_def_dc_pred[Y_LUMA] + i2_dc_diff; ps_dec->u2_def_dc_pred[Y_LUMA] = i2_dc_val; i2_dc_val = CLIP_U8(i2_dc_val); ps_dec->pf_memset_8bit_8x8_block(pu1_vld_buf, i2_dc_val, u4_dst_wd); } /* Process U block of the MB */ u4_dst_x_offset >>= 1; u4_dst_y_offset >>= 2; u4_dst_wd >>= 1; pu1_vld_buf = ps_cur_frm_buf->pu1_u + u4_dst_x_offset + u4_dst_y_offset; i2_dc_diff = impeg2d_get_chroma_dc_diff(ps_stream); i2_dc_val = ps_dec->u2_def_dc_pred[U_CHROMA] + i2_dc_diff; ps_dec->u2_def_dc_pred[U_CHROMA] = i2_dc_val; i2_dc_val = CLIP_U8(i2_dc_val); ps_dec->pf_memset_8bit_8x8_block(pu1_vld_buf, i2_dc_val, u4_dst_wd); /* Process V block of the MB */ pu1_vld_buf = ps_cur_frm_buf->pu1_v + u4_dst_x_offset + u4_dst_y_offset; i2_dc_diff = impeg2d_get_chroma_dc_diff(ps_stream); i2_dc_val = ps_dec->u2_def_dc_pred[V_CHROMA] + i2_dc_diff; ps_dec->u2_def_dc_pred[V_CHROMA] = i2_dc_val; i2_dc_val = CLIP_U8(i2_dc_val); ps_dec->pf_memset_8bit_8x8_block(pu1_vld_buf, i2_dc_val, u4_dst_wd); /* Common MB processing Steps */ ps_dec->u2_num_mbs_left--; ps_dec->u2_mb_x++; if(ps_dec->s_bit_stream.u4_offset > ps_dec->s_bit_stream.u4_max_offset) { return IMPEG2D_BITSTREAM_BUFF_EXCEEDED_ERR; } else if (ps_dec->u2_mb_x == ps_dec->u2_num_horiz_mb) { ps_dec->u2_mb_x = 0; ps_dec->u2_mb_y++; } /* Flush end of macro block */ impeg2d_bit_stream_flush(ps_stream,1); } while(ps_dec->u2_num_mbs_left != 0 && impeg2d_bit_stream_nxt(&ps_dec->s_bit_stream,23) != 0x0); return (IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE; }/* End of impeg2d_dec_d_slice() */
173,943
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static MagickBooleanType ReadPSDChannel(Image *image, const ImageInfo *image_info,const PSDInfo *psd_info,LayerInfo* layer_info, const size_t channel,const PSDCompressionType compression, ExceptionInfo *exception) { Image *channel_image, *mask; MagickOffsetType offset; MagickBooleanType status; channel_image=image; mask=(Image *) NULL; if (layer_info->channel_info[channel].type < -1) { const char *option; /* Ignore mask that is not a user supplied layer mask, if the mask is disabled or if the flags have unsupported values. */ option=GetImageOption(image_info,"psd:preserve-opacity-mask"); if ((layer_info->channel_info[channel].type != -2) || (layer_info->mask.flags > 2) || ((layer_info->mask.flags & 0x02) && (IsStringTrue(option) == MagickFalse))) { SeekBlob(image,layer_info->channel_info[channel].size-2,SEEK_CUR); return(MagickTrue); } mask=CloneImage(image,layer_info->mask.page.width, layer_info->mask.page.height,MagickFalse,exception); mask->matte=MagickFalse; channel_image=mask; } offset=TellBlob(image); status=MagickTrue; switch(compression) { case Raw: status=ReadPSDChannelRaw(channel_image,psd_info->channels, layer_info->channel_info[channel].type,exception); break; case RLE: { MagickOffsetType *sizes; sizes=ReadPSDRLESizes(channel_image,psd_info,channel_image->rows); if (sizes == (MagickOffsetType *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); status=ReadPSDChannelRLE(channel_image,psd_info, layer_info->channel_info[channel].type,sizes,exception); sizes=(MagickOffsetType *) RelinquishMagickMemory(sizes); } break; case ZipWithPrediction: case ZipWithoutPrediction: #ifdef MAGICKCORE_ZLIB_DELEGATE status=ReadPSDChannelZip(channel_image,layer_info->channels, layer_info->channel_info[channel].type,compression, layer_info->channel_info[channel].size-2,exception); #else (void) ThrowMagickException(exception,GetMagickModule(), MissingDelegateWarning,"DelegateLibrarySupportNotBuiltIn", "'%s' (ZLIB)",image->filename); #endif break; default: (void) ThrowMagickException(exception,GetMagickModule(),TypeWarning, "CompressionNotSupported","'%.20g'",(double) compression); break; } SeekBlob(image,offset+layer_info->channel_info[channel].size-2,SEEK_SET); if (status == MagickFalse) { if (mask != (Image *) NULL) DestroyImage(mask); ThrowBinaryException(CoderError,"UnableToDecompressImage", image->filename); } layer_info->mask.image=mask; return(status); } Commit Message: Added missing null check. CWE ID: CWE-476
static MagickBooleanType ReadPSDChannel(Image *image, const ImageInfo *image_info,const PSDInfo *psd_info,LayerInfo* layer_info, const size_t channel,const PSDCompressionType compression, ExceptionInfo *exception) { Image *channel_image, *mask; MagickOffsetType offset; MagickBooleanType status; channel_image=image; mask=(Image *) NULL; if (layer_info->channel_info[channel].type < -1) { const char *option; /* Ignore mask that is not a user supplied layer mask, if the mask is disabled or if the flags have unsupported values. */ option=GetImageOption(image_info,"psd:preserve-opacity-mask"); if ((layer_info->channel_info[channel].type != -2) || (layer_info->mask.flags > 2) || ((layer_info->mask.flags & 0x02) && (IsStringTrue(option) == MagickFalse))) { SeekBlob(image,layer_info->channel_info[channel].size-2,SEEK_CUR); return(MagickTrue); } mask=CloneImage(image,layer_info->mask.page.width, layer_info->mask.page.height,MagickFalse,exception); if (mask != (Image *) NULL) { mask->matte=MagickFalse; channel_image=mask; } } offset=TellBlob(image); status=MagickTrue; switch(compression) { case Raw: status=ReadPSDChannelRaw(channel_image,psd_info->channels, layer_info->channel_info[channel].type,exception); break; case RLE: { MagickOffsetType *sizes; sizes=ReadPSDRLESizes(channel_image,psd_info,channel_image->rows); if (sizes == (MagickOffsetType *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); status=ReadPSDChannelRLE(channel_image,psd_info, layer_info->channel_info[channel].type,sizes,exception); sizes=(MagickOffsetType *) RelinquishMagickMemory(sizes); } break; case ZipWithPrediction: case ZipWithoutPrediction: #ifdef MAGICKCORE_ZLIB_DELEGATE status=ReadPSDChannelZip(channel_image,layer_info->channels, layer_info->channel_info[channel].type,compression, layer_info->channel_info[channel].size-2,exception); #else (void) ThrowMagickException(exception,GetMagickModule(), MissingDelegateWarning,"DelegateLibrarySupportNotBuiltIn", "'%s' (ZLIB)",image->filename); #endif break; default: (void) ThrowMagickException(exception,GetMagickModule(),TypeWarning, "CompressionNotSupported","'%.20g'",(double) compression); break; } SeekBlob(image,offset+layer_info->channel_info[channel].size-2,SEEK_SET); if (status == MagickFalse) { if (mask != (Image *) NULL) DestroyImage(mask); ThrowBinaryException(CoderError,"UnableToDecompressImage", image->filename); } layer_info->mask.image=mask; return(status); }
168,332
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void ExtensionTtsController::SetPlatformImpl( ExtensionTtsPlatformImpl* platform_impl) { platform_impl_ = platform_impl; } Commit Message: Extend TTS extension API to support richer events returned from the engine to the client. Previously we just had a completed event; this adds start, word boundary, sentence boundary, and marker boundary. In addition, interrupted and canceled, which were previously errors, now become events. Mac and Windows implementations extended to support as many of these events as possible. BUG=67713 BUG=70198 BUG=75106 BUG=83404 TEST=Updates all TTS API tests to be event-based, and adds new tests. Review URL: http://codereview.chromium.org/6792014 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@91665 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
void ExtensionTtsController::SetPlatformImpl(
170,386
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void PlatformSensorProviderLinux::CreateSensorAndNotify( mojom::SensorType type, SensorInfoLinux* sensor_device) { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); scoped_refptr<PlatformSensorLinux> sensor; mojo::ScopedSharedBufferMapping mapping = MapSharedBufferForType(type); if (sensor_device && mapping && StartPollingThread()) { sensor = new PlatformSensorLinux(type, std::move(mapping), this, sensor_device, polling_thread_->task_runner()); } NotifySensorCreated(type, sensor); } Commit Message: android: Fix sensors in device service. This patch fixes a bug that prevented more than one sensor data to be available at once when using the device motion/orientation API. The issue was introduced by this other patch [1] which fixed some security-related issues in the way shared memory region handles are managed throughout Chromium (more details at https://crbug.com/789959). The device service´s sensor implementation doesn´t work correctly because it assumes it is possible to create a writable mapping of a given shared memory region at any time. This assumption is not correct on Android, once an Ashmem region has been turned read-only, such mappings are no longer possible. To fix the implementation, this CL changes the following: - PlatformSensor used to require moving a mojo::ScopedSharedBufferMapping into the newly-created instance. Said mapping being owned by and destroyed with the PlatformSensor instance. With this patch, the constructor instead takes a single pointer to the corresponding SensorReadingSharedBuffer, i.e. the area in memory where the sensor-specific reading data is located, and can be either updated or read-from. Note that the PlatformSensor does not own the mapping anymore. - PlatformSensorProviderBase holds the *single* writable mapping that is used to store all SensorReadingSharedBuffer buffers. It is created just after the region itself, and thus can be used even after the region's access mode has been changed to read-only. Addresses within the mapping will be passed to PlatformSensor constructors, computed from the mapping's base address plus a sensor-specific offset. The mapping is now owned by the PlatformSensorProviderBase instance. Note that, security-wise, nothing changes, because all mojo::ScopedSharedBufferMapping before the patch actually pointed to the same writable-page in memory anyway. Since unit or integration tests didn't catch the regression when [1] was submitted, this patch was tested manually by running a newly-built Chrome apk in the Android emulator and on a real device running Android O. [1] https://chromium-review.googlesource.com/c/chromium/src/+/805238 BUG=805146 [email protected],[email protected],[email protected],[email protected] Change-Id: I7d60a1cad278f48c361d2ece5a90de10eb082b44 Reviewed-on: https://chromium-review.googlesource.com/891180 Commit-Queue: David Turner <[email protected]> Reviewed-by: Reilly Grant <[email protected]> Reviewed-by: Matthew Cary <[email protected]> Reviewed-by: Alexandr Ilin <[email protected]> Cr-Commit-Position: refs/heads/master@{#532607} CWE ID: CWE-732
void PlatformSensorProviderLinux::CreateSensorAndNotify( mojom::SensorType type, SensorInfoLinux* sensor_device) { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); scoped_refptr<PlatformSensorLinux> sensor; SensorReadingSharedBuffer* reading_buffer = GetSensorReadingSharedBufferForType(type); if (sensor_device && reading_buffer && StartPollingThread()) { sensor = new PlatformSensorLinux(type, reading_buffer, this, sensor_device, polling_thread_->task_runner()); } NotifySensorCreated(type, sensor); }
172,843
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int logi_dj_raw_event(struct hid_device *hdev, struct hid_report *report, u8 *data, int size) { struct dj_receiver_dev *djrcv_dev = hid_get_drvdata(hdev); struct dj_report *dj_report = (struct dj_report *) data; unsigned long flags; bool report_processed = false; dbg_hid("%s, size:%d\n", __func__, size); /* Here we receive all data coming from iface 2, there are 4 cases: * * 1) Data should continue its normal processing i.e. data does not * come from the DJ collection, in which case we do nothing and * return 0, so hid-core can continue normal processing (will forward * to associated hidraw device) * * 2) Data is from DJ collection, and is intended for this driver i. e. * data contains arrival, departure, etc notifications, in which case * we queue them for delayed processing by the work queue. We return 1 * to hid-core as no further processing is required from it. * * 3) Data is from DJ collection, and informs a connection change, * if the change means rf link loss, then we must send a null report * to the upper layer to discard potentially pressed keys that may be * repeated forever by the input layer. Return 1 to hid-core as no * further processing is required. * * 4) Data is from DJ collection and is an actual input event from * a paired DJ device in which case we forward it to the correct hid * device (via hid_input_report() ) and return 1 so hid-core does not do * anything else with it. */ spin_lock_irqsave(&djrcv_dev->lock, flags); if (dj_report->report_id == REPORT_ID_DJ_SHORT) { switch (dj_report->report_type) { case REPORT_TYPE_NOTIF_DEVICE_PAIRED: case REPORT_TYPE_NOTIF_DEVICE_UNPAIRED: logi_dj_recv_queue_notification(djrcv_dev, dj_report); break; case REPORT_TYPE_NOTIF_CONNECTION_STATUS: if (dj_report->report_params[CONNECTION_STATUS_PARAM_STATUS] == STATUS_LINKLOSS) { logi_dj_recv_forward_null_report(djrcv_dev, dj_report); } break; default: logi_dj_recv_forward_report(djrcv_dev, dj_report); } report_processed = true; } spin_unlock_irqrestore(&djrcv_dev->lock, flags); return report_processed; } Commit Message: HID: logitech: perform bounds checking on device_id early enough device_index is a char type and the size of paired_dj_deivces is 7 elements, therefore proper bounds checking has to be applied to device_index before it is used. We are currently performing the bounds checking in logi_dj_recv_add_djhid_device(), which is too late, as malicious device could send REPORT_TYPE_NOTIF_DEVICE_UNPAIRED early enough and trigger the problem in one of the report forwarding functions called from logi_dj_raw_event(). Fix this by performing the check at the earliest possible ocasion in logi_dj_raw_event(). Cc: [email protected] Reported-by: Ben Hawkes <[email protected]> Reviewed-by: Benjamin Tissoires <[email protected]> Signed-off-by: Jiri Kosina <[email protected]> CWE ID: CWE-119
static int logi_dj_raw_event(struct hid_device *hdev, struct hid_report *report, u8 *data, int size) { struct dj_receiver_dev *djrcv_dev = hid_get_drvdata(hdev); struct dj_report *dj_report = (struct dj_report *) data; unsigned long flags; bool report_processed = false; dbg_hid("%s, size:%d\n", __func__, size); /* Here we receive all data coming from iface 2, there are 4 cases: * * 1) Data should continue its normal processing i.e. data does not * come from the DJ collection, in which case we do nothing and * return 0, so hid-core can continue normal processing (will forward * to associated hidraw device) * * 2) Data is from DJ collection, and is intended for this driver i. e. * data contains arrival, departure, etc notifications, in which case * we queue them for delayed processing by the work queue. We return 1 * to hid-core as no further processing is required from it. * * 3) Data is from DJ collection, and informs a connection change, * if the change means rf link loss, then we must send a null report * to the upper layer to discard potentially pressed keys that may be * repeated forever by the input layer. Return 1 to hid-core as no * further processing is required. * * 4) Data is from DJ collection and is an actual input event from * a paired DJ device in which case we forward it to the correct hid * device (via hid_input_report() ) and return 1 so hid-core does not do * anything else with it. */ if ((dj_report->device_index < DJ_DEVICE_INDEX_MIN) || (dj_report->device_index > DJ_DEVICE_INDEX_MAX)) { dev_err(&hdev->dev, "%s: invalid device index:%d\n", __func__, dj_report->device_index); return false; } spin_lock_irqsave(&djrcv_dev->lock, flags); if (dj_report->report_id == REPORT_ID_DJ_SHORT) { switch (dj_report->report_type) { case REPORT_TYPE_NOTIF_DEVICE_PAIRED: case REPORT_TYPE_NOTIF_DEVICE_UNPAIRED: logi_dj_recv_queue_notification(djrcv_dev, dj_report); break; case REPORT_TYPE_NOTIF_CONNECTION_STATUS: if (dj_report->report_params[CONNECTION_STATUS_PARAM_STATUS] == STATUS_LINKLOSS) { logi_dj_recv_forward_null_report(djrcv_dev, dj_report); } break; default: logi_dj_recv_forward_report(djrcv_dev, dj_report); } report_processed = true; } spin_unlock_irqrestore(&djrcv_dev->lock, flags); return report_processed; }
166,377
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void ServerWrapper::OnHttpRequest(int connection_id, const net::HttpServerRequestInfo& info) { server_->SetSendBufferSize(connection_id, kSendBufferSizeForDevTools); if (base::StartsWith(info.path, "/json", base::CompareCase::SENSITIVE)) { BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, base::BindOnce(&DevToolsHttpHandler::OnJsonRequest, handler_, connection_id, info)); return; } if (info.path.empty() || info.path == "/") { BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::BindOnce(&DevToolsHttpHandler::OnDiscoveryPageRequest, handler_, connection_id)); return; } if (!base::StartsWith(info.path, "/devtools/", base::CompareCase::SENSITIVE)) { server_->Send404(connection_id, kDevtoolsHttpHandlerTrafficAnnotation); return; } std::string filename = PathWithoutParams(info.path.substr(10)); std::string mime_type = GetMimeType(filename); if (!debug_frontend_dir_.empty()) { base::FilePath path = debug_frontend_dir_.AppendASCII(filename); std::string data; base::ReadFileToString(path, &data); server_->Send200(connection_id, data, mime_type, kDevtoolsHttpHandlerTrafficAnnotation); return; } if (bundles_resources_) { BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::BindOnce(&DevToolsHttpHandler::OnFrontendResourceRequest, handler_, connection_id, filename)); return; } server_->Send404(connection_id, kDevtoolsHttpHandlerTrafficAnnotation); } Commit Message: DevTools: check Host header for being IP or localhost when connecting over RDP. Bug: 813540 Change-Id: I9338aa2475c15090b8a60729be25502eb866efb7 Reviewed-on: https://chromium-review.googlesource.com/952522 Reviewed-by: Dmitry Gozman <[email protected]> Commit-Queue: Pavel Feldman <[email protected]> Cr-Commit-Position: refs/heads/master@{#541547} CWE ID: CWE-20
void ServerWrapper::OnHttpRequest(int connection_id, const net::HttpServerRequestInfo& info) { if (!RequestIsSafeToServe(info)) { Send500(connection_id, "Host header is specified and is not an IP address or localhost."); return; } server_->SetSendBufferSize(connection_id, kSendBufferSizeForDevTools); if (base::StartsWith(info.path, "/json", base::CompareCase::SENSITIVE)) { BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, base::BindOnce(&DevToolsHttpHandler::OnJsonRequest, handler_, connection_id, info)); return; } if (info.path.empty() || info.path == "/") { BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::BindOnce(&DevToolsHttpHandler::OnDiscoveryPageRequest, handler_, connection_id)); return; } if (!base::StartsWith(info.path, "/devtools/", base::CompareCase::SENSITIVE)) { server_->Send404(connection_id, kDevtoolsHttpHandlerTrafficAnnotation); return; } std::string filename = PathWithoutParams(info.path.substr(10)); std::string mime_type = GetMimeType(filename); if (!debug_frontend_dir_.empty()) { base::FilePath path = debug_frontend_dir_.AppendASCII(filename); std::string data; base::ReadFileToString(path, &data); server_->Send200(connection_id, data, mime_type, kDevtoolsHttpHandlerTrafficAnnotation); return; } if (bundles_resources_) { BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::BindOnce(&DevToolsHttpHandler::OnFrontendResourceRequest, handler_, connection_id, filename)); return; } server_->Send404(connection_id, kDevtoolsHttpHandlerTrafficAnnotation); }
172,732
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: SessionStartupPref StartupBrowserCreator::GetSessionStartupPref( const base::CommandLine& command_line, Profile* profile) { DCHECK(profile); PrefService* prefs = profile->GetPrefs(); SessionStartupPref pref = SessionStartupPref::GetStartupPref(prefs); #if defined(OS_CHROMEOS) const bool is_first_run = user_manager::UserManager::Get()->IsCurrentUserNew(); const bool did_restart = false; StartupBrowserCreator::WasRestarted(); #else const bool is_first_run = first_run::IsChromeFirstRun(); const bool did_restart = StartupBrowserCreator::WasRestarted(); #endif if (is_first_run && SessionStartupPref::TypeIsDefault(prefs)) pref.type = SessionStartupPref::DEFAULT; if ((command_line.HasSwitch(switches::kRestoreLastSession) || did_restart) && !profile->IsNewProfile()) { pref.type = SessionStartupPref::LAST; } if (!profile->IsGuestSession()) { ProfileAttributesEntry* entry = nullptr; bool has_entry = g_browser_process->profile_manager() ->GetProfileAttributesStorage() .GetProfileAttributesWithPath(profile->GetPath(), &entry); if (has_entry && entry->IsSigninRequired()) pref.type = SessionStartupPref::LAST; } if (pref.type == SessionStartupPref::LAST && IncognitoModePrefs::ShouldLaunchIncognito(command_line, prefs)) { pref.type = SessionStartupPref::DEFAULT; } return pref; } Commit Message: Prevent regular mode session startup pref type turning to default. When user loses past session tabs of regular mode after invoking a new window from the incognito mode. This was happening because the SessionStartUpPref type was being set to default, from last, for regular user mode. This was happening in the RestoreIfNecessary method where the restoration was taking place for users whose SessionStartUpPref type was set to last. The fix was to make the protocol of changing the pref type to default more explicit to incognito users and not regular users of pref type last. Bug: 481373 Change-Id: I96efb4cf196949312181c83c6dcd45986ddded13 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1774441 Reviewed-by: Tommy Martino <[email protected]> Reviewed-by: Ramin Halavati <[email protected]> Commit-Queue: Rohit Agarwal <[email protected]> Cr-Commit-Position: refs/heads/master@{#691726} CWE ID: CWE-79
SessionStartupPref StartupBrowserCreator::GetSessionStartupPref( const base::CommandLine& command_line, Profile* profile) { DCHECK(profile); PrefService* prefs = profile->GetPrefs(); SessionStartupPref pref = SessionStartupPref::GetStartupPref(prefs); #if defined(OS_CHROMEOS) const bool is_first_run = user_manager::UserManager::Get()->IsCurrentUserNew(); const bool did_restart = false; StartupBrowserCreator::WasRestarted(); #else const bool is_first_run = first_run::IsChromeFirstRun(); const bool did_restart = StartupBrowserCreator::WasRestarted(); #endif if (is_first_run && SessionStartupPref::TypeIsDefault(prefs)) pref.type = SessionStartupPref::DEFAULT; if ((command_line.HasSwitch(switches::kRestoreLastSession) || did_restart) && !profile->IsNewProfile()) { pref.type = SessionStartupPref::LAST; } if (!profile->IsGuestSession()) { ProfileAttributesEntry* entry = nullptr; bool has_entry = g_browser_process->profile_manager() ->GetProfileAttributesStorage() .GetProfileAttributesWithPath(profile->GetPath(), &entry); if (has_entry && entry->IsSigninRequired()) pref.type = SessionStartupPref::LAST; } if (pref.type == SessionStartupPref::LAST && profile->IsOffTheRecord()) { pref.type = SessionStartupPref::DEFAULT; } return pref; }
172,398
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int nsv_read_chunk(AVFormatContext *s, int fill_header) { NSVContext *nsv = s->priv_data; AVIOContext *pb = s->pb; AVStream *st[2] = {NULL, NULL}; NSVStream *nst; AVPacket *pkt; int i, err = 0; uint8_t auxcount; /* number of aux metadata, also 4 bits of vsize */ uint32_t vsize; uint16_t asize; uint16_t auxsize; if (nsv->ahead[0].data || nsv->ahead[1].data) return 0; //-1; /* hey! eat what you've in your plate first! */ null_chunk_retry: if (pb->eof_reached) return -1; for (i = 0; i < NSV_MAX_RESYNC_TRIES && nsv->state < NSV_FOUND_NSVS && !err; i++) err = nsv_resync(s); if (err < 0) return err; if (nsv->state == NSV_FOUND_NSVS) err = nsv_parse_NSVs_header(s); if (err < 0) return err; if (nsv->state != NSV_HAS_READ_NSVS && nsv->state != NSV_FOUND_BEEF) return -1; auxcount = avio_r8(pb); vsize = avio_rl16(pb); asize = avio_rl16(pb); vsize = (vsize << 4) | (auxcount >> 4); auxcount &= 0x0f; av_log(s, AV_LOG_TRACE, "NSV CHUNK %"PRIu8" aux, %"PRIu32" bytes video, %"PRIu16" bytes audio\n", auxcount, vsize, asize); /* skip aux stuff */ for (i = 0; i < auxcount; i++) { uint32_t av_unused auxtag; auxsize = avio_rl16(pb); auxtag = avio_rl32(pb); avio_skip(pb, auxsize); vsize -= auxsize + sizeof(uint16_t) + sizeof(uint32_t); /* that's becoming brain-dead */ } if (pb->eof_reached) return -1; if (!vsize && !asize) { nsv->state = NSV_UNSYNC; goto null_chunk_retry; } /* map back streams to v,a */ if (s->nb_streams > 0) st[s->streams[0]->id] = s->streams[0]; if (s->nb_streams > 1) st[s->streams[1]->id] = s->streams[1]; if (vsize && st[NSV_ST_VIDEO]) { nst = st[NSV_ST_VIDEO]->priv_data; pkt = &nsv->ahead[NSV_ST_VIDEO]; av_get_packet(pb, pkt, vsize); pkt->stream_index = st[NSV_ST_VIDEO]->index;//NSV_ST_VIDEO; pkt->dts = nst->frame_offset; pkt->flags |= nsv->state == NSV_HAS_READ_NSVS ? AV_PKT_FLAG_KEY : 0; /* keyframe only likely on a sync frame */ for (i = 0; i < FFMIN(8, vsize); i++) av_log(s, AV_LOG_TRACE, "NSV video: [%d] = %02"PRIx8"\n", i, pkt->data[i]); } if(st[NSV_ST_VIDEO]) ((NSVStream*)st[NSV_ST_VIDEO]->priv_data)->frame_offset++; if (asize && st[NSV_ST_AUDIO]) { nst = st[NSV_ST_AUDIO]->priv_data; pkt = &nsv->ahead[NSV_ST_AUDIO]; /* read raw audio specific header on the first audio chunk... */ /* on ALL audio chunks ?? seems so! */ if (asize && st[NSV_ST_AUDIO]->codecpar->codec_tag == MKTAG('P', 'C', 'M', ' ')/* && fill_header*/) { uint8_t bps; uint8_t channels; uint16_t samplerate; bps = avio_r8(pb); channels = avio_r8(pb); samplerate = avio_rl16(pb); if (!channels || !samplerate) return AVERROR_INVALIDDATA; asize-=4; av_log(s, AV_LOG_TRACE, "NSV RAWAUDIO: bps %"PRIu8", nchan %"PRIu8", srate %"PRIu16"\n", bps, channels, samplerate); if (fill_header) { st[NSV_ST_AUDIO]->need_parsing = AVSTREAM_PARSE_NONE; /* we know everything */ if (bps != 16) { av_log(s, AV_LOG_TRACE, "NSV AUDIO bit/sample != 16 (%"PRIu8")!!!\n", bps); } bps /= channels; // ??? if (bps == 8) st[NSV_ST_AUDIO]->codecpar->codec_id = AV_CODEC_ID_PCM_U8; samplerate /= 4;/* UGH ??? XXX */ channels = 1; st[NSV_ST_AUDIO]->codecpar->channels = channels; st[NSV_ST_AUDIO]->codecpar->sample_rate = samplerate; av_log(s, AV_LOG_TRACE, "NSV RAWAUDIO: bps %"PRIu8", nchan %"PRIu8", srate %"PRIu16"\n", bps, channels, samplerate); } } av_get_packet(pb, pkt, asize); pkt->stream_index = st[NSV_ST_AUDIO]->index;//NSV_ST_AUDIO; pkt->flags |= nsv->state == NSV_HAS_READ_NSVS ? AV_PKT_FLAG_KEY : 0; /* keyframe only likely on a sync frame */ if( nsv->state == NSV_HAS_READ_NSVS && st[NSV_ST_VIDEO] ) { /* on a nsvs frame we have new information on a/v sync */ pkt->dts = (((NSVStream*)st[NSV_ST_VIDEO]->priv_data)->frame_offset-1); pkt->dts *= (int64_t)1000 * nsv->framerate.den; pkt->dts += (int64_t)nsv->avsync * nsv->framerate.num; av_log(s, AV_LOG_TRACE, "NSV AUDIO: sync:%"PRId16", dts:%"PRId64, nsv->avsync, pkt->dts); } nst->frame_offset++; } nsv->state = NSV_UNSYNC; return 0; } Commit Message: nsvdec: don't ignore the return value of av_get_packet() Fixes invalid reads with corrupted files. CC: [email protected] Bug-Id: 1039 CWE ID: CWE-476
static int nsv_read_chunk(AVFormatContext *s, int fill_header) { NSVContext *nsv = s->priv_data; AVIOContext *pb = s->pb; AVStream *st[2] = {NULL, NULL}; NSVStream *nst; AVPacket *pkt; int i, err = 0; uint8_t auxcount; /* number of aux metadata, also 4 bits of vsize */ uint32_t vsize; uint16_t asize; uint16_t auxsize; int ret; if (nsv->ahead[0].data || nsv->ahead[1].data) return 0; //-1; /* hey! eat what you've in your plate first! */ null_chunk_retry: if (pb->eof_reached) return -1; for (i = 0; i < NSV_MAX_RESYNC_TRIES && nsv->state < NSV_FOUND_NSVS && !err; i++) err = nsv_resync(s); if (err < 0) return err; if (nsv->state == NSV_FOUND_NSVS) err = nsv_parse_NSVs_header(s); if (err < 0) return err; if (nsv->state != NSV_HAS_READ_NSVS && nsv->state != NSV_FOUND_BEEF) return -1; auxcount = avio_r8(pb); vsize = avio_rl16(pb); asize = avio_rl16(pb); vsize = (vsize << 4) | (auxcount >> 4); auxcount &= 0x0f; av_log(s, AV_LOG_TRACE, "NSV CHUNK %"PRIu8" aux, %"PRIu32" bytes video, %"PRIu16" bytes audio\n", auxcount, vsize, asize); /* skip aux stuff */ for (i = 0; i < auxcount; i++) { uint32_t av_unused auxtag; auxsize = avio_rl16(pb); auxtag = avio_rl32(pb); avio_skip(pb, auxsize); vsize -= auxsize + sizeof(uint16_t) + sizeof(uint32_t); /* that's becoming brain-dead */ } if (pb->eof_reached) return -1; if (!vsize && !asize) { nsv->state = NSV_UNSYNC; goto null_chunk_retry; } /* map back streams to v,a */ if (s->nb_streams > 0) st[s->streams[0]->id] = s->streams[0]; if (s->nb_streams > 1) st[s->streams[1]->id] = s->streams[1]; if (vsize && st[NSV_ST_VIDEO]) { nst = st[NSV_ST_VIDEO]->priv_data; pkt = &nsv->ahead[NSV_ST_VIDEO]; if ((ret = av_get_packet(pb, pkt, vsize)) < 0) return ret; pkt->stream_index = st[NSV_ST_VIDEO]->index;//NSV_ST_VIDEO; pkt->dts = nst->frame_offset; pkt->flags |= nsv->state == NSV_HAS_READ_NSVS ? AV_PKT_FLAG_KEY : 0; /* keyframe only likely on a sync frame */ for (i = 0; i < FFMIN(8, vsize); i++) av_log(s, AV_LOG_TRACE, "NSV video: [%d] = %02"PRIx8"\n", i, pkt->data[i]); } if(st[NSV_ST_VIDEO]) ((NSVStream*)st[NSV_ST_VIDEO]->priv_data)->frame_offset++; if (asize && st[NSV_ST_AUDIO]) { nst = st[NSV_ST_AUDIO]->priv_data; pkt = &nsv->ahead[NSV_ST_AUDIO]; /* read raw audio specific header on the first audio chunk... */ /* on ALL audio chunks ?? seems so! */ if (asize && st[NSV_ST_AUDIO]->codecpar->codec_tag == MKTAG('P', 'C', 'M', ' ')/* && fill_header*/) { uint8_t bps; uint8_t channels; uint16_t samplerate; bps = avio_r8(pb); channels = avio_r8(pb); samplerate = avio_rl16(pb); if (!channels || !samplerate) return AVERROR_INVALIDDATA; asize-=4; av_log(s, AV_LOG_TRACE, "NSV RAWAUDIO: bps %"PRIu8", nchan %"PRIu8", srate %"PRIu16"\n", bps, channels, samplerate); if (fill_header) { st[NSV_ST_AUDIO]->need_parsing = AVSTREAM_PARSE_NONE; /* we know everything */ if (bps != 16) { av_log(s, AV_LOG_TRACE, "NSV AUDIO bit/sample != 16 (%"PRIu8")!!!\n", bps); } bps /= channels; // ??? if (bps == 8) st[NSV_ST_AUDIO]->codecpar->codec_id = AV_CODEC_ID_PCM_U8; samplerate /= 4;/* UGH ??? XXX */ channels = 1; st[NSV_ST_AUDIO]->codecpar->channels = channels; st[NSV_ST_AUDIO]->codecpar->sample_rate = samplerate; av_log(s, AV_LOG_TRACE, "NSV RAWAUDIO: bps %"PRIu8", nchan %"PRIu8", srate %"PRIu16"\n", bps, channels, samplerate); } } if ((ret = av_get_packet(pb, pkt, asize)) < 0) return ret; pkt->stream_index = st[NSV_ST_AUDIO]->index;//NSV_ST_AUDIO; pkt->flags |= nsv->state == NSV_HAS_READ_NSVS ? AV_PKT_FLAG_KEY : 0; /* keyframe only likely on a sync frame */ if( nsv->state == NSV_HAS_READ_NSVS && st[NSV_ST_VIDEO] ) { /* on a nsvs frame we have new information on a/v sync */ pkt->dts = (((NSVStream*)st[NSV_ST_VIDEO]->priv_data)->frame_offset-1); pkt->dts *= (int64_t)1000 * nsv->framerate.den; pkt->dts += (int64_t)nsv->avsync * nsv->framerate.num; av_log(s, AV_LOG_TRACE, "NSV AUDIO: sync:%"PRId16", dts:%"PRId64, nsv->avsync, pkt->dts); } nst->frame_offset++; } nsv->state = NSV_UNSYNC; return 0; }
168,185
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void RenderViewTest::SetUp() { if (!GetContentClient()->renderer()) GetContentClient()->set_renderer(&mock_content_renderer_client_); if (!render_thread_.get()) render_thread_.reset(new MockRenderThread()); render_thread_->set_routing_id(kRouteId); render_thread_->set_surface_id(kSurfaceId); render_thread_->set_new_window_routing_id(kNewWindowRouteId); command_line_.reset(new CommandLine(CommandLine::NO_PROGRAM)); params_.reset(new content::MainFunctionParams(*command_line_)); platform_.reset(new RendererMainPlatformDelegate(*params_)); platform_->PlatformInitialize(); webkit_glue::SetJavaScriptFlags(" --expose-gc"); WebKit::initialize(&webkit_platform_support_); mock_process_.reset(new MockRenderProcess); RenderViewImpl* view = RenderViewImpl::Create( 0, kOpenerId, content::RendererPreferences(), WebPreferences(), new SharedRenderViewCounter(0), kRouteId, kSurfaceId, kInvalidSessionStorageNamespaceId, string16(), 1, WebKit::WebScreenInfo(), false); view->AddRef(); view_ = view; mock_keyboard_.reset(new MockKeyboard()); } Commit Message: Use a new scheme for swapping out RenderViews. BUG=118664 TEST=none Review URL: http://codereview.chromium.org/9720004 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@127986 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
void RenderViewTest::SetUp() { if (!GetContentClient()->renderer()) GetContentClient()->set_renderer(&mock_content_renderer_client_); if (!render_thread_.get()) render_thread_.reset(new MockRenderThread()); render_thread_->set_routing_id(kRouteId); render_thread_->set_surface_id(kSurfaceId); render_thread_->set_new_window_routing_id(kNewWindowRouteId); command_line_.reset(new CommandLine(CommandLine::NO_PROGRAM)); params_.reset(new content::MainFunctionParams(*command_line_)); platform_.reset(new RendererMainPlatformDelegate(*params_)); platform_->PlatformInitialize(); webkit_glue::SetJavaScriptFlags(" --expose-gc"); WebKit::initialize(&webkit_platform_support_); // Ensure that we register any necessary schemes when initializing WebKit, // since we are using a MockRenderThread. RenderThreadImpl::RegisterSchemes(); mock_process_.reset(new MockRenderProcess); RenderViewImpl* view = RenderViewImpl::Create( 0, kOpenerId, content::RendererPreferences(), WebPreferences(), new SharedRenderViewCounter(0), kRouteId, kSurfaceId, kInvalidSessionStorageNamespaceId, string16(), 1, WebKit::WebScreenInfo(), false); view->AddRef(); view_ = view; mock_keyboard_.reset(new MockKeyboard()); }
171,034
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: ChooserContextBase::GetGrantedObjects(const GURL& requesting_origin, const GURL& embedding_origin) { DCHECK_EQ(requesting_origin, requesting_origin.GetOrigin()); DCHECK_EQ(embedding_origin, embedding_origin.GetOrigin()); if (!CanRequestObjectPermission(requesting_origin, embedding_origin)) return {}; std::vector<std::unique_ptr<Object>> results; auto* info = new content_settings::SettingInfo(); std::unique_ptr<base::DictionaryValue> setting = GetWebsiteSetting(requesting_origin, embedding_origin, info); std::unique_ptr<base::Value> objects; if (!setting->Remove(kObjectListKey, &objects)) return results; std::unique_ptr<base::ListValue> object_list = base::ListValue::From(std::move(objects)); if (!object_list) return results; for (auto& object : *object_list) { base::DictionaryValue* object_dict; if (object.GetAsDictionary(&object_dict) && IsValidObject(*object_dict)) { results.push_back(std::make_unique<Object>( requesting_origin, embedding_origin, object_dict, info->source, host_content_settings_map_->is_incognito())); } } return results; } Commit Message: Fix memory leak in ChooserContextBase::GetGrantedObjects. Bug: 854329 Change-Id: Ia163d503a4207859cd41c847c9d5f67e77580fbc Reviewed-on: https://chromium-review.googlesource.com/c/1456080 Reviewed-by: Balazs Engedy <[email protected]> Reviewed-by: Raymes Khoury <[email protected]> Commit-Queue: Marek Haranczyk <[email protected]> Cr-Commit-Position: refs/heads/master@{#629919} CWE ID: CWE-190
ChooserContextBase::GetGrantedObjects(const GURL& requesting_origin, const GURL& embedding_origin) { DCHECK_EQ(requesting_origin, requesting_origin.GetOrigin()); DCHECK_EQ(embedding_origin, embedding_origin.GetOrigin()); if (!CanRequestObjectPermission(requesting_origin, embedding_origin)) return {}; std::vector<std::unique_ptr<Object>> results; content_settings::SettingInfo info; std::unique_ptr<base::DictionaryValue> setting = GetWebsiteSetting(requesting_origin, embedding_origin, &info); std::unique_ptr<base::Value> objects; if (!setting->Remove(kObjectListKey, &objects)) return results; std::unique_ptr<base::ListValue> object_list = base::ListValue::From(std::move(objects)); if (!object_list) return results; for (auto& object : *object_list) { base::DictionaryValue* object_dict; if (object.GetAsDictionary(&object_dict) && IsValidObject(*object_dict)) { results.push_back(std::make_unique<Object>( requesting_origin, embedding_origin, object_dict, info.source, host_content_settings_map_->is_incognito())); } } return results; }
172,055
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: _WM_ParseNewMus(uint8_t *mus_data, uint32_t mus_size) { uint8_t mus_hdr[] = { 'M', 'U', 'S', 0x1A }; uint32_t mus_song_ofs = 0; uint32_t mus_song_len = 0; uint16_t mus_ch_cnt1 = 0; uint16_t mus_ch_cnt2 = 0; uint16_t mus_no_instr = 0; uint32_t mus_data_ofs = 0; uint16_t * mus_mid_instr = NULL; uint16_t mus_instr_cnt = 0; struct _mdi *mus_mdi; uint32_t mus_divisions = 60; float tempo_f = 0.0; uint16_t mus_freq = 0; float samples_per_tick_f = 0.0; uint8_t mus_event[] = { 0, 0, 0, 0 }; uint8_t mus_event_size = 0; uint8_t mus_prev_vol[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; uint32_t setup_ret = 0; uint32_t mus_ticks = 0; uint32_t sample_count = 0; float sample_count_f = 0.0; float sample_remainder = 0.0; uint16_t pitchbend_tmp = 0; if (mus_size < 17) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_MUS, "File too short", 0); return NULL; } if (memcmp(mus_data, mus_hdr, 4)) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_MUS, NULL, 0); return NULL; } mus_song_len = (mus_data[5] << 8) | mus_data[4]; mus_song_ofs = (mus_data[7] << 8) | mus_data[6]; mus_ch_cnt1 = (mus_data[9] << 8) | mus_data[8]; mus_ch_cnt2 = (mus_data[11] << 8) | mus_data[10]; UNUSED(mus_ch_cnt1); UNUSED(mus_ch_cnt2); mus_no_instr = (mus_data[13] << 8) | mus_data[12]; mus_data_ofs = 16; if (mus_size < (mus_data_ofs + (mus_no_instr << 1) + mus_song_len)) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_MUS, "File too short", 0); return NULL; } mus_mid_instr = malloc(mus_no_instr * sizeof(uint16_t)); for (mus_instr_cnt = 0; mus_instr_cnt < mus_no_instr; mus_instr_cnt++) { mus_mid_instr[mus_instr_cnt] = (mus_data[mus_data_ofs + 1] << 8) | mus_data[mus_data_ofs]; mus_data_ofs += 2; } mus_data_ofs = mus_song_ofs; mus_freq = _cvt_get_option(WM_CO_FREQUENCY); if (mus_freq == 0) mus_freq = 140; if ((_WM_MixerOptions & WM_MO_ROUNDTEMPO)) { tempo_f = (float) (60000000 / mus_freq) + 0.5f; } else { tempo_f = (float) (60000000 / mus_freq); } samples_per_tick_f = _WM_GetSamplesPerTick(mus_divisions, (uint32_t)tempo_f); mus_mdi = _WM_initMDI(); _WM_midi_setup_divisions(mus_mdi, mus_divisions); _WM_midi_setup_tempo(mus_mdi, (uint32_t)tempo_f); do { _mus_build_event: #if 1 MUS_EVENT_DEBUG("Before", mus_data[mus_data_ofs], 0); if ((mus_data[mus_data_ofs] & 0x0f) == 0x0f) { mus_data[mus_data_ofs] = (mus_data[mus_data_ofs] & 0xf0) | 0x09; } else if ((mus_data[mus_data_ofs] & 0x0f) == 0x09) { mus_data[mus_data_ofs] = (mus_data[mus_data_ofs] & 0xf0) | 0x0f; } MUS_EVENT_DEBUG("After", mus_data[mus_data_ofs], 0); #endif switch ((mus_data[mus_data_ofs] >> 4) & 0x07) { case 0: // Note Off mus_event_size = 2; mus_event[0] = 0x80 | (mus_data[mus_data_ofs] & 0x0f); mus_event[1] = mus_data[mus_data_ofs + 1]; mus_event[2] = 0; mus_event[3] = 0; break; case 1: // Note On if (mus_data[mus_data_ofs + 1] & 0x80) { mus_event_size = 3; mus_event[0] = 0x90 | (mus_data[mus_data_ofs] & 0x0f); mus_event[1] = mus_data[mus_data_ofs + 1] & 0x7f; mus_event[2] = mus_data[mus_data_ofs + 2]; mus_event[3] = 0; mus_prev_vol[mus_data[mus_data_ofs] & 0x0f] = mus_event[2]; } else { mus_event_size = 2; mus_event[0] = 0x90 | (mus_data[mus_data_ofs] & 0x0f); mus_event[1] = mus_data[mus_data_ofs + 1]; mus_event[2] = mus_prev_vol[mus_data[mus_data_ofs] & 0x0f]; mus_event[3] = 0; } break; case 2: // Pitch Bend mus_event_size = 2; mus_event[0] = 0xe0 | (mus_data[mus_data_ofs] & 0x0f); pitchbend_tmp = mus_data[mus_data_ofs + 1] << 6; mus_event[1] = pitchbend_tmp & 0x7f; mus_event[2] = (pitchbend_tmp >> 7) & 0x7f; mus_event[3] = 0; break; case 3: mus_event_size = 2; switch (mus_data[mus_data_ofs + 1]) { case 10: // All Sounds Off mus_event[0] = 0xb0 | (mus_data[mus_data_ofs] & 0x0f); mus_event[1] = 120; mus_event[2] = 0; mus_event[3] = 0; break; case 11: // All Notes Off mus_event[0] = 0xb0 | (mus_data[mus_data_ofs] & 0x0f); mus_event[1] = 123; mus_event[2] = 0; mus_event[3] = 0; break; case 12: // Mono (Not supported by WildMIDI) /* ************************** FIXME: Add dummy mdi event ************************** */ mus_event[0] = 0xb0 | (mus_data[mus_data_ofs] & 0x0f); mus_event[1] = 126; mus_event[2] = 0; mus_event[3] = 0; break; case 13: // Poly (Not supported by WildMIDI) /* ************************** FIXME: Add dummy mdi event ************************** */ mus_event[0] = 0xb0 | (mus_data[mus_data_ofs] & 0x0f); mus_event[1] = 127; mus_event[2] = 0; mus_event[3] = 0; break; case 14: // Reset All Controllers mus_event[0] = 0xb0 | (mus_data[mus_data_ofs] & 0x0f); mus_event[1] = 121; mus_event[2] = 0; mus_event[3] = 0; break; default: // Unsupported goto _mus_next_data; } break; case 4: mus_event_size = 3; switch (mus_data[mus_data_ofs + 1]) { case 0: // Patch /* ************************************************* FIXME: Check if setting is MIDI or MUS instrument ************************************************* */ mus_event[0] = 0xc0 | (mus_data[mus_data_ofs] & 0x0f); mus_event[1] = mus_data[mus_data_ofs + 2]; mus_event[2] = 0; mus_event[3] = 0; break; case 1: // Bank Select mus_event[0] = 0xb0 | (mus_data[mus_data_ofs] & 0x0f); mus_event[1] = 0; mus_event[2] = mus_data[mus_data_ofs + 2]; mus_event[3] = 0; break; case 2: // Modulation (Not supported by WildMidi) mus_event[0] = 0xb0 | (mus_data[mus_data_ofs] & 0x0f); mus_event[1] = 1; mus_event[2] = mus_data[mus_data_ofs + 2]; mus_event[3] = 0; break; case 3: // Volume mus_event[0] = 0xb0 | (mus_data[mus_data_ofs] & 0x0f); mus_event[1] = 7; mus_event[2] = mus_data[mus_data_ofs + 2]; mus_event[3] = 0; break; case 4: // Pan mus_event[0] = 0xb0 | (mus_data[mus_data_ofs] & 0x0f); mus_event[1] = 10; mus_event[2] = mus_data[mus_data_ofs + 2]; mus_event[3] = 0; break; case 5: // Expression mus_event[0] = 0xb0 | (mus_data[mus_data_ofs] & 0x0f); mus_event[1] = 11; mus_event[2] = mus_data[mus_data_ofs + 2]; mus_event[3] = 0; break; case 6: // Reverb (Not supported by WildMidi) mus_event[0] = 0xb0 | (mus_data[mus_data_ofs] & 0x0f); mus_event[1] = 91; mus_event[2] = mus_data[mus_data_ofs + 2]; mus_event[3] = 0; break; case 7: // Chorus (Not supported by WildMidi) mus_event[0] = 0xb0 | (mus_data[mus_data_ofs] & 0x0f); mus_event[1] = 93; mus_event[2] = mus_data[mus_data_ofs + 2]; mus_event[3] = 0; break; case 8: // Sustain mus_event[0] = 0xb0 | (mus_data[mus_data_ofs] & 0x0f); mus_event[1] = 64; mus_event[2] = mus_data[mus_data_ofs + 2]; mus_event[3] = 0; break; case 9: // Soft Peddle (Not supported by WildMidi) mus_event[0] = 0xb0 | (mus_data[mus_data_ofs] & 0x0f); mus_event[1] = 67; mus_event[2] = mus_data[mus_data_ofs + 2]; mus_event[3] = 0; break; default: // Unsupported goto _mus_next_data; } break; case 5: mus_event_size = 1; goto _mus_next_data; break; case 6: goto _mus_end_of_song; break; case 7: mus_event_size = 1; goto _mus_next_data; break; } setup_ret = _WM_SetupMidiEvent(mus_mdi, (uint8_t *)mus_event, 0); if (setup_ret == 0) { goto _mus_end; } _mus_next_data: if (!(mus_data[mus_data_ofs] & 0x80)) { mus_data_ofs += mus_event_size; goto _mus_build_event; } mus_data_ofs += mus_event_size; mus_ticks = 0; do { mus_ticks = (mus_ticks << 7) | (mus_data[mus_data_ofs++] & 0x7f); } while (mus_data[mus_data_ofs - 1] & 0x80); sample_count_f = ((float)mus_ticks * samples_per_tick_f) + sample_remainder; sample_count = (uint32_t)sample_count_f; sample_remainder = sample_count_f - (float)sample_count; mus_mdi->events[mus_mdi->event_count - 1].samples_to_next = sample_count; mus_mdi->extra_info.approx_total_samples += sample_count; } while (mus_data_ofs < mus_size); _mus_end_of_song: if ((mus_mdi->reverb = _WM_init_reverb(_WM_SampleRate, _WM_reverb_room_width, _WM_reverb_room_length, _WM_reverb_listen_posx, _WM_reverb_listen_posy)) == NULL) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_MEM, "to init reverb", 0); goto _mus_end; } _WM_midi_setup_endoftrack(mus_mdi); mus_mdi->extra_info.current_sample = 0; mus_mdi->current_event = &mus_mdi->events[0]; mus_mdi->samples_to_mix = 0; mus_mdi->note = NULL; _WM_ResetToStart(mus_mdi); _mus_end: free(mus_mid_instr); if (mus_mdi->reverb) return (mus_mdi); _WM_freeMDI(mus_mdi); return NULL; } Commit Message: Add a new size parameter to _WM_SetupMidiEvent() so that it knows where to stop reading, and adjust its users properly. Fixes bug #175 (CVE-2017-11661, CVE-2017-11662, CVE-2017-11663, CVE-2017-11664.) CWE ID: CWE-125
_WM_ParseNewMus(uint8_t *mus_data, uint32_t mus_size) { uint8_t mus_hdr[] = { 'M', 'U', 'S', 0x1A }; uint32_t mus_song_ofs = 0; uint32_t mus_song_len = 0; uint16_t mus_ch_cnt1 = 0; uint16_t mus_ch_cnt2 = 0; uint16_t mus_no_instr = 0; uint32_t mus_data_ofs = 0; uint16_t * mus_mid_instr = NULL; uint16_t mus_instr_cnt = 0; struct _mdi *mus_mdi; uint32_t mus_divisions = 60; float tempo_f = 0.0; uint16_t mus_freq = 0; float samples_per_tick_f = 0.0; #define MUS_SZ 4 uint8_t mus_event[MUS_SZ] = { 0, 0, 0, 0 }; uint8_t mus_event_size = 0; uint8_t mus_prev_vol[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; uint32_t setup_ret = 0; uint32_t mus_ticks = 0; uint32_t sample_count = 0; float sample_count_f = 0.0; float sample_remainder = 0.0; uint16_t pitchbend_tmp = 0; if (mus_size < 17) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_MUS, "File too short", 0); return NULL; } if (memcmp(mus_data, mus_hdr, 4)) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_MUS, NULL, 0); return NULL; } mus_song_len = (mus_data[5] << 8) | mus_data[4]; mus_song_ofs = (mus_data[7] << 8) | mus_data[6]; mus_ch_cnt1 = (mus_data[9] << 8) | mus_data[8]; mus_ch_cnt2 = (mus_data[11] << 8) | mus_data[10]; UNUSED(mus_ch_cnt1); UNUSED(mus_ch_cnt2); mus_no_instr = (mus_data[13] << 8) | mus_data[12]; mus_data_ofs = 16; if (mus_size < (mus_data_ofs + (mus_no_instr << 1) + mus_song_len)) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_MUS, "File too short", 0); return NULL; } mus_mid_instr = malloc(mus_no_instr * sizeof(uint16_t)); for (mus_instr_cnt = 0; mus_instr_cnt < mus_no_instr; mus_instr_cnt++) { mus_mid_instr[mus_instr_cnt] = (mus_data[mus_data_ofs + 1] << 8) | mus_data[mus_data_ofs]; mus_data_ofs += 2; } mus_data_ofs = mus_song_ofs; mus_freq = _cvt_get_option(WM_CO_FREQUENCY); if (mus_freq == 0) mus_freq = 140; if ((_WM_MixerOptions & WM_MO_ROUNDTEMPO)) { tempo_f = (float) (60000000 / mus_freq) + 0.5f; } else { tempo_f = (float) (60000000 / mus_freq); } samples_per_tick_f = _WM_GetSamplesPerTick(mus_divisions, (uint32_t)tempo_f); mus_mdi = _WM_initMDI(); _WM_midi_setup_divisions(mus_mdi, mus_divisions); _WM_midi_setup_tempo(mus_mdi, (uint32_t)tempo_f); do { _mus_build_event: #if 1 MUS_EVENT_DEBUG("Before", mus_data[mus_data_ofs], 0); if ((mus_data[mus_data_ofs] & 0x0f) == 0x0f) { mus_data[mus_data_ofs] = (mus_data[mus_data_ofs] & 0xf0) | 0x09; } else if ((mus_data[mus_data_ofs] & 0x0f) == 0x09) { mus_data[mus_data_ofs] = (mus_data[mus_data_ofs] & 0xf0) | 0x0f; } MUS_EVENT_DEBUG("After", mus_data[mus_data_ofs], 0); #endif switch ((mus_data[mus_data_ofs] >> 4) & 0x07) { case 0: // Note Off mus_event_size = 2; mus_event[0] = 0x80 | (mus_data[mus_data_ofs] & 0x0f); mus_event[1] = mus_data[mus_data_ofs + 1]; mus_event[2] = 0; mus_event[3] = 0; break; case 1: // Note On if (mus_data[mus_data_ofs + 1] & 0x80) { mus_event_size = 3; mus_event[0] = 0x90 | (mus_data[mus_data_ofs] & 0x0f); mus_event[1] = mus_data[mus_data_ofs + 1] & 0x7f; mus_event[2] = mus_data[mus_data_ofs + 2]; mus_event[3] = 0; mus_prev_vol[mus_data[mus_data_ofs] & 0x0f] = mus_event[2]; } else { mus_event_size = 2; mus_event[0] = 0x90 | (mus_data[mus_data_ofs] & 0x0f); mus_event[1] = mus_data[mus_data_ofs + 1]; mus_event[2] = mus_prev_vol[mus_data[mus_data_ofs] & 0x0f]; mus_event[3] = 0; } break; case 2: // Pitch Bend mus_event_size = 2; mus_event[0] = 0xe0 | (mus_data[mus_data_ofs] & 0x0f); pitchbend_tmp = mus_data[mus_data_ofs + 1] << 6; mus_event[1] = pitchbend_tmp & 0x7f; mus_event[2] = (pitchbend_tmp >> 7) & 0x7f; mus_event[3] = 0; break; case 3: mus_event_size = 2; switch (mus_data[mus_data_ofs + 1]) { case 10: // All Sounds Off mus_event[0] = 0xb0 | (mus_data[mus_data_ofs] & 0x0f); mus_event[1] = 120; mus_event[2] = 0; mus_event[3] = 0; break; case 11: // All Notes Off mus_event[0] = 0xb0 | (mus_data[mus_data_ofs] & 0x0f); mus_event[1] = 123; mus_event[2] = 0; mus_event[3] = 0; break; case 12: // Mono (Not supported by WildMIDI) /* ************************** FIXME: Add dummy mdi event ************************** */ mus_event[0] = 0xb0 | (mus_data[mus_data_ofs] & 0x0f); mus_event[1] = 126; mus_event[2] = 0; mus_event[3] = 0; break; case 13: // Poly (Not supported by WildMIDI) /* ************************** FIXME: Add dummy mdi event ************************** */ mus_event[0] = 0xb0 | (mus_data[mus_data_ofs] & 0x0f); mus_event[1] = 127; mus_event[2] = 0; mus_event[3] = 0; break; case 14: // Reset All Controllers mus_event[0] = 0xb0 | (mus_data[mus_data_ofs] & 0x0f); mus_event[1] = 121; mus_event[2] = 0; mus_event[3] = 0; break; default: // Unsupported goto _mus_next_data; } break; case 4: mus_event_size = 3; switch (mus_data[mus_data_ofs + 1]) { case 0: // Patch /* ************************************************* FIXME: Check if setting is MIDI or MUS instrument ************************************************* */ mus_event[0] = 0xc0 | (mus_data[mus_data_ofs] & 0x0f); mus_event[1] = mus_data[mus_data_ofs + 2]; mus_event[2] = 0; mus_event[3] = 0; break; case 1: // Bank Select mus_event[0] = 0xb0 | (mus_data[mus_data_ofs] & 0x0f); mus_event[1] = 0; mus_event[2] = mus_data[mus_data_ofs + 2]; mus_event[3] = 0; break; case 2: // Modulation (Not supported by WildMidi) mus_event[0] = 0xb0 | (mus_data[mus_data_ofs] & 0x0f); mus_event[1] = 1; mus_event[2] = mus_data[mus_data_ofs + 2]; mus_event[3] = 0; break; case 3: // Volume mus_event[0] = 0xb0 | (mus_data[mus_data_ofs] & 0x0f); mus_event[1] = 7; mus_event[2] = mus_data[mus_data_ofs + 2]; mus_event[3] = 0; break; case 4: // Pan mus_event[0] = 0xb0 | (mus_data[mus_data_ofs] & 0x0f); mus_event[1] = 10; mus_event[2] = mus_data[mus_data_ofs + 2]; mus_event[3] = 0; break; case 5: // Expression mus_event[0] = 0xb0 | (mus_data[mus_data_ofs] & 0x0f); mus_event[1] = 11; mus_event[2] = mus_data[mus_data_ofs + 2]; mus_event[3] = 0; break; case 6: // Reverb (Not supported by WildMidi) mus_event[0] = 0xb0 | (mus_data[mus_data_ofs] & 0x0f); mus_event[1] = 91; mus_event[2] = mus_data[mus_data_ofs + 2]; mus_event[3] = 0; break; case 7: // Chorus (Not supported by WildMidi) mus_event[0] = 0xb0 | (mus_data[mus_data_ofs] & 0x0f); mus_event[1] = 93; mus_event[2] = mus_data[mus_data_ofs + 2]; mus_event[3] = 0; break; case 8: // Sustain mus_event[0] = 0xb0 | (mus_data[mus_data_ofs] & 0x0f); mus_event[1] = 64; mus_event[2] = mus_data[mus_data_ofs + 2]; mus_event[3] = 0; break; case 9: // Soft Peddle (Not supported by WildMidi) mus_event[0] = 0xb0 | (mus_data[mus_data_ofs] & 0x0f); mus_event[1] = 67; mus_event[2] = mus_data[mus_data_ofs + 2]; mus_event[3] = 0; break; default: // Unsupported goto _mus_next_data; } break; case 5: mus_event_size = 1; goto _mus_next_data; break; case 6: goto _mus_end_of_song; break; case 7: mus_event_size = 1; goto _mus_next_data; break; } setup_ret = _WM_SetupMidiEvent(mus_mdi, (uint8_t *)mus_event, MUS_SZ, 0); if (setup_ret == 0) { goto _mus_end; } _mus_next_data: if (!(mus_data[mus_data_ofs] & 0x80)) { mus_data_ofs += mus_event_size; goto _mus_build_event; } mus_data_ofs += mus_event_size; mus_ticks = 0; do { mus_ticks = (mus_ticks << 7) | (mus_data[mus_data_ofs++] & 0x7f); } while (mus_data[mus_data_ofs - 1] & 0x80); sample_count_f = ((float)mus_ticks * samples_per_tick_f) + sample_remainder; sample_count = (uint32_t)sample_count_f; sample_remainder = sample_count_f - (float)sample_count; mus_mdi->events[mus_mdi->event_count - 1].samples_to_next = sample_count; mus_mdi->extra_info.approx_total_samples += sample_count; } while (mus_data_ofs < mus_size); _mus_end_of_song: if ((mus_mdi->reverb = _WM_init_reverb(_WM_SampleRate, _WM_reverb_room_width, _WM_reverb_room_length, _WM_reverb_listen_posx, _WM_reverb_listen_posy)) == NULL) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_MEM, "to init reverb", 0); goto _mus_end; } _WM_midi_setup_endoftrack(mus_mdi); mus_mdi->extra_info.current_sample = 0; mus_mdi->current_event = &mus_mdi->events[0]; mus_mdi->samples_to_mix = 0; mus_mdi->note = NULL; _WM_ResetToStart(mus_mdi); _mus_end: free(mus_mid_instr); if (mus_mdi->reverb) return (mus_mdi); _WM_freeMDI(mus_mdi); return NULL; }
168,005
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static MagickBooleanType DrawDashPolygon(const DrawInfo *draw_info, const PrimitiveInfo *primitive_info,Image *image,ExceptionInfo *exception) { DrawInfo *clone_info; double length, maximum_length, offset, scale, total_length; MagickStatusType status; PrimitiveInfo *dash_polygon; register ssize_t i; register double dx, dy; size_t number_vertices; ssize_t j, n; assert(draw_info != (const DrawInfo *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule()," begin draw-dash"); for (i=0; primitive_info[i].primitive != UndefinedPrimitive; i++) ; number_vertices=(size_t) i; dash_polygon=(PrimitiveInfo *) AcquireQuantumMemory((size_t) (2UL*number_vertices+1UL),sizeof(*dash_polygon)); if (dash_polygon == (PrimitiveInfo *) NULL) return(MagickFalse); clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info); clone_info->miterlimit=0; dash_polygon[0]=primitive_info[0]; scale=ExpandAffine(&draw_info->affine); length=scale*(draw_info->dash_pattern[0]-0.5); offset=draw_info->dash_offset != 0.0 ? scale*draw_info->dash_offset : 0.0; j=1; for (n=0; offset > 0.0; j=0) { if (draw_info->dash_pattern[n] <= 0.0) break; length=scale*(draw_info->dash_pattern[n]+(n == 0 ? -0.5 : 0.5)); if (offset > length) { offset-=length; n++; length=scale*(draw_info->dash_pattern[n]+0.5); continue; } if (offset < length) { length-=offset; offset=0.0; break; } offset=0.0; n++; } status=MagickTrue; maximum_length=0.0; total_length=0.0; for (i=1; (i < number_vertices) && (length >= 0.0); i++) { dx=primitive_info[i].point.x-primitive_info[i-1].point.x; dy=primitive_info[i].point.y-primitive_info[i-1].point.y; maximum_length=hypot((double) dx,dy); if (length == 0.0) { n++; if (draw_info->dash_pattern[n] == 0.0) n=0; length=scale*(draw_info->dash_pattern[n]+(n == 0 ? -0.5 : 0.5)); } for (total_length=0.0; (length >= 0.0) && (maximum_length >= (total_length+length)); ) { total_length+=length; if ((n & 0x01) != 0) { dash_polygon[0]=primitive_info[0]; dash_polygon[0].point.x=(double) (primitive_info[i-1].point.x+dx* total_length/maximum_length); dash_polygon[0].point.y=(double) (primitive_info[i-1].point.y+dy* total_length/maximum_length); j=1; } else { if ((j+1) > (ssize_t) (2*number_vertices)) break; dash_polygon[j]=primitive_info[i-1]; dash_polygon[j].point.x=(double) (primitive_info[i-1].point.x+dx* total_length/maximum_length); dash_polygon[j].point.y=(double) (primitive_info[i-1].point.y+dy* total_length/maximum_length); dash_polygon[j].coordinates=1; j++; dash_polygon[0].coordinates=(size_t) j; dash_polygon[j].primitive=UndefinedPrimitive; status&=DrawStrokePolygon(image,clone_info,dash_polygon,exception); } n++; if (draw_info->dash_pattern[n] == 0.0) n=0; length=scale*(draw_info->dash_pattern[n]+(n == 0 ? -0.5 : 0.5)); } length-=(maximum_length-total_length); if ((n & 0x01) != 0) continue; dash_polygon[j]=primitive_info[i]; dash_polygon[j].coordinates=1; j++; } if ((total_length <= maximum_length) && ((n & 0x01) == 0) && (j > 1)) { dash_polygon[j]=primitive_info[i-1]; dash_polygon[j].point.x+=MagickEpsilon; dash_polygon[j].point.y+=MagickEpsilon; dash_polygon[j].coordinates=1; j++; dash_polygon[0].coordinates=(size_t) j; dash_polygon[j].primitive=UndefinedPrimitive; status&=DrawStrokePolygon(image,clone_info,dash_polygon,exception); } dash_polygon=(PrimitiveInfo *) RelinquishMagickMemory(dash_polygon); clone_info=DestroyDrawInfo(clone_info); if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule()," end draw-dash"); return(status != 0 ? MagickTrue : MagickFalse); } Commit Message: Prevent buffer overflow in magick/draw.c CWE ID: CWE-119
static MagickBooleanType DrawDashPolygon(const DrawInfo *draw_info, const PrimitiveInfo *primitive_info,Image *image,ExceptionInfo *exception) { DrawInfo *clone_info; double length, maximum_length, offset, scale, total_length; MagickStatusType status; PrimitiveInfo *dash_polygon; register ssize_t i; register double dx, dy; size_t number_vertices; ssize_t j, n; assert(draw_info != (const DrawInfo *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule()," begin draw-dash"); for (i=0; primitive_info[i].primitive != UndefinedPrimitive; i++) ; number_vertices=(size_t) i; dash_polygon=(PrimitiveInfo *) AcquireQuantumMemory((size_t) (2UL*number_vertices+1UL),sizeof(*dash_polygon)); if (dash_polygon == (PrimitiveInfo *) NULL) return(MagickFalse); clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info); clone_info->miterlimit=0; dash_polygon[0]=primitive_info[0]; scale=ExpandAffine(&draw_info->affine); length=scale*(draw_info->dash_pattern[0]-0.5); offset=draw_info->dash_offset != 0.0 ? scale*draw_info->dash_offset : 0.0; j=1; for (n=0; offset > 0.0; j=0) { if (draw_info->dash_pattern[n] <= 0.0) break; length=scale*(draw_info->dash_pattern[n]+(n == 0 ? -0.5 : 0.5)); if (offset > length) { offset-=length; n++; length=scale*(draw_info->dash_pattern[n]+0.5); continue; } if (offset < length) { length-=offset; offset=0.0; break; } offset=0.0; n++; } status=MagickTrue; maximum_length=0.0; total_length=0.0; for (i=1; (i < (ssize_t) number_vertices) && (length >= 0.0); i++) { dx=primitive_info[i].point.x-primitive_info[i-1].point.x; dy=primitive_info[i].point.y-primitive_info[i-1].point.y; maximum_length=hypot((double) dx,dy); if (length == 0.0) { n++; if (draw_info->dash_pattern[n] == 0.0) n=0; length=scale*(draw_info->dash_pattern[n]+(n == 0 ? -0.5 : 0.5)); } for (total_length=0.0; (length >= 0.0) && (maximum_length >= (total_length+length)); ) { total_length+=length; if ((n & 0x01) != 0) { dash_polygon[0]=primitive_info[0]; dash_polygon[0].point.x=(double) (primitive_info[i-1].point.x+dx* total_length/maximum_length); dash_polygon[0].point.y=(double) (primitive_info[i-1].point.y+dy* total_length/maximum_length); j=1; } else { if ((j+1) > (ssize_t) (2*number_vertices)) break; dash_polygon[j]=primitive_info[i-1]; dash_polygon[j].point.x=(double) (primitive_info[i-1].point.x+dx* total_length/maximum_length); dash_polygon[j].point.y=(double) (primitive_info[i-1].point.y+dy* total_length/maximum_length); dash_polygon[j].coordinates=1; j++; dash_polygon[0].coordinates=(size_t) j; dash_polygon[j].primitive=UndefinedPrimitive; status&=DrawStrokePolygon(image,clone_info,dash_polygon,exception); } n++; if (draw_info->dash_pattern[n] == 0.0) n=0; length=scale*(draw_info->dash_pattern[n]+(n == 0 ? -0.5 : 0.5)); } length-=(maximum_length-total_length); if ((n & 0x01) != 0) continue; dash_polygon[j]=primitive_info[i]; dash_polygon[j].coordinates=1; j++; } if ((total_length <= maximum_length) && ((n & 0x01) == 0) && (j > 1)) { dash_polygon[j]=primitive_info[i-1]; dash_polygon[j].point.x+=MagickEpsilon; dash_polygon[j].point.y+=MagickEpsilon; dash_polygon[j].coordinates=1; j++; dash_polygon[0].coordinates=(size_t) j; dash_polygon[j].primitive=UndefinedPrimitive; status&=DrawStrokePolygon(image,clone_info,dash_polygon,exception); } dash_polygon=(PrimitiveInfo *) RelinquishMagickMemory(dash_polygon); clone_info=DestroyDrawInfo(clone_info); if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule()," end draw-dash"); return(status != 0 ? MagickTrue : MagickFalse); }
167,244
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int decode_cblk(Jpeg2000DecoderContext *s, Jpeg2000CodingStyle *codsty, Jpeg2000T1Context *t1, Jpeg2000Cblk *cblk, int width, int height, int bandpos) { int passno = cblk->npasses, pass_t = 2, bpno = cblk->nonzerobits - 1, y; int clnpass_cnt = 0; int bpass_csty_symbol = codsty->cblk_style & JPEG2000_CBLK_BYPASS; int vert_causal_ctx_csty_symbol = codsty->cblk_style & JPEG2000_CBLK_VSC; for (y = 0; y < height; y++) memset(t1->data[y], 0, width * sizeof(**t1->data)); /* If code-block contains no compressed data: nothing to do. */ if (!cblk->length) return 0; for (y = 0; y < height + 2; y++) memset(t1->flags[y], 0, (width + 2) * sizeof(**t1->flags)); cblk->data[cblk->length] = 0xff; cblk->data[cblk->length+1] = 0xff; ff_mqc_initdec(&t1->mqc, cblk->data); while (passno--) { switch(pass_t) { case 0: decode_sigpass(t1, width, height, bpno + 1, bandpos, bpass_csty_symbol && (clnpass_cnt >= 4), vert_causal_ctx_csty_symbol); break; case 1: decode_refpass(t1, width, height, bpno + 1); if (bpass_csty_symbol && clnpass_cnt >= 4) ff_mqc_initdec(&t1->mqc, cblk->data); break; case 2: decode_clnpass(s, t1, width, height, bpno + 1, bandpos, codsty->cblk_style & JPEG2000_CBLK_SEGSYM, vert_causal_ctx_csty_symbol); clnpass_cnt = clnpass_cnt + 1; if (bpass_csty_symbol && clnpass_cnt >= 4) ff_mqc_initdec(&t1->mqc, cblk->data); break; } pass_t++; if (pass_t == 3) { bpno--; pass_t = 0; } } return 0; } Commit Message: jpeg2000: check log2_cblk dimensions Fixes out of array access Fixes Ticket2895 Found-by: Piotr Bandurski <[email protected]> Signed-off-by: Michael Niedermayer <[email protected]> CWE ID: CWE-119
static int decode_cblk(Jpeg2000DecoderContext *s, Jpeg2000CodingStyle *codsty, Jpeg2000T1Context *t1, Jpeg2000Cblk *cblk, int width, int height, int bandpos) { int passno = cblk->npasses, pass_t = 2, bpno = cblk->nonzerobits - 1, y; int clnpass_cnt = 0; int bpass_csty_symbol = codsty->cblk_style & JPEG2000_CBLK_BYPASS; int vert_causal_ctx_csty_symbol = codsty->cblk_style & JPEG2000_CBLK_VSC; av_assert0(width <= JPEG2000_MAX_CBLKW); av_assert0(height <= JPEG2000_MAX_CBLKH); for (y = 0; y < height; y++) memset(t1->data[y], 0, width * sizeof(**t1->data)); /* If code-block contains no compressed data: nothing to do. */ if (!cblk->length) return 0; for (y = 0; y < height + 2; y++) memset(t1->flags[y], 0, (width + 2) * sizeof(**t1->flags)); cblk->data[cblk->length] = 0xff; cblk->data[cblk->length+1] = 0xff; ff_mqc_initdec(&t1->mqc, cblk->data); while (passno--) { switch(pass_t) { case 0: decode_sigpass(t1, width, height, bpno + 1, bandpos, bpass_csty_symbol && (clnpass_cnt >= 4), vert_causal_ctx_csty_symbol); break; case 1: decode_refpass(t1, width, height, bpno + 1); if (bpass_csty_symbol && clnpass_cnt >= 4) ff_mqc_initdec(&t1->mqc, cblk->data); break; case 2: decode_clnpass(s, t1, width, height, bpno + 1, bandpos, codsty->cblk_style & JPEG2000_CBLK_SEGSYM, vert_causal_ctx_csty_symbol); clnpass_cnt = clnpass_cnt + 1; if (bpass_csty_symbol && clnpass_cnt >= 4) ff_mqc_initdec(&t1->mqc, cblk->data); break; } pass_t++; if (pass_t == 3) { bpno--; pass_t = 0; } } return 0; }
165,919
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: rpl_daoack_print(netdissect_options *ndo, const u_char *bp, u_int length) { const struct nd_rpl_daoack *daoack = (const struct nd_rpl_daoack *)bp; const char *dagid_str = "<elided>"; ND_TCHECK2(*daoack, ND_RPL_DAOACK_MIN_LEN); if (length < ND_RPL_DAOACK_MIN_LEN) goto tooshort; bp += ND_RPL_DAOACK_MIN_LEN; length -= ND_RPL_DAOACK_MIN_LEN; if(RPL_DAOACK_D(daoack->rpl_flags)) { ND_TCHECK2(daoack->rpl_dagid, DAGID_LEN); if (length < DAGID_LEN) goto tooshort; dagid_str = ip6addr_string (ndo, daoack->rpl_dagid); bp += DAGID_LEN; length -= DAGID_LEN; } ND_PRINT((ndo, " [dagid:%s,seq:%u,instance:%u,status:%u]", dagid_str, daoack->rpl_daoseq, daoack->rpl_instanceid, daoack->rpl_status)); /* no officially defined options for DAOACK, but print any we find */ if(ndo->ndo_vflag > 1) { const struct rpl_dio_genoption *opt = (const struct rpl_dio_genoption *)bp; rpl_dio_printopt(ndo, opt, length); } return; trunc: ND_PRINT((ndo," [|dao-truncated]")); return; tooshort: ND_PRINT((ndo," [|dao-length too short]")); return; } Commit Message: (for 4.9.3) CVE-2018-14882/ICMP6 RPL: Add a missing bounds check Moreover: Add and use *_tstr[] strings. Update four tests outputs accordingly. Fix a space. Wang Junjie of 360 ESG Codesafe Team had independently identified this vulnerability in 2018 by means of fuzzing and provided the packet capture file for the test. CWE ID: CWE-125
rpl_daoack_print(netdissect_options *ndo, const u_char *bp, u_int length) { const struct nd_rpl_daoack *daoack = (const struct nd_rpl_daoack *)bp; const char *dagid_str = "<elided>"; ND_TCHECK2(*daoack, ND_RPL_DAOACK_MIN_LEN); if (length < ND_RPL_DAOACK_MIN_LEN) goto tooshort; bp += ND_RPL_DAOACK_MIN_LEN; length -= ND_RPL_DAOACK_MIN_LEN; if(RPL_DAOACK_D(daoack->rpl_flags)) { ND_TCHECK2(daoack->rpl_dagid, DAGID_LEN); if (length < DAGID_LEN) goto tooshort; dagid_str = ip6addr_string (ndo, daoack->rpl_dagid); bp += DAGID_LEN; length -= DAGID_LEN; } ND_PRINT((ndo, " [dagid:%s,seq:%u,instance:%u,status:%u]", dagid_str, daoack->rpl_daoseq, daoack->rpl_instanceid, daoack->rpl_status)); /* no officially defined options for DAOACK, but print any we find */ if(ndo->ndo_vflag > 1) { const struct rpl_dio_genoption *opt = (const struct rpl_dio_genoption *)bp; rpl_dio_printopt(ndo, opt, length); } return; trunc: ND_PRINT((ndo, "%s", rpl_tstr)); return; tooshort: ND_PRINT((ndo," [|dao-length too short]")); return; }
169,829
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int inet6_sk_rebuild_header(struct sock *sk) { struct ipv6_pinfo *np = inet6_sk(sk); struct dst_entry *dst; dst = __sk_dst_check(sk, np->dst_cookie); if (!dst) { struct inet_sock *inet = inet_sk(sk); struct in6_addr *final_p, final; struct flowi6 fl6; memset(&fl6, 0, sizeof(fl6)); fl6.flowi6_proto = sk->sk_protocol; fl6.daddr = sk->sk_v6_daddr; fl6.saddr = np->saddr; fl6.flowlabel = np->flow_label; fl6.flowi6_oif = sk->sk_bound_dev_if; fl6.flowi6_mark = sk->sk_mark; fl6.fl6_dport = inet->inet_dport; fl6.fl6_sport = inet->inet_sport; security_sk_classify_flow(sk, flowi6_to_flowi(&fl6)); final_p = fl6_update_dst(&fl6, np->opt, &final); dst = ip6_dst_lookup_flow(sk, &fl6, final_p); if (IS_ERR(dst)) { sk->sk_route_caps = 0; sk->sk_err_soft = -PTR_ERR(dst); return PTR_ERR(dst); } __ip6_dst_store(sk, dst, NULL, NULL); } return 0; } Commit Message: ipv6: add complete rcu protection around np->opt This patch addresses multiple problems : UDP/RAW sendmsg() need to get a stable struct ipv6_txoptions while socket is not locked : Other threads can change np->opt concurrently. Dmitry posted a syzkaller (http://github.com/google/syzkaller) program desmonstrating use-after-free. Starting with TCP/DCCP lockless listeners, tcp_v6_syn_recv_sock() and dccp_v6_request_recv_sock() also need to use RCU protection to dereference np->opt once (before calling ipv6_dup_options()) This patch adds full RCU protection to np->opt Reported-by: Dmitry Vyukov <[email protected]> Signed-off-by: Eric Dumazet <[email protected]> Acked-by: Hannes Frederic Sowa <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-416
int inet6_sk_rebuild_header(struct sock *sk) { struct ipv6_pinfo *np = inet6_sk(sk); struct dst_entry *dst; dst = __sk_dst_check(sk, np->dst_cookie); if (!dst) { struct inet_sock *inet = inet_sk(sk); struct in6_addr *final_p, final; struct flowi6 fl6; memset(&fl6, 0, sizeof(fl6)); fl6.flowi6_proto = sk->sk_protocol; fl6.daddr = sk->sk_v6_daddr; fl6.saddr = np->saddr; fl6.flowlabel = np->flow_label; fl6.flowi6_oif = sk->sk_bound_dev_if; fl6.flowi6_mark = sk->sk_mark; fl6.fl6_dport = inet->inet_dport; fl6.fl6_sport = inet->inet_sport; security_sk_classify_flow(sk, flowi6_to_flowi(&fl6)); rcu_read_lock(); final_p = fl6_update_dst(&fl6, rcu_dereference(np->opt), &final); rcu_read_unlock(); dst = ip6_dst_lookup_flow(sk, &fl6, final_p); if (IS_ERR(dst)) { sk->sk_route_caps = 0; sk->sk_err_soft = -PTR_ERR(dst); return PTR_ERR(dst); } __ip6_dst_store(sk, dst, NULL, NULL); } return 0; }
167,328
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: get_cdtext_generic (void *p_user_data) { generic_img_private_t *p_env = p_user_data; uint8_t *p_cdtext_data = NULL; size_t len; if (!p_env) return NULL; if (p_env->b_cdtext_error) return NULL; if (NULL == p_env->cdtext) { p_cdtext_data = read_cdtext_generic (p_env); if (NULL != p_cdtext_data) { len = CDIO_MMC_GET_LEN16(p_cdtext_data)-2; p_env->cdtext = cdtext_init(); if(len <= 0 || 0 != cdtext_data_init (p_env->cdtext, &p_cdtext_data[4], len)) { p_env->b_cdtext_error = true; cdtext_destroy (p_env->cdtext); free(p_env->cdtext); p_env->cdtext = NULL; } } free(p_cdtext_data); } } Commit Message: CWE ID: CWE-415
get_cdtext_generic (void *p_user_data) { generic_img_private_t *p_env = p_user_data; uint8_t *p_cdtext_data = NULL; size_t len; if (!p_env) return NULL; if (p_env->b_cdtext_error) return NULL; if (NULL == p_env->cdtext) { p_cdtext_data = read_cdtext_generic (p_env); if (NULL != p_cdtext_data) { len = CDIO_MMC_GET_LEN16(p_cdtext_data)-2; p_env->cdtext = cdtext_init(); if(len <= 0 || 0 != cdtext_data_init (p_env->cdtext, &p_cdtext_data[4], len)) { p_env->b_cdtext_error = true; free(p_env->cdtext); p_env->cdtext = NULL; } } free(p_cdtext_data); } }
165,370
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: llc_print(netdissect_options *ndo, const u_char *p, u_int length, u_int caplen, const struct lladdr_info *src, const struct lladdr_info *dst) { uint8_t dsap_field, dsap, ssap_field, ssap; uint16_t control; int hdrlen; int is_u; if (caplen < 3) { ND_PRINT((ndo, "[|llc]")); ND_DEFAULTPRINT((const u_char *)p, caplen); return (caplen); } if (length < 3) { ND_PRINT((ndo, "[|llc]")); ND_DEFAULTPRINT((const u_char *)p, caplen); return (length); } dsap_field = *p; ssap_field = *(p + 1); /* * OK, what type of LLC frame is this? The length * of the control field depends on that - I frames * have a two-byte control field, and U frames have * a one-byte control field. */ control = *(p + 2); if ((control & LLC_U_FMT) == LLC_U_FMT) { /* * U frame. */ is_u = 1; hdrlen = 3; /* DSAP, SSAP, 1-byte control field */ } else { /* * The control field in I and S frames is * 2 bytes... */ if (caplen < 4) { ND_PRINT((ndo, "[|llc]")); ND_DEFAULTPRINT((const u_char *)p, caplen); return (caplen); } if (length < 4) { ND_PRINT((ndo, "[|llc]")); ND_DEFAULTPRINT((const u_char *)p, caplen); return (length); } /* * ...and is little-endian. */ control = EXTRACT_LE_16BITS(p + 2); is_u = 0; hdrlen = 4; /* DSAP, SSAP, 2-byte control field */ } if (ssap_field == LLCSAP_GLOBAL && dsap_field == LLCSAP_GLOBAL) { /* * This is an Ethernet_802.3 IPX frame; it has an * 802.3 header (i.e., an Ethernet header where the * type/length field is <= ETHERMTU, i.e. it's a length * field, not a type field), but has no 802.2 header - * the IPX packet starts right after the Ethernet header, * with a signature of two bytes of 0xFF (which is * LLCSAP_GLOBAL). * * (It might also have been an Ethernet_802.3 IPX at * one time, but got bridged onto another network, * such as an 802.11 network; this has appeared in at * least one capture file.) */ if (ndo->ndo_eflag) ND_PRINT((ndo, "IPX 802.3: ")); ipx_print(ndo, p, length); return (0); /* no LLC header */ } dsap = dsap_field & ~LLC_IG; ssap = ssap_field & ~LLC_GSAP; if (ndo->ndo_eflag) { ND_PRINT((ndo, "LLC, dsap %s (0x%02x) %s, ssap %s (0x%02x) %s", tok2str(llc_values, "Unknown", dsap), dsap, tok2str(llc_ig_flag_values, "Unknown", dsap_field & LLC_IG), tok2str(llc_values, "Unknown", ssap), ssap, tok2str(llc_flag_values, "Unknown", ssap_field & LLC_GSAP))); if (is_u) { ND_PRINT((ndo, ", ctrl 0x%02x: ", control)); } else { ND_PRINT((ndo, ", ctrl 0x%04x: ", control)); } } /* * Skip LLC header. */ p += hdrlen; length -= hdrlen; caplen -= hdrlen; if (ssap == LLCSAP_SNAP && dsap == LLCSAP_SNAP && control == LLC_UI) { /* * XXX - what *is* the right bridge pad value here? * Does anybody ever bridge one form of LAN traffic * over a networking type that uses 802.2 LLC? */ if (!snap_print(ndo, p, length, caplen, src, dst, 2)) { /* * Unknown packet type; tell our caller, by * returning a negative value, so they * can print the raw packet. */ return (-(hdrlen + 5)); /* include LLC and SNAP header */ } else return (hdrlen + 5); /* include LLC and SNAP header */ } if (ssap == LLCSAP_8021D && dsap == LLCSAP_8021D && control == LLC_UI) { stp_print(ndo, p, length); return (hdrlen); } if (ssap == LLCSAP_IP && dsap == LLCSAP_IP && control == LLC_UI) { /* * This is an RFC 948-style IP packet, with * an 802.3 header and an 802.2 LLC header * with the source and destination SAPs being * the IP SAP. */ ip_print(ndo, p, length); return (hdrlen); } if (ssap == LLCSAP_IPX && dsap == LLCSAP_IPX && control == LLC_UI) { /* * This is an Ethernet_802.2 IPX frame, with an 802.3 * header and an 802.2 LLC header with the source and * destination SAPs being the IPX SAP. */ if (ndo->ndo_eflag) ND_PRINT((ndo, "IPX 802.2: ")); ipx_print(ndo, p, length); return (hdrlen); } #ifdef ENABLE_SMB if (ssap == LLCSAP_NETBEUI && dsap == LLCSAP_NETBEUI && (!(control & LLC_S_FMT) || control == LLC_U_FMT)) { /* * we don't actually have a full netbeui parser yet, but the * smb parser can handle many smb-in-netbeui packets, which * is very useful, so we call that * * We don't call it for S frames, however, just I frames * (which are frames that don't have the low-order bit, * LLC_S_FMT, set in the first byte of the control field) * and UI frames (whose control field is just 3, LLC_U_FMT). */ netbeui_print(ndo, control, p, length); return (hdrlen); } #endif if (ssap == LLCSAP_ISONS && dsap == LLCSAP_ISONS && control == LLC_UI) { isoclns_print(ndo, p, length, caplen); return (hdrlen); } if (!ndo->ndo_eflag) { if (ssap == dsap) { if (src == NULL || dst == NULL) ND_PRINT((ndo, "%s ", tok2str(llc_values, "Unknown DSAP 0x%02x", dsap))); else ND_PRINT((ndo, "%s > %s %s ", (src->addr_string)(ndo, src->addr), (dst->addr_string)(ndo, dst->addr), tok2str(llc_values, "Unknown DSAP 0x%02x", dsap))); } else { if (src == NULL || dst == NULL) ND_PRINT((ndo, "%s > %s ", tok2str(llc_values, "Unknown SSAP 0x%02x", ssap), tok2str(llc_values, "Unknown DSAP 0x%02x", dsap))); else ND_PRINT((ndo, "%s %s > %s %s ", (src->addr_string)(ndo, src->addr), tok2str(llc_values, "Unknown SSAP 0x%02x", ssap), (dst->addr_string)(ndo, dst->addr), tok2str(llc_values, "Unknown DSAP 0x%02x", dsap))); } } if (is_u) { ND_PRINT((ndo, "Unnumbered, %s, Flags [%s], length %u", tok2str(llc_cmd_values, "%02x", LLC_U_CMD(control)), tok2str(llc_flag_values,"?",(ssap_field & LLC_GSAP) | (control & LLC_U_POLL)), length + hdrlen)); if ((control & ~LLC_U_POLL) == LLC_XID) { if (length == 0) { /* * XID with no payload. * This could, for example, be an SNA * "short form" XID. */ return (hdrlen); } if (caplen < 1) { ND_PRINT((ndo, "[|llc]")); if (caplen > 0) ND_DEFAULTPRINT((const u_char *)p, caplen); return (hdrlen); } if (*p == LLC_XID_FI) { if (caplen < 3 || length < 3) { ND_PRINT((ndo, "[|llc]")); if (caplen > 0) ND_DEFAULTPRINT((const u_char *)p, caplen); } else ND_PRINT((ndo, ": %02x %02x", p[1], p[2])); return (hdrlen); } } } else { if ((control & LLC_S_FMT) == LLC_S_FMT) { ND_PRINT((ndo, "Supervisory, %s, rcv seq %u, Flags [%s], length %u", tok2str(llc_supervisory_values,"?",LLC_S_CMD(control)), LLC_IS_NR(control), tok2str(llc_flag_values,"?",(ssap_field & LLC_GSAP) | (control & LLC_IS_POLL)), length + hdrlen)); return (hdrlen); /* no payload to print */ } else { ND_PRINT((ndo, "Information, send seq %u, rcv seq %u, Flags [%s], length %u", LLC_I_NS(control), LLC_IS_NR(control), tok2str(llc_flag_values,"?",(ssap_field & LLC_GSAP) | (control & LLC_IS_POLL)), length + hdrlen)); } } return (-hdrlen); } Commit Message: CVE-2017-12897/ISO CLNS: Use ND_TTEST() for the bounds checks in isoclns_print(). This fixes a buffer over-read discovered by Kamil Frankowicz. Don't pass the remaining caplen - that's too hard to get right, and we were getting it wrong in at least one case; just use ND_TTEST(). Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-125
llc_print(netdissect_options *ndo, const u_char *p, u_int length, u_int caplen, const struct lladdr_info *src, const struct lladdr_info *dst) { uint8_t dsap_field, dsap, ssap_field, ssap; uint16_t control; int hdrlen; int is_u; if (caplen < 3) { ND_PRINT((ndo, "[|llc]")); ND_DEFAULTPRINT((const u_char *)p, caplen); return (caplen); } if (length < 3) { ND_PRINT((ndo, "[|llc]")); ND_DEFAULTPRINT((const u_char *)p, caplen); return (length); } dsap_field = *p; ssap_field = *(p + 1); /* * OK, what type of LLC frame is this? The length * of the control field depends on that - I frames * have a two-byte control field, and U frames have * a one-byte control field. */ control = *(p + 2); if ((control & LLC_U_FMT) == LLC_U_FMT) { /* * U frame. */ is_u = 1; hdrlen = 3; /* DSAP, SSAP, 1-byte control field */ } else { /* * The control field in I and S frames is * 2 bytes... */ if (caplen < 4) { ND_PRINT((ndo, "[|llc]")); ND_DEFAULTPRINT((const u_char *)p, caplen); return (caplen); } if (length < 4) { ND_PRINT((ndo, "[|llc]")); ND_DEFAULTPRINT((const u_char *)p, caplen); return (length); } /* * ...and is little-endian. */ control = EXTRACT_LE_16BITS(p + 2); is_u = 0; hdrlen = 4; /* DSAP, SSAP, 2-byte control field */ } if (ssap_field == LLCSAP_GLOBAL && dsap_field == LLCSAP_GLOBAL) { /* * This is an Ethernet_802.3 IPX frame; it has an * 802.3 header (i.e., an Ethernet header where the * type/length field is <= ETHERMTU, i.e. it's a length * field, not a type field), but has no 802.2 header - * the IPX packet starts right after the Ethernet header, * with a signature of two bytes of 0xFF (which is * LLCSAP_GLOBAL). * * (It might also have been an Ethernet_802.3 IPX at * one time, but got bridged onto another network, * such as an 802.11 network; this has appeared in at * least one capture file.) */ if (ndo->ndo_eflag) ND_PRINT((ndo, "IPX 802.3: ")); ipx_print(ndo, p, length); return (0); /* no LLC header */ } dsap = dsap_field & ~LLC_IG; ssap = ssap_field & ~LLC_GSAP; if (ndo->ndo_eflag) { ND_PRINT((ndo, "LLC, dsap %s (0x%02x) %s, ssap %s (0x%02x) %s", tok2str(llc_values, "Unknown", dsap), dsap, tok2str(llc_ig_flag_values, "Unknown", dsap_field & LLC_IG), tok2str(llc_values, "Unknown", ssap), ssap, tok2str(llc_flag_values, "Unknown", ssap_field & LLC_GSAP))); if (is_u) { ND_PRINT((ndo, ", ctrl 0x%02x: ", control)); } else { ND_PRINT((ndo, ", ctrl 0x%04x: ", control)); } } /* * Skip LLC header. */ p += hdrlen; length -= hdrlen; caplen -= hdrlen; if (ssap == LLCSAP_SNAP && dsap == LLCSAP_SNAP && control == LLC_UI) { /* * XXX - what *is* the right bridge pad value here? * Does anybody ever bridge one form of LAN traffic * over a networking type that uses 802.2 LLC? */ if (!snap_print(ndo, p, length, caplen, src, dst, 2)) { /* * Unknown packet type; tell our caller, by * returning a negative value, so they * can print the raw packet. */ return (-(hdrlen + 5)); /* include LLC and SNAP header */ } else return (hdrlen + 5); /* include LLC and SNAP header */ } if (ssap == LLCSAP_8021D && dsap == LLCSAP_8021D && control == LLC_UI) { stp_print(ndo, p, length); return (hdrlen); } if (ssap == LLCSAP_IP && dsap == LLCSAP_IP && control == LLC_UI) { /* * This is an RFC 948-style IP packet, with * an 802.3 header and an 802.2 LLC header * with the source and destination SAPs being * the IP SAP. */ ip_print(ndo, p, length); return (hdrlen); } if (ssap == LLCSAP_IPX && dsap == LLCSAP_IPX && control == LLC_UI) { /* * This is an Ethernet_802.2 IPX frame, with an 802.3 * header and an 802.2 LLC header with the source and * destination SAPs being the IPX SAP. */ if (ndo->ndo_eflag) ND_PRINT((ndo, "IPX 802.2: ")); ipx_print(ndo, p, length); return (hdrlen); } #ifdef ENABLE_SMB if (ssap == LLCSAP_NETBEUI && dsap == LLCSAP_NETBEUI && (!(control & LLC_S_FMT) || control == LLC_U_FMT)) { /* * we don't actually have a full netbeui parser yet, but the * smb parser can handle many smb-in-netbeui packets, which * is very useful, so we call that * * We don't call it for S frames, however, just I frames * (which are frames that don't have the low-order bit, * LLC_S_FMT, set in the first byte of the control field) * and UI frames (whose control field is just 3, LLC_U_FMT). */ netbeui_print(ndo, control, p, length); return (hdrlen); } #endif if (ssap == LLCSAP_ISONS && dsap == LLCSAP_ISONS && control == LLC_UI) { isoclns_print(ndo, p, length); return (hdrlen); } if (!ndo->ndo_eflag) { if (ssap == dsap) { if (src == NULL || dst == NULL) ND_PRINT((ndo, "%s ", tok2str(llc_values, "Unknown DSAP 0x%02x", dsap))); else ND_PRINT((ndo, "%s > %s %s ", (src->addr_string)(ndo, src->addr), (dst->addr_string)(ndo, dst->addr), tok2str(llc_values, "Unknown DSAP 0x%02x", dsap))); } else { if (src == NULL || dst == NULL) ND_PRINT((ndo, "%s > %s ", tok2str(llc_values, "Unknown SSAP 0x%02x", ssap), tok2str(llc_values, "Unknown DSAP 0x%02x", dsap))); else ND_PRINT((ndo, "%s %s > %s %s ", (src->addr_string)(ndo, src->addr), tok2str(llc_values, "Unknown SSAP 0x%02x", ssap), (dst->addr_string)(ndo, dst->addr), tok2str(llc_values, "Unknown DSAP 0x%02x", dsap))); } } if (is_u) { ND_PRINT((ndo, "Unnumbered, %s, Flags [%s], length %u", tok2str(llc_cmd_values, "%02x", LLC_U_CMD(control)), tok2str(llc_flag_values,"?",(ssap_field & LLC_GSAP) | (control & LLC_U_POLL)), length + hdrlen)); if ((control & ~LLC_U_POLL) == LLC_XID) { if (length == 0) { /* * XID with no payload. * This could, for example, be an SNA * "short form" XID. */ return (hdrlen); } if (caplen < 1) { ND_PRINT((ndo, "[|llc]")); if (caplen > 0) ND_DEFAULTPRINT((const u_char *)p, caplen); return (hdrlen); } if (*p == LLC_XID_FI) { if (caplen < 3 || length < 3) { ND_PRINT((ndo, "[|llc]")); if (caplen > 0) ND_DEFAULTPRINT((const u_char *)p, caplen); } else ND_PRINT((ndo, ": %02x %02x", p[1], p[2])); return (hdrlen); } } } else { if ((control & LLC_S_FMT) == LLC_S_FMT) { ND_PRINT((ndo, "Supervisory, %s, rcv seq %u, Flags [%s], length %u", tok2str(llc_supervisory_values,"?",LLC_S_CMD(control)), LLC_IS_NR(control), tok2str(llc_flag_values,"?",(ssap_field & LLC_GSAP) | (control & LLC_IS_POLL)), length + hdrlen)); return (hdrlen); /* no payload to print */ } else { ND_PRINT((ndo, "Information, send seq %u, rcv seq %u, Flags [%s], length %u", LLC_I_NS(control), LLC_IS_NR(control), tok2str(llc_flag_values,"?",(ssap_field & LLC_GSAP) | (control & LLC_IS_POLL)), length + hdrlen)); } } return (-hdrlen); }
167,953
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: AppModalDialog::AppModalDialog(WebContents* web_contents, const string16& title) : valid_(true), native_dialog_(NULL), title_(title), web_contents_(web_contents) { } Commit Message: Fix a Windows crash bug with javascript alerts from extension popups. BUG=137707 Review URL: https://chromiumcodereview.appspot.com/10828423 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@152716 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
AppModalDialog::AppModalDialog(WebContents* web_contents, const string16& title) : valid_(true), native_dialog_(NULL), title_(title), web_contents_(web_contents), completed_(false) { }
170,753
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void NTPResourceCache::CreateNewTabHTML() { PrefService* prefs = profile_->GetPrefs(); base::DictionaryValue load_time_data; load_time_data.SetBoolean("bookmarkbarattached", prefs->GetBoolean(prefs::kShowBookmarkBar)); load_time_data.SetBoolean("hasattribution", ThemeServiceFactory::GetForProfile(profile_)->HasCustomImage( IDR_THEME_NTP_ATTRIBUTION)); load_time_data.SetBoolean("showMostvisited", should_show_most_visited_page_); load_time_data.SetBoolean("showAppLauncherPromo", ShouldShowAppLauncherPromo()); load_time_data.SetBoolean("showRecentlyClosed", should_show_recently_closed_menu_); load_time_data.SetString("title", l10n_util::GetStringUTF16(IDS_NEW_TAB_TITLE)); load_time_data.SetString("mostvisited", l10n_util::GetStringUTF16(IDS_NEW_TAB_MOST_VISITED)); load_time_data.SetString("suggestions", l10n_util::GetStringUTF16(IDS_NEW_TAB_SUGGESTIONS)); load_time_data.SetString("restoreThumbnailsShort", l10n_util::GetStringUTF16(IDS_NEW_TAB_RESTORE_THUMBNAILS_SHORT_LINK)); load_time_data.SetString("recentlyclosed", l10n_util::GetStringUTF16(IDS_NEW_TAB_RECENTLY_CLOSED)); load_time_data.SetString("webStoreTitle", l10n_util::GetStringUTF16(IDS_EXTENSION_WEB_STORE_TITLE)); load_time_data.SetString("webStoreTitleShort", l10n_util::GetStringUTF16(IDS_EXTENSION_WEB_STORE_TITLE_SHORT)); load_time_data.SetString("closedwindowsingle", l10n_util::GetStringUTF16(IDS_NEW_TAB_RECENTLY_CLOSED_WINDOW_SINGLE)); load_time_data.SetString("closedwindowmultiple", l10n_util::GetStringUTF16(IDS_NEW_TAB_RECENTLY_CLOSED_WINDOW_MULTIPLE)); load_time_data.SetString("attributionintro", l10n_util::GetStringUTF16(IDS_NEW_TAB_ATTRIBUTION_INTRO)); load_time_data.SetString("thumbnailremovednotification", l10n_util::GetStringUTF16(IDS_NEW_TAB_THUMBNAIL_REMOVED_NOTIFICATION)); load_time_data.SetString("undothumbnailremove", l10n_util::GetStringUTF16(IDS_NEW_TAB_UNDO_THUMBNAIL_REMOVE)); load_time_data.SetString("removethumbnailtooltip", l10n_util::GetStringUTF16(IDS_NEW_TAB_REMOVE_THUMBNAIL_TOOLTIP)); load_time_data.SetString("appuninstall", l10n_util::GetStringUTF16(IDS_EXTENSIONS_UNINSTALL)); load_time_data.SetString("appoptions", l10n_util::GetStringUTF16(IDS_NEW_TAB_APP_OPTIONS)); load_time_data.SetString("appdetails", l10n_util::GetStringUTF16(IDS_NEW_TAB_APP_DETAILS)); load_time_data.SetString("appcreateshortcut", l10n_util::GetStringUTF16(IDS_NEW_TAB_APP_CREATE_SHORTCUT)); load_time_data.SetString("appDefaultPageName", l10n_util::GetStringUTF16(IDS_APP_DEFAULT_PAGE_NAME)); load_time_data.SetString("applaunchtypepinned", l10n_util::GetStringUTF16(IDS_APP_CONTEXT_MENU_OPEN_PINNED)); load_time_data.SetString("applaunchtyperegular", l10n_util::GetStringUTF16(IDS_APP_CONTEXT_MENU_OPEN_REGULAR)); load_time_data.SetString("applaunchtypewindow", l10n_util::GetStringUTF16(IDS_APP_CONTEXT_MENU_OPEN_WINDOW)); load_time_data.SetString("applaunchtypefullscreen", l10n_util::GetStringUTF16(IDS_APP_CONTEXT_MENU_OPEN_FULLSCREEN)); load_time_data.SetString("syncpromotext", l10n_util::GetStringUTF16(IDS_SYNC_START_SYNC_BUTTON_LABEL)); load_time_data.SetString("syncLinkText", l10n_util::GetStringUTF16(IDS_SYNC_ADVANCED_OPTIONS)); load_time_data.SetBoolean("shouldShowSyncLogin", NTPLoginHandler::ShouldShow(profile_)); load_time_data.SetString("otherSessions", l10n_util::GetStringUTF16(IDS_NEW_TAB_OTHER_SESSIONS_LABEL)); load_time_data.SetString("otherSessionsEmpty", l10n_util::GetStringUTF16(IDS_NEW_TAB_OTHER_SESSIONS_EMPTY)); load_time_data.SetString("otherSessionsLearnMoreUrl", l10n_util::GetStringUTF16(IDS_NEW_TAB_OTHER_SESSIONS_LEARN_MORE_URL)); load_time_data.SetString("learnMore", l10n_util::GetStringUTF16(IDS_LEARN_MORE)); load_time_data.SetString("webStoreLink", GetUrlWithLang(GURL(extension_urls::GetWebstoreLaunchURL()))); load_time_data.SetString("appInstallHintText", l10n_util::GetStringUTF16(IDS_NEW_TAB_APP_INSTALL_HINT_LABEL)); load_time_data.SetBoolean("isDiscoveryInNTPEnabled", NewTabUI::IsDiscoveryInNTPEnabled()); load_time_data.SetString("collapseSessionMenuItemText", l10n_util::GetStringUTF16(IDS_NEW_TAB_OTHER_SESSIONS_COLLAPSE_SESSION)); load_time_data.SetString("expandSessionMenuItemText", l10n_util::GetStringUTF16(IDS_NEW_TAB_OTHER_SESSIONS_EXPAND_SESSION)); load_time_data.SetString("restoreSessionMenuItemText", l10n_util::GetStringUTF16(IDS_NEW_TAB_OTHER_SESSIONS_OPEN_ALL)); load_time_data.SetString("learn_more", l10n_util::GetStringUTF16(IDS_LEARN_MORE)); load_time_data.SetString("tile_grid_screenreader_accessible_description", l10n_util::GetStringUTF16(IDS_NEW_TAB_TILE_GRID_ACCESSIBLE_DESCRIPTION)); load_time_data.SetString("page_switcher_change_title", l10n_util::GetStringUTF16(IDS_NEW_TAB_PAGE_SWITCHER_CHANGE_TITLE)); load_time_data.SetString("page_switcher_same_title", l10n_util::GetStringUTF16(IDS_NEW_TAB_PAGE_SWITCHER_SAME_TITLE)); load_time_data.SetString("appsPromoTitle", l10n_util::GetStringUTF16(IDS_NEW_TAB_PAGE_APPS_PROMO_TITLE)); load_time_data.SetBoolean("isSwipeTrackingFromScrollEventsEnabled", is_swipe_tracking_from_scroll_events_enabled_); if (profile_->IsManaged()) should_show_apps_page_ = false; load_time_data.SetBoolean("showApps", should_show_apps_page_); load_time_data.SetBoolean("showWebStoreIcon", !prefs->GetBoolean(prefs::kHideWebStoreIcon)); bool streamlined_hosted_apps = CommandLine::ForCurrentProcess()->HasSwitch( switches::kEnableStreamlinedHostedApps); load_time_data.SetBoolean("enableStreamlinedHostedApps", streamlined_hosted_apps); if (streamlined_hosted_apps) { load_time_data.SetString("applaunchtypetab", l10n_util::GetStringUTF16(IDS_APP_CONTEXT_MENU_OPEN_TAB)); } #if defined(OS_MACOSX) load_time_data.SetBoolean( "disableCreateAppShortcut", CommandLine::ForCurrentProcess()->HasSwitch(switches::kDisableAppShims)); #endif #if defined(OS_CHROMEOS) load_time_data.SetString("expandMenu", l10n_util::GetStringUTF16(IDS_NEW_TAB_CLOSE_MENU_EXPAND)); #endif NewTabPageHandler::GetLocalizedValues(profile_, &load_time_data); NTPLoginHandler::GetLocalizedValues(profile_, &load_time_data); webui::SetFontAndTextDirection(&load_time_data); load_time_data.SetBoolean("anim", gfx::Animation::ShouldRenderRichAnimation()); ui::ThemeProvider* tp = ThemeServiceFactory::GetForProfile(profile_); int alignment = tp->GetDisplayProperty( ThemeProperties::NTP_BACKGROUND_ALIGNMENT); load_time_data.SetString("themegravity", (alignment & ThemeProperties::ALIGN_RIGHT) ? "right" : ""); if (first_run::IsChromeFirstRun()) { NotificationPromo::HandleClosed(NotificationPromo::NTP_NOTIFICATION_PROMO); } else { NotificationPromo notification_promo; notification_promo.InitFromPrefs(NotificationPromo::NTP_NOTIFICATION_PROMO); if (notification_promo.CanShow()) { load_time_data.SetString("notificationPromoText", notification_promo.promo_text()); DVLOG(1) << "Notification promo:" << notification_promo.promo_text(); } NotificationPromo bubble_promo; bubble_promo.InitFromPrefs(NotificationPromo::NTP_BUBBLE_PROMO); if (bubble_promo.CanShow()) { load_time_data.SetString("bubblePromoText", bubble_promo.promo_text()); DVLOG(1) << "Bubble promo:" << bubble_promo.promo_text(); } } bool show_other_sessions_menu = should_show_other_devices_menu_ && !CommandLine::ForCurrentProcess()->HasSwitch( switches::kDisableNTPOtherSessionsMenu); load_time_data.SetBoolean("showOtherSessionsMenu", show_other_sessions_menu); load_time_data.SetBoolean("isUserSignedIn", !prefs->GetString(prefs::kGoogleServicesUsername).empty()); base::StringPiece new_tab_html(ResourceBundle::GetSharedInstance(). GetRawDataResource(IDR_NEW_TAB_4_HTML)); webui::UseVersion2 version2; std::string full_html = webui::GetI18nTemplateHtml(new_tab_html, &load_time_data); new_tab_html_ = base::RefCountedString::TakeString(&full_html); } Commit Message: Remove --disable-app-shims. App shims have been enabled by default for 3 milestones (since r242711). BUG=350161 Review URL: https://codereview.chromium.org/298953002 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@272786 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void NTPResourceCache::CreateNewTabHTML() { PrefService* prefs = profile_->GetPrefs(); base::DictionaryValue load_time_data; load_time_data.SetBoolean("bookmarkbarattached", prefs->GetBoolean(prefs::kShowBookmarkBar)); load_time_data.SetBoolean("hasattribution", ThemeServiceFactory::GetForProfile(profile_)->HasCustomImage( IDR_THEME_NTP_ATTRIBUTION)); load_time_data.SetBoolean("showMostvisited", should_show_most_visited_page_); load_time_data.SetBoolean("showAppLauncherPromo", ShouldShowAppLauncherPromo()); load_time_data.SetBoolean("showRecentlyClosed", should_show_recently_closed_menu_); load_time_data.SetString("title", l10n_util::GetStringUTF16(IDS_NEW_TAB_TITLE)); load_time_data.SetString("mostvisited", l10n_util::GetStringUTF16(IDS_NEW_TAB_MOST_VISITED)); load_time_data.SetString("suggestions", l10n_util::GetStringUTF16(IDS_NEW_TAB_SUGGESTIONS)); load_time_data.SetString("restoreThumbnailsShort", l10n_util::GetStringUTF16(IDS_NEW_TAB_RESTORE_THUMBNAILS_SHORT_LINK)); load_time_data.SetString("recentlyclosed", l10n_util::GetStringUTF16(IDS_NEW_TAB_RECENTLY_CLOSED)); load_time_data.SetString("webStoreTitle", l10n_util::GetStringUTF16(IDS_EXTENSION_WEB_STORE_TITLE)); load_time_data.SetString("webStoreTitleShort", l10n_util::GetStringUTF16(IDS_EXTENSION_WEB_STORE_TITLE_SHORT)); load_time_data.SetString("closedwindowsingle", l10n_util::GetStringUTF16(IDS_NEW_TAB_RECENTLY_CLOSED_WINDOW_SINGLE)); load_time_data.SetString("closedwindowmultiple", l10n_util::GetStringUTF16(IDS_NEW_TAB_RECENTLY_CLOSED_WINDOW_MULTIPLE)); load_time_data.SetString("attributionintro", l10n_util::GetStringUTF16(IDS_NEW_TAB_ATTRIBUTION_INTRO)); load_time_data.SetString("thumbnailremovednotification", l10n_util::GetStringUTF16(IDS_NEW_TAB_THUMBNAIL_REMOVED_NOTIFICATION)); load_time_data.SetString("undothumbnailremove", l10n_util::GetStringUTF16(IDS_NEW_TAB_UNDO_THUMBNAIL_REMOVE)); load_time_data.SetString("removethumbnailtooltip", l10n_util::GetStringUTF16(IDS_NEW_TAB_REMOVE_THUMBNAIL_TOOLTIP)); load_time_data.SetString("appuninstall", l10n_util::GetStringUTF16(IDS_EXTENSIONS_UNINSTALL)); load_time_data.SetString("appoptions", l10n_util::GetStringUTF16(IDS_NEW_TAB_APP_OPTIONS)); load_time_data.SetString("appdetails", l10n_util::GetStringUTF16(IDS_NEW_TAB_APP_DETAILS)); load_time_data.SetString("appcreateshortcut", l10n_util::GetStringUTF16(IDS_NEW_TAB_APP_CREATE_SHORTCUT)); load_time_data.SetString("appDefaultPageName", l10n_util::GetStringUTF16(IDS_APP_DEFAULT_PAGE_NAME)); load_time_data.SetString("applaunchtypepinned", l10n_util::GetStringUTF16(IDS_APP_CONTEXT_MENU_OPEN_PINNED)); load_time_data.SetString("applaunchtyperegular", l10n_util::GetStringUTF16(IDS_APP_CONTEXT_MENU_OPEN_REGULAR)); load_time_data.SetString("applaunchtypewindow", l10n_util::GetStringUTF16(IDS_APP_CONTEXT_MENU_OPEN_WINDOW)); load_time_data.SetString("applaunchtypefullscreen", l10n_util::GetStringUTF16(IDS_APP_CONTEXT_MENU_OPEN_FULLSCREEN)); load_time_data.SetString("syncpromotext", l10n_util::GetStringUTF16(IDS_SYNC_START_SYNC_BUTTON_LABEL)); load_time_data.SetString("syncLinkText", l10n_util::GetStringUTF16(IDS_SYNC_ADVANCED_OPTIONS)); load_time_data.SetBoolean("shouldShowSyncLogin", NTPLoginHandler::ShouldShow(profile_)); load_time_data.SetString("otherSessions", l10n_util::GetStringUTF16(IDS_NEW_TAB_OTHER_SESSIONS_LABEL)); load_time_data.SetString("otherSessionsEmpty", l10n_util::GetStringUTF16(IDS_NEW_TAB_OTHER_SESSIONS_EMPTY)); load_time_data.SetString("otherSessionsLearnMoreUrl", l10n_util::GetStringUTF16(IDS_NEW_TAB_OTHER_SESSIONS_LEARN_MORE_URL)); load_time_data.SetString("learnMore", l10n_util::GetStringUTF16(IDS_LEARN_MORE)); load_time_data.SetString("webStoreLink", GetUrlWithLang(GURL(extension_urls::GetWebstoreLaunchURL()))); load_time_data.SetString("appInstallHintText", l10n_util::GetStringUTF16(IDS_NEW_TAB_APP_INSTALL_HINT_LABEL)); load_time_data.SetBoolean("isDiscoveryInNTPEnabled", NewTabUI::IsDiscoveryInNTPEnabled()); load_time_data.SetString("collapseSessionMenuItemText", l10n_util::GetStringUTF16(IDS_NEW_TAB_OTHER_SESSIONS_COLLAPSE_SESSION)); load_time_data.SetString("expandSessionMenuItemText", l10n_util::GetStringUTF16(IDS_NEW_TAB_OTHER_SESSIONS_EXPAND_SESSION)); load_time_data.SetString("restoreSessionMenuItemText", l10n_util::GetStringUTF16(IDS_NEW_TAB_OTHER_SESSIONS_OPEN_ALL)); load_time_data.SetString("learn_more", l10n_util::GetStringUTF16(IDS_LEARN_MORE)); load_time_data.SetString("tile_grid_screenreader_accessible_description", l10n_util::GetStringUTF16(IDS_NEW_TAB_TILE_GRID_ACCESSIBLE_DESCRIPTION)); load_time_data.SetString("page_switcher_change_title", l10n_util::GetStringUTF16(IDS_NEW_TAB_PAGE_SWITCHER_CHANGE_TITLE)); load_time_data.SetString("page_switcher_same_title", l10n_util::GetStringUTF16(IDS_NEW_TAB_PAGE_SWITCHER_SAME_TITLE)); load_time_data.SetString("appsPromoTitle", l10n_util::GetStringUTF16(IDS_NEW_TAB_PAGE_APPS_PROMO_TITLE)); load_time_data.SetBoolean("isSwipeTrackingFromScrollEventsEnabled", is_swipe_tracking_from_scroll_events_enabled_); if (profile_->IsManaged()) should_show_apps_page_ = false; load_time_data.SetBoolean("showApps", should_show_apps_page_); load_time_data.SetBoolean("showWebStoreIcon", !prefs->GetBoolean(prefs::kHideWebStoreIcon)); bool streamlined_hosted_apps = CommandLine::ForCurrentProcess()->HasSwitch( switches::kEnableStreamlinedHostedApps); load_time_data.SetBoolean("enableStreamlinedHostedApps", streamlined_hosted_apps); if (streamlined_hosted_apps) { load_time_data.SetString("applaunchtypetab", l10n_util::GetStringUTF16(IDS_APP_CONTEXT_MENU_OPEN_TAB)); } #if defined(OS_CHROMEOS) load_time_data.SetString("expandMenu", l10n_util::GetStringUTF16(IDS_NEW_TAB_CLOSE_MENU_EXPAND)); #endif NewTabPageHandler::GetLocalizedValues(profile_, &load_time_data); NTPLoginHandler::GetLocalizedValues(profile_, &load_time_data); webui::SetFontAndTextDirection(&load_time_data); load_time_data.SetBoolean("anim", gfx::Animation::ShouldRenderRichAnimation()); ui::ThemeProvider* tp = ThemeServiceFactory::GetForProfile(profile_); int alignment = tp->GetDisplayProperty( ThemeProperties::NTP_BACKGROUND_ALIGNMENT); load_time_data.SetString("themegravity", (alignment & ThemeProperties::ALIGN_RIGHT) ? "right" : ""); if (first_run::IsChromeFirstRun()) { NotificationPromo::HandleClosed(NotificationPromo::NTP_NOTIFICATION_PROMO); } else { NotificationPromo notification_promo; notification_promo.InitFromPrefs(NotificationPromo::NTP_NOTIFICATION_PROMO); if (notification_promo.CanShow()) { load_time_data.SetString("notificationPromoText", notification_promo.promo_text()); DVLOG(1) << "Notification promo:" << notification_promo.promo_text(); } NotificationPromo bubble_promo; bubble_promo.InitFromPrefs(NotificationPromo::NTP_BUBBLE_PROMO); if (bubble_promo.CanShow()) { load_time_data.SetString("bubblePromoText", bubble_promo.promo_text()); DVLOG(1) << "Bubble promo:" << bubble_promo.promo_text(); } } bool show_other_sessions_menu = should_show_other_devices_menu_ && !CommandLine::ForCurrentProcess()->HasSwitch( switches::kDisableNTPOtherSessionsMenu); load_time_data.SetBoolean("showOtherSessionsMenu", show_other_sessions_menu); load_time_data.SetBoolean("isUserSignedIn", !prefs->GetString(prefs::kGoogleServicesUsername).empty()); base::StringPiece new_tab_html(ResourceBundle::GetSharedInstance(). GetRawDataResource(IDR_NEW_TAB_4_HTML)); webui::UseVersion2 version2; std::string full_html = webui::GetI18nTemplateHtml(new_tab_html, &load_time_data); new_tab_html_ = base::RefCountedString::TakeString(&full_html); }
171,148
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: status_t OMXNodeInstance::fillBuffer(OMX::buffer_id buffer, int fenceFd) { Mutex::Autolock autoLock(mLock); OMX_BUFFERHEADERTYPE *header = findBufferHeader(buffer); header->nFilledLen = 0; header->nOffset = 0; header->nFlags = 0; status_t res = storeFenceInMeta_l(header, fenceFd, kPortIndexOutput); if (res != OK) { CLOG_ERROR(fillBuffer::storeFenceInMeta, res, EMPTY_BUFFER(buffer, header, fenceFd)); return res; } { Mutex::Autolock _l(mDebugLock); mOutputBuffersWithCodec.add(header); CLOG_BUMPED_BUFFER(fillBuffer, WITH_STATS(EMPTY_BUFFER(buffer, header, fenceFd))); } OMX_ERRORTYPE err = OMX_FillThisBuffer(mHandle, header); if (err != OMX_ErrorNone) { CLOG_ERROR(fillBuffer, err, EMPTY_BUFFER(buffer, header, fenceFd)); Mutex::Autolock _l(mDebugLock); mOutputBuffersWithCodec.remove(header); } return StatusFromOMXError(err); } Commit Message: DO NOT MERGE omx: check buffer port before using Bug: 28816827 Change-Id: I3d5bad4a1ef96dec544b05bb31cc6f7109aae0a5 CWE ID: CWE-119
status_t OMXNodeInstance::fillBuffer(OMX::buffer_id buffer, int fenceFd) { Mutex::Autolock autoLock(mLock); OMX_BUFFERHEADERTYPE *header = findBufferHeader(buffer, kPortIndexOutput); if (header == NULL) { return BAD_VALUE; } header->nFilledLen = 0; header->nOffset = 0; header->nFlags = 0; status_t res = storeFenceInMeta_l(header, fenceFd, kPortIndexOutput); if (res != OK) { CLOG_ERROR(fillBuffer::storeFenceInMeta, res, EMPTY_BUFFER(buffer, header, fenceFd)); return res; } { Mutex::Autolock _l(mDebugLock); mOutputBuffersWithCodec.add(header); CLOG_BUMPED_BUFFER(fillBuffer, WITH_STATS(EMPTY_BUFFER(buffer, header, fenceFd))); } OMX_ERRORTYPE err = OMX_FillThisBuffer(mHandle, header); if (err != OMX_ErrorNone) { CLOG_ERROR(fillBuffer, err, EMPTY_BUFFER(buffer, header, fenceFd)); Mutex::Autolock _l(mDebugLock); mOutputBuffersWithCodec.remove(header); } return StatusFromOMXError(err); }
173,527
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: convert_to_decimal (mpn_t a, size_t extra_zeroes) { mp_limb_t *a_ptr = a.limbs; size_t a_len = a.nlimbs; /* 0.03345 is slightly larger than log(2)/(9*log(10)). */ size_t c_len = 9 * ((size_t)(a_len * (GMP_LIMB_BITS * 0.03345f)) + 1); char *c_ptr = (char *) malloc (xsum (c_len, extra_zeroes)); if (c_ptr != NULL) { char *d_ptr = c_ptr; for (; extra_zeroes > 0; extra_zeroes--) *d_ptr++ = '0'; while (a_len > 0) { /* Divide a by 10^9, in-place. */ mp_limb_t remainder = 0; mp_limb_t *ptr = a_ptr + a_len; size_t count; for (count = a_len; count > 0; count--) { mp_twolimb_t num = ((mp_twolimb_t) remainder << GMP_LIMB_BITS) | *--ptr; *ptr = num / 1000000000; remainder = num % 1000000000; } /* Store the remainder as 9 decimal digits. */ for (count = 9; count > 0; count--) { *d_ptr++ = '0' + (remainder % 10); remainder = remainder / 10; } /* Normalize a. */ if (a_ptr[a_len - 1] == 0) a_len--; } /* Remove leading zeroes. */ while (d_ptr > c_ptr && d_ptr[-1] == '0') d_ptr--; /* But keep at least one zero. */ if (d_ptr == c_ptr) *d_ptr++ = '0'; /* Terminate the string. */ *d_ptr = '\0'; } return c_ptr; } Commit Message: vasnprintf: Fix heap memory overrun bug. Reported by Ben Pfaff <[email protected]> in <https://lists.gnu.org/archive/html/bug-gnulib/2018-09/msg00107.html>. * lib/vasnprintf.c (convert_to_decimal): Allocate one more byte of memory. * tests/test-vasnprintf.c (test_function): Add another test. CWE ID: CWE-119
convert_to_decimal (mpn_t a, size_t extra_zeroes) { mp_limb_t *a_ptr = a.limbs; size_t a_len = a.nlimbs; /* 0.03345 is slightly larger than log(2)/(9*log(10)). */ size_t c_len = 9 * ((size_t)(a_len * (GMP_LIMB_BITS * 0.03345f)) + 1); /* We need extra_zeroes bytes for zeroes, followed by c_len bytes for the digits of a, followed by 1 byte for the terminating NUL. */ char *c_ptr = (char *) malloc (xsum (xsum (extra_zeroes, c_len), 1)); if (c_ptr != NULL) { char *d_ptr = c_ptr; for (; extra_zeroes > 0; extra_zeroes--) *d_ptr++ = '0'; while (a_len > 0) { /* Divide a by 10^9, in-place. */ mp_limb_t remainder = 0; mp_limb_t *ptr = a_ptr + a_len; size_t count; for (count = a_len; count > 0; count--) { mp_twolimb_t num = ((mp_twolimb_t) remainder << GMP_LIMB_BITS) | *--ptr; *ptr = num / 1000000000; remainder = num % 1000000000; } /* Store the remainder as 9 decimal digits. */ for (count = 9; count > 0; count--) { *d_ptr++ = '0' + (remainder % 10); remainder = remainder / 10; } /* Normalize a. */ if (a_ptr[a_len - 1] == 0) a_len--; } /* Remove leading zeroes. */ while (d_ptr > c_ptr && d_ptr[-1] == '0') d_ptr--; /* But keep at least one zero. */ if (d_ptr == c_ptr) *d_ptr++ = '0'; /* Terminate the string. */ *d_ptr = '\0'; } return c_ptr; }
169,013
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: EncodedJSValue JSC_HOST_CALL jsTestObjPrototypeFunctionConvert5(ExecState* exec) { JSValue thisValue = exec->hostThisValue(); if (!thisValue.inherits(&JSTestObj::s_info)) return throwVMTypeError(exec); JSTestObj* castedThis = jsCast<JSTestObj*>(asObject(thisValue)); ASSERT_GC_OBJECT_INHERITS(castedThis, &JSTestObj::s_info); TestObj* impl = static_cast<TestObj*>(castedThis->impl()); if (exec->argumentCount() < 1) return throwVMError(exec, createTypeError(exec, "Not enough arguments")); e* (toe(MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined))); if (exec->hadException()) return JSValue::encode(jsUndefined()); impl->convert5(); return JSValue::encode(jsUndefined()); } Commit Message: [JSC] Implement a helper method createNotEnoughArgumentsError() https://bugs.webkit.org/show_bug.cgi?id=85102 Reviewed by Geoffrey Garen. In bug 84787, kbr@ requested to avoid hard-coding createTypeError(exec, "Not enough arguments") here and there. This patch implements createNotEnoughArgumentsError(exec) and uses it in JSC bindings. c.f. a corresponding bug for V8 bindings is bug 85097. Source/JavaScriptCore: * runtime/Error.cpp: (JSC::createNotEnoughArgumentsError): (JSC): * runtime/Error.h: (JSC): Source/WebCore: Test: bindings/scripts/test/TestObj.idl * bindings/scripts/CodeGeneratorJS.pm: Modified as described above. (GenerateArgumentsCountCheck): * bindings/js/JSDataViewCustom.cpp: Ditto. (WebCore::getDataViewMember): (WebCore::setDataViewMember): * bindings/js/JSDeprecatedPeerConnectionCustom.cpp: (WebCore::JSDeprecatedPeerConnectionConstructor::constructJSDeprecatedPeerConnection): * bindings/js/JSDirectoryEntryCustom.cpp: (WebCore::JSDirectoryEntry::getFile): (WebCore::JSDirectoryEntry::getDirectory): * bindings/js/JSSharedWorkerCustom.cpp: (WebCore::JSSharedWorkerConstructor::constructJSSharedWorker): * bindings/js/JSWebKitMutationObserverCustom.cpp: (WebCore::JSWebKitMutationObserverConstructor::constructJSWebKitMutationObserver): (WebCore::JSWebKitMutationObserver::observe): * bindings/js/JSWorkerCustom.cpp: (WebCore::JSWorkerConstructor::constructJSWorker): * bindings/scripts/test/JS/JSFloat64Array.cpp: Updated run-bindings-tests. (WebCore::jsFloat64ArrayPrototypeFunctionFoo): * bindings/scripts/test/JS/JSTestActiveDOMObject.cpp: (WebCore::jsTestActiveDOMObjectPrototypeFunctionExcitingFunction): (WebCore::jsTestActiveDOMObjectPrototypeFunctionPostMessage): * bindings/scripts/test/JS/JSTestCustomNamedGetter.cpp: (WebCore::jsTestCustomNamedGetterPrototypeFunctionAnotherFunction): * bindings/scripts/test/JS/JSTestEventTarget.cpp: (WebCore::jsTestEventTargetPrototypeFunctionItem): (WebCore::jsTestEventTargetPrototypeFunctionAddEventListener): (WebCore::jsTestEventTargetPrototypeFunctionRemoveEventListener): (WebCore::jsTestEventTargetPrototypeFunctionDispatchEvent): * bindings/scripts/test/JS/JSTestInterface.cpp: (WebCore::JSTestInterfaceConstructor::constructJSTestInterface): (WebCore::jsTestInterfacePrototypeFunctionSupplementalMethod2): * bindings/scripts/test/JS/JSTestMediaQueryListListener.cpp: (WebCore::jsTestMediaQueryListListenerPrototypeFunctionMethod): * bindings/scripts/test/JS/JSTestNamedConstructor.cpp: (WebCore::JSTestNamedConstructorNamedConstructor::constructJSTestNamedConstructor): * bindings/scripts/test/JS/JSTestObj.cpp: (WebCore::JSTestObjConstructor::constructJSTestObj): (WebCore::jsTestObjPrototypeFunctionVoidMethodWithArgs): (WebCore::jsTestObjPrototypeFunctionIntMethodWithArgs): (WebCore::jsTestObjPrototypeFunctionObjMethodWithArgs): (WebCore::jsTestObjPrototypeFunctionMethodWithSequenceArg): (WebCore::jsTestObjPrototypeFunctionMethodReturningSequence): (WebCore::jsTestObjPrototypeFunctionMethodThatRequiresAllArgsAndThrows): (WebCore::jsTestObjPrototypeFunctionSerializedValue): (WebCore::jsTestObjPrototypeFunctionIdbKey): (WebCore::jsTestObjPrototypeFunctionOptionsObject): (WebCore::jsTestObjPrototypeFunctionAddEventListener): (WebCore::jsTestObjPrototypeFunctionRemoveEventListener): (WebCore::jsTestObjPrototypeFunctionMethodWithNonOptionalArgAndOptionalArg): (WebCore::jsTestObjPrototypeFunctionMethodWithNonOptionalArgAndTwoOptionalArgs): (WebCore::jsTestObjPrototypeFunctionMethodWithCallbackArg): (WebCore::jsTestObjPrototypeFunctionMethodWithNonCallbackArgAndCallbackArg): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod1): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod2): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod3): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod4): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod5): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod6): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod7): (WebCore::jsTestObjConstructorFunctionClassMethod2): (WebCore::jsTestObjConstructorFunctionOverloadedMethod11): (WebCore::jsTestObjConstructorFunctionOverloadedMethod12): (WebCore::jsTestObjPrototypeFunctionMethodWithUnsignedLongArray): (WebCore::jsTestObjPrototypeFunctionConvert1): (WebCore::jsTestObjPrototypeFunctionConvert2): (WebCore::jsTestObjPrototypeFunctionConvert3): (WebCore::jsTestObjPrototypeFunctionConvert4): (WebCore::jsTestObjPrototypeFunctionConvert5): (WebCore::jsTestObjPrototypeFunctionStrictFunction): * bindings/scripts/test/JS/JSTestSerializedScriptValueInterface.cpp: (WebCore::JSTestSerializedScriptValueInterfaceConstructor::constructJSTestSerializedScriptValueInterface): (WebCore::jsTestSerializedScriptValueInterfacePrototypeFunctionAcceptTransferList): git-svn-id: svn://svn.chromium.org/blink/trunk@115536 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-20
EncodedJSValue JSC_HOST_CALL jsTestObjPrototypeFunctionConvert5(ExecState* exec) { JSValue thisValue = exec->hostThisValue(); if (!thisValue.inherits(&JSTestObj::s_info)) return throwVMTypeError(exec); JSTestObj* castedThis = jsCast<JSTestObj*>(asObject(thisValue)); ASSERT_GC_OBJECT_INHERITS(castedThis, &JSTestObj::s_info); TestObj* impl = static_cast<TestObj*>(castedThis->impl()); if (exec->argumentCount() < 1) return throwVMError(exec, createNotEnoughArgumentsError(exec)); e* (toe(MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined))); if (exec->hadException()) return JSValue::encode(jsUndefined()); impl->convert5(); return JSValue::encode(jsUndefined()); }
170,587
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool Track::GetLacing() const { return m_info.lacing; } 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 Track::GetLacing() const
174,334
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void MessageService::OpenChannelToTab( int source_process_id, int source_routing_id, int receiver_port_id, int tab_id, const std::string& extension_id, const std::string& channel_name) { content::RenderProcessHost* source = content::RenderProcessHost::FromID(source_process_id); if (!source) return; Profile* profile = Profile::FromBrowserContext(source->GetBrowserContext()); WebContents* contents = NULL; scoped_ptr<MessagePort> receiver; if (ExtensionTabUtil::GetTabById(tab_id, profile, true, NULL, NULL, &contents, NULL)) { receiver.reset(new ExtensionMessagePort( contents->GetRenderProcessHost(), contents->GetRenderViewHost()->GetRoutingID(), extension_id)); } if (contents && contents->GetController().NeedsReload()) { ExtensionMessagePort port(source, MSG_ROUTING_CONTROL, extension_id); port.DispatchOnDisconnect(GET_OPPOSITE_PORT_ID(receiver_port_id), true); return; } WebContents* source_contents = tab_util::GetWebContentsByID( source_process_id, source_routing_id); std::string tab_json = "null"; if (source_contents) { scoped_ptr<DictionaryValue> tab_value(ExtensionTabUtil::CreateTabValue( source_contents, ExtensionTabUtil::INCLUDE_PRIVACY_SENSITIVE_FIELDS)); base::JSONWriter::Write(tab_value.get(), &tab_json); } scoped_ptr<OpenChannelParams> params(new OpenChannelParams(source, tab_json, receiver.release(), receiver_port_id, extension_id, extension_id, channel_name)); OpenChannelImpl(params.Pass()); } Commit Message: Do not pass URLs in onUpdated events to extensions unless they have the "tabs" permission. BUG=168442 Review URL: https://chromiumcodereview.appspot.com/11824004 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@176406 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264
void MessageService::OpenChannelToTab( int source_process_id, int source_routing_id, int receiver_port_id, int tab_id, const std::string& extension_id, const std::string& channel_name) { content::RenderProcessHost* source = content::RenderProcessHost::FromID(source_process_id); if (!source) return; Profile* profile = Profile::FromBrowserContext(source->GetBrowserContext()); WebContents* contents = NULL; scoped_ptr<MessagePort> receiver; if (ExtensionTabUtil::GetTabById(tab_id, profile, true, NULL, NULL, &contents, NULL)) { receiver.reset(new ExtensionMessagePort( contents->GetRenderProcessHost(), contents->GetRenderViewHost()->GetRoutingID(), extension_id)); } if (contents && contents->GetController().NeedsReload()) { ExtensionMessagePort port(source, MSG_ROUTING_CONTROL, extension_id); port.DispatchOnDisconnect(GET_OPPOSITE_PORT_ID(receiver_port_id), true); return; } WebContents* source_contents = tab_util::GetWebContentsByID( source_process_id, source_routing_id); std::string tab_json = "null"; if (source_contents) { scoped_ptr<DictionaryValue> tab_value(ExtensionTabUtil::CreateTabValue( source_contents)); base::JSONWriter::Write(tab_value.get(), &tab_json); } scoped_ptr<OpenChannelParams> params(new OpenChannelParams(source, tab_json, receiver.release(), receiver_port_id, extension_id, extension_id, channel_name)); OpenChannelImpl(params.Pass()); }
171,448
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: LayerTreeHost::LayerTreeHost(InitParams* params, CompositorMode mode) : micro_benchmark_controller_(this), image_worker_task_runner_(params->image_worker_task_runner), compositor_mode_(mode), ui_resource_manager_(base::MakeUnique<UIResourceManager>()), client_(params->client), rendering_stats_instrumentation_(RenderingStatsInstrumentation::Create()), settings_(*params->settings), debug_state_(settings_.initial_debug_state), id_(s_layer_tree_host_sequence_number.GetNext() + 1), task_graph_runner_(params->task_graph_runner), event_listener_properties_(), mutator_host_(params->mutator_host) { DCHECK(task_graph_runner_); DCHECK(!settings_.enable_checker_imaging || image_worker_task_runner_); DCHECK(!settings_.enable_checker_imaging || settings_.image_decode_tasks_enabled); mutator_host_->SetMutatorHostClient(this); rendering_stats_instrumentation_->set_record_rendering_stats( debug_state_.RecordRenderingStats()); } Commit Message: (Reland) Discard compositor frames from unloaded web content This is a reland of https://codereview.chromium.org/2707243005/ with a small change to fix an uninitialized memory error that fails on MSAN bots. BUG=672847 [email protected], [email protected] CQ_INCLUDE_TRYBOTS=master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_site_isolation Review-Url: https://codereview.chromium.org/2731283003 Cr-Commit-Position: refs/heads/master@{#454954} CWE ID: CWE-362
LayerTreeHost::LayerTreeHost(InitParams* params, CompositorMode mode) : micro_benchmark_controller_(this), image_worker_task_runner_(params->image_worker_task_runner), compositor_mode_(mode), ui_resource_manager_(base::MakeUnique<UIResourceManager>()), client_(params->client), rendering_stats_instrumentation_(RenderingStatsInstrumentation::Create()), settings_(*params->settings), debug_state_(settings_.initial_debug_state), id_(s_layer_tree_host_sequence_number.GetNext() + 1), task_graph_runner_(params->task_graph_runner), content_source_id_(0), event_listener_properties_(), mutator_host_(params->mutator_host) { DCHECK(task_graph_runner_); DCHECK(!settings_.enable_checker_imaging || image_worker_task_runner_); DCHECK(!settings_.enable_checker_imaging || settings_.image_decode_tasks_enabled); mutator_host_->SetMutatorHostClient(this); rendering_stats_instrumentation_->set_record_rendering_stats( debug_state_.RecordRenderingStats()); }
172,394
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void nfs4_open_confirm_release(void *calldata) { struct nfs4_opendata *data = calldata; struct nfs4_state *state = NULL; /* If this request hasn't been cancelled, do nothing */ if (data->cancelled == 0) goto out_free; /* In case of error, no cleanup! */ if (!data->rpc_done) goto out_free; state = nfs4_opendata_to_nfs4_state(data); if (!IS_ERR(state)) nfs4_close_state(&data->path, state, data->o_arg.open_flags); out_free: nfs4_opendata_put(data); } Commit Message: NFSv4: Convert the open and close ops to use fmode Signed-off-by: Trond Myklebust <[email protected]> CWE ID:
static void nfs4_open_confirm_release(void *calldata) { struct nfs4_opendata *data = calldata; struct nfs4_state *state = NULL; /* If this request hasn't been cancelled, do nothing */ if (data->cancelled == 0) goto out_free; /* In case of error, no cleanup! */ if (!data->rpc_done) goto out_free; state = nfs4_opendata_to_nfs4_state(data); if (!IS_ERR(state)) nfs4_close_state(&data->path, state, data->o_arg.fmode); out_free: nfs4_opendata_put(data); }
165,694
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static ssize_t ucma_write(struct file *filp, const char __user *buf, size_t len, loff_t *pos) { struct ucma_file *file = filp->private_data; struct rdma_ucm_cmd_hdr hdr; ssize_t ret; if (len < sizeof(hdr)) return -EINVAL; if (copy_from_user(&hdr, buf, sizeof(hdr))) return -EFAULT; if (hdr.cmd >= ARRAY_SIZE(ucma_cmd_table)) return -EINVAL; if (hdr.in + sizeof(hdr) > len) return -EINVAL; if (!ucma_cmd_table[hdr.cmd]) return -ENOSYS; ret = ucma_cmd_table[hdr.cmd](file, buf + sizeof(hdr), hdr.in, hdr.out); if (!ret) ret = len; return ret; } Commit Message: IB/security: Restrict use of the write() interface The drivers/infiniband stack uses write() as a replacement for bi-directional ioctl(). This is not safe. There are ways to trigger write calls that result in the return structure that is normally written to user space being shunted off to user specified kernel memory instead. For the immediate repair, detect and deny suspicious accesses to the write API. For long term, update the user space libraries and the kernel API to something that doesn't present the same security vulnerabilities (likely a structured ioctl() interface). The impacted uAPI interfaces are generally only available if hardware from drivers/infiniband is installed in the system. Reported-by: Jann Horn <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> Signed-off-by: Jason Gunthorpe <[email protected]> [ Expanded check to all known write() entry points ] Cc: [email protected] Signed-off-by: Doug Ledford <[email protected]> CWE ID: CWE-264
static ssize_t ucma_write(struct file *filp, const char __user *buf, size_t len, loff_t *pos) { struct ucma_file *file = filp->private_data; struct rdma_ucm_cmd_hdr hdr; ssize_t ret; if (WARN_ON_ONCE(!ib_safe_file_access(filp))) return -EACCES; if (len < sizeof(hdr)) return -EINVAL; if (copy_from_user(&hdr, buf, sizeof(hdr))) return -EFAULT; if (hdr.cmd >= ARRAY_SIZE(ucma_cmd_table)) return -EINVAL; if (hdr.in + sizeof(hdr) > len) return -EINVAL; if (!ucma_cmd_table[hdr.cmd]) return -ENOSYS; ret = ucma_cmd_table[hdr.cmd](file, buf + sizeof(hdr), hdr.in, hdr.out); if (!ret) ret = len; return ret; }
167,239
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void DownloadRequestLimiter::TabDownloadState::SetDownloadStatusAndNotifyImpl( DownloadStatus status, ContentSetting setting) { DCHECK((GetSettingFromDownloadStatus(status) == setting) || (GetDownloadStatusFromSetting(setting) == status)) << "status " << status << " and setting " << setting << " do not correspond to each other"; ContentSetting last_setting = GetSettingFromDownloadStatus(status_); DownloadUiStatus last_ui_status = ui_status_; status_ = status; ui_status_ = GetUiStatusFromDownloadStatus(status_, download_seen_); if (!web_contents()) return; if (last_setting == setting && last_ui_status == ui_status_) return; content::NotificationService::current()->Notify( chrome::NOTIFICATION_WEB_CONTENT_SETTINGS_CHANGED, content::Source<content::WebContents>(web_contents()), content::NotificationService::NoDetails()); } Commit Message: Don't reset TabDownloadState on history back/forward Currently performing forward/backward on a tab will reset the TabDownloadState. Which allows javascript code to do trigger multiple downloads. This CL disables that behavior by not resetting the TabDownloadState on forward/back. It is still possible to reset the TabDownloadState through user gesture or using browser initiated download. BUG=848535 Change-Id: I7f9bf6e8fb759b4dcddf5ac0c214e8c6c9f48863 Reviewed-on: https://chromium-review.googlesource.com/1108959 Commit-Queue: Min Qin <[email protected]> Reviewed-by: Xing Liu <[email protected]> Cr-Commit-Position: refs/heads/master@{#574437} CWE ID:
void DownloadRequestLimiter::TabDownloadState::SetDownloadStatusAndNotifyImpl( DownloadStatus status, ContentSetting setting) { DCHECK((GetSettingFromDownloadStatus(status) == setting) || (GetDownloadStatusFromSetting(setting) == status)) << "status " << status << " and setting " << setting << " do not correspond to each other"; ContentSetting last_setting = GetSettingFromDownloadStatus(status_); DownloadUiStatus last_ui_status = ui_status_; status_ = status; ui_status_ = GetUiStatusFromDownloadStatus(status_, download_seen_); if (!web_contents()) return; if (status_ == PROMPT_BEFORE_DOWNLOAD || status_ == DOWNLOADS_NOT_ALLOWED) { if (!initial_page_host_.empty()) restricted_hosts_.emplace(initial_page_host_); } if (last_setting == setting && last_ui_status == ui_status_) return; content::NotificationService::current()->Notify( chrome::NOTIFICATION_WEB_CONTENT_SETTINGS_CHANGED, content::Source<content::WebContents>(web_contents()), content::NotificationService::NoDetails()); }
173,190
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool PluginInfoMessageFilter::Context::FindEnabledPlugin( int render_view_id, const GURL& url, const GURL& top_origin_url, const std::string& mime_type, ChromeViewHostMsg_GetPluginInfo_Status* status, WebPluginInfo* plugin, std::string* actual_mime_type, scoped_ptr<PluginMetadata>* plugin_metadata) const { bool allow_wildcard = true; std::vector<WebPluginInfo> matching_plugins; std::vector<std::string> mime_types; PluginService::GetInstance()->GetPluginInfoArray( url, mime_type, allow_wildcard, &matching_plugins, &mime_types); if (matching_plugins.empty()) { status->value = ChromeViewHostMsg_GetPluginInfo_Status::kNotFound; return false; } content::PluginServiceFilter* filter = PluginService::GetInstance()->GetFilter(); size_t i = 0; for (; i < matching_plugins.size(); ++i) { if (!filter || filter->IsPluginEnabled(render_process_id_, render_view_id, resource_context_, url, top_origin_url, &matching_plugins[i])) { break; } } bool enabled = i < matching_plugins.size(); if (!enabled) { i = 0; status->value = ChromeViewHostMsg_GetPluginInfo_Status::kDisabled; } *plugin = matching_plugins[i]; *actual_mime_type = mime_types[i]; if (plugin_metadata) *plugin_metadata = PluginFinder::GetInstance()->GetPluginMetadata(*plugin); return enabled; } Commit Message: Follow-on fixes and naming changes for https://codereview.chromium.org/12086077/ BUG=172573 Review URL: https://codereview.chromium.org/12177018 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@180600 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-287
bool PluginInfoMessageFilter::Context::FindEnabledPlugin( int render_view_id, const GURL& url, const GURL& top_origin_url, const std::string& mime_type, ChromeViewHostMsg_GetPluginInfo_Status* status, WebPluginInfo* plugin, std::string* actual_mime_type, scoped_ptr<PluginMetadata>* plugin_metadata) const { bool allow_wildcard = true; std::vector<WebPluginInfo> matching_plugins; std::vector<std::string> mime_types; PluginService::GetInstance()->GetPluginInfoArray( url, mime_type, allow_wildcard, &matching_plugins, &mime_types); if (matching_plugins.empty()) { status->value = ChromeViewHostMsg_GetPluginInfo_Status::kNotFound; return false; } content::PluginServiceFilter* filter = PluginService::GetInstance()->GetFilter(); size_t i = 0; for (; i < matching_plugins.size(); ++i) { if (!filter || filter->IsPluginAvailable(render_process_id_, render_view_id, resource_context_, url, top_origin_url, &matching_plugins[i])) { break; } } bool enabled = i < matching_plugins.size(); if (!enabled) { i = 0; status->value = ChromeViewHostMsg_GetPluginInfo_Status::kDisabled; } *plugin = matching_plugins[i]; *actual_mime_type = mime_types[i]; if (plugin_metadata) *plugin_metadata = PluginFinder::GetInstance()->GetPluginMetadata(*plugin); return enabled; }
171,471
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void IBusBusNameOwnerChangedCallback( IBusBus* bus, const gchar* name, const gchar* old_name, const gchar* new_name, gpointer user_data) { DCHECK(name); DCHECK(old_name); DCHECK(new_name); DLOG(INFO) << "Name owner is changed: name=" << name << ", old_name=" << old_name << ", new_name=" << new_name; if (name != std::string("org.freedesktop.IBus.Config")) { return; } const std::string empty_string; if (old_name != empty_string || new_name == empty_string) { LOG(WARNING) << "Unexpected name owner change: name=" << name << ", old_name=" << old_name << ", new_name=" << new_name; return; } LOG(INFO) << "IBus config daemon is started. Recovering ibus_config_"; g_return_if_fail(user_data); InputMethodStatusConnection* self = static_cast<InputMethodStatusConnection*>(user_data); self->MaybeRestoreConnections(); } 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
static void IBusBusNameOwnerChangedCallback( void IBusBusNameOwnerChanged(IBusBus* bus, const gchar* name, const gchar* old_name, const gchar* new_name) { DCHECK(name); DCHECK(old_name); DCHECK(new_name); VLOG(1) << "Name owner is changed: name=" << name << ", old_name=" << old_name << ", new_name=" << new_name; if (name != std::string("org.freedesktop.IBus.Config")) { return; } const std::string empty_string; if (old_name != empty_string || new_name == empty_string) { LOG(WARNING) << "Unexpected name owner change: name=" << name << ", old_name=" << old_name << ", new_name=" << new_name; // |OnConnectionChange| with false here to allow Chrome to return; } VLOG(1) << "IBus config daemon is started. Recovering ibus_config_"; // successfully created, |OnConnectionChange| will be called to MaybeRestoreConnections(); }
170,539
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: WORD32 ih264d_mark_err_slice_skip(dec_struct_t * ps_dec, WORD32 num_mb_skip, UWORD8 u1_is_idr_slice, UWORD16 u2_frame_num, pocstruct_t *ps_cur_poc, WORD32 prev_slice_err) { WORD32 i2_cur_mb_addr; UWORD32 u1_num_mbs, u1_num_mbsNby2; UWORD32 u1_mb_idx = ps_dec->u1_mb_idx; UWORD32 i2_mb_skip_run; UWORD32 u1_num_mbs_next, u1_end_of_row; const UWORD32 i2_pic_wdin_mbs = ps_dec->u2_frm_wd_in_mbs; UWORD32 u1_slice_end; UWORD32 u1_tfr_n_mb; UWORD32 u1_decode_nmb; dec_bit_stream_t * const ps_bitstrm = ps_dec->ps_bitstrm; dec_slice_params_t * ps_slice = ps_dec->ps_cur_slice; UWORD32 *pu4_bitstrm_buf = ps_bitstrm->pu4_buffer; UWORD32 *pu4_bitstrm_ofst = &ps_bitstrm->u4_ofst; deblk_mb_t *ps_cur_deblk_mb; dec_mb_info_t *ps_cur_mb_info; parse_pmbarams_t *ps_parse_mb_data; UWORD32 u1_inter_mb_type; UWORD32 u1_deblk_mb_type; UWORD16 u2_total_mbs_coded; UWORD32 u1_mbaff = ps_slice->u1_mbaff_frame_flag; parse_part_params_t *ps_part_info; WORD32 ret; if(ps_dec->ps_dec_err_status->u1_err_flag & REJECT_CUR_PIC) { ih264d_err_pic_dispbuf_mgr(ps_dec); return 0; } ps_dec->ps_dpb_cmds->u1_long_term_reference_flag = 0; if(prev_slice_err == 1) { /* first slice - missing/header corruption */ ps_dec->ps_cur_slice->u2_frame_num = u2_frame_num; if(!ps_dec->u1_first_slice_in_stream) { ih264d_end_of_pic(ps_dec, u1_is_idr_slice, ps_dec->ps_cur_slice->u2_frame_num); ps_dec->s_cur_pic_poc.u2_frame_num = ps_dec->ps_cur_slice->u2_frame_num; } { WORD32 i, j, poc = 0; ps_dec->ps_cur_slice->u2_first_mb_in_slice = 0; ps_dec->pf_mvpred = ih264d_mvpred_nonmbaff; ps_dec->p_form_mb_part_info = ih264d_form_mb_part_info_bp; ps_dec->p_motion_compensate = ih264d_motion_compensate_bp; if(ps_dec->ps_cur_pic != NULL) poc = ps_dec->ps_cur_pic->i4_poc + 2; j = 0; for(i = 0; i < MAX_NUM_PIC_PARAMS; i++) if(ps_dec->ps_pps[i].u1_is_valid == TRUE) j = i; { ps_dec->ps_cur_slice->u1_bottom_field_flag = 0; ps_dec->ps_cur_slice->u1_field_pic_flag = 0; ps_dec->ps_cur_slice->u1_slice_type = P_SLICE; ps_dec->ps_cur_slice->u1_nal_ref_idc = 1; ps_dec->ps_cur_slice->u1_nal_unit_type = 1; ret = ih264d_start_of_pic(ps_dec, poc, ps_cur_poc, ps_dec->ps_cur_slice->u2_frame_num, &ps_dec->ps_pps[j]); if(ret != OK) { return ret; } } ps_dec->ps_ref_pic_buf_lx[0][0]->u1_pic_buf_id = 0; ps_dec->u4_output_present = 0; { ih264d_get_next_display_field(ps_dec, ps_dec->ps_out_buffer, &(ps_dec->s_disp_op)); /* If error code is non-zero then there is no buffer available for display, hence avoid format conversion */ if(0 != ps_dec->s_disp_op.u4_error_code) { ps_dec->u4_fmt_conv_cur_row = ps_dec->s_disp_frame_info.u4_y_ht; } else ps_dec->u4_output_present = 1; } if(ps_dec->u1_separate_parse == 1) { if(ps_dec->u4_dec_thread_created == 0) { ithread_create(ps_dec->pv_dec_thread_handle, NULL, (void *)ih264d_decode_picture_thread, (void *)ps_dec); ps_dec->u4_dec_thread_created = 1; } if((ps_dec->u4_num_cores == 3) && ((ps_dec->u4_app_disable_deblk_frm == 0) || ps_dec->i1_recon_in_thread3_flag) && (ps_dec->u4_bs_deblk_thread_created == 0)) { ps_dec->u4_start_recon_deblk = 0; ithread_create(ps_dec->pv_bs_deblk_thread_handle, NULL, (void *)ih264d_recon_deblk_thread, (void *)ps_dec); ps_dec->u4_bs_deblk_thread_created = 1; } } } } else { dec_slice_struct_t *ps_parse_cur_slice; ps_parse_cur_slice = ps_dec->ps_dec_slice_buf + ps_dec->u2_cur_slice_num; if(ps_dec->u1_slice_header_done && ps_parse_cur_slice == ps_dec->ps_parse_cur_slice) { u1_num_mbs = ps_dec->u4_num_mbs_cur_nmb; if(u1_num_mbs) { ps_cur_mb_info = ps_dec->ps_nmb_info + u1_num_mbs - 1; } else { if(ps_dec->u1_separate_parse) { ps_cur_mb_info = ps_dec->ps_nmb_info - 1; } else { ps_cur_mb_info = ps_dec->ps_nmb_info + ps_dec->u4_num_mbs_prev_nmb - 1; } } ps_dec->u2_mby = ps_cur_mb_info->u2_mby; ps_dec->u2_mbx = ps_cur_mb_info->u2_mbx; ps_dec->u1_mb_ngbr_availablity = ps_cur_mb_info->u1_mb_ngbr_availablity; ps_dec->pv_parse_tu_coeff_data = ps_dec->pv_prev_mb_parse_tu_coeff_data; ps_dec->u2_cur_mb_addr--; ps_dec->i4_submb_ofst -= SUB_BLK_SIZE; if(u1_num_mbs) { if (ps_dec->u1_pr_sl_type == P_SLICE || ps_dec->u1_pr_sl_type == B_SLICE) { ps_dec->pf_mvpred_ref_tfr_nby2mb(ps_dec, u1_mb_idx, u1_num_mbs); ps_dec->ps_part = ps_dec->ps_parse_part_params; } u1_num_mbs_next = i2_pic_wdin_mbs - ps_dec->u2_mbx - 1; u1_end_of_row = (!u1_num_mbs_next) && (!(u1_mbaff && (u1_num_mbs & 0x01))); u1_slice_end = 1; u1_tfr_n_mb = 1; ps_cur_mb_info->u1_end_of_slice = u1_slice_end; if(ps_dec->u1_separate_parse) { ih264d_parse_tfr_nmb(ps_dec, u1_mb_idx, u1_num_mbs, u1_num_mbs_next, u1_tfr_n_mb, u1_end_of_row); ps_dec->ps_nmb_info += u1_num_mbs; } else { ih264d_decode_recon_tfr_nmb(ps_dec, u1_mb_idx, u1_num_mbs, u1_num_mbs_next, u1_tfr_n_mb, u1_end_of_row); } ps_dec->u2_total_mbs_coded += u1_num_mbs; ps_dec->u1_mb_idx = 0; ps_dec->u4_num_mbs_cur_nmb = 0; } if(ps_dec->u2_total_mbs_coded >= ps_dec->u2_frm_ht_in_mbs * ps_dec->u2_frm_wd_in_mbs) { ps_dec->u1_pic_decode_done = 1; return 0; } ps_dec->u2_cur_slice_num++; ps_dec->i2_prev_slice_mbx = ps_dec->u2_mbx; ps_dec->i2_prev_slice_mby = ps_dec->u2_mby; ps_dec->ps_parse_cur_slice++; } else { ps_dec->ps_parse_cur_slice = ps_dec->ps_dec_slice_buf + ps_dec->u2_cur_slice_num; } } /******************************************************/ /* Initializations to new slice */ /******************************************************/ { WORD32 num_entries; WORD32 size; UWORD8 *pu1_buf; num_entries = MAX_FRAMES; if((1 >= ps_dec->ps_cur_sps->u1_num_ref_frames) && (0 == ps_dec->i4_display_delay)) { num_entries = 1; } num_entries = ((2 * num_entries) + 1); if(BASE_PROFILE_IDC != ps_dec->ps_cur_sps->u1_profile_idc) { num_entries *= 2; } size = num_entries * sizeof(void *); size += PAD_MAP_IDX_POC * sizeof(void *); pu1_buf = (UWORD8 *)ps_dec->pv_map_ref_idx_to_poc_buf; pu1_buf += size * ps_dec->u2_cur_slice_num; ps_dec->ps_parse_cur_slice->ppv_map_ref_idx_to_poc = (volatile void **)pu1_buf; } ps_dec->ps_cur_slice->u2_first_mb_in_slice = ps_dec->u2_total_mbs_coded << u1_mbaff; ps_dec->ps_cur_slice->i1_slice_alpha_c0_offset = 0; ps_dec->ps_cur_slice->i1_slice_beta_offset = 0; if(ps_dec->ps_cur_slice->u1_field_pic_flag) ps_dec->u2_prv_frame_num = ps_dec->ps_cur_slice->u2_frame_num; ps_dec->ps_parse_cur_slice->u4_first_mb_in_slice = ps_dec->u2_total_mbs_coded << u1_mbaff; ps_dec->ps_parse_cur_slice->u2_log2Y_crwd = ps_dec->ps_cur_slice->u2_log2Y_crwd; if(ps_dec->u1_separate_parse) { ps_dec->ps_parse_cur_slice->pv_tu_coeff_data_start = ps_dec->pv_parse_tu_coeff_data; } else { ps_dec->pv_proc_tu_coeff_data = ps_dec->pv_parse_tu_coeff_data; } /******************************************************/ /* Initializations specific to P slice */ /******************************************************/ u1_inter_mb_type = P_MB; u1_deblk_mb_type = D_INTER_MB; ps_dec->ps_cur_slice->u1_slice_type = P_SLICE; ps_dec->ps_parse_cur_slice->slice_type = P_SLICE; ps_dec->pf_mvpred_ref_tfr_nby2mb = ih264d_mv_pred_ref_tfr_nby2_pmb; ps_dec->ps_part = ps_dec->ps_parse_part_params; /******************************************************/ /* Parsing / decoding the slice */ /******************************************************/ ps_dec->u1_slice_header_done = 2; ps_dec->u1_qp = ps_slice->u1_slice_qp; ih264d_update_qp(ps_dec, 0); u1_mb_idx = ps_dec->u1_mb_idx; ps_parse_mb_data = ps_dec->ps_parse_mb_data; u1_num_mbs = u1_mb_idx; u1_slice_end = 0; u1_tfr_n_mb = 0; u1_decode_nmb = 0; u1_num_mbsNby2 = 0; i2_cur_mb_addr = ps_dec->u2_total_mbs_coded; i2_mb_skip_run = num_mb_skip; while(!u1_slice_end) { UWORD8 u1_mb_type; if(i2_cur_mb_addr > ps_dec->ps_cur_sps->u2_max_mb_addr) break; ps_cur_mb_info = ps_dec->ps_nmb_info + u1_num_mbs; ps_dec->u4_num_mbs_cur_nmb = u1_num_mbs; ps_cur_mb_info->u1_Mux = 0; ps_dec->u4_num_pmbair = (u1_num_mbs >> u1_mbaff); ps_cur_deblk_mb = ps_dec->ps_deblk_mbn + u1_num_mbs; ps_cur_mb_info->u1_end_of_slice = 0; /* Storing Default partition info */ ps_parse_mb_data->u1_num_part = 1; ps_parse_mb_data->u1_isI_mb = 0; /**************************************************************/ /* Get the required information for decoding of MB */ /**************************************************************/ /* mb_x, mb_y, neighbor availablity, */ if (u1_mbaff) ih264d_get_mb_info_cavlc_mbaff(ps_dec, i2_cur_mb_addr, ps_cur_mb_info, i2_mb_skip_run); else ih264d_get_mb_info_cavlc_nonmbaff(ps_dec, i2_cur_mb_addr, ps_cur_mb_info, i2_mb_skip_run); /* Set the deblocking parameters for this MB */ if(ps_dec->u4_app_disable_deblk_frm == 0) { ih264d_set_deblocking_parameters(ps_cur_deblk_mb, ps_slice, ps_dec->u1_mb_ngbr_availablity, ps_dec->u1_cur_mb_fld_dec_flag); } /* Set appropriate flags in ps_cur_mb_info and ps_dec */ ps_dec->i1_prev_mb_qp_delta = 0; ps_dec->u1_sub_mb_num = 0; ps_cur_mb_info->u1_mb_type = MB_SKIP; ps_cur_mb_info->u1_mb_mc_mode = PRED_16x16; ps_cur_mb_info->u1_cbp = 0; /* Storing Skip partition info */ ps_part_info = ps_dec->ps_part; ps_part_info->u1_is_direct = PART_DIRECT_16x16; ps_part_info->u1_sub_mb_num = 0; ps_dec->ps_part++; /* Update Nnzs */ ih264d_update_nnz_for_skipmb(ps_dec, ps_cur_mb_info, CAVLC); ps_cur_mb_info->ps_curmb->u1_mb_type = u1_inter_mb_type; ps_cur_deblk_mb->u1_mb_type |= u1_deblk_mb_type; i2_mb_skip_run--; ps_cur_deblk_mb->u1_mb_qp = ps_dec->u1_qp; if (u1_mbaff) { ih264d_update_mbaff_left_nnz(ps_dec, ps_cur_mb_info); } /**************************************************************/ /* Get next Macroblock address */ /**************************************************************/ i2_cur_mb_addr++; u1_num_mbs++; u1_num_mbsNby2++; ps_parse_mb_data++; /****************************************************************/ /* Check for End Of Row and other flags that determine when to */ /* do DMA setup for N/2-Mb, Decode for N-Mb, and Transfer for */ /* N-Mb */ /****************************************************************/ u1_num_mbs_next = i2_pic_wdin_mbs - ps_dec->u2_mbx - 1; u1_end_of_row = (!u1_num_mbs_next) && (!(u1_mbaff && (u1_num_mbs & 0x01))); u1_slice_end = !i2_mb_skip_run; u1_tfr_n_mb = (u1_num_mbs == ps_dec->u1_recon_mb_grp) || u1_end_of_row || u1_slice_end; u1_decode_nmb = u1_tfr_n_mb || u1_slice_end; ps_cur_mb_info->u1_end_of_slice = u1_slice_end; if(u1_decode_nmb) { ps_dec->pf_mvpred_ref_tfr_nby2mb(ps_dec, u1_mb_idx, u1_num_mbs); u1_num_mbsNby2 = 0; ps_parse_mb_data = ps_dec->ps_parse_mb_data; ps_dec->ps_part = ps_dec->ps_parse_part_params; if(ps_dec->u1_separate_parse) { ih264d_parse_tfr_nmb(ps_dec, u1_mb_idx, u1_num_mbs, u1_num_mbs_next, u1_tfr_n_mb, u1_end_of_row); ps_dec->ps_nmb_info += u1_num_mbs; } else { ih264d_decode_recon_tfr_nmb(ps_dec, u1_mb_idx, u1_num_mbs, u1_num_mbs_next, u1_tfr_n_mb, u1_end_of_row); } ps_dec->u2_total_mbs_coded += u1_num_mbs; if(u1_tfr_n_mb) u1_num_mbs = 0; u1_mb_idx = u1_num_mbs; ps_dec->u1_mb_idx = u1_num_mbs; } } ps_dec->u4_num_mbs_cur_nmb = 0; ps_dec->ps_cur_slice->u4_mbs_in_slice = i2_cur_mb_addr - ps_dec->ps_parse_cur_slice->u4_first_mb_in_slice; H264_DEC_DEBUG_PRINT("Mbs in slice: %d\n", ps_dec->ps_cur_slice->u4_mbs_in_slice); ps_dec->u2_cur_slice_num++; /* incremented here only if first slice is inserted */ if(ps_dec->u4_first_slice_in_pic != 0) ps_dec->ps_parse_cur_slice++; ps_dec->i2_prev_slice_mbx = ps_dec->u2_mbx; ps_dec->i2_prev_slice_mby = ps_dec->u2_mby; if(ps_dec->u2_total_mbs_coded >= ps_dec->u2_frm_ht_in_mbs * ps_dec->u2_frm_wd_in_mbs) { ps_dec->u1_pic_decode_done = 1; } return 0; } Commit Message: Fix slice params for interlaced video Bug: 28165661 Change-Id: I912a86bd78ebf0617fd2bc6eb2b5a61afc17bf53 CWE ID: CWE-20
WORD32 ih264d_mark_err_slice_skip(dec_struct_t * ps_dec, WORD32 num_mb_skip, UWORD8 u1_is_idr_slice, UWORD16 u2_frame_num, pocstruct_t *ps_cur_poc, WORD32 prev_slice_err) { WORD32 i2_cur_mb_addr; UWORD32 u1_num_mbs, u1_num_mbsNby2; UWORD32 u1_mb_idx = ps_dec->u1_mb_idx; UWORD32 i2_mb_skip_run; UWORD32 u1_num_mbs_next, u1_end_of_row; const UWORD32 i2_pic_wdin_mbs = ps_dec->u2_frm_wd_in_mbs; UWORD32 u1_slice_end; UWORD32 u1_tfr_n_mb; UWORD32 u1_decode_nmb; dec_bit_stream_t * const ps_bitstrm = ps_dec->ps_bitstrm; dec_slice_params_t * ps_slice = ps_dec->ps_cur_slice; UWORD32 *pu4_bitstrm_buf = ps_bitstrm->pu4_buffer; UWORD32 *pu4_bitstrm_ofst = &ps_bitstrm->u4_ofst; deblk_mb_t *ps_cur_deblk_mb; dec_mb_info_t *ps_cur_mb_info; parse_pmbarams_t *ps_parse_mb_data; UWORD32 u1_inter_mb_type; UWORD32 u1_deblk_mb_type; UWORD16 u2_total_mbs_coded; UWORD32 u1_mbaff = ps_slice->u1_mbaff_frame_flag; parse_part_params_t *ps_part_info; WORD32 ret; if(ps_dec->ps_dec_err_status->u1_err_flag & REJECT_CUR_PIC) { ih264d_err_pic_dispbuf_mgr(ps_dec); return 0; } ps_dec->ps_dpb_cmds->u1_long_term_reference_flag = 0; if(prev_slice_err == 1) { /* first slice - missing/header corruption */ ps_dec->ps_cur_slice->u2_frame_num = u2_frame_num; if(!ps_dec->u1_first_slice_in_stream) { ih264d_end_of_pic(ps_dec, u1_is_idr_slice, ps_dec->ps_cur_slice->u2_frame_num); ps_dec->s_cur_pic_poc.u2_frame_num = ps_dec->ps_cur_slice->u2_frame_num; } { WORD32 i, j, poc = 0; ps_dec->ps_cur_slice->u2_first_mb_in_slice = 0; ps_dec->pf_mvpred = ih264d_mvpred_nonmbaff; ps_dec->p_form_mb_part_info = ih264d_form_mb_part_info_bp; ps_dec->p_motion_compensate = ih264d_motion_compensate_bp; if(ps_dec->ps_cur_pic != NULL) poc = ps_dec->ps_cur_pic->i4_poc + 2; j = 0; for(i = 0; i < MAX_NUM_PIC_PARAMS; i++) if(ps_dec->ps_pps[i].u1_is_valid == TRUE) j = i; { ps_dec->ps_cur_slice->u1_slice_type = P_SLICE; ps_dec->ps_cur_slice->u1_nal_ref_idc = 1; ps_dec->ps_cur_slice->u1_nal_unit_type = 1; ret = ih264d_start_of_pic(ps_dec, poc, ps_cur_poc, ps_dec->ps_cur_slice->u2_frame_num, &ps_dec->ps_pps[j]); if(ret != OK) { return ret; } } ps_dec->ps_ref_pic_buf_lx[0][0]->u1_pic_buf_id = 0; ps_dec->u4_output_present = 0; { ih264d_get_next_display_field(ps_dec, ps_dec->ps_out_buffer, &(ps_dec->s_disp_op)); /* If error code is non-zero then there is no buffer available for display, hence avoid format conversion */ if(0 != ps_dec->s_disp_op.u4_error_code) { ps_dec->u4_fmt_conv_cur_row = ps_dec->s_disp_frame_info.u4_y_ht; } else ps_dec->u4_output_present = 1; } if(ps_dec->u1_separate_parse == 1) { if(ps_dec->u4_dec_thread_created == 0) { ithread_create(ps_dec->pv_dec_thread_handle, NULL, (void *)ih264d_decode_picture_thread, (void *)ps_dec); ps_dec->u4_dec_thread_created = 1; } if((ps_dec->u4_num_cores == 3) && ((ps_dec->u4_app_disable_deblk_frm == 0) || ps_dec->i1_recon_in_thread3_flag) && (ps_dec->u4_bs_deblk_thread_created == 0)) { ps_dec->u4_start_recon_deblk = 0; ithread_create(ps_dec->pv_bs_deblk_thread_handle, NULL, (void *)ih264d_recon_deblk_thread, (void *)ps_dec); ps_dec->u4_bs_deblk_thread_created = 1; } } } } else { dec_slice_struct_t *ps_parse_cur_slice; ps_parse_cur_slice = ps_dec->ps_dec_slice_buf + ps_dec->u2_cur_slice_num; if(ps_dec->u1_slice_header_done && ps_parse_cur_slice == ps_dec->ps_parse_cur_slice) { u1_num_mbs = ps_dec->u4_num_mbs_cur_nmb; if(u1_num_mbs) { ps_cur_mb_info = ps_dec->ps_nmb_info + u1_num_mbs - 1; } else { if(ps_dec->u1_separate_parse) { ps_cur_mb_info = ps_dec->ps_nmb_info - 1; } else { ps_cur_mb_info = ps_dec->ps_nmb_info + ps_dec->u4_num_mbs_prev_nmb - 1; } } ps_dec->u2_mby = ps_cur_mb_info->u2_mby; ps_dec->u2_mbx = ps_cur_mb_info->u2_mbx; ps_dec->u1_mb_ngbr_availablity = ps_cur_mb_info->u1_mb_ngbr_availablity; ps_dec->pv_parse_tu_coeff_data = ps_dec->pv_prev_mb_parse_tu_coeff_data; ps_dec->u2_cur_mb_addr--; ps_dec->i4_submb_ofst -= SUB_BLK_SIZE; if(u1_num_mbs) { if (ps_dec->u1_pr_sl_type == P_SLICE || ps_dec->u1_pr_sl_type == B_SLICE) { ps_dec->pf_mvpred_ref_tfr_nby2mb(ps_dec, u1_mb_idx, u1_num_mbs); ps_dec->ps_part = ps_dec->ps_parse_part_params; } u1_num_mbs_next = i2_pic_wdin_mbs - ps_dec->u2_mbx - 1; u1_end_of_row = (!u1_num_mbs_next) && (!(u1_mbaff && (u1_num_mbs & 0x01))); u1_slice_end = 1; u1_tfr_n_mb = 1; ps_cur_mb_info->u1_end_of_slice = u1_slice_end; if(ps_dec->u1_separate_parse) { ih264d_parse_tfr_nmb(ps_dec, u1_mb_idx, u1_num_mbs, u1_num_mbs_next, u1_tfr_n_mb, u1_end_of_row); ps_dec->ps_nmb_info += u1_num_mbs; } else { ih264d_decode_recon_tfr_nmb(ps_dec, u1_mb_idx, u1_num_mbs, u1_num_mbs_next, u1_tfr_n_mb, u1_end_of_row); } ps_dec->u2_total_mbs_coded += u1_num_mbs; ps_dec->u1_mb_idx = 0; ps_dec->u4_num_mbs_cur_nmb = 0; } if(ps_dec->u2_total_mbs_coded >= ps_dec->u2_frm_ht_in_mbs * ps_dec->u2_frm_wd_in_mbs) { ps_dec->u1_pic_decode_done = 1; return 0; } ps_dec->u2_cur_slice_num++; ps_dec->i2_prev_slice_mbx = ps_dec->u2_mbx; ps_dec->i2_prev_slice_mby = ps_dec->u2_mby; ps_dec->ps_parse_cur_slice++; } else { ps_dec->ps_parse_cur_slice = ps_dec->ps_dec_slice_buf + ps_dec->u2_cur_slice_num; } } /******************************************************/ /* Initializations to new slice */ /******************************************************/ { WORD32 num_entries; WORD32 size; UWORD8 *pu1_buf; num_entries = MAX_FRAMES; if((1 >= ps_dec->ps_cur_sps->u1_num_ref_frames) && (0 == ps_dec->i4_display_delay)) { num_entries = 1; } num_entries = ((2 * num_entries) + 1); if(BASE_PROFILE_IDC != ps_dec->ps_cur_sps->u1_profile_idc) { num_entries *= 2; } size = num_entries * sizeof(void *); size += PAD_MAP_IDX_POC * sizeof(void *); pu1_buf = (UWORD8 *)ps_dec->pv_map_ref_idx_to_poc_buf; pu1_buf += size * ps_dec->u2_cur_slice_num; ps_dec->ps_parse_cur_slice->ppv_map_ref_idx_to_poc = (volatile void **)pu1_buf; } ps_dec->ps_cur_slice->u2_first_mb_in_slice = ps_dec->u2_total_mbs_coded << u1_mbaff; ps_dec->ps_cur_slice->i1_slice_alpha_c0_offset = 0; ps_dec->ps_cur_slice->i1_slice_beta_offset = 0; if(ps_dec->ps_cur_slice->u1_field_pic_flag) ps_dec->u2_prv_frame_num = ps_dec->ps_cur_slice->u2_frame_num; ps_dec->ps_parse_cur_slice->u4_first_mb_in_slice = ps_dec->u2_total_mbs_coded << u1_mbaff; ps_dec->ps_parse_cur_slice->u2_log2Y_crwd = ps_dec->ps_cur_slice->u2_log2Y_crwd; if(ps_dec->u1_separate_parse) { ps_dec->ps_parse_cur_slice->pv_tu_coeff_data_start = ps_dec->pv_parse_tu_coeff_data; } else { ps_dec->pv_proc_tu_coeff_data = ps_dec->pv_parse_tu_coeff_data; } /******************************************************/ /* Initializations specific to P slice */ /******************************************************/ u1_inter_mb_type = P_MB; u1_deblk_mb_type = D_INTER_MB; ps_dec->ps_cur_slice->u1_slice_type = P_SLICE; ps_dec->ps_parse_cur_slice->slice_type = P_SLICE; ps_dec->pf_mvpred_ref_tfr_nby2mb = ih264d_mv_pred_ref_tfr_nby2_pmb; ps_dec->ps_part = ps_dec->ps_parse_part_params; /******************************************************/ /* Parsing / decoding the slice */ /******************************************************/ ps_dec->u1_slice_header_done = 2; ps_dec->u1_qp = ps_slice->u1_slice_qp; ih264d_update_qp(ps_dec, 0); u1_mb_idx = ps_dec->u1_mb_idx; ps_parse_mb_data = ps_dec->ps_parse_mb_data; u1_num_mbs = u1_mb_idx; u1_slice_end = 0; u1_tfr_n_mb = 0; u1_decode_nmb = 0; u1_num_mbsNby2 = 0; i2_cur_mb_addr = ps_dec->u2_total_mbs_coded; i2_mb_skip_run = num_mb_skip; while(!u1_slice_end) { UWORD8 u1_mb_type; if(i2_cur_mb_addr > ps_dec->ps_cur_sps->u2_max_mb_addr) break; ps_cur_mb_info = ps_dec->ps_nmb_info + u1_num_mbs; ps_dec->u4_num_mbs_cur_nmb = u1_num_mbs; ps_cur_mb_info->u1_Mux = 0; ps_dec->u4_num_pmbair = (u1_num_mbs >> u1_mbaff); ps_cur_deblk_mb = ps_dec->ps_deblk_mbn + u1_num_mbs; ps_cur_mb_info->u1_end_of_slice = 0; /* Storing Default partition info */ ps_parse_mb_data->u1_num_part = 1; ps_parse_mb_data->u1_isI_mb = 0; /**************************************************************/ /* Get the required information for decoding of MB */ /**************************************************************/ /* mb_x, mb_y, neighbor availablity, */ if (u1_mbaff) ih264d_get_mb_info_cavlc_mbaff(ps_dec, i2_cur_mb_addr, ps_cur_mb_info, i2_mb_skip_run); else ih264d_get_mb_info_cavlc_nonmbaff(ps_dec, i2_cur_mb_addr, ps_cur_mb_info, i2_mb_skip_run); /* Set the deblocking parameters for this MB */ if(ps_dec->u4_app_disable_deblk_frm == 0) { ih264d_set_deblocking_parameters(ps_cur_deblk_mb, ps_slice, ps_dec->u1_mb_ngbr_availablity, ps_dec->u1_cur_mb_fld_dec_flag); } /* Set appropriate flags in ps_cur_mb_info and ps_dec */ ps_dec->i1_prev_mb_qp_delta = 0; ps_dec->u1_sub_mb_num = 0; ps_cur_mb_info->u1_mb_type = MB_SKIP; ps_cur_mb_info->u1_mb_mc_mode = PRED_16x16; ps_cur_mb_info->u1_cbp = 0; /* Storing Skip partition info */ ps_part_info = ps_dec->ps_part; ps_part_info->u1_is_direct = PART_DIRECT_16x16; ps_part_info->u1_sub_mb_num = 0; ps_dec->ps_part++; /* Update Nnzs */ ih264d_update_nnz_for_skipmb(ps_dec, ps_cur_mb_info, CAVLC); ps_cur_mb_info->ps_curmb->u1_mb_type = u1_inter_mb_type; ps_cur_deblk_mb->u1_mb_type |= u1_deblk_mb_type; i2_mb_skip_run--; ps_cur_deblk_mb->u1_mb_qp = ps_dec->u1_qp; if (u1_mbaff) { ih264d_update_mbaff_left_nnz(ps_dec, ps_cur_mb_info); } /**************************************************************/ /* Get next Macroblock address */ /**************************************************************/ i2_cur_mb_addr++; u1_num_mbs++; u1_num_mbsNby2++; ps_parse_mb_data++; /****************************************************************/ /* Check for End Of Row and other flags that determine when to */ /* do DMA setup for N/2-Mb, Decode for N-Mb, and Transfer for */ /* N-Mb */ /****************************************************************/ u1_num_mbs_next = i2_pic_wdin_mbs - ps_dec->u2_mbx - 1; u1_end_of_row = (!u1_num_mbs_next) && (!(u1_mbaff && (u1_num_mbs & 0x01))); u1_slice_end = !i2_mb_skip_run; u1_tfr_n_mb = (u1_num_mbs == ps_dec->u1_recon_mb_grp) || u1_end_of_row || u1_slice_end; u1_decode_nmb = u1_tfr_n_mb || u1_slice_end; ps_cur_mb_info->u1_end_of_slice = u1_slice_end; if(u1_decode_nmb) { ps_dec->pf_mvpred_ref_tfr_nby2mb(ps_dec, u1_mb_idx, u1_num_mbs); u1_num_mbsNby2 = 0; ps_parse_mb_data = ps_dec->ps_parse_mb_data; ps_dec->ps_part = ps_dec->ps_parse_part_params; if(ps_dec->u1_separate_parse) { ih264d_parse_tfr_nmb(ps_dec, u1_mb_idx, u1_num_mbs, u1_num_mbs_next, u1_tfr_n_mb, u1_end_of_row); ps_dec->ps_nmb_info += u1_num_mbs; } else { ih264d_decode_recon_tfr_nmb(ps_dec, u1_mb_idx, u1_num_mbs, u1_num_mbs_next, u1_tfr_n_mb, u1_end_of_row); } ps_dec->u2_total_mbs_coded += u1_num_mbs; if(u1_tfr_n_mb) u1_num_mbs = 0; u1_mb_idx = u1_num_mbs; ps_dec->u1_mb_idx = u1_num_mbs; } } ps_dec->u4_num_mbs_cur_nmb = 0; ps_dec->ps_cur_slice->u4_mbs_in_slice = i2_cur_mb_addr - ps_dec->ps_parse_cur_slice->u4_first_mb_in_slice; H264_DEC_DEBUG_PRINT("Mbs in slice: %d\n", ps_dec->ps_cur_slice->u4_mbs_in_slice); ps_dec->u2_cur_slice_num++; /* incremented here only if first slice is inserted */ if(ps_dec->u4_first_slice_in_pic != 0) ps_dec->ps_parse_cur_slice++; ps_dec->i2_prev_slice_mbx = ps_dec->u2_mbx; ps_dec->i2_prev_slice_mby = ps_dec->u2_mby; if(ps_dec->u2_total_mbs_coded >= ps_dec->u2_frm_ht_in_mbs * ps_dec->u2_frm_wd_in_mbs) { ps_dec->u1_pic_decode_done = 1; } return 0; }
173,761
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int perf_event_overflow(struct perf_event *event, int nmi, struct perf_sample_data *data, struct pt_regs *regs) { return __perf_event_overflow(event, nmi, 1, data, regs); } Commit Message: perf: Remove the nmi parameter from the swevent and overflow interface The nmi parameter indicated if we could do wakeups from the current context, if not, we would set some state and self-IPI and let the resulting interrupt do the wakeup. For the various event classes: - hardware: nmi=0; PMI is in fact an NMI or we run irq_work_run from the PMI-tail (ARM etc.) - tracepoint: nmi=0; since tracepoint could be from NMI context. - software: nmi=[0,1]; some, like the schedule thing cannot perform wakeups, and hence need 0. As one can see, there is very little nmi=1 usage, and the down-side of not using it is that on some platforms some software events can have a jiffy delay in wakeup (when arch_irq_work_raise isn't implemented). The up-side however is that we can remove the nmi parameter and save a bunch of conditionals in fast paths. Signed-off-by: Peter Zijlstra <[email protected]> Cc: Michael Cree <[email protected]> Cc: Will Deacon <[email protected]> Cc: Deng-Cheng Zhu <[email protected]> Cc: Anton Blanchard <[email protected]> Cc: Eric B Munson <[email protected]> Cc: Heiko Carstens <[email protected]> Cc: Paul Mundt <[email protected]> Cc: David S. Miller <[email protected]> Cc: Frederic Weisbecker <[email protected]> Cc: Jason Wessel <[email protected]> Cc: Don Zickus <[email protected]> Link: http://lkml.kernel.org/n/[email protected] Signed-off-by: Ingo Molnar <[email protected]> CWE ID: CWE-399
int perf_event_overflow(struct perf_event *event, int nmi, int perf_event_overflow(struct perf_event *event, struct perf_sample_data *data, struct pt_regs *regs) { return __perf_event_overflow(event, 1, data, regs); }
165,833
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void ManifestManager::FetchManifest() { manifest_url_ = render_frame()->GetWebFrame()->GetDocument().ManifestURL(); if (manifest_url_.is_empty()) { ManifestUmaUtil::FetchFailed(ManifestUmaUtil::FETCH_EMPTY_URL); ResolveCallbacks(ResolveStateFailure); return; } fetcher_.reset(new ManifestFetcher(manifest_url_)); fetcher_->Start( render_frame()->GetWebFrame(), render_frame()->GetWebFrame()->GetDocument().ManifestUseCredentials(), base::Bind(&ManifestManager::OnManifestFetchComplete, base::Unretained(this), render_frame()->GetWebFrame()->GetDocument().Url())); } Commit Message: Fail the web app manifest fetch if the document is sandboxed. This ensures that sandboxed pages are regarded as non-PWAs, and that other features in the browser process which trust the web manifest do not receive the manifest at all if the document itself cannot access the manifest. BUG=771709 Change-Id: Ifd4d00c2fccff8cc0e5e8d2457bd55b992b0a8f4 Reviewed-on: https://chromium-review.googlesource.com/866529 Commit-Queue: Dominick Ng <[email protected]> Reviewed-by: Mounir Lamouri <[email protected]> Reviewed-by: Mike West <[email protected]> Cr-Commit-Position: refs/heads/master@{#531121} CWE ID:
void ManifestManager::FetchManifest() { if (!CanFetchManifest(render_frame())) { ManifestUmaUtil::FetchFailed(ManifestUmaUtil::FETCH_FROM_UNIQUE_ORIGIN); ResolveCallbacks(ResolveStateFailure); return; } manifest_url_ = render_frame()->GetWebFrame()->GetDocument().ManifestURL(); if (manifest_url_.is_empty()) { ManifestUmaUtil::FetchFailed(ManifestUmaUtil::FETCH_EMPTY_URL); ResolveCallbacks(ResolveStateFailure); return; } fetcher_.reset(new ManifestFetcher(manifest_url_)); fetcher_->Start( render_frame()->GetWebFrame(), render_frame()->GetWebFrame()->GetDocument().ManifestUseCredentials(), base::Bind(&ManifestManager::OnManifestFetchComplete, base::Unretained(this), render_frame()->GetWebFrame()->GetDocument().Url())); }
172,921
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void PrintWebViewHelper::PrintNode(const WebKit::WebNode& node) { if (node.isNull() || !node.document().frame()) { return; } if (is_preview_enabled_) { print_preview_context_.InitWithNode(node); RequestPrintPreview(PRINT_PREVIEW_USER_INITIATED_CONTEXT_NODE); } else { WebKit::WebNode duplicate_node(node); Print(duplicate_node.document().frame(), duplicate_node); } } Commit Message: Guard against the same PrintWebViewHelper being re-entered. BUG=159165 Review URL: https://chromiumcodereview.appspot.com/11367076 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@165821 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void PrintWebViewHelper::PrintNode(const WebKit::WebNode& node) { if (node.isNull() || !node.document().frame()) { return; } if (print_node_in_progress_) { // This can happen as a result of processing sync messages when printing // from ppapi plugins. It's a rare case, so its OK to just fail here. // See http://crbug.com/159165. return; } print_node_in_progress_ = true; if (is_preview_enabled_) { print_preview_context_.InitWithNode(node); RequestPrintPreview(PRINT_PREVIEW_USER_INITIATED_CONTEXT_NODE); } else { WebKit::WebNode duplicate_node(node); Print(duplicate_node.document().frame(), duplicate_node); } print_node_in_progress_ = false; }
170,697
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void webkitWebViewBaseContainerAdd(GtkContainer* container, GtkWidget* widget) { WebKitWebViewBase* webView = WEBKIT_WEB_VIEW_BASE(container); WebKitWebViewBasePrivate* priv = webView->priv; if (WEBKIT_IS_WEB_VIEW_BASE(widget) && WebInspectorProxy::isInspectorPage(WEBKIT_WEB_VIEW_BASE(widget)->priv->pageProxy.get())) { ASSERT(!priv->inspectorView); priv->inspectorView = widget; priv->inspectorViewHeight = gMinimumAttachedInspectorHeight; } else { GtkAllocation childAllocation; gtk_widget_get_allocation(widget, &childAllocation); priv->children.set(widget, childAllocation); } gtk_widget_set_parent(widget, GTK_WIDGET(container)); } Commit Message: [GTK] Inspector should set a default attached height before being attached https://bugs.webkit.org/show_bug.cgi?id=90767 Reviewed by Xan Lopez. We are currently using the minimum attached height in WebKitWebViewBase as the default height for the inspector when attached. It would be easier for WebKitWebViewBase and embedders implementing attach() if the inspector already had an attached height set when it's being attached. * UIProcess/API/gtk/WebKitWebViewBase.cpp: (webkitWebViewBaseContainerAdd): Don't initialize inspectorViewHeight. (webkitWebViewBaseSetInspectorViewHeight): Allow to set the inspector view height before having an inpector view, but only queue a resize when the view already has an inspector view. * UIProcess/API/gtk/tests/TestInspector.cpp: (testInspectorDefault): (testInspectorManualAttachDetach): * UIProcess/gtk/WebInspectorProxyGtk.cpp: (WebKit::WebInspectorProxy::platformAttach): Set the default attached height before attach the inspector view. git-svn-id: svn://svn.chromium.org/blink/trunk@124479 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399
static void webkitWebViewBaseContainerAdd(GtkContainer* container, GtkWidget* widget) { WebKitWebViewBase* webView = WEBKIT_WEB_VIEW_BASE(container); WebKitWebViewBasePrivate* priv = webView->priv; if (WEBKIT_IS_WEB_VIEW_BASE(widget) && WebInspectorProxy::isInspectorPage(WEBKIT_WEB_VIEW_BASE(widget)->priv->pageProxy.get())) { ASSERT(!priv->inspectorView); priv->inspectorView = widget; } else { GtkAllocation childAllocation; gtk_widget_get_allocation(widget, &childAllocation); priv->children.set(widget, childAllocation); } gtk_widget_set_parent(widget, GTK_WIDGET(container)); }
171,052
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void unmarshallAudioAttributes(const Parcel& parcel, audio_attributes_t *attributes) { attributes->usage = (audio_usage_t) parcel.readInt32(); attributes->content_type = (audio_content_type_t) parcel.readInt32(); attributes->source = (audio_source_t) parcel.readInt32(); attributes->flags = (audio_flags_mask_t) parcel.readInt32(); const bool hasFlattenedTag = (parcel.readInt32() == kAudioAttributesMarshallTagFlattenTags); if (hasFlattenedTag) { String16 tags = parcel.readString16(); ssize_t realTagSize = utf16_to_utf8_length(tags.string(), tags.size()); if (realTagSize <= 0) { strcpy(attributes->tags, ""); } else { size_t tagSize = realTagSize > AUDIO_ATTRIBUTES_TAGS_MAX_SIZE - 1 ? AUDIO_ATTRIBUTES_TAGS_MAX_SIZE - 1 : realTagSize; utf16_to_utf8(tags.string(), tagSize, attributes->tags); } } else { ALOGE("unmarshallAudioAttributes() received unflattened tags, ignoring tag values"); strcpy(attributes->tags, ""); } } Commit Message: Add bound checks to utf16_to_utf8 Bug: 29250543 Change-Id: I3518416e89ed901021970958fb6005fd69129f7c (cherry picked from commit 1d3f4278b2666d1a145af2f54782c993aa07d1d9) CWE ID: CWE-119
void unmarshallAudioAttributes(const Parcel& parcel, audio_attributes_t *attributes) { attributes->usage = (audio_usage_t) parcel.readInt32(); attributes->content_type = (audio_content_type_t) parcel.readInt32(); attributes->source = (audio_source_t) parcel.readInt32(); attributes->flags = (audio_flags_mask_t) parcel.readInt32(); const bool hasFlattenedTag = (parcel.readInt32() == kAudioAttributesMarshallTagFlattenTags); if (hasFlattenedTag) { String16 tags = parcel.readString16(); ssize_t realTagSize = utf16_to_utf8_length(tags.string(), tags.size()); if (realTagSize <= 0) { strcpy(attributes->tags, ""); } else { size_t tagSize = realTagSize > AUDIO_ATTRIBUTES_TAGS_MAX_SIZE - 1 ? AUDIO_ATTRIBUTES_TAGS_MAX_SIZE - 1 : realTagSize; utf16_to_utf8(tags.string(), tagSize, attributes->tags, sizeof(attributes->tags) / sizeof(attributes->tags[0])); } } else { ALOGE("unmarshallAudioAttributes() received unflattened tags, ignoring tag values"); strcpy(attributes->tags, ""); } }
174,159
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static bool r_bin_mdmp_init_directory_entry(struct r_bin_mdmp_obj *obj, struct minidump_directory *entry) { int i; struct minidump_handle_operation_list *handle_operation_list; struct minidump_memory_list *memory_list; struct minidump_memory64_list *memory64_list; struct minidump_memory_info_list *memory_info_list; struct minidump_module_list *module_list; struct minidump_thread_list *thread_list; struct minidump_thread_ex_list *thread_ex_list; struct minidump_thread_info_list *thread_info_list; struct minidump_unloaded_module_list *unloaded_module_list; struct avrf_handle_operation *handle_operations; struct minidump_memory_descriptor *memories; struct minidump_memory_descriptor64 *memories64; struct minidump_memory_info *memory_infos; struct minidump_module *modules; struct minidump_thread *threads; struct minidump_thread_ex *ex_threads; struct minidump_thread_info *thread_infos; struct minidump_unloaded_module *unloaded_modules; /* We could confirm data sizes but a malcious MDMP will always get around ** this! But we can ensure that the data is not outside of the file */ if (entry->location.rva + entry->location.data_size > obj->b->length) { eprintf("[ERROR] Size Mismatch - Stream data is larger than file size!\n"); return false; } switch (entry->stream_type) { case THREAD_LIST_STREAM: thread_list = (struct minidump_thread_list *)(obj->b->buf + entry->location.rva); sdb_set (obj->kv, "mdmp_thread.format", "ddddq?? " "ThreadId SuspendCount PriorityClass Priority " "Teb (mdmp_memory_descriptor)Stack " "(mdmp_location_descriptor)ThreadContext", 0); sdb_num_set (obj->kv, "mdmp_thread_list.offset", entry->location.rva, 0); sdb_set (obj->kv, "mdmp_thread_list.format", sdb_fmt ("d[%i]? " "NumberOfThreads (mdmp_thread)Threads", thread_list->number_of_threads), 0); /* TODO: Not yet fully parsed or utilised */ for (i = 0; i < thread_list->number_of_threads; i++) { threads = (struct minidump_thread *)(&(thread_list->threads)); r_list_append (obj->streams.threads, &(threads[i])); } break; case MODULE_LIST_STREAM: module_list = (struct minidump_module_list *)(obj->b->buf + entry->location.rva); sdb_set (obj->kv, "mdmp_module.format", "qddtd???qq " "BaseOfImage SizeOfImage CheckSum " "TimeDateStamp ModuleNameRVA " "(mdmp_vs_fixedfileinfo)VersionInfo " "(mdmp_location_descriptor)CvRecord " "(mdmp_location_descriptor)MiscRecord " "Reserved0 Reserved1", 0); sdb_num_set (obj->kv, "mdmp_module_list.offset", entry->location.rva, 0); sdb_set (obj->kv, "mdmp_module_list.format", sdb_fmt ("d[%i]? " "NumberOfModule (mdmp_module)Modules", module_list->number_of_modules, 0), 0); for (i = 0; i < module_list->number_of_modules; i++) { modules = (struct minidump_module *)(&(module_list->modules)); r_list_append(obj->streams.modules, &(modules[i])); } break; case MEMORY_LIST_STREAM: memory_list = (struct minidump_memory_list *)(obj->b->buf + entry->location.rva); sdb_num_set (obj->kv, "mdmp_memory_list.offset", entry->location.rva, 0); sdb_set (obj->kv, "mdmp_memory_list.format", sdb_fmt ("d[%i]? " "NumberOfMemoryRanges " "(mdmp_memory_descriptor)MemoryRanges ", memory_list->number_of_memory_ranges, 0), 0); for (i = 0; i < memory_list->number_of_memory_ranges; i++) { memories = (struct minidump_memory_descriptor *)(&(memory_list->memory_ranges)); r_list_append (obj->streams.memories, &(memories[i])); } break; case EXCEPTION_STREAM: /* TODO: Not yet fully parsed or utilised */ obj->streams.exception = (struct minidump_exception_stream *)(obj->b->buf + entry->location.rva); sdb_set (obj->kv, "mdmp_exception.format", "[4]E[4]Eqqdd[15]q " "(mdmp_exception_code)ExceptionCode " "(mdmp_exception_flags)ExceptionFlags " "ExceptionRecord ExceptionAddress " "NumberParameters __UnusedAlignment " "ExceptionInformation", 0); sdb_num_set (obj->kv, "mdmp_exception_stream.offset", entry->location.rva, 0); sdb_set (obj->kv, "mdmp_exception_stream.format", "dd?? " "ThreadId __Alignment " "(mdmp_exception)ExceptionRecord " "(mdmp_location_descriptor)ThreadContext", 0); break; case SYSTEM_INFO_STREAM: obj->streams.system_info = (struct minidump_system_info *)(obj->b->buf + entry->location.rva); sdb_num_set (obj->kv, "mdmp_system_info.offset", entry->location.rva, 0); /* TODO: We need E as a byte! */ sdb_set (obj->kv, "mdmp_system_info.format", "[2]EwwbBddd[4]Ed[2]Ew[2]q " "(mdmp_processor_architecture)ProcessorArchitecture " "ProcessorLevel ProcessorRevision NumberOfProcessors " "(mdmp_product_type)ProductType " "MajorVersion MinorVersion BuildNumber (mdmp_platform_id)PlatformId " "CsdVersionRva (mdmp_suite_mask)SuiteMask Reserved2 ProcessorFeatures", 0); break; case THREAD_EX_LIST_STREAM: /* TODO: Not yet fully parsed or utilised */ thread_ex_list = (struct minidump_thread_ex_list *)(obj->b->buf + entry->location.rva); sdb_set (obj->kv, "mdmp_thread_ex.format", "ddddq??? " "ThreadId SuspendCount PriorityClass Priority " "Teb (mdmp_memory_descriptor)Stack " "(mdmp_location_descriptor)ThreadContext " "(mdmp_memory_descriptor)BackingStore", 0); sdb_num_set (obj->kv, "mdmp_thread_ex_list.offset", entry->location.rva, 0); sdb_set (obj->kv, "mdmp_thread_ex_list.format", sdb_fmt ("d[%i]? NumberOfThreads " "(mdmp_thread_ex)Threads", thread_ex_list->number_of_threads, 0), 0); for (i = 0; i < thread_ex_list->number_of_threads; i++) { ex_threads = (struct minidump_thread_ex *)(&(thread_ex_list->threads)); r_list_append (obj->streams.ex_threads, &(ex_threads[i])); } break; case MEMORY_64_LIST_STREAM: memory64_list = (struct minidump_memory64_list *)(obj->b->buf + entry->location.rva); sdb_num_set (obj->kv, "mdmp_memory64_list.offset", entry->location.rva, 0); sdb_set (obj->kv, "mdmp_memory64_list.format", sdb_fmt ("qq[%i]? NumberOfMemoryRanges " "BaseRva " "(mdmp_memory_descriptor64)MemoryRanges", memory64_list->number_of_memory_ranges), 0); obj->streams.memories64.base_rva = memory64_list->base_rva; for (i = 0; i < memory64_list->number_of_memory_ranges; i++) { memories64 = (struct minidump_memory_descriptor64 *)(&(memory64_list->memory_ranges)); r_list_append (obj->streams.memories64.memories, &(memories64[i])); } break; case COMMENT_STREAM_A: /* TODO: Not yet fully parsed or utilised */ obj->streams.comments_a = obj->b->buf + entry->location.rva; sdb_num_set (obj->kv, "mdmp_comment_stream_a.offset", entry->location.rva, 0); sdb_set (obj->kv, "mdmp_comment_stream_a.format", "s CommentA", 0); break; case COMMENT_STREAM_W: /* TODO: Not yet fully parsed or utilised */ obj->streams.comments_w = obj->b->buf + entry->location.rva; sdb_num_set (obj->kv, "mdmp_comment_stream_w.offset", entry->location.rva, 0); sdb_set (obj->kv, "mdmp_comment_stream_w.format", "s CommentW", 0); break; case HANDLE_DATA_STREAM: /* TODO: Not yet fully parsed or utilised */ obj->streams.handle_data = (struct minidump_handle_data_stream *)(obj->b->buf + entry->location.rva); sdb_num_set (obj->kv, "mdmp_handle_data_stream.offset", entry->location.rva, 0); sdb_set (obj->kv, "mdmp_handle_data_stream.format", "dddd " "SizeOfHeader SizeOfDescriptor " "NumberOfDescriptors Reserved", 0); break; case FUNCTION_TABLE_STREAM: /* TODO: Not yet fully parsed or utilised */ obj->streams.function_table = (struct minidump_function_table_stream *)(obj->b->buf + entry->location.rva); sdb_num_set (obj->kv, "mdmp_function_table_stream.offset", entry->location.rva, 0); sdb_set (obj->kv, "mdmp_function_table_stream.format", "dddddd " "SizeOfHeader SizeOfDescriptor SizeOfNativeDescriptor " "SizeOfFunctionEntry NumberOfDescriptors SizeOfAlignPad", 0); break; case UNLOADED_MODULE_LIST_STREAM: /* TODO: Not yet fully parsed or utilised */ unloaded_module_list = (struct minidump_unloaded_module_list *)(obj->b->buf + entry->location.rva); sdb_set (obj->kv, "mdmp_unloaded_module.format", "qddtd " "BaseOfImage SizeOfImage CheckSum TimeDateStamp " "ModuleNameRva", 0); sdb_num_set (obj->kv, "mdmp_unloaded_module_list.offset", entry->location.rva, 0); sdb_set (obj->kv, "mdmp_unloaded_module_list.format", "ddd " "SizeOfHeader SizeOfEntry NumberOfEntries", 0); for (i = 0; i < unloaded_module_list->number_of_entries; i++) { unloaded_modules = (struct minidump_unloaded_module *)((ut8 *)&unloaded_module_list + sizeof (struct minidump_unloaded_module_list)); r_list_append (obj->streams.unloaded_modules, &(unloaded_modules[i])); } break; case MISC_INFO_STREAM: /* TODO: Not yet fully parsed or utilised */ obj->streams.misc_info.misc_info_1 = (struct minidump_misc_info *)(obj->b->buf + entry->location.rva); /* TODO: Handle different sizes */ sdb_num_set (obj->kv, "mdmp_misc_info.offset", entry->location.rva, 0); sdb_set (obj->kv, "mdmp_misc_info.format", "d[4]Bdtttddddd " "SizeOfInfo (mdmp_misc1_flags)Flags1 ProcessId " "ProcessCreateTime ProcessUserTime ProcessKernelTime " "ProcessorMaxMhz ProcessorCurrentMhz " "ProcessorMhzLimit ProcessorMaxIdleState " "ProcessorCurrentIdleState", 0); break; case MEMORY_INFO_LIST_STREAM: memory_info_list = (struct minidump_memory_info_list *)(obj->b->buf + entry->location.rva); sdb_set (obj->kv, "mdmp_memory_info.format", "qq[4]Edq[4]E[4]E[4]Ed BaseAddress AllocationBase " "(mdmp_page_protect)AllocationProtect __Alignment1 RegionSize " "(mdmp_mem_state)State (mdmp_page_protect)Protect " "(mdmp_mem_type)Type __Alignment2", 0); sdb_num_set (obj->kv, "mdmp_memory_info_list.offset", entry->location.rva, 0); sdb_set (obj->kv, "mdmp_memory_info_list.format", sdb_fmt ("ddq[%i]? SizeOfHeader SizeOfEntry " "NumberOfEntries (mdmp_memory_info)MemoryInfo", memory_info_list->number_of_entries), 0); for (i = 0; i < memory_info_list->number_of_entries; i++) { memory_infos = (struct minidump_memory_info *)((ut8 *)memory_info_list + sizeof (struct minidump_memory_info_list)); r_list_append (obj->streams.memory_infos, &(memory_infos[i])); } break; case THREAD_INFO_LIST_STREAM: /* TODO: Not yet fully parsed or utilised */ thread_info_list = (struct minidump_thread_info_list *)(obj->b->buf + entry->location.rva); sdb_set (obj->kv, "mdmp_thread_info.format", "ddddttttqq " "ThreadId DumpFlags DumpError ExitStatus CreateTime " "ExitTime KernelTime UserTime StartAddress Affinity", 0); sdb_num_set (obj->kv, "mdmp_thread_info_list.offset", entry->location.rva, 0); sdb_set (obj->kv, "mdmp_thread_info_list.format", "ddd " "SizeOfHeader SizeOfEntry NumberOfEntries", 0); for (i = 0; i < thread_info_list->number_of_entries; i++) { thread_infos = (struct minidump_thread_info *)((ut8 *)thread_info_list + sizeof (struct minidump_thread_info_list)); r_list_append (obj->streams.thread_infos, &(thread_infos[i])); } break; case HANDLE_OPERATION_LIST_STREAM: /* TODO: Not yet fully parsed or utilised */ handle_operation_list = (struct minidump_handle_operation_list *)(obj->b->buf + entry->location.rva); sdb_num_set (obj->kv, "mdmp_handle_operation_list.offset", entry->location.rva, 0); sdb_set (obj->kv, "mdmp_handle_operation_list.format", "dddd " "SizeOfHeader SizeOfEntry NumberOfEntries Reserved", 0); for (i = 0; i < handle_operation_list->number_of_entries; i++) { handle_operations = (struct avrf_handle_operation *)((ut8 *)handle_operation_list + sizeof (struct minidump_handle_operation_list)); r_list_append (obj->streams.operations, &(handle_operations[i])); } break; case LAST_RESERVED_STREAM: /* TODO: Not yet fully parsed or utilised */ break; case UNUSED_STREAM: case RESERVED_STREAM_0: case RESERVED_STREAM_1: /* Silently ignore reserved streams */ break; default: eprintf ("[WARN] Invalid or unsupported enumeration encountered %i\n", entry->stream_type); return false; } return true; } Commit Message: Fix #10464 - oobread crash in mdmp CWE ID: CWE-125
static bool r_bin_mdmp_init_directory_entry(struct r_bin_mdmp_obj *obj, struct minidump_directory *entry) { int i; struct minidump_handle_operation_list *handle_operation_list; struct minidump_memory_list *memory_list; struct minidump_memory64_list *memory64_list; struct minidump_memory_info_list *memory_info_list; struct minidump_module_list *module_list; struct minidump_thread_list *thread_list; struct minidump_thread_ex_list *thread_ex_list; struct minidump_thread_info_list *thread_info_list; struct minidump_unloaded_module_list *unloaded_module_list; struct avrf_handle_operation *handle_operations; struct minidump_memory_descriptor *memories; struct minidump_memory_descriptor64 *memories64; struct minidump_memory_info *memory_infos; struct minidump_module *modules; struct minidump_thread *threads; struct minidump_thread_ex *ex_threads; struct minidump_thread_info *thread_infos; struct minidump_unloaded_module *unloaded_modules; /* We could confirm data sizes but a malcious MDMP will always get around ** this! But we can ensure that the data is not outside of the file */ if (entry->location.rva + entry->location.data_size > obj->b->length) { eprintf ("[ERROR] Size Mismatch - Stream data is larger than file size!\n"); return false; } switch (entry->stream_type) { case THREAD_LIST_STREAM: thread_list = (struct minidump_thread_list *)(obj->b->buf + entry->location.rva); sdb_set (obj->kv, "mdmp_thread.format", "ddddq?? " "ThreadId SuspendCount PriorityClass Priority " "Teb (mdmp_memory_descriptor)Stack " "(mdmp_location_descriptor)ThreadContext", 0); sdb_num_set (obj->kv, "mdmp_thread_list.offset", entry->location.rva, 0); sdb_set (obj->kv, "mdmp_thread_list.format", sdb_fmt ("d[%i]? " "NumberOfThreads (mdmp_thread)Threads", thread_list->number_of_threads), 0); /* TODO: Not yet fully parsed or utilised */ for (i = 0; i < thread_list->number_of_threads; i++) { threads = (struct minidump_thread *)(&(thread_list->threads)); r_list_append (obj->streams.threads, &(threads[i])); } break; case MODULE_LIST_STREAM: module_list = (struct minidump_module_list *)(obj->b->buf + entry->location.rva); sdb_set (obj->kv, "mdmp_module.format", "qddtd???qq " "BaseOfImage SizeOfImage CheckSum " "TimeDateStamp ModuleNameRVA " "(mdmp_vs_fixedfileinfo)VersionInfo " "(mdmp_location_descriptor)CvRecord " "(mdmp_location_descriptor)MiscRecord " "Reserved0 Reserved1", 0); sdb_num_set (obj->kv, "mdmp_module_list.offset", entry->location.rva, 0); sdb_set (obj->kv, "mdmp_module_list.format", sdb_fmt ("d[%i]? " "NumberOfModule (mdmp_module)Modules", module_list->number_of_modules, 0), 0); for (i = 0; i < module_list->number_of_modules; i++) { modules = (struct minidump_module *)(&(module_list->modules)); r_list_append(obj->streams.modules, &(modules[i])); } break; case MEMORY_LIST_STREAM: memory_list = (struct minidump_memory_list *)(obj->b->buf + entry->location.rva); sdb_num_set (obj->kv, "mdmp_memory_list.offset", entry->location.rva, 0); sdb_set (obj->kv, "mdmp_memory_list.format", sdb_fmt ("d[%i]? " "NumberOfMemoryRanges " "(mdmp_memory_descriptor)MemoryRanges ", memory_list->number_of_memory_ranges, 0), 0); for (i = 0; i < memory_list->number_of_memory_ranges; i++) { memories = (struct minidump_memory_descriptor *)(&(memory_list->memory_ranges)); r_list_append (obj->streams.memories, &(memories[i])); } break; case EXCEPTION_STREAM: /* TODO: Not yet fully parsed or utilised */ obj->streams.exception = (struct minidump_exception_stream *)(obj->b->buf + entry->location.rva); sdb_set (obj->kv, "mdmp_exception.format", "[4]E[4]Eqqdd[15]q " "(mdmp_exception_code)ExceptionCode " "(mdmp_exception_flags)ExceptionFlags " "ExceptionRecord ExceptionAddress " "NumberParameters __UnusedAlignment " "ExceptionInformation", 0); sdb_num_set (obj->kv, "mdmp_exception_stream.offset", entry->location.rva, 0); sdb_set (obj->kv, "mdmp_exception_stream.format", "dd?? " "ThreadId __Alignment " "(mdmp_exception)ExceptionRecord " "(mdmp_location_descriptor)ThreadContext", 0); break; case SYSTEM_INFO_STREAM: obj->streams.system_info = (struct minidump_system_info *)(obj->b->buf + entry->location.rva); sdb_num_set (obj->kv, "mdmp_system_info.offset", entry->location.rva, 0); /* TODO: We need E as a byte! */ sdb_set (obj->kv, "mdmp_system_info.format", "[2]EwwbBddd[4]Ed[2]Ew[2]q " "(mdmp_processor_architecture)ProcessorArchitecture " "ProcessorLevel ProcessorRevision NumberOfProcessors " "(mdmp_product_type)ProductType " "MajorVersion MinorVersion BuildNumber (mdmp_platform_id)PlatformId " "CsdVersionRva (mdmp_suite_mask)SuiteMask Reserved2 ProcessorFeatures", 0); break; case THREAD_EX_LIST_STREAM: /* TODO: Not yet fully parsed or utilised */ thread_ex_list = (struct minidump_thread_ex_list *)(obj->b->buf + entry->location.rva); sdb_set (obj->kv, "mdmp_thread_ex.format", "ddddq??? " "ThreadId SuspendCount PriorityClass Priority " "Teb (mdmp_memory_descriptor)Stack " "(mdmp_location_descriptor)ThreadContext " "(mdmp_memory_descriptor)BackingStore", 0); sdb_num_set (obj->kv, "mdmp_thread_ex_list.offset", entry->location.rva, 0); sdb_set (obj->kv, "mdmp_thread_ex_list.format", sdb_fmt ("d[%i]? NumberOfThreads " "(mdmp_thread_ex)Threads", thread_ex_list->number_of_threads, 0), 0); for (i = 0; i < thread_ex_list->number_of_threads; i++) { ex_threads = (struct minidump_thread_ex *)(&(thread_ex_list->threads)); r_list_append (obj->streams.ex_threads, &(ex_threads[i])); } break; case MEMORY_64_LIST_STREAM: memory64_list = (struct minidump_memory64_list *)(obj->b->buf + entry->location.rva); sdb_num_set (obj->kv, "mdmp_memory64_list.offset", entry->location.rva, 0); sdb_set (obj->kv, "mdmp_memory64_list.format", sdb_fmt ("qq[%i]? NumberOfMemoryRanges " "BaseRva " "(mdmp_memory_descriptor64)MemoryRanges", memory64_list->number_of_memory_ranges), 0); obj->streams.memories64.base_rva = memory64_list->base_rva; for (i = 0; i < memory64_list->number_of_memory_ranges; i++) { memories64 = (struct minidump_memory_descriptor64 *)(&(memory64_list->memory_ranges)); r_list_append (obj->streams.memories64.memories, &(memories64[i])); } break; case COMMENT_STREAM_A: /* TODO: Not yet fully parsed or utilised */ obj->streams.comments_a = obj->b->buf + entry->location.rva; sdb_num_set (obj->kv, "mdmp_comment_stream_a.offset", entry->location.rva, 0); sdb_set (obj->kv, "mdmp_comment_stream_a.format", "s CommentA", 0); break; case COMMENT_STREAM_W: /* TODO: Not yet fully parsed or utilised */ obj->streams.comments_w = obj->b->buf + entry->location.rva; sdb_num_set (obj->kv, "mdmp_comment_stream_w.offset", entry->location.rva, 0); sdb_set (obj->kv, "mdmp_comment_stream_w.format", "s CommentW", 0); break; case HANDLE_DATA_STREAM: /* TODO: Not yet fully parsed or utilised */ obj->streams.handle_data = (struct minidump_handle_data_stream *)(obj->b->buf + entry->location.rva); sdb_num_set (obj->kv, "mdmp_handle_data_stream.offset", entry->location.rva, 0); sdb_set (obj->kv, "mdmp_handle_data_stream.format", "dddd " "SizeOfHeader SizeOfDescriptor " "NumberOfDescriptors Reserved", 0); break; case FUNCTION_TABLE_STREAM: /* TODO: Not yet fully parsed or utilised */ obj->streams.function_table = (struct minidump_function_table_stream *)(obj->b->buf + entry->location.rva); sdb_num_set (obj->kv, "mdmp_function_table_stream.offset", entry->location.rva, 0); sdb_set (obj->kv, "mdmp_function_table_stream.format", "dddddd " "SizeOfHeader SizeOfDescriptor SizeOfNativeDescriptor " "SizeOfFunctionEntry NumberOfDescriptors SizeOfAlignPad", 0); break; case UNLOADED_MODULE_LIST_STREAM: /* TODO: Not yet fully parsed or utilised */ unloaded_module_list = (struct minidump_unloaded_module_list *)(obj->b->buf + entry->location.rva); sdb_set (obj->kv, "mdmp_unloaded_module.format", "qddtd " "BaseOfImage SizeOfImage CheckSum TimeDateStamp " "ModuleNameRva", 0); sdb_num_set (obj->kv, "mdmp_unloaded_module_list.offset", entry->location.rva, 0); sdb_set (obj->kv, "mdmp_unloaded_module_list.format", "ddd " "SizeOfHeader SizeOfEntry NumberOfEntries", 0); for (i = 0; i < unloaded_module_list->number_of_entries; i++) { unloaded_modules = (struct minidump_unloaded_module *)((ut8 *)&unloaded_module_list + sizeof (struct minidump_unloaded_module_list)); r_list_append (obj->streams.unloaded_modules, &(unloaded_modules[i])); } break; case MISC_INFO_STREAM: /* TODO: Not yet fully parsed or utilised */ obj->streams.misc_info.misc_info_1 = (struct minidump_misc_info *)(obj->b->buf + entry->location.rva); /* TODO: Handle different sizes */ sdb_num_set (obj->kv, "mdmp_misc_info.offset", entry->location.rva, 0); sdb_set (obj->kv, "mdmp_misc_info.format", "d[4]Bdtttddddd " "SizeOfInfo (mdmp_misc1_flags)Flags1 ProcessId " "ProcessCreateTime ProcessUserTime ProcessKernelTime " "ProcessorMaxMhz ProcessorCurrentMhz " "ProcessorMhzLimit ProcessorMaxIdleState " "ProcessorCurrentIdleState", 0); break; case MEMORY_INFO_LIST_STREAM: memory_info_list = (struct minidump_memory_info_list *)(obj->b->buf + entry->location.rva); sdb_set (obj->kv, "mdmp_memory_info.format", "qq[4]Edq[4]E[4]E[4]Ed BaseAddress AllocationBase " "(mdmp_page_protect)AllocationProtect __Alignment1 RegionSize " "(mdmp_mem_state)State (mdmp_page_protect)Protect " "(mdmp_mem_type)Type __Alignment2", 0); sdb_num_set (obj->kv, "mdmp_memory_info_list.offset", entry->location.rva, 0); sdb_set (obj->kv, "mdmp_memory_info_list.format", sdb_fmt ("ddq[%i]? SizeOfHeader SizeOfEntry " "NumberOfEntries (mdmp_memory_info)MemoryInfo", memory_info_list->number_of_entries), 0); for (i = 0; i < memory_info_list->number_of_entries; i++) { memory_infos = (struct minidump_memory_info *)((ut8 *)memory_info_list + sizeof (struct minidump_memory_info_list)); r_list_append (obj->streams.memory_infos, &(memory_infos[i])); } break; case THREAD_INFO_LIST_STREAM: /* TODO: Not yet fully parsed or utilised */ thread_info_list = (struct minidump_thread_info_list *)(obj->b->buf + entry->location.rva); sdb_set (obj->kv, "mdmp_thread_info.format", "ddddttttqq " "ThreadId DumpFlags DumpError ExitStatus CreateTime " "ExitTime KernelTime UserTime StartAddress Affinity", 0); sdb_num_set (obj->kv, "mdmp_thread_info_list.offset", entry->location.rva, 0); sdb_set (obj->kv, "mdmp_thread_info_list.format", "ddd " "SizeOfHeader SizeOfEntry NumberOfEntries", 0); for (i = 0; i < thread_info_list->number_of_entries; i++) { thread_infos = (struct minidump_thread_info *)((ut8 *)thread_info_list + sizeof (struct minidump_thread_info_list)); r_list_append (obj->streams.thread_infos, &(thread_infos[i])); } break; case HANDLE_OPERATION_LIST_STREAM: /* TODO: Not yet fully parsed or utilised */ handle_operation_list = (struct minidump_handle_operation_list *)(obj->b->buf + entry->location.rva); sdb_num_set (obj->kv, "mdmp_handle_operation_list.offset", entry->location.rva, 0); sdb_set (obj->kv, "mdmp_handle_operation_list.format", "dddd " "SizeOfHeader SizeOfEntry NumberOfEntries Reserved", 0); for (i = 0; i < handle_operation_list->number_of_entries; i++) { handle_operations = (struct avrf_handle_operation *)((ut8 *)handle_operation_list + sizeof (struct minidump_handle_operation_list)); r_list_append (obj->streams.operations, &(handle_operations[i])); } break; case LAST_RESERVED_STREAM: /* TODO: Not yet fully parsed or utilised */ break; case UNUSED_STREAM: case RESERVED_STREAM_0: case RESERVED_STREAM_1: /* Silently ignore reserved streams */ break; default: eprintf ("[WARN] Invalid or unsupported enumeration encountered %i\n", entry->stream_type); return false; } return true; }
169,149
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: views::ImageButton* close_button() const { return media_controls_view_->close_button_; } Commit Message: [Lock Screen Media Controls] Tweak UI based on new mocks This CL rearranges the different components of the CrOS lock screen media controls based on the newest mocks. This involves resizing most of the child views and their spacings. The artwork was also resized and re-positioned. Additionally, the close button was moved from the main view to the header row child view. Artist and title data about the current session will eventually be placed to the right of the artwork, but right now this space is empty. See the bug for before and after pictures. Bug: 991647 Change-Id: I7b97f31982ccf2912bd2564d5241bfd849d21d92 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1746554 Reviewed-by: Xiyuan Xia <[email protected]> Reviewed-by: Becca Hughes <[email protected]> Commit-Queue: Mia Bergeron <[email protected]> Cr-Commit-Position: refs/heads/master@{#686253} CWE ID: CWE-200
views::ImageButton* close_button() const {
172,343
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void SavePackage::OnReceivedSavableResourceLinksForCurrentPage( const std::vector<GURL>& resources_list, const std::vector<Referrer>& referrers_list, const std::vector<GURL>& frames_list) { if (wait_state_ != RESOURCES_LIST) return; DCHECK(resources_list.size() == referrers_list.size()); all_save_items_count_ = static_cast<int>(resources_list.size()) + static_cast<int>(frames_list.size()); if (download_ && download_->IsInProgress()) download_->SetTotalBytes(all_save_items_count_); if (all_save_items_count_) { for (int i = 0; i < static_cast<int>(resources_list.size()); ++i) { const GURL& u = resources_list[i]; DCHECK(u.is_valid()); SaveFileCreateInfo::SaveFileSource save_source = u.SchemeIsFile() ? SaveFileCreateInfo::SAVE_FILE_FROM_FILE : SaveFileCreateInfo::SAVE_FILE_FROM_NET; SaveItem* save_item = new SaveItem(u, referrers_list[i], this, save_source); waiting_item_queue_.push(save_item); } for (int i = 0; i < static_cast<int>(frames_list.size()); ++i) { const GURL& u = frames_list[i]; DCHECK(u.is_valid()); SaveItem* save_item = new SaveItem( u, Referrer(), this, SaveFileCreateInfo::SAVE_FILE_FROM_DOM); waiting_item_queue_.push(save_item); } wait_state_ = NET_FILES; DoSavingProcess(); } else { Cancel(true); } } Commit Message: Fix crash with mismatched vector sizes. BUG=169295 Review URL: https://codereview.chromium.org/11817050 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@176252 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
void SavePackage::OnReceivedSavableResourceLinksForCurrentPage( const std::vector<GURL>& resources_list, const std::vector<Referrer>& referrers_list, const std::vector<GURL>& frames_list) { if (wait_state_ != RESOURCES_LIST) return; if (resources_list.size() != referrers_list.size()) return; all_save_items_count_ = static_cast<int>(resources_list.size()) + static_cast<int>(frames_list.size()); if (download_ && download_->IsInProgress()) download_->SetTotalBytes(all_save_items_count_); if (all_save_items_count_) { for (int i = 0; i < static_cast<int>(resources_list.size()); ++i) { const GURL& u = resources_list[i]; DCHECK(u.is_valid()); SaveFileCreateInfo::SaveFileSource save_source = u.SchemeIsFile() ? SaveFileCreateInfo::SAVE_FILE_FROM_FILE : SaveFileCreateInfo::SAVE_FILE_FROM_NET; SaveItem* save_item = new SaveItem(u, referrers_list[i], this, save_source); waiting_item_queue_.push(save_item); } for (int i = 0; i < static_cast<int>(frames_list.size()); ++i) { const GURL& u = frames_list[i]; DCHECK(u.is_valid()); SaveItem* save_item = new SaveItem( u, Referrer(), this, SaveFileCreateInfo::SAVE_FILE_FROM_DOM); waiting_item_queue_.push(save_item); } wait_state_ = NET_FILES; DoSavingProcess(); } else { Cancel(true); } }
171,400
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: long do_shmat(int shmid, char __user *shmaddr, int shmflg, ulong *raddr, unsigned long shmlba) { struct shmid_kernel *shp; unsigned long addr; unsigned long size; struct file * file; int err; unsigned long flags; unsigned long prot; int acc_mode; struct ipc_namespace *ns; struct shm_file_data *sfd; struct path path; fmode_t f_mode; unsigned long populate = 0; err = -EINVAL; if (shmid < 0) goto out; else if ((addr = (ulong)shmaddr)) { if (addr & (shmlba - 1)) { if (shmflg & SHM_RND) addr &= ~(shmlba - 1); /* round down */ else #ifndef __ARCH_FORCE_SHMLBA if (addr & ~PAGE_MASK) #endif goto out; } flags = MAP_SHARED | MAP_FIXED; } else { if ((shmflg & SHM_REMAP)) goto out; flags = MAP_SHARED; } if (shmflg & SHM_RDONLY) { prot = PROT_READ; acc_mode = S_IRUGO; f_mode = FMODE_READ; } else { prot = PROT_READ | PROT_WRITE; acc_mode = S_IRUGO | S_IWUGO; f_mode = FMODE_READ | FMODE_WRITE; } if (shmflg & SHM_EXEC) { prot |= PROT_EXEC; acc_mode |= S_IXUGO; } /* * We cannot rely on the fs check since SYSV IPC does have an * additional creator id... */ ns = current->nsproxy->ipc_ns; rcu_read_lock(); shp = shm_obtain_object_check(ns, shmid); if (IS_ERR(shp)) { err = PTR_ERR(shp); goto out_unlock; } err = -EACCES; if (ipcperms(ns, &shp->shm_perm, acc_mode)) goto out_unlock; err = security_shm_shmat(shp, shmaddr, shmflg); if (err) goto out_unlock; ipc_lock_object(&shp->shm_perm); path = shp->shm_file->f_path; path_get(&path); shp->shm_nattch++; size = i_size_read(path.dentry->d_inode); ipc_unlock_object(&shp->shm_perm); rcu_read_unlock(); err = -ENOMEM; sfd = kzalloc(sizeof(*sfd), GFP_KERNEL); if (!sfd) { path_put(&path); goto out_nattch; } file = alloc_file(&path, f_mode, is_file_hugepages(shp->shm_file) ? &shm_file_operations_huge : &shm_file_operations); err = PTR_ERR(file); if (IS_ERR(file)) { kfree(sfd); path_put(&path); goto out_nattch; } file->private_data = sfd; file->f_mapping = shp->shm_file->f_mapping; sfd->id = shp->shm_perm.id; sfd->ns = get_ipc_ns(ns); sfd->file = shp->shm_file; sfd->vm_ops = NULL; err = security_mmap_file(file, prot, flags); if (err) goto out_fput; down_write(&current->mm->mmap_sem); if (addr && !(shmflg & SHM_REMAP)) { err = -EINVAL; if (find_vma_intersection(current->mm, addr, addr + size)) goto invalid; /* * If shm segment goes below stack, make sure there is some * space left for the stack to grow (at least 4 pages). */ if (addr < current->mm->start_stack && addr > current->mm->start_stack - size - PAGE_SIZE * 5) goto invalid; } addr = do_mmap_pgoff(file, addr, size, prot, flags, 0, &populate); *raddr = addr; err = 0; if (IS_ERR_VALUE(addr)) err = (long)addr; invalid: up_write(&current->mm->mmap_sem); if (populate) mm_populate(addr, populate); out_fput: fput(file); out_nattch: down_write(&shm_ids(ns).rwsem); shp = shm_lock(ns, shmid); BUG_ON(IS_ERR(shp)); shp->shm_nattch--; if (shm_may_destroy(ns, shp)) shm_destroy(ns, shp); else shm_unlock(shp); up_write(&shm_ids(ns).rwsem); return err; out_unlock: rcu_read_unlock(); out: return err; } Commit Message: ipc,shm: fix shm_file deletion races When IPC_RMID races with other shm operations there's potential for use-after-free of the shm object's associated file (shm_file). Here's the race before this patch: TASK 1 TASK 2 ------ ------ shm_rmid() ipc_lock_object() shmctl() shp = shm_obtain_object_check() shm_destroy() shum_unlock() fput(shp->shm_file) ipc_lock_object() shmem_lock(shp->shm_file) <OOPS> The oops is caused because shm_destroy() calls fput() after dropping the ipc_lock. fput() clears the file's f_inode, f_path.dentry, and f_path.mnt, which causes various NULL pointer references in task 2. I reliably see the oops in task 2 if with shmlock, shmu This patch fixes the races by: 1) set shm_file=NULL in shm_destroy() while holding ipc_object_lock(). 2) modify at risk operations to check shm_file while holding ipc_object_lock(). Example workloads, which each trigger oops... Workload 1: while true; do id=$(shmget 1 4096) shm_rmid $id & shmlock $id & wait done The oops stack shows accessing NULL f_inode due to racing fput: _raw_spin_lock shmem_lock SyS_shmctl Workload 2: while true; do id=$(shmget 1 4096) shmat $id 4096 & shm_rmid $id & wait done The oops stack is similar to workload 1 due to NULL f_inode: touch_atime shmem_mmap shm_mmap mmap_region do_mmap_pgoff do_shmat SyS_shmat Workload 3: while true; do id=$(shmget 1 4096) shmlock $id shm_rmid $id & shmunlock $id & wait done The oops stack shows second fput tripping on an NULL f_inode. The first fput() completed via from shm_destroy(), but a racing thread did a get_file() and queued this fput(): locks_remove_flock __fput ____fput task_work_run do_notify_resume int_signal Fixes: c2c737a0461e ("ipc,shm: shorten critical region for shmat") Fixes: 2caacaa82a51 ("ipc,shm: shorten critical region for shmctl") Signed-off-by: Greg Thelen <[email protected]> Cc: Davidlohr Bueso <[email protected]> Cc: Rik van Riel <[email protected]> Cc: Manfred Spraul <[email protected]> Cc: <[email protected]> # 3.10.17+ 3.11.6+ Signed-off-by: Andrew Morton <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-362
long do_shmat(int shmid, char __user *shmaddr, int shmflg, ulong *raddr, unsigned long shmlba) { struct shmid_kernel *shp; unsigned long addr; unsigned long size; struct file * file; int err; unsigned long flags; unsigned long prot; int acc_mode; struct ipc_namespace *ns; struct shm_file_data *sfd; struct path path; fmode_t f_mode; unsigned long populate = 0; err = -EINVAL; if (shmid < 0) goto out; else if ((addr = (ulong)shmaddr)) { if (addr & (shmlba - 1)) { if (shmflg & SHM_RND) addr &= ~(shmlba - 1); /* round down */ else #ifndef __ARCH_FORCE_SHMLBA if (addr & ~PAGE_MASK) #endif goto out; } flags = MAP_SHARED | MAP_FIXED; } else { if ((shmflg & SHM_REMAP)) goto out; flags = MAP_SHARED; } if (shmflg & SHM_RDONLY) { prot = PROT_READ; acc_mode = S_IRUGO; f_mode = FMODE_READ; } else { prot = PROT_READ | PROT_WRITE; acc_mode = S_IRUGO | S_IWUGO; f_mode = FMODE_READ | FMODE_WRITE; } if (shmflg & SHM_EXEC) { prot |= PROT_EXEC; acc_mode |= S_IXUGO; } /* * We cannot rely on the fs check since SYSV IPC does have an * additional creator id... */ ns = current->nsproxy->ipc_ns; rcu_read_lock(); shp = shm_obtain_object_check(ns, shmid); if (IS_ERR(shp)) { err = PTR_ERR(shp); goto out_unlock; } err = -EACCES; if (ipcperms(ns, &shp->shm_perm, acc_mode)) goto out_unlock; err = security_shm_shmat(shp, shmaddr, shmflg); if (err) goto out_unlock; ipc_lock_object(&shp->shm_perm); /* check if shm_destroy() is tearing down shp */ if (shp->shm_file == NULL) { ipc_unlock_object(&shp->shm_perm); err = -EIDRM; goto out_unlock; } path = shp->shm_file->f_path; path_get(&path); shp->shm_nattch++; size = i_size_read(path.dentry->d_inode); ipc_unlock_object(&shp->shm_perm); rcu_read_unlock(); err = -ENOMEM; sfd = kzalloc(sizeof(*sfd), GFP_KERNEL); if (!sfd) { path_put(&path); goto out_nattch; } file = alloc_file(&path, f_mode, is_file_hugepages(shp->shm_file) ? &shm_file_operations_huge : &shm_file_operations); err = PTR_ERR(file); if (IS_ERR(file)) { kfree(sfd); path_put(&path); goto out_nattch; } file->private_data = sfd; file->f_mapping = shp->shm_file->f_mapping; sfd->id = shp->shm_perm.id; sfd->ns = get_ipc_ns(ns); sfd->file = shp->shm_file; sfd->vm_ops = NULL; err = security_mmap_file(file, prot, flags); if (err) goto out_fput; down_write(&current->mm->mmap_sem); if (addr && !(shmflg & SHM_REMAP)) { err = -EINVAL; if (find_vma_intersection(current->mm, addr, addr + size)) goto invalid; /* * If shm segment goes below stack, make sure there is some * space left for the stack to grow (at least 4 pages). */ if (addr < current->mm->start_stack && addr > current->mm->start_stack - size - PAGE_SIZE * 5) goto invalid; } addr = do_mmap_pgoff(file, addr, size, prot, flags, 0, &populate); *raddr = addr; err = 0; if (IS_ERR_VALUE(addr)) err = (long)addr; invalid: up_write(&current->mm->mmap_sem); if (populate) mm_populate(addr, populate); out_fput: fput(file); out_nattch: down_write(&shm_ids(ns).rwsem); shp = shm_lock(ns, shmid); BUG_ON(IS_ERR(shp)); shp->shm_nattch--; if (shm_may_destroy(ns, shp)) shm_destroy(ns, shp); else shm_unlock(shp); up_write(&shm_ids(ns).rwsem); return err; out_unlock: rcu_read_unlock(); out: return err; }
165,911
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static uint16_t transmit_data(serial_data_type_t type, uint8_t *data, uint16_t length) { assert(data != NULL); assert(length > 0); if (type < DATA_TYPE_COMMAND || type > DATA_TYPE_SCO) { LOG_ERROR("%s invalid data type: %d", __func__, type); return 0; } --data; uint8_t previous_byte = *data; *(data) = type; ++length; uint16_t transmitted_length = 0; while (length > 0) { ssize_t ret = write(uart_fd, data + transmitted_length, length); switch (ret) { case -1: LOG_ERROR("In %s, error writing to the uart serial port: %s", __func__, strerror(errno)); goto done; case 0: goto done; default: transmitted_length += ret; length -= ret; break; } } done:; *(data) = previous_byte; if (transmitted_length > 0) --transmitted_length; return transmitted_length; } 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 uint16_t transmit_data(serial_data_type_t type, uint8_t *data, uint16_t length) { assert(data != NULL); assert(length > 0); if (type < DATA_TYPE_COMMAND || type > DATA_TYPE_SCO) { LOG_ERROR("%s invalid data type: %d", __func__, type); return 0; } --data; uint8_t previous_byte = *data; *(data) = type; ++length; uint16_t transmitted_length = 0; while (length > 0) { ssize_t ret = TEMP_FAILURE_RETRY(write(uart_fd, data + transmitted_length, length)); switch (ret) { case -1: LOG_ERROR("In %s, error writing to the uart serial port: %s", __func__, strerror(errno)); goto done; case 0: goto done; default: transmitted_length += ret; length -= ret; break; } } done:; *(data) = previous_byte; if (transmitted_length > 0) --transmitted_length; return transmitted_length; }
173,476
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: l2tp_framing_type_print(netdissect_options *ndo, const u_char *dat) { const uint32_t *ptr = (const uint32_t *)dat; if (EXTRACT_32BITS(ptr) & L2TP_FRAMING_TYPE_ASYNC_MASK) { ND_PRINT((ndo, "A")); } if (EXTRACT_32BITS(ptr) & L2TP_FRAMING_TYPE_SYNC_MASK) { ND_PRINT((ndo, "S")); } } 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_framing_type_print(netdissect_options *ndo, const u_char *dat) l2tp_framing_type_print(netdissect_options *ndo, const u_char *dat, u_int length) { const uint32_t *ptr = (const uint32_t *)dat; if (length < 4) { ND_PRINT((ndo, "AVP too short")); return; } if (EXTRACT_32BITS(ptr) & L2TP_FRAMING_TYPE_ASYNC_MASK) { ND_PRINT((ndo, "A")); } if (EXTRACT_32BITS(ptr) & L2TP_FRAMING_TYPE_SYNC_MASK) { ND_PRINT((ndo, "S")); } }
167,895
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: LockServer(void) { char tmp[PATH_MAX], pid_str[12]; int lfd, i, haslock, l_pid, t; char *tmppath = NULL; int len; char port[20]; if (nolock) return; /* * Path names */ tmppath = LOCK_DIR; sprintf(port, "%d", atoi(display)); len = strlen(LOCK_PREFIX) > strlen(LOCK_TMP_PREFIX) ? strlen(LOCK_PREFIX) : strlen(LOCK_TMP_PREFIX); len += strlen(tmppath) + strlen(port) + strlen(LOCK_SUFFIX) + 1; if (len > sizeof(LockFile)) FatalError("Display name `%s' is too long\n", port); (void)sprintf(tmp, "%s" LOCK_TMP_PREFIX "%s" LOCK_SUFFIX, tmppath, port); (void)sprintf(LockFile, "%s" LOCK_PREFIX "%s" LOCK_SUFFIX, tmppath, port); /* * Create a temporary file containing our PID. Attempt three times * to create the file. */ StillLocking = TRUE; i = 0; do { i++; lfd = open(tmp, O_CREAT | O_EXCL | O_WRONLY, 0644); if (lfd < 0) sleep(2); else break; } while (i < 3); if (lfd < 0) { unlink(tmp); i = 0; do { i++; lfd = open(tmp, O_CREAT | O_EXCL | O_WRONLY, 0644); if (lfd < 0) sleep(2); else break; } while (i < 3); } if (lfd < 0) FatalError("Could not create lock file in %s\n", tmp); (void) sprintf(pid_str, "%10ld\n", (long)getpid()); (void) write(lfd, pid_str, 11); (void) chmod(tmp, 0444); (void) close(lfd); /* * OK. Now the tmp file exists. Try three times to move it in place * for the lock. */ i = 0; haslock = 0; while ((!haslock) && (i++ < 3)) { haslock = (link(tmp,LockFile) == 0); if (haslock) { /* * We're done. */ break; } else { /* * Read the pid from the existing file */ lfd = open(LockFile, O_RDONLY); if (lfd < 0) { unlink(tmp); FatalError("Can't read lock file %s\n", LockFile); } pid_str[0] = '\0'; if (read(lfd, pid_str, 11) != 11) { /* * Bogus lock file. */ unlink(LockFile); close(lfd); continue; } pid_str[11] = '\0'; sscanf(pid_str, "%d", &l_pid); close(lfd); /* * Now try to kill the PID to see if it exists. */ errno = 0; t = kill(l_pid, 0); if ((t< 0) && (errno == ESRCH)) { /* * Stale lock file. */ unlink(LockFile); continue; } else if (((t < 0) && (errno == EPERM)) || (t == 0)) { /* * Process is still active. */ unlink(tmp); FatalError("Server is already active for display %s\n%s %s\n%s\n", port, "\tIf this server is no longer running, remove", LockFile, "\tand start again."); } } } unlink(tmp); if (!haslock) FatalError("Could not create server lock file: %s\n", LockFile); StillLocking = FALSE; } Commit Message: CWE ID: CWE-59
LockServer(void) { char tmp[PATH_MAX], pid_str[12]; int lfd, i, haslock, l_pid, t; char *tmppath = NULL; int len; char port[20]; if (nolock) return; /* * Path names */ tmppath = LOCK_DIR; sprintf(port, "%d", atoi(display)); len = strlen(LOCK_PREFIX) > strlen(LOCK_TMP_PREFIX) ? strlen(LOCK_PREFIX) : strlen(LOCK_TMP_PREFIX); len += strlen(tmppath) + strlen(port) + strlen(LOCK_SUFFIX) + 1; if (len > sizeof(LockFile)) FatalError("Display name `%s' is too long\n", port); (void)sprintf(tmp, "%s" LOCK_TMP_PREFIX "%s" LOCK_SUFFIX, tmppath, port); (void)sprintf(LockFile, "%s" LOCK_PREFIX "%s" LOCK_SUFFIX, tmppath, port); /* * Create a temporary file containing our PID. Attempt three times * to create the file. */ StillLocking = TRUE; i = 0; do { i++; lfd = open(tmp, O_CREAT | O_EXCL | O_WRONLY, 0644); if (lfd < 0) sleep(2); else break; } while (i < 3); if (lfd < 0) { unlink(tmp); i = 0; do { i++; lfd = open(tmp, O_CREAT | O_EXCL | O_WRONLY, 0644); if (lfd < 0) sleep(2); else break; } while (i < 3); } if (lfd < 0) FatalError("Could not create lock file in %s\n", tmp); (void) sprintf(pid_str, "%10ld\n", (long)getpid()); (void) write(lfd, pid_str, 11); (void) chmod(tmp, 0444); (void) close(lfd); /* * OK. Now the tmp file exists. Try three times to move it in place * for the lock. */ i = 0; haslock = 0; while ((!haslock) && (i++ < 3)) { haslock = (link(tmp,LockFile) == 0); if (haslock) { /* * We're done. */ break; } else { /* * Read the pid from the existing file */ lfd = open(LockFile, O_RDONLY|O_NOFOLLOW); if (lfd < 0) { unlink(tmp); FatalError("Can't read lock file %s\n", LockFile); } pid_str[0] = '\0'; if (read(lfd, pid_str, 11) != 11) { /* * Bogus lock file. */ unlink(LockFile); close(lfd); continue; } pid_str[11] = '\0'; sscanf(pid_str, "%d", &l_pid); close(lfd); /* * Now try to kill the PID to see if it exists. */ errno = 0; t = kill(l_pid, 0); if ((t< 0) && (errno == ESRCH)) { /* * Stale lock file. */ unlink(LockFile); continue; } else if (((t < 0) && (errno == EPERM)) || (t == 0)) { /* * Process is still active. */ unlink(tmp); FatalError("Server is already active for display %s\n%s %s\n%s\n", port, "\tIf this server is no longer running, remove", LockFile, "\tand start again."); } } } unlink(tmp); if (!haslock) FatalError("Could not create server lock file: %s\n", LockFile); StillLocking = FALSE; }
165,237
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: UNCURL_EXPORT int32_t uncurl_ws_accept(struct uncurl_conn *ucc, char **origins, int32_t n_origins) { int32_t e; e = uncurl_read_header(ucc); if (e != UNCURL_OK) return e; uncurl_set_header_str(ucc, "Upgrade", "websocket"); uncurl_set_header_str(ucc, "Connection", "Upgrade"); char *origin = NULL; e = uncurl_get_header_str(ucc, "Origin", &origin); if (e != UNCURL_OK) return e; bool origin_ok = false; for (int32_t x = 0; x < n_origins; x++) if (strstr(origin, origins[x])) {origin_ok = true; break;} if (!origin_ok) return UNCURL_WS_ERR_ORIGIN; char *sec_key = NULL; e = uncurl_get_header_str(ucc, "Sec-WebSocket-Key", &sec_key); if (e != UNCURL_OK) return e; char *accept_key = ws_create_accept_key(sec_key); uncurl_set_header_str(ucc, "Sec-WebSocket-Accept", accept_key); free(accept_key); e = uncurl_write_header(ucc, "101", "Switching Protocols", UNCURL_RESPONSE); if (e != UNCURL_OK) return e; ucc->ws_mask = 0; return UNCURL_OK; } Commit Message: origin matching must come at str end CWE ID: CWE-352
UNCURL_EXPORT int32_t uncurl_ws_accept(struct uncurl_conn *ucc, char **origins, int32_t n_origins) { int32_t e; e = uncurl_read_header(ucc); if (e != UNCURL_OK) return e; uncurl_set_header_str(ucc, "Upgrade", "websocket"); uncurl_set_header_str(ucc, "Connection", "Upgrade"); char *origin = NULL; e = uncurl_get_header_str(ucc, "Origin", &origin); if (e != UNCURL_OK) return e; //the substring MUST came at the end of the origin header, thus a strstr AND a strcmp bool origin_ok = false; for (int32_t x = 0; x < n_origins; x++) { char *match = strstr(origin, origins[x]); if (match && !strcmp(match, origins[x])) {origin_ok = true; break;} } if (!origin_ok) return UNCURL_WS_ERR_ORIGIN; char *sec_key = NULL; e = uncurl_get_header_str(ucc, "Sec-WebSocket-Key", &sec_key); if (e != UNCURL_OK) return e; char *accept_key = ws_create_accept_key(sec_key); uncurl_set_header_str(ucc, "Sec-WebSocket-Accept", accept_key); free(accept_key); e = uncurl_write_header(ucc, "101", "Switching Protocols", UNCURL_RESPONSE); if (e != UNCURL_OK) return e; ucc->ws_mask = 0; return UNCURL_OK; }
169,336
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: xps_load_sfnt_name(xps_font_t *font, char *namep) { byte *namedata; int offset, length; /*int format;*/ int count, stringoffset; int found; int i, k; found = 0; strcpy(namep, "Unknown"); offset = xps_find_sfnt_table(font, "name", &length); if (offset < 0 || length < 6) { gs_warn("cannot find name table"); return; } namedata = font->data + offset; /*format = u16(namedata + 0);*/ count = u16(namedata + 2); stringoffset = u16(namedata + 4); if (length < 6 + (count * 12)) { gs_warn("name table too short"); { if (pid == 1 && eid == 0 && langid == 0) /* mac roman, english */ { if (found < 3) { memcpy(namep, namedata + stringoffset + offset, length); namep[length] = 0; found = 3; } } if (pid == 3 && eid == 1 && langid == 0x409) /* windows unicode ucs-2, US */ { if (found < 2) { unsigned char *s = namedata + stringoffset + offset; int n = length / 2; for (k = 0; k < n; k ++) { int c = u16(s + k * 2); namep[k] = isprint(c) ? c : '?'; } namep[k] = 0; found = 2; } } if (pid == 3 && eid == 10 && langid == 0x409) /* windows unicode ucs-4, US */ { if (found < 1) { unsigned char *s = namedata + stringoffset + offset; int n = length / 4; for (k = 0; k < n; k ++) { int c = u32(s + k * 4); namep[k] = isprint(c) ? c : '?'; } namep[k] = 0; found = 1; } } } } } Commit Message: CWE ID: CWE-125
xps_load_sfnt_name(xps_font_t *font, char *namep) { byte *namedata; int offset, length; /*int format;*/ int count, stringoffset; int found; int i, k; found = 0; strcpy(namep, "Unknown"); offset = xps_find_sfnt_table(font, "name", &length); if (offset < 0 || length < 6) { gs_warn("cannot find name table"); return; } /* validate the offset, and the data for the two * values we're about to read */ if (offset + 6 > font->length) { gs_warn("name table byte offset invalid"); return; } namedata = font->data + offset; /*format = u16(namedata + 0);*/ count = u16(namedata + 2); stringoffset = u16(namedata + 4); if (stringoffset + offset > font->length || offset + 6 + count * 12 > font->length) { gs_warn("name table invalid"); return; } if (length < 6 + (count * 12)) { gs_warn("name table too short"); { if (pid == 1 && eid == 0 && langid == 0) /* mac roman, english */ { if (found < 3) { memcpy(namep, namedata + stringoffset + offset, length); namep[length] = 0; found = 3; } } if (pid == 3 && eid == 1 && langid == 0x409) /* windows unicode ucs-2, US */ { if (found < 2) { unsigned char *s = namedata + stringoffset + offset; int n = length / 2; for (k = 0; k < n; k ++) { int c = u16(s + k * 2); namep[k] = isprint(c) ? c : '?'; } namep[k] = 0; found = 2; } } if (pid == 3 && eid == 10 && langid == 0x409) /* windows unicode ucs-4, US */ { if (found < 1) { unsigned char *s = namedata + stringoffset + offset; int n = length / 4; for (k = 0; k < n; k ++) { int c = u32(s + k * 4); namep[k] = isprint(c) ? c : '?'; } namep[k] = 0; found = 1; } } } } }
164,787
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void NetworkHandler::SetRenderer(RenderProcessHost* process_host, RenderFrameHostImpl* frame_host) { process_ = process_host; host_ = frame_host; } Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable This keeps BrowserContext* and StoragePartition* instead of RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost upon closure of DevTools front-end. Bug: 801117, 783067, 780694 Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b Reviewed-on: https://chromium-review.googlesource.com/876657 Commit-Queue: Andrey Kosyakov <[email protected]> Reviewed-by: Dmitry Gozman <[email protected]> Cr-Commit-Position: refs/heads/master@{#531157} CWE ID: CWE-20
void NetworkHandler::SetRenderer(RenderProcessHost* process_host, void NetworkHandler::SetRenderer(int render_process_host_id, RenderFrameHostImpl* frame_host) { RenderProcessHost* process_host = RenderProcessHost::FromID(render_process_host_id); if (process_host) { storage_partition_ = process_host->GetStoragePartition(); browser_context_ = process_host->GetBrowserContext(); } else { storage_partition_ = nullptr; browser_context_ = nullptr; } host_ = frame_host; }
172,763