prompt
stringlengths
1.19k
236k
output
int64
0
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: OMX_ERRORTYPE omx_venc::set_parameter(OMX_IN OMX_HANDLETYPE hComp, OMX_IN OMX_INDEXTYPE paramIndex, OMX_IN OMX_PTR paramData) { (void)hComp; OMX_ERRORTYPE eRet = OMX_ErrorNone; if (m_state == OMX_StateInvalid) { DEBUG_PRINT_ERROR("ERROR: Set Param in Invalid State"); return OMX_ErrorInvalidState; } if (paramData == NULL) { DEBUG_PRINT_ERROR("ERROR: Get Param in Invalid paramData"); return OMX_ErrorBadParameter; } /*set_parameter can be called in loaded state or disabled port */ if (m_state == OMX_StateLoaded || m_sInPortDef.bEnabled == OMX_FALSE || m_sOutPortDef.bEnabled == OMX_FALSE) { DEBUG_PRINT_LOW("Set Parameter called in valid state"); } else { DEBUG_PRINT_ERROR("ERROR: Set Parameter called in Invalid State"); return OMX_ErrorIncorrectStateOperation; } switch ((int)paramIndex) { case OMX_IndexParamPortDefinition: { OMX_PARAM_PORTDEFINITIONTYPE *portDefn; portDefn = (OMX_PARAM_PORTDEFINITIONTYPE *) paramData; DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamPortDefinition H= %d, W = %d", (int)portDefn->format.video.nFrameHeight, (int)portDefn->format.video.nFrameWidth); if (PORT_INDEX_IN == portDefn->nPortIndex) { if (!dev_is_video_session_supported(portDefn->format.video.nFrameWidth, portDefn->format.video.nFrameHeight)) { DEBUG_PRINT_ERROR("video session not supported"); omx_report_unsupported_setting(); return OMX_ErrorUnsupportedSetting; } DEBUG_PRINT_LOW("i/p actual cnt requested = %u", (unsigned int)portDefn->nBufferCountActual); DEBUG_PRINT_LOW("i/p min cnt requested = %u", (unsigned int)portDefn->nBufferCountMin); DEBUG_PRINT_LOW("i/p buffersize requested = %u", (unsigned int)portDefn->nBufferSize); if (portDefn->nBufferCountMin > portDefn->nBufferCountActual) { DEBUG_PRINT_ERROR("ERROR: (In_PORT) Min buffers (%u) > actual count (%u)", (unsigned int)portDefn->nBufferCountMin, (unsigned int)portDefn->nBufferCountActual); return OMX_ErrorUnsupportedSetting; } if (handle->venc_set_param(paramData,OMX_IndexParamPortDefinition) != true) { DEBUG_PRINT_ERROR("ERROR: venc_set_param input failed"); return handle->hw_overload ? OMX_ErrorInsufficientResources : OMX_ErrorUnsupportedSetting; } DEBUG_PRINT_LOW("i/p previous actual cnt = %u", (unsigned int)m_sInPortDef.nBufferCountActual); DEBUG_PRINT_LOW("i/p previous min cnt = %u", (unsigned int)m_sInPortDef.nBufferCountMin); memcpy(&m_sInPortDef, portDefn,sizeof(OMX_PARAM_PORTDEFINITIONTYPE)); #ifdef _ANDROID_ICS_ if (portDefn->format.video.eColorFormat == (OMX_COLOR_FORMATTYPE)QOMX_COLOR_FormatAndroidOpaque) { m_sInPortDef.format.video.eColorFormat = (OMX_COLOR_FORMATTYPE) QOMX_COLOR_FORMATYUV420PackedSemiPlanar32m; if (!mUseProxyColorFormat) { if (!c2d_conv.init()) { DEBUG_PRINT_ERROR("C2D init failed"); return OMX_ErrorUnsupportedSetting; } DEBUG_PRINT_HIGH("C2D init is successful"); } mUseProxyColorFormat = true; m_input_msg_id = OMX_COMPONENT_GENERATE_ETB_OPQ; } else mUseProxyColorFormat = false; #endif /*Query Input Buffer Requirements*/ dev_get_buf_req (&m_sInPortDef.nBufferCountMin, &m_sInPortDef.nBufferCountActual, &m_sInPortDef.nBufferSize, m_sInPortDef.nPortIndex); /*Query ouput Buffer Requirements*/ dev_get_buf_req (&m_sOutPortDef.nBufferCountMin, &m_sOutPortDef.nBufferCountActual, &m_sOutPortDef.nBufferSize, m_sOutPortDef.nPortIndex); m_sInPortDef.nBufferCountActual = portDefn->nBufferCountActual; } else if (PORT_INDEX_OUT == portDefn->nPortIndex) { DEBUG_PRINT_LOW("o/p actual cnt requested = %u", (unsigned int)portDefn->nBufferCountActual); DEBUG_PRINT_LOW("o/p min cnt requested = %u", (unsigned int)portDefn->nBufferCountMin); DEBUG_PRINT_LOW("o/p buffersize requested = %u", (unsigned int)portDefn->nBufferSize); if (portDefn->nBufferCountMin > portDefn->nBufferCountActual) { DEBUG_PRINT_ERROR("ERROR: (Out_PORT) Min buffers (%u) > actual count (%u)", (unsigned int)portDefn->nBufferCountMin, (unsigned int)portDefn->nBufferCountActual); return OMX_ErrorUnsupportedSetting; } if (handle->venc_set_param(paramData,OMX_IndexParamPortDefinition) != true) { DEBUG_PRINT_ERROR("ERROR: venc_set_param output failed"); return OMX_ErrorUnsupportedSetting; } #ifdef _MSM8974_ /*Query ouput Buffer Requirements*/ dev_get_buf_req(&m_sOutPortDef.nBufferCountMin, &m_sOutPortDef.nBufferCountActual, &m_sOutPortDef.nBufferSize, m_sOutPortDef.nPortIndex); #endif memcpy(&m_sOutPortDef,portDefn,sizeof(struct OMX_PARAM_PORTDEFINITIONTYPE)); update_profile_level(); //framerate , bitrate DEBUG_PRINT_LOW("o/p previous actual cnt = %u", (unsigned int)m_sOutPortDef.nBufferCountActual); DEBUG_PRINT_LOW("o/p previous min cnt = %u", (unsigned int)m_sOutPortDef.nBufferCountMin); m_sOutPortDef.nBufferCountActual = portDefn->nBufferCountActual; } else { DEBUG_PRINT_ERROR("ERROR: Set_parameter: Bad Port idx %d", (int)portDefn->nPortIndex); eRet = OMX_ErrorBadPortIndex; } m_sConfigFramerate.xEncodeFramerate = portDefn->format.video.xFramerate; m_sConfigBitrate.nEncodeBitrate = portDefn->format.video.nBitrate; m_sParamBitrate.nTargetBitrate = portDefn->format.video.nBitrate; } break; case OMX_IndexParamVideoPortFormat: { OMX_VIDEO_PARAM_PORTFORMATTYPE *portFmt = (OMX_VIDEO_PARAM_PORTFORMATTYPE *)paramData; DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamVideoPortFormat %d", portFmt->eColorFormat); if (PORT_INDEX_IN == portFmt->nPortIndex) { if (handle->venc_set_param(paramData,OMX_IndexParamVideoPortFormat) != true) { return OMX_ErrorUnsupportedSetting; } DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamVideoPortFormat %d", portFmt->eColorFormat); update_profile_level(); //framerate #ifdef _ANDROID_ICS_ if (portFmt->eColorFormat == (OMX_COLOR_FORMATTYPE)QOMX_COLOR_FormatAndroidOpaque) { m_sInPortFormat.eColorFormat = (OMX_COLOR_FORMATTYPE) QOMX_COLOR_FORMATYUV420PackedSemiPlanar32m; if (!mUseProxyColorFormat) { if (!c2d_conv.init()) { DEBUG_PRINT_ERROR("C2D init failed"); return OMX_ErrorUnsupportedSetting; } DEBUG_PRINT_HIGH("C2D init is successful"); } mUseProxyColorFormat = true; m_input_msg_id = OMX_COMPONENT_GENERATE_ETB_OPQ; } else #endif { m_sInPortFormat.eColorFormat = portFmt->eColorFormat; m_sInPortDef.format.video.eColorFormat = portFmt->eColorFormat; m_input_msg_id = OMX_COMPONENT_GENERATE_ETB; mUseProxyColorFormat = false; } m_sInPortFormat.xFramerate = portFmt->xFramerate; } } break; case OMX_IndexParamVideoInit: { //TODO, do we need this index set param OMX_PORT_PARAM_TYPE* pParam = (OMX_PORT_PARAM_TYPE*)(paramData); DEBUG_PRINT_LOW("Set OMX_IndexParamVideoInit called"); break; } case OMX_IndexParamVideoBitrate: { OMX_VIDEO_PARAM_BITRATETYPE* pParam = (OMX_VIDEO_PARAM_BITRATETYPE*)paramData; DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamVideoBitrate"); if (handle->venc_set_param(paramData,OMX_IndexParamVideoBitrate) != true) { return OMX_ErrorUnsupportedSetting; } m_sParamBitrate.nTargetBitrate = pParam->nTargetBitrate; m_sParamBitrate.eControlRate = pParam->eControlRate; update_profile_level(); //bitrate m_sConfigBitrate.nEncodeBitrate = pParam->nTargetBitrate; m_sInPortDef.format.video.nBitrate = pParam->nTargetBitrate; m_sOutPortDef.format.video.nBitrate = pParam->nTargetBitrate; DEBUG_PRINT_LOW("bitrate = %u", (unsigned int)m_sOutPortDef.format.video.nBitrate); break; } case OMX_IndexParamVideoMpeg4: { OMX_VIDEO_PARAM_MPEG4TYPE* pParam = (OMX_VIDEO_PARAM_MPEG4TYPE*)paramData; OMX_VIDEO_PARAM_MPEG4TYPE mp4_param; memcpy(&mp4_param, pParam, sizeof(struct OMX_VIDEO_PARAM_MPEG4TYPE)); DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamVideoMpeg4"); if (pParam->eProfile == OMX_VIDEO_MPEG4ProfileAdvancedSimple) { #ifdef MAX_RES_1080P if (pParam->nBFrames) { DEBUG_PRINT_HIGH("INFO: Only 1 Bframe is supported"); mp4_param.nBFrames = 1; } #else if (pParam->nBFrames) { DEBUG_PRINT_ERROR("Warning: B frames not supported"); mp4_param.nBFrames = 0; } #endif #ifdef _MSM8974_ if (pParam->nBFrames || bframes) mp4_param.nBFrames = (pParam->nBFrames > (unsigned int) bframes)? pParam->nBFrames : bframes; DEBUG_PRINT_HIGH("MPEG4: %u BFrames are being set", (unsigned int)mp4_param.nBFrames); #endif } else { if (pParam->nBFrames) { DEBUG_PRINT_ERROR("Warning: B frames not supported"); mp4_param.nBFrames = 0; } } if (handle->venc_set_param(&mp4_param,OMX_IndexParamVideoMpeg4) != true) { return OMX_ErrorUnsupportedSetting; } memcpy(&m_sParamMPEG4,pParam, sizeof(struct OMX_VIDEO_PARAM_MPEG4TYPE)); m_sIntraperiod.nPFrames = m_sParamMPEG4.nPFrames; if (pParam->nBFrames || bframes) m_sIntraperiod.nBFrames = m_sParamMPEG4.nBFrames = mp4_param.nBFrames; else m_sIntraperiod.nBFrames = m_sParamMPEG4.nBFrames; break; } case OMX_IndexParamVideoH263: { OMX_VIDEO_PARAM_H263TYPE* pParam = (OMX_VIDEO_PARAM_H263TYPE*)paramData; DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamVideoH263"); if (handle->venc_set_param(paramData,OMX_IndexParamVideoH263) != true) { return OMX_ErrorUnsupportedSetting; } memcpy(&m_sParamH263,pParam, sizeof(struct OMX_VIDEO_PARAM_H263TYPE)); m_sIntraperiod.nPFrames = m_sParamH263.nPFrames; m_sIntraperiod.nBFrames = m_sParamH263.nBFrames; break; } case OMX_IndexParamVideoAvc: { OMX_VIDEO_PARAM_AVCTYPE* pParam = (OMX_VIDEO_PARAM_AVCTYPE*)paramData; OMX_VIDEO_PARAM_AVCTYPE avc_param; memcpy(&avc_param, pParam, sizeof( struct OMX_VIDEO_PARAM_AVCTYPE)); DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamVideoAvc"); if ((pParam->eProfile == OMX_VIDEO_AVCProfileHigh)|| (pParam->eProfile == OMX_VIDEO_AVCProfileMain)) { #ifdef MAX_RES_1080P if (pParam->nBFrames) { DEBUG_PRINT_HIGH("INFO: Only 1 Bframe is supported"); avc_param.nBFrames = 1; } if (pParam->nRefFrames != 2) { DEBUG_PRINT_ERROR("Warning: 2 RefFrames are needed, changing RefFrames from %u to 2", (unsigned int)pParam->nRefFrames); avc_param.nRefFrames = 2; } #else if (pParam->nBFrames) { DEBUG_PRINT_ERROR("Warning: B frames not supported"); avc_param.nBFrames = 0; } if (pParam->nRefFrames != 1) { DEBUG_PRINT_ERROR("Warning: Only 1 RefFrame is supported, changing RefFrame from %u to 1)", (unsigned int)pParam->nRefFrames); avc_param.nRefFrames = 1; } #endif #ifdef _MSM8974_ if (pParam->nBFrames || bframes) { avc_param.nBFrames = (pParam->nBFrames > (unsigned int) bframes)? pParam->nBFrames : bframes; avc_param.nRefFrames = (avc_param.nBFrames < 4)? avc_param.nBFrames + 1 : 4; } DEBUG_PRINT_HIGH("AVC: RefFrames: %u, BFrames: %u", (unsigned int)avc_param.nRefFrames, (unsigned int)avc_param.nBFrames); avc_param.bEntropyCodingCABAC = (OMX_BOOL)(avc_param.bEntropyCodingCABAC && entropy); avc_param.nCabacInitIdc = entropy ? avc_param.nCabacInitIdc : 0; #endif } else { if (pParam->nRefFrames != 1) { DEBUG_PRINT_ERROR("Warning: Only 1 RefFrame is supported, changing RefFrame from %u to 1)", (unsigned int)pParam->nRefFrames); avc_param.nRefFrames = 1; } if (pParam->nBFrames) { DEBUG_PRINT_ERROR("Warning: B frames not supported"); avc_param.nBFrames = 0; } } if (handle->venc_set_param(&avc_param,OMX_IndexParamVideoAvc) != true) { return OMX_ErrorUnsupportedSetting; } memcpy(&m_sParamAVC,pParam, sizeof(struct OMX_VIDEO_PARAM_AVCTYPE)); m_sIntraperiod.nPFrames = m_sParamAVC.nPFrames; if (pParam->nBFrames || bframes) m_sIntraperiod.nBFrames = m_sParamAVC.nBFrames = avc_param.nBFrames; else m_sIntraperiod.nBFrames = m_sParamAVC.nBFrames; break; } case (OMX_INDEXTYPE)OMX_IndexParamVideoVp8: { OMX_VIDEO_PARAM_VP8TYPE* pParam = (OMX_VIDEO_PARAM_VP8TYPE*)paramData; OMX_VIDEO_PARAM_VP8TYPE vp8_param; DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamVideoVp8"); if (pParam->nDCTPartitions != m_sParamVP8.nDCTPartitions || pParam->bErrorResilientMode != m_sParamVP8.bErrorResilientMode) { DEBUG_PRINT_ERROR("VP8 doesn't support nDCTPartitions or bErrorResilientMode"); } memcpy(&vp8_param, pParam, sizeof( struct OMX_VIDEO_PARAM_VP8TYPE)); if (handle->venc_set_param(&vp8_param, (OMX_INDEXTYPE)OMX_IndexParamVideoVp8) != true) { return OMX_ErrorUnsupportedSetting; } memcpy(&m_sParamVP8,pParam, sizeof(struct OMX_VIDEO_PARAM_VP8TYPE)); break; } case (OMX_INDEXTYPE)OMX_IndexParamVideoHevc: { OMX_VIDEO_PARAM_HEVCTYPE* pParam = (OMX_VIDEO_PARAM_HEVCTYPE*)paramData; OMX_VIDEO_PARAM_HEVCTYPE hevc_param; DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamVideoHevc"); memcpy(&hevc_param, pParam, sizeof( struct OMX_VIDEO_PARAM_HEVCTYPE)); if (handle->venc_set_param(&hevc_param, (OMX_INDEXTYPE)OMX_IndexParamVideoHevc) != true) { DEBUG_PRINT_ERROR("Failed : set_parameter: OMX_IndexParamVideoHevc"); return OMX_ErrorUnsupportedSetting; } memcpy(&m_sParamHEVC, pParam, sizeof(struct OMX_VIDEO_PARAM_HEVCTYPE)); break; } case OMX_IndexParamVideoProfileLevelCurrent: { OMX_VIDEO_PARAM_PROFILELEVELTYPE* pParam = (OMX_VIDEO_PARAM_PROFILELEVELTYPE*)paramData; DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamVideoProfileLevelCurrent"); if (handle->venc_set_param(pParam,OMX_IndexParamVideoProfileLevelCurrent) != true) { DEBUG_PRINT_ERROR("set_parameter: OMX_IndexParamVideoProfileLevelCurrent failed for Profile: %u " "Level :%u", (unsigned int)pParam->eProfile, (unsigned int)pParam->eLevel); return OMX_ErrorUnsupportedSetting; } m_sParamProfileLevel.eProfile = pParam->eProfile; m_sParamProfileLevel.eLevel = pParam->eLevel; if (!strncmp((char *)m_nkind, "OMX.qcom.video.encoder.mpeg4",\ OMX_MAX_STRINGNAME_SIZE)) { m_sParamMPEG4.eProfile = (OMX_VIDEO_MPEG4PROFILETYPE)m_sParamProfileLevel.eProfile; m_sParamMPEG4.eLevel = (OMX_VIDEO_MPEG4LEVELTYPE)m_sParamProfileLevel.eLevel; DEBUG_PRINT_LOW("MPEG4 profile = %d, level = %d", m_sParamMPEG4.eProfile, m_sParamMPEG4.eLevel); } else if (!strncmp((char *)m_nkind, "OMX.qcom.video.encoder.h263",\ OMX_MAX_STRINGNAME_SIZE)) { m_sParamH263.eProfile = (OMX_VIDEO_H263PROFILETYPE)m_sParamProfileLevel.eProfile; m_sParamH263.eLevel = (OMX_VIDEO_H263LEVELTYPE)m_sParamProfileLevel.eLevel; DEBUG_PRINT_LOW("H263 profile = %d, level = %d", m_sParamH263.eProfile, m_sParamH263.eLevel); } else if (!strncmp((char *)m_nkind, "OMX.qcom.video.encoder.avc",\ OMX_MAX_STRINGNAME_SIZE)) { m_sParamAVC.eProfile = (OMX_VIDEO_AVCPROFILETYPE)m_sParamProfileLevel.eProfile; m_sParamAVC.eLevel = (OMX_VIDEO_AVCLEVELTYPE)m_sParamProfileLevel.eLevel; DEBUG_PRINT_LOW("AVC profile = %d, level = %d", m_sParamAVC.eProfile, m_sParamAVC.eLevel); } else if (!strncmp((char *)m_nkind, "OMX.qcom.video.encoder.avc.secure",\ OMX_MAX_STRINGNAME_SIZE)) { m_sParamAVC.eProfile = (OMX_VIDEO_AVCPROFILETYPE)m_sParamProfileLevel.eProfile; m_sParamAVC.eLevel = (OMX_VIDEO_AVCLEVELTYPE)m_sParamProfileLevel.eLevel; DEBUG_PRINT_LOW("\n AVC profile = %d, level = %d", m_sParamAVC.eProfile, m_sParamAVC.eLevel); } else if (!strncmp((char*)m_nkind, "OMX.qcom.video.encoder.vp8",\ OMX_MAX_STRINGNAME_SIZE)) { m_sParamVP8.eProfile = (OMX_VIDEO_VP8PROFILETYPE)m_sParamProfileLevel.eProfile; m_sParamVP8.eLevel = (OMX_VIDEO_VP8LEVELTYPE)m_sParamProfileLevel.eLevel; DEBUG_PRINT_LOW("VP8 profile = %d, level = %d", m_sParamVP8.eProfile, m_sParamVP8.eLevel); } else if (!strncmp((char*)m_nkind, "OMX.qcom.video.encoder.hevc",\ OMX_MAX_STRINGNAME_SIZE)) { m_sParamHEVC.eProfile = (OMX_VIDEO_HEVCPROFILETYPE)m_sParamProfileLevel.eProfile; m_sParamHEVC.eLevel = (OMX_VIDEO_HEVCLEVELTYPE)m_sParamProfileLevel.eLevel; DEBUG_PRINT_LOW("HEVC profile = %d, level = %d", m_sParamHEVC.eProfile, m_sParamHEVC.eLevel); } break; } case OMX_IndexParamStandardComponentRole: { OMX_PARAM_COMPONENTROLETYPE *comp_role; comp_role = (OMX_PARAM_COMPONENTROLETYPE *) paramData; DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamStandardComponentRole %s", comp_role->cRole); if ((m_state == OMX_StateLoaded)&& !BITMASK_PRESENT(&m_flags,OMX_COMPONENT_IDLE_PENDING)) { DEBUG_PRINT_LOW("Set Parameter called in valid state"); } else { DEBUG_PRINT_ERROR("Set Parameter called in Invalid State"); return OMX_ErrorIncorrectStateOperation; } if (!strncmp((char*)m_nkind, "OMX.qcom.video.encoder.avc",OMX_MAX_STRINGNAME_SIZE)) { if (!strncmp((char*)comp_role->cRole,"video_encoder.avc",OMX_MAX_STRINGNAME_SIZE)) { strlcpy((char*)m_cRole,"video_encoder.avc",OMX_MAX_STRINGNAME_SIZE); } else { DEBUG_PRINT_ERROR("ERROR: Setparameter: unknown Index %s", comp_role->cRole); eRet =OMX_ErrorUnsupportedSetting; } } else if (!strncmp((char*)m_nkind, "OMX.qcom.video.encoder.avc.secure",OMX_MAX_STRINGNAME_SIZE)) { if (!strncmp((char*)comp_role->cRole,"video_encoder.avc",OMX_MAX_STRINGNAME_SIZE)) { strlcpy((char*)m_cRole,"video_encoder.avc",OMX_MAX_STRINGNAME_SIZE); } else { DEBUG_PRINT_ERROR("ERROR: Setparameter: unknown Index %s\n", comp_role->cRole); eRet =OMX_ErrorUnsupportedSetting; } } else if (!strncmp((char*)m_nkind, "OMX.qcom.video.encoder.mpeg4",OMX_MAX_STRINGNAME_SIZE)) { if (!strncmp((const char*)comp_role->cRole,"video_encoder.mpeg4",OMX_MAX_STRINGNAME_SIZE)) { strlcpy((char*)m_cRole,"video_encoder.mpeg4",OMX_MAX_STRINGNAME_SIZE); } else { DEBUG_PRINT_ERROR("ERROR: Setparameter: unknown Index %s", comp_role->cRole); eRet = OMX_ErrorUnsupportedSetting; } } else if (!strncmp((char*)m_nkind, "OMX.qcom.video.encoder.h263",OMX_MAX_STRINGNAME_SIZE)) { if (!strncmp((const char*)comp_role->cRole,"video_encoder.h263",OMX_MAX_STRINGNAME_SIZE)) { strlcpy((char*)m_cRole,"video_encoder.h263",OMX_MAX_STRINGNAME_SIZE); } else { DEBUG_PRINT_ERROR("ERROR: Setparameter: unknown Index %s", comp_role->cRole); eRet =OMX_ErrorUnsupportedSetting; } } #ifdef _MSM8974_ else if (!strncmp((char*)m_nkind, "OMX.qcom.video.encoder.vp8",OMX_MAX_STRINGNAME_SIZE)) { if (!strncmp((const char*)comp_role->cRole,"video_encoder.vp8",OMX_MAX_STRINGNAME_SIZE)) { strlcpy((char*)m_cRole,"video_encoder.vp8",OMX_MAX_STRINGNAME_SIZE); } else { DEBUG_PRINT_ERROR("ERROR: Setparameter: unknown Index %s", comp_role->cRole); eRet =OMX_ErrorUnsupportedSetting; } } #endif else if (!strncmp((char*)m_nkind, "OMX.qcom.video.encoder.hevc",OMX_MAX_STRINGNAME_SIZE)) { if (!strncmp((const char*)comp_role->cRole,"video_encoder.hevc",OMX_MAX_STRINGNAME_SIZE)) { strlcpy((char*)m_cRole,"video_encoder.hevc",OMX_MAX_STRINGNAME_SIZE); } else { DEBUG_PRINT_ERROR("ERROR: Setparameter: unknown Index %s", comp_role->cRole); eRet = OMX_ErrorUnsupportedSetting; } } else { DEBUG_PRINT_ERROR("ERROR: Setparameter: unknown param %s", m_nkind); eRet = OMX_ErrorInvalidComponentName; } break; } case OMX_IndexParamPriorityMgmt: { DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamPriorityMgmt"); if (m_state != OMX_StateLoaded) { DEBUG_PRINT_ERROR("ERROR: Set Parameter called in Invalid State"); return OMX_ErrorIncorrectStateOperation; } OMX_PRIORITYMGMTTYPE *priorityMgmtype = (OMX_PRIORITYMGMTTYPE*) paramData; DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamPriorityMgmt %u", (unsigned int)priorityMgmtype->nGroupID); DEBUG_PRINT_LOW("set_parameter: priorityMgmtype %u", (unsigned int)priorityMgmtype->nGroupPriority); m_sPriorityMgmt.nGroupID = priorityMgmtype->nGroupID; m_sPriorityMgmt.nGroupPriority = priorityMgmtype->nGroupPriority; break; } case OMX_IndexParamCompBufferSupplier: { DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamCompBufferSupplier"); OMX_PARAM_BUFFERSUPPLIERTYPE *bufferSupplierType = (OMX_PARAM_BUFFERSUPPLIERTYPE*) paramData; DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamCompBufferSupplier %d", bufferSupplierType->eBufferSupplier); if (bufferSupplierType->nPortIndex == 0 || bufferSupplierType->nPortIndex ==1) m_sInBufSupplier.eBufferSupplier = bufferSupplierType->eBufferSupplier; else eRet = OMX_ErrorBadPortIndex; break; } case OMX_IndexParamVideoQuantization: { DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamVideoQuantization"); OMX_VIDEO_PARAM_QUANTIZATIONTYPE *session_qp = (OMX_VIDEO_PARAM_QUANTIZATIONTYPE*) paramData; if (session_qp->nPortIndex == PORT_INDEX_OUT) { if (handle->venc_set_param(paramData, OMX_IndexParamVideoQuantization) != true) { return OMX_ErrorUnsupportedSetting; } m_sSessionQuantization.nQpI = session_qp->nQpI; m_sSessionQuantization.nQpP = session_qp->nQpP; m_sSessionQuantization.nQpB = session_qp->nQpB; } else { DEBUG_PRINT_ERROR("ERROR: Unsupported port Index for Session QP setting"); eRet = OMX_ErrorBadPortIndex; } break; } case OMX_QcomIndexParamVideoQPRange: { DEBUG_PRINT_LOW("set_parameter: OMX_QcomIndexParamVideoQPRange"); OMX_QCOM_VIDEO_PARAM_QPRANGETYPE *qp_range = (OMX_QCOM_VIDEO_PARAM_QPRANGETYPE*) paramData; if (qp_range->nPortIndex == PORT_INDEX_OUT) { if (handle->venc_set_param(paramData, (OMX_INDEXTYPE)OMX_QcomIndexParamVideoQPRange) != true) { return OMX_ErrorUnsupportedSetting; } m_sSessionQPRange.minQP= qp_range->minQP; m_sSessionQPRange.maxQP= qp_range->maxQP; } else { DEBUG_PRINT_ERROR("ERROR: Unsupported port Index for QP range setting"); eRet = OMX_ErrorBadPortIndex; } break; } case OMX_QcomIndexPortDefn: { OMX_QCOM_PARAM_PORTDEFINITIONTYPE* pParam = (OMX_QCOM_PARAM_PORTDEFINITIONTYPE*)paramData; DEBUG_PRINT_LOW("set_parameter: OMX_QcomIndexPortDefn"); if (pParam->nPortIndex == (OMX_U32)PORT_INDEX_IN) { if (pParam->nMemRegion > OMX_QCOM_MemRegionInvalid && pParam->nMemRegion < OMX_QCOM_MemRegionMax) { m_use_input_pmem = OMX_TRUE; } else { m_use_input_pmem = OMX_FALSE; } } else if (pParam->nPortIndex == (OMX_U32)PORT_INDEX_OUT) { if (pParam->nMemRegion > OMX_QCOM_MemRegionInvalid && pParam->nMemRegion < OMX_QCOM_MemRegionMax) { m_use_output_pmem = OMX_TRUE; } else { m_use_output_pmem = OMX_FALSE; } } else { DEBUG_PRINT_ERROR("ERROR: SetParameter called on unsupported Port Index for QcomPortDefn"); return OMX_ErrorBadPortIndex; } break; } case OMX_IndexParamVideoErrorCorrection: { DEBUG_PRINT_LOW("OMX_IndexParamVideoErrorCorrection"); OMX_VIDEO_PARAM_ERRORCORRECTIONTYPE* pParam = (OMX_VIDEO_PARAM_ERRORCORRECTIONTYPE*)paramData; if (!handle->venc_set_param(paramData, OMX_IndexParamVideoErrorCorrection)) { DEBUG_PRINT_ERROR("ERROR: Request for setting Error Resilience failed"); return OMX_ErrorUnsupportedSetting; } memcpy(&m_sErrorCorrection,pParam, sizeof(m_sErrorCorrection)); break; } case OMX_IndexParamVideoIntraRefresh: { DEBUG_PRINT_LOW("set_param:OMX_IndexParamVideoIntraRefresh"); OMX_VIDEO_PARAM_INTRAREFRESHTYPE* pParam = (OMX_VIDEO_PARAM_INTRAREFRESHTYPE*)paramData; if (!handle->venc_set_param(paramData,OMX_IndexParamVideoIntraRefresh)) { DEBUG_PRINT_ERROR("ERROR: Request for setting intra refresh failed"); return OMX_ErrorUnsupportedSetting; } memcpy(&m_sIntraRefresh, pParam, sizeof(m_sIntraRefresh)); break; } #ifdef _ANDROID_ICS_ case OMX_QcomIndexParamVideoMetaBufferMode: { StoreMetaDataInBuffersParams *pParam = (StoreMetaDataInBuffersParams*)paramData; DEBUG_PRINT_HIGH("set_parameter:OMX_QcomIndexParamVideoMetaBufferMode: " "port_index = %u, meta_mode = %d", (unsigned int)pParam->nPortIndex, pParam->bStoreMetaData); if (pParam->nPortIndex == PORT_INDEX_IN) { if (pParam->bStoreMetaData != meta_mode_enable) { if (!handle->venc_set_meta_mode(pParam->bStoreMetaData)) { DEBUG_PRINT_ERROR("ERROR: set Metabuffer mode %d fail", pParam->bStoreMetaData); return OMX_ErrorUnsupportedSetting; } meta_mode_enable = pParam->bStoreMetaData; if (meta_mode_enable) { m_sInPortDef.nBufferCountActual = m_sInPortDef.nBufferCountMin; if (handle->venc_set_param(&m_sInPortDef,OMX_IndexParamPortDefinition) != true) { DEBUG_PRINT_ERROR("ERROR: venc_set_param input failed"); return OMX_ErrorUnsupportedSetting; } } else { /*TODO: reset encoder driver Meta mode*/ dev_get_buf_req (&m_sOutPortDef.nBufferCountMin, &m_sOutPortDef.nBufferCountActual, &m_sOutPortDef.nBufferSize, m_sOutPortDef.nPortIndex); } } } else if (pParam->nPortIndex == PORT_INDEX_OUT && secure_session) { if (pParam->bStoreMetaData != meta_mode_enable) { if (!handle->venc_set_meta_mode(pParam->bStoreMetaData)) { DEBUG_PRINT_ERROR("\nERROR: set Metabuffer mode %d fail", pParam->bStoreMetaData); return OMX_ErrorUnsupportedSetting; } meta_mode_enable = pParam->bStoreMetaData; } } else { DEBUG_PRINT_ERROR("set_parameter: metamode is " "valid for input port only"); eRet = OMX_ErrorUnsupportedIndex; } } break; #endif #if !defined(MAX_RES_720P) || defined(_MSM8974_) case OMX_QcomIndexParamIndexExtraDataType: { DEBUG_PRINT_HIGH("set_parameter: OMX_QcomIndexParamIndexExtraDataType"); QOMX_INDEXEXTRADATATYPE *pParam = (QOMX_INDEXEXTRADATATYPE *)paramData; bool enable = false; OMX_U32 mask = 0; if (pParam->nIndex == (OMX_INDEXTYPE)OMX_ExtraDataVideoEncoderSliceInfo) { if (pParam->nPortIndex == PORT_INDEX_OUT) { mask = VEN_EXTRADATA_SLICEINFO; DEBUG_PRINT_HIGH("SliceInfo extradata %s", ((pParam->bEnabled == OMX_TRUE) ? "enabled" : "disabled")); } else { DEBUG_PRINT_ERROR("set_parameter: Slice information is " "valid for output port only"); eRet = OMX_ErrorUnsupportedIndex; break; } } else if (pParam->nIndex == (OMX_INDEXTYPE)OMX_ExtraDataVideoEncoderMBInfo) { if (pParam->nPortIndex == PORT_INDEX_OUT) { mask = VEN_EXTRADATA_MBINFO; DEBUG_PRINT_HIGH("MBInfo extradata %s", ((pParam->bEnabled == OMX_TRUE) ? "enabled" : "disabled")); } else { DEBUG_PRINT_ERROR("set_parameter: MB information is " "valid for output port only"); eRet = OMX_ErrorUnsupportedIndex; break; } } #ifndef _MSM8974_ else if (pParam->nIndex == (OMX_INDEXTYPE)OMX_ExtraDataVideoLTRInfo) { if (pParam->nPortIndex == PORT_INDEX_OUT) { if (pParam->bEnabled == OMX_TRUE) mask = VEN_EXTRADATA_LTRINFO; DEBUG_PRINT_HIGH("LTRInfo extradata %s", ((pParam->bEnabled == OMX_TRUE) ? "enabled" : "disabled")); } else { DEBUG_PRINT_ERROR("set_parameter: LTR information is " "valid for output port only"); eRet = OMX_ErrorUnsupportedIndex; break; } } #endif else { DEBUG_PRINT_ERROR("set_parameter: unsupported extrdata index (%x)", pParam->nIndex); eRet = OMX_ErrorUnsupportedIndex; break; } if (pParam->bEnabled == OMX_TRUE) m_sExtraData |= mask; else m_sExtraData &= ~mask; enable = !!(m_sExtraData & mask); if (handle->venc_set_param(&enable, (OMX_INDEXTYPE)pParam->nIndex) != true) { DEBUG_PRINT_ERROR("ERROR: Setting Extradata (%x) failed", pParam->nIndex); return OMX_ErrorUnsupportedSetting; } else { m_sOutPortDef.nPortIndex = PORT_INDEX_OUT; dev_get_buf_req(&m_sOutPortDef.nBufferCountMin, &m_sOutPortDef.nBufferCountActual, &m_sOutPortDef.nBufferSize, m_sOutPortDef.nPortIndex); DEBUG_PRINT_HIGH("updated out_buf_req: buffer cnt=%u, " "count min=%u, buffer size=%u", (unsigned int)m_sOutPortDef.nBufferCountActual, (unsigned int)m_sOutPortDef.nBufferCountMin, (unsigned int)m_sOutPortDef.nBufferSize); } break; } case QOMX_IndexParamVideoLTRMode: { QOMX_VIDEO_PARAM_LTRMODE_TYPE* pParam = (QOMX_VIDEO_PARAM_LTRMODE_TYPE*)paramData; if (!handle->venc_set_param(paramData, (OMX_INDEXTYPE)QOMX_IndexParamVideoLTRMode)) { DEBUG_PRINT_ERROR("ERROR: Setting LTR mode failed"); return OMX_ErrorUnsupportedSetting; } memcpy(&m_sParamLTRMode, pParam, sizeof(m_sParamLTRMode)); break; } case QOMX_IndexParamVideoLTRCount: { QOMX_VIDEO_PARAM_LTRCOUNT_TYPE* pParam = (QOMX_VIDEO_PARAM_LTRCOUNT_TYPE*)paramData; if (!handle->venc_set_param(paramData, (OMX_INDEXTYPE)QOMX_IndexParamVideoLTRCount)) { DEBUG_PRINT_ERROR("ERROR: Setting LTR count failed"); return OMX_ErrorUnsupportedSetting; } memcpy(&m_sParamLTRCount, pParam, sizeof(m_sParamLTRCount)); break; } #endif case OMX_QcomIndexParamVideoMaxAllowedBitrateCheck: { QOMX_EXTNINDEX_PARAMTYPE* pParam = (QOMX_EXTNINDEX_PARAMTYPE*)paramData; if (pParam->nPortIndex == PORT_INDEX_OUT) { handle->m_max_allowed_bitrate_check = ((pParam->bEnable == OMX_TRUE) ? true : false); DEBUG_PRINT_HIGH("set_parameter: max allowed bitrate check %s", ((pParam->bEnable == OMX_TRUE) ? "enabled" : "disabled")); } else { DEBUG_PRINT_ERROR("ERROR: OMX_QcomIndexParamVideoMaxAllowedBitrateCheck " " called on wrong port(%u)", (unsigned int)pParam->nPortIndex); return OMX_ErrorBadPortIndex; } break; } #ifdef MAX_RES_1080P case OMX_QcomIndexEnableSliceDeliveryMode: { QOMX_EXTNINDEX_PARAMTYPE* pParam = (QOMX_EXTNINDEX_PARAMTYPE*)paramData; if (pParam->nPortIndex == PORT_INDEX_OUT) { if (!handle->venc_set_param(paramData, (OMX_INDEXTYPE)OMX_QcomIndexEnableSliceDeliveryMode)) { DEBUG_PRINT_ERROR("ERROR: Request for setting slice delivery mode failed"); return OMX_ErrorUnsupportedSetting; } } else { DEBUG_PRINT_ERROR("ERROR: OMX_QcomIndexEnableSliceDeliveryMode " "called on wrong port(%u)", (unsigned int)pParam->nPortIndex); return OMX_ErrorBadPortIndex; } break; } #endif case OMX_QcomIndexEnableH263PlusPType: { QOMX_EXTNINDEX_PARAMTYPE* pParam = (QOMX_EXTNINDEX_PARAMTYPE*)paramData; DEBUG_PRINT_LOW("OMX_QcomIndexEnableH263PlusPType"); if (pParam->nPortIndex == PORT_INDEX_OUT) { if (!handle->venc_set_param(paramData, (OMX_INDEXTYPE)OMX_QcomIndexEnableH263PlusPType)) { DEBUG_PRINT_ERROR("ERROR: Request for setting PlusPType failed"); return OMX_ErrorUnsupportedSetting; } } else { DEBUG_PRINT_ERROR("ERROR: OMX_QcomIndexEnableH263PlusPType " "called on wrong port(%u)", (unsigned int)pParam->nPortIndex); return OMX_ErrorBadPortIndex; } break; } case OMX_QcomIndexParamSequenceHeaderWithIDR: { if(!handle->venc_set_param(paramData, (OMX_INDEXTYPE)OMX_QcomIndexParamSequenceHeaderWithIDR)) { DEBUG_PRINT_ERROR("%s: %s", "OMX_QComIndexParamSequenceHeaderWithIDR:", "request for inband sps/pps failed."); return OMX_ErrorUnsupportedSetting; } break; } case OMX_QcomIndexParamH264AUDelimiter: { if(!handle->venc_set_param(paramData, (OMX_INDEXTYPE)OMX_QcomIndexParamH264AUDelimiter)) { DEBUG_PRINT_ERROR("%s: %s", "OMX_QComIndexParamh264AUDelimiter:", "request for AU Delimiters failed."); return OMX_ErrorUnsupportedSetting; } break; } case OMX_QcomIndexHierarchicalStructure: { QOMX_VIDEO_HIERARCHICALLAYERS* pParam = (QOMX_VIDEO_HIERARCHICALLAYERS*)paramData; DEBUG_PRINT_LOW("OMX_QcomIndexHierarchicalStructure"); if (pParam->nPortIndex == PORT_INDEX_OUT) { if (!handle->venc_set_param(paramData, (OMX_INDEXTYPE)OMX_QcomIndexHierarchicalStructure)) { DEBUG_PRINT_ERROR("ERROR: Request for setting PlusPType failed"); return OMX_ErrorUnsupportedSetting; } if((pParam->eHierarchicalCodingType == QOMX_HIERARCHICALCODING_B) && pParam->nNumLayers) hier_b_enabled = true; m_sHierLayers.nNumLayers = pParam->nNumLayers; m_sHierLayers.eHierarchicalCodingType = pParam->eHierarchicalCodingType; } else { DEBUG_PRINT_ERROR("ERROR: OMX_QcomIndexHierarchicalStructure called on wrong port(%u)", (unsigned int)pParam->nPortIndex); return OMX_ErrorBadPortIndex; } break; } case OMX_QcomIndexParamPerfLevel: { if (!handle->venc_set_param(paramData, (OMX_INDEXTYPE) OMX_QcomIndexParamPerfLevel)) { DEBUG_PRINT_ERROR("ERROR: Setting performance level"); return OMX_ErrorUnsupportedSetting; } break; } case OMX_QcomIndexParamH264VUITimingInfo: { if (!handle->venc_set_param(paramData, (OMX_INDEXTYPE) OMX_QcomIndexParamH264VUITimingInfo)) { DEBUG_PRINT_ERROR("ERROR: Setting VUI timing info"); return OMX_ErrorUnsupportedSetting; } break; } case OMX_QcomIndexParamPeakBitrate: { if (!handle->venc_set_param(paramData, (OMX_INDEXTYPE) OMX_QcomIndexParamPeakBitrate)) { DEBUG_PRINT_ERROR("ERROR: Setting peak bitrate"); return OMX_ErrorUnsupportedSetting; } break; } case QOMX_IndexParamVideoInitialQp: { if(!handle->venc_set_param(paramData, (OMX_INDEXTYPE)QOMX_IndexParamVideoInitialQp)) { DEBUG_PRINT_ERROR("Request to Enable initial QP failed"); return OMX_ErrorUnsupportedSetting; } memcpy(&m_sParamInitqp, paramData, sizeof(m_sParamInitqp)); break; } case OMX_QcomIndexParamSetMVSearchrange: { if (!handle->venc_set_param(paramData, (OMX_INDEXTYPE) OMX_QcomIndexParamSetMVSearchrange)) { DEBUG_PRINT_ERROR("ERROR: Setting Searchrange"); return OMX_ErrorUnsupportedSetting; } break; } case OMX_QcomIndexParamVideoHybridHierpMode: { if(!handle->venc_set_param(paramData, (OMX_INDEXTYPE)OMX_QcomIndexParamVideoHybridHierpMode)) { DEBUG_PRINT_ERROR("Request to Enable Hybrid Hier-P failed"); return OMX_ErrorUnsupportedSetting; } break; } case OMX_IndexParamVideoSliceFMO: default: { DEBUG_PRINT_ERROR("ERROR: Setparameter: unknown param %d", paramIndex); eRet = OMX_ErrorUnsupportedIndex; break; } } return eRet; } Commit Message: DO NOT MERGE mm-video-v4l2: vidc: validate omx param/config data Check the sanity of config/param strcuture objects passed to get/set _ config()/parameter() methods. Bug: 27533317 Security Vulnerability in MediaServer omx_vdec::get_config() Can lead to arbitrary write Change-Id: I6c3243afe12055ab94f1a1ecf758c10e88231809 Conflicts: mm-core/inc/OMX_QCOMExtns.h mm-video-v4l2/vidc/vdec/src/omx_vdec_msm8974.cpp mm-video-v4l2/vidc/venc/src/omx_video_base.cpp mm-video-v4l2/vidc/venc/src/omx_video_encoder.cpp CWE ID: CWE-20 Target: 1 Example 2: Code: ExtensionInstallDialogView::~ExtensionInstallDialogView() { if (!handled_result_ && !done_callback_.is_null()) { base::ResetAndReturn(&done_callback_) .Run(ExtensionInstallPrompt::Result::USER_CANCELED); } } Commit Message: [Extensions UI] Initially disabled OK button for extension install prompts and enable them after a 500 ms time period. BUG=394518 Review-Url: https://codereview.chromium.org/2716353003 Cr-Commit-Position: refs/heads/master@{#461933} CWE ID: CWE-20 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static struct kvm *kvm_create_vm(unsigned long type) { int r, i; struct kvm *kvm = kvm_arch_alloc_vm(); if (!kvm) return ERR_PTR(-ENOMEM); r = kvm_arch_init_vm(kvm, type); if (r) goto out_err_nodisable; r = hardware_enable_all(); if (r) goto out_err_nodisable; #ifdef CONFIG_HAVE_KVM_IRQCHIP INIT_HLIST_HEAD(&kvm->mask_notifier_list); INIT_HLIST_HEAD(&kvm->irq_ack_notifier_list); #endif r = -ENOMEM; kvm->memslots = kzalloc(sizeof(struct kvm_memslots), GFP_KERNEL); if (!kvm->memslots) goto out_err_nosrcu; kvm_init_memslots_id(kvm); if (init_srcu_struct(&kvm->srcu)) goto out_err_nosrcu; for (i = 0; i < KVM_NR_BUSES; i++) { kvm->buses[i] = kzalloc(sizeof(struct kvm_io_bus), GFP_KERNEL); if (!kvm->buses[i]) goto out_err; } spin_lock_init(&kvm->mmu_lock); kvm->mm = current->mm; atomic_inc(&kvm->mm->mm_count); kvm_eventfd_init(kvm); mutex_init(&kvm->lock); mutex_init(&kvm->irq_lock); mutex_init(&kvm->slots_lock); atomic_set(&kvm->users_count, 1); r = kvm_init_mmu_notifier(kvm); if (r) goto out_err; raw_spin_lock(&kvm_lock); list_add(&kvm->vm_list, &vm_list); raw_spin_unlock(&kvm_lock); return kvm; out_err: cleanup_srcu_struct(&kvm->srcu); out_err_nosrcu: hardware_disable_all(); out_err_nodisable: for (i = 0; i < KVM_NR_BUSES; i++) kfree(kvm->buses[i]); kfree(kvm->memslots); kvm_arch_free_vm(kvm); return ERR_PTR(r); } Commit Message: KVM: perform an invalid memslot step for gpa base change PPC must flush all translations before the new memory slot is visible. Signed-off-by: Marcelo Tosatti <[email protected]> Signed-off-by: Avi Kivity <[email protected]> CWE ID: CWE-399 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: icmp_print(netdissect_options *ndo, const u_char *bp, u_int plen, const u_char *bp2, int fragmented) { char *cp; const struct icmp *dp; const struct icmp_ext_t *ext_dp; const struct ip *ip; const char *str, *fmt; const struct ip *oip; const struct udphdr *ouh; const uint8_t *obj_tptr; uint32_t raw_label; const u_char *snapend_save; const struct icmp_mpls_ext_object_header_t *icmp_mpls_ext_object_header; u_int hlen, dport, mtu, obj_tlen, obj_class_num, obj_ctype; char buf[MAXHOSTNAMELEN + 100]; struct cksum_vec vec[1]; dp = (const struct icmp *)bp; ext_dp = (const struct icmp_ext_t *)bp; ip = (const struct ip *)bp2; str = buf; ND_TCHECK(dp->icmp_code); switch (dp->icmp_type) { case ICMP_ECHO: case ICMP_ECHOREPLY: ND_TCHECK(dp->icmp_seq); (void)snprintf(buf, sizeof(buf), "echo %s, id %u, seq %u", dp->icmp_type == ICMP_ECHO ? "request" : "reply", EXTRACT_16BITS(&dp->icmp_id), EXTRACT_16BITS(&dp->icmp_seq)); break; case ICMP_UNREACH: ND_TCHECK(dp->icmp_ip.ip_dst); switch (dp->icmp_code) { case ICMP_UNREACH_PROTOCOL: ND_TCHECK(dp->icmp_ip.ip_p); (void)snprintf(buf, sizeof(buf), "%s protocol %d unreachable", ipaddr_string(ndo, &dp->icmp_ip.ip_dst), dp->icmp_ip.ip_p); break; case ICMP_UNREACH_PORT: ND_TCHECK(dp->icmp_ip.ip_p); oip = &dp->icmp_ip; hlen = IP_HL(oip) * 4; ouh = (const struct udphdr *)(((const u_char *)oip) + hlen); ND_TCHECK(ouh->uh_dport); dport = EXTRACT_16BITS(&ouh->uh_dport); switch (oip->ip_p) { case IPPROTO_TCP: (void)snprintf(buf, sizeof(buf), "%s tcp port %s unreachable", ipaddr_string(ndo, &oip->ip_dst), tcpport_string(ndo, dport)); break; case IPPROTO_UDP: (void)snprintf(buf, sizeof(buf), "%s udp port %s unreachable", ipaddr_string(ndo, &oip->ip_dst), udpport_string(ndo, dport)); break; default: (void)snprintf(buf, sizeof(buf), "%s protocol %d port %d unreachable", ipaddr_string(ndo, &oip->ip_dst), oip->ip_p, dport); break; } break; case ICMP_UNREACH_NEEDFRAG: { register const struct mtu_discovery *mp; mp = (const struct mtu_discovery *)(const u_char *)&dp->icmp_void; mtu = EXTRACT_16BITS(&mp->nexthopmtu); if (mtu) { (void)snprintf(buf, sizeof(buf), "%s unreachable - need to frag (mtu %d)", ipaddr_string(ndo, &dp->icmp_ip.ip_dst), mtu); } else { (void)snprintf(buf, sizeof(buf), "%s unreachable - need to frag", ipaddr_string(ndo, &dp->icmp_ip.ip_dst)); } } break; default: fmt = tok2str(unreach2str, "#%d %%s unreachable", dp->icmp_code); (void)snprintf(buf, sizeof(buf), fmt, ipaddr_string(ndo, &dp->icmp_ip.ip_dst)); break; } break; case ICMP_REDIRECT: ND_TCHECK(dp->icmp_ip.ip_dst); fmt = tok2str(type2str, "redirect-#%d %%s to net %%s", dp->icmp_code); (void)snprintf(buf, sizeof(buf), fmt, ipaddr_string(ndo, &dp->icmp_ip.ip_dst), ipaddr_string(ndo, &dp->icmp_gwaddr)); break; case ICMP_ROUTERADVERT: { register const struct ih_rdiscovery *ihp; register const struct id_rdiscovery *idp; u_int lifetime, num, size; (void)snprintf(buf, sizeof(buf), "router advertisement"); cp = buf + strlen(buf); ihp = (const struct ih_rdiscovery *)&dp->icmp_void; ND_TCHECK(*ihp); (void)strncpy(cp, " lifetime ", sizeof(buf) - (cp - buf)); cp = buf + strlen(buf); lifetime = EXTRACT_16BITS(&ihp->ird_lifetime); if (lifetime < 60) { (void)snprintf(cp, sizeof(buf) - (cp - buf), "%u", lifetime); } else if (lifetime < 60 * 60) { (void)snprintf(cp, sizeof(buf) - (cp - buf), "%u:%02u", lifetime / 60, lifetime % 60); } else { (void)snprintf(cp, sizeof(buf) - (cp - buf), "%u:%02u:%02u", lifetime / 3600, (lifetime % 3600) / 60, lifetime % 60); } cp = buf + strlen(buf); num = ihp->ird_addrnum; (void)snprintf(cp, sizeof(buf) - (cp - buf), " %d:", num); cp = buf + strlen(buf); size = ihp->ird_addrsiz; if (size != 2) { (void)snprintf(cp, sizeof(buf) - (cp - buf), " [size %d]", size); break; } idp = (const struct id_rdiscovery *)&dp->icmp_data; while (num-- > 0) { ND_TCHECK(*idp); (void)snprintf(cp, sizeof(buf) - (cp - buf), " {%s %u}", ipaddr_string(ndo, &idp->ird_addr), EXTRACT_32BITS(&idp->ird_pref)); cp = buf + strlen(buf); ++idp; } } break; case ICMP_TIMXCEED: ND_TCHECK(dp->icmp_ip.ip_dst); switch (dp->icmp_code) { case ICMP_TIMXCEED_INTRANS: str = "time exceeded in-transit"; break; case ICMP_TIMXCEED_REASS: str = "ip reassembly time exceeded"; break; default: (void)snprintf(buf, sizeof(buf), "time exceeded-#%d", dp->icmp_code); break; } break; case ICMP_PARAMPROB: if (dp->icmp_code) (void)snprintf(buf, sizeof(buf), "parameter problem - code %d", dp->icmp_code); else { ND_TCHECK(dp->icmp_pptr); (void)snprintf(buf, sizeof(buf), "parameter problem - octet %d", dp->icmp_pptr); } break; case ICMP_MASKREPLY: ND_TCHECK(dp->icmp_mask); (void)snprintf(buf, sizeof(buf), "address mask is 0x%08x", EXTRACT_32BITS(&dp->icmp_mask)); break; case ICMP_TSTAMP: ND_TCHECK(dp->icmp_seq); (void)snprintf(buf, sizeof(buf), "time stamp query id %u seq %u", EXTRACT_16BITS(&dp->icmp_id), EXTRACT_16BITS(&dp->icmp_seq)); break; case ICMP_TSTAMPREPLY: ND_TCHECK(dp->icmp_ttime); (void)snprintf(buf, sizeof(buf), "time stamp reply id %u seq %u: org %s", EXTRACT_16BITS(&dp->icmp_id), EXTRACT_16BITS(&dp->icmp_seq), icmp_tstamp_print(EXTRACT_32BITS(&dp->icmp_otime))); (void)snprintf(buf+strlen(buf),sizeof(buf)-strlen(buf),", recv %s", icmp_tstamp_print(EXTRACT_32BITS(&dp->icmp_rtime))); (void)snprintf(buf+strlen(buf),sizeof(buf)-strlen(buf),", xmit %s", icmp_tstamp_print(EXTRACT_32BITS(&dp->icmp_ttime))); break; default: str = tok2str(icmp2str, "type-#%d", dp->icmp_type); break; } ND_PRINT((ndo, "ICMP %s, length %u", str, plen)); if (ndo->ndo_vflag && !fragmented) { /* don't attempt checksumming if this is a frag */ uint16_t sum, icmp_sum; if (ND_TTEST2(*bp, plen)) { vec[0].ptr = (const uint8_t *)(const void *)dp; vec[0].len = plen; sum = in_cksum(vec, 1); if (sum != 0) { icmp_sum = EXTRACT_16BITS(&dp->icmp_cksum); ND_PRINT((ndo, " (wrong icmp cksum %x (->%x)!)", icmp_sum, in_cksum_shouldbe(icmp_sum, sum))); } } } /* * print the remnants of the IP packet. * save the snaplength as this may get overidden in the IP printer. */ if (ndo->ndo_vflag >= 1 && ICMP_ERRTYPE(dp->icmp_type)) { bp += 8; ND_PRINT((ndo, "\n\t")); ip = (const struct ip *)bp; snapend_save = ndo->ndo_snapend; ip_print(ndo, bp, EXTRACT_16BITS(&ip->ip_len)); ndo->ndo_snapend = snapend_save; } /* * Attempt to decode the MPLS extensions only for some ICMP types. */ if (ndo->ndo_vflag >= 1 && plen > ICMP_EXTD_MINLEN && ICMP_MPLS_EXT_TYPE(dp->icmp_type)) { ND_TCHECK(*ext_dp); /* * Check first if the mpls extension header shows a non-zero length. * If the length field is not set then silently verify the checksum * to check if an extension header is present. This is expedient, * however not all implementations set the length field proper. */ if (!ext_dp->icmp_length && ND_TTEST2(ext_dp->icmp_ext_version_res, plen - ICMP_EXTD_MINLEN)) { vec[0].ptr = (const uint8_t *)(const void *)&ext_dp->icmp_ext_version_res; vec[0].len = plen - ICMP_EXTD_MINLEN; if (in_cksum(vec, 1)) { return; } } ND_PRINT((ndo, "\n\tMPLS extension v%u", ICMP_MPLS_EXT_EXTRACT_VERSION(*(ext_dp->icmp_ext_version_res)))); /* * Sanity checking of the header. */ if (ICMP_MPLS_EXT_EXTRACT_VERSION(*(ext_dp->icmp_ext_version_res)) != ICMP_MPLS_EXT_VERSION) { ND_PRINT((ndo, " packet not supported")); return; } hlen = plen - ICMP_EXTD_MINLEN; if (ND_TTEST2(ext_dp->icmp_ext_version_res, hlen)) { vec[0].ptr = (const uint8_t *)(const void *)&ext_dp->icmp_ext_version_res; vec[0].len = hlen; ND_PRINT((ndo, ", checksum 0x%04x (%scorrect), length %u", EXTRACT_16BITS(ext_dp->icmp_ext_checksum), in_cksum(vec, 1) ? "in" : "", hlen)); } hlen -= 4; /* subtract common header size */ obj_tptr = (const uint8_t *)ext_dp->icmp_ext_data; while (hlen > sizeof(struct icmp_mpls_ext_object_header_t)) { icmp_mpls_ext_object_header = (const struct icmp_mpls_ext_object_header_t *)obj_tptr; ND_TCHECK(*icmp_mpls_ext_object_header); obj_tlen = EXTRACT_16BITS(icmp_mpls_ext_object_header->length); obj_class_num = icmp_mpls_ext_object_header->class_num; obj_ctype = icmp_mpls_ext_object_header->ctype; obj_tptr += sizeof(struct icmp_mpls_ext_object_header_t); ND_PRINT((ndo, "\n\t %s Object (%u), Class-Type: %u, length %u", tok2str(icmp_mpls_ext_obj_values,"unknown",obj_class_num), obj_class_num, obj_ctype, obj_tlen)); hlen-=sizeof(struct icmp_mpls_ext_object_header_t); /* length field includes tlv header */ /* infinite loop protection */ if ((obj_class_num == 0) || (obj_tlen < sizeof(struct icmp_mpls_ext_object_header_t))) { return; } obj_tlen-=sizeof(struct icmp_mpls_ext_object_header_t); switch (obj_class_num) { case 1: switch(obj_ctype) { case 1: ND_TCHECK2(*obj_tptr, 4); raw_label = EXTRACT_32BITS(obj_tptr); ND_PRINT((ndo, "\n\t label %u, exp %u", MPLS_LABEL(raw_label), MPLS_EXP(raw_label))); if (MPLS_STACK(raw_label)) ND_PRINT((ndo, ", [S]")); ND_PRINT((ndo, ", ttl %u", MPLS_TTL(raw_label))); break; default: print_unknown_data(ndo, obj_tptr, "\n\t ", obj_tlen); } break; /* * FIXME those are the defined objects that lack a decoder * you are welcome to contribute code ;-) */ case 2: default: print_unknown_data(ndo, obj_tptr, "\n\t ", obj_tlen); break; } if (hlen < obj_tlen) break; hlen -= obj_tlen; obj_tptr += obj_tlen; } } return; trunc: ND_PRINT((ndo, "[|icmp]")); } Commit Message: CVE-2017-13012/ICMP: Add a missing bounds check. Check before fetching the length from the included packet's IPv4 header. This fixes a buffer over-read discovered by Bhargava Shastry, SecT/TU Berlin. Add a test using the capture file supplied by the reporter(s), modified so the capture file won't be rejected as an invalid capture. CWE ID: CWE-125 Target: 1 Example 2: Code: static int read_reset_stat(struct ctl_table *table, int write, void __user *buffer, size_t *lenp, loff_t *ppos) { atomic_t *stat = (atomic_t *)table->data; if (!stat) return -EINVAL; if (write) atomic_set(stat, 0); else { char str_buf[32]; char *data; int len = snprintf(str_buf, 32, "%d\n", atomic_read(stat)); if (len >= 32) return -EFAULT; len = strlen(str_buf); if (*ppos > len) { *lenp = 0; return 0; } data = &str_buf[*ppos]; len -= *ppos; if (len > *lenp) len = *lenp; if (len && copy_to_user(buffer, str_buf, len)) return -EFAULT; *lenp = len; *ppos += len; } return 0; } Commit Message: Merge tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux Pull nfsd updates from Bruce Fields: "Another RDMA update from Chuck Lever, and a bunch of miscellaneous bugfixes" * tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux: (26 commits) nfsd: Fix up the "supattr_exclcreat" attributes nfsd: encoders mustn't use unitialized values in error cases nfsd: fix undefined behavior in nfsd4_layout_verify lockd: fix lockd shutdown race NFSv4: Fix callback server shutdown SUNRPC: Refactor svc_set_num_threads() NFSv4.x/callback: Create the callback service through svc_create_pooled lockd: remove redundant check on block svcrdma: Clean out old XDR encoders svcrdma: Remove the req_map cache svcrdma: Remove unused RDMA Write completion handler svcrdma: Reduce size of sge array in struct svc_rdma_op_ctxt svcrdma: Clean up RPC-over-RDMA backchannel reply processing svcrdma: Report Write/Reply chunk overruns svcrdma: Clean up RDMA_ERROR path svcrdma: Use rdma_rw API in RPC reply path svcrdma: Introduce local rdma_rw API helpers svcrdma: Clean up svc_rdma_get_inv_rkey() svcrdma: Add helper to save pages under I/O svcrdma: Eliminate RPCRDMA_SQ_DEPTH_MULT ... CWE ID: CWE-404 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: MagickBooleanType SyncExifProfile(Image *image,StringInfo *profile) { #define MaxDirectoryStack 16 #define EXIF_DELIMITER "\n" #define EXIF_NUM_FORMATS 12 #define TAG_EXIF_OFFSET 0x8769 #define TAG_INTEROP_OFFSET 0xa005 typedef struct _DirectoryInfo { unsigned char *directory; size_t entry; } DirectoryInfo; DirectoryInfo directory_stack[MaxDirectoryStack]; EndianType endian; size_t entry, length, number_entries; ssize_t id, level, offset; static int format_bytes[] = {0, 1, 1, 2, 4, 8, 1, 1, 2, 4, 8, 4, 8}; unsigned char *directory, *exif; /* Set EXIF resolution tag. */ length=GetStringInfoLength(profile); exif=GetStringInfoDatum(profile); if (length < 16) return(MagickFalse); id=(ssize_t) ReadProfileShort(LSBEndian,exif); if ((id != 0x4949) && (id != 0x4D4D)) { while (length != 0) { if (ReadProfileByte(&exif,&length) != 0x45) continue; if (ReadProfileByte(&exif,&length) != 0x78) continue; if (ReadProfileByte(&exif,&length) != 0x69) continue; if (ReadProfileByte(&exif,&length) != 0x66) continue; if (ReadProfileByte(&exif,&length) != 0x00) continue; if (ReadProfileByte(&exif,&length) != 0x00) continue; break; } if (length < 16) return(MagickFalse); id=(ssize_t) ReadProfileShort(LSBEndian,exif); } endian=LSBEndian; if (id == 0x4949) endian=LSBEndian; else if (id == 0x4D4D) endian=MSBEndian; else return(MagickFalse); if (ReadProfileShort(endian,exif+2) != 0x002a) return(MagickFalse); /* This the offset to the first IFD. */ offset=(ssize_t) ReadProfileLong(endian,exif+4); if ((offset < 0) || (size_t) offset >= length) return(MagickFalse); directory=exif+offset; level=0; entry=0; do { if (level > 0) { level--; directory=directory_stack[level].directory; entry=directory_stack[level].entry; } if ((directory < exif) || (directory > (exif+length-2))) break; /* Determine how many entries there are in the current IFD. */ number_entries=ReadProfileShort(endian,directory); for ( ; entry < number_entries; entry++) { int components; register unsigned char *p, *q; size_t number_bytes; ssize_t format, tag_value; q=(unsigned char *) (directory+2+(12*entry)); if (q > (exif+length-12)) break; /* corrupt EXIF */ tag_value=(ssize_t) ReadProfileShort(endian,q); format=(ssize_t) ReadProfileShort(endian,q+2); if ((format-1) >= EXIF_NUM_FORMATS) break; components=(ssize_t) ReadProfileLong(endian,q+4); if (components < 0) break; /* corrupt EXIF */ number_bytes=(size_t) components*format_bytes[format]; if ((ssize_t) number_bytes < components) break; /* prevent overflow */ if (number_bytes <= 4) p=q+8; else { /* The directory entry contains an offset. */ offset=(ssize_t) ReadProfileLong(endian,q+8); if ((size_t) (offset+number_bytes) > length) continue; if (~length < number_bytes) continue; /* prevent overflow */ p=(unsigned char *) (exif+offset); } switch (tag_value) { case 0x011a: { (void) WriteProfileLong(endian,(size_t) (image->resolution.x+0.5),p); (void) WriteProfileLong(endian,1UL,p+4); break; } case 0x011b: { (void) WriteProfileLong(endian,(size_t) (image->resolution.y+0.5),p); (void) WriteProfileLong(endian,1UL,p+4); break; } case 0x0112: { if (number_bytes == 4) { (void) WriteProfileLong(endian,(size_t) image->orientation,p); break; } (void) WriteProfileShort(endian,(unsigned short) image->orientation, p); break; } case 0x0128: { if (number_bytes == 4) { (void) WriteProfileLong(endian,(size_t) (image->units+1),p); break; } (void) WriteProfileShort(endian,(unsigned short) (image->units+1),p); break; } default: break; } if ((tag_value == TAG_EXIF_OFFSET) || (tag_value == TAG_INTEROP_OFFSET)) { offset=(ssize_t) ReadProfileLong(endian,p); if (((size_t) offset < length) && (level < (MaxDirectoryStack-2))) { directory_stack[level].directory=directory; entry++; directory_stack[level].entry=entry; level++; directory_stack[level].directory=exif+offset; directory_stack[level].entry=0; level++; if ((directory+2+(12*number_entries)) > (exif+length)) break; offset=(ssize_t) ReadProfileLong(endian,directory+2+(12* number_entries)); if ((offset != 0) && ((size_t) offset < length) && (level < (MaxDirectoryStack-2))) { directory_stack[level].directory=exif+offset; directory_stack[level].entry=0; level++; } } break; } } } while (level > 0); return(MagickTrue); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/280 CWE ID: CWE-125 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: I18NCustomBindings::I18NCustomBindings(ScriptContext* context) : ObjectBackedNativeHandler(context) { RouteFunction( "GetL10nMessage", base::Bind(&I18NCustomBindings::GetL10nMessage, base::Unretained(this))); RouteFunction("GetL10nUILanguage", base::Bind(&I18NCustomBindings::GetL10nUILanguage, base::Unretained(this))); RouteFunction("DetectTextLanguage", base::Bind(&I18NCustomBindings::DetectTextLanguage, base::Unretained(this))); } Commit Message: [Extensions] Expand bindings access checks BUG=601149 BUG=601073 Review URL: https://codereview.chromium.org/1866103002 Cr-Commit-Position: refs/heads/master@{#387710} CWE ID: CWE-284 Target: 1 Example 2: Code: static bool GetTopFramePath(const net::TestServer& http_server, const net::TestServer& good_https_server, const net::TestServer& bad_https_server, std::string* top_frame_path) { GURL http_url = http_server.GetURL("files/ssl/google.html"); GURL good_https_url = good_https_server.GetURL("files/ssl/google.html"); GURL bad_https_url = bad_https_server.GetURL( "files/ssl/bad_iframe.html"); std::vector<net::TestServer::StringPair> replacement_text_frame_left; replacement_text_frame_left.push_back( make_pair("REPLACE_WITH_HTTP_PAGE", http_url.spec())); replacement_text_frame_left.push_back( make_pair("REPLACE_WITH_GOOD_HTTPS_PAGE", good_https_url.spec())); replacement_text_frame_left.push_back( make_pair("REPLACE_WITH_BAD_HTTPS_PAGE", bad_https_url.spec())); std::string frame_left_path; if (!net::TestServer::GetFilePathWithReplacements( "frame_left.html", replacement_text_frame_left, &frame_left_path)) return false; std::vector<net::TestServer::StringPair> replacement_text_top_frame; replacement_text_top_frame.push_back( make_pair("REPLACE_WITH_FRAME_LEFT_PATH", frame_left_path)); return net::TestServer::GetFilePathWithReplacements( "files/ssl/top_frame.html", replacement_text_top_frame, top_frame_path); } Commit Message: Disable SSLUITest.TestCNInvalidStickiness, flakily hits an assertion. TBR=rsleevi BUG=68448, 49377 TEST=browser_tests Review URL: http://codereview.chromium.org/6178005 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@70876 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-362 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: OMX_ERRORTYPE omx_vdec::get_parameter(OMX_IN OMX_HANDLETYPE hComp, OMX_IN OMX_INDEXTYPE paramIndex, OMX_INOUT OMX_PTR paramData) { (void) hComp; OMX_ERRORTYPE eRet = OMX_ErrorNone; DEBUG_PRINT_LOW("get_parameter:"); if (m_state == OMX_StateInvalid) { DEBUG_PRINT_ERROR("Get Param in Invalid State"); return OMX_ErrorInvalidState; } if (paramData == NULL) { DEBUG_PRINT_LOW("Get Param in Invalid paramData"); return OMX_ErrorBadParameter; } switch ((unsigned long)paramIndex) { case OMX_IndexParamPortDefinition: { OMX_PARAM_PORTDEFINITIONTYPE *portDefn = (OMX_PARAM_PORTDEFINITIONTYPE *) paramData; DEBUG_PRINT_LOW("get_parameter: OMX_IndexParamPortDefinition"); eRet = update_portdef(portDefn); if (eRet == OMX_ErrorNone) m_port_def = *portDefn; break; } case OMX_IndexParamVideoInit: { OMX_PORT_PARAM_TYPE *portParamType = (OMX_PORT_PARAM_TYPE *) paramData; DEBUG_PRINT_LOW("get_parameter: OMX_IndexParamVideoInit"); portParamType->nVersion.nVersion = OMX_SPEC_VERSION; portParamType->nSize = sizeof(portParamType); portParamType->nPorts = 2; portParamType->nStartPortNumber = 0; break; } case OMX_IndexParamVideoPortFormat: { OMX_VIDEO_PARAM_PORTFORMATTYPE *portFmt = (OMX_VIDEO_PARAM_PORTFORMATTYPE *)paramData; DEBUG_PRINT_LOW("get_parameter: OMX_IndexParamVideoPortFormat"); portFmt->nVersion.nVersion = OMX_SPEC_VERSION; portFmt->nSize = sizeof(portFmt); if (0 == portFmt->nPortIndex) { if (0 == portFmt->nIndex) { portFmt->eColorFormat = OMX_COLOR_FormatUnused; portFmt->eCompressionFormat = eCompressionFormat; } else { DEBUG_PRINT_ERROR("get_parameter: OMX_IndexParamVideoPortFormat:"\ " NoMore compression formats"); eRet = OMX_ErrorNoMore; } } else if (1 == portFmt->nPortIndex) { portFmt->eCompressionFormat = OMX_VIDEO_CodingUnused; bool useNonSurfaceMode = false; #if defined(_ANDROID_) && !defined(FLEXYUV_SUPPORTED) useNonSurfaceMode = (m_enable_android_native_buffers == OMX_FALSE); #endif portFmt->eColorFormat = useNonSurfaceMode ? getPreferredColorFormatNonSurfaceMode(portFmt->nIndex) : getPreferredColorFormatDefaultMode(portFmt->nIndex); if (portFmt->eColorFormat == OMX_COLOR_FormatMax ) { eRet = OMX_ErrorNoMore; DEBUG_PRINT_LOW("get_parameter: OMX_IndexParamVideoPortFormat:"\ " NoMore Color formats"); } DEBUG_PRINT_HIGH("returning color-format: 0x%x", portFmt->eColorFormat); } else { DEBUG_PRINT_ERROR("get_parameter: Bad port index %d", (int)portFmt->nPortIndex); eRet = OMX_ErrorBadPortIndex; } break; } /*Component should support this port definition*/ case OMX_IndexParamAudioInit: { OMX_PORT_PARAM_TYPE *audioPortParamType = (OMX_PORT_PARAM_TYPE *) paramData; DEBUG_PRINT_LOW("get_parameter: OMX_IndexParamAudioInit"); audioPortParamType->nVersion.nVersion = OMX_SPEC_VERSION; audioPortParamType->nSize = sizeof(audioPortParamType); audioPortParamType->nPorts = 0; audioPortParamType->nStartPortNumber = 0; break; } /*Component should support this port definition*/ case OMX_IndexParamImageInit: { OMX_PORT_PARAM_TYPE *imagePortParamType = (OMX_PORT_PARAM_TYPE *) paramData; DEBUG_PRINT_LOW("get_parameter: OMX_IndexParamImageInit"); imagePortParamType->nVersion.nVersion = OMX_SPEC_VERSION; imagePortParamType->nSize = sizeof(imagePortParamType); imagePortParamType->nPorts = 0; imagePortParamType->nStartPortNumber = 0; break; } /*Component should support this port definition*/ case OMX_IndexParamOtherInit: { DEBUG_PRINT_ERROR("get_parameter: OMX_IndexParamOtherInit %08x", paramIndex); eRet =OMX_ErrorUnsupportedIndex; break; } case OMX_IndexParamStandardComponentRole: { OMX_PARAM_COMPONENTROLETYPE *comp_role; comp_role = (OMX_PARAM_COMPONENTROLETYPE *) paramData; comp_role->nVersion.nVersion = OMX_SPEC_VERSION; comp_role->nSize = sizeof(*comp_role); DEBUG_PRINT_LOW("Getparameter: OMX_IndexParamStandardComponentRole %d", paramIndex); strlcpy((char*)comp_role->cRole,(const char*)m_cRole, OMX_MAX_STRINGNAME_SIZE); break; } /* Added for parameter test */ case OMX_IndexParamPriorityMgmt: { OMX_PRIORITYMGMTTYPE *priorityMgmType = (OMX_PRIORITYMGMTTYPE *) paramData; DEBUG_PRINT_LOW("get_parameter: OMX_IndexParamPriorityMgmt"); priorityMgmType->nVersion.nVersion = OMX_SPEC_VERSION; priorityMgmType->nSize = sizeof(priorityMgmType); break; } /* Added for parameter test */ case OMX_IndexParamCompBufferSupplier: { OMX_PARAM_BUFFERSUPPLIERTYPE *bufferSupplierType = (OMX_PARAM_BUFFERSUPPLIERTYPE*) paramData; DEBUG_PRINT_LOW("get_parameter: OMX_IndexParamCompBufferSupplier"); bufferSupplierType->nSize = sizeof(bufferSupplierType); bufferSupplierType->nVersion.nVersion = OMX_SPEC_VERSION; if (0 == bufferSupplierType->nPortIndex) bufferSupplierType->nPortIndex = OMX_BufferSupplyUnspecified; else if (1 == bufferSupplierType->nPortIndex) bufferSupplierType->nPortIndex = OMX_BufferSupplyUnspecified; else eRet = OMX_ErrorBadPortIndex; break; } case OMX_IndexParamVideoAvc: { DEBUG_PRINT_LOW("get_parameter: OMX_IndexParamVideoAvc %08x", paramIndex); break; } case (OMX_INDEXTYPE)QOMX_IndexParamVideoMvc: { DEBUG_PRINT_LOW("get_parameter: QOMX_IndexParamVideoMvc %08x", paramIndex); break; } case OMX_IndexParamVideoH263: { DEBUG_PRINT_LOW("get_parameter: OMX_IndexParamVideoH263 %08x", paramIndex); break; } case OMX_IndexParamVideoMpeg4: { DEBUG_PRINT_LOW("get_parameter: OMX_IndexParamVideoMpeg4 %08x", paramIndex); break; } case OMX_IndexParamVideoMpeg2: { DEBUG_PRINT_LOW("get_parameter: OMX_IndexParamVideoMpeg2 %08x", paramIndex); break; } case OMX_IndexParamVideoProfileLevelQuerySupported: { DEBUG_PRINT_LOW("get_parameter: OMX_IndexParamVideoProfileLevelQuerySupported %08x", paramIndex); OMX_VIDEO_PARAM_PROFILELEVELTYPE *profileLevelType = (OMX_VIDEO_PARAM_PROFILELEVELTYPE *)paramData; eRet = get_supported_profile_level_for_1080p(profileLevelType); break; } #if defined (_ANDROID_HONEYCOMB_) || defined (_ANDROID_ICS_) case OMX_GoogleAndroidIndexGetAndroidNativeBufferUsage: { DEBUG_PRINT_LOW("get_parameter: OMX_GoogleAndroidIndexGetAndroidNativeBufferUsage"); GetAndroidNativeBufferUsageParams* nativeBuffersUsage = (GetAndroidNativeBufferUsageParams *) paramData; if (nativeBuffersUsage->nPortIndex == OMX_CORE_OUTPUT_PORT_INDEX) { if (secure_mode && !secure_scaling_to_non_secure_opb) { nativeBuffersUsage->nUsage = (GRALLOC_USAGE_PRIVATE_MM_HEAP | GRALLOC_USAGE_PROTECTED | GRALLOC_USAGE_PRIVATE_UNCACHED); } else { nativeBuffersUsage->nUsage = (GRALLOC_USAGE_PRIVATE_IOMMU_HEAP | GRALLOC_USAGE_PRIVATE_UNCACHED); } } else { DEBUG_PRINT_HIGH("get_parameter: OMX_GoogleAndroidIndexGetAndroidNativeBufferUsage failed!"); eRet = OMX_ErrorBadParameter; } } break; #endif #ifdef FLEXYUV_SUPPORTED case OMX_QcomIndexFlexibleYUVDescription: { DEBUG_PRINT_LOW("get_parameter: describeColorFormat"); eRet = describeColorFormat(paramData); break; } #endif default: { DEBUG_PRINT_ERROR("get_parameter: unknown param %08x", paramIndex); eRet =OMX_ErrorUnsupportedIndex; } } DEBUG_PRINT_LOW("get_parameter returning WxH(%d x %d) SxSH(%d x %d)", drv_ctx.video_resolution.frame_width, drv_ctx.video_resolution.frame_height, drv_ctx.video_resolution.stride, drv_ctx.video_resolution.scan_lines); return eRet; } Commit Message: DO NOT MERGE mm-video-v4l2: vidc: validate omx param/config data Check the sanity of config/param strcuture objects passed to get/set _ config()/parameter() methods. Bug: 27533317 Security Vulnerability in MediaServer omx_vdec::get_config() Can lead to arbitrary write Change-Id: I6c3243afe12055ab94f1a1ecf758c10e88231809 Conflicts: mm-core/inc/OMX_QCOMExtns.h mm-video-v4l2/vidc/vdec/src/omx_vdec_msm8974.cpp mm-video-v4l2/vidc/venc/src/omx_video_base.cpp mm-video-v4l2/vidc/venc/src/omx_video_encoder.cpp CWE ID: CWE-20 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: kg_unseal_v1(context, minor_status, ctx, ptr, bodysize, message_buffer, conf_state, qop_state, toktype) krb5_context context; OM_uint32 *minor_status; krb5_gss_ctx_id_rec *ctx; unsigned char *ptr; int bodysize; gss_buffer_t message_buffer; int *conf_state; gss_qop_t *qop_state; int toktype; { krb5_error_code code; int conflen = 0; int signalg; int sealalg; gss_buffer_desc token; krb5_checksum cksum; krb5_checksum md5cksum; krb5_data plaind; char *data_ptr; unsigned char *plain; unsigned int cksum_len = 0; size_t plainlen; int direction; krb5_ui_4 seqnum; OM_uint32 retval; size_t sumlen; krb5_keyusage sign_usage = KG_USAGE_SIGN; if (toktype == KG_TOK_SEAL_MSG) { message_buffer->length = 0; message_buffer->value = NULL; } /* get the sign and seal algorithms */ signalg = ptr[0] + (ptr[1]<<8); sealalg = ptr[2] + (ptr[3]<<8); /* Sanity checks */ if ((ptr[4] != 0xff) || (ptr[5] != 0xff)) { *minor_status = 0; return GSS_S_DEFECTIVE_TOKEN; } if ((toktype != KG_TOK_SEAL_MSG) && (sealalg != 0xffff)) { *minor_status = 0; return GSS_S_DEFECTIVE_TOKEN; } /* in the current spec, there is only one valid seal algorithm per key type, so a simple comparison is ok */ if ((toktype == KG_TOK_SEAL_MSG) && !((sealalg == 0xffff) || (sealalg == ctx->sealalg))) { *minor_status = 0; return GSS_S_DEFECTIVE_TOKEN; } /* there are several mappings of seal algorithms to sign algorithms, but few enough that we can try them all. */ if ((ctx->sealalg == SEAL_ALG_NONE && signalg > 1) || (ctx->sealalg == SEAL_ALG_1 && signalg != SGN_ALG_3) || (ctx->sealalg == SEAL_ALG_DES3KD && signalg != SGN_ALG_HMAC_SHA1_DES3_KD)|| (ctx->sealalg == SEAL_ALG_MICROSOFT_RC4 && signalg != SGN_ALG_HMAC_MD5)) { *minor_status = 0; return GSS_S_DEFECTIVE_TOKEN; } switch (signalg) { case SGN_ALG_DES_MAC_MD5: case SGN_ALG_MD2_5: case SGN_ALG_HMAC_MD5: cksum_len = 8; if (toktype != KG_TOK_SEAL_MSG) sign_usage = 15; break; case SGN_ALG_3: cksum_len = 16; break; case SGN_ALG_HMAC_SHA1_DES3_KD: cksum_len = 20; break; default: *minor_status = 0; return GSS_S_DEFECTIVE_TOKEN; } /* get the token parameters */ if ((code = kg_get_seq_num(context, ctx->seq, ptr+14, ptr+6, &direction, &seqnum))) { *minor_status = code; return(GSS_S_BAD_SIG); } /* decode the message, if SEAL */ if (toktype == KG_TOK_SEAL_MSG) { size_t tmsglen = bodysize-(14+cksum_len); if (sealalg != 0xffff) { if ((plain = (unsigned char *) xmalloc(tmsglen)) == NULL) { *minor_status = ENOMEM; return(GSS_S_FAILURE); } if (ctx->sealalg == SEAL_ALG_MICROSOFT_RC4) { unsigned char bigend_seqnum[4]; krb5_keyblock *enc_key; int i; store_32_be(seqnum, bigend_seqnum); code = krb5_k_key_keyblock(context, ctx->enc, &enc_key); if (code) { xfree(plain); *minor_status = code; return(GSS_S_FAILURE); } assert (enc_key->length == 16); for (i = 0; i <= 15; i++) ((char *) enc_key->contents)[i] ^=0xf0; code = kg_arcfour_docrypt (enc_key, 0, &bigend_seqnum[0], 4, ptr+14+cksum_len, tmsglen, plain); krb5_free_keyblock (context, enc_key); } else { code = kg_decrypt(context, ctx->enc, KG_USAGE_SEAL, NULL, ptr+14+cksum_len, plain, tmsglen); } if (code) { xfree(plain); *minor_status = code; return(GSS_S_FAILURE); } } else { plain = ptr+14+cksum_len; } plainlen = tmsglen; conflen = kg_confounder_size(context, ctx->enc->keyblock.enctype); token.length = tmsglen - conflen - plain[tmsglen-1]; if (token.length) { if ((token.value = (void *) gssalloc_malloc(token.length)) == NULL) { if (sealalg != 0xffff) xfree(plain); *minor_status = ENOMEM; return(GSS_S_FAILURE); } memcpy(token.value, plain+conflen, token.length); } else { token.value = NULL; } } else if (toktype == KG_TOK_SIGN_MSG) { token = *message_buffer; plain = token.value; plainlen = token.length; } else { token.length = 0; token.value = NULL; plain = token.value; plainlen = token.length; } /* compute the checksum of the message */ /* initialize the the cksum */ switch (signalg) { case SGN_ALG_DES_MAC_MD5: case SGN_ALG_MD2_5: case SGN_ALG_DES_MAC: case SGN_ALG_3: md5cksum.checksum_type = CKSUMTYPE_RSA_MD5; break; case SGN_ALG_HMAC_MD5: md5cksum.checksum_type = CKSUMTYPE_HMAC_MD5_ARCFOUR; break; case SGN_ALG_HMAC_SHA1_DES3_KD: md5cksum.checksum_type = CKSUMTYPE_HMAC_SHA1_DES3; break; default: abort (); } code = krb5_c_checksum_length(context, md5cksum.checksum_type, &sumlen); if (code) return(code); md5cksum.length = sumlen; switch (signalg) { case SGN_ALG_DES_MAC_MD5: case SGN_ALG_3: /* compute the checksum of the message */ /* 8 = bytes of token body to be checksummed according to spec */ if (! (data_ptr = xmalloc(8 + plainlen))) { if (sealalg != 0xffff) xfree(plain); if (toktype == KG_TOK_SEAL_MSG) gssalloc_free(token.value); *minor_status = ENOMEM; return(GSS_S_FAILURE); } (void) memcpy(data_ptr, ptr-2, 8); (void) memcpy(data_ptr+8, plain, plainlen); plaind.length = 8 + plainlen; plaind.data = data_ptr; code = krb5_k_make_checksum(context, md5cksum.checksum_type, ctx->seq, sign_usage, &plaind, &md5cksum); xfree(data_ptr); if (code) { if (toktype == KG_TOK_SEAL_MSG) gssalloc_free(token.value); *minor_status = code; return(GSS_S_FAILURE); } code = kg_encrypt_inplace(context, ctx->seq, KG_USAGE_SEAL, (g_OID_equal(ctx->mech_used, gss_mech_krb5_old) ? ctx->seq->keyblock.contents : NULL), md5cksum.contents, 16); if (code) { krb5_free_checksum_contents(context, &md5cksum); if (toktype == KG_TOK_SEAL_MSG) gssalloc_free(token.value); *minor_status = code; return GSS_S_FAILURE; } if (signalg == 0) cksum.length = 8; else cksum.length = 16; cksum.contents = md5cksum.contents + 16 - cksum.length; code = k5_bcmp(cksum.contents, ptr + 14, cksum.length); break; case SGN_ALG_MD2_5: if (!ctx->seed_init && (code = kg_make_seed(context, ctx->subkey, ctx->seed))) { krb5_free_checksum_contents(context, &md5cksum); if (sealalg != 0xffff) xfree(plain); if (toktype == KG_TOK_SEAL_MSG) gssalloc_free(token.value); *minor_status = code; return GSS_S_FAILURE; } if (! (data_ptr = xmalloc(sizeof(ctx->seed) + 8 + plainlen))) { krb5_free_checksum_contents(context, &md5cksum); if (sealalg == 0) xfree(plain); if (toktype == KG_TOK_SEAL_MSG) gssalloc_free(token.value); *minor_status = ENOMEM; return(GSS_S_FAILURE); } (void) memcpy(data_ptr, ptr-2, 8); (void) memcpy(data_ptr+8, ctx->seed, sizeof(ctx->seed)); (void) memcpy(data_ptr+8+sizeof(ctx->seed), plain, plainlen); plaind.length = 8 + sizeof(ctx->seed) + plainlen; plaind.data = data_ptr; krb5_free_checksum_contents(context, &md5cksum); code = krb5_k_make_checksum(context, md5cksum.checksum_type, ctx->seq, sign_usage, &plaind, &md5cksum); xfree(data_ptr); if (code) { if (sealalg == 0) xfree(plain); if (toktype == KG_TOK_SEAL_MSG) gssalloc_free(token.value); *minor_status = code; return(GSS_S_FAILURE); } code = k5_bcmp(md5cksum.contents, ptr + 14, 8); /* Falls through to defective-token?? */ default: *minor_status = 0; return(GSS_S_DEFECTIVE_TOKEN); case SGN_ALG_HMAC_SHA1_DES3_KD: case SGN_ALG_HMAC_MD5: /* compute the checksum of the message */ /* 8 = bytes of token body to be checksummed according to spec */ if (! (data_ptr = xmalloc(8 + plainlen))) { if (sealalg != 0xffff) xfree(plain); if (toktype == KG_TOK_SEAL_MSG) gssalloc_free(token.value); *minor_status = ENOMEM; return(GSS_S_FAILURE); } (void) memcpy(data_ptr, ptr-2, 8); (void) memcpy(data_ptr+8, plain, plainlen); plaind.length = 8 + plainlen; plaind.data = data_ptr; code = krb5_k_make_checksum(context, md5cksum.checksum_type, ctx->seq, sign_usage, &plaind, &md5cksum); xfree(data_ptr); if (code) { if (toktype == KG_TOK_SEAL_MSG) gssalloc_free(token.value); *minor_status = code; return(GSS_S_FAILURE); } code = k5_bcmp(md5cksum.contents, ptr + 14, cksum_len); break; } krb5_free_checksum_contents(context, &md5cksum); if (sealalg != 0xffff) xfree(plain); /* compare the computed checksum against the transmitted checksum */ if (code) { if (toktype == KG_TOK_SEAL_MSG) gssalloc_free(token.value); *minor_status = 0; return(GSS_S_BAD_SIG); } /* it got through unscathed. Make sure the context is unexpired */ if (toktype == KG_TOK_SEAL_MSG) *message_buffer = token; if (conf_state) *conf_state = (sealalg != 0xffff); if (qop_state) *qop_state = GSS_C_QOP_DEFAULT; /* do sequencing checks */ if ((ctx->initiate && direction != 0xff) || (!ctx->initiate && direction != 0)) { if (toktype == KG_TOK_SEAL_MSG) { gssalloc_free(token.value); message_buffer->value = NULL; message_buffer->length = 0; } *minor_status = (OM_uint32)G_BAD_DIRECTION; return(GSS_S_BAD_SIG); } retval = g_order_check(&(ctx->seqstate), (gssint_uint64)seqnum); /* success or ordering violation */ *minor_status = 0; return(retval); } Commit Message: Handle invalid RFC 1964 tokens [CVE-2014-4341...] Detect the following cases which would otherwise cause invalid memory accesses and/or integer underflow: * An RFC 1964 token being processed by an RFC 4121-only context [CVE-2014-4342] * A header with fewer than 22 bytes after the token ID or an incomplete checksum [CVE-2014-4341 CVE-2014-4342] * A ciphertext shorter than the confounder [CVE-2014-4341] * A declared padding length longer than the plaintext [CVE-2014-4341] If we detect a bad pad byte, continue on to compute the checksum to avoid creating a padding oracle, but treat the checksum as invalid even if it compares equal. CVE-2014-4341: In MIT krb5, an unauthenticated remote attacker with the ability to inject packets into a legitimately established GSSAPI application session can cause a program crash due to invalid memory references when attempting to read beyond the end of a buffer. CVSSv2 Vector: AV:N/AC:M/Au:N/C:N/I:N/A:P/E:POC/RL:OF/RC:C CVE-2014-4342: In MIT krb5 releases krb5-1.7 and later, an unauthenticated remote attacker with the ability to inject packets into a legitimately established GSSAPI application session can cause a program crash due to invalid memory references when reading beyond the end of a buffer or by causing a null pointer dereference. CVSSv2 Vector: AV:N/AC:M/Au:N/C:N/I:N/A:P/E:POC/RL:OF/RC:C [[email protected]: CVE summaries, CVSS] (cherry picked from commit fb99962cbd063ac04c9a9d2cc7c75eab73f3533d) ticket: 7949 version_fixed: 1.12.2 status: resolved CWE ID: CWE-119 Target: 1 Example 2: Code: void GLES2DecoderImpl::DoGetIntegeri_v(GLenum target, GLuint index, GLint* params, GLsizei params_size) { GetIndexedIntegerImpl<GLint>("glGetIntegeri_v", target, index, params); } Commit Message: Add GL_PROGRAM_COMPLETION_QUERY_CHROMIUM This makes the query of GL_COMPLETION_STATUS_KHR to programs much cheaper by minimizing the round-trip to the GPU thread. Bug: 881152, 957001 Change-Id: Iadfa798af29225e752c710ca5c25f50b3dd3101a Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1586630 Commit-Queue: Kenneth Russell <[email protected]> Reviewed-by: Kentaro Hara <[email protected]> Reviewed-by: Geoff Lang <[email protected]> Reviewed-by: Kenneth Russell <[email protected]> Cr-Commit-Position: refs/heads/master@{#657568} CWE ID: CWE-416 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void ClearActiveTab() { active_tab_->permissions_data()->ClearTabSpecificPermissions(kTabId); } Commit Message: Call CanCaptureVisiblePage in page capture API. Currently the pageCapture permission allows access to arbitrary local files and chrome:// pages which can be a security concern. In order to address this, the page capture API needs to be changed similar to the captureVisibleTab API. The API will now only allow extensions to capture otherwise-restricted URLs if the user has granted activeTab. In addition, file:// URLs are only capturable with the "Allow on file URLs" option enabled. Bug: 893087 Change-Id: I6d6225a3efb70fc033e2e1c031c633869afac624 Reviewed-on: https://chromium-review.googlesource.com/c/1330689 Commit-Queue: Bettina Dea <[email protected]> Reviewed-by: Devlin <[email protected]> Reviewed-by: Varun Khaneja <[email protected]> Cr-Commit-Position: refs/heads/master@{#615248} CWE ID: CWE-20 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int __kvm_set_memory_region(struct kvm *kvm, struct kvm_userspace_memory_region *mem, int user_alloc) { int r; gfn_t base_gfn; unsigned long npages; unsigned long i; struct kvm_memory_slot *memslot; struct kvm_memory_slot old, new; struct kvm_memslots *slots, *old_memslots; r = -EINVAL; /* General sanity checks */ if (mem->memory_size & (PAGE_SIZE - 1)) goto out; if (mem->guest_phys_addr & (PAGE_SIZE - 1)) goto out; /* We can read the guest memory with __xxx_user() later on. */ if (user_alloc && ((mem->userspace_addr & (PAGE_SIZE - 1)) || !access_ok(VERIFY_WRITE, (void __user *)(unsigned long)mem->userspace_addr, mem->memory_size))) goto out; if (mem->slot >= KVM_MEM_SLOTS_NUM) goto out; if (mem->guest_phys_addr + mem->memory_size < mem->guest_phys_addr) goto out; memslot = id_to_memslot(kvm->memslots, mem->slot); base_gfn = mem->guest_phys_addr >> PAGE_SHIFT; npages = mem->memory_size >> PAGE_SHIFT; r = -EINVAL; if (npages > KVM_MEM_MAX_NR_PAGES) goto out; if (!npages) mem->flags &= ~KVM_MEM_LOG_DIRTY_PAGES; new = old = *memslot; new.id = mem->slot; new.base_gfn = base_gfn; new.npages = npages; new.flags = mem->flags; /* Disallow changing a memory slot's size. */ r = -EINVAL; if (npages && old.npages && npages != old.npages) goto out_free; /* Check for overlaps */ r = -EEXIST; for (i = 0; i < KVM_MEMORY_SLOTS; ++i) { struct kvm_memory_slot *s = &kvm->memslots->memslots[i]; if (s == memslot || !s->npages) continue; if (!((base_gfn + npages <= s->base_gfn) || (base_gfn >= s->base_gfn + s->npages))) goto out_free; } /* Free page dirty bitmap if unneeded */ if (!(new.flags & KVM_MEM_LOG_DIRTY_PAGES)) new.dirty_bitmap = NULL; r = -ENOMEM; /* Allocate if a slot is being created */ #ifndef CONFIG_S390 if (npages && !new.rmap) { new.rmap = vzalloc(npages * sizeof(*new.rmap)); if (!new.rmap) goto out_free; new.user_alloc = user_alloc; new.userspace_addr = mem->userspace_addr; } if (!npages) goto skip_lpage; for (i = 0; i < KVM_NR_PAGE_SIZES - 1; ++i) { unsigned long ugfn; unsigned long j; int lpages; int level = i + 2; /* Avoid unused variable warning if no large pages */ (void)level; if (new.lpage_info[i]) continue; lpages = 1 + ((base_gfn + npages - 1) >> KVM_HPAGE_GFN_SHIFT(level)); lpages -= base_gfn >> KVM_HPAGE_GFN_SHIFT(level); new.lpage_info[i] = vzalloc(lpages * sizeof(*new.lpage_info[i])); if (!new.lpage_info[i]) goto out_free; if (base_gfn & (KVM_PAGES_PER_HPAGE(level) - 1)) new.lpage_info[i][0].write_count = 1; if ((base_gfn+npages) & (KVM_PAGES_PER_HPAGE(level) - 1)) new.lpage_info[i][lpages - 1].write_count = 1; ugfn = new.userspace_addr >> PAGE_SHIFT; /* * If the gfn and userspace address are not aligned wrt each * other, or if explicitly asked to, disable large page * support for this slot */ if ((base_gfn ^ ugfn) & (KVM_PAGES_PER_HPAGE(level) - 1) || !largepages_enabled) for (j = 0; j < lpages; ++j) new.lpage_info[i][j].write_count = 1; } skip_lpage: /* Allocate page dirty bitmap if needed */ if ((new.flags & KVM_MEM_LOG_DIRTY_PAGES) && !new.dirty_bitmap) { if (kvm_create_dirty_bitmap(&new) < 0) goto out_free; /* destroy any largepage mappings for dirty tracking */ } #else /* not defined CONFIG_S390 */ new.user_alloc = user_alloc; if (user_alloc) new.userspace_addr = mem->userspace_addr; #endif /* not defined CONFIG_S390 */ if (!npages) { struct kvm_memory_slot *slot; r = -ENOMEM; slots = kmemdup(kvm->memslots, sizeof(struct kvm_memslots), GFP_KERNEL); if (!slots) goto out_free; slot = id_to_memslot(slots, mem->slot); slot->flags |= KVM_MEMSLOT_INVALID; update_memslots(slots, NULL); old_memslots = kvm->memslots; rcu_assign_pointer(kvm->memslots, slots); synchronize_srcu_expedited(&kvm->srcu); /* From this point no new shadow pages pointing to a deleted * memslot will be created. * * validation of sp->gfn happens in: * - gfn_to_hva (kvm_read_guest, gfn_to_pfn) * - kvm_is_visible_gfn (mmu_check_roots) */ kvm_arch_flush_shadow(kvm); kfree(old_memslots); } r = kvm_arch_prepare_memory_region(kvm, &new, old, mem, user_alloc); if (r) goto out_free; /* map the pages in iommu page table */ if (npages) { r = kvm_iommu_map_pages(kvm, &new); if (r) goto out_free; } r = -ENOMEM; slots = kmemdup(kvm->memslots, sizeof(struct kvm_memslots), GFP_KERNEL); if (!slots) goto out_free; /* actual memory is freed via old in kvm_free_physmem_slot below */ if (!npages) { new.rmap = NULL; new.dirty_bitmap = NULL; for (i = 0; i < KVM_NR_PAGE_SIZES - 1; ++i) new.lpage_info[i] = NULL; } update_memslots(slots, &new); old_memslots = kvm->memslots; rcu_assign_pointer(kvm->memslots, slots); synchronize_srcu_expedited(&kvm->srcu); kvm_arch_commit_memory_region(kvm, mem, old, user_alloc); /* * If the new memory slot is created, we need to clear all * mmio sptes. */ if (npages && old.base_gfn != mem->guest_phys_addr >> PAGE_SHIFT) kvm_arch_flush_shadow(kvm); kvm_free_physmem_slot(&old, &new); kfree(old_memslots); return 0; out_free: kvm_free_physmem_slot(&new, &old); out: return r; } Commit Message: KVM: unmap pages from the iommu when slots are removed commit 32f6daad4651a748a58a3ab6da0611862175722f upstream. We've been adding new mappings, but not destroying old mappings. This can lead to a page leak as pages are pinned using get_user_pages, but only unpinned with put_page if they still exist in the memslots list on vm shutdown. A memslot that is destroyed while an iommu domain is enabled for the guest will therefore result in an elevated page reference count that is never cleared. Additionally, without this fix, the iommu is only programmed with the first translation for a gpa. This can result in peer-to-peer errors if a mapping is destroyed and replaced by a new mapping at the same gpa as the iommu will still be pointing to the original, pinned memory address. Signed-off-by: Alex Williamson <[email protected]> Signed-off-by: Marcelo Tosatti <[email protected]> Signed-off-by: Greg Kroah-Hartman <[email protected]> CWE ID: CWE-264 Target: 1 Example 2: Code: vrrp_gnotify_fault_handler(vector_t *strvec) { vrrp_sgroup_t *vgroup = LIST_TAIL_DATA(vrrp_data->vrrp_sync_group); if (vgroup->script_fault) { report_config_error(CONFIG_GENERAL_ERROR, "vrrp group %s: notify_fault script already specified - ignoring %s", vgroup->gname, FMT_STR_VSLOT(strvec,1)); return; } vgroup->script_fault = set_vrrp_notify_script(strvec, 0); vgroup->notify_exec = true; } Commit Message: When opening files for write, ensure they aren't symbolic links Issue #1048 identified that if, for example, a non privileged user created a symbolic link from /etc/keepalvied.data to /etc/passwd, writing to /etc/keepalived.data (which could be invoked via DBus) would cause /etc/passwd to be overwritten. This commit stops keepalived writing to pathnames where the ultimate component is a symbolic link, by setting O_NOFOLLOW whenever opening a file for writing. This might break some setups, where, for example, /etc/keepalived.data was a symbolic link to /home/fred/keepalived.data. If this was the case, instead create a symbolic link from /home/fred/keepalived.data to /tmp/keepalived.data, so that the file is still accessible via /home/fred/keepalived.data. There doesn't appear to be a way around this backward incompatibility, since even checking if the pathname is a symbolic link prior to opening for writing would create a race condition. Signed-off-by: Quentin Armitage <[email protected]> CWE ID: CWE-59 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: SYSCALL_DEFINE4(recv, int, fd, void __user *, ubuf, size_t, size, unsigned int, flags) { return __sys_recvfrom(fd, ubuf, size, flags, NULL, NULL); } Commit Message: socket: close race condition between sock_close() and sockfs_setattr() fchownat() doesn't even hold refcnt of fd until it figures out fd is really needed (otherwise is ignored) and releases it after it resolves the path. This means sock_close() could race with sockfs_setattr(), which leads to a NULL pointer dereference since typically we set sock->sk to NULL in ->release(). As pointed out by Al, this is unique to sockfs. So we can fix this in socket layer by acquiring inode_lock in sock_close() and checking against NULL in sockfs_setattr(). sock_release() is called in many places, only the sock_close() path matters here. And fortunately, this should not affect normal sock_close() as it is only called when the last fd refcnt is gone. It only affects sock_close() with a parallel sockfs_setattr() in progress, which is not common. Fixes: 86741ec25462 ("net: core: Add a UID field to struct sock.") Reported-by: shankarapailoor <[email protected]> Cc: Tetsuo Handa <[email protected]> Cc: Lorenzo Colitti <[email protected]> Cc: Al Viro <[email protected]> Signed-off-by: Cong Wang <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-362 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: get_pols_2_svc(gpols_arg *arg, struct svc_req *rqstp) { static gpols_ret ret; char *prime_arg; gss_buffer_desc client_name, service_name; OM_uint32 minor_stat; kadm5_server_handle_t handle; const char *errmsg = NULL; xdr_free(xdr_gpols_ret, &ret); if ((ret.code = new_server_handle(arg->api_version, rqstp, &handle))) goto exit_func; if ((ret.code = check_handle((void *)handle))) goto exit_func; ret.api_version = handle->api_version; if (setup_gss_names(rqstp, &client_name, &service_name) < 0) { ret.code = KADM5_FAILURE; goto exit_func; } prime_arg = arg->exp; if (prime_arg == NULL) prime_arg = "*"; if (CHANGEPW_SERVICE(rqstp) || !kadm5int_acl_check(handle->context, rqst2name(rqstp), ACL_LIST, NULL, NULL)) { ret.code = KADM5_AUTH_LIST; log_unauth("kadm5_get_policies", prime_arg, &client_name, &service_name, rqstp); } else { ret.code = kadm5_get_policies((void *)handle, arg->exp, &ret.pols, &ret.count); if( ret.code != 0 ) errmsg = krb5_get_error_message(handle->context, ret.code); log_done("kadm5_get_policies", prime_arg, errmsg, &client_name, &service_name, rqstp); if (errmsg != NULL) krb5_free_error_message(handle->context, errmsg); } gss_release_buffer(&minor_stat, &client_name); gss_release_buffer(&minor_stat, &service_name); exit_func: free_server_handle(handle); return &ret; } Commit Message: Fix leaks in kadmin server stubs [CVE-2015-8631] In each kadmind server stub, initialize the client_name and server_name variables, and release them in the cleanup handler. Many of the stubs will otherwise leak the client and server name if krb5_unparse_name() fails. Also make sure to free the prime_arg variables in rename_principal_2_svc(), or we can leak the first one if unparsing the second one fails. Discovered by Simo Sorce. CVE-2015-8631: In all versions of MIT krb5, an authenticated attacker can cause kadmind to leak memory by supplying a null principal name in a request which uses one. Repeating these requests will eventually cause kadmind to exhaust all available memory. CVSSv2 Vector: AV:N/AC:L/Au:S/C:N/I:N/A:C/E:POC/RL:OF/RC:C ticket: 8343 (new) target_version: 1.14-next target_version: 1.13-next tags: pullup CWE ID: CWE-119 Target: 1 Example 2: Code: ZEND_API void* ZEND_FASTCALL _safe_malloc(size_t nmemb, size_t size, size_t offset) { return pemalloc(safe_address(nmemb, size, offset), 1); } Commit Message: Fix bug #72742 - memory allocator fails to realloc small block to large one CWE ID: CWE-190 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: cff_parse_real( FT_Byte* start, FT_Byte* limit, FT_Long power_ten, FT_Long* scaling ) { FT_Byte* p = start; FT_Int nib; FT_UInt phase; FT_Long result, number, exponent; FT_Int sign = 0, exponent_sign = 0, have_overflow = 0; FT_Long exponent_add, integer_length, fraction_length; if ( scaling ) *scaling = 0; result = 0; number = 0; exponent = 0; exponent_add = 0; integer_length = 0; fraction_length = 0; /* First of all, read the integer part. */ phase = 4; for (;;) { /* If we entered this iteration with phase == 4, we need to */ /* read a new byte. This also skips past the initial 0x1E. */ if ( phase ) { p++; /* Make sure we don't read past the end. */ if ( p >= limit ) goto Bad; } /* Get the nibble. */ nib = (FT_Int)( p[0] >> phase ) & 0xF; phase = 4 - phase; if ( nib == 0xE ) sign = 1; else if ( nib > 9 ) break; else { /* Increase exponent if we can't add the digit. */ if ( number >= 0xCCCCCCCL ) exponent_add++; /* Skip leading zeros. */ else if ( nib || number ) { integer_length++; number = number * 10 + nib; } } } /* Read fraction part, if any. */ if ( nib == 0xA ) for (;;) { /* If we entered this iteration with phase == 4, we need */ /* to read a new byte. */ if ( phase ) { p++; /* Make sure we don't read past the end. */ if ( p >= limit ) goto Bad; } /* Get the nibble. */ nib = ( p[0] >> phase ) & 0xF; phase = 4 - phase; if ( nib >= 10 ) break; /* Skip leading zeros if possible. */ if ( !nib && !number ) exponent_add--; /* Only add digit if we don't overflow. */ else if ( number < 0xCCCCCCCL && fraction_length < 9 ) { fraction_length++; number = number * 10 + nib; } } /* Read exponent, if any. */ if ( nib == 12 ) { exponent_sign = 1; nib = 11; } if ( nib == 11 ) { for (;;) { /* If we entered this iteration with phase == 4, */ /* we need to read a new byte. */ if ( phase ) { p++; /* Make sure we don't read past the end. */ if ( p >= limit ) goto Bad; } /* Get the nibble. */ nib = ( p[0] >> phase ) & 0xF; phase = 4 - phase; if ( nib >= 10 ) break; /* Arbitrarily limit exponent. */ if ( exponent > 1000 ) have_overflow = 1; else exponent = exponent * 10 + nib; } if ( exponent_sign ) exponent = -exponent; } if ( !number ) goto Exit; if ( have_overflow ) { if ( exponent_sign ) goto Underflow; else goto Overflow; } /* We don't check `power_ten' and `exponent_add'. */ exponent += power_ten + exponent_add; if ( scaling ) { /* Only use `fraction_length'. */ fraction_length += integer_length; exponent += integer_length; if ( fraction_length <= 5 ) { if ( number > 0x7FFFL ) { result = FT_DivFix( number, 10 ); *scaling = exponent - fraction_length + 1; } else { if ( exponent > 0 ) { FT_Long new_fraction_length, shift; /* Make `scaling' as small as possible. */ new_fraction_length = FT_MIN( exponent, 5 ); shift = new_fraction_length - fraction_length; if ( shift > 0 ) { exponent -= new_fraction_length; number *= power_tens[shift]; if ( number > 0x7FFFL ) { number /= 10; exponent += 1; } } else exponent -= fraction_length; } else exponent -= fraction_length; result = (FT_Long)( (FT_ULong)number << 16 ); *scaling = exponent; } } else { if ( ( number / power_tens[fraction_length - 5] ) > 0x7FFFL ) { result = FT_DivFix( number, power_tens[fraction_length - 4] ); *scaling = exponent - 4; } else { result = FT_DivFix( number, power_tens[fraction_length - 5] ); *scaling = exponent - 5; } } } else { integer_length += exponent; fraction_length -= exponent; if ( integer_length > 5 ) goto Overflow; if ( integer_length < -5 ) goto Underflow; /* Remove non-significant digits. */ if ( integer_length < 0 ) { number /= power_tens[-integer_length]; fraction_length += integer_length; } /* this can only happen if exponent was non-zero */ if ( fraction_length == 10 ) { number /= 10; fraction_length -= 1; } /* Convert into 16.16 format. */ if ( fraction_length > 0 ) { if ( ( number / power_tens[fraction_length] ) > 0x7FFFL ) goto Exit; result = FT_DivFix( number, power_tens[fraction_length] ); } else { number *= power_tens[-fraction_length]; if ( number > 0x7FFFL ) goto Overflow; result = (FT_Long)( (FT_ULong)number << 16 ); } } Exit: if ( sign ) result = -result; return result; Overflow: result = 0x7FFFFFFFL; FT_TRACE4(( "!!!OVERFLOW:!!!" )); goto Exit; Underflow: result = 0; FT_TRACE4(( "!!!UNDERFLOW:!!!" )); goto Exit; Bad: result = 0; FT_TRACE4(( "!!!END OF DATA:!!!" )); goto Exit; } Commit Message: CWE ID: CWE-787 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: png_read_start_row(png_structp png_ptr) { #ifdef PNG_READ_INTERLACING_SUPPORTED /* Arrays to facilitate easy interlacing - use pass (0 - 6) as index */ /* Start of interlace block */ PNG_CONST int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0}; /* Offset to next interlace block */ PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1}; /* Start of interlace block in the y direction */ PNG_CONST int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1}; /* Offset to next interlace block in the y direction */ PNG_CONST int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2}; #endif int max_pixel_depth; png_size_t row_bytes; png_debug(1, "in png_read_start_row"); png_ptr->zstream.avail_in = 0; png_init_read_transformations(png_ptr); #ifdef PNG_READ_INTERLACING_SUPPORTED if (png_ptr->interlaced) { if (!(png_ptr->transformations & PNG_INTERLACE)) png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 - png_pass_ystart[0]) / png_pass_yinc[0]; else png_ptr->num_rows = png_ptr->height; png_ptr->iwidth = (png_ptr->width + png_pass_inc[png_ptr->pass] - 1 - png_pass_start[png_ptr->pass]) / png_pass_inc[png_ptr->pass]; } else #endif /* PNG_READ_INTERLACING_SUPPORTED */ { png_ptr->num_rows = png_ptr->height; png_ptr->iwidth = png_ptr->width; } max_pixel_depth = png_ptr->pixel_depth; #ifdef PNG_READ_PACK_SUPPORTED if ((png_ptr->transformations & PNG_PACK) && png_ptr->bit_depth < 8) max_pixel_depth = 8; #endif #ifdef PNG_READ_EXPAND_SUPPORTED if (png_ptr->transformations & PNG_EXPAND) { if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) { if (png_ptr->num_trans) max_pixel_depth = 32; else max_pixel_depth = 24; } else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY) { if (max_pixel_depth < 8) max_pixel_depth = 8; if (png_ptr->num_trans) max_pixel_depth *= 2; } else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB) { if (png_ptr->num_trans) { max_pixel_depth *= 4; max_pixel_depth /= 3; } } } #endif #ifdef PNG_READ_FILLER_SUPPORTED if (png_ptr->transformations & (PNG_FILLER)) { if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) max_pixel_depth = 32; else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY) { if (max_pixel_depth <= 8) max_pixel_depth = 16; else max_pixel_depth = 32; } else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB) { if (max_pixel_depth <= 32) max_pixel_depth = 32; else max_pixel_depth = 64; } } #endif #ifdef PNG_READ_GRAY_TO_RGB_SUPPORTED if (png_ptr->transformations & PNG_GRAY_TO_RGB) { if ( #ifdef PNG_READ_EXPAND_SUPPORTED (png_ptr->num_trans && (png_ptr->transformations & PNG_EXPAND)) || #endif #ifdef PNG_READ_FILLER_SUPPORTED (png_ptr->transformations & (PNG_FILLER)) || #endif png_ptr->color_type == PNG_COLOR_TYPE_GRAY_ALPHA) { if (max_pixel_depth <= 16) max_pixel_depth = 32; else max_pixel_depth = 64; } else { if (max_pixel_depth <= 8) { if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA) max_pixel_depth = 32; else max_pixel_depth = 24; } else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA) max_pixel_depth = 64; else max_pixel_depth = 48; } } #endif #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) && \ defined(PNG_USER_TRANSFORM_PTR_SUPPORTED) if (png_ptr->transformations & PNG_USER_TRANSFORM) { int user_pixel_depth = png_ptr->user_transform_depth* png_ptr->user_transform_channels; if (user_pixel_depth > max_pixel_depth) max_pixel_depth=user_pixel_depth; } #endif /* Align the width on the next larger 8 pixels. Mainly used * for interlacing */ row_bytes = ((png_ptr->width + 7) & ~((png_uint_32)7)); /* Calculate the maximum bytes needed, adding a byte and a pixel * for safety's sake */ row_bytes = PNG_ROWBYTES(max_pixel_depth, row_bytes) + 1 + ((max_pixel_depth + 7) >> 3); #ifdef PNG_MAX_MALLOC_64K if (row_bytes > (png_uint_32)65536L) png_error(png_ptr, "This image requires a row greater than 64KB"); #endif if (row_bytes + 64 > png_ptr->old_big_row_buf_size) { png_free(png_ptr, png_ptr->big_row_buf); if (png_ptr->interlaced) png_ptr->big_row_buf = (png_bytep)png_calloc(png_ptr, row_bytes + 64); else png_ptr->big_row_buf = (png_bytep)png_malloc(png_ptr, row_bytes + 64); png_ptr->old_big_row_buf_size = row_bytes + 64; /* Use 32 bytes of padding before and after row_buf. */ png_ptr->row_buf = png_ptr->big_row_buf + 32; png_ptr->old_big_row_buf_size = row_bytes + 64; } #ifdef PNG_MAX_MALLOC_64K if ((png_uint_32)row_bytes + 1 > (png_uint_32)65536L) png_error(png_ptr, "This image requires a row greater than 64KB"); #endif if ((png_uint_32)row_bytes > (png_uint_32)(PNG_SIZE_MAX - 1)) png_error(png_ptr, "Row has too many bytes to allocate in memory."); if (row_bytes + 1 > png_ptr->old_prev_row_size) { png_free(png_ptr, png_ptr->prev_row); png_ptr->prev_row = (png_bytep)png_malloc(png_ptr, (png_uint_32)( row_bytes + 1)); png_memset_check(png_ptr, png_ptr->prev_row, 0, row_bytes + 1); png_ptr->old_prev_row_size = row_bytes + 1; } png_ptr->rowbytes = row_bytes; png_debug1(3, "width = %lu,", png_ptr->width); png_debug1(3, "height = %lu,", png_ptr->height); png_debug1(3, "iwidth = %lu,", png_ptr->iwidth); png_debug1(3, "num_rows = %lu,", png_ptr->num_rows); png_debug1(3, "rowbytes = %lu,", png_ptr->rowbytes); png_debug1(3, "irowbytes = %lu", PNG_ROWBYTES(png_ptr->pixel_depth, png_ptr->iwidth) + 1); png_ptr->flags |= PNG_FLAG_ROW_INIT; } Commit Message: third_party/libpng: update to 1.2.54 [email protected] BUG=560291 Review URL: https://codereview.chromium.org/1467263003 Cr-Commit-Position: refs/heads/master@{#362298} CWE ID: CWE-119 Target: 1 Example 2: Code: htmlIsScriptAttribute(const xmlChar *name) { unsigned int i; if (name == NULL) return(0); /* * all script attributes start with 'on' */ if ((name[0] != 'o') || (name[1] != 'n')) return(0); for (i = 0; i < sizeof(htmlScriptAttributes)/sizeof(htmlScriptAttributes[0]); i++) { if (xmlStrEqual(name, (const xmlChar *) htmlScriptAttributes[i])) return(1); } return(0); } 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 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void tcp_v6_send_response(const struct sock *sk, struct sk_buff *skb, u32 seq, u32 ack, u32 win, u32 tsval, u32 tsecr, int oif, struct tcp_md5sig_key *key, int rst, u8 tclass, __be32 label) { const struct tcphdr *th = tcp_hdr(skb); struct tcphdr *t1; struct sk_buff *buff; struct flowi6 fl6; struct net *net = sk ? sock_net(sk) : dev_net(skb_dst(skb)->dev); struct sock *ctl_sk = net->ipv6.tcp_sk; unsigned int tot_len = sizeof(struct tcphdr); struct dst_entry *dst; __be32 *topt; if (tsecr) tot_len += TCPOLEN_TSTAMP_ALIGNED; #ifdef CONFIG_TCP_MD5SIG if (key) tot_len += TCPOLEN_MD5SIG_ALIGNED; #endif buff = alloc_skb(MAX_HEADER + sizeof(struct ipv6hdr) + tot_len, GFP_ATOMIC); if (!buff) return; skb_reserve(buff, MAX_HEADER + sizeof(struct ipv6hdr) + tot_len); t1 = (struct tcphdr *) skb_push(buff, tot_len); skb_reset_transport_header(buff); /* Swap the send and the receive. */ memset(t1, 0, sizeof(*t1)); t1->dest = th->source; t1->source = th->dest; t1->doff = tot_len / 4; t1->seq = htonl(seq); t1->ack_seq = htonl(ack); t1->ack = !rst || !th->ack; t1->rst = rst; t1->window = htons(win); topt = (__be32 *)(t1 + 1); if (tsecr) { *topt++ = htonl((TCPOPT_NOP << 24) | (TCPOPT_NOP << 16) | (TCPOPT_TIMESTAMP << 8) | TCPOLEN_TIMESTAMP); *topt++ = htonl(tsval); *topt++ = htonl(tsecr); } #ifdef CONFIG_TCP_MD5SIG if (key) { *topt++ = htonl((TCPOPT_NOP << 24) | (TCPOPT_NOP << 16) | (TCPOPT_MD5SIG << 8) | TCPOLEN_MD5SIG); tcp_v6_md5_hash_hdr((__u8 *)topt, key, &ipv6_hdr(skb)->saddr, &ipv6_hdr(skb)->daddr, t1); } #endif memset(&fl6, 0, sizeof(fl6)); fl6.daddr = ipv6_hdr(skb)->saddr; fl6.saddr = ipv6_hdr(skb)->daddr; fl6.flowlabel = label; buff->ip_summed = CHECKSUM_PARTIAL; buff->csum = 0; __tcp_v6_send_check(buff, &fl6.saddr, &fl6.daddr); fl6.flowi6_proto = IPPROTO_TCP; if (rt6_need_strict(&fl6.daddr) && !oif) fl6.flowi6_oif = tcp_v6_iif(skb); else { if (!oif && netif_index_is_l3_master(net, skb->skb_iif)) oif = skb->skb_iif; fl6.flowi6_oif = oif; } fl6.flowi6_mark = IP6_REPLY_MARK(net, skb->mark); fl6.fl6_dport = t1->dest; fl6.fl6_sport = t1->source; fl6.flowi6_uid = sock_net_uid(net, sk && sk_fullsock(sk) ? sk : NULL); security_skb_classify_flow(skb, flowi6_to_flowi(&fl6)); /* Pass a socket to ip6_dst_lookup either it is for RST * Underlying function will use this to retrieve the network * namespace */ dst = ip6_dst_lookup_flow(ctl_sk, &fl6, NULL); if (!IS_ERR(dst)) { skb_dst_set(buff, dst); ip6_xmit(ctl_sk, buff, &fl6, fl6.flowi6_mark, NULL, tclass); TCP_INC_STATS(net, TCP_MIB_OUTSEGS); if (rst) TCP_INC_STATS(net, TCP_MIB_OUTRSTS); return; } kfree_skb(buff); } Commit Message: ipv6/dccp: do not inherit ipv6_mc_list from parent Like commit 657831ffc38e ("dccp/tcp: do not inherit mc_list from parent") we should clear ipv6_mc_list etc. for IPv6 sockets too. Cc: Eric Dumazet <[email protected]> Signed-off-by: Cong Wang <[email protected]> Acked-by: Eric Dumazet <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: PrintingContext::Result PrintingContextCairo::UpdatePrinterSettings( const DictionaryValue& job_settings, const PageRanges& ranges) { #if defined(OS_CHROMEOS) bool landscape = false; if (!job_settings.GetBoolean(kSettingLandscape, &landscape)) return OnError(); settings_.SetOrientation(landscape); settings_.ranges = ranges; return OK; #else DCHECK(!in_print_job_); if (!print_dialog_->UpdateSettings(job_settings, ranges)) return OnError(); return OK; #endif } Commit Message: Fix print preview workflow to reflect settings of selected printer. BUG=95110 TEST=none Review URL: http://codereview.chromium.org/7831041 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@102242 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399 Target: 1 Example 2: Code: static void setup_delta_attr_check(struct git_attr_check *check) { static struct git_attr *attr_delta; if (!attr_delta) attr_delta = git_attr("delta"); check[0].attr = attr_delta; } Commit Message: list-objects: pass full pathname to callbacks When we find a blob at "a/b/c", we currently pass this to our show_object_fn callbacks as two components: "a/b/" and "c". Callbacks which want the full value then call path_name(), which concatenates the two. But this is an inefficient interface; the path is a strbuf, and we could simply append "c" to it temporarily, then roll back the length, without creating a new copy. So we could improve this by teaching the callsites of path_name() this trick (and there are only 3). But we can also notice that no callback actually cares about the broken-down representation, and simply pass each callback the full path "a/b/c" as a string. The callback code becomes even simpler, then, as we do not have to worry about freeing an allocated buffer, nor rolling back our modification to the strbuf. This is theoretically less efficient, as some callbacks would not bother to format the final path component. But in practice this is not measurable. Since we use the same strbuf over and over, our work to grow it is amortized, and we really only pay to memcpy a few bytes. Signed-off-by: Jeff King <[email protected]> Signed-off-by: Junio C Hamano <[email protected]> CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void testRandomDecodeAfterClearFrameBufferCache(const char* gifFile) { SCOPED_TRACE(gifFile); RefPtr<SharedBuffer> data = readFile(gifFile); ASSERT_TRUE(data.get()); Vector<unsigned> baselineHashes; createDecodingBaseline(data.get(), &baselineHashes); size_t frameCount = baselineHashes.size(); OwnPtr<GIFImageDecoder> decoder = createDecoder(); decoder->setData(data.get(), true); for (size_t clearExceptFrame = 0; clearExceptFrame < frameCount; ++clearExceptFrame) { decoder->clearCacheExceptFrame(clearExceptFrame); const size_t skippingStep = 5; for (size_t i = 0; i < skippingStep; ++i) { for (size_t j = 0; j < frameCount; j += skippingStep) { SCOPED_TRACE(testing::Message() << "Random i:" << i << " j:" << j); ImageFrame* frame = decoder->frameBufferAtIndex(j); EXPECT_EQ(baselineHashes[j], hashSkBitmap(frame->getSkBitmap())); } } } } Commit Message: Fix handling of broken GIFs with weird frame sizes Code didn't handle well if a GIF frame has dimension greater than the "screen" dimension. This will break deferred image decoding. This change reports the size as final only when the first frame is encountered. Added a test to verify this behavior. Frame size reported by the decoder should be constant. BUG=437651 [email protected], [email protected] Review URL: https://codereview.chromium.org/813943003 git-svn-id: svn://svn.chromium.org/blink/trunk@188423 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: mp_join_print(netdissect_options *ndo, const u_char *opt, u_int opt_len, u_char flags) { const struct mp_join *mpj = (const struct mp_join *) opt; if (!(opt_len == 12 && flags & TH_SYN) && !(opt_len == 16 && (flags & (TH_SYN | TH_ACK)) == (TH_SYN | TH_ACK)) && !(opt_len == 24 && flags & TH_ACK)) return 0; if (opt_len != 24) { if (mpj->sub_b & MP_JOIN_B) ND_PRINT((ndo, " backup")); ND_PRINT((ndo, " id %u", mpj->addr_id)); } switch (opt_len) { case 12: /* SYN */ ND_PRINT((ndo, " token 0x%x" " nonce 0x%x", EXTRACT_32BITS(mpj->u.syn.token), EXTRACT_32BITS(mpj->u.syn.nonce))); break; case 16: /* SYN/ACK */ ND_PRINT((ndo, " hmac 0x%" PRIx64 " nonce 0x%x", EXTRACT_64BITS(mpj->u.synack.mac), EXTRACT_32BITS(mpj->u.synack.nonce))); break; case 24: {/* ACK */ size_t i; ND_PRINT((ndo, " hmac 0x")); for (i = 0; i < sizeof(mpj->u.ack.mac); ++i) ND_PRINT((ndo, "%02x", mpj->u.ack.mac[i])); } default: break; } return 1; } Commit Message: CVE-2017-13040/MPTCP: Clean up printing DSS suboption. Do the length checking inline; that means we print stuff up to the point at which we run out of option data. First check to make sure we have at least 4 bytes of option, so we have flags to check. This fixes a buffer over-read discovered by Kim Gwan Yeong. Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-125 Target: 1 Example 2: Code: DownloadPathReservationTrackerTest::GetLongNamePathInDownloadsDirectory( size_t repeat, const base::FilePath::CharType* suffix) { return GetPathInDownloadsDirectory( (base::FilePath::StringType(repeat, FILE_PATH_LITERAL('a')) + suffix).c_str()); } Commit Message: Fix OS_MACOS typos. Should be OS_MACOSX. BUG=163208 TEST=none Review URL: https://codereview.chromium.org/12829005 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@189130 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int get_crl_sk(X509_STORE_CTX *ctx, X509_CRL **pcrl, X509_CRL **pdcrl, X509 **pissuer, int *pscore, unsigned int *preasons, STACK_OF(X509_CRL) *crls) { int i, crl_score, best_score = *pscore; unsigned int reasons, best_reasons = 0; X509 *x = ctx->current_cert; X509_CRL *crl, *best_crl = NULL; X509 *crl_issuer = NULL, *best_crl_issuer = NULL; for (i = 0; i < sk_X509_CRL_num(crls); i++) { crl = sk_X509_CRL_value(crls, i); reasons = *preasons; crl_score = get_crl_score(ctx, &crl_issuer, &reasons, crl, x); if (crl_score < best_score) continue; /* If current CRL is equivalent use it if it is newer */ if (crl_score == best_score) { int day, sec; if (ASN1_TIME_diff(&day, &sec, X509_CRL_get_lastUpdate(best_crl), X509_CRL_get_lastUpdate(crl)) == 0) continue; /* * ASN1_TIME_diff never returns inconsistent signs for |day| * and |sec|. */ if (day <= 0 && sec <= 0) continue; } best_crl = crl; best_crl_issuer = crl_issuer; best_score = crl_score; best_reasons = reasons; } if (best_crl) { if (*pcrl) X509_CRL_free(*pcrl); *pcrl = best_crl; *pissuer = best_crl_issuer; *pscore = best_score; *preasons = best_reasons; CRYPTO_add(&best_crl->references, 1, CRYPTO_LOCK_X509_CRL); if (*pdcrl) { X509_CRL_free(*pdcrl); *pdcrl = NULL; } get_delta_sk(ctx, pdcrl, pscore, best_crl, crls); } if (best_score >= CRL_SCORE_VALID) return 1; return 0; } Commit Message: CWE ID: CWE-476 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void ff_jpeg2000_cleanup(Jpeg2000Component *comp, Jpeg2000CodingStyle *codsty) { int reslevelno, bandno, precno; for (reslevelno = 0; comp->reslevel && reslevelno < codsty->nreslevels; reslevelno++) { Jpeg2000ResLevel *reslevel = comp->reslevel + reslevelno; for (bandno = 0; bandno < reslevel->nbands; bandno++) { Jpeg2000Band *band = reslevel->band + bandno; for (precno = 0; precno < reslevel->num_precincts_x * reslevel->num_precincts_y; precno++) { Jpeg2000Prec *prec = band->prec + precno; av_freep(&prec->zerobits); av_freep(&prec->cblkincl); av_freep(&prec->cblk); } av_freep(&band->prec); } av_freep(&reslevel->band); } ff_dwt_destroy(&comp->dwt); av_freep(&comp->reslevel); av_freep(&comp->i_data); av_freep(&comp->f_data); } Commit Message: jpeg2000: fix dereferencing invalid pointers Found-by: Laurent Butti <[email protected]> Signed-off-by: Michael Niedermayer <[email protected]> CWE ID: Target: 1 Example 2: Code: static inline __be64 *metapointer(unsigned int height, const struct metapath *mp) { struct buffer_head *bh = mp->mp_bh[height]; unsigned int head_size = (height > 0) ? sizeof(struct gfs2_meta_header) : sizeof(struct gfs2_dinode); return ((__be64 *)(bh->b_data + head_size)) + mp->mp_list[height]; } Commit Message: GFS2: rewrite fallocate code to write blocks directly GFS2's fallocate code currently goes through the page cache. Since it's only writing to the end of the file or to holes in it, it doesn't need to, and it was causing issues on low memory environments. This patch pulls in some of Steve's block allocation work, and uses it to simply allocate the blocks for the file, and zero them out at allocation time. It provides a slight performance increase, and it dramatically simplifies the code. Signed-off-by: Benjamin Marzinski <[email protected]> Signed-off-by: Steven Whitehouse <[email protected]> CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: ExtensionInstallDialogView::ExtensionInstallDialogView( Profile* profile, content::PageNavigator* navigator, const ExtensionInstallPrompt::DoneCallback& done_callback, std::unique_ptr<ExtensionInstallPrompt::Prompt> prompt) : profile_(profile), navigator_(navigator), done_callback_(done_callback), prompt_(std::move(prompt)), container_(NULL), scroll_view_(NULL), handled_result_(false) { InitView(); } Commit Message: [Extensions UI] Initially disabled OK button for extension install prompts and enable them after a 500 ms time period. BUG=394518 Review-Url: https://codereview.chromium.org/2716353003 Cr-Commit-Position: refs/heads/master@{#461933} CWE ID: CWE-20 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static void avrc_msg_cback(uint8_t handle, uint8_t label, uint8_t cr, BT_HDR* p_pkt) { uint8_t opcode; tAVRC_MSG msg; uint8_t* p_data; uint8_t* p_begin; bool drop = false; bool do_free = true; BT_HDR* p_rsp = NULL; uint8_t* p_rsp_data; int xx; bool reject = false; const char* p_drop_msg = "dropped"; tAVRC_MSG_VENDOR* p_msg = &msg.vendor; if (cr == AVCT_CMD && (p_pkt->layer_specific & AVCT_DATA_CTRL && AVRC_PACKET_LEN < sizeof(p_pkt->len))) { /* Ignore the invalid AV/C command frame */ p_drop_msg = "dropped - too long AV/C cmd frame size"; osi_free(p_pkt); return; } if (cr == AVCT_REJ) { /* The peer thinks that this PID is no longer open - remove this handle */ /* */ osi_free(p_pkt); AVCT_RemoveConn(handle); return; } else if (cr == AVCT_RSP) { /* Received response. Stop command timeout timer */ AVRC_TRACE_DEBUG("AVRC: stopping timer (handle=0x%02x)", handle); alarm_cancel(avrc_cb.ccb_int[handle].tle); } p_data = (uint8_t*)(p_pkt + 1) + p_pkt->offset; memset(&msg, 0, sizeof(tAVRC_MSG)); if (p_pkt->layer_specific == AVCT_DATA_BROWSE) { opcode = AVRC_OP_BROWSE; msg.browse.hdr.ctype = cr; msg.browse.p_browse_data = p_data; msg.browse.browse_len = p_pkt->len; msg.browse.p_browse_pkt = p_pkt; } else { msg.hdr.ctype = p_data[0] & AVRC_CTYPE_MASK; AVRC_TRACE_DEBUG("%s handle:%d, ctype:%d, offset:%d, len: %d", __func__, handle, msg.hdr.ctype, p_pkt->offset, p_pkt->len); msg.hdr.subunit_type = (p_data[1] & AVRC_SUBTYPE_MASK) >> AVRC_SUBTYPE_SHIFT; msg.hdr.subunit_id = p_data[1] & AVRC_SUBID_MASK; opcode = p_data[2]; } if (((avrc_cb.ccb[handle].control & AVRC_CT_TARGET) && (cr == AVCT_CMD)) || ((avrc_cb.ccb[handle].control & AVRC_CT_CONTROL) && (cr == AVCT_RSP))) { switch (opcode) { case AVRC_OP_UNIT_INFO: if (cr == AVCT_CMD) { /* send the response to the peer */ p_rsp = avrc_copy_packet(p_pkt, AVRC_OP_UNIT_INFO_RSP_LEN); p_rsp_data = avrc_get_data_ptr(p_rsp); *p_rsp_data = AVRC_RSP_IMPL_STBL; /* check & set the offset. set response code, set subunit_type & subunit_id, set AVRC_OP_UNIT_INFO */ /* 3 bytes: ctype, subunit*, opcode */ p_rsp_data += AVRC_AVC_HDR_SIZE; *p_rsp_data++ = 7; /* Panel subunit & id=0 */ *p_rsp_data++ = (AVRC_SUB_PANEL << AVRC_SUBTYPE_SHIFT); AVRC_CO_ID_TO_BE_STREAM(p_rsp_data, avrc_cb.ccb[handle].company_id); p_rsp->len = (uint16_t)(p_rsp_data - (uint8_t*)(p_rsp + 1) - p_rsp->offset); cr = AVCT_RSP; p_drop_msg = "auto respond"; } else { /* parse response */ p_data += 4; /* 3 bytes: ctype, subunit*, opcode + octet 3 (is 7)*/ msg.unit.unit_type = (*p_data & AVRC_SUBTYPE_MASK) >> AVRC_SUBTYPE_SHIFT; msg.unit.unit = *p_data & AVRC_SUBID_MASK; p_data++; AVRC_BE_STREAM_TO_CO_ID(msg.unit.company_id, p_data); } break; case AVRC_OP_SUB_INFO: if (cr == AVCT_CMD) { /* send the response to the peer */ p_rsp = avrc_copy_packet(p_pkt, AVRC_OP_SUB_UNIT_INFO_RSP_LEN); p_rsp_data = avrc_get_data_ptr(p_rsp); *p_rsp_data = AVRC_RSP_IMPL_STBL; /* check & set the offset. set response code, set (subunit_type & subunit_id), set AVRC_OP_SUB_INFO, set (page & extention code) */ p_rsp_data += 4; /* Panel subunit & id=0 */ *p_rsp_data++ = (AVRC_SUB_PANEL << AVRC_SUBTYPE_SHIFT); memset(p_rsp_data, AVRC_CMD_OPRND_PAD, AVRC_SUBRSP_OPRND_BYTES); p_rsp_data += AVRC_SUBRSP_OPRND_BYTES; p_rsp->len = (uint16_t)(p_rsp_data - (uint8_t*)(p_rsp + 1) - p_rsp->offset); cr = AVCT_RSP; p_drop_msg = "auto responded"; } else { /* parse response */ p_data += AVRC_AVC_HDR_SIZE; /* 3 bytes: ctype, subunit*, opcode */ msg.sub.page = (*p_data++ >> AVRC_SUB_PAGE_SHIFT) & AVRC_SUB_PAGE_MASK; xx = 0; while (*p_data != AVRC_CMD_OPRND_PAD && xx < AVRC_SUB_TYPE_LEN) { msg.sub.subunit_type[xx] = *p_data++ >> AVRC_SUBTYPE_SHIFT; if (msg.sub.subunit_type[xx] == AVRC_SUB_PANEL) msg.sub.panel = true; xx++; } } break; case AVRC_OP_VENDOR: { p_data = (uint8_t*)(p_pkt + 1) + p_pkt->offset; p_begin = p_data; if (p_pkt->len < AVRC_VENDOR_HDR_SIZE) /* 6 = ctype, subunit*, opcode & CO_ID */ { if (cr == AVCT_CMD) reject = true; else drop = true; break; } p_data += AVRC_AVC_HDR_SIZE; /* skip the first 3 bytes: ctype, subunit*, opcode */ AVRC_BE_STREAM_TO_CO_ID(p_msg->company_id, p_data); p_msg->p_vendor_data = p_data; p_msg->vendor_len = p_pkt->len - (p_data - p_begin); uint8_t drop_code = 0; if (p_msg->company_id == AVRC_CO_METADATA) { /* Validate length for metadata message */ if (p_pkt->len < (AVRC_VENDOR_HDR_SIZE + AVRC_MIN_META_HDR_SIZE)) { if (cr == AVCT_CMD) reject = true; else drop = true; break; } /* Check+handle fragmented messages */ drop_code = avrc_proc_far_msg(handle, label, cr, &p_pkt, p_msg); if (drop_code > 0) drop = true; } if (drop_code > 0) { if (drop_code != 4) do_free = false; switch (drop_code) { case 1: p_drop_msg = "sent_frag"; break; case 2: p_drop_msg = "req_cont"; break; case 3: p_drop_msg = "sent_frag3"; break; case 4: p_drop_msg = "sent_frag_free"; break; default: p_drop_msg = "sent_fragd"; } } /* If vendor response received, and did not ask for continuation */ /* then check queue for addition commands to send */ if ((cr == AVCT_RSP) && (drop_code != 2)) { avrc_send_next_vendor_cmd(handle); } } break; case AVRC_OP_PASS_THRU: if (p_pkt->len < 5) /* 3 bytes: ctype, subunit*, opcode & op_id & len */ { if (cr == AVCT_CMD) reject = true; else drop = true; break; } p_data += AVRC_AVC_HDR_SIZE; /* skip the first 3 bytes: ctype, subunit*, opcode */ msg.pass.op_id = (AVRC_PASS_OP_ID_MASK & *p_data); if (AVRC_PASS_STATE_MASK & *p_data) msg.pass.state = true; else msg.pass.state = false; p_data++; msg.pass.pass_len = *p_data++; if (msg.pass.pass_len != p_pkt->len - 5) msg.pass.pass_len = p_pkt->len - 5; if (msg.pass.pass_len) msg.pass.p_pass_data = p_data; else msg.pass.p_pass_data = NULL; break; case AVRC_OP_BROWSE: /* If browse response received, then check queue for addition commands * to send */ if (cr == AVCT_RSP) { avrc_send_next_vendor_cmd(handle); } break; default: if ((avrc_cb.ccb[handle].control & AVRC_CT_TARGET) && (cr == AVCT_CMD)) { /* reject unsupported opcode */ reject = true; } drop = true; break; } } else /* drop the event */ { if (opcode != AVRC_OP_BROWSE) drop = true; } if (reject) { /* reject unsupported opcode */ p_rsp = avrc_copy_packet(p_pkt, AVRC_OP_REJ_MSG_LEN); p_rsp_data = avrc_get_data_ptr(p_rsp); *p_rsp_data = AVRC_RSP_REJ; p_drop_msg = "rejected"; cr = AVCT_RSP; drop = true; } if (p_rsp) { /* set to send response right away */ AVCT_MsgReq(handle, label, cr, p_rsp); drop = true; } if (!drop) { msg.hdr.opcode = opcode; avrc_cb.ccb[handle].msg_cback.Run(handle, label, opcode, &msg); } else { AVRC_TRACE_WARNING("%s %s msg handle:%d, control:%d, cr:%d, opcode:x%x", __func__, p_drop_msg, handle, avrc_cb.ccb[handle].control, cr, opcode); } if (opcode == AVRC_OP_BROWSE && msg.browse.p_browse_pkt == NULL) { do_free = false; } if (do_free) osi_free(p_pkt); } Commit Message: Add missing AVRCP message length checks inside avrc_msg_cback Explicitly check the length of the received message before accessing the data. Bug: 111803925 Bug: 79883824 Test: POC scripts Change-Id: I00b1c6bd6dd7e18ac2c469ef2032c7ff10dcaecb Merged-In: I00b1c6bd6dd7e18ac2c469ef2032c7ff10dcaecb (cherry picked from commit 282deb3e27407aaa88b8ddbdbd7bb7d56ddc635f) (cherry picked from commit 007868d05f4b761842c7345161aeda6fd40dd245) CWE ID: CWE-125 Target: 1 Example 2: Code: Ins_RTDG( TT_ExecContext exc ) { exc->GS.round_state = TT_Round_To_Double_Grid; exc->func_round = (TT_Round_Func)Round_To_Double_Grid; } Commit Message: CWE ID: CWE-476 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: virtual bool SetImeConfig(const std::string& section, const std::string& config_name, const ImeConfigValue& value) { return false; } 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 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void bta_hl_co_put_rx_data (UINT8 app_id, tBTA_HL_MDL_HANDLE mdl_handle, UINT16 data_size, UINT8 *p_data, UINT16 evt) { UINT8 app_idx, mcl_idx, mdl_idx; btif_hl_mdl_cb_t *p_dcb; tBTA_HL_STATUS status = BTA_HL_STATUS_FAIL; int r; BTIF_TRACE_DEBUG("%s app_id=%d mdl_handle=0x%x data_size=%d", __FUNCTION__,app_id, mdl_handle, data_size); if (btif_hl_find_mdl_idx_using_handle(mdl_handle, &app_idx, &mcl_idx, &mdl_idx)) { p_dcb = BTIF_HL_GET_MDL_CB_PTR(app_idx, mcl_idx, mdl_idx); if ((p_dcb->p_rx_pkt = (UINT8 *)btif_hl_get_buf(data_size)) != NULL) { memcpy(p_dcb->p_rx_pkt, p_data, data_size); if (p_dcb->p_scb) { BTIF_TRACE_DEBUG("app_idx=%d mcl_idx=0x%x mdl_idx=0x%x data_size=%d", app_idx, mcl_idx, mdl_idx, data_size); r = send(p_dcb->p_scb->socket_id[1], p_dcb->p_rx_pkt, data_size, 0); if (r == data_size) { BTIF_TRACE_DEBUG("socket send success data_size=%d", data_size); status = BTA_HL_STATUS_OK; } else { BTIF_TRACE_ERROR("socket send failed r=%d data_size=%d",r, data_size); } } btif_hl_free_buf((void **) &p_dcb->p_rx_pkt); } } bta_hl_ci_put_rx_data(mdl_handle, status, evt); } 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 Target: 1 Example 2: Code: static inline void rb_inc_page(struct ring_buffer_per_cpu *cpu_buffer, struct buffer_page **bpage) { struct list_head *p = rb_list_head((*bpage)->list.next); *bpage = list_entry(p, struct buffer_page, list); } Commit Message: ring-buffer: Prevent overflow of size in ring_buffer_resize() If the size passed to ring_buffer_resize() is greater than MAX_LONG - BUF_PAGE_SIZE then the DIV_ROUND_UP() will return zero. Here's the details: # echo 18014398509481980 > /sys/kernel/debug/tracing/buffer_size_kb tracing_entries_write() processes this and converts kb to bytes. 18014398509481980 << 10 = 18446744073709547520 and this is passed to ring_buffer_resize() as unsigned long size. size = DIV_ROUND_UP(size, BUF_PAGE_SIZE); Where DIV_ROUND_UP(a, b) is (a + b - 1)/b BUF_PAGE_SIZE is 4080 and here 18446744073709547520 + 4080 - 1 = 18446744073709551599 where 18446744073709551599 is still smaller than 2^64 2^64 - 18446744073709551599 = 17 But now 18446744073709551599 / 4080 = 4521260802379792 and size = size * 4080 = 18446744073709551360 This is checked to make sure its still greater than 2 * 4080, which it is. Then we convert to the number of buffer pages needed. nr_page = DIV_ROUND_UP(size, BUF_PAGE_SIZE) but this time size is 18446744073709551360 and 2^64 - (18446744073709551360 + 4080 - 1) = -3823 Thus it overflows and the resulting number is less than 4080, which makes 3823 / 4080 = 0 an nr_pages is set to this. As we already checked against the minimum that nr_pages may be, this causes the logic to fail as well, and we crash the kernel. There's no reason to have the two DIV_ROUND_UP() (that's just result of historical code changes), clean up the code and fix this bug. Cc: [email protected] # 3.5+ Fixes: 83f40318dab00 ("ring-buffer: Make removal of ring buffer pages atomic") Signed-off-by: Steven Rostedt <[email protected]> CWE ID: CWE-190 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: ZEND_API int zend_update_static_property_bool(zend_class_entry *scope, const char *name, int name_length, long value TSRMLS_DC) /* {{{ */ { zval *tmp; ALLOC_ZVAL(tmp); Z_UNSET_ISREF_P(tmp); Z_SET_REFCOUNT_P(tmp, 0); ZVAL_BOOL(tmp, value); return zend_update_static_property(scope, name, name_length, tmp TSRMLS_CC); } /* }}} */ Commit Message: CWE ID: CWE-416 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static const char *parse_string( cJSON *item, const char *str ) { const char *ptr = str + 1; char *ptr2; char *out; int len = 0; unsigned uc, uc2; if ( *str != '\"' ) { /* Not a string! */ ep = str; return 0; } /* Skip escaped quotes. */ while ( *ptr != '\"' && *ptr && ++len ) if ( *ptr++ == '\\' ) ptr++; if ( ! ( out = (char*) cJSON_malloc( len + 1 ) ) ) return 0; ptr = str + 1; ptr2 = out; while ( *ptr != '\"' && *ptr ) { if ( *ptr != '\\' ) *ptr2++ = *ptr++; else { ptr++; switch ( *ptr ) { case 'b': *ptr2++ ='\b'; break; case 'f': *ptr2++ ='\f'; break; case 'n': *ptr2++ ='\n'; break; case 'r': *ptr2++ ='\r'; break; case 't': *ptr2++ ='\t'; break; case 'u': /* Transcode utf16 to utf8. */ /* Get the unicode char. */ sscanf( ptr + 1,"%4x", &uc ); ptr += 4; /* Check for invalid. */ if ( ( uc >= 0xDC00 && uc <= 0xDFFF ) || uc == 0 ) break; /* UTF16 surrogate pairs. */ if ( uc >= 0xD800 && uc <= 0xDBFF ) { if ( ptr[1] != '\\' || ptr[2] != 'u' ) /* Missing second-half of surrogate. */ break; sscanf( ptr + 3, "%4x", &uc2 ); ptr += 6; if ( uc2 < 0xDC00 || uc2 > 0xDFFF ) /* Invalid second-half of surrogate. */ break; uc = 0x10000 | ( ( uc & 0x3FF ) << 10 ) | ( uc2 & 0x3FF ); } len = 4; if ( uc < 0x80 ) len = 1; else if ( uc < 0x800 ) len = 2; else if ( uc < 0x10000 ) len = 3; ptr2 += len; switch ( len ) { case 4: *--ptr2 = ( ( uc | 0x80) & 0xBF ); uc >>= 6; case 3: *--ptr2 = ( ( uc | 0x80) & 0xBF ); uc >>= 6; case 2: *--ptr2 = ( ( uc | 0x80) & 0xBF ); uc >>= 6; case 1: *--ptr2 = ( uc | firstByteMark[len] ); } ptr2 += len; break; default: *ptr2++ = *ptr; break; } ++ptr; } } *ptr2 = 0; if ( *ptr == '\"' ) ++ptr; item->valuestring = out; item->type = cJSON_String; return ptr; } Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a malformed JSON string was passed on the control channel. This issue, present in the cJSON library, was already fixed upstream, so was addressed here in iperf3 by importing a newer version of cJSON (plus local ESnet modifications). Discovered and reported by Dave McDaniel, Cisco Talos. Based on a patch by @dopheide-esnet, with input from @DaveGamble. Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001, CVE-2016-4303 (cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40) Signed-off-by: Bruce A. Mah <[email protected]> CWE ID: CWE-119 Target: 1 Example 2: Code: GLuint GetBufferId(const Buffer* buffer) { if (buffer) return buffer->service_id(); return 0; } Commit Message: Fix tabs sharing TEXTURE_2D_ARRAY/TEXTURE_3D data. In linux and android, we are seeing an issue where texture data from one tab overwrites the texture data of another tab. This is happening for apps which are using webgl2 texture of type TEXTURE_2D_ARRAY/TEXTURE_3D. Due to a bug in virtual context save/restore code for above texture formats, the texture data is not properly restored while switching tabs. Hence texture data from one tab overwrites other. This CL has fix for that issue, an update for existing test expectations and a new unit test for this bug. Bug: 788448 Cq-Include-Trybots: master.tryserver.chromium.android:android_optional_gpu_tests_rel;master.tryserver.chromium.linux:linux_optional_gpu_tests_rel;master.tryserver.chromium.mac:mac_optional_gpu_tests_rel;master.tryserver.chromium.win:win_optional_gpu_tests_rel Change-Id: Ie933984cdd2d1381f42eb4638f730c8245207a28 Reviewed-on: https://chromium-review.googlesource.com/930327 Reviewed-by: Zhenyao Mo <[email protected]> Commit-Queue: vikas soni <[email protected]> Cr-Commit-Position: refs/heads/master@{#539111} CWE ID: CWE-200 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void ScriptLoader::executeScript(const ScriptSourceCode& sourceCode) { ASSERT(m_alreadyStarted); if (sourceCode.isEmpty()) return; RefPtr<Document> elementDocument(m_element->document()); RefPtr<Document> contextDocument = elementDocument->contextDocument().get(); if (!contextDocument) return; LocalFrame* frame = contextDocument->frame(); bool shouldBypassMainWorldContentSecurityPolicy = (frame && frame->script().shouldBypassMainWorldContentSecurityPolicy()) || elementDocument->contentSecurityPolicy()->allowScriptNonce(m_element->fastGetAttribute(HTMLNames::nonceAttr)) || elementDocument->contentSecurityPolicy()->allowScriptHash(sourceCode.source()); if (!m_isExternalScript && (!shouldBypassMainWorldContentSecurityPolicy && !elementDocument->contentSecurityPolicy()->allowInlineScript(elementDocument->url(), m_startLineNumber))) return; if (m_isExternalScript && m_resource && !m_resource->mimeTypeAllowedByNosniff()) { contextDocument->addConsoleMessage(SecurityMessageSource, ErrorMessageLevel, "Refused to execute script from '" + m_resource->url().elidedString() + "' because its MIME type ('" + m_resource->mimeType() + "') is not executable, and strict MIME type checking is enabled."); return; } if (frame) { const bool isImportedScript = contextDocument != elementDocument; IgnoreDestructiveWriteCountIncrementer ignoreDestructiveWriteCountIncrementer(m_isExternalScript || isImportedScript ? contextDocument.get() : 0); if (isHTMLScriptLoader(m_element)) contextDocument->pushCurrentScript(toHTMLScriptElement(m_element)); AccessControlStatus corsCheck = NotSharableCrossOrigin; if (sourceCode.resource() && sourceCode.resource()->passesAccessControlCheck(m_element->document().securityOrigin())) corsCheck = SharableCrossOrigin; frame->script().executeScriptInMainWorld(sourceCode, corsCheck); if (isHTMLScriptLoader(m_element)) { ASSERT(contextDocument->currentScript() == m_element); contextDocument->popCurrentScript(); } } } Commit Message: Apply 'x-content-type-options' check to dynamically inserted script. BUG=348581 Review URL: https://codereview.chromium.org/185593011 git-svn-id: svn://svn.chromium.org/blink/trunk@168570 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-362 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: SPL_METHOD(SplFileObject, current) { 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.file.current_line && !intern->u.file.current_zval) { spl_filesystem_file_read_line(getThis(), intern, 1 TSRMLS_CC); } if (intern->u.file.current_line && (!SPL_HAS_FLAG(intern->flags, SPL_FILE_OBJECT_READ_CSV) || !intern->u.file.current_zval)) { RETURN_STRINGL(intern->u.file.current_line, intern->u.file.current_line_len, 1); } else if (intern->u.file.current_zval) { RETURN_ZVAL(intern->u.file.current_zval, 1, 0); } RETURN_FALSE; } /* }}} */ /* {{{ proto int SplFileObject::key() Commit Message: Fix bug #72262 - do not overflow int CWE ID: CWE-190 Target: 1 Example 2: Code: xsltNewStackElem(xsltTransformContextPtr ctxt) { xsltStackElemPtr ret; /* * Reuse a stack item from the cache if available. */ if (ctxt && ctxt->cache->stackItems) { ret = ctxt->cache->stackItems; ctxt->cache->stackItems = ret->next; ret->next = NULL; ctxt->cache->nbStackItems--; #ifdef XSLT_DEBUG_PROFILE_CACHE ctxt->cache->dbgReusedVars++; #endif return(ret); } ret = (xsltStackElemPtr) xmlMalloc(sizeof(xsltStackElem)); if (ret == NULL) { xsltTransformError(NULL, NULL, NULL, "xsltNewStackElem : malloc failed\n"); return(NULL); } memset(ret, 0, sizeof(xsltStackElem)); ret->context = ctxt; return(ret); } Commit Message: Roll libxslt to 891681e3e948f31732229f53cb6db7215f740fc7 BUG=583156,583171 Review URL: https://codereview.chromium.org/1853083002 Cr-Commit-Position: refs/heads/master@{#385338} CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int spl_filesystem_file_call(spl_filesystem_object *intern, zend_function *func_ptr, int pass_num_args, zval *return_value, zval *arg2 TSRMLS_DC) /* {{{ */ { zend_fcall_info fci; zend_fcall_info_cache fcic; zval z_fname; zval * zresource_ptr = &intern->u.file.zresource, *retval; int result; int num_args = pass_num_args + (arg2 ? 2 : 1); zval ***params = (zval***)safe_emalloc(num_args, sizeof(zval**), 0); params[0] = &zresource_ptr; if (arg2) { params[1] = &arg2; } zend_get_parameters_array_ex(pass_num_args, params+(arg2 ? 2 : 1)); ZVAL_STRING(&z_fname, func_ptr->common.function_name, 0); fci.size = sizeof(fci); fci.function_table = EG(function_table); fci.object_ptr = NULL; fci.function_name = &z_fname; fci.retval_ptr_ptr = &retval; fci.param_count = num_args; fci.params = params; fci.no_separation = 1; fci.symbol_table = NULL; fcic.initialized = 1; fcic.function_handler = func_ptr; fcic.calling_scope = NULL; fcic.called_scope = NULL; fcic.object_ptr = NULL; result = zend_call_function(&fci, &fcic TSRMLS_CC); if (result == FAILURE) { RETVAL_FALSE; } else { ZVAL_ZVAL(return_value, retval, 1, 1); } efree(params); return result; } /* }}} */ Commit Message: Fix bug #72262 - do not overflow int CWE ID: CWE-190 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: DWORD WtsSessionProcessDelegate::GetExitCode() { if (!core_) return CONTROL_C_EXIT; return core_->GetExitCode(); } Commit Message: Validate and report peer's PID to WorkerProcessIpcDelegate so it will be able to duplicate handles to and from the worker process. As a side effect WorkerProcessLauncher::Delegate is now responsible for retrieving the client's PID and deciding whether a launch failed due to a permanent error condition. BUG=134694 Review URL: https://chromiumcodereview.appspot.com/11143025 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@162778 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399 Target: 1 Example 2: Code: static int em_sysexit(struct x86_emulate_ctxt *ctxt) { const struct x86_emulate_ops *ops = ctxt->ops; struct desc_struct cs, ss; u64 msr_data, rcx, rdx; int usermode; u16 cs_sel = 0, ss_sel = 0; /* inject #GP if in real mode or Virtual 8086 mode */ if (ctxt->mode == X86EMUL_MODE_REAL || ctxt->mode == X86EMUL_MODE_VM86) return emulate_gp(ctxt, 0); setup_syscalls_segments(ctxt, &cs, &ss); if ((ctxt->rex_prefix & 0x8) != 0x0) usermode = X86EMUL_MODE_PROT64; else usermode = X86EMUL_MODE_PROT32; rcx = reg_read(ctxt, VCPU_REGS_RCX); rdx = reg_read(ctxt, VCPU_REGS_RDX); cs.dpl = 3; ss.dpl = 3; ops->get_msr(ctxt, MSR_IA32_SYSENTER_CS, &msr_data); switch (usermode) { case X86EMUL_MODE_PROT32: cs_sel = (u16)(msr_data + 16); if ((msr_data & 0xfffc) == 0x0) return emulate_gp(ctxt, 0); ss_sel = (u16)(msr_data + 24); rcx = (u32)rcx; rdx = (u32)rdx; break; case X86EMUL_MODE_PROT64: cs_sel = (u16)(msr_data + 32); if (msr_data == 0x0) return emulate_gp(ctxt, 0); ss_sel = cs_sel + 8; cs.d = 0; cs.l = 1; if (is_noncanonical_address(rcx) || is_noncanonical_address(rdx)) return emulate_gp(ctxt, 0); break; } cs_sel |= SELECTOR_RPL_MASK; ss_sel |= SELECTOR_RPL_MASK; ops->set_segment(ctxt, cs_sel, &cs, 0, VCPU_SREG_CS); ops->set_segment(ctxt, ss_sel, &ss, 0, VCPU_SREG_SS); ctxt->_eip = rdx; *reg_write(ctxt, VCPU_REGS_RSP) = rcx; return X86EMUL_CONTINUE; } Commit Message: KVM: x86: SYSENTER emulation is broken SYSENTER emulation is broken in several ways: 1. It misses the case of 16-bit code segments completely (CVE-2015-0239). 2. MSR_IA32_SYSENTER_CS is checked in 64-bit mode incorrectly (bits 0 and 1 can still be set without causing #GP). 3. MSR_IA32_SYSENTER_EIP and MSR_IA32_SYSENTER_ESP are not masked in legacy-mode. 4. There is some unneeded code. Fix it. Cc: [email protected] Signed-off-by: Nadav Amit <[email protected]> Signed-off-by: Paolo Bonzini <[email protected]> CWE ID: CWE-362 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: newEntry(struct rx_call *call, char aname[], afs_int32 flag, afs_int32 oid, afs_int32 *aid, afs_int32 *cid) { afs_int32 code; struct ubik_trans *tt; int admin; char cname[PR_MAXNAMELEN]; stolower(aname); code = Initdb(); if (code) return code; code = ubik_BeginTrans(dbase, UBIK_WRITETRANS, &tt); if (code) return code; code = ubik_SetLock(tt, 1, 1, LOCKWRITE); if (code) ABORT_WITH(tt, code); code = read_DbHeader(tt); if (code) ABORT_WITH(tt, code); /* this is for cross-cell self registration. It is not added in the * SPR_INewEntry because we want self-registration to only do * automatic id assignment. */ code = WhoIsThisWithName(call, tt, cid, cname); if (code != 2) { /* 2 specifies that this is a foreign cell request */ if (code) ABORT_WITH(tt, PRPERM); admin = IsAMemberOf(tt, *cid, SYSADMINID); } else { admin = ((!restricted && !strcmp(aname, cname))) || IsAMemberOf(tt, *cid, SYSADMINID); oid = *cid = SYSADMINID; } if (!CreateOK(tt, *cid, oid, flag, admin)) ABORT_WITH(tt, PRPERM); if (code) return code; return PRSUCCESS; } Commit Message: CWE ID: CWE-284 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: email_close(FILE *mailer) { char *temp; mode_t prev_umask; priv_state priv; char *customSig; if ( mailer == NULL ) { return; } /* Want the letter to come from "condor" if possible */ priv = set_condor_priv(); customSig = NULL; if ((customSig = param("EMAIL_SIGNATURE")) != NULL) { fprintf( mailer, "\n\n"); fprintf( mailer, customSig); fprintf( mailer, "\n"); free(customSig); } else { /* Put a signature on the bottom of the email */ fprintf( mailer, "\n\n-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\n" ); fprintf( mailer, "Questions about this message or Condor in general?\n" ); /* See if there's an address users should use for help */ temp = param( "CONDOR_SUPPORT_EMAIL" ); if( ! temp ) { temp = param( "CONDOR_ADMIN" ); } if( temp ) { fprintf( mailer, "Email address of the local Condor administrator: " "%s\n", temp ); free( temp ); } fprintf( mailer, "The Official Condor Homepage is " "http://www.cs.wisc.edu/condor\n" ); } fflush(mailer); /* there are some oddities with how pclose can close a file. In some arches, pclose will create temp files for locking and they need to be of the correct perms in order to be deleted. So the umask is set to something useable for the close operation. -pete 9/11/99 */ prev_umask = umask(022); /* ** we fclose() on UNIX, pclose on win32 */ #if defined(WIN32) if (EMAIL_FINAL_COMMAND == NULL) { my_pclose( mailer ); } else { char *email_filename = NULL; /* Should this be a pclose??? -Erik 9/21/00 */ fclose( mailer ); dprintf(D_FULLDEBUG,"Sending email via system(%s)\n", EMAIL_FINAL_COMMAND); system(EMAIL_FINAL_COMMAND); if ( (email_filename=strrchr(EMAIL_FINAL_COMMAND,'<')) ) { email_filename++; /* go past the "<" */ email_filename++; /* go past the space after the < */ if ( unlink(email_filename) == -1 ) { dprintf(D_ALWAYS,"email_close: cannot unlink temp file %s\n", email_filename); } } free(EMAIL_FINAL_COMMAND); EMAIL_FINAL_COMMAND = NULL; } #else (void)fclose( mailer ); #endif umask(prev_umask); /* Set priv state back */ set_priv(priv); } Commit Message: CWE ID: CWE-134 Target: 1 Example 2: Code: static int printmyrights(const char *extname, const mbentry_t *mbentry) { int rights = 0; char str[ACL_MAXSTR]; rights = cyrus_acl_myrights(imapd_authstate, mbentry->acl); /* Add in implicit rights */ if (imapd_userisadmin) { rights |= ACL_LOOKUP|ACL_ADMIN; } else if (mboxname_userownsmailbox(imapd_userid, mbentry->name)) { rights |= config_implicitrights; } if (!(rights & (ACL_LOOKUP|ACL_READ|ACL_INSERT|ACL_CREATE|ACL_DELETEMBOX|ACL_ADMIN))) { return IMAP_MAILBOX_NONEXISTENT; } prot_printf(imapd_out, "* MYRIGHTS "); prot_printastring(imapd_out, extname); prot_printf(imapd_out, " "); prot_printastring(imapd_out, cyrus_acl_masktostr(rights, str)); prot_printf(imapd_out, "\r\n"); return 0; } Commit Message: imapd: check for isadmin BEFORE parsing sync lines CWE ID: CWE-20 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int64_t http_seek_internal(URLContext *h, int64_t off, int whence, int force_reconnect) { HTTPContext *s = h->priv_data; URLContext *old_hd = s->hd; int64_t old_off = s->off; uint8_t old_buf[BUFFER_SIZE]; int old_buf_size, ret; AVDictionary *options = NULL; if (whence == AVSEEK_SIZE) return s->filesize; else if (!force_reconnect && ((whence == SEEK_CUR && off == 0) || (whence == SEEK_SET && off == s->off))) return s->off; else if ((s->filesize == -1 && whence == SEEK_END)) return AVERROR(ENOSYS); if (whence == SEEK_CUR) off += s->off; else if (whence == SEEK_END) off += s->filesize; else if (whence != SEEK_SET) return AVERROR(EINVAL); if (off < 0) return AVERROR(EINVAL); s->off = off; if (s->off && h->is_streamed) return AVERROR(ENOSYS); /* we save the old context in case the seek fails */ old_buf_size = s->buf_end - s->buf_ptr; memcpy(old_buf, s->buf_ptr, old_buf_size); s->hd = NULL; /* if it fails, continue on old connection */ if ((ret = http_open_cnx(h, &options)) < 0) { av_dict_free(&options); memcpy(s->buffer, old_buf, old_buf_size); s->buf_ptr = s->buffer; s->buf_end = s->buffer + old_buf_size; s->hd = old_hd; s->off = old_off; return ret; } av_dict_free(&options); ffurl_close(old_hd); return off; } Commit Message: http: make length/offset-related variables unsigned. Fixes #5992, reported and found by Paul Cher <[email protected]>. CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: SYSCALL_DEFINE4(semtimedop, int, semid, struct sembuf __user *, tsops, unsigned, nsops, const struct timespec __user *, timeout) { int error = -EINVAL; struct sem_array *sma; struct sembuf fast_sops[SEMOPM_FAST]; struct sembuf* sops = fast_sops, *sop; struct sem_undo *un; int undos = 0, alter = 0, max; struct sem_queue queue; unsigned long jiffies_left = 0; struct ipc_namespace *ns; struct list_head tasks; ns = current->nsproxy->ipc_ns; if (nsops < 1 || semid < 0) return -EINVAL; if (nsops > ns->sc_semopm) return -E2BIG; if(nsops > SEMOPM_FAST) { sops = kmalloc(sizeof(*sops)*nsops,GFP_KERNEL); if(sops==NULL) return -ENOMEM; } if (copy_from_user (sops, tsops, nsops * sizeof(*tsops))) { error=-EFAULT; goto out_free; } if (timeout) { struct timespec _timeout; if (copy_from_user(&_timeout, timeout, sizeof(*timeout))) { error = -EFAULT; goto out_free; } if (_timeout.tv_sec < 0 || _timeout.tv_nsec < 0 || _timeout.tv_nsec >= 1000000000L) { error = -EINVAL; goto out_free; } jiffies_left = timespec_to_jiffies(&_timeout); } max = 0; for (sop = sops; sop < sops + nsops; sop++) { if (sop->sem_num >= max) max = sop->sem_num; if (sop->sem_flg & SEM_UNDO) undos = 1; if (sop->sem_op != 0) alter = 1; } if (undos) { un = find_alloc_undo(ns, semid); if (IS_ERR(un)) { error = PTR_ERR(un); goto out_free; } } else un = NULL; INIT_LIST_HEAD(&tasks); rcu_read_lock(); sma = sem_obtain_object_check(ns, semid); if (IS_ERR(sma)) { if (un) rcu_read_unlock(); error = PTR_ERR(sma); goto out_free; } error = -EFBIG; if (max >= sma->sem_nsems) { rcu_read_unlock(); goto out_wakeup; } error = -EACCES; if (ipcperms(ns, &sma->sem_perm, alter ? S_IWUGO : S_IRUGO)) { rcu_read_unlock(); goto out_wakeup; } error = security_sem_semop(sma, sops, nsops, alter); if (error) { rcu_read_unlock(); goto out_wakeup; } /* * semid identifiers are not unique - find_alloc_undo may have * allocated an undo structure, it was invalidated by an RMID * and now a new array with received the same id. Check and fail. * This case can be detected checking un->semid. The existence of * "un" itself is guaranteed by rcu. */ error = -EIDRM; ipc_lock_object(&sma->sem_perm); if (un) { if (un->semid == -1) { rcu_read_unlock(); goto out_unlock_free; } else { /* * rcu lock can be released, "un" cannot disappear: * - sem_lock is acquired, thus IPC_RMID is * impossible. * - exit_sem is impossible, it always operates on * current (or a dead task). */ rcu_read_unlock(); } } error = try_atomic_semop (sma, sops, nsops, un, task_tgid_vnr(current)); if (error <= 0) { if (alter && error == 0) do_smart_update(sma, sops, nsops, 1, &tasks); goto out_unlock_free; } /* We need to sleep on this operation, so we put the current * task into the pending queue and go to sleep. */ queue.sops = sops; queue.nsops = nsops; queue.undo = un; queue.pid = task_tgid_vnr(current); queue.alter = alter; if (nsops == 1) { struct sem *curr; curr = &sma->sem_base[sops->sem_num]; if (alter) list_add_tail(&queue.list, &curr->sem_pending); else list_add(&queue.list, &curr->sem_pending); } else { if (alter) list_add_tail(&queue.list, &sma->sem_pending); else list_add(&queue.list, &sma->sem_pending); sma->complex_count++; } queue.status = -EINTR; queue.sleeper = current; sleep_again: current->state = TASK_INTERRUPTIBLE; sem_unlock(sma); if (timeout) jiffies_left = schedule_timeout(jiffies_left); else schedule(); error = get_queue_result(&queue); if (error != -EINTR) { /* fast path: update_queue already obtained all requested * resources. * Perform a smp_mb(): User space could assume that semop() * is a memory barrier: Without the mb(), the cpu could * speculatively read in user space stale data that was * overwritten by the previous owner of the semaphore. */ smp_mb(); goto out_free; } sma = sem_obtain_lock(ns, semid); /* * Wait until it's guaranteed that no wakeup_sem_queue_do() is ongoing. */ error = get_queue_result(&queue); /* * Array removed? If yes, leave without sem_unlock(). */ if (IS_ERR(sma)) { goto out_free; } /* * If queue.status != -EINTR we are woken up by another process. * Leave without unlink_queue(), but with sem_unlock(). */ if (error != -EINTR) { goto out_unlock_free; } /* * If an interrupt occurred we have to clean up the queue */ if (timeout && jiffies_left == 0) error = -EAGAIN; /* * If the wakeup was spurious, just retry */ if (error == -EINTR && !signal_pending(current)) goto sleep_again; unlink_queue(sma, &queue); out_unlock_free: sem_unlock(sma); out_wakeup: wake_up_sem_queue_do(&tasks); out_free: if(sops != fast_sops) kfree(sops); return error; } Commit Message: ipc,sem: fine grained locking for semtimedop Introduce finer grained locking for semtimedop, to handle the common case of a program wanting to manipulate one semaphore from an array with multiple semaphores. If the call is a semop manipulating just one semaphore in an array with multiple semaphores, only take the lock for that semaphore itself. If the call needs to manipulate multiple semaphores, or another caller is in a transaction that manipulates multiple semaphores, the sem_array lock is taken, as well as all the locks for the individual semaphores. On a 24 CPU system, performance numbers with the semop-multi test with N threads and N semaphores, look like this: vanilla Davidlohr's Davidlohr's + Davidlohr's + threads patches rwlock patches v3 patches 10 610652 726325 1783589 2142206 20 341570 365699 1520453 1977878 30 288102 307037 1498167 2037995 40 290714 305955 1612665 2256484 50 288620 312890 1733453 2650292 60 289987 306043 1649360 2388008 70 291298 306347 1723167 2717486 80 290948 305662 1729545 2763582 90 290996 306680 1736021 2757524 100 292243 306700 1773700 3059159 [[email protected]: do not call sem_lock when bogus sma] [[email protected]: make refcounter atomic] Signed-off-by: Rik van Riel <[email protected]> Suggested-by: Linus Torvalds <[email protected]> Acked-by: Davidlohr Bueso <[email protected]> Cc: Chegu Vinod <[email protected]> Cc: Jason Low <[email protected]> Reviewed-by: Michel Lespinasse <[email protected]> Cc: Peter Hurley <[email protected]> Cc: Stanislav Kinsbursky <[email protected]> Tested-by: Emmanuel Benisty <[email protected]> Tested-by: Sedat Dilek <[email protected]> Signed-off-by: Andrew Morton <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-189 Target: 1 Example 2: Code: static void br_ip6_multicast_leave_group(struct net_bridge *br, struct net_bridge_port *port, const struct in6_addr *group) { struct br_ip br_group; if (ipv6_is_local_multicast(group)) return; ipv6_addr_copy(&br_group.u.ip6, group); br_group.proto = htons(ETH_P_IPV6); br_multicast_leave_group(br, port, &br_group); } Commit Message: bridge: Fix mglist corruption that leads to memory corruption The list mp->mglist is used to indicate whether a multicast group is active on the bridge interface itself as opposed to one of the constituent interfaces in the bridge. Unfortunately the operation that adds the mp->mglist node to the list neglected to check whether it has already been added. This leads to list corruption in the form of nodes pointing to itself. Normally this would be quite obvious as it would cause an infinite loop when walking the list. However, as this list is never actually walked (which means that we don't really need it, I'll get rid of it in a subsequent patch), this instead is hidden until we perform a delete operation on the affected nodes. As the same node may now be pointed to by more than one node, the delete operations can then cause modification of freed memory. This was observed in practice to cause corruption in 512-byte slabs, most commonly leading to crashes in jbd2. Thanks to Josef Bacik for pointing me in the right direction. Reported-by: Ian Page Hands <[email protected]> Signed-off-by: Herbert Xu <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-399 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: std::unique_ptr<base::SharedMemory> GetShmFromMojoHandle( mojo::ScopedSharedBufferHandle handle) { base::SharedMemoryHandle memory_handle; size_t memory_size = 0; bool read_only_flag = false; const MojoResult result = mojo::UnwrapSharedMemoryHandle( std::move(handle), &memory_handle, &memory_size, &read_only_flag); if (result != MOJO_RESULT_OK) return nullptr; DCHECK_GT(memory_size, 0u); std::unique_ptr<base::SharedMemory> shm = std::make_unique<base::SharedMemory>(memory_handle, read_only_flag); if (!shm->Map(memory_size)) { DLOG(ERROR) << "Map shared memory failed."; return nullptr; } return shm; } Commit Message: Correct mojo::WrapSharedMemoryHandle usage Fixes some incorrect uses of mojo::WrapSharedMemoryHandle which were assuming that the call actually has any control over the memory protection applied to a handle when mapped. Where fixing usage is infeasible for this CL, TODOs are added to annotate follow-up work. Also updates the API and documentation to (hopefully) improve clarity and avoid similar mistakes from being made in the future. BUG=792900 Cq-Include-Trybots: master.tryserver.chromium.android:android_optional_gpu_tests_rel;master.tryserver.chromium.linux:linux_optional_gpu_tests_rel;master.tryserver.chromium.mac:mac_optional_gpu_tests_rel;master.tryserver.chromium.win:win_optional_gpu_tests_rel Change-Id: I0578aaa9ca3bfcb01aaf2451315d1ede95458477 Reviewed-on: https://chromium-review.googlesource.com/818282 Reviewed-by: Wei Li <[email protected]> Reviewed-by: Lei Zhang <[email protected]> Reviewed-by: John Abd-El-Malek <[email protected]> Reviewed-by: Daniel Cheng <[email protected]> Reviewed-by: Sadrul Chowdhury <[email protected]> Reviewed-by: Yuzhu Shen <[email protected]> Reviewed-by: Robert Sesek <[email protected]> Commit-Queue: Ken Rockot <[email protected]> Cr-Commit-Position: refs/heads/master@{#530268} CWE ID: CWE-787 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void ProcessStateChangesUnifiedPlan( WebRtcSetDescriptionObserver::States states) { DCHECK_EQ(sdp_semantics_, webrtc::SdpSemantics::kUnifiedPlan); handler_->OnModifyTransceivers( std::move(states.transceiver_states), action_ == PeerConnectionTracker::ACTION_SET_REMOTE_DESCRIPTION); } Commit Message: Check weak pointers in RTCPeerConnectionHandler::WebRtcSetDescriptionObserverImpl Bug: 912074 Change-Id: I8ba86751f5d5bf12db51520f985ef0d3dae63ed8 Reviewed-on: https://chromium-review.googlesource.com/c/1411916 Commit-Queue: Guido Urdaneta <[email protected]> Reviewed-by: Henrik Boström <[email protected]> Cr-Commit-Position: refs/heads/master@{#622945} CWE ID: CWE-416 Target: 1 Example 2: Code: connection_ap_detach_retriable(entry_connection_t *conn, origin_circuit_t *circ, int reason) { control_event_stream_status(conn, STREAM_EVENT_FAILED_RETRIABLE, reason); ENTRY_TO_CONN(conn)->timestamp_lastread = time(NULL); /* Roll back path bias use state so that we probe the circuit * if nothing else succeeds on it */ pathbias_mark_use_rollback(circ); if (conn->pending_optimistic_data) { buf_set_to_copy(&conn->sending_optimistic_data, conn->pending_optimistic_data); } if (!get_options()->LeaveStreamsUnattached || conn->use_begindir) { /* If we're attaching streams ourself, or if this connection is * a tunneled directory connection, then just attach it. */ ENTRY_TO_CONN(conn)->state = AP_CONN_STATE_CIRCUIT_WAIT; circuit_detach_stream(TO_CIRCUIT(circ),ENTRY_TO_EDGE_CONN(conn)); connection_ap_mark_as_pending_circuit(conn); } else { CONNECTION_AP_EXPECT_NONPENDING(conn); ENTRY_TO_CONN(conn)->state = AP_CONN_STATE_CONTROLLER_WAIT; circuit_detach_stream(TO_CIRCUIT(circ),ENTRY_TO_EDGE_CONN(conn)); } return 0; } Commit Message: TROVE-2017-004: Fix assertion failure in relay_send_end_cell_from_edge_ This fixes an assertion failure in relay_send_end_cell_from_edge_() when an origin circuit and a cpath_layer = NULL were passed. A service rendezvous circuit could do such a thing when a malformed BEGIN cell is received but shouldn't in the first place because the service needs to send an END cell on the circuit for which it can not do without a cpath_layer. Fixes #22493 Reported-by: Roger Dingledine <[email protected]> Signed-off-by: David Goulet <[email protected]> CWE ID: CWE-617 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void SADs(unsigned int *results) { const uint8_t* refs[] = {GetReference(0), GetReference(1), GetReference(2), GetReference(3)}; REGISTER_STATE_CHECK(GET_PARAM(2)(source_data_, source_stride_, refs, reference_stride_, results)); } 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 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: 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 Target: 1 Example 2: Code: static int fips_cprng_reset(struct crypto_rng *tfm, u8 *seed, unsigned int slen) { u8 rdata[DEFAULT_BLK_SZ]; u8 *key = seed + DEFAULT_BLK_SZ; int rc; struct prng_context *prng = crypto_rng_ctx(tfm); if (slen < DEFAULT_PRNG_KSZ + DEFAULT_BLK_SZ) return -EINVAL; /* fips strictly requires seed != key */ if (!memcmp(seed, key, DEFAULT_PRNG_KSZ)) return -EINVAL; rc = cprng_reset(tfm, seed, slen); if (!rc) goto out; /* this primes our continuity test */ rc = get_prng_bytes(rdata, DEFAULT_BLK_SZ, prng, 0); prng->rand_data_valid = DEFAULT_BLK_SZ; out: return rc; } Commit Message: crypto: prefix module autoloading with "crypto-" This prefixes all crypto module loading with "crypto-" so we never run the risk of exposing module auto-loading to userspace via a crypto API, as demonstrated by Mathias Krause: https://lkml.org/lkml/2013/3/4/70 Signed-off-by: Kees Cook <[email protected]> Signed-off-by: Herbert Xu <[email protected]> CWE ID: CWE-264 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: ofpact_next_flattened(const struct ofpact *ofpact) { switch (ofpact->type) { case OFPACT_OUTPUT: case OFPACT_GROUP: case OFPACT_CONTROLLER: case OFPACT_ENQUEUE: case OFPACT_OUTPUT_REG: case OFPACT_OUTPUT_TRUNC: case OFPACT_BUNDLE: case OFPACT_SET_FIELD: case OFPACT_SET_VLAN_VID: case OFPACT_SET_VLAN_PCP: case OFPACT_STRIP_VLAN: case OFPACT_PUSH_VLAN: case OFPACT_SET_ETH_SRC: case OFPACT_SET_ETH_DST: case OFPACT_SET_IPV4_SRC: case OFPACT_SET_IPV4_DST: case OFPACT_SET_IP_DSCP: case OFPACT_SET_IP_ECN: case OFPACT_SET_IP_TTL: case OFPACT_SET_L4_SRC_PORT: case OFPACT_SET_L4_DST_PORT: case OFPACT_REG_MOVE: case OFPACT_STACK_PUSH: case OFPACT_STACK_POP: case OFPACT_DEC_TTL: case OFPACT_SET_MPLS_LABEL: case OFPACT_SET_MPLS_TC: case OFPACT_SET_MPLS_TTL: case OFPACT_DEC_MPLS_TTL: case OFPACT_PUSH_MPLS: case OFPACT_POP_MPLS: case OFPACT_SET_TUNNEL: case OFPACT_SET_QUEUE: case OFPACT_POP_QUEUE: case OFPACT_FIN_TIMEOUT: case OFPACT_RESUBMIT: case OFPACT_LEARN: case OFPACT_CONJUNCTION: case OFPACT_MULTIPATH: case OFPACT_NOTE: case OFPACT_EXIT: case OFPACT_SAMPLE: case OFPACT_UNROLL_XLATE: case OFPACT_CT_CLEAR: case OFPACT_DEBUG_RECIRC: case OFPACT_METER: case OFPACT_CLEAR_ACTIONS: case OFPACT_WRITE_METADATA: case OFPACT_GOTO_TABLE: case OFPACT_NAT: return ofpact_next(ofpact); case OFPACT_CLONE: return ofpact_get_CLONE(ofpact)->actions; case OFPACT_CT: return ofpact_get_CT(ofpact)->actions; case OFPACT_WRITE_ACTIONS: return ofpact_get_WRITE_ACTIONS(ofpact)->actions; } OVS_NOT_REACHED(); } Commit Message: ofp-actions: Avoid buffer overread in BUNDLE action decoding. Reported-at: https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=9052 Signed-off-by: Ben Pfaff <[email protected]> Acked-by: Justin Pettit <[email protected]> CWE ID: Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: xscale2pmu_handle_irq(int irq_num, void *dev) { unsigned long pmnc, of_flags; struct perf_sample_data data; struct cpu_hw_events *cpuc; struct pt_regs *regs; int idx; /* Disable the PMU. */ pmnc = xscale2pmu_read_pmnc(); xscale2pmu_write_pmnc(pmnc & ~XSCALE_PMU_ENABLE); /* Check the overflow flag register. */ of_flags = xscale2pmu_read_overflow_flags(); if (!(of_flags & XSCALE2_OVERFLOWED_MASK)) return IRQ_NONE; /* Clear the overflow bits. */ xscale2pmu_write_overflow_flags(of_flags); regs = get_irq_regs(); perf_sample_data_init(&data, 0); cpuc = &__get_cpu_var(cpu_hw_events); for (idx = 0; idx <= armpmu->num_events; ++idx) { struct perf_event *event = cpuc->events[idx]; struct hw_perf_event *hwc; if (!test_bit(idx, cpuc->active_mask)) continue; if (!xscale2_pmnc_counter_has_overflowed(pmnc, idx)) continue; hwc = &event->hw; armpmu_event_update(event, hwc, idx, 1); data.period = event->hw.last_period; if (!armpmu_event_set_period(event, hwc, idx)) continue; if (perf_event_overflow(event, 0, &data, regs)) armpmu->disable(hwc, idx); } irq_work_run(); /* * Re-enable the PMU. */ pmnc = xscale2pmu_read_pmnc() | XSCALE_PMU_ENABLE; xscale2pmu_write_pmnc(pmnc); return IRQ_HANDLED; } 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 Target: 1 Example 2: Code: __ip_vs_get_dest_entries(struct net *net, const struct ip_vs_get_dests *get, struct ip_vs_get_dests __user *uptr) { struct ip_vs_service *svc; union nf_inet_addr addr = { .ip = get->addr }; int ret = 0; if (get->fwmark) svc = __ip_vs_svc_fwm_find(net, AF_INET, get->fwmark); else svc = __ip_vs_service_find(net, AF_INET, get->protocol, &addr, get->port); if (svc) { int count = 0; struct ip_vs_dest *dest; struct ip_vs_dest_entry entry; list_for_each_entry(dest, &svc->destinations, n_list) { if (count >= get->num_dests) break; entry.addr = dest->addr.ip; entry.port = dest->port; entry.conn_flags = atomic_read(&dest->conn_flags); entry.weight = atomic_read(&dest->weight); entry.u_threshold = dest->u_threshold; entry.l_threshold = dest->l_threshold; entry.activeconns = atomic_read(&dest->activeconns); entry.inactconns = atomic_read(&dest->inactconns); entry.persistconns = atomic_read(&dest->persistconns); ip_vs_copy_stats(&entry.stats, &dest->stats); if (copy_to_user(&uptr->entrytable[count], &entry, sizeof(entry))) { ret = -EFAULT; break; } count++; } } else ret = -ESRCH; return ret; } Commit Message: ipvs: fix info leak in getsockopt(IP_VS_SO_GET_TIMEOUT) If at least one of CONFIG_IP_VS_PROTO_TCP or CONFIG_IP_VS_PROTO_UDP is not set, __ip_vs_get_timeouts() does not fully initialize the structure that gets copied to userland and that for leaks up to 12 bytes of kernel stack. Add an explicit memset(0) before passing the structure to __ip_vs_get_timeouts() to avoid the info leak. Signed-off-by: Mathias Krause <[email protected]> Cc: Wensong Zhang <[email protected]> Cc: Simon Horman <[email protected]> Cc: Julian Anastasov <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-200 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void Browser::OpenInstantConfirmDialogWindow(Profile* profile) { Browser* browser = Browser::Create(profile); browser->OpenInstantConfirmDialog(); browser->window()->Show(); } Commit Message: Implement a bubble that appears at the top of the screen when a tab enters fullscreen mode via webkitRequestFullScreen(), telling the user how to exit fullscreen. This is implemented as an NSView rather than an NSWindow because the floating chrome that appears in presentation mode should overlap the bubble. Content-initiated fullscreen mode makes use of 'presentation mode' on the Mac: the mode in which the UI is hidden, accessible by moving the cursor to the top of the screen. On Snow Leopard, this mode is synonymous with fullscreen mode. On Lion, however, fullscreen mode does not imply presentation mode: in non-presentation fullscreen mode, the chrome is permanently shown. It is possible to switch between presentation mode and fullscreen mode using the presentation mode UI control. When a tab initiates fullscreen mode on Lion, we enter presentation mode if not in presentation mode already. When the user exits fullscreen mode using Chrome UI (i.e. keyboard shortcuts, menu items, buttons, switching tabs, etc.) we return the user to the mode they were in before the tab entered fullscreen. BUG=14471 TEST=Enter fullscreen mode using webkitRequestFullScreen. You should see a bubble pop down from the top of the screen. Need to test the Lion logic somehow, with no Lion trybots. BUG=96883 Original review http://codereview.chromium.org/7890056/ TBR=thakis Review URL: http://codereview.chromium.org/7920024 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@101624 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int raw_recvmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg, size_t len, int noblock, int flags, int *addr_len) { struct inet_sock *inet = inet_sk(sk); size_t copied = 0; int err = -EOPNOTSUPP; struct sockaddr_in *sin = (struct sockaddr_in *)msg->msg_name; struct sk_buff *skb; if (flags & MSG_OOB) goto out; if (addr_len) *addr_len = sizeof(*sin); if (flags & MSG_ERRQUEUE) { err = ip_recv_error(sk, msg, len); goto out; } skb = skb_recv_datagram(sk, flags, noblock, &err); if (!skb) goto out; copied = skb->len; if (len < copied) { msg->msg_flags |= MSG_TRUNC; copied = len; } err = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied); if (err) goto done; sock_recv_ts_and_drops(msg, sk, skb); /* Copy the address. */ if (sin) { sin->sin_family = AF_INET; sin->sin_addr.s_addr = ip_hdr(skb)->saddr; sin->sin_port = 0; memset(&sin->sin_zero, 0, sizeof(sin->sin_zero)); } if (inet->cmsg_flags) ip_cmsg_recv(msg, skb); if (flags & MSG_TRUNC) copied = skb->len; done: skb_free_datagram(sk, skb); out: if (err) return err; return copied; } Commit Message: inet: prevent leakage of uninitialized memory to user in recv syscalls Only update *addr_len when we actually fill in sockaddr, otherwise we can return uninitialized memory from the stack to the caller in the recvfrom, recvmmsg and recvmsg syscalls. Drop the the (addr_len == NULL) checks because we only get called with a valid addr_len pointer either from sock_common_recvmsg or inet_recvmsg. If a blocking read waits on a socket which is concurrently shut down we now return zero and set msg_msgnamelen to 0. Reported-by: mpb <[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-200 Target: 1 Example 2: Code: scoped_refptr<TransportSocketParams> GetTcpParams() { if (GetParam() != HTTP) return scoped_refptr<TransportSocketParams>(); return ignored_transport_socket_params_; } Commit Message: net: don't process truncated headers on HTTPS connections. This change causes us to not process any headers unless they are correctly terminated with a \r\n\r\n sequence. BUG=244260 Review URL: https://chromiumcodereview.appspot.com/15688012 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@202927 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: String InspectorPageAgent::CachedResourceTypeJson( const Resource& cached_resource) { return ResourceTypeJson(CachedResourceType(cached_resource)); } Commit Message: DevTools: send proper resource type in Network.RequestWillBeSent This patch plumbs resoure type into the DispatchWillSendRequest instrumenation. This allows us to report accurate type in Network.RequestWillBeSent event, instead of "Other", that we report today. BUG=765501 R=dgozman Change-Id: I0134c08b841e8dd247fdc8ff208bfd51e462709c Reviewed-on: https://chromium-review.googlesource.com/667504 Reviewed-by: Pavel Feldman <[email protected]> Reviewed-by: Dmitry Gozman <[email protected]> Commit-Queue: Andrey Lushnikov <[email protected]> Cr-Commit-Position: refs/heads/master@{#507936} CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int bta_co_rfc_data_outgoing_size(void *user_data, int *size) { pthread_mutex_lock(&slot_lock); uint32_t id = (uintptr_t)user_data; int ret = false; *size = 0; rfc_slot_t *slot = find_rfc_slot_by_id(id); if (!slot) goto out; if (ioctl(slot->fd, FIONREAD, size) == 0) { ret = true; } else { LOG_ERROR("%s unable to determine bytes remaining to be read on fd %d: %s", __func__, slot->fd, strerror(errno)); cleanup_rfc_slot(slot); } out:; pthread_mutex_unlock(&slot_lock); return ret; } 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 Target: 1 Example 2: Code: GF_Err meta_dump(GF_Box *a, FILE * trace) { GF_MetaBox *p; p = (GF_MetaBox *)a; gf_isom_box_dump_start(a, "MetaBox", trace); fprintf(trace, ">\n"); if (p->handler) gf_isom_box_dump(p->handler, trace); if (p->primary_resource) gf_isom_box_dump(p->primary_resource, trace); if (p->file_locations) gf_isom_box_dump(p->file_locations, trace); if (p->item_locations) gf_isom_box_dump(p->item_locations, trace); if (p->protections) gf_isom_box_dump(p->protections, trace); if (p->item_infos) gf_isom_box_dump(p->item_infos, trace); if (p->IPMP_control) gf_isom_box_dump(p->IPMP_control, trace); if (p->item_refs) gf_isom_box_dump(p->item_refs, trace); if (p->item_props) gf_isom_box_dump(p->item_props, trace); gf_isom_box_dump_done("MetaBox", a, trace); return GF_OK; } Commit Message: fixed 2 possible heap overflows (inc. #1088) CWE ID: CWE-125 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: GF_Err rely_Read(GF_Box *s, GF_BitStream *bs) { GF_RelyHintBox *ptr = (GF_RelyHintBox *)s; ptr->reserved = gf_bs_read_int(bs, 6); ptr->prefered = gf_bs_read_int(bs, 1); ptr->required = gf_bs_read_int(bs, 1); return GF_OK; } Commit Message: fixed 2 possible heap overflows (inc. #1088) CWE ID: CWE-125 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void impeg2d_dec_pic_data_thread(dec_state_t *ps_dec) { WORD32 i4_continue_decode; WORD32 i4_cur_row, temp; UWORD32 u4_bits_read; WORD32 i4_dequeue_job; IMPEG2D_ERROR_CODES_T e_error; i4_cur_row = ps_dec->u2_mb_y + 1; i4_continue_decode = 1; i4_dequeue_job = 1; do { if(i4_cur_row > ps_dec->u2_num_vert_mb) { i4_continue_decode = 0; break; } { if((ps_dec->i4_num_cores> 1) && (i4_dequeue_job)) { job_t s_job; IV_API_CALL_STATUS_T e_ret; UWORD8 *pu1_buf; e_ret = impeg2_jobq_dequeue(ps_dec->pv_jobq, &s_job, sizeof(s_job), 1, 1); if(e_ret != IV_SUCCESS) break; if(CMD_PROCESS == s_job.i4_cmd) { pu1_buf = ps_dec->pu1_inp_bits_buf + s_job.i4_bistream_ofst; impeg2d_bit_stream_init(&(ps_dec->s_bit_stream), pu1_buf, (ps_dec->u4_num_inp_bytes - s_job.i4_bistream_ofst) + 8); i4_cur_row = s_job.i2_start_mb_y; ps_dec->i4_start_mb_y = s_job.i2_start_mb_y; ps_dec->i4_end_mb_y = s_job.i2_end_mb_y; ps_dec->u2_mb_x = 0; ps_dec->u2_mb_y = ps_dec->i4_start_mb_y; ps_dec->u2_num_mbs_left = (ps_dec->i4_end_mb_y - ps_dec->i4_start_mb_y) * ps_dec->u2_num_horiz_mb; } else { WORD32 start_row; WORD32 num_rows; start_row = s_job.i2_start_mb_y << 4; num_rows = MIN((s_job.i2_end_mb_y << 4), ps_dec->u2_vertical_size); num_rows -= start_row; impeg2d_format_convert(ps_dec, ps_dec->ps_disp_pic, ps_dec->ps_disp_frm_buf, start_row, num_rows); break; } } e_error = impeg2d_dec_slice(ps_dec); if ((IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE != e_error) { impeg2d_next_start_code(ps_dec); } } /* Detecting next slice start code */ while(1) { u4_bits_read = impeg2d_bit_stream_nxt(&ps_dec->s_bit_stream,START_CODE_LEN); temp = u4_bits_read & 0xFF; i4_continue_decode = (((u4_bits_read >> 8) == 0x01) && (temp) && (temp <= 0xAF)); if(i4_continue_decode) { /* If the slice is from the same row, then continue decoding without dequeue */ if((temp - 1) == i4_cur_row) { i4_dequeue_job = 0; break; } if(temp < ps_dec->i4_end_mb_y) { i4_cur_row = ps_dec->u2_mb_y; } else { i4_dequeue_job = 1; } break; } else break; } }while(i4_continue_decode); if(ps_dec->i4_num_cores > 1) { while(1) { job_t s_job; IV_API_CALL_STATUS_T e_ret; e_ret = impeg2_jobq_dequeue(ps_dec->pv_jobq, &s_job, sizeof(s_job), 1, 1); if(e_ret != IV_SUCCESS) break; if(CMD_FMTCONV == s_job.i4_cmd) { WORD32 start_row; WORD32 num_rows; start_row = s_job.i2_start_mb_y << 4; num_rows = MIN((s_job.i2_end_mb_y << 4), ps_dec->u2_vertical_size); num_rows -= start_row; impeg2d_format_convert(ps_dec, ps_dec->ps_disp_pic, ps_dec->ps_disp_frm_buf, start_row, num_rows); } } } else { if((NULL != ps_dec->ps_disp_pic) && ((0 == ps_dec->u4_share_disp_buf) || (IV_YUV_420P != ps_dec->i4_chromaFormat))) impeg2d_format_convert(ps_dec, ps_dec->ps_disp_pic, ps_dec->ps_disp_frm_buf, 0, ps_dec->u2_vertical_size); } } Commit Message: Fix for handling streams which resulted in negative num_mbs_left Bug: 26070014 Change-Id: Id9f063a2c72a802d991b92abaf00ec687db5bb0f CWE ID: CWE-119 Target: 1 Example 2: Code: static void zrle_choose_palette_rle(VncState *vs, int w, int h, VncPalette *palette, int bpp_out, int runs, int single_pixels, int zywrle_level, bool *use_rle, bool *use_palette) { size_t estimated_bytes; size_t plain_rle_bytes; *use_palette = *use_rle = false; estimated_bytes = w * h * (bpp_out / 8); /* start assuming raw */ if (bpp_out != 8) { if (zywrle_level > 0 && !(zywrle_level & 0x80)) estimated_bytes >>= zywrle_level; } plain_rle_bytes = ((bpp_out / 8) + 1) * (runs + single_pixels); if (plain_rle_bytes < estimated_bytes) { *use_rle = true; estimated_bytes = plain_rle_bytes; } if (palette_size(palette) < 128) { int palette_rle_bytes; palette_rle_bytes = (bpp_out / 8) * palette_size(palette); palette_rle_bytes += 2 * runs + single_pixels; if (palette_rle_bytes < estimated_bytes) { *use_rle = true; *use_palette = true; estimated_bytes = palette_rle_bytes; } if (palette_size(palette) < 17) { int packed_bytes; packed_bytes = (bpp_out / 8) * palette_size(palette); packed_bytes += w * h * bits_per_packed_pixel[palette_size(palette)-1] / 8; if (packed_bytes < estimated_bytes) { *use_rle = false; *use_palette = true; estimated_bytes = packed_bytes; } } } } Commit Message: CWE ID: CWE-125 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void CreateMediaPlayerRenderer( content::RenderFrameHost* render_frame_host, mojo::InterfaceRequest<media::mojom::Renderer> request) { std::unique_ptr<MediaPlayerRenderer> renderer = base::MakeUnique<MediaPlayerRenderer>(render_frame_host); media::MojoRendererService::InitiateSurfaceRequestCB surface_request_cb = base::Bind(&MediaPlayerRenderer::InitiateScopedSurfaceRequest, base::Unretained(renderer.get())); media::MojoRendererService::Create( nullptr, // CDMs are not supported. nullptr, // Manages its own audio_sink. nullptr, // Does not use video_sink. See StreamTextureWrapper instead. std::move(renderer), surface_request_cb, std::move(request)); } Commit Message: Correctly reset FP in RFHI whenever origin changes Bug: 713364 Change-Id: Id8bb923750e20f3db6fc9358b1d44120513ac95f CQ_INCLUDE_TRYBOTS=master.tryserver.chromium.linux:linux_site_isolation Change-Id: Id8bb923750e20f3db6fc9358b1d44120513ac95f Reviewed-on: https://chromium-review.googlesource.com/482380 Commit-Queue: Ian Clelland <[email protected]> Reviewed-by: Charles Reis <[email protected]> Cr-Commit-Position: refs/heads/master@{#466778} CWE ID: CWE-254 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int ext4_split_unwritten_extents(handle_t *handle, struct inode *inode, struct ext4_map_blocks *map, struct ext4_ext_path *path, int flags) { struct ext4_extent *ex, newex, orig_ex; struct ext4_extent *ex1 = NULL; struct ext4_extent *ex2 = NULL; struct ext4_extent *ex3 = NULL; ext4_lblk_t ee_block, eof_block; unsigned int allocated, ee_len, depth; ext4_fsblk_t newblock; int err = 0; int may_zeroout; ext_debug("ext4_split_unwritten_extents: inode %lu, logical" "block %llu, max_blocks %u\n", inode->i_ino, (unsigned long long)map->m_lblk, map->m_len); eof_block = (inode->i_size + inode->i_sb->s_blocksize - 1) >> inode->i_sb->s_blocksize_bits; if (eof_block < map->m_lblk + map->m_len) eof_block = map->m_lblk + map->m_len; depth = ext_depth(inode); ex = path[depth].p_ext; ee_block = le32_to_cpu(ex->ee_block); ee_len = ext4_ext_get_actual_len(ex); allocated = ee_len - (map->m_lblk - ee_block); newblock = map->m_lblk - ee_block + ext4_ext_pblock(ex); ex2 = ex; orig_ex.ee_block = ex->ee_block; orig_ex.ee_len = cpu_to_le16(ee_len); ext4_ext_store_pblock(&orig_ex, ext4_ext_pblock(ex)); /* * It is safe to convert extent to initialized via explicit * zeroout only if extent is fully insde i_size or new_size. */ may_zeroout = ee_block + ee_len <= eof_block; /* * If the uninitialized extent begins at the same logical * block where the write begins, and the write completely * covers the extent, then we don't need to split it. */ if ((map->m_lblk == ee_block) && (allocated <= map->m_len)) return allocated; err = ext4_ext_get_access(handle, inode, path + depth); if (err) goto out; /* ex1: ee_block to map->m_lblk - 1 : uninitialized */ if (map->m_lblk > ee_block) { ex1 = ex; ex1->ee_len = cpu_to_le16(map->m_lblk - ee_block); ext4_ext_mark_uninitialized(ex1); ex2 = &newex; } /* * for sanity, update the length of the ex2 extent before * we insert ex3, if ex1 is NULL. This is to avoid temporary * overlap of blocks. */ if (!ex1 && allocated > map->m_len) ex2->ee_len = cpu_to_le16(map->m_len); /* ex3: to ee_block + ee_len : uninitialised */ if (allocated > map->m_len) { unsigned int newdepth; ex3 = &newex; ex3->ee_block = cpu_to_le32(map->m_lblk + map->m_len); ext4_ext_store_pblock(ex3, newblock + map->m_len); ex3->ee_len = cpu_to_le16(allocated - map->m_len); ext4_ext_mark_uninitialized(ex3); err = ext4_ext_insert_extent(handle, inode, path, ex3, flags); if (err == -ENOSPC && may_zeroout) { err = ext4_ext_zeroout(inode, &orig_ex); if (err) goto fix_extent_len; /* update the extent length and mark as initialized */ ex->ee_block = orig_ex.ee_block; ex->ee_len = orig_ex.ee_len; ext4_ext_store_pblock(ex, ext4_ext_pblock(&orig_ex)); ext4_ext_dirty(handle, inode, path + depth); /* zeroed the full extent */ /* blocks available from map->m_lblk */ return allocated; } else if (err) goto fix_extent_len; /* * The depth, and hence eh & ex might change * as part of the insert above. */ newdepth = ext_depth(inode); /* * update the extent length after successful insert of the * split extent */ ee_len -= ext4_ext_get_actual_len(ex3); orig_ex.ee_len = cpu_to_le16(ee_len); may_zeroout = ee_block + ee_len <= eof_block; depth = newdepth; ext4_ext_drop_refs(path); path = ext4_ext_find_extent(inode, map->m_lblk, path); if (IS_ERR(path)) { err = PTR_ERR(path); goto out; } ex = path[depth].p_ext; if (ex2 != &newex) ex2 = ex; err = ext4_ext_get_access(handle, inode, path + depth); if (err) goto out; allocated = map->m_len; } /* * If there was a change of depth as part of the * insertion of ex3 above, we need to update the length * of the ex1 extent again here */ if (ex1 && ex1 != ex) { ex1 = ex; ex1->ee_len = cpu_to_le16(map->m_lblk - ee_block); ext4_ext_mark_uninitialized(ex1); ex2 = &newex; } /* * ex2: map->m_lblk to map->m_lblk + map->m_len-1 : to be written * using direct I/O, uninitialised still. */ ex2->ee_block = cpu_to_le32(map->m_lblk); ext4_ext_store_pblock(ex2, newblock); ex2->ee_len = cpu_to_le16(allocated); ext4_ext_mark_uninitialized(ex2); if (ex2 != ex) goto insert; /* Mark modified extent as dirty */ err = ext4_ext_dirty(handle, inode, path + depth); ext_debug("out here\n"); goto out; insert: err = ext4_ext_insert_extent(handle, inode, path, &newex, flags); if (err == -ENOSPC && may_zeroout) { err = ext4_ext_zeroout(inode, &orig_ex); if (err) goto fix_extent_len; /* update the extent length and mark as initialized */ ex->ee_block = orig_ex.ee_block; ex->ee_len = orig_ex.ee_len; ext4_ext_store_pblock(ex, ext4_ext_pblock(&orig_ex)); ext4_ext_dirty(handle, inode, path + depth); /* zero out the first half */ return allocated; } else if (err) goto fix_extent_len; out: ext4_ext_show_leaf(inode, path); return err ? err : allocated; fix_extent_len: ex->ee_block = orig_ex.ee_block; ex->ee_len = orig_ex.ee_len; ext4_ext_store_pblock(ex, ext4_ext_pblock(&orig_ex)); ext4_ext_mark_uninitialized(ex); ext4_ext_dirty(handle, inode, path + depth); return err; } Commit Message: ext4: reimplement convert and split_unwritten Reimplement ext4_ext_convert_to_initialized() and ext4_split_unwritten_extents() using ext4_split_extent() Signed-off-by: Yongqiang Yang <[email protected]> Signed-off-by: "Theodore Ts'o" <[email protected]> Tested-by: Allison Henderson <[email protected]> CWE ID: Target: 1 Example 2: Code: static void put_fb_info(struct fb_info *fb_info) { if (!atomic_dec_and_test(&fb_info->count)) return; if (fb_info->fbops->fb_destroy) fb_info->fbops->fb_destroy(fb_info); } Commit Message: vm: convert fb_mmap to vm_iomap_memory() helper This is my example conversion of a few existing mmap users. The fb_mmap() case is a good example because it is a bit more complicated than some: fb_mmap() mmaps one of two different memory areas depending on the page offset of the mmap (but happily there is never any mixing of the two, so the helper function still works). Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-189 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: char *curl_easy_unescape(CURL *handle, const char *string, int length, int *olen) { int alloc = (length?length:(int)strlen(string))+1; char *ns = malloc(alloc); unsigned char in; int strindex=0; unsigned long hex; CURLcode res; if(!ns) return NULL; while(--alloc > 0) { in = *string; if(('%' == in) && ISXDIGIT(string[1]) && ISXDIGIT(string[2])) { /* this is two hexadecimal digits following a '%' */ char hexstr[3]; char *ptr; hexstr[0] = string[1]; hexstr[1] = string[2]; hexstr[2] = 0; hex = strtoul(hexstr, &ptr, 16); in = curlx_ultouc(hex); /* this long is never bigger than 255 anyway */ res = Curl_convert_from_network(handle, &in, 1); if(res) { /* Curl_convert_from_network calls failf if unsuccessful */ free(ns); return NULL; } string+=2; alloc-=2; } ns[strindex++] = in; string++; } ns[strindex]=0; /* terminate it */ if(olen) /* store output size */ *olen = strindex; return ns; } Commit Message: URL sanitize: reject URLs containing bad data Protocols (IMAP, POP3 and SMTP) that use the path part of a URL in a decoded manner now use the new Curl_urldecode() function to reject URLs with embedded control codes (anything that is or decodes to a byte value less than 32). URLs containing such codes could easily otherwise be used to do harm and allow users to do unintended actions with otherwise innocent tools and applications. Like for example using a URL like pop3://pop3.example.com/1%0d%0aDELE%201 when the app wants a URL to get a mail and instead this would delete one. This flaw is considered a security vulnerability: CVE-2012-0036 Security advisory at: http://curl.haxx.se/docs/adv_20120124.html Reported by: Dan Fandrich CWE ID: CWE-89 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static OPJ_BOOL opj_pi_next_pcrl(opj_pi_iterator_t * pi) { opj_pi_comp_t *comp = NULL; opj_pi_resolution_t *res = NULL; OPJ_UINT32 index = 0; if (!pi->first) { comp = &pi->comps[pi->compno]; goto LABEL_SKIP; } else { OPJ_UINT32 compno, resno; pi->first = 0; pi->dx = 0; pi->dy = 0; for (compno = 0; compno < pi->numcomps; compno++) { comp = &pi->comps[compno]; for (resno = 0; resno < comp->numresolutions; resno++) { OPJ_UINT32 dx, dy; res = &comp->resolutions[resno]; dx = comp->dx * (1u << (res->pdx + comp->numresolutions - 1 - resno)); dy = comp->dy * (1u << (res->pdy + comp->numresolutions - 1 - resno)); pi->dx = !pi->dx ? dx : opj_uint_min(pi->dx, dx); pi->dy = !pi->dy ? dy : opj_uint_min(pi->dy, dy); } } } if (!pi->tp_on) { pi->poc.ty0 = pi->ty0; pi->poc.tx0 = pi->tx0; pi->poc.ty1 = pi->ty1; pi->poc.tx1 = pi->tx1; } for (pi->y = pi->poc.ty0; pi->y < pi->poc.ty1; pi->y += (OPJ_INT32)(pi->dy - (OPJ_UINT32)(pi->y % (OPJ_INT32)pi->dy))) { for (pi->x = pi->poc.tx0; pi->x < pi->poc.tx1; pi->x += (OPJ_INT32)(pi->dx - (OPJ_UINT32)(pi->x % (OPJ_INT32)pi->dx))) { for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) { comp = &pi->comps[pi->compno]; for (pi->resno = pi->poc.resno0; pi->resno < opj_uint_min(pi->poc.resno1, comp->numresolutions); pi->resno++) { OPJ_UINT32 levelno; OPJ_INT32 trx0, try0; OPJ_INT32 trx1, try1; OPJ_UINT32 rpx, rpy; OPJ_INT32 prci, prcj; res = &comp->resolutions[pi->resno]; levelno = comp->numresolutions - 1 - pi->resno; trx0 = opj_int_ceildiv(pi->tx0, (OPJ_INT32)(comp->dx << levelno)); try0 = opj_int_ceildiv(pi->ty0, (OPJ_INT32)(comp->dy << levelno)); trx1 = opj_int_ceildiv(pi->tx1, (OPJ_INT32)(comp->dx << levelno)); try1 = opj_int_ceildiv(pi->ty1, (OPJ_INT32)(comp->dy << levelno)); rpx = res->pdx + levelno; rpy = res->pdy + levelno; if (!((pi->y % (OPJ_INT32)(comp->dy << rpy) == 0) || ((pi->y == pi->ty0) && ((try0 << levelno) % (1 << rpy))))) { continue; } if (!((pi->x % (OPJ_INT32)(comp->dx << rpx) == 0) || ((pi->x == pi->tx0) && ((trx0 << levelno) % (1 << rpx))))) { continue; } if ((res->pw == 0) || (res->ph == 0)) { continue; } if ((trx0 == trx1) || (try0 == try1)) { continue; } prci = opj_int_floordivpow2(opj_int_ceildiv(pi->x, (OPJ_INT32)(comp->dx << levelno)), (OPJ_INT32)res->pdx) - opj_int_floordivpow2(trx0, (OPJ_INT32)res->pdx); prcj = opj_int_floordivpow2(opj_int_ceildiv(pi->y, (OPJ_INT32)(comp->dy << levelno)), (OPJ_INT32)res->pdy) - opj_int_floordivpow2(try0, (OPJ_INT32)res->pdy); pi->precno = (OPJ_UINT32)(prci + prcj * (OPJ_INT32)res->pw); for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) { index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno * pi->step_c + pi->precno * pi->step_p; if (!pi->include[index]) { pi->include[index] = 1; return OPJ_TRUE; } LABEL_SKIP: ; } } } } } return OPJ_FALSE; } Commit Message: Avoid division by zero in opj_pi_next_rpcl, opj_pi_next_pcrl and opj_pi_next_cprl (#938) Fixes issues with id:000026,sig:08,src:002419,op:int32,pos:60,val:+32 and id:000019,sig:08,src:001098,op:flip1,pos:49 CWE ID: CWE-369 Target: 1 Example 2: Code: void addObjectVectorAttribute(AXObjectVectorAttribute attribute, HeapVector<Member<AXObject>>& objects) { switch (attribute) { case AXObjectVectorAttribute::AriaControls: m_properties.addItem(createRelatedNodeListProperty( AXRelationshipAttributesEnum::Controls, objects, aria_controlsAttr, *m_axObject)); break; case AXObjectVectorAttribute::AriaDetails: m_properties.addItem(createRelatedNodeListProperty( AXRelationshipAttributesEnum::Details, objects, aria_controlsAttr, *m_axObject)); break; case AXObjectVectorAttribute::AriaFlowTo: m_properties.addItem(createRelatedNodeListProperty( AXRelationshipAttributesEnum::Flowto, objects, aria_flowtoAttr, *m_axObject)); break; } } Commit Message: Switch to equalIgnoringASCIICase throughout modules/accessibility BUG=627682 Review-Url: https://codereview.chromium.org/2793913007 Cr-Commit-Position: refs/heads/master@{#461858} CWE ID: CWE-254 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void cmd_getquota(const char *tag, const char *name) { int r; char quotarootbuf[MAX_MAILBOX_BUFFER]; mbentry_t *mbentry = NULL; struct quota q; char *intname = mboxname_from_external(name, &imapd_namespace, imapd_userid); quota_init(&q, intname); imapd_check(NULL, 0); if (!imapd_userisadmin && !imapd_userisproxyadmin) { r = IMAP_PERMISSION_DENIED; goto done; } r = mlookup(NULL, NULL, intname, &mbentry); if (!r && (mbentry->mbtype & MBTYPE_REMOTE)) { /* remote mailbox */ snprintf(quotarootbuf, sizeof(quotarootbuf), "%s.", intname); r = mboxlist_allmbox(quotarootbuf, quota_cb, (void *)mbentry->server, 0); if (r) goto done; struct backend *s; s = proxy_findserver(mbentry->server, &imap_protocol, proxy_userid, &backend_cached, &backend_current, &backend_inbox, imapd_in); if (!s) { r = IMAP_SERVER_UNAVAILABLE; goto done; } imapd_check(s, 0); prot_printf(s->out, "%s Getquota {" SIZE_T_FMT "+}\r\n%s\r\n", tag, strlen(name), name); pipe_including_tag(s, tag, 0); goto done; } /* local mailbox */ r = quota_read(&q, NULL, 0); if (r) goto done; prot_printf(imapd_out, "* QUOTA "); prot_printastring(imapd_out, name); prot_printf(imapd_out, " "); print_quota_used(imapd_out, &q); prot_printf(imapd_out, "\r\n"); prot_printf(imapd_out, "%s OK %s\r\n", tag, error_message(IMAP_OK_COMPLETED)); done: if (r) prot_printf(imapd_out, "%s NO %s\r\n", tag, error_message(r)); mboxlist_entry_free(&mbentry); quota_free(&q); free(intname); } Commit Message: imapd: check for isadmin BEFORE parsing sync lines CWE ID: CWE-20 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int tty_open(struct inode *inode, struct file *filp) { struct tty_struct *tty = NULL; int noctty, retval; struct tty_driver *driver; int index; dev_t device = inode->i_rdev; unsigned saved_flags = filp->f_flags; nonseekable_open(inode, filp); retry_open: noctty = filp->f_flags & O_NOCTTY; index = -1; retval = 0; mutex_lock(&tty_mutex); tty_lock(); if (device == MKDEV(TTYAUX_MAJOR, 0)) { tty = get_current_tty(); if (!tty) { tty_unlock(); mutex_unlock(&tty_mutex); return -ENXIO; } driver = tty_driver_kref_get(tty->driver); index = tty->index; filp->f_flags |= O_NONBLOCK; /* Don't let /dev/tty block */ /* noctty = 1; */ /* FIXME: Should we take a driver reference ? */ tty_kref_put(tty); goto got_driver; } #ifdef CONFIG_VT if (device == MKDEV(TTY_MAJOR, 0)) { extern struct tty_driver *console_driver; driver = tty_driver_kref_get(console_driver); index = fg_console; noctty = 1; goto got_driver; } #endif if (device == MKDEV(TTYAUX_MAJOR, 1)) { struct tty_driver *console_driver = console_device(&index); if (console_driver) { driver = tty_driver_kref_get(console_driver); if (driver) { /* Don't let /dev/console block */ filp->f_flags |= O_NONBLOCK; noctty = 1; goto got_driver; } } tty_unlock(); mutex_unlock(&tty_mutex); return -ENODEV; } driver = get_tty_driver(device, &index); if (!driver) { tty_unlock(); mutex_unlock(&tty_mutex); return -ENODEV; } got_driver: if (!tty) { /* check whether we're reopening an existing tty */ tty = tty_driver_lookup_tty(driver, inode, index); if (IS_ERR(tty)) { tty_unlock(); mutex_unlock(&tty_mutex); return PTR_ERR(tty); } } if (tty) { retval = tty_reopen(tty); if (retval) tty = ERR_PTR(retval); } else tty = tty_init_dev(driver, index, 0); mutex_unlock(&tty_mutex); tty_driver_kref_put(driver); if (IS_ERR(tty)) { tty_unlock(); return PTR_ERR(tty); } retval = tty_add_file(tty, filp); if (retval) { tty_unlock(); tty_release(inode, filp); return retval; } check_tty_count(tty, "tty_open"); if (tty->driver->type == TTY_DRIVER_TYPE_PTY && tty->driver->subtype == PTY_TYPE_MASTER) noctty = 1; #ifdef TTY_DEBUG_HANGUP printk(KERN_DEBUG "opening %s...", tty->name); #endif if (tty->ops->open) retval = tty->ops->open(tty, filp); else retval = -ENODEV; filp->f_flags = saved_flags; if (!retval && test_bit(TTY_EXCLUSIVE, &tty->flags) && !capable(CAP_SYS_ADMIN)) retval = -EBUSY; if (retval) { #ifdef TTY_DEBUG_HANGUP printk(KERN_DEBUG "error %d in opening %s...", retval, tty->name); #endif tty_unlock(); /* need to call tty_release without BTM */ tty_release(inode, filp); if (retval != -ERESTARTSYS) return retval; if (signal_pending(current)) return retval; schedule(); /* * Need to reset f_op in case a hangup happened. */ tty_lock(); if (filp->f_op == &hung_up_tty_fops) filp->f_op = &tty_fops; tty_unlock(); goto retry_open; } tty_unlock(); mutex_lock(&tty_mutex); tty_lock(); spin_lock_irq(&current->sighand->siglock); if (!noctty && current->signal->leader && !current->signal->tty && tty->session == NULL) __proc_set_tty(current, tty); spin_unlock_irq(&current->sighand->siglock); tty_unlock(); mutex_unlock(&tty_mutex); return 0; } Commit Message: TTY: drop driver reference in tty_open fail path When tty_driver_lookup_tty fails in tty_open, we forget to drop a reference to the tty driver. This was added by commit 4a2b5fddd5 (Move tty lookup/reopen to caller). Fix that by adding tty_driver_kref_put to the fail path. I will refactor the code later. This is for the ease of backporting to stable. Introduced-in: v2.6.28-rc2 Signed-off-by: Jiri Slaby <[email protected]> Cc: stable <[email protected]> Cc: Alan Cox <[email protected]> Acked-by: Sukadev Bhattiprolu <[email protected]> Signed-off-by: Greg Kroah-Hartman <[email protected]> CWE ID: Target: 1 Example 2: Code: String Resource::GetMemoryDumpName() const { return String::Format( "web_cache/%s_resources/%ld", ResourceTypeToString(GetType(), Options().initiator_info.name), identifier_); } Commit Message: Check CORS using PassesAccessControlCheck() with supplied SecurityOrigin Partial revert of https://chromium-review.googlesource.com/535694. Bug: 799477 Change-Id: I878bb9bcb83afaafe8601293db9aa644fc5929b3 Reviewed-on: https://chromium-review.googlesource.com/898427 Commit-Queue: Hiroshige Hayashizaki <[email protected]> Reviewed-by: Kouhei Ueno <[email protected]> Reviewed-by: Yutaka Hirano <[email protected]> Reviewed-by: Takeshi Yoshino <[email protected]> Cr-Commit-Position: refs/heads/master@{#535176} CWE ID: CWE-200 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int pppol2tp_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t len, int flags) { int err; struct sk_buff *skb; struct sock *sk = sock->sk; err = -EIO; if (sk->sk_state & PPPOX_BOUND) goto end; msg->msg_namelen = 0; err = 0; skb = skb_recv_datagram(sk, flags & ~MSG_DONTWAIT, flags & MSG_DONTWAIT, &err); if (!skb) goto end; if (len > skb->len) len = skb->len; else if (len < skb->len) msg->msg_flags |= MSG_TRUNC; err = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, len); if (likely(err == 0)) err = len; kfree_skb(skb); end: return err; } Commit Message: net: rework recvmsg handler msg_name and msg_namelen logic This patch now always passes msg->msg_namelen as 0. recvmsg handlers must set msg_namelen to the proper size <= sizeof(struct sockaddr_storage) to return msg_name to the user. This prevents numerous uninitialized memory leaks we had in the recvmsg handlers and makes it harder for new code to accidentally leak uninitialized memory. Optimize for the case recvfrom is called with NULL as address. We don't need to copy the address at all, so set it to NULL before invoking the recvmsg handler. We can do so, because all the recvmsg handlers must cope with the case a plain read() is called on them. read() also sets msg_name to NULL. Also document these changes in include/linux/net.h as suggested by David Miller. Changes since RFC: Set msg->msg_name = NULL if user specified a NULL in msg_name but had a non-null msg_namelen in verify_iovec/verify_compat_iovec. This doesn't affect sendto as it would bail out earlier while trying to copy-in the address. It also more naturally reflects the logic by the callers of verify_iovec. With this change in place I could remove " if (!uaddr || msg_sys->msg_namelen == 0) msg->msg_name = NULL ". This change does not alter the user visible error logic as we ignore msg_namelen as long as msg_name is NULL. Also remove two unnecessary curly brackets in ___sys_recvmsg and change comments to netdev style. Cc: David Miller <[email protected]> Suggested-by: Eric Dumazet <[email protected]> Signed-off-by: Hannes Frederic Sowa <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-20 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: virtual void TreeNodeChanged(TreeModel* model, TreeModelNode* node) { changed_count_++; } Commit Message: Add OVERRIDE to ui::TreeModelObserver overridden methods. BUG=None TEST=None [email protected] Review URL: http://codereview.chromium.org/7046093 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@88827 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119 Target: 1 Example 2: Code: void RenderProcessHostImpl::ProcessDied(bool already_dead, RendererClosedDetails* known_details) { DCHECK(!within_process_died_observer_); DCHECK(!deleting_soon_); base::TerminationStatus status = base::TERMINATION_STATUS_NORMAL_TERMINATION; int exit_code = 0; if (known_details) { status = known_details->status; exit_code = known_details->exit_code; } else if (child_process_launcher_.get()) { status = child_process_launcher_->GetChildTerminationStatus(already_dead, &exit_code); if (already_dead && status == base::TERMINATION_STATUS_STILL_RUNNING) { status = base::TERMINATION_STATUS_PROCESS_CRASHED; } } RendererClosedDetails details(status, exit_code); child_process_launcher_.reset(); is_dead_ = true; if (route_provider_binding_.is_bound()) route_provider_binding_.Close(); associated_interfaces_.reset(); process_resource_coordinator_.reset(); ResetChannelProxy(); UpdateProcessPriority(); within_process_died_observer_ = true; NotificationService::current()->Notify( NOTIFICATION_RENDERER_PROCESS_CLOSED, Source<RenderProcessHost>(this), Details<RendererClosedDetails>(&details)); for (auto& observer : observers_) observer.RenderProcessExited(this, status, exit_code); within_process_died_observer_ = false; RemoveUserData(kSessionStorageHolderKey); base::IDMap<IPC::Listener*>::iterator iter(&listeners_); while (!iter.IsAtEnd()) { iter.GetCurrentValue()->OnMessageReceived(FrameHostMsg_RenderProcessGone( iter.GetCurrentKey(), static_cast<int>(status), exit_code)); iter.Advance(); } EnableSendQueue(); if (delayed_cleanup_needed_) Cleanup(); frame_sink_provider_.Unbind(); if (renderer_host_binding_.is_bound()) renderer_host_binding_.Unbind(); compositing_mode_reporter_.reset(); shared_bitmap_allocation_notifier_impl_.ChildDied(); HistogramController::GetInstance()->NotifyChildDied<RenderProcessHost>(this); } Commit Message: Correct mojo::WrapSharedMemoryHandle usage Fixes some incorrect uses of mojo::WrapSharedMemoryHandle which were assuming that the call actually has any control over the memory protection applied to a handle when mapped. Where fixing usage is infeasible for this CL, TODOs are added to annotate follow-up work. Also updates the API and documentation to (hopefully) improve clarity and avoid similar mistakes from being made in the future. BUG=792900 Cq-Include-Trybots: master.tryserver.chromium.android:android_optional_gpu_tests_rel;master.tryserver.chromium.linux:linux_optional_gpu_tests_rel;master.tryserver.chromium.mac:mac_optional_gpu_tests_rel;master.tryserver.chromium.win:win_optional_gpu_tests_rel Change-Id: I0578aaa9ca3bfcb01aaf2451315d1ede95458477 Reviewed-on: https://chromium-review.googlesource.com/818282 Reviewed-by: Wei Li <[email protected]> Reviewed-by: Lei Zhang <[email protected]> Reviewed-by: John Abd-El-Malek <[email protected]> Reviewed-by: Daniel Cheng <[email protected]> Reviewed-by: Sadrul Chowdhury <[email protected]> Reviewed-by: Yuzhu Shen <[email protected]> Reviewed-by: Robert Sesek <[email protected]> Commit-Queue: Ken Rockot <[email protected]> Cr-Commit-Position: refs/heads/master@{#530268} CWE ID: CWE-787 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: chrand_principal_2_svc(chrand_arg *arg, struct svc_req *rqstp) { static chrand_ret ret; krb5_keyblock *k; int nkeys; char *prime_arg, *funcname; gss_buffer_desc client_name, service_name; OM_uint32 minor_stat; kadm5_server_handle_t handle; const char *errmsg = NULL; xdr_free(xdr_chrand_ret, &ret); if ((ret.code = new_server_handle(arg->api_version, rqstp, &handle))) goto exit_func; if ((ret.code = check_handle((void *)handle))) goto exit_func; ret.api_version = handle->api_version; funcname = "kadm5_randkey_principal"; if (setup_gss_names(rqstp, &client_name, &service_name) < 0) { ret.code = KADM5_FAILURE; goto exit_func; } if (krb5_unparse_name(handle->context, arg->princ, &prime_arg)) { ret.code = KADM5_BAD_PRINCIPAL; goto exit_func; } if (cmp_gss_krb5_name(handle, rqst2name(rqstp), arg->princ)) { ret.code = randkey_principal_wrapper_3((void *)handle, arg->princ, FALSE, 0, NULL, &k, &nkeys); } else if (!(CHANGEPW_SERVICE(rqstp)) && kadm5int_acl_check(handle->context, rqst2name(rqstp), ACL_CHANGEPW, arg->princ, NULL)) { ret.code = kadm5_randkey_principal((void *)handle, arg->princ, &k, &nkeys); } else { log_unauth(funcname, prime_arg, &client_name, &service_name, rqstp); ret.code = KADM5_AUTH_CHANGEPW; } if(ret.code == KADM5_OK) { ret.keys = k; ret.n_keys = nkeys; } if(ret.code != KADM5_AUTH_CHANGEPW) { if( ret.code != 0 ) errmsg = krb5_get_error_message(handle->context, ret.code); log_done(funcname, prime_arg, errmsg, &client_name, &service_name, rqstp); if (errmsg != NULL) krb5_free_error_message(handle->context, errmsg); } free(prime_arg); gss_release_buffer(&minor_stat, &client_name); gss_release_buffer(&minor_stat, &service_name); exit_func: free_server_handle(handle); return &ret; } Commit Message: Fix leaks in kadmin server stubs [CVE-2015-8631] In each kadmind server stub, initialize the client_name and server_name variables, and release them in the cleanup handler. Many of the stubs will otherwise leak the client and server name if krb5_unparse_name() fails. Also make sure to free the prime_arg variables in rename_principal_2_svc(), or we can leak the first one if unparsing the second one fails. Discovered by Simo Sorce. CVE-2015-8631: In all versions of MIT krb5, an authenticated attacker can cause kadmind to leak memory by supplying a null principal name in a request which uses one. Repeating these requests will eventually cause kadmind to exhaust all available memory. CVSSv2 Vector: AV:N/AC:L/Au:S/C:N/I:N/A:C/E:POC/RL:OF/RC:C ticket: 8343 (new) target_version: 1.14-next target_version: 1.13-next tags: pullup CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void AppCacheUpdateJob::OnDestructionImminent(AppCacheHost* host) { PendingMasters::iterator found = pending_master_entries_.find(host->pending_master_entry_url()); DCHECK(found != pending_master_entries_.end()); PendingHosts& hosts = found->second; PendingHosts::iterator it = std::find(hosts.begin(), hosts.end(), host); DCHECK(it != hosts.end()); hosts.erase(it); } Commit Message: Fix possible map::end() dereference in AppCacheUpdateJob triggered by a compromised renderer. BUG=551044 Review URL: https://codereview.chromium.org/1418783005 Cr-Commit-Position: refs/heads/master@{#358815} CWE ID: Target: 1 Example 2: Code: static size_t parse_mb(struct parse_state *state, parse_mb_what_t what, const char *ptr, const char *end, const char *begin, zend_bool silent) { unsigned wchar; size_t consumed = 0; if (state->flags & PHP_HTTP_URL_PARSE_MBUTF8) { consumed = parse_mb_utf8(&wchar, ptr, end); } #ifdef PHP_HTTP_HAVE_WCHAR else if (state->flags & PHP_HTTP_URL_PARSE_MBLOC) { consumed = parse_mb_loc(&wchar, ptr, end); } #endif while (consumed) { if (!(state->flags & PHP_HTTP_URL_PARSE_TOPCT) || what == PARSE_HOSTINFO || what == PARSE_SCHEME) { if (what == PARSE_HOSTINFO && (state->flags & PHP_HTTP_URL_PARSE_TOIDN)) { /* idna */ } else if (state->flags & PHP_HTTP_URL_PARSE_MBUTF8) { if (!isualnum(wchar)) { break; } #ifdef PHP_HTTP_HAVE_WCHAR } else if (state->flags & PHP_HTTP_URL_PARSE_MBLOC) { if (!iswalnum(wchar)) { break; } #endif } PHP_HTTP_DUFF(consumed, state->buffer[state->offset++] = *ptr++); } else { int i = 0; PHP_HTTP_DUFF(consumed, state->buffer[state->offset++] = '%'; state->buffer[state->offset++] = parse_xdigits[((unsigned char) ptr[i]) >> 4]; state->buffer[state->offset++] = parse_xdigits[((unsigned char) ptr[i]) & 0xf]; ++i; ); } return consumed; } if (!silent) { TSRMLS_FETCH_FROM_CTX(state->ts); if (consumed) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to parse %s; unexpected multibyte sequence 0x%x at pos %u in '%s'", parse_what[what], wchar, (unsigned) (ptr - begin), begin); } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to parse %s; unexpected byte 0x%02x at pos %u in '%s'", parse_what[what], (unsigned char) *ptr, (unsigned) (ptr - begin), begin); } } return 0; } Commit Message: fix bug #71719 (Buffer overflow in HTTP url parsing functions) The parser's offset was not reset when we softfail in scheme parsing and continue to parse a path. Thanks to hlt99 at blinkenshell dot org for the report. CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void OneClickSigninSyncStarter::SigninFailed( const GoogleServiceAuthError& error) { FinishProfileSyncServiceSetup(); if (confirmation_required_ == CONFIRM_AFTER_SIGNIN) { switch (error.state()) { case GoogleServiceAuthError::SERVICE_UNAVAILABLE: DisplayFinalConfirmationBubble(l10n_util::GetStringUTF16( IDS_SYNC_UNRECOVERABLE_ERROR)); break; case GoogleServiceAuthError::REQUEST_CANCELED: break; default: DisplayFinalConfirmationBubble(l10n_util::GetStringUTF16( IDS_SYNC_ERROR_SIGNING_IN)); break; } } delete this; } Commit Message: Display confirmation dialog for untrusted signins BUG=252062 Review URL: https://chromiumcodereview.appspot.com/17482002 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@208520 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-200 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: image_transform_add(PNG_CONST image_transform **this, unsigned int max, png_uint_32 counter, char *name, size_t sizeof_name, size_t *pos, png_byte colour_type, png_byte bit_depth) { for (;;) /* until we manage to add something */ { png_uint_32 mask; image_transform *list; /* Find the next counter value, if the counter is zero this is the start * of the list. This routine always returns the current counter (not the * next) so it returns 0 at the end and expects 0 at the beginning. */ if (counter == 0) /* first time */ { image_transform_reset_count(); if (max <= 1) counter = 1; else counter = random_32(); } else /* advance the counter */ { switch (max) { case 0: ++counter; break; case 1: counter <<= 1; break; default: counter = random_32(); break; } } /* Now add all these items, if possible */ *this = &image_transform_end; list = image_transform_first; mask = 1; /* Go through the whole list adding anything that the counter selects: */ while (list != &image_transform_end) { if ((counter & mask) != 0 && list->enable && (max == 0 || list->local_use < max)) { /* Candidate to add: */ if (list->add(list, this, colour_type, bit_depth) || max == 0) { /* Added, so add to the name too. */ *pos = safecat(name, sizeof_name, *pos, " +"); *pos = safecat(name, sizeof_name, *pos, list->name); } else { /* Not useful and max>0, so remove it from *this: */ *this = list->next; list->next = 0; /* And, since we know it isn't useful, stop it being added again * in this run: */ list->local_use = max; } } mask <<= 1; list = list->list; } /* Now if anything was added we have something to do. */ if (*this != &image_transform_end) return counter; /* Nothing added, but was there anything in there to add? */ if (!image_transform_test_counter(counter, max)) return 0; } } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID: Target: 1 Example 2: Code: static struct dentry *nsfs_mount(struct file_system_type *fs_type, int flags, const char *dev_name, void *data) { return mount_pseudo(fs_type, "nsfs:", &nsfs_ops, &ns_dentry_operations, NSFS_MAGIC); } Commit Message: nsfs: mark dentry with DCACHE_RCUACCESS Andrey reported a use-after-free in __ns_get_path(): spin_lock include/linux/spinlock.h:299 [inline] lockref_get_not_dead+0x19/0x80 lib/lockref.c:179 __ns_get_path+0x197/0x860 fs/nsfs.c:66 open_related_ns+0xda/0x200 fs/nsfs.c:143 sock_ioctl+0x39d/0x440 net/socket.c:1001 vfs_ioctl fs/ioctl.c:45 [inline] do_vfs_ioctl+0x1bf/0x1780 fs/ioctl.c:685 SYSC_ioctl fs/ioctl.c:700 [inline] SyS_ioctl+0x8f/0xc0 fs/ioctl.c:691 We are under rcu read lock protection at that point: rcu_read_lock(); d = atomic_long_read(&ns->stashed); if (!d) goto slow; dentry = (struct dentry *)d; if (!lockref_get_not_dead(&dentry->d_lockref)) goto slow; rcu_read_unlock(); but don't use a proper RCU API on the free path, therefore a parallel __d_free() could free it at the same time. We need to mark the stashed dentry with DCACHE_RCUACCESS so that __d_free() will be called after all readers leave RCU. Fixes: e149ed2b805f ("take the targets of /proc/*/ns/* symlinks to separate fs") Cc: Alexander Viro <[email protected]> Cc: Andrew Morton <[email protected]> Reported-by: Andrey Konovalov <[email protected]> Signed-off-by: Cong Wang <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-416 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: NetworkThrottleManagerImpl::NetworkThrottleManagerImpl() : lifetime_median_estimate_(PercentileEstimator::kMedianPercentile, kInitialMedianInMs), outstanding_recomputation_timer_( base::MakeUnique<base::Timer>(false /* retain_user_task */, false /* is_repeating */)), tick_clock_(new base::DefaultTickClock()), weak_ptr_factory_(this) {} Commit Message: Replace base::MakeUnique with std::make_unique in net/. base/memory/ptr_util.h includes will be cleaned up later. Bug: 755727 Change-Id: Ibaf46f05c9b02b76f9a91e819984b087a8c0d434 Reviewed-on: https://chromium-review.googlesource.com/627300 Commit-Queue: Jeremy Roman <[email protected]> Reviewed-by: Daniel Cheng <[email protected]> Reviewed-by: Bence Béky <[email protected]> Cr-Commit-Position: refs/heads/master@{#498123} CWE ID: CWE-311 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void migrate_page_copy(struct page *newpage, struct page *page) { int cpupid; if (PageHuge(page) || PageTransHuge(page)) copy_huge_page(newpage, page); else copy_highpage(newpage, page); if (PageError(page)) SetPageError(newpage); if (PageReferenced(page)) SetPageReferenced(newpage); if (PageUptodate(page)) SetPageUptodate(newpage); if (TestClearPageActive(page)) { VM_BUG_ON_PAGE(PageUnevictable(page), page); SetPageActive(newpage); } else if (TestClearPageUnevictable(page)) SetPageUnevictable(newpage); if (PageChecked(page)) SetPageChecked(newpage); if (PageMappedToDisk(page)) SetPageMappedToDisk(newpage); if (PageDirty(page)) { clear_page_dirty_for_io(page); /* * Want to mark the page and the radix tree as dirty, and * redo the accounting that clear_page_dirty_for_io undid, * but we can't use set_page_dirty because that function * is actually a signal that all of the page has become dirty. * Whereas only part of our page may be dirty. */ if (PageSwapBacked(page)) SetPageDirty(newpage); else __set_page_dirty_nobuffers(newpage); } if (page_is_young(page)) set_page_young(newpage); if (page_is_idle(page)) set_page_idle(newpage); /* * Copy NUMA information to the new page, to prevent over-eager * future migrations of this same page. */ cpupid = page_cpupid_xchg_last(page, -1); page_cpupid_xchg_last(newpage, cpupid); ksm_migrate_page(newpage, page); /* * Please do not reorder this without considering how mm/ksm.c's * get_ksm_page() depends upon ksm_migrate_page() and PageSwapCache(). */ if (PageSwapCache(page)) ClearPageSwapCache(page); ClearPagePrivate(page); set_page_private(page, 0); /* * If any waiters have accumulated on the new page then * wake them up. */ if (PageWriteback(newpage)) end_page_writeback(newpage); } Commit Message: mm: migrate dirty page without clear_page_dirty_for_io etc clear_page_dirty_for_io() has accumulated writeback and memcg subtleties since v2.6.16 first introduced page migration; and the set_page_dirty() which completed its migration of PageDirty, later had to be moderated to __set_page_dirty_nobuffers(); then PageSwapBacked had to skip that too. No actual problems seen with this procedure recently, but if you look into what the clear_page_dirty_for_io(page)+set_page_dirty(newpage) is actually achieving, it turns out to be nothing more than moving the PageDirty flag, and its NR_FILE_DIRTY stat from one zone to another. It would be good to avoid a pile of irrelevant decrementations and incrementations, and improper event counting, and unnecessary descent of the radix_tree under tree_lock (to set the PAGECACHE_TAG_DIRTY which radix_tree_replace_slot() left in place anyway). Do the NR_FILE_DIRTY movement, like the other stats movements, while interrupts still disabled in migrate_page_move_mapping(); and don't even bother if the zone is the same. Do the PageDirty movement there under tree_lock too, where old page is frozen and newpage not yet visible: bearing in mind that as soon as newpage becomes visible in radix_tree, an un-page-locked set_page_dirty() might interfere (or perhaps that's just not possible: anything doing so should already hold an additional reference to the old page, preventing its migration; but play safe). But we do still need to transfer PageDirty in migrate_page_copy(), for those who don't go the mapping route through migrate_page_move_mapping(). Signed-off-by: Hugh Dickins <[email protected]> Cc: Christoph Lameter <[email protected]> Cc: "Kirill A. Shutemov" <[email protected]> Cc: Rik van Riel <[email protected]> Cc: Vlastimil Babka <[email protected]> Cc: Davidlohr Bueso <[email protected]> Cc: Oleg Nesterov <[email protected]> Cc: Sasha Levin <[email protected]> Cc: Dmitry Vyukov <[email protected]> Cc: KOSAKI Motohiro <[email protected]> Signed-off-by: Andrew Morton <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-476 Target: 1 Example 2: Code: DocumentInit& DocumentInit::WithOwnerDocument(Document* owner_document) { DCHECK(!owner_document_); owner_document_ = owner_document; return *this; } Commit Message: Inherit CSP when self-navigating to local-scheme URL As the linked bug example shows, we should inherit CSP when we navigate to a local-scheme URL (even if we are in a main browsing context). Bug: 799747 Change-Id: I8413aa8e8049461ebcf0ffbf7b04c41d1340af02 Reviewed-on: https://chromium-review.googlesource.com/c/1234337 Reviewed-by: Mike West <[email protected]> Commit-Queue: Andy Paicu <[email protected]> Cr-Commit-Position: refs/heads/master@{#597889} CWE ID: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int hci_sock_getname(struct socket *sock, struct sockaddr *addr, int *addr_len, int peer) { struct sockaddr_hci *haddr = (struct sockaddr_hci *) addr; struct sock *sk = sock->sk; struct hci_dev *hdev = hci_pi(sk)->hdev; BT_DBG("sock %p sk %p", sock, sk); if (!hdev) return -EBADFD; lock_sock(sk); *addr_len = sizeof(*haddr); haddr->hci_family = AF_BLUETOOTH; haddr->hci_dev = hdev->id; release_sock(sk); return 0; } Commit Message: Bluetooth: HCI - Fix info leak via getsockname() The HCI code fails to initialize the hci_channel member of struct sockaddr_hci and that for leaks two bytes kernel stack via the getsockname() syscall. Initialize hci_channel with 0 to avoid the info leak. Signed-off-by: Mathias Krause <[email protected]> Cc: Marcel Holtmann <[email protected]> Cc: Gustavo Padovan <[email protected]> Cc: Johan Hedberg <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-200 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static Image *ReadDPSImage(const ImageInfo *image_info,ExceptionInfo *exception) { const char *client_name; Display *display; float pixels_per_point; Image *image; int sans, status; Pixmap pixmap; register IndexPacket *indexes; register ssize_t i; register PixelPacket *q; register size_t pixel; Screen *screen; ssize_t x, y; XColor *colors; XImage *dps_image; XRectangle page, bits_per_pixel; XResourceInfo resource_info; XrmDatabase resource_database; XStandardColormap *map_info; XVisualInfo *visual_info; /* Open X server connection. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); display=XOpenDisplay(image_info->server_name); if (display == (Display *) NULL) return((Image *) NULL); /* Set our forgiving exception handler. */ (void) XSetErrorHandler(XError); /* Open image file. */ image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) return((Image *) NULL); /* Get user defaults from X resource database. */ client_name=GetClientName(); resource_database=XGetResourceDatabase(display,client_name); XGetResourceInfo(image_info,resource_database,client_name,&resource_info); /* Allocate standard colormap. */ map_info=XAllocStandardColormap(); visual_info=(XVisualInfo *) NULL; if (map_info == (XStandardColormap *) NULL) ThrowReaderException(ResourceLimitError,"UnableToCreateStandardColormap") else { /* Initialize visual info. */ (void) CloneString(&resource_info.visual_type,"default"); visual_info=XBestVisualInfo(display,map_info,&resource_info); map_info->colormap=(Colormap) NULL; } if ((map_info == (XStandardColormap *) NULL) || (visual_info == (XVisualInfo *) NULL)) { image=DestroyImage(image); XFreeResources(display,visual_info,map_info,(XPixelInfo *) NULL, (XFontStruct *) NULL,&resource_info,(XWindowInfo *) NULL); return((Image *) NULL); } /* Create a pixmap the appropriate size for the image. */ screen=ScreenOfDisplay(display,visual_info->screen); pixels_per_point=XDPSPixelsPerPoint(screen); if ((image->x_resolution != 0.0) && (image->y_resolution != 0.0)) pixels_per_point=MagickMin(image->x_resolution,image->y_resolution)/ DefaultResolution; status=XDPSCreatePixmapForEPSF((DPSContext) NULL,screen, GetBlobFileHandle(image),visual_info->depth,pixels_per_point,&pixmap, &bits_per_pixel,&page); if ((status == dps_status_failure) || (status == dps_status_no_extension)) { image=DestroyImage(image); XFreeResources(display,visual_info,map_info,(XPixelInfo *) NULL, (XFontStruct *) NULL,&resource_info,(XWindowInfo *) NULL); return((Image *) NULL); } /* Rasterize the file into the pixmap. */ status=XDPSImageFileIntoDrawable((DPSContext) NULL,screen,pixmap, GetBlobFileHandle(image),(int) bits_per_pixel.height,visual_info->depth, &page,-page.x,-page.y,pixels_per_point,MagickTrue,MagickFalse,MagickTrue, &sans); if (status != dps_status_success) { image=DestroyImage(image); XFreeResources(display,visual_info,map_info,(XPixelInfo *) NULL, (XFontStruct *) NULL,&resource_info,(XWindowInfo *) NULL); return((Image *) NULL); } /* Initialize DPS X image. */ dps_image=XGetImage(display,pixmap,0,0,bits_per_pixel.width, bits_per_pixel.height,AllPlanes,ZPixmap); (void) XFreePixmap(display,pixmap); if (dps_image == (XImage *) NULL) { image=DestroyImage(image); XFreeResources(display,visual_info,map_info,(XPixelInfo *) NULL, (XFontStruct *) NULL,&resource_info,(XWindowInfo *) NULL); return((Image *) NULL); } /* Get the colormap colors. */ colors=(XColor *) AcquireQuantumMemory(visual_info->colormap_size, sizeof(*colors)); if (colors == (XColor *) NULL) { image=DestroyImage(image); XDestroyImage(dps_image); XFreeResources(display,visual_info,map_info,(XPixelInfo *) NULL, (XFontStruct *) NULL,&resource_info,(XWindowInfo *) NULL); return((Image *) NULL); } if ((visual_info->klass != DirectColor) && (visual_info->klass != TrueColor)) for (i=0; i < visual_info->colormap_size; i++) { colors[i].pixel=(size_t) i; colors[i].pad=0; } else { size_t blue, blue_bit, green, green_bit, red, red_bit; /* DirectColor or TrueColor visual. */ red=0; green=0; blue=0; red_bit=visual_info->red_mask & (~(visual_info->red_mask)+1); green_bit=visual_info->green_mask & (~(visual_info->green_mask)+1); blue_bit=visual_info->blue_mask & (~(visual_info->blue_mask)+1); for (i=0; i < visual_info->colormap_size; i++) { colors[i].pixel=red | green | blue; colors[i].pad=0; red+=red_bit; if (red > visual_info->red_mask) red=0; green+=green_bit; if (green > visual_info->green_mask) green=0; blue+=blue_bit; if (blue > visual_info->blue_mask) blue=0; } } (void) XQueryColors(display,XDefaultColormap(display,visual_info->screen), colors,visual_info->colormap_size); /* Convert X image to MIFF format. */ if ((visual_info->klass != TrueColor) && (visual_info->klass != DirectColor)) image->storage_class=PseudoClass; image->columns=(size_t) dps_image->width; image->rows=(size_t) dps_image->height; if (image_info->ping != MagickFalse) { (void) CloseBlob(image); return(GetFirstImageInList(image)); } switch (image->storage_class) { case DirectClass: default: { register size_t color, index; size_t blue_mask, blue_shift, green_mask, green_shift, red_mask, red_shift; /* Determine shift and mask for red, green, and blue. */ red_mask=visual_info->red_mask; red_shift=0; while ((red_mask != 0) && ((red_mask & 0x01) == 0)) { red_mask>>=1; red_shift++; } green_mask=visual_info->green_mask; green_shift=0; while ((green_mask != 0) && ((green_mask & 0x01) == 0)) { green_mask>>=1; green_shift++; } blue_mask=visual_info->blue_mask; blue_shift=0; while ((blue_mask != 0) && ((blue_mask & 0x01) == 0)) { blue_mask>>=1; blue_shift++; } /* Convert X image to DirectClass packets. */ if ((visual_info->colormap_size > 0) && (visual_info->klass == DirectColor)) for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { pixel=XGetPixel(dps_image,x,y); index=(pixel >> red_shift) & red_mask; SetPixelRed(q,ScaleShortToQuantum(colors[index].red)); index=(pixel >> green_shift) & green_mask; SetPixelGreen(q,ScaleShortToQuantum(colors[index].green)); index=(pixel >> blue_shift) & blue_mask; SetPixelBlue(q,ScaleShortToQuantum(colors[index].blue)); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (SetImageProgress(image,LoadImageTag,y,image->rows) == MagickFalse) break; } else for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { pixel=XGetPixel(dps_image,x,y); color=(pixel >> red_shift) & red_mask; color=(color*65535L)/red_mask; SetPixelRed(q,ScaleShortToQuantum((unsigned short) color)); color=(pixel >> green_shift) & green_mask; color=(color*65535L)/green_mask; SetPixelGreen(q,ScaleShortToQuantum((unsigned short) color)); color=(pixel >> blue_shift) & blue_mask; color=(color*65535L)/blue_mask; SetPixelBlue(q,ScaleShortToQuantum((unsigned short) color)); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (SetImageProgress(image,LoadImageTag,y,image->rows) == MagickFalse) break; } break; } case PseudoClass: { /* Create colormap. */ if (AcquireImageColormap(image,(size_t) visual_info->colormap_size) == MagickFalse) { image=DestroyImage(image); colors=(XColor *) RelinquishMagickMemory(colors); XDestroyImage(dps_image); XFreeResources(display,visual_info,map_info,(XPixelInfo *) NULL, (XFontStruct *) NULL,&resource_info,(XWindowInfo *) NULL); return((Image *) NULL); } for (i=0; i < (ssize_t) image->colors; i++) { image->colormap[colors[i].pixel].red=ScaleShortToQuantum(colors[i].red); image->colormap[colors[i].pixel].green= ScaleShortToQuantum(colors[i].green); image->colormap[colors[i].pixel].blue= ScaleShortToQuantum(colors[i].blue); } /* Convert X image to PseudoClass packets. */ for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) SetPixelIndex(indexes+x,(unsigned short) XGetPixel(dps_image,x,y)); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (SetImageProgress(image,LoadImageTag,y,image->rows) == MagickFalse) break; } break; } } colors=(XColor *) RelinquishMagickMemory(colors); XDestroyImage(dps_image); if (image->storage_class == PseudoClass) (void) SyncImage(image); /* Rasterize matte image. */ status=XDPSCreatePixmapForEPSF((DPSContext) NULL,screen, GetBlobFileHandle(image),1,pixels_per_point,&pixmap,&bits_per_pixel,&page); if ((status != dps_status_failure) && (status != dps_status_no_extension)) { status=XDPSImageFileIntoDrawable((DPSContext) NULL,screen,pixmap, GetBlobFileHandle(image),(int) bits_per_pixel.height,1,&page,-page.x, -page.y,pixels_per_point,MagickTrue,MagickTrue,MagickTrue,&sans); if (status == dps_status_success) { XImage *matte_image; /* Initialize image matte. */ matte_image=XGetImage(display,pixmap,0,0,bits_per_pixel.width, bits_per_pixel.height,AllPlanes,ZPixmap); (void) XFreePixmap(display,pixmap); if (matte_image != (XImage *) NULL) { image->storage_class=DirectClass; image->matte=MagickTrue; for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelOpacity(q,OpaqueOpacity); if (XGetPixel(matte_image,x,y) == 0) SetPixelOpacity(q,TransparentOpacity); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } XDestroyImage(matte_image); } } } /* Relinquish resources. */ XFreeResources(display,visual_info,map_info,(XPixelInfo *) NULL, (XFontStruct *) NULL,&resource_info,(XWindowInfo *) NULL); (void) CloseBlob(image); return(GetFirstImageInList(image)); } Commit Message: CWE ID: CWE-119 Target: 1 Example 2: Code: bool TopSitesImpl::HasBlacklistedItems() const { const base::DictionaryValue* blacklist = pref_service_->GetDictionary(kMostVisitedURLsBlacklist); return blacklist && !blacklist->empty(); } Commit Message: TopSites: Clear thumbnails from the cache when their URLs get removed We already cleared the thumbnails from persistent storage, but they remained in the in-memory cache, so they remained accessible (until the next Chrome restart) even after all browsing data was cleared. Bug: 758169 Change-Id: Id916d22358430a82e6d5043ac04fa463a32f824f Reviewed-on: https://chromium-review.googlesource.com/758640 Commit-Queue: Marc Treib <[email protected]> Reviewed-by: Sylvain Defresne <[email protected]> Cr-Commit-Position: refs/heads/master@{#514861} CWE ID: CWE-200 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static jobject Bitmap_createFromParcel(JNIEnv* env, jobject, jobject parcel) { if (parcel == NULL) { SkDebugf("-------- unparcel parcel is NULL\n"); return NULL; } android::Parcel* p = android::parcelForJavaObject(env, parcel); const bool isMutable = p->readInt32() != 0; const SkColorType colorType = (SkColorType)p->readInt32(); const SkAlphaType alphaType = (SkAlphaType)p->readInt32(); const int width = p->readInt32(); const int height = p->readInt32(); const int rowBytes = p->readInt32(); const int density = p->readInt32(); if (kN32_SkColorType != colorType && kRGB_565_SkColorType != colorType && kARGB_4444_SkColorType != colorType && kIndex_8_SkColorType != colorType && kAlpha_8_SkColorType != colorType) { SkDebugf("Bitmap_createFromParcel unknown colortype: %d\n", colorType); return NULL; } SkBitmap* bitmap = new SkBitmap; bitmap->setInfo(SkImageInfo::Make(width, height, colorType, alphaType), rowBytes); SkColorTable* ctable = NULL; if (colorType == kIndex_8_SkColorType) { int count = p->readInt32(); if (count > 0) { size_t size = count * sizeof(SkPMColor); const SkPMColor* src = (const SkPMColor*)p->readInplace(size); ctable = new SkColorTable(src, count); } } jbyteArray buffer = GraphicsJNI::allocateJavaPixelRef(env, bitmap, ctable); if (NULL == buffer) { SkSafeUnref(ctable); delete bitmap; return NULL; } SkSafeUnref(ctable); size_t size = bitmap->getSize(); android::Parcel::ReadableBlob blob; android::status_t status = p->readBlob(size, &blob); if (status) { doThrowRE(env, "Could not read bitmap from parcel blob."); delete bitmap; return NULL; } bitmap->lockPixels(); memcpy(bitmap->getPixels(), blob.data(), size); bitmap->unlockPixels(); blob.release(); return GraphicsJNI::createBitmap(env, bitmap, buffer, getPremulBitmapCreateFlags(isMutable), NULL, NULL, density); } Commit Message: Make Bitmap_createFromParcel check the color count. DO NOT MERGE When reading from the parcel, if the number of colors is invalid, early exit. Add two more checks: setInfo must return true, and Parcel::readInplace must return non-NULL. The former ensures that the previously read values (width, height, etc) were valid, and the latter checks that the Parcel had enough data even if the number of colors was reasonable. Also use an auto-deleter to handle deletion of the SkBitmap. Cherry pick from change-Id: Icbd562d6d1f131a723724883fd31822d337cf5a6 BUG=19666945 Change-Id: Iab0d218c41ae0c39606e333e44cda078eef32291 CWE ID: CWE-189 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int attach_recursive_mnt(struct mount *source_mnt, struct mount *dest_mnt, struct mountpoint *dest_mp, struct path *parent_path) { HLIST_HEAD(tree_list); struct mount *child, *p; struct hlist_node *n; int err; if (IS_MNT_SHARED(dest_mnt)) { err = invent_group_ids(source_mnt, true); if (err) goto out; err = propagate_mnt(dest_mnt, dest_mp, source_mnt, &tree_list); lock_mount_hash(); if (err) goto out_cleanup_ids; for (p = source_mnt; p; p = next_mnt(p, source_mnt)) set_mnt_shared(p); } else { lock_mount_hash(); } if (parent_path) { detach_mnt(source_mnt, parent_path); attach_mnt(source_mnt, dest_mnt, dest_mp); touch_mnt_namespace(source_mnt->mnt_ns); } else { mnt_set_mountpoint(dest_mnt, dest_mp, source_mnt); commit_tree(source_mnt, NULL); } hlist_for_each_entry_safe(child, n, &tree_list, mnt_hash) { struct mount *q; hlist_del_init(&child->mnt_hash); q = __lookup_mnt_last(&child->mnt_parent->mnt, child->mnt_mountpoint); commit_tree(child, q); } unlock_mount_hash(); return 0; out_cleanup_ids: while (!hlist_empty(&tree_list)) { child = hlist_entry(tree_list.first, struct mount, mnt_hash); umount_tree(child, UMOUNT_SYNC); } unlock_mount_hash(); cleanup_group_ids(source_mnt, NULL); out: return err; } Commit Message: mnt: Add a per mount namespace limit on the number of mounts CAI Qian <[email protected]> pointed out that the semantics of shared subtrees make it possible to create an exponentially increasing number of mounts in a mount namespace. mkdir /tmp/1 /tmp/2 mount --make-rshared / for i in $(seq 1 20) ; do mount --bind /tmp/1 /tmp/2 ; done Will create create 2^20 or 1048576 mounts, which is a practical problem as some people have managed to hit this by accident. As such CVE-2016-6213 was assigned. Ian Kent <[email protected]> described the situation for autofs users as follows: > The number of mounts for direct mount maps is usually not very large because of > the way they are implemented, large direct mount maps can have performance > problems. There can be anywhere from a few (likely case a few hundred) to less > than 10000, plus mounts that have been triggered and not yet expired. > > Indirect mounts have one autofs mount at the root plus the number of mounts that > have been triggered and not yet expired. > > The number of autofs indirect map entries can range from a few to the common > case of several thousand and in rare cases up to between 30000 and 50000. I've > not heard of people with maps larger than 50000 entries. > > The larger the number of map entries the greater the possibility for a large > number of active mounts so it's not hard to expect cases of a 1000 or somewhat > more active mounts. So I am setting the default number of mounts allowed per mount namespace at 100,000. This is more than enough for any use case I know of, but small enough to quickly stop an exponential increase in mounts. Which should be perfect to catch misconfigurations and malfunctioning programs. For anyone who needs a higher limit this can be changed by writing to the new /proc/sys/fs/mount-max sysctl. Tested-by: CAI Qian <[email protected]> Signed-off-by: "Eric W. Biederman" <[email protected]> CWE ID: CWE-400 Target: 1 Example 2: Code: bool GetStringProperty( XID window, const std::string& property_name, std::string* value) { Atom type = None; int format = 0; // size in bits of each item in 'property' unsigned long num_items = 0; unsigned char* property = NULL; int result = GetProperty(window, property_name, 1024, &type, &format, &num_items, &property); if (result != Success) return false; if (format != 8) { XFree(property); return false; } value->assign(reinterpret_cast<char*>(property), num_items); XFree(property); return true; } Commit Message: Make shared memory segments writable only by their rightful owners. BUG=143859 TEST=Chrome's UI still works on Linux and Chrome OS Review URL: https://chromiumcodereview.appspot.com/10854242 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@158289 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void RenderViewImpl::FrameDidStartLoading(WebFrame* frame) { DCHECK_GE(frames_in_progress_, 0); if (frames_in_progress_ == 0) { for (auto& observer : observers_) observer.DidStartLoading(); } frames_in_progress_++; } Commit Message: Prevent renderer initiated back navigation to cancel a browser one. Renderer initiated back/forward navigations must not be able to cancel ongoing browser initiated navigation if they are not user initiated. Note: 'normal' renderer initiated navigation uses the FrameHost::BeginNavigation() path. A code similar to this patch is done in NavigatorImpl::OnBeginNavigation(). Test: ----- Added: NavigationBrowserTest. * HistoryBackInBeforeUnload * HistoryBackInBeforeUnloadAfterSetTimeout * HistoryBackCancelPendingNavigationNoUserGesture * HistoryBackCancelPendingNavigationUserGesture Fixed: * (WPT) .../the-history-interface/traverse_the_history_2.html * (WPT) .../the-history-interface/traverse_the_history_3.html * (WPT) .../the-history-interface/traverse_the_history_4.html * (WPT) .../the-history-interface/traverse_the_history_5.html Bug: 879965 Change-Id: I1a9bfaaea1ffc219e6c32f6e676b660e746c578c Reviewed-on: https://chromium-review.googlesource.com/1209744 Commit-Queue: Arthur Sonzogni <[email protected]> Reviewed-by: Daniel Cheng <[email protected]> Reviewed-by: Mustaq Ahmed <[email protected]> Reviewed-by: Camille Lamy <[email protected]> Reviewed-by: Charlie Reis <[email protected]> Cr-Commit-Position: refs/heads/master@{#592823} CWE ID: CWE-254 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int kvm_vm_ioctl_assign_device(struct kvm *kvm, struct kvm_assigned_pci_dev *assigned_dev) { int r = 0, idx; struct kvm_assigned_dev_kernel *match; struct pci_dev *dev; if (!(assigned_dev->flags & KVM_DEV_ASSIGN_ENABLE_IOMMU)) return -EINVAL; mutex_lock(&kvm->lock); idx = srcu_read_lock(&kvm->srcu); match = kvm_find_assigned_dev(&kvm->arch.assigned_dev_head, assigned_dev->assigned_dev_id); if (match) { /* device already assigned */ r = -EEXIST; goto out; } match = kzalloc(sizeof(struct kvm_assigned_dev_kernel), GFP_KERNEL); if (match == NULL) { printk(KERN_INFO "%s: Couldn't allocate memory\n", __func__); r = -ENOMEM; goto out; } dev = pci_get_domain_bus_and_slot(assigned_dev->segnr, assigned_dev->busnr, assigned_dev->devfn); if (!dev) { printk(KERN_INFO "%s: host device not found\n", __func__); r = -EINVAL; goto out_free; } if (pci_enable_device(dev)) { printk(KERN_INFO "%s: Could not enable PCI device\n", __func__); r = -EBUSY; goto out_put; } r = pci_request_regions(dev, "kvm_assigned_device"); if (r) { printk(KERN_INFO "%s: Could not get access to device regions\n", __func__); goto out_disable; } pci_reset_function(dev); pci_save_state(dev); match->pci_saved_state = pci_store_saved_state(dev); if (!match->pci_saved_state) printk(KERN_DEBUG "%s: Couldn't store %s saved state\n", __func__, dev_name(&dev->dev)); match->assigned_dev_id = assigned_dev->assigned_dev_id; match->host_segnr = assigned_dev->segnr; match->host_busnr = assigned_dev->busnr; match->host_devfn = assigned_dev->devfn; match->flags = assigned_dev->flags; match->dev = dev; spin_lock_init(&match->intx_lock); match->irq_source_id = -1; match->kvm = kvm; match->ack_notifier.irq_acked = kvm_assigned_dev_ack_irq; list_add(&match->list, &kvm->arch.assigned_dev_head); if (!kvm->arch.iommu_domain) { r = kvm_iommu_map_guest(kvm); if (r) goto out_list_del; } r = kvm_assign_device(kvm, match); if (r) goto out_list_del; out: srcu_read_unlock(&kvm->srcu, idx); mutex_unlock(&kvm->lock); return r; out_list_del: if (pci_load_and_free_saved_state(dev, &match->pci_saved_state)) printk(KERN_INFO "%s: Couldn't reload %s saved state\n", __func__, dev_name(&dev->dev)); list_del(&match->list); pci_release_regions(dev); out_disable: pci_disable_device(dev); out_put: pci_dev_put(dev); out_free: kfree(match); srcu_read_unlock(&kvm->srcu, idx); mutex_unlock(&kvm->lock); return r; } Commit Message: KVM: Device assignment permission checks (cherry picked from commit 3d27e23b17010c668db311140b17bbbb70c78fb9) Only allow KVM device assignment to attach to devices which: - Are not bridges - Have BAR resources (assume others are special devices) - The user has permissions to use Assigning a bridge is a configuration error, it's not supported, and typically doesn't result in the behavior the user is expecting anyway. Devices without BAR resources are typically chipset components that also don't have host drivers. We don't want users to hold such devices captive or cause system problems by fencing them off into an iommu domain. We determine "permission to use" by testing whether the user has access to the PCI sysfs resource files. By default a normal user will not have access to these files, so it provides a good indication that an administration agent has granted the user access to the device. [Yang Bai: add missing #include] [avi: fix comment style] Signed-off-by: Alex Williamson <[email protected]> Signed-off-by: Yang Bai <[email protected]> Signed-off-by: Marcelo Tosatti <[email protected]> Signed-off-by: Greg Kroah-Hartman <[email protected]> CWE ID: CWE-264 Target: 1 Example 2: Code: static int rose_del_node(struct rose_route_struct *rose_route, struct net_device *dev) { struct rose_node *rose_node; struct rose_neigh *rose_neigh; int i, err = 0; spin_lock_bh(&rose_node_list_lock); spin_lock_bh(&rose_neigh_list_lock); rose_node = rose_node_list; while (rose_node != NULL) { if ((rose_node->mask == rose_route->mask) && (rosecmpm(&rose_route->address, &rose_node->address, rose_route->mask) == 0)) break; rose_node = rose_node->next; } if (rose_node == NULL || rose_node->loopback) { err = -EINVAL; goto out; } rose_neigh = rose_neigh_list; while (rose_neigh != NULL) { if (ax25cmp(&rose_route->neighbour, &rose_neigh->callsign) == 0 && rose_neigh->dev == dev) break; rose_neigh = rose_neigh->next; } if (rose_neigh == NULL) { err = -EINVAL; goto out; } for (i = 0; i < rose_node->count; i++) { if (rose_node->neighbour[i] == rose_neigh) { rose_neigh->count--; if (rose_neigh->count == 0 && rose_neigh->use == 0) rose_remove_neigh(rose_neigh); rose_node->count--; if (rose_node->count == 0) { rose_remove_node(rose_node); } else { switch (i) { case 0: rose_node->neighbour[0] = rose_node->neighbour[1]; case 1: rose_node->neighbour[1] = rose_node->neighbour[2]; case 2: break; } } goto out; } } err = -EINVAL; out: spin_unlock_bh(&rose_neigh_list_lock); spin_unlock_bh(&rose_node_list_lock); return err; } Commit Message: rose: Add length checks to CALL_REQUEST parsing Define some constant offsets for CALL_REQUEST based on the description at <http://www.techfest.com/networking/wan/x25plp.htm> and the definition of ROSE as using 10-digit (5-byte) addresses. Use them consistently. Validate all implicit and explicit facilities lengths. Validate the address length byte rather than either trusting or assuming its value. Signed-off-by: Ben Hutchings <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-20 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void UserSelectionScreen::FillMultiProfileUserPrefs( user_manager::User* user, base::DictionaryValue* user_dict, bool is_signin_to_add) { if (!is_signin_to_add) { user_dict->SetBoolean(kKeyMultiProfilesAllowed, true); return; } bool is_user_allowed; ash::mojom::MultiProfileUserBehavior policy; GetMultiProfilePolicy(user, &is_user_allowed, &policy); user_dict->SetBoolean(kKeyMultiProfilesAllowed, is_user_allowed); user_dict->SetInteger(kKeyMultiProfilesPolicy, static_cast<int>(policy)); } Commit Message: cros: Check initial auth type when showing views login. Bug: 859611 Change-Id: I0298db9bbf4aed6bd40600aef2e1c5794e8cd058 Reviewed-on: https://chromium-review.googlesource.com/1123056 Reviewed-by: Xiaoyin Hu <[email protected]> Commit-Queue: Jacob Dufault <[email protected]> Cr-Commit-Position: refs/heads/master@{#572224} CWE ID: Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void ImageBitmapFactories::ImageBitmapLoader::DidFinishLoading() { DOMArrayBuffer* array_buffer = loader_->ArrayBufferResult(); if (!array_buffer) { RejectPromise(kAllocationFailureImageBitmapRejectionReason); return; } ScheduleAsyncImageBitmapDecoding(array_buffer); } Commit Message: Fix UAP in ImageBitmapLoader/FileReaderLoader FileReaderLoader stores its client as a raw pointer, so in cases like ImageBitmapLoader where the FileReaderLoaderClient really is garbage collected we have to make sure to destroy the FileReaderLoader when the ExecutionContext that owns it is destroyed. Bug: 913970 Change-Id: I40b02115367cf7bf5bbbbb8e9b57874d2510f861 Reviewed-on: https://chromium-review.googlesource.com/c/1374511 Reviewed-by: Jeremy Roman <[email protected]> Commit-Queue: Marijn Kruisselbrink <[email protected]> Cr-Commit-Position: refs/heads/master@{#616342} CWE ID: CWE-416 Target: 1 Example 2: Code: void TemplateURL::SetPrepopulateId(int id) { data_.prepopulate_id = id; const bool prepopulated = id > 0; for (TemplateURLRef& ref : url_refs_) ref.prepopulated_ = prepopulated; suggestions_url_ref_.prepopulated_ = prepopulated; instant_url_ref_.prepopulated_ = prepopulated; image_url_ref_.prepopulated_ = prepopulated; new_tab_url_ref_.prepopulated_ = prepopulated; contextual_search_url_ref_.prepopulated_ = prepopulated; } Commit Message: [Contextual Search] Change "Now on Tap" to "Contextual Cards" BUG=644934 Review-Url: https://codereview.chromium.org/2361163003 Cr-Commit-Position: refs/heads/master@{#420899} CWE ID: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: long long Cluster::GetTimeCode() const { long long pos; long len; const long status = Load(pos, len); if (status < 0) //error return status; return m_timecode; } 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 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: fm_mgr_config_init ( OUT p_fm_config_conx_hdlt *p_hdl, IN int instance, OPTIONAL IN char *rem_address, OPTIONAL IN char *community ) { fm_config_conx_hdl *hdl; fm_mgr_config_errno_t res = FM_CONF_OK; if ( (hdl = calloc(1,sizeof(fm_config_conx_hdl))) == NULL ) { res = FM_CONF_NO_MEM; goto cleanup; } hdl->instance = instance; *p_hdl = hdl; if(!rem_address || (strcmp(rem_address,"localhost") == 0)) { if ( fm_mgr_config_mgr_connect(hdl, FM_MGR_SM) == FM_CONF_INIT_ERR ) { res = FM_CONF_INIT_ERR; goto cleanup; } if ( fm_mgr_config_mgr_connect(hdl, FM_MGR_PM) == FM_CONF_INIT_ERR ) { res = FM_CONF_INIT_ERR; goto cleanup; } if ( fm_mgr_config_mgr_connect(hdl, FM_MGR_FE) == FM_CONF_INIT_ERR ) { res = FM_CONF_INIT_ERR; goto cleanup; } } return res; cleanup: if ( hdl ) { free(hdl); hdl = NULL; } return res; } Commit Message: Fix scripts and code that use well-known tmp files. CWE ID: CWE-362 Target: 1 Example 2: Code: void mwifiex_set_tpc_params(struct mwifiex_private *priv, struct mwifiex_uap_bss_param *bss_cfg, struct cfg80211_ap_settings *params) { const u8 *tpc_ie; tpc_ie = cfg80211_find_ie(WLAN_EID_TPC_REQUEST, params->beacon.tail, params->beacon.tail_len); if (tpc_ie) bss_cfg->power_constraint = *(tpc_ie + 2); else bss_cfg->power_constraint = 0; } Commit Message: mwifiex: Fix three heap overflow at parsing element in cfg80211_ap_settings mwifiex_update_vs_ie(),mwifiex_set_uap_rates() and mwifiex_set_wmm_params() call memcpy() without checking the destination size.Since the source is given from user-space, this may trigger a heap buffer overflow. Fix them by putting the length check before performing memcpy(). This fix addresses CVE-2019-14814,CVE-2019-14815,CVE-2019-14816. Signed-off-by: Wen Huang <[email protected]> Acked-by: Ganapathi Bhat <[email protected]> Signed-off-by: Kalle Valo <[email protected]> CWE ID: CWE-120 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: xsltIf(xsltTransformContextPtr ctxt, xmlNodePtr contextNode, xmlNodePtr inst, xsltStylePreCompPtr castedComp) { int res = 0; #ifdef XSLT_REFACTORED xsltStyleItemIfPtr comp = (xsltStyleItemIfPtr) castedComp; #else xsltStylePreCompPtr comp = castedComp; #endif if ((ctxt == NULL) || (contextNode == NULL) || (inst == NULL)) return; if ((comp == NULL) || (comp->test == NULL) || (comp->comp == NULL)) { xsltTransformError(ctxt, NULL, inst, "Internal error in xsltIf(): " "The XSLT 'if' instruction was not compiled.\n"); return; } #ifdef WITH_XSLT_DEBUG_PROCESS XSLT_TRACE(ctxt,XSLT_TRACE_IF,xsltGenericDebug(xsltGenericDebugContext, "xsltIf: test %s\n", comp->test)); #endif #ifdef XSLT_FAST_IF { xmlXPathContextPtr xpctxt = ctxt->xpathCtxt; xmlDocPtr oldXPContextDoc = xpctxt->doc; xmlNsPtr *oldXPNamespaces = xpctxt->namespaces; xmlNodePtr oldXPContextNode = xpctxt->node; int oldXPProximityPosition = xpctxt->proximityPosition; int oldXPContextSize = xpctxt->contextSize; int oldXPNsNr = xpctxt->nsNr; xmlDocPtr oldLocalFragmentTop = ctxt->localRVT; xpctxt->node = contextNode; if (comp != NULL) { #ifdef XSLT_REFACTORED if (comp->inScopeNs != NULL) { xpctxt->namespaces = comp->inScopeNs->list; xpctxt->nsNr = comp->inScopeNs->xpathNumber; } else { xpctxt->namespaces = NULL; xpctxt->nsNr = 0; } #else xpctxt->namespaces = comp->nsList; xpctxt->nsNr = comp->nsNr; #endif } else { xpctxt->namespaces = NULL; xpctxt->nsNr = 0; } /* * This XPath function is optimized for boolean results. */ res = xmlXPathCompiledEvalToBoolean(comp->comp, xpctxt); /* * Cleanup fragments created during evaluation of the * "select" expression. */ if (oldLocalFragmentTop != ctxt->localRVT) xsltReleaseLocalRVTs(ctxt, oldLocalFragmentTop); xpctxt->doc = oldXPContextDoc; xpctxt->node = oldXPContextNode; xpctxt->contextSize = oldXPContextSize; xpctxt->proximityPosition = oldXPProximityPosition; xpctxt->nsNr = oldXPNsNr; xpctxt->namespaces = oldXPNamespaces; } #ifdef WITH_XSLT_DEBUG_PROCESS XSLT_TRACE(ctxt,XSLT_TRACE_IF,xsltGenericDebug(xsltGenericDebugContext, "xsltIf: test evaluate to %d\n", res)); #endif if (res == -1) { ctxt->state = XSLT_STATE_STOPPED; goto error; } if (res == 1) { /* * Instantiate the sequence constructor of xsl:if. */ xsltApplySequenceConstructor(ctxt, contextNode, inst->children, NULL); } #else /* XSLT_FAST_IF */ { xmlXPathObjectPtr xpobj = NULL; /* * OLD CODE: */ { xmlXPathContextPtr xpctxt = ctxt->xpathCtxt; xmlDocPtr oldXPContextDoc = xpctxt->doc; xmlNsPtr *oldXPNamespaces = xpctxt->namespaces; xmlNodePtr oldXPContextNode = xpctxt->node; int oldXPProximityPosition = xpctxt->proximityPosition; int oldXPContextSize = xpctxt->contextSize; int oldXPNsNr = xpctxt->nsNr; xpctxt->node = contextNode; if (comp != NULL) { #ifdef XSLT_REFACTORED if (comp->inScopeNs != NULL) { xpctxt->namespaces = comp->inScopeNs->list; xpctxt->nsNr = comp->inScopeNs->xpathNumber; } else { xpctxt->namespaces = NULL; xpctxt->nsNr = 0; } #else xpctxt->namespaces = comp->nsList; xpctxt->nsNr = comp->nsNr; #endif } else { xpctxt->namespaces = NULL; xpctxt->nsNr = 0; } /* * This XPath function is optimized for boolean results. */ xpobj = xmlXPathCompiledEval(comp->comp, xpctxt); xpctxt->doc = oldXPContextDoc; xpctxt->node = oldXPContextNode; xpctxt->contextSize = oldXPContextSize; xpctxt->proximityPosition = oldXPProximityPosition; xpctxt->nsNr = oldXPNsNr; xpctxt->namespaces = oldXPNamespaces; } if (xpobj != NULL) { if (xpobj->type != XPATH_BOOLEAN) xpobj = xmlXPathConvertBoolean(xpobj); if (xpobj->type == XPATH_BOOLEAN) { res = xpobj->boolval; #ifdef WITH_XSLT_DEBUG_PROCESS XSLT_TRACE(ctxt,XSLT_TRACE_IF,xsltGenericDebug(xsltGenericDebugContext, "xsltIf: test evaluate to %d\n", res)); #endif if (res) { xsltApplySequenceConstructor(ctxt, contextNode, inst->children, NULL); } } else { #ifdef WITH_XSLT_DEBUG_PROCESS XSLT_TRACE(ctxt, XSLT_TRACE_IF, xsltGenericDebug(xsltGenericDebugContext, "xsltIf: test didn't evaluate to a boolean\n")); #endif ctxt->state = XSLT_STATE_STOPPED; } xmlXPathFreeObject(xpobj); } else { ctxt->state = XSLT_STATE_STOPPED; } } #endif /* else of XSLT_FAST_IF */ error: return; } Commit Message: Roll libxslt to 891681e3e948f31732229f53cb6db7215f740fc7 BUG=583156,583171 Review URL: https://codereview.chromium.org/1853083002 Cr-Commit-Position: refs/heads/master@{#385338} CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: PepperDeviceEnumerationHostHelper::PepperDeviceEnumerationHostHelper( ppapi::host::ResourceHost* resource_host, Delegate* delegate, PP_DeviceType_Dev device_type, const GURL& document_url) : resource_host_(resource_host), delegate_(delegate), device_type_(device_type), document_url_(document_url) {} Commit Message: Pepper: Access PepperMediaDeviceManager through a WeakPtr Its lifetime is scoped to the RenderFrame, and it might go away before the hosts that refer to it. BUG=423030 Review URL: https://codereview.chromium.org/653243003 Cr-Commit-Position: refs/heads/master@{#299897} CWE ID: CWE-399 Target: 1 Example 2: Code: int compat_put_timex(struct compat_timex __user *utp, const struct timex *txc) { struct compat_timex tx32; memset(&tx32, 0, sizeof(struct compat_timex)); tx32.modes = txc->modes; tx32.offset = txc->offset; tx32.freq = txc->freq; tx32.maxerror = txc->maxerror; tx32.esterror = txc->esterror; tx32.status = txc->status; tx32.constant = txc->constant; tx32.precision = txc->precision; tx32.tolerance = txc->tolerance; tx32.time.tv_sec = txc->time.tv_sec; tx32.time.tv_usec = txc->time.tv_usec; tx32.tick = txc->tick; tx32.ppsfreq = txc->ppsfreq; tx32.jitter = txc->jitter; tx32.shift = txc->shift; tx32.stabil = txc->stabil; tx32.jitcnt = txc->jitcnt; tx32.calcnt = txc->calcnt; tx32.errcnt = txc->errcnt; tx32.stbcnt = txc->stbcnt; tx32.tai = txc->tai; if (copy_to_user(utp, &tx32, sizeof(struct compat_timex))) return -EFAULT; return 0; } Commit Message: compat: fix 4-byte infoleak via uninitialized struct field Commit 3a4d44b61625 ("ntp: Move adjtimex related compat syscalls to native counterparts") removed the memset() in compat_get_timex(). Since then, the compat adjtimex syscall can invoke do_adjtimex() with an uninitialized ->tai. If do_adjtimex() doesn't write to ->tai (e.g. because the arguments are invalid), compat_put_timex() then copies the uninitialized ->tai field to userspace. Fix it by adding the memset() back. Fixes: 3a4d44b61625 ("ntp: Move adjtimex related compat syscalls to native counterparts") Signed-off-by: Jann Horn <[email protected]> Acked-by: Kees Cook <[email protected]> Acked-by: Al Viro <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-200 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void deprecatedStaticReadOnlyAttrAttributeGetterCallback(v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Value>& info) { TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMGetter"); UseCounter::countDeprecation(callingExecutionContext(info.GetIsolate()), UseCounter::StaticReadonlyAttribute); TestObjectV8Internal::deprecatedStaticReadOnlyAttrAttributeGetter(info); TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution"); } Commit Message: document.location bindings fix BUG=352374 [email protected] Review URL: https://codereview.chromium.org/196343011 git-svn-id: svn://svn.chromium.org/blink/trunk@169176 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int nl80211_start_sched_scan(struct sk_buff *skb, struct genl_info *info) { struct cfg80211_sched_scan_request *request; struct cfg80211_registered_device *rdev = info->user_ptr[0]; struct net_device *dev = info->user_ptr[1]; struct nlattr *attr; struct wiphy *wiphy; int err, tmp, n_ssids = 0, n_channels, i; u32 interval; enum ieee80211_band band; size_t ie_len; if (!(rdev->wiphy.flags & WIPHY_FLAG_SUPPORTS_SCHED_SCAN) || !rdev->ops->sched_scan_start) return -EOPNOTSUPP; if (!is_valid_ie_attr(info->attrs[NL80211_ATTR_IE])) return -EINVAL; if (rdev->sched_scan_req) return -EINPROGRESS; if (!info->attrs[NL80211_ATTR_SCHED_SCAN_INTERVAL]) return -EINVAL; interval = nla_get_u32(info->attrs[NL80211_ATTR_SCHED_SCAN_INTERVAL]); if (interval == 0) return -EINVAL; wiphy = &rdev->wiphy; if (info->attrs[NL80211_ATTR_SCAN_FREQUENCIES]) { n_channels = validate_scan_freqs( info->attrs[NL80211_ATTR_SCAN_FREQUENCIES]); if (!n_channels) return -EINVAL; } else { n_channels = 0; for (band = 0; band < IEEE80211_NUM_BANDS; band++) if (wiphy->bands[band]) n_channels += wiphy->bands[band]->n_channels; } if (info->attrs[NL80211_ATTR_SCAN_SSIDS]) nla_for_each_nested(attr, info->attrs[NL80211_ATTR_SCAN_SSIDS], tmp) n_ssids++; if (n_ssids > wiphy->max_scan_ssids) return -EINVAL; if (info->attrs[NL80211_ATTR_IE]) ie_len = nla_len(info->attrs[NL80211_ATTR_IE]); else ie_len = 0; if (ie_len > wiphy->max_scan_ie_len) return -EINVAL; request = kzalloc(sizeof(*request) + sizeof(*request->ssids) * n_ssids + sizeof(*request->channels) * n_channels + ie_len, GFP_KERNEL); if (!request) return -ENOMEM; if (n_ssids) request->ssids = (void *)&request->channels[n_channels]; request->n_ssids = n_ssids; if (ie_len) { if (request->ssids) request->ie = (void *)(request->ssids + n_ssids); else request->ie = (void *)(request->channels + n_channels); } i = 0; if (info->attrs[NL80211_ATTR_SCAN_FREQUENCIES]) { /* user specified, bail out if channel not found */ nla_for_each_nested(attr, info->attrs[NL80211_ATTR_SCAN_FREQUENCIES], tmp) { struct ieee80211_channel *chan; chan = ieee80211_get_channel(wiphy, nla_get_u32(attr)); if (!chan) { err = -EINVAL; goto out_free; } /* ignore disabled channels */ if (chan->flags & IEEE80211_CHAN_DISABLED) continue; request->channels[i] = chan; i++; } } else { /* all channels */ for (band = 0; band < IEEE80211_NUM_BANDS; band++) { int j; if (!wiphy->bands[band]) continue; for (j = 0; j < wiphy->bands[band]->n_channels; j++) { struct ieee80211_channel *chan; chan = &wiphy->bands[band]->channels[j]; if (chan->flags & IEEE80211_CHAN_DISABLED) continue; request->channels[i] = chan; i++; } } } if (!i) { err = -EINVAL; goto out_free; } request->n_channels = i; i = 0; if (info->attrs[NL80211_ATTR_SCAN_SSIDS]) { nla_for_each_nested(attr, info->attrs[NL80211_ATTR_SCAN_SSIDS], tmp) { if (request->ssids[i].ssid_len > IEEE80211_MAX_SSID_LEN) { err = -EINVAL; goto out_free; } memcpy(request->ssids[i].ssid, nla_data(attr), nla_len(attr)); request->ssids[i].ssid_len = nla_len(attr); i++; } } if (info->attrs[NL80211_ATTR_IE]) { request->ie_len = nla_len(info->attrs[NL80211_ATTR_IE]); memcpy((void *)request->ie, nla_data(info->attrs[NL80211_ATTR_IE]), request->ie_len); } request->dev = dev; request->wiphy = &rdev->wiphy; request->interval = interval; err = rdev->ops->sched_scan_start(&rdev->wiphy, dev, request); if (!err) { rdev->sched_scan_req = request; nl80211_send_sched_scan(rdev, dev, NL80211_CMD_START_SCHED_SCAN); goto out; } out_free: kfree(request); out: return err; } Commit Message: nl80211: fix check for valid SSID size in scan operations In both trigger_scan and sched_scan operations, we were checking for the SSID length before assigning the value correctly. Since the memory was just kzalloc'ed, the check was always failing and SSID with over 32 characters were allowed to go through. This was causing a buffer overflow when copying the actual SSID to the proper place. This bug has been there since 2.6.29-rc4. Cc: [email protected] Signed-off-by: Luciano Coelho <[email protected]> Signed-off-by: John W. Linville <[email protected]> CWE ID: CWE-119 Target: 1 Example 2: Code: void RuntimeCustomBindings::OpenChannelToNativeApp( const v8::FunctionCallbackInfo<v8::Value>& args) { Feature::Availability availability = FeatureProvider::GetPermissionFeatures() ->GetFeature("nativeMessaging") ->IsAvailableToContext(context()->extension(), context()->context_type(), context()->url()); if (!availability.is_available()) return; content::RenderFrame* render_frame = context()->GetRenderFrame(); if (!render_frame) return; CHECK(args.Length() >= 2 && args[0]->IsString() && args[1]->IsString()); std::string extension_id = *v8::String::Utf8Value(args[0]); std::string native_app_name = *v8::String::Utf8Value(args[1]); int port_id = -1; render_frame->Send(new ExtensionHostMsg_OpenChannelToNativeApp( render_frame->GetRoutingID(), extension_id, native_app_name, &port_id)); args.GetReturnValue().Set(static_cast<int32_t>(port_id)); } Commit Message: [Extensions] Expand bindings access checks BUG=601149 BUG=601073 Review URL: https://codereview.chromium.org/1866103002 Cr-Commit-Position: refs/heads/master@{#387710} CWE ID: CWE-284 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void WriteFakeData(uint8* audio_data, size_t length) { Type* output = reinterpret_cast<Type*>(audio_data); for (size_t i = 0; i < length; i++) { output[i] = i % 5 + 10; } } Commit Message: Protect AudioRendererAlgorithm from invalid step sizes. BUG=165430 TEST=unittests and asan pass. Review URL: https://codereview.chromium.org/11573023 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@173249 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int config__parse_args(struct mosquitto_db *db, struct mosquitto__config *config, int argc, char *argv[]) { int i; int port_tmp; for(i=1; i<argc; i++){ if(!strcmp(argv[i], "-c") || !strcmp(argv[i], "--config-file")){ if(i<argc-1){ db->config_file = argv[i+1]; if(config__read(db, config, false)){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Unable to open configuration file."); return MOSQ_ERR_INVAL; } }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: -c argument given, but no config file specified."); return MOSQ_ERR_INVAL; } i++; }else if(!strcmp(argv[i], "-d") || !strcmp(argv[i], "--daemon")){ config->daemon = true; }else if(!strcmp(argv[i], "-h") || !strcmp(argv[i], "--help")){ print_usage(); return MOSQ_ERR_INVAL; }else if(!strcmp(argv[i], "-p") || !strcmp(argv[i], "--port")){ if(i<argc-1){ port_tmp = atoi(argv[i+1]); if(port_tmp<1 || port_tmp>65535){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid port specified (%d).", port_tmp); return MOSQ_ERR_INVAL; }else{ if(config->default_listener.port){ log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Default listener port specified multiple times. Only the latest will be used."); } config->default_listener.port = port_tmp; } }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: -p argument given, but no port specified."); return MOSQ_ERR_INVAL; } i++; }else if(!strcmp(argv[i], "-v") || !strcmp(argv[i], "--verbose")){ db->verbose = true; }else{ fprintf(stderr, "Error: Unknown option '%s'.\n",argv[i]); print_usage(); return MOSQ_ERR_INVAL; } } if(config->listener_count == 0 #ifdef WITH_TLS || config->default_listener.cafile || config->default_listener.capath || config->default_listener.certfile || config->default_listener.keyfile || config->default_listener.ciphers || config->default_listener.psk_hint || config->default_listener.require_certificate || config->default_listener.crlfile || config->default_listener.use_identity_as_username || config->default_listener.use_subject_as_username #endif || config->default_listener.use_username_as_clientid || config->default_listener.host || config->default_listener.port || config->default_listener.max_connections != -1 || config->default_listener.mount_point || config->default_listener.protocol != mp_mqtt || config->default_listener.socket_domain || config->default_listener.security_options.password_file || config->default_listener.security_options.psk_file || config->default_listener.security_options.auth_plugin_config_count || config->default_listener.security_options.allow_anonymous != -1 ){ config->listener_count++; config->listeners = mosquitto__realloc(config->listeners, sizeof(struct mosquitto__listener)*config->listener_count); if(!config->listeners){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); return MOSQ_ERR_NOMEM; } memset(&config->listeners[config->listener_count-1], 0, sizeof(struct mosquitto__listener)); if(config->default_listener.port){ config->listeners[config->listener_count-1].port = config->default_listener.port; }else{ config->listeners[config->listener_count-1].port = 1883; } if(config->default_listener.host){ config->listeners[config->listener_count-1].host = config->default_listener.host; }else{ config->listeners[config->listener_count-1].host = NULL; } if(config->default_listener.mount_point){ config->listeners[config->listener_count-1].mount_point = config->default_listener.mount_point; }else{ config->listeners[config->listener_count-1].mount_point = NULL; } config->listeners[config->listener_count-1].max_connections = config->default_listener.max_connections; config->listeners[config->listener_count-1].protocol = config->default_listener.protocol; config->listeners[config->listener_count-1].socket_domain = config->default_listener.socket_domain; config->listeners[config->listener_count-1].client_count = 0; config->listeners[config->listener_count-1].socks = NULL; config->listeners[config->listener_count-1].sock_count = 0; config->listeners[config->listener_count-1].client_count = 0; config->listeners[config->listener_count-1].use_username_as_clientid = config->default_listener.use_username_as_clientid; #ifdef WITH_TLS config->listeners[config->listener_count-1].tls_version = config->default_listener.tls_version; config->listeners[config->listener_count-1].cafile = config->default_listener.cafile; config->listeners[config->listener_count-1].capath = config->default_listener.capath; config->listeners[config->listener_count-1].certfile = config->default_listener.certfile; config->listeners[config->listener_count-1].keyfile = config->default_listener.keyfile; config->listeners[config->listener_count-1].ciphers = config->default_listener.ciphers; config->listeners[config->listener_count-1].psk_hint = config->default_listener.psk_hint; config->listeners[config->listener_count-1].require_certificate = config->default_listener.require_certificate; config->listeners[config->listener_count-1].ssl_ctx = NULL; config->listeners[config->listener_count-1].crlfile = config->default_listener.crlfile; config->listeners[config->listener_count-1].use_identity_as_username = config->default_listener.use_identity_as_username; config->listeners[config->listener_count-1].use_subject_as_username = config->default_listener.use_subject_as_username; #endif config->listeners[config->listener_count-1].security_options.password_file = config->default_listener.security_options.password_file; config->listeners[config->listener_count-1].security_options.psk_file = config->default_listener.security_options.psk_file; config->listeners[config->listener_count-1].security_options.auth_plugin_configs = config->default_listener.security_options.auth_plugin_configs; config->listeners[config->listener_count-1].security_options.auth_plugin_config_count = config->default_listener.security_options.auth_plugin_config_count; config->listeners[config->listener_count-1].security_options.allow_anonymous = config->default_listener.security_options.allow_anonymous; } /* Default to drop to mosquitto user if we are privileged and no user specified. */ if(!config->user){ config->user = "mosquitto"; } if(db->verbose){ config->log_type = INT_MAX; } return config__check(config); } Commit Message: Fix acl_file being ignore for default listener if with per_listener_settings Close #1073. Thanks to Jef Driesen. Bug: https://github.com/eclipse/mosquitto/issues/1073 CWE ID: Target: 1 Example 2: Code: static int init_entropy_decoder(APEContext *ctx) { /* Read the CRC */ if (ctx->fileversion >= 3900) { if (ctx->data_end - ctx->ptr < 6) return AVERROR_INVALIDDATA; ctx->CRC = bytestream_get_be32(&ctx->ptr); } else { ctx->CRC = get_bits_long(&ctx->gb, 32); } /* Read the frame flags if they exist */ ctx->frameflags = 0; if ((ctx->fileversion > 3820) && (ctx->CRC & 0x80000000)) { ctx->CRC &= ~0x80000000; if (ctx->data_end - ctx->ptr < 6) return AVERROR_INVALIDDATA; ctx->frameflags = bytestream_get_be32(&ctx->ptr); } /* Initialize the rice structs */ ctx->riceX.k = 10; ctx->riceX.ksum = (1 << ctx->riceX.k) * 16; ctx->riceY.k = 10; ctx->riceY.ksum = (1 << ctx->riceY.k) * 16; if (ctx->fileversion >= 3900) { /* The first 8 bits of input are ignored. */ ctx->ptr++; range_start_decoding(ctx); } return 0; } Commit Message: avcodec/apedec: Fix integer overflow Fixes: out of array access Fixes: PoC.ape and others Found-by: Bingchang, Liu@VARAS of IIE Signed-off-by: Michael Niedermayer <[email protected]> CWE ID: CWE-125 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: IHEVCD_ERROR_T ihevcd_parse_pcm_sample(codec_t *ps_codec, WORD32 x0, WORD32 y0, WORD32 log2_cb_size) { IHEVCD_ERROR_T ret = (IHEVCD_ERROR_T)IHEVCD_SUCCESS; cab_ctxt_t *ps_cabac = &ps_codec->s_parse.s_cabac; sps_t *ps_sps; WORD32 value; WORD32 i; WORD32 num_bits; UWORD32 u4_sig_coeff_map; bitstrm_t *ps_bitstrm = &ps_codec->s_parse.s_bitstrm; tu_t *ps_tu = ps_codec->s_parse.ps_tu; tu_sblk_coeff_data_t *ps_tu_sblk_coeff_data; UWORD8 *pu1_coeff_data; ps_sps = ps_codec->s_parse.ps_sps; UNUSED(value); UNUSED(ps_tu); UNUSED(ps_cabac); UNUSED(x0); UNUSED(y0); { WORD8 *pi1_scan_idx; WORD8 *pi1_buf = (WORD8 *)ps_codec->s_parse.pv_tu_coeff_data; WORD8 *pi1_num_coded_subblks; /* First WORD8 gives number of coded subblocks */ pi1_num_coded_subblks = pi1_buf++; /* Set number of coded subblocks in the current TU to zero */ /* For PCM there will be only one subblock which is the same size as CU */ *pi1_num_coded_subblks = 1; /* Second WORD8 gives (scan idx << 1) | trans_skip */ pi1_scan_idx = pi1_buf++; *pi1_scan_idx = (0 << 1) | 1; /* Store the incremented pointer in pv_tu_coeff_data */ ps_codec->s_parse.pv_tu_coeff_data = pi1_buf; } u4_sig_coeff_map = 0xFFFFFFFF; ps_tu_sblk_coeff_data = (tu_sblk_coeff_data_t *)ps_codec->s_parse.pv_tu_coeff_data; ps_tu_sblk_coeff_data->u2_sig_coeff_map = u4_sig_coeff_map; ps_tu_sblk_coeff_data->u2_subblk_pos = 0; pu1_coeff_data = (UWORD8 *)&ps_tu_sblk_coeff_data->ai2_level[0]; num_bits = ps_sps->i1_pcm_sample_bit_depth_luma; for(i = 0; i < 1 << (log2_cb_size << 1); i++) { TRACE_CABAC_CTXT("pcm_sample_luma", ps_cabac->u4_range, 0); BITS_PARSE("pcm_sample_luma", value, ps_bitstrm, num_bits); *pu1_coeff_data++ = value << (BIT_DEPTH_LUMA - num_bits); } num_bits = ps_sps->i1_pcm_sample_bit_depth_chroma; for(i = 0; i < (1 << (log2_cb_size << 1)) >> 1; i++) { TRACE_CABAC_CTXT("pcm_sample_chroma", ps_cabac->u4_range, 0); BITS_PARSE("pcm_sample_chroma", value, ps_bitstrm, num_bits); *pu1_coeff_data++ = value << (BIT_DEPTH_CHROMA - num_bits); } ps_codec->s_parse.pv_tu_coeff_data = pu1_coeff_data; return ret; } Commit Message: Return error from cabac init if offset is greater than range When the offset was greater than range, the bitstream was read more than the valid range in leaf-level cabac parsing modules. Error check was added to cabac init to fix this issue. Additionally end of slice and slice error were signalled to suppress further parsing of current slice. Bug: 34897036 Change-Id: I1263f1d1219684ffa6e952c76e5a08e9a933c9d2 (cherry picked from commit 3b175da88a1807d19cdd248b74bce60e57f05c6a) (cherry picked from commit b92314c860d01d754ef579eafe55d7377962b3ba) CWE ID: CWE-119 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int set_geometry(unsigned int cmd, struct floppy_struct *g, int drive, int type, struct block_device *bdev) { int cnt; /* sanity checking for parameters. */ if (g->sect <= 0 || g->head <= 0 || /* check for zero in F_SECT_PER_TRACK */ (unsigned char)((g->sect << 2) >> FD_SIZECODE(g)) == 0 || g->track <= 0 || g->track > UDP->tracks >> STRETCH(g) || /* check if reserved bits are set */ (g->stretch & ~(FD_STRETCH | FD_SWAPSIDES | FD_SECTBASEMASK)) != 0) return -EINVAL; if (type) { if (!capable(CAP_SYS_ADMIN)) return -EPERM; mutex_lock(&open_lock); if (lock_fdc(drive)) { mutex_unlock(&open_lock); return -EINTR; } floppy_type[type] = *g; floppy_type[type].name = "user format"; for (cnt = type << 2; cnt < (type << 2) + 4; cnt++) floppy_sizes[cnt] = floppy_sizes[cnt + 0x80] = floppy_type[type].size + 1; process_fd_request(); for (cnt = 0; cnt < N_DRIVE; cnt++) { struct block_device *bdev = opened_bdev[cnt]; if (!bdev || ITYPE(drive_state[cnt].fd_device) != type) continue; __invalidate_device(bdev, true); } mutex_unlock(&open_lock); } else { int oldStretch; if (lock_fdc(drive)) return -EINTR; if (cmd != FDDEFPRM) { /* notice a disk change immediately, else * we lose our settings immediately*/ if (poll_drive(true, FD_RAW_NEED_DISK) == -EINTR) return -EINTR; } oldStretch = g->stretch; user_params[drive] = *g; if (buffer_drive == drive) SUPBOUND(buffer_max, user_params[drive].sect); current_type[drive] = &user_params[drive]; floppy_sizes[drive] = user_params[drive].size; if (cmd == FDDEFPRM) DRS->keep_data = -1; else DRS->keep_data = 1; /* invalidation. Invalidate only when needed, i.e. * when there are already sectors in the buffer cache * whose number will change. This is useful, because * mtools often changes the geometry of the disk after * looking at the boot block */ if (DRS->maxblock > user_params[drive].sect || DRS->maxtrack || ((user_params[drive].sect ^ oldStretch) & (FD_SWAPSIDES | FD_SECTBASEMASK))) invalidate_drive(bdev); else process_fd_request(); } return 0; } Commit Message: floppy: fix out-of-bounds read in copy_buffer This fixes a global out-of-bounds read access in the copy_buffer function of the floppy driver. The FDDEFPRM ioctl allows one to set the geometry of a disk. The sect and head fields (unsigned int) of the floppy_drive structure are used to compute the max_sector (int) in the make_raw_rw_request function. It is possible to overflow the max_sector. Next, max_sector is passed to the copy_buffer function and used in one of the memcpy calls. An unprivileged user could trigger the bug if the device is accessible, but requires a floppy disk to be inserted. The patch adds the check for the .sect * .head multiplication for not overflowing in the set_geometry function. The bug was found by syzkaller. Signed-off-by: Denis Efremov <[email protected]> Tested-by: Willy Tarreau <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-125 Target: 1 Example 2: Code: static struct futex_q *futex_top_waiter(struct futex_hash_bucket *hb, union futex_key *key) { struct futex_q *this; plist_for_each_entry(this, &hb->chain, list) { if (match_futex(&this->key, key)) return this; } return NULL; } Commit Message: futex-prevent-requeue-pi-on-same-futex.patch futex: Forbid uaddr == uaddr2 in futex_requeue(..., requeue_pi=1) If uaddr == uaddr2, then we have broken the rule of only requeueing from a non-pi futex to a pi futex with this call. If we attempt this, then dangling pointers may be left for rt_waiter resulting in an exploitable condition. This change brings futex_requeue() in line with futex_wait_requeue_pi() which performs the same check as per commit 6f7b0a2a5c0f ("futex: Forbid uaddr == uaddr2 in futex_wait_requeue_pi()") [ tglx: Compare the resulting keys as well, as uaddrs might be different depending on the mapping ] Fixes CVE-2014-3153. Reported-by: Pinkie Pie Signed-off-by: Will Drewry <[email protected]> Signed-off-by: Kees Cook <[email protected]> Cc: [email protected] Signed-off-by: Thomas Gleixner <[email protected]> Reviewed-by: Darren Hart <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-264 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static const SSL_METHOD *ssl23_get_client_method(int ver) { #ifndef OPENSSL_NO_SSL2 if (ver == SSL2_VERSION) return(SSLv2_client_method()); #endif if (ver == SSL3_VERSION) return(SSLv3_client_method()); else if (ver == TLS1_VERSION) return(TLSv1_client_method()); else if (ver == TLS1_1_VERSION) return(TLSv1_1_client_method()); else return(NULL); } Commit Message: CWE ID: CWE-310 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int net_ctl_permissions(struct ctl_table_header *head, struct ctl_table *table) { struct net *net = container_of(head->set, struct net, sysctls); kuid_t root_uid = make_kuid(net->user_ns, 0); kgid_t root_gid = make_kgid(net->user_ns, 0); /* Allow network administrator to have same access as root. */ if (ns_capable(net->user_ns, CAP_NET_ADMIN) || uid_eq(root_uid, current_uid())) { int mode = (table->mode >> 6) & 7; return (mode << 6) | (mode << 3) | mode; } /* Allow netns root group to have the same access as the root group */ if (gid_eq(root_gid, current_gid())) { int mode = (table->mode >> 3) & 7; return (mode << 3) | mode; } return table->mode; } Commit Message: net: Update the sysctl permissions handler to test effective uid/gid Modify the code to use current_euid(), and in_egroup_p, as in done in fs/proc/proc_sysctl.c:test_perm() Cc: [email protected] Reviewed-by: Eric Sandeen <[email protected]> Reported-by: Eric Sandeen <[email protected]> Signed-off-by: "Eric W. Biederman" <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-20 Target: 1 Example 2: Code: bool RenderWidgetHostViewAura::GetCompositionCharacterBounds( uint32_t index, gfx::Rect* rect) const { DCHECK(rect); if (!text_input_manager_ || !text_input_manager_->GetActiveWidget()) return false; const TextInputManager::CompositionRangeInfo* composition_range_info = text_input_manager_->GetCompositionRangeInfo(); if (index >= composition_range_info->character_bounds.size()) return false; *rect = ConvertRectToScreen(composition_range_info->character_bounds[index]); return true; } Commit Message: Allocate a FrameSinkId for RenderWidgetHostViewAura in mus+ash RenderWidgetHostViewChildFrame expects its parent to have a valid FrameSinkId. Make sure RenderWidgetHostViewAura has a FrameSinkId even if DelegatedFrameHost is not used (in mus+ash). BUG=706553 [email protected] Review-Url: https://codereview.chromium.org/2847253003 Cr-Commit-Position: refs/heads/master@{#468179} CWE ID: CWE-254 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: get_policy_2_svc(gpol_arg *arg, struct svc_req *rqstp) { static gpol_ret ret; kadm5_ret_t ret2; char *prime_arg, *funcname; gss_buffer_desc client_name, service_name; OM_uint32 minor_stat; kadm5_principal_ent_rec caller_ent; kadm5_server_handle_t handle; const char *errmsg = NULL; xdr_free(xdr_gpol_ret, &ret); if ((ret.code = new_server_handle(arg->api_version, rqstp, &handle))) goto exit_func; if ((ret.code = check_handle((void *)handle))) goto exit_func; ret.api_version = handle->api_version; funcname = "kadm5_get_policy"; if (setup_gss_names(rqstp, &client_name, &service_name) < 0) { ret.code = KADM5_FAILURE; goto exit_func; } prime_arg = arg->name; ret.code = KADM5_AUTH_GET; if (!CHANGEPW_SERVICE(rqstp) && kadm5int_acl_check(handle->context, rqst2name(rqstp), ACL_INQUIRE, NULL, NULL)) ret.code = KADM5_OK; else { ret.code = kadm5_get_principal(handle->lhandle, handle->current_caller, &caller_ent, KADM5_PRINCIPAL_NORMAL_MASK); if (ret.code == KADM5_OK) { if (caller_ent.aux_attributes & KADM5_POLICY && strcmp(caller_ent.policy, arg->name) == 0) { ret.code = KADM5_OK; } else ret.code = KADM5_AUTH_GET; ret2 = kadm5_free_principal_ent(handle->lhandle, &caller_ent); ret.code = ret.code ? ret.code : ret2; } } if (ret.code == KADM5_OK) { ret.code = kadm5_get_policy(handle, arg->name, &ret.rec); if( ret.code != 0 ) errmsg = krb5_get_error_message(handle->context, ret.code); log_done(funcname, ((prime_arg == NULL) ? "(null)" : prime_arg), errmsg, &client_name, &service_name, rqstp); if (errmsg != NULL) krb5_free_error_message(handle->context, errmsg); } else { log_unauth(funcname, prime_arg, &client_name, &service_name, rqstp); } gss_release_buffer(&minor_stat, &client_name); gss_release_buffer(&minor_stat, &service_name); exit_func: free_server_handle(handle); return &ret; } Commit Message: Fix leaks in kadmin server stubs [CVE-2015-8631] In each kadmind server stub, initialize the client_name and server_name variables, and release them in the cleanup handler. Many of the stubs will otherwise leak the client and server name if krb5_unparse_name() fails. Also make sure to free the prime_arg variables in rename_principal_2_svc(), or we can leak the first one if unparsing the second one fails. Discovered by Simo Sorce. CVE-2015-8631: In all versions of MIT krb5, an authenticated attacker can cause kadmind to leak memory by supplying a null principal name in a request which uses one. Repeating these requests will eventually cause kadmind to exhaust all available memory. CVSSv2 Vector: AV:N/AC:L/Au:S/C:N/I:N/A:C/E:POC/RL:OF/RC:C ticket: 8343 (new) target_version: 1.14-next target_version: 1.13-next tags: pullup CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: WebString WebPageSerializer::generateMetaCharsetDeclaration(const WebString& charset) { String charsetString = "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=" + static_cast<const String&>(charset) + "\">"; return charsetString; } Commit Message: Escape "--" in the page URL at page serialization This patch makes page serializer to escape the page URL embed into a HTML comment of result HTML[1] to avoid inserting text as HTML from URL by introducing a static member function |PageSerialzier::markOfTheWebDeclaration()| for sharing it between |PageSerialzier| and |WebPageSerialzier| classes. [1] We use following format for serialized HTML: saved from url=(${lengthOfURL})${URL} BUG=503217 TEST=webkit_unit_tests --gtest_filter=PageSerializerTest.markOfTheWebDeclaration TEST=webkit_unit_tests --gtest_filter=WebPageSerializerTest.fromUrlWithMinusMinu Review URL: https://codereview.chromium.org/1371323003 Cr-Commit-Position: refs/heads/master@{#351736} CWE ID: CWE-20 Target: 1 Example 2: Code: _asn1_find_up (asn1_node node) { asn1_node p; if (node == NULL) return NULL; p = node; while ((p->left != NULL) && (p->left->right == p)) p = p->left; return p->left; } Commit Message: CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static MagickBooleanType OpenPixelCache(Image *image,const MapMode mode, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info, source_info; char format[MagickPathExtent], message[MagickPathExtent]; const char *type; MagickBooleanType status; MagickSizeType length, number_pixels; size_t columns, packet_size; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if ((image->columns == 0) || (image->rows == 0)) ThrowBinaryException(CacheError,"NoPixelsDefinedInCache",image->filename); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); if ((AcquireMagickResource(WidthResource,image->columns) == MagickFalse) || (AcquireMagickResource(HeightResource,image->rows) == MagickFalse)) ThrowBinaryException(ImageError,"WidthOrHeightExceedsLimit", image->filename); source_info=(*cache_info); source_info.file=(-1); (void) FormatLocaleString(cache_info->filename,MagickPathExtent,"%s[%.20g]", image->filename,(double) GetImageIndexInList(image)); cache_info->storage_class=image->storage_class; cache_info->colorspace=image->colorspace; cache_info->alpha_trait=image->alpha_trait; cache_info->read_mask=image->read_mask; cache_info->write_mask=image->write_mask; cache_info->rows=image->rows; cache_info->columns=image->columns; InitializePixelChannelMap(image); cache_info->number_channels=GetPixelChannels(image); (void) memcpy(cache_info->channel_map,image->channel_map,MaxPixelChannels* sizeof(*image->channel_map)); cache_info->metacontent_extent=image->metacontent_extent; cache_info->mode=mode; number_pixels=(MagickSizeType) cache_info->columns*cache_info->rows; packet_size=cache_info->number_channels*sizeof(Quantum); if (image->metacontent_extent != 0) packet_size+=cache_info->metacontent_extent; length=number_pixels*packet_size; columns=(size_t) (length/cache_info->rows/packet_size); if ((cache_info->columns != columns) || ((ssize_t) cache_info->columns < 0) || ((ssize_t) cache_info->rows < 0)) ThrowBinaryException(ResourceLimitError,"PixelCacheAllocationFailed", image->filename); cache_info->length=length; if (image->ping != MagickFalse) { cache_info->storage_class=image->storage_class; cache_info->colorspace=image->colorspace; cache_info->type=PingCache; return(MagickTrue); } status=AcquireMagickResource(AreaResource,cache_info->length); length=number_pixels*(cache_info->number_channels*sizeof(Quantum)+ cache_info->metacontent_extent); if ((status != MagickFalse) && (length == (MagickSizeType) ((size_t) length))) { status=AcquireMagickResource(MemoryResource,cache_info->length); if (((cache_info->type == UndefinedCache) && (status != MagickFalse)) || (cache_info->type == MemoryCache)) { cache_info->mapped=MagickFalse; cache_info->pixels=(Quantum *) MagickAssumeAligned( AcquireAlignedMemory(1,(size_t) cache_info->length)); if (cache_info->pixels == (Quantum *) NULL) cache_info->pixels=source_info.pixels; else { /* Create memory pixel cache. */ status=MagickTrue; cache_info->type=MemoryCache; cache_info->metacontent=(void *) NULL; if (cache_info->metacontent_extent != 0) cache_info->metacontent=(void *) (cache_info->pixels+ number_pixels*cache_info->number_channels); if ((source_info.storage_class != UndefinedClass) && (mode != ReadMode)) { status=ClonePixelCacheRepository(cache_info,&source_info, exception); RelinquishPixelCachePixels(&source_info); } if (image->debug != MagickFalse) { (void) FormatMagickSize(cache_info->length,MagickTrue,"B", MagickPathExtent,format); type=CommandOptionToMnemonic(MagickCacheOptions,(ssize_t) cache_info->type); (void) FormatLocaleString(message,MagickPathExtent, "open %s (%s %s, %.20gx%.20gx%.20g %s)", cache_info->filename,cache_info->mapped != MagickFalse ? "Anonymous" : "Heap",type,(double) cache_info->columns, (double) cache_info->rows,(double) cache_info->number_channels,format); (void) LogMagickEvent(CacheEvent,GetMagickModule(),"%s", message); } return(status); } } RelinquishMagickResource(MemoryResource,cache_info->length); } /* Create pixel cache on disk. */ status=AcquireMagickResource(DiskResource,cache_info->length); if ((status == MagickFalse) || (cache_info->type == DistributedCache)) { DistributeCacheInfo *server_info; if (cache_info->type == DistributedCache) RelinquishMagickResource(DiskResource,cache_info->length); server_info=AcquireDistributeCacheInfo(exception); if (server_info != (DistributeCacheInfo *) NULL) { status=OpenDistributePixelCache(server_info,image); if (status == MagickFalse) { ThrowFileException(exception,CacheError,"UnableToOpenPixelCache", GetDistributeCacheHostname(server_info)); server_info=DestroyDistributeCacheInfo(server_info); } else { /* Create a distributed pixel cache. */ cache_info->type=DistributedCache; cache_info->server_info=server_info; (void) FormatLocaleString(cache_info->cache_filename, MagickPathExtent,"%s:%d",GetDistributeCacheHostname( (DistributeCacheInfo *) cache_info->server_info), GetDistributeCachePort((DistributeCacheInfo *) cache_info->server_info)); if ((source_info.storage_class != UndefinedClass) && (mode != ReadMode)) { status=ClonePixelCacheRepository(cache_info,&source_info, exception); RelinquishPixelCachePixels(&source_info); } if (image->debug != MagickFalse) { (void) FormatMagickSize(cache_info->length,MagickFalse,"B", MagickPathExtent,format); type=CommandOptionToMnemonic(MagickCacheOptions,(ssize_t) cache_info->type); (void) FormatLocaleString(message,MagickPathExtent, "open %s (%s[%d], %s, %.20gx%.20gx%.20g %s)", cache_info->filename,cache_info->cache_filename, GetDistributeCacheFile((DistributeCacheInfo *) cache_info->server_info),type,(double) cache_info->columns, (double) cache_info->rows,(double) cache_info->number_channels,format); (void) LogMagickEvent(CacheEvent,GetMagickModule(),"%s", message); } return(MagickTrue); } } RelinquishMagickResource(DiskResource,cache_info->length); (void) ThrowMagickException(exception,GetMagickModule(),CacheError, "CacheResourcesExhausted","`%s'",image->filename); return(MagickFalse); } if ((source_info.storage_class != UndefinedClass) && (mode != ReadMode)) { (void) ClosePixelCacheOnDisk(cache_info); *cache_info->cache_filename='\0'; } if (OpenPixelCacheOnDisk(cache_info,mode) == MagickFalse) { RelinquishMagickResource(DiskResource,cache_info->length); ThrowFileException(exception,CacheError,"UnableToOpenPixelCache", image->filename); return(MagickFalse); } status=SetPixelCacheExtent(image,(MagickSizeType) cache_info->offset+ cache_info->length); if (status == MagickFalse) { ThrowFileException(exception,CacheError,"UnableToExtendCache", image->filename); return(MagickFalse); } length=number_pixels*(cache_info->number_channels*sizeof(Quantum)+ cache_info->metacontent_extent); if (length != (MagickSizeType) ((size_t) length)) cache_info->type=DiskCache; else { status=AcquireMagickResource(MapResource,cache_info->length); if ((status == MagickFalse) && (cache_info->type != MapCache) && (cache_info->type != MemoryCache)) cache_info->type=DiskCache; else { cache_info->pixels=(Quantum *) MapBlob(cache_info->file,mode, cache_info->offset,(size_t) cache_info->length); if (cache_info->pixels == (Quantum *) NULL) { cache_info->type=DiskCache; cache_info->pixels=source_info.pixels; } else { /* Create file-backed memory-mapped pixel cache. */ status=MagickTrue; (void) ClosePixelCacheOnDisk(cache_info); cache_info->type=MapCache; cache_info->mapped=MagickTrue; cache_info->metacontent=(void *) NULL; if (cache_info->metacontent_extent != 0) cache_info->metacontent=(void *) (cache_info->pixels+ number_pixels*cache_info->number_channels); if ((source_info.storage_class != UndefinedClass) && (mode != ReadMode)) { status=ClonePixelCacheRepository(cache_info,&source_info, exception); RelinquishPixelCachePixels(&source_info); } if (image->debug != MagickFalse) { (void) FormatMagickSize(cache_info->length,MagickTrue,"B", MagickPathExtent,format); type=CommandOptionToMnemonic(MagickCacheOptions,(ssize_t) cache_info->type); (void) FormatLocaleString(message,MagickPathExtent, "open %s (%s[%d], %s, %.20gx%.20gx%.20g %s)", cache_info->filename,cache_info->cache_filename, cache_info->file,type,(double) cache_info->columns,(double) cache_info->rows,(double) cache_info->number_channels, format); (void) LogMagickEvent(CacheEvent,GetMagickModule(),"%s", message); } return(status); } } RelinquishMagickResource(MapResource,cache_info->length); } status=MagickTrue; if ((source_info.storage_class != UndefinedClass) && (mode != ReadMode)) { status=ClonePixelCacheRepository(cache_info,&source_info,exception); RelinquishPixelCachePixels(&source_info); } if (image->debug != MagickFalse) { (void) FormatMagickSize(cache_info->length,MagickFalse,"B", MagickPathExtent,format); type=CommandOptionToMnemonic(MagickCacheOptions,(ssize_t) cache_info->type); (void) FormatLocaleString(message,MagickPathExtent, "open %s (%s[%d], %s, %.20gx%.20gx%.20g %s)",cache_info->filename, cache_info->cache_filename,cache_info->file,type,(double) cache_info->columns,(double) cache_info->rows,(double) cache_info->number_channels,format); (void) LogMagickEvent(CacheEvent,GetMagickModule(),"%s",message); } return(status); } Commit Message: Set pixel cache to undefined if any resource limit is exceeded CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static void pcrypt_free(struct crypto_instance *inst) { struct pcrypt_instance_ctx *ctx = crypto_instance_ctx(inst); crypto_drop_aead(&ctx->spawn); kfree(inst); } Commit Message: crypto: pcrypt - fix freeing pcrypt instances pcrypt is using the old way of freeing instances, where the ->free() method specified in the 'struct crypto_template' is passed a pointer to the 'struct crypto_instance'. But the crypto_instance is being kfree()'d directly, which is incorrect because the memory was actually allocated as an aead_instance, which contains the crypto_instance at a nonzero offset. Thus, the wrong pointer was being kfree()'d. Fix it by switching to the new way to free aead_instance's where the ->free() method is specified in the aead_instance itself. Reported-by: syzbot <[email protected]> Fixes: 0496f56065e0 ("crypto: pcrypt - Add support for new AEAD interface") Cc: <[email protected]> # v4.2+ Signed-off-by: Eric Biggers <[email protected]> Signed-off-by: Herbert Xu <[email protected]> CWE ID: CWE-763 Target: 1 Example 2: Code: views::MdTextButton* ConfirmInfoBar::CreateButton( ConfirmInfoBarDelegate::InfoBarButton type) { auto* button = views::MdTextButton::Create(this, GetDelegate()->GetButtonLabel(type)); button->SetProperty( views::kMarginsKey, new gfx::Insets(ChromeLayoutProvider::Get()->GetDistanceMetric( DISTANCE_TOAST_CONTROL_VERTICAL), 0)); AddChildView(button); button->SizeToPreferredSize(); return button; } Commit Message: Allow to specify elide behavior for confrim infobar message Used in "<extension name> is debugging this browser" infobar. Bug: 823194 Change-Id: Iff6627097c020cccca8f7cc3e21a803a41fd8f2c Reviewed-on: https://chromium-review.googlesource.com/1048064 Commit-Queue: Dmitry Gozman <[email protected]> Reviewed-by: Devlin <[email protected]> Reviewed-by: Peter Kasting <[email protected]> Cr-Commit-Position: refs/heads/master@{#557245} CWE ID: CWE-254 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void fuse_prepare_release(struct fuse_file *ff, int flags, int opcode) { struct fuse_conn *fc = ff->fc; struct fuse_req *req = ff->reserved_req; struct fuse_release_in *inarg = &req->misc.release.in; spin_lock(&fc->lock); list_del(&ff->write_entry); if (!RB_EMPTY_NODE(&ff->polled_node)) rb_erase(&ff->polled_node, &fc->polled_files); spin_unlock(&fc->lock); wake_up_interruptible_sync(&ff->poll_wait); inarg->fh = ff->fh; inarg->flags = flags; req->in.h.opcode = opcode; req->in.h.nodeid = ff->nodeid; req->in.numargs = 1; req->in.args[0].size = sizeof(struct fuse_release_in); req->in.args[0].value = inarg; } Commit Message: fuse: verify ioctl retries Verify that the total length of the iovec returned in FUSE_IOCTL_RETRY doesn't overflow iov_length(). Signed-off-by: Miklos Szeredi <[email protected]> CC: Tejun Heo <[email protected]> CC: <[email protected]> [2.6.31+] CWE ID: CWE-119 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void Part::slotOpenExtractedEntry(KJob *job) { if (!job->error()) { OpenJob *openJob = qobject_cast<OpenJob*>(job); Q_ASSERT(openJob); m_tmpExtractDirList << openJob->tempDir(); const QString fullName = openJob->validatedFilePath(); bool isWritable = m_model->archive() && !m_model->archive()->isReadOnly(); if (!isWritable) { QFile::setPermissions(fullName, QFileDevice::ReadOwner | QFileDevice::ReadGroup | QFileDevice::ReadOther); } if (isWritable) { m_fileWatcher = new QFileSystemWatcher; connect(m_fileWatcher, &QFileSystemWatcher::fileChanged, this, &Part::slotWatchedFileModified); m_fileWatcher->addPath(fullName); } if (qobject_cast<OpenWithJob*>(job)) { const QList<QUrl> urls = {QUrl::fromUserInput(fullName, QString(), QUrl::AssumeLocalFile)}; KRun::displayOpenWithDialog(urls, widget()); } else { KRun::runUrl(QUrl::fromUserInput(fullName, QString(), QUrl::AssumeLocalFile), QMimeDatabase().mimeTypeForFile(fullName).name(), widget()); } } else if (job->error() != KJob::KilledJobError) { KMessageBox::error(widget(), job->errorString()); } setReadyGui(); } Commit Message: CWE ID: CWE-78 Target: 1 Example 2: Code: void CheckClientDownloadRequest::MaybeUploadBinary(DownloadCheckResult result, const std::string& token) { if (ShouldUploadBinary(result)) { content::BrowserContext* browser_context = GetBrowserContext(); if (browser_context) { Profile* profile = Profile::FromBrowserContext(browser_context); auto request = std::make_unique<DownloadItemRequest>( item_, base::BindOnce(&MaybeReportDownloadDeepScanningVerdict, profile, item_->GetURL(), item_->GetTargetFilePath().AsUTF8Unsafe(), item_->GetHash())); DlpDeepScanningClientRequest dlp_request; dlp_request.set_content_source( DlpDeepScanningClientRequest::FILE_DOWNLOAD); request->set_request_dlp_scan(std::move(dlp_request)); MalwareDeepScanningClientRequest malware_request; malware_request.set_population( MalwareDeepScanningClientRequest::POPULATION_ENTERPRISE); malware_request.set_download_token(token); request->set_request_malware_scan(std::move(malware_request)); request->set_dm_token( policy::BrowserDMTokenStorage::Get()->RetrieveDMToken()); service()->UploadForDeepScanning(profile, std::move(request)); } } } Commit Message: Add reporting for DLP deep scanning For each triggered rule in the DLP response, we report the download as violating that rule. This also implements the UnsafeReportingEnabled enterprise policy, which controls whether or not we do any reporting. Bug: 980777 Change-Id: I48100cfb4dd5aa92ed80da1f34e64a6e393be2fa Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1772381 Commit-Queue: Daniel Rubery <[email protected]> Reviewed-by: Karan Bhatia <[email protected]> Reviewed-by: Roger Tawa <[email protected]> Cr-Commit-Position: refs/heads/master@{#691371} CWE ID: CWE-416 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void __exit zlib_mod_fini(void) { crypto_unregister_pcomp(&zlib_alg); } Commit Message: crypto: prefix module autoloading with "crypto-" This prefixes all crypto module loading with "crypto-" so we never run the risk of exposing module auto-loading to userspace via a crypto API, as demonstrated by Mathias Krause: https://lkml.org/lkml/2013/3/4/70 Signed-off-by: Kees Cook <[email protected]> Signed-off-by: Herbert Xu <[email protected]> CWE ID: CWE-264 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: http_rxchunk(struct http *hp) { char *q; int l, i; l = hp->prxbuf; do (void)http_rxchar(hp, 1, 0); while (hp->rxbuf[hp->prxbuf - 1] != '\n'); vtc_dump(hp->vl, 4, "len", hp->rxbuf + l, -1); i = strtoul(hp->rxbuf + l, &q, 16); bprintf(hp->chunklen, "%d", i); if ((q == hp->rxbuf + l) || (*q != '\0' && !vct_islws(*q))) { vtc_log(hp->vl, hp->fatal, "chunked fail %02x @ %d", *q, q - (hp->rxbuf + l)); } assert(q != hp->rxbuf + l); assert(*q == '\0' || vct_islws(*q)); hp->prxbuf = l; if (i > 0) { (void)http_rxchar(hp, i, 0); vtc_dump(hp->vl, 4, "chunk", hp->rxbuf + l, i); } l = hp->prxbuf; (void)http_rxchar(hp, 2, 0); if(!vct_iscrlf(hp->rxbuf[l])) vtc_log(hp->vl, hp->fatal, "Wrong chunk tail[0] = %02x", hp->rxbuf[l] & 0xff); if(!vct_iscrlf(hp->rxbuf[l + 1])) vtc_log(hp->vl, hp->fatal, "Wrong chunk tail[1] = %02x", hp->rxbuf[l + 1] & 0xff); hp->prxbuf = l; hp->rxbuf[l] = '\0'; return (i); } Commit Message: Do not consider a CR by itself as a valid line terminator Varnish (prior to version 4.0) was not following the standard with regard to line separator. Spotted and analyzed by: Régis Leroy [regilero] [email protected] CWE ID: Target: 1 Example 2: Code: void ASF_LegacyManager::ComputeDigest() { MD5_CTX context; MD5_Digest digest; char buffer[40]; MD5Init ( &context ); digestStr.clear(); digestStr.reserve ( 160 ); for ( int type=0; type < fieldLast; ++type ) { if (fields[type].size ( ) > 0 ) { snprintf ( buffer, sizeof(buffer), "%d,", type ); digestStr.append ( buffer ); MD5Update ( &context, (XMP_Uns8*)fields[type].data(), fields[type].size() ); } } if( digestStr.size() > 0 ) digestStr[digestStr.size()-1] = ';'; MD5Final ( digest, &context ); size_t in, out; for ( in = 0, out = 0; in < 16; in += 1, out += 2 ) { XMP_Uns8 byte = digest[in]; buffer[out] = ReconcileUtils::kHexDigits [ byte >> 4 ]; buffer[out+1] = ReconcileUtils::kHexDigits [ byte & 0xF ]; } buffer[32] = 0; digestStr.append ( buffer ); digestComputed = true; } Commit Message: CWE ID: CWE-835 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: int udp_recvmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg, size_t len, int noblock, int flags, int *addr_len) { struct inet_sock *inet = inet_sk(sk); struct sockaddr_in *sin = (struct sockaddr_in *)msg->msg_name; struct sk_buff *skb; unsigned int ulen, copied; int peeked, off = 0; int err; int is_udplite = IS_UDPLITE(sk); bool slow; /* * Check any passed addresses */ if (addr_len) *addr_len = sizeof(*sin); if (flags & MSG_ERRQUEUE) return ip_recv_error(sk, msg, len); try_again: skb = __skb_recv_datagram(sk, flags | (noblock ? MSG_DONTWAIT : 0), &peeked, &off, &err); if (!skb) goto out; ulen = skb->len - sizeof(struct udphdr); copied = len; if (copied > ulen) copied = ulen; else if (copied < ulen) msg->msg_flags |= MSG_TRUNC; /* * If checksum is needed at all, try to do it while copying the * data. If the data is truncated, or if we only want a partial * coverage checksum (UDP-Lite), do it before the copy. */ if (copied < ulen || UDP_SKB_CB(skb)->partial_cov) { if (udp_lib_checksum_complete(skb)) goto csum_copy_err; } if (skb_csum_unnecessary(skb)) err = skb_copy_datagram_iovec(skb, sizeof(struct udphdr), msg->msg_iov, copied); else { err = skb_copy_and_csum_datagram_iovec(skb, sizeof(struct udphdr), msg->msg_iov); if (err == -EINVAL) goto csum_copy_err; } if (unlikely(err)) { trace_kfree_skb(skb, udp_recvmsg); if (!peeked) { atomic_inc(&sk->sk_drops); UDP_INC_STATS_USER(sock_net(sk), UDP_MIB_INERRORS, is_udplite); } goto out_free; } if (!peeked) UDP_INC_STATS_USER(sock_net(sk), UDP_MIB_INDATAGRAMS, is_udplite); sock_recv_ts_and_drops(msg, sk, skb); /* Copy the address. */ if (sin) { sin->sin_family = AF_INET; sin->sin_port = udp_hdr(skb)->source; sin->sin_addr.s_addr = ip_hdr(skb)->saddr; memset(sin->sin_zero, 0, sizeof(sin->sin_zero)); } if (inet->cmsg_flags) ip_cmsg_recv(msg, skb); err = copied; if (flags & MSG_TRUNC) err = ulen; out_free: skb_free_datagram_locked(sk, skb); out: return err; csum_copy_err: slow = lock_sock_fast(sk); if (!skb_kill_datagram(sk, skb, flags)) { UDP_INC_STATS_USER(sock_net(sk), UDP_MIB_CSUMERRORS, is_udplite); UDP_INC_STATS_USER(sock_net(sk), UDP_MIB_INERRORS, is_udplite); } unlock_sock_fast(sk, slow); if (noblock) return -EAGAIN; /* starting over for a new packet */ msg->msg_flags &= ~MSG_TRUNC; goto try_again; } Commit Message: ipv6: call udp_push_pending_frames when uncorking a socket with AF_INET pending data We accidentally call down to ip6_push_pending_frames when uncorking pending AF_INET data on a ipv6 socket. This results in the following splat (from Dave Jones): skbuff: skb_under_panic: text:ffffffff816765f6 len:48 put:40 head:ffff88013deb6df0 data:ffff88013deb6dec tail:0x2c end:0xc0 dev:<NULL> ------------[ cut here ]------------ kernel BUG at net/core/skbuff.c:126! invalid opcode: 0000 [#1] PREEMPT SMP DEBUG_PAGEALLOC Modules linked in: dccp_ipv4 dccp 8021q garp bridge stp dlci mpoa snd_seq_dummy sctp fuse hidp tun bnep nfnetlink scsi_transport_iscsi rfcomm can_raw can_bcm af_802154 appletalk caif_socket can caif ipt_ULOG x25 rose af_key pppoe pppox ipx phonet irda llc2 ppp_generic slhc p8023 psnap p8022 llc crc_ccitt atm bluetooth +netrom ax25 nfc rfkill rds af_rxrpc coretemp hwmon kvm_intel kvm crc32c_intel snd_hda_codec_realtek ghash_clmulni_intel microcode pcspkr snd_hda_codec_hdmi snd_hda_intel snd_hda_codec snd_hwdep usb_debug snd_seq snd_seq_device snd_pcm e1000e snd_page_alloc snd_timer ptp snd pps_core soundcore xfs libcrc32c CPU: 2 PID: 8095 Comm: trinity-child2 Not tainted 3.10.0-rc7+ #37 task: ffff8801f52c2520 ti: ffff8801e6430000 task.ti: ffff8801e6430000 RIP: 0010:[<ffffffff816e759c>] [<ffffffff816e759c>] skb_panic+0x63/0x65 RSP: 0018:ffff8801e6431de8 EFLAGS: 00010282 RAX: 0000000000000086 RBX: ffff8802353d3cc0 RCX: 0000000000000006 RDX: 0000000000003b90 RSI: ffff8801f52c2ca0 RDI: ffff8801f52c2520 RBP: ffff8801e6431e08 R08: 0000000000000000 R09: 0000000000000000 R10: 0000000000000001 R11: 0000000000000001 R12: ffff88022ea0c800 R13: ffff88022ea0cdf8 R14: ffff8802353ecb40 R15: ffffffff81cc7800 FS: 00007f5720a10740(0000) GS:ffff880244c00000(0000) knlGS:0000000000000000 CS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033 CR2: 0000000005862000 CR3: 000000022843c000 CR4: 00000000001407e0 DR0: 0000000000000000 DR1: 0000000000000000 DR2: 0000000000000000 DR3: 0000000000000000 DR6: 00000000fffe0ff0 DR7: 0000000000000600 Stack: ffff88013deb6dec 000000000000002c 00000000000000c0 ffffffff81a3f6e4 ffff8801e6431e18 ffffffff8159a9aa ffff8801e6431e90 ffffffff816765f6 ffffffff810b756b 0000000700000002 ffff8801e6431e40 0000fea9292aa8c0 Call Trace: [<ffffffff8159a9aa>] skb_push+0x3a/0x40 [<ffffffff816765f6>] ip6_push_pending_frames+0x1f6/0x4d0 [<ffffffff810b756b>] ? mark_held_locks+0xbb/0x140 [<ffffffff81694919>] udp_v6_push_pending_frames+0x2b9/0x3d0 [<ffffffff81694660>] ? udplite_getfrag+0x20/0x20 [<ffffffff8162092a>] udp_lib_setsockopt+0x1aa/0x1f0 [<ffffffff811cc5e7>] ? fget_light+0x387/0x4f0 [<ffffffff816958a4>] udpv6_setsockopt+0x34/0x40 [<ffffffff815949f4>] sock_common_setsockopt+0x14/0x20 [<ffffffff81593c31>] SyS_setsockopt+0x71/0xd0 [<ffffffff816f5d54>] tracesys+0xdd/0xe2 Code: 00 00 48 89 44 24 10 8b 87 d8 00 00 00 48 89 44 24 08 48 8b 87 e8 00 00 00 48 c7 c7 c0 04 aa 81 48 89 04 24 31 c0 e8 e1 7e ff ff <0f> 0b 55 48 89 e5 0f 0b 55 48 89 e5 0f 0b 55 48 89 e5 0f 0b 55 RIP [<ffffffff816e759c>] skb_panic+0x63/0x65 RSP <ffff8801e6431de8> This patch adds a check if the pending data is of address family AF_INET and directly calls udp_push_ending_frames from udp_v6_push_pending_frames if that is the case. This bug was found by Dave Jones with trinity. (Also move the initialization of fl6 below the AF_INET check, even if not strictly necessary.) Cc: Dave Jones <[email protected]> Cc: YOSHIFUJI Hideaki <[email protected]> Signed-off-by: Hannes Frederic Sowa <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-399 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: mm_zalloc(struct mm_master *mm, u_int ncount, u_int size) { if (size == 0 || ncount == 0 || ncount > SIZE_MAX / size) fatal("%s: mm_zalloc(%u, %u)", __func__, ncount, size); return mm_malloc(mm, size * ncount); } Commit Message: Remove support for pre-authentication compression. Doing compression early in the protocol probably seemed reasonable in the 1990s, but today it's clearly a bad idea in terms of both cryptography (cf. multiple compression oracle attacks in TLS) and attack surface. Moreover, to support it across privilege-separation zlib needed the assistance of a complex shared-memory manager that made the required attack surface considerably larger. Prompted by Guido Vranken pointing out a compiler-elided security check in the shared memory manager found by Stack (http://css.csail.mit.edu/stack/); ok deraadt@ markus@ NB. pre-auth authentication has been disabled by default in sshd for >10 years. CWE ID: CWE-119 Target: 1 Example 2: Code: static u8 sctp_trans_score(const struct sctp_transport *trans) { return sctp_trans_state_to_prio_map[trans->state]; } Commit Message: net: sctp: inherit auth_capable on INIT collisions Jason reported an oops caused by SCTP on his ARM machine with SCTP authentication enabled: Internal error: Oops: 17 [#1] ARM CPU: 0 PID: 104 Comm: sctp-test Not tainted 3.13.0-68744-g3632f30c9b20-dirty #1 task: c6eefa40 ti: c6f52000 task.ti: c6f52000 PC is at sctp_auth_calculate_hmac+0xc4/0x10c LR is at sg_init_table+0x20/0x38 pc : [<c024bb80>] lr : [<c00f32dc>] psr: 40000013 sp : c6f538e8 ip : 00000000 fp : c6f53924 r10: c6f50d80 r9 : 00000000 r8 : 00010000 r7 : 00000000 r6 : c7be4000 r5 : 00000000 r4 : c6f56254 r3 : c00c8170 r2 : 00000001 r1 : 00000008 r0 : c6f1e660 Flags: nZcv IRQs on FIQs on Mode SVC_32 ISA ARM Segment user Control: 0005397f Table: 06f28000 DAC: 00000015 Process sctp-test (pid: 104, stack limit = 0xc6f521c0) Stack: (0xc6f538e8 to 0xc6f54000) [...] Backtrace: [<c024babc>] (sctp_auth_calculate_hmac+0x0/0x10c) from [<c0249af8>] (sctp_packet_transmit+0x33c/0x5c8) [<c02497bc>] (sctp_packet_transmit+0x0/0x5c8) from [<c023e96c>] (sctp_outq_flush+0x7fc/0x844) [<c023e170>] (sctp_outq_flush+0x0/0x844) from [<c023ef78>] (sctp_outq_uncork+0x24/0x28) [<c023ef54>] (sctp_outq_uncork+0x0/0x28) from [<c0234364>] (sctp_side_effects+0x1134/0x1220) [<c0233230>] (sctp_side_effects+0x0/0x1220) from [<c02330b0>] (sctp_do_sm+0xac/0xd4) [<c0233004>] (sctp_do_sm+0x0/0xd4) from [<c023675c>] (sctp_assoc_bh_rcv+0x118/0x160) [<c0236644>] (sctp_assoc_bh_rcv+0x0/0x160) from [<c023d5bc>] (sctp_inq_push+0x6c/0x74) [<c023d550>] (sctp_inq_push+0x0/0x74) from [<c024a6b0>] (sctp_rcv+0x7d8/0x888) While we already had various kind of bugs in that area ec0223ec48a9 ("net: sctp: fix sctp_sf_do_5_1D_ce to verify if we/peer is AUTH capable") and b14878ccb7fa ("net: sctp: cache auth_enable per endpoint"), this one is a bit of a different kind. Giving a bit more background on why SCTP authentication is needed can be found in RFC4895: SCTP uses 32-bit verification tags to protect itself against blind attackers. These values are not changed during the lifetime of an SCTP association. Looking at new SCTP extensions, there is the need to have a method of proving that an SCTP chunk(s) was really sent by the original peer that started the association and not by a malicious attacker. To cause this bug, we're triggering an INIT collision between peers; normal SCTP handshake where both sides intent to authenticate packets contains RANDOM; CHUNKS; HMAC-ALGO parameters that are being negotiated among peers: ---------- INIT[RANDOM; CHUNKS; HMAC-ALGO] ----------> <------- INIT-ACK[RANDOM; CHUNKS; HMAC-ALGO] --------- -------------------- COOKIE-ECHO --------------------> <-------------------- COOKIE-ACK --------------------- RFC4895 says that each endpoint therefore knows its own random number and the peer's random number *after* the association has been established. The local and peer's random number along with the shared key are then part of the secret used for calculating the HMAC in the AUTH chunk. Now, in our scenario, we have 2 threads with 1 non-blocking SEQ_PACKET socket each, setting up common shared SCTP_AUTH_KEY and SCTP_AUTH_ACTIVE_KEY properly, and each of them calling sctp_bindx(3), listen(2) and connect(2) against each other, thus the handshake looks similar to this, e.g.: ---------- INIT[RANDOM; CHUNKS; HMAC-ALGO] ----------> <------- INIT-ACK[RANDOM; CHUNKS; HMAC-ALGO] --------- <--------- INIT[RANDOM; CHUNKS; HMAC-ALGO] ----------- -------- INIT-ACK[RANDOM; CHUNKS; HMAC-ALGO] --------> ... Since such collisions can also happen with verification tags, the RFC4895 for AUTH rather vaguely says under section 6.1: In case of INIT collision, the rules governing the handling of this Random Number follow the same pattern as those for the Verification Tag, as explained in Section 5.2.4 of RFC 2960 [5]. Therefore, each endpoint knows its own Random Number and the peer's Random Number after the association has been established. In RFC2960, section 5.2.4, we're eventually hitting Action B: B) In this case, both sides may be attempting to start an association at about the same time but the peer endpoint started its INIT after responding to the local endpoint's INIT. Thus it may have picked a new Verification Tag not being aware of the previous Tag it had sent this endpoint. The endpoint should stay in or enter the ESTABLISHED state but it MUST update its peer's Verification Tag from the State Cookie, stop any init or cookie timers that may running and send a COOKIE ACK. In other words, the handling of the Random parameter is the same as behavior for the Verification Tag as described in Action B of section 5.2.4. Looking at the code, we exactly hit the sctp_sf_do_dupcook_b() case which triggers an SCTP_CMD_UPDATE_ASSOC command to the side effect interpreter, and in fact it properly copies over peer_{random, hmacs, chunks} parameters from the newly created association to update the existing one. Also, the old asoc_shared_key is being released and based on the new params, sctp_auth_asoc_init_active_key() updated. However, the issue observed in this case is that the previous asoc->peer.auth_capable was 0, and has *not* been updated, so that instead of creating a new secret, we're doing an early return from the function sctp_auth_asoc_init_active_key() leaving asoc->asoc_shared_key as NULL. However, we now have to authenticate chunks from the updated chunk list (e.g. COOKIE-ACK). That in fact causes the server side when responding with ... <------------------ AUTH; COOKIE-ACK ----------------- ... to trigger a NULL pointer dereference, since in sctp_packet_transmit(), it discovers that an AUTH chunk is being queued for xmit, and thus it calls sctp_auth_calculate_hmac(). Since the asoc->active_key_id is still inherited from the endpoint, and the same as encoded into the chunk, it uses asoc->asoc_shared_key, which is still NULL, as an asoc_key and dereferences it in ... crypto_hash_setkey(desc.tfm, &asoc_key->data[0], asoc_key->len) ... causing an oops. All this happens because sctp_make_cookie_ack() called with the *new* association has the peer.auth_capable=1 and therefore marks the chunk with auth=1 after checking sctp_auth_send_cid(), but it is *actually* sent later on over the then *updated* association's transport that didn't initialize its shared key due to peer.auth_capable=0. Since control chunks in that case are not sent by the temporary association which are scheduled for deletion, they are issued for xmit via SCTP_CMD_REPLY in the interpreter with the context of the *updated* association. peer.auth_capable was 0 in the updated association (which went from COOKIE_WAIT into ESTABLISHED state), since all previous processing that performed sctp_process_init() was being done on temporary associations, that we eventually throw away each time. The correct fix is to update to the new peer.auth_capable value as well in the collision case via sctp_assoc_update(), so that in case the collision migrated from 0 -> 1, sctp_auth_asoc_init_active_key() can properly recalculate the secret. This therefore fixes the observed server panic. Fixes: 730fc3d05cd4 ("[SCTP]: Implete SCTP-AUTH parameter processing") Reported-by: Jason Gunthorpe <[email protected]> Signed-off-by: Daniel Borkmann <[email protected]> Tested-by: Jason Gunthorpe <[email protected]> Cc: Vlad Yasevich <[email protected]> Acked-by: Vlad Yasevich <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int __fib_validate_source(struct sk_buff *skb, __be32 src, __be32 dst, u8 tos, int oif, struct net_device *dev, int rpf, struct in_device *idev, u32 *itag) { int ret, no_addr; struct fib_result res; struct flowi4 fl4; struct net *net; bool dev_match; fl4.flowi4_oif = 0; fl4.flowi4_iif = l3mdev_master_ifindex_rcu(dev); if (!fl4.flowi4_iif) fl4.flowi4_iif = oif ? : LOOPBACK_IFINDEX; fl4.daddr = src; fl4.saddr = dst; fl4.flowi4_tos = tos; fl4.flowi4_scope = RT_SCOPE_UNIVERSE; fl4.flowi4_tun_key.tun_id = 0; fl4.flowi4_flags = 0; no_addr = idev->ifa_list == NULL; fl4.flowi4_mark = IN_DEV_SRC_VMARK(idev) ? skb->mark : 0; trace_fib_validate_source(dev, &fl4); net = dev_net(dev); if (fib_lookup(net, &fl4, &res, 0)) goto last_resort; if (res.type != RTN_UNICAST && (res.type != RTN_LOCAL || !IN_DEV_ACCEPT_LOCAL(idev))) goto e_inval; if (!rpf && !fib_num_tclassid_users(dev_net(dev)) && (dev->ifindex != oif || !IN_DEV_TX_REDIRECTS(idev))) goto last_resort; fib_combine_itag(itag, &res); dev_match = false; #ifdef CONFIG_IP_ROUTE_MULTIPATH for (ret = 0; ret < res.fi->fib_nhs; ret++) { struct fib_nh *nh = &res.fi->fib_nh[ret]; if (nh->nh_dev == dev) { dev_match = true; break; } else if (l3mdev_master_ifindex_rcu(nh->nh_dev) == dev->ifindex) { dev_match = true; break; } } #else if (FIB_RES_DEV(res) == dev) dev_match = true; #endif if (dev_match) { ret = FIB_RES_NH(res).nh_scope >= RT_SCOPE_HOST; return ret; } if (no_addr) goto last_resort; if (rpf == 1) goto e_rpf; fl4.flowi4_oif = dev->ifindex; ret = 0; if (fib_lookup(net, &fl4, &res, FIB_LOOKUP_IGNORE_LINKSTATE) == 0) { if (res.type == RTN_UNICAST) ret = FIB_RES_NH(res).nh_scope >= RT_SCOPE_HOST; } return ret; last_resort: if (rpf) goto e_rpf; *itag = 0; return 0; e_inval: return -EINVAL; e_rpf: return -EXDEV; } Commit Message: ipv4: Don't do expensive useless work during inetdev destroy. When an inetdev is destroyed, every address assigned to the interface is removed. And in this scenerio we do two pointless things which can be very expensive if the number of assigned interfaces is large: 1) Address promotion. We are deleting all addresses, so there is no point in doing this. 2) A full nf conntrack table purge for every address. We only need to do this once, as is already caught by the existing masq_dev_notifier so masq_inet_event() can skip this. Reported-by: Solar Designer <[email protected]> Signed-off-by: David S. Miller <[email protected]> Tested-by: Cyrill Gorcunov <[email protected]> CWE ID: CWE-399 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: cJSON *cJSON_CreateFloat( double num ) { cJSON *item = cJSON_New_Item(); if ( item ) { item->type = cJSON_Number; item->valuefloat = num; item->valueint = num; } return item; } Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a malformed JSON string was passed on the control channel. This issue, present in the cJSON library, was already fixed upstream, so was addressed here in iperf3 by importing a newer version of cJSON (plus local ESnet modifications). Discovered and reported by Dave McDaniel, Cisco Talos. Based on a patch by @dopheide-esnet, with input from @DaveGamble. Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001, CVE-2016-4303 (cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40) Signed-off-by: Bruce A. Mah <[email protected]> CWE ID: CWE-119 Target: 1 Example 2: Code: static int airo_get_encode(struct net_device *dev, struct iw_request_info *info, struct iw_point *dwrq, char *extra) { struct airo_info *local = dev->ml_priv; int index = (dwrq->flags & IW_ENCODE_INDEX) - 1; int wep_key_len; u8 buf[16]; if (!local->wep_capable) return -EOPNOTSUPP; readConfigRid(local, 1); /* Check encryption mode */ switch(local->config.authType) { case AUTH_ENCRYPT: dwrq->flags = IW_ENCODE_OPEN; break; case AUTH_SHAREDKEY: dwrq->flags = IW_ENCODE_RESTRICTED; break; default: case AUTH_OPEN: dwrq->flags = IW_ENCODE_DISABLED; break; } /* We can't return the key, so set the proper flag and return zero */ dwrq->flags |= IW_ENCODE_NOKEY; memset(extra, 0, 16); /* Which key do we want ? -1 -> tx index */ if (!valid_index(local, index)) { index = get_wep_tx_idx(local); if (index < 0) index = 0; } dwrq->flags |= index + 1; /* Copy the key to the user buffer */ wep_key_len = get_wep_key(local, index, &buf[0], sizeof(buf)); if (wep_key_len < 0) { dwrq->length = 0; } else { dwrq->length = wep_key_len; memcpy(extra, buf, dwrq->length); } return 0; } Commit Message: net: Audit drivers to identify those needing IFF_TX_SKB_SHARING cleared After the last patch, We are left in a state in which only drivers calling ether_setup have IFF_TX_SKB_SHARING set (we assume that drivers touching real hardware call ether_setup for their net_devices and don't hold any state in their skbs. There are a handful of drivers that violate this assumption of course, and need to be fixed up. This patch identifies those drivers, and marks them as not being able to support the safe transmission of skbs by clearning the IFF_TX_SKB_SHARING flag in priv_flags Signed-off-by: Neil Horman <[email protected]> CC: Karsten Keil <[email protected]> CC: "David S. Miller" <[email protected]> CC: Jay Vosburgh <[email protected]> CC: Andy Gospodarek <[email protected]> CC: Patrick McHardy <[email protected]> CC: Krzysztof Halasa <[email protected]> CC: "John W. Linville" <[email protected]> CC: Greg Kroah-Hartman <[email protected]> CC: Marcel Holtmann <[email protected]> CC: Johannes Berg <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-264 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: int wait_for_key_construction(struct key *key, bool intr) { int ret; ret = wait_on_bit(&key->flags, KEY_FLAG_USER_CONSTRUCT, intr ? TASK_INTERRUPTIBLE : TASK_UNINTERRUPTIBLE); if (ret) return -ERESTARTSYS; if (test_bit(KEY_FLAG_NEGATIVE, &key->flags)) { smp_rmb(); return key->reject_error; } return key_validate(key); } Commit Message: KEYS: Fix race between updating and finding a negative key Consolidate KEY_FLAG_INSTANTIATED, KEY_FLAG_NEGATIVE and the rejection error into one field such that: (1) The instantiation state can be modified/read atomically. (2) The error can be accessed atomically with the state. (3) The error isn't stored unioned with the payload pointers. This deals with the problem that the state is spread over three different objects (two bits and a separate variable) and reading or updating them atomically isn't practical, given that not only can uninstantiated keys change into instantiated or rejected keys, but rejected keys can also turn into instantiated keys - and someone accessing the key might not be using any locking. The main side effect of this problem is that what was held in the payload may change, depending on the state. For instance, you might observe the key to be in the rejected state. You then read the cached error, but if the key semaphore wasn't locked, the key might've become instantiated between the two reads - and you might now have something in hand that isn't actually an error code. The state is now KEY_IS_UNINSTANTIATED, KEY_IS_POSITIVE or a negative error code if the key is negatively instantiated. The key_is_instantiated() function is replaced with key_is_positive() to avoid confusion as negative keys are also 'instantiated'. Additionally, barriering is included: (1) Order payload-set before state-set during instantiation. (2) Order state-read before payload-read when using the key. Further separate barriering is necessary if RCU is being used to access the payload content after reading the payload pointers. Fixes: 146aa8b1453b ("KEYS: Merge the type-specific data with the payload data") Cc: [email protected] # v4.4+ Reported-by: Eric Biggers <[email protected]> Signed-off-by: David Howells <[email protected]> Reviewed-by: Eric Biggers <[email protected]> CWE ID: CWE-20 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: pvscsi_ring_init_data(PVSCSIRingInfo *m, PVSCSICmdDescSetupRings *ri) { int i; uint32_t txr_len_log2, rxr_len_log2; uint32_t req_ring_size, cmp_ring_size; m->rs_pa = ri->ringsStatePPN << VMW_PAGE_SHIFT; if ((ri->reqRingNumPages > PVSCSI_SETUP_RINGS_MAX_NUM_PAGES) || (ri->cmpRingNumPages > PVSCSI_SETUP_RINGS_MAX_NUM_PAGES)) { return -1; } req_ring_size = ri->reqRingNumPages * PVSCSI_MAX_NUM_REQ_ENTRIES_PER_PAGE; cmp_ring_size = ri->cmpRingNumPages * PVSCSI_MAX_NUM_CMP_ENTRIES_PER_PAGE; txr_len_log2 = pvscsi_log2(req_ring_size - 1); } Commit Message: CWE ID: CWE-125 Target: 1 Example 2: Code: static int des_setkey(struct crypto_tfm *tfm, const u8 *key, unsigned int keylen) { struct des_ctx *dctx = crypto_tfm_ctx(tfm); u32 *flags = &tfm->crt_flags; u32 tmp[DES_EXPKEY_WORDS]; int ret; /* Expand to tmp */ ret = des_ekey(tmp, key); if (unlikely(ret == 0) && (*flags & CRYPTO_TFM_REQ_WEAK_KEY)) { *flags |= CRYPTO_TFM_RES_WEAK_KEY; return -EINVAL; } /* Copy to output */ memcpy(dctx->expkey, tmp, sizeof(dctx->expkey)); return 0; } Commit Message: crypto: prefix module autoloading with "crypto-" This prefixes all crypto module loading with "crypto-" so we never run the risk of exposing module auto-loading to userspace via a crypto API, as demonstrated by Mathias Krause: https://lkml.org/lkml/2013/3/4/70 Signed-off-by: Kees Cook <[email protected]> Signed-off-by: Herbert Xu <[email protected]> CWE ID: CWE-264 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int v9fs_xattr_fid_clunk(V9fsPDU *pdu, V9fsFidState *fidp) { int retval = 0; if (fidp->fs.xattr.copied_len == -1) { /* getxattr/listxattr fid */ goto free_value; } /* * if this is fid for setxattr. clunk should * result in setxattr localcall */ if (fidp->fs.xattr.len != fidp->fs.xattr.copied_len) { /* clunk after partial write */ retval = -EINVAL; goto free_out; } if (fidp->fs.xattr.len) { retval = v9fs_co_lsetxattr(pdu, &fidp->path, &fidp->fs.xattr.name, fidp->fs.xattr.value, fidp->fs.xattr.len, fidp->fs.xattr.flags); } else { retval = v9fs_co_lremovexattr(pdu, &fidp->path, &fidp->fs.xattr.name); } free_out: v9fs_string_free(&fidp->fs.xattr.name); free_value: g_free(fidp->fs.xattr.value); return retval; } Commit Message: CWE ID: CWE-399 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: 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 Target: 1 Example 2: Code: P2PSocketDispatcherHost::~P2PSocketDispatcherHost() { DCHECK(sockets_.empty()); } Commit Message: Fixing Coverity bugs (DEAD_CODE and PASS_BY_VALUE) CIDs 16230, 16439, 16610, 16635 BUG=NONE TEST=NONE Review URL: http://codereview.chromium.org/7215029 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@90134 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: NavigationPolicy FrameLoader::ShouldContinueForRedirectNavigationPolicy( const ResourceRequest& request, const SubstituteData& substitute_data, DocumentLoader* loader, ContentSecurityPolicyDisposition should_check_main_world_content_security_policy, NavigationType type, NavigationPolicy policy, FrameLoadType frame_load_type, bool is_client_redirect, HTMLFormElement* form) { Settings* settings = frame_->GetSettings(); MaybeCheckCSP(request, type, frame_, policy, should_check_main_world_content_security_policy == kCheckContentSecurityPolicy, settings && settings->GetBrowserSideNavigationEnabled(), ContentSecurityPolicy::CheckHeaderType::kCheckReportOnly); return ShouldContinueForNavigationPolicy( request, nullptr, // origin_document substitute_data, loader, should_check_main_world_content_security_policy, type, policy, frame_load_type, is_client_redirect, WebTriggeringEventInfo::kNotFromEvent, form); } Commit Message: Fix detach with open()ed document leaving parent loading indefinitely Change-Id: I26c2a054b9f1e5eb076acd677e1223058825f6d6 Bug: 803416 Test: fast/loader/document-open-iframe-then-detach.html Change-Id: I26c2a054b9f1e5eb076acd677e1223058825f6d6 Reviewed-on: https://chromium-review.googlesource.com/887298 Reviewed-by: Mike West <[email protected]> Commit-Queue: Nate Chapin <[email protected]> Cr-Commit-Position: refs/heads/master@{#532967} CWE ID: CWE-362 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: IDNSpoofChecker::IDNSpoofChecker() { UErrorCode status = U_ZERO_ERROR; checker_ = uspoof_open(&status); if (U_FAILURE(status)) { checker_ = nullptr; return; } uspoof_setRestrictionLevel(checker_, USPOOF_HIGHLY_RESTRICTIVE); SetAllowedUnicodeSet(&status); int32_t checks = uspoof_getChecks(checker_, &status) | USPOOF_AUX_INFO; uspoof_setChecks(checker_, checks, &status); deviation_characters_ = icu::UnicodeSet( UNICODE_STRING_SIMPLE("[\\u00df\\u03c2\\u200c\\u200d]"), status); deviation_characters_.freeze(); non_ascii_latin_letters_ = icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Latin:] - [a-zA-Z]]"), status); non_ascii_latin_letters_.freeze(); kana_letters_exceptions_ = icu::UnicodeSet( UNICODE_STRING_SIMPLE("[\\u3078-\\u307a\\u30d8-\\u30da\\u30fb-\\u30fe]"), status); kana_letters_exceptions_.freeze(); combining_diacritics_exceptions_ = icu::UnicodeSet(UNICODE_STRING_SIMPLE("[\\u0300-\\u0339]"), status); combining_diacritics_exceptions_.freeze(); cyrillic_letters_latin_alike_ = icu::UnicodeSet( icu::UnicodeString::fromUTF8("[асԁеһіјӏорԛѕԝхуъЬҽпгѵѡ]"), status); cyrillic_letters_latin_alike_.freeze(); cyrillic_letters_ = icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Cyrl:]]"), status); cyrillic_letters_.freeze(); DCHECK(U_SUCCESS(status)); lgc_letters_n_ascii_ = icu::UnicodeSet( UNICODE_STRING_SIMPLE("[[:Latin:][:Greek:][:Cyrillic:][0-9\\u002e_" "\\u002d][\\u0300-\\u0339]]"), status); lgc_letters_n_ascii_.freeze(); UParseError parse_error; diacritic_remover_.reset(icu::Transliterator::createFromRules( UNICODE_STRING_SIMPLE("DropAcc"), icu::UnicodeString::fromUTF8("::NFD; ::[:Nonspacing Mark:] Remove; ::NFC;" " ł > l; ø > o; đ > d;"), UTRANS_FORWARD, parse_error, status)); extra_confusable_mapper_.reset(icu::Transliterator::createFromRules( UNICODE_STRING_SIMPLE("ExtraConf"), icu::UnicodeString::fromUTF8( "[æӕ] > ae; [þϼҏ] > p; [ħнћңҥӈӊԋԧԩ] > h;" "[ĸκкқҝҟҡӄԟ] > k; [ŋпԥ] > n; œ > ce;" "[ŧтҭԏ] > t; [ƅьҍв] > b; [ωшщพฟພຟ] > w;" "[мӎ] > m; [єҽҿၔ] > e; ґ > r; [ғӻ] > f;" "[ҫင] > c; ұ > y; [χҳӽӿ] > x;" "ԃ > d; [ԍဌ] > g; [ടรຣຮ] > s; ၂ > j;" "[зҙӡვဒ] > 3; [บບ] > u"), UTRANS_FORWARD, parse_error, status)); DCHECK(U_SUCCESS(status)) << "Spoofchecker initalization failed due to an error: " << u_errorName(status); } Commit Message: Add additional Lao character to IDN confusables U+0E01 (ก) => n Prior Lao/Thai entries were added in crrev.com/c/1058710. Test: components_unittests --gtest_filter=*IDN* Bug: 882078 Change-Id: I1e90b144a1d791341b515d026a6bc4be7cbed57d Reviewed-on: https://chromium-review.googlesource.com/1220773 Reviewed-by: Peter Kasting <[email protected]> Commit-Queue: Christopher Thompson <[email protected]> Cr-Commit-Position: refs/heads/master@{#591227} CWE ID: CWE-20 Target: 1 Example 2: Code: R_API void r_bin_java_bootstrap_method_free(void /*/RBinJavaBootStrapMethod*/ *b) { RBinJavaBootStrapMethod *bsm = b; RListIter *iter, *iter_tmp; RBinJavaBootStrapArgument *obj = NULL; if (bsm) { if (bsm->bootstrap_arguments) { r_list_foreach_safe (bsm->bootstrap_arguments, iter, iter_tmp, obj) { if (obj) { r_bin_java_bootstrap_method_argument_free (obj); } } r_list_free (bsm->bootstrap_arguments); bsm->bootstrap_arguments = NULL; } free (bsm); } } Commit Message: Fix #10498 - Crash in fuzzed java file CWE ID: CWE-125 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void OverloadedPerWorldBindingsMethod1MethodForMainWorld(const v8::FunctionCallbackInfo<v8::Value>& info) { TestObject* impl = V8TestObject::ToImpl(info.Holder()); impl->overloadedPerWorldBindingsMethod(); } Commit Message: bindings: Support "attribute FrozenArray<T>?" Adds a quick hack to support a case of "attribute FrozenArray<T>?". Bug: 1028047 Change-Id: Ib3cecc4beb6bcc0fb0dbc667aca595454cc90c86 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1933866 Reviewed-by: Hitoshi Yoshida <[email protected]> Commit-Queue: Yuki Shiino <[email protected]> Cr-Commit-Position: refs/heads/master@{#718676} CWE ID: Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void impeg2d_next_code(dec_state_t *ps_dec, UWORD32 u4_start_code_val) { stream_t *ps_stream; ps_stream = &ps_dec->s_bit_stream; impeg2d_bit_stream_flush_to_byte_boundary(ps_stream); while ((impeg2d_bit_stream_nxt(ps_stream,START_CODE_LEN) != u4_start_code_val) && (ps_dec->s_bit_stream.u4_offset <= ps_dec->s_bit_stream.u4_max_offset)) { if (impeg2d_bit_stream_get(ps_stream,8) != 0) { /* Ignore stuffing bit errors. */ } } return; } 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 Target: 1 Example 2: Code: cleanup_handler(int sig) { cleanup_socket(); #ifdef ENABLE_PKCS11 pkcs11_terminate(); #endif _exit(2); } Commit Message: add a whitelist of paths from which ssh-agent will load (via ssh-pkcs11-helper) a PKCS#11 module; ok markus@ CWE ID: CWE-426 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void Document::InitDNSPrefetch() { Settings* settings = GetSettings(); have_explicitly_disabled_dns_prefetch_ = false; is_dns_prefetch_enabled_ = settings && settings->GetDNSPrefetchingEnabled() && GetSecurityOrigin()->Protocol() == "http"; if (Document* parent = ParentDocument()) { if (!parent->IsDNSPrefetchEnabled()) is_dns_prefetch_enabled_ = false; } } Commit Message: Cleanup and remove dead code in SetFocusedElement This early-out was added in: https://crrev.com/ce8ea3446283965c7eabab592cbffe223b1cf2bc Back then, we applied fragment focus in LayoutUpdated() which could cause this issue. This got cleaned up in: https://crrev.com/45236fd563e9df53dc45579be1f3d0b4784885a2 so that focus is no longer applied after layout. +Cleanup: Goto considered harmful Bug: 795381 Change-Id: Ifeb4d2e03e872fd48cca6720b1d4de36ad1ecbb7 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1524417 Commit-Queue: David Bokan <[email protected]> Reviewed-by: Stefan Zager <[email protected]> Cr-Commit-Position: refs/heads/master@{#641101} CWE ID: CWE-416 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: ConflictResolver::ProcessSimpleConflict(WriteTransaction* trans, const Id& id, const Cryptographer* cryptographer, StatusController* status) { MutableEntry entry(trans, syncable::GET_BY_ID, id); CHECK(entry.good()); if (!entry.Get(syncable::IS_UNAPPLIED_UPDATE) || !entry.Get(syncable::IS_UNSYNCED)) { return NO_SYNC_PROGRESS; } if (entry.Get(syncable::IS_DEL) && entry.Get(syncable::SERVER_IS_DEL)) { entry.Put(syncable::IS_UNSYNCED, false); entry.Put(syncable::IS_UNAPPLIED_UPDATE, false); return NO_SYNC_PROGRESS; } if (!entry.Get(syncable::SERVER_IS_DEL)) { bool name_matches = entry.Get(syncable::NON_UNIQUE_NAME) == entry.Get(syncable::SERVER_NON_UNIQUE_NAME); bool parent_matches = entry.Get(syncable::PARENT_ID) == entry.Get(syncable::SERVER_PARENT_ID); bool entry_deleted = entry.Get(syncable::IS_DEL); syncable::Id server_prev_id = entry.ComputePrevIdFromServerPosition( entry.Get(syncable::SERVER_PARENT_ID)); bool needs_reinsertion = !parent_matches || server_prev_id != entry.Get(syncable::PREV_ID); DVLOG_IF(1, needs_reinsertion) << "Insertion needed, server prev id " << " is " << server_prev_id << ", local prev id is " << entry.Get(syncable::PREV_ID); const sync_pb::EntitySpecifics& specifics = entry.Get(syncable::SPECIFICS); const sync_pb::EntitySpecifics& server_specifics = entry.Get(syncable::SERVER_SPECIFICS); const sync_pb::EntitySpecifics& base_server_specifics = entry.Get(syncable::BASE_SERVER_SPECIFICS); std::string decrypted_specifics, decrypted_server_specifics; bool specifics_match = false; bool server_encrypted_with_default_key = false; if (specifics.has_encrypted()) { DCHECK(cryptographer->CanDecryptUsingDefaultKey(specifics.encrypted())); decrypted_specifics = cryptographer->DecryptToString( specifics.encrypted()); } else { decrypted_specifics = specifics.SerializeAsString(); } if (server_specifics.has_encrypted()) { server_encrypted_with_default_key = cryptographer->CanDecryptUsingDefaultKey( server_specifics.encrypted()); decrypted_server_specifics = cryptographer->DecryptToString( server_specifics.encrypted()); } else { decrypted_server_specifics = server_specifics.SerializeAsString(); } if (decrypted_server_specifics == decrypted_specifics && server_encrypted_with_default_key == specifics.has_encrypted()) { specifics_match = true; } bool base_server_specifics_match = false; if (server_specifics.has_encrypted() && IsRealDataType(GetModelTypeFromSpecifics(base_server_specifics))) { std::string decrypted_base_server_specifics; if (!base_server_specifics.has_encrypted()) { decrypted_base_server_specifics = base_server_specifics.SerializeAsString(); } else { decrypted_base_server_specifics = cryptographer->DecryptToString( base_server_specifics.encrypted()); } if (decrypted_server_specifics == decrypted_base_server_specifics) base_server_specifics_match = true; } if (entry.GetModelType() == syncable::NIGORI) { sync_pb::EntitySpecifics specifics = entry.Get(syncable::SERVER_SPECIFICS); sync_pb::NigoriSpecifics* server_nigori = specifics.mutable_nigori(); cryptographer->UpdateNigoriFromEncryptedTypes(server_nigori); if (cryptographer->is_ready()) { cryptographer->GetKeys(server_nigori->mutable_encrypted()); server_nigori->set_using_explicit_passphrase( entry.Get(syncable::SPECIFICS).nigori(). using_explicit_passphrase()); } if (entry.Get(syncable::SPECIFICS).nigori().sync_tabs()) { server_nigori->set_sync_tabs(true); } entry.Put(syncable::SPECIFICS, specifics); DVLOG(1) << "Resolving simple conflict, merging nigori nodes: " << entry; status->increment_num_server_overwrites(); OverwriteServerChanges(trans, &entry); UMA_HISTOGRAM_ENUMERATION("Sync.ResolveSimpleConflict", NIGORI_MERGE, CONFLICT_RESOLUTION_SIZE); } else if (!entry_deleted && name_matches && parent_matches && specifics_match && !needs_reinsertion) { DVLOG(1) << "Resolving simple conflict, everything matches, ignoring " << "changes for: " << entry; OverwriteServerChanges(trans, &entry); IgnoreLocalChanges(&entry); UMA_HISTOGRAM_ENUMERATION("Sync.ResolveSimpleConflict", CHANGES_MATCH, CONFLICT_RESOLUTION_SIZE); } else if (base_server_specifics_match) { DVLOG(1) << "Resolving simple conflict, ignoring server encryption " << " changes for: " << entry; status->increment_num_server_overwrites(); OverwriteServerChanges(trans, &entry); UMA_HISTOGRAM_ENUMERATION("Sync.ResolveSimpleConflict", IGNORE_ENCRYPTION, CONFLICT_RESOLUTION_SIZE); } else if (entry_deleted || !name_matches || !parent_matches) { OverwriteServerChanges(trans, &entry); status->increment_num_server_overwrites(); DVLOG(1) << "Resolving simple conflict, overwriting server changes " << "for: " << entry; UMA_HISTOGRAM_ENUMERATION("Sync.ResolveSimpleConflict", OVERWRITE_SERVER, CONFLICT_RESOLUTION_SIZE); } else { DVLOG(1) << "Resolving simple conflict, ignoring local changes for: " << entry; IgnoreLocalChanges(&entry); status->increment_num_local_overwrites(); UMA_HISTOGRAM_ENUMERATION("Sync.ResolveSimpleConflict", OVERWRITE_LOCAL, CONFLICT_RESOLUTION_SIZE); } entry.Put(syncable::BASE_SERVER_SPECIFICS, sync_pb::EntitySpecifics()); return SYNC_PROGRESS; } else { // SERVER_IS_DEL is true if (entry.Get(syncable::IS_DIR)) { Directory::ChildHandles children; trans->directory()->GetChildHandlesById(trans, entry.Get(syncable::ID), &children); if (0 != children.size()) { DVLOG(1) << "Entry is a server deleted directory with local contents, " << "should be a hierarchy conflict. (race condition)."; return NO_SYNC_PROGRESS; } } if (!entry.Get(syncable::UNIQUE_CLIENT_TAG).empty()) { DCHECK_EQ(entry.Get(syncable::SERVER_VERSION), 0) << "For the server to " "know to re-create, client-tagged items should revert to version 0 " "when server-deleted."; OverwriteServerChanges(trans, &entry); status->increment_num_server_overwrites(); DVLOG(1) << "Resolving simple conflict, undeleting server entry: " << entry; UMA_HISTOGRAM_ENUMERATION("Sync.ResolveSimpleConflict", OVERWRITE_SERVER, CONFLICT_RESOLUTION_SIZE); entry.Put(syncable::SERVER_VERSION, 0); entry.Put(syncable::BASE_VERSION, 0); } else { SyncerUtil::SplitServerInformationIntoNewEntry(trans, &entry); MutableEntry server_update(trans, syncable::GET_BY_ID, id); CHECK(server_update.good()); CHECK(server_update.Get(syncable::META_HANDLE) != entry.Get(syncable::META_HANDLE)) << server_update << entry; UMA_HISTOGRAM_ENUMERATION("Sync.ResolveSimpleConflict", UNDELETE, CONFLICT_RESOLUTION_SIZE); } return SYNC_PROGRESS; } } Commit Message: [Sync] Cleanup all tab sync enabling logic now that its on by default. BUG=none TEST= Review URL: https://chromiumcodereview.appspot.com/10443046 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@139462 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-362 Target: 1 Example 2: Code: void ResourceDispatcherHostImpl::DidFinishLoading(ResourceLoader* loader) { ResourceRequestInfoImpl* info = loader->GetRequestInfo(); if (delegate_) delegate_->RequestComplete(loader->request()); RemovePendingRequest(info->GetChildID(), info->GetRequestID()); } Commit Message: When turning a download into a navigation, navigate the right frame Code changes from Nate Chapin <[email protected]> Bug: 926105 Change-Id: I098599394e6ebe7d2fce5af838014297a337d294 Reviewed-on: https://chromium-review.googlesource.com/c/1454962 Reviewed-by: Camille Lamy <[email protected]> Commit-Queue: Jochen Eisinger <[email protected]> Cr-Commit-Position: refs/heads/master@{#629547} CWE ID: CWE-284 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int oz_usb_vendor_class_req(void *hpd, u8 req_id, u8 req_type, u8 request, __le16 value, __le16 index, const u8 *data, int data_len) { struct oz_usb_ctx *usb_ctx = hpd; struct oz_pd *pd = usb_ctx->pd; struct oz_elt *elt; struct oz_elt_buf *eb = &pd->elt_buff; struct oz_elt_info *ei = oz_elt_info_alloc(&pd->elt_buff); struct oz_vendor_class_req *body; if (ei == NULL) return -1; elt = (struct oz_elt *)ei->data; elt->length = sizeof(struct oz_vendor_class_req) - 1 + data_len; body = (struct oz_vendor_class_req *)(elt+1); body->type = OZ_VENDOR_CLASS_REQ; body->req_id = req_id; body->req_type = req_type; body->request = request; put_unaligned(value, &body->value); put_unaligned(index, &body->index); if (data_len) memcpy(body->data, data, data_len); return oz_usb_submit_elt(eb, ei, usb_ctx, 0, 0); } Commit Message: ozwpan: divide-by-zero leading to panic A network supplied parameter was not checked before division, leading to a divide-by-zero. Since this happens in the softirq path, it leads to a crash. A PoC follows below, which requires the ozprotocol.h file from this module. =-=-=-=-=-= #include <arpa/inet.h> #include <linux/if_packet.h> #include <net/if.h> #include <netinet/ether.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <endian.h> #include <sys/ioctl.h> #include <sys/socket.h> #define u8 uint8_t #define u16 uint16_t #define u32 uint32_t #define __packed __attribute__((__packed__)) #include "ozprotocol.h" static int hex2num(char c) { if (c >= '0' && c <= '9') return c - '0'; if (c >= 'a' && c <= 'f') return c - 'a' + 10; if (c >= 'A' && c <= 'F') return c - 'A' + 10; return -1; } static int hwaddr_aton(const char *txt, uint8_t *addr) { int i; for (i = 0; i < 6; i++) { int a, b; a = hex2num(*txt++); if (a < 0) return -1; b = hex2num(*txt++); if (b < 0) return -1; *addr++ = (a << 4) | b; if (i < 5 && *txt++ != ':') return -1; } return 0; } int main(int argc, char *argv[]) { if (argc < 3) { fprintf(stderr, "Usage: %s interface destination_mac\n", argv[0]); return 1; } uint8_t dest_mac[6]; if (hwaddr_aton(argv[2], dest_mac)) { fprintf(stderr, "Invalid mac address.\n"); return 1; } int sockfd = socket(AF_PACKET, SOCK_RAW, IPPROTO_RAW); if (sockfd < 0) { perror("socket"); return 1; } struct ifreq if_idx; int interface_index; strncpy(if_idx.ifr_ifrn.ifrn_name, argv[1], IFNAMSIZ - 1); if (ioctl(sockfd, SIOCGIFINDEX, &if_idx) < 0) { perror("SIOCGIFINDEX"); return 1; } interface_index = if_idx.ifr_ifindex; if (ioctl(sockfd, SIOCGIFHWADDR, &if_idx) < 0) { perror("SIOCGIFHWADDR"); return 1; } uint8_t *src_mac = (uint8_t *)&if_idx.ifr_hwaddr.sa_data; struct { struct ether_header ether_header; struct oz_hdr oz_hdr; struct oz_elt oz_elt; struct oz_elt_connect_req oz_elt_connect_req; struct oz_elt oz_elt2; struct oz_multiple_fixed oz_multiple_fixed; } __packed packet = { .ether_header = { .ether_type = htons(OZ_ETHERTYPE), .ether_shost = { src_mac[0], src_mac[1], src_mac[2], src_mac[3], src_mac[4], src_mac[5] }, .ether_dhost = { dest_mac[0], dest_mac[1], dest_mac[2], dest_mac[3], dest_mac[4], dest_mac[5] } }, .oz_hdr = { .control = OZ_F_ACK_REQUESTED | (OZ_PROTOCOL_VERSION << OZ_VERSION_SHIFT), .last_pkt_num = 0, .pkt_num = htole32(0) }, .oz_elt = { .type = OZ_ELT_CONNECT_REQ, .length = sizeof(struct oz_elt_connect_req) }, .oz_elt_connect_req = { .mode = 0, .resv1 = {0}, .pd_info = 0, .session_id = 0, .presleep = 0, .ms_isoc_latency = 0, .host_vendor = 0, .keep_alive = 0, .apps = htole16((1 << OZ_APPID_USB) | 0x1), .max_len_div16 = 0, .ms_per_isoc = 0, .up_audio_buf = 0, .ms_per_elt = 0 }, .oz_elt2 = { .type = OZ_ELT_APP_DATA, .length = sizeof(struct oz_multiple_fixed) }, .oz_multiple_fixed = { .app_id = OZ_APPID_USB, .elt_seq_num = 0, .type = OZ_USB_ENDPOINT_DATA, .endpoint = 0, .format = OZ_DATA_F_MULTIPLE_FIXED, .unit_size = 0, .data = {0} } }; struct sockaddr_ll socket_address = { .sll_ifindex = interface_index, .sll_halen = ETH_ALEN, .sll_addr = { dest_mac[0], dest_mac[1], dest_mac[2], dest_mac[3], dest_mac[4], dest_mac[5] } }; if (sendto(sockfd, &packet, sizeof(packet), 0, (struct sockaddr *)&socket_address, sizeof(socket_address)) < 0) { perror("sendto"); return 1; } return 0; } Signed-off-by: Jason A. Donenfeld <[email protected]> Acked-by: Dan Carpenter <[email protected]> Cc: stable <[email protected]> Signed-off-by: Greg Kroah-Hartman <[email protected]> CWE ID: CWE-189 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void rng_backend_request_entropy(RngBackend *s, size_t size, EntropyReceiveFunc *receive_entropy, void *opaque) { RngBackendClass *k = RNG_BACKEND_GET_CLASS(s); if (k->request_entropy) { k->request_entropy(s, size, receive_entropy, opaque); } } Commit Message: CWE ID: CWE-119 Target: 1 Example 2: Code: int curl_msnprintf(char *buffer, size_t maxlength, const char *format, ...) { int retcode; va_list ap_save; /* argument pointer */ va_start(ap_save, format); retcode = curl_mvsnprintf(buffer, maxlength, format, ap_save); va_end(ap_save); return retcode; } Commit Message: printf: fix floating point buffer overflow issues ... and add a bunch of floating point printf tests CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void BackTexture::Copy() { DCHECK_NE(id(), 0u); ScopedGLErrorSuppressor suppressor("BackTexture::Copy", decoder_->state_.GetErrorState()); ScopedTextureBinder binder(&decoder_->state_, id(), Target()); api()->glCopyTexSubImage2DFn(Target(), 0, // level 0, 0, 0, 0, size_.width(), size_.height()); } Commit Message: Implement immutable texture base/max level clamping It seems some drivers fail to handle that gracefully, so let's always clamp to be on the safe side. BUG=877874 TEST=test case in the bug, gpu_unittests [email protected] Cq-Include-Trybots: luci.chromium.try:android_optional_gpu_tests_rel;luci.chromium.try:linux_optional_gpu_tests_rel;luci.chromium.try:mac_optional_gpu_tests_rel;luci.chromium.try:win_optional_gpu_tests_rel Change-Id: I6d93cb9389ea70525df4604112223604577582a2 Reviewed-on: https://chromium-review.googlesource.com/1194994 Reviewed-by: Kenneth Russell <[email protected]> Commit-Queue: Zhenyao Mo <[email protected]> Cr-Commit-Position: refs/heads/master@{#587264} CWE ID: CWE-119 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: read_callback(png_structp pp, png_unknown_chunkp pc) { /* This function mimics the behavior of png_set_keep_unknown_chunks by * returning '0' to keep the chunk and '1' to discard it. */ display *d = voidcast(display*, png_get_user_chunk_ptr(pp)); int chunk = findb(pc->name); int keep, discard; if (chunk < 0) /* not one in our list, so not a known chunk */ keep = d->keep; else { keep = chunk_info[chunk].keep; if (keep == PNG_HANDLE_CHUNK_AS_DEFAULT) { /* See the comments in png.h - use the default for unknown chunks, * do not keep known chunks. */ if (chunk_info[chunk].unknown) keep = d->keep; else keep = PNG_HANDLE_CHUNK_NEVER; } } switch (keep) { default: fprintf(stderr, "%s(%s): %d: unrecognized chunk option\n", d->file, d->test, chunk_info[chunk].keep); display_exit(d); case PNG_HANDLE_CHUNK_AS_DEFAULT: case PNG_HANDLE_CHUNK_NEVER: discard = 1/*handled; discard*/; break; case PNG_HANDLE_CHUNK_IF_SAFE: case PNG_HANDLE_CHUNK_ALWAYS: discard = 0/*not handled; keep*/; break; } /* Also store information about this chunk in the display, the relevant flag * is set if the chunk is to be kept ('not handled'.) */ if (chunk >= 0) if (!discard) /* stupidity to stop a GCC warning */ { png_uint_32 flag = chunk_info[chunk].flag; if (pc->location & PNG_AFTER_IDAT) d->after_IDAT |= flag; else d->before_IDAT |= flag; } /* However if there is no support to store unknown chunks don't ask libpng to * do it; there will be an png_error. */ # ifdef PNG_STORE_UNKNOWN_CHUNKS_SUPPORTED return discard; # else return 1; /*handled; discard*/ # endif } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID: Target: 1 Example 2: Code: void btif_hh_disconnect(bt_bdaddr_t *bd_addr) { btif_hh_device_t *p_dev; p_dev = btif_hh_find_connected_dev_by_bda(bd_addr); if (p_dev != NULL) { BTA_HhClose(p_dev->dev_handle); } else BTIF_TRACE_DEBUG("%s-- Error: device not connected:",__FUNCTION__); } 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 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void BluetoothDeviceChromeOS::OnRegisterAgentError( const ConnectErrorCallback& error_callback, const std::string& error_name, const std::string& error_message) { if (--num_connecting_calls_ == 0) adapter_->NotifyDeviceChanged(this); DCHECK(num_connecting_calls_ >= 0); LOG(WARNING) << object_path_.value() << ": Failed to register agent: " << error_name << ": " << error_message; VLOG(1) << object_path_.value() << ": " << num_connecting_calls_ << " still in progress"; UnregisterAgent(); ConnectErrorCode error_code = ERROR_UNKNOWN; if (error_name == bluetooth_agent_manager::kErrorAlreadyExists) error_code = ERROR_INPROGRESS; RecordPairingResult(error_code); error_callback.Run(error_code); } Commit Message: Refactor to support default Bluetooth pairing delegate In order to support a default pairing delegate we need to move the agent service provider delegate implementation from BluetoothDevice to BluetoothAdapter while retaining the existing API. BUG=338492 TEST=device_unittests, unit_tests, browser_tests Review URL: https://codereview.chromium.org/148293003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@252216 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: virtual InputMethodDescriptors* GetActiveInputMethods() { return GetInputMethodDescriptorsForTesting(); } 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 Target: 1 Example 2: Code: void InlineSigninHelper::OnClientOAuthFailure( const GoogleServiceAuthError& error) { if (handler_) handler_->HandleLoginError(error.ToString(), base::string16()); AboutSigninInternals* about_signin_internals = AboutSigninInternalsFactory::GetForProfile(profile_); about_signin_internals->OnRefreshTokenReceived("Failure"); base::ThreadTaskRunnerHandle::Get()->DeleteSoon(FROM_HERE, this); } Commit Message: [signin] Add metrics to track the source for refresh token updated events This CL add a source for update and revoke credentials operations. It then surfaces the source in the chrome://signin-internals page. This CL also records the following histograms that track refresh token events: * Signin.RefreshTokenUpdated.ToValidToken.Source * Signin.RefreshTokenUpdated.ToInvalidToken.Source * Signin.RefreshTokenRevoked.Source These histograms are needed to validate the assumptions of how often tokens are revoked by the browser and the sources for the token revocations. Bug: 896182 Change-Id: I2fcab80ee8e5699708e695bc3289fa6d34859a90 Reviewed-on: https://chromium-review.googlesource.com/c/1286464 Reviewed-by: Jochen Eisinger <[email protected]> Reviewed-by: David Roger <[email protected]> Reviewed-by: Ilya Sherman <[email protected]> Commit-Queue: Mihai Sardarescu <[email protected]> Cr-Commit-Position: refs/heads/master@{#606181} CWE ID: CWE-20 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: ConfirmInfoBar::ConfirmInfoBar(std::unique_ptr<ConfirmInfoBarDelegate> delegate) : InfoBarView(std::move(delegate)) { auto* delegate_ptr = GetDelegate(); label_ = CreateLabel(delegate_ptr->GetMessageText()); AddChildView(label_); const auto buttons = delegate_ptr->GetButtons(); if (buttons & ConfirmInfoBarDelegate::BUTTON_OK) { ok_button_ = CreateButton(ConfirmInfoBarDelegate::BUTTON_OK); ok_button_->SetProminent(true); if (delegate_ptr->OKButtonTriggersUACPrompt()) { elevation_icon_setter_.reset(new ElevationIconSetter( ok_button_, base::BindOnce(&ConfirmInfoBar::Layout, base::Unretained(this)))); } } if (buttons & ConfirmInfoBarDelegate::BUTTON_CANCEL) { cancel_button_ = CreateButton(ConfirmInfoBarDelegate::BUTTON_CANCEL); if (buttons == ConfirmInfoBarDelegate::BUTTON_CANCEL) cancel_button_->SetProminent(true); } link_ = CreateLink(delegate_ptr->GetLinkText(), this); AddChildView(link_); } Commit Message: Allow to specify elide behavior for confrim infobar message Used in "<extension name> is debugging this browser" infobar. Bug: 823194 Change-Id: Iff6627097c020cccca8f7cc3e21a803a41fd8f2c Reviewed-on: https://chromium-review.googlesource.com/1048064 Commit-Queue: Dmitry Gozman <[email protected]> Reviewed-by: Devlin <[email protected]> Reviewed-by: Peter Kasting <[email protected]> Cr-Commit-Position: refs/heads/master@{#557245} CWE ID: CWE-254 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: long long Segment::CreateInstance( IMkvReader* pReader, long long pos, Segment*& pSegment) { assert(pReader); assert(pos >= 0); pSegment = NULL; long long total, available; const long status = pReader->Length(&total, &available); if (status < 0) //error return status; if (available < 0) return -1; if ((total >= 0) && (available > total)) return -1; for (;;) { if ((total >= 0) && (pos >= total)) return E_FILE_FORMAT_INVALID; long len; long long result = GetUIntLength(pReader, pos, len); if (result) //error, or too few available bytes return result; if ((total >= 0) && ((pos + len) > total)) return E_FILE_FORMAT_INVALID; if ((pos + len) > available) return pos + len; const long long idpos = pos; const long long id = ReadUInt(pReader, pos, len); if (id < 0) //error return id; pos += len; //consume ID result = GetUIntLength(pReader, pos, len); if (result) //error, or too few available bytes return result; if ((total >= 0) && ((pos + len) > total)) return E_FILE_FORMAT_INVALID; if ((pos + len) > available) return pos + len; long long size = ReadUInt(pReader, pos, len); if (size < 0) //error return size; pos += len; //consume length of size of element const long long unknown_size = (1LL << (7 * len)) - 1; if (id == 0x08538067) //Segment ID { if (size == unknown_size) size = -1; else if (total < 0) size = -1; else if ((pos + size) > total) size = -1; pSegment = new (std::nothrow) Segment( pReader, idpos, pos, size); if (pSegment == 0) return -1; //generic error return 0; //success } if (size == unknown_size) return E_FILE_FORMAT_INVALID; if ((total >= 0) && ((pos + size) > total)) return E_FILE_FORMAT_INVALID; if ((pos + size) > available) return pos + size; pos += size; //consume payload } } 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 Target: 1 Example 2: Code: void ServiceWorkerHandler::OnErrorReported( int64_t registration_id, int64_t version_id, const ServiceWorkerContextCoreObserver::ErrorInfo& info) { frontend_->WorkerErrorReported( ServiceWorker::ServiceWorkerErrorMessage::Create() .SetErrorMessage(base::UTF16ToUTF8(info.error_message)) .SetRegistrationId(base::Int64ToString(registration_id)) .SetVersionId(base::Int64ToString(version_id)) .SetSourceURL(info.source_url.spec()) .SetLineNumber(info.line_number) .SetColumnNumber(info.column_number) .Build()); } 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 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void LocalFileSystem::fileSystemAllowedInternal( PassRefPtrWillBeRawPtr<ExecutionContext> context, FileSystemType type, PassRefPtr<CallbackWrapper> callbacks) { if (!fileSystem()) { fileSystemNotAvailable(context, callbacks); return; } KURL storagePartition = KURL(KURL(), context->securityOrigin()->toString()); fileSystem()->openFileSystem(storagePartition, static_cast<WebFileSystemType>(type), callbacks->release()); } Commit Message: Oilpan: Ship Oilpan for SyncCallbackHelper, CreateFileResult and CallbackWrapper in filesystem/ These are leftovers when we shipped Oilpan for filesystem/ once. BUG=340522 Review URL: https://codereview.chromium.org/501263003 git-svn-id: svn://svn.chromium.org/blink/trunk@180909 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static ext4_io_end_t *ext4_init_io_end (struct inode *inode) { ext4_io_end_t *io = NULL; io = kmalloc(sizeof(*io), GFP_NOFS); if (io) { igrab(inode); io->inode = inode; io->flag = 0; io->offset = 0; io->size = 0; io->error = 0; INIT_WORK(&io->work, ext4_end_io_work); INIT_LIST_HEAD(&io->list); } return io; } Commit Message: ext4: use ext4_get_block_write in buffer write Allocate uninitialized extent before ext4 buffer write and convert the extent to initialized after io completes. The purpose is to make sure an extent can only be marked initialized after it has been written with new data so we can safely drop the i_mutex lock in ext4 DIO read without exposing stale data. This helps to improve multi-thread DIO read performance on high-speed disks. Skip the nobh and data=journal mount cases to make things simple for now. Signed-off-by: Jiaying Zhang <[email protected]> Signed-off-by: "Theodore Ts'o" <[email protected]> CWE ID: Target: 1 Example 2: Code: zip_read_mac_metadata(struct archive_read *a, struct archive_entry *entry, struct zip_entry *rsrc) { struct zip *zip = (struct zip *)a->format->data; unsigned char *metadata, *mp; int64_t offset = archive_filter_bytes(&a->archive, 0); size_t remaining_bytes, metadata_bytes; ssize_t hsize; int ret = ARCHIVE_OK, eof; switch(rsrc->compression) { case 0: /* No compression. */ if (rsrc->uncompressed_size != rsrc->compressed_size) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Malformed OS X metadata entry: inconsistent size"); return (ARCHIVE_FATAL); } #ifdef HAVE_ZLIB_H case 8: /* Deflate compression. */ #endif break; default: /* Unsupported compression. */ /* Return a warning. */ archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Unsupported ZIP compression method (%s)", compression_name(rsrc->compression)); /* We can't decompress this entry, but we will * be able to skip() it and try the next entry. */ return (ARCHIVE_WARN); } if (rsrc->uncompressed_size > (4 * 1024 * 1024)) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Mac metadata is too large: %jd > 4M bytes", (intmax_t)rsrc->uncompressed_size); return (ARCHIVE_WARN); } if (rsrc->compressed_size > (4 * 1024 * 1024)) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Mac metadata is too large: %jd > 4M bytes", (intmax_t)rsrc->compressed_size); return (ARCHIVE_WARN); } metadata = malloc((size_t)rsrc->uncompressed_size); if (metadata == NULL) { archive_set_error(&a->archive, ENOMEM, "Can't allocate memory for Mac metadata"); return (ARCHIVE_FATAL); } if (offset < rsrc->local_header_offset) __archive_read_consume(a, rsrc->local_header_offset - offset); else if (offset != rsrc->local_header_offset) { __archive_read_seek(a, rsrc->local_header_offset, SEEK_SET); } hsize = zip_get_local_file_header_size(a, 0); __archive_read_consume(a, hsize); remaining_bytes = (size_t)rsrc->compressed_size; metadata_bytes = (size_t)rsrc->uncompressed_size; mp = metadata; eof = 0; while (!eof && remaining_bytes) { const unsigned char *p; ssize_t bytes_avail; size_t bytes_used; p = __archive_read_ahead(a, 1, &bytes_avail); if (p == NULL) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Truncated ZIP file header"); ret = ARCHIVE_WARN; goto exit_mac_metadata; } if ((size_t)bytes_avail > remaining_bytes) bytes_avail = remaining_bytes; switch(rsrc->compression) { case 0: /* No compression. */ if ((size_t)bytes_avail > metadata_bytes) bytes_avail = metadata_bytes; memcpy(mp, p, bytes_avail); bytes_used = (size_t)bytes_avail; metadata_bytes -= bytes_used; mp += bytes_used; if (metadata_bytes == 0) eof = 1; break; #ifdef HAVE_ZLIB_H case 8: /* Deflate compression. */ { int r; ret = zip_deflate_init(a, zip); if (ret != ARCHIVE_OK) goto exit_mac_metadata; zip->stream.next_in = (Bytef *)(uintptr_t)(const void *)p; zip->stream.avail_in = (uInt)bytes_avail; zip->stream.total_in = 0; zip->stream.next_out = mp; zip->stream.avail_out = (uInt)metadata_bytes; zip->stream.total_out = 0; r = inflate(&zip->stream, 0); switch (r) { case Z_OK: break; case Z_STREAM_END: eof = 1; break; case Z_MEM_ERROR: archive_set_error(&a->archive, ENOMEM, "Out of memory for ZIP decompression"); ret = ARCHIVE_FATAL; goto exit_mac_metadata; default: archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "ZIP decompression failed (%d)", r); ret = ARCHIVE_FATAL; goto exit_mac_metadata; } bytes_used = zip->stream.total_in; metadata_bytes -= zip->stream.total_out; mp += zip->stream.total_out; break; } #endif default: bytes_used = 0; break; } __archive_read_consume(a, bytes_used); remaining_bytes -= bytes_used; } archive_entry_copy_mac_metadata(entry, metadata, (size_t)rsrc->uncompressed_size - metadata_bytes); exit_mac_metadata: __archive_read_seek(a, offset, SEEK_SET); zip->decompress_init = 0; free(metadata); return (ret); } Commit Message: Fix typo in preprocessor macro in archive_read_format_zip_cleanup() Frees lzma_stream on cleanup() Fixes #1165 CWE ID: CWE-399 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: bool ReceiverWasAdded(const RtpTransceiverState& transceiver_state) { uintptr_t receiver_id = RTCRtpReceiver::getId( transceiver_state.receiver_state()->webrtc_receiver().get()); for (const auto& receiver : handler_->rtp_receivers_) { if (receiver->Id() == receiver_id) return false; } return true; } Commit Message: Check weak pointers in RTCPeerConnectionHandler::WebRtcSetDescriptionObserverImpl Bug: 912074 Change-Id: I8ba86751f5d5bf12db51520f985ef0d3dae63ed8 Reviewed-on: https://chromium-review.googlesource.com/c/1411916 Commit-Queue: Guido Urdaneta <[email protected]> Reviewed-by: Henrik Boström <[email protected]> Cr-Commit-Position: refs/heads/master@{#622945} CWE ID: CWE-416 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void CCLayerTreeHostTest::endTest() { if (!isMainThread()) CCMainThread::postTask(createMainThreadTask(this, &CCLayerTreeHostTest::endTest)); else { if (m_beginning) m_endWhenBeginReturns = true; else onEndTest(static_cast<void*>(this)); } } Commit Message: [chromium] Fix shutdown race when posting main thread task to CCThreadProxy and enable tests https://bugs.webkit.org/show_bug.cgi?id=70161 Reviewed by David Levin. Source/WebCore: Adds a weak pointer mechanism to cancel main thread tasks posted to CCThreadProxy instances from the compositor thread. Previously there was a race condition where main thread tasks could run even after the CCThreadProxy was destroyed. This race does not exist in the other direction because when tearing down a CCThreadProxy we first post a quit task to the compositor thread and then suspend execution of the main thread until all compositor tasks for the CCThreadProxy have been drained. Covered by the now-enabled CCLayerTreeHostTest* unit tests. * WebCore.gypi: * platform/graphics/chromium/cc/CCScopedMainThreadProxy.h: Added. (WebCore::CCScopedMainThreadProxy::create): (WebCore::CCScopedMainThreadProxy::postTask): (WebCore::CCScopedMainThreadProxy::shutdown): (WebCore::CCScopedMainThreadProxy::CCScopedMainThreadProxy): (WebCore::CCScopedMainThreadProxy::runTaskIfNotShutdown): * platform/graphics/chromium/cc/CCThreadProxy.cpp: (WebCore::CCThreadProxy::CCThreadProxy): (WebCore::CCThreadProxy::~CCThreadProxy): (WebCore::CCThreadProxy::createBeginFrameAndCommitTaskOnCCThread): * platform/graphics/chromium/cc/CCThreadProxy.h: Source/WebKit/chromium: Enables the CCLayerTreeHostTest* tests by default. Most tests are run twice in a single thread and multiple thread configuration. Some tests run only in the multiple thread configuration if they depend on the compositor thread scheduling draws by itself. * tests/CCLayerTreeHostTest.cpp: (::CCLayerTreeHostTest::timeout): (::CCLayerTreeHostTest::clearTimeout): (::CCLayerTreeHostTest::CCLayerTreeHostTest): (::CCLayerTreeHostTest::onEndTest): (::CCLayerTreeHostTest::TimeoutTask::TimeoutTask): (::CCLayerTreeHostTest::TimeoutTask::clearTest): (::CCLayerTreeHostTest::TimeoutTask::~TimeoutTask): (::CCLayerTreeHostTest::TimeoutTask::Run): (::CCLayerTreeHostTest::runTest): (::CCLayerTreeHostTest::doBeginTest): (::CCLayerTreeHostTestThreadOnly::runTest): (::CCLayerTreeHostTestSetNeedsRedraw::commitCompleteOnCCThread): git-svn-id: svn://svn.chromium.org/blink/trunk@97784 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-119 Target: 1 Example 2: Code: static ResourceLoadPriority loadPriority(Resource::Type type, const FetchRequest& request) { if (request.priority() != ResourceLoadPriorityUnresolved) return request.priority(); switch (type) { case Resource::MainResource: return ResourceLoadPriorityVeryHigh; case Resource::CSSStyleSheet: return ResourceLoadPriorityHigh; case Resource::Raw: return request.options().synchronousPolicy == RequestSynchronously ? ResourceLoadPriorityVeryHigh : ResourceLoadPriorityMedium; case Resource::Script: case Resource::Font: case Resource::ImportResource: return ResourceLoadPriorityMedium; case Resource::Image: return ResourceLoadPriorityVeryLow; case Resource::Media: return ResourceLoadPriorityLow; case Resource::XSLStyleSheet: ASSERT(RuntimeEnabledFeatures::xsltEnabled()); return ResourceLoadPriorityHigh; case Resource::SVGDocument: return ResourceLoadPriorityLow; case Resource::LinkPrefetch: return ResourceLoadPriorityVeryLow; case Resource::LinkSubresource: return ResourceLoadPriorityLow; case Resource::TextTrack: return ResourceLoadPriorityLow; } ASSERT_NOT_REACHED(); return ResourceLoadPriorityUnresolved; } Commit Message: Enforce SVG image security rules SVG images have unique security rules that prevent them from loading any external resources. This patch enforces these rules in ResourceFetcher::canRequest for all non-data-uri resources. This locks down our SVG resource handling and fixes two security bugs. In the case of SVG images that reference other images, we had a bug where a cached subresource would be used directly from the cache. This has been fixed because the canRequest check occurs before we use cached resources. In the case of SVG images that use CSS imports, we had a bug where imports were blindly requested. This has been fixed by stopping all non-data-uri requests in SVG images. With this patch we now match Gecko's behavior on both testcases. BUG=380885, 382296 Review URL: https://codereview.chromium.org/320763002 git-svn-id: svn://svn.chromium.org/blink/trunk@176084 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-264 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: _PUBLIC_ codepoint_t next_codepoint_handle_ext( struct smb_iconv_handle *ic, const char *str, size_t len, charset_t src_charset, size_t *bytes_consumed) { /* it cannot occupy more than 4 bytes in UTF16 format */ uint8_t buf[4]; smb_iconv_t descriptor; size_t ilen_orig; size_t ilen; size_t olen; char *outbuf; if ((str[0] & 0x80) == 0) { *bytes_consumed = 1; return (codepoint_t)str[0]; } * This is OK as we only support codepoints up to 1M (U+100000) */ ilen_orig = MIN(len, 5); ilen = ilen_orig; descriptor = get_conv_handle(ic, src_charset, CH_UTF16); if (descriptor == (smb_iconv_t)-1) { *bytes_consumed = 1; return INVALID_CODEPOINT; } /* * this looks a little strange, but it is needed to cope with * codepoints above 64k (U+1000) which are encoded as per RFC2781. */ olen = 2; outbuf = (char *)buf; smb_iconv(descriptor, &str, &ilen, &outbuf, &olen); if (olen == 2) { olen = 4; outbuf = (char *)buf; smb_iconv(descriptor, &str, &ilen, &outbuf, &olen); if (olen == 4) { /* we didn't convert any bytes */ *bytes_consumed = 1; return INVALID_CODEPOINT; } olen = 4 - olen; } else { olen = 2 - olen; } *bytes_consumed = ilen_orig - ilen; if (olen == 2) { return (codepoint_t)SVAL(buf, 0); } if (olen == 4) { /* decode a 4 byte UTF16 character manually */ return (codepoint_t)0x10000 + (buf[2] | ((buf[3] & 0x3)<<8) | (buf[0]<<10) | ((buf[1] & 0x3)<<18)); } /* no other length is valid */ return INVALID_CODEPOINT; } Commit Message: CWE ID: CWE-200 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static void llc_sap_rcv(struct llc_sap *sap, struct sk_buff *skb, struct sock *sk) { struct llc_sap_state_ev *ev = llc_sap_ev(skb); ev->type = LLC_SAP_EV_TYPE_PDU; ev->reason = 0; skb->sk = sk; llc_sap_state_process(sap, skb); } Commit Message: net/llc: avoid BUG_ON() in skb_orphan() It seems nobody used LLC since linux-3.12. Fortunately fuzzers like syzkaller still know how to run this code, otherwise it would be no fun. Setting skb->sk without skb->destructor leads to all kinds of bugs, we now prefer to be very strict about it. Ideally here we would use skb_set_owner() but this helper does not exist yet, only CAN seems to have a private helper for that. Fixes: 376c7311bdb6 ("net: add a temporary sanity check in skb_orphan()") Signed-off-by: Eric Dumazet <[email protected]> Reported-by: Andrey Konovalov <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-20 Target: 1 Example 2: Code: void AppListSyncableService::UpdateAppItemFromSyncItem( const AppListSyncableService::SyncItem* sync_item, AppListItem* app_item) { VLOG(2) << this << " UpdateAppItemFromSyncItem: " << sync_item->ToString(); if (!app_item->position().Equals(sync_item->item_ordinal)) model_->SetItemPosition(app_item, sync_item->item_ordinal); if (sync_item->item_name != app_item->name() && sync_item->item_id != kOemFolderId && (app_item->GetItemType() == AppListFolderItem::kItemType || app_item->name().empty())) { model_->SetItemName(app_item, sync_item->item_name); } } Commit Message: [Extensions] Add GetInstalledExtension() method to ExtensionRegistry This CL adds GetInstalledExtension() method to ExtensionRegistry and uses it instead of deprecated ExtensionService::GetInstalledExtension() in chrome/browser/ui/app_list/. Part of removing the deprecated GetInstalledExtension() call from the ExtensionService. BUG=489687 Review URL: https://codereview.chromium.org/1130353010 Cr-Commit-Position: refs/heads/master@{#333036} CWE ID: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: hb_buffer_create (unsigned int pre_alloc_size) { hb_buffer_t *buffer; if (!HB_OBJECT_DO_CREATE (hb_buffer_t, buffer)) return &_hb_buffer_nil; if (pre_alloc_size) hb_buffer_ensure(buffer, pre_alloc_size); buffer->unicode = &_hb_unicode_funcs_nil; return buffer; } Commit Message: CWE ID: Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static BOOL nsc_context_initialize_encode(NSC_CONTEXT* context) { int i; UINT32 length; UINT32 tempWidth; UINT32 tempHeight; tempWidth = ROUND_UP_TO(context->width, 8); tempHeight = ROUND_UP_TO(context->height, 2); /* The maximum length a decoded plane can reach in all cases */ length = tempWidth * tempHeight + 16; if (length > context->priv->PlaneBuffersLength) { for (i = 0; i < 5; i++) { BYTE* tmp = (BYTE*) realloc(context->priv->PlaneBuffers[i], length); if (!tmp) goto fail; context->priv->PlaneBuffers[i] = tmp; } context->priv->PlaneBuffersLength = length; } if (context->ChromaSubsamplingLevel) { context->OrgByteCount[0] = tempWidth * context->height; context->OrgByteCount[1] = tempWidth * tempHeight / 4; context->OrgByteCount[2] = tempWidth * tempHeight / 4; context->OrgByteCount[3] = context->width * context->height; } else { context->OrgByteCount[0] = context->width * context->height; context->OrgByteCount[1] = context->width * context->height; context->OrgByteCount[2] = context->width * context->height; context->OrgByteCount[3] = context->width * context->height; } return TRUE; fail: if (length > context->priv->PlaneBuffersLength) { for (i = 0; i < 5; i++) free(context->priv->PlaneBuffers[i]); } return FALSE; } Commit Message: Fixed CVE-2018-8788 Thanks to Eyal Itkin from Check Point Software Technologies. CWE ID: CWE-787 Target: 1 Example 2: Code: static struct dm_target *dm_dax_get_live_target(struct mapped_device *md, sector_t sector, int *srcu_idx) { struct dm_table *map; struct dm_target *ti; map = dm_get_live_table(md, srcu_idx); if (!map) return NULL; ti = dm_table_find_target(map, sector); if (!dm_target_is_valid(ti)) return NULL; return ti; } Commit Message: dm: fix race between dm_get_from_kobject() and __dm_destroy() The following BUG_ON was hit when testing repeat creation and removal of DM devices: kernel BUG at drivers/md/dm.c:2919! CPU: 7 PID: 750 Comm: systemd-udevd Not tainted 4.1.44 Call Trace: [<ffffffff81649e8b>] dm_get_from_kobject+0x34/0x3a [<ffffffff81650ef1>] dm_attr_show+0x2b/0x5e [<ffffffff817b46d1>] ? mutex_lock+0x26/0x44 [<ffffffff811df7f5>] sysfs_kf_seq_show+0x83/0xcf [<ffffffff811de257>] kernfs_seq_show+0x23/0x25 [<ffffffff81199118>] seq_read+0x16f/0x325 [<ffffffff811de994>] kernfs_fop_read+0x3a/0x13f [<ffffffff8117b625>] __vfs_read+0x26/0x9d [<ffffffff8130eb59>] ? security_file_permission+0x3c/0x44 [<ffffffff8117bdb8>] ? rw_verify_area+0x83/0xd9 [<ffffffff8117be9d>] vfs_read+0x8f/0xcf [<ffffffff81193e34>] ? __fdget_pos+0x12/0x41 [<ffffffff8117c686>] SyS_read+0x4b/0x76 [<ffffffff817b606e>] system_call_fastpath+0x12/0x71 The bug can be easily triggered, if an extra delay (e.g. 10ms) is added between the test of DMF_FREEING & DMF_DELETING and dm_get() in dm_get_from_kobject(). To fix it, we need to ensure the test of DMF_FREEING & DMF_DELETING and dm_get() are done in an atomic way, so _minor_lock is used. The other callers of dm_get() have also been checked to be OK: some callers invoke dm_get() under _minor_lock, some callers invoke it under _hash_lock, and dm_start_request() invoke it after increasing md->open_count. Cc: [email protected] Signed-off-by: Hou Tao <[email protected]> Signed-off-by: Mike Snitzer <[email protected]> CWE ID: CWE-362 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: explicit LogoDelegateImpl( std::unique_ptr<image_fetcher::ImageDecoder> image_decoder) : image_decoder_(std::move(image_decoder)) {} Commit Message: Local NTP: add smoke tests for doodles Split LogoService into LogoService interface and LogoServiceImpl to make it easier to provide fake data to the test. Bug: 768419 Cq-Include-Trybots: master.tryserver.chromium.linux:closure_compilation Change-Id: I84639189d2db1b24a2e139936c99369352bab587 Reviewed-on: https://chromium-review.googlesource.com/690198 Reviewed-by: Sylvain Defresne <[email protected]> Reviewed-by: Marc Treib <[email protected]> Commit-Queue: Chris Pickel <[email protected]> Cr-Commit-Position: refs/heads/master@{#505374} CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: open_log_file(const char *name, const char *prog, const char *namespace, const char *instance) { char *file_name; if (log_file) { fclose(log_file); log_file = NULL; } if (!name) return; file_name = make_file_name(name, prog, namespace, instance); log_file = fopen(file_name, "a"); if (log_file) { int n = fileno(log_file); fcntl(n, F_SETFD, FD_CLOEXEC | fcntl(n, F_GETFD)); fcntl(n, F_SETFL, O_NONBLOCK | fcntl(n, F_GETFL)); } FREE(file_name); } Commit Message: When opening files for write, ensure they aren't symbolic links Issue #1048 identified that if, for example, a non privileged user created a symbolic link from /etc/keepalvied.data to /etc/passwd, writing to /etc/keepalived.data (which could be invoked via DBus) would cause /etc/passwd to be overwritten. This commit stops keepalived writing to pathnames where the ultimate component is a symbolic link, by setting O_NOFOLLOW whenever opening a file for writing. This might break some setups, where, for example, /etc/keepalived.data was a symbolic link to /home/fred/keepalived.data. If this was the case, instead create a symbolic link from /home/fred/keepalived.data to /tmp/keepalived.data, so that the file is still accessible via /home/fred/keepalived.data. There doesn't appear to be a way around this backward incompatibility, since even checking if the pathname is a symbolic link prior to opening for writing would create a race condition. Signed-off-by: Quentin Armitage <[email protected]> CWE ID: CWE-59 Target: 1 Example 2: Code: String FrameFetchContext::GetUserAgent() const { if (IsDetached()) return frozen_state_->user_agent; return GetFrame()->Loader().UserAgent(); } Commit Message: DevTools: send proper resource type in Network.RequestWillBeSent This patch plumbs resoure type into the DispatchWillSendRequest instrumenation. This allows us to report accurate type in Network.RequestWillBeSent event, instead of "Other", that we report today. BUG=765501 R=dgozman Change-Id: I0134c08b841e8dd247fdc8ff208bfd51e462709c Reviewed-on: https://chromium-review.googlesource.com/667504 Reviewed-by: Pavel Feldman <[email protected]> Reviewed-by: Dmitry Gozman <[email protected]> Commit-Queue: Andrey Lushnikov <[email protected]> Cr-Commit-Position: refs/heads/master@{#507936} CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: bool Segment::DoneParsing() const { if (m_size < 0) { long long total, avail; const int status = m_pReader->Length(&total, &avail); if (status < 0) //error return true; //must assume done if (total < 0) return false; //assume live stream return (m_pos >= total); } const long long stop = m_start + m_size; return (m_pos >= stop); } 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 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int ip6_mroute_setsockopt(struct sock *sk, int optname, char __user *optval, unsigned int optlen) { int ret, parent = 0; struct mif6ctl vif; struct mf6cctl mfc; mifi_t mifi; struct net *net = sock_net(sk); struct mr6_table *mrt; mrt = ip6mr_get_table(net, raw6_sk(sk)->ip6mr_table ? : RT6_TABLE_DFLT); if (!mrt) return -ENOENT; if (optname != MRT6_INIT) { if (sk != mrt->mroute6_sk && !ns_capable(net->user_ns, CAP_NET_ADMIN)) return -EACCES; } switch (optname) { case MRT6_INIT: if (sk->sk_type != SOCK_RAW || inet_sk(sk)->inet_num != IPPROTO_ICMPV6) return -EOPNOTSUPP; if (optlen < sizeof(int)) return -EINVAL; return ip6mr_sk_init(mrt, sk); case MRT6_DONE: return ip6mr_sk_done(sk); case MRT6_ADD_MIF: if (optlen < sizeof(vif)) return -EINVAL; if (copy_from_user(&vif, optval, sizeof(vif))) return -EFAULT; if (vif.mif6c_mifi >= MAXMIFS) return -ENFILE; rtnl_lock(); ret = mif6_add(net, mrt, &vif, sk == mrt->mroute6_sk); rtnl_unlock(); return ret; case MRT6_DEL_MIF: if (optlen < sizeof(mifi_t)) return -EINVAL; if (copy_from_user(&mifi, optval, sizeof(mifi_t))) return -EFAULT; rtnl_lock(); ret = mif6_delete(mrt, mifi, NULL); rtnl_unlock(); return ret; /* * Manipulate the forwarding caches. These live * in a sort of kernel/user symbiosis. */ case MRT6_ADD_MFC: case MRT6_DEL_MFC: parent = -1; case MRT6_ADD_MFC_PROXY: case MRT6_DEL_MFC_PROXY: if (optlen < sizeof(mfc)) return -EINVAL; if (copy_from_user(&mfc, optval, sizeof(mfc))) return -EFAULT; if (parent == 0) parent = mfc.mf6cc_parent; rtnl_lock(); if (optname == MRT6_DEL_MFC || optname == MRT6_DEL_MFC_PROXY) ret = ip6mr_mfc_delete(mrt, &mfc, parent); else ret = ip6mr_mfc_add(net, mrt, &mfc, sk == mrt->mroute6_sk, parent); rtnl_unlock(); return ret; /* * Control PIM assert (to activate pim will activate assert) */ case MRT6_ASSERT: { int v; if (optlen != sizeof(v)) return -EINVAL; if (get_user(v, (int __user *)optval)) return -EFAULT; mrt->mroute_do_assert = v; return 0; } #ifdef CONFIG_IPV6_PIMSM_V2 case MRT6_PIM: { int v; if (optlen != sizeof(v)) return -EINVAL; if (get_user(v, (int __user *)optval)) return -EFAULT; v = !!v; rtnl_lock(); ret = 0; if (v != mrt->mroute_do_pim) { mrt->mroute_do_pim = v; mrt->mroute_do_assert = v; } rtnl_unlock(); return ret; } #endif #ifdef CONFIG_IPV6_MROUTE_MULTIPLE_TABLES case MRT6_TABLE: { u32 v; if (optlen != sizeof(u32)) return -EINVAL; if (get_user(v, (u32 __user *)optval)) return -EFAULT; /* "pim6reg%u" should not exceed 16 bytes (IFNAMSIZ) */ if (v != RT_TABLE_DEFAULT && v >= 100000000) return -EINVAL; if (sk == mrt->mroute6_sk) return -EBUSY; rtnl_lock(); ret = 0; if (!ip6mr_new_table(net, v)) ret = -ENOMEM; raw6_sk(sk)->ip6mr_table = v; rtnl_unlock(); return ret; } #endif /* * Spurious command, or MRT6_VERSION which you cannot * set. */ default: return -ENOPROTOOPT; } } Commit Message: ipv6: check sk sk_type and protocol early in ip_mroute_set/getsockopt Commit 5e1859fbcc3c ("ipv4: ipmr: various fixes and cleanups") fixed the issue for ipv4 ipmr: ip_mroute_setsockopt() & ip_mroute_getsockopt() should not access/set raw_sk(sk)->ipmr_table before making sure the socket is a raw socket, and protocol is IGMP The same fix should be done for ipv6 ipmr as well. This patch can fix the panic caused by overwriting the same offset as ipmr_table as in raw_sk(sk) when accessing other type's socket by ip_mroute_setsockopt(). Signed-off-by: Xin Long <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-20 Target: 1 Example 2: Code: static void ehci_flush_qh(EHCIQueue *q) { uint32_t *qh = (uint32_t *) &q->qh; uint32_t dwords = sizeof(EHCIqh) >> 2; uint32_t addr = NLPTR_GET(q->qhaddr); put_dwords(q->ehci, addr + 3 * sizeof(uint32_t), qh + 3, dwords - 3); } Commit Message: CWE ID: CWE-772 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void MemStream::reset() { bufPtr = buf + start; } Commit Message: CWE ID: CWE-119 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: hugetlbfs_fill_super(struct super_block *sb, void *data, int silent) { struct inode * inode; struct dentry * root; int ret; struct hugetlbfs_config config; struct hugetlbfs_sb_info *sbinfo; save_mount_options(sb, data); config.nr_blocks = -1; /* No limit on size by default */ config.nr_inodes = -1; /* No limit on number of inodes by default */ config.uid = current_fsuid(); config.gid = current_fsgid(); config.mode = 0755; config.hstate = &default_hstate; ret = hugetlbfs_parse_options(data, &config); if (ret) return ret; sbinfo = kmalloc(sizeof(struct hugetlbfs_sb_info), GFP_KERNEL); if (!sbinfo) return -ENOMEM; sb->s_fs_info = sbinfo; sbinfo->hstate = config.hstate; spin_lock_init(&sbinfo->stat_lock); sbinfo->max_blocks = config.nr_blocks; sbinfo->free_blocks = config.nr_blocks; sbinfo->max_inodes = config.nr_inodes; sbinfo->free_inodes = config.nr_inodes; sb->s_maxbytes = MAX_LFS_FILESIZE; sb->s_blocksize = huge_page_size(config.hstate); sb->s_blocksize_bits = huge_page_shift(config.hstate); sb->s_magic = HUGETLBFS_MAGIC; sb->s_op = &hugetlbfs_ops; sb->s_time_gran = 1; inode = hugetlbfs_get_root(sb, &config); if (!inode) goto out_free; root = d_alloc_root(inode); if (!root) { iput(inode); goto out_free; } sb->s_root = root; return 0; out_free: kfree(sbinfo); return -ENOMEM; } 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 Target: 1 Example 2: Code: static void IdAttributeSetter( v8::Local<v8::Value> v8_value, const v8::FunctionCallbackInfo<v8::Value>& info) { v8::Isolate* isolate = info.GetIsolate(); ALLOW_UNUSED_LOCAL(isolate); v8::Local<v8::Object> holder = info.Holder(); ALLOW_UNUSED_LOCAL(holder); TestObject* impl = V8TestObject::ToImpl(holder); V0CustomElementProcessingStack::CallbackDeliveryScope delivery_scope; V8StringResource<> cpp_value = v8_value; if (!cpp_value.Prepare()) return; impl->setAttribute(html_names::kIdAttr, cpp_value); } Commit Message: bindings: Support "attribute FrozenArray<T>?" Adds a quick hack to support a case of "attribute FrozenArray<T>?". Bug: 1028047 Change-Id: Ib3cecc4beb6bcc0fb0dbc667aca595454cc90c86 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1933866 Reviewed-by: Hitoshi Yoshida <[email protected]> Commit-Queue: Yuki Shiino <[email protected]> Cr-Commit-Position: refs/heads/master@{#718676} CWE ID: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int gup_huge_pgd(pgd_t orig, pgd_t *pgdp, unsigned long addr, unsigned long end, int write, struct page **pages, int *nr) { int refs; struct page *head, *page; if (!pgd_access_permitted(orig, write)) return 0; BUILD_BUG_ON(pgd_devmap(orig)); refs = 0; page = pgd_page(orig) + ((addr & ~PGDIR_MASK) >> PAGE_SHIFT); do { pages[*nr] = page; (*nr)++; page++; refs++; } while (addr += PAGE_SIZE, addr != end); head = compound_head(pgd_page(orig)); if (!page_cache_add_speculative(head, refs)) { *nr -= refs; return 0; } if (unlikely(pgd_val(orig) != pgd_val(*pgdp))) { *nr -= refs; while (refs--) put_page(head); return 0; } SetPageReferenced(head); return 1; } Commit Message: Merge branch 'page-refs' (page ref overflow) Merge page ref overflow branch. Jann Horn reported that he can overflow the page ref count with sufficient memory (and a filesystem that is intentionally extremely slow). Admittedly it's not exactly easy. To have more than four billion references to a page requires a minimum of 32GB of kernel memory just for the pointers to the pages, much less any metadata to keep track of those pointers. Jann needed a total of 140GB of memory and a specially crafted filesystem that leaves all reads pending (in order to not ever free the page references and just keep adding more). Still, we have a fairly straightforward way to limit the two obvious user-controllable sources of page references: direct-IO like page references gotten through get_user_pages(), and the splice pipe page duplication. So let's just do that. * branch page-refs: fs: prevent page refcount overflow in pipe_buf_get mm: prevent get_user_pages() from overflowing page refcount mm: add 'try_get_page()' helper function mm: make page ref count overflow check tighter and more explicit CWE ID: CWE-416 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: dtls1_get_message_fragment(SSL *s, int st1, int stn, long max, int *ok) { unsigned char wire[DTLS1_HM_HEADER_LENGTH]; unsigned long len, frag_off, frag_len; int i,al; struct hm_header_st msg_hdr; /* see if we have the required fragment already */ if ((frag_len = dtls1_retrieve_buffered_fragment(s,max,ok)) || *ok) { return frag_len; } /* read handshake message header */ i=s->method->ssl_read_bytes(s,SSL3_RT_HANDSHAKE,wire, DTLS1_HM_HEADER_LENGTH, 0); if (i <= 0) /* nbio, or an error */ { s->rwstate=SSL_READING; *ok = 0; return i; } /* Handshake fails if message header is incomplete */ if (i != DTLS1_HM_HEADER_LENGTH) { al=SSL_AD_UNEXPECTED_MESSAGE; SSLerr(SSL_F_DTLS1_GET_MESSAGE_FRAGMENT,SSL_R_UNEXPECTED_MESSAGE); goto f_err; } /* parse the message fragment header */ dtls1_get_message_header(wire, &msg_hdr); /* * if this is a future (or stale) message it gets buffered * (or dropped)--no further processing at this time * While listening, we accept seq 1 (ClientHello with cookie) * although we're still expecting seq 0 (ClientHello) */ if (msg_hdr.seq != s->d1->handshake_read_seq && !(s->d1->listen && msg_hdr.seq == 1)) return dtls1_process_out_of_seq_message(s, &msg_hdr, ok); len = msg_hdr.msg_len; frag_off = msg_hdr.frag_off; frag_len = msg_hdr.frag_len; if (frag_len && frag_len < len) return dtls1_reassemble_fragment(s, &msg_hdr, ok); if (!s->server && s->d1->r_msg_hdr.frag_off == 0 && wire[0] == SSL3_MT_HELLO_REQUEST) { /* The server may always send 'Hello Request' messages -- * we are doing a handshake anyway now, so ignore them * if their format is correct. Does not count for * 'Finished' MAC. */ if (wire[1] == 0 && wire[2] == 0 && wire[3] == 0) { if (s->msg_callback) s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE, wire, DTLS1_HM_HEADER_LENGTH, s, s->msg_callback_arg); s->msg_callback_arg); s->init_num = 0; return dtls1_get_message_fragment(s, st1, stn, max, ok); } else /* Incorrectly formated Hello request */ { al=SSL_AD_UNEXPECTED_MESSAGE; SSLerr(SSL_F_DTLS1_GET_MESSAGE_FRAGMENT,SSL_R_UNEXPECTED_MESSAGE); goto f_err; } } if ((al=dtls1_preprocess_fragment(s,&msg_hdr,max))) goto f_err; /* XDTLS: ressurect this when restart is in place */ s->state=stn; if ( frag_len > 0) { unsigned char *p=(unsigned char *)s->init_buf->data+DTLS1_HM_HEADER_LENGTH; i=s->method->ssl_read_bytes(s,SSL3_RT_HANDSHAKE, &p[frag_off],frag_len,0); /* XDTLS: fix this--message fragments cannot span multiple packets */ if (i <= 0) { s->rwstate=SSL_READING; *ok = 0; return i; } } else i = 0; /* XDTLS: an incorrectly formatted fragment should cause the * handshake to fail */ if (i != (int)frag_len) { al=SSL3_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_DTLS1_GET_MESSAGE_FRAGMENT,SSL3_AD_ILLEGAL_PARAMETER); goto f_err; } *ok = 1; /* Note that s->init_num is *not* used as current offset in * s->init_buf->data, but as a counter summing up fragments' * lengths: as soon as they sum up to handshake packet * length, we assume we have got all the fragments. */ s->init_num = frag_len; return frag_len; f_err: ssl3_send_alert(s,SSL3_AL_FATAL,al); s->init_num = 0; *ok=0; return(-1); } Commit Message: CWE ID: CWE-399 Target: 1 Example 2: Code: static int invent_group_ids(struct mount *mnt, bool recurse) { struct mount *p; for (p = mnt; p; p = recurse ? next_mnt(p, mnt) : NULL) { if (!p->mnt_group_id && !IS_MNT_SHARED(p)) { int err = mnt_alloc_group_id(p); if (err) { cleanup_group_ids(mnt, p); return err; } } } return 0; } Commit Message: mnt: Add a per mount namespace limit on the number of mounts CAI Qian <[email protected]> pointed out that the semantics of shared subtrees make it possible to create an exponentially increasing number of mounts in a mount namespace. mkdir /tmp/1 /tmp/2 mount --make-rshared / for i in $(seq 1 20) ; do mount --bind /tmp/1 /tmp/2 ; done Will create create 2^20 or 1048576 mounts, which is a practical problem as some people have managed to hit this by accident. As such CVE-2016-6213 was assigned. Ian Kent <[email protected]> described the situation for autofs users as follows: > The number of mounts for direct mount maps is usually not very large because of > the way they are implemented, large direct mount maps can have performance > problems. There can be anywhere from a few (likely case a few hundred) to less > than 10000, plus mounts that have been triggered and not yet expired. > > Indirect mounts have one autofs mount at the root plus the number of mounts that > have been triggered and not yet expired. > > The number of autofs indirect map entries can range from a few to the common > case of several thousand and in rare cases up to between 30000 and 50000. I've > not heard of people with maps larger than 50000 entries. > > The larger the number of map entries the greater the possibility for a large > number of active mounts so it's not hard to expect cases of a 1000 or somewhat > more active mounts. So I am setting the default number of mounts allowed per mount namespace at 100,000. This is more than enough for any use case I know of, but small enough to quickly stop an exponential increase in mounts. Which should be perfect to catch misconfigurations and malfunctioning programs. For anyone who needs a higher limit this can be changed by writing to the new /proc/sys/fs/mount-max sysctl. Tested-by: CAI Qian <[email protected]> Signed-off-by: "Eric W. Biederman" <[email protected]> CWE ID: CWE-400 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void ip_mc_clear_src(struct ip_mc_list *pmc) { struct ip_sf_list *psf, *nextpsf; for (psf=pmc->tomb; psf; psf=nextpsf) { nextpsf = psf->sf_next; kfree(psf); } pmc->tomb = NULL; for (psf=pmc->sources; psf; psf=nextpsf) { nextpsf = psf->sf_next; kfree(psf); } pmc->sources = NULL; pmc->sfmode = MCAST_EXCLUDE; pmc->sfcount[MCAST_INCLUDE] = 0; pmc->sfcount[MCAST_EXCLUDE] = 1; } Commit Message: igmp: Avoid zero delay when receiving odd mixture of IGMP queries Commit 5b7c84066733c5dfb0e4016d939757b38de189e4 ('ipv4: correct IGMP behavior on v3 query during v2-compatibility mode') added yet another case for query parsing, which can result in max_delay = 0. Substitute a value of 1, as in the usual v3 case. Reported-by: Simon McVittie <[email protected]> References: http://bugs.debian.org/654876 Signed-off-by: Ben Hutchings <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-399 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: IHEVCD_ERROR_T ihevcd_parse_sps(codec_t *ps_codec) { IHEVCD_ERROR_T ret = (IHEVCD_ERROR_T)IHEVCD_SUCCESS; WORD32 value; WORD32 i; WORD32 vps_id; WORD32 sps_max_sub_layers; WORD32 sps_id; WORD32 sps_temporal_id_nesting_flag; sps_t *ps_sps; profile_tier_lvl_info_t s_ptl; bitstrm_t *ps_bitstrm = &ps_codec->s_parse.s_bitstrm; BITS_PARSE("video_parameter_set_id", value, ps_bitstrm, 4); vps_id = value; vps_id = CLIP3(vps_id, 0, MAX_VPS_CNT - 1); BITS_PARSE("sps_max_sub_layers_minus1", value, ps_bitstrm, 3); sps_max_sub_layers = value + 1; sps_max_sub_layers = CLIP3(sps_max_sub_layers, 1, 7); BITS_PARSE("sps_temporal_id_nesting_flag", value, ps_bitstrm, 1); sps_temporal_id_nesting_flag = value; ret = ihevcd_profile_tier_level(ps_bitstrm, &(s_ptl), 1, (sps_max_sub_layers - 1)); UEV_PARSE("seq_parameter_set_id", value, ps_bitstrm); sps_id = value; if((sps_id >= MAX_SPS_CNT) || (sps_id < 0)) { if(ps_codec->i4_sps_done) return IHEVCD_UNSUPPORTED_SPS_ID; else sps_id = 0; } ps_sps = (ps_codec->s_parse.ps_sps_base + MAX_SPS_CNT - 1); ps_sps->i1_sps_id = sps_id; ps_sps->i1_vps_id = vps_id; ps_sps->i1_sps_max_sub_layers = sps_max_sub_layers; ps_sps->i1_sps_temporal_id_nesting_flag = sps_temporal_id_nesting_flag; /* This is used only during initialization to get reorder count etc */ ps_codec->i4_sps_id = sps_id; memcpy(&ps_sps->s_ptl, &s_ptl, sizeof(profile_tier_lvl_info_t)); UEV_PARSE("chroma_format_idc", value, ps_bitstrm); ps_sps->i1_chroma_format_idc = value; if(ps_sps->i1_chroma_format_idc != CHROMA_FMT_IDC_YUV420) { ps_codec->s_parse.i4_error_code = IHEVCD_UNSUPPORTED_CHROMA_FMT_IDC; return (IHEVCD_ERROR_T)IHEVCD_UNSUPPORTED_CHROMA_FMT_IDC; } if(CHROMA_FMT_IDC_YUV444_PLANES == ps_sps->i1_chroma_format_idc) { BITS_PARSE("separate_colour_plane_flag", value, ps_bitstrm, 1); ps_sps->i1_separate_colour_plane_flag = value; } else { ps_sps->i1_separate_colour_plane_flag = 0; } UEV_PARSE("pic_width_in_luma_samples", value, ps_bitstrm); ps_sps->i2_pic_width_in_luma_samples = value; UEV_PARSE("pic_height_in_luma_samples", value, ps_bitstrm); ps_sps->i2_pic_height_in_luma_samples = value; if((0 >= ps_sps->i2_pic_width_in_luma_samples) || (0 >= ps_sps->i2_pic_height_in_luma_samples)) return IHEVCD_INVALID_PARAMETER; /* i2_pic_width_in_luma_samples and i2_pic_height_in_luma_samples should be multiples of min_cb_size. Here these are aligned to 8, i.e. smallest CB size */ ps_sps->i2_pic_width_in_luma_samples = ALIGN8(ps_sps->i2_pic_width_in_luma_samples); ps_sps->i2_pic_height_in_luma_samples = ALIGN8(ps_sps->i2_pic_height_in_luma_samples); if((ps_sps->i2_pic_width_in_luma_samples > ps_codec->i4_max_wd) || (ps_sps->i2_pic_width_in_luma_samples * ps_sps->i2_pic_height_in_luma_samples > ps_codec->i4_max_wd * ps_codec->i4_max_ht) || (ps_sps->i2_pic_height_in_luma_samples > MAX(ps_codec->i4_max_wd, ps_codec->i4_max_ht))) { ps_codec->i4_new_max_wd = ps_sps->i2_pic_width_in_luma_samples; ps_codec->i4_new_max_ht = ps_sps->i2_pic_height_in_luma_samples; return (IHEVCD_ERROR_T)IHEVCD_UNSUPPORTED_DIMENSIONS; } BITS_PARSE("pic_cropping_flag", value, ps_bitstrm, 1); ps_sps->i1_pic_cropping_flag = value; if(ps_sps->i1_pic_cropping_flag) { UEV_PARSE("pic_crop_left_offset", value, ps_bitstrm); ps_sps->i2_pic_crop_left_offset = value; UEV_PARSE("pic_crop_right_offset", value, ps_bitstrm); ps_sps->i2_pic_crop_right_offset = value; UEV_PARSE("pic_crop_top_offset", value, ps_bitstrm); ps_sps->i2_pic_crop_top_offset = value; UEV_PARSE("pic_crop_bottom_offset", value, ps_bitstrm); ps_sps->i2_pic_crop_bottom_offset = value; } else { ps_sps->i2_pic_crop_left_offset = 0; ps_sps->i2_pic_crop_right_offset = 0; ps_sps->i2_pic_crop_top_offset = 0; ps_sps->i2_pic_crop_bottom_offset = 0; } UEV_PARSE("bit_depth_luma_minus8", value, ps_bitstrm); if(0 != value) return IHEVCD_UNSUPPORTED_BIT_DEPTH; UEV_PARSE("bit_depth_chroma_minus8", value, ps_bitstrm); if(0 != value) return IHEVCD_UNSUPPORTED_BIT_DEPTH; UEV_PARSE("log2_max_pic_order_cnt_lsb_minus4", value, ps_bitstrm); ps_sps->i1_log2_max_pic_order_cnt_lsb = value + 4; BITS_PARSE("sps_sub_layer_ordering_info_present_flag", value, ps_bitstrm, 1); ps_sps->i1_sps_sub_layer_ordering_info_present_flag = value; i = (ps_sps->i1_sps_sub_layer_ordering_info_present_flag ? 0 : (ps_sps->i1_sps_max_sub_layers - 1)); for(; i < ps_sps->i1_sps_max_sub_layers; i++) { UEV_PARSE("max_dec_pic_buffering", value, ps_bitstrm); ps_sps->ai1_sps_max_dec_pic_buffering[i] = value + 1; UEV_PARSE("num_reorder_pics", value, ps_bitstrm); ps_sps->ai1_sps_max_num_reorder_pics[i] = value; UEV_PARSE("max_latency_increase", value, ps_bitstrm); ps_sps->ai1_sps_max_latency_increase[i] = value; } UEV_PARSE("log2_min_coding_block_size_minus3", value, ps_bitstrm); ps_sps->i1_log2_min_coding_block_size = value + 3; UEV_PARSE("log2_diff_max_min_coding_block_size", value, ps_bitstrm); ps_sps->i1_log2_diff_max_min_coding_block_size = value; UEV_PARSE("log2_min_transform_block_size_minus2", value, ps_bitstrm); ps_sps->i1_log2_min_transform_block_size = value + 2; UEV_PARSE("log2_diff_max_min_transform_block_size", value, ps_bitstrm); ps_sps->i1_log2_diff_max_min_transform_block_size = value; ps_sps->i1_log2_max_transform_block_size = ps_sps->i1_log2_min_transform_block_size + ps_sps->i1_log2_diff_max_min_transform_block_size; ps_sps->i1_log2_ctb_size = ps_sps->i1_log2_min_coding_block_size + ps_sps->i1_log2_diff_max_min_coding_block_size; if((ps_sps->i1_log2_min_coding_block_size < 3) || (ps_sps->i1_log2_min_transform_block_size < 2) || (ps_sps->i1_log2_diff_max_min_transform_block_size < 0) || (ps_sps->i1_log2_max_transform_block_size > ps_sps->i1_log2_ctb_size) || (ps_sps->i1_log2_ctb_size < 4) || (ps_sps->i1_log2_ctb_size > 6)) { return IHEVCD_INVALID_PARAMETER; } ps_sps->i1_log2_min_pcm_coding_block_size = 0; ps_sps->i1_log2_diff_max_min_pcm_coding_block_size = 0; UEV_PARSE("max_transform_hierarchy_depth_inter", value, ps_bitstrm); ps_sps->i1_max_transform_hierarchy_depth_inter = value; UEV_PARSE("max_transform_hierarchy_depth_intra", value, ps_bitstrm); ps_sps->i1_max_transform_hierarchy_depth_intra = value; /* String has a d (enabled) in order to match with HM */ BITS_PARSE("scaling_list_enabled_flag", value, ps_bitstrm, 1); ps_sps->i1_scaling_list_enable_flag = value; if(ps_sps->i1_scaling_list_enable_flag) { COPY_DEFAULT_SCALING_LIST(ps_sps->pi2_scaling_mat); BITS_PARSE("sps_scaling_list_data_present_flag", value, ps_bitstrm, 1); ps_sps->i1_sps_scaling_list_data_present_flag = value; if(ps_sps->i1_sps_scaling_list_data_present_flag) ihevcd_scaling_list_data(ps_codec, ps_sps->pi2_scaling_mat); } else { COPY_FLAT_SCALING_LIST(ps_sps->pi2_scaling_mat); } /* String is asymmetric_motion_partitions_enabled_flag instead of amp_enabled_flag in order to match with HM */ BITS_PARSE("asymmetric_motion_partitions_enabled_flag", value, ps_bitstrm, 1); ps_sps->i1_amp_enabled_flag = value; BITS_PARSE("sample_adaptive_offset_enabled_flag", value, ps_bitstrm, 1); ps_sps->i1_sample_adaptive_offset_enabled_flag = value; BITS_PARSE("pcm_enabled_flag", value, ps_bitstrm, 1); ps_sps->i1_pcm_enabled_flag = value; if(ps_sps->i1_pcm_enabled_flag) { BITS_PARSE("pcm_sample_bit_depth_luma", value, ps_bitstrm, 4); ps_sps->i1_pcm_sample_bit_depth_luma = value + 1; BITS_PARSE("pcm_sample_bit_depth_chroma", value, ps_bitstrm, 4); ps_sps->i1_pcm_sample_bit_depth_chroma = value + 1; UEV_PARSE("log2_min_pcm_coding_block_size_minus3", value, ps_bitstrm); ps_sps->i1_log2_min_pcm_coding_block_size = value + 3; UEV_PARSE("log2_diff_max_min_pcm_coding_block_size", value, ps_bitstrm); ps_sps->i1_log2_diff_max_min_pcm_coding_block_size = value; BITS_PARSE("pcm_loop_filter_disable_flag", value, ps_bitstrm, 1); ps_sps->i1_pcm_loop_filter_disable_flag = value; } UEV_PARSE("num_short_term_ref_pic_sets", value, ps_bitstrm); ps_sps->i1_num_short_term_ref_pic_sets = value; ps_sps->i1_num_short_term_ref_pic_sets = CLIP3(ps_sps->i1_num_short_term_ref_pic_sets, 0, MAX_STREF_PICS_SPS); for(i = 0; i < ps_sps->i1_num_short_term_ref_pic_sets; i++) ihevcd_short_term_ref_pic_set(ps_bitstrm, &ps_sps->as_stref_picset[0], ps_sps->i1_num_short_term_ref_pic_sets, i, &ps_sps->as_stref_picset[i]); BITS_PARSE("long_term_ref_pics_present_flag", value, ps_bitstrm, 1); ps_sps->i1_long_term_ref_pics_present_flag = value; if(ps_sps->i1_long_term_ref_pics_present_flag) { UEV_PARSE("num_long_term_ref_pics_sps", value, ps_bitstrm); ps_sps->i1_num_long_term_ref_pics_sps = value; for(i = 0; i < ps_sps->i1_num_long_term_ref_pics_sps; i++) { BITS_PARSE("lt_ref_pic_poc_lsb_sps[ i ]", value, ps_bitstrm, ps_sps->i1_log2_max_pic_order_cnt_lsb); ps_sps->ai1_lt_ref_pic_poc_lsb_sps[i] = value; BITS_PARSE("used_by_curr_pic_lt_sps_flag[ i ]", value, ps_bitstrm, 1); ps_sps->ai1_used_by_curr_pic_lt_sps_flag[i] = value; } } BITS_PARSE("sps_temporal_mvp_enable_flag", value, ps_bitstrm, 1); ps_sps->i1_sps_temporal_mvp_enable_flag = value; /* Print matches HM 8-2 */ BITS_PARSE("sps_strong_intra_smoothing_enable_flag", value, ps_bitstrm, 1); ps_sps->i1_strong_intra_smoothing_enable_flag = value; BITS_PARSE("vui_parameters_present_flag", value, ps_bitstrm, 1); ps_sps->i1_vui_parameters_present_flag = value; if(ps_sps->i1_vui_parameters_present_flag) ihevcd_parse_vui_parameters(ps_bitstrm, &ps_sps->s_vui_parameters, ps_sps->i1_sps_max_sub_layers - 1); BITS_PARSE("sps_extension_flag", value, ps_bitstrm, 1); { WORD32 numerator; WORD32 ceil_offset; ceil_offset = (1 << ps_sps->i1_log2_ctb_size) - 1; numerator = ps_sps->i2_pic_width_in_luma_samples; ps_sps->i2_pic_wd_in_ctb = ((numerator + ceil_offset) / (1 << ps_sps->i1_log2_ctb_size)); numerator = ps_sps->i2_pic_height_in_luma_samples; ps_sps->i2_pic_ht_in_ctb = ((numerator + ceil_offset) / (1 << ps_sps->i1_log2_ctb_size)); ps_sps->i4_pic_size_in_ctb = ps_sps->i2_pic_ht_in_ctb * ps_sps->i2_pic_wd_in_ctb; if(0 == ps_codec->i4_sps_done) ps_codec->s_parse.i4_next_ctb_indx = ps_sps->i4_pic_size_in_ctb; numerator = ps_sps->i2_pic_width_in_luma_samples; ps_sps->i2_pic_wd_in_min_cb = numerator / (1 << ps_sps->i1_log2_min_coding_block_size); numerator = ps_sps->i2_pic_height_in_luma_samples; ps_sps->i2_pic_ht_in_min_cb = numerator / (1 << ps_sps->i1_log2_min_coding_block_size); } if((0 != ps_codec->i4_first_pic_done) && ((ps_codec->i4_wd != ps_sps->i2_pic_width_in_luma_samples) || (ps_codec->i4_ht != ps_sps->i2_pic_height_in_luma_samples))) { ps_codec->i4_reset_flag = 1; ps_codec->i4_error_code = IVD_RES_CHANGED; return (IHEVCD_ERROR_T)IHEVCD_FAIL; } /* Update display width and display height */ { WORD32 disp_wd, disp_ht; WORD32 crop_unit_x, crop_unit_y; crop_unit_x = 1; crop_unit_y = 1; if(CHROMA_FMT_IDC_YUV420 == ps_sps->i1_chroma_format_idc) { crop_unit_x = 2; crop_unit_y = 2; } disp_wd = ps_sps->i2_pic_width_in_luma_samples; disp_wd -= ps_sps->i2_pic_crop_left_offset * crop_unit_x; disp_wd -= ps_sps->i2_pic_crop_right_offset * crop_unit_x; disp_ht = ps_sps->i2_pic_height_in_luma_samples; disp_ht -= ps_sps->i2_pic_crop_top_offset * crop_unit_y; disp_ht -= ps_sps->i2_pic_crop_bottom_offset * crop_unit_y; if((0 >= disp_wd) || (0 >= disp_ht)) return IHEVCD_INVALID_PARAMETER; ps_codec->i4_disp_wd = disp_wd; ps_codec->i4_disp_ht = disp_ht; ps_codec->i4_wd = ps_sps->i2_pic_width_in_luma_samples; ps_codec->i4_ht = ps_sps->i2_pic_height_in_luma_samples; { WORD32 ref_strd; ref_strd = ALIGN32(ps_sps->i2_pic_width_in_luma_samples + PAD_WD); if(ps_codec->i4_strd < ref_strd) { ps_codec->i4_strd = ref_strd; } } if(0 == ps_codec->i4_share_disp_buf) { if(ps_codec->i4_disp_strd < ps_codec->i4_disp_wd) { ps_codec->i4_disp_strd = ps_codec->i4_disp_wd; } } else { if(ps_codec->i4_disp_strd < ps_codec->i4_strd) { ps_codec->i4_disp_strd = ps_codec->i4_strd; } } } ps_codec->i4_sps_done = 1; return ret; } Commit Message: Handle invalid num_reorder_pics & max_dec_pic_buffering in SPS Bug: 33864300 Change-Id: I920e45c3420a1a41a366ad45bd4186c5f6af6d6b CWE ID: CWE-119 Target: 1 Example 2: Code: static void webkitWebViewBaseDragLeave(GtkWidget* widget, GdkDragContext* context, guint time) { WEBKIT_WEB_VIEW_BASE(widget)->priv->dragAndDropHelper.handleDragLeave(context, dragExitedCallback); } 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 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int bsg_put_device(struct bsg_device *bd) { int ret = 0, do_free; struct request_queue *q = bd->queue; mutex_lock(&bsg_mutex); do_free = atomic_dec_and_test(&bd->ref_count); if (!do_free) { mutex_unlock(&bsg_mutex); goto out; } hlist_del(&bd->dev_list); mutex_unlock(&bsg_mutex); dprintk("%s: tearing down\n", bd->name); /* * close can always block */ set_bit(BSG_F_BLOCK, &bd->flags); /* * correct error detection baddies here again. it's the responsibility * of the app to properly reap commands before close() if it wants * fool-proof error detection */ ret = bsg_complete_all_commands(bd); kfree(bd); out: kref_put(&q->bsg_dev.ref, bsg_kref_release_function); if (do_free) blk_put_queue(q); return ret; } Commit Message: sg_write()/bsg_write() is not fit to be called under KERNEL_DS Both damn things interpret userland pointers embedded into the payload; worse, they are actually traversing those. Leaving aside the bad API design, this is very much _not_ safe to call with KERNEL_DS. Bail out early if that happens. Cc: [email protected] Signed-off-by: Al Viro <[email protected]> CWE ID: CWE-416 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: long Chapters::Display::Parse( IMkvReader* pReader, long long pos, long long size) { const long long stop = pos + size; while (pos < stop) { long long id, size; long status = ParseElementHeader( pReader, pos, stop, id, size); if (status < 0) // error return status; if (size == 0) // weird continue; if (id == 0x05) // ChapterString ID { status = UnserializeString(pReader, pos, size, m_string); if (status) return status; } else if (id == 0x037C) // ChapterLanguage ID { status = UnserializeString(pReader, pos, size, m_language); if (status) return status; } else if (id == 0x037E) // ChapterCountry ID { status = UnserializeString(pReader, pos, size, m_country); if (status) return status; } pos += size; assert(pos <= stop); } assert(pos == stop); return 0; } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119 Target: 1 Example 2: Code: static inline u32 nfsd4_commit_rsize(struct svc_rqst *rqstp, struct nfsd4_op *op) { return (op_encode_hdr_size + op_encode_verifier_maxsz) * sizeof(__be32); } Commit Message: Merge tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux Pull nfsd updates from Bruce Fields: "Another RDMA update from Chuck Lever, and a bunch of miscellaneous bugfixes" * tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux: (26 commits) nfsd: Fix up the "supattr_exclcreat" attributes nfsd: encoders mustn't use unitialized values in error cases nfsd: fix undefined behavior in nfsd4_layout_verify lockd: fix lockd shutdown race NFSv4: Fix callback server shutdown SUNRPC: Refactor svc_set_num_threads() NFSv4.x/callback: Create the callback service through svc_create_pooled lockd: remove redundant check on block svcrdma: Clean out old XDR encoders svcrdma: Remove the req_map cache svcrdma: Remove unused RDMA Write completion handler svcrdma: Reduce size of sge array in struct svc_rdma_op_ctxt svcrdma: Clean up RPC-over-RDMA backchannel reply processing svcrdma: Report Write/Reply chunk overruns svcrdma: Clean up RDMA_ERROR path svcrdma: Use rdma_rw API in RPC reply path svcrdma: Introduce local rdma_rw API helpers svcrdma: Clean up svc_rdma_get_inv_rkey() svcrdma: Add helper to save pages under I/O svcrdma: Eliminate RPCRDMA_SQ_DEPTH_MULT ... CWE ID: CWE-404 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: bool RenderFrameHostImpl::OnMessageReceived(const IPC::Message &msg) { if (!render_frame_created_) return false; ScopedActiveURL scoped_active_url(this); bool handled = true; IPC_BEGIN_MESSAGE_MAP(RenderFrameHostImpl, msg) IPC_MESSAGE_HANDLER(FrameHostMsg_RenderProcessGone, OnRenderProcessGone) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() if (handled) return true; if (delegate_->OnMessageReceived(this, msg)) return true; RenderFrameProxyHost* proxy = frame_tree_node_->render_manager()->GetProxyToParent(); if (proxy && proxy->cross_process_frame_connector() && proxy->cross_process_frame_connector()->OnMessageReceived(msg)) return true; handled = true; IPC_BEGIN_MESSAGE_MAP(RenderFrameHostImpl, msg) IPC_MESSAGE_HANDLER(FrameHostMsg_DidAddMessageToConsole, OnDidAddMessageToConsole) IPC_MESSAGE_HANDLER(FrameHostMsg_Detach, OnDetach) IPC_MESSAGE_HANDLER(FrameHostMsg_FrameFocused, OnFrameFocused) IPC_MESSAGE_HANDLER(FrameHostMsg_DidStartProvisionalLoad, OnDidStartProvisionalLoad) IPC_MESSAGE_HANDLER(FrameHostMsg_DidFailProvisionalLoadWithError, OnDidFailProvisionalLoadWithError) IPC_MESSAGE_HANDLER(FrameHostMsg_DidFailLoadWithError, OnDidFailLoadWithError) IPC_MESSAGE_HANDLER(FrameHostMsg_UpdateState, OnUpdateState) IPC_MESSAGE_HANDLER(FrameHostMsg_OpenURL, OnOpenURL) IPC_MESSAGE_HANDLER(FrameHostMsg_DocumentOnLoadCompleted, OnDocumentOnLoadCompleted) IPC_MESSAGE_HANDLER(FrameHostMsg_BeforeUnload_ACK, OnBeforeUnloadACK) IPC_MESSAGE_HANDLER(FrameHostMsg_SwapOut_ACK, OnSwapOutACK) IPC_MESSAGE_HANDLER(FrameHostMsg_ContextMenu, OnContextMenu) IPC_MESSAGE_HANDLER(FrameHostMsg_JavaScriptExecuteResponse, OnJavaScriptExecuteResponse) IPC_MESSAGE_HANDLER(FrameHostMsg_VisualStateResponse, OnVisualStateResponse) IPC_MESSAGE_HANDLER_DELAY_REPLY(FrameHostMsg_RunJavaScriptDialog, OnRunJavaScriptDialog) IPC_MESSAGE_HANDLER_DELAY_REPLY(FrameHostMsg_RunBeforeUnloadConfirm, OnRunBeforeUnloadConfirm) IPC_MESSAGE_HANDLER(FrameHostMsg_RunFileChooser, OnRunFileChooser) IPC_MESSAGE_HANDLER(FrameHostMsg_DidAccessInitialDocument, OnDidAccessInitialDocument) IPC_MESSAGE_HANDLER(FrameHostMsg_DidChangeOpener, OnDidChangeOpener) IPC_MESSAGE_HANDLER(FrameHostMsg_DidAddContentSecurityPolicies, OnDidAddContentSecurityPolicies) IPC_MESSAGE_HANDLER(FrameHostMsg_DidChangeFramePolicy, OnDidChangeFramePolicy) IPC_MESSAGE_HANDLER(FrameHostMsg_DidChangeFrameOwnerProperties, OnDidChangeFrameOwnerProperties) IPC_MESSAGE_HANDLER(FrameHostMsg_UpdateTitle, OnUpdateTitle) IPC_MESSAGE_HANDLER(FrameHostMsg_DidBlockFramebust, OnDidBlockFramebust) IPC_MESSAGE_HANDLER(FrameHostMsg_AbortNavigation, OnAbortNavigation) IPC_MESSAGE_HANDLER(FrameHostMsg_DispatchLoad, OnDispatchLoad) IPC_MESSAGE_HANDLER(FrameHostMsg_ForwardResourceTimingToParent, OnForwardResourceTimingToParent) IPC_MESSAGE_HANDLER(FrameHostMsg_TextSurroundingSelectionResponse, OnTextSurroundingSelectionResponse) IPC_MESSAGE_HANDLER(AccessibilityHostMsg_Events, OnAccessibilityEvents) IPC_MESSAGE_HANDLER(AccessibilityHostMsg_LocationChanges, OnAccessibilityLocationChanges) IPC_MESSAGE_HANDLER(AccessibilityHostMsg_FindInPageResult, OnAccessibilityFindInPageResult) IPC_MESSAGE_HANDLER(AccessibilityHostMsg_ChildFrameHitTestResult, OnAccessibilityChildFrameHitTestResult) IPC_MESSAGE_HANDLER(AccessibilityHostMsg_SnapshotResponse, OnAccessibilitySnapshotResponse) IPC_MESSAGE_HANDLER(FrameHostMsg_ToggleFullscreen, OnToggleFullscreen) IPC_MESSAGE_HANDLER(FrameHostMsg_SuddenTerminationDisablerChanged, OnSuddenTerminationDisablerChanged) IPC_MESSAGE_HANDLER(FrameHostMsg_DidStartLoading, OnDidStartLoading) IPC_MESSAGE_HANDLER(FrameHostMsg_DidStopLoading, OnDidStopLoading) IPC_MESSAGE_HANDLER(FrameHostMsg_DidChangeLoadProgress, OnDidChangeLoadProgress) IPC_MESSAGE_HANDLER(FrameHostMsg_SerializeAsMHTMLResponse, OnSerializeAsMHTMLResponse) IPC_MESSAGE_HANDLER(FrameHostMsg_SelectionChanged, OnSelectionChanged) IPC_MESSAGE_HANDLER(FrameHostMsg_FocusedNodeChanged, OnFocusedNodeChanged) IPC_MESSAGE_HANDLER(FrameHostMsg_SetHasReceivedUserGesture, OnSetHasReceivedUserGesture) IPC_MESSAGE_HANDLER(FrameHostMsg_SetHasReceivedUserGestureBeforeNavigation, OnSetHasReceivedUserGestureBeforeNavigation) IPC_MESSAGE_HANDLER(FrameHostMsg_ScrollRectToVisibleInParentFrame, OnScrollRectToVisibleInParentFrame) #if BUILDFLAG(USE_EXTERNAL_POPUP_MENU) IPC_MESSAGE_HANDLER(FrameHostMsg_ShowPopup, OnShowPopup) IPC_MESSAGE_HANDLER(FrameHostMsg_HidePopup, OnHidePopup) #endif IPC_MESSAGE_HANDLER(FrameHostMsg_RequestOverlayRoutingToken, OnRequestOverlayRoutingToken) IPC_MESSAGE_HANDLER(FrameHostMsg_ShowCreatedWindow, OnShowCreatedWindow) IPC_MESSAGE_HANDLER(FrameHostMsg_StreamHandleConsumed, OnStreamHandleConsumed) IPC_END_MESSAGE_MAP() return handled; } Commit Message: If a page calls |window.focus()|, kick it out of fullscreen. BUG=776418, 800056 Change-Id: I1880fe600e4814c073f247c43b1c1ac80c8fc017 Reviewed-on: https://chromium-review.googlesource.com/852378 Reviewed-by: Nasko Oskov <[email protected]> Reviewed-by: Philip Jägenstedt <[email protected]> Commit-Queue: Avi Drissman <[email protected]> Cr-Commit-Position: refs/heads/master@{#533790} CWE ID: Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: Node::InsertionNotificationRequest SVGStyleElement::InsertedInto( ContainerNode* insertion_point) { SVGElement::InsertedInto(insertion_point); return kInsertionShouldCallDidNotifySubtreeInsertions; } Commit Message: Do not crash while reentrantly appending to style element. When a node is inserted into a container, it is notified via ::InsertedInto. However, a node may request a second notification via DidNotifySubtreeInsertionsToDocument, which occurs after all the children have been notified as well. *StyleElement is currently using this second notification. This causes a problem, because *ScriptElement is using the same mechanism, which in turn means that scripts can execute before the state of *StyleElements are properly updated. This patch avoids ::DidNotifySubtreeInsertionsToDocument, and instead processes the stylesheet in ::InsertedInto. The original reason for using ::DidNotifySubtreeInsertionsToDocument in the first place appears to be invalid now, as the test case is still passing. [email protected], [email protected] Bug: 853709, 847570 Cq-Include-Trybots: luci.chromium.try:linux_layout_tests_slimming_paint_v2;master.tryserver.blink:linux_trusty_blink_rel Change-Id: Ic0b5fa611044c78c5745cf26870a747f88920a14 Reviewed-on: https://chromium-review.googlesource.com/1104347 Commit-Queue: Anders Ruud <[email protected]> Reviewed-by: Rune Lillesveen <[email protected]> Cr-Commit-Position: refs/heads/master@{#568368} CWE ID: CWE-416 Target: 1 Example 2: Code: getAttributeId(XML_Parser parser, const ENCODING *enc, const char *start, const char *end) { DTD * const dtd = parser->m_dtd; /* save one level of indirection */ ATTRIBUTE_ID *id; const XML_Char *name; if (!poolAppendChar(&dtd->pool, XML_T('\0'))) return NULL; name = poolStoreString(&dtd->pool, enc, start, end); if (!name) return NULL; /* skip quotation mark - its storage will be re-used (like in name[-1]) */ ++name; id = (ATTRIBUTE_ID *)lookup(parser, &dtd->attributeIds, name, sizeof(ATTRIBUTE_ID)); if (!id) return NULL; if (id->name != name) poolDiscard(&dtd->pool); else { poolFinish(&dtd->pool); if (!parser->m_ns) ; else if (name[0] == XML_T(ASCII_x) && name[1] == XML_T(ASCII_m) && name[2] == XML_T(ASCII_l) && name[3] == XML_T(ASCII_n) && name[4] == XML_T(ASCII_s) && (name[5] == XML_T('\0') || name[5] == XML_T(ASCII_COLON))) { if (name[5] == XML_T('\0')) id->prefix = &dtd->defaultPrefix; else id->prefix = (PREFIX *)lookup(parser, &dtd->prefixes, name + 6, sizeof(PREFIX)); id->xmlns = XML_TRUE; } else { int i; for (i = 0; name[i]; i++) { /* attributes without prefix are *not* in the default namespace */ if (name[i] == XML_T(ASCII_COLON)) { int j; for (j = 0; j < i; j++) { if (!poolAppendChar(&dtd->pool, name[j])) return NULL; } if (!poolAppendChar(&dtd->pool, XML_T('\0'))) return NULL; id->prefix = (PREFIX *)lookup(parser, &dtd->prefixes, poolStart(&dtd->pool), sizeof(PREFIX)); if (!id->prefix) return NULL; if (id->prefix->name == poolStart(&dtd->pool)) poolFinish(&dtd->pool); else poolDiscard(&dtd->pool); break; } } } } return id; } Commit Message: xmlparse.c: Fix extraction of namespace prefix from XML name (#186) CWE ID: CWE-611 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void RenderFrameHostImpl::SwapOut( RenderFrameProxyHost* proxy, bool is_loading) { TRACE_EVENT_ASYNC_BEGIN1("navigation", "RenderFrameHostImpl::SwapOut", this, "frame_tree_node", frame_tree_node_->frame_tree_node_id()); if (!is_active()) { NOTREACHED() << "RFH should be in default state when calling SwapOut."; return; } if (swapout_event_monitor_timeout_) { swapout_event_monitor_timeout_->Start(base::TimeDelta::FromMilliseconds( RenderViewHostImpl::kUnloadTimeoutMS)); } CHECK(proxy); if (IsRenderFrameLive()) { FrameReplicationState replication_state = proxy->frame_tree_node()->current_replication_state(); Send(new FrameMsg_SwapOut(routing_id_, proxy->GetRoutingID(), is_loading, replication_state)); } if (web_ui()) web_ui()->RenderFrameHostSwappingOut(); is_waiting_for_swapout_ack_ = true; if (frame_tree_node_->IsMainFrame()) render_view_host_->SetIsActive(false); } Commit Message: Apply ExtensionNavigationThrottle filesystem/blob checks to all frames. BUG=836858 Change-Id: I34333a72501129fd40b5a9aa6378c9f35f1e7fc2 Reviewed-on: https://chromium-review.googlesource.com/1028511 Reviewed-by: Devlin <[email protected]> Reviewed-by: Alex Moshchuk <[email protected]> Reviewed-by: Nick Carter <[email protected]> Commit-Queue: Charlie Reis <[email protected]> Cr-Commit-Position: refs/heads/master@{#553867} CWE ID: CWE-20 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: my_object_rec_arrays (MyObject *obj, GPtrArray *in, GPtrArray **ret, GError **error) { char **strs; GArray *ints; guint v_UINT; if (in->len != 2) { g_set_error (error, MY_OBJECT_ERROR, MY_OBJECT_ERROR_FOO, "invalid array len"); return FALSE; } strs = g_ptr_array_index (in, 0); if (!*strs || strcmp (*strs, "foo")) { g_set_error (error, MY_OBJECT_ERROR, MY_OBJECT_ERROR_FOO, "invalid string 0"); return FALSE; } strs++; if (!*strs || strcmp (*strs, "bar")) { g_set_error (error, MY_OBJECT_ERROR, MY_OBJECT_ERROR_FOO, "invalid string 1"); return FALSE; } strs++; if (*strs) { g_set_error (error, MY_OBJECT_ERROR, MY_OBJECT_ERROR_FOO, "invalid string array len in pos 0"); return FALSE; } strs = g_ptr_array_index (in, 1); if (!*strs || strcmp (*strs, "baz")) { g_set_error (error, MY_OBJECT_ERROR, MY_OBJECT_ERROR_FOO, "invalid string 0"); return FALSE; } strs++; if (!*strs || strcmp (*strs, "whee")) { g_set_error (error, MY_OBJECT_ERROR, MY_OBJECT_ERROR_FOO, "invalid string 1"); return FALSE; } strs++; if (!*strs || strcmp (*strs, "moo")) { g_set_error (error, MY_OBJECT_ERROR, MY_OBJECT_ERROR_FOO, "invalid string 2"); return FALSE; } strs++; if (*strs) { g_set_error (error, MY_OBJECT_ERROR, MY_OBJECT_ERROR_FOO, "invalid string array len in pos 1"); return FALSE; } *ret = g_ptr_array_new (); ints = g_array_new (TRUE, TRUE, sizeof (guint)); v_UINT = 10; g_array_append_val (ints, v_UINT); v_UINT = 42; g_array_append_val (ints, v_UINT); v_UINT = 27; g_array_append_val (ints, v_UINT); g_ptr_array_add (*ret, ints); ints = g_array_new (TRUE, TRUE, sizeof (guint)); v_UINT = 30; g_array_append_val (ints, v_UINT); g_ptr_array_add (*ret, ints); return TRUE; } Commit Message: CWE ID: CWE-264 Target: 1 Example 2: Code: GahpClient::check_pending_timeout(const char *,const char *) { if ( pending_reqid == 0 ) { return false; } if ( pending_submitted_to_gahp == false ) { return false; } if ( pending_timeout && (time(NULL) > pending_timeout) ) { clear_pending(); // we no longer want to hear about it... return true; } return false; } Commit Message: CWE ID: CWE-134 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: bool Textfield::CanHandleAccelerators() const { return GetRenderText()->focused() && View::CanHandleAccelerators(); } Commit Message: MacViews: Enable secure text input for password Textfields. In Cocoa the NSTextInputContext automatically enables secure text input when activated and it's in the secure text entry mode. RenderWidgetHostViewMac did the similar thing for ages following the WebKit example. views::Textfield needs to do the same thing in a fashion that's sycnrhonized with RenderWidgetHostViewMac, otherwise the race conditions are possible when the Textfield gets focus, activates the secure text input mode and the RWHVM loses focus immediately afterwards and disables the secure text input instead of leaving it in the enabled state. BUG=818133,677220 Change-Id: I6db6c4b59e4a1a72cbb7f8c7056f71b04a3df08b Reviewed-on: https://chromium-review.googlesource.com/943064 Commit-Queue: Michail Pishchagin <[email protected]> Reviewed-by: Pavel Feldman <[email protected]> Reviewed-by: Avi Drissman <[email protected]> Reviewed-by: Peter Kasting <[email protected]> Cr-Commit-Position: refs/heads/master@{#542517} CWE ID: Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void PageInfo::ComputeUIInputs( const GURL& url, security_state::SecurityLevel security_level, const security_state::VisibleSecurityState& visible_security_state) { #if !defined(OS_ANDROID) DCHECK(!url.SchemeIs(content::kChromeUIScheme) && !url.SchemeIs(content::kChromeDevToolsScheme) && !url.SchemeIs(content::kViewSourceScheme) && !url.SchemeIs(content_settings::kExtensionScheme)); #endif bool is_chrome_ui_native_scheme = false; #if defined(OS_ANDROID) is_chrome_ui_native_scheme = url.SchemeIs(chrome::kChromeUINativeScheme); #endif security_level_ = security_level; if (url.SchemeIs(url::kAboutScheme)) { DCHECK_EQ(url::kAboutBlankURL, url.spec()); site_identity_status_ = SITE_IDENTITY_STATUS_NO_CERT; site_details_message_ = l10n_util::GetStringUTF16(IDS_PAGE_INFO_SECURITY_TAB_INSECURE_IDENTITY); site_connection_status_ = SITE_CONNECTION_STATUS_UNENCRYPTED; site_connection_details_ = l10n_util::GetStringFUTF16( IDS_PAGE_INFO_SECURITY_TAB_NOT_ENCRYPTED_CONNECTION_TEXT, UTF8ToUTF16(url.spec())); return; } if (url.SchemeIs(content::kChromeUIScheme) || is_chrome_ui_native_scheme) { site_identity_status_ = SITE_IDENTITY_STATUS_INTERNAL_PAGE; site_details_message_ = l10n_util::GetStringUTF16(IDS_PAGE_INFO_INTERNAL_PAGE); site_connection_status_ = SITE_CONNECTION_STATUS_INTERNAL_PAGE; return; } certificate_ = visible_security_state.certificate; if (certificate_ && (!net::IsCertStatusError(visible_security_state.cert_status) || net::IsCertStatusMinorError(visible_security_state.cert_status))) { if (security_level == security_state::SECURE_WITH_POLICY_INSTALLED_CERT) { #if defined(OS_CHROMEOS) site_identity_status_ = SITE_IDENTITY_STATUS_ADMIN_PROVIDED_CERT; site_details_message_ = l10n_util::GetStringFUTF16( IDS_CERT_POLICY_PROVIDED_CERT_MESSAGE, UTF8ToUTF16(url.host())); #else DCHECK(false) << "Policy certificates exist only on ChromeOS"; #endif } else if (net::IsCertStatusMinorError( visible_security_state.cert_status)) { site_identity_status_ = SITE_IDENTITY_STATUS_CERT_REVOCATION_UNKNOWN; base::string16 issuer_name( UTF8ToUTF16(certificate_->issuer().GetDisplayName())); if (issuer_name.empty()) { issuer_name.assign(l10n_util::GetStringUTF16( IDS_PAGE_INFO_SECURITY_TAB_UNKNOWN_PARTY)); } site_details_message_.assign(l10n_util::GetStringFUTF16( IDS_PAGE_INFO_SECURITY_TAB_SECURE_IDENTITY_VERIFIED, issuer_name)); site_details_message_ += ASCIIToUTF16("\n\n"); if (visible_security_state.cert_status & net::CERT_STATUS_UNABLE_TO_CHECK_REVOCATION) { site_details_message_ += l10n_util::GetStringUTF16( IDS_PAGE_INFO_SECURITY_TAB_UNABLE_TO_CHECK_REVOCATION); } else if (visible_security_state.cert_status & net::CERT_STATUS_NO_REVOCATION_MECHANISM) { site_details_message_ += l10n_util::GetStringUTF16( IDS_PAGE_INFO_SECURITY_TAB_NO_REVOCATION_MECHANISM); } else { NOTREACHED() << "Need to specify string for this warning"; } } else { if (visible_security_state.cert_status & net::CERT_STATUS_IS_EV) { site_identity_status_ = SITE_IDENTITY_STATUS_EV_CERT; DCHECK(!certificate_->subject().organization_names.empty()); organization_name_ = UTF8ToUTF16(certificate_->subject().organization_names[0]); DCHECK(!certificate_->subject().locality_name.empty()); DCHECK(!certificate_->subject().country_name.empty()); site_details_message_.assign(l10n_util::GetStringFUTF16( IDS_PAGE_INFO_SECURITY_TAB_SECURE_IDENTITY_EV_VERIFIED, organization_name_, UTF8ToUTF16(certificate_->subject().country_name))); } else { site_identity_status_ = SITE_IDENTITY_STATUS_CERT; base::string16 issuer_name( UTF8ToUTF16(certificate_->issuer().GetDisplayName())); if (issuer_name.empty()) { issuer_name.assign(l10n_util::GetStringUTF16( IDS_PAGE_INFO_SECURITY_TAB_UNKNOWN_PARTY)); } site_details_message_.assign(l10n_util::GetStringFUTF16( IDS_PAGE_INFO_SECURITY_TAB_SECURE_IDENTITY_VERIFIED, issuer_name)); } if (security_state::IsSHA1InChain(visible_security_state)) { site_identity_status_ = SITE_IDENTITY_STATUS_DEPRECATED_SIGNATURE_ALGORITHM; site_details_message_ += UTF8ToUTF16("\n\n") + l10n_util::GetStringUTF16( IDS_PAGE_INFO_SECURITY_TAB_DEPRECATED_SIGNATURE_ALGORITHM); } } } else { site_details_message_.assign(l10n_util::GetStringUTF16( IDS_PAGE_INFO_SECURITY_TAB_INSECURE_IDENTITY)); if (!security_state::IsSchemeCryptographic(visible_security_state.url) || !visible_security_state.certificate) { site_identity_status_ = SITE_IDENTITY_STATUS_NO_CERT; } else { site_identity_status_ = SITE_IDENTITY_STATUS_ERROR; } const base::string16 bullet = UTF8ToUTF16("\n • "); std::vector<ssl_errors::ErrorInfo> errors; ssl_errors::ErrorInfo::GetErrorsForCertStatus( certificate_, visible_security_state.cert_status, url, &errors); for (size_t i = 0; i < errors.size(); ++i) { site_details_message_ += bullet; site_details_message_ += errors[i].short_description(); } if (visible_security_state.cert_status & net::CERT_STATUS_NON_UNIQUE_NAME) { site_details_message_ += ASCIIToUTF16("\n\n"); site_details_message_ += l10n_util::GetStringUTF16(IDS_PAGE_INFO_SECURITY_TAB_NON_UNIQUE_NAME); } } if (visible_security_state.malicious_content_status != security_state::MALICIOUS_CONTENT_STATUS_NONE) { GetSafeBrowsingStatusByMaliciousContentStatus( visible_security_state.malicious_content_status, &safe_browsing_status_, &site_details_message_); #if defined(FULL_SAFE_BROWSING) bool old_show_change_pw_buttons = show_change_password_buttons_; #endif show_change_password_buttons_ = (visible_security_state.malicious_content_status == security_state::MALICIOUS_CONTENT_STATUS_SIGN_IN_PASSWORD_REUSE || visible_security_state.malicious_content_status == security_state:: MALICIOUS_CONTENT_STATUS_ENTERPRISE_PASSWORD_REUSE); #if defined(FULL_SAFE_BROWSING) if (show_change_password_buttons_ && !old_show_change_pw_buttons) { RecordPasswordReuseEvent(); } #endif } site_connection_status_ = SITE_CONNECTION_STATUS_UNKNOWN; base::string16 subject_name(GetSimpleSiteName(url)); if (subject_name.empty()) { subject_name.assign( l10n_util::GetStringUTF16(IDS_PAGE_INFO_SECURITY_TAB_UNKNOWN_PARTY)); } if (!visible_security_state.certificate || !security_state::IsSchemeCryptographic(visible_security_state.url)) { site_connection_status_ = SITE_CONNECTION_STATUS_UNENCRYPTED; site_connection_details_.assign(l10n_util::GetStringFUTF16( IDS_PAGE_INFO_SECURITY_TAB_NOT_ENCRYPTED_CONNECTION_TEXT, subject_name)); } else if (!visible_security_state.connection_info_initialized) { DCHECK_NE(security_level, security_state::NONE); site_connection_status_ = SITE_CONNECTION_STATUS_ENCRYPTED_ERROR; } else { site_connection_status_ = SITE_CONNECTION_STATUS_ENCRYPTED; if (net::ObsoleteSSLStatus( visible_security_state.connection_status, visible_security_state.peer_signature_algorithm) == net::OBSOLETE_SSL_NONE) { site_connection_details_.assign(l10n_util::GetStringFUTF16( IDS_PAGE_INFO_SECURITY_TAB_ENCRYPTED_CONNECTION_TEXT, subject_name)); } else { site_connection_details_.assign(l10n_util::GetStringFUTF16( IDS_PAGE_INFO_SECURITY_TAB_WEAK_ENCRYPTION_CONNECTION_TEXT, subject_name)); } ReportAnyInsecureContent(visible_security_state, &site_connection_status_, &site_connection_details_); } uint16_t cipher_suite = net::SSLConnectionStatusToCipherSuite( visible_security_state.connection_status); if (visible_security_state.connection_info_initialized && cipher_suite) { int ssl_version = net::SSLConnectionStatusToVersion( visible_security_state.connection_status); const char* ssl_version_str; net::SSLVersionToString(&ssl_version_str, ssl_version); site_connection_details_ += ASCIIToUTF16("\n\n"); site_connection_details_ += l10n_util::GetStringFUTF16( IDS_PAGE_INFO_SECURITY_TAB_SSL_VERSION, ASCIIToUTF16(ssl_version_str)); const char *key_exchange, *cipher, *mac; bool is_aead, is_tls13; net::SSLCipherSuiteToStrings(&key_exchange, &cipher, &mac, &is_aead, &is_tls13, cipher_suite); site_connection_details_ += ASCIIToUTF16("\n\n"); if (is_aead) { if (is_tls13) { key_exchange = SSL_get_curve_name(visible_security_state.key_exchange_group); if (!key_exchange) { NOTREACHED(); key_exchange = ""; } } site_connection_details_ += l10n_util::GetStringFUTF16( IDS_PAGE_INFO_SECURITY_TAB_ENCRYPTION_DETAILS_AEAD, ASCIIToUTF16(cipher), ASCIIToUTF16(key_exchange)); } else { site_connection_details_ += l10n_util::GetStringFUTF16( IDS_PAGE_INFO_SECURITY_TAB_ENCRYPTION_DETAILS, ASCIIToUTF16(cipher), ASCIIToUTF16(mac), ASCIIToUTF16(key_exchange)); } } ChromeSSLHostStateDelegate* delegate = ChromeSSLHostStateDelegateFactory::GetForProfile(profile_); DCHECK(delegate); show_ssl_decision_revoke_button_ = delegate->HasAllowException(url.host()) && visible_security_state.malicious_content_status == security_state::MALICIOUS_CONTENT_STATUS_NONE; } Commit Message: Revert "PageInfo: decouple safe browsing and TLS statii." This reverts commit ee95bc44021230127c7e6e9a8cf9d3820760f77c. Reason for revert: suspect causing unit_tests failure on Linux MSAN Tests: https://ci.chromium.org/p/chromium/builders/ci/Linux%20MSan%20Tests/17649 PageInfoBubbleViewTest.ChangingFlashSettingForSiteIsRemembered PageInfoBubbleViewTest.EnsureCloseCallback PageInfoBubbleViewTest.NotificationPermissionRevokeUkm PageInfoBubbleViewTest.OpenPageInfoBubbleAfterNavigationStart PageInfoBubbleViewTest.SetPermissionInfo PageInfoBubbleViewTest.SetPermissionInfoForUsbGuard PageInfoBubbleViewTest.SetPermissionInfoWithPolicyUsbDevices PageInfoBubbleViewTest.SetPermissionInfoWithUsbDevice PageInfoBubbleViewTest.SetPermissionInfoWithUserAndPolicyUsbDevices PageInfoBubbleViewTest.UpdatingSiteDataRetainsLayout https://logs.chromium.org/logs/chromium/buildbucket/cr-buildbucket.appspot.com/8909718923797040064/+/steps/unit_tests/0/logs/Deterministic_failure:_PageInfoBubbleViewTest.ChangingFlashSettingForSiteIsRemembered__status_CRASH_/0 [ RUN ] PageInfoBubbleViewTest.ChangingFlashSettingForSiteIsRemembered ==9056==WARNING: MemorySanitizer: use-of-uninitialized-value #0 0x561baaab15ec in PageInfoUI::GetSecurityDescription(PageInfoUI::IdentityInfo const&) const ./../../chrome/browser/ui/page_info/page_info_ui.cc:250:3 #1 0x561bab6a1548 in PageInfoBubbleView::SetIdentityInfo(PageInfoUI::IdentityInfo const&) ./../../chrome/browser/ui/views/page_info/page_info_bubble_view.cc:802:7 #2 0x561baaaab3bb in PageInfo::PresentSiteIdentity() ./../../chrome/browser/ui/page_info/page_info.cc:969:8 #3 0x561baaaa0a21 in PageInfo::PageInfo(PageInfoUI*, Profile*, TabSpecificContentSettings*, content::WebContents*, GURL const&, security_state::SecurityLevel, security_state::VisibleSecurityState const&) ./../../chrome/browser/ui/page_info/page_info.cc:344:3 #4 0x561bab69b6dd in PageInfoBubbleView::PageInfoBubbleView(views::View*, gfx::Rect const&, aura::Window*, Profile*, content::WebContents*, GURL const&, security_state::SecurityLevel, security_state::VisibleSecurityState const&, base::OnceCallback<void (views::Widget::ClosedReason, bool)>) ./../../chrome/browser/ui/views/page_info/page_info_bubble_view.cc:576:24 ... Original change's description: > PageInfo: decouple safe browsing and TLS statii. > > Previously, the Page Info bubble maintained a single variable to > identify all reasons that a page might have a non-standard status. This > lead to the display logic making assumptions about, for instance, the > validity of a certificate when the page was flagged by Safe Browsing. > > This CL separates out the Safe Browsing status from the site identity > status so that the page info bubble can inform the user that the site's > certificate is invalid, even if it's also flagged by Safe Browsing. > > Bug: 869925 > Change-Id: I34107225b4206c8f32771ccd75e9367668d0a72b > Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1662537 > Reviewed-by: Mustafa Emre Acer <[email protected]> > Reviewed-by: Bret Sepulveda <[email protected]> > Auto-Submit: Joe DeBlasio <[email protected]> > Commit-Queue: Joe DeBlasio <[email protected]> > Cr-Commit-Position: refs/heads/master@{#671847} [email protected],[email protected],[email protected] Change-Id: I8be652952e7276bcc9266124693352e467159cc4 No-Presubmit: true No-Tree-Checks: true No-Try: true Bug: 869925 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1673985 Reviewed-by: Takashi Sakamoto <[email protected]> Commit-Queue: Takashi Sakamoto <[email protected]> Cr-Commit-Position: refs/heads/master@{#671932} CWE ID: CWE-311 Target: 1 Example 2: Code: String Document::visibilityState() const { return pageVisibilityStateString(pageVisibilityState()); } Commit Message: Change Document::detach() to RELEASE_ASSERT all subframes are gone. BUG=556724,577105 Review URL: https://codereview.chromium.org/1667573002 Cr-Commit-Position: refs/heads/master@{#373642} CWE ID: CWE-264 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int kvm_vcpu_ioctl_enable_cap(struct kvm_vcpu *vcpu, struct kvm_enable_cap *cap) { int r; if (cap->flags) return -EINVAL; switch (cap->cap) { case KVM_CAP_PPC_OSI: r = 0; vcpu->arch.osi_enabled = true; break; case KVM_CAP_PPC_PAPR: r = 0; vcpu->arch.papr_enabled = true; break; case KVM_CAP_PPC_EPR: r = 0; if (cap->args[0]) vcpu->arch.epr_flags |= KVMPPC_EPR_USER; else vcpu->arch.epr_flags &= ~KVMPPC_EPR_USER; break; #ifdef CONFIG_BOOKE case KVM_CAP_PPC_BOOKE_WATCHDOG: r = 0; vcpu->arch.watchdog_enabled = true; break; #endif #if defined(CONFIG_KVM_E500V2) || defined(CONFIG_KVM_E500MC) case KVM_CAP_SW_TLB: { struct kvm_config_tlb cfg; void __user *user_ptr = (void __user *)(uintptr_t)cap->args[0]; r = -EFAULT; if (copy_from_user(&cfg, user_ptr, sizeof(cfg))) break; r = kvm_vcpu_ioctl_config_tlb(vcpu, &cfg); break; } #endif #ifdef CONFIG_KVM_MPIC case KVM_CAP_IRQ_MPIC: { struct fd f; struct kvm_device *dev; r = -EBADF; f = fdget(cap->args[0]); if (!f.file) break; r = -EPERM; dev = kvm_device_from_filp(f.file); if (dev) r = kvmppc_mpic_connect_vcpu(dev, vcpu, cap->args[1]); fdput(f); break; } #endif #ifdef CONFIG_KVM_XICS case KVM_CAP_IRQ_XICS: { struct fd f; struct kvm_device *dev; r = -EBADF; f = fdget(cap->args[0]); if (!f.file) break; r = -EPERM; dev = kvm_device_from_filp(f.file); if (dev) { if (xive_enabled()) r = kvmppc_xive_connect_vcpu(dev, vcpu, cap->args[1]); else r = kvmppc_xics_connect_vcpu(dev, vcpu, cap->args[1]); } fdput(f); break; } #endif /* CONFIG_KVM_XICS */ #ifdef CONFIG_KVM_BOOK3S_HV_POSSIBLE case KVM_CAP_PPC_FWNMI: r = -EINVAL; if (!is_kvmppc_hv_enabled(vcpu->kvm)) break; r = 0; vcpu->kvm->arch.fwnmi_enabled = true; break; #endif /* CONFIG_KVM_BOOK3S_HV_POSSIBLE */ default: r = -EINVAL; break; } if (!r) r = kvmppc_sanity_check(vcpu); return r; } Commit Message: KVM: PPC: Fix oops when checking KVM_CAP_PPC_HTM The following program causes a kernel oops: #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <sys/ioctl.h> #include <linux/kvm.h> main() { int fd = open("/dev/kvm", O_RDWR); ioctl(fd, KVM_CHECK_EXTENSION, KVM_CAP_PPC_HTM); } This happens because when using the global KVM fd with KVM_CHECK_EXTENSION, kvm_vm_ioctl_check_extension() gets called with a NULL kvm argument, which gets dereferenced in is_kvmppc_hv_enabled(). Spotted while reading the code. Let's use the hv_enabled fallback variable, like everywhere else in this function. Fixes: 23528bb21ee2 ("KVM: PPC: Introduce KVM_CAP_PPC_HTM") Cc: [email protected] # v4.7+ Signed-off-by: Greg Kurz <[email protected]> Reviewed-by: David Gibson <[email protected]> Reviewed-by: Thomas Huth <[email protected]> Signed-off-by: Paul Mackerras <[email protected]> CWE ID: CWE-476 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int tls1_enc(SSL *s, SSL3_RECORD *recs, unsigned int n_recs, int send) { EVP_CIPHER_CTX *ds; size_t reclen[SSL_MAX_PIPELINES]; unsigned char buf[SSL_MAX_PIPELINES][EVP_AEAD_TLS1_AAD_LEN]; int bs, i, j, k, pad = 0, ret, mac_size = 0; const EVP_CIPHER *enc; unsigned int ctr; if (send) { if (EVP_MD_CTX_md(s->write_hash)) { int n = EVP_MD_CTX_size(s->write_hash); OPENSSL_assert(n >= 0); } ds = s->enc_write_ctx; if (s->enc_write_ctx == NULL) enc = NULL; else { int ivlen; enc = EVP_CIPHER_CTX_cipher(s->enc_write_ctx); /* For TLSv1.1 and later explicit IV */ if (SSL_USE_EXPLICIT_IV(s) && EVP_CIPHER_mode(enc) == EVP_CIPH_CBC_MODE) ivlen = EVP_CIPHER_iv_length(enc); else ivlen = 0; if (ivlen > 1) { for (ctr = 0; ctr < n_recs; ctr++) { if (recs[ctr].data != recs[ctr].input) { /* * we can't write into the input stream: Can this ever * happen?? (steve) */ SSLerr(SSL_F_TLS1_ENC, ERR_R_INTERNAL_ERROR); return -1; } else if (RAND_bytes(recs[ctr].input, ivlen) <= 0) { SSLerr(SSL_F_TLS1_ENC, ERR_R_INTERNAL_ERROR); return -1; } } } } } else { if (EVP_MD_CTX_md(s->read_hash)) { int n = EVP_MD_CTX_size(s->read_hash); OPENSSL_assert(n >= 0); } ds = s->enc_read_ctx; if (s->enc_read_ctx == NULL) enc = NULL; else enc = EVP_CIPHER_CTX_cipher(s->enc_read_ctx); } if ((s->session == NULL) || (ds == NULL) || (enc == NULL)) { for (ctr = 0; ctr < n_recs; ctr++) { memmove(recs[ctr].data, recs[ctr].input, recs[ctr].length); recs[ctr].input = recs[ctr].data; } ret = 1; } else { bs = EVP_CIPHER_block_size(EVP_CIPHER_CTX_cipher(ds)); if (n_recs > 1) { if (!(EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(ds)) & EVP_CIPH_FLAG_PIPELINE)) { /* * We shouldn't have been called with pipeline data if the * cipher doesn't support pipelining */ SSLerr(SSL_F_TLS1_ENC, SSL_R_PIPELINE_FAILURE); return -1; } } for (ctr = 0; ctr < n_recs; ctr++) { reclen[ctr] = recs[ctr].length; if (EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(ds)) & EVP_CIPH_FLAG_AEAD_CIPHER) { unsigned char *seq; seq = send ? RECORD_LAYER_get_write_sequence(&s->rlayer) : RECORD_LAYER_get_read_sequence(&s->rlayer); if (SSL_IS_DTLS(s)) { /* DTLS does not support pipelining */ unsigned char dtlsseq[9], *p = dtlsseq; s2n(send ? DTLS_RECORD_LAYER_get_w_epoch(&s->rlayer) : DTLS_RECORD_LAYER_get_r_epoch(&s->rlayer), p); memcpy(p, &seq[2], 6); memcpy(buf[ctr], dtlsseq, 8); } else { memcpy(buf[ctr], seq, 8); for (i = 7; i >= 0; i--) { /* increment */ ++seq[i]; if (seq[i] != 0) break; } } buf[ctr][8] = recs[ctr].type; buf[ctr][9] = (unsigned char)(s->version >> 8); buf[ctr][10] = (unsigned char)(s->version); buf[ctr][11] = recs[ctr].length >> 8; buf[ctr][12] = recs[ctr].length & 0xff; pad = EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_AEAD_TLS1_AAD, EVP_AEAD_TLS1_AAD_LEN, buf[ctr]); if (pad <= 0) return -1; if (send) { reclen[ctr] += pad; recs[ctr].length += pad; } } else if ((bs != 1) && send) { i = bs - ((int)reclen[ctr] % bs); /* Add weird padding of upto 256 bytes */ /* we need to add 'i' padding bytes of value j */ j = i - 1; for (k = (int)reclen[ctr]; k < (int)(reclen[ctr] + i); k++) recs[ctr].input[k] = j; reclen[ctr] += i; recs[ctr].length += i; } if (!send) { if (reclen[ctr] == 0 || reclen[ctr] % bs != 0) return 0; } } if (n_recs > 1) { unsigned char *data[SSL_MAX_PIPELINES]; /* Set the output buffers */ for (ctr = 0; ctr < n_recs; ctr++) { data[ctr] = recs[ctr].data; } if (EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_SET_PIPELINE_OUTPUT_BUFS, n_recs, data) <= 0) { SSLerr(SSL_F_TLS1_ENC, SSL_R_PIPELINE_FAILURE); } /* Set the input buffers */ for (ctr = 0; ctr < n_recs; ctr++) { data[ctr] = recs[ctr].input; } if (EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_SET_PIPELINE_INPUT_BUFS, n_recs, data) <= 0 || EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_SET_PIPELINE_INPUT_LENS, n_recs, reclen) <= 0) { SSLerr(SSL_F_TLS1_ENC, SSL_R_PIPELINE_FAILURE); return -1; } } i = EVP_Cipher(ds, recs[0].data, recs[0].input, reclen[0]); if ((EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(ds)) & EVP_CIPH_FLAG_CUSTOM_CIPHER) ? (i < 0) : (i == 0)) return -1; /* AEAD can fail to verify MAC */ if (send == 0) { if (EVP_CIPHER_mode(enc) == EVP_CIPH_GCM_MODE) { for (ctr = 0; ctr < n_recs; ctr++) { recs[ctr].data += EVP_GCM_TLS_EXPLICIT_IV_LEN; recs[ctr].input += EVP_GCM_TLS_EXPLICIT_IV_LEN; recs[ctr].length -= EVP_GCM_TLS_EXPLICIT_IV_LEN; } } else if (EVP_CIPHER_mode(enc) == EVP_CIPH_CCM_MODE) { for (ctr = 0; ctr < n_recs; ctr++) { recs[ctr].data += EVP_CCM_TLS_EXPLICIT_IV_LEN; recs[ctr].input += EVP_CCM_TLS_EXPLICIT_IV_LEN; recs[ctr].length -= EVP_CCM_TLS_EXPLICIT_IV_LEN; } } } ret = 1; if (!SSL_USE_ETM(s) && EVP_MD_CTX_md(s->read_hash) != NULL) mac_size = EVP_MD_CTX_size(s->read_hash); if ((bs != 1) && !send) { int tmpret; for (ctr = 0; ctr < n_recs; ctr++) { tmpret = tls1_cbc_remove_padding(s, &recs[ctr], bs, mac_size); /* * If tmpret == 0 then this means publicly invalid so we can * short circuit things here. Otherwise we must respect constant * time behaviour. */ if (tmpret == 0) return 0; ret = constant_time_select_int(constant_time_eq_int(tmpret, 1), ret, -1); } } if (pad && !send) { for (ctr = 0; ctr < n_recs; ctr++) { recs[ctr].length -= pad; } } } return ret; } Commit Message: Don't change the state of the ETM flags until CCS processing Changing the ciphersuite during a renegotiation can result in a crash leading to a DoS attack. ETM has not been implemented in 1.1.0 for DTLS so this is TLS only. The problem is caused by changing the flag indicating whether to use ETM or not immediately on negotiation of ETM, rather than at CCS. Therefore, during a renegotiation, if the ETM state is changing (usually due to a change of ciphersuite), then an error/crash will occur. Due to the fact that there are separate CCS messages for read and write we actually now need two flags to determine whether to use ETM or not. CVE-2017-3733 Reviewed-by: Richard Levitte <[email protected]> CWE ID: CWE-20 Target: 1 Example 2: Code: static bool ieee80211_tx_frags(struct ieee80211_local *local, struct ieee80211_vif *vif, struct ieee80211_sta *sta, struct sk_buff_head *skbs, bool txpending) { struct ieee80211_tx_control control; struct sk_buff *skb, *tmp; unsigned long flags; skb_queue_walk_safe(skbs, skb, tmp) { struct ieee80211_tx_info *info = IEEE80211_SKB_CB(skb); int q = info->hw_queue; #ifdef CONFIG_MAC80211_VERBOSE_DEBUG if (WARN_ON_ONCE(q >= local->hw.queues)) { __skb_unlink(skb, skbs); ieee80211_free_txskb(&local->hw, skb); continue; } #endif spin_lock_irqsave(&local->queue_stop_reason_lock, flags); if (local->queue_stop_reasons[q] || (!txpending && !skb_queue_empty(&local->pending[q]))) { if (unlikely(info->flags & IEEE80211_TX_INTFL_OFFCHAN_TX_OK)) { if (local->queue_stop_reasons[q] & ~BIT(IEEE80211_QUEUE_STOP_REASON_OFFCHANNEL)) { /* * Drop off-channel frames if queues * are stopped for any reason other * than off-channel operation. Never * queue them. */ spin_unlock_irqrestore( &local->queue_stop_reason_lock, flags); ieee80211_purge_tx_queue(&local->hw, skbs); return true; } } else { /* * Since queue is stopped, queue up frames for * later transmission from the tx-pending * tasklet when the queue is woken again. */ if (txpending) skb_queue_splice_init(skbs, &local->pending[q]); else skb_queue_splice_tail_init(skbs, &local->pending[q]); spin_unlock_irqrestore(&local->queue_stop_reason_lock, flags); return false; } } spin_unlock_irqrestore(&local->queue_stop_reason_lock, flags); info->control.vif = vif; control.sta = sta; __skb_unlink(skb, skbs); drv_tx(local, &control, skb); } return true; } Commit Message: mac80211: fix fragmentation code, particularly for encryption The "new" fragmentation code (since my rewrite almost 5 years ago) erroneously sets skb->len rather than using skb_trim() to adjust the length of the first fragment after copying out all the others. This leaves the skb tail pointer pointing to after where the data originally ended, and thus causes the encryption MIC to be written at that point, rather than where it belongs: immediately after the data. The impact of this is that if software encryption is done, then a) encryption doesn't work for the first fragment, the connection becomes unusable as the first fragment will never be properly verified at the receiver, the MIC is practically guaranteed to be wrong b) we leak up to 8 bytes of plaintext (!) of the packet out into the air This is only mitigated by the fact that many devices are capable of doing encryption in hardware, in which case this can't happen as the tail pointer is irrelevant in that case. Additionally, fragmentation is not used very frequently and would normally have to be configured manually. Fix this by using skb_trim() properly. Cc: [email protected] Fixes: 2de8e0d999b8 ("mac80211: rewrite fragmentation") Reported-by: Jouni Malinen <[email protected]> Signed-off-by: Johannes Berg <[email protected]> CWE ID: CWE-200 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void RTCSessionDescriptionRequestImpl::requestSucceeded(PassRefPtr<RTCSessionDescriptionDescriptor> descriptor) { if (m_successCallback) { RefPtr<RTCSessionDescription> sessionDescription = RTCSessionDescription::create(descriptor); m_successCallback->handleEvent(sessionDescription.get()); } clear(); } Commit Message: Unreviewed, rolling out r127612, r127660, and r127664. http://trac.webkit.org/changeset/127612 http://trac.webkit.org/changeset/127660 http://trac.webkit.org/changeset/127664 https://bugs.webkit.org/show_bug.cgi?id=95920 Source/Platform: * Platform.gypi: * chromium/public/WebRTCPeerConnectionHandler.h: (WebKit): (WebRTCPeerConnectionHandler): * chromium/public/WebRTCVoidRequest.h: Removed. Source/WebCore: * CMakeLists.txt: * GNUmakefile.list.am: * Modules/mediastream/RTCErrorCallback.h: (WebCore): (RTCErrorCallback): * Modules/mediastream/RTCErrorCallback.idl: * Modules/mediastream/RTCPeerConnection.cpp: (WebCore::RTCPeerConnection::createOffer): * Modules/mediastream/RTCPeerConnection.h: (WebCore): (RTCPeerConnection): * Modules/mediastream/RTCPeerConnection.idl: * Modules/mediastream/RTCSessionDescriptionCallback.h: (WebCore): (RTCSessionDescriptionCallback): * Modules/mediastream/RTCSessionDescriptionCallback.idl: * Modules/mediastream/RTCSessionDescriptionRequestImpl.cpp: (WebCore::RTCSessionDescriptionRequestImpl::create): (WebCore::RTCSessionDescriptionRequestImpl::RTCSessionDescriptionRequestImpl): (WebCore::RTCSessionDescriptionRequestImpl::requestSucceeded): (WebCore::RTCSessionDescriptionRequestImpl::requestFailed): (WebCore::RTCSessionDescriptionRequestImpl::clear): * Modules/mediastream/RTCSessionDescriptionRequestImpl.h: (RTCSessionDescriptionRequestImpl): * Modules/mediastream/RTCVoidRequestImpl.cpp: Removed. * Modules/mediastream/RTCVoidRequestImpl.h: Removed. * WebCore.gypi: * platform/chromium/support/WebRTCVoidRequest.cpp: Removed. * platform/mediastream/RTCPeerConnectionHandler.cpp: (RTCPeerConnectionHandlerDummy): (WebCore::RTCPeerConnectionHandlerDummy::RTCPeerConnectionHandlerDummy): * platform/mediastream/RTCPeerConnectionHandler.h: (WebCore): (WebCore::RTCPeerConnectionHandler::~RTCPeerConnectionHandler): (RTCPeerConnectionHandler): (WebCore::RTCPeerConnectionHandler::RTCPeerConnectionHandler): * platform/mediastream/RTCVoidRequest.h: Removed. * platform/mediastream/chromium/RTCPeerConnectionHandlerChromium.cpp: * platform/mediastream/chromium/RTCPeerConnectionHandlerChromium.h: (RTCPeerConnectionHandlerChromium): Tools: * DumpRenderTree/chromium/MockWebRTCPeerConnectionHandler.cpp: (MockWebRTCPeerConnectionHandler::SuccessCallbackTask::SuccessCallbackTask): (MockWebRTCPeerConnectionHandler::SuccessCallbackTask::runIfValid): (MockWebRTCPeerConnectionHandler::FailureCallbackTask::FailureCallbackTask): (MockWebRTCPeerConnectionHandler::FailureCallbackTask::runIfValid): (MockWebRTCPeerConnectionHandler::createOffer): * DumpRenderTree/chromium/MockWebRTCPeerConnectionHandler.h: (MockWebRTCPeerConnectionHandler): (SuccessCallbackTask): (FailureCallbackTask): LayoutTests: * fast/mediastream/RTCPeerConnection-createOffer.html: * fast/mediastream/RTCPeerConnection-localDescription-expected.txt: Removed. * fast/mediastream/RTCPeerConnection-localDescription.html: Removed. * fast/mediastream/RTCPeerConnection-remoteDescription-expected.txt: Removed. * fast/mediastream/RTCPeerConnection-remoteDescription.html: Removed. git-svn-id: svn://svn.chromium.org/blink/trunk@127679 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-20 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int vnc_hextile_send_framebuffer_update(VncState *vs, int x, int y, int w, int h) { int i, j; int has_fg, has_bg; uint8_t *last_fg, *last_bg; VncDisplay *vd = vs->vd; last_fg = (uint8_t *) g_malloc(vd->server->pf.bytes_per_pixel); last_bg = (uint8_t *) g_malloc(vd->server->pf.bytes_per_pixel); has_fg = has_bg = 0; for (j = y; j < (y + h); j += 16) { for (i = x; i < (x + w); i += 16) { for (i = x; i < (x + w); i += 16) { vs->hextile.send_tile(vs, i, j, MIN(16, x + w - i), MIN(16, y + h - j), last_bg, last_fg, &has_bg, &has_fg); } } g_free(last_fg); g_free(last_bg); return 1; } void vnc_hextile_set_pixel_conversion(VncState *vs, int generic) { if (!generic) { switch (vs->ds->surface->pf.bits_per_pixel) { case 8: vs->hextile.send_tile = send_hextile_tile_8; break; case 16: vs->hextile.send_tile = send_hextile_tile_16; break; case 32: vs->hextile.send_tile = send_hextile_tile_32; break; } } else { switch (vs->ds->surface->pf.bits_per_pixel) { case 8: vs->hextile.send_tile = send_hextile_tile_generic_8; break; case 16: vs->hextile.send_tile = send_hextile_tile_generic_16; break; case 32: vs->hextile.send_tile = send_hextile_tile_generic_32; break; } } } } Commit Message: CWE ID: CWE-125 Target: 1 Example 2: Code: hook_exec_start () { hook_exec_recursion++; } Commit Message: CWE ID: CWE-20 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: PHPAPI char *php_escape_shell_arg(char *str) { int x, y = 0, l = strlen(str); char *cmd; size_t estimate = (4 * l) + 3; TSRMLS_FETCH(); cmd = safe_emalloc(4, l, 3); /* worst case */ #ifdef PHP_WIN32 cmd[y++] = '"'; #else cmd[y++] = '\''; #endif for (x = 0; x < l; x++) { int mb_len = php_mblen(str + x, (l - x)); /* skip non-valid multibyte characters */ if (mb_len < 0) { continue; } else if (mb_len > 1) { memcpy(cmd + y, str + x, mb_len); y += mb_len; x += mb_len - 1; continue; } switch (str[x]) { #ifdef PHP_WIN32 case '"': case '%': cmd[y++] = ' '; break; #else case '\'': cmd[y++] = '\''; cmd[y++] = '\\'; cmd[y++] = '\''; #endif /* fall-through */ default: cmd[y++] = str[x]; } } #ifdef PHP_WIN32 cmd[y++] = '"'; #else cmd[y++] = '\''; return cmd; } Commit Message: CWE ID: CWE-78 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void RenderWidgetHostViewAura::AdjustSurfaceProtection() { bool surface_is_protected = current_surface_ || !host_->is_hidden() || (current_surface_is_protected_ && (pending_thumbnail_tasks_ > 0 || current_surface_in_use_by_compositor_)); if (current_surface_is_protected_ == surface_is_protected) return; current_surface_is_protected_ = surface_is_protected; ++protection_state_id_; if (!surface_route_id_ || !shared_surface_handle_.parent_gpu_process_id) return; RenderWidgetHostImpl::SendFrontSurfaceIsProtected( surface_is_protected, protection_state_id_, surface_route_id_, shared_surface_handle_.parent_gpu_process_id); } Commit Message: Implement TextureImageTransportSurface using texture mailbox This has a couple of advantages: - allow tearing down and recreating the UI parent context without losing the renderer contexts - do not require a context to be able to generate textures when creating the GLSurfaceHandle - clearer ownership semantics that potentially allows for more robust and easier lost context handling/thumbnailing/etc., since a texture is at any given time owned by either: UI parent, mailbox, or TextureImageTransportSurface - simplify frontbuffer protection logic; the frontbuffer textures are now owned by RWHV where they are refcounted The TextureImageTransportSurface informs RenderWidgetHostView of the mailbox names for the front- and backbuffer textures by associating them with a surface_handle (1 or 2) in the AcceleratedSurfaceNew message. During SwapBuffers() or PostSubBuffer() cycles, it then uses produceTextureCHROMIUM() and consumeTextureCHROMIUM() to transfer ownership between renderer and browser compositor. RWHV sends back the surface_handle of the buffer being returned with the Swap ACK (or 0 if no buffer is being returned in which case TextureImageTransportSurface will allocate a new texture - note that this could be used to simply keep textures for thumbnailing). BUG=154815,139616 [email protected] Review URL: https://chromiumcodereview.appspot.com/11194042 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171569 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: Target: 1 Example 2: Code: XML_SetEndElementHandler(XML_Parser parser, XML_EndElementHandler end) { if (parser != NULL) parser->m_endElementHandler = end; } Commit Message: xmlparse.c: Fix extraction of namespace prefix from XML name (#186) CWE ID: CWE-611 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void ChromeRenderProcessObserver::OnWriteTcmallocHeapProfile( const FilePath::StringType& filename) { #if !defined(OS_WIN) if (!IsHeapProfilerRunning()) return; char* profile = GetHeapProfile(); if (!profile) { LOG(WARNING) << "Unable to get heap profile."; return; } std::string result(profile); delete profile; RenderThread::Get()->Send( new ChromeViewHostMsg_WriteTcmallocHeapProfile_ACK(filename, result)); #endif } Commit Message: Disable tcmalloc profile files. BUG=154983 [email protected] NOTRY=true Review URL: https://chromiumcodereview.appspot.com/11087041 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@161048 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: M_fs_error_t M_fs_delete(const char *path, M_bool remove_children, M_fs_progress_cb_t cb, M_uint32 progress_flags) { char *norm_path; char *join_path; M_fs_dir_entries_t *entries; const M_fs_dir_entry_t *entry; M_fs_info_t *info; M_fs_progress_t *progress = NULL; M_fs_dir_walk_filter_t filter = M_FS_DIR_WALK_FILTER_ALL|M_FS_DIR_WALK_FILTER_RECURSE; M_fs_type_t type; /* The result that will be returned by this function. */ M_fs_error_t res; /* The result of the delete itself. */ M_fs_error_t res2; size_t len; size_t i; M_uint64 total_size = 0; M_uint64 total_size_progress = 0; M_uint64 entry_size; /* Normalize the path we are going to delete so we have a valid path to pass around. */ res = M_fs_path_norm(&norm_path, path, M_FS_PATH_NORM_HOME, M_FS_SYSTEM_AUTO); if (res != M_FS_ERROR_SUCCESS) { M_free(norm_path); return res; } /* We need the info to determine if the path is valid and because we need the type. */ res = M_fs_info(&info, norm_path, M_FS_PATH_INFO_FLAGS_BASIC); if (res != M_FS_ERROR_SUCCESS) { M_free(norm_path); return res; } /* We must know the type because there are different functions for deleting a file and deleting a directory. */ type = M_fs_info_get_type(info); if (type == M_FS_TYPE_UNKNOWN) { M_fs_info_destroy(info); M_free(norm_path); return M_FS_ERROR_GENERIC; } /* Create a list of entries to store all the places we need to delete. */ entries = M_fs_dir_entries_create(); /* Recursive directory deletion isn't intuitive. We have to generate a list of files and delete the list. * We cannot delete as walk because not all file systems support that operation. The walk; delete; behavior * is undefined in Posix and HFS is known to skip files if the directory contents is modifies as the * directory is being walked. */ if (type == M_FS_TYPE_DIR && remove_children) { /* We need to read the basic info if the we need to report the size totals to the cb. */ if (cb && progress_flags & (M_FS_PROGRESS_SIZE_TOTAL|M_FS_PROGRESS_SIZE_CUR)) { filter |= M_FS_DIR_WALK_FILTER_READ_INFO_BASIC; } M_fs_dir_entries_merge(&entries, M_fs_dir_walk_entries(norm_path, NULL, filter)); } /* Add the original path to the list of entries. This may be the only entry in the list. We need to add * it after a potential walk because we can't delete a directory that isn't empty. * Note: * - The info will be owned by the entry and destroyed when it is destroyed. * - The basic info param doesn't get the info in this case. it's set so the info is stored in the entry. */ M_fs_dir_entries_insert(entries, M_fs_dir_walk_fill_entry(norm_path, NULL, type, info, M_FS_DIR_WALK_FILTER_READ_INFO_BASIC)); len = M_fs_dir_entries_len(entries); if (cb) { /* Create the progress. The same progress will be used for the entire operation. It will be updated with * new info as necessary. */ progress = M_fs_progress_create(); /* Get the total size of all files to be deleted if using the progress cb and size totals is set. */ if (progress_flags & M_FS_PROGRESS_SIZE_TOTAL) { for (i=0; i<len; i++) { entry = M_fs_dir_entries_at(entries, i); entry_size = M_fs_info_get_size(M_fs_dir_entry_get_info(entry)); total_size += entry_size; } /* Change the progress total size to reflect all entries. */ M_fs_progress_set_size_total(progress, total_size); } /* Change the progress count to reflect the count. */ if (progress_flags & M_FS_PROGRESS_COUNT) { M_fs_progress_set_count_total(progress, len); } } /* Assume success. Set error if there is an error. */ res = M_FS_ERROR_SUCCESS; /* Loop though all entries and delete. */ for (i=0; i<len; i++) { entry = M_fs_dir_entries_at(entries, i); join_path = M_fs_path_join(norm_path, M_fs_dir_entry_get_name(entry), M_FS_SYSTEM_AUTO); /* Call the appropriate delete function. */ if (M_fs_dir_entry_get_type(entry) == M_FS_TYPE_DIR) { res2 = M_fs_delete_dir(join_path); } else { res2 = M_fs_delete_file(join_path); } /* Set the return result to denote there was an error. The real error will be sent via the * progress callback for the entry. */ if (res2 != M_FS_ERROR_SUCCESS) { res = M_FS_ERROR_GENERIC; } /* Set the progress data for the entry. */ if (cb) { entry_size = M_fs_info_get_size(M_fs_dir_entry_get_info(entry)); total_size_progress += entry_size; M_fs_progress_set_path(progress, join_path); M_fs_progress_set_type(progress, M_fs_dir_entry_get_type(entry)); M_fs_progress_set_result(progress, res2); if (progress_flags & M_FS_PROGRESS_COUNT) { M_fs_progress_set_count(progress, i+1); } if (progress_flags & M_FS_PROGRESS_SIZE_TOTAL) { M_fs_progress_set_size_total_progess(progress, total_size_progress); } if (progress_flags & M_FS_PROGRESS_SIZE_CUR) { M_fs_progress_set_size_current(progress, entry_size); M_fs_progress_set_size_current_progress(progress, entry_size); } } M_free(join_path); /* Call the callback and stop processing if requested. */ if (cb && !cb(progress)) { res = M_FS_ERROR_CANCELED; break; } } M_fs_dir_entries_destroy(entries); M_fs_progress_destroy(progress); M_free(norm_path); return res; } Commit Message: fs: Don't try to delete the file when copying. It could cause a security issue if the file exists and doesn't allow other's to read/write. delete could allow someone to create the file and have access to the data. CWE ID: CWE-732 Target: 1 Example 2: Code: ScrollNode* LayerTreeHostImpl::OuterViewportScrollNode() const { if (!viewport()->MainScrollLayer()) return nullptr; ScrollTree& scroll_tree = active_tree_->property_trees()->scroll_tree; return scroll_tree.Node(viewport()->MainScrollLayer()->scroll_tree_index()); } 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 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void FragmentPaintPropertyTreeBuilder::SetNeedsPaintPropertyUpdateIfNeeded() { if (!object_.IsBox()) return; const LayoutBox& box = ToLayoutBox(object_); if (NeedsOverflowClip(box)) { bool had_overflow_clip = properties_ && properties_->OverflowClip(); if (had_overflow_clip == CanOmitOverflowClip(box)) box.GetMutableForPainting().SetNeedsPaintPropertyUpdate(); } if (box.Size() == box.PreviousSize()) return; const bool box_generates_property_nodes_for_mask_and_clip_path = RuntimeEnabledFeatures::SlimmingPaintV175Enabled() && (box.HasMask() || box.HasClipPath()); if (NeedsOverflowClip(box) || NeedsInnerBorderRadiusClip(box) || NeedsCssClip(box) || box.StyleRef().HasTransform() || NeedsPerspective(box) || box_generates_property_nodes_for_mask_and_clip_path) { box.GetMutableForPainting().SetNeedsPaintPropertyUpdate(); } if (box.HasClipPath()) box.GetMutableForPainting().InvalidateClipPathCache(); if (box.HasReflection()) { DCHECK(box.HasLayer()); box.Layer()->SetFilterOnEffectNodeDirty(); box.GetMutableForPainting().SetNeedsPaintPropertyUpdate(); } } 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: Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: OMX_ERRORTYPE SoftMP3::internalSetParameter( OMX_INDEXTYPE index, const OMX_PTR params) { switch (index) { case OMX_IndexParamStandardComponentRole: { const OMX_PARAM_COMPONENTROLETYPE *roleParams = (const OMX_PARAM_COMPONENTROLETYPE *)params; if (strncmp((const char *)roleParams->cRole, "audio_decoder.mp3", OMX_MAX_STRINGNAME_SIZE - 1)) { return OMX_ErrorUndefined; } return OMX_ErrorNone; } case OMX_IndexParamAudioPcm: { const OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams = (const OMX_AUDIO_PARAM_PCMMODETYPE *)params; if (pcmParams->nPortIndex != 1) { return OMX_ErrorUndefined; } mNumChannels = pcmParams->nChannels; mSamplingRate = pcmParams->nSamplingRate; return OMX_ErrorNone; } default: return SimpleSoftOMXComponent::internalSetParameter(index, params); } } Commit Message: DO NOT MERGE Verify OMX buffer sizes prior to access Bug: 27207275 Change-Id: I4412825d1ee233d993af0a67708bea54304ff62d CWE ID: CWE-119 Target: 1 Example 2: Code: HandleInterpBody(CompatInfo *info, VarDef *def, SymInterpInfo *si) { bool ok = true; const char *elem, *field; ExprDef *arrayNdx; for (; def; def = (VarDef *) def->common.next) { if (def->name && def->name->expr.op == EXPR_FIELD_REF) { log_err(info->ctx, "Cannot set a global default value from within an interpret statement; " "Move statements to the global file scope\n"); ok = false; continue; } ok = ExprResolveLhs(info->ctx, def->name, &elem, &field, &arrayNdx); if (!ok) continue; ok = SetInterpField(info, si, field, arrayNdx, def->value); } return ok; } Commit Message: xkbcomp: Don't crash on no-op modmask expressions If we have an expression of the form 'l1' in an interp section, we unconditionally try to dereference its args, even if it has none. Signed-off-by: Daniel Stone <[email protected]> CWE ID: CWE-476 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void NetworkHandler::SetCookies( std::unique_ptr<protocol::Array<Network::CookieParam>> cookies, std::unique_ptr<SetCookiesCallback> callback) { if (!process_) { callback->sendFailure(Response::InternalError()); return; } BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::BindOnce( &SetCookiesOnIO, base::Unretained( process_->GetStoragePartition()->GetURLRequestContext()), std::move(cookies), base::BindOnce(&CookiesSetOnIO, std::move(callback)))); } Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable This keeps BrowserContext* and StoragePartition* instead of RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost upon closure of DevTools front-end. Bug: 801117, 783067, 780694 Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b Reviewed-on: https://chromium-review.googlesource.com/876657 Commit-Queue: Andrey Kosyakov <[email protected]> Reviewed-by: Dmitry Gozman <[email protected]> Cr-Commit-Position: refs/heads/master@{#531157} CWE ID: CWE-20 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: IMPEG2D_ERROR_CODES_T impeg2d_dec_seq_hdr(dec_state_t *ps_dec) { stream_t *ps_stream; ps_stream = &ps_dec->s_bit_stream; UWORD16 u2_height; UWORD16 u2_width; if (impeg2d_bit_stream_nxt(ps_stream,START_CODE_LEN) != SEQUENCE_HEADER_CODE) { impeg2d_bit_stream_flush(ps_stream,START_CODE_LEN); return IMPEG2D_FRM_HDR_START_CODE_NOT_FOUND; } impeg2d_bit_stream_flush(ps_stream,START_CODE_LEN); u2_width = impeg2d_bit_stream_get(ps_stream,12); u2_height = impeg2d_bit_stream_get(ps_stream,12); if ((u2_width != ps_dec->u2_horizontal_size) || (u2_height != ps_dec->u2_vertical_size)) { if (0 == ps_dec->u2_header_done) { /* This is the first time we are reading the resolution */ ps_dec->u2_horizontal_size = u2_width; ps_dec->u2_vertical_size = u2_height; if (0 == ps_dec->u4_frm_buf_stride) { ps_dec->u4_frm_buf_stride = (UWORD32) ALIGN16(u2_width); } } else { if((u2_width > ps_dec->u2_create_max_width) || (u2_height > ps_dec->u2_create_max_height)) { IMPEG2D_ERROR_CODES_T e_error = IMPEG2D_UNSUPPORTED_DIMENSIONS; ps_dec->u2_reinit_max_height = u2_height; ps_dec->u2_reinit_max_width = u2_width; return e_error; } else { /* The resolution has changed */ return (IMPEG2D_ERROR_CODES_T)IVD_RES_CHANGED; } } } if((ps_dec->u2_horizontal_size > ps_dec->u2_create_max_width) || (ps_dec->u2_vertical_size > ps_dec->u2_create_max_height)) { IMPEG2D_ERROR_CODES_T e_error = IMPEG2D_UNSUPPORTED_DIMENSIONS; return SET_IVD_FATAL_ERROR(e_error); } /*------------------------------------------------------------------------*/ /* Flush the following as they are not being used */ /* aspect_ratio_info (4 bits) */ /*------------------------------------------------------------------------*/ ps_dec->u2_aspect_ratio_info = impeg2d_bit_stream_get(ps_stream,4); /*------------------------------------------------------------------------*/ /* Frame rate code(4 bits) */ /*------------------------------------------------------------------------*/ ps_dec->u2_frame_rate_code = impeg2d_bit_stream_get(ps_stream,4); /*------------------------------------------------------------------------*/ /* Flush the following as they are not being used */ /* bit_rate_value (18 bits) */ /*------------------------------------------------------------------------*/ impeg2d_bit_stream_flush(ps_stream,18); GET_MARKER_BIT(ps_dec,ps_stream); /*------------------------------------------------------------------------*/ /* Flush the following as they are not being used */ /* vbv_buffer_size_value(10 bits), constrained_parameter_flag (1 bit) */ /*------------------------------------------------------------------------*/ impeg2d_bit_stream_flush(ps_stream,11); /*------------------------------------------------------------------------*/ /* Quantization matrix for the intra blocks */ /*------------------------------------------------------------------------*/ if(impeg2d_bit_stream_get_bit(ps_stream) == 1) { UWORD16 i; for(i = 0; i < NUM_PELS_IN_BLOCK; i++) { ps_dec->au1_intra_quant_matrix[gau1_impeg2_inv_scan_zig_zag[i]] = (UWORD8)impeg2d_bit_stream_get(ps_stream,8); } } else { memcpy(ps_dec->au1_intra_quant_matrix,gau1_impeg2_intra_quant_matrix_default, NUM_PELS_IN_BLOCK); } /*------------------------------------------------------------------------*/ /* Quantization matrix for the inter blocks */ /*------------------------------------------------------------------------*/ if(impeg2d_bit_stream_get_bit(ps_stream) == 1) { UWORD16 i; for(i = 0; i < NUM_PELS_IN_BLOCK; i++) { ps_dec->au1_inter_quant_matrix[gau1_impeg2_inv_scan_zig_zag[i]] = (UWORD8)impeg2d_bit_stream_get(ps_stream,8); } } else { memcpy(ps_dec->au1_inter_quant_matrix,gau1_impeg2_inter_quant_matrix_default, NUM_PELS_IN_BLOCK); } impeg2d_next_start_code(ps_dec); return (IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE; } Commit Message: Check for Valid Frame Rate in Header Bug: 34093952 Change-Id: I9f009edda84555e8d14b138684a38114fb888bf8 (cherry picked from commit 3f068a4e66cc972cf798c79a196099bd7d3bfceb) CWE ID: CWE-200 Target: 1 Example 2: Code: bool PDFiumEngineExports::GetPDFDocInfo(const void* pdf_buffer, int buffer_size, int* page_count, double* max_page_width) { FPDF_DOCUMENT doc = FPDF_LoadMemDocument(pdf_buffer, buffer_size, nullptr); if (!doc) return false; int page_count_local = FPDF_GetPageCount(doc); if (page_count) { *page_count = page_count_local; } if (max_page_width) { *max_page_width = 0; for (int page_number = 0; page_number < page_count_local; page_number++) { double page_width = 0; double page_height = 0; FPDF_GetPageSizeByIndex(doc, page_number, &page_width, &page_height); if (page_width > *max_page_width) { *max_page_width = page_width; } } } FPDF_CloseDocument(doc); return true; } Commit Message: [pdf] Defer page unloading in JS callback. One of the callbacks from PDFium JavaScript into the embedder is to get the current page number. In Chromium, this will trigger a call to CalculateMostVisiblePage that method will determine the visible pages and unload any non-visible pages. But, if the originating JS is on a non-visible page we'll delete the page and annotations associated with that page. This will cause issues as we are currently working with those objects when the JavaScript returns. This Cl defers the page unloading triggered by getting the most visible page until the next event is handled by the Chromium embedder. BUG=chromium:653090 Review-Url: https://codereview.chromium.org/2418533002 Cr-Commit-Position: refs/heads/master@{#424781} CWE ID: CWE-416 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int ecryptfs_parse_options(struct ecryptfs_sb_info *sbi, char *options) { char *p; int rc = 0; int sig_set = 0; int cipher_name_set = 0; int fn_cipher_name_set = 0; int cipher_key_bytes; int cipher_key_bytes_set = 0; int fn_cipher_key_bytes; int fn_cipher_key_bytes_set = 0; struct ecryptfs_mount_crypt_stat *mount_crypt_stat = &sbi->mount_crypt_stat; substring_t args[MAX_OPT_ARGS]; int token; char *sig_src; char *cipher_name_dst; char *cipher_name_src; char *fn_cipher_name_dst; char *fn_cipher_name_src; char *fnek_dst; char *fnek_src; char *cipher_key_bytes_src; char *fn_cipher_key_bytes_src; if (!options) { rc = -EINVAL; goto out; } ecryptfs_init_mount_crypt_stat(mount_crypt_stat); while ((p = strsep(&options, ",")) != NULL) { if (!*p) continue; token = match_token(p, tokens, args); switch (token) { case ecryptfs_opt_sig: case ecryptfs_opt_ecryptfs_sig: sig_src = args[0].from; rc = ecryptfs_add_global_auth_tok(mount_crypt_stat, sig_src, 0); if (rc) { printk(KERN_ERR "Error attempting to register " "global sig; rc = [%d]\n", rc); goto out; } sig_set = 1; break; case ecryptfs_opt_cipher: case ecryptfs_opt_ecryptfs_cipher: cipher_name_src = args[0].from; cipher_name_dst = mount_crypt_stat-> global_default_cipher_name; strncpy(cipher_name_dst, cipher_name_src, ECRYPTFS_MAX_CIPHER_NAME_SIZE); cipher_name_dst[ECRYPTFS_MAX_CIPHER_NAME_SIZE] = '\0'; cipher_name_set = 1; break; case ecryptfs_opt_ecryptfs_key_bytes: cipher_key_bytes_src = args[0].from; cipher_key_bytes = (int)simple_strtol(cipher_key_bytes_src, &cipher_key_bytes_src, 0); mount_crypt_stat->global_default_cipher_key_size = cipher_key_bytes; cipher_key_bytes_set = 1; break; case ecryptfs_opt_passthrough: mount_crypt_stat->flags |= ECRYPTFS_PLAINTEXT_PASSTHROUGH_ENABLED; break; case ecryptfs_opt_xattr_metadata: mount_crypt_stat->flags |= ECRYPTFS_XATTR_METADATA_ENABLED; break; case ecryptfs_opt_encrypted_view: mount_crypt_stat->flags |= ECRYPTFS_XATTR_METADATA_ENABLED; mount_crypt_stat->flags |= ECRYPTFS_ENCRYPTED_VIEW_ENABLED; break; case ecryptfs_opt_fnek_sig: fnek_src = args[0].from; fnek_dst = mount_crypt_stat->global_default_fnek_sig; strncpy(fnek_dst, fnek_src, ECRYPTFS_SIG_SIZE_HEX); mount_crypt_stat->global_default_fnek_sig[ ECRYPTFS_SIG_SIZE_HEX] = '\0'; rc = ecryptfs_add_global_auth_tok( mount_crypt_stat, mount_crypt_stat->global_default_fnek_sig, ECRYPTFS_AUTH_TOK_FNEK); if (rc) { printk(KERN_ERR "Error attempting to register " "global fnek sig [%s]; rc = [%d]\n", mount_crypt_stat->global_default_fnek_sig, rc); goto out; } mount_crypt_stat->flags |= (ECRYPTFS_GLOBAL_ENCRYPT_FILENAMES | ECRYPTFS_GLOBAL_ENCFN_USE_MOUNT_FNEK); break; case ecryptfs_opt_fn_cipher: fn_cipher_name_src = args[0].from; fn_cipher_name_dst = mount_crypt_stat->global_default_fn_cipher_name; strncpy(fn_cipher_name_dst, fn_cipher_name_src, ECRYPTFS_MAX_CIPHER_NAME_SIZE); mount_crypt_stat->global_default_fn_cipher_name[ ECRYPTFS_MAX_CIPHER_NAME_SIZE] = '\0'; fn_cipher_name_set = 1; break; case ecryptfs_opt_fn_cipher_key_bytes: fn_cipher_key_bytes_src = args[0].from; fn_cipher_key_bytes = (int)simple_strtol(fn_cipher_key_bytes_src, &fn_cipher_key_bytes_src, 0); mount_crypt_stat->global_default_fn_cipher_key_bytes = fn_cipher_key_bytes; fn_cipher_key_bytes_set = 1; break; case ecryptfs_opt_unlink_sigs: mount_crypt_stat->flags |= ECRYPTFS_UNLINK_SIGS; break; case ecryptfs_opt_mount_auth_tok_only: mount_crypt_stat->flags |= ECRYPTFS_GLOBAL_MOUNT_AUTH_TOK_ONLY; break; case ecryptfs_opt_err: default: printk(KERN_WARNING "%s: eCryptfs: unrecognized option [%s]\n", __func__, p); } } if (!sig_set) { rc = -EINVAL; ecryptfs_printk(KERN_ERR, "You must supply at least one valid " "auth tok signature as a mount " "parameter; see the eCryptfs README\n"); goto out; } if (!cipher_name_set) { int cipher_name_len = strlen(ECRYPTFS_DEFAULT_CIPHER); BUG_ON(cipher_name_len >= ECRYPTFS_MAX_CIPHER_NAME_SIZE); strcpy(mount_crypt_stat->global_default_cipher_name, ECRYPTFS_DEFAULT_CIPHER); } if ((mount_crypt_stat->flags & ECRYPTFS_GLOBAL_ENCRYPT_FILENAMES) && !fn_cipher_name_set) strcpy(mount_crypt_stat->global_default_fn_cipher_name, mount_crypt_stat->global_default_cipher_name); if (!cipher_key_bytes_set) mount_crypt_stat->global_default_cipher_key_size = 0; if ((mount_crypt_stat->flags & ECRYPTFS_GLOBAL_ENCRYPT_FILENAMES) && !fn_cipher_key_bytes_set) mount_crypt_stat->global_default_fn_cipher_key_bytes = mount_crypt_stat->global_default_cipher_key_size; mutex_lock(&key_tfm_list_mutex); if (!ecryptfs_tfm_exists(mount_crypt_stat->global_default_cipher_name, NULL)) { rc = ecryptfs_add_new_key_tfm( NULL, mount_crypt_stat->global_default_cipher_name, mount_crypt_stat->global_default_cipher_key_size); if (rc) { printk(KERN_ERR "Error attempting to initialize " "cipher with name = [%s] and key size = [%td]; " "rc = [%d]\n", mount_crypt_stat->global_default_cipher_name, mount_crypt_stat->global_default_cipher_key_size, rc); rc = -EINVAL; mutex_unlock(&key_tfm_list_mutex); goto out; } } if ((mount_crypt_stat->flags & ECRYPTFS_GLOBAL_ENCRYPT_FILENAMES) && !ecryptfs_tfm_exists( mount_crypt_stat->global_default_fn_cipher_name, NULL)) { rc = ecryptfs_add_new_key_tfm( NULL, mount_crypt_stat->global_default_fn_cipher_name, mount_crypt_stat->global_default_fn_cipher_key_bytes); if (rc) { printk(KERN_ERR "Error attempting to initialize " "cipher with name = [%s] and key size = [%td]; " "rc = [%d]\n", mount_crypt_stat->global_default_fn_cipher_name, mount_crypt_stat->global_default_fn_cipher_key_bytes, rc); rc = -EINVAL; mutex_unlock(&key_tfm_list_mutex); goto out; } } mutex_unlock(&key_tfm_list_mutex); rc = ecryptfs_init_global_auth_toks(mount_crypt_stat); if (rc) printk(KERN_WARNING "One or more global auth toks could not " "properly register; rc = [%d]\n", rc); out: return rc; } Commit Message: Ecryptfs: Add mount option to check uid of device being mounted = expect uid Close a TOCTOU race for mounts done via ecryptfs-mount-private. The mount source (device) can be raced when the ownership test is done in userspace. Provide Ecryptfs a means to force the uid check at mount time. Signed-off-by: John Johansen <[email protected]> Cc: <[email protected]> Signed-off-by: Tyler Hicks <[email protected]> CWE ID: CWE-264 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: cJSON *cJSON_CreateBool( int b ) { cJSON *item = cJSON_New_Item(); if ( item ) item->type = b ? cJSON_True : cJSON_False; return item; } Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a malformed JSON string was passed on the control channel. This issue, present in the cJSON library, was already fixed upstream, so was addressed here in iperf3 by importing a newer version of cJSON (plus local ESnet modifications). Discovered and reported by Dave McDaniel, Cisco Talos. Based on a patch by @dopheide-esnet, with input from @DaveGamble. Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001, CVE-2016-4303 (cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40) Signed-off-by: Bruce A. Mah <[email protected]> CWE ID: CWE-119 Target: 1 Example 2: Code: static inline int private_mapping_ok(struct vm_area_struct *vma) { return vma->vm_flags & VM_MAYSHARE; } Commit Message: mm: Tighten x86 /dev/mem with zeroing reads Under CONFIG_STRICT_DEVMEM, reading System RAM through /dev/mem is disallowed. However, on x86, the first 1MB was always allowed for BIOS and similar things, regardless of it actually being System RAM. It was possible for heap to end up getting allocated in low 1MB RAM, and then read by things like x86info or dd, which would trip hardened usercopy: usercopy: kernel memory exposure attempt detected from ffff880000090000 (dma-kmalloc-256) (4096 bytes) This changes the x86 exception for the low 1MB by reading back zeros for System RAM areas instead of blindly allowing them. More work is needed to extend this to mmap, but currently mmap doesn't go through usercopy, so hardened usercopy won't Oops the kernel. Reported-by: Tommi Rantala <[email protected]> Tested-by: Tommi Rantala <[email protected]> Signed-off-by: Kees Cook <[email protected]> CWE ID: CWE-732 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static char* lookup_loc_range(const char* loc_range, HashTable* hash_arr, int canonicalize TSRMLS_DC) { int i = 0; int cur_arr_len = 0; int result = 0; char* lang_tag = NULL; zval** ele_value = NULL; char** cur_arr = NULL; char* cur_loc_range = NULL; char* can_loc_range = NULL; int saved_pos = 0; char* return_value = NULL; cur_arr = ecalloc(zend_hash_num_elements(hash_arr)*2, sizeof(char *)); /* convert the array to lowercase , also replace hyphens with the underscore and store it in cur_arr */ for(zend_hash_internal_pointer_reset(hash_arr); zend_hash_has_more_elements(hash_arr) == SUCCESS; zend_hash_move_forward(hash_arr)) { if (zend_hash_get_current_data(hash_arr, (void**)&ele_value) == FAILURE) { /* Should never actually fail since the key is known to exist.*/ continue; } if(Z_TYPE_PP(ele_value)!= IS_STRING) { /* element value is not a string */ intl_error_set(NULL, U_ILLEGAL_ARGUMENT_ERROR, "lookup_loc_range: locale array element is not a string", 0 TSRMLS_CC); LOOKUP_CLEAN_RETURN(NULL); } cur_arr[cur_arr_len*2] = estrndup(Z_STRVAL_PP(ele_value), Z_STRLEN_PP(ele_value)); result = strToMatch(Z_STRVAL_PP(ele_value), cur_arr[cur_arr_len*2]); if(result == 0) { intl_error_set(NULL, U_ILLEGAL_ARGUMENT_ERROR, "lookup_loc_range: unable to canonicalize lang_tag", 0 TSRMLS_CC); LOOKUP_CLEAN_RETURN(NULL); } cur_arr[cur_arr_len*2+1] = Z_STRVAL_PP(ele_value); cur_arr_len++ ; } /* end of for */ /* Canonicalize array elements */ if(canonicalize) { for(i=0; i<cur_arr_len; i++) { lang_tag = get_icu_value_internal(cur_arr[i*2], LOC_CANONICALIZE_TAG, &result, 0); if(result != 1 || lang_tag == NULL || !lang_tag[0]) { if(lang_tag) { efree(lang_tag); } intl_error_set(NULL, U_ILLEGAL_ARGUMENT_ERROR, "lookup_loc_range: unable to canonicalize lang_tag" , 0 TSRMLS_CC); LOOKUP_CLEAN_RETURN(NULL); } cur_arr[i*2] = erealloc(cur_arr[i*2], strlen(lang_tag)+1); result = strToMatch(lang_tag, cur_arr[i*2]); efree(lang_tag); if(result == 0) { intl_error_set(NULL, U_ILLEGAL_ARGUMENT_ERROR, "lookup_loc_range: unable to canonicalize lang_tag" , 0 TSRMLS_CC); LOOKUP_CLEAN_RETURN(NULL); } } } if(canonicalize) { /* Canonicalize the loc_range */ can_loc_range = get_icu_value_internal(loc_range, LOC_CANONICALIZE_TAG, &result , 0); if( result != 1 || can_loc_range == NULL || !can_loc_range[0]) { /* Error */ intl_error_set(NULL, U_ILLEGAL_ARGUMENT_ERROR, "lookup_loc_range: unable to canonicalize loc_range" , 0 TSRMLS_CC ); if(can_loc_range) { efree(can_loc_range); } LOOKUP_CLEAN_RETURN(NULL); } else { loc_range = can_loc_range; } } cur_loc_range = ecalloc(1, strlen(loc_range)+1); /* convert to lower and replace hyphens */ result = strToMatch(loc_range, cur_loc_range); if(can_loc_range) { efree(can_loc_range); } if(result == 0) { intl_error_set(NULL, U_ILLEGAL_ARGUMENT_ERROR, "lookup_loc_range: unable to canonicalize lang_tag" , 0 TSRMLS_CC); LOOKUP_CLEAN_RETURN(NULL); } /* Lookup for the lang_tag match */ saved_pos = strlen(cur_loc_range); while(saved_pos > 0) { for(i=0; i< cur_arr_len; i++){ if(cur_arr[i*2] != NULL && strlen(cur_arr[i*2]) == saved_pos && strncmp(cur_loc_range, cur_arr[i*2], saved_pos) == 0) { /* Match found */ return_value = estrdup(canonicalize?cur_arr[i*2]:cur_arr[i*2+1]); efree(cur_loc_range); LOOKUP_CLEAN_RETURN(return_value); } } saved_pos = getStrrtokenPos(cur_loc_range, saved_pos); } /* Match not found */ efree(cur_loc_range); LOOKUP_CLEAN_RETURN(NULL); } Commit Message: Fix bug #72241: get_icu_value_internal out-of-bounds read CWE ID: CWE-125 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int rndis_set_response(USBNetState *s, rndis_set_msg_type *buf, unsigned int length) { rndis_set_cmplt_type *resp = rndis_queue_response(s, sizeof(rndis_set_cmplt_type)); uint32_t bufoffs, buflen; int ret; if (!resp) return USB_RET_STALL; bufoffs = le32_to_cpu(buf->InformationBufferOffset) + 8; buflen = le32_to_cpu(buf->InformationBufferLength); if (bufoffs + buflen > length) return USB_RET_STALL; ret = ndis_set(s, le32_to_cpu(buf->OID), bufoffs + (uint8_t *) buf, buflen); resp->MessageLength = cpu_to_le32(sizeof(rndis_set_cmplt_type)); if (ret < 0) { /* OID not supported */ resp->Status = cpu_to_le32(RNDIS_STATUS_NOT_SUPPORTED); return 0; } resp->Status = cpu_to_le32(RNDIS_STATUS_SUCCESS); return 0; } Commit Message: CWE ID: CWE-189 Target: 1 Example 2: Code: void FrameLoader::handleFallbackContent() { HTMLFrameOwnerElement* owner = m_frame->ownerElement(); if (!owner || !owner->hasTagName(objectTag)) return; toHTMLObjectElement(owner)->renderFallbackContent(); } Commit Message: Don't wait to notify client of spoof attempt if a modal dialog is created. BUG=281256 TEST=See bug for repro steps. Review URL: https://chromiumcodereview.appspot.com/23620020 git-svn-id: svn://svn.chromium.org/blink/trunk@157196 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int cop1Emulate(struct pt_regs *xcp, struct mips_fpu_struct *ctx, void *__user *fault_addr) { mips_instruction ir; unsigned long emulpc, contpc; unsigned int cond; if (!access_ok(VERIFY_READ, xcp->cp0_epc, sizeof(mips_instruction))) { MIPS_FPU_EMU_INC_STATS(errors); *fault_addr = (mips_instruction __user *)xcp->cp0_epc; return SIGBUS; } if (__get_user(ir, (mips_instruction __user *) xcp->cp0_epc)) { MIPS_FPU_EMU_INC_STATS(errors); *fault_addr = (mips_instruction __user *)xcp->cp0_epc; return SIGSEGV; } /* XXX NEC Vr54xx bug workaround */ if ((xcp->cp0_cause & CAUSEF_BD) && !isBranchInstr(&ir)) xcp->cp0_cause &= ~CAUSEF_BD; if (xcp->cp0_cause & CAUSEF_BD) { /* * The instruction to be emulated is in a branch delay slot * which means that we have to emulate the branch instruction * BEFORE we do the cop1 instruction. * * This branch could be a COP1 branch, but in that case we * would have had a trap for that instruction, and would not * come through this route. * * Linux MIPS branch emulator operates on context, updating the * cp0_epc. */ emulpc = xcp->cp0_epc + 4; /* Snapshot emulation target */ if (__compute_return_epc(xcp)) { #ifdef CP1DBG printk("failed to emulate branch at %p\n", (void *) (xcp->cp0_epc)); #endif return SIGILL; } if (!access_ok(VERIFY_READ, emulpc, sizeof(mips_instruction))) { MIPS_FPU_EMU_INC_STATS(errors); *fault_addr = (mips_instruction __user *)emulpc; return SIGBUS; } if (__get_user(ir, (mips_instruction __user *) emulpc)) { MIPS_FPU_EMU_INC_STATS(errors); *fault_addr = (mips_instruction __user *)emulpc; return SIGSEGV; } /* __compute_return_epc() will have updated cp0_epc */ contpc = xcp->cp0_epc; /* In order not to confuse ptrace() et al, tweak context */ xcp->cp0_epc = emulpc - 4; } else { emulpc = xcp->cp0_epc; contpc = xcp->cp0_epc + 4; } emul: perf_sw_event(PERF_COUNT_SW_EMULATION_FAULTS, 1, 0, xcp, 0); MIPS_FPU_EMU_INC_STATS(emulated); switch (MIPSInst_OPCODE(ir)) { case ldc1_op:{ u64 __user *va = (u64 __user *) (xcp->regs[MIPSInst_RS(ir)] + MIPSInst_SIMM(ir)); u64 val; MIPS_FPU_EMU_INC_STATS(loads); if (!access_ok(VERIFY_READ, va, sizeof(u64))) { MIPS_FPU_EMU_INC_STATS(errors); *fault_addr = va; return SIGBUS; } if (__get_user(val, va)) { MIPS_FPU_EMU_INC_STATS(errors); *fault_addr = va; return SIGSEGV; } DITOREG(val, MIPSInst_RT(ir)); break; } case sdc1_op:{ u64 __user *va = (u64 __user *) (xcp->regs[MIPSInst_RS(ir)] + MIPSInst_SIMM(ir)); u64 val; MIPS_FPU_EMU_INC_STATS(stores); DIFROMREG(val, MIPSInst_RT(ir)); if (!access_ok(VERIFY_WRITE, va, sizeof(u64))) { MIPS_FPU_EMU_INC_STATS(errors); *fault_addr = va; return SIGBUS; } if (__put_user(val, va)) { MIPS_FPU_EMU_INC_STATS(errors); *fault_addr = va; return SIGSEGV; } break; } case lwc1_op:{ u32 __user *va = (u32 __user *) (xcp->regs[MIPSInst_RS(ir)] + MIPSInst_SIMM(ir)); u32 val; MIPS_FPU_EMU_INC_STATS(loads); if (!access_ok(VERIFY_READ, va, sizeof(u32))) { MIPS_FPU_EMU_INC_STATS(errors); *fault_addr = va; return SIGBUS; } if (__get_user(val, va)) { MIPS_FPU_EMU_INC_STATS(errors); *fault_addr = va; return SIGSEGV; } SITOREG(val, MIPSInst_RT(ir)); break; } case swc1_op:{ u32 __user *va = (u32 __user *) (xcp->regs[MIPSInst_RS(ir)] + MIPSInst_SIMM(ir)); u32 val; MIPS_FPU_EMU_INC_STATS(stores); SIFROMREG(val, MIPSInst_RT(ir)); if (!access_ok(VERIFY_WRITE, va, sizeof(u32))) { MIPS_FPU_EMU_INC_STATS(errors); *fault_addr = va; return SIGBUS; } if (__put_user(val, va)) { MIPS_FPU_EMU_INC_STATS(errors); *fault_addr = va; return SIGSEGV; } break; } case cop1_op: switch (MIPSInst_RS(ir)) { #if defined(__mips64) case dmfc_op: /* copregister fs -> gpr[rt] */ if (MIPSInst_RT(ir) != 0) { DIFROMREG(xcp->regs[MIPSInst_RT(ir)], MIPSInst_RD(ir)); } break; case dmtc_op: /* copregister fs <- rt */ DITOREG(xcp->regs[MIPSInst_RT(ir)], MIPSInst_RD(ir)); break; #endif case mfc_op: /* copregister rd -> gpr[rt] */ if (MIPSInst_RT(ir) != 0) { SIFROMREG(xcp->regs[MIPSInst_RT(ir)], MIPSInst_RD(ir)); } break; case mtc_op: /* copregister rd <- rt */ SITOREG(xcp->regs[MIPSInst_RT(ir)], MIPSInst_RD(ir)); break; case cfc_op:{ /* cop control register rd -> gpr[rt] */ u32 value; if (MIPSInst_RD(ir) == FPCREG_CSR) { value = ctx->fcr31; value = (value & ~FPU_CSR_RM) | mips_rm[modeindex(value)]; #ifdef CSRTRACE printk("%p gpr[%d]<-csr=%08x\n", (void *) (xcp->cp0_epc), MIPSInst_RT(ir), value); #endif } else if (MIPSInst_RD(ir) == FPCREG_RID) value = 0; else value = 0; if (MIPSInst_RT(ir)) xcp->regs[MIPSInst_RT(ir)] = value; break; } case ctc_op:{ /* copregister rd <- rt */ u32 value; if (MIPSInst_RT(ir) == 0) value = 0; else value = xcp->regs[MIPSInst_RT(ir)]; /* we only have one writable control reg */ if (MIPSInst_RD(ir) == FPCREG_CSR) { #ifdef CSRTRACE printk("%p gpr[%d]->csr=%08x\n", (void *) (xcp->cp0_epc), MIPSInst_RT(ir), value); #endif /* * Don't write reserved bits, * and convert to ieee library modes */ ctx->fcr31 = (value & ~(FPU_CSR_RSVD | FPU_CSR_RM)) | ieee_rm[modeindex(value)]; } if ((ctx->fcr31 >> 5) & ctx->fcr31 & FPU_CSR_ALL_E) { return SIGFPE; } break; } case bc_op:{ int likely = 0; if (xcp->cp0_cause & CAUSEF_BD) return SIGILL; #if __mips >= 4 cond = ctx->fcr31 & fpucondbit[MIPSInst_RT(ir) >> 2]; #else cond = ctx->fcr31 & FPU_CSR_COND; #endif switch (MIPSInst_RT(ir) & 3) { case bcfl_op: likely = 1; case bcf_op: cond = !cond; break; case bctl_op: likely = 1; case bct_op: break; default: /* thats an illegal instruction */ return SIGILL; } xcp->cp0_cause |= CAUSEF_BD; if (cond) { /* branch taken: emulate dslot * instruction */ xcp->cp0_epc += 4; contpc = (xcp->cp0_epc + (MIPSInst_SIMM(ir) << 2)); if (!access_ok(VERIFY_READ, xcp->cp0_epc, sizeof(mips_instruction))) { MIPS_FPU_EMU_INC_STATS(errors); *fault_addr = (mips_instruction __user *)xcp->cp0_epc; return SIGBUS; } if (__get_user(ir, (mips_instruction __user *) xcp->cp0_epc)) { MIPS_FPU_EMU_INC_STATS(errors); *fault_addr = (mips_instruction __user *)xcp->cp0_epc; return SIGSEGV; } switch (MIPSInst_OPCODE(ir)) { case lwc1_op: case swc1_op: #if (__mips >= 2 || defined(__mips64)) case ldc1_op: case sdc1_op: #endif case cop1_op: #if __mips >= 4 && __mips != 32 case cop1x_op: #endif /* its one of ours */ goto emul; #if __mips >= 4 case spec_op: if (MIPSInst_FUNC(ir) == movc_op) goto emul; break; #endif } /* * Single step the non-cp1 * instruction in the dslot */ return mips_dsemul(xcp, ir, contpc); } else { /* branch not taken */ if (likely) { /* * branch likely nullifies * dslot if not taken */ xcp->cp0_epc += 4; contpc += 4; /* * else continue & execute * dslot as normal insn */ } } break; } default: if (!(MIPSInst_RS(ir) & 0x10)) return SIGILL; { int sig; /* a real fpu computation instruction */ if ((sig = fpu_emu(xcp, ctx, ir))) return sig; } } break; #if __mips >= 4 && __mips != 32 case cop1x_op:{ int sig = fpux_emu(xcp, ctx, ir, fault_addr); if (sig) return sig; break; } #endif #if __mips >= 4 case spec_op: if (MIPSInst_FUNC(ir) != movc_op) return SIGILL; cond = fpucondbit[MIPSInst_RT(ir) >> 2]; if (((ctx->fcr31 & cond) != 0) == ((MIPSInst_RT(ir) & 1) != 0)) xcp->regs[MIPSInst_RD(ir)] = xcp->regs[MIPSInst_RS(ir)]; break; #endif default: return SIGILL; } /* we did it !! */ xcp->cp0_epc = contpc; xcp->cp0_cause &= ~CAUSEF_BD; return 0; } 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 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void GLSurfaceEGLSurfaceControl::CommitPendingTransaction( SwapCompletionCallback completion_callback, PresentationCallback present_callback) { DCHECK(pending_transaction_); ResourceRefs resources_to_release; resources_to_release.swap(current_frame_resources_); current_frame_resources_.clear(); current_frame_resources_.swap(pending_frame_resources_); pending_frame_resources_.clear(); SurfaceControl::Transaction::OnCompleteCb callback = base::BindOnce( &GLSurfaceEGLSurfaceControl::OnTransactionAckOnGpuThread, weak_factory_.GetWeakPtr(), std::move(completion_callback), std::move(present_callback), std::move(resources_to_release)); pending_transaction_->SetOnCompleteCb(std::move(callback), gpu_task_runner_); pending_transaction_->Apply(); pending_transaction_.reset(); DCHECK_GE(surface_list_.size(), pending_surfaces_count_); surface_list_.resize(pending_surfaces_count_); pending_surfaces_count_ = 0u; } Commit Message: gpu/android : Add support for partial swap with surface control. Add support for PostSubBuffer to GLSurfaceEGLSurfaceControl. This should allow the display compositor to draw the minimum sub-rect necessary from the damage tracking in BufferQueue on the client-side, and also to pass this damage rect to the framework. [email protected] Bug: 926020 Change-Id: I73d3320cab68250d4c6865bf21c5531682d8bf61 Reviewed-on: https://chromium-review.googlesource.com/c/1457467 Commit-Queue: Khushal <[email protected]> Commit-Queue: Antoine Labour <[email protected]> Reviewed-by: Antoine Labour <[email protected]> Auto-Submit: Khushal <[email protected]> Cr-Commit-Position: refs/heads/master@{#629852} CWE ID: Target: 1 Example 2: Code: FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj) { FLAC__uint32 i, j, x; FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)); memset(obj, 0, sizeof(FLAC__StreamMetadata_CueSheet)); FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0); if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)obj->media_catalog_number, FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN/8)) return false; /* read_callback_ sets the state for us */ if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &obj->lead_in, FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN)) return false; /* read_callback_ sets the state for us */ if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN)) return false; /* read_callback_ sets the state for us */ obj->is_cd = x? true : false; if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN)) return false; /* read_callback_ sets the state for us */ if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN)) return false; /* read_callback_ sets the state for us */ obj->num_tracks = x; if(obj->num_tracks > 0) { if(0 == (obj->tracks = safe_calloc_(obj->num_tracks, sizeof(FLAC__StreamMetadata_CueSheet_Track)))) { decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR; return false; } for(i = 0; i < obj->num_tracks; i++) { FLAC__StreamMetadata_CueSheet_Track *track = &obj->tracks[i]; if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &track->offset, FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN)) return false; /* read_callback_ sets the state for us */ if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN)) return false; /* read_callback_ sets the state for us */ track->number = (FLAC__byte)x; FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0); if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)track->isrc, FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN/8)) return false; /* read_callback_ sets the state for us */ if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN)) return false; /* read_callback_ sets the state for us */ track->type = x; if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN)) return false; /* read_callback_ sets the state for us */ track->pre_emphasis = x; if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN)) return false; /* read_callback_ sets the state for us */ if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN)) return false; /* read_callback_ sets the state for us */ track->num_indices = (FLAC__byte)x; if(track->num_indices > 0) { if(0 == (track->indices = safe_calloc_(track->num_indices, sizeof(FLAC__StreamMetadata_CueSheet_Index)))) { decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR; return false; } for(j = 0; j < track->num_indices; j++) { FLAC__StreamMetadata_CueSheet_Index *indx = &track->indices[j]; if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &indx->offset, FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN)) return false; /* read_callback_ sets the state for us */ if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN)) return false; /* read_callback_ sets the state for us */ indx->number = (FLAC__byte)x; if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN)) return false; /* read_callback_ sets the state for us */ } } } } return true; } Commit Message: Avoid free-before-initialize vulnerability in heap Bug: 27211885 Change-Id: Ib9c93bd9ffdde2a5f8d31a86f06e267dc9c152db CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: bool ResourceDispatcherHostImpl::AcceptAuthRequest( ResourceLoader* loader, net::AuthChallengeInfo* auth_info) { if (delegate_ && !delegate_->AcceptAuthRequest(loader->request(), auth_info)) return false; if (!auth_info->is_proxy) { HttpAuthResourceType resource_type = HttpAuthResourceTypeOf(loader->request()); UMA_HISTOGRAM_ENUMERATION("Net.HttpAuthResource", resource_type, HTTP_AUTH_RESOURCE_LAST); if (resource_type == HTTP_AUTH_RESOURCE_BLOCKED_CROSS) return false; } return true; } Commit Message: Revert cross-origin auth prompt blocking. BUG=174129 Review URL: https://chromiumcodereview.appspot.com/12183030 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@181113 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: bool MediaStreamDevicesController::IsRequestAllowedByDefault() const { if (ShouldAlwaysAllowOrigin()) return true; struct { bool has_capability; const char* policy_name; const char* list_policy_name; ContentSettingsType settings_type; } device_checks[] = { { microphone_requested_, prefs::kAudioCaptureAllowed, prefs::kAudioCaptureAllowedUrls, CONTENT_SETTINGS_TYPE_MEDIASTREAM_MIC }, { webcam_requested_, prefs::kVideoCaptureAllowed, prefs::kVideoCaptureAllowedUrls, CONTENT_SETTINGS_TYPE_MEDIASTREAM_CAMERA }, }; for (size_t i = 0; i < ARRAYSIZE_UNSAFE(device_checks); ++i) { if (!device_checks[i].has_capability) continue; DevicePolicy policy = GetDevicePolicy(device_checks[i].policy_name, device_checks[i].list_policy_name); if (policy == ALWAYS_DENY || (policy == POLICY_NOT_SET && profile_->GetHostContentSettingsMap()->GetContentSetting( request_.security_origin, request_.security_origin, device_checks[i].settings_type, NO_RESOURCE_IDENTIFIER) != CONTENT_SETTING_ALLOW)) { return false; } } return true; } Commit Message: Make the content setting for webcam/mic sticky for Pepper requests. This makes the content setting sticky for webcam/mic requests from Pepper from non-https origins. BUG=249335 [email protected], [email protected] Review URL: https://codereview.chromium.org/17060006 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@206479 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264 Target: 1 Example 2: Code: static int __init af_unix_init(void) { int rc = -1; struct sk_buff *dummy_skb; BUILD_BUG_ON(sizeof(struct unix_skb_parms) > sizeof(dummy_skb->cb)); rc = proto_register(&unix_proto, 1); if (rc != 0) { printk(KERN_CRIT "%s: Cannot create unix_sock SLAB cache!\n", __func__); goto out; } sock_register(&unix_family_ops); register_pernet_subsys(&unix_net_ops); out: return rc; } Commit Message: af_netlink: force credentials passing [CVE-2012-3520] Pablo Neira Ayuso discovered that avahi and potentially NetworkManager accept spoofed Netlink messages because of a kernel bug. The kernel passes all-zero SCM_CREDENTIALS ancillary data to the receiver if the sender did not provide such data, instead of not including any such data at all or including the correct data from the peer (as it is the case with AF_UNIX). This bug was introduced in commit 16e572626961 (af_unix: dont send SCM_CREDENTIALS by default) This patch forces passing credentials for netlink, as before the regression. Another fix would be to not add SCM_CREDENTIALS in netlink messages if not provided by the sender, but it might break some programs. With help from Florian Weimer & Petr Matousek This issue is designated as CVE-2012-3520 Signed-off-by: Eric Dumazet <[email protected]> Cc: Petr Matousek <[email protected]> Cc: Florian Weimer <[email protected]> Cc: Pablo Neira Ayuso <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-287 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int get_ngot_entries(struct r_bin_bflt_obj *obj) { ut32 data_size = obj->hdr->data_end - obj->hdr->data_start; int i = 0, n_got = 0; if (data_size > obj->size) { return 0; } for (i = 0, n_got = 0; i < data_size ; i+= 4, n_got++) { ut32 entry, offset = obj->hdr->data_start; if (offset + i + sizeof (ut32) > obj->size || offset + i + sizeof (ut32) < offset) { return 0; } int len = r_buf_read_at (obj->b, offset + i, (ut8 *)&entry, sizeof (ut32)); if (len != sizeof (ut32)) { return 0; } if (!VALID_GOT_ENTRY (entry)) { break; } } return n_got; } Commit Message: Fix #6829 oob write because of using wrong struct CWE ID: CWE-119 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: WorkerProcessLauncherTest::WorkerProcessLauncherTest() : message_loop_(MessageLoop::TYPE_IO) { } Commit Message: Validate and report peer's PID to WorkerProcessIpcDelegate so it will be able to duplicate handles to and from the worker process. As a side effect WorkerProcessLauncher::Delegate is now responsible for retrieving the client's PID and deciding whether a launch failed due to a permanent error condition. BUG=134694 Review URL: https://chromiumcodereview.appspot.com/11143025 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@162778 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399 Target: 1 Example 2: Code: pkinit_octetstring2key(krb5_context context, krb5_enctype etype, unsigned char *key, unsigned int dh_key_len, krb5_keyblock *key_block) { krb5_error_code retval; unsigned char *buf = NULL; unsigned char md[SHA_DIGEST_LENGTH]; unsigned char counter; size_t keybytes, keylength, offset; krb5_data random_data; if ((buf = malloc(dh_key_len)) == NULL) { retval = ENOMEM; goto cleanup; } memset(buf, 0, dh_key_len); counter = 0; offset = 0; do { SHA_CTX c; SHA1_Init(&c); SHA1_Update(&c, &counter, 1); SHA1_Update(&c, key, dh_key_len); SHA1_Final(md, &c); if (dh_key_len - offset < sizeof(md)) memcpy(buf + offset, md, dh_key_len - offset); else memcpy(buf + offset, md, sizeof(md)); offset += sizeof(md); counter++; } while (offset < dh_key_len); key_block->magic = 0; key_block->enctype = etype; retval = krb5_c_keylengths(context, etype, &keybytes, &keylength); if (retval) goto cleanup; key_block->length = keylength; key_block->contents = malloc(keylength); if (key_block->contents == NULL) { retval = ENOMEM; goto cleanup; } random_data.length = keybytes; random_data.data = (char *)buf; retval = krb5_c_random_to_key(context, etype, &random_data, key_block); cleanup: free(buf); /* If this is an error return, free the allocated keyblock, if any */ if (retval) { krb5_free_keyblock_contents(context, key_block); } return retval; } Commit Message: PKINIT null pointer deref [CVE-2013-1415] Don't dereference a null pointer when cleaning up. The KDC plugin for PKINIT can dereference a null pointer when a malformed packet causes processing to terminate early, leading to a crash of the KDC process. An attacker would need to have a valid PKINIT certificate or have observed a successful PKINIT authentication, or an unauthenticated attacker could execute the attack if anonymous PKINIT is enabled. CVSSv2 vector: AV:N/AC:M/Au:N/C:N/I:N/A:C/E:P/RL:O/RC:C This is a minimal commit for pullup; style fixes in a followup. [[email protected]: reformat and edit commit message] (cherry picked from commit c773d3c775e9b2d88bcdff5f8a8ba88d7ec4e8ed) ticket: 7570 version_fixed: 1.11.1 status: resolved CWE ID: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: __releases(kernel_lock) __acquires(kernel_lock) { char *orig_data = kstrdup(data, GFP_KERNEL); struct buffer_head *bh; struct ext4_super_block *es = NULL; struct ext4_sb_info *sbi; ext4_fsblk_t block; ext4_fsblk_t sb_block = get_sb_block(&data); ext4_fsblk_t logical_sb_block; unsigned long offset = 0; unsigned long journal_devnum = 0; unsigned long def_mount_opts; struct inode *root; char *cp; const char *descr; int ret = -ENOMEM; int blocksize; unsigned int db_count; unsigned int i; int needs_recovery, has_huge_files; __u64 blocks_count; int err; unsigned int journal_ioprio = DEFAULT_JOURNAL_IOPRIO; ext4_group_t first_not_zeroed; sbi = kzalloc(sizeof(*sbi), GFP_KERNEL); if (!sbi) goto out_free_orig; sbi->s_blockgroup_lock = kzalloc(sizeof(struct blockgroup_lock), GFP_KERNEL); if (!sbi->s_blockgroup_lock) { kfree(sbi); goto out_free_orig; } sb->s_fs_info = sbi; sbi->s_mount_opt = 0; sbi->s_resuid = EXT4_DEF_RESUID; sbi->s_resgid = EXT4_DEF_RESGID; sbi->s_inode_readahead_blks = EXT4_DEF_INODE_READAHEAD_BLKS; sbi->s_sb_block = sb_block; if (sb->s_bdev->bd_part) sbi->s_sectors_written_start = part_stat_read(sb->s_bdev->bd_part, sectors[1]); /* Cleanup superblock name */ for (cp = sb->s_id; (cp = strchr(cp, '/'));) *cp = '!'; ret = -EINVAL; blocksize = sb_min_blocksize(sb, EXT4_MIN_BLOCK_SIZE); if (!blocksize) { ext4_msg(sb, KERN_ERR, "unable to set blocksize"); goto out_fail; } /* * The ext4 superblock will not be buffer aligned for other than 1kB * block sizes. We need to calculate the offset from buffer start. */ if (blocksize != EXT4_MIN_BLOCK_SIZE) { logical_sb_block = sb_block * EXT4_MIN_BLOCK_SIZE; offset = do_div(logical_sb_block, blocksize); } else { logical_sb_block = sb_block; } if (!(bh = sb_bread(sb, logical_sb_block))) { ext4_msg(sb, KERN_ERR, "unable to read superblock"); goto out_fail; } /* * Note: s_es must be initialized as soon as possible because * some ext4 macro-instructions depend on its value */ es = (struct ext4_super_block *) (((char *)bh->b_data) + offset); sbi->s_es = es; sb->s_magic = le16_to_cpu(es->s_magic); if (sb->s_magic != EXT4_SUPER_MAGIC) goto cantfind_ext4; sbi->s_kbytes_written = le64_to_cpu(es->s_kbytes_written); /* Set defaults before we parse the mount options */ def_mount_opts = le32_to_cpu(es->s_default_mount_opts); set_opt(sb, INIT_INODE_TABLE); if (def_mount_opts & EXT4_DEFM_DEBUG) set_opt(sb, DEBUG); if (def_mount_opts & EXT4_DEFM_BSDGROUPS) { ext4_msg(sb, KERN_WARNING, deprecated_msg, "bsdgroups", "2.6.38"); set_opt(sb, GRPID); } if (def_mount_opts & EXT4_DEFM_UID16) set_opt(sb, NO_UID32); /* xattr user namespace & acls are now defaulted on */ #ifdef CONFIG_EXT4_FS_XATTR set_opt(sb, XATTR_USER); #endif #ifdef CONFIG_EXT4_FS_POSIX_ACL set_opt(sb, POSIX_ACL); #endif set_opt(sb, MBLK_IO_SUBMIT); if ((def_mount_opts & EXT4_DEFM_JMODE) == EXT4_DEFM_JMODE_DATA) set_opt(sb, JOURNAL_DATA); else if ((def_mount_opts & EXT4_DEFM_JMODE) == EXT4_DEFM_JMODE_ORDERED) set_opt(sb, ORDERED_DATA); else if ((def_mount_opts & EXT4_DEFM_JMODE) == EXT4_DEFM_JMODE_WBACK) set_opt(sb, WRITEBACK_DATA); if (le16_to_cpu(sbi->s_es->s_errors) == EXT4_ERRORS_PANIC) set_opt(sb, ERRORS_PANIC); else if (le16_to_cpu(sbi->s_es->s_errors) == EXT4_ERRORS_CONTINUE) set_opt(sb, ERRORS_CONT); else set_opt(sb, ERRORS_RO); if (def_mount_opts & EXT4_DEFM_BLOCK_VALIDITY) set_opt(sb, BLOCK_VALIDITY); if (def_mount_opts & EXT4_DEFM_DISCARD) set_opt(sb, DISCARD); sbi->s_resuid = le16_to_cpu(es->s_def_resuid); sbi->s_resgid = le16_to_cpu(es->s_def_resgid); sbi->s_commit_interval = JBD2_DEFAULT_MAX_COMMIT_AGE * HZ; sbi->s_min_batch_time = EXT4_DEF_MIN_BATCH_TIME; sbi->s_max_batch_time = EXT4_DEF_MAX_BATCH_TIME; if ((def_mount_opts & EXT4_DEFM_NOBARRIER) == 0) set_opt(sb, BARRIER); /* * enable delayed allocation by default * Use -o nodelalloc to turn it off */ if (!IS_EXT3_SB(sb) && ((def_mount_opts & EXT4_DEFM_NODELALLOC) == 0)) set_opt(sb, DELALLOC); if (!parse_options((char *) sbi->s_es->s_mount_opts, sb, &journal_devnum, &journal_ioprio, NULL, 0)) { ext4_msg(sb, KERN_WARNING, "failed to parse options in superblock: %s", sbi->s_es->s_mount_opts); } if (!parse_options((char *) data, sb, &journal_devnum, &journal_ioprio, NULL, 0)) goto failed_mount; sb->s_flags = (sb->s_flags & ~MS_POSIXACL) | (test_opt(sb, POSIX_ACL) ? MS_POSIXACL : 0); if (le32_to_cpu(es->s_rev_level) == EXT4_GOOD_OLD_REV && (EXT4_HAS_COMPAT_FEATURE(sb, ~0U) || EXT4_HAS_RO_COMPAT_FEATURE(sb, ~0U) || EXT4_HAS_INCOMPAT_FEATURE(sb, ~0U))) ext4_msg(sb, KERN_WARNING, "feature flags set on rev 0 fs, " "running e2fsck is recommended"); /* * Check feature flags regardless of the revision level, since we * previously didn't change the revision level when setting the flags, * so there is a chance incompat flags are set on a rev 0 filesystem. */ if (!ext4_feature_set_ok(sb, (sb->s_flags & MS_RDONLY))) goto failed_mount; blocksize = BLOCK_SIZE << le32_to_cpu(es->s_log_block_size); if (blocksize < EXT4_MIN_BLOCK_SIZE || blocksize > EXT4_MAX_BLOCK_SIZE) { ext4_msg(sb, KERN_ERR, "Unsupported filesystem blocksize %d", blocksize); goto failed_mount; } if (sb->s_blocksize != blocksize) { /* Validate the filesystem blocksize */ if (!sb_set_blocksize(sb, blocksize)) { ext4_msg(sb, KERN_ERR, "bad block size %d", blocksize); goto failed_mount; } brelse(bh); logical_sb_block = sb_block * EXT4_MIN_BLOCK_SIZE; offset = do_div(logical_sb_block, blocksize); bh = sb_bread(sb, logical_sb_block); if (!bh) { ext4_msg(sb, KERN_ERR, "Can't read superblock on 2nd try"); goto failed_mount; } es = (struct ext4_super_block *)(((char *)bh->b_data) + offset); sbi->s_es = es; if (es->s_magic != cpu_to_le16(EXT4_SUPER_MAGIC)) { ext4_msg(sb, KERN_ERR, "Magic mismatch, very weird!"); goto failed_mount; } } has_huge_files = EXT4_HAS_RO_COMPAT_FEATURE(sb, EXT4_FEATURE_RO_COMPAT_HUGE_FILE); sbi->s_bitmap_maxbytes = ext4_max_bitmap_size(sb->s_blocksize_bits, has_huge_files); sb->s_maxbytes = ext4_max_size(sb->s_blocksize_bits, has_huge_files); if (le32_to_cpu(es->s_rev_level) == EXT4_GOOD_OLD_REV) { sbi->s_inode_size = EXT4_GOOD_OLD_INODE_SIZE; sbi->s_first_ino = EXT4_GOOD_OLD_FIRST_INO; } else { sbi->s_inode_size = le16_to_cpu(es->s_inode_size); sbi->s_first_ino = le32_to_cpu(es->s_first_ino); if ((sbi->s_inode_size < EXT4_GOOD_OLD_INODE_SIZE) || (!is_power_of_2(sbi->s_inode_size)) || (sbi->s_inode_size > blocksize)) { ext4_msg(sb, KERN_ERR, "unsupported inode size: %d", sbi->s_inode_size); goto failed_mount; } if (sbi->s_inode_size > EXT4_GOOD_OLD_INODE_SIZE) sb->s_time_gran = 1 << (EXT4_EPOCH_BITS - 2); } sbi->s_desc_size = le16_to_cpu(es->s_desc_size); if (EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_64BIT)) { if (sbi->s_desc_size < EXT4_MIN_DESC_SIZE_64BIT || sbi->s_desc_size > EXT4_MAX_DESC_SIZE || !is_power_of_2(sbi->s_desc_size)) { ext4_msg(sb, KERN_ERR, "unsupported descriptor size %lu", sbi->s_desc_size); goto failed_mount; } } else sbi->s_desc_size = EXT4_MIN_DESC_SIZE; sbi->s_blocks_per_group = le32_to_cpu(es->s_blocks_per_group); sbi->s_inodes_per_group = le32_to_cpu(es->s_inodes_per_group); if (EXT4_INODE_SIZE(sb) == 0 || EXT4_INODES_PER_GROUP(sb) == 0) goto cantfind_ext4; sbi->s_inodes_per_block = blocksize / EXT4_INODE_SIZE(sb); if (sbi->s_inodes_per_block == 0) goto cantfind_ext4; sbi->s_itb_per_group = sbi->s_inodes_per_group / sbi->s_inodes_per_block; sbi->s_desc_per_block = blocksize / EXT4_DESC_SIZE(sb); sbi->s_sbh = bh; sbi->s_mount_state = le16_to_cpu(es->s_state); sbi->s_addr_per_block_bits = ilog2(EXT4_ADDR_PER_BLOCK(sb)); sbi->s_desc_per_block_bits = ilog2(EXT4_DESC_PER_BLOCK(sb)); for (i = 0; i < 4; i++) sbi->s_hash_seed[i] = le32_to_cpu(es->s_hash_seed[i]); sbi->s_def_hash_version = es->s_def_hash_version; i = le32_to_cpu(es->s_flags); if (i & EXT2_FLAGS_UNSIGNED_HASH) sbi->s_hash_unsigned = 3; else if ((i & EXT2_FLAGS_SIGNED_HASH) == 0) { #ifdef __CHAR_UNSIGNED__ es->s_flags |= cpu_to_le32(EXT2_FLAGS_UNSIGNED_HASH); sbi->s_hash_unsigned = 3; #else es->s_flags |= cpu_to_le32(EXT2_FLAGS_SIGNED_HASH); #endif sb->s_dirt = 1; } if (sbi->s_blocks_per_group > blocksize * 8) { ext4_msg(sb, KERN_ERR, "#blocks per group too big: %lu", sbi->s_blocks_per_group); goto failed_mount; } if (sbi->s_inodes_per_group > blocksize * 8) { ext4_msg(sb, KERN_ERR, "#inodes per group too big: %lu", sbi->s_inodes_per_group); goto failed_mount; } /* * Test whether we have more sectors than will fit in sector_t, * and whether the max offset is addressable by the page cache. */ err = generic_check_addressable(sb->s_blocksize_bits, ext4_blocks_count(es)); if (err) { ext4_msg(sb, KERN_ERR, "filesystem" " too large to mount safely on this system"); if (sizeof(sector_t) < 8) ext4_msg(sb, KERN_WARNING, "CONFIG_LBDAF not enabled"); ret = err; goto failed_mount; } if (EXT4_BLOCKS_PER_GROUP(sb) == 0) goto cantfind_ext4; /* check blocks count against device size */ blocks_count = sb->s_bdev->bd_inode->i_size >> sb->s_blocksize_bits; if (blocks_count && ext4_blocks_count(es) > blocks_count) { ext4_msg(sb, KERN_WARNING, "bad geometry: block count %llu " "exceeds size of device (%llu blocks)", ext4_blocks_count(es), blocks_count); goto failed_mount; } /* * It makes no sense for the first data block to be beyond the end * of the filesystem. */ if (le32_to_cpu(es->s_first_data_block) >= ext4_blocks_count(es)) { ext4_msg(sb, KERN_WARNING, "bad geometry: first data" "block %u is beyond end of filesystem (%llu)", le32_to_cpu(es->s_first_data_block), ext4_blocks_count(es)); goto failed_mount; } blocks_count = (ext4_blocks_count(es) - le32_to_cpu(es->s_first_data_block) + EXT4_BLOCKS_PER_GROUP(sb) - 1); do_div(blocks_count, EXT4_BLOCKS_PER_GROUP(sb)); if (blocks_count > ((uint64_t)1<<32) - EXT4_DESC_PER_BLOCK(sb)) { ext4_msg(sb, KERN_WARNING, "groups count too large: %u " "(block count %llu, first data block %u, " "blocks per group %lu)", sbi->s_groups_count, ext4_blocks_count(es), le32_to_cpu(es->s_first_data_block), EXT4_BLOCKS_PER_GROUP(sb)); goto failed_mount; } sbi->s_groups_count = blocks_count; sbi->s_blockfile_groups = min_t(ext4_group_t, sbi->s_groups_count, (EXT4_MAX_BLOCK_FILE_PHYS / EXT4_BLOCKS_PER_GROUP(sb))); db_count = (sbi->s_groups_count + EXT4_DESC_PER_BLOCK(sb) - 1) / EXT4_DESC_PER_BLOCK(sb); sbi->s_group_desc = kmalloc(db_count * sizeof(struct buffer_head *), GFP_KERNEL); if (sbi->s_group_desc == NULL) { ext4_msg(sb, KERN_ERR, "not enough memory"); goto failed_mount; } #ifdef CONFIG_PROC_FS if (ext4_proc_root) sbi->s_proc = proc_mkdir(sb->s_id, ext4_proc_root); #endif bgl_lock_init(sbi->s_blockgroup_lock); for (i = 0; i < db_count; i++) { block = descriptor_loc(sb, logical_sb_block, i); sbi->s_group_desc[i] = sb_bread(sb, block); if (!sbi->s_group_desc[i]) { ext4_msg(sb, KERN_ERR, "can't read group descriptor %d", i); db_count = i; goto failed_mount2; } } if (!ext4_check_descriptors(sb, &first_not_zeroed)) { ext4_msg(sb, KERN_ERR, "group descriptors corrupted!"); goto failed_mount2; } if (EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_FLEX_BG)) if (!ext4_fill_flex_info(sb)) { ext4_msg(sb, KERN_ERR, "unable to initialize " "flex_bg meta info!"); goto failed_mount2; } sbi->s_gdb_count = db_count; get_random_bytes(&sbi->s_next_generation, sizeof(u32)); spin_lock_init(&sbi->s_next_gen_lock); err = percpu_counter_init(&sbi->s_freeblocks_counter, ext4_count_free_blocks(sb)); if (!err) { err = percpu_counter_init(&sbi->s_freeinodes_counter, ext4_count_free_inodes(sb)); } if (!err) { err = percpu_counter_init(&sbi->s_dirs_counter, ext4_count_dirs(sb)); } if (!err) { err = percpu_counter_init(&sbi->s_dirtyblocks_counter, 0); } if (err) { ext4_msg(sb, KERN_ERR, "insufficient memory"); goto failed_mount3; } sbi->s_stripe = ext4_get_stripe_size(sbi); sbi->s_max_writeback_mb_bump = 128; /* * set up enough so that it can read an inode */ if (!test_opt(sb, NOLOAD) && EXT4_HAS_COMPAT_FEATURE(sb, EXT4_FEATURE_COMPAT_HAS_JOURNAL)) sb->s_op = &ext4_sops; else sb->s_op = &ext4_nojournal_sops; sb->s_export_op = &ext4_export_ops; sb->s_xattr = ext4_xattr_handlers; #ifdef CONFIG_QUOTA sb->s_qcop = &ext4_qctl_operations; sb->dq_op = &ext4_quota_operations; #endif memcpy(sb->s_uuid, es->s_uuid, sizeof(es->s_uuid)); INIT_LIST_HEAD(&sbi->s_orphan); /* unlinked but open files */ mutex_init(&sbi->s_orphan_lock); mutex_init(&sbi->s_resize_lock); sb->s_root = NULL; needs_recovery = (es->s_last_orphan != 0 || EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_RECOVER)); /* * The first inode we look at is the journal inode. Don't try * root first: it may be modified in the journal! */ if (!test_opt(sb, NOLOAD) && EXT4_HAS_COMPAT_FEATURE(sb, EXT4_FEATURE_COMPAT_HAS_JOURNAL)) { if (ext4_load_journal(sb, es, journal_devnum)) goto failed_mount3; } else if (test_opt(sb, NOLOAD) && !(sb->s_flags & MS_RDONLY) && EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_RECOVER)) { ext4_msg(sb, KERN_ERR, "required journal recovery " "suppressed and not mounted read-only"); goto failed_mount_wq; } else { clear_opt(sb, DATA_FLAGS); set_opt(sb, WRITEBACK_DATA); sbi->s_journal = NULL; needs_recovery = 0; goto no_journal; } if (ext4_blocks_count(es) > 0xffffffffULL && !jbd2_journal_set_features(EXT4_SB(sb)->s_journal, 0, 0, JBD2_FEATURE_INCOMPAT_64BIT)) { ext4_msg(sb, KERN_ERR, "Failed to set 64-bit journal feature"); goto failed_mount_wq; } if (test_opt(sb, JOURNAL_ASYNC_COMMIT)) { jbd2_journal_set_features(sbi->s_journal, JBD2_FEATURE_COMPAT_CHECKSUM, 0, JBD2_FEATURE_INCOMPAT_ASYNC_COMMIT); } else if (test_opt(sb, JOURNAL_CHECKSUM)) { jbd2_journal_set_features(sbi->s_journal, JBD2_FEATURE_COMPAT_CHECKSUM, 0, 0); jbd2_journal_clear_features(sbi->s_journal, 0, 0, JBD2_FEATURE_INCOMPAT_ASYNC_COMMIT); } else { jbd2_journal_clear_features(sbi->s_journal, JBD2_FEATURE_COMPAT_CHECKSUM, 0, JBD2_FEATURE_INCOMPAT_ASYNC_COMMIT); } /* We have now updated the journal if required, so we can * validate the data journaling mode. */ switch (test_opt(sb, DATA_FLAGS)) { case 0: /* No mode set, assume a default based on the journal * capabilities: ORDERED_DATA if the journal can * cope, else JOURNAL_DATA */ if (jbd2_journal_check_available_features (sbi->s_journal, 0, 0, JBD2_FEATURE_INCOMPAT_REVOKE)) set_opt(sb, ORDERED_DATA); else set_opt(sb, JOURNAL_DATA); break; case EXT4_MOUNT_ORDERED_DATA: case EXT4_MOUNT_WRITEBACK_DATA: if (!jbd2_journal_check_available_features (sbi->s_journal, 0, 0, JBD2_FEATURE_INCOMPAT_REVOKE)) { ext4_msg(sb, KERN_ERR, "Journal does not support " "requested data journaling mode"); goto failed_mount_wq; } default: break; } set_task_ioprio(sbi->s_journal->j_task, journal_ioprio); /* * The journal may have updated the bg summary counts, so we * need to update the global counters. */ percpu_counter_set(&sbi->s_freeblocks_counter, ext4_count_free_blocks(sb)); percpu_counter_set(&sbi->s_freeinodes_counter, ext4_count_free_inodes(sb)); percpu_counter_set(&sbi->s_dirs_counter, ext4_count_dirs(sb)); percpu_counter_set(&sbi->s_dirtyblocks_counter, 0); no_journal: /* * The maximum number of concurrent works can be high and * concurrency isn't really necessary. Limit it to 1. */ EXT4_SB(sb)->dio_unwritten_wq = alloc_workqueue("ext4-dio-unwritten", WQ_MEM_RECLAIM | WQ_UNBOUND, 1); if (!EXT4_SB(sb)->dio_unwritten_wq) { printk(KERN_ERR "EXT4-fs: failed to create DIO workqueue\n"); goto failed_mount_wq; } /* * The jbd2_journal_load will have done any necessary log recovery, * so we can safely mount the rest of the filesystem now. */ root = ext4_iget(sb, EXT4_ROOT_INO); if (IS_ERR(root)) { ext4_msg(sb, KERN_ERR, "get root inode failed"); ret = PTR_ERR(root); root = NULL; goto failed_mount4; } if (!S_ISDIR(root->i_mode) || !root->i_blocks || !root->i_size) { ext4_msg(sb, KERN_ERR, "corrupt root inode, run e2fsck"); goto failed_mount4; } sb->s_root = d_alloc_root(root); if (!sb->s_root) { ext4_msg(sb, KERN_ERR, "get root dentry failed"); ret = -ENOMEM; goto failed_mount4; } ext4_setup_super(sb, es, sb->s_flags & MS_RDONLY); /* determine the minimum size of new large inodes, if present */ if (sbi->s_inode_size > EXT4_GOOD_OLD_INODE_SIZE) { sbi->s_want_extra_isize = sizeof(struct ext4_inode) - EXT4_GOOD_OLD_INODE_SIZE; if (EXT4_HAS_RO_COMPAT_FEATURE(sb, EXT4_FEATURE_RO_COMPAT_EXTRA_ISIZE)) { if (sbi->s_want_extra_isize < le16_to_cpu(es->s_want_extra_isize)) sbi->s_want_extra_isize = le16_to_cpu(es->s_want_extra_isize); if (sbi->s_want_extra_isize < le16_to_cpu(es->s_min_extra_isize)) sbi->s_want_extra_isize = le16_to_cpu(es->s_min_extra_isize); } } /* Check if enough inode space is available */ if (EXT4_GOOD_OLD_INODE_SIZE + sbi->s_want_extra_isize > sbi->s_inode_size) { sbi->s_want_extra_isize = sizeof(struct ext4_inode) - EXT4_GOOD_OLD_INODE_SIZE; ext4_msg(sb, KERN_INFO, "required extra inode space not" "available"); } if (test_opt(sb, DELALLOC) && (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_JOURNAL_DATA)) { ext4_msg(sb, KERN_WARNING, "Ignoring delalloc option - " "requested data journaling mode"); clear_opt(sb, DELALLOC); } if (test_opt(sb, DIOREAD_NOLOCK)) { if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_JOURNAL_DATA) { ext4_msg(sb, KERN_WARNING, "Ignoring dioread_nolock " "option - requested data journaling mode"); clear_opt(sb, DIOREAD_NOLOCK); } if (sb->s_blocksize < PAGE_SIZE) { ext4_msg(sb, KERN_WARNING, "Ignoring dioread_nolock " "option - block size is too small"); clear_opt(sb, DIOREAD_NOLOCK); } } err = ext4_setup_system_zone(sb); if (err) { ext4_msg(sb, KERN_ERR, "failed to initialize system " "zone (%d)", err); goto failed_mount4; } ext4_ext_init(sb); err = ext4_mb_init(sb, needs_recovery); if (err) { ext4_msg(sb, KERN_ERR, "failed to initialize mballoc (%d)", err); goto failed_mount4; } err = ext4_register_li_request(sb, first_not_zeroed); if (err) goto failed_mount4; sbi->s_kobj.kset = ext4_kset; init_completion(&sbi->s_kobj_unregister); err = kobject_init_and_add(&sbi->s_kobj, &ext4_ktype, NULL, "%s", sb->s_id); if (err) { ext4_mb_release(sb); ext4_ext_release(sb); goto failed_mount4; }; EXT4_SB(sb)->s_mount_state |= EXT4_ORPHAN_FS; ext4_orphan_cleanup(sb, es); EXT4_SB(sb)->s_mount_state &= ~EXT4_ORPHAN_FS; if (needs_recovery) { ext4_msg(sb, KERN_INFO, "recovery complete"); ext4_mark_recovery_complete(sb, es); } if (EXT4_SB(sb)->s_journal) { if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_JOURNAL_DATA) descr = " journalled data mode"; else if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_ORDERED_DATA) descr = " ordered data mode"; else descr = " writeback data mode"; } else descr = "out journal"; ext4_msg(sb, KERN_INFO, "mounted filesystem with%s. " "Opts: %s%s%s", descr, sbi->s_es->s_mount_opts, *sbi->s_es->s_mount_opts ? "; " : "", orig_data); init_timer(&sbi->s_err_report); sbi->s_err_report.function = print_daily_error_info; sbi->s_err_report.data = (unsigned long) sb; if (es->s_error_count) mod_timer(&sbi->s_err_report, jiffies + 300*HZ); /* 5 minutes */ kfree(orig_data); return 0; cantfind_ext4: if (!silent) ext4_msg(sb, KERN_ERR, "VFS: Can't find ext4 filesystem"); goto failed_mount; failed_mount4: iput(root); sb->s_root = NULL; ext4_msg(sb, KERN_ERR, "mount failed"); destroy_workqueue(EXT4_SB(sb)->dio_unwritten_wq); failed_mount_wq: ext4_release_system_zone(sb); if (sbi->s_journal) { jbd2_journal_destroy(sbi->s_journal); sbi->s_journal = NULL; } failed_mount3: if (sbi->s_flex_groups) { if (is_vmalloc_addr(sbi->s_flex_groups)) vfree(sbi->s_flex_groups); else kfree(sbi->s_flex_groups); } percpu_counter_destroy(&sbi->s_freeblocks_counter); percpu_counter_destroy(&sbi->s_freeinodes_counter); percpu_counter_destroy(&sbi->s_dirs_counter); percpu_counter_destroy(&sbi->s_dirtyblocks_counter); failed_mount2: for (i = 0; i < db_count; i++) brelse(sbi->s_group_desc[i]); kfree(sbi->s_group_desc); failed_mount: if (sbi->s_proc) { remove_proc_entry(sb->s_id, ext4_proc_root); } #ifdef CONFIG_QUOTA for (i = 0; i < MAXQUOTAS; i++) kfree(sbi->s_qf_names[i]); #endif ext4_blkdev_remove(sbi); brelse(bh); out_fail: sb->s_fs_info = NULL; kfree(sbi->s_blockgroup_lock); kfree(sbi); out_free_orig: kfree(orig_data); return ret; } Commit Message: ext4: init timer earlier to avoid a kernel panic in __save_error_info During mount, when we fail to open journal inode or root inode, the __save_error_info will mod_timer. But actually s_err_report isn't initialized yet and the kernel oops. The detailed information can be found https://bugzilla.kernel.org/show_bug.cgi?id=32082. The best way is to check whether the timer s_err_report is initialized or not. But it seems that in include/linux/timer.h, we can't find a good function to check the status of this timer, so this patch just move the initializtion of s_err_report earlier so that we can avoid the kernel panic. The corresponding del_timer is also added in the error path. Reported-by: Sami Liedes <[email protected]> Signed-off-by: Tao Ma <[email protected]> Signed-off-by: "Theodore Ts'o" <[email protected]> CWE ID: Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: PHP_FUNCTION(pg_get_notify) { zval *pgsql_link; int id = -1; long result_type = PGSQL_ASSOC; PGconn *pgsql; PGnotify *pgsql_notify; if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS() TSRMLS_CC, "r|l", &pgsql_link, &result_type) == FAILURE) { RETURN_FALSE; } ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink); if (!(result_type & PGSQL_BOTH)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid result type"); RETURN_FALSE; } PQconsumeInput(pgsql); pgsql_notify = PQnotifies(pgsql); if (!pgsql_notify) { /* no notify message */ RETURN_FALSE; } array_init(return_value); if (result_type & PGSQL_NUM) { add_index_string(return_value, 0, pgsql_notify->relname, 1); add_index_long(return_value, 1, pgsql_notify->be_pid); #if HAVE_PQPROTOCOLVERSION && HAVE_PQPARAMETERSTATUS if (PQprotocolVersion(pgsql) >= 3 && atof(PQparameterStatus(pgsql, "server_version")) >= 9.0) { #else if (atof(PG_VERSION) >= 9.0) { #endif #if HAVE_PQPARAMETERSTATUS add_index_string(return_value, 2, pgsql_notify->extra, 1); #endif } } if (result_type & PGSQL_ASSOC) { add_assoc_string(return_value, "message", pgsql_notify->relname, 1); add_assoc_long(return_value, "pid", pgsql_notify->be_pid); #if HAVE_PQPROTOCOLVERSION && HAVE_PQPARAMETERSTATUS if (PQprotocolVersion(pgsql) >= 3 && atof(PQparameterStatus(pgsql, "server_version")) >= 9.0) { #else if (atof(PG_VERSION) >= 9.0) { #endif #if HAVE_PQPARAMETERSTATUS add_assoc_string(return_value, "payload", pgsql_notify->extra, 1); #endif } } PQfreemem(pgsql_notify); } /* }}} */ /* {{{ proto int pg_get_pid([resource connection) Get backend(server) pid */ PHP_FUNCTION(pg_get_pid) { zval *pgsql_link; int id = -1; PGconn *pgsql; if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS() TSRMLS_CC, "r", &pgsql_link) == FAILURE) { RETURN_FALSE; } ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink); RETURN_LONG(PQbackendPID(pgsql)); } /* }}} */ /* {{{ php_pgsql_meta_data * TODO: Add meta_data cache for better performance */ PHP_PGSQL_API int php_pgsql_meta_data(PGconn *pg_link, const char *table_name, zval *meta TSRMLS_DC) { PGresult *pg_result; char *src, *tmp_name, *tmp_name2 = NULL; char *escaped; smart_str querystr = {0}; size_t new_len; int i, num_rows; zval *elem; if (!*table_name) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "The table name must be specified"); return FAILURE; } src = estrdup(table_name); tmp_name = php_strtok_r(src, ".", &tmp_name2); if (!tmp_name2 || !*tmp_name2) { /* Default schema */ tmp_name2 = tmp_name; "SELECT a.attname, a.attnum, t.typname, a.attlen, a.attnotnull, a.atthasdef, a.attndims, t.typtype = 'e' " "FROM pg_class as c, pg_attribute a, pg_type t, pg_namespace n " "WHERE a.attnum > 0 AND a.attrelid = c.oid AND c.relname = '"); escaped = (char *)safe_emalloc(strlen(tmp_name2), 2, 1); new_len = PQescapeStringConn(pg_link, escaped, tmp_name2, strlen(tmp_name2), NULL); if (new_len) { smart_str_appendl(&querystr, escaped, new_len); } efree(escaped); smart_str_appends(&querystr, "' AND c.relnamespace = n.oid AND n.nspname = '"); escaped = (char *)safe_emalloc(strlen(tmp_name), 2, 1); new_len = PQescapeStringConn(pg_link, escaped, tmp_name, strlen(tmp_name), NULL); if (new_len) { smart_str_appendl(&querystr, escaped, new_len); } efree(escaped); smart_str_appends(&querystr, "' AND a.atttypid = t.oid ORDER BY a.attnum;"); smart_str_0(&querystr); efree(src); pg_result = PQexec(pg_link, querystr.c); if (PQresultStatus(pg_result) != PGRES_TUPLES_OK || (num_rows = PQntuples(pg_result)) == 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Table '%s' doesn't exists", table_name); smart_str_free(&querystr); PQclear(pg_result); return FAILURE; } smart_str_free(&querystr); for (i = 0; i < num_rows; i++) { char *name; MAKE_STD_ZVAL(elem); array_init(elem); add_assoc_long(elem, "num", atoi(PQgetvalue(pg_result,i,1))); add_assoc_string(elem, "type", PQgetvalue(pg_result,i,2), 1); add_assoc_long(elem, "len", atoi(PQgetvalue(pg_result,i,3))); if (!strcmp(PQgetvalue(pg_result,i,4), "t")) { add_assoc_bool(elem, "not null", 1); } else { add_assoc_bool(elem, "not null", 0); } if (!strcmp(PQgetvalue(pg_result,i,5), "t")) { add_assoc_bool(elem, "has default", 1); } else { add_assoc_bool(elem, "has default", 0); } add_assoc_long(elem, "array dims", atoi(PQgetvalue(pg_result,i,6))); if (!strcmp(PQgetvalue(pg_result,i,7), "t")) { add_assoc_bool(elem, "is enum", 1); } else { add_assoc_bool(elem, "is enum", 0); } name = PQgetvalue(pg_result,i,0); add_assoc_zval(meta, name, elem); } PQclear(pg_result); return SUCCESS; } /* }}} */ Commit Message: CWE ID: Target: 1 Example 2: Code: bool AppListControllerDelegate::HasOptionsPage( Profile* profile, const std::string& app_id) { const extensions::Extension* extension = GetExtension(profile, app_id); return extensions::util::IsAppLaunchableWithoutEnabling(app_id, profile) && extension && extensions::OptionsPageInfo::HasOptionsPage(extension); } Commit Message: [Extensions] Add GetInstalledExtension() method to ExtensionRegistry This CL adds GetInstalledExtension() method to ExtensionRegistry and uses it instead of deprecated ExtensionService::GetInstalledExtension() in chrome/browser/ui/app_list/. Part of removing the deprecated GetInstalledExtension() call from the ExtensionService. BUG=489687 Review URL: https://codereview.chromium.org/1130353010 Cr-Commit-Position: refs/heads/master@{#333036} CWE ID: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void SoftGSM::initPorts() { OMX_PARAM_PORTDEFINITIONTYPE def; InitOMXParams(&def); def.nPortIndex = 0; def.eDir = OMX_DirInput; def.nBufferCountMin = kNumBuffers; def.nBufferCountActual = def.nBufferCountMin; def.nBufferSize = 1024 / kMSGSMFrameSize * kMSGSMFrameSize; def.bEnabled = OMX_TRUE; def.bPopulated = OMX_FALSE; def.eDomain = OMX_PortDomainAudio; def.bBuffersContiguous = OMX_FALSE; def.nBufferAlignment = 1; def.format.audio.cMIMEType = const_cast<char *>(MEDIA_MIMETYPE_AUDIO_MSGSM); def.format.audio.pNativeRender = NULL; def.format.audio.bFlagErrorConcealment = OMX_FALSE; def.format.audio.eEncoding = OMX_AUDIO_CodingGSMFR; addPort(def); def.nPortIndex = 1; def.eDir = OMX_DirOutput; def.nBufferCountMin = kNumBuffers; def.nBufferCountActual = def.nBufferCountMin; def.nBufferSize = kMaxNumSamplesPerFrame * sizeof(int16_t); def.bEnabled = OMX_TRUE; def.bPopulated = OMX_FALSE; def.eDomain = OMX_PortDomainAudio; def.bBuffersContiguous = OMX_FALSE; def.nBufferAlignment = 2; def.format.audio.cMIMEType = const_cast<char *>("audio/raw"); def.format.audio.pNativeRender = NULL; def.format.audio.bFlagErrorConcealment = OMX_FALSE; def.format.audio.eEncoding = OMX_AUDIO_CodingPCM; addPort(def); } Commit Message: codecs: check OMX buffer size before use in (gsm|g711)dec Bug: 27793163 Bug: 27793367 Change-Id: Iec3de8a237ee2379d87a8371c13e543878c6652c CWE ID: CWE-119 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void VRDisplay::ProcessScheduledAnimations(double timestamp) { Document* doc = this->GetDocument(); if (!doc || display_blurred_ || !scripted_animation_controller_) return; TRACE_EVENT1("gpu", "VRDisplay::OnVSync", "frame", vr_frame_id_); AutoReset<bool> animating(&in_animation_frame_, true); pending_raf_ = false; scripted_animation_controller_->ServiceScriptedAnimations(timestamp); if (is_presenting_ && !capabilities_->hasExternalDisplay()) { Platform::Current()->CurrentThread()->GetWebTaskRunner()->PostTask( BLINK_FROM_HERE, WTF::Bind(&VRDisplay::ProcessScheduledWindowAnimations, WrapWeakPersistent(this), timestamp)); } } 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: Target: 1 Example 2: Code: static bool vmx_mpx_supported(void) { return (vmcs_config.vmexit_ctrl & VM_EXIT_CLEAR_BNDCFGS) && (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_BNDCFGS); } Commit Message: x86,kvm,vmx: Preserve CR4 across VM entry CR4 isn't constant; at least the TSD and PCE bits can vary. TBH, treating CR0 and CR3 as constant scares me a bit, too, but it looks like it's correct. This adds a branch and a read from cr4 to each vm entry. Because it is extremely likely that consecutive entries into the same vcpu will have the same host cr4 value, this fixes up the vmcs instead of restoring cr4 after the fact. A subsequent patch will add a kernel-wide cr4 shadow, reducing the overhead in the common case to just two memory reads and a branch. Signed-off-by: Andy Lutomirski <[email protected]> Acked-by: Paolo Bonzini <[email protected]> Cc: [email protected] Cc: Petr Matousek <[email protected]> Cc: Gleb Natapov <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-399 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void ftrace_exports(struct ring_buffer_event *event) { struct trace_export *export; preempt_disable_notrace(); export = rcu_dereference_raw_notrace(ftrace_exports_list); while (export) { trace_process_export(export, event); export = rcu_dereference_raw_notrace(export->next); } preempt_enable_notrace(); } Commit Message: Merge branch 'page-refs' (page ref overflow) Merge page ref overflow branch. Jann Horn reported that he can overflow the page ref count with sufficient memory (and a filesystem that is intentionally extremely slow). Admittedly it's not exactly easy. To have more than four billion references to a page requires a minimum of 32GB of kernel memory just for the pointers to the pages, much less any metadata to keep track of those pointers. Jann needed a total of 140GB of memory and a specially crafted filesystem that leaves all reads pending (in order to not ever free the page references and just keep adding more). Still, we have a fairly straightforward way to limit the two obvious user-controllable sources of page references: direct-IO like page references gotten through get_user_pages(), and the splice pipe page duplication. So let's just do that. * branch page-refs: fs: prevent page refcount overflow in pipe_buf_get mm: prevent get_user_pages() from overflowing page refcount mm: add 'try_get_page()' helper function mm: make page ref count overflow check tighter and more explicit CWE ID: CWE-416 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void SendTabToSelfInfoBarDelegate::OpenTab() { NOTIMPLEMENTED(); } Commit Message: [SendTabToSelf] Added logic to display an infobar for the feature. This CL is one of many to come. It covers: * Creation of the infobar from the SendTabToSelfInfoBarController * Plumbed the call to create the infobar to the native code. * Open the link when user taps on the link In follow-up CLs, the following will be done: * Instantiate the InfobarController in the ChromeActivity * Listen for Model changes in the Controller Bug: 949233,963193 Change-Id: I5df1359debb5f0f35c32c2df3b691bf9129cdeb8 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1604406 Reviewed-by: Tommy Nyquist <[email protected]> Reviewed-by: Avi Drissman <[email protected]> Reviewed-by: Mikel Astiz <[email protected]> Reviewed-by: sebsg <[email protected]> Reviewed-by: Jeffrey Cohen <[email protected]> Reviewed-by: Matthew Jones <[email protected]> Commit-Queue: Tanya Gupta <[email protected]> Cr-Commit-Position: refs/heads/master@{#660854} CWE ID: CWE-190 Target: 1 Example 2: Code: daemon_msg_setsampling_req(uint8 ver, struct daemon_slpars *pars, uint32 plen, struct rpcap_sampling *samp_param) { char errbuf[PCAP_ERRBUF_SIZE]; // buffer for network errors char errmsgbuf[PCAP_ERRBUF_SIZE]; struct rpcap_header header; struct rpcap_sampling rpcap_samp; int status; status = rpcapd_recv(pars->sockctrl, (char *) &rpcap_samp, sizeof(struct rpcap_sampling), &plen, errmsgbuf); if (status == -1) { return -1; } if (status == -2) { goto error; } samp_param->method = rpcap_samp.method; samp_param->value = ntohl(rpcap_samp.value); rpcap_createhdr(&header, ver, RPCAP_MSG_SETSAMPLING_REPLY, 0, 0); if (sock_send(pars->sockctrl, (char *) &header, sizeof (struct rpcap_header), errbuf, PCAP_ERRBUF_SIZE) == -1) { rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf); return -1; } if (rpcapd_discard(pars->sockctrl, plen) == -1) { return -1; } return 0; error: if (rpcap_senderror(pars->sockctrl, ver, PCAP_ERR_SETSAMPLING, errmsgbuf, errbuf) == -1) { rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf); return -1; } if (rpcapd_discard(pars->sockctrl, plen) == -1) { return -1; } return 0; } Commit Message: In the open request, reject capture sources that are URLs. You shouldn't be able to ask a server to open a remote device on some *other* server; just open it yourself. This addresses Include Security issue F13: [libpcap] Remote Packet Capture Daemon Allows Opening Capture URLs. CWE ID: CWE-918 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void VP8XChunk::height(XMP_Uns32 val) { PutLE24(&this->data[7], val - 1); } Commit Message: CWE ID: CWE-20 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: EncodedJSValue JSC_HOST_CALL jsTestActiveDOMObjectPrototypeFunctionExcitingFunction(ExecState* exec) { JSValue thisValue = exec->hostThisValue(); if (!thisValue.inherits(&JSTestActiveDOMObject::s_info)) return throwVMTypeError(exec); JSTestActiveDOMObject* castedThis = jsCast<JSTestActiveDOMObject*>(asObject(thisValue)); ASSERT_GC_OBJECT_INHERITS(castedThis, &JSTestActiveDOMObject::s_info); if (!castedThis->allowsAccessFrom(exec)) return JSValue::encode(jsUndefined()); TestActiveDOMObject* impl = static_cast<TestActiveDOMObject*>(castedThis->impl()); if (exec->argumentCount() < 1) return throwVMError(exec, createTypeError(exec, "Not enough arguments")); Node* nextChild(toNode(MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined))); if (exec->hadException()) return JSValue::encode(jsUndefined()); impl->excitingFunction(nextChild); 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 Target: 1 Example 2: Code: void V8TestObject::VoidMethodVariadicStringArgMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info) { RUNTIME_CALL_TIMER_SCOPE_DISABLED_BY_DEFAULT(info.GetIsolate(), "Blink_TestObject_voidMethodVariadicStringArg"); test_object_v8_internal::VoidMethodVariadicStringArgMethod(info); } Commit Message: bindings: Support "attribute FrozenArray<T>?" Adds a quick hack to support a case of "attribute FrozenArray<T>?". Bug: 1028047 Change-Id: Ib3cecc4beb6bcc0fb0dbc667aca595454cc90c86 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1933866 Reviewed-by: Hitoshi Yoshida <[email protected]> Commit-Queue: Yuki Shiino <[email protected]> Cr-Commit-Position: refs/heads/master@{#718676} CWE ID: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: status_t ACodec::freeBuffersOnPort(OMX_U32 portIndex) { status_t err = OK; for (size_t i = mBuffers[portIndex].size(); i > 0;) { i--; status_t err2 = freeBuffer(portIndex, i); if (err == OK) { err = err2; } } mDealer[portIndex].clear(); return err; } Commit Message: Fix initialization of AAC presentation struct Otherwise the new size checks trip on this. Bug: 27207275 Change-Id: I1f8f01097e3a88ff041b69279a6121be842f1766 CWE ID: CWE-119 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: IDNSpoofChecker::IDNSpoofChecker() { UErrorCode status = U_ZERO_ERROR; checker_ = uspoof_open(&status); if (U_FAILURE(status)) { checker_ = nullptr; return; } uspoof_setRestrictionLevel(checker_, USPOOF_HIGHLY_RESTRICTIVE); SetAllowedUnicodeSet(&status); int32_t checks = uspoof_getChecks(checker_, &status) | USPOOF_AUX_INFO; uspoof_setChecks(checker_, checks, &status); deviation_characters_ = icu::UnicodeSet( UNICODE_STRING_SIMPLE("[\\u00df\\u03c2\\u200c\\u200d]"), status); deviation_characters_.freeze(); non_ascii_latin_letters_ = icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Latin:] - [a-zA-Z]]"), status); non_ascii_latin_letters_.freeze(); kana_letters_exceptions_ = icu::UnicodeSet( UNICODE_STRING_SIMPLE("[\\u3078-\\u307a\\u30d8-\\u30da\\u30fb-\\u30fe]"), status); kana_letters_exceptions_.freeze(); combining_diacritics_exceptions_ = icu::UnicodeSet(UNICODE_STRING_SIMPLE("[\\u0300-\\u0339]"), status); combining_diacritics_exceptions_.freeze(); cyrillic_letters_latin_alike_ = icu::UnicodeSet( icu::UnicodeString::fromUTF8("[асԁеһіјӏорԛѕԝхуъЬҽпгѵѡ]"), status); cyrillic_letters_latin_alike_.freeze(); cyrillic_letters_ = icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Cyrl:]]"), status); cyrillic_letters_.freeze(); DCHECK(U_SUCCESS(status)); lgc_letters_n_ascii_ = icu::UnicodeSet( UNICODE_STRING_SIMPLE("[[:Latin:][:Greek:][:Cyrillic:][0-9\\u002e_" "\\u002d][\\u0300-\\u0339]]"), status); lgc_letters_n_ascii_.freeze(); UParseError parse_error; diacritic_remover_.reset(icu::Transliterator::createFromRules( UNICODE_STRING_SIMPLE("DropAcc"), icu::UnicodeString::fromUTF8("::NFD; ::[:Nonspacing Mark:] Remove; ::NFC;" " ł > l; ø > o; đ > d;"), UTRANS_FORWARD, parse_error, status)); extra_confusable_mapper_.reset(icu::Transliterator::createFromRules( UNICODE_STRING_SIMPLE("ExtraConf"), icu::UnicodeString::fromUTF8("[þϼҏ] > p; [ħнћңҥӈӊԧԩ] > h;" "[ĸκкқҝҟҡӄԟ] > k; [ŋп] > n; [ŧтҭ] > t;" "[ƅьҍв] > b; [ωшщฟ] > w; [мӎ] > m;" "[єҽҿၔ] > e; ґ > r; ғ > f; [ҫင] > c;" "ұ > y; [χҳӽӿ] > x;" #if defined(OS_WIN) "ӏ > i;" #else "ӏ > l;" #endif "ԃ > d; [ԍဌ] > g; [ടร] > s; ၂ > j"), UTRANS_FORWARD, parse_error, status)); DCHECK(U_SUCCESS(status)) << "Spoofchecker initalization failed due to an error: " << u_errorName(status); } Commit Message: Add more to confusables list U+04FB (ӻ) to f U+050F (ԏ) to t U+050B (ԋ) and U+0527 (ԧ) to h U+0437(з) and U+04E1(ӡ) to 3 Add tests for the above entries and tests for ASCII-digit spoofing. Bug: 816769,820068 Test: components_unittests --gtest_filter=*IDN* Change-Id: I6cd0a7e97cd0ec2df522ce30f632acfd7b78eee2 Reviewed-on: https://chromium-review.googlesource.com/962875 Reviewed-by: Peter Kasting <[email protected]> Commit-Queue: Peter Kasting <[email protected]> Cr-Commit-Position: refs/heads/master@{#543600} CWE ID: Target: 1 Example 2: Code: OobeUI::~OobeUI() { core_handler_->SetDelegate(nullptr); network_dropdown_handler_->RemoveObserver(error_screen_handler_); } Commit Message: One polymer_config.js to rule them all. [email protected],[email protected],[email protected] BUG=425626 Review URL: https://codereview.chromium.org/1224783005 Cr-Commit-Position: refs/heads/master@{#337882} CWE ID: CWE-399 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: PHPAPI ps_module *_php_find_ps_module(char *name TSRMLS_DC) /* {{{ */ { ps_module *ret = NULL; ps_module **mod; int i; for (i = 0, mod = ps_modules; i < MAX_MODULES; i++, mod++) { if (*mod && !strcasecmp(name, (*mod)->s_name)) { ret = *mod; break; } } return ret; } /* }}} */ Commit Message: CWE ID: CWE-416 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int ssl_scan_clienthello_tlsext(SSL *s, unsigned char **p, unsigned char *limit, int *al) { unsigned short type; unsigned short size; unsigned short len; unsigned char *data = *p; int renegotiate_seen = 0; s->servername_done = 0; s->tlsext_status_type = -1; # ifndef OPENSSL_NO_NEXTPROTONEG s->s3->next_proto_neg_seen = 0; # endif if (s->s3->alpn_selected) { OPENSSL_free(s->s3->alpn_selected); s->s3->alpn_selected = NULL; } s->s3->alpn_selected_len = 0; if (s->cert->alpn_proposed) { OPENSSL_free(s->cert->alpn_proposed); s->cert->alpn_proposed = NULL; } s->cert->alpn_proposed_len = 0; # ifndef OPENSSL_NO_HEARTBEATS s->tlsext_heartbeat &= ~(SSL_TLSEXT_HB_ENABLED | SSL_TLSEXT_HB_DONT_SEND_REQUESTS); # endif # ifndef OPENSSL_NO_EC if (s->options & SSL_OP_SAFARI_ECDHE_ECDSA_BUG) ssl_check_for_safari(s, data, limit); # endif /* !OPENSSL_NO_EC */ /* Clear any signature algorithms extension received */ if (s->cert->peer_sigalgs) { OPENSSL_free(s->cert->peer_sigalgs); s->cert->peer_sigalgs = NULL; } # ifndef OPENSSL_NO_SRP if (s->srp_ctx.login != NULL) { OPENSSL_free(s->srp_ctx.login); s->srp_ctx.login = NULL; } # endif s->srtp_profile = NULL; if (data == limit) goto ri_check; if (data > (limit - 2)) goto err; n2s(data, len); if (data + len != limit) goto err; while (data <= (limit - 4)) { n2s(data, type); n2s(data, size); if (data + size > (limit)) goto err; # if 0 fprintf(stderr, "Received extension type %d size %d\n", type, size); # endif if (s->tlsext_debug_cb) s->tlsext_debug_cb(s, 0, type, data, size, s->tlsext_debug_arg); /*- * The servername extension is treated as follows: * * - Only the hostname type is supported with a maximum length of 255. * - The servername is rejected if too long or if it contains zeros, * in which case an fatal alert is generated. * - The servername field is maintained together with the session cache. * - When a session is resumed, the servername call back invoked in order * to allow the application to position itself to the right context. * - The servername is acknowledged if it is new for a session or when * it is identical to a previously used for the same session. * Applications can control the behaviour. They can at any time * set a 'desirable' servername for a new SSL object. This can be the * case for example with HTTPS when a Host: header field is received and * a renegotiation is requested. In this case, a possible servername * presented in the new client hello is only acknowledged if it matches * the value of the Host: field. * - Applications must use SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION * if they provide for changing an explicit servername context for the * session, i.e. when the session has been established with a servername * extension. * - On session reconnect, the servername extension may be absent. * */ if (type == TLSEXT_TYPE_server_name) { unsigned char *sdata; int servname_type; int dsize; if (size < 2) goto err; n2s(data, dsize); size -= 2; if (dsize > size) goto err; sdata = data; while (dsize > 3) { servname_type = *(sdata++); n2s(sdata, len); dsize -= 3; if (len > dsize) goto err; if (s->servername_done == 0) switch (servname_type) { case TLSEXT_NAMETYPE_host_name: if (!s->hit) { if (s->session->tlsext_hostname) goto err; if (len > TLSEXT_MAXLEN_host_name) { *al = TLS1_AD_UNRECOGNIZED_NAME; return 0; } if ((s->session->tlsext_hostname = OPENSSL_malloc(len + 1)) == NULL) { *al = TLS1_AD_INTERNAL_ERROR; return 0; } memcpy(s->session->tlsext_hostname, sdata, len); s->session->tlsext_hostname[len] = '\0'; if (strlen(s->session->tlsext_hostname) != len) { OPENSSL_free(s->session->tlsext_hostname); s->session->tlsext_hostname = NULL; *al = TLS1_AD_UNRECOGNIZED_NAME; return 0; } s->servername_done = 1; } else s->servername_done = s->session->tlsext_hostname && strlen(s->session->tlsext_hostname) == len && strncmp(s->session->tlsext_hostname, (char *)sdata, len) == 0; break; default: break; } dsize -= len; } if (dsize != 0) goto err; } # ifndef OPENSSL_NO_SRP else if (type == TLSEXT_TYPE_srp) { if (size == 0 || ((len = data[0])) != (size - 1)) goto err; if (s->srp_ctx.login != NULL) goto err; if ((s->srp_ctx.login = OPENSSL_malloc(len + 1)) == NULL) return -1; memcpy(s->srp_ctx.login, &data[1], len); s->srp_ctx.login[len] = '\0'; if (strlen(s->srp_ctx.login) != len) goto err; } # endif # ifndef OPENSSL_NO_EC else if (type == TLSEXT_TYPE_ec_point_formats) { unsigned char *sdata = data; int ecpointformatlist_length = *(sdata++); if (ecpointformatlist_length != size - 1 || ecpointformatlist_length < 1) goto err; if (!s->hit) { if (s->session->tlsext_ecpointformatlist) { OPENSSL_free(s->session->tlsext_ecpointformatlist); s->session->tlsext_ecpointformatlist = NULL; } s->session->tlsext_ecpointformatlist_length = 0; if ((s->session->tlsext_ecpointformatlist = OPENSSL_malloc(ecpointformatlist_length)) == NULL) { *al = TLS1_AD_INTERNAL_ERROR; return 0; } s->session->tlsext_ecpointformatlist_length = ecpointformatlist_length; memcpy(s->session->tlsext_ecpointformatlist, sdata, ecpointformatlist_length); } # if 0 fprintf(stderr, "ssl_parse_clienthello_tlsext s->session->tlsext_ecpointformatlist (length=%i) ", s->session->tlsext_ecpointformatlist_length); sdata = s->session->tlsext_ecpointformatlist; for (i = 0; i < s->session->tlsext_ecpointformatlist_length; i++) fprintf(stderr, "%i ", *(sdata++)); fprintf(stderr, "\n"); # endif } else if (type == TLSEXT_TYPE_elliptic_curves) { unsigned char *sdata = data; int ellipticcurvelist_length = (*(sdata++) << 8); ellipticcurvelist_length += (*(sdata++)); if (ellipticcurvelist_length != size - 2 || ellipticcurvelist_length < 1 || /* Each NamedCurve is 2 bytes. */ ellipticcurvelist_length & 1) goto err; if (!s->hit) { if (s->session->tlsext_ellipticcurvelist) goto err; s->session->tlsext_ellipticcurvelist_length = 0; if ((s->session->tlsext_ellipticcurvelist = OPENSSL_malloc(ellipticcurvelist_length)) == NULL) { *al = TLS1_AD_INTERNAL_ERROR; return 0; } s->session->tlsext_ellipticcurvelist_length = ellipticcurvelist_length; memcpy(s->session->tlsext_ellipticcurvelist, sdata, ellipticcurvelist_length); } # if 0 fprintf(stderr, "ssl_parse_clienthello_tlsext s->session->tlsext_ellipticcurvelist (length=%i) ", s->session->tlsext_ellipticcurvelist_length); sdata = s->session->tlsext_ellipticcurvelist; for (i = 0; i < s->session->tlsext_ellipticcurvelist_length; i++) fprintf(stderr, "%i ", *(sdata++)); fprintf(stderr, "\n"); # endif } # endif /* OPENSSL_NO_EC */ # ifdef TLSEXT_TYPE_opaque_prf_input else if (type == TLSEXT_TYPE_opaque_prf_input) { unsigned char *sdata = data; if (size < 2) { *al = SSL_AD_DECODE_ERROR; return 0; } n2s(sdata, s->s3->client_opaque_prf_input_len); if (s->s3->client_opaque_prf_input_len != size - 2) { *al = SSL_AD_DECODE_ERROR; return 0; } if (s->s3->client_opaque_prf_input != NULL) { /* shouldn't really happen */ OPENSSL_free(s->s3->client_opaque_prf_input); } /* dummy byte just to get non-NULL */ if (s->s3->client_opaque_prf_input_len == 0) s->s3->client_opaque_prf_input = OPENSSL_malloc(1); else s->s3->client_opaque_prf_input = BUF_memdup(sdata, s->s3->client_opaque_prf_input_len); if (s->s3->client_opaque_prf_input == NULL) { *al = TLS1_AD_INTERNAL_ERROR; return 0; } } # endif else if (type == TLSEXT_TYPE_session_ticket) { if (s->tls_session_ticket_ext_cb && !s->tls_session_ticket_ext_cb(s, data, size, s->tls_session_ticket_ext_cb_arg)) { *al = TLS1_AD_INTERNAL_ERROR; return 0; } } else if (type == TLSEXT_TYPE_renegotiate) { if (!ssl_parse_clienthello_renegotiate_ext(s, data, size, al)) return 0; renegotiate_seen = 1; } else if (type == TLSEXT_TYPE_signature_algorithms) { int dsize; if (s->cert->peer_sigalgs || size < 2) goto err; n2s(data, dsize); size -= 2; if (dsize != size || dsize & 1 || !dsize) goto err; if (!tls1_save_sigalgs(s, data, dsize)) goto err; } else if (type == TLSEXT_TYPE_status_request) { if (size < 5) goto err; s->tlsext_status_type = *data++; size--; if (s->tlsext_status_type == TLSEXT_STATUSTYPE_ocsp) { const unsigned char *sdata; int dsize; /* Read in responder_id_list */ n2s(data, dsize); size -= 2; if (dsize > size) goto err; while (dsize > 0) { OCSP_RESPID *id; int idsize; if (dsize < 4) goto err; n2s(data, idsize); dsize -= 2 + idsize; size -= 2 + idsize; if (dsize < 0) goto err; sdata = data; data += idsize; id = d2i_OCSP_RESPID(NULL, &sdata, idsize); if (!id) goto err; if (data != sdata) { OCSP_RESPID_free(id); goto err; } if (!s->tlsext_ocsp_ids && !(s->tlsext_ocsp_ids = sk_OCSP_RESPID_new_null())) { OCSP_RESPID_free(id); *al = SSL_AD_INTERNAL_ERROR; return 0; } if (!sk_OCSP_RESPID_push(s->tlsext_ocsp_ids, id)) { OCSP_RESPID_free(id); *al = SSL_AD_INTERNAL_ERROR; return 0; } } /* Read in request_extensions */ if (size < 2) goto err; n2s(data, dsize); size -= 2; if (dsize != size) goto err; sdata = data; if (dsize > 0) { if (s->tlsext_ocsp_exts) { sk_X509_EXTENSION_pop_free(s->tlsext_ocsp_exts, X509_EXTENSION_free); } s->tlsext_ocsp_exts = d2i_X509_EXTENSIONS(NULL, &sdata, dsize); if (!s->tlsext_ocsp_exts || (data + dsize != sdata)) goto err; } } /* * We don't know what to do with any other type * so ignore it. */ else s->tlsext_status_type = -1; } # ifndef OPENSSL_NO_HEARTBEATS else if (type == TLSEXT_TYPE_heartbeat) { switch (data[0]) { case 0x01: /* Client allows us to send HB requests */ s->tlsext_heartbeat |= SSL_TLSEXT_HB_ENABLED; break; case 0x02: /* Client doesn't accept HB requests */ s->tlsext_heartbeat |= SSL_TLSEXT_HB_ENABLED; s->tlsext_heartbeat |= SSL_TLSEXT_HB_DONT_SEND_REQUESTS; break; default: *al = SSL_AD_ILLEGAL_PARAMETER; return 0; } } # endif # ifndef OPENSSL_NO_NEXTPROTONEG else if (type == TLSEXT_TYPE_next_proto_neg && s->s3->tmp.finish_md_len == 0) { /*- * We shouldn't accept this extension on a * renegotiation. * * s->new_session will be set on renegotiation, but we * probably shouldn't rely that it couldn't be set on * the initial renegotation too in certain cases (when * there's some other reason to disallow resuming an * earlier session -- the current code won't be doing * anything like that, but this might change). * * A valid sign that there's been a previous handshake * in this connection is if s->s3->tmp.finish_md_len > * 0. (We are talking about a check that will happen * in the Hello protocol round, well before a new * Finished message could have been computed.) */ s->s3->next_proto_neg_seen = 1; } # endif else if (type == TLSEXT_TYPE_application_layer_protocol_negotiation && s->s3->tmp.finish_md_len == 0) { if (tls1_alpn_handle_client_hello(s, data, size, al) != 0) return 0; } /* session ticket processed earlier */ # ifndef OPENSSL_NO_SRTP else if (SSL_IS_DTLS(s) && SSL_get_srtp_profiles(s) && type == TLSEXT_TYPE_use_srtp) { if (ssl_parse_clienthello_use_srtp_ext(s, data, size, al)) return 0; } # endif data += size; } /* Spurious data on the end */ if (data != limit) goto err; *p = data; ri_check: /* Need RI if renegotiating */ if (!renegotiate_seen && s->renegotiate && !(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)) { *al = SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL_SCAN_CLIENTHELLO_TLSEXT, SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED); return 0; } return 1; err: *al = SSL_AD_DECODE_ERROR; return 0; } Commit Message: CWE ID: CWE-190 Target: 1 Example 2: Code: static int ecb_encrypt(struct blkcipher_desc *desc, struct scatterlist *dst, struct scatterlist *src, unsigned int nbytes) { struct blkcipher_walk walk; blkcipher_walk_init(&walk, dst, src, nbytes); return ecb_crypt(desc, &walk, blowfish_enc_blk, blowfish_enc_blk_4way); } Commit Message: crypto: prefix module autoloading with "crypto-" This prefixes all crypto module loading with "crypto-" so we never run the risk of exposing module auto-loading to userspace via a crypto API, as demonstrated by Mathias Krause: https://lkml.org/lkml/2013/3/4/70 Signed-off-by: Kees Cook <[email protected]> Signed-off-by: Herbert Xu <[email protected]> CWE ID: CWE-264 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void AutofillManager::GetAvailableSuggestions( const FormData& form, const FormFieldData& field, std::vector<Suggestion>* suggestions, SuggestionsContext* context) { DCHECK(suggestions); DCHECK(context); bool is_autofill_possible = RefreshDataModels(); bool got_autofillable_form = GetCachedFormAndField(form, field, &context->form_structure, &context->focused_field) && context->form_structure->ShouldBeParsed(); if (got_autofillable_form) { if (context->focused_field->Type().group() == CREDIT_CARD) { context->is_filling_credit_card = true; driver()->DidInteractWithCreditCardForm(); credit_card_form_event_logger_->OnDidInteractWithAutofillableForm( context->form_structure->form_signature()); } else { address_form_event_logger_->OnDidInteractWithAutofillableForm( context->form_structure->form_signature()); } } context->is_context_secure = !IsFormNonSecure(form) || !base::FeatureList::IsEnabled( features::kAutofillRequireSecureCreditCardContext); if (!is_autofill_possible || !driver()->RendererIsAvailable() || !got_autofillable_form) return; context->is_autofill_available = true; if (context->is_filling_credit_card) { *suggestions = GetCreditCardSuggestions(field, context->focused_field->Type(), &context->is_all_server_suggestions); if (base::FeatureList::IsEnabled(kAutofillCreditCardAblationExperiment) && !suggestions->empty()) { context->suppress_reason = SuppressReason::kCreditCardsAblation; suggestions->clear(); return; } } else { if (!base::FeatureList::IsEnabled(kAutofillAlwaysFillAddresses) && IsDesktopPlatform() && !field.should_autocomplete) { context->suppress_reason = SuppressReason::kAutocompleteOff; return; } *suggestions = GetProfileSuggestions(*context->form_structure, field, *context->focused_field); } if (!suggestions->empty() && context->is_filling_credit_card && !context->is_context_secure) { Suggestion warning_suggestion( l10n_util::GetStringUTF16(IDS_AUTOFILL_WARNING_INSECURE_CONNECTION)); warning_suggestion.frontend_id = POPUP_ITEM_ID_INSECURE_CONTEXT_PAYMENT_DISABLED_MESSAGE; suggestions->assign(1, warning_suggestion); } else { context->section_has_autofilled_field = SectionHasAutofilledField( *context->form_structure, form, context->focused_field->section); if (context->section_has_autofilled_field) { std::set<base::string16> seen_values; for (auto iter = suggestions->begin(); iter != suggestions->end();) { if (!seen_values.insert(iter->value).second) { iter = suggestions->erase(iter); } else { iter->label.clear(); iter->icon.clear(); ++iter; } } } } } Commit Message: [AF] Don't simplify/dedupe suggestions for (partially) filled sections. Since Autofill does not fill field by field anymore, this simplifying and deduping of suggestions is not useful anymore. Bug: 858820 Cq-Include-Trybots: luci.chromium.try:ios-simulator-full-configs;master.tryserver.chromium.mac:ios-simulator-cronet Change-Id: I36f7cfe425a0bdbf5ba7503a3d96773b405cc19b Reviewed-on: https://chromium-review.googlesource.com/1128255 Reviewed-by: Roger McFarlane <[email protected]> Commit-Queue: Sebastien Seguin-Gagnon <[email protected]> Cr-Commit-Position: refs/heads/master@{#573315} CWE ID: Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int ivr_read_header(AVFormatContext *s) { unsigned tag, type, len, tlen, value; int i, j, n, count, nb_streams = 0, ret; uint8_t key[256], val[256]; AVIOContext *pb = s->pb; AVStream *st; int64_t pos, offset, temp; pos = avio_tell(pb); tag = avio_rl32(pb); if (tag == MKTAG('.','R','1','M')) { if (avio_rb16(pb) != 1) return AVERROR_INVALIDDATA; if (avio_r8(pb) != 1) return AVERROR_INVALIDDATA; len = avio_rb32(pb); avio_skip(pb, len); avio_skip(pb, 5); temp = avio_rb64(pb); while (!avio_feof(pb) && temp) { offset = temp; temp = avio_rb64(pb); } avio_skip(pb, offset - avio_tell(pb)); if (avio_r8(pb) != 1) return AVERROR_INVALIDDATA; len = avio_rb32(pb); avio_skip(pb, len); if (avio_r8(pb) != 2) return AVERROR_INVALIDDATA; avio_skip(pb, 16); pos = avio_tell(pb); tag = avio_rl32(pb); } if (tag != MKTAG('.','R','E','C')) return AVERROR_INVALIDDATA; if (avio_r8(pb) != 0) return AVERROR_INVALIDDATA; count = avio_rb32(pb); for (i = 0; i < count; i++) { if (avio_feof(pb)) return AVERROR_INVALIDDATA; type = avio_r8(pb); tlen = avio_rb32(pb); avio_get_str(pb, tlen, key, sizeof(key)); len = avio_rb32(pb); if (type == 5) { avio_get_str(pb, len, val, sizeof(val)); av_log(s, AV_LOG_DEBUG, "%s = '%s'\n", key, val); } else if (type == 4) { av_log(s, AV_LOG_DEBUG, "%s = '0x", key); for (j = 0; j < len; j++) av_log(s, AV_LOG_DEBUG, "%X", avio_r8(pb)); av_log(s, AV_LOG_DEBUG, "'\n"); } else if (len == 4 && type == 3 && !strncmp(key, "StreamCount", tlen)) { nb_streams = value = avio_rb32(pb); } else if (len == 4 && type == 3) { value = avio_rb32(pb); av_log(s, AV_LOG_DEBUG, "%s = %d\n", key, value); } else { av_log(s, AV_LOG_DEBUG, "Skipping unsupported key: %s\n", key); avio_skip(pb, len); } } for (n = 0; n < nb_streams; n++) { st = avformat_new_stream(s, NULL); if (!st) return AVERROR(ENOMEM); st->priv_data = ff_rm_alloc_rmstream(); if (!st->priv_data) return AVERROR(ENOMEM); if (avio_r8(pb) != 1) return AVERROR_INVALIDDATA; count = avio_rb32(pb); for (i = 0; i < count; i++) { if (avio_feof(pb)) return AVERROR_INVALIDDATA; type = avio_r8(pb); tlen = avio_rb32(pb); avio_get_str(pb, tlen, key, sizeof(key)); len = avio_rb32(pb); if (type == 5) { avio_get_str(pb, len, val, sizeof(val)); av_log(s, AV_LOG_DEBUG, "%s = '%s'\n", key, val); } else if (type == 4 && !strncmp(key, "OpaqueData", tlen)) { ret = ffio_ensure_seekback(pb, 4); if (ret < 0) return ret; if (avio_rb32(pb) == MKBETAG('M', 'L', 'T', 'I')) { ret = rm_read_multi(s, pb, st, NULL); } else { avio_seek(pb, -4, SEEK_CUR); ret = ff_rm_read_mdpr_codecdata(s, pb, st, st->priv_data, len, NULL); } if (ret < 0) return ret; } else if (type == 4) { int j; av_log(s, AV_LOG_DEBUG, "%s = '0x", key); for (j = 0; j < len; j++) av_log(s, AV_LOG_DEBUG, "%X", avio_r8(pb)); av_log(s, AV_LOG_DEBUG, "'\n"); } else if (len == 4 && type == 3 && !strncmp(key, "Duration", tlen)) { st->duration = avio_rb32(pb); } else if (len == 4 && type == 3) { value = avio_rb32(pb); av_log(s, AV_LOG_DEBUG, "%s = %d\n", key, value); } else { av_log(s, AV_LOG_DEBUG, "Skipping unsupported key: %s\n", key); avio_skip(pb, len); } } } if (avio_r8(pb) != 6) return AVERROR_INVALIDDATA; avio_skip(pb, 12); avio_skip(pb, avio_rb64(pb) + pos - avio_tell(s->pb)); if (avio_r8(pb) != 8) return AVERROR_INVALIDDATA; avio_skip(pb, 8); return 0; } Commit Message: avformat/rmdec: Fix DoS due to lack of eof check Fixes: loop.ivr Found-by: Xiaohei and Wangchu from Alibaba Security Team Signed-off-by: Michael Niedermayer <[email protected]> CWE ID: CWE-834 Target: 1 Example 2: Code: void JBIG2Bitmap::combine(JBIG2Bitmap *bitmap, int x, int y, Guint combOp) { int x0, x1, y0, y1, xx, yy; Guchar *srcPtr, *destPtr; Guint src0, src1, src, dest, s1, s2, m1, m2, m3; GBool oneByte; if (y < 0) { y0 = -y; } else { y0 = 0; } if (y + bitmap->h > h) { y1 = h - y; } else { y1 = bitmap->h; } if (y0 >= y1) { return; } if (x >= 0) { x0 = x & ~7; } else { x0 = 0; } x1 = x + bitmap->w; if (x1 > w) { x1 = w; } if (x0 >= x1) { return; } s1 = x & 7; s2 = 8 - s1; m1 = 0xff >> (x1 & 7); m2 = 0xff << (((x1 & 7) == 0) ? 0 : 8 - (x1 & 7)); m3 = (0xff >> s1) & m2; oneByte = x0 == ((x1 - 1) & ~7); for (yy = y0; yy < y1; ++yy) { if (oneByte) { if (x >= 0) { destPtr = data + (y + yy) * line + (x >> 3); srcPtr = bitmap->data + yy * bitmap->line; dest = *destPtr; src1 = *srcPtr; switch (combOp) { case 0: // or dest |= (src1 >> s1) & m2; break; case 1: // and dest &= ((0xff00 | src1) >> s1) | m1; break; case 2: // xor dest ^= (src1 >> s1) & m2; break; case 3: // xnor dest ^= ((src1 ^ 0xff) >> s1) & m2; break; case 4: // replace dest = (dest & ~m3) | ((src1 >> s1) & m3); break; } *destPtr = dest; } else { destPtr = data + (y + yy) * line; srcPtr = bitmap->data + yy * bitmap->line + (-x >> 3); dest = *destPtr; src1 = *srcPtr; switch (combOp) { case 0: // or dest |= src1 & m2; break; case 1: // and dest &= src1 | m1; break; case 2: // xor dest ^= src1 & m2; break; case 3: // xnor dest ^= (src1 ^ 0xff) & m2; break; case 4: // replace dest = (src1 & m2) | (dest & m1); break; } *destPtr = dest; } } else { if (x >= 0) { destPtr = data + (y + yy) * line + (x >> 3); srcPtr = bitmap->data + yy * bitmap->line; src1 = *srcPtr++; dest = *destPtr; switch (combOp) { case 0: // or dest |= src1 >> s1; break; case 1: // and dest &= (0xff00 | src1) >> s1; break; case 2: // xor dest ^= src1 >> s1; break; case 3: // xnor dest ^= (src1 ^ 0xff) >> s1; break; case 4: // replace dest = (dest & (0xff << s2)) | (src1 >> s1); break; } *destPtr++ = dest; xx = x0 + 8; } else { destPtr = data + (y + yy) * line; srcPtr = bitmap->data + yy * bitmap->line + (-x >> 3); src1 = *srcPtr++; xx = x0; } for (; xx < x1 - 8; xx += 8) { dest = *destPtr; src0 = src1; src1 = *srcPtr++; src = (((src0 << 8) | src1) >> s1) & 0xff; switch (combOp) { case 0: // or dest |= src; break; case 1: // and dest &= src; break; case 2: // xor dest ^= src; break; case 3: // xnor dest ^= src ^ 0xff; break; case 4: // replace dest = src; break; } *destPtr++ = dest; } dest = *destPtr; src0 = src1; src1 = *srcPtr++; src = (((src0 << 8) | src1) >> s1) & 0xff; switch (combOp) { case 0: // or dest |= src & m2; break; case 1: // and dest &= src | m1; break; case 2: // xor dest ^= src & m2; break; case 3: // xnor dest ^= (src ^ 0xff) & m2; break; case 4: // replace dest = (src & m2) | (dest & m1); break; } *destPtr = dest; } } } Commit Message: CWE ID: CWE-189 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int vcpu_enter_guest(struct kvm_vcpu *vcpu) { int r; bool req_int_win = !irqchip_in_kernel(vcpu->kvm) && vcpu->run->request_interrupt_window; bool req_immediate_exit = 0; if (vcpu->requests) { if (kvm_check_request(KVM_REQ_MMU_RELOAD, vcpu)) kvm_mmu_unload(vcpu); if (kvm_check_request(KVM_REQ_MIGRATE_TIMER, vcpu)) __kvm_migrate_timers(vcpu); if (kvm_check_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu)) kvm_gen_update_masterclock(vcpu->kvm); if (kvm_check_request(KVM_REQ_CLOCK_UPDATE, vcpu)) { r = kvm_guest_time_update(vcpu); if (unlikely(r)) goto out; } if (kvm_check_request(KVM_REQ_MMU_SYNC, vcpu)) kvm_mmu_sync_roots(vcpu); if (kvm_check_request(KVM_REQ_TLB_FLUSH, vcpu)) kvm_x86_ops->tlb_flush(vcpu); if (kvm_check_request(KVM_REQ_REPORT_TPR_ACCESS, vcpu)) { vcpu->run->exit_reason = KVM_EXIT_TPR_ACCESS; r = 0; goto out; } if (kvm_check_request(KVM_REQ_TRIPLE_FAULT, vcpu)) { vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN; r = 0; goto out; } if (kvm_check_request(KVM_REQ_DEACTIVATE_FPU, vcpu)) { vcpu->fpu_active = 0; kvm_x86_ops->fpu_deactivate(vcpu); } if (kvm_check_request(KVM_REQ_APF_HALT, vcpu)) { /* Page is swapped out. Do synthetic halt */ vcpu->arch.apf.halted = true; r = 1; goto out; } if (kvm_check_request(KVM_REQ_STEAL_UPDATE, vcpu)) record_steal_time(vcpu); if (kvm_check_request(KVM_REQ_NMI, vcpu)) process_nmi(vcpu); req_immediate_exit = kvm_check_request(KVM_REQ_IMMEDIATE_EXIT, vcpu); if (kvm_check_request(KVM_REQ_PMU, vcpu)) kvm_handle_pmu_event(vcpu); if (kvm_check_request(KVM_REQ_PMI, vcpu)) kvm_deliver_pmi(vcpu); if (kvm_check_request(KVM_REQ_EOIBITMAP, vcpu)) update_eoi_exitmap(vcpu); } if (kvm_check_request(KVM_REQ_EVENT, vcpu) || req_int_win) { inject_pending_event(vcpu); /* enable NMI/IRQ window open exits if needed */ if (vcpu->arch.nmi_pending) kvm_x86_ops->enable_nmi_window(vcpu); else if (kvm_cpu_has_injectable_intr(vcpu) || req_int_win) kvm_x86_ops->enable_irq_window(vcpu); if (kvm_lapic_enabled(vcpu)) { /* * Update architecture specific hints for APIC * virtual interrupt delivery. */ if (kvm_x86_ops->hwapic_irr_update) kvm_x86_ops->hwapic_irr_update(vcpu, kvm_lapic_find_highest_irr(vcpu)); update_cr8_intercept(vcpu); kvm_lapic_sync_to_vapic(vcpu); } } r = kvm_mmu_reload(vcpu); if (unlikely(r)) { goto cancel_injection; } preempt_disable(); kvm_x86_ops->prepare_guest_switch(vcpu); if (vcpu->fpu_active) kvm_load_guest_fpu(vcpu); kvm_load_guest_xcr0(vcpu); vcpu->mode = IN_GUEST_MODE; /* We should set ->mode before check ->requests, * see the comment in make_all_cpus_request. */ smp_mb(); local_irq_disable(); if (vcpu->mode == EXITING_GUEST_MODE || vcpu->requests || need_resched() || signal_pending(current)) { vcpu->mode = OUTSIDE_GUEST_MODE; smp_wmb(); local_irq_enable(); preempt_enable(); r = 1; goto cancel_injection; } srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx); if (req_immediate_exit) smp_send_reschedule(vcpu->cpu); kvm_guest_enter(); if (unlikely(vcpu->arch.switch_db_regs)) { set_debugreg(0, 7); set_debugreg(vcpu->arch.eff_db[0], 0); set_debugreg(vcpu->arch.eff_db[1], 1); set_debugreg(vcpu->arch.eff_db[2], 2); set_debugreg(vcpu->arch.eff_db[3], 3); } trace_kvm_entry(vcpu->vcpu_id); kvm_x86_ops->run(vcpu); /* * If the guest has used debug registers, at least dr7 * will be disabled while returning to the host. * If we don't have active breakpoints in the host, we don't * care about the messed up debug address registers. But if * we have some of them active, restore the old state. */ if (hw_breakpoint_active()) hw_breakpoint_restore(); vcpu->arch.last_guest_tsc = kvm_x86_ops->read_l1_tsc(vcpu, native_read_tsc()); vcpu->mode = OUTSIDE_GUEST_MODE; smp_wmb(); local_irq_enable(); ++vcpu->stat.exits; /* * We must have an instruction between local_irq_enable() and * kvm_guest_exit(), so the timer interrupt isn't delayed by * the interrupt shadow. The stat.exits increment will do nicely. * But we need to prevent reordering, hence this barrier(): */ barrier(); kvm_guest_exit(); preempt_enable(); vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu); /* * Profile KVM exit RIPs: */ if (unlikely(prof_on == KVM_PROFILING)) { unsigned long rip = kvm_rip_read(vcpu); profile_hit(KVM_PROFILING, (void *)rip); } if (unlikely(vcpu->arch.tsc_always_catchup)) kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu); if (vcpu->arch.apic_attention) kvm_lapic_sync_from_vapic(vcpu); r = kvm_x86_ops->handle_exit(vcpu); return r; cancel_injection: kvm_x86_ops->cancel_injection(vcpu); if (unlikely(vcpu->arch.apic_attention)) kvm_lapic_sync_from_vapic(vcpu); out: return r; } Commit Message: KVM: x86: Convert MSR_KVM_SYSTEM_TIME to use gfn_to_hva_cache functions (CVE-2013-1797) There is a potential use after free issue with the handling of MSR_KVM_SYSTEM_TIME. If the guest specifies a GPA in a movable or removable memory such as frame buffers then KVM might continue to write to that address even after it's removed via KVM_SET_USER_MEMORY_REGION. KVM pins the page in memory so it's unlikely to cause an issue, but if the user space component re-purposes the memory previously used for the guest, then the guest will be able to corrupt that memory. Tested: Tested against kvmclock unit test Signed-off-by: Andrew Honig <[email protected]> Signed-off-by: Marcelo Tosatti <[email protected]> CWE ID: CWE-399 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: CURLcode Curl_smtp_escape_eob(struct connectdata *conn, const ssize_t nread) { /* When sending a SMTP payload we must detect CRLF. sequences making sure they are sent as CRLF.. instead, as a . on the beginning of a line will be deleted by the server when not part of an EOB terminator and a genuine CRLF.CRLF which isn't escaped will wrongly be detected as end of data by the server */ ssize_t i; ssize_t si; struct Curl_easy *data = conn->data; struct SMTP *smtp = data->req.protop; char *scratch = data->state.scratch; char *newscratch = NULL; char *oldscratch = NULL; size_t eob_sent; /* Do we need to allocate a scratch buffer? */ if(!scratch || data->set.crlf) { oldscratch = scratch; scratch = newscratch = malloc(2 * data->set.buffer_size); if(!newscratch) { failf(data, "Failed to alloc scratch buffer!"); return CURLE_OUT_OF_MEMORY; } } /* Have we already sent part of the EOB? */ eob_sent = smtp->eob; /* This loop can be improved by some kind of Boyer-Moore style of approach but that is saved for later... */ for(i = 0, si = 0; i < nread; i++) { if(SMTP_EOB[smtp->eob] == data->req.upload_fromhere[i]) { smtp->eob++; /* Is the EOB potentially the terminating CRLF? */ if(2 == smtp->eob || SMTP_EOB_LEN == smtp->eob) smtp->trailing_crlf = TRUE; else smtp->trailing_crlf = FALSE; } else if(smtp->eob) { /* A previous substring matched so output that first */ memcpy(&scratch[si], &SMTP_EOB[eob_sent], smtp->eob - eob_sent); si += smtp->eob - eob_sent; /* Then compare the first byte */ if(SMTP_EOB[0] == data->req.upload_fromhere[i]) smtp->eob = 1; else smtp->eob = 0; eob_sent = 0; /* Reset the trailing CRLF flag as there was more data */ smtp->trailing_crlf = FALSE; } /* Do we have a match for CRLF. as per RFC-5321, sect. 4.5.2 */ if(SMTP_EOB_FIND_LEN == smtp->eob) { /* Copy the replacement data to the target buffer */ memcpy(&scratch[si], &SMTP_EOB_REPL[eob_sent], SMTP_EOB_REPL_LEN - eob_sent); si += SMTP_EOB_REPL_LEN - eob_sent; smtp->eob = 0; eob_sent = 0; } else if(!smtp->eob) scratch[si++] = data->req.upload_fromhere[i]; } if(smtp->eob - eob_sent) { /* A substring matched before processing ended so output that now */ memcpy(&scratch[si], &SMTP_EOB[eob_sent], smtp->eob - eob_sent); si += smtp->eob - eob_sent; } /* Only use the new buffer if we replaced something */ if(si != nread) { /* Upload from the new (replaced) buffer instead */ data->req.upload_fromhere = scratch; /* Save the buffer so it can be freed later */ data->state.scratch = scratch; /* Free the old scratch buffer */ free(oldscratch); /* Set the new amount too */ data->req.upload_present = si; } else free(newscratch); return CURLE_OK; } Commit Message: smtp: use the upload buffer size for scratch buffer malloc ... not the read buffer size, as that can be set smaller and thus cause a buffer overflow! CVE-2018-0500 Reported-by: Peter Wu Bug: https://curl.haxx.se/docs/adv_2018-70a2.html CWE ID: CWE-119 Target: 1 Example 2: Code: void DelegatedFrameHost::SetNeedsBeginFrames(bool needs_begin_frames) { needs_begin_frame_ = needs_begin_frames; support_->SetNeedsBeginFrame(needs_begin_frames); } Commit Message: mac: Make RWHVMac::ClearCompositorFrame clear locks Ensure that the BrowserCompositorMac not hold on to a compositor lock when requested to clear its compositor frame. This lock may be held indefinitely (if the renderer hangs) and so the frame will never be cleared. Bug: 739621 Change-Id: I15d0e82bdf632f3379a48e959f198afb8a4ac218 Reviewed-on: https://chromium-review.googlesource.com/608239 Commit-Queue: ccameron chromium <[email protected]> Reviewed-by: Ken Buchanan <[email protected]> Cr-Commit-Position: refs/heads/master@{#493563} CWE ID: CWE-20 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: image_transform_png_set_@_set(PNG_CONST image_transform *this, transform_display *that, png_structp pp, png_infop pi) { png_set_@(pp); this->next->set(this->next, that, pp, pi); } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID: Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void UnloadController::TabReplacedAt(TabStripModel* tab_strip_model, TabContents* old_contents, TabContents* new_contents, int index) { TabDetachedImpl(old_contents); TabAttachedImpl(new_contents->web_contents()); } Commit Message: Remove TabContents from TabStripModelObserver::TabDetachedAt. BUG=107201 TEST=no visible change Review URL: https://chromiumcodereview.appspot.com/11293205 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@167122 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20 Target: 1 Example 2: Code: Browser::CreateParams::CreateParams(Profile* profile) : type(TYPE_TABBED), profile(profile), host_desktop_type(kDefaultHostDesktopType), app_type(APP_TYPE_HOST), initial_show_state(ui::SHOW_STATE_DEFAULT), is_session_restore(false), window(NULL) { } Commit Message: Remove TabContents from TabStripModelObserver::TabDetachedAt. BUG=107201 TEST=no visible change Review URL: https://chromiumcodereview.appspot.com/11293205 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@167122 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int vhost_scsi_write_pending_status(struct se_cmd *se_cmd) { return 0; } Commit Message: vhost/scsi: potential memory corruption This code in vhost_scsi_make_tpg() is confusing because we limit "tpgt" to UINT_MAX but the data type of "tpg->tport_tpgt" and that is a u16. I looked at the context and it turns out that in vhost_scsi_set_endpoint(), "tpg->tport_tpgt" is used as an offset into the vs_tpg[] array which has VHOST_SCSI_MAX_TARGET (256) elements so anything higher than 255 then it is invalid. I have made that the limit now. In vhost_scsi_send_evt() we mask away values higher than 255, but now that the limit has changed, we don't need the mask. Signed-off-by: Dan Carpenter <[email protected]> Signed-off-by: Nicholas Bellinger <[email protected]> CWE ID: CWE-119 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void ExtensionServiceBackend::OnExtensionInstalled( const scoped_refptr<const Extension>& extension) { CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); if (frontend_.get()) frontend_->OnExtensionInstalled(extension); } Commit Message: Unrevert: Show the install dialog for the initial load of an unpacked extension with plugins. First landing broke some browser tests. BUG=83273 TEST=in the extensions managmenet page, with developer mode enabled, Load an unpacked extension on an extension with NPAPI plugins. You should get an install dialog. TBR=mihaip git-svn-id: svn://svn.chromium.org/chrome/trunk/src@87738 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20 Target: 1 Example 2: Code: void init_source(j_decompress_ptr) { } Commit Message: Progressive JPEG outputScanlines() calls should handle failure outputScanlines() can fail and delete |this|, so any attempt to access members thereafter should be avoided. Copy the decoder pointer member, and use that copy to detect and handle the failure case. BUG=232763 [email protected] Review URL: https://codereview.chromium.org/14844003 git-svn-id: svn://svn.chromium.org/blink/trunk@150545 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void NTPResourceCache::CreateNewTabGuestHTML() { base::DictionaryValue localized_strings; localized_strings.SetString("title", l10n_util::GetStringUTF16(IDS_NEW_TAB_TITLE)); const char* guest_tab_link = kLearnMoreGuestSessionUrl; int guest_tab_ids = IDR_GUEST_TAB_HTML; int guest_tab_description_ids = IDS_NEW_TAB_GUEST_SESSION_DESCRIPTION; int guest_tab_heading_ids = IDS_NEW_TAB_GUEST_SESSION_HEADING; int guest_tab_link_ids = IDS_NEW_TAB_GUEST_SESSION_LEARN_MORE_LINK; #if defined(OS_CHROMEOS) guest_tab_ids = IDR_GUEST_SESSION_TAB_HTML; guest_tab_link = kLearnMoreGuestSessionUrl; policy::BrowserPolicyConnectorChromeOS* connector = g_browser_process->platform_part()->browser_policy_connector_chromeos(); std::string enterprise_domain = connector->GetEnterpriseDomain(); if (!enterprise_domain.empty()) { localized_strings.SetString("enterpriseInfoVisible", "true"); base::string16 enterprise_info = l10n_util::GetStringFUTF16( IDS_DEVICE_OWNED_BY_NOTICE, base::UTF8ToUTF16(enterprise_domain)); localized_strings.SetString("enterpriseInfoMessage", enterprise_info); localized_strings.SetString("enterpriseLearnMore", l10n_util::GetStringUTF16(IDS_LEARN_MORE)); localized_strings.SetString("enterpriseInfoHintLink", GetUrlWithLang(GURL(chrome::kLearnMoreEnterpriseURL))); } else { localized_strings.SetString("enterpriseInfoVisible", "false"); } #endif localized_strings.SetString("guestTabDescription", l10n_util::GetStringUTF16(guest_tab_description_ids)); localized_strings.SetString("guestTabHeading", l10n_util::GetStringUTF16(guest_tab_heading_ids)); localized_strings.SetString("learnMore", l10n_util::GetStringUTF16(guest_tab_link_ids)); localized_strings.SetString("learnMoreLink", GetUrlWithLang(GURL(guest_tab_link))); webui::SetFontAndTextDirection(&localized_strings); static const base::StringPiece guest_tab_html( ResourceBundle::GetSharedInstance().GetRawDataResource(guest_tab_ids)); std::string full_html = webui::GetI18nTemplateHtml( guest_tab_html, &localized_strings); new_tab_guest_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 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void ChromeContentBrowserClient::AppendExtraCommandLineSwitches( CommandLine* command_line, int child_process_id) { #if defined(USE_LINUX_BREAKPAD) if (IsCrashReporterEnabled()) { command_line->AppendSwitchASCII(switches::kEnableCrashReporter, child_process_logging::GetClientId() + "," + base::GetLinuxDistro()); } #elif defined(OS_MACOSX) if (IsCrashReporterEnabled()) { command_line->AppendSwitchASCII(switches::kEnableCrashReporter, child_process_logging::GetClientId()); } #endif // OS_MACOSX if (logging::DialogsAreSuppressed()) command_line->AppendSwitch(switches::kNoErrorDialogs); std::string process_type = command_line->GetSwitchValueASCII(switches::kProcessType); const CommandLine& browser_command_line = *CommandLine::ForCurrentProcess(); if (process_type == switches::kExtensionProcess || process_type == switches::kRendererProcess) { FilePath user_data_dir = browser_command_line.GetSwitchValuePath(switches::kUserDataDir); if (!user_data_dir.empty()) command_line->AppendSwitchPath(switches::kUserDataDir, user_data_dir); #if defined(OS_CHROMEOS) const std::string& login_profile = browser_command_line.GetSwitchValueASCII(switches::kLoginProfile); if (!login_profile.empty()) command_line->AppendSwitchASCII(switches::kLoginProfile, login_profile); #endif RenderProcessHost* process = RenderProcessHost::FromID(child_process_id); PrefService* prefs = process->profile()->GetPrefs(); if (prefs->HasPrefPath(prefs::kDisable3DAPIs) && prefs->GetBoolean(prefs::kDisable3DAPIs)) { command_line->AppendSwitch(switches::kDisable3DAPIs); } if (!prefs->GetBoolean(prefs::kSafeBrowsingEnabled) || !g_browser_process->safe_browsing_detection_service()) { command_line->AppendSwitch(switches::kDisableClientSidePhishingDetection); } static const char* const kSwitchNames[] = { switches::kAllowHTTPBackgroundPage, switches::kAllowScriptingGallery, switches::kAppsCheckoutURL, switches::kAppsGalleryURL, switches::kCloudPrintServiceURL, switches::kDebugPrint, #if defined(GOOGLE_CHROME_BUILD) && !defined(OS_CHROMEOS) && !defined(OS_MACOSX) switches::kDisablePrintPreview, #else switches::kEnablePrintPreview, #endif switches::kDomAutomationController, switches::kDumpHistogramsOnExit, switches::kEnableClickToPlay, switches::kEnableCrxlessWebApps, switches::kEnableExperimentalExtensionApis, switches::kEnableInBrowserThumbnailing, switches::kEnableIPCFuzzing, switches::kEnableNaCl, switches::kEnableRemoting, switches::kEnableResourceContentSettings, switches::kEnableSearchProviderApiV2, switches::kEnableWatchdog, switches::kExperimentalSpellcheckerFeatures, switches::kMemoryProfiling, switches::kMessageLoopHistogrammer, switches::kPpapiFlashArgs, switches::kPpapiFlashInProcess, switches::kPpapiFlashPath, switches::kPpapiFlashVersion, switches::kProfilingAtStart, switches::kProfilingFile, switches::kProfilingFlush, switches::kRemoteShellPort, switches::kSilentDumpOnDCHECK, }; command_line->CopySwitchesFrom(browser_command_line, kSwitchNames, arraysize(kSwitchNames)); } else if (process_type == switches::kUtilityProcess) { if (browser_command_line.HasSwitch( switches::kEnableExperimentalExtensionApis)) { command_line->AppendSwitch(switches::kEnableExperimentalExtensionApis); } } else if (process_type == switches::kPluginProcess) { static const char* const kSwitchNames[] = { #if defined(OS_CHROMEOS) switches::kLoginProfile, #endif switches::kMemoryProfiling, switches::kSilentDumpOnDCHECK, switches::kUserDataDir, }; command_line->CopySwitchesFrom(browser_command_line, kSwitchNames, arraysize(kSwitchNames)); } else if (process_type == switches::kZygoteProcess) { static const char* const kSwitchNames[] = { switches::kEnableRemoting, switches::kUserDataDir, // Make logs go to the right file. switches::kPpapiFlashInProcess, switches::kPpapiFlashPath, switches::kPpapiFlashVersion, }; command_line->CopySwitchesFrom(browser_command_line, kSwitchNames, arraysize(kSwitchNames)); } } Commit Message: DevTools: move DevToolsAgent/Client into content. BUG=84078 TEST= Review URL: http://codereview.chromium.org/7461019 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@93596 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20 Target: 1 Example 2: Code: static QImage decodeNotificationSpecImageHint(const QDBusArgument& arg) { int width, height, rowStride, hasAlpha, bitsPerSample, channels; QByteArray pixels; char* ptr; char* end; arg.beginStructure(); arg >> width >> height >> rowStride >> hasAlpha >> bitsPerSample >> channels >> pixels; arg.endStructure(); #define SANITY_CHECK(condition) \ if (!(condition)) { \ qWarning() << "Sanity check failed on" << #condition; \ return QImage(); \ } SANITY_CHECK(width > 0); SANITY_CHECK(width < 2048); SANITY_CHECK(height > 0); SANITY_CHECK(height < 2048); SANITY_CHECK(rowStride > 0); #undef SANITY_CHECK QImage::Format format = QImage::Format_Invalid; void (*fcn)(QRgb*, const char*, int) = 0; if (bitsPerSample == 8) { if (channels == 4) { format = QImage::Format_ARGB32; fcn = copyLineARGB32; } else if (channels == 3) { format = QImage::Format_RGB32; fcn = copyLineRGB32; } } if (format == QImage::Format_Invalid) { qWarning() << "Unsupported image format (hasAlpha:" << hasAlpha << "bitsPerSample:" << bitsPerSample << "channels:" << channels << ")"; return QImage(); } QImage image(width, height, format); ptr = pixels.data(); end = ptr + pixels.length(); for (int y=0; y<height; ++y, ptr += rowStride) { if (ptr + channels * width > end) { qWarning() << "Image data is incomplete. y:" << y << "height:" << height; break; } fcn((QRgb*)image.scanLine(y), ptr, width); } return image; } Commit Message: CWE ID: CWE-200 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: int ParseWave64HeaderConfig (FILE *infile, char *infilename, char *fourcc, WavpackContext *wpc, WavpackConfig *config) { int64_t total_samples = 0, infilesize; Wave64ChunkHeader chunk_header; Wave64FileHeader filehdr; WaveHeader WaveHeader; uint32_t bcount; infilesize = DoGetFileSize (infile); memcpy (&filehdr, fourcc, 4); if (!DoReadFile (infile, ((char *) &filehdr) + 4, sizeof (Wave64FileHeader) - 4, &bcount) || bcount != sizeof (Wave64FileHeader) - 4 || memcmp (filehdr.ckID, riff_guid, sizeof (riff_guid)) || memcmp (filehdr.formType, wave_guid, sizeof (wave_guid))) { error_line ("%s is not a valid .W64 file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &filehdr, sizeof (filehdr))) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } #if 1 // this might be a little too picky... WavpackLittleEndianToNative (&filehdr, Wave64ChunkHeaderFormat); if (infilesize && !(config->qmode & QMODE_IGNORE_LENGTH) && filehdr.ckSize && filehdr.ckSize + 1 && filehdr.ckSize != infilesize) { error_line ("%s is not a valid .W64 file!", infilename); return WAVPACK_SOFT_ERROR; } #endif while (1) { if (!DoReadFile (infile, &chunk_header, sizeof (Wave64ChunkHeader), &bcount) || bcount != sizeof (Wave64ChunkHeader)) { error_line ("%s is not a valid .W64 file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &chunk_header, sizeof (Wave64ChunkHeader))) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } WavpackLittleEndianToNative (&chunk_header, Wave64ChunkHeaderFormat); chunk_header.ckSize -= sizeof (chunk_header); if (!memcmp (chunk_header.ckID, fmt_guid, sizeof (fmt_guid))) { int supported = TRUE, format; chunk_header.ckSize = (chunk_header.ckSize + 7) & ~7L; if (chunk_header.ckSize < 16 || chunk_header.ckSize > sizeof (WaveHeader) || !DoReadFile (infile, &WaveHeader, (uint32_t) chunk_header.ckSize, &bcount) || bcount != chunk_header.ckSize) { error_line ("%s is not a valid .W64 file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &WaveHeader, (uint32_t) chunk_header.ckSize)) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } WavpackLittleEndianToNative (&WaveHeader, WaveHeaderFormat); if (debug_logging_mode) { error_line ("format tag size = %d", chunk_header.ckSize); error_line ("FormatTag = %x, NumChannels = %d, BitsPerSample = %d", WaveHeader.FormatTag, WaveHeader.NumChannels, WaveHeader.BitsPerSample); error_line ("BlockAlign = %d, SampleRate = %d, BytesPerSecond = %d", WaveHeader.BlockAlign, WaveHeader.SampleRate, WaveHeader.BytesPerSecond); if (chunk_header.ckSize > 16) error_line ("cbSize = %d, ValidBitsPerSample = %d", WaveHeader.cbSize, WaveHeader.ValidBitsPerSample); if (chunk_header.ckSize > 20) error_line ("ChannelMask = %x, SubFormat = %d", WaveHeader.ChannelMask, WaveHeader.SubFormat); } if (chunk_header.ckSize > 16 && WaveHeader.cbSize == 2) config->qmode |= QMODE_ADOBE_MODE; format = (WaveHeader.FormatTag == 0xfffe && chunk_header.ckSize == 40) ? WaveHeader.SubFormat : WaveHeader.FormatTag; config->bits_per_sample = (chunk_header.ckSize == 40 && WaveHeader.ValidBitsPerSample) ? WaveHeader.ValidBitsPerSample : WaveHeader.BitsPerSample; if (format != 1 && format != 3) supported = FALSE; if (format == 3 && config->bits_per_sample != 32) supported = FALSE; if (!WaveHeader.NumChannels || WaveHeader.NumChannels > 256 || WaveHeader.BlockAlign / WaveHeader.NumChannels < (config->bits_per_sample + 7) / 8 || WaveHeader.BlockAlign / WaveHeader.NumChannels > 4 || WaveHeader.BlockAlign % WaveHeader.NumChannels) supported = FALSE; if (config->bits_per_sample < 1 || config->bits_per_sample > 32) supported = FALSE; if (!supported) { error_line ("%s is an unsupported .W64 format!", infilename); return WAVPACK_SOFT_ERROR; } if (chunk_header.ckSize < 40) { if (!config->channel_mask && !(config->qmode & QMODE_CHANS_UNASSIGNED)) { if (WaveHeader.NumChannels <= 2) config->channel_mask = 0x5 - WaveHeader.NumChannels; else if (WaveHeader.NumChannels <= 18) config->channel_mask = (1 << WaveHeader.NumChannels) - 1; else config->channel_mask = 0x3ffff; } } else if (WaveHeader.ChannelMask && (config->channel_mask || (config->qmode & QMODE_CHANS_UNASSIGNED))) { error_line ("this W64 file already has channel order information!"); return WAVPACK_SOFT_ERROR; } else if (WaveHeader.ChannelMask) config->channel_mask = WaveHeader.ChannelMask; if (format == 3) config->float_norm_exp = 127; else if ((config->qmode & QMODE_ADOBE_MODE) && WaveHeader.BlockAlign / WaveHeader.NumChannels == 4) { if (WaveHeader.BitsPerSample == 24) config->float_norm_exp = 127 + 23; else if (WaveHeader.BitsPerSample == 32) config->float_norm_exp = 127 + 15; } if (debug_logging_mode) { if (config->float_norm_exp == 127) error_line ("data format: normalized 32-bit floating point"); else error_line ("data format: %d-bit integers stored in %d byte(s)", config->bits_per_sample, WaveHeader.BlockAlign / WaveHeader.NumChannels); } } else if (!memcmp (chunk_header.ckID, data_guid, sizeof (data_guid))) { // on the data chunk, get size and exit loop if (!WaveHeader.NumChannels) { // make sure we saw "fmt" chunk error_line ("%s is not a valid .W64 file!", infilename); return WAVPACK_SOFT_ERROR; } if ((config->qmode & QMODE_IGNORE_LENGTH) || chunk_header.ckSize <= 0) { config->qmode |= QMODE_IGNORE_LENGTH; if (infilesize && DoGetFilePosition (infile) != -1) total_samples = (infilesize - DoGetFilePosition (infile)) / WaveHeader.BlockAlign; else total_samples = -1; } else { if (infilesize && infilesize - chunk_header.ckSize > 16777216) { error_line ("this .W64 file has over 16 MB of extra RIFF data, probably is corrupt!"); return WAVPACK_SOFT_ERROR; } total_samples = chunk_header.ckSize / WaveHeader.BlockAlign; if (!total_samples) { error_line ("this .W64 file has no audio samples, probably is corrupt!"); return WAVPACK_SOFT_ERROR; } if (total_samples > MAX_WAVPACK_SAMPLES) { error_line ("%s has too many samples for WavPack!", infilename); return WAVPACK_SOFT_ERROR; } } config->bytes_per_sample = WaveHeader.BlockAlign / WaveHeader.NumChannels; config->num_channels = WaveHeader.NumChannels; config->sample_rate = WaveHeader.SampleRate; break; } else { // just copy unknown chunks to output file int bytes_to_copy = (chunk_header.ckSize + 7) & ~7L; char *buff = malloc (bytes_to_copy); if (debug_logging_mode) error_line ("extra unknown chunk \"%c%c%c%c\" of %d bytes", chunk_header.ckID [0], chunk_header.ckID [1], chunk_header.ckID [2], chunk_header.ckID [3], chunk_header.ckSize); if (!DoReadFile (infile, buff, bytes_to_copy, &bcount) || bcount != bytes_to_copy || (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, buff, bytes_to_copy))) { error_line ("%s", WavpackGetErrorMessage (wpc)); free (buff); return WAVPACK_SOFT_ERROR; } free (buff); } } if (!WavpackSetConfiguration64 (wpc, config, total_samples, NULL)) { error_line ("%s: %s", infilename, WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } return WAVPACK_NO_ERROR; } Commit Message: issue #33, sanitize size of unknown chunks before malloc() CWE ID: CWE-787 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: check_compat_entry_size_and_hooks(struct compat_ip6t_entry *e, struct xt_table_info *newinfo, unsigned int *size, const unsigned char *base, const unsigned char *limit, const unsigned int *hook_entries, const unsigned int *underflows, const char *name) { struct xt_entry_match *ematch; struct xt_entry_target *t; struct xt_target *target; unsigned int entry_offset; unsigned int j; int ret, off, h; duprintf("check_compat_entry_size_and_hooks %p\n", e); if ((unsigned long)e % __alignof__(struct compat_ip6t_entry) != 0 || (unsigned char *)e + sizeof(struct compat_ip6t_entry) >= limit) { duprintf("Bad offset %p, limit = %p\n", e, limit); return -EINVAL; } if (e->next_offset < sizeof(struct compat_ip6t_entry) + sizeof(struct compat_xt_entry_target)) { duprintf("checking: element %p size %u\n", e, e->next_offset); return -EINVAL; } /* For purposes of check_entry casting the compat entry is fine */ ret = check_entry((struct ip6t_entry *)e); if (ret) return ret; off = sizeof(struct ip6t_entry) - sizeof(struct compat_ip6t_entry); entry_offset = (void *)e - (void *)base; j = 0; xt_ematch_foreach(ematch, e) { ret = compat_find_calc_match(ematch, name, &e->ipv6, &off); if (ret != 0) goto release_matches; ++j; } t = compat_ip6t_get_target(e); target = xt_request_find_target(NFPROTO_IPV6, t->u.user.name, t->u.user.revision); if (IS_ERR(target)) { duprintf("check_compat_entry_size_and_hooks: `%s' not found\n", t->u.user.name); ret = PTR_ERR(target); goto release_matches; } t->u.kernel.target = target; off += xt_compat_target_offset(target); *size += off; ret = xt_compat_add_offset(AF_INET6, entry_offset, off); if (ret) goto out; /* Check hooks & underflows */ for (h = 0; h < NF_INET_NUMHOOKS; h++) { if ((unsigned char *)e - base == hook_entries[h]) newinfo->hook_entry[h] = hook_entries[h]; if ((unsigned char *)e - base == underflows[h]) newinfo->underflow[h] = underflows[h]; } /* Clear counters and comefrom */ memset(&e->counters, 0, sizeof(e->counters)); e->comefrom = 0; return 0; out: module_put(t->u.kernel.target->me); release_matches: xt_ematch_foreach(ematch, e) { if (j-- == 0) break; module_put(ematch->u.kernel.match->me); } return ret; } Commit Message: netfilter: x_tables: make sure e->next_offset covers remaining blob size Otherwise this function may read data beyond the ruleset blob. Signed-off-by: Florian Westphal <[email protected]> Signed-off-by: Pablo Neira Ayuso <[email protected]> CWE ID: CWE-119 Target: 1 Example 2: Code: void OxideQQuickWebView::mousePressEvent(QMouseEvent* event) { Q_D(OxideQQuickWebView); QQuickItem::mousePressEvent(event); d->contents_view_->handleMousePressEvent(event); } Commit Message: CWE ID: CWE-20 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void DrawRoundLinecap(Image *image,const DrawInfo *draw_info, const PrimitiveInfo *primitive_info,ExceptionInfo *exception) { PrimitiveInfo linecap[5]; register ssize_t i; for (i=0; i < 4; i++) linecap[i]=(*primitive_info); linecap[0].coordinates=4; linecap[1].point.x+=(double) (10.0*MagickEpsilon); linecap[2].point.x+=(double) (10.0*MagickEpsilon); linecap[2].point.y+=(double) (10.0*MagickEpsilon); linecap[3].point.y+=(double) (10.0*MagickEpsilon); linecap[4].primitive=UndefinedPrimitive; (void) DrawPolygonPrimitive(image,draw_info,linecap,exception); } Commit Message: Prevent buffer overflow in magick/draw.c CWE ID: CWE-119 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static Sdb *store_versioninfo_gnu_verdef(ELFOBJ *bin, Elf_(Shdr) *shdr, int sz) { const char *section_name = ""; const char *link_section_name = ""; char *end = NULL; Elf_(Shdr) *link_shdr = NULL; ut8 dfs[sizeof (Elf_(Verdef))] = {0}; Sdb *sdb; int cnt, i; if (shdr->sh_link > bin->ehdr.e_shnum) { return false; } link_shdr = &bin->shdr[shdr->sh_link]; if ((int)shdr->sh_size < 1) { return false; } Elf_(Verdef) *defs = calloc (shdr->sh_size, sizeof (char)); if (!defs) { return false; } if (bin->shstrtab && shdr->sh_name < bin->shstrtab_size) { section_name = &bin->shstrtab[shdr->sh_name]; } if (link_shdr && bin->shstrtab && link_shdr->sh_name < bin->shstrtab_size) { link_section_name = &bin->shstrtab[link_shdr->sh_name]; } if (!defs) { bprintf ("Warning: Cannot allocate memory (Check Elf_(Verdef))\n"); return NULL; } sdb = sdb_new0 (); end = (char *)defs + shdr->sh_size; sdb_set (sdb, "section_name", section_name, 0); sdb_num_set (sdb, "entries", shdr->sh_info, 0); sdb_num_set (sdb, "addr", shdr->sh_addr, 0); sdb_num_set (sdb, "offset", shdr->sh_offset, 0); sdb_num_set (sdb, "link", shdr->sh_link, 0); sdb_set (sdb, "link_section_name", link_section_name, 0); for (cnt = 0, i = 0; i >= 0 && cnt < shdr->sh_info && ((char *)defs + i < end); ++cnt) { Sdb *sdb_verdef = sdb_new0 (); char *vstart = ((char*)defs) + i; char key[32] = {0}; Elf_(Verdef) *verdef = (Elf_(Verdef)*)vstart; Elf_(Verdaux) aux = {0}; int j = 0; int isum = 0; r_buf_read_at (bin->b, shdr->sh_offset + i, dfs, sizeof (Elf_(Verdef))); verdef->vd_version = READ16 (dfs, j) verdef->vd_flags = READ16 (dfs, j) verdef->vd_ndx = READ16 (dfs, j) verdef->vd_cnt = READ16 (dfs, j) verdef->vd_hash = READ32 (dfs, j) verdef->vd_aux = READ32 (dfs, j) verdef->vd_next = READ32 (dfs, j) int vdaux = verdef->vd_aux; if (vdaux < 1 || vstart + vdaux < vstart) { sdb_free (sdb_verdef); goto out_error; } vstart += vdaux; if (vstart > end || vstart + sizeof (Elf_(Verdaux)) > end) { sdb_free (sdb_verdef); goto out_error; } j = 0; aux.vda_name = READ32 (vstart, j) aux.vda_next = READ32 (vstart, j) isum = i + verdef->vd_aux; if (aux.vda_name > bin->dynstr_size) { sdb_free (sdb_verdef); goto out_error; } sdb_num_set (sdb_verdef, "idx", i, 0); sdb_num_set (sdb_verdef, "vd_version", verdef->vd_version, 0); sdb_num_set (sdb_verdef, "vd_ndx", verdef->vd_ndx, 0); sdb_num_set (sdb_verdef, "vd_cnt", verdef->vd_cnt, 0); sdb_set (sdb_verdef, "vda_name", &bin->dynstr[aux.vda_name], 0); sdb_set (sdb_verdef, "flags", get_ver_flags (verdef->vd_flags), 0); for (j = 1; j < verdef->vd_cnt; ++j) { int k; Sdb *sdb_parent = sdb_new0 (); isum += aux.vda_next; vstart += aux.vda_next; if (vstart > end || vstart + sizeof (Elf_(Verdaux)) > end) { sdb_free (sdb_verdef); sdb_free (sdb_parent); goto out_error; } k = 0; aux.vda_name = READ32 (vstart, k) aux.vda_next = READ32 (vstart, k) if (aux.vda_name > bin->dynstr_size) { sdb_free (sdb_verdef); sdb_free (sdb_parent); goto out_error; } sdb_num_set (sdb_parent, "idx", isum, 0); sdb_num_set (sdb_parent, "parent", j, 0); sdb_set (sdb_parent, "vda_name", &bin->dynstr[aux.vda_name], 0); snprintf (key, sizeof (key), "parent%d", j - 1); sdb_ns_set (sdb_verdef, key, sdb_parent); } snprintf (key, sizeof (key), "verdef%d", cnt); sdb_ns_set (sdb, key, sdb_verdef); if (!verdef->vd_next) { sdb_free (sdb_verdef); goto out_error; } if ((st32)verdef->vd_next < 1) { eprintf ("Warning: Invalid vd_next in the ELF version\n"); break; } i += verdef->vd_next; } free (defs); return sdb; out_error: free (defs); sdb_free (sdb); return NULL; } Commit Message: Fix #8764 a 3rd time since 2nd time is UB and can be optimized away CWE ID: CWE-476 Target: 1 Example 2: Code: void RenderWidgetHostImpl::DidAllocateSharedBitmap( mojo::ScopedSharedBufferHandle buffer, const viz::SharedBitmapId& id) { if (!viz::ServerSharedBitmapManager::current()->ChildAllocatedSharedBitmap( std::move(buffer), id)) { bad_message::ReceivedBadMessage(GetProcess(), bad_message::RWH_SHARED_BITMAP); } owned_bitmaps_.insert(id); } Commit Message: Force a flush of drawing to the widget when a dialog is shown. BUG=823353 TEST=as in bug Change-Id: I5da777068fc29c5638ef02d50e59d5d7b2729260 Reviewed-on: https://chromium-review.googlesource.com/971661 Reviewed-by: Ken Buchanan <[email protected]> Commit-Queue: Avi Drissman <[email protected]> Cr-Commit-Position: refs/heads/master@{#544518} CWE ID: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: gs_malloc_wrap(gs_memory_t **wrapped, gs_malloc_memory_t *contents) { # ifdef USE_RETRY_MEMORY_WRAPPER /* * This is deprecated since 'retry' for clist reversion/cycling * will ONLY work for monochrome, simple PS or PCL, not for a * color device and not for PDF or XPS with transparency */ { gs_memory_retrying_t *rmem; rmem = (gs_memory_retrying_t *) gs_alloc_bytes_immovable((gs_memory_t *)lmem, sizeof(gs_memory_retrying_t), "gs_malloc_wrap(retrying)"); if (rmem == 0) { gs_memory_locked_release(lmem); gs_free_object(cmem, lmem, "gs_malloc_wrap(locked)"); return_error(gs_error_VMerror); } code = gs_memory_retrying_init(rmem, (gs_memory_t *)lmem); if (code < 0) { gs_free_object((gs_memory_t *)lmem, rmem, "gs_malloc_wrap(retrying)"); gs_memory_locked_release(lmem); gs_free_object(cmem, lmem, "gs_malloc_wrap(locked)"); return code; } *wrapped = (gs_memory_t *)rmem; } # endif /* retrying */ return 0; } Commit Message: CWE ID: CWE-189 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static void rtc_irq_eoi_tracking_reset(struct kvm_ioapic *ioapic) { ioapic->rtc_status.pending_eoi = 0; bitmap_zero(ioapic->rtc_status.dest_map.map, KVM_MAX_VCPUS); } Commit Message: KVM: x86: fix out-of-bounds accesses of rtc_eoi map KVM was using arrays of size KVM_MAX_VCPUS with vcpu_id, but ID can be bigger that the maximal number of VCPUs, resulting in out-of-bounds access. Found by syzkaller: BUG: KASAN: slab-out-of-bounds in __apic_accept_irq+0xb33/0xb50 at addr [...] Write of size 1 by task a.out/27101 CPU: 1 PID: 27101 Comm: a.out Not tainted 4.9.0-rc5+ #49 Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS Bochs 01/01/2011 [...] Call Trace: [...] __apic_accept_irq+0xb33/0xb50 arch/x86/kvm/lapic.c:905 [...] kvm_apic_set_irq+0x10e/0x180 arch/x86/kvm/lapic.c:495 [...] kvm_irq_delivery_to_apic+0x732/0xc10 arch/x86/kvm/irq_comm.c:86 [...] ioapic_service+0x41d/0x760 arch/x86/kvm/ioapic.c:360 [...] ioapic_set_irq+0x275/0x6c0 arch/x86/kvm/ioapic.c:222 [...] kvm_ioapic_inject_all arch/x86/kvm/ioapic.c:235 [...] kvm_set_ioapic+0x223/0x310 arch/x86/kvm/ioapic.c:670 [...] kvm_vm_ioctl_set_irqchip arch/x86/kvm/x86.c:3668 [...] kvm_arch_vm_ioctl+0x1a08/0x23c0 arch/x86/kvm/x86.c:3999 [...] kvm_vm_ioctl+0x1fa/0x1a70 arch/x86/kvm/../../../virt/kvm/kvm_main.c:3099 Reported-by: Dmitry Vyukov <[email protected]> Cc: [email protected] Fixes: af1bae5497b9 ("KVM: x86: bump KVM_MAX_VCPU_ID to 1023") Reviewed-by: Paolo Bonzini <[email protected]> Reviewed-by: David Hildenbrand <[email protected]> Signed-off-by: Radim Krčmář <[email protected]> CWE ID: CWE-125 Target: 1 Example 2: Code: int sock_diag_register(const struct sock_diag_handler *hndl) { int err = 0; if (hndl->family >= AF_MAX) return -EINVAL; mutex_lock(&sock_diag_table_mutex); if (sock_diag_handlers[hndl->family]) err = -EBUSY; else sock_diag_handlers[hndl->family] = hndl; mutex_unlock(&sock_diag_table_mutex); return err; } Commit Message: sock_diag: Fix out-of-bounds access to sock_diag_handlers[] Userland can send a netlink message requesting SOCK_DIAG_BY_FAMILY with a family greater or equal then AF_MAX -- the array size of sock_diag_handlers[]. The current code does not test for this condition therefore is vulnerable to an out-of-bound access opening doors for a privilege escalation. Signed-off-by: Mathias Krause <[email protected]> Acked-by: Eric Dumazet <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-20 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: char **XListExtensions( register Display *dpy, int *nextensions) /* RETURN */ { xListExtensionsReply rep; char **list = NULL; char *ch = NULL; char *chend; int count = 0; register unsigned i; register int length; _X_UNUSED register xReq *req; unsigned long rlen = 0; LockDisplay(dpy); GetEmptyReq (ListExtensions, req); if (! _XReply (dpy, (xReply *) &rep, 0, xFalse)) { UnlockDisplay(dpy); SyncHandle(); return (char **) NULL; } if (rep.nExtensions) { list = Xmalloc (rep.nExtensions * sizeof (char *)); if (rep.length > 0 && rep.length < (INT_MAX >> 2)) { rlen = rep.length << 2; ch = Xmalloc (rlen + 1); /* +1 to leave room for last null-terminator */ } if ((!list) || (!ch)) { Xfree(list); Xfree(ch); _XEatDataWords(dpy, rep.length); UnlockDisplay(dpy); SyncHandle(); return (char **) NULL; } _XReadPad (dpy, ch, rlen); /* * unpack into null terminated strings. */ chend = ch + (rlen + 1); length = *ch; for (i = 0; i < rep.nExtensions; i++) { if (ch + length < chend) { list[i] = ch+1; /* skip over length */ ch += length + 1; /* find next length ... */ if (ch <= chend) { length = *ch; *ch = '\0'; /* and replace with null-termination */ count++; } else { list[i] = NULL; } } else list[i] = NULL; } } } else Commit Message: CWE ID: CWE-682 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: WORD32 ih264d_video_decode(iv_obj_t *dec_hdl, void *pv_api_ip, void *pv_api_op) { /* ! */ dec_struct_t * ps_dec = (dec_struct_t *)(dec_hdl->pv_codec_handle); WORD32 i4_err_status = 0; UWORD8 *pu1_buf = NULL; WORD32 buflen; UWORD32 u4_max_ofst, u4_length_of_start_code = 0; UWORD32 bytes_consumed = 0; UWORD32 cur_slice_is_nonref = 0; UWORD32 u4_next_is_aud; UWORD32 u4_first_start_code_found = 0; WORD32 ret = 0,api_ret_value = IV_SUCCESS; WORD32 header_data_left = 0,frame_data_left = 0; UWORD8 *pu1_bitstrm_buf; ivd_video_decode_ip_t *ps_dec_ip; ivd_video_decode_op_t *ps_dec_op; ithread_set_name((void*)"Parse_thread"); ps_dec_ip = (ivd_video_decode_ip_t *)pv_api_ip; ps_dec_op = (ivd_video_decode_op_t *)pv_api_op; { UWORD32 u4_size; u4_size = ps_dec_op->u4_size; memset(ps_dec_op, 0, sizeof(ivd_video_decode_op_t)); ps_dec_op->u4_size = u4_size; } ps_dec->pv_dec_out = ps_dec_op; ps_dec->process_called = 1; if(ps_dec->init_done != 1) { return IV_FAIL; } /*Data memory barries instruction,so that bitstream write by the application is complete*/ DATA_SYNC(); if(0 == ps_dec->u1_flushfrm) { if(ps_dec_ip->pv_stream_buffer == NULL) { ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM; ps_dec_op->u4_error_code |= IVD_DEC_FRM_BS_BUF_NULL; return IV_FAIL; } if(ps_dec_ip->u4_num_Bytes <= 0) { ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM; ps_dec_op->u4_error_code |= IVD_DEC_NUMBYTES_INV; return IV_FAIL; } } ps_dec->u1_pic_decode_done = 0; ps_dec_op->u4_num_bytes_consumed = 0; ps_dec->ps_out_buffer = NULL; if(ps_dec_ip->u4_size >= offsetof(ivd_video_decode_ip_t, s_out_buffer)) ps_dec->ps_out_buffer = &ps_dec_ip->s_out_buffer; ps_dec->u4_fmt_conv_cur_row = 0; ps_dec->u4_output_present = 0; ps_dec->s_disp_op.u4_error_code = 1; ps_dec->u4_fmt_conv_num_rows = FMT_CONV_NUM_ROWS; ps_dec->u4_stop_threads = 0; if(0 == ps_dec->u4_share_disp_buf && ps_dec->i4_decode_header == 0) { UWORD32 i; if(ps_dec->ps_out_buffer->u4_num_bufs == 0) { ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM; ps_dec_op->u4_error_code |= IVD_DISP_FRM_ZERO_OP_BUFS; return IV_FAIL; } for(i = 0; i < ps_dec->ps_out_buffer->u4_num_bufs; i++) { if(ps_dec->ps_out_buffer->pu1_bufs[i] == NULL) { ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM; ps_dec_op->u4_error_code |= IVD_DISP_FRM_OP_BUF_NULL; return IV_FAIL; } if(ps_dec->ps_out_buffer->u4_min_out_buf_size[i] == 0) { ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM; ps_dec_op->u4_error_code |= IVD_DISP_FRM_ZERO_OP_BUF_SIZE; return IV_FAIL; } } } if(ps_dec->u4_total_frames_decoded >= NUM_FRAMES_LIMIT) { ps_dec_op->u4_error_code = ERROR_FRAME_LIMIT_OVER; return IV_FAIL; } /* ! */ ps_dec->u4_ts = ps_dec_ip->u4_ts; ps_dec_op->u4_error_code = 0; ps_dec_op->e_pic_type = -1; ps_dec_op->u4_output_present = 0; ps_dec_op->u4_frame_decoded_flag = 0; ps_dec->i4_frametype = -1; ps_dec->i4_content_type = -1; ps_dec->u4_slice_start_code_found = 0; /* In case the deocder is not in flush mode(in shared mode), then decoder has to pick up a buffer to write current frame. Check if a frame is available in such cases */ if(ps_dec->u1_init_dec_flag == 1 && ps_dec->u4_share_disp_buf == 1 && ps_dec->u1_flushfrm == 0) { UWORD32 i; WORD32 disp_avail = 0, free_id; /* Check if at least one buffer is available with the codec */ /* If not then return to application with error */ for(i = 0; i < ps_dec->u1_pic_bufs; i++) { if(0 == ps_dec->u4_disp_buf_mapping[i] || 1 == ps_dec->u4_disp_buf_to_be_freed[i]) { disp_avail = 1; break; } } if(0 == disp_avail) { /* If something is queued for display wait for that buffer to be returned */ ps_dec_op->u4_error_code = IVD_DEC_REF_BUF_NULL; ps_dec_op->u4_error_code |= (1 << IVD_UNSUPPORTEDPARAM); return (IV_FAIL); } while(1) { pic_buffer_t *ps_pic_buf; ps_pic_buf = (pic_buffer_t *)ih264_buf_mgr_get_next_free( (buf_mgr_t *)ps_dec->pv_pic_buf_mgr, &free_id); if(ps_pic_buf == NULL) { UWORD32 i, display_queued = 0; /* check if any buffer was given for display which is not returned yet */ for(i = 0; i < (MAX_DISP_BUFS_NEW); i++) { if(0 != ps_dec->u4_disp_buf_mapping[i]) { display_queued = 1; break; } } /* If some buffer is queued for display, then codec has to singal an error and wait for that buffer to be returned. If nothing is queued for display then codec has ownership of all display buffers and it can reuse any of the existing buffers and continue decoding */ if(1 == display_queued) { /* If something is queued for display wait for that buffer to be returned */ ps_dec_op->u4_error_code = IVD_DEC_REF_BUF_NULL; ps_dec_op->u4_error_code |= (1 << IVD_UNSUPPORTEDPARAM); return (IV_FAIL); } } else { /* If the buffer is with display, then mark it as in use and then look for a buffer again */ if(1 == ps_dec->u4_disp_buf_mapping[free_id]) { ih264_buf_mgr_set_status( (buf_mgr_t *)ps_dec->pv_pic_buf_mgr, free_id, BUF_MGR_IO); } else { /** * Found a free buffer for present call. Release it now. * Will be again obtained later. */ ih264_buf_mgr_release((buf_mgr_t *)ps_dec->pv_pic_buf_mgr, free_id, BUF_MGR_IO); break; } } } } if(ps_dec->u1_flushfrm && ps_dec->u1_init_dec_flag) { ih264d_get_next_display_field(ps_dec, ps_dec->ps_out_buffer, &(ps_dec->s_disp_op)); if(0 == ps_dec->s_disp_op.u4_error_code) { ps_dec->u4_fmt_conv_cur_row = 0; ps_dec->u4_fmt_conv_num_rows = ps_dec->s_disp_frame_info.u4_y_ht; ih264d_format_convert(ps_dec, &(ps_dec->s_disp_op), ps_dec->u4_fmt_conv_cur_row, ps_dec->u4_fmt_conv_num_rows); ps_dec->u4_fmt_conv_cur_row += ps_dec->u4_fmt_conv_num_rows; ps_dec->u4_output_present = 1; } ih264d_release_display_field(ps_dec, &(ps_dec->s_disp_op)); ps_dec_op->u4_pic_wd = (UWORD32)ps_dec->u2_disp_width; ps_dec_op->u4_pic_ht = (UWORD32)ps_dec->u2_disp_height; ps_dec_op->u4_new_seq = 0; ps_dec_op->u4_output_present = ps_dec->u4_output_present; ps_dec_op->u4_progressive_frame_flag = ps_dec->s_disp_op.u4_progressive_frame_flag; ps_dec_op->e_output_format = ps_dec->s_disp_op.e_output_format; ps_dec_op->s_disp_frm_buf = ps_dec->s_disp_op.s_disp_frm_buf; ps_dec_op->e4_fld_type = ps_dec->s_disp_op.e4_fld_type; ps_dec_op->u4_ts = ps_dec->s_disp_op.u4_ts; ps_dec_op->u4_disp_buf_id = ps_dec->s_disp_op.u4_disp_buf_id; /*In the case of flush ,since no frame is decoded set pic type as invalid*/ ps_dec_op->u4_is_ref_flag = -1; ps_dec_op->e_pic_type = IV_NA_FRAME; ps_dec_op->u4_frame_decoded_flag = 0; if(0 == ps_dec->s_disp_op.u4_error_code) { return (IV_SUCCESS); } else return (IV_FAIL); } if(ps_dec->u1_res_changed == 1) { /*if resolution has changed and all buffers have been flushed, reset decoder*/ ih264d_init_decoder(ps_dec); } ps_dec->u4_prev_nal_skipped = 0; ps_dec->u2_cur_mb_addr = 0; ps_dec->u2_total_mbs_coded = 0; ps_dec->u2_cur_slice_num = 0; ps_dec->cur_dec_mb_num = 0; ps_dec->cur_recon_mb_num = 0; ps_dec->u4_first_slice_in_pic = 2; ps_dec->u1_first_pb_nal_in_pic = 1; ps_dec->u1_slice_header_done = 0; ps_dec->u1_dangling_field = 0; ps_dec->u4_dec_thread_created = 0; ps_dec->u4_bs_deblk_thread_created = 0; ps_dec->u4_cur_bs_mb_num = 0; ps_dec->u4_start_recon_deblk = 0; DEBUG_THREADS_PRINTF(" Starting process call\n"); ps_dec->u4_pic_buf_got = 0; do { pu1_buf = (UWORD8*)ps_dec_ip->pv_stream_buffer + ps_dec_op->u4_num_bytes_consumed; u4_max_ofst = ps_dec_ip->u4_num_Bytes - ps_dec_op->u4_num_bytes_consumed; pu1_bitstrm_buf = ps_dec->ps_mem_tab[MEM_REC_BITSBUF].pv_base; u4_next_is_aud = 0; buflen = ih264d_find_start_code(pu1_buf, 0, u4_max_ofst, &u4_length_of_start_code, &u4_next_is_aud); if(buflen == -1) buflen = 0; /* Ignore bytes beyond the allocated size of intermediate buffer */ /* Since 8 bytes are read ahead, ensure 8 bytes are free at the end of the buffer, which will be memset to 0 after emulation prevention */ buflen = MIN(buflen, (WORD32)(ps_dec->ps_mem_tab[MEM_REC_BITSBUF].u4_mem_size - 8)); bytes_consumed = buflen + u4_length_of_start_code; ps_dec_op->u4_num_bytes_consumed += bytes_consumed; if(buflen >= MAX_NAL_UNIT_SIZE) { ih264d_fill_output_struct_from_context(ps_dec, ps_dec_op); H264_DEC_DEBUG_PRINT( "\nNal Size exceeded %d, Processing Stopped..\n", MAX_NAL_UNIT_SIZE); ps_dec->i4_error_code = 1 << IVD_CORRUPTEDDATA; ps_dec_op->e_pic_type = -1; /*signal the decode thread*/ ih264d_signal_decode_thread(ps_dec); /*signal end of frame decode for curren frame*/ if(ps_dec->u4_pic_buf_got == 0) { if(ps_dec->i4_header_decoded == 3) { ps_dec->u2_total_mbs_coded = ps_dec->ps_cur_sps->u2_max_mb_addr + 1; } /* close deblock thread if it is not closed yet*/ if(ps_dec->u4_num_cores == 3) { ih264d_signal_bs_deblk_thread(ps_dec); } return IV_FAIL; } else { ps_dec->u1_pic_decode_done = 1; continue; } } { UWORD8 u1_firstbyte, u1_nal_ref_idc; if(ps_dec->i4_app_skip_mode == IVD_SKIP_B) { u1_firstbyte = *(pu1_buf + u4_length_of_start_code); u1_nal_ref_idc = (UWORD8)(NAL_REF_IDC(u1_firstbyte)); if(u1_nal_ref_idc == 0) { /*skip non reference frames*/ cur_slice_is_nonref = 1; continue; } else { if(1 == cur_slice_is_nonref) { /*We have encountered a referenced frame,return to app*/ ps_dec_op->u4_num_bytes_consumed -= bytes_consumed; ps_dec_op->e_pic_type = IV_B_FRAME; ps_dec_op->u4_error_code = IVD_DEC_FRM_SKIPPED; ps_dec_op->u4_error_code |= (1 << IVD_UNSUPPORTEDPARAM); ps_dec_op->u4_frame_decoded_flag = 0; ps_dec_op->u4_size = sizeof(ivd_video_decode_op_t); /*signal the decode thread*/ ih264d_signal_decode_thread(ps_dec); /* close deblock thread if it is not closed yet*/ if(ps_dec->u4_num_cores == 3) { ih264d_signal_bs_deblk_thread(ps_dec); } return (IV_FAIL); } } } } if(buflen) { memcpy(pu1_bitstrm_buf, pu1_buf + u4_length_of_start_code, buflen); u4_first_start_code_found = 1; } else { /*start code not found*/ if(u4_first_start_code_found == 0) { /*no start codes found in current process call*/ ps_dec->i4_error_code = ERROR_START_CODE_NOT_FOUND; ps_dec_op->u4_error_code |= 1 << IVD_INSUFFICIENTDATA; if(ps_dec->u4_pic_buf_got == 0) { ih264d_fill_output_struct_from_context(ps_dec, ps_dec_op); ps_dec_op->u4_error_code = ps_dec->i4_error_code; ps_dec_op->u4_frame_decoded_flag = 0; return (IV_FAIL); } else { ps_dec->u1_pic_decode_done = 1; continue; } } else { /* a start code has already been found earlier in the same process call*/ frame_data_left = 0; header_data_left = 0; continue; } } ps_dec->u4_return_to_app = 0; ret = ih264d_parse_nal_unit(dec_hdl, ps_dec_op, pu1_bitstrm_buf, buflen); if(ret != OK) { UWORD32 error = ih264d_map_error(ret); ps_dec_op->u4_error_code = error | ret; api_ret_value = IV_FAIL; if((ret == IVD_RES_CHANGED) || (ret == IVD_STREAM_WIDTH_HEIGHT_NOT_SUPPORTED) || (ret == ERROR_UNAVAIL_PICBUF_T) || (ret == ERROR_UNAVAIL_MVBUF_T) || (ret == ERROR_INV_SPS_PPS_T)) { ps_dec->u4_slice_start_code_found = 0; break; } if((ret == ERROR_INCOMPLETE_FRAME) || (ret == ERROR_DANGLING_FIELD_IN_PIC)) { ps_dec_op->u4_num_bytes_consumed -= bytes_consumed; api_ret_value = IV_FAIL; break; } if(ret == ERROR_IN_LAST_SLICE_OF_PIC) { api_ret_value = IV_FAIL; break; } } if(ps_dec->u4_return_to_app) { /*We have encountered a referenced frame,return to app*/ ps_dec_op->u4_num_bytes_consumed -= bytes_consumed; ps_dec_op->u4_error_code = IVD_DEC_FRM_SKIPPED; ps_dec_op->u4_error_code |= (1 << IVD_UNSUPPORTEDPARAM); ps_dec_op->u4_frame_decoded_flag = 0; ps_dec_op->u4_size = sizeof(ivd_video_decode_op_t); /*signal the decode thread*/ ih264d_signal_decode_thread(ps_dec); /* close deblock thread if it is not closed yet*/ if(ps_dec->u4_num_cores == 3) { ih264d_signal_bs_deblk_thread(ps_dec); } return (IV_FAIL); } header_data_left = ((ps_dec->i4_decode_header == 1) && (ps_dec->i4_header_decoded != 3) && (ps_dec_op->u4_num_bytes_consumed < ps_dec_ip->u4_num_Bytes)); frame_data_left = (((ps_dec->i4_decode_header == 0) && ((ps_dec->u1_pic_decode_done == 0) || (u4_next_is_aud == 1))) && (ps_dec_op->u4_num_bytes_consumed < ps_dec_ip->u4_num_Bytes)); } while(( header_data_left == 1)||(frame_data_left == 1)); if((ps_dec->u4_slice_start_code_found == 1) && ps_dec->u2_total_mbs_coded < ps_dec->u2_frm_ht_in_mbs * ps_dec->u2_frm_wd_in_mbs) { WORD32 num_mb_skipped; WORD32 prev_slice_err; pocstruct_t temp_poc; WORD32 ret1; WORD32 ht_in_mbs; ht_in_mbs = ps_dec->u2_pic_ht >> (4 + ps_dec->ps_cur_slice->u1_field_pic_flag); num_mb_skipped = (ht_in_mbs * ps_dec->u2_frm_wd_in_mbs) - ps_dec->u2_total_mbs_coded; if(ps_dec->u4_first_slice_in_pic && (ps_dec->u4_pic_buf_got == 0)) prev_slice_err = 1; else prev_slice_err = 2; if(ps_dec->u4_first_slice_in_pic && (ps_dec->u2_total_mbs_coded == 0)) prev_slice_err = 1; ret1 = ih264d_mark_err_slice_skip(ps_dec, num_mb_skipped, ps_dec->u1_nal_unit_type == IDR_SLICE_NAL, ps_dec->ps_cur_slice->u2_frame_num, &temp_poc, prev_slice_err); if((ret1 == ERROR_UNAVAIL_PICBUF_T) || (ret1 == ERROR_UNAVAIL_MVBUF_T) || (ret1 == ERROR_INV_SPS_PPS_T)) { ret = ret1; } } if((ret == IVD_RES_CHANGED) || (ret == IVD_STREAM_WIDTH_HEIGHT_NOT_SUPPORTED) || (ret == ERROR_UNAVAIL_PICBUF_T) || (ret == ERROR_UNAVAIL_MVBUF_T) || (ret == ERROR_INV_SPS_PPS_T)) { /* signal the decode thread */ ih264d_signal_decode_thread(ps_dec); /* close deblock thread if it is not closed yet */ if(ps_dec->u4_num_cores == 3) { ih264d_signal_bs_deblk_thread(ps_dec); } /* dont consume bitstream for change in resolution case */ if(ret == IVD_RES_CHANGED) { ps_dec_op->u4_num_bytes_consumed -= bytes_consumed; } return IV_FAIL; } if(ps_dec->u1_separate_parse) { /* If Format conversion is not complete, complete it here */ if(ps_dec->u4_num_cores == 2) { /*do deblocking of all mbs*/ if((ps_dec->u4_nmb_deblk == 0) &&(ps_dec->u4_start_recon_deblk == 1) && (ps_dec->ps_cur_sps->u1_mb_aff_flag == 0)) { UWORD32 u4_num_mbs,u4_max_addr; tfr_ctxt_t s_tfr_ctxt; tfr_ctxt_t *ps_tfr_cxt = &s_tfr_ctxt; pad_mgr_t *ps_pad_mgr = &ps_dec->s_pad_mgr; /*BS is done for all mbs while parsing*/ u4_max_addr = (ps_dec->u2_frm_wd_in_mbs * ps_dec->u2_frm_ht_in_mbs) - 1; ps_dec->u4_cur_bs_mb_num = u4_max_addr + 1; ih264d_init_deblk_tfr_ctxt(ps_dec, ps_pad_mgr, ps_tfr_cxt, ps_dec->u2_frm_wd_in_mbs, 0); u4_num_mbs = u4_max_addr - ps_dec->u4_cur_deblk_mb_num + 1; DEBUG_PERF_PRINTF("mbs left for deblocking= %d \n",u4_num_mbs); if(u4_num_mbs != 0) ih264d_check_mb_map_deblk(ps_dec, u4_num_mbs, ps_tfr_cxt,1); ps_dec->u4_start_recon_deblk = 0; } } /*signal the decode thread*/ ih264d_signal_decode_thread(ps_dec); /* close deblock thread if it is not closed yet*/ if(ps_dec->u4_num_cores == 3) { ih264d_signal_bs_deblk_thread(ps_dec); } } DATA_SYNC(); if((ps_dec_op->u4_error_code & 0xff) != ERROR_DYNAMIC_RESOLUTION_NOT_SUPPORTED) { ps_dec_op->u4_pic_wd = (UWORD32)ps_dec->u2_disp_width; ps_dec_op->u4_pic_ht = (UWORD32)ps_dec->u2_disp_height; } if(ps_dec->i4_header_decoded != 3) { ps_dec_op->u4_error_code |= (1 << IVD_INSUFFICIENTDATA); } if(ps_dec->i4_decode_header == 1 && ps_dec->i4_header_decoded != 3) { ps_dec_op->u4_error_code |= (1 << IVD_INSUFFICIENTDATA); } if(ps_dec->u4_prev_nal_skipped) { /*We have encountered a referenced frame,return to app*/ ps_dec_op->u4_error_code = IVD_DEC_FRM_SKIPPED; ps_dec_op->u4_error_code |= (1 << IVD_UNSUPPORTEDPARAM); ps_dec_op->u4_frame_decoded_flag = 0; ps_dec_op->u4_size = sizeof(ivd_video_decode_op_t); /* close deblock thread if it is not closed yet*/ if(ps_dec->u4_num_cores == 3) { ih264d_signal_bs_deblk_thread(ps_dec); } return (IV_FAIL); } if((ps_dec->u4_slice_start_code_found == 1) && (ERROR_DANGLING_FIELD_IN_PIC != i4_err_status)) { /* * For field pictures, set the bottom and top picture decoded u4_flag correctly. */ if(ps_dec->ps_cur_slice->u1_field_pic_flag) { if(1 == ps_dec->ps_cur_slice->u1_bottom_field_flag) { ps_dec->u1_top_bottom_decoded |= BOT_FIELD_ONLY; } else { ps_dec->u1_top_bottom_decoded |= TOP_FIELD_ONLY; } } /* if new frame in not found (if we are still getting slices from previous frame) * ih264d_deblock_display is not called. Such frames will not be added to reference /display */ if (((ps_dec->ps_dec_err_status->u1_err_flag & REJECT_CUR_PIC) == 0) && (ps_dec->u4_pic_buf_got == 1)) { /* Calling Function to deblock Picture and Display */ ret = ih264d_deblock_display(ps_dec); } /*set to complete ,as we dont support partial frame decode*/ if(ps_dec->i4_header_decoded == 3) { ps_dec->u2_total_mbs_coded = ps_dec->ps_cur_sps->u2_max_mb_addr + 1; } /*Update the i4_frametype at the end of picture*/ if(ps_dec->ps_cur_slice->u1_nal_unit_type == IDR_SLICE_NAL) { ps_dec->i4_frametype = IV_IDR_FRAME; } else if(ps_dec->i4_pic_type == B_SLICE) { ps_dec->i4_frametype = IV_B_FRAME; } else if(ps_dec->i4_pic_type == P_SLICE) { ps_dec->i4_frametype = IV_P_FRAME; } else if(ps_dec->i4_pic_type == I_SLICE) { ps_dec->i4_frametype = IV_I_FRAME; } else { H264_DEC_DEBUG_PRINT("Shouldn't come here\n"); } ps_dec->i4_content_type = ps_dec->ps_cur_slice->u1_field_pic_flag; ps_dec->u4_total_frames_decoded = ps_dec->u4_total_frames_decoded + 2; ps_dec->u4_total_frames_decoded = ps_dec->u4_total_frames_decoded - ps_dec->ps_cur_slice->u1_field_pic_flag; } /* close deblock thread if it is not closed yet*/ if(ps_dec->u4_num_cores == 3) { ih264d_signal_bs_deblk_thread(ps_dec); } { /* In case the decoder is configured to run in low delay mode, * then get display buffer and then format convert. * Note in this mode, format conversion does not run paralelly in a thread and adds to the codec cycles */ if((0 == ps_dec->u4_num_reorder_frames_at_init) && ps_dec->u1_init_dec_flag) { ih264d_get_next_display_field(ps_dec, ps_dec->ps_out_buffer, &(ps_dec->s_disp_op)); if(0 == ps_dec->s_disp_op.u4_error_code) { ps_dec->u4_fmt_conv_cur_row = 0; ps_dec->u4_output_present = 1; } } ih264d_fill_output_struct_from_context(ps_dec, ps_dec_op); /* If Format conversion is not complete, complete it here */ if(ps_dec->u4_output_present && (ps_dec->u4_fmt_conv_cur_row < ps_dec->s_disp_frame_info.u4_y_ht)) { ps_dec->u4_fmt_conv_num_rows = ps_dec->s_disp_frame_info.u4_y_ht - ps_dec->u4_fmt_conv_cur_row; ih264d_format_convert(ps_dec, &(ps_dec->s_disp_op), ps_dec->u4_fmt_conv_cur_row, ps_dec->u4_fmt_conv_num_rows); ps_dec->u4_fmt_conv_cur_row += ps_dec->u4_fmt_conv_num_rows; } ih264d_release_display_field(ps_dec, &(ps_dec->s_disp_op)); } if(ps_dec->i4_decode_header == 1 && (ps_dec->i4_header_decoded & 1) == 1) { ps_dec_op->u4_progressive_frame_flag = 1; if((NULL != ps_dec->ps_cur_sps) && (1 == (ps_dec->ps_cur_sps->u1_is_valid))) { if((0 == ps_dec->ps_sps->u1_frame_mbs_only_flag) && (0 == ps_dec->ps_sps->u1_mb_aff_flag)) ps_dec_op->u4_progressive_frame_flag = 0; } } if((TOP_FIELD_ONLY | BOT_FIELD_ONLY) == ps_dec->u1_top_bottom_decoded) { ps_dec->u1_top_bottom_decoded = 0; } /*--------------------------------------------------------------------*/ /* Do End of Pic processing. */ /* Should be called only if frame was decoded in previous process call*/ /*--------------------------------------------------------------------*/ if(ps_dec->u4_pic_buf_got == 1) { if(1 == ps_dec->u1_last_pic_not_decoded) { ret = ih264d_end_of_pic_dispbuf_mgr(ps_dec); if(ret != OK) return ret; ret = ih264d_end_of_pic(ps_dec); if(ret != OK) return ret; } else { ret = ih264d_end_of_pic(ps_dec); if(ret != OK) return ret; } } /*Data memory barrier instruction,so that yuv write by the library is complete*/ DATA_SYNC(); H264_DEC_DEBUG_PRINT("The num bytes consumed: %d\n", ps_dec_op->u4_num_bytes_consumed); return api_ret_value; } Commit Message: Decoder: Fixed initialization of first_slice_in_pic To handle some errors, first_slice_in_pic was being set to 2. This is now cleaned up and first_slice_in_pic is set to 1 only once per pic. This will ensure picture level initializations are done only once even in case of error clips Bug: 33717589 Bug: 33551775 Bug: 33716442 Bug: 33677995 Change-Id: If341436b3cbaa724017eedddd88c2e6fac36d8ba CWE ID: CWE-200 Target: 1 Example 2: Code: IntSize PaintLayerScrollableArea::MaximumScrollOffsetInt() const { if (!GetLayoutBox() || !GetLayoutBox()->HasOverflowClip()) return ToIntSize(-ScrollOrigin()); IntSize content_size = ContentsSize(); Page* page = GetLayoutBox()->GetDocument().GetPage(); DCHECK(page); TopDocumentRootScrollerController& controller = page->GlobalRootScrollerController(); IntSize visible_size; if (this == controller.RootScrollerArea()) { visible_size = controller.RootScrollerVisibleArea(); } else { visible_size = PixelSnappedIntRect(GetLayoutBox()->OverflowClipRect( GetLayoutBox()->Location(), kIgnorePlatformAndCSSOverlayScrollbarSize)) .Size(); } content_size = content_size.ExpandedTo(visible_size); return ToIntSize(-ScrollOrigin() + (content_size - visible_size)); } Commit Message: Always call UpdateCompositedScrollOffset, not just for the root layer Bug: 927560 Change-Id: I1d5522aae4f11dd3f5b8947bb089bac1bf19bdb4 Reviewed-on: https://chromium-review.googlesource.com/c/1452701 Reviewed-by: Chris Harrelson <[email protected]> Commit-Queue: Mason Freed <[email protected]> Cr-Commit-Position: refs/heads/master@{#628942} CWE ID: CWE-79 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void DetachWebContentsTest(DiscardReason reason) { LifecycleUnit* first_lifecycle_unit = nullptr; LifecycleUnit* second_lifecycle_unit = nullptr; CreateTwoTabs(true /* focus_tab_strip */, &first_lifecycle_unit, &second_lifecycle_unit); ExpectCanDiscardTrueAllReasons(first_lifecycle_unit); std::unique_ptr<content::WebContents> owned_contents = tab_strip_model_->DetachWebContentsAt(0); ExpectCanDiscardFalseTrivialAllReasons(first_lifecycle_unit); NoUnloadListenerTabStripModelDelegate other_tab_strip_model_delegate; TabStripModel other_tab_strip_model(&other_tab_strip_model_delegate, profile()); other_tab_strip_model.AddObserver(source_); EXPECT_CALL(source_observer_, OnLifecycleUnitCreated(testing::_)); other_tab_strip_model.AppendWebContents(CreateTestWebContents(), /*foreground=*/true); other_tab_strip_model.AppendWebContents(std::move(owned_contents), false); ExpectCanDiscardTrueAllReasons(first_lifecycle_unit); EXPECT_EQ(LifecycleUnitState::ACTIVE, first_lifecycle_unit->GetState()); EXPECT_CALL(tab_observer_, OnDiscardedStateChange(testing::_, true)); first_lifecycle_unit->Discard(reason); testing::Mock::VerifyAndClear(&tab_observer_); TransitionFromPendingDiscardToDiscardedIfNeeded(reason, first_lifecycle_unit); CloseTabsAndExpectNotifications(&other_tab_strip_model, {first_lifecycle_unit}); } Commit Message: Connect the LocalDB to TabManager. Bug: 773382 Change-Id: Iec8fe5226ee175105d51f300f30b4865478ac099 Reviewed-on: https://chromium-review.googlesource.com/1118611 Commit-Queue: Sébastien Marchand <[email protected]> Reviewed-by: François Doray <[email protected]> Cr-Commit-Position: refs/heads/master@{#572871} CWE ID: Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: MagickExport MagickBooleanType DrawImage(Image *image,const DrawInfo *draw_info, ExceptionInfo *exception) { #define RenderImageTag "Render/Image" AffineMatrix affine, current; char keyword[MagickPathExtent], geometry[MagickPathExtent], pattern[MagickPathExtent], *primitive, *token; const char *q; DrawInfo **graphic_context; MagickBooleanType proceed; MagickStatusType status; double angle, factor, primitive_extent; PointInfo point; PrimitiveInfo *primitive_info; PrimitiveType primitive_type; register const char *p; register ssize_t i, x; SegmentInfo bounds; size_t extent, length, number_points, number_stops; ssize_t j, k, n; StopInfo *stops; /* Ensure the annotation info is valid. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(draw_info != (DrawInfo *) NULL); assert(draw_info->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); if ((draw_info->primitive == (char *) NULL) || (*draw_info->primitive == '\0')) return(MagickFalse); if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule(),"begin draw-image"); if (*draw_info->primitive != '@') primitive=AcquireString(draw_info->primitive); else primitive=FileToString(draw_info->primitive+1,~0UL,exception); if (primitive == (char *) NULL) return(MagickFalse); primitive_extent=(double) strlen(primitive); (void) SetImageArtifact(image,"MVG",primitive); n=0; number_stops=0; stops=(StopInfo *) NULL; /* Allocate primitive info memory. */ graphic_context=(DrawInfo **) AcquireMagickMemory( sizeof(*graphic_context)); if (graphic_context == (DrawInfo **) NULL) { primitive=DestroyString(primitive); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } number_points=6553; primitive_info=(PrimitiveInfo *) AcquireQuantumMemory((size_t) number_points, sizeof(*primitive_info)); if (primitive_info == (PrimitiveInfo *) NULL) { primitive=DestroyString(primitive); for ( ; n >= 0; n--) graphic_context[n]=DestroyDrawInfo(graphic_context[n]); graphic_context=(DrawInfo **) RelinquishMagickMemory(graphic_context); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } graphic_context[n]=CloneDrawInfo((ImageInfo *) NULL,draw_info); graphic_context[n]->viewbox=image->page; if ((image->page.width == 0) || (image->page.height == 0)) { graphic_context[n]->viewbox.width=image->columns; graphic_context[n]->viewbox.height=image->rows; } token=AcquireString(primitive); extent=strlen(token)+MagickPathExtent; if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); status=MagickTrue; for (q=primitive; *q != '\0'; ) { /* Interpret graphic primitive. */ GetNextToken(q,&q,extent,keyword); if (*keyword == '\0') break; if (*keyword == '#') { /* Comment. */ while ((*q != '\n') && (*q != '\0')) q++; continue; } p=q-strlen(keyword)-1; primitive_type=UndefinedPrimitive; current=graphic_context[n]->affine; GetAffineMatrix(&affine); switch (*keyword) { case ';': break; case 'a': case 'A': { if (LocaleCompare("affine",keyword) == 0) { GetNextToken(q,&q,extent,token); affine.sx=StringToDouble(token,(char **) NULL); GetNextToken(q,&q,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); affine.rx=StringToDouble(token,(char **) NULL); GetNextToken(q,&q,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); affine.ry=StringToDouble(token,(char **) NULL); GetNextToken(q,&q,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); affine.sy=StringToDouble(token,(char **) NULL); GetNextToken(q,&q,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); affine.tx=StringToDouble(token,(char **) NULL); GetNextToken(q,&q,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); affine.ty=StringToDouble(token,(char **) NULL); break; } if (LocaleCompare("alpha",keyword) == 0) { primitive_type=AlphaPrimitive; break; } if (LocaleCompare("arc",keyword) == 0) { primitive_type=ArcPrimitive; break; } status=MagickFalse; break; } case 'b': case 'B': { if (LocaleCompare("bezier",keyword) == 0) { primitive_type=BezierPrimitive; break; } if (LocaleCompare("border-color",keyword) == 0) { GetNextToken(q,&q,extent,token); (void) QueryColorCompliance(token,AllCompliance, &graphic_context[n]->border_color,exception); break; } status=MagickFalse; break; } case 'c': case 'C': { if (LocaleCompare("clip-path",keyword) == 0) { /* Create clip mask. */ GetNextToken(q,&q,extent,token); (void) CloneString(&graphic_context[n]->clip_mask,token); (void) DrawClipPath(image,graphic_context[n], graphic_context[n]->clip_mask,exception); break; } if (LocaleCompare("clip-rule",keyword) == 0) { ssize_t fill_rule; GetNextToken(q,&q,extent,token); fill_rule=ParseCommandOption(MagickFillRuleOptions,MagickFalse, token); if (fill_rule == -1) status=MagickFalse; else graphic_context[n]->fill_rule=(FillRule) fill_rule; break; } if (LocaleCompare("clip-units",keyword) == 0) { ssize_t clip_units; GetNextToken(q,&q,extent,token); clip_units=ParseCommandOption(MagickClipPathOptions,MagickFalse, token); if (clip_units == -1) { status=MagickFalse; break; } graphic_context[n]->clip_units=(ClipPathUnits) clip_units; if (clip_units == ObjectBoundingBox) { GetAffineMatrix(&current); affine.sx=draw_info->bounds.x2; affine.sy=draw_info->bounds.y2; affine.tx=draw_info->bounds.x1; affine.ty=draw_info->bounds.y1; break; } break; } if (LocaleCompare("circle",keyword) == 0) { primitive_type=CirclePrimitive; break; } if (LocaleCompare("color",keyword) == 0) { primitive_type=ColorPrimitive; break; } status=MagickFalse; break; } case 'd': case 'D': { if (LocaleCompare("decorate",keyword) == 0) { ssize_t decorate; GetNextToken(q,&q,extent,token); decorate=ParseCommandOption(MagickDecorateOptions,MagickFalse, token); if (decorate == -1) status=MagickFalse; else graphic_context[n]->decorate=(DecorationType) decorate; break; } if (LocaleCompare("density",keyword) == 0) { GetNextToken(q,&q,extent,token); (void) CloneString(&graphic_context[n]->density,token); break; } if (LocaleCompare("direction",keyword) == 0) { ssize_t direction; GetNextToken(q,&q,extent,token); direction=ParseCommandOption(MagickDirectionOptions,MagickFalse, token); if (direction == -1) status=MagickFalse; else graphic_context[n]->direction=(DirectionType) direction; break; } status=MagickFalse; break; } case 'e': case 'E': { if (LocaleCompare("ellipse",keyword) == 0) { primitive_type=EllipsePrimitive; break; } if (LocaleCompare("encoding",keyword) == 0) { GetNextToken(q,&q,extent,token); (void) CloneString(&graphic_context[n]->encoding,token); break; } status=MagickFalse; break; } case 'f': case 'F': { if (LocaleCompare("fill",keyword) == 0) { GetNextToken(q,&q,extent,token); (void) FormatLocaleString(pattern,MagickPathExtent,"%s",token); if (GetImageArtifact(image,pattern) != (const char *) NULL) (void) DrawPatternPath(image,draw_info,token, &graphic_context[n]->fill_pattern,exception); else { status&=QueryColorCompliance(token,AllCompliance, &graphic_context[n]->fill,exception); if (status == MagickFalse) { ImageInfo *pattern_info; pattern_info=AcquireImageInfo(); (void) CopyMagickString(pattern_info->filename,token, MagickPathExtent); graphic_context[n]->fill_pattern=ReadImage(pattern_info, exception); CatchException(exception); pattern_info=DestroyImageInfo(pattern_info); } } break; } if (LocaleCompare("fill-opacity",keyword) == 0) { GetNextToken(q,&q,extent,token); factor=strchr(token,'%') != (char *) NULL ? 0.01 : 1.0; graphic_context[n]->fill.alpha=(double) QuantumRange* factor*StringToDouble(token,(char **) NULL); break; } if (LocaleCompare("fill-rule",keyword) == 0) { ssize_t fill_rule; GetNextToken(q,&q,extent,token); fill_rule=ParseCommandOption(MagickFillRuleOptions,MagickFalse, token); if (fill_rule == -1) status=MagickFalse; else graphic_context[n]->fill_rule=(FillRule) fill_rule; break; } if (LocaleCompare("font",keyword) == 0) { GetNextToken(q,&q,extent,token); (void) CloneString(&graphic_context[n]->font,token); if (LocaleCompare("none",token) == 0) graphic_context[n]->font=(char *) RelinquishMagickMemory(graphic_context[n]->font); break; } if (LocaleCompare("font-family",keyword) == 0) { GetNextToken(q,&q,extent,token); (void) CloneString(&graphic_context[n]->family,token); break; } if (LocaleCompare("font-size",keyword) == 0) { GetNextToken(q,&q,extent,token); graphic_context[n]->pointsize=StringToDouble(token,(char **) NULL); break; } if (LocaleCompare("font-stretch",keyword) == 0) { ssize_t stretch; GetNextToken(q,&q,extent,token); stretch=ParseCommandOption(MagickStretchOptions,MagickFalse,token); if (stretch == -1) status=MagickFalse; else graphic_context[n]->stretch=(StretchType) stretch; break; } if (LocaleCompare("font-style",keyword) == 0) { ssize_t style; GetNextToken(q,&q,extent,token); style=ParseCommandOption(MagickStyleOptions,MagickFalse,token); if (style == -1) status=MagickFalse; else graphic_context[n]->style=(StyleType) style; break; } if (LocaleCompare("font-weight",keyword) == 0) { ssize_t weight; GetNextToken(q,&q,extent,token); weight=ParseCommandOption(MagickWeightOptions,MagickFalse,token); if (weight == -1) weight=StringToUnsignedLong(token); graphic_context[n]->weight=(size_t) weight; break; } status=MagickFalse; break; } case 'g': case 'G': { if (LocaleCompare("gradient-units",keyword) == 0) { GetNextToken(q,&q,extent,token); break; } if (LocaleCompare("gravity",keyword) == 0) { ssize_t gravity; GetNextToken(q,&q,extent,token); gravity=ParseCommandOption(MagickGravityOptions,MagickFalse,token); if (gravity == -1) status=MagickFalse; else graphic_context[n]->gravity=(GravityType) gravity; break; } status=MagickFalse; break; } case 'i': case 'I': { if (LocaleCompare("image",keyword) == 0) { ssize_t compose; primitive_type=ImagePrimitive; GetNextToken(q,&q,extent,token); compose=ParseCommandOption(MagickComposeOptions,MagickFalse,token); if (compose == -1) status=MagickFalse; else graphic_context[n]->compose=(CompositeOperator) compose; break; } if (LocaleCompare("interline-spacing",keyword) == 0) { GetNextToken(q,&q,extent,token); graphic_context[n]->interline_spacing=StringToDouble(token, (char **) NULL); break; } if (LocaleCompare("interword-spacing",keyword) == 0) { GetNextToken(q,&q,extent,token); graphic_context[n]->interword_spacing=StringToDouble(token, (char **) NULL); break; } status=MagickFalse; break; } case 'k': case 'K': { if (LocaleCompare("kerning",keyword) == 0) { GetNextToken(q,&q,extent,token); graphic_context[n]->kerning=StringToDouble(token,(char **) NULL); break; } status=MagickFalse; break; } case 'l': case 'L': { if (LocaleCompare("line",keyword) == 0) primitive_type=LinePrimitive; else status=MagickFalse; break; } case 'o': case 'O': { if (LocaleCompare("offset",keyword) == 0) { GetNextToken(q,&q,extent,token); break; } if (LocaleCompare("opacity",keyword) == 0) { GetNextToken(q,&q,extent,token); factor=strchr(token,'%') != (char *) NULL ? 0.01 : 1.0; graphic_context[n]->alpha=ClampToQuantum(QuantumRange*(1.0-((1.0- QuantumScale*graphic_context[n]->alpha)*factor* StringToDouble(token,(char **) NULL)))); graphic_context[n]->fill.alpha=(double) graphic_context[n]->alpha; graphic_context[n]->stroke.alpha=(double) graphic_context[n]->alpha; break; } status=MagickFalse; break; } case 'p': case 'P': { if (LocaleCompare("path",keyword) == 0) { primitive_type=PathPrimitive; break; } if (LocaleCompare("point",keyword) == 0) { primitive_type=PointPrimitive; break; } if (LocaleCompare("polyline",keyword) == 0) { primitive_type=PolylinePrimitive; break; } if (LocaleCompare("polygon",keyword) == 0) { primitive_type=PolygonPrimitive; break; } if (LocaleCompare("pop",keyword) == 0) { GetNextToken(q,&q,extent,token); if (LocaleCompare("clip-path",token) == 0) break; if (LocaleCompare("defs",token) == 0) break; if (LocaleCompare("gradient",token) == 0) break; if (LocaleCompare("graphic-context",token) == 0) { if (n <= 0) { (void) ThrowMagickException(exception,GetMagickModule(), DrawError,"UnbalancedGraphicContextPushPop","`%s'",token); n=0; break; } if (graphic_context[n]->clip_mask != (char *) NULL) if (LocaleCompare(graphic_context[n]->clip_mask, graphic_context[n-1]->clip_mask) != 0) (void) SetImageMask(image,ReadPixelMask,(Image *) NULL, exception); graphic_context[n]=DestroyDrawInfo(graphic_context[n]); n--; break; } if (LocaleCompare("pattern",token) == 0) break; status=MagickFalse; break; } if (LocaleCompare("push",keyword) == 0) { GetNextToken(q,&q,extent,token); if (LocaleCompare("clip-path",token) == 0) { char name[MagickPathExtent]; GetNextToken(q,&q,extent,token); (void) FormatLocaleString(name,MagickPathExtent,"%s",token); for (p=q; *q != '\0'; ) { GetNextToken(q,&q,extent,token); if (LocaleCompare(token,"pop") != 0) continue; GetNextToken(q,(const char **) NULL,extent,token); if (LocaleCompare(token,"clip-path") != 0) continue; break; } (void) CopyMagickString(token,p,(size_t) (q-p-4+1)); (void) SetImageArtifact(image,name,token); GetNextToken(q,&q,extent,token); break; } if (LocaleCompare("gradient",token) == 0) { char key[2*MagickPathExtent], name[MagickPathExtent], type[MagickPathExtent]; SegmentInfo segment; GetNextToken(q,&q,extent,token); (void) CopyMagickString(name,token,MagickPathExtent); GetNextToken(q,&q,extent,token); (void) CopyMagickString(type,token,MagickPathExtent); GetNextToken(q,&q,extent,token); segment.x1=StringToDouble(token,(char **) NULL); GetNextToken(q,&q,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); segment.y1=StringToDouble(token,(char **) NULL); GetNextToken(q,&q,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); segment.x2=StringToDouble(token,(char **) NULL); GetNextToken(q,&q,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); segment.y2=StringToDouble(token,(char **) NULL); if (LocaleCompare(type,"radial") == 0) { GetNextToken(q,&q,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); } for (p=q; *q != '\0'; ) { GetNextToken(q,&q,extent,token); if (LocaleCompare(token,"pop") != 0) continue; GetNextToken(q,(const char **) NULL,extent,token); if (LocaleCompare(token,"gradient") != 0) continue; break; } (void) CopyMagickString(token,p,(size_t) (q-p-4+1)); bounds.x1=graphic_context[n]->affine.sx*segment.x1+ graphic_context[n]->affine.ry*segment.y1+ graphic_context[n]->affine.tx; bounds.y1=graphic_context[n]->affine.rx*segment.x1+ graphic_context[n]->affine.sy*segment.y1+ graphic_context[n]->affine.ty; bounds.x2=graphic_context[n]->affine.sx*segment.x2+ graphic_context[n]->affine.ry*segment.y2+ graphic_context[n]->affine.tx; bounds.y2=graphic_context[n]->affine.rx*segment.x2+ graphic_context[n]->affine.sy*segment.y2+ graphic_context[n]->affine.ty; (void) FormatLocaleString(key,MagickPathExtent,"%s",name); (void) SetImageArtifact(image,key,token); (void) FormatLocaleString(key,MagickPathExtent,"%s-type",name); (void) SetImageArtifact(image,key,type); (void) FormatLocaleString(key,MagickPathExtent,"%s-geometry",name); (void) FormatLocaleString(geometry,MagickPathExtent, "%gx%g%+.15g%+.15g", MagickMax(fabs(bounds.x2-bounds.x1+1.0),1.0), MagickMax(fabs(bounds.y2-bounds.y1+1.0),1.0), bounds.x1,bounds.y1); (void) SetImageArtifact(image,key,geometry); GetNextToken(q,&q,extent,token); break; } if (LocaleCompare("pattern",token) == 0) { char key[2*MagickPathExtent], name[MagickPathExtent]; RectangleInfo pattern_bounds; GetNextToken(q,&q,extent,token); (void) CopyMagickString(name,token,MagickPathExtent); GetNextToken(q,&q,extent,token); pattern_bounds.x=(ssize_t) ceil(StringToDouble(token, (char **) NULL)-0.5); GetNextToken(q,&q,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); pattern_bounds.y=(ssize_t) ceil(StringToDouble(token, (char **) NULL)-0.5); GetNextToken(q,&q,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); pattern_bounds.width=(size_t) floor(StringToDouble(token, (char **) NULL)+0.5); GetNextToken(q,&q,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); pattern_bounds.height=(size_t) floor(StringToDouble(token, (char **) NULL)+0.5); for (p=q; *q != '\0'; ) { GetNextToken(q,&q,extent,token); if (LocaleCompare(token,"pop") != 0) continue; GetNextToken(q,(const char **) NULL,extent,token); if (LocaleCompare(token,"pattern") != 0) continue; break; } (void) CopyMagickString(token,p,(size_t) (q-p-4+1)); (void) FormatLocaleString(key,MagickPathExtent,"%s",name); (void) SetImageArtifact(image,key,token); (void) FormatLocaleString(key,MagickPathExtent,"%s-geometry", name); (void) FormatLocaleString(geometry,MagickPathExtent, "%.20gx%.20g%+.20g%+.20g",(double)pattern_bounds.width, (double)pattern_bounds.height,(double)pattern_bounds.x, (double)pattern_bounds.y); (void) SetImageArtifact(image,key,geometry); GetNextToken(q,&q,extent,token); break; } if (LocaleCompare("graphic-context",token) == 0) { n++; graphic_context=(DrawInfo **) ResizeQuantumMemory( graphic_context,(size_t) (n+1),sizeof(*graphic_context)); if (graphic_context == (DrawInfo **) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'", image->filename); break; } graphic_context[n]=CloneDrawInfo((ImageInfo *) NULL, graphic_context[n-1]); break; } if (LocaleCompare("defs",token) == 0) break; status=MagickFalse; break; } status=MagickFalse; break; } case 'r': case 'R': { if (LocaleCompare("rectangle",keyword) == 0) { primitive_type=RectanglePrimitive; break; } if (LocaleCompare("rotate",keyword) == 0) { GetNextToken(q,&q,extent,token); angle=StringToDouble(token,(char **) NULL); affine.sx=cos(DegreesToRadians(fmod((double) angle,360.0))); affine.rx=sin(DegreesToRadians(fmod((double) angle,360.0))); affine.ry=(-sin(DegreesToRadians(fmod((double) angle,360.0)))); affine.sy=cos(DegreesToRadians(fmod((double) angle,360.0))); break; } if (LocaleCompare("roundRectangle",keyword) == 0) { primitive_type=RoundRectanglePrimitive; break; } status=MagickFalse; break; } case 's': case 'S': { if (LocaleCompare("scale",keyword) == 0) { GetNextToken(q,&q,extent,token); affine.sx=StringToDouble(token,(char **) NULL); GetNextToken(q,&q,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); affine.sy=StringToDouble(token,(char **) NULL); break; } if (LocaleCompare("skewX",keyword) == 0) { GetNextToken(q,&q,extent,token); angle=StringToDouble(token,(char **) NULL); affine.ry=sin(DegreesToRadians(angle)); break; } if (LocaleCompare("skewY",keyword) == 0) { GetNextToken(q,&q,extent,token); angle=StringToDouble(token,(char **) NULL); affine.rx=(-tan(DegreesToRadians(angle)/2.0)); break; } if (LocaleCompare("stop-color",keyword) == 0) { PixelInfo stop_color; number_stops++; if (number_stops == 1) stops=(StopInfo *) AcquireQuantumMemory(2,sizeof(*stops)); else if (number_stops > 2) stops=(StopInfo *) ResizeQuantumMemory(stops,number_stops, sizeof(*stops)); if (stops == (StopInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'", image->filename); break; } GetNextToken(q,&q,extent,token); (void) QueryColorCompliance(token,AllCompliance,&stop_color, exception); stops[number_stops-1].color=stop_color; GetNextToken(q,&q,extent,token); stops[number_stops-1].offset=StringToDouble(token,(char **) NULL); break; } if (LocaleCompare("stroke",keyword) == 0) { GetNextToken(q,&q,extent,token); (void) FormatLocaleString(pattern,MagickPathExtent,"%s",token); if (GetImageArtifact(image,pattern) != (const char *) NULL) (void) DrawPatternPath(image,draw_info,token, &graphic_context[n]->stroke_pattern,exception); else { status&=QueryColorCompliance(token,AllCompliance, &graphic_context[n]->stroke,exception); if (status == MagickFalse) { ImageInfo *pattern_info; pattern_info=AcquireImageInfo(); (void) CopyMagickString(pattern_info->filename,token, MagickPathExtent); graphic_context[n]->stroke_pattern=ReadImage(pattern_info, exception); CatchException(exception); pattern_info=DestroyImageInfo(pattern_info); } } break; } if (LocaleCompare("stroke-antialias",keyword) == 0) { GetNextToken(q,&q,extent,token); graphic_context[n]->stroke_antialias= StringToLong(token) != 0 ? MagickTrue : MagickFalse; break; } if (LocaleCompare("stroke-dasharray",keyword) == 0) { if (graphic_context[n]->dash_pattern != (double *) NULL) graphic_context[n]->dash_pattern=(double *) RelinquishMagickMemory(graphic_context[n]->dash_pattern); if (IsPoint(q) != MagickFalse) { const char *r; r=q; GetNextToken(r,&r,extent,token); if (*token == ',') GetNextToken(r,&r,extent,token); for (x=0; IsPoint(token) != MagickFalse; x++) { GetNextToken(r,&r,extent,token); if (*token == ',') GetNextToken(r,&r,extent,token); } graphic_context[n]->dash_pattern=(double *) AcquireQuantumMemory((size_t) (2UL*x+1UL), sizeof(*graphic_context[n]->dash_pattern)); if (graphic_context[n]->dash_pattern == (double *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'", image->filename); break; } for (j=0; j < x; j++) { GetNextToken(q,&q,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); graphic_context[n]->dash_pattern[j]=StringToDouble(token, (char **) NULL); if (graphic_context[n]->dash_pattern[j] < 0.0) status=MagickFalse; } if ((x & 0x01) != 0) for ( ; j < (2*x); j++) graphic_context[n]->dash_pattern[j]= graphic_context[n]->dash_pattern[j-x]; graphic_context[n]->dash_pattern[j]=0.0; break; } GetNextToken(q,&q,extent,token); break; } if (LocaleCompare("stroke-dashoffset",keyword) == 0) { GetNextToken(q,&q,extent,token); graphic_context[n]->dash_offset=StringToDouble(token, (char **) NULL); break; } if (LocaleCompare("stroke-linecap",keyword) == 0) { ssize_t linecap; GetNextToken(q,&q,extent,token); linecap=ParseCommandOption(MagickLineCapOptions,MagickFalse,token); if (linecap == -1) status=MagickFalse; else graphic_context[n]->linecap=(LineCap) linecap; break; } if (LocaleCompare("stroke-linejoin",keyword) == 0) { ssize_t linejoin; GetNextToken(q,&q,extent,token); linejoin=ParseCommandOption(MagickLineJoinOptions,MagickFalse, token); if (linejoin == -1) status=MagickFalse; else graphic_context[n]->linejoin=(LineJoin) linejoin; break; } if (LocaleCompare("stroke-miterlimit",keyword) == 0) { GetNextToken(q,&q,extent,token); graphic_context[n]->miterlimit=StringToUnsignedLong(token); break; } if (LocaleCompare("stroke-opacity",keyword) == 0) { GetNextToken(q,&q,extent,token); factor=strchr(token,'%') != (char *) NULL ? 0.01 : 1.0; graphic_context[n]->stroke.alpha=(double) QuantumRange* factor*StringToDouble(token,(char **) NULL); break; } if (LocaleCompare("stroke-width",keyword) == 0) { GetNextToken(q,&q,extent,token); graphic_context[n]->stroke_width=StringToDouble(token, (char **) NULL); break; } status=MagickFalse; break; } case 't': case 'T': { if (LocaleCompare("text",keyword) == 0) { primitive_type=TextPrimitive; break; } if (LocaleCompare("text-align",keyword) == 0) { ssize_t align; GetNextToken(q,&q,extent,token); align=ParseCommandOption(MagickAlignOptions,MagickFalse,token); if (align == -1) status=MagickFalse; else graphic_context[n]->align=(AlignType) align; break; } if (LocaleCompare("text-anchor",keyword) == 0) { ssize_t align; GetNextToken(q,&q,extent,token); align=ParseCommandOption(MagickAlignOptions,MagickFalse,token); if (align == -1) status=MagickFalse; else graphic_context[n]->align=(AlignType) align; break; } if (LocaleCompare("text-antialias",keyword) == 0) { GetNextToken(q,&q,extent,token); graphic_context[n]->text_antialias= StringToLong(token) != 0 ? MagickTrue : MagickFalse; break; } if (LocaleCompare("text-undercolor",keyword) == 0) { GetNextToken(q,&q,extent,token); (void) QueryColorCompliance(token,AllCompliance, &graphic_context[n]->undercolor,exception); break; } if (LocaleCompare("translate",keyword) == 0) { GetNextToken(q,&q,extent,token); affine.tx=StringToDouble(token,(char **) NULL); GetNextToken(q,&q,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); affine.ty=StringToDouble(token,(char **) NULL); break; } status=MagickFalse; break; } case 'v': case 'V': { if (LocaleCompare("viewbox",keyword) == 0) { GetNextToken(q,&q,extent,token); graphic_context[n]->viewbox.x=(ssize_t) ceil(StringToDouble(token, (char **) NULL)-0.5); GetNextToken(q,&q,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); graphic_context[n]->viewbox.y=(ssize_t) ceil(StringToDouble(token, (char **) NULL)-0.5); GetNextToken(q,&q,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); graphic_context[n]->viewbox.width=(size_t) floor(StringToDouble( token,(char **) NULL)+0.5); GetNextToken(q,&q,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); graphic_context[n]->viewbox.height=(size_t) floor(StringToDouble( token,(char **) NULL)+0.5); break; } status=MagickFalse; break; } default: { status=MagickFalse; break; } } if (status == MagickFalse) break; if ((affine.sx != 1.0) || (affine.rx != 0.0) || (affine.ry != 0.0) || (affine.sy != 1.0) || (affine.tx != 0.0) || (affine.ty != 0.0)) { graphic_context[n]->affine.sx=current.sx*affine.sx+current.ry*affine.rx; graphic_context[n]->affine.rx=current.rx*affine.sx+current.sy*affine.rx; graphic_context[n]->affine.ry=current.sx*affine.ry+current.ry*affine.sy; graphic_context[n]->affine.sy=current.rx*affine.ry+current.sy*affine.sy; graphic_context[n]->affine.tx=current.sx*affine.tx+current.ry*affine.ty+ current.tx; graphic_context[n]->affine.ty=current.rx*affine.tx+current.sy*affine.ty+ current.ty; } if (primitive_type == UndefinedPrimitive) { if (*q == '\0') { if (number_stops > 1) { GradientType type; type=LinearGradient; if (draw_info->gradient.type == RadialGradient) type=RadialGradient; (void) GradientImage(image,type,PadSpread,stops,number_stops, exception); } if (number_stops > 0) stops=(StopInfo *) RelinquishMagickMemory(stops); } if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule()," %.*s", (int) (q-p),p); continue; } /* Parse the primitive attributes. */ i=0; j=0; primitive_info[0].point.x=0.0; primitive_info[0].point.y=0.0; for (x=0; *q != '\0'; x++) { /* Define points. */ if (IsPoint(q) == MagickFalse) break; GetNextToken(q,&q,extent,token); point.x=StringToDouble(token,(char **) NULL); GetNextToken(q,&q,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); point.y=StringToDouble(token,(char **) NULL); GetNextToken(q,(const char **) NULL,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); primitive_info[i].primitive=primitive_type; primitive_info[i].point=point; primitive_info[i].coordinates=0; primitive_info[i].method=FloodfillMethod; i++; if (i < (ssize_t) number_points) continue; number_points<<=1; primitive_info=(PrimitiveInfo *) ResizeQuantumMemory(primitive_info, (size_t) number_points,sizeof(*primitive_info)); if (primitive_info == (PrimitiveInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); break; } } primitive_info[j].primitive=primitive_type; primitive_info[j].coordinates=(size_t) x; primitive_info[j].method=FloodfillMethod; primitive_info[j].text=(char *) NULL; /* Circumscribe primitive within a circle. */ bounds.x1=primitive_info[j].point.x; bounds.y1=primitive_info[j].point.y; bounds.x2=primitive_info[j].point.x; bounds.y2=primitive_info[j].point.y; for (k=1; k < (ssize_t) primitive_info[j].coordinates; k++) { point=primitive_info[j+k].point; if (point.x < bounds.x1) bounds.x1=point.x; if (point.y < bounds.y1) bounds.y1=point.y; if (point.x > bounds.x2) bounds.x2=point.x; if (point.y > bounds.y2) bounds.y2=point.y; } /* Speculate how many points our primitive might consume. */ length=primitive_info[j].coordinates; switch (primitive_type) { case RectanglePrimitive: { length*=5; break; } case RoundRectanglePrimitive: { double alpha, beta, radius; alpha=bounds.x2-bounds.x1; beta=bounds.y2-bounds.y1; radius=hypot((double) alpha,(double) beta); length*=5; length+=2*((size_t) ceil((double) MagickPI*radius))+6*BezierQuantum+360; break; } case BezierPrimitive: { if (primitive_info[j].coordinates > 107) (void) ThrowMagickException(exception,GetMagickModule(),DrawError, "TooManyBezierCoordinates","`%s'",token); length=BezierQuantum*primitive_info[j].coordinates; break; } case PathPrimitive: { char *s, *t; GetNextToken(q,&q,extent,token); length=1; t=token; for (s=token; *s != '\0'; s=t) { double value; value=StringToDouble(s,&t); (void) value; if (s == t) { t++; continue; } length++; } length=length*BezierQuantum/2; break; } case CirclePrimitive: case ArcPrimitive: case EllipsePrimitive: { double alpha, beta, radius; alpha=bounds.x2-bounds.x1; beta=bounds.y2-bounds.y1; radius=hypot((double) alpha,(double) beta); length=2*((size_t) ceil((double) MagickPI*radius))+6*BezierQuantum+360; break; } default: break; } if ((size_t) (i+length) >= number_points) { /* Resize based on speculative points required by primitive. */ number_points+=length+1; primitive_info=(PrimitiveInfo *) ResizeQuantumMemory(primitive_info, (size_t) number_points,sizeof(*primitive_info)); if (primitive_info == (PrimitiveInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'", image->filename); break; } } switch (primitive_type) { case PointPrimitive: default: { if (primitive_info[j].coordinates != 1) { status=MagickFalse; break; } TracePoint(primitive_info+j,primitive_info[j].point); i=(ssize_t) (j+primitive_info[j].coordinates); break; } case LinePrimitive: { if (primitive_info[j].coordinates != 2) { status=MagickFalse; break; } TraceLine(primitive_info+j,primitive_info[j].point, primitive_info[j+1].point); i=(ssize_t) (j+primitive_info[j].coordinates); break; } case RectanglePrimitive: { if (primitive_info[j].coordinates != 2) { status=MagickFalse; break; } TraceRectangle(primitive_info+j,primitive_info[j].point, primitive_info[j+1].point); i=(ssize_t) (j+primitive_info[j].coordinates); break; } case RoundRectanglePrimitive: { if (primitive_info[j].coordinates != 3) { status=MagickFalse; break; } TraceRoundRectangle(primitive_info+j,primitive_info[j].point, primitive_info[j+1].point,primitive_info[j+2].point); i=(ssize_t) (j+primitive_info[j].coordinates); break; } case ArcPrimitive: { if (primitive_info[j].coordinates != 3) { primitive_type=UndefinedPrimitive; break; } TraceArc(primitive_info+j,primitive_info[j].point, primitive_info[j+1].point,primitive_info[j+2].point); i=(ssize_t) (j+primitive_info[j].coordinates); break; } case EllipsePrimitive: { if (primitive_info[j].coordinates != 3) { status=MagickFalse; break; } TraceEllipse(primitive_info+j,primitive_info[j].point, primitive_info[j+1].point,primitive_info[j+2].point); i=(ssize_t) (j+primitive_info[j].coordinates); break; } case CirclePrimitive: { if (primitive_info[j].coordinates != 2) { status=MagickFalse; break; } TraceCircle(primitive_info+j,primitive_info[j].point, primitive_info[j+1].point); i=(ssize_t) (j+primitive_info[j].coordinates); break; } case PolylinePrimitive: break; case PolygonPrimitive: { primitive_info[i]=primitive_info[j]; primitive_info[i].coordinates=0; primitive_info[j].coordinates++; i++; break; } case BezierPrimitive: { if (primitive_info[j].coordinates < 3) { status=MagickFalse; break; } TraceBezier(primitive_info+j,primitive_info[j].coordinates); i=(ssize_t) (j+primitive_info[j].coordinates); break; } case PathPrimitive: { i=(ssize_t) (j+TracePath(primitive_info+j,token)); break; } case AlphaPrimitive: case ColorPrimitive: { ssize_t method; if (primitive_info[j].coordinates != 1) { status=MagickFalse; break; } GetNextToken(q,&q,extent,token); method=ParseCommandOption(MagickMethodOptions,MagickFalse,token); if (method == -1) status=MagickFalse; else primitive_info[j].method=(PaintMethod) method; break; } case TextPrimitive: { if (primitive_info[j].coordinates != 1) { status=MagickFalse; break; } if (*token != ',') GetNextToken(q,&q,extent,token); primitive_info[j].text=AcquireString(token); break; } case ImagePrimitive: { if (primitive_info[j].coordinates != 2) { status=MagickFalse; break; } GetNextToken(q,&q,extent,token); primitive_info[j].text=AcquireString(token); break; } } if (primitive_info == (PrimitiveInfo *) NULL) break; if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule()," %.*s",(int) (q-p),p); if (status == MagickFalse) break; primitive_info[i].primitive=UndefinedPrimitive; if (i == 0) continue; /* Transform points. */ for (i=0; primitive_info[i].primitive != UndefinedPrimitive; i++) { point=primitive_info[i].point; primitive_info[i].point.x=graphic_context[n]->affine.sx*point.x+ graphic_context[n]->affine.ry*point.y+graphic_context[n]->affine.tx; primitive_info[i].point.y=graphic_context[n]->affine.rx*point.x+ graphic_context[n]->affine.sy*point.y+graphic_context[n]->affine.ty; point=primitive_info[i].point; if (point.x < graphic_context[n]->bounds.x1) graphic_context[n]->bounds.x1=point.x; if (point.y < graphic_context[n]->bounds.y1) graphic_context[n]->bounds.y1=point.y; if (point.x > graphic_context[n]->bounds.x2) graphic_context[n]->bounds.x2=point.x; if (point.y > graphic_context[n]->bounds.y2) graphic_context[n]->bounds.y2=point.y; if (primitive_info[i].primitive == ImagePrimitive) break; if (i >= (ssize_t) number_points) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); } if (graphic_context[n]->render != MagickFalse) { if ((n != 0) && (graphic_context[n]->clip_mask != (char *) NULL) && (LocaleCompare(graphic_context[n]->clip_mask, graphic_context[n-1]->clip_mask) != 0)) status&=DrawClipPath(image,graphic_context[n], graphic_context[n]->clip_mask,exception); status&=DrawPrimitive(image,graphic_context[n],primitive_info, exception); } if (primitive_info->text != (char *) NULL) primitive_info->text=(char *) RelinquishMagickMemory( primitive_info->text); proceed=SetImageProgress(image,RenderImageTag,q-primitive,(MagickSizeType) primitive_extent); if (proceed == MagickFalse) break; if (status == 0) break; } if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule(),"end draw-image"); /* Relinquish resources. */ token=DestroyString(token); if (primitive_info != (PrimitiveInfo *) NULL) primitive_info=(PrimitiveInfo *) RelinquishMagickMemory(primitive_info); primitive=DestroyString(primitive); for ( ; n >= 0; n--) graphic_context[n]=DestroyDrawInfo(graphic_context[n]); graphic_context=(DrawInfo **) RelinquishMagickMemory(graphic_context); if (status == MagickFalse) ThrowBinaryException(DrawError,"NonconformingDrawingPrimitiveDefinition", keyword); return(status != 0 ? MagickTrue : MagickFalse); } Commit Message: Prevent buffer overflow in magick/draw.c CWE ID: CWE-119 Target: 1 Example 2: Code: coolkey_process_combined_object(sc_card_t *card, coolkey_private_data_t *priv, u8 *object, size_t object_length) { coolkey_combined_header_t *header = (coolkey_combined_header_t *)object; unsigned short compressed_offset; unsigned short compressed_length; unsigned short compressed_type; unsigned short object_offset; unsigned short object_count; coolkey_decompressed_header_t *decompressed_header; u8 *decompressed_object = NULL; size_t decompressed_object_len = 0; int free_decompressed = 0; int i, r; if (object_length < sizeof(coolkey_combined_header_t)) { return SC_ERROR_CORRUPTED_DATA; } compressed_offset = bebytes2ushort(header->compression_offset); compressed_length = bebytes2ushort(header->compression_length); compressed_type = bebytes2ushort(header->compression_type); if ((((size_t)compressed_offset) + (size_t)compressed_length) > object_length) { return SC_ERROR_CORRUPTED_DATA; } /* store the CUID */ memcpy(&priv->cuid, &header->cuid, sizeof(priv->cuid)); if (compressed_type == COOLKEY_COMPRESSION_ZLIB) { #ifdef ENABLE_ZLIB r = sc_decompress_alloc(&decompressed_object, &decompressed_object_len, &object[compressed_offset], compressed_length, COMPRESSION_AUTO); if (r) goto done; free_decompressed = 1; #else sc_log(card->ctx, "Coolkey compression not supported, no zlib"); LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED); #endif } else { decompressed_object =&object[compressed_offset]; decompressed_object_len = (size_t) compressed_length; } decompressed_header = (coolkey_decompressed_header_t *)decompressed_object; if (decompressed_object_len < sizeof(coolkey_decompressed_header_t)) { return SC_ERROR_CORRUPTED_DATA; } object_offset = bebytes2ushort(decompressed_header->object_offset); object_count = bebytes2ushort(decompressed_header->object_count); /* * using 2 different tests here so we can log different errors if logging is * turned on. */ /* make sure token_name doesn't overrun the buffer */ if (decompressed_header->token_name_length + offsetof(coolkey_decompressed_header_t,token_name) > decompressed_object_len) { r = SC_ERROR_CORRUPTED_DATA; goto done; } /* make sure it doesn't overlap the object space */ if (decompressed_header->token_name_length + offsetof(coolkey_decompressed_header_t,token_name) > object_offset) { r = SC_ERROR_CORRUPTED_DATA; goto done; } /* store the token name in the priv structure so the emulator can set it */ priv->token_name = malloc(decompressed_header->token_name_length+1); if (priv->token_name == NULL) { r = SC_ERROR_OUT_OF_MEMORY; goto done; } memcpy(priv->token_name, &decompressed_header->token_name[0], decompressed_header->token_name_length); priv->token_name[decompressed_header->token_name_length] = 0; priv->token_name_length = decompressed_header->token_name_length; for (i=0; i < object_count && object_offset < decompressed_object_len; i++ ) { u8 *current_object = &decompressed_object[object_offset]; coolkey_combined_object_header_t *object_header = (coolkey_combined_object_header_t *)current_object; unsigned long object_id = bebytes2ulong(object_header->object_id); int current_object_len; /* figure out how big it is */ r = coolkey_v1_get_object_length(current_object, decompressed_object_len-object_offset); if (r < 0) { goto done; } if ((size_t)r + object_offset > decompressed_object_len) { r = SC_ERROR_CORRUPTED_DATA; goto done; } current_object_len = r; object_offset += current_object_len; /* record this object */ r = coolkey_add_object(priv, object_id, current_object, current_object_len, 1); if (r) { goto done; } } r = SC_SUCCESS; done: if (free_decompressed) { free(decompressed_object); } return r; } Commit Message: fixed out of bounds reads Thanks to Eric Sesterhenn from X41 D-SEC GmbH for reporting and suggesting security fixes. CWE ID: CWE-125 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void UpdateDeskContainersBackdrops() { for (auto* root : Shell::GetAllRootWindows()) { for (auto* desk_container : desks_util::GetDesksContainers(root)) { WorkspaceController* controller = GetWorkspaceController(desk_container); WorkspaceLayoutManager* layout_manager = controller->layout_manager(); BackdropController* backdrop_controller = layout_manager->backdrop_controller(); backdrop_controller->UpdateBackdrop(); } } } Commit Message: Fix the crash after clamshell -> tablet transition in overview mode. This CL just reverted some changes that were made in https://chromium-review.googlesource.com/c/chromium/src/+/1658955. In that CL, we changed the clamshell <-> tablet transition when clamshell split view mode is enabled, however, we should keep the old behavior unchanged if the feature is not enabled, i.e., overview should be ended if it's active before the transition. Otherwise, it will cause a nullptr dereference crash since |split_view_drag_indicators_| is not created in clamshell overview and will be used in tablet overview. Bug: 982507 Change-Id: I238fe9472648a446cff4ab992150658c228714dd Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1705474 Commit-Queue: Xiaoqian Dai <[email protected]> Reviewed-by: Mitsuru Oshima (Slow - on/off site) <[email protected]> Cr-Commit-Position: refs/heads/master@{#679306} CWE ID: CWE-362 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int tmx_check_pretran(sip_msg_t *msg) { unsigned int chid; unsigned int slotid; int dsize; struct via_param *vbr; str scallid; str scseqmet; str scseqnum; str sftag; str svbranch = {NULL, 0}; pretran_t *it; if(_tmx_ptran_table==NULL) { LM_ERR("pretran hash table not initialized yet\n"); return -1; } if(get_route_type()!=REQUEST_ROUTE) { LM_ERR("invalid usage - not in request route\n"); return -1; } if(msg->first_line.type!=SIP_REQUEST) { LM_ERR("invalid usage - not a sip request\n"); return -1; } if(parse_headers(msg, HDR_FROM_F|HDR_VIA1_F|HDR_CALLID_F|HDR_CSEQ_F, 0)<0) { LM_ERR("failed to parse required headers\n"); return -1; } if(msg->cseq==NULL || msg->cseq->parsed==NULL) { LM_ERR("failed to parse cseq headers\n"); return -1; } if(get_cseq(msg)->method_id==METHOD_ACK || get_cseq(msg)->method_id==METHOD_CANCEL) { LM_DBG("no pre-transaction management for ACK or CANCEL\n"); return -1; } if (msg->via1==0) { LM_ERR("failed to get Via header\n"); return -1; } if (parse_from_header(msg)<0 || get_from(msg)->tag_value.len==0) { LM_ERR("failed to get From header\n"); return -1; } if (msg->callid==NULL || msg->callid->body.s==NULL) { LM_ERR("failed to parse callid headers\n"); return -1; } vbr = msg->via1->branch; scallid = msg->callid->body; trim(&scallid); scseqmet = get_cseq(msg)->method; trim(&scseqmet); scseqnum = get_cseq(msg)->number; trim(&scseqnum); sftag = get_from(msg)->tag_value; trim(&sftag); chid = get_hash1_raw(msg->callid->body.s, msg->callid->body.len); slotid = chid & (_tmx_ptran_size-1); if(unlikely(_tmx_proc_ptran == NULL)) { _tmx_proc_ptran = (pretran_t*)shm_malloc(sizeof(pretran_t)); if(_tmx_proc_ptran == NULL) { LM_ERR("not enough memory for pretran structure\n"); return -1; } memset(_tmx_proc_ptran, 0, sizeof(pretran_t)); _tmx_proc_ptran->pid = my_pid(); } dsize = scallid.len + scseqnum.len + scseqmet.len + sftag.len + 4; if(likely(vbr!=NULL)) { svbranch = vbr->value; trim(&svbranch); dsize += svbranch.len; } if(dsize<256) dsize = 256; tmx_pretran_unlink(); if(dsize > _tmx_proc_ptran->dbuf.len) { if(_tmx_proc_ptran->dbuf.s) shm_free(_tmx_proc_ptran->dbuf.s); _tmx_proc_ptran->dbuf.s = (char*)shm_malloc(dsize); if(_tmx_proc_ptran->dbuf.s==NULL) { LM_ERR("not enough memory for pretran data\n"); return -1; } _tmx_proc_ptran->dbuf.len = dsize; } _tmx_proc_ptran->hid = chid; _tmx_proc_ptran->cseqmetid = (get_cseq(msg))->method_id; _tmx_proc_ptran->callid.s = _tmx_proc_ptran->dbuf.s; memcpy(_tmx_proc_ptran->callid.s, scallid.s, scallid.len); _tmx_proc_ptran->callid.len = scallid.len; _tmx_proc_ptran->callid.s[_tmx_proc_ptran->callid.len] = '\0'; _tmx_proc_ptran->ftag.s = _tmx_proc_ptran->callid.s + _tmx_proc_ptran->callid.len + 1; memcpy(_tmx_proc_ptran->ftag.s, sftag.s, sftag.len); _tmx_proc_ptran->ftag.len = sftag.len; _tmx_proc_ptran->ftag.s[_tmx_proc_ptran->ftag.len] = '\0'; _tmx_proc_ptran->cseqnum.s = _tmx_proc_ptran->ftag.s + _tmx_proc_ptran->ftag.len + 1; memcpy(_tmx_proc_ptran->cseqnum.s, scseqnum.s, scseqnum.len); _tmx_proc_ptran->cseqnum.len = scseqnum.len; _tmx_proc_ptran->cseqnum.s[_tmx_proc_ptran->cseqnum.len] = '\0'; _tmx_proc_ptran->cseqmet.s = _tmx_proc_ptran->cseqnum.s + _tmx_proc_ptran->cseqnum.len + 1; memcpy(_tmx_proc_ptran->cseqmet.s, scseqmet.s, scseqmet.len); _tmx_proc_ptran->cseqmet.len = scseqmet.len; _tmx_proc_ptran->cseqmet.s[_tmx_proc_ptran->cseqmet.len] = '\0'; if(likely(vbr!=NULL)) { _tmx_proc_ptran->vbranch.s = _tmx_proc_ptran->cseqmet.s + _tmx_proc_ptran->cseqmet.len + 1; memcpy(_tmx_proc_ptran->vbranch.s, svbranch.s, svbranch.len); _tmx_proc_ptran->vbranch.len = svbranch.len; _tmx_proc_ptran->vbranch.s[_tmx_proc_ptran->vbranch.len] = '\0'; } else { _tmx_proc_ptran->vbranch.s = NULL; _tmx_proc_ptran->vbranch.len = 0; } lock_get(&_tmx_ptran_table[slotid].lock); it = _tmx_ptran_table[slotid].plist; tmx_pretran_link_safe(slotid); for(; it!=NULL; it=it->next) { if(_tmx_proc_ptran->hid != it->hid || _tmx_proc_ptran->cseqmetid != it->cseqmetid || _tmx_proc_ptran->callid.len != it->callid.len || _tmx_proc_ptran->ftag.len != it->ftag.len || _tmx_proc_ptran->cseqmet.len != it->cseqmet.len || _tmx_proc_ptran->cseqnum.len != it->cseqnum.len) continue; if(_tmx_proc_ptran->vbranch.s != NULL && it->vbranch.s != NULL) { if(_tmx_proc_ptran->vbranch.len != it->vbranch.len) continue; /* shortcut - check last char in Via branch * - kamailio/ser adds there branch index => in case of paralel * forking by previous hop, catch it here quickly */ if(_tmx_proc_ptran->vbranch.s[it->vbranch.len-1] != it->vbranch.s[it->vbranch.len-1]) continue; if(memcmp(_tmx_proc_ptran->vbranch.s, it->vbranch.s, it->vbranch.len)!=0) continue; /* shall stop by matching magic cookie? * if (vbr && vbr->value.s && vbr->value.len > MCOOKIE_LEN * && memcmp(vbr->value.s, MCOOKIE, MCOOKIE_LEN)==0) { * LM_DBG("rfc3261 cookie found in Via branch\n"); * } */ } if(memcmp(_tmx_proc_ptran->callid.s, it->callid.s, it->callid.len)!=0 || memcmp(_tmx_proc_ptran->ftag.s, it->ftag.s, it->ftag.len)!=0 || memcmp(_tmx_proc_ptran->cseqnum.s, it->cseqnum.s, it->cseqnum.len)!=0) continue; if((it->cseqmetid==METHOD_OTHER || it->cseqmetid==METHOD_UNDEF) && memcmp(_tmx_proc_ptran->cseqmet.s, it->cseqmet.s, it->cseqmet.len)!=0) continue; LM_DBG("matched another pre-transaction by pid %d for [%.*s]\n", it->pid, it->callid.len, it->callid.s); lock_release(&_tmx_ptran_table[slotid].lock); return 1; } lock_release(&_tmx_ptran_table[slotid].lock); return 0; } Commit Message: tmx: allocate space to store ending 0 for branch value - reported by Alfred Farrugia and Sandro Gauci CWE ID: CWE-119 Target: 1 Example 2: Code: bool HasExactMatchSuggestion(const PasswordFormFillData& fill_data, const base::string16& current_username) { if (fill_data.username_field.value == current_username) return true; for (const auto& usernames : fill_data.other_possible_usernames) { for (const auto& username_string : usernames.second) { if (username_string == current_username) return true; } } for (const auto& login : fill_data.additional_logins) { if (login.first == current_username) return true; } return false; } Commit Message: Remove WeakPtrFactory from PasswordAutofillAgent Unlike in AutofillAgent, the factory is no longer used in PAA. [email protected] BUG=609010,609007,608100,608101,433486 Review-Url: https://codereview.chromium.org/1945723003 Cr-Commit-Position: refs/heads/master@{#391475} CWE ID: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: WORD32 ih264d_parse_decode_slice(UWORD8 u1_is_idr_slice, UWORD8 u1_nal_ref_idc, dec_struct_t *ps_dec /* Decoder parameters */ ) { dec_bit_stream_t * ps_bitstrm = ps_dec->ps_bitstrm; dec_pic_params_t *ps_pps; dec_seq_params_t *ps_seq; dec_slice_params_t *ps_cur_slice = ps_dec->ps_cur_slice; pocstruct_t s_tmp_poc; WORD32 i_delta_poc[2]; WORD32 i4_poc = 0; UWORD16 u2_first_mb_in_slice, u2_frame_num; UWORD8 u1_field_pic_flag, u1_redundant_pic_cnt = 0, u1_slice_type; UWORD32 u4_idr_pic_id = 0; UWORD8 u1_bottom_field_flag, u1_pic_order_cnt_type; UWORD8 u1_nal_unit_type; UWORD32 *pu4_bitstrm_buf = ps_bitstrm->pu4_buffer; UWORD32 *pu4_bitstrm_ofst = &ps_bitstrm->u4_ofst; WORD8 i1_is_end_of_poc; WORD32 ret, end_of_frame; WORD32 prev_slice_err, num_mb_skipped; UWORD8 u1_mbaff; pocstruct_t *ps_cur_poc; UWORD32 u4_temp; WORD32 i_temp; UWORD32 u4_call_end_of_pic = 0; /* read FirstMbInSlice and slice type*/ ps_dec->ps_dpb_cmds->u1_dpb_commands_read_slc = 0; u2_first_mb_in_slice = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf); if(u2_first_mb_in_slice > (ps_dec->u2_frm_ht_in_mbs * ps_dec->u2_frm_wd_in_mbs)) { return ERROR_CORRUPTED_SLICE; } /*we currently don not support ASO*/ if(((u2_first_mb_in_slice << ps_cur_slice->u1_mbaff_frame_flag) <= ps_dec->u2_cur_mb_addr) && (ps_dec->u2_cur_mb_addr != 0) && (ps_dec->u4_first_slice_in_pic != 0)) { return ERROR_CORRUPTED_SLICE; } COPYTHECONTEXT("SH: first_mb_in_slice",u2_first_mb_in_slice); u4_temp = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf); if(u4_temp > 9) return ERROR_INV_SLC_TYPE_T; u1_slice_type = u4_temp; COPYTHECONTEXT("SH: slice_type",(u1_slice_type)); ps_dec->u1_sl_typ_5_9 = 0; /* Find Out the Slice Type is 5 to 9 or not then Set the Flag */ /* u1_sl_typ_5_9 = 1 .Which tells that all the slices in the Pic*/ /* will be of same type of current */ if(u1_slice_type > 4) { u1_slice_type -= 5; ps_dec->u1_sl_typ_5_9 = 1; } { UWORD32 skip; if((ps_dec->i4_app_skip_mode == IVD_SKIP_PB) || (ps_dec->i4_dec_skip_mode == IVD_SKIP_PB)) { UWORD32 u4_bit_stream_offset = 0; if(ps_dec->u1_nal_unit_type == IDR_SLICE_NAL) { skip = 0; ps_dec->i4_dec_skip_mode = IVD_SKIP_NONE; } else if((I_SLICE == u1_slice_type) && (1 >= ps_dec->ps_cur_sps->u1_num_ref_frames)) { skip = 0; ps_dec->i4_dec_skip_mode = IVD_SKIP_NONE; } else { skip = 1; } /* If one frame worth of data is already skipped, do not skip the next one */ if((0 == u2_first_mb_in_slice) && (1 == ps_dec->u4_prev_nal_skipped)) { skip = 0; } if(skip) { ps_dec->u4_prev_nal_skipped = 1; ps_dec->i4_dec_skip_mode = IVD_SKIP_PB; return 0; } else { /* If the previous NAL was skipped, then do not process that buffer in this call. Return to app and process it in the next call. This is necessary to handle cases where I/IDR is not complete in the current buffer and application intends to fill the remaining part of the bitstream later. This ensures we process only frame worth of data in every call */ if(1 == ps_dec->u4_prev_nal_skipped) { ps_dec->u4_return_to_app = 1; return 0; } } } } u4_temp = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf); if(u4_temp & MASK_ERR_PIC_SET_ID) return ERROR_INV_SPS_PPS_T; /* discard slice if pic param is invalid */ COPYTHECONTEXT("SH: pic_parameter_set_id", u4_temp); ps_pps = &ps_dec->ps_pps[u4_temp]; if(FALSE == ps_pps->u1_is_valid) { return ERROR_INV_SPS_PPS_T; } ps_seq = ps_pps->ps_sps; if(!ps_seq) return ERROR_INV_SPS_PPS_T; if(FALSE == ps_seq->u1_is_valid) return ERROR_INV_SPS_PPS_T; /* Get the frame num */ u2_frame_num = ih264d_get_bits_h264(ps_bitstrm, ps_seq->u1_bits_in_frm_num); COPYTHECONTEXT("SH: frame_num", u2_frame_num); /* Get the field related flags */ if(!ps_seq->u1_frame_mbs_only_flag) { u1_field_pic_flag = ih264d_get_bit_h264(ps_bitstrm); COPYTHECONTEXT("SH: field_pic_flag", u1_field_pic_flag); u1_bottom_field_flag = 0; if(u1_field_pic_flag) { ps_dec->pu1_inv_scan = (UWORD8 *)gau1_ih264d_inv_scan_fld; u1_bottom_field_flag = ih264d_get_bit_h264(ps_bitstrm); COPYTHECONTEXT("SH: bottom_field_flag", u1_bottom_field_flag); } else { ps_dec->pu1_inv_scan = (UWORD8 *)gau1_ih264d_inv_scan; } } else { u1_field_pic_flag = 0; u1_bottom_field_flag = 0; ps_dec->pu1_inv_scan = (UWORD8 *)gau1_ih264d_inv_scan; } u1_nal_unit_type = SLICE_NAL; if(u1_is_idr_slice) { if(0 == u1_field_pic_flag) { ps_dec->u1_top_bottom_decoded = TOP_FIELD_ONLY | BOT_FIELD_ONLY; } u1_nal_unit_type = IDR_SLICE_NAL; u4_idr_pic_id = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf); if(u4_idr_pic_id > 65535) return ERROR_INV_SPS_PPS_T; COPYTHECONTEXT("SH: ", u4_idr_pic_id); } /* read delta pic order count information*/ i_delta_poc[0] = i_delta_poc[1] = 0; s_tmp_poc.i4_pic_order_cnt_lsb = 0; s_tmp_poc.i4_delta_pic_order_cnt_bottom = 0; u1_pic_order_cnt_type = ps_seq->u1_pic_order_cnt_type; if(u1_pic_order_cnt_type == 0) { i_temp = ih264d_get_bits_h264( ps_bitstrm, ps_seq->u1_log2_max_pic_order_cnt_lsb_minus); if(i_temp < 0 || i_temp >= ps_seq->i4_max_pic_order_cntLsb) return ERROR_INV_SPS_PPS_T; s_tmp_poc.i4_pic_order_cnt_lsb = i_temp; COPYTHECONTEXT("SH: pic_order_cnt_lsb", s_tmp_poc.i4_pic_order_cnt_lsb); if((ps_pps->u1_pic_order_present_flag == 1) && (!u1_field_pic_flag)) { s_tmp_poc.i4_delta_pic_order_cnt_bottom = ih264d_sev( pu4_bitstrm_ofst, pu4_bitstrm_buf); COPYTHECONTEXT("SH: delta_pic_order_cnt_bottom", s_tmp_poc.i4_delta_pic_order_cnt_bottom); } } s_tmp_poc.i4_delta_pic_order_cnt[0] = 0; s_tmp_poc.i4_delta_pic_order_cnt[1] = 0; if(u1_pic_order_cnt_type == 1 && (!ps_seq->u1_delta_pic_order_always_zero_flag)) { s_tmp_poc.i4_delta_pic_order_cnt[0] = ih264d_sev(pu4_bitstrm_ofst, pu4_bitstrm_buf); COPYTHECONTEXT("SH: delta_pic_order_cnt[0]", s_tmp_poc.i4_delta_pic_order_cnt[0]); if(ps_pps->u1_pic_order_present_flag && !u1_field_pic_flag) { s_tmp_poc.i4_delta_pic_order_cnt[1] = ih264d_sev( pu4_bitstrm_ofst, pu4_bitstrm_buf); COPYTHECONTEXT("SH: delta_pic_order_cnt[1]", s_tmp_poc.i4_delta_pic_order_cnt[1]); } } if(ps_pps->u1_redundant_pic_cnt_present_flag) { u4_temp = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf); if(u4_temp > MAX_REDUNDANT_PIC_CNT) return ERROR_INV_SPS_PPS_T; u1_redundant_pic_cnt = u4_temp; COPYTHECONTEXT("SH: redundant_pic_cnt", u1_redundant_pic_cnt); } /*--------------------------------------------------------------------*/ /* Check if the slice is part of new picture */ /*--------------------------------------------------------------------*/ i1_is_end_of_poc = 0; if(!ps_dec->u1_first_slice_in_stream) { i1_is_end_of_poc = ih264d_is_end_of_pic(u2_frame_num, u1_nal_ref_idc, &s_tmp_poc, &ps_dec->s_cur_pic_poc, ps_cur_slice, u1_pic_order_cnt_type, u1_nal_unit_type, u4_idr_pic_id, u1_field_pic_flag, u1_bottom_field_flag); /* since we support only Full frame decode, every new process should * process a new pic */ if((ps_dec->u4_first_slice_in_pic == 2) && (i1_is_end_of_poc == 0)) { /* if it is the first slice is process call ,it should be a new frame. If it is not * reject current pic and dont add it to dpb */ ps_dec->ps_dec_err_status->u1_err_flag |= REJECT_CUR_PIC; i1_is_end_of_poc = 1; } else { /* reset REJECT_CUR_PIC */ ps_dec->ps_dec_err_status->u1_err_flag &= MASK_REJECT_CUR_PIC; } } /*--------------------------------------------------------------------*/ /* Check for error in slice and parse the missing/corrupted MB's */ /* as skip-MB's in an inserted P-slice */ /*--------------------------------------------------------------------*/ u1_mbaff = ps_seq->u1_mb_aff_flag && (!u1_field_pic_flag); prev_slice_err = 0; if(i1_is_end_of_poc || ps_dec->u1_first_slice_in_stream) { if(u2_frame_num != ps_dec->u2_prv_frame_num && ps_dec->u1_top_bottom_decoded != 0 && ps_dec->u1_top_bottom_decoded != (TOP_FIELD_ONLY | BOT_FIELD_ONLY)) { ps_dec->u1_dangling_field = 1; if(ps_dec->u4_first_slice_in_pic) { prev_slice_err = 1; } else { prev_slice_err = 2; } if(ps_dec->u1_top_bottom_decoded ==TOP_FIELD_ONLY) ps_cur_slice->u1_bottom_field_flag = 1; else ps_cur_slice->u1_bottom_field_flag = 0; num_mb_skipped = (ps_dec->u2_frm_ht_in_mbs * ps_dec->u2_frm_wd_in_mbs) - ps_dec->u2_total_mbs_coded; ps_cur_poc = &ps_dec->s_cur_pic_poc; u1_is_idr_slice = ps_cur_slice->u1_nal_unit_type == IDR_SLICE_NAL; } else if(ps_dec->u4_first_slice_in_pic == 2) { if(u2_first_mb_in_slice > 0) { prev_slice_err = 1; num_mb_skipped = u2_first_mb_in_slice << u1_mbaff; ps_cur_poc = &s_tmp_poc; ps_cur_slice->u4_idr_pic_id = u4_idr_pic_id; ps_cur_slice->u1_field_pic_flag = u1_field_pic_flag; ps_cur_slice->u1_bottom_field_flag = u1_bottom_field_flag; ps_cur_slice->i4_pic_order_cnt_lsb = s_tmp_poc.i4_pic_order_cnt_lsb; ps_cur_slice->u1_nal_unit_type = u1_nal_unit_type; ps_cur_slice->u1_redundant_pic_cnt = u1_redundant_pic_cnt; ps_cur_slice->u1_nal_ref_idc = u1_nal_ref_idc; ps_cur_slice->u1_pic_order_cnt_type = u1_pic_order_cnt_type; } } else { if(ps_dec->u4_first_slice_in_pic) { /* if valid slice header is not decoded do start of pic processing * since in the current process call, frame num is not updated in the slice structure yet * ih264d_is_end_of_pic is checked with valid frame num of previous process call, * although i1_is_end_of_poc is set there could be more slices in the frame, * so conceal only till cur slice */ prev_slice_err = 1; num_mb_skipped = u2_first_mb_in_slice << u1_mbaff; } else { /* since i1_is_end_of_poc is set ,means new frame num is encountered. so conceal the current frame * completely */ prev_slice_err = 2; num_mb_skipped = (ps_dec->u2_frm_ht_in_mbs * ps_dec->u2_frm_wd_in_mbs) - ps_dec->u2_total_mbs_coded; } ps_cur_poc = &s_tmp_poc; } } else { if((u2_first_mb_in_slice << u1_mbaff) > ps_dec->u2_total_mbs_coded) { prev_slice_err = 2; num_mb_skipped = (u2_first_mb_in_slice << u1_mbaff) - ps_dec->u2_total_mbs_coded; ps_cur_poc = &s_tmp_poc; } else if((u2_first_mb_in_slice << u1_mbaff) < ps_dec->u2_total_mbs_coded) { return ERROR_CORRUPTED_SLICE; } } if(prev_slice_err) { ret = ih264d_mark_err_slice_skip(ps_dec, num_mb_skipped, u1_is_idr_slice, u2_frame_num, ps_cur_poc, prev_slice_err); if(ps_dec->u1_dangling_field == 1) { ps_dec->u1_second_field = 1 - ps_dec->u1_second_field; ps_cur_slice->u1_bottom_field_flag = u1_bottom_field_flag; ps_dec->u2_prv_frame_num = u2_frame_num; ps_dec->u1_first_slice_in_stream = 0; return ERROR_DANGLING_FIELD_IN_PIC; } if(prev_slice_err == 2) { ps_dec->u1_first_slice_in_stream = 0; return ERROR_INCOMPLETE_FRAME; } if(ps_dec->u2_total_mbs_coded >= ps_dec->u2_frm_ht_in_mbs * ps_dec->u2_frm_wd_in_mbs) { /* return if all MBs in frame are parsed*/ ps_dec->u1_first_slice_in_stream = 0; return ERROR_IN_LAST_SLICE_OF_PIC; } if(ps_dec->ps_dec_err_status->u1_err_flag & REJECT_CUR_PIC) { ih264d_err_pic_dispbuf_mgr(ps_dec); return ERROR_NEW_FRAME_EXPECTED; } if(ret != OK) return ret; i1_is_end_of_poc = 0; } if (ps_dec->u4_first_slice_in_pic == 0) ps_dec->ps_parse_cur_slice++; ps_dec->u1_slice_header_done = 0; /*--------------------------------------------------------------------*/ /* If the slice is part of new picture, do End of Pic processing. */ /*--------------------------------------------------------------------*/ if(!ps_dec->u1_first_slice_in_stream) { UWORD8 uc_mbs_exceed = 0; if(ps_dec->u2_total_mbs_coded == (ps_dec->ps_cur_sps->u2_max_mb_addr + 1)) { /*u2_total_mbs_coded is forced to u2_max_mb_addr+ 1 at the end of decode ,so ,if it is first slice in pic dont consider u2_total_mbs_coded to detect new picture */ if(ps_dec->u4_first_slice_in_pic == 0) uc_mbs_exceed = 1; } if(i1_is_end_of_poc || uc_mbs_exceed) { if(1 == ps_dec->u1_last_pic_not_decoded) { ret = ih264d_end_of_pic_dispbuf_mgr(ps_dec); if(ret != OK) return ret; ret = ih264d_end_of_pic(ps_dec, u1_is_idr_slice, u2_frame_num); if(ret != OK) return ret; #if WIN32 H264_DEC_DEBUG_PRINT(" ------ PIC SKIPPED ------\n"); #endif return RET_LAST_SKIP; } else { ret = ih264d_end_of_pic(ps_dec, u1_is_idr_slice, u2_frame_num); if(ret != OK) return ret; } } } if(u1_field_pic_flag) { ps_dec->u2_prv_frame_num = u2_frame_num; } if(ps_cur_slice->u1_mmco_equalto5) { WORD32 i4_temp_poc; WORD32 i4_top_field_order_poc, i4_bot_field_order_poc; if(!ps_cur_slice->u1_field_pic_flag) // or a complementary field pair { i4_top_field_order_poc = ps_dec->ps_cur_pic->i4_top_field_order_cnt; i4_bot_field_order_poc = ps_dec->ps_cur_pic->i4_bottom_field_order_cnt; i4_temp_poc = MIN(i4_top_field_order_poc, i4_bot_field_order_poc); } else if(!ps_cur_slice->u1_bottom_field_flag) i4_temp_poc = ps_dec->ps_cur_pic->i4_top_field_order_cnt; else i4_temp_poc = ps_dec->ps_cur_pic->i4_bottom_field_order_cnt; ps_dec->ps_cur_pic->i4_top_field_order_cnt = i4_temp_poc - ps_dec->ps_cur_pic->i4_top_field_order_cnt; ps_dec->ps_cur_pic->i4_bottom_field_order_cnt = i4_temp_poc - ps_dec->ps_cur_pic->i4_bottom_field_order_cnt; ps_dec->ps_cur_pic->i4_poc = i4_temp_poc; ps_dec->ps_cur_pic->i4_avg_poc = i4_temp_poc; } if(ps_dec->u4_first_slice_in_pic == 2) { ret = ih264d_decode_pic_order_cnt(u1_is_idr_slice, u2_frame_num, &ps_dec->s_prev_pic_poc, &s_tmp_poc, ps_cur_slice, ps_pps, u1_nal_ref_idc, u1_bottom_field_flag, u1_field_pic_flag, &i4_poc); if(ret != OK) return ret; /* Display seq no calculations */ if(i4_poc >= ps_dec->i4_max_poc) ps_dec->i4_max_poc = i4_poc; /* IDR Picture or POC wrap around */ if(i4_poc == 0) { ps_dec->i4_prev_max_display_seq = ps_dec->i4_prev_max_display_seq + ps_dec->i4_max_poc + ps_dec->u1_max_dec_frame_buffering + 1; ps_dec->i4_max_poc = 0; } } /*--------------------------------------------------------------------*/ /* Copy the values read from the bitstream to the slice header and then*/ /* If the slice is first slice in picture, then do Start of Picture */ /* processing. */ /*--------------------------------------------------------------------*/ ps_cur_slice->i4_delta_pic_order_cnt[0] = i_delta_poc[0]; ps_cur_slice->i4_delta_pic_order_cnt[1] = i_delta_poc[1]; ps_cur_slice->u4_idr_pic_id = u4_idr_pic_id; ps_cur_slice->u2_first_mb_in_slice = u2_first_mb_in_slice; ps_cur_slice->u1_field_pic_flag = u1_field_pic_flag; ps_cur_slice->u1_bottom_field_flag = u1_bottom_field_flag; ps_cur_slice->u1_slice_type = u1_slice_type; ps_cur_slice->i4_pic_order_cnt_lsb = s_tmp_poc.i4_pic_order_cnt_lsb; ps_cur_slice->u1_nal_unit_type = u1_nal_unit_type; ps_cur_slice->u1_redundant_pic_cnt = u1_redundant_pic_cnt; ps_cur_slice->u1_nal_ref_idc = u1_nal_ref_idc; ps_cur_slice->u1_pic_order_cnt_type = u1_pic_order_cnt_type; if(ps_seq->u1_frame_mbs_only_flag) ps_cur_slice->u1_direct_8x8_inference_flag = ps_seq->u1_direct_8x8_inference_flag; else ps_cur_slice->u1_direct_8x8_inference_flag = 1; if(u1_slice_type == B_SLICE) { ps_cur_slice->u1_direct_spatial_mv_pred_flag = ih264d_get_bit_h264( ps_bitstrm); COPYTHECONTEXT("SH: direct_spatial_mv_pred_flag", ps_cur_slice->u1_direct_spatial_mv_pred_flag); if(ps_cur_slice->u1_direct_spatial_mv_pred_flag) ps_cur_slice->pf_decodeDirect = ih264d_decode_spatial_direct; else ps_cur_slice->pf_decodeDirect = ih264d_decode_temporal_direct; if(!((ps_pps->ps_sps->u1_mb_aff_flag) && (!u1_field_pic_flag))) ps_dec->pf_mvpred = ih264d_mvpred_nonmbaffB; } else { if(!((ps_pps->ps_sps->u1_mb_aff_flag) && (!u1_field_pic_flag))) ps_dec->pf_mvpred = ih264d_mvpred_nonmbaff; } if(ps_dec->u4_first_slice_in_pic == 2) { if(u2_first_mb_in_slice == 0) { ret = ih264d_start_of_pic(ps_dec, i4_poc, &s_tmp_poc, u2_frame_num, ps_pps); if(ret != OK) return ret; } 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; } } } /* INITIALIZATION of fn ptrs for MC and formMbPartInfo functions */ { UWORD8 uc_nofield_nombaff; uc_nofield_nombaff = ((ps_dec->ps_cur_slice->u1_field_pic_flag == 0) && (ps_dec->ps_cur_slice->u1_mbaff_frame_flag == 0) && (u1_slice_type != B_SLICE) && (ps_dec->ps_cur_pps->u1_wted_pred_flag == 0)); /* Initialise MC and formMbPartInfo fn ptrs one time based on profile_idc */ if(uc_nofield_nombaff) { ps_dec->p_form_mb_part_info = ih264d_form_mb_part_info_bp; ps_dec->p_motion_compensate = ih264d_motion_compensate_bp; } else { ps_dec->p_form_mb_part_info = ih264d_form_mb_part_info_mp; ps_dec->p_motion_compensate = ih264d_motion_compensate_mp; } } /* * Decide whether to decode the current picture or not */ { dec_err_status_t * ps_err = ps_dec->ps_dec_err_status; if(ps_err->u4_frm_sei_sync == u2_frame_num) { ps_err->u1_err_flag = ACCEPT_ALL_PICS; ps_err->u4_frm_sei_sync = SYNC_FRM_DEFAULT; } ps_err->u4_cur_frm = u2_frame_num; } /* Decision for decoding if the picture is to be skipped */ { WORD32 i4_skip_b_pic, i4_skip_p_pic; i4_skip_b_pic = (ps_dec->u4_skip_frm_mask & B_SLC_BIT) && (B_SLICE == u1_slice_type) && (0 == u1_nal_ref_idc); i4_skip_p_pic = (ps_dec->u4_skip_frm_mask & P_SLC_BIT) && (P_SLICE == u1_slice_type) && (0 == u1_nal_ref_idc); /**************************************************************/ /* Skip the B picture if skip mask is set for B picture and */ /* Current B picture is a non reference B picture or there is */ /* no user for reference B picture */ /**************************************************************/ if(i4_skip_b_pic) { ps_dec->ps_cur_pic->u4_pack_slc_typ |= B_SLC_BIT; /* Don't decode the picture in SKIP-B mode if that picture is B */ /* and also it is not to be used as a reference picture */ ps_dec->u1_last_pic_not_decoded = 1; return OK; } /**************************************************************/ /* Skip the P picture if skip mask is set for P picture and */ /* Current P picture is a non reference P picture or there is */ /* no user for reference P picture */ /**************************************************************/ if(i4_skip_p_pic) { ps_dec->ps_cur_pic->u4_pack_slc_typ |= P_SLC_BIT; /* Don't decode the picture in SKIP-P mode if that picture is P */ /* and also it is not to be used as a reference picture */ ps_dec->u1_last_pic_not_decoded = 1; return OK; } } { UWORD16 u2_mb_x, u2_mb_y; ps_dec->i4_submb_ofst = ((u2_first_mb_in_slice << ps_cur_slice->u1_mbaff_frame_flag) * SUB_BLK_SIZE) - SUB_BLK_SIZE; if(u2_first_mb_in_slice) { UWORD8 u1_mb_aff; UWORD8 u1_field_pic; UWORD16 u2_frm_wd_in_mbs; u2_frm_wd_in_mbs = ps_seq->u2_frm_wd_in_mbs; u1_mb_aff = ps_cur_slice->u1_mbaff_frame_flag; u1_field_pic = ps_cur_slice->u1_field_pic_flag; { UWORD32 x_offset; UWORD32 y_offset; UWORD32 u4_frame_stride; tfr_ctxt_t *ps_trns_addr; // = &ps_dec->s_tran_addrecon_parse; if(ps_dec->u1_separate_parse) { ps_trns_addr = &ps_dec->s_tran_addrecon_parse; } else { ps_trns_addr = &ps_dec->s_tran_addrecon; } u2_mb_x = MOD(u2_first_mb_in_slice, u2_frm_wd_in_mbs); u2_mb_y = DIV(u2_first_mb_in_slice, u2_frm_wd_in_mbs); u2_mb_y <<= u1_mb_aff; if((u2_mb_x > u2_frm_wd_in_mbs - 1) || (u2_mb_y > ps_dec->u2_frm_ht_in_mbs - 1)) { return ERROR_CORRUPTED_SLICE; } u4_frame_stride = ps_dec->u2_frm_wd_y << u1_field_pic; x_offset = u2_mb_x << 4; y_offset = (u2_mb_y * u4_frame_stride) << 4; ps_trns_addr->pu1_dest_y = ps_dec->s_cur_pic.pu1_buf1 + x_offset + y_offset; u4_frame_stride = ps_dec->u2_frm_wd_uv << u1_field_pic; x_offset >>= 1; y_offset = (u2_mb_y * u4_frame_stride) << 3; x_offset *= YUV420SP_FACTOR; ps_trns_addr->pu1_dest_u = ps_dec->s_cur_pic.pu1_buf2 + x_offset + y_offset; ps_trns_addr->pu1_dest_v = ps_dec->s_cur_pic.pu1_buf3 + x_offset + y_offset; ps_trns_addr->pu1_mb_y = ps_trns_addr->pu1_dest_y; ps_trns_addr->pu1_mb_u = ps_trns_addr->pu1_dest_u; ps_trns_addr->pu1_mb_v = ps_trns_addr->pu1_dest_v; if(ps_dec->u1_separate_parse == 1) { ps_dec->ps_deblk_mbn = ps_dec->ps_deblk_pic + (u2_first_mb_in_slice << u1_mb_aff); } else { ps_dec->ps_deblk_mbn = ps_dec->ps_deblk_pic + (u2_first_mb_in_slice << u1_mb_aff); } ps_dec->u2_cur_mb_addr = (u2_first_mb_in_slice << u1_mb_aff); ps_dec->ps_mv_cur = ps_dec->s_cur_pic.ps_mv + ((u2_first_mb_in_slice << u1_mb_aff) << 4); } } else { tfr_ctxt_t *ps_trns_addr; if(ps_dec->u1_separate_parse) { ps_trns_addr = &ps_dec->s_tran_addrecon_parse; } else { ps_trns_addr = &ps_dec->s_tran_addrecon; } u2_mb_x = 0xffff; u2_mb_y = 0; ps_dec->u2_cur_mb_addr = 0; ps_dec->ps_deblk_mbn = ps_dec->ps_deblk_pic; ps_dec->ps_mv_cur = ps_dec->s_cur_pic.ps_mv; ps_trns_addr->pu1_dest_y = ps_dec->s_cur_pic.pu1_buf1; ps_trns_addr->pu1_dest_u = ps_dec->s_cur_pic.pu1_buf2; ps_trns_addr->pu1_dest_v = ps_dec->s_cur_pic.pu1_buf3; ps_trns_addr->pu1_mb_y = ps_trns_addr->pu1_dest_y; ps_trns_addr->pu1_mb_u = ps_trns_addr->pu1_dest_u; ps_trns_addr->pu1_mb_v = ps_trns_addr->pu1_dest_v; } ps_dec->ps_part = ps_dec->ps_parse_part_params; ps_dec->u2_mbx = (MOD(u2_first_mb_in_slice - 1, ps_seq->u2_frm_wd_in_mbs)); ps_dec->u2_mby = (DIV(u2_first_mb_in_slice - 1, ps_seq->u2_frm_wd_in_mbs)); ps_dec->u2_mby <<= ps_cur_slice->u1_mbaff_frame_flag; ps_dec->i2_prev_slice_mbx = ps_dec->u2_mbx; ps_dec->i2_prev_slice_mby = ps_dec->u2_mby; } /* RBSP stop bit is used for CABAC decoding*/ ps_bitstrm->u4_max_ofst += ps_dec->ps_cur_pps->u1_entropy_coding_mode; ps_dec->u1_B = (u1_slice_type == B_SLICE); ps_dec->u4_next_mb_skip = 0; ps_dec->ps_parse_cur_slice->u4_first_mb_in_slice = ps_dec->ps_cur_slice->u2_first_mb_in_slice; ps_dec->ps_parse_cur_slice->slice_type = ps_dec->ps_cur_slice->u1_slice_type; ps_dec->u4_start_recon_deblk = 1; { 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 = ( void *)pu1_buf; } 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; } ps_dec->pu4_wt_ofsts = ps_dec->pu4_wts_ofsts_mat; if(u1_slice_type == I_SLICE) { ps_dec->ps_cur_pic->u4_pack_slc_typ |= I_SLC_BIT; ret = ih264d_parse_islice(ps_dec, u2_first_mb_in_slice); if(ps_dec->i4_pic_type != B_SLICE && ps_dec->i4_pic_type != P_SLICE) ps_dec->i4_pic_type = I_SLICE; } else if(u1_slice_type == P_SLICE) { ps_dec->ps_cur_pic->u4_pack_slc_typ |= P_SLC_BIT; ret = ih264d_parse_pslice(ps_dec, u2_first_mb_in_slice); ps_dec->u1_pr_sl_type = u1_slice_type; if(ps_dec->i4_pic_type != B_SLICE) ps_dec->i4_pic_type = P_SLICE; } else if(u1_slice_type == B_SLICE) { ps_dec->ps_cur_pic->u4_pack_slc_typ |= B_SLC_BIT; ret = ih264d_parse_bslice(ps_dec, u2_first_mb_in_slice); ps_dec->u1_pr_sl_type = u1_slice_type; ps_dec->i4_pic_type = B_SLICE; } else return ERROR_INV_SLC_TYPE_T; if(ps_dec->u1_slice_header_done) { /* set to zero to indicate a valid slice has been decoded */ /* first slice header successfully decoded */ ps_dec->u4_first_slice_in_pic = 0; ps_dec->u1_first_slice_in_stream = 0; } if(ret != OK) return ret; ps_dec->u2_cur_slice_num++; /* storing last Mb X and MbY of the slice */ ps_dec->i2_prev_slice_mbx = ps_dec->u2_mbx; ps_dec->i2_prev_slice_mby = ps_dec->u2_mby; /* End of Picture detection */ if(ps_dec->u2_total_mbs_coded >= (ps_seq->u2_max_mb_addr + 1)) { ps_dec->u1_pic_decode_done = 1; } { dec_err_status_t * ps_err = ps_dec->ps_dec_err_status; if((ps_err->u1_err_flag & REJECT_PB_PICS) && (ps_err->u1_cur_pic_type == PIC_TYPE_I)) { ps_err->u1_err_flag = ACCEPT_ALL_PICS; } } PRINT_BIN_BIT_RATIO(ps_dec) return ret; } Commit Message: Decoder: Initialize slice parameters before concealing error MBs Also memset ps_dec_op structure to zero. For error input, this ensures dimensions are initialized to zero Bug: 28165661 Change-Id: I66eb2ddc5e02e74b7ff04da5f749443920f37141 CWE ID: CWE-20 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void GaiaOAuthClient::Core::RefreshToken( const OAuthClientInfo& oauth_client_info, const std::string& refresh_token, GaiaOAuthClient::Delegate* delegate) { DCHECK(!request_.get()) << "Tried to fetch two things at once!"; delegate_ = delegate; access_token_.clear(); expires_in_seconds_ = 0; std::string post_body = "refresh_token=" + net::EscapeUrlEncodedData(refresh_token, true) + "&client_id=" + net::EscapeUrlEncodedData(oauth_client_info.client_id, true) + "&client_secret=" + net::EscapeUrlEncodedData(oauth_client_info.client_secret, true) + "&grant_type=refresh_token"; request_.reset(new UrlFetcher(GURL(provider_info_.access_token_url), UrlFetcher::POST)); request_->SetRequestContext(request_context_getter_); request_->SetUploadData("application/x-www-form-urlencoded", post_body); request_->Start( base::Bind(&GaiaOAuthClient::Core::OnAuthTokenFetchComplete, this)); } Commit Message: Remove UrlFetcher from remoting and use the one in net instead. BUG=133790 TEST=Stop and restart the Me2Me host. It should still work. Review URL: https://chromiumcodereview.appspot.com/10637008 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143798 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399 Target: 1 Example 2: Code: INST_HANDLER (in) { // IN Rd, A int r = ((buf[0] >> 4) & 0x0f) | ((buf[1] & 0x01) << 4); int a = (buf[0] & 0x0f) | ((buf[1] & 0x6) << 3); RStrBuf *io_src = __generic_io_dest (a, 0, cpu); op->type2 = 0; op->val = a; op->family = R_ANAL_OP_FAMILY_IO; ESIL_A ("%s,r%d,=,", r_strbuf_get (io_src), r); r_strbuf_free (io_src); } Commit Message: Fix #9943 - Invalid free on RAnal.avr CWE ID: CWE-416 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: bool WebPagePrivate::dispatchMouseEventToFullScreenPlugin(PluginView* plugin, const Platform::MouseEvent& event) { NPEvent npEvent; NPMouseEvent mouseEvent; mouseEvent.x = event.screenPosition().x(); mouseEvent.y = event.screenPosition().y(); switch (event.type()) { case Platform::MouseEvent::MouseButtonDown: mouseEvent.type = MOUSE_BUTTON_DOWN; m_pluginMouseButtonPressed = true; break; case Platform::MouseEvent::MouseButtonUp: mouseEvent.type = MOUSE_BUTTON_UP; m_pluginMouseButtonPressed = false; break; case Platform::MouseEvent::MouseMove: mouseEvent.type = MOUSE_MOTION; break; default: return false; } mouseEvent.flags = 0; mouseEvent.button = m_pluginMouseButtonPressed; npEvent.type = NP_MouseEvent; npEvent.data = &mouseEvent; return plugin->dispatchFullScreenNPEvent(npEvent); } 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: Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: PixelBufferRasterWorkerPool::PixelBufferRasterWorkerPool( ResourceProvider* resource_provider, ContextProvider* context_provider, size_t num_threads, size_t max_transfer_buffer_usage_bytes) : RasterWorkerPool(resource_provider, context_provider, num_threads), shutdown_(false), scheduled_raster_task_count_(0), bytes_pending_upload_(0), max_bytes_pending_upload_(max_transfer_buffer_usage_bytes), has_performed_uploads_since_last_flush_(false), check_for_completed_raster_tasks_pending_(false), should_notify_client_if_no_tasks_are_pending_(false), should_notify_client_if_no_tasks_required_for_activation_are_pending_( false) { } Commit Message: cc: Simplify raster task completion notification logic (Relanding after missing activation bug fixed in https://codereview.chromium.org/131763003/) Previously the pixel buffer raster worker pool used a combination of polling and explicit notifications from the raster worker pool to decide when to tell the client about the completion of 1) all tasks or 2) the subset of tasks required for activation. This patch simplifies the logic by only triggering the notification based on the OnRasterTasksFinished and OnRasterTasksRequiredForActivationFinished calls from the worker pool. BUG=307841,331534 Review URL: https://codereview.chromium.org/99873007 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@243991 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20 Target: 1 Example 2: Code: void DocumentThreadableLoader::start(const ResourceRequest& request) { ASSERT(m_async || request.httpReferrer().isEmpty()); m_sameOriginRequest = getSecurityOrigin()->canRequestNoSuborigin(request.url()); m_requestContext = request.requestContext(); m_redirectMode = request.fetchRedirectMode(); if (!m_sameOriginRequest && m_options.crossOriginRequestPolicy == DenyCrossOriginRequests) { InspectorInstrumentation::documentThreadableLoaderFailedToStartLoadingForClient(m_document, m_client); ThreadableLoaderClient* client = m_client; clear(); client->didFail(ResourceError(errorDomainBlinkInternal, 0, request.url().getString(), "Cross origin requests are not supported.")); return; } m_requestStartedSeconds = monotonicallyIncreasingTime(); const HTTPHeaderMap& headerMap = request.httpHeaderFields(); for (const auto& header : headerMap) { if (FetchUtils::isSimpleHeader(header.key, header.value)) { m_simpleRequestHeaders.add(header.key, header.value); } else if (equalIgnoringCase(header.key, HTTPNames::Range) && m_options.crossOriginRequestPolicy == UseAccessControl && m_options.preflightPolicy == PreventPreflight) { m_simpleRequestHeaders.add(header.key, header.value); } } if (request.httpMethod() != HTTPNames::GET) { if (Page* page = m_document->page()) page->chromeClient().didObserveNonGetFetchFromScript(); } if (m_async && !request.skipServiceWorker() && SchemeRegistry::shouldTreatURLSchemeAsAllowingServiceWorkers(request.url().protocol()) && m_document->fetcher()->isControlledByServiceWorker()) { ResourceRequest newRequest(request); const WebURLRequest::RequestContext requestContext(request.requestContext()); if (requestContext != WebURLRequest::RequestContextFetch) { switch (m_options.crossOriginRequestPolicy) { case DenyCrossOriginRequests: newRequest.setFetchRequestMode(WebURLRequest::FetchRequestModeSameOrigin); break; case UseAccessControl: if (m_options.preflightPolicy == ForcePreflight) newRequest.setFetchRequestMode(WebURLRequest::FetchRequestModeCORSWithForcedPreflight); else newRequest.setFetchRequestMode(WebURLRequest::FetchRequestModeCORS); break; case AllowCrossOriginRequests: SECURITY_CHECK(requestContext == WebURLRequest::RequestContextAudio || requestContext == WebURLRequest::RequestContextVideo || requestContext == WebURLRequest::RequestContextObject || requestContext == WebURLRequest::RequestContextFavicon || requestContext == WebURLRequest::RequestContextImage || requestContext == WebURLRequest::RequestContextScript); newRequest.setFetchRequestMode(WebURLRequest::FetchRequestModeNoCORS); break; } if (m_resourceLoaderOptions.allowCredentials == AllowStoredCredentials) newRequest.setFetchCredentialsMode(WebURLRequest::FetchCredentialsModeInclude); else newRequest.setFetchCredentialsMode(WebURLRequest::FetchCredentialsModeSameOrigin); } if (newRequest.fetchRequestMode() == WebURLRequest::FetchRequestModeCORS || newRequest.fetchRequestMode() == WebURLRequest::FetchRequestModeCORSWithForcedPreflight) { m_fallbackRequestForServiceWorker = ResourceRequest(request); m_fallbackRequestForServiceWorker.setSkipServiceWorker(true); } loadRequest(newRequest, m_resourceLoaderOptions); return; } dispatchInitialRequest(request); } Commit Message: DocumentThreadableLoader: Add guards for sync notifyFinished() in setResource() In loadRequest(), setResource() can call clear() synchronously: DocumentThreadableLoader::clear() DocumentThreadableLoader::handleError() Resource::didAddClient() RawResource::didAddClient() and thus |m_client| can be null while resource() isn't null after setResource(), causing crashes (Issue 595964). This CL checks whether |*this| is destructed and whether |m_client| is null after setResource(). BUG=595964 Review-Url: https://codereview.chromium.org/1902683002 Cr-Commit-Position: refs/heads/master@{#391001} CWE ID: CWE-189 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void FrameFetchContext::DispatchWillSendRequest( unsigned long identifier, ResourceRequest& request, const ResourceResponse& redirect_response, const FetchInitiatorInfo& initiator_info) { if (IsDetached()) return; if (redirect_response.IsNull()) { GetFrame()->Loader().Progress().WillStartLoading(identifier, request.Priority()); } probe::willSendRequest(GetFrame()->GetDocument(), identifier, MasterDocumentLoader(), request, redirect_response, initiator_info); if (IdlenessDetector* idleness_detector = GetFrame()->GetIdlenessDetector()) idleness_detector->OnWillSendRequest(); if (GetFrame()->FrameScheduler()) GetFrame()->FrameScheduler()->DidStartLoading(identifier); } Commit Message: DevTools: send proper resource type in Network.RequestWillBeSent This patch plumbs resoure type into the DispatchWillSendRequest instrumenation. This allows us to report accurate type in Network.RequestWillBeSent event, instead of "Other", that we report today. BUG=765501 R=dgozman Change-Id: I0134c08b841e8dd247fdc8ff208bfd51e462709c Reviewed-on: https://chromium-review.googlesource.com/667504 Reviewed-by: Pavel Feldman <[email protected]> Reviewed-by: Dmitry Gozman <[email protected]> Commit-Queue: Andrey Lushnikov <[email protected]> Cr-Commit-Position: refs/heads/master@{#507936} CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: bool VaapiVideoDecodeAccelerator::VaapiVP8Accelerator::OutputPicture( const scoped_refptr<VP8Picture>& pic) { scoped_refptr<VaapiDecodeSurface> dec_surface = VP8PictureToVaapiDecodeSurface(pic); dec_surface->set_visible_rect(pic->visible_rect); vaapi_dec_->SurfaceReady(dec_surface); return true; } Commit Message: vaapi vda: Delete owned objects on worker thread in Cleanup() This CL adds a SEQUENCE_CHECKER to Vaapi*Accelerator classes, and posts the destruction of those objects to the appropriate thread on Cleanup(). Also makes {H264,VP8,VP9}Picture RefCountedThreadSafe, see miu@ comment in https://chromium-review.googlesource.com/c/chromium/src/+/794091#message-a64bed985cfaf8a19499a517bb110a7ce581dc0f TEST=play back VP9/VP8/H264 w/ simplechrome on soraka, Release build unstripped, let video play for a few seconds then navigate back; no crashes. Unittests as before: video_decode_accelerator_unittest --test_video_data=test-25fps.vp9:320:240:250:250:35:150:12 video_decode_accelerator_unittest --test_video_data=test-25fps.vp8:320:240:250:250:35:150:11 video_decode_accelerator_unittest --test_video_data=test-25fps.h264:320:240:250:258:35:150:1 Bug: 789160 Cq-Include-Trybots: master.tryserver.chromium.android:android_optional_gpu_tests_rel;master.tryserver.chromium.linux:linux_optional_gpu_tests_rel;master.tryserver.chromium.mac:mac_optional_gpu_tests_rel;master.tryserver.chromium.win:win_optional_gpu_tests_rel Change-Id: I7d96aaf89c92bf46f00c8b8b36798e057a842ed2 Reviewed-on: https://chromium-review.googlesource.com/794091 Reviewed-by: Pawel Osciak <[email protected]> Commit-Queue: Miguel Casas <[email protected]> Cr-Commit-Position: refs/heads/master@{#523372} CWE ID: CWE-362 Target: 1 Example 2: Code: pad_to_4byte (size_t length) { return (length+3) & ~3; } Commit Message: Use asserts on lengths to prevent invalid reads/writes. CWE ID: CWE-125 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: GeometryMapper::SourceToDestinationProjectionInternal( const TransformPaintPropertyNode* source, const TransformPaintPropertyNode* destination, bool& success) { DCHECK(source && destination); DEFINE_STATIC_LOCAL(TransformationMatrix, identity, (TransformationMatrix())); DEFINE_STATIC_LOCAL(TransformationMatrix, temp, (TransformationMatrix())); if (source == destination) { success = true; return identity; } const GeometryMapperTransformCache& source_cache = source->GetTransformCache(); const GeometryMapperTransformCache& destination_cache = destination->GetTransformCache(); if (source_cache.plane_root() == destination_cache.plane_root()) { success = true; if (source == destination_cache.plane_root()) return destination_cache.from_plane_root(); if (destination == source_cache.plane_root()) return source_cache.to_plane_root(); temp = destination_cache.from_plane_root(); temp.Multiply(source_cache.to_plane_root()); return temp; } if (!destination_cache.projection_from_screen_is_valid()) { success = false; return identity; } const auto* root = TransformPaintPropertyNode::Root(); success = true; if (source == root) return destination_cache.projection_from_screen(); if (destination == root) { temp = source_cache.to_screen(); } else { temp = destination_cache.projection_from_screen(); temp.Multiply(source_cache.to_screen()); } temp.FlattenTo2d(); return temp; } 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: Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static void php_wddx_process_data(void *user_data, const XML_Char *s, int len) { st_entry *ent; wddx_stack *stack = (wddx_stack *)user_data; TSRMLS_FETCH(); if (!wddx_stack_is_empty(stack) && !stack->done) { wddx_stack_top(stack, (void**)&ent); switch (ent->type) { case ST_STRING: if (Z_STRLEN_P(ent->data) == 0) { STR_FREE(Z_STRVAL_P(ent->data)); Z_STRVAL_P(ent->data) = estrndup(s, len); Z_STRLEN_P(ent->data) = len; } else { Z_STRVAL_P(ent->data) = erealloc(Z_STRVAL_P(ent->data), Z_STRLEN_P(ent->data) + len + 1); memcpy(Z_STRVAL_P(ent->data) + Z_STRLEN_P(ent->data), s, len); Z_STRLEN_P(ent->data) += len; Z_STRVAL_P(ent->data)[Z_STRLEN_P(ent->data)] = '\0'; } break; case ST_BINARY: if (Z_STRLEN_P(ent->data) == 0) { STR_FREE(Z_STRVAL_P(ent->data)); Z_STRVAL_P(ent->data) = estrndup(s, len + 1); } else { Z_STRVAL_P(ent->data) = erealloc(Z_STRVAL_P(ent->data), Z_STRLEN_P(ent->data) + len + 1); memcpy(Z_STRVAL_P(ent->data) + Z_STRLEN_P(ent->data), s, len); } Z_STRLEN_P(ent->data) += len; Z_STRVAL_P(ent->data)[Z_STRLEN_P(ent->data)] = '\0'; break; case ST_NUMBER: Z_TYPE_P(ent->data) = IS_STRING; Z_STRLEN_P(ent->data) = len; Z_STRVAL_P(ent->data) = estrndup(s, len); convert_scalar_to_number(ent->data TSRMLS_CC); break; case ST_BOOLEAN: if (!strcmp(s, "true")) { Z_LVAL_P(ent->data) = 1; } else if (!strcmp(s, "false")) { Z_LVAL_P(ent->data) = 0; } else { zval_ptr_dtor(&ent->data); if (ent->varname) { efree(ent->varname); } ent->data = NULL; } break; case ST_DATETIME: { char *tmp; tmp = emalloc(len + 1); memcpy(tmp, s, len); tmp[len] = '\0'; Z_LVAL_P(ent->data) = php_parse_date(tmp, NULL); /* date out of range < 1969 or > 2038 */ if (Z_LVAL_P(ent->data) == -1) { Z_TYPE_P(ent->data) = IS_STRING; Z_STRLEN_P(ent->data) = len; Z_STRVAL_P(ent->data) = estrndup(s, len); } efree(tmp); } break; default: break; } } } Commit Message: Fix bug #72340: Double Free Courruption in wddx_deserialize CWE ID: CWE-415 Target: 1 Example 2: Code: bool AXLayoutObject::isRichlyEditable() const { if (getNode() && hasRichlyEditableStyle(*getNode())) return true; if (isWebArea()) { Document& document = m_layoutObject->document(); HTMLElement* body = document.body(); if (body && hasRichlyEditableStyle(*body)) { AXObject* axBody = axObjectCache().getOrCreate(body); return axBody && axBody != axBody->ariaHiddenRoot(); } return hasRichlyEditableStyle(document); } return AXNodeObject::isRichlyEditable(); } Commit Message: Switch to equalIgnoringASCIICase throughout modules/accessibility BUG=627682 Review-Url: https://codereview.chromium.org/2793913007 Cr-Commit-Position: refs/heads/master@{#461858} CWE ID: CWE-254 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: bittok2str_internal(register const struct tok *lp, register const char *fmt, register u_int v, const char *sep) { static char buf[256]; /* our stringbuffer */ int buflen=0; register u_int rotbit; /* this is the bit we rotate through all bitpositions */ register u_int tokval; const char * sepstr = ""; while (lp != NULL && lp->s != NULL) { tokval=lp->v; /* load our first value */ rotbit=1; while (rotbit != 0) { /* * lets AND the rotating bit with our token value * and see if we have got a match */ if (tokval == (v&rotbit)) { /* ok we have found something */ buflen+=snprintf(buf+buflen, sizeof(buf)-buflen, "%s%s", sepstr, lp->s); sepstr = sep; break; } rotbit=rotbit<<1; /* no match - lets shift and try again */ } lp++; } if (buflen == 0) /* bummer - lets print the "unknown" message as advised in the fmt string if we got one */ (void)snprintf(buf, sizeof(buf), fmt == NULL ? "#%08x" : fmt, v); return (buf); } Commit Message: CVE-2017-13011/Properly check for buffer overflow in bittok2str_internal(). Also, make the buffer bigger. This fixes a buffer overflow discovered by Bhargava Shastry, SecT/TU Berlin. Add a test using the capture file supplied by the reporter(s), modified so the capture file won't be rejected as an invalid capture. CWE ID: CWE-119 Output:
1