diff --git "a/bigvul/split/bigvul_1024-*_test.json" "b/bigvul/split/bigvul_1024-*_test.json" new file mode 100644--- /dev/null +++ "b/bigvul/split/bigvul_1024-*_test.json" @@ -0,0 +1,983 @@ +[ + { + "index": 179941, + "code": "doshn(struct magic_set *ms, int clazz, int swap, int fd, off_t off, int num,\n size_t size, off_t fsize, int *flags, int mach, int strtab)\n{\n\tElf32_Shdr sh32;\n\tElf64_Shdr sh64;\n\tint stripped = 1;\n\tsize_t nbadcap = 0;\n\tvoid *nbuf;\n\toff_t noff, coff, name_off;\n \tuint64_t cap_hw1 = 0;\t/* SunOS 5.x hardware capabilites */\n \tuint64_t cap_sf1 = 0;\t/* SunOS 5.x software capabilites */\n \tchar name[50];\n \n \tif (size != xsh_sizeof) {\n \t\tif (file_printf(ms, \", corrupted section header size\") == -1)\n\t\t\treturn -1;\n\t\treturn 0;\n \t}\n \n \t/* Read offset of name section to be able to read section names later */\n\tif (pread(fd, xsh_addr, xsh_sizeof, off + size * strtab) == -1) {\n \t\tfile_badread(ms);\n \t\treturn -1;\n \t}\n \tname_off = xsh_offset;\n \n \tfor ( ; num; num--) {\n \t\t/* Read the name of this section. */\n\t\tif (pread(fd, name, sizeof(name), name_off + xsh_name) == -1) {\n \t\t\tfile_badread(ms);\n \t\t\treturn -1;\n \t\t}\n\t\tname[sizeof(name) - 1] = '\\0';\n \t\tif (strcmp(name, \".debug_info\") == 0)\n \t\t\tstripped = 0;\n \n\t\tif (pread(fd, xsh_addr, xsh_sizeof, off) == -1) {\n \t\t\tfile_badread(ms);\n \t\t\treturn -1;\n \t\t}\n\t\toff += size;\n\n\t\t/* Things we can determine before we seek */\n\t\tswitch (xsh_type) {\n\t\tcase SHT_SYMTAB:\n#if 0\n\t\tcase SHT_DYNSYM:\n#endif\n\t\t\tstripped = 0;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tif (fsize != SIZE_UNKNOWN && xsh_offset > fsize) {\n\t\t\t\t/* Perhaps warn here */\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\n\t\t/* Things we can determine when we seek */\n\t\tswitch (xsh_type) {\n\t\tcase SHT_NOTE:\n\t\t\tif ((nbuf = malloc(xsh_size)) == NULL) {\n\t\t\t\tfile_error(ms, errno, \"Cannot allocate memory\"\n \t\t\t\t \" for note\");\n \t\t\t\treturn -1;\n \t\t\t}\n\t\t\tif (pread(fd, nbuf, xsh_size, xsh_offset) == -1) {\n \t\t\t\tfile_badread(ms);\n \t\t\t\tfree(nbuf);\n \t\t\t\treturn -1;\n\t\t\t}\n\n\t\t\tnoff = 0;\n\t\t\tfor (;;) {\n\t\t\t\tif (noff >= (off_t)xsh_size)\n\t\t\t\t\tbreak;\n\t\t\t\tnoff = donote(ms, nbuf, (size_t)noff,\n\t\t\t\t xsh_size, clazz, swap, 4, flags);\n\t\t\t\tif (noff == 0)\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\tfree(nbuf);\n\t\t\tbreak;\n\t\tcase SHT_SUNW_cap:\n\t\t\tswitch (mach) {\n\t\t\tcase EM_SPARC:\n\t\t\tcase EM_SPARCV9:\n\t\t\tcase EM_IA_64:\n\t\t\tcase EM_386:\n\t\t\tcase EM_AMD64:\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tgoto skip;\n\t\t\t}\n\n\t\t\tif (nbadcap > 5)\n\t\t\t\tbreak;\n\t\t\tif (lseek(fd, xsh_offset, SEEK_SET) == (off_t)-1) {\n\t\t\t\tfile_badseek(ms);\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t\tcoff = 0;\n\t\t\tfor (;;) {\n\t\t\t\tElf32_Cap cap32;\n\t\t\t\tElf64_Cap cap64;\n\t\t\t\tchar cbuf[/*CONSTCOND*/\n\t\t\t\t MAX(sizeof cap32, sizeof cap64)];\n\t\t\t\tif ((coff += xcap_sizeof) > (off_t)xsh_size)\n\t\t\t\t\tbreak;\n\t\t\t\tif (read(fd, cbuf, (size_t)xcap_sizeof) !=\n\t\t\t\t (ssize_t)xcap_sizeof) {\n\t\t\t\t\tfile_badread(ms);\n\t\t\t\t\treturn -1;\n\t\t\t\t}\n\t\t\t\tif (cbuf[0] == 'A') {\n#ifdef notyet\n\t\t\t\t\tchar *p = cbuf + 1;\n\t\t\t\t\tuint32_t len, tag;\n\t\t\t\t\tmemcpy(&len, p, sizeof(len));\n\t\t\t\t\tp += 4;\n\t\t\t\t\tlen = getu32(swap, len);\n\t\t\t\t\tif (memcmp(\"gnu\", p, 3) != 0) {\n\t\t\t\t\t if (file_printf(ms,\n\t\t\t\t\t\t\", unknown capability %.3s\", p)\n\t\t\t\t\t\t== -1)\n\t\t\t\t\t\treturn -1;\n\t\t\t\t\t break;\n\t\t\t\t\t}\n\t\t\t\t\tp += strlen(p) + 1;\n\t\t\t\t\ttag = *p++;\n\t\t\t\t\tmemcpy(&len, p, sizeof(len));\n\t\t\t\t\tp += 4;\n\t\t\t\t\tlen = getu32(swap, len);\n\t\t\t\t\tif (tag != 1) {\n\t\t\t\t\t if (file_printf(ms, \", unknown gnu\"\n\t\t\t\t\t\t\" capability tag %d\", tag)\n\t\t\t\t\t\t== -1)\n\t\t\t\t\t\treturn -1;\n\t\t\t\t\t break;\n\t\t\t\t\t}\n#endif\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\t(void)memcpy(xcap_addr, cbuf, xcap_sizeof);\n\t\t\t\tswitch (xcap_tag) {\n\t\t\t\tcase CA_SUNW_NULL:\n\t\t\t\t\tbreak;\n\t\t\t\tcase CA_SUNW_HW_1:\n\t\t\t\t\tcap_hw1 |= xcap_val;\n\t\t\t\t\tbreak;\n\t\t\t\tcase CA_SUNW_SF_1:\n\t\t\t\t\tcap_sf1 |= xcap_val;\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tif (file_printf(ms,\n\t\t\t\t\t \", with unknown capability \"\n\t\t\t\t\t \"0x%\" INT64_T_FORMAT \"x = 0x%\"\n\t\t\t\t\t INT64_T_FORMAT \"x\",\n\t\t\t\t\t (unsigned long long)xcap_tag,\n\t\t\t\t\t (unsigned long long)xcap_val) == -1)\n\t\t\t\t\t\treturn -1;\n\t\t\t\t\tif (nbadcap++ > 2)\n\t\t\t\t\t\tcoff = xsh_size;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\t/*FALLTHROUGH*/\n\t\tskip:\n\t\tdefault:\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tif (file_printf(ms, \", %sstripped\", stripped ? \"\" : \"not \") == -1)\n\t\treturn -1;\n\tif (cap_hw1) {\n\t\tconst cap_desc_t *cdp;\n\t\tswitch (mach) {\n\t\tcase EM_SPARC:\n\t\tcase EM_SPARC32PLUS:\n\t\tcase EM_SPARCV9:\n\t\t\tcdp = cap_desc_sparc;\n\t\t\tbreak;\n\t\tcase EM_386:\n\t\tcase EM_IA_64:\n\t\tcase EM_AMD64:\n\t\t\tcdp = cap_desc_386;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tcdp = NULL;\n\t\t\tbreak;\n\t\t}\n\t\tif (file_printf(ms, \", uses\") == -1)\n\t\t\treturn -1;\n\t\tif (cdp) {\n\t\t\twhile (cdp->cd_name) {\n\t\t\t\tif (cap_hw1 & cdp->cd_mask) {\n\t\t\t\t\tif (file_printf(ms,\n\t\t\t\t\t \" %s\", cdp->cd_name) == -1)\n\t\t\t\t\t\treturn -1;\n\t\t\t\t\tcap_hw1 &= ~cdp->cd_mask;\n\t\t\t\t}\n\t\t\t\t++cdp;\n\t\t\t}\n\t\t\tif (cap_hw1)\n\t\t\t\tif (file_printf(ms,\n\t\t\t\t \" unknown hardware capability 0x%\"\n\t\t\t\t INT64_T_FORMAT \"x\",\n\t\t\t\t (unsigned long long)cap_hw1) == -1)\n\t\t\t\t\treturn -1;\n\t\t} else {\n\t\t\tif (file_printf(ms,\n\t\t\t \" hardware capability 0x%\" INT64_T_FORMAT \"x\",\n\t\t\t (unsigned long long)cap_hw1) == -1)\n\t\t\t\treturn -1;\n\t\t}\n\t}\n\tif (cap_sf1) {\n\t\tif (cap_sf1 & SF1_SUNW_FPUSED) {\n\t\t\tif (file_printf(ms,\n\t\t\t (cap_sf1 & SF1_SUNW_FPKNWN)\n\t\t\t ? \", uses frame pointer\"\n\t\t\t : \", not known to use frame pointer\") == -1)\n\t\t\t\treturn -1;\n\t\t}\n\t\tcap_sf1 &= ~SF1_SUNW_MASK;\n\t\tif (cap_sf1)\n\t\t\tif (file_printf(ms,\n\t\t\t \", with unknown software capability 0x%\"\n\t\t\t INT64_T_FORMAT \"x\",\n\t\t\t (unsigned long long)cap_sf1) == -1)\n\t\t\t\treturn -1;\n\t}\n\treturn 0;\n}\n", + "line": "\tif (pread(fd, xsh_addr, xsh_sizeof, off + size * strtab) == -1) {\n\t\tif (pread(fd, name, sizeof(name), name_off + xsh_name) == -1) {\n\t\tname[sizeof(name) - 1] = '\\0';\n\t\tif (pread(fd, xsh_addr, xsh_sizeof, off) == -1) {\n\t\t\tif (pread(fd, nbuf, xsh_size, xsh_offset) == -1) {\n", + "label": 1, + "cwe": "CWE-20", + "cve": "CVE-2014-9653", + "length": 1797 + }, + { + "index": 174719, + "code": "WORD32 ih264d_cavlc_parse_8x8block_top_available(WORD16 *pi2_coeff_block,\n UWORD32 u4_sub_block_strd,\n UWORD32 u4_isdc,\n dec_struct_t * ps_dec,\n UWORD8 *pu1_top_nnz,\n UWORD8 *pu1_left_nnz,\n UWORD8 u1_tran_form8x8,\n UWORD8 u1_mb_field_decodingflag,\n UWORD32 *pu4_csbp)\n{\n UWORD32 u4_num_coeff, u4_n, u4_subblock_coded;\n UWORD32 u4_top0, u4_top1;\n UWORD32 *pu4_dummy;\n WORD32 (**pf_cavlc_parse4x4coeff)(WORD16 *pi2_coeff_block,\n UWORD32 u4_isdc,\n WORD32 u4_n,\n struct _DecStruct *ps_dec,\n UWORD32 *pu4_dummy) =\n ps_dec->pf_cavlc_parse4x4coeff;\n UWORD32 u4_idx = 0;\n UWORD8 *puc_temp;\n WORD32 ret;\n\n *pu4_csbp = 0;\n puc_temp = ps_dec->pu1_inv_scan;\n\n /*------------------------------------------------------*/\n /* Residual 4x4 decoding: SubBlock 0 */\n /*------------------------------------------------------*/\n if(u1_tran_form8x8)\n {\n if(!u1_mb_field_decodingflag)\n {\n ps_dec->pu1_inv_scan =\n (UWORD8*)gau1_ih264d_inv_scan_prog8x8_cavlc[0];\n }\n else\n {\n ps_dec->pu1_inv_scan =\n (UWORD8*)gau1_ih264d_inv_scan_int8x8_cavlc[0];\n }\n }\n u4_n = pu1_top_nnz[0];\n ret = pf_cavlc_parse4x4coeff[(u4_n > 7)](pi2_coeff_block, u4_isdc,\n u4_n, ps_dec, &u4_num_coeff);\n if(ret != OK)\n return ret;\n\n u4_top0 = u4_num_coeff;\n u4_subblock_coded = (u4_num_coeff != 0);\n INSERT_BIT(*pu4_csbp, u4_idx, u4_subblock_coded);\n\n /*------------------------------------------------------*/\n /* Residual 4x4 decoding: SubBlock 1 */\n /*------------------------------------------------------*/\n u4_idx++;\n if(u1_tran_form8x8)\n {\n if(!u1_mb_field_decodingflag)\n {\n ps_dec->pu1_inv_scan =\n (UWORD8*)gau1_ih264d_inv_scan_prog8x8_cavlc[1];\n }\n else\n {\n ps_dec->pu1_inv_scan =\n (UWORD8*)gau1_ih264d_inv_scan_int8x8_cavlc[1];\n }\n }\n else\n {\n pi2_coeff_block += NUM_COEFFS_IN_4x4BLK;\n }\n u4_n = (pu1_top_nnz[1] + u4_num_coeff + 1) >> 1;\n ret = pf_cavlc_parse4x4coeff[(u4_n > 7)](pi2_coeff_block, u4_isdc,\n u4_n, ps_dec, &u4_num_coeff);\n if(ret != OK)\n return ret;\n\n u4_top1 = pu1_left_nnz[0] = u4_num_coeff;\n u4_subblock_coded = (u4_num_coeff != 0);\n INSERT_BIT(*pu4_csbp, u4_idx, u4_subblock_coded);\n\n /*------------------------------------------------------*/\n /* Residual 4x4 decoding: SubBlock 2 */\n /*------------------------------------------------------*/\n u4_idx += (u4_sub_block_strd - 1);\n if(u1_tran_form8x8)\n {\n if(!u1_mb_field_decodingflag)\n {\n ps_dec->pu1_inv_scan =\n (UWORD8*)gau1_ih264d_inv_scan_prog8x8_cavlc[2];\n }\n else\n {\n ps_dec->pu1_inv_scan =\n (UWORD8*)gau1_ih264d_inv_scan_int8x8_cavlc[2];\n }\n }\n else\n {\n pi2_coeff_block += ((u4_sub_block_strd - 1) * NUM_COEFFS_IN_4x4BLK);\n }\n u4_n = u4_top0;\n ret = pf_cavlc_parse4x4coeff[(u4_n > 7)](pi2_coeff_block, u4_isdc,\n u4_n, ps_dec, &u4_num_coeff);\n if(ret != OK)\n return ret;\n\n pu1_top_nnz[0] = u4_num_coeff;\n u4_subblock_coded = (u4_num_coeff != 0);\n INSERT_BIT(*pu4_csbp, u4_idx, u4_subblock_coded);\n\n /*------------------------------------------------------*/\n /* Residual 4x4 decoding: SubBlock 3 */\n /*------------------------------------------------------*/\n u4_idx++;\n if(u1_tran_form8x8)\n {\n if(!u1_mb_field_decodingflag)\n {\n ps_dec->pu1_inv_scan =\n (UWORD8*)gau1_ih264d_inv_scan_prog8x8_cavlc[3];\n }\n else\n {\n ps_dec->pu1_inv_scan =\n (UWORD8*)gau1_ih264d_inv_scan_int8x8_cavlc[3];\n }\n }\n else\n {\n pi2_coeff_block += NUM_COEFFS_IN_4x4BLK;\n }\n u4_n = (u4_top1 + u4_num_coeff + 1) >> 1;\n ret = pf_cavlc_parse4x4coeff[(u4_n > 7)](pi2_coeff_block, u4_isdc,\n u4_n, ps_dec, &u4_num_coeff);\n if(ret != OK)\n return ret;\n\n pu1_top_nnz[1] = pu1_left_nnz[1] = u4_num_coeff;\n u4_subblock_coded = (u4_num_coeff != 0);\n INSERT_BIT(*pu4_csbp, u4_idx, u4_subblock_coded);\n\n ps_dec->pu1_inv_scan = puc_temp;\n\n return OK;\n}\n", + "line": null, + "label": 0, + "cwe": "CWE-119", + "cve": "CVE-2016-0840", + "length": 1364 + }, + { + "index": 149736, + "code": "void FeatureInfo::InitializeFeatures() {\n std::string extensions_string(gl::GetGLExtensionsFromCurrentContext());\n gfx::ExtensionSet extensions(gfx::MakeExtensionSet(extensions_string));\n\n const char* version_str =\n reinterpret_cast(glGetString(GL_VERSION));\n const char* renderer_str =\n reinterpret_cast(glGetString(GL_RENDERER));\n\n gl_version_info_.reset(\n new gl::GLVersionInfo(version_str, renderer_str, extensions));\n\n bool enable_es3 = IsWebGL2OrES3OrHigherContext();\n\n bool has_pixel_buffers =\n gl_version_info_->is_es3 || gl_version_info_->is_desktop_core_profile ||\n gfx::HasExtension(extensions, \"GL_ARB_pixel_buffer_object\") ||\n gfx::HasExtension(extensions, \"GL_NV_pixel_buffer_object\");\n\n ScopedPixelUnpackBufferOverride scoped_pbo_override(has_pixel_buffers, 0);\n\n AddExtensionString(\"GL_ANGLE_translated_shader_source\");\n AddExtensionString(\"GL_CHROMIUM_async_pixel_transfers\");\n AddExtensionString(\"GL_CHROMIUM_bind_uniform_location\");\n AddExtensionString(\"GL_CHROMIUM_color_space_metadata\");\n AddExtensionString(\"GL_CHROMIUM_command_buffer_query\");\n AddExtensionString(\"GL_CHROMIUM_command_buffer_latency_query\");\n AddExtensionString(\"GL_CHROMIUM_copy_texture\");\n AddExtensionString(\"GL_CHROMIUM_deschedule\");\n AddExtensionString(\"GL_CHROMIUM_get_error_query\");\n AddExtensionString(\"GL_CHROMIUM_lose_context\");\n AddExtensionString(\"GL_CHROMIUM_pixel_transfer_buffer_object\");\n AddExtensionString(\"GL_CHROMIUM_rate_limit_offscreen_context\");\n AddExtensionString(\"GL_CHROMIUM_resize\");\n AddExtensionString(\"GL_CHROMIUM_resource_safe\");\n AddExtensionString(\"GL_CHROMIUM_strict_attribs\");\n AddExtensionString(\"GL_CHROMIUM_texture_mailbox\");\n AddExtensionString(\"GL_CHROMIUM_trace_marker\");\n AddExtensionString(\"GL_EXT_debug_marker\");\n\n AddExtensionString(\"GL_EXT_unpack_subimage\");\n\n AddExtensionString(\"GL_OES_vertex_array_object\");\n\n if (gfx::HasExtension(extensions, \"GL_ANGLE_translated_shader_source\")) {\n feature_flags_.angle_translated_shader_source = true;\n }\n\n bool enable_dxt1 = false;\n bool enable_dxt3 = false;\n bool enable_dxt5 = false;\n bool have_s3tc =\n gfx::HasExtension(extensions, \"GL_EXT_texture_compression_s3tc\");\n bool have_dxt3 =\n have_s3tc ||\n gfx::HasExtension(extensions, \"GL_ANGLE_texture_compression_dxt3\");\n bool have_dxt5 =\n have_s3tc ||\n gfx::HasExtension(extensions, \"GL_ANGLE_texture_compression_dxt5\");\n\n if (gfx::HasExtension(extensions, \"GL_EXT_texture_compression_dxt1\") ||\n gfx::HasExtension(extensions, \"GL_ANGLE_texture_compression_dxt1\") ||\n have_s3tc) {\n enable_dxt1 = true;\n }\n if (have_dxt3) {\n enable_dxt3 = true;\n }\n if (have_dxt5) {\n enable_dxt5 = true;\n }\n\n if (enable_dxt1) {\n feature_flags_.ext_texture_format_dxt1 = true;\n\n AddExtensionString(\"GL_ANGLE_texture_compression_dxt1\");\n validators_.compressed_texture_format.AddValue(\n GL_COMPRESSED_RGB_S3TC_DXT1_EXT);\n validators_.compressed_texture_format.AddValue(\n GL_COMPRESSED_RGBA_S3TC_DXT1_EXT);\n\n validators_.texture_internal_format_storage.AddValue(\n GL_COMPRESSED_RGB_S3TC_DXT1_EXT);\n validators_.texture_internal_format_storage.AddValue(\n GL_COMPRESSED_RGBA_S3TC_DXT1_EXT);\n }\n\n if (enable_dxt3) {\n AddExtensionString(\"GL_ANGLE_texture_compression_dxt3\");\n validators_.compressed_texture_format.AddValue(\n GL_COMPRESSED_RGBA_S3TC_DXT3_EXT);\n validators_.texture_internal_format_storage.AddValue(\n GL_COMPRESSED_RGBA_S3TC_DXT3_EXT);\n }\n\n if (enable_dxt5) {\n feature_flags_.ext_texture_format_dxt5 = true;\n\n AddExtensionString(\"GL_ANGLE_texture_compression_dxt5\");\n validators_.compressed_texture_format.AddValue(\n GL_COMPRESSED_RGBA_S3TC_DXT5_EXT);\n validators_.texture_internal_format_storage.AddValue(\n GL_COMPRESSED_RGBA_S3TC_DXT5_EXT);\n }\n\n bool have_astc =\n gfx::HasExtension(extensions, \"GL_KHR_texture_compression_astc_ldr\");\n if (have_astc) {\n feature_flags_.ext_texture_format_astc = true;\n AddExtensionString(\"GL_KHR_texture_compression_astc_ldr\");\n\n GLint astc_format_it = GL_COMPRESSED_RGBA_ASTC_4x4_KHR;\n GLint astc_format_max = GL_COMPRESSED_RGBA_ASTC_12x12_KHR;\n for (; astc_format_it <= astc_format_max; astc_format_it++) {\n validators_.compressed_texture_format.AddValue(astc_format_it);\n validators_.texture_internal_format_storage.AddValue(astc_format_it);\n }\n\n astc_format_it = GL_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR;\n astc_format_max = GL_COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR;\n for (; astc_format_it <= astc_format_max; astc_format_it++) {\n validators_.compressed_texture_format.AddValue(astc_format_it);\n validators_.texture_internal_format_storage.AddValue(astc_format_it);\n }\n }\n\n bool have_atc =\n gfx::HasExtension(extensions, \"GL_AMD_compressed_ATC_texture\") ||\n gfx::HasExtension(extensions, \"GL_ATI_texture_compression_atitc\");\n if (have_atc) {\n feature_flags_.ext_texture_format_atc = true;\n\n AddExtensionString(\"GL_AMD_compressed_ATC_texture\");\n validators_.compressed_texture_format.AddValue(GL_ATC_RGB_AMD);\n validators_.compressed_texture_format.AddValue(\n GL_ATC_RGBA_INTERPOLATED_ALPHA_AMD);\n\n validators_.texture_internal_format_storage.AddValue(GL_ATC_RGB_AMD);\n validators_.texture_internal_format_storage.AddValue(\n GL_ATC_RGBA_INTERPOLATED_ALPHA_AMD);\n }\n\n if (gfx::HasExtension(extensions, \"GL_EXT_texture_filter_anisotropic\")) {\n AddExtensionString(\"GL_EXT_texture_filter_anisotropic\");\n validators_.texture_parameter.AddValue(GL_TEXTURE_MAX_ANISOTROPY_EXT);\n validators_.g_l_state.AddValue(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT);\n }\n\n bool enable_depth_texture = false;\n GLenum depth_texture_format = GL_NONE;\n if (!workarounds_.disable_depth_texture &&\n (gfx::HasExtension(extensions, \"GL_ARB_depth_texture\") ||\n gfx::HasExtension(extensions, \"GL_OES_depth_texture\") ||\n gfx::HasExtension(extensions, \"GL_ANGLE_depth_texture\") ||\n gl_version_info_->is_desktop_core_profile)) {\n enable_depth_texture = true;\n depth_texture_format = GL_DEPTH_COMPONENT;\n feature_flags_.angle_depth_texture =\n gfx::HasExtension(extensions, \"GL_ANGLE_depth_texture\");\n }\n\n if (enable_depth_texture) {\n AddExtensionString(\"GL_CHROMIUM_depth_texture\");\n AddExtensionString(\"GL_GOOGLE_depth_texture\");\n validators_.texture_internal_format.AddValue(GL_DEPTH_COMPONENT);\n validators_.texture_format.AddValue(GL_DEPTH_COMPONENT);\n validators_.pixel_type.AddValue(GL_UNSIGNED_SHORT);\n validators_.pixel_type.AddValue(GL_UNSIGNED_INT);\n validators_.texture_depth_renderable_internal_format.AddValue(\n GL_DEPTH_COMPONENT);\n }\n\n GLenum depth_stencil_texture_format = GL_NONE;\n if (gfx::HasExtension(extensions, \"GL_EXT_packed_depth_stencil\") ||\n gfx::HasExtension(extensions, \"GL_OES_packed_depth_stencil\") ||\n gl_version_info_->is_es3 || gl_version_info_->is_desktop_core_profile) {\n AddExtensionString(\"GL_OES_packed_depth_stencil\");\n feature_flags_.packed_depth24_stencil8 = true;\n if (enable_depth_texture) {\n if (gl_version_info_->is_es3) {\n depth_stencil_texture_format = GL_DEPTH24_STENCIL8;\n } else {\n depth_stencil_texture_format = GL_DEPTH_STENCIL;\n }\n validators_.texture_internal_format.AddValue(GL_DEPTH_STENCIL);\n validators_.texture_format.AddValue(GL_DEPTH_STENCIL);\n validators_.pixel_type.AddValue(GL_UNSIGNED_INT_24_8);\n validators_.texture_depth_renderable_internal_format.AddValue(\n GL_DEPTH_STENCIL);\n validators_.texture_stencil_renderable_internal_format.AddValue(\n GL_DEPTH_STENCIL);\n }\n validators_.render_buffer_format.AddValue(GL_DEPTH24_STENCIL8);\n if (context_type_ == CONTEXT_TYPE_WEBGL1) {\n validators_.attachment.AddValue(GL_DEPTH_STENCIL_ATTACHMENT);\n validators_.attachment_query.AddValue(GL_DEPTH_STENCIL_ATTACHMENT);\n }\n }\n\n if (gl_version_info_->is_es3 || gl_version_info_->is_desktop_core_profile ||\n gfx::HasExtension(extensions, \"GL_OES_vertex_array_object\") ||\n gfx::HasExtension(extensions, \"GL_ARB_vertex_array_object\") ||\n gfx::HasExtension(extensions, \"GL_APPLE_vertex_array_object\")) {\n feature_flags_.native_vertex_array_object = true;\n }\n\n if (workarounds_.use_client_side_arrays_for_stream_buffers) {\n feature_flags_.native_vertex_array_object = false;\n }\n\n if (gl_version_info_->is_es3 ||\n gfx::HasExtension(extensions, \"GL_OES_element_index_uint\") ||\n gl::HasDesktopGLFeatures()) {\n AddExtensionString(\"GL_OES_element_index_uint\");\n validators_.index_type.AddValue(GL_UNSIGNED_INT);\n }\n\n bool has_srgb_framebuffer_support = false;\n if (gl_version_info_->IsAtLeastGL(3, 2) ||\n (gl_version_info_->IsAtLeastGL(2, 0) &&\n (gfx::HasExtension(extensions, \"GL_EXT_framebuffer_sRGB\") ||\n gfx::HasExtension(extensions, \"GL_ARB_framebuffer_sRGB\")))) {\n feature_flags_.desktop_srgb_support = true;\n has_srgb_framebuffer_support = true;\n }\n if ((((gl_version_info_->is_es3 ||\n gfx::HasExtension(extensions, \"GL_OES_rgb8_rgba8\")) &&\n gfx::HasExtension(extensions, \"GL_EXT_sRGB\")) ||\n feature_flags_.desktop_srgb_support) &&\n IsWebGL1OrES2Context()) {\n feature_flags_.ext_srgb = true;\n AddExtensionString(\"GL_EXT_sRGB\");\n validators_.texture_internal_format.AddValue(GL_SRGB_EXT);\n validators_.texture_internal_format.AddValue(GL_SRGB_ALPHA_EXT);\n validators_.texture_format.AddValue(GL_SRGB_EXT);\n validators_.texture_format.AddValue(GL_SRGB_ALPHA_EXT);\n validators_.render_buffer_format.AddValue(GL_SRGB8_ALPHA8_EXT);\n validators_.framebuffer_attachment_parameter.AddValue(\n GL_FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING_EXT);\n validators_.texture_unsized_internal_format.AddValue(GL_SRGB_EXT);\n validators_.texture_unsized_internal_format.AddValue(GL_SRGB_ALPHA_EXT);\n has_srgb_framebuffer_support = true;\n }\n if (gl_version_info_->is_es3)\n has_srgb_framebuffer_support = true;\n\n if (has_srgb_framebuffer_support && !IsWebGLContext()) {\n if (feature_flags_.desktop_srgb_support ||\n gfx::HasExtension(extensions, \"GL_EXT_sRGB_write_control\")) {\n feature_flags_.ext_srgb_write_control = true;\n AddExtensionString(\"GL_EXT_sRGB_write_control\");\n validators_.capability.AddValue(GL_FRAMEBUFFER_SRGB_EXT);\n }\n }\n\n if (gfx::HasExtension(extensions, \"GL_EXT_texture_sRGB_decode\") &&\n !IsWebGLContext()) {\n AddExtensionString(\"GL_EXT_texture_sRGB_decode\");\n validators_.texture_parameter.AddValue(GL_TEXTURE_SRGB_DECODE_EXT);\n }\n\n bool have_s3tc_srgb = false;\n if (gl_version_info_->is_es) {\n have_s3tc_srgb =\n gfx::HasExtension(extensions, \"GL_NV_sRGB_formats\") ||\n gfx::HasExtension(extensions, \"GL_EXT_texture_compression_s3tc_srgb\");\n } else {\n if (gfx::HasExtension(extensions, \"GL_EXT_texture_sRGB\") ||\n gl_version_info_->IsAtLeastGL(4, 1)) {\n have_s3tc_srgb =\n gfx::HasExtension(extensions, \"GL_EXT_texture_compression_s3tc\");\n }\n }\n\n if (have_s3tc_srgb) {\n AddExtensionString(\"GL_EXT_texture_compression_s3tc_srgb\");\n\n validators_.compressed_texture_format.AddValue(\n GL_COMPRESSED_SRGB_S3TC_DXT1_EXT);\n validators_.compressed_texture_format.AddValue(\n GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT);\n validators_.compressed_texture_format.AddValue(\n GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT);\n validators_.compressed_texture_format.AddValue(\n GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT);\n\n validators_.texture_internal_format_storage.AddValue(\n GL_COMPRESSED_SRGB_S3TC_DXT1_EXT);\n validators_.texture_internal_format_storage.AddValue(\n GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT);\n validators_.texture_internal_format_storage.AddValue(\n GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT);\n validators_.texture_internal_format_storage.AddValue(\n GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT);\n }\n\n bool has_apple_bgra =\n gfx::HasExtension(extensions, \"GL_APPLE_texture_format_BGRA8888\");\n bool has_ext_bgra =\n gfx::HasExtension(extensions, \"GL_EXT_texture_format_BGRA8888\");\n bool enable_texture_format_bgra8888 =\n has_ext_bgra || has_apple_bgra || !gl_version_info_->is_es;\n\n bool has_ext_texture_storage =\n gfx::HasExtension(extensions, \"GL_EXT_texture_storage\");\n bool has_arb_texture_storage =\n gfx::HasExtension(extensions, \"GL_ARB_texture_storage\");\n bool has_texture_storage =\n !workarounds_.disable_texture_storage &&\n (has_ext_texture_storage || has_arb_texture_storage ||\n gl_version_info_->is_es3 || gl_version_info_->IsAtLeastGL(4, 2));\n\n bool enable_texture_storage = has_texture_storage;\n\n bool texture_storage_incompatible_with_bgra =\n gl_version_info_->is_es3 && !has_ext_texture_storage && !has_apple_bgra;\n if (texture_storage_incompatible_with_bgra &&\n enable_texture_format_bgra8888 && enable_texture_storage) {\n switch (context_type_) {\n case CONTEXT_TYPE_OPENGLES2:\n enable_texture_storage = false;\n break;\n case CONTEXT_TYPE_OPENGLES3:\n enable_texture_format_bgra8888 = false;\n break;\n case CONTEXT_TYPE_WEBGL1:\n case CONTEXT_TYPE_WEBGL2:\n case CONTEXT_TYPE_WEBGL2_COMPUTE:\n case CONTEXT_TYPE_WEBGPU:\n break;\n }\n }\n\n if (enable_texture_storage) {\n feature_flags_.ext_texture_storage = true;\n AddExtensionString(\"GL_EXT_texture_storage\");\n validators_.texture_parameter.AddValue(GL_TEXTURE_IMMUTABLE_FORMAT_EXT);\n }\n\n if (enable_texture_format_bgra8888) {\n feature_flags_.ext_texture_format_bgra8888 = true;\n AddExtensionString(\"GL_EXT_texture_format_BGRA8888\");\n validators_.texture_internal_format.AddValue(GL_BGRA_EXT);\n validators_.texture_format.AddValue(GL_BGRA_EXT);\n validators_.texture_unsized_internal_format.AddValue(GL_BGRA_EXT);\n validators_.texture_internal_format_storage.AddValue(GL_BGRA8_EXT);\n validators_.texture_sized_color_renderable_internal_format.AddValue(\n GL_BGRA8_EXT);\n validators_.texture_sized_texture_filterable_internal_format.AddValue(\n GL_BGRA8_EXT);\n feature_flags_.gpu_memory_buffer_formats.Add(gfx::BufferFormat::BGRA_8888);\n feature_flags_.gpu_memory_buffer_formats.Add(gfx::BufferFormat::BGRX_8888);\n }\n\n bool enable_render_buffer_bgra =\n gl_version_info_->is_angle || !gl_version_info_->is_es;\n\n if (enable_render_buffer_bgra) {\n feature_flags_.ext_render_buffer_format_bgra8888 = true;\n AddExtensionString(\"GL_CHROMIUM_renderbuffer_format_BGRA8888\");\n validators_.render_buffer_format.AddValue(GL_BGRA8_EXT);\n }\n\n bool enable_read_format_bgra =\n gfx::HasExtension(extensions, \"GL_EXT_read_format_bgra\") ||\n !gl_version_info_->is_es;\n\n if (enable_read_format_bgra) {\n feature_flags_.ext_read_format_bgra = true;\n AddExtensionString(\"GL_EXT_read_format_bgra\");\n validators_.read_pixel_format.AddValue(GL_BGRA_EXT);\n }\n\n feature_flags_.arb_es3_compatibility =\n gfx::HasExtension(extensions, \"GL_ARB_ES3_compatibility\") &&\n !gl_version_info_->is_es;\n\n feature_flags_.ext_disjoint_timer_query =\n gfx::HasExtension(extensions, \"GL_EXT_disjoint_timer_query\");\n if (feature_flags_.ext_disjoint_timer_query ||\n gfx::HasExtension(extensions, \"GL_ARB_timer_query\") ||\n gfx::HasExtension(extensions, \"GL_EXT_timer_query\")) {\n AddExtensionString(\"GL_EXT_disjoint_timer_query\");\n }\n\n if (gfx::HasExtension(extensions, \"GL_OES_rgb8_rgba8\") ||\n gl::HasDesktopGLFeatures()) {\n AddExtensionString(\"GL_OES_rgb8_rgba8\");\n validators_.render_buffer_format.AddValue(GL_RGB8_OES);\n validators_.render_buffer_format.AddValue(GL_RGBA8_OES);\n }\n\n if (!disallowed_features_.npot_support &&\n (gl_version_info_->is_es3 || gl_version_info_->is_desktop_core_profile ||\n gfx::HasExtension(extensions, \"GL_ARB_texture_non_power_of_two\") ||\n gfx::HasExtension(extensions, \"GL_OES_texture_npot\"))) {\n AddExtensionString(\"GL_OES_texture_npot\");\n feature_flags_.npot_ok = true;\n }\n\n InitializeFloatAndHalfFloatFeatures(extensions);\n\n if (!workarounds_.disable_chromium_framebuffer_multisample) {\n bool ext_has_multisample =\n gfx::HasExtension(extensions, \"GL_ARB_framebuffer_object\") ||\n (gfx::HasExtension(extensions, \"GL_EXT_framebuffer_multisample\") &&\n gfx::HasExtension(extensions, \"GL_EXT_framebuffer_blit\")) ||\n gl_version_info_->is_es3 || gl_version_info_->is_desktop_core_profile;\n if (gl_version_info_->is_angle || gl_version_info_->is_swiftshader) {\n ext_has_multisample |=\n gfx::HasExtension(extensions, \"GL_ANGLE_framebuffer_multisample\");\n }\n if (ext_has_multisample) {\n feature_flags_.chromium_framebuffer_multisample = true;\n validators_.framebuffer_target.AddValue(GL_READ_FRAMEBUFFER_EXT);\n validators_.framebuffer_target.AddValue(GL_DRAW_FRAMEBUFFER_EXT);\n validators_.g_l_state.AddValue(GL_READ_FRAMEBUFFER_BINDING_EXT);\n validators_.g_l_state.AddValue(GL_MAX_SAMPLES_EXT);\n validators_.render_buffer_parameter.AddValue(GL_RENDERBUFFER_SAMPLES_EXT);\n AddExtensionString(\"GL_CHROMIUM_framebuffer_multisample\");\n }\n }\n\n if (gfx::HasExtension(extensions, \"GL_EXT_multisampled_render_to_texture\")) {\n feature_flags_.multisampled_render_to_texture = true;\n } else if (gfx::HasExtension(extensions,\n \"GL_IMG_multisampled_render_to_texture\")) {\n feature_flags_.multisampled_render_to_texture = true;\n feature_flags_.use_img_for_multisampled_render_to_texture = true;\n }\n if (feature_flags_.multisampled_render_to_texture) {\n validators_.render_buffer_parameter.AddValue(GL_RENDERBUFFER_SAMPLES_EXT);\n validators_.g_l_state.AddValue(GL_MAX_SAMPLES_EXT);\n validators_.framebuffer_attachment_parameter.AddValue(\n GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_SAMPLES_EXT);\n AddExtensionString(\"GL_EXT_multisampled_render_to_texture\");\n }\n\n if (!gl_version_info_->is_es ||\n gfx::HasExtension(extensions, \"GL_EXT_multisample_compatibility\")) {\n AddExtensionString(\"GL_EXT_multisample_compatibility\");\n feature_flags_.ext_multisample_compatibility = true;\n validators_.capability.AddValue(GL_MULTISAMPLE_EXT);\n validators_.capability.AddValue(GL_SAMPLE_ALPHA_TO_ONE_EXT);\n }\n\n if (gfx::HasExtension(extensions, \"GL_INTEL_framebuffer_CMAA\")) {\n feature_flags_.chromium_screen_space_antialiasing = true;\n AddExtensionString(\"GL_CHROMIUM_screen_space_antialiasing\");\n } else if (gl_version_info_->IsAtLeastGLES(3, 1) ||\n (gl_version_info_->IsAtLeastGL(3, 0) &&\n gfx::HasExtension(extensions,\n \"GL_ARB_shading_language_420pack\") &&\n gfx::HasExtension(extensions, \"GL_ARB_texture_storage\") &&\n gfx::HasExtension(extensions, \"GL_ARB_texture_gather\") &&\n gfx::HasExtension(extensions,\n \"GL_ARB_explicit_uniform_location\") &&\n gfx::HasExtension(extensions,\n \"GL_ARB_explicit_attrib_location\") &&\n gfx::HasExtension(extensions,\n \"GL_ARB_shader_image_load_store\"))) {\n feature_flags_.chromium_screen_space_antialiasing = true;\n feature_flags_.use_chromium_screen_space_antialiasing_via_shaders = true;\n AddExtensionString(\"GL_CHROMIUM_screen_space_antialiasing\");\n }\n\n if (gfx::HasExtension(extensions, \"GL_OES_depth24\") ||\n gl::HasDesktopGLFeatures() || gl_version_info_->is_es3) {\n AddExtensionString(\"GL_OES_depth24\");\n feature_flags_.oes_depth24 = true;\n validators_.render_buffer_format.AddValue(GL_DEPTH_COMPONENT24);\n }\n\n if (gl_version_info_->is_es3 ||\n gfx::HasExtension(extensions, \"GL_OES_standard_derivatives\") ||\n gl::HasDesktopGLFeatures()) {\n AddExtensionString(\"GL_OES_standard_derivatives\");\n feature_flags_.oes_standard_derivatives = true;\n validators_.hint_target.AddValue(GL_FRAGMENT_SHADER_DERIVATIVE_HINT_OES);\n validators_.g_l_state.AddValue(GL_FRAGMENT_SHADER_DERIVATIVE_HINT_OES);\n }\n\n if (gfx::HasExtension(extensions, \"GL_CHROMIUM_texture_filtering_hint\")) {\n AddExtensionString(\"GL_CHROMIUM_texture_filtering_hint\");\n feature_flags_.chromium_texture_filtering_hint = true;\n validators_.hint_target.AddValue(GL_TEXTURE_FILTERING_HINT_CHROMIUM);\n validators_.g_l_state.AddValue(GL_TEXTURE_FILTERING_HINT_CHROMIUM);\n }\n\n if (gfx::HasExtension(extensions, \"GL_OES_EGL_image_external\")) {\n AddExtensionString(\"GL_OES_EGL_image_external\");\n feature_flags_.oes_egl_image_external = true;\n }\n if (gfx::HasExtension(extensions, \"GL_NV_EGL_stream_consumer_external\")) {\n AddExtensionString(\"GL_NV_EGL_stream_consumer_external\");\n feature_flags_.nv_egl_stream_consumer_external = true;\n }\n\n if (feature_flags_.oes_egl_image_external ||\n feature_flags_.nv_egl_stream_consumer_external) {\n validators_.texture_bind_target.AddValue(GL_TEXTURE_EXTERNAL_OES);\n validators_.get_tex_param_target.AddValue(GL_TEXTURE_EXTERNAL_OES);\n validators_.texture_parameter.AddValue(GL_REQUIRED_TEXTURE_IMAGE_UNITS_OES);\n validators_.g_l_state.AddValue(GL_TEXTURE_BINDING_EXTERNAL_OES);\n }\n\n if (gfx::HasExtension(extensions, \"GL_OES_compressed_ETC1_RGB8_texture\")) {\n AddExtensionString(\"GL_OES_compressed_ETC1_RGB8_texture\");\n feature_flags_.oes_compressed_etc1_rgb8_texture = true;\n validators_.compressed_texture_format.AddValue(GL_ETC1_RGB8_OES);\n validators_.texture_internal_format_storage.AddValue(GL_ETC1_RGB8_OES);\n }\n\n if (gfx::HasExtension(extensions, \"GL_CHROMIUM_compressed_texture_etc\") ||\n (gl_version_info_->is_es3 && !gl_version_info_->is_angle)) {\n AddExtensionString(\"GL_CHROMIUM_compressed_texture_etc\");\n validators_.UpdateETCCompressedTextureFormats();\n }\n\n if (gfx::HasExtension(extensions, \"GL_AMD_compressed_ATC_texture\")) {\n AddExtensionString(\"GL_AMD_compressed_ATC_texture\");\n validators_.compressed_texture_format.AddValue(GL_ATC_RGB_AMD);\n validators_.compressed_texture_format.AddValue(\n GL_ATC_RGBA_EXPLICIT_ALPHA_AMD);\n validators_.compressed_texture_format.AddValue(\n GL_ATC_RGBA_INTERPOLATED_ALPHA_AMD);\n\n validators_.texture_internal_format_storage.AddValue(GL_ATC_RGB_AMD);\n validators_.texture_internal_format_storage.AddValue(\n GL_ATC_RGBA_EXPLICIT_ALPHA_AMD);\n validators_.texture_internal_format_storage.AddValue(\n GL_ATC_RGBA_INTERPOLATED_ALPHA_AMD);\n }\n\n if (gfx::HasExtension(extensions, \"GL_IMG_texture_compression_pvrtc\")) {\n AddExtensionString(\"GL_IMG_texture_compression_pvrtc\");\n validators_.compressed_texture_format.AddValue(\n GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG);\n validators_.compressed_texture_format.AddValue(\n GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG);\n validators_.compressed_texture_format.AddValue(\n GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG);\n validators_.compressed_texture_format.AddValue(\n GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG);\n\n validators_.texture_internal_format_storage.AddValue(\n GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG);\n validators_.texture_internal_format_storage.AddValue(\n GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG);\n validators_.texture_internal_format_storage.AddValue(\n GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG);\n validators_.texture_internal_format_storage.AddValue(\n GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG);\n }\n\n if (gfx::HasExtension(extensions, \"GL_ARB_texture_rectangle\") ||\n gfx::HasExtension(extensions, \"GL_ANGLE_texture_rectangle\") ||\n gl_version_info_->is_desktop_core_profile) {\n AddExtensionString(\"GL_ARB_texture_rectangle\");\n feature_flags_.arb_texture_rectangle = true;\n validators_.texture_bind_target.AddValue(GL_TEXTURE_RECTANGLE_ARB);\n validators_.texture_target.AddValue(GL_TEXTURE_RECTANGLE_ARB);\n validators_.get_tex_param_target.AddValue(GL_TEXTURE_RECTANGLE_ARB);\n validators_.g_l_state.AddValue(GL_TEXTURE_BINDING_RECTANGLE_ARB);\n }\n\n if (feature_flags_.chromium_image_ycbcr_420v) {\n AddExtensionString(\"GL_CHROMIUM_ycbcr_420v_image\");\n feature_flags_.gpu_memory_buffer_formats.Add(\n gfx::BufferFormat::YUV_420_BIPLANAR);\n }\n\n#if defined(OS_MACOSX)\n feature_flags_.chromium_image_xr30 = base::mac::IsAtLeastOS10_13();\n#elif !defined(OS_WIN)\n feature_flags_.chromium_image_xb30 =\n gl_version_info_->IsAtLeastGL(3, 3) ||\n gl_version_info_->IsAtLeastGLES(3, 0) ||\n gfx::HasExtension(extensions, \"GL_EXT_texture_type_2_10_10_10_REV\");\n#endif\n if (feature_flags_.chromium_image_xr30 ||\n feature_flags_.chromium_image_xb30) {\n validators_.texture_internal_format.AddValue(GL_RGB10_A2_EXT);\n validators_.render_buffer_format.AddValue(GL_RGB10_A2_EXT);\n validators_.texture_internal_format_storage.AddValue(GL_RGB10_A2_EXT);\n validators_.pixel_type.AddValue(GL_UNSIGNED_INT_2_10_10_10_REV);\n }\n if (feature_flags_.chromium_image_xr30) {\n feature_flags_.gpu_memory_buffer_formats.Add(\n gfx::BufferFormat::BGRX_1010102);\n }\n if (feature_flags_.chromium_image_xb30) {\n feature_flags_.gpu_memory_buffer_formats.Add(\n gfx::BufferFormat::RGBX_1010102);\n }\n\n if (feature_flags_.chromium_image_ycbcr_p010) {\n AddExtensionString(\"GL_CHROMIUM_ycbcr_p010_image\");\n feature_flags_.gpu_memory_buffer_formats.Add(gfx::BufferFormat::P010);\n }\n\n\n if (gfx::HasExtension(extensions, \"GL_ANGLE_texture_usage\")) {\n feature_flags_.angle_texture_usage = true;\n AddExtensionString(\"GL_ANGLE_texture_usage\");\n validators_.texture_parameter.AddValue(GL_TEXTURE_USAGE_ANGLE);\n }\n\n bool have_occlusion_query = gl_version_info_->IsAtLeastGLES(3, 0) ||\n gl_version_info_->IsAtLeastGL(3, 3);\n bool have_ext_occlusion_query_boolean =\n gfx::HasExtension(extensions, \"GL_EXT_occlusion_query_boolean\");\n bool have_arb_occlusion_query2 =\n gfx::HasExtension(extensions, \"GL_ARB_occlusion_query2\");\n bool have_arb_occlusion_query =\n (gl_version_info_->is_desktop_core_profile &&\n gl_version_info_->IsAtLeastGL(1, 5)) ||\n gfx::HasExtension(extensions, \"GL_ARB_occlusion_query\");\n\n if (have_occlusion_query || have_ext_occlusion_query_boolean ||\n have_arb_occlusion_query2 || have_arb_occlusion_query) {\n feature_flags_.occlusion_query = have_arb_occlusion_query;\n if (context_type_ == CONTEXT_TYPE_OPENGLES2) {\n AddExtensionString(\"GL_EXT_occlusion_query_boolean\");\n }\n feature_flags_.occlusion_query_boolean = true;\n feature_flags_.use_arb_occlusion_query2_for_occlusion_query_boolean =\n !have_ext_occlusion_query_boolean &&\n (have_arb_occlusion_query2 || (gl_version_info_->IsAtLeastGL(3, 3) &&\n gl_version_info_->IsLowerThanGL(4, 3)));\n feature_flags_.use_arb_occlusion_query_for_occlusion_query_boolean =\n !have_ext_occlusion_query_boolean && have_arb_occlusion_query &&\n !have_arb_occlusion_query2;\n }\n\n if (gfx::HasExtension(extensions, \"GL_ANGLE_instanced_arrays\") ||\n (gfx::HasExtension(extensions, \"GL_ARB_instanced_arrays\") &&\n gfx::HasExtension(extensions, \"GL_ARB_draw_instanced\")) ||\n gl_version_info_->is_es3 || gl_version_info_->is_desktop_core_profile) {\n AddExtensionString(\"GL_ANGLE_instanced_arrays\");\n feature_flags_.angle_instanced_arrays = true;\n validators_.vertex_attribute.AddValue(GL_VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE);\n }\n\n bool have_es2_draw_buffers_vendor_agnostic =\n gl_version_info_->is_desktop_core_profile ||\n gfx::HasExtension(extensions, \"GL_ARB_draw_buffers\") ||\n gfx::HasExtension(extensions, \"GL_EXT_draw_buffers\");\n bool can_emulate_es2_draw_buffers_on_es3_nv =\n gl_version_info_->is_es3 &&\n gfx::HasExtension(extensions, \"GL_NV_draw_buffers\");\n bool is_webgl_compatibility_context =\n gfx::HasExtension(extensions, \"GL_ANGLE_webgl_compatibility\");\n bool have_es2_draw_buffers =\n !workarounds_.disable_ext_draw_buffers &&\n (have_es2_draw_buffers_vendor_agnostic ||\n can_emulate_es2_draw_buffers_on_es3_nv) &&\n (context_type_ == CONTEXT_TYPE_OPENGLES2 ||\n (context_type_ == CONTEXT_TYPE_WEBGL1 &&\n IsWebGLDrawBuffersSupported(is_webgl_compatibility_context,\n depth_texture_format,\n depth_stencil_texture_format)));\n if (have_es2_draw_buffers) {\n AddExtensionString(\"GL_EXT_draw_buffers\");\n feature_flags_.ext_draw_buffers = true;\n\n feature_flags_.nv_draw_buffers = can_emulate_es2_draw_buffers_on_es3_nv &&\n !have_es2_draw_buffers_vendor_agnostic;\n }\n\n if (IsWebGL2OrES3OrHigherContext() || have_es2_draw_buffers) {\n GLint max_color_attachments = 0;\n glGetIntegerv(GL_MAX_COLOR_ATTACHMENTS_EXT, &max_color_attachments);\n for (GLenum i = GL_COLOR_ATTACHMENT1_EXT;\n i < static_cast(GL_COLOR_ATTACHMENT0 + max_color_attachments);\n ++i) {\n validators_.attachment.AddValue(i);\n validators_.attachment_query.AddValue(i);\n }\n static_assert(GL_COLOR_ATTACHMENT0_EXT == GL_COLOR_ATTACHMENT0,\n \"GL_COLOR_ATTACHMENT0_EXT should equal GL_COLOR_ATTACHMENT0\");\n\n validators_.g_l_state.AddValue(GL_MAX_COLOR_ATTACHMENTS_EXT);\n validators_.g_l_state.AddValue(GL_MAX_DRAW_BUFFERS_ARB);\n GLint max_draw_buffers = 0;\n glGetIntegerv(GL_MAX_DRAW_BUFFERS_ARB, &max_draw_buffers);\n for (GLenum i = GL_DRAW_BUFFER0_ARB;\n i < static_cast(GL_DRAW_BUFFER0_ARB + max_draw_buffers); ++i) {\n validators_.g_l_state.AddValue(i);\n }\n }\n\n if (gl_version_info_->is_es3 ||\n gfx::HasExtension(extensions, \"GL_EXT_blend_minmax\") ||\n gl::HasDesktopGLFeatures()) {\n AddExtensionString(\"GL_EXT_blend_minmax\");\n validators_.equation.AddValue(GL_MIN_EXT);\n validators_.equation.AddValue(GL_MAX_EXT);\n static_assert(GL_MIN_EXT == GL_MIN && GL_MAX_EXT == GL_MAX,\n \"min & max variations must match\");\n }\n\n if (gfx::HasExtension(extensions, \"GL_EXT_frag_depth\") ||\n gl::HasDesktopGLFeatures()) {\n AddExtensionString(\"GL_EXT_frag_depth\");\n feature_flags_.ext_frag_depth = true;\n }\n\n if (gfx::HasExtension(extensions, \"GL_EXT_shader_texture_lod\") ||\n gl::HasDesktopGLFeatures()) {\n AddExtensionString(\"GL_EXT_shader_texture_lod\");\n feature_flags_.ext_shader_texture_lod = true;\n }\n\n bool ui_gl_fence_works = gl::GLFence::IsSupported();\n UMA_HISTOGRAM_BOOLEAN(\"GPU.FenceSupport\", ui_gl_fence_works);\n\n feature_flags_.map_buffer_range =\n gl_version_info_->is_es3 || gl_version_info_->is_desktop_core_profile ||\n gfx::HasExtension(extensions, \"GL_ARB_map_buffer_range\") ||\n gfx::HasExtension(extensions, \"GL_EXT_map_buffer_range\");\n\n if (has_pixel_buffers && ui_gl_fence_works &&\n !workarounds_.disable_async_readpixels) {\n feature_flags_.use_async_readpixels = true;\n }\n\n if (gl_version_info_->is_es3 ||\n gfx::HasExtension(extensions, \"GL_ARB_sampler_objects\")) {\n feature_flags_.enable_samplers = true;\n }\n\n if ((gl_version_info_->is_es3 ||\n gfx::HasExtension(extensions, \"GL_EXT_discard_framebuffer\")) &&\n !workarounds_.disable_discard_framebuffer) {\n AddExtensionString(\"GL_EXT_discard_framebuffer\");\n feature_flags_.ext_discard_framebuffer = true;\n }\n\n if (ui_gl_fence_works) {\n AddExtensionString(\"GL_CHROMIUM_sync_query\");\n feature_flags_.chromium_sync_query = true;\n }\n\n if (!workarounds_.disable_blend_equation_advanced) {\n bool blend_equation_advanced_coherent =\n gfx::HasExtension(extensions,\n \"GL_NV_blend_equation_advanced_coherent\") ||\n gfx::HasExtension(extensions,\n \"GL_KHR_blend_equation_advanced_coherent\");\n\n if (blend_equation_advanced_coherent ||\n gfx::HasExtension(extensions, \"GL_NV_blend_equation_advanced\") ||\n gfx::HasExtension(extensions, \"GL_KHR_blend_equation_advanced\")) {\n const GLenum equations[] = {\n GL_MULTIPLY_KHR, GL_SCREEN_KHR, GL_OVERLAY_KHR,\n GL_DARKEN_KHR, GL_LIGHTEN_KHR, GL_COLORDODGE_KHR,\n GL_COLORBURN_KHR, GL_HARDLIGHT_KHR, GL_SOFTLIGHT_KHR,\n GL_DIFFERENCE_KHR, GL_EXCLUSION_KHR, GL_HSL_HUE_KHR,\n GL_HSL_SATURATION_KHR, GL_HSL_COLOR_KHR, GL_HSL_LUMINOSITY_KHR};\n\n for (GLenum equation : equations)\n validators_.equation.AddValue(equation);\n if (blend_equation_advanced_coherent)\n AddExtensionString(\"GL_KHR_blend_equation_advanced_coherent\");\n\n AddExtensionString(\"GL_KHR_blend_equation_advanced\");\n feature_flags_.blend_equation_advanced = true;\n feature_flags_.blend_equation_advanced_coherent =\n blend_equation_advanced_coherent;\n }\n }\n\n if (gfx::HasExtension(extensions, \"GL_NV_framebuffer_mixed_samples\")) {\n AddExtensionString(\"GL_CHROMIUM_framebuffer_mixed_samples\");\n feature_flags_.chromium_framebuffer_mixed_samples = true;\n validators_.g_l_state.AddValue(GL_COVERAGE_MODULATION_CHROMIUM);\n }\n\n if (gfx::HasExtension(extensions, \"GL_NV_path_rendering\")) {\n bool has_dsa = gl_version_info_->IsAtLeastGL(4, 5) ||\n gfx::HasExtension(extensions, \"GL_EXT_direct_state_access\");\n bool has_piq =\n gl_version_info_->IsAtLeastGL(4, 3) ||\n gfx::HasExtension(extensions, \"GL_ARB_program_interface_query\");\n bool has_fms = feature_flags_.chromium_framebuffer_mixed_samples;\n if ((gl_version_info_->IsAtLeastGLES(3, 1) ||\n (gl_version_info_->IsAtLeastGL(3, 2) && has_dsa && has_piq)) &&\n has_fms) {\n AddExtensionString(\"GL_CHROMIUM_path_rendering\");\n feature_flags_.chromium_path_rendering = true;\n validators_.g_l_state.AddValue(GL_PATH_MODELVIEW_MATRIX_CHROMIUM);\n validators_.g_l_state.AddValue(GL_PATH_PROJECTION_MATRIX_CHROMIUM);\n validators_.g_l_state.AddValue(GL_PATH_STENCIL_FUNC_CHROMIUM);\n validators_.g_l_state.AddValue(GL_PATH_STENCIL_REF_CHROMIUM);\n validators_.g_l_state.AddValue(GL_PATH_STENCIL_VALUE_MASK_CHROMIUM);\n }\n }\n\n if ((gl_version_info_->is_es3 || gl_version_info_->is_desktop_core_profile ||\n gfx::HasExtension(extensions, \"GL_EXT_texture_rg\") ||\n gfx::HasExtension(extensions, \"GL_ARB_texture_rg\")) &&\n IsGL_REDSupportedOnFBOs()) {\n feature_flags_.ext_texture_rg = true;\n AddExtensionString(\"GL_EXT_texture_rg\");\n\n validators_.texture_format.AddValue(GL_RED_EXT);\n validators_.texture_format.AddValue(GL_RG_EXT);\n\n validators_.texture_internal_format.AddValue(GL_RED_EXT);\n validators_.texture_internal_format.AddValue(GL_R8_EXT);\n validators_.texture_internal_format.AddValue(GL_RG_EXT);\n validators_.texture_internal_format.AddValue(GL_RG8_EXT);\n\n validators_.read_pixel_format.AddValue(GL_RED_EXT);\n validators_.read_pixel_format.AddValue(GL_RG_EXT);\n\n validators_.render_buffer_format.AddValue(GL_R8_EXT);\n validators_.render_buffer_format.AddValue(GL_RG8_EXT);\n\n validators_.texture_unsized_internal_format.AddValue(GL_RED_EXT);\n validators_.texture_unsized_internal_format.AddValue(GL_RG_EXT);\n\n validators_.texture_internal_format_storage.AddValue(GL_R8_EXT);\n validators_.texture_internal_format_storage.AddValue(GL_RG8_EXT);\n\n feature_flags_.gpu_memory_buffer_formats.Add(gfx::BufferFormat::R_8);\n feature_flags_.gpu_memory_buffer_formats.Add(gfx::BufferFormat::RG_88);\n }\n UMA_HISTOGRAM_BOOLEAN(\"GPU.TextureRG\", feature_flags_.ext_texture_rg);\n\n if (gl_version_info_->is_desktop_core_profile ||\n (gl_version_info_->IsAtLeastGL(2, 1) &&\n gfx::HasExtension(extensions, \"GL_ARB_texture_rg\")) ||\n gfx::HasExtension(extensions, \"GL_EXT_texture_norm16\")) {\n feature_flags_.ext_texture_norm16 = true;\n g_r16_is_present = true;\n\n validators_.pixel_type.AddValue(GL_UNSIGNED_SHORT);\n validators_.texture_format.AddValue(GL_RED_EXT);\n validators_.texture_internal_format.AddValue(GL_R16_EXT);\n validators_.texture_internal_format.AddValue(GL_RED_EXT);\n validators_.texture_unsized_internal_format.AddValue(GL_RED_EXT);\n validators_.texture_internal_format_storage.AddValue(GL_R16_EXT);\n\n feature_flags_.gpu_memory_buffer_formats.Add(gfx::BufferFormat::R_16);\n }\n\n UMA_HISTOGRAM_ENUMERATION(\n \"GPU.TextureR16Ext_LuminanceF16\", GpuTextureUMAHelper(),\n static_cast(GpuTextureResultR16_L16::kMax) + 1);\n\n if (enable_es3 && gfx::HasExtension(extensions, \"GL_EXT_window_rectangles\")) {\n AddExtensionString(\"GL_EXT_window_rectangles\");\n feature_flags_.ext_window_rectangles = true;\n validators_.g_l_state.AddValue(GL_WINDOW_RECTANGLE_MODE_EXT);\n validators_.g_l_state.AddValue(GL_MAX_WINDOW_RECTANGLES_EXT);\n validators_.g_l_state.AddValue(GL_NUM_WINDOW_RECTANGLES_EXT);\n validators_.indexed_g_l_state.AddValue(GL_WINDOW_RECTANGLE_EXT);\n }\n\n bool has_opengl_dual_source_blending =\n gl_version_info_->IsAtLeastGL(3, 3) ||\n (gl_version_info_->IsAtLeastGL(3, 2) &&\n gfx::HasExtension(extensions, \"GL_ARB_blend_func_extended\"));\n if (!disable_shader_translator_ && !workarounds_.get_frag_data_info_bug &&\n ((gl_version_info_->IsAtLeastGL(3, 2) &&\n has_opengl_dual_source_blending) ||\n (gl_version_info_->IsAtLeastGLES(3, 0) &&\n gfx::HasExtension(extensions, \"GL_EXT_blend_func_extended\")))) {\n feature_flags_.ext_blend_func_extended = true;\n AddExtensionString(\"GL_EXT_blend_func_extended\");\n\n validators_.dst_blend_factor.AddValue(GL_SRC_ALPHA_SATURATE_EXT);\n\n validators_.src_blend_factor.AddValue(GL_SRC1_ALPHA_EXT);\n validators_.dst_blend_factor.AddValue(GL_SRC1_ALPHA_EXT);\n validators_.src_blend_factor.AddValue(GL_SRC1_COLOR_EXT);\n validators_.dst_blend_factor.AddValue(GL_SRC1_COLOR_EXT);\n validators_.src_blend_factor.AddValue(GL_ONE_MINUS_SRC1_COLOR_EXT);\n validators_.dst_blend_factor.AddValue(GL_ONE_MINUS_SRC1_COLOR_EXT);\n validators_.src_blend_factor.AddValue(GL_ONE_MINUS_SRC1_ALPHA_EXT);\n validators_.dst_blend_factor.AddValue(GL_ONE_MINUS_SRC1_ALPHA_EXT);\n validators_.g_l_state.AddValue(GL_MAX_DUAL_SOURCE_DRAW_BUFFERS_EXT);\n }\n\n#if !defined(OS_MACOSX)\n if (workarounds_.ignore_egl_sync_failures) {\n gl::GLFenceEGL::SetIgnoreFailures();\n }\n#endif\n\n if (workarounds_.avoid_egl_image_target_texture_reuse) {\n TextureDefinition::AvoidEGLTargetTextureReuse();\n }\n\n if (gl_version_info_->IsLowerThanGL(4, 3)) {\n feature_flags_.emulate_primitive_restart_fixed_index = true;\n }\n\n feature_flags_.angle_robust_client_memory =\n gfx::HasExtension(extensions, \"GL_ANGLE_robust_client_memory\");\n\n feature_flags_.khr_debug = gl_version_info_->IsAtLeastGL(4, 3) ||\n gl_version_info_->IsAtLeastGLES(3, 2) ||\n gfx::HasExtension(extensions, \"GL_KHR_debug\");\n\n feature_flags_.chromium_gpu_fence = gl::GLFence::IsGpuFenceSupported();\n if (feature_flags_.chromium_gpu_fence)\n AddExtensionString(\"GL_CHROMIUM_gpu_fence\");\n\n feature_flags_.chromium_bind_generates_resource =\n gfx::HasExtension(extensions, \"GL_CHROMIUM_bind_generates_resource\");\n feature_flags_.angle_webgl_compatibility = is_webgl_compatibility_context;\n feature_flags_.chromium_copy_texture =\n gfx::HasExtension(extensions, \"GL_CHROMIUM_copy_texture\");\n feature_flags_.chromium_copy_compressed_texture =\n gfx::HasExtension(extensions, \"GL_CHROMIUM_copy_compressed_texture\");\n feature_flags_.angle_client_arrays =\n gfx::HasExtension(extensions, \"GL_ANGLE_client_arrays\");\n feature_flags_.angle_request_extension =\n gfx::HasExtension(extensions, \"GL_ANGLE_request_extension\");\n feature_flags_.ext_debug_marker =\n gfx::HasExtension(extensions, \"GL_EXT_debug_marker\");\n feature_flags_.ext_pixel_buffer_object =\n gfx::HasExtension(extensions, \"GL_ARB_pixel_buffer_object\") ||\n gfx::HasExtension(extensions, \"GL_NV_pixel_buffer_object\");\n feature_flags_.ext_unpack_subimage =\n gfx::HasExtension(extensions, \"GL_EXT_unpack_subimage\");\n feature_flags_.oes_rgb8_rgba8 =\n gfx::HasExtension(extensions, \"GL_OES_rgb8_rgba8\");\n feature_flags_.angle_robust_resource_initialization =\n gfx::HasExtension(extensions, \"GL_ANGLE_robust_resource_initialization\");\n feature_flags_.nv_fence = gfx::HasExtension(extensions, \"GL_NV_fence\");\n\n feature_flags_.unpremultiply_and_dither_copy = !is_passthrough_cmd_decoder_;\n if (feature_flags_.unpremultiply_and_dither_copy)\n AddExtensionString(\"GL_CHROMIUM_unpremultiply_and_dither_copy\");\n\n feature_flags_.separate_stencil_ref_mask_writemask =\n !(gl_version_info_->is_d3d) && !IsWebGLContext();\n\n if (gfx::HasExtension(extensions, \"GL_MESA_framebuffer_flip_y\")) {\n feature_flags_.mesa_framebuffer_flip_y = true;\n validators_.framebuffer_parameter.AddValue(GL_FRAMEBUFFER_FLIP_Y_MESA);\n AddExtensionString(\"GL_MESA_framebuffer_flip_y\");\n }\n\n if (is_passthrough_cmd_decoder_ &&\n gfx::HasExtension(extensions, \"GL_OVR_multiview2\")) {\n AddExtensionString(\"GL_OVR_multiview2\");\n feature_flags_.ovr_multiview2 = true;\n }\n\n if (is_passthrough_cmd_decoder_ &&\n gfx::HasExtension(extensions, \"GL_KHR_parallel_shader_compile\")) {\n AddExtensionString(\"GL_KHR_parallel_shader_compile\");\n feature_flags_.khr_parallel_shader_compile = true;\n validators_.g_l_state.AddValue(GL_MAX_SHADER_COMPILER_THREADS_KHR);\n validators_.shader_parameter.AddValue(GL_COMPLETION_STATUS_KHR);\n validators_.program_parameter.AddValue(GL_COMPLETION_STATUS_KHR);\n\n AddExtensionString(\"GL_CHROMIUM_completion_query\");\n feature_flags_.chromium_completion_query = true;\n }\n\n if (gfx::HasExtension(extensions, \"GL_KHR_robust_buffer_access_behavior\")) {\n AddExtensionString(\"GL_KHR_robust_buffer_access_behavior\");\n feature_flags_.khr_robust_buffer_access_behavior = true;\n }\n\n if (!is_passthrough_cmd_decoder_ ||\n gfx::HasExtension(extensions, \"GL_ANGLE_multi_draw\")) {\n feature_flags_.webgl_multi_draw = true;\n AddExtensionString(\"GL_WEBGL_multi_draw\");\n\n if (gfx::HasExtension(extensions, \"GL_ANGLE_instanced_arrays\") ||\n feature_flags_.angle_instanced_arrays || gl_version_info_->is_es3 ||\n gl_version_info_->is_desktop_core_profile) {\n feature_flags_.webgl_multi_draw_instanced = true;\n AddExtensionString(\"GL_WEBGL_multi_draw_instanced\");\n }\n }\n\n if (gfx::HasExtension(extensions, \"GL_NV_internalformat_sample_query\")) {\n feature_flags_.nv_internalformat_sample_query = true;\n }\n\n if (gfx::HasExtension(extensions,\n \"GL_AMD_framebuffer_multisample_advanced\")) {\n feature_flags_.amd_framebuffer_multisample_advanced = true;\n AddExtensionString(\"GL_AMD_framebuffer_multisample_advanced\");\n }\n}\n", + "line": null, + "label": 0, + "cwe": "CWE-125", + "cve": "CVE-2017-5057", + "length": 10448 + }, + { + "index": 50572, + "code": "int __generic_block_fiemap(struct inode *inode,\n\t\t\t struct fiemap_extent_info *fieinfo, loff_t start,\n\t\t\t loff_t len, get_block_t *get_block)\n{\n\tstruct buffer_head map_bh;\n\tsector_t start_blk, last_blk;\n\tloff_t isize = i_size_read(inode);\n\tu64 logical = 0, phys = 0, size = 0;\n\tu32 flags = FIEMAP_EXTENT_MERGED;\n\tbool past_eof = false, whole_file = false;\n\tint ret = 0;\n\n\tret = fiemap_check_flags(fieinfo, FIEMAP_FLAG_SYNC);\n\tif (ret)\n\t\treturn ret;\n\n\t/*\n\t * Either the i_mutex or other appropriate locking needs to be held\n\t * since we expect isize to not change at all through the duration of\n\t * this call.\n\t */\n\tif (len >= isize) {\n\t\twhole_file = true;\n\t\tlen = isize;\n\t}\n\n\t/*\n\t * Some filesystems can't deal with being asked to map less than\n\t * blocksize, so make sure our len is at least block length.\n\t */\n\tif (logical_to_blk(inode, len) == 0)\n\t\tlen = blk_to_logical(inode, 1);\n\n\tstart_blk = logical_to_blk(inode, start);\n\tlast_blk = logical_to_blk(inode, start + len - 1);\n\n\tdo {\n\t\t/*\n\t\t * we set b_size to the total size we want so it will map as\n\t\t * many contiguous blocks as possible at once\n\t\t */\n\t\tmemset(&map_bh, 0, sizeof(struct buffer_head));\n\t\tmap_bh.b_size = len;\n\n\t\tret = get_block(inode, start_blk, &map_bh, 0);\n\t\tif (ret)\n\t\t\tbreak;\n\n\t\t/* HOLE */\n\t\tif (!buffer_mapped(&map_bh)) {\n\t\t\tstart_blk++;\n\n\t\t\t/*\n\t\t\t * We want to handle the case where there is an\n\t\t\t * allocated block at the front of the file, and then\n\t\t\t * nothing but holes up to the end of the file properly,\n\t\t\t * to make sure that extent at the front gets properly\n\t\t\t * marked with FIEMAP_EXTENT_LAST\n\t\t\t */\n\t\t\tif (!past_eof &&\n\t\t\t blk_to_logical(inode, start_blk) >= isize)\n\t\t\t\tpast_eof = 1;\n\n\t\t\t/*\n\t\t\t * First hole after going past the EOF, this is our\n\t\t\t * last extent\n\t\t\t */\n\t\t\tif (past_eof && size) {\n\t\t\t\tflags = FIEMAP_EXTENT_MERGED|FIEMAP_EXTENT_LAST;\n\t\t\t\tret = fiemap_fill_next_extent(fieinfo, logical,\n\t\t\t\t\t\t\t phys, size,\n\t\t\t\t\t\t\t flags);\n\t\t\t} else if (size) {\n\t\t\t\tret = fiemap_fill_next_extent(fieinfo, logical,\n\t\t\t\t\t\t\t phys, size, flags);\n\t\t\t\tsize = 0;\n\t\t\t}\n\n\t\t\t/* if we have holes up to/past EOF then we're done */\n\t\t\tif (start_blk > last_blk || past_eof || ret)\n\t\t\t\tbreak;\n\t\t} else {\n\t\t\t/*\n\t\t\t * We have gone over the length of what we wanted to\n\t\t\t * map, and it wasn't the entire file, so add the extent\n\t\t\t * we got last time and exit.\n\t\t\t *\n\t\t\t * This is for the case where say we want to map all the\n\t\t\t * way up to the second to the last block in a file, but\n\t\t\t * the last block is a hole, making the second to last\n\t\t\t * block FIEMAP_EXTENT_LAST. In this case we want to\n\t\t\t * see if there is a hole after the second to last block\n\t\t\t * so we can mark it properly. If we found data after\n\t\t\t * we exceeded the length we were requesting, then we\n\t\t\t * are good to go, just add the extent to the fieinfo\n\t\t\t * and break\n\t\t\t */\n\t\t\tif (start_blk > last_blk && !whole_file) {\n\t\t\t\tret = fiemap_fill_next_extent(fieinfo, logical,\n\t\t\t\t\t\t\t phys, size,\n\t\t\t\t\t\t\t flags);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\t/*\n\t\t\t * if size != 0 then we know we already have an extent\n\t\t\t * to add, so add it.\n\t\t\t */\n\t\t\tif (size) {\n\t\t\t\tret = fiemap_fill_next_extent(fieinfo, logical,\n\t\t\t\t\t\t\t phys, size,\n\t\t\t\t\t\t\t flags);\n\t\t\t\tif (ret)\n\t\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tlogical = blk_to_logical(inode, start_blk);\n\t\t\tphys = blk_to_logical(inode, map_bh.b_blocknr);\n\t\t\tsize = map_bh.b_size;\n\t\t\tflags = FIEMAP_EXTENT_MERGED;\n\n\t\t\tstart_blk += logical_to_blk(inode, size);\n\n\t\t\t/*\n\t\t\t * If we are past the EOF, then we need to make sure as\n\t\t\t * soon as we find a hole that the last extent we found\n\t\t\t * is marked with FIEMAP_EXTENT_LAST\n\t\t\t */\n\t\t\tif (!past_eof && logical + size >= isize)\n\t\t\t\tpast_eof = true;\n\t\t}\n\t\tcond_resched();\n\t\tif (fatal_signal_pending(current)) {\n\t\t\tret = -EINTR;\n\t\t\tbreak;\n\t\t}\n\n\t} while (1);\n\n\t/* If ret is 1 then we just hit the end of the extent array */\n\tif (ret == 1)\n\t\tret = 0;\n\n\treturn ret;\n}\n", + "line": null, + "label": 0, + "cwe": "CWE-119", + "cve": "CVE-2016-6516", + "length": 1129 + }, + { + "index": 173311, + "code": "read_callback(png_structp png_ptr, png_bytep buffer, size_t count)\n /* Return 'count' bytes to libpng in 'buffer' */\n{\n struct file *file = get_control(png_ptr);\n png_uint_32 type, length; /* For the chunk be *WRITTEN* */\n struct chunk *chunk;\n\n /* libpng should always ask for at least one byte */\n if (count == 0)\n stop(file, UNEXPECTED_ERROR_CODE, \"read callback for 0 bytes\");\n\n /* The callback always reads ahead by 8 bytes - the signature or chunk header\n * - these bytes are stored in chunk_length and chunk_type. This block is\n * executed once for the signature and once for the first chunk right at the\n * start.\n */\n if (file->read_count < 8)\n {\n assert(file->read_count == 0);\n assert((file->status_code & TRUNCATED) == 0);\n\n (void)read_4(file, &file->length);\n\n if (file->read_count == 4)\n (void)read_4(file, &file->type);\n\n if (file->read_count < 8)\n {\n assert((file->status_code & TRUNCATED) != 0);\n stop(file, READ_ERROR_CODE, \"not a PNG (too short)\");\n }\n\n if (file->state == STATE_SIGNATURE)\n {\n if (file->length != sig1 || file->type != sig2)\n stop(file, LIBPNG_ERROR_CODE, \"not a PNG (signature)\");\n\n /* Else write it (this is the initialization of write_count, prior to\n * this it contains CLEAR garbage.)\n */\n file->write_count = 0;\n }\n\n else\n {\n assert(file->state == STATE_CHUNKS);\n\n /* The first chunk must be a well formed IHDR (this could be relaxed to\n * use the checks in process_chunk, but that seems unnecessary.)\n */\n if (file->length != 13 || file->type != png_IHDR)\n stop(file, LIBPNG_ERROR_CODE, \"not a PNG (IHDR)\");\n\n /* The position of the data must be stored too */\n getpos(file);\n }\n }\n\n /* Retrieve previous state (because the read callbacks are made pretty much\n * byte-by-byte in the sequential reader prior to 1.7).\n */\n chunk = file->chunk;\n\n if (chunk != NULL)\n {\n length = chunk->chunk_length;\n type = chunk->chunk_type;\n }\n\n else\n {\n /* This is the signature case; for IDAT and other chunks these values will\n * be overwritten when read_chunk is called below.\n */\n length = file->length;\n type = file->type;\n }\n\n do\n {\n png_uint_32 b;\n\n /* Complete the read of a chunk; as a side effect this also instantiates\n * a chunk control structure and sets the file length/type/data_pos fields\n * for the *NEXT* chunk header.\n *\n * NOTE: at an IDAT any following IDAT chunks will also be read and the\n * next_ fields will refer to the chunk after the last IDAT.\n *\n * NOTE: read_chunk only returns when it has read a chunk that must now be\n * written.\n */\n if (file->state != STATE_SIGNATURE && chunk == NULL)\n {\n assert(file->read_count == 8);\n assert(file->idat == NULL);\n read_chunk(file);\n chunk = file->chunk;\n assert(chunk != NULL);\n\n /* Do the initialization that was not done before. */\n length = chunk->chunk_length;\n type = chunk->chunk_type;\n\n /* And start writing the new chunk. */\n file->write_count = 0;\n }\n\n /* The chunk_ fields describe a chunk that must be written, or hold the\n * signature. Write the header first. In the signature case this\n * rewrites the signature.\n */\n switch (file->write_count)\n {\n case 0: b = length >> 24; break;\n case 1: b = length >> 16; break;\n case 2: b = length >> 8; break;\n case 3: b = length ; break;\n\n case 4: b = type >> 24; break;\n case 5: b = type >> 16; break;\n case 6: b = type >> 8; break;\n case 7: b = type ; break;\n\n case 8:\n /* The header has been written. If this is really the signature\n * that's all that is required and we can go to normal chunk\n * processing.\n */\n if (file->state == STATE_SIGNATURE)\n {\n /* The signature has been written, the tail call to read_callback\n * below (it's just a goto to the start with a decent compiler)\n * will read the IHDR header ahead and validate it.\n */\n assert(length == sig1 && type == sig2);\n file->read_count = 0; /* Forces a header read */\n file->state = STATE_CHUNKS; /* IHDR: checked above */\n read_callback(png_ptr, buffer, count);\n return;\n }\n\n else\n {\n assert(chunk != NULL);\n\n /* Set up for write, notice that repositioning the input stream\n * is only necessary if something is to be read from it. Also\n * notice that for the IDAT stream this must only happen once -\n * on the first IDAT - to get back to the start of the list and\n * this is done inside process_IDAT:\n */\n chunk->write_crc = crc_init_4(type);\n if (file->state != STATE_IDAT && length > 0)\n setpos(chunk);\n }\n /* FALL THROUGH */\n\n default:\n assert(chunk != NULL);\n\n /* NOTE: the arithmetic below overflows and gives a large positive\n * png_uint_32 value until the whole chunk data has been written.\n */\n switch (file->write_count - length)\n {\n /* Write the chunk data, normally this just comes from\n * the file. The only exception is for that part of a\n * chunk which is zlib data and which must be rewritten,\n * and IDAT chunks which can be completely\n * reconstructed.\n */\n default:\n if (file->state == STATE_IDAT)\n {\n struct IDAT *idat = file->idat;\n\n assert(idat != NULL);\n\n /* Read an IDAT byte from the input stream of IDAT chunks.\n * Because the IDAT stream can be re-chunked this stream is\n * held in the struct IDAT members. The chunk members, in\n * particular chunk_length (and therefore the length local)\n * refer to the output chunk.\n */\n while (idat->idat_index >= idat->idat_length)\n {\n /* Advance one chunk */\n struct IDAT_list *cur = idat->idat_cur;\n\n assert(idat->idat_index == idat->idat_length);\n assert(cur != NULL && cur->count > 0);\n\n /* NOTE: IDAT_list::count here, not IDAT_list::length */\n if (++(idat->idat_count) >= cur->count)\n {\n assert(idat->idat_count == cur->count);\n\n /* Move on to the next IDAT_list: */\n cur = cur->next;\n\n /* This is an internal error - read beyond the end of\n * the pre-calculated stream.\n */\n if (cur == NULL || cur->count == 0)\n stop(file, UNEXPECTED_ERROR_CODE,\n \"read beyond end of IDAT\");\n\n idat->idat_count = 0;\n idat->idat_cur = cur;\n }\n\n idat->idat_index = 0;\n /* Zero length IDAT chunks are permitted, so the length\n * here may be 0.\n */\n idat->idat_length = cur->lengths[idat->idat_count];\n\n /* And skip 12 bytes to the next chunk data */\n skip_12(file);\n }\n\n /* The index is always that of the next byte, the rest of\n * the information is always the current IDAT chunk and the\n * current list.\n */\n ++(idat->idat_index);\n }\n\n /* Read the byte from the stream. */\n b = reread_byte(file);\n\n /* If the byte must be rewritten handle that here */\n if (chunk->rewrite_length > 0)\n {\n if (chunk->rewrite_offset > 0)\n --(chunk->rewrite_offset);\n\n else\n {\n b = chunk->rewrite_buffer[0];\n memmove(chunk->rewrite_buffer, chunk->rewrite_buffer+1,\n (sizeof chunk->rewrite_buffer)-\n (sizeof chunk->rewrite_buffer[0]));\n\n --(chunk->rewrite_length);\n }\n }\n\n chunk->write_crc = crc_one_byte(chunk->write_crc, b);\n break;\n\n /* The CRC is written at:\n *\n * chunk_write == chunk_length+8..chunk_length+11\n *\n * so 8 to 11. The CRC is not (yet) conditioned.\n */\n case 8: b = chunk->write_crc >> 24; goto write_crc;\n case 9: b = chunk->write_crc >> 16; goto write_crc;\n case 10: b = chunk->write_crc >> 8; goto write_crc;\n case 11:\n /* This must happen before the chunk_end below: */\n b = chunk->write_crc;\n\n if (file->global->verbose > 2)\n {\n fputs(\" \", stderr);\n type_name(type, stderr);\n fprintf(stderr, \" %lu 0x%.8x\\n\", (unsigned long)length,\n chunk->write_crc ^ 0xffffffff);\n }\n\n /* The IDAT stream is written without a call to read_chunk\n * until the end is reached. rechunk_length() calculates the\n * length of the output chunks. Control gets to this point at\n * the end of an *output* chunk - the length calculated by\n * rechunk_length. If this corresponds to the end of the\n * input stream stop writing IDAT chunks, otherwise continue.\n */\n if (file->state == STATE_IDAT &&\n (file->idat->idat_index < file->idat->idat_length ||\n 1+file->idat->idat_count < file->idat->idat_cur->count ||\n file->idat->idat_cur != file->idat->idat_list_tail))\n {\n /* Write another IDAT chunk. Call rechunk_length to\n * calculate the length required.\n */\n length = chunk->chunk_length = rechunk_length(file->idat);\n assert(type == png_IDAT);\n file->write_count = 0; /* for the new chunk */\n --(file->write_count); /* fake out the increment below */\n }\n\n else\n {\n /* Entered at the end of a non-IDAT chunk and at the end of\n * the IDAT stream. The rewrite should have been cleared.\n */\n if (chunk->rewrite_length > 0 || chunk->rewrite_offset > 0)\n stop(file, UNEXPECTED_ERROR_CODE, \"pending rewrite\");\n\n /* This is the last byte so reset chunk_read for the next\n * chunk and move the input file to the position after the\n * *next* chunk header if required.\n */\n file->read_count = 8;\n file_setpos(file, &file->data_pos);\n\n if (file->idat == NULL)\n chunk_end(&file->chunk);\n\n else\n IDAT_end(&file->idat);\n }\n\n write_crc:\n b ^= 0xff; /* conditioning */\n break;\n }\n break;\n }\n\n /* Write one byte */\n b &= 0xff;\n *buffer++ = (png_byte)b;\n --count;\n write_byte(file, (png_byte)b); /* increments chunk_write */\n }\n while (count > 0);\n}\n", + "line": null, + "label": 0, + "cwe": null, + "cve": "CVE-2016-3751", + "length": 2526 + }, + { + "index": 42630, + "code": "int udpv6_sendmsg(struct sock *sk, struct msghdr *msg, size_t len)\n{\n\tstruct ipv6_txoptions opt_space;\n\tstruct udp_sock *up = udp_sk(sk);\n\tstruct inet_sock *inet = inet_sk(sk);\n\tstruct ipv6_pinfo *np = inet6_sk(sk);\n\tDECLARE_SOCKADDR(struct sockaddr_in6 *, sin6, msg->msg_name);\n\tstruct in6_addr *daddr, *final_p, final;\n\tstruct ipv6_txoptions *opt = NULL;\n\tstruct ip6_flowlabel *flowlabel = NULL;\n\tstruct flowi6 fl6;\n\tstruct dst_entry *dst;\n\tint addr_len = msg->msg_namelen;\n\tint ulen = len;\n\tint hlimit = -1;\n\tint tclass = -1;\n\tint dontfrag = -1;\n\tint corkreq = up->corkflag || msg->msg_flags&MSG_MORE;\n\tint err;\n\tint connected = 0;\n\tint is_udplite = IS_UDPLITE(sk);\n\tint (*getfrag)(void *, char *, int, int, int, struct sk_buff *);\n\n\t/* destination address check */\n\tif (sin6) {\n\t\tif (addr_len < offsetof(struct sockaddr, sa_data))\n\t\t\treturn -EINVAL;\n\n\t\tswitch (sin6->sin6_family) {\n\t\tcase AF_INET6:\n\t\t\tif (addr_len < SIN6_LEN_RFC2133)\n\t\t\t\treturn -EINVAL;\n\t\t\tdaddr = &sin6->sin6_addr;\n\t\t\tbreak;\n\t\tcase AF_INET:\n\t\t\tgoto do_udp_sendmsg;\n\t\tcase AF_UNSPEC:\n\t\t\tmsg->msg_name = sin6 = NULL;\n\t\t\tmsg->msg_namelen = addr_len = 0;\n\t\t\tdaddr = NULL;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\treturn -EINVAL;\n\t\t}\n\t} else if (!up->pending) {\n\t\tif (sk->sk_state != TCP_ESTABLISHED)\n\t\t\treturn -EDESTADDRREQ;\n\t\tdaddr = &sk->sk_v6_daddr;\n\t} else\n\t\tdaddr = NULL;\n\n\tif (daddr) {\n\t\tif (ipv6_addr_v4mapped(daddr)) {\n\t\t\tstruct sockaddr_in sin;\n\t\t\tsin.sin_family = AF_INET;\n\t\t\tsin.sin_port = sin6 ? sin6->sin6_port : inet->inet_dport;\n\t\t\tsin.sin_addr.s_addr = daddr->s6_addr32[3];\n\t\t\tmsg->msg_name = &sin;\n\t\t\tmsg->msg_namelen = sizeof(sin);\ndo_udp_sendmsg:\n\t\t\tif (__ipv6_only_sock(sk))\n\t\t\t\treturn -ENETUNREACH;\n\t\t\treturn udp_sendmsg(sk, msg, len);\n\t\t}\n\t}\n\n\tif (up->pending == AF_INET)\n\t\treturn udp_sendmsg(sk, msg, len);\n\n\t/* Rough check on arithmetic overflow,\n\t better check is made in ip6_append_data().\n\t */\n\tif (len > INT_MAX - sizeof(struct udphdr))\n\t\treturn -EMSGSIZE;\n\n\tgetfrag = is_udplite ? udplite_getfrag : ip_generic_getfrag;\n\tif (up->pending) {\n\t\t/*\n\t\t * There are pending frames.\n\t\t * The socket lock must be held while it's corked.\n\t\t */\n\t\tlock_sock(sk);\n\t\tif (likely(up->pending)) {\n\t\t\tif (unlikely(up->pending != AF_INET6)) {\n\t\t\t\trelease_sock(sk);\n\t\t\t\treturn -EAFNOSUPPORT;\n\t\t\t}\n\t\t\tdst = NULL;\n\t\t\tgoto do_append_data;\n\t\t}\n\t\trelease_sock(sk);\n\t}\n\tulen += sizeof(struct udphdr);\n\n\tmemset(&fl6, 0, sizeof(fl6));\n\n\tif (sin6) {\n\t\tif (sin6->sin6_port == 0)\n\t\t\treturn -EINVAL;\n\n\t\tfl6.fl6_dport = sin6->sin6_port;\n\t\tdaddr = &sin6->sin6_addr;\n\n\t\tif (np->sndflow) {\n\t\t\tfl6.flowlabel = sin6->sin6_flowinfo&IPV6_FLOWINFO_MASK;\n\t\t\tif (fl6.flowlabel&IPV6_FLOWLABEL_MASK) {\n\t\t\t\tflowlabel = fl6_sock_lookup(sk, fl6.flowlabel);\n\t\t\t\tif (!flowlabel)\n\t\t\t\t\treturn -EINVAL;\n\t\t\t}\n\t\t}\n\n\t\t/*\n\t\t * Otherwise it will be difficult to maintain\n\t\t * sk->sk_dst_cache.\n\t\t */\n\t\tif (sk->sk_state == TCP_ESTABLISHED &&\n\t\t ipv6_addr_equal(daddr, &sk->sk_v6_daddr))\n\t\t\tdaddr = &sk->sk_v6_daddr;\n\n\t\tif (addr_len >= sizeof(struct sockaddr_in6) &&\n\t\t sin6->sin6_scope_id &&\n\t\t __ipv6_addr_needs_scope_id(__ipv6_addr_type(daddr)))\n\t\t\tfl6.flowi6_oif = sin6->sin6_scope_id;\n\t} else {\n\t\tif (sk->sk_state != TCP_ESTABLISHED)\n\t\t\treturn -EDESTADDRREQ;\n\n\t\tfl6.fl6_dport = inet->inet_dport;\n\t\tdaddr = &sk->sk_v6_daddr;\n\t\tfl6.flowlabel = np->flow_label;\n\t\tconnected = 1;\n\t}\n\n\tif (!fl6.flowi6_oif)\n\t\tfl6.flowi6_oif = sk->sk_bound_dev_if;\n\n\tif (!fl6.flowi6_oif)\n\t\tfl6.flowi6_oif = np->sticky_pktinfo.ipi6_ifindex;\n\n\tfl6.flowi6_mark = sk->sk_mark;\n\n\tif (msg->msg_controllen) {\n\t\topt = &opt_space;\n\t\tmemset(opt, 0, sizeof(struct ipv6_txoptions));\n\t\topt->tot_len = sizeof(*opt);\n\n\t\terr = ip6_datagram_send_ctl(sock_net(sk), sk, msg, &fl6, opt,\n\t\t\t\t\t &hlimit, &tclass, &dontfrag);\n\t\tif (err < 0) {\n\t\t\tfl6_sock_release(flowlabel);\n\t\t\treturn err;\n\t\t}\n\t\tif ((fl6.flowlabel&IPV6_FLOWLABEL_MASK) && !flowlabel) {\n\t\t\tflowlabel = fl6_sock_lookup(sk, fl6.flowlabel);\n\t\t\tif (!flowlabel)\n\t\t\t\treturn -EINVAL;\n\t\t}\n\t\tif (!(opt->opt_nflen|opt->opt_flen))\n\t\t\topt = NULL;\n\t\tconnected = 0;\n\t}\n\tif (!opt)\n\t\topt = np->opt;\n\tif (flowlabel)\n\t\topt = fl6_merge_options(&opt_space, flowlabel, opt);\n\topt = ipv6_fixup_options(&opt_space, opt);\n\n\tfl6.flowi6_proto = sk->sk_protocol;\n\tif (!ipv6_addr_any(daddr))\n\t\tfl6.daddr = *daddr;\n\telse\n\t\tfl6.daddr.s6_addr[15] = 0x1; /* :: means loopback (BSD'ism) */\n\tif (ipv6_addr_any(&fl6.saddr) && !ipv6_addr_any(&np->saddr))\n\t\tfl6.saddr = np->saddr;\n\tfl6.fl6_sport = inet->inet_sport;\n\n\tfinal_p = fl6_update_dst(&fl6, opt, &final);\n\tif (final_p)\n\t\tconnected = 0;\n\n\tif (!fl6.flowi6_oif && ipv6_addr_is_multicast(&fl6.daddr)) {\n\t\tfl6.flowi6_oif = np->mcast_oif;\n\t\tconnected = 0;\n\t} else if (!fl6.flowi6_oif)\n\t\tfl6.flowi6_oif = np->ucast_oif;\n\n\tsecurity_sk_classify_flow(sk, flowi6_to_flowi(&fl6));\n\n\tdst = ip6_sk_dst_lookup_flow(sk, &fl6, final_p);\n\tif (IS_ERR(dst)) {\n\t\terr = PTR_ERR(dst);\n\t\tdst = NULL;\n\t\tgoto out;\n\t}\n\n\tif (hlimit < 0)\n\t\thlimit = ip6_sk_dst_hoplimit(np, &fl6, dst);\n\n\tif (tclass < 0)\n\t\ttclass = np->tclass;\n\n\tif (msg->msg_flags&MSG_CONFIRM)\n\t\tgoto do_confirm;\nback_from_confirm:\n\n\t/* Lockless fast path for the non-corking case */\n\tif (!corkreq) {\n\t\tstruct sk_buff *skb;\n\n\t\tskb = ip6_make_skb(sk, getfrag, msg, ulen,\n\t\t\t\t sizeof(struct udphdr), hlimit, tclass, opt,\n\t\t\t\t &fl6, (struct rt6_info *)dst,\n\t\t\t\t msg->msg_flags, dontfrag);\n\t\terr = PTR_ERR(skb);\n\t\tif (!IS_ERR_OR_NULL(skb))\n\t\t\terr = udp_v6_send_skb(skb, &fl6);\n\t\tgoto release_dst;\n\t}\n\n\tlock_sock(sk);\n\tif (unlikely(up->pending)) {\n\t\t/* The socket is already corked while preparing it. */\n\t\t/* ... which is an evident application bug. --ANK */\n\t\trelease_sock(sk);\n\n\t\tnet_dbg_ratelimited(\"udp cork app bug 2\\n\");\n\t\terr = -EINVAL;\n\t\tgoto out;\n\t}\n\n\tup->pending = AF_INET6;\n\ndo_append_data:\n\tif (dontfrag < 0)\n\t\tdontfrag = np->dontfrag;\n\tup->len += ulen;\n\terr = ip6_append_data(sk, getfrag, msg, ulen,\n\t\tsizeof(struct udphdr), hlimit, tclass, opt, &fl6,\n\t\t(struct rt6_info *)dst,\n\t\tcorkreq ? msg->msg_flags|MSG_MORE : msg->msg_flags, dontfrag);\n\tif (err)\n\t\tudp_v6_flush_pending_frames(sk);\n\telse if (!corkreq)\n\t\terr = udp_v6_push_pending_frames(sk);\n\telse if (unlikely(skb_queue_empty(&sk->sk_write_queue)))\n\t\tup->pending = 0;\n\n\tif (err > 0)\n\t\terr = np->recverr ? net_xmit_errno(err) : 0;\n\trelease_sock(sk);\n\nrelease_dst:\n\tif (dst) {\n\t\tif (connected) {\n\t\t\tip6_dst_store(sk, dst,\n\t\t\t\t ipv6_addr_equal(&fl6.daddr, &sk->sk_v6_daddr) ?\n\t\t\t\t &sk->sk_v6_daddr : NULL,\n#ifdef CONFIG_IPV6_SUBTREES\n\t\t\t\t ipv6_addr_equal(&fl6.saddr, &np->saddr) ?\n\t\t\t\t &np->saddr :\n#endif\n\t\t\t\t NULL);\n\t\t} else {\n\t\t\tdst_release(dst);\n\t\t}\n\t\tdst = NULL;\n\t}\n\nout:\n\tdst_release(dst);\n\tfl6_sock_release(flowlabel);\n\tif (!err)\n\t\treturn len;\n\t/*\n\t * ENOBUFS = no kernel mem, SOCK_NOSPACE = no sndbuf space. Reporting\n\t * ENOBUFS might not be good (it's not tunable per se), but otherwise\n\t * we don't have a good statistic (IpOutDiscards but it can be too many\n\t * things). We could add another new stat but at least for now that\n\t * seems like overkill.\n\t */\n\tif (err == -ENOBUFS || test_bit(SOCK_NOSPACE, &sk->sk_socket->flags)) {\n\t\tUDP6_INC_STATS_USER(sock_net(sk),\n\t\t\t\tUDP_MIB_SNDBUFERRORS, is_udplite);\n\t}\n\treturn err;\n\ndo_confirm:\n\tdst_confirm(dst);\n\tif (!(msg->msg_flags&MSG_PROBE) || len)\n\t\tgoto back_from_confirm;\n\terr = 0;\n\tgoto out;\n}\n", + "line": null, + "label": 0, + "cwe": "CWE-399", + "cve": "CVE-2015-5366", + "length": 2436 + }, + { + "index": 167027, + "code": "void NavigationControllerImpl::RendererDidNavigateToExistingPage(\n RenderFrameHostImpl* rfh,\n const FrameHostMsg_DidCommitProvisionalLoad_Params& params,\n bool is_same_document,\n bool was_restored,\n NavigationHandleImpl* handle) {\n DCHECK(GetLastCommittedEntry()) << \"ClassifyNavigation should guarantee \"\n << \"that a last committed entry exists.\";\n\n DCHECK(!rfh->GetParent());\n\n NavigationEntryImpl* entry;\n if (params.intended_as_new_entry) {\n entry = GetLastCommittedEntry();\n if (!is_same_document)\n entry->GetSSL() = SSLStatus(handle->GetSSLInfo());\n\n if (params.url.SchemeIs(url::kHttpsScheme) && !rfh->GetParent() &&\n handle->GetNetErrorCode() == net::OK) {\n bool has_cert = !!entry->GetSSL().certificate;\n if (is_same_document) {\n UMA_HISTOGRAM_BOOLEAN(\n \"Navigation.SecureSchemeHasSSLStatus.\"\n \"ExistingPageSameDocumentIntendedAsNew\",\n has_cert);\n } else {\n UMA_HISTOGRAM_BOOLEAN(\n \"Navigation.SecureSchemeHasSSLStatus.\"\n \"ExistingPageDifferentDocumentIntendedAsNew\",\n has_cert);\n }\n }\n } else if (params.nav_entry_id) {\n entry = GetEntryWithUniqueID(params.nav_entry_id);\n\n if (is_same_document) {\n NavigationEntryImpl* last_entry = GetLastCommittedEntry();\n if (entry->GetURL().GetOrigin() == last_entry->GetURL().GetOrigin() &&\n last_entry->GetSSL().initialized && !entry->GetSSL().initialized &&\n was_restored) {\n entry->GetSSL() = last_entry->GetSSL();\n }\n } else {\n if (handle->GetSSLInfo().is_valid()) {\n entry->GetSSL() = SSLStatus(handle->GetSSLInfo());\n } else if (entry->GetURL().GetOrigin() != handle->GetURL().GetOrigin()) {\n entry->GetSSL() = SSLStatus();\n }\n }\n\n if (params.url.SchemeIs(url::kHttpsScheme) && !rfh->GetParent() &&\n handle->GetNetErrorCode() == net::OK) {\n bool has_cert = !!entry->GetSSL().certificate;\n if (is_same_document && was_restored) {\n UMA_HISTOGRAM_BOOLEAN(\n \"Navigation.SecureSchemeHasSSLStatus.\"\n \"ExistingPageSameDocumentRestoredBrowserInitiated\",\n has_cert);\n } else if (is_same_document && !was_restored) {\n UMA_HISTOGRAM_BOOLEAN(\n \"Navigation.SecureSchemeHasSSLStatus.\"\n \"ExistingPageSameDocumentBrowserInitiated\",\n has_cert);\n } else if (!is_same_document && was_restored) {\n UMA_HISTOGRAM_BOOLEAN(\n \"Navigation.SecureSchemeHasSSLStatus.\"\n \"ExistingPageRestoredBrowserInitiated\",\n has_cert);\n } else {\n UMA_HISTOGRAM_BOOLEAN(\n \"Navigation.SecureSchemeHasSSLStatus.ExistingPageBrowserInitiated\",\n has_cert);\n }\n }\n } else {\n entry = GetLastCommittedEntry();\n\n\n CopyReplacedNavigationEntryDataIfPreviouslyEmpty(*entry, entry);\n\n if (!is_same_document)\n entry->GetSSL() = SSLStatus(handle->GetSSLInfo());\n\n if (params.url.SchemeIs(url::kHttpsScheme) && !rfh->GetParent() &&\n handle->GetNetErrorCode() == net::OK) {\n bool has_cert = !!entry->GetSSL().certificate;\n if (is_same_document) {\n UMA_HISTOGRAM_BOOLEAN(\n \"Navigation.SecureSchemeHasSSLStatus.\"\n \"ExistingPageSameDocumentRendererInitiated\",\n has_cert);\n } else {\n UMA_HISTOGRAM_BOOLEAN(\n \"Navigation.SecureSchemeHasSSLStatus.\"\n \"ExistingPageDifferentDocumentRendererInitiated\",\n has_cert);\n }\n }\n }\n DCHECK(entry);\n\n entry->set_page_type(params.url_is_unreachable ? PAGE_TYPE_ERROR\n : PAGE_TYPE_NORMAL);\n entry->SetURL(params.url);\n entry->SetReferrer(params.referrer);\n if (entry->update_virtual_url_with_url())\n UpdateVirtualURLToURL(entry, params.url);\n\n DCHECK(entry->site_instance() == nullptr ||\n !entry->GetRedirectChain().empty() ||\n entry->site_instance() == rfh->GetSiteInstance());\n\n entry->AddOrUpdateFrameEntry(\n rfh->frame_tree_node(), params.item_sequence_number,\n params.document_sequence_number, rfh->GetSiteInstance(), nullptr,\n params.url, params.referrer, params.redirects, params.page_state,\n params.method, params.post_id, nullptr /* blob_url_loader_factory */);\n\n if (ui::PageTransitionIsRedirect(params.transition) && !is_same_document)\n entry->GetFavicon() = FaviconStatus();\n\n DiscardNonCommittedEntriesInternal();\n\n last_committed_entry_index_ = GetIndexOfEntry(entry);\n}\n", + "line": null, + "label": 0, + "cwe": null, + "cve": "CVE-2018-6165", + "length": 1080 + }, + { + "index": 183156, + "code": "ext2_xattr_set2(struct inode *inode, struct buffer_head *old_bh,\n\t\tstruct ext2_xattr_header *header)\n{\n \tstruct super_block *sb = inode->i_sb;\n \tstruct buffer_head *new_bh = NULL;\n \tint error;\n \n \tif (header) {\n \t\tnew_bh = ext2_xattr_cache_find(inode, header);\n\t\tif (new_bh) {\n\t\t\t/* We found an identical block in the cache. */\n\t\t\tif (new_bh == old_bh) {\n\t\t\t\tea_bdebug(new_bh, \"keeping this block\");\n\t\t\t} else {\n\t\t\t\t/* The old block is released after updating\n\t\t\t\t the inode. */\n\t\t\t\tea_bdebug(new_bh, \"reusing block\");\n\n\t\t\t\terror = dquot_alloc_block(inode, 1);\n\t\t\t\tif (error) {\n\t\t\t\t\tunlock_buffer(new_bh);\n\t\t\t\t\tgoto cleanup;\n\t\t\t\t}\n\t\t\t\tle32_add_cpu(&HDR(new_bh)->h_refcount, 1);\n\t\t\t\tea_bdebug(new_bh, \"refcount now=%d\",\n\t\t\t\t\tle32_to_cpu(HDR(new_bh)->h_refcount));\n\t\t\t}\n\t\t\tunlock_buffer(new_bh);\n\t\t} else if (old_bh && header == HDR(old_bh)) {\n\t\t\t/* Keep this block. No need to lock the block as we\n \t\t\t don't need to change the reference count. */\n \t\t\tnew_bh = old_bh;\n \t\t\tget_bh(new_bh);\n\t\t\text2_xattr_cache_insert(new_bh);\n \t\t} else {\n \t\t\t/* We need to allocate a new block */\n \t\t\text2_fsblk_t goal = ext2_group_first_block_no(sb,\n\t\t\t\t\t\tEXT2_I(inode)->i_block_group);\n\t\t\tint block = ext2_new_block(inode, goal, &error);\n\t\t\tif (error)\n\t\t\t\tgoto cleanup;\n\t\t\tea_idebug(inode, \"creating block %d\", block);\n\n\t\t\tnew_bh = sb_getblk(sb, block);\n\t\t\tif (unlikely(!new_bh)) {\n\t\t\t\text2_free_blocks(inode, block, 1);\n\t\t\t\tmark_inode_dirty(inode);\n\t\t\t\terror = -ENOMEM;\n\t\t\t\tgoto cleanup;\n\t\t\t}\n\t\t\tlock_buffer(new_bh);\n \t\t\tmemcpy(new_bh->b_data, header, new_bh->b_size);\n \t\t\tset_buffer_uptodate(new_bh);\n \t\t\tunlock_buffer(new_bh);\n\t\t\text2_xattr_cache_insert(new_bh);\n \t\t\t\n \t\t\text2_xattr_update_super_block(sb);\n \t\t}\n\t\tmark_buffer_dirty(new_bh);\n\t\tif (IS_SYNC(inode)) {\n\t\t\tsync_dirty_buffer(new_bh);\n\t\t\terror = -EIO;\n\t\t\tif (buffer_req(new_bh) && !buffer_uptodate(new_bh))\n\t\t\t\tgoto cleanup;\n\t\t}\n\t}\n\n\t/* Update the inode. */\n\tEXT2_I(inode)->i_file_acl = new_bh ? new_bh->b_blocknr : 0;\n\tinode->i_ctime = CURRENT_TIME_SEC;\n\tif (IS_SYNC(inode)) {\n\t\terror = sync_inode_metadata(inode, 1);\n\t\t/* In case sync failed due to ENOSPC the inode was actually\n\t\t * written (only some dirty data were not) so we just proceed\n\t\t * as if nothing happened and cleanup the unused block */\n\t\tif (error && error != -ENOSPC) {\n\t\t\tif (new_bh && new_bh != old_bh) {\n\t\t\t\tdquot_free_block_nodirty(inode, 1);\n\t\t\t\tmark_inode_dirty(inode);\n\t\t\t}\n\t\t\tgoto cleanup;\n\t\t}\n\t} else\n\t\tmark_inode_dirty(inode);\n \n \terror = 0;\n \tif (old_bh && old_bh != new_bh) {\n\t\tstruct mb_cache_entry *ce;\n \t\t/*\n \t\t * If there was an old block and we are no longer using it,\n \t\t * release the old block.\n \t\t */\n\t\tce = mb_cache_entry_get(ext2_xattr_cache, old_bh->b_bdev,\n\t\t\t\t\told_bh->b_blocknr);\n \t\tlock_buffer(old_bh);\n \t\tif (HDR(old_bh)->h_refcount == cpu_to_le32(1)) {\n \t\t\t/* Free the old block. */\n\t\t\tif (ce)\n\t\t\t\tmb_cache_entry_free(ce);\n \t\t\tea_bdebug(old_bh, \"freeing\");\n \t\t\text2_free_blocks(inode, old_bh->b_blocknr, 1);\n \t\t\tmark_inode_dirty(inode);\n\t\t\t/* We let our caller release old_bh, so we\n\t\t\t * need to duplicate the buffer before. */\n\t\t\tget_bh(old_bh);\n\t\t\tbforget(old_bh);\n \t\t} else {\n \t\t\t/* Decrement the refcount only. */\n \t\t\tle32_add_cpu(&HDR(old_bh)->h_refcount, -1);\n\t\t\tif (ce)\n\t\t\t\tmb_cache_entry_release(ce);\n \t\t\tdquot_free_block_nodirty(inode, 1);\n \t\t\tmark_inode_dirty(inode);\n \t\t\tmark_buffer_dirty(old_bh);\n\t\t\tea_bdebug(old_bh, \"refcount now=%d\",\n\t\t\t\tle32_to_cpu(HDR(old_bh)->h_refcount));\n\t\t}\n\t\tunlock_buffer(old_bh);\n\t}\n\ncleanup:\n\tbrelse(new_bh);\n\n\treturn error;\n}\n", + "line": "\t\t\text2_xattr_cache_insert(new_bh);\n\t\t\text2_xattr_cache_insert(new_bh);\n\t\tstruct mb_cache_entry *ce;\n\t\tce = mb_cache_entry_get(ext2_xattr_cache, old_bh->b_bdev,\n\t\t\t\t\told_bh->b_blocknr);\n\t\t\tif (ce)\n\t\t\t\tmb_cache_entry_free(ce);\n\t\t\tif (ce)\n\t\t\t\tmb_cache_entry_release(ce);\n", + "label": 1, + "cwe": "CWE-19", + "cve": "CVE-2015-8952", + "length": 1073 + }, + { + "index": 53558, + "code": "init_decompression(struct archive_read *a, struct _7zip *zip,\n const struct _7z_coder *coder1, const struct _7z_coder *coder2)\n{\n\tint r;\n\n\tzip->codec = coder1->codec;\n\tzip->codec2 = -1;\n\n\tswitch (zip->codec) {\n\tcase _7Z_COPY:\n\tcase _7Z_BZ2:\n\tcase _7Z_DEFLATE:\n\tcase _7Z_PPMD:\n\t\tif (coder2 != NULL) {\n\t\t\tif (coder2->codec != _7Z_X86 &&\n\t\t\t coder2->codec != _7Z_X86_BCJ2) {\n\t\t\t\tarchive_set_error(&a->archive,\n\t\t\t\t ARCHIVE_ERRNO_MISC,\n\t\t\t\t \"Unsupported filter %lx for %lx\",\n\t\t\t\t coder2->codec, coder1->codec);\n\t\t\t\treturn (ARCHIVE_FAILED);\n\t\t\t}\n\t\t\tzip->codec2 = coder2->codec;\n\t\t\tzip->bcj_state = 0;\n\t\t\tif (coder2->codec == _7Z_X86)\n\t\t\t\tx86_Init(zip);\n\t\t}\n\t\tbreak;\n\tdefault:\n\t\tbreak;\n\t}\n\n\tswitch (zip->codec) {\n\tcase _7Z_COPY:\n\t\tbreak;\n\n\tcase _7Z_LZMA: case _7Z_LZMA2:\n#ifdef HAVE_LZMA_H\n#if LZMA_VERSION_MAJOR >= 5\n/* Effectively disable the limiter. */\n#define LZMA_MEMLIMIT UINT64_MAX\n#else\n/* NOTE: This needs to check memory size which running system has. */\n#define LZMA_MEMLIMIT (1U << 30)\n#endif\n\t{\n\t\tlzma_options_delta delta_opt;\n\t\tlzma_filter filters[LZMA_FILTERS_MAX];\n#if LZMA_VERSION < 50010000\n\t\tlzma_filter *ff;\n#endif\n\t\tint fi = 0;\n\n\t\tif (zip->lzstream_valid) {\n\t\t\tlzma_end(&(zip->lzstream));\n\t\t\tzip->lzstream_valid = 0;\n\t\t}\n\n\t\t/*\n\t\t * NOTE: liblzma incompletely handle the BCJ+LZMA compressed\n\t\t * data made by 7-Zip because 7-Zip does not add End-Of-\n\t\t * Payload Marker(EOPM) at the end of LZMA compressed data,\n\t\t * and so liblzma cannot know the end of the compressed data\n\t\t * without EOPM. So consequently liblzma will not return last\n\t\t * three or four bytes of uncompressed data because\n\t\t * LZMA_FILTER_X86 filter does not handle input data if its\n\t\t * data size is less than five bytes. If liblzma detect EOPM\n\t\t * or know the uncompressed data size, liblzma will flush out\n\t\t * the remaining that three or four bytes of uncompressed\n\t\t * data. That is why we have to use our converting program\n\t\t * for BCJ+LZMA. If we were able to tell the uncompressed\n\t\t * size to liblzma when using lzma_raw_decoder() liblzma\n\t\t * could correctly deal with BCJ+LZMA. But unfortunately\n\t\t * there is no way to do that.\n\t\t * Discussion about this can be found at XZ Utils forum.\n\t\t */\n\t\tif (coder2 != NULL) {\n\t\t\tzip->codec2 = coder2->codec;\n\n\t\t\tfilters[fi].options = NULL;\n\t\t\tswitch (zip->codec2) {\n\t\t\tcase _7Z_X86:\n\t\t\t\tif (zip->codec == _7Z_LZMA2) {\n\t\t\t\t\tfilters[fi].id = LZMA_FILTER_X86;\n\t\t\t\t\tfi++;\n\t\t\t\t} else\n\t\t\t\t\t/* Use our filter. */\n\t\t\t\t\tx86_Init(zip);\n\t\t\t\tbreak;\n\t\t\tcase _7Z_X86_BCJ2:\n\t\t\t\t/* Use our filter. */\n\t\t\t\tzip->bcj_state = 0;\n\t\t\t\tbreak;\n\t\t\tcase _7Z_DELTA:\n\t\t\t\tfilters[fi].id = LZMA_FILTER_DELTA;\n\t\t\t\tmemset(&delta_opt, 0, sizeof(delta_opt));\n\t\t\t\tdelta_opt.type = LZMA_DELTA_TYPE_BYTE;\n\t\t\t\tdelta_opt.dist = 1;\n\t\t\t\tfilters[fi].options = &delta_opt;\n\t\t\t\tfi++;\n\t\t\t\tbreak;\n\t\t\t/* Following filters have not been tested yet. */\n\t\t\tcase _7Z_POWERPC:\n\t\t\t\tfilters[fi].id = LZMA_FILTER_POWERPC;\n\t\t\t\tfi++;\n\t\t\t\tbreak;\n\t\t\tcase _7Z_IA64:\n\t\t\t\tfilters[fi].id = LZMA_FILTER_IA64;\n\t\t\t\tfi++;\n\t\t\t\tbreak;\n\t\t\tcase _7Z_ARM:\n\t\t\t\tfilters[fi].id = LZMA_FILTER_ARM;\n\t\t\t\tfi++;\n\t\t\t\tbreak;\n\t\t\tcase _7Z_ARMTHUMB:\n\t\t\t\tfilters[fi].id = LZMA_FILTER_ARMTHUMB;\n\t\t\t\tfi++;\n\t\t\t\tbreak;\n\t\t\tcase _7Z_SPARC:\n\t\t\t\tfilters[fi].id = LZMA_FILTER_SPARC;\n\t\t\t\tfi++;\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tarchive_set_error(&a->archive,\n\t\t\t\t ARCHIVE_ERRNO_MISC,\n\t\t\t\t \"Unexpected codec ID: %lX\", zip->codec2);\n\t\t\t\treturn (ARCHIVE_FAILED);\n\t\t\t}\n\t\t}\n\n\t\tif (zip->codec == _7Z_LZMA2)\n\t\t\tfilters[fi].id = LZMA_FILTER_LZMA2;\n\t\telse\n\t\t\tfilters[fi].id = LZMA_FILTER_LZMA1;\n\t\tfilters[fi].options = NULL;\n#if LZMA_VERSION < 50010000\n\t\tff = &filters[fi];\n#endif\n\t\tr = lzma_properties_decode(&filters[fi], NULL,\n\t\t coder1->properties, (size_t)coder1->propertiesSize);\n\t\tif (r != LZMA_OK) {\n\t\t\tset_error(a, r);\n\t\t\treturn (ARCHIVE_FAILED);\n\t\t}\n\t\tfi++;\n\n\t\tfilters[fi].id = LZMA_VLI_UNKNOWN;\n\t\tfilters[fi].options = NULL;\n\t\tr = lzma_raw_decoder(&(zip->lzstream), filters);\n#if LZMA_VERSION < 50010000\n\t\tfree(ff->options);\n#endif\n\t\tif (r != LZMA_OK) {\n\t\t\tset_error(a, r);\n\t\t\treturn (ARCHIVE_FAILED);\n\t\t}\n\t\tzip->lzstream_valid = 1;\n\t\tzip->lzstream.total_in = 0;\n\t\tzip->lzstream.total_out = 0;\n\t\tbreak;\n\t}\n#else\n\t\tarchive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,\n\t\t \"LZMA codec is unsupported\");\n\t\treturn (ARCHIVE_FAILED);\n#endif\n\tcase _7Z_BZ2:\n#if defined(HAVE_BZLIB_H) && defined(BZ_CONFIG_ERROR)\n\t\tif (zip->bzstream_valid) {\n\t\t\tBZ2_bzDecompressEnd(&(zip->bzstream));\n\t\t\tzip->bzstream_valid = 0;\n\t\t}\n\t\tr = BZ2_bzDecompressInit(&(zip->bzstream), 0, 0);\n\t\tif (r == BZ_MEM_ERROR)\n\t\t\tr = BZ2_bzDecompressInit(&(zip->bzstream), 0, 1);\n\t\tif (r != BZ_OK) {\n\t\t\tint err = ARCHIVE_ERRNO_MISC;\n\t\t\tconst char *detail = NULL;\n\t\t\tswitch (r) {\n\t\t\tcase BZ_PARAM_ERROR:\n\t\t\t\tdetail = \"invalid setup parameter\";\n\t\t\t\tbreak;\n\t\t\tcase BZ_MEM_ERROR:\n\t\t\t\terr = ENOMEM;\n\t\t\t\tdetail = \"out of memory\";\n\t\t\t\tbreak;\n\t\t\tcase BZ_CONFIG_ERROR:\n\t\t\t\tdetail = \"mis-compiled library\";\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tarchive_set_error(&a->archive, err,\n\t\t\t \"Internal error initializing decompressor: %s\",\n\t\t\t detail != NULL ? detail : \"??\");\n\t\t\tzip->bzstream_valid = 0;\n\t\t\treturn (ARCHIVE_FAILED);\n\t\t}\n\t\tzip->bzstream_valid = 1;\n\t\tzip->bzstream.total_in_lo32 = 0;\n\t\tzip->bzstream.total_in_hi32 = 0;\n\t\tzip->bzstream.total_out_lo32 = 0;\n\t\tzip->bzstream.total_out_hi32 = 0;\n\t\tbreak;\n#else\n\t\tarchive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,\n\t\t \"BZ2 codec is unsupported\");\n\t\treturn (ARCHIVE_FAILED);\n#endif\n\tcase _7Z_DEFLATE:\n#ifdef HAVE_ZLIB_H\n\t\tif (zip->stream_valid)\n\t\t\tr = inflateReset(&(zip->stream));\n\t\telse\n\t\t\tr = inflateInit2(&(zip->stream),\n\t\t\t -15 /* Don't check for zlib header */);\n\t\tif (r != Z_OK) {\n\t\t\tarchive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,\n\t\t\t \"Couldn't initialize zlib stream.\");\n\t\t\treturn (ARCHIVE_FAILED);\n\t\t}\n\t\tzip->stream_valid = 1;\n\t\tzip->stream.total_in = 0;\n\t\tzip->stream.total_out = 0;\n\t\tbreak;\n#else\n\t\tarchive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,\n\t\t \"DEFLATE codec is unsupported\");\n\t\treturn (ARCHIVE_FAILED);\n#endif\n\tcase _7Z_PPMD:\n\t{\n\t\tunsigned order;\n\t\tuint32_t msize;\n\n\t\tif (zip->ppmd7_valid) {\n\t\t\t__archive_ppmd7_functions.Ppmd7_Free(\n\t\t\t &zip->ppmd7_context, &g_szalloc);\n\t\t\tzip->ppmd7_valid = 0;\n\t\t}\n\n\t\tif (coder1->propertiesSize < 5) {\n\t\t\tarchive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,\n\t\t\t \"Malformed PPMd parameter\");\n\t\t\treturn (ARCHIVE_FAILED);\n\t\t}\n\t\torder = coder1->properties[0];\n\t\tmsize = archive_le32dec(&(coder1->properties[1]));\n\t\tif (order < PPMD7_MIN_ORDER || order > PPMD7_MAX_ORDER ||\n\t\t msize < PPMD7_MIN_MEM_SIZE || msize > PPMD7_MAX_MEM_SIZE) {\n\t\t\tarchive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,\n\t\t\t \"Malformed PPMd parameter\");\n\t\t\treturn (ARCHIVE_FAILED);\n\t\t}\n\t\t__archive_ppmd7_functions.Ppmd7_Construct(&zip->ppmd7_context);\n\t\tr = __archive_ppmd7_functions.Ppmd7_Alloc(\n\t\t\t&zip->ppmd7_context, msize, &g_szalloc);\n\t\tif (r == 0) {\n\t\t\tarchive_set_error(&a->archive, ENOMEM,\n\t\t\t \"Coludn't allocate memory for PPMd\");\n\t\t\treturn (ARCHIVE_FATAL);\n\t\t}\n\t\t__archive_ppmd7_functions.Ppmd7_Init(\n\t\t\t&zip->ppmd7_context, order);\n\t\t__archive_ppmd7_functions.Ppmd7z_RangeDec_CreateVTable(\n\t\t\t&zip->range_dec);\n\t\tzip->ppmd7_valid = 1;\n\t\tzip->ppmd7_stat = 0;\n\t\tzip->ppstream.overconsumed = 0;\n\t\tzip->ppstream.total_in = 0;\n\t\tzip->ppstream.total_out = 0;\n\t\tbreak;\n\t}\n\tcase _7Z_X86:\n\tcase _7Z_X86_BCJ2:\n\tcase _7Z_POWERPC:\n\tcase _7Z_IA64:\n\tcase _7Z_ARM:\n\tcase _7Z_ARMTHUMB:\n\tcase _7Z_SPARC:\n\tcase _7Z_DELTA:\n\t\tarchive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,\n\t\t \"Unexpected codec ID: %lX\", zip->codec);\n\t\treturn (ARCHIVE_FAILED);\n\tcase _7Z_CRYPTO_MAIN_ZIP:\n\tcase _7Z_CRYPTO_RAR_29:\n\tcase _7Z_CRYPTO_AES_256_SHA_256:\n\t\tif (a->entry) {\n\t\t\tarchive_entry_set_is_metadata_encrypted(a->entry, 1);\n\t\t\tarchive_entry_set_is_data_encrypted(a->entry, 1);\n\t\t\tzip->has_encrypted_entries = 1;\n\t\t}\n\t\tarchive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,\n\t\t \"Crypto codec not supported yet (ID: 0x%lX)\", zip->codec);\n\t\treturn (ARCHIVE_FAILED);\n\tdefault:\n\t\tarchive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,\n\t\t \"Unknown codec ID: %lX\", zip->codec);\n\t\treturn (ARCHIVE_FAILED);\n\t}\n\n\treturn (ARCHIVE_OK);\n}\n", + "line": null, + "label": 0, + "cwe": "CWE-190", + "cve": "CVE-2016-4300", + "length": 2672 + }, + { + "index": 182938, + "code": "static void opj_get_encoding_parameters(const opj_image_t *p_image,\n const opj_cp_t *p_cp,\n OPJ_UINT32 p_tileno,\n OPJ_INT32 * p_tx0,\n OPJ_INT32 * p_tx1,\n OPJ_INT32 * p_ty0,\n OPJ_INT32 * p_ty1,\n OPJ_UINT32 * p_dx_min,\n OPJ_UINT32 * p_dy_min,\n OPJ_UINT32 * p_max_prec,\n OPJ_UINT32 * p_max_res)\n{\n /* loop */\n OPJ_UINT32 compno, resno;\n /* pointers */\n const opj_tcp_t *l_tcp = 00;\n const opj_tccp_t * l_tccp = 00;\n const opj_image_comp_t * l_img_comp = 00;\n\n /* position in x and y of tile */\n OPJ_UINT32 p, q;\n \n /* preconditions */\n assert(p_cp != 00);\n assert(p_image != 00);\n assert(p_tileno < p_cp->tw * p_cp->th);\n\n /* initializations */\n l_tcp = &p_cp->tcps [p_tileno];\n l_img_comp = p_image->comps;\n l_tccp = l_tcp->tccps;\n\n /* here calculation of tx0, tx1, ty0, ty1, maxprec, dx and dy */\n p = p_tileno % p_cp->tw;\n q = p_tileno / p_cp->tw;\n \n /* find extent of tile */\n *p_tx0 = opj_int_max((OPJ_INT32)(p_cp->tx0 + p * p_cp->tdx),\n (OPJ_INT32)p_image->x0);\n *p_tx1 = opj_int_min((OPJ_INT32)(p_cp->tx0 + (p + 1) * p_cp->tdx),\n (OPJ_INT32)p_image->x1);\n *p_ty0 = opj_int_max((OPJ_INT32)(p_cp->ty0 + q * p_cp->tdy),\n (OPJ_INT32)p_image->y0);\n *p_ty1 = opj_int_min((OPJ_INT32)(p_cp->ty0 + (q + 1) * p_cp->tdy),\n (OPJ_INT32)p_image->y1);\n \n /* max precision is 0 (can only grow) */\n *p_max_prec = 0;\n *p_max_res = 0;\n\n /* take the largest value for dx_min and dy_min */\n *p_dx_min = 0x7fffffff;\n *p_dy_min = 0x7fffffff;\n\n for (compno = 0; compno < p_image->numcomps; ++compno) {\n /* arithmetic variables to calculate */\n OPJ_UINT32 l_level_no;\n OPJ_INT32 l_rx0, l_ry0, l_rx1, l_ry1;\n OPJ_INT32 l_px0, l_py0, l_px1, py1;\n OPJ_UINT32 l_pdx, l_pdy;\n OPJ_UINT32 l_pw, l_ph;\n OPJ_UINT32 l_product;\n OPJ_INT32 l_tcx0, l_tcy0, l_tcx1, l_tcy1;\n\n l_tcx0 = opj_int_ceildiv(*p_tx0, (OPJ_INT32)l_img_comp->dx);\n l_tcy0 = opj_int_ceildiv(*p_ty0, (OPJ_INT32)l_img_comp->dy);\n l_tcx1 = opj_int_ceildiv(*p_tx1, (OPJ_INT32)l_img_comp->dx);\n l_tcy1 = opj_int_ceildiv(*p_ty1, (OPJ_INT32)l_img_comp->dy);\n\n if (l_tccp->numresolutions > *p_max_res) {\n *p_max_res = l_tccp->numresolutions;\n }\n\n /* use custom size for precincts */\n for (resno = 0; resno < l_tccp->numresolutions; ++resno) {\n OPJ_UINT32 l_dx, l_dy;\n\n /* precinct width and height */\n l_pdx = l_tccp->prcw[resno];\n l_pdy = l_tccp->prch[resno];\n\n l_dx = l_img_comp->dx * (1u << (l_pdx + l_tccp->numresolutions - 1 - resno));\n l_dy = l_img_comp->dy * (1u << (l_pdy + l_tccp->numresolutions - 1 - resno));\n\n /* take the minimum size for dx for each comp and resolution */\n *p_dx_min = opj_uint_min(*p_dx_min, l_dx);\n *p_dy_min = opj_uint_min(*p_dy_min, l_dy);\n\n /* various calculations of extents */\n l_level_no = l_tccp->numresolutions - 1 - resno;\n\n l_rx0 = opj_int_ceildivpow2(l_tcx0, (OPJ_INT32)l_level_no);\n l_ry0 = opj_int_ceildivpow2(l_tcy0, (OPJ_INT32)l_level_no);\n l_rx1 = opj_int_ceildivpow2(l_tcx1, (OPJ_INT32)l_level_no);\n l_ry1 = opj_int_ceildivpow2(l_tcy1, (OPJ_INT32)l_level_no);\n\n l_px0 = opj_int_floordivpow2(l_rx0, (OPJ_INT32)l_pdx) << l_pdx;\n l_py0 = opj_int_floordivpow2(l_ry0, (OPJ_INT32)l_pdy) << l_pdy;\n l_px1 = opj_int_ceildivpow2(l_rx1, (OPJ_INT32)l_pdx) << l_pdx;\n\n py1 = opj_int_ceildivpow2(l_ry1, (OPJ_INT32)l_pdy) << l_pdy;\n\n l_pw = (l_rx0 == l_rx1) ? 0 : (OPJ_UINT32)((l_px1 - l_px0) >> l_pdx);\n l_ph = (l_ry0 == l_ry1) ? 0 : (OPJ_UINT32)((py1 - l_py0) >> l_pdy);\n\n l_product = l_pw * l_ph;\n\n /* update precision */\n if (l_product > *p_max_prec) {\n *p_max_prec = l_product;\n }\n }\n ++l_img_comp;\n ++l_tccp;\n }\n}\n", + "line": " *p_tx0 = opj_int_max((OPJ_INT32)(p_cp->tx0 + p * p_cp->tdx),\n (OPJ_INT32)p_image->x0);\n *p_tx1 = opj_int_min((OPJ_INT32)(p_cp->tx0 + (p + 1) * p_cp->tdx),\n (OPJ_INT32)p_image->x1);\n *p_ty0 = opj_int_max((OPJ_INT32)(p_cp->ty0 + q * p_cp->tdy),\n (OPJ_INT32)p_image->y0);\n *p_ty1 = opj_int_min((OPJ_INT32)(p_cp->ty0 + (q + 1) * p_cp->tdy),\n (OPJ_INT32)p_image->y1);\n", + "label": 1, + "cwe": "CWE-190", + "cve": "CVE-2018-20847", + "length": 1488 + }, + { + "index": 182684, + "code": "static void WritePixels(struct ngiflib_img * i, struct ngiflib_decode_context * context, const u8 * pixels, u16 n) {\n\tu16 tocopy;\t\n\tstruct ngiflib_gif * p = i->parent;\n\n\twhile(n > 0) {\n\t\ttocopy = (context->Xtogo < n) ? context->Xtogo : n;\n\t\tif(!i->gce.transparent_flag) {\n#ifndef NGIFLIB_INDEXED_ONLY\n\t\t\tif(p->mode & NGIFLIB_MODE_INDEXED) {\n#endif /* NGIFLIB_INDEXED_ONLY */\n\t\t\t\tngiflib_memcpy(context->frbuff_p.p8, pixels, tocopy);\n\t\t\t\tpixels += tocopy;\n\t\t\t\tcontext->frbuff_p.p8 += tocopy;\n#ifndef NGIFLIB_INDEXED_ONLY\n\t\t\t} else {\n\t\t\t\tint j;\n\t\t\t\tfor(j = (int)tocopy; j > 0; j--) {\n\t\t\t\t\t*(context->frbuff_p.p32++) =\n\t\t\t\t\t GifIndexToTrueColor(i->palette, *pixels++);\n\t\t\t\t}\n\t\t\t}\n#endif /* NGIFLIB_INDEXED_ONLY */\n\t\t} else {\n\t\t\tint j;\n#ifndef NGIFLIB_INDEXED_ONLY\n\t\t\tif(p->mode & NGIFLIB_MODE_INDEXED) {\n#endif /* NGIFLIB_INDEXED_ONLY */\n\t\t\t\tfor(j = (int)tocopy; j > 0; j--) {\n\t\t\t\t\tif(*pixels != i->gce.transparent_color) *context->frbuff_p.p8 = *pixels;\n\t\t\t\t\tpixels++;\n\t\t\t\t\tcontext->frbuff_p.p8++;\n\t\t\t\t}\n#ifndef NGIFLIB_INDEXED_ONLY\n\t\t\t} else {\n\t\t\t\tfor(j = (int)tocopy; j > 0; j--) {\n\t\t\t\t\tif(*pixels != i->gce.transparent_color) {\n\t\t\t\t\t\t*context->frbuff_p.p32 = GifIndexToTrueColor(i->palette, *pixels);\n\t\t\t\t\t}\n\t\t\t\t\tpixels++;\n\t\t\t\t\tcontext->frbuff_p.p32++;\n\t\t\t\t}\n\t\t\t}\n#endif /* NGIFLIB_INDEXED_ONLY */\n\t\t}\n\t\tcontext->Xtogo -= tocopy;\n\t\tif(context->Xtogo == 0) {\n\t\t\t#ifdef NGIFLIB_ENABLE_CALLBACKS\n\t\t\tif(p->line_cb) p->line_cb(p, context->line_p, context->curY);\n\t\t\t#endif /* NGIFLIB_ENABLE_CALLBACKS */\n\t\t\tcontext->Xtogo = i->width;\n\t\t\tswitch(context->pass) {\n\t\t\tcase 0:\n\t\t\t\tcontext->curY++;\n \t\t\t\tbreak;\n \t\t\tcase 1:\t/* 1st pass : every eighth row starting from 0 */\n \t\t\t\tcontext->curY += 8;\n\t\t\t\tif(context->curY >= p->height) {\n\t\t\t\t\tcontext->pass++;\n\t\t\t\t\tcontext->curY = i->posY + 4;\n\t\t\t\t}\n \t\t\t\tbreak;\n \t\t\tcase 2:\t/* 2nd pass : every eighth row starting from 4 */\n \t\t\t\tcontext->curY += 8;\n\t\t\t\tif(context->curY >= p->height) {\n\t\t\t\t\tcontext->pass++;\n\t\t\t\t\tcontext->curY = i->posY + 2;\n\t\t\t\t}\n \t\t\t\tbreak;\n \t\t\tcase 3:\t/* 3rd pass : every fourth row starting from 2 */\n \t\t\t\tcontext->curY += 4;\n\t\t\t\tif(context->curY >= p->height) {\n\t\t\t\t\tcontext->pass++;\n\t\t\t\t\tcontext->curY = i->posY + 1;\n\t\t\t\t}\n \t\t\t\tbreak;\n \t\t\tcase 4:\t/* 4th pass : every odd row */\n \t\t\t\tcontext->curY += 2;\n \t\t\t\tbreak;\n \t\t\t}\n #ifndef NGIFLIB_INDEXED_ONLY\n \t\t\tif(p->mode & NGIFLIB_MODE_INDEXED) {\n #endif /* NGIFLIB_INDEXED_ONLY */\n\t\t\t\t#ifdef NGIFLIB_ENABLE_CALLBACKS\n\t\t\t\tcontext->line_p.p8 = p->frbuff.p8 + (u32)context->curY*p->width;\n\t\t\t\tcontext->frbuff_p.p8 = context->line_p.p8 + i->posX;\n\t\t\t\t#else\n\t\t\t\tcontext->frbuff_p.p8 = p->frbuff.p8 + (u32)context->curY*p->width + i->posX;\n\t\t\t\t#endif /* NGIFLIB_ENABLE_CALLBACKS */\n#ifndef NGIFLIB_INDEXED_ONLY\n\t\t\t} else {\n\t\t\t\t#ifdef NGIFLIB_ENABLE_CALLBACKS\n\t\t\t\tcontext->line_p.p32 = p->frbuff.p32 + (u32)context->curY*p->width;\n\t\t\t\tcontext->frbuff_p.p32 = context->line_p.p32 + i->posX;\n\t\t\t\t#else\n\t\t\t\tcontext->frbuff_p.p32 = p->frbuff.p32 + (u32)context->curY*p->width + i->posX;\n\t\t\t\t#endif /* NGIFLIB_ENABLE_CALLBACKS */\n\t\t\t}\n#endif /* NGIFLIB_INDEXED_ONLY */\n\t\t}\n\t\tn -= tocopy;\n\t}\n}\n", + "line": "\t\t\t\tif(context->curY >= p->height) {\n\t\t\t\t\tcontext->pass++;\n\t\t\t\t\tcontext->curY = i->posY + 4;\n\t\t\t\t}\n\t\t\t\tif(context->curY >= p->height) {\n\t\t\t\t\tcontext->pass++;\n\t\t\t\t\tcontext->curY = i->posY + 2;\n\t\t\t\t}\n\t\t\t\tif(context->curY >= p->height) {\n\t\t\t\t\tcontext->pass++;\n\t\t\t\t\tcontext->curY = i->posY + 1;\n\t\t\t\t}\n", + "label": 1, + "cwe": "CWE-119", + "cve": "CVE-2019-16347", + "length": 1047 + }, + { + "index": 113663, + "code": "xsltCompilePatternInternal(const xmlChar *pattern, xmlDocPtr doc,\n\t xmlNodePtr node, xsltStylesheetPtr style,\n\t\t xsltTransformContextPtr runtime, int novar) {\n xsltParserContextPtr ctxt = NULL;\n xsltCompMatchPtr element, first = NULL, previous = NULL;\n int current, start, end, level, j;\n\n if (pattern == NULL) {\n\txsltTransformError(NULL, NULL, node,\n\t\t\t \"xsltCompilePattern : NULL pattern\\n\");\n\treturn(NULL);\n }\n\n ctxt = xsltNewParserContext(style, runtime);\n if (ctxt == NULL)\n\treturn(NULL);\n ctxt->doc = doc;\n ctxt->elem = node;\n current = end = 0;\n while (pattern[current] != 0) {\n\tstart = current;\n\twhile (IS_BLANK_CH(pattern[current]))\n\t current++;\n\tend = current;\n\tlevel = 0;\n\twhile ((pattern[end] != 0) && ((pattern[end] != '|') || (level != 0))) {\n\t if (pattern[end] == '[')\n\t\tlevel++;\n\t else if (pattern[end] == ']')\n\t\tlevel--;\n\t else if (pattern[end] == '\\'') {\n\t\tend++;\n\t\twhile ((pattern[end] != 0) && (pattern[end] != '\\''))\n\t\t end++;\n\t } else if (pattern[end] == '\"') {\n\t\tend++;\n\t\twhile ((pattern[end] != 0) && (pattern[end] != '\"'))\n\t\t end++;\n\t }\n if (pattern[end] == 0)\n break;\n\t end++;\n\t}\n\tif (current == end) {\n\t xsltTransformError(NULL, NULL, node,\n\t\t\t \"xsltCompilePattern : NULL pattern\\n\");\n\t goto error;\n\t}\n\telement = xsltNewCompMatch();\n\tif (element == NULL) {\n\t goto error;\n\t}\n\tif (first == NULL)\n\t first = element;\n\telse if (previous != NULL)\n\t previous->next = element;\n\tprevious = element;\n\n\tctxt->comp = element;\n\tctxt->base = xmlStrndup(&pattern[start], end - start);\n\tif (ctxt->base == NULL)\n\t goto error;\n\tctxt->cur = &(ctxt->base)[current - start];\n\telement->pattern = ctxt->base;\n\telement->nsList = xmlGetNsList(doc, node);\n\tj = 0;\n\tif (element->nsList != NULL) {\n\t while (element->nsList[j] != NULL)\n\t\tj++;\n\t}\n\telement->nsNr = j;\n\n\n#ifdef WITH_XSLT_DEBUG_PATTERN\n\txsltGenericDebug(xsltGenericDebugContext,\n\t\t\t \"xsltCompilePattern : parsing '%s'\\n\",\n\t\t\t element->pattern);\n#endif\n\t/*\n\t Preset default priority to be zero.\n\t This may be changed by xsltCompileLocationPathPattern.\n\t */\n\telement->priority = 0;\n\txsltCompileLocationPathPattern(ctxt, novar);\n\tif (ctxt->error) {\n\t xsltTransformError(NULL, style, node,\n\t\t\t \"xsltCompilePattern : failed to compile '%s'\\n\",\n\t\t\t element->pattern);\n\t if (style != NULL) style->errors++;\n\t goto error;\n\t}\n\n\t/*\n\t * Reverse for faster interpretation.\n\t */\n\txsltReverseCompMatch(ctxt, element);\n\n\t/*\n\t * Set-up the priority\n\t */\n\tif (element->priority == 0) {\t/* if not yet determined */\n\t if (((element->steps[0].op == XSLT_OP_ELEM) ||\n\t\t (element->steps[0].op == XSLT_OP_ATTR) ||\n\t\t (element->steps[0].op == XSLT_OP_PI)) &&\n\t\t(element->steps[0].value != NULL) &&\n\t\t(element->steps[1].op == XSLT_OP_END)) {\n\t\t;\t/* previously preset */\n\t } else if ((element->steps[0].op == XSLT_OP_ATTR) &&\n\t\t (element->steps[0].value2 != NULL) &&\n\t\t (element->steps[1].op == XSLT_OP_END)) {\n\t\t\telement->priority = -0.25;\n\t } else if ((element->steps[0].op == XSLT_OP_NS) &&\n\t\t (element->steps[0].value != NULL) &&\n\t\t (element->steps[1].op == XSLT_OP_END)) {\n\t\t\telement->priority = -0.25;\n\t } else if ((element->steps[0].op == XSLT_OP_ATTR) &&\n\t\t (element->steps[0].value == NULL) &&\n\t\t (element->steps[0].value2 == NULL) &&\n\t\t (element->steps[1].op == XSLT_OP_END)) {\n\t\t\telement->priority = -0.5;\n\t } else if (((element->steps[0].op == XSLT_OP_PI) ||\n\t\t (element->steps[0].op == XSLT_OP_TEXT) ||\n\t\t (element->steps[0].op == XSLT_OP_ALL) ||\n\t\t (element->steps[0].op == XSLT_OP_NODE) ||\n\t\t (element->steps[0].op == XSLT_OP_COMMENT)) &&\n\t\t (element->steps[1].op == XSLT_OP_END)) {\n\t\t\telement->priority = -0.5;\n\t } else {\n\t\telement->priority = 0.5;\n\t }\n\t}\n#ifdef WITH_XSLT_DEBUG_PATTERN\n\txsltGenericDebug(xsltGenericDebugContext,\n\t\t \"xsltCompilePattern : parsed %s, default priority %f\\n\",\n\t\t\t element->pattern, element->priority);\n#endif\n\tif (pattern[end] == '|')\n\t end++;\n\tcurrent = end;\n }\n if (end == 0) {\n\txsltTransformError(NULL, style, node,\n\t\t\t \"xsltCompilePattern : NULL pattern\\n\");\n\tif (style != NULL) style->errors++;\n\tgoto error;\n }\n\n xsltFreeParserContext(ctxt);\n return(first);\n\nerror:\n if (ctxt != NULL)\n\txsltFreeParserContext(ctxt);\n if (first != NULL)\n\txsltFreeCompMatchList(first);\n return(NULL);\n}\n", + "line": null, + "label": 0, + "cwe": "CWE-399", + "cve": "CVE-2012-2870", + "length": 1294 + }, + { + "index": 21223, + "code": "static int do_swap_page(struct mm_struct *mm, struct vm_area_struct *vma,\n\t\tunsigned long address, pte_t *page_table, pmd_t *pmd,\n\t\tunsigned int flags, pte_t orig_pte)\n{\n\tspinlock_t *ptl;\n\tstruct page *page, *swapcache = NULL;\n\tswp_entry_t entry;\n\tpte_t pte;\n\tint locked;\n\tstruct mem_cgroup *ptr;\n\tint exclusive = 0;\n\tint ret = 0;\n\n\tif (!pte_unmap_same(mm, pmd, page_table, orig_pte))\n\t\tgoto out;\n\n\tentry = pte_to_swp_entry(orig_pte);\n\tif (unlikely(non_swap_entry(entry))) {\n\t\tif (is_migration_entry(entry)) {\n\t\t\tmigration_entry_wait(mm, pmd, address);\n\t\t} else if (is_hwpoison_entry(entry)) {\n\t\t\tret = VM_FAULT_HWPOISON;\n\t\t} else {\n\t\t\tprint_bad_pte(vma, address, orig_pte, NULL);\n\t\t\tret = VM_FAULT_SIGBUS;\n\t\t}\n\t\tgoto out;\n\t}\n\tdelayacct_set_flag(DELAYACCT_PF_SWAPIN);\n\tpage = lookup_swap_cache(entry);\n\tif (!page) {\n\t\tgrab_swap_token(mm); /* Contend for token _before_ read-in */\n\t\tpage = swapin_readahead(entry,\n\t\t\t\t\tGFP_HIGHUSER_MOVABLE, vma, address);\n\t\tif (!page) {\n\t\t\t/*\n\t\t\t * Back out if somebody else faulted in this pte\n\t\t\t * while we released the pte lock.\n\t\t\t */\n\t\t\tpage_table = pte_offset_map_lock(mm, pmd, address, &ptl);\n\t\t\tif (likely(pte_same(*page_table, orig_pte)))\n\t\t\t\tret = VM_FAULT_OOM;\n\t\t\tdelayacct_clear_flag(DELAYACCT_PF_SWAPIN);\n\t\t\tgoto unlock;\n\t\t}\n\n\t\t/* Had to read the page from swap area: Major fault */\n\t\tret = VM_FAULT_MAJOR;\n\t\tcount_vm_event(PGMAJFAULT);\n\t\tmem_cgroup_count_vm_event(mm, PGMAJFAULT);\n\t} else if (PageHWPoison(page)) {\n\t\t/*\n\t\t * hwpoisoned dirty swapcache pages are kept for killing\n\t\t * owner processes (which may be unknown at hwpoison time)\n\t\t */\n\t\tret = VM_FAULT_HWPOISON;\n\t\tdelayacct_clear_flag(DELAYACCT_PF_SWAPIN);\n\t\tgoto out_release;\n\t}\n\n\tlocked = lock_page_or_retry(page, mm, flags);\n\tdelayacct_clear_flag(DELAYACCT_PF_SWAPIN);\n\tif (!locked) {\n\t\tret |= VM_FAULT_RETRY;\n\t\tgoto out_release;\n\t}\n\n\t/*\n\t * Make sure try_to_free_swap or reuse_swap_page or swapoff did not\n\t * release the swapcache from under us. The page pin, and pte_same\n\t * test below, are not enough to exclude that. Even if it is still\n\t * swapcache, we need to check that the page's swap has not changed.\n\t */\n\tif (unlikely(!PageSwapCache(page) || page_private(page) != entry.val))\n\t\tgoto out_page;\n\n\tif (ksm_might_need_to_copy(page, vma, address)) {\n\t\tswapcache = page;\n\t\tpage = ksm_does_need_to_copy(page, vma, address);\n\n\t\tif (unlikely(!page)) {\n\t\t\tret = VM_FAULT_OOM;\n\t\t\tpage = swapcache;\n\t\t\tswapcache = NULL;\n\t\t\tgoto out_page;\n\t\t}\n\t}\n\n\tif (mem_cgroup_try_charge_swapin(mm, page, GFP_KERNEL, &ptr)) {\n\t\tret = VM_FAULT_OOM;\n\t\tgoto out_page;\n\t}\n\n\t/*\n\t * Back out if somebody else already faulted in this pte.\n\t */\n\tpage_table = pte_offset_map_lock(mm, pmd, address, &ptl);\n\tif (unlikely(!pte_same(*page_table, orig_pte)))\n\t\tgoto out_nomap;\n\n\tif (unlikely(!PageUptodate(page))) {\n\t\tret = VM_FAULT_SIGBUS;\n\t\tgoto out_nomap;\n\t}\n\n\t/*\n\t * The page isn't present yet, go ahead with the fault.\n\t *\n\t * Be careful about the sequence of operations here.\n\t * To get its accounting right, reuse_swap_page() must be called\n\t * while the page is counted on swap but not yet in mapcount i.e.\n\t * before page_add_anon_rmap() and swap_free(); try_to_free_swap()\n\t * must be called after the swap_free(), or it will never succeed.\n\t * Because delete_from_swap_page() may be called by reuse_swap_page(),\n\t * mem_cgroup_commit_charge_swapin() may not be able to find swp_entry\n\t * in page->private. In this case, a record in swap_cgroup is silently\n\t * discarded at swap_free().\n\t */\n\n\tinc_mm_counter_fast(mm, MM_ANONPAGES);\n\tdec_mm_counter_fast(mm, MM_SWAPENTS);\n\tpte = mk_pte(page, vma->vm_page_prot);\n\tif ((flags & FAULT_FLAG_WRITE) && reuse_swap_page(page)) {\n\t\tpte = maybe_mkwrite(pte_mkdirty(pte), vma);\n\t\tflags &= ~FAULT_FLAG_WRITE;\n\t\tret |= VM_FAULT_WRITE;\n\t\texclusive = 1;\n\t}\n\tflush_icache_page(vma, page);\n\tset_pte_at(mm, address, page_table, pte);\n\tdo_page_add_anon_rmap(page, vma, address, exclusive);\n\t/* It's better to call commit-charge after rmap is established */\n\tmem_cgroup_commit_charge_swapin(page, ptr);\n\n\tswap_free(entry);\n\tif (vm_swap_full() || (vma->vm_flags & VM_LOCKED) || PageMlocked(page))\n\t\ttry_to_free_swap(page);\n\tunlock_page(page);\n\tif (swapcache) {\n\t\t/*\n\t\t * Hold the lock to avoid the swap entry to be reused\n\t\t * until we take the PT lock for the pte_same() check\n\t\t * (to avoid false positives from pte_same). For\n\t\t * further safety release the lock after the swap_free\n\t\t * so that the swap count won't change under a\n\t\t * parallel locked swapcache.\n\t\t */\n\t\tunlock_page(swapcache);\n\t\tpage_cache_release(swapcache);\n\t}\n\n\tif (flags & FAULT_FLAG_WRITE) {\n\t\tret |= do_wp_page(mm, vma, address, page_table, pmd, ptl, pte);\n\t\tif (ret & VM_FAULT_ERROR)\n\t\t\tret &= VM_FAULT_ERROR;\n\t\tgoto out;\n\t}\n\n\t/* No need to invalidate - it was non-present before */\n\tupdate_mmu_cache(vma, address, page_table);\nunlock:\n\tpte_unmap_unlock(page_table, ptl);\nout:\n\treturn ret;\nout_nomap:\n\tmem_cgroup_cancel_charge_swapin(ptr);\n\tpte_unmap_unlock(page_table, ptl);\nout_page:\n\tunlock_page(page);\nout_release:\n\tpage_cache_release(page);\n\tif (swapcache) {\n\t\tunlock_page(swapcache);\n\t\tpage_cache_release(swapcache);\n\t}\n\treturn ret;\n}\n", + "line": null, + "label": 0, + "cwe": "CWE-264", + "cve": "CVE-2012-1179", + "length": 1499 + }, + { + "index": 144127, + "code": "png_write_IHDR(png_structp png_ptr, png_uint_32 width, png_uint_32 height,\n int bit_depth, int color_type, int compression_type, int filter_type,\n int interlace_type)\n{\n#ifdef PNG_USE_LOCAL_ARRAYS\n PNG_IHDR;\n#endif\n int ret;\n\n png_byte buf[13]; /* Buffer to store the IHDR info */\n\n png_debug(1, \"in png_write_IHDR\");\n\n /* Check that we have valid input data from the application info */\n switch (color_type)\n {\n case PNG_COLOR_TYPE_GRAY:\n switch (bit_depth)\n {\n case 1:\n case 2:\n case 4:\n case 8:\n case 16: png_ptr->channels = 1; break;\n default: png_error(png_ptr,\n \"Invalid bit depth for grayscale image\");\n }\n break;\n case PNG_COLOR_TYPE_RGB:\n if (bit_depth != 8 && bit_depth != 16)\n png_error(png_ptr, \"Invalid bit depth for RGB image\");\n png_ptr->channels = 3;\n break;\n case PNG_COLOR_TYPE_PALETTE:\n switch (bit_depth)\n {\n case 1:\n case 2:\n case 4:\n case 8: png_ptr->channels = 1; break;\n default: png_error(png_ptr, \"Invalid bit depth for paletted image\");\n }\n break;\n case PNG_COLOR_TYPE_GRAY_ALPHA:\n if (bit_depth != 8 && bit_depth != 16)\n png_error(png_ptr, \"Invalid bit depth for grayscale+alpha image\");\n png_ptr->channels = 2;\n break;\n case PNG_COLOR_TYPE_RGB_ALPHA:\n if (bit_depth != 8 && bit_depth != 16)\n png_error(png_ptr, \"Invalid bit depth for RGBA image\");\n png_ptr->channels = 4;\n break;\n default:\n png_error(png_ptr, \"Invalid image color type specified\");\n }\n\n if (compression_type != PNG_COMPRESSION_TYPE_BASE)\n {\n png_warning(png_ptr, \"Invalid compression type specified\");\n compression_type = PNG_COMPRESSION_TYPE_BASE;\n }\n\n /* Write filter_method 64 (intrapixel differencing) only if\n * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and\n * 2. Libpng did not write a PNG signature (this filter_method is only\n * used in PNG datastreams that are embedded in MNG datastreams) and\n * 3. The application called png_permit_mng_features with a mask that\n * included PNG_FLAG_MNG_FILTER_64 and\n * 4. The filter_method is 64 and\n * 5. The color_type is RGB or RGBA\n */\n if (\n#ifdef PNG_MNG_FEATURES_SUPPORTED\n !((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&\n ((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE) == 0) &&\n (color_type == PNG_COLOR_TYPE_RGB ||\n color_type == PNG_COLOR_TYPE_RGB_ALPHA) &&\n (filter_type == PNG_INTRAPIXEL_DIFFERENCING)) &&\n#endif\n filter_type != PNG_FILTER_TYPE_BASE)\n {\n png_warning(png_ptr, \"Invalid filter type specified\");\n filter_type = PNG_FILTER_TYPE_BASE;\n }\n\n#ifdef PNG_WRITE_INTERLACING_SUPPORTED\n if (interlace_type != PNG_INTERLACE_NONE &&\n interlace_type != PNG_INTERLACE_ADAM7)\n {\n png_warning(png_ptr, \"Invalid interlace type specified\");\n interlace_type = PNG_INTERLACE_ADAM7;\n }\n#else\n interlace_type=PNG_INTERLACE_NONE;\n#endif\n\n /* Save the relevent information */\n png_ptr->bit_depth = (png_byte)bit_depth;\n png_ptr->color_type = (png_byte)color_type;\n png_ptr->interlaced = (png_byte)interlace_type;\n#ifdef PNG_MNG_FEATURES_SUPPORTED\n png_ptr->filter_type = (png_byte)filter_type;\n#endif\n png_ptr->compression_type = (png_byte)compression_type;\n png_ptr->width = width;\n png_ptr->height = height;\n\n png_ptr->pixel_depth = (png_byte)(bit_depth * png_ptr->channels);\n png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth, width);\n /* Set the usr info, so any transformations can modify it */\n png_ptr->usr_width = png_ptr->width;\n png_ptr->usr_bit_depth = png_ptr->bit_depth;\n png_ptr->usr_channels = png_ptr->channels;\n\n /* Pack the header information into the buffer */\n png_save_uint_32(buf, width);\n png_save_uint_32(buf + 4, height);\n buf[8] = (png_byte)bit_depth;\n buf[9] = (png_byte)color_type;\n buf[10] = (png_byte)compression_type;\n buf[11] = (png_byte)filter_type;\n buf[12] = (png_byte)interlace_type;\n\n /* Write the chunk */\n png_write_chunk(png_ptr, (png_bytep)png_IHDR, buf, (png_size_t)13);\n\n /* Initialize zlib with PNG info */\n png_ptr->zstream.zalloc = png_zalloc;\n png_ptr->zstream.zfree = png_zfree;\n png_ptr->zstream.opaque = (voidpf)png_ptr;\n if (!(png_ptr->do_filter))\n {\n if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE ||\n png_ptr->bit_depth < 8)\n png_ptr->do_filter = PNG_FILTER_NONE;\n else\n png_ptr->do_filter = PNG_ALL_FILTERS;\n }\n if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_STRATEGY))\n {\n if (png_ptr->do_filter != PNG_FILTER_NONE)\n png_ptr->zlib_strategy = Z_FILTERED;\n else\n png_ptr->zlib_strategy = Z_DEFAULT_STRATEGY;\n }\n if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_LEVEL))\n png_ptr->zlib_level = Z_DEFAULT_COMPRESSION;\n if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL))\n png_ptr->zlib_mem_level = 8;\n if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS))\n png_ptr->zlib_window_bits = 15;\n if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_METHOD))\n png_ptr->zlib_method = 8;\n ret = deflateInit2(&png_ptr->zstream, png_ptr->zlib_level,\n png_ptr->zlib_method, png_ptr->zlib_window_bits,\n png_ptr->zlib_mem_level, png_ptr->zlib_strategy);\n if (ret != Z_OK)\n {\n if (ret == Z_VERSION_ERROR) png_error(png_ptr,\n \"zlib failed to initialize compressor -- version error\");\n if (ret == Z_STREAM_ERROR) png_error(png_ptr,\n \"zlib failed to initialize compressor -- stream error\");\n if (ret == Z_MEM_ERROR) png_error(png_ptr,\n \"zlib failed to initialize compressor -- mem error\");\n png_error(png_ptr, \"zlib failed to initialize compressor\");\n }\n png_ptr->zstream.next_out = png_ptr->zbuf;\n png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;\n /* libpng is not interested in zstream.data_type */\n /* Set it to a predefined value, to avoid its evaluation inside zlib */\n png_ptr->zstream.data_type = Z_BINARY;\n\n png_ptr->mode = PNG_HAVE_IHDR;\n}\n", + "line": null, + "label": 0, + "cwe": "CWE-119", + "cve": "CVE-2015-8126", + "length": 1652 + }, + { + "index": 16552, + "code": "email_open( const char *email_addr, const char *subject )\n{\n\tchar *Mailer;\n\tchar *SmtpServer = NULL;\n\tchar *FromAddress = NULL;\n\tchar *FinalSubject;\n\tchar *FinalAddr;\n\tchar *temp;\n\tint token_boundary;\n\tint num_addresses;\n\tint arg_index;\n\tFILE *mailerstream;\n\n\tif ( (Mailer = param(\"MAIL\")) == NULL ) {\n\t\tdprintf(D_FULLDEBUG,\n\t\t\t\"Trying to email, but MAIL not specified in config file\\n\");\n\t\treturn NULL;\n\t}\n\n\t/* Take care of the subject. */\n\tif ( subject ) {\n\t\tsize_t prolog_length = strlen(EMAIL_SUBJECT_PROLOG);\n\t\tsize_t subject_length = strlen(subject);\n\t\tFinalSubject = (char *)malloc(prolog_length + subject_length + 1);\n\t\tmemcpy(FinalSubject, EMAIL_SUBJECT_PROLOG, prolog_length);\n\t\tmemcpy(&FinalSubject[prolog_length], subject, subject_length);\n\t\tFinalSubject[prolog_length + subject_length] = '\\0';\n\t}\n\telse {\n\t\tFinalSubject = strdup(EMAIL_SUBJECT_PROLOG);\n\t}\n\n\t/** The following will not cause a fatal error, it just means\n\t\tthat on Windows we may construct an invalid \"from\" address. */\n\tFromAddress = param(\"MAIL_FROM\");\n\t\n#ifdef WIN32\n\t/* On WinNT, we need to be given an SMTP server, and we must pass\n\t * this servername to the Mailer with a -relay option.\n\t */\n\tif ( (SmtpServer=param(\"SMTP_SERVER\")) == NULL ) {\n\t\tdprintf(D_FULLDEBUG,\n\t\t\t\"Trying to email, but SMTP_SERVER not specified in config file\\n\");\n\t\tfree(Mailer);\n\t\tfree(FinalSubject);\n\t\tif (FromAddress) free(FromAddress);\n\t\treturn NULL;\n\t}\n#endif \t\n\n\t/* Take care of destination email address. If it is NULL, grab \n\t * the email of the Condor admin from the config file.\n\t * We strdup this since we modify it (we split it into tokens so that\n\t * each address is a separate argument to the mailer).\n\t */\n\tif ( email_addr ) {\n\t\tFinalAddr = strdup(email_addr);\n\t} else {\n\t\tif ( (FinalAddr = param(\"CONDOR_ADMIN\")) == NULL ) {\n\t\t\tdprintf(D_FULLDEBUG,\n\t\t\t\t\"Trying to email, but CONDOR_ADMIN not specified in config file\\n\");\n\t\t\tfree(Mailer);\n\t\t\tfree(FinalSubject);\n\t\t\tif (FromAddress) free(FromAddress);\n\t\t\tif (SmtpServer) free(SmtpServer);\n\t\t\treturn NULL;\n\t\t}\n\t}\n\n\t/* Now tokenize the list of addresses on commas and/or spaces (by replacing\n\t * commas and spaces with nils). We also count the addresses here so we\n\t * know how large to make our argument vector\n\t */\n\ttoken_boundary = TRUE;\n\tnum_addresses = 0;\n\tfor (temp = FinalAddr; *temp != '\\0'; temp++) {\n\t\tif (*temp == ',' || *temp == ' ') {\n\t\t\t*temp = '\\0';\n\t\t\ttoken_boundary = TRUE;\n\t\t}\n\t\telse if (token_boundary) {\n\t\t\tnum_addresses++;\n\t\t\ttoken_boundary = FALSE;\n\t\t}\n\t}\n\tif (num_addresses == 0) {\n\t\tdprintf(D_FULLDEBUG, \"Trying to email, but address list is empty\\n\");\n\t\tfree(Mailer);\n\t\tfree(FinalSubject);\n\t\tif (FromAddress) free(FromAddress);\n\t\tif (SmtpServer) free(SmtpServer);\n\t\tfree(FinalAddr);\n\t\treturn NULL;\n\t}\n\n\t/* construct the argument vector for the mailer */\n\tconst char * * final_args;\n\tfinal_args = (char const * *)malloc((8 + num_addresses) * sizeof(char*));\n\tif (final_args == NULL) {\n\t\tEXCEPT(\"Out of memory\");\n\t}\n\targ_index = 0;\n\tfinal_args[arg_index++] = Mailer;\n\tfinal_args[arg_index++] = \"-s\";\n\tfinal_args[arg_index++] = FinalSubject;\n\tif (FromAddress) {\n\t\tfinal_args[arg_index++] = \"-f\";\n\t\tfinal_args[arg_index++] = FromAddress;\n\t}\n\tif (SmtpServer) {\n\t\tfinal_args[arg_index++] = \"-relay\";\n\t\tfinal_args[arg_index++] = SmtpServer;\n\t}\n\ttemp = FinalAddr;\n\tfor (;;) {\n\t\twhile (*temp == '\\0') temp++;\n\t\tfinal_args[arg_index++] = temp;\n\t\tif (--num_addresses == 0) break;\n\t\twhile (*temp != '\\0') temp++;\n\t}\n\tfinal_args[arg_index] = NULL;\n\n/* NEW CODE */\n\t/* open a FILE* so that the mail we get will end up from condor,\n\t\tand not from root */\n#ifdef WIN32\n\tmailerstream = email_open_implementation(Mailer, final_args);\n#else\n\tmailerstream = email_open_implementation(final_args);\n#endif\n\n\tif ( mailerstream ) {\n\t\tfprintf(mailerstream,\"This is an automated email from the Condor \"\n\t\t\t\"system\\non machine \\\"%s\\\". Do not reply.\\n\\n\",get_local_fqdn().Value());\n\t}\n\n\t/* free up everything we strdup-ed and param-ed, and return result */\n\tfree(Mailer);\n\tfree(FinalSubject);\n\tif (FromAddress) free(FromAddress);\n\tif (SmtpServer) free(SmtpServer);\n\tfree(FinalAddr);\n\tfree(final_args);\n\n\treturn mailerstream;\n}\n", + "line": null, + "label": 0, + "cwe": "CWE-134", + "cve": "CVE-2011-4930", + "length": 1135 + }, + { + "index": 66974, + "code": "int attribute_align_arg avcodec_encode_audio2(AVCodecContext *avctx,\n AVPacket *avpkt,\n const AVFrame *frame,\n int *got_packet_ptr)\n{\n AVFrame *extended_frame = NULL;\n AVFrame *padded_frame = NULL;\n int ret;\n AVPacket user_pkt = *avpkt;\n int needs_realloc = !user_pkt.data;\n\n *got_packet_ptr = 0;\n\n if (!avctx->codec->encode2) {\n av_log(avctx, AV_LOG_ERROR, \"This encoder requires using the avcodec_send_frame() API.\\n\");\n return AVERROR(ENOSYS);\n }\n\n if (!(avctx->codec->capabilities & AV_CODEC_CAP_DELAY) && !frame) {\n av_packet_unref(avpkt);\n av_init_packet(avpkt);\n return 0;\n }\n\n /* ensure that extended_data is properly set */\n if (frame && !frame->extended_data) {\n if (av_sample_fmt_is_planar(avctx->sample_fmt) &&\n avctx->channels > AV_NUM_DATA_POINTERS) {\n av_log(avctx, AV_LOG_ERROR, \"Encoding to a planar sample format, \"\n \"with more than %d channels, but extended_data is not set.\\n\",\n AV_NUM_DATA_POINTERS);\n return AVERROR(EINVAL);\n }\n av_log(avctx, AV_LOG_WARNING, \"extended_data is not set.\\n\");\n\n extended_frame = av_frame_alloc();\n if (!extended_frame)\n return AVERROR(ENOMEM);\n\n memcpy(extended_frame, frame, sizeof(AVFrame));\n extended_frame->extended_data = extended_frame->data;\n frame = extended_frame;\n }\n\n /* extract audio service type metadata */\n if (frame) {\n AVFrameSideData *sd = av_frame_get_side_data(frame, AV_FRAME_DATA_AUDIO_SERVICE_TYPE);\n if (sd && sd->size >= sizeof(enum AVAudioServiceType))\n avctx->audio_service_type = *(enum AVAudioServiceType*)sd->data;\n }\n\n /* check for valid frame size */\n if (frame) {\n if (avctx->codec->capabilities & AV_CODEC_CAP_SMALL_LAST_FRAME) {\n if (frame->nb_samples > avctx->frame_size) {\n av_log(avctx, AV_LOG_ERROR, \"more samples than frame size (avcodec_encode_audio2)\\n\");\n ret = AVERROR(EINVAL);\n goto end;\n }\n } else if (!(avctx->codec->capabilities & AV_CODEC_CAP_VARIABLE_FRAME_SIZE)) {\n if (frame->nb_samples < avctx->frame_size &&\n !avctx->internal->last_audio_frame) {\n ret = pad_last_frame(avctx, &padded_frame, frame);\n if (ret < 0)\n goto end;\n\n frame = padded_frame;\n avctx->internal->last_audio_frame = 1;\n }\n\n if (frame->nb_samples != avctx->frame_size) {\n av_log(avctx, AV_LOG_ERROR, \"nb_samples (%d) != frame_size (%d) (avcodec_encode_audio2)\\n\", frame->nb_samples, avctx->frame_size);\n ret = AVERROR(EINVAL);\n goto end;\n }\n }\n }\n\n av_assert0(avctx->codec->encode2);\n\n ret = avctx->codec->encode2(avctx, avpkt, frame, got_packet_ptr);\n if (!ret) {\n if (*got_packet_ptr) {\n if (!(avctx->codec->capabilities & AV_CODEC_CAP_DELAY)) {\n if (avpkt->pts == AV_NOPTS_VALUE)\n avpkt->pts = frame->pts;\n if (!avpkt->duration)\n avpkt->duration = ff_samples_to_time_base(avctx,\n frame->nb_samples);\n }\n avpkt->dts = avpkt->pts;\n } else {\n avpkt->size = 0;\n }\n }\n if (avpkt->data && avpkt->data == avctx->internal->byte_buffer) {\n needs_realloc = 0;\n if (user_pkt.data) {\n if (user_pkt.size >= avpkt->size) {\n memcpy(user_pkt.data, avpkt->data, avpkt->size);\n } else {\n av_log(avctx, AV_LOG_ERROR, \"Provided packet is too small, needs to be %d\\n\", avpkt->size);\n avpkt->size = user_pkt.size;\n ret = -1;\n }\n avpkt->buf = user_pkt.buf;\n avpkt->data = user_pkt.data;\n } else {\n if (av_dup_packet(avpkt) < 0) {\n ret = AVERROR(ENOMEM);\n }\n }\n }\n\n if (!ret) {\n if (needs_realloc && avpkt->data) {\n ret = av_buffer_realloc(&avpkt->buf, avpkt->size + AV_INPUT_BUFFER_PADDING_SIZE);\n if (ret >= 0)\n avpkt->data = avpkt->buf->data;\n }\n\n avctx->frame_number++;\n }\n\n if (ret < 0 || !*got_packet_ptr) {\n av_packet_unref(avpkt);\n av_init_packet(avpkt);\n goto end;\n }\n\n /* NOTE: if we add any audio encoders which output non-keyframe packets,\n * this needs to be moved to the encoders, but for now we can do it\n * here to simplify things */\n avpkt->flags |= AV_PKT_FLAG_KEY;\n\nend:\n av_frame_free(&padded_frame);\n av_free(extended_frame);\n\n#if FF_API_AUDIOENC_DELAY\n avctx->delay = avctx->initial_padding;\n#endif\n\n return ret;\n}\n", + "line": null, + "label": 0, + "cwe": "CWE-787", + "cve": "CVE-2017-7865", + "length": 1220 + }, + { + "index": 31899, + "code": "SYSCALL_DEFINE5(perf_event_open,\n\t\tstruct perf_event_attr __user *, attr_uptr,\n\t\tpid_t, pid, int, cpu, int, group_fd, unsigned long, flags)\n{\n\tstruct perf_event *group_leader = NULL, *output_event = NULL;\n\tstruct perf_event *event, *sibling;\n\tstruct perf_event_attr attr;\n\tstruct perf_event_context *ctx;\n\tstruct file *event_file = NULL;\n\tstruct fd group = {NULL, 0};\n\tstruct task_struct *task = NULL;\n\tstruct pmu *pmu;\n\tint event_fd;\n\tint move_group = 0;\n\tint err;\n\n\t/* for future expandability... */\n\tif (flags & ~PERF_FLAG_ALL)\n\t\treturn -EINVAL;\n\n\terr = perf_copy_attr(attr_uptr, &attr);\n\tif (err)\n\t\treturn err;\n\n\tif (!attr.exclude_kernel) {\n\t\tif (perf_paranoid_kernel() && !capable(CAP_SYS_ADMIN))\n\t\t\treturn -EACCES;\n\t}\n\n\tif (attr.freq) {\n\t\tif (attr.sample_freq > sysctl_perf_event_sample_rate)\n\t\t\treturn -EINVAL;\n\t}\n\n\t/*\n\t * In cgroup mode, the pid argument is used to pass the fd\n\t * opened to the cgroup directory in cgroupfs. The cpu argument\n\t * designates the cpu on which to monitor threads from that\n\t * cgroup.\n\t */\n\tif ((flags & PERF_FLAG_PID_CGROUP) && (pid == -1 || cpu == -1))\n\t\treturn -EINVAL;\n\n\tevent_fd = get_unused_fd();\n\tif (event_fd < 0)\n\t\treturn event_fd;\n\n\tif (group_fd != -1) {\n\t\terr = perf_fget_light(group_fd, &group);\n\t\tif (err)\n\t\t\tgoto err_fd;\n\t\tgroup_leader = group.file->private_data;\n\t\tif (flags & PERF_FLAG_FD_OUTPUT)\n\t\t\toutput_event = group_leader;\n\t\tif (flags & PERF_FLAG_FD_NO_GROUP)\n\t\t\tgroup_leader = NULL;\n\t}\n\n\tif (pid != -1 && !(flags & PERF_FLAG_PID_CGROUP)) {\n\t\ttask = find_lively_task_by_vpid(pid);\n\t\tif (IS_ERR(task)) {\n\t\t\terr = PTR_ERR(task);\n\t\t\tgoto err_group_fd;\n\t\t}\n\t}\n\n\tget_online_cpus();\n\n\tevent = perf_event_alloc(&attr, cpu, task, group_leader, NULL,\n\t\t\t\t NULL, NULL);\n\tif (IS_ERR(event)) {\n\t\terr = PTR_ERR(event);\n\t\tgoto err_task;\n\t}\n\n\tif (flags & PERF_FLAG_PID_CGROUP) {\n\t\terr = perf_cgroup_connect(pid, event, &attr, group_leader);\n\t\tif (err)\n\t\t\tgoto err_alloc;\n\t\t/*\n\t\t * one more event:\n\t\t * - that has cgroup constraint on event->cpu\n\t\t * - that may need work on context switch\n\t\t */\n\t\tatomic_inc(&per_cpu(perf_cgroup_events, event->cpu));\n\t\tstatic_key_slow_inc(&perf_sched_events.key);\n\t}\n\n\t/*\n\t * Special case software events and allow them to be part of\n\t * any hardware group.\n\t */\n\tpmu = event->pmu;\n\n\tif (group_leader &&\n\t (is_software_event(event) != is_software_event(group_leader))) {\n\t\tif (is_software_event(event)) {\n\t\t\t/*\n\t\t\t * If event and group_leader are not both a software\n\t\t\t * event, and event is, then group leader is not.\n\t\t\t *\n\t\t\t * Allow the addition of software events to !software\n\t\t\t * groups, this is safe because software events never\n\t\t\t * fail to schedule.\n\t\t\t */\n\t\t\tpmu = group_leader->pmu;\n\t\t} else if (is_software_event(group_leader) &&\n\t\t\t (group_leader->group_flags & PERF_GROUP_SOFTWARE)) {\n\t\t\t/*\n\t\t\t * In case the group is a pure software group, and we\n\t\t\t * try to add a hardware event, move the whole group to\n\t\t\t * the hardware context.\n\t\t\t */\n\t\t\tmove_group = 1;\n\t\t}\n\t}\n\n\t/*\n\t * Get the target context (task or percpu):\n\t */\n\tctx = find_get_context(pmu, task, event->cpu);\n\tif (IS_ERR(ctx)) {\n\t\terr = PTR_ERR(ctx);\n\t\tgoto err_alloc;\n\t}\n\n\tif (task) {\n\t\tput_task_struct(task);\n\t\ttask = NULL;\n\t}\n\n\t/*\n\t * Look up the group leader (we will attach this event to it):\n\t */\n\tif (group_leader) {\n\t\terr = -EINVAL;\n\n\t\t/*\n\t\t * Do not allow a recursive hierarchy (this new sibling\n\t\t * becoming part of another group-sibling):\n\t\t */\n\t\tif (group_leader->group_leader != group_leader)\n\t\t\tgoto err_context;\n\t\t/*\n\t\t * Do not allow to attach to a group in a different\n\t\t * task or CPU context:\n\t\t */\n\t\tif (move_group) {\n\t\t\tif (group_leader->ctx->type != ctx->type)\n\t\t\t\tgoto err_context;\n\t\t} else {\n\t\t\tif (group_leader->ctx != ctx)\n\t\t\t\tgoto err_context;\n\t\t}\n\n\t\t/*\n\t\t * Only a group leader can be exclusive or pinned\n\t\t */\n\t\tif (attr.exclusive || attr.pinned)\n\t\t\tgoto err_context;\n\t}\n\n\tif (output_event) {\n\t\terr = perf_event_set_output(event, output_event);\n\t\tif (err)\n\t\t\tgoto err_context;\n\t}\n\n\tevent_file = anon_inode_getfile(\"[perf_event]\", &perf_fops, event, O_RDWR);\n\tif (IS_ERR(event_file)) {\n\t\terr = PTR_ERR(event_file);\n\t\tgoto err_context;\n\t}\n\n\tif (move_group) {\n\t\tstruct perf_event_context *gctx = group_leader->ctx;\n\n\t\tmutex_lock(&gctx->mutex);\n\t\tperf_remove_from_context(group_leader);\n\n\t\t/*\n\t\t * Removing from the context ends up with disabled\n\t\t * event. What we want here is event in the initial\n\t\t * startup state, ready to be add into new context.\n\t\t */\n\t\tperf_event__state_init(group_leader);\n\t\tlist_for_each_entry(sibling, &group_leader->sibling_list,\n\t\t\t\t group_entry) {\n\t\t\tperf_remove_from_context(sibling);\n\t\t\tperf_event__state_init(sibling);\n\t\t\tput_ctx(gctx);\n\t\t}\n\t\tmutex_unlock(&gctx->mutex);\n\t\tput_ctx(gctx);\n\t}\n\n\tWARN_ON_ONCE(ctx->parent_ctx);\n\tmutex_lock(&ctx->mutex);\n\n\tif (move_group) {\n\t\tsynchronize_rcu();\n\t\tperf_install_in_context(ctx, group_leader, event->cpu);\n\t\tget_ctx(ctx);\n\t\tlist_for_each_entry(sibling, &group_leader->sibling_list,\n\t\t\t\t group_entry) {\n\t\t\tperf_install_in_context(ctx, sibling, event->cpu);\n\t\t\tget_ctx(ctx);\n\t\t}\n\t}\n\n\tperf_install_in_context(ctx, event, event->cpu);\n\t++ctx->generation;\n\tperf_unpin_context(ctx);\n\tmutex_unlock(&ctx->mutex);\n\n\tput_online_cpus();\n\n\tevent->owner = current;\n\n\tmutex_lock(¤t->perf_event_mutex);\n\tlist_add_tail(&event->owner_entry, ¤t->perf_event_list);\n\tmutex_unlock(¤t->perf_event_mutex);\n\n\t/*\n\t * Precalculate sample_data sizes\n\t */\n\tperf_event__header_size(event);\n\tperf_event__id_header_size(event);\n\n\t/*\n\t * Drop the reference on the group_event after placing the\n\t * new event on the sibling_list. This ensures destruction\n\t * of the group leader will find the pointer to itself in\n\t * perf_group_detach().\n\t */\n\tfdput(group);\n\tfd_install(event_fd, event_file);\n\treturn event_fd;\n\nerr_context:\n\tperf_unpin_context(ctx);\n\tput_ctx(ctx);\nerr_alloc:\n\tfree_event(event);\nerr_task:\n\tput_online_cpus();\n\tif (task)\n\t\tput_task_struct(task);\nerr_group_fd:\n\tfdput(group);\nerr_fd:\n\tput_unused_fd(event_fd);\n\treturn err;\n}\n", + "line": null, + "label": 0, + "cwe": "CWE-189", + "cve": "CVE-2013-2094", + "length": 1648 + }, + { + "index": 89172, + "code": "is_exclusive(Node* x, Node* y, regex_t* reg)\n{\n int i, len;\n OnigCodePoint code;\n UChar *p;\n NodeType ytype;\n\n retry:\n ytype = NODE_TYPE(y);\n switch (NODE_TYPE(x)) {\n case NODE_CTYPE:\n {\n if (CTYPE_(x)->ctype == CTYPE_ANYCHAR ||\n CTYPE_(y)->ctype == CTYPE_ANYCHAR)\n break;\n\n switch (ytype) {\n case NODE_CTYPE:\n if (CTYPE_(y)->ctype == CTYPE_(x)->ctype &&\n CTYPE_(y)->not != CTYPE_(x)->not &&\n CTYPE_(y)->ascii_mode == CTYPE_(x)->ascii_mode)\n return 1;\n else\n return 0;\n break;\n\n case NODE_CCLASS:\n swap:\n {\n Node* tmp;\n tmp = x; x = y; y = tmp;\n goto retry;\n }\n break;\n\n case NODE_STRING:\n goto swap;\n break;\n\n default:\n break;\n }\n }\n break;\n\n case NODE_CCLASS:\n {\n int range;\n CClassNode* xc = CCLASS_(x);\n\n switch (ytype) {\n case NODE_CTYPE:\n switch (CTYPE_(y)->ctype) {\n case CTYPE_ANYCHAR:\n return 0;\n break;\n\n case ONIGENC_CTYPE_WORD:\n if (CTYPE_(y)->not == 0) {\n if (IS_NULL(xc->mbuf) && !IS_NCCLASS_NOT(xc)) {\n range = CTYPE_(y)->ascii_mode != 0 ? 128 : SINGLE_BYTE_SIZE;\n for (i = 0; i < range; i++) {\n if (BITSET_AT(xc->bs, i)) {\n if (ONIGENC_IS_CODE_WORD(reg->enc, i)) return 0;\n }\n }\n return 1;\n }\n return 0;\n }\n else {\n if (IS_NOT_NULL(xc->mbuf)) return 0;\n if (IS_NCCLASS_NOT(xc)) return 0;\n\n range = CTYPE_(y)->ascii_mode != 0 ? 128 : SINGLE_BYTE_SIZE;\n for (i = 0; i < range; i++) {\n if (! ONIGENC_IS_CODE_WORD(reg->enc, i)) {\n if (BITSET_AT(xc->bs, i))\n return 0;\n }\n }\n for (i = range; i < SINGLE_BYTE_SIZE; i++) {\n if (BITSET_AT(xc->bs, i)) return 0;\n }\n return 1;\n }\n break;\n\n default:\n break;\n }\n break;\n\n case NODE_CCLASS:\n {\n int v;\n CClassNode* yc = CCLASS_(y);\n\n for (i = 0; i < SINGLE_BYTE_SIZE; i++) {\n v = BITSET_AT(xc->bs, i);\n if ((v != 0 && !IS_NCCLASS_NOT(xc)) || (v == 0 && IS_NCCLASS_NOT(xc))) {\n v = BITSET_AT(yc->bs, i);\n if ((v != 0 && !IS_NCCLASS_NOT(yc)) ||\n (v == 0 && IS_NCCLASS_NOT(yc)))\n return 0;\n }\n }\n if ((IS_NULL(xc->mbuf) && !IS_NCCLASS_NOT(xc)) ||\n (IS_NULL(yc->mbuf) && !IS_NCCLASS_NOT(yc)))\n return 1;\n return 0;\n }\n break;\n\n case NODE_STRING:\n goto swap;\n break;\n\n default:\n break;\n }\n }\n break;\n\n case NODE_STRING:\n {\n StrNode* xs = STR_(x);\n\n if (NODE_STRING_LEN(x) == 0)\n break;\n\n switch (ytype) {\n case NODE_CTYPE:\n switch (CTYPE_(y)->ctype) {\n case CTYPE_ANYCHAR:\n break;\n\n case ONIGENC_CTYPE_WORD:\n if (CTYPE_(y)->ascii_mode == 0) {\n if (ONIGENC_IS_MBC_WORD(reg->enc, xs->s, xs->end))\n return CTYPE_(y)->not;\n else\n return !(CTYPE_(y)->not);\n }\n else {\n if (ONIGENC_IS_MBC_WORD_ASCII(reg->enc, xs->s, xs->end))\n return CTYPE_(y)->not;\n else\n return !(CTYPE_(y)->not);\n }\n break;\n default:\n break;\n }\n break;\n\n case NODE_CCLASS:\n {\n CClassNode* cc = CCLASS_(y);\n\n code = ONIGENC_MBC_TO_CODE(reg->enc, xs->s,\n xs->s + ONIGENC_MBC_MAXLEN(reg->enc));\n return onig_is_code_in_cc(reg->enc, code, cc) == 0;\n }\n break;\n\n case NODE_STRING:\n {\n UChar *q;\n StrNode* ys = STR_(y);\n\n len = NODE_STRING_LEN(x);\n if (len > NODE_STRING_LEN(y)) len = NODE_STRING_LEN(y);\n if (NODE_STRING_IS_AMBIG(x) || NODE_STRING_IS_AMBIG(y)) {\n /* tiny version */\n return 0;\n }\n else {\n for (i = 0, p = ys->s, q = xs->s; i < len; i++, p++, q++) {\n if (*p != *q) return 1;\n }\n }\n }\n break;\n\n default:\n break;\n }\n }\n break;\n\n default:\n break;\n }\n\n return 0;\n}\n", + "line": null, + "label": 0, + "cwe": "CWE-476", + "cve": "CVE-2019-13225", + "length": 1248 + }, + { + "index": 68012, + "code": "static MagickBooleanType WriteSUNImage(const ImageInfo *image_info,Image *image)\n{\n#define RMT_EQUAL_RGB 1\n#define RMT_NONE 0\n#define RMT_RAW 2\n#define RT_STANDARD 1\n#define RT_FORMAT_RGB 3\n\n typedef struct _SUNInfo\n {\n unsigned int\n magic,\n width,\n height,\n depth,\n length,\n type,\n maptype,\n maplength;\n } SUNInfo;\n\n MagickBooleanType\n status;\n\n MagickOffsetType\n scene;\n\n MagickSizeType\n number_pixels;\n\n register const IndexPacket\n *indexes;\n\n register const PixelPacket\n *p;\n\n register ssize_t\n i,\n x;\n\n ssize_t\n y;\n\n SUNInfo\n sun_info;\n\n /*\n Open output image file.\n */\n assert(image_info != (const ImageInfo *) NULL);\n assert(image_info->signature == MagickSignature);\n assert(image != (Image *) NULL);\n assert(image->signature == MagickSignature);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",image->filename);\n status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);\n if (status == MagickFalse)\n return(status);\n scene=0;\n do\n {\n /*\n Initialize SUN raster file header.\n */\n (void) TransformImageColorspace(image,sRGBColorspace);\n sun_info.magic=0x59a66a95;\n if ((image->columns != (unsigned int) image->columns) ||\n (image->rows != (unsigned int) image->rows))\n ThrowWriterException(ImageError,\"WidthOrHeightExceedsLimit\");\n sun_info.width=(unsigned int) image->columns;\n sun_info.height=(unsigned int) image->rows;\n sun_info.type=(unsigned int) (image->storage_class == DirectClass ?\n RT_FORMAT_RGB : RT_STANDARD);\n sun_info.maptype=RMT_NONE;\n sun_info.maplength=0;\n number_pixels=(MagickSizeType) image->columns*image->rows;\n if ((4*number_pixels) != (size_t) (4*number_pixels))\n ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\");\n if (image->storage_class == DirectClass)\n {\n /*\n Full color SUN raster.\n */\n sun_info.depth=(unsigned int) image->matte ? 32U : 24U;\n sun_info.length=(unsigned int) ((image->matte ? 4 : 3)*number_pixels);\n sun_info.length+=sun_info.length & 0x01 ? (unsigned int) image->rows :\n 0;\n }\n else\n if (SetImageMonochrome(image,&image->exception))\n {\n /*\n Monochrome SUN raster.\n */\n sun_info.depth=1;\n sun_info.length=(unsigned int) (((image->columns+7) >> 3)*\n image->rows);\n sun_info.length+=(unsigned int) (((image->columns/8)+(image->columns %\n 8 ? 1 : 0)) % 2 ? image->rows : 0);\n }\n else\n {\n /*\n Colormapped SUN raster.\n */\n sun_info.depth=8;\n sun_info.length=(unsigned int) number_pixels;\n sun_info.length+=(unsigned int) (image->columns & 0x01 ? image->rows :\n 0);\n sun_info.maptype=RMT_EQUAL_RGB;\n sun_info.maplength=(unsigned int) (3*image->colors);\n }\n /*\n Write SUN header.\n */\n (void) WriteBlobMSBLong(image,sun_info.magic);\n (void) WriteBlobMSBLong(image,sun_info.width);\n (void) WriteBlobMSBLong(image,sun_info.height);\n (void) WriteBlobMSBLong(image,sun_info.depth);\n (void) WriteBlobMSBLong(image,sun_info.length);\n (void) WriteBlobMSBLong(image,sun_info.type);\n (void) WriteBlobMSBLong(image,sun_info.maptype);\n (void) WriteBlobMSBLong(image,sun_info.maplength);\n /*\n Convert MIFF to SUN raster pixels.\n */\n x=0;\n y=0;\n if (image->storage_class == DirectClass)\n {\n register unsigned char\n *q;\n\n size_t\n bytes_per_pixel,\n length;\n\n unsigned char\n *pixels;\n\n /*\n Allocate memory for pixels.\n */\n bytes_per_pixel=3;\n if (image->matte != MagickFalse)\n bytes_per_pixel++;\n length=image->columns;\n pixels=(unsigned char *) AcquireQuantumMemory(length,4*sizeof(*pixels));\n if (pixels == (unsigned char *) NULL)\n ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\");\n /*\n Convert DirectClass packet to SUN RGB pixel.\n */\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);\n if (p == (const PixelPacket *) NULL)\n break;\n q=pixels;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n if (image->matte != MagickFalse)\n *q++=ScaleQuantumToChar(GetPixelAlpha(p));\n *q++=ScaleQuantumToChar(GetPixelRed(p));\n *q++=ScaleQuantumToChar(GetPixelGreen(p));\n *q++=ScaleQuantumToChar(GetPixelBlue(p));\n p++;\n }\n if (((bytes_per_pixel*image->columns) & 0x01) != 0)\n *q++='\\0'; /* pad scanline */\n (void) WriteBlob(image,(size_t) (q-pixels),pixels);\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,\n image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n pixels=(unsigned char *) RelinquishMagickMemory(pixels);\n }\n else\n if (SetImageMonochrome(image,&image->exception))\n {\n register unsigned char\n bit,\n byte;\n\n /*\n Convert PseudoClass image to a SUN monochrome image.\n */\n (void) SetImageType(image,BilevelType);\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);\n if (p == (const PixelPacket *) NULL)\n break;\n indexes=GetVirtualIndexQueue(image);\n bit=0;\n byte=0;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n byte<<=1;\n if (GetPixelLuma(image,p) < (QuantumRange/2.0))\n byte|=0x01;\n bit++;\n if (bit == 8)\n {\n (void) WriteBlobByte(image,byte);\n bit=0;\n byte=0;\n }\n p++;\n }\n if (bit != 0)\n (void) WriteBlobByte(image,(unsigned char) (byte << (8-bit)));\n if ((((image->columns/8)+\n (image->columns % 8 ? 1 : 0)) % 2) != 0)\n (void) WriteBlobByte(image,0); /* pad scanline */\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,\n image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n }\n else\n {\n /*\n Dump colormap to file.\n */\n for (i=0; i < (ssize_t) image->colors; i++)\n (void) WriteBlobByte(image,ScaleQuantumToChar(\n image->colormap[i].red));\n for (i=0; i < (ssize_t) image->colors; i++)\n (void) WriteBlobByte(image,ScaleQuantumToChar(\n image->colormap[i].green));\n for (i=0; i < (ssize_t) image->colors; i++)\n (void) WriteBlobByte(image,ScaleQuantumToChar(\n image->colormap[i].blue));\n /*\n Convert PseudoClass packet to SUN colormapped pixel.\n */\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);\n if (p == (const PixelPacket *) NULL)\n break;\n indexes=GetVirtualIndexQueue(image);\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n (void) WriteBlobByte(image,(unsigned char)\n GetPixelIndex(indexes+x));\n p++;\n }\n if (image->columns & 0x01)\n (void) WriteBlobByte(image,0); /* pad scanline */\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,\n image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n }\n if (GetNextImageInList(image) == (Image *) NULL)\n break;\n image=SyncNextImageInList(image);\n status=SetImageProgress(image,SaveImagesTag,scene++,\n GetImageListLength(image));\n if (status == MagickFalse)\n break;\n } while (image_info->adjoin != MagickFalse);\n (void) CloseBlob(image);\n return(MagickTrue);\n}\n", + "line": null, + "label": 0, + "cwe": "CWE-125", + "cve": "CVE-2017-6500", + "length": 2160 + }, + { + "index": 184955, + "code": "void PixelBufferRasterWorkerPool::ScheduleMoreTasks() {\n TRACE_EVENT0(\"cc\", \"PixelBufferRasterWorkerPool::ScheduleMoreTasks\");\n\n enum RasterTaskType {\n PREPAINT_TYPE = 0,\n REQUIRED_FOR_ACTIVATION_TYPE = 1,\n NUM_TYPES = 2\n };\n NodeVector tasks[NUM_TYPES];\n unsigned priority = 2u; // 0-1 reserved for RasterFinished tasks.\n TaskGraph graph;\n\n size_t bytes_pending_upload = bytes_pending_upload_;\n bool did_throttle_raster_tasks = false;\n\n for (RasterTaskVector::const_iterator it = raster_tasks().begin();\n it != raster_tasks().end(); ++it) {\n internal::RasterWorkerPoolTask* task = it->get();\n\n TaskMap::iterator pixel_buffer_it = pixel_buffer_tasks_.find(task);\n if (pixel_buffer_it == pixel_buffer_tasks_.end())\n continue;\n\n if (task->HasFinishedRunning()) {\n DCHECK(std::find(completed_tasks_.begin(),\n completed_tasks_.end(),\n task) != completed_tasks_.end());\n continue;\n }\n\n size_t new_bytes_pending_upload = bytes_pending_upload;\n new_bytes_pending_upload += task->resource()->bytes();\n if (new_bytes_pending_upload > max_bytes_pending_upload_) {\n did_throttle_raster_tasks = true;\n break;\n }\n\n internal::WorkerPoolTask* pixel_buffer_task = pixel_buffer_it->second.get();\n\n if (pixel_buffer_task && pixel_buffer_task->HasCompleted()) {\n bytes_pending_upload = new_bytes_pending_upload;\n continue;\n }\n\n size_t scheduled_raster_task_count =\n tasks[PREPAINT_TYPE].container().size() +\n tasks[REQUIRED_FOR_ACTIVATION_TYPE].container().size();\n if (scheduled_raster_task_count >= kMaxScheduledRasterTasks) {\n did_throttle_raster_tasks = true;\n break;\n }\n\n bytes_pending_upload = new_bytes_pending_upload;\n\n RasterTaskType type = IsRasterTaskRequiredForActivation(task) ?\n REQUIRED_FOR_ACTIVATION_TYPE :\n PREPAINT_TYPE;\n\n if (pixel_buffer_task) {\n tasks[type].container().push_back(\n CreateGraphNodeForRasterTask(pixel_buffer_task,\n task->dependencies(),\n priority++,\n &graph));\n continue;\n }\n\n resource_provider()->AcquirePixelBuffer(task->resource()->id());\n\n uint8* buffer = resource_provider()->MapPixelBuffer(\n task->resource()->id());\n\n scoped_refptr new_pixel_buffer_task(\n new PixelBufferWorkerPoolTaskImpl(\n task,\n buffer,\n base::Bind(&PixelBufferRasterWorkerPool::OnRasterTaskCompleted,\n base::Unretained(this),\n make_scoped_refptr(task))));\n pixel_buffer_tasks_[task] = new_pixel_buffer_task;\n tasks[type].container().push_back(\n CreateGraphNodeForRasterTask(new_pixel_buffer_task.get(),\n task->dependencies(),\n priority++,\n &graph));\n }\n\n scoped_refptr\n new_raster_required_for_activation_finished_task;\n\n size_t scheduled_raster_task_required_for_activation_count =\n tasks[REQUIRED_FOR_ACTIVATION_TYPE].container().size();\n DCHECK_LE(scheduled_raster_task_required_for_activation_count,\n tasks_required_for_activation_.size());\n if (scheduled_raster_task_required_for_activation_count ==\n tasks_required_for_activation_.size() &&\n should_notify_client_if_no_tasks_required_for_activation_are_pending_) {\n new_raster_required_for_activation_finished_task =\n CreateRasterRequiredForActivationFinishedTask();\n internal::GraphNode* raster_required_for_activation_finished_node =\n CreateGraphNodeForTask(\n new_raster_required_for_activation_finished_task.get(),\n 0u, // Priority 0\n &graph);\n AddDependenciesToGraphNode(\n raster_required_for_activation_finished_node,\n tasks[REQUIRED_FOR_ACTIVATION_TYPE].container());\n }\n\n scoped_refptr new_raster_finished_task;\n\n size_t scheduled_raster_task_count =\n tasks[PREPAINT_TYPE].container().size() +\n tasks[REQUIRED_FOR_ACTIVATION_TYPE].container().size();\n DCHECK_LE(scheduled_raster_task_count, PendingRasterTaskCount());\n if (!did_throttle_raster_tasks &&\n should_notify_client_if_no_tasks_are_pending_) {\n new_raster_finished_task = CreateRasterFinishedTask();\n internal::GraphNode* raster_finished_node =\n CreateGraphNodeForTask(new_raster_finished_task.get(),\n 1u, // Priority 1\n &graph);\n for (unsigned type = 0; type < NUM_TYPES; ++type) {\n AddDependenciesToGraphNode(\n raster_finished_node,\n tasks[type].container());\n }\n }\n\n SetTaskGraph(&graph);\n\n scheduled_raster_task_count_ = scheduled_raster_task_count;\n\n set_raster_finished_task(new_raster_finished_task);\n set_raster_required_for_activation_finished_task(\n new_raster_required_for_activation_finished_task);\n}\n", + "line": null, + "label": 1, + "cwe": "CWE-20", + "cve": "CVE-2013-2871", + "length": 1050 + }, + { + "index": 178009, + "code": " parse_encoding( T1_Face face,\n T1_Loader loader )\n {\n T1_Parser parser = &loader->parser;\n FT_Byte* cur;\n FT_Byte* limit = parser->root.limit;\n\n PSAux_Service psaux = (PSAux_Service)face->psaux;\n\n\n T1_Skip_Spaces( parser );\n cur = parser->root.cursor;\n if ( cur >= limit )\n {\n FT_ERROR(( \"parse_encoding: out of bounds\\n\" ));\n parser->root.error = FT_THROW( Invalid_File_Format );\n return;\n }\n\n /* if we have a number or `[', the encoding is an array, */\n /* and we must load it now */\n if ( ft_isdigit( *cur ) || *cur == '[' )\n {\n T1_Encoding encode = &face->type1.encoding;\n FT_Int count, n;\n PS_Table char_table = &loader->encoding_table;\n FT_Memory memory = parser->root.memory;\n FT_Error error;\n FT_Bool only_immediates = 0;\n\n\n /* read the number of entries in the encoding; should be 256 */\n if ( *cur == '[' )\n {\n count = 256;\n only_immediates = 1;\n parser->root.cursor++;\n }\n else\n count = (FT_Int)T1_ToInt( parser );\n\n T1_Skip_Spaces( parser );\n if ( parser->root.cursor >= limit )\n return;\n\n /* we use a T1_Table to store our charnames */\n loader->num_chars = encode->num_chars = count;\n if ( FT_NEW_ARRAY( encode->char_index, count ) ||\n FT_NEW_ARRAY( encode->char_name, count ) ||\n FT_SET_ERROR( psaux->ps_table_funcs->init(\n char_table, count, memory ) ) )\n {\n parser->root.error = error;\n return;\n }\n\n /* We need to `zero' out encoding_table.elements */\n for ( n = 0; n < count; n++ )\n {\n char* notdef = (char *)\".notdef\";\n\n\n T1_Add_Table( char_table, n, notdef, 8 );\n }\n\n /* Now we need to read records of the form */\n /* */\n /* ... charcode /charname ... */\n /* */\n /* for each entry in our table. */\n /* */\n /* We simply look for a number followed by an immediate */\n /* name. Note that this ignores correctly the sequence */\n /* that is often seen in type1 fonts: */\n /* */\n /* 0 1 255 { 1 index exch /.notdef put } for dup */\n /* */\n /* used to clean the encoding array before anything else. */\n /* */\n /* Alternatively, if the array is directly given as */\n /* */\n /* /Encoding [ ... ] */\n /* */\n /* we only read immediates. */\n\n n = 0;\n T1_Skip_Spaces( parser );\n\n while ( parser->root.cursor < limit )\n {\n cur = parser->root.cursor;\n\n /* we stop when we encounter a `def' or `]' */\n if ( *cur == 'd' && cur + 3 < limit )\n {\n if ( cur[1] == 'e' &&\n cur[2] == 'f' &&\n IS_PS_DELIM( cur[3] ) )\n {\n FT_TRACE6(( \"encoding end\\n\" ));\n cur += 3;\n break;\n }\n }\n if ( *cur == ']' )\n {\n FT_TRACE6(( \"encoding end\\n\" ));\n cur++;\n break;\n }\n\n /* check whether we've found an entry */\n if ( ft_isdigit( *cur ) || only_immediates )\n {\n FT_Int charcode;\n\n\n if ( only_immediates )\n charcode = n;\n else\n {\n charcode = (FT_Int)T1_ToInt( parser );\n T1_Skip_Spaces( parser );\n }\n \n cur = parser->root.cursor;\n\n parser->root.cursor = cur;\n T1_Skip_PS_Token( parser );\n if ( parser->root.cursor >= limit )\n return;\n if ( parser->root.error )\n return;\n\n len = parser->root.cursor - cur;\n\n parser->root.error = T1_Add_Table( char_table, charcode,\n cur, len + 1 );\n if ( parser->root.error )\n return;\n char_table->elements[charcode][len] = '\\0';\n\n n++;\n }\n else if ( only_immediates )\n {\n /* Since the current position is not updated for */\n /* immediates-only mode we would get an infinite loop if */\n /* we don't do anything here. */\n /* */\n /* This encoding array is not valid according to the type1 */\n /* specification (it might be an encoding for a CID type1 */\n /* font, however), so we conclude that this font is NOT a */\n /* type1 font. */\n parser->root.error = FT_THROW( Unknown_File_Format );\n return;\n }\n }\n else\n {\n T1_Skip_PS_Token( parser );\n if ( parser->root.error )\n return;\n }\n\n T1_Skip_Spaces( parser );\n }\n\n face->type1.encoding_type = T1_ENCODING_TYPE_ARRAY;\n parser->root.cursor = cur;\n }\n", + "line": null, + "label": 1, + "cwe": "CWE-399", + "cve": "CVE-2014-9745", + "length": 1231 + }, + { + "index": 78717, + "code": "static int itacns_init(sc_pkcs15_card_t *p15card)\n{\n\tint r;\n\tsc_path_t path;\n\tint certificate_count = 0;\n\tint found_certs;\n\tint card_is_cie_v1, cns0_secenv;\n\n\tSC_FUNC_CALLED(p15card->card->ctx, 1);\n\n\tset_string(&p15card->tokeninfo->label, p15card->card->name);\n\tif(p15card->card->drv_data) {\n\t\tunsigned int mask_code, ic_code;\n\t\tchar buffer[256];\n\t\titacns_drv_data_t *data =\n\t\t\t(itacns_drv_data_t*) p15card->card->drv_data;\n\t\tmask_code = data->mask_manufacturer_code;\n\t\tif (mask_code >= sizeof(itacns_mask_manufacturers)\n\t\t\t/sizeof(itacns_mask_manufacturers[0]))\n\t\t\tmask_code = 0;\n\t\tic_code = data->ic_manufacturer_code;\n\t\tif (ic_code >= sizeof(iso7816_ic_manufacturers)\n\t\t\t/sizeof(iso7816_ic_manufacturers[0]))\n\t\t\tic_code = 0;\n\t\tsnprintf(buffer, sizeof(buffer), \"IC: %s; mask: %s\",\n\t\t\tiso7816_ic_manufacturers[ic_code],\n\t\t\titacns_mask_manufacturers[mask_code]);\n\t\tset_string(&p15card->tokeninfo->manufacturer_id, buffer);\n\t}\n\n\t/* Read and set serial */\n\t{\n\t\tu8 serial[17];\n\t\tint bytes;\n\t\tsc_format_path(path_serial, &path);\n\t\tbytes = loadFile(p15card, &path, serial, 16);\n\t\tif (bytes < 0) return bytes;\n\t\tif (bytes > 16) return -1;\n\t\tserial[bytes] = '\\0';\n\t\tset_string(&p15card->tokeninfo->serial_number, (char*)serial);\n\t}\n\n\t/* Is the card a CIE v1? */\n\tcard_is_cie_v1 =\n\t\t (p15card->card->type == SC_CARD_TYPE_ITACNS_CIE_V1)\n\t\t|| (p15card->card->type == SC_CARD_TYPE_CARDOS_CIE_V1);\n\tcns0_secenv = (card_is_cie_v1 ? 0x31 : 0x01);\n\n\t/* If it's a Siemens CIE v1 card, set algo flags accordingly. */\n\tif (card_is_cie_v1) {\n\t\tint i;\n\t\tfor (i = 0; i < p15card->card->algorithm_count; i++) {\n\t\t\tsc_algorithm_info_t *info =\n\t\t\t\t&p15card->card->algorithms[i];\n\n\t\t\tif (info->algorithm != SC_ALGORITHM_RSA)\n\t\t\t\tcontinue;\n\t\t\tinfo->flags &= ~(SC_ALGORITHM_RSA_RAW\n\t\t\t\t| SC_ALGORITHM_RSA_HASH_NONE);\n\t\t\tinfo->flags |= (SC_ALGORITHM_RSA_PAD_PKCS1\n\t\t\t\t| SC_ALGORITHM_RSA_HASHES);\n\t\t}\n\t}\n\n\t/* Data files */\n\tr = itacns_add_data_files(p15card);\n\tSC_TEST_RET(p15card->card->ctx, SC_LOG_DEBUG_NORMAL, r,\n\t\t\"Could not add data files\");\n\n\t/*** Certificate and keys. ***/\n\t/* Standard CNS */\n\tr = itacns_check_and_add_keyset(p15card, \"CNS0\", cns0_secenv,\n\t\t0, \"3F0011001101\", \"3F003F01\", NULL,\n\t\t0x10, &found_certs);\n\tSC_TEST_RET(p15card->card->ctx, SC_LOG_DEBUG_NORMAL, r,\n\t\t\"Could not add CNS0\");\n\tcertificate_count += found_certs;\n\n\t/* Infocamere 1204 */\n\tr = itacns_check_and_add_keyset(p15card, \"CNS01\", 0x21,\n\t\t5, \"3F002FFF8228\", NULL, \"3F002FFF0000\",\n\t\t0x10, &found_certs);\n\tSC_TEST_RET(p15card->card->ctx, SC_LOG_DEBUG_NORMAL, r,\n\t\t\"Could not add CNS01\");\n\tcertificate_count += found_certs;\n\n\t/* Digital signature */\n\tr = itacns_check_and_add_keyset(p15card, \"CNS1\", 0x10,\n\t\t0, \"3F0014009010\", \"3F00140081108010\", \"3F0014008110\",\n\t\t0x1a, &found_certs);\n\tSC_TEST_RET(p15card->card->ctx, SC_LOG_DEBUG_NORMAL, r,\n\t\t\"Could not add CNS1\");\n\tcertificate_count += found_certs;\n\n\t/* Did we find anything? */\n\tif (certificate_count == 0)\n\t\tsc_debug(p15card->card->ctx, SC_LOG_DEBUG_VERBOSE,\n\t\t\t\"Warning: no certificates found!\");\n\n\t/* Back to Master File */\n\tsc_format_path(\"3F00\", &path);\n\tr = sc_select_file(p15card->card, &path, NULL);\n\tSC_TEST_RET(p15card->card->ctx, SC_LOG_DEBUG_NORMAL, r,\n\t\t\"Could not select master file again\");\n\n\treturn r;\n}\n", + "line": null, + "label": 0, + "cwe": "CWE-125", + "cve": "CVE-2018-16427", + "length": 1091 + }, + { + "index": 180014, + "code": "static void icmp6_send(struct sk_buff *skb, u8 type, u8 code, __u32 info,\n\t\t const struct in6_addr *force_saddr)\n{\n\tstruct net *net = dev_net(skb->dev);\n\tstruct inet6_dev *idev = NULL;\n\tstruct ipv6hdr *hdr = ipv6_hdr(skb);\n\tstruct sock *sk;\n\tstruct ipv6_pinfo *np;\n\tconst struct in6_addr *saddr = NULL;\n\tstruct dst_entry *dst;\n\tstruct icmp6hdr tmp_hdr;\n\tstruct flowi6 fl6;\n\tstruct icmpv6_msg msg;\n\tstruct sockcm_cookie sockc_unused = {0};\n\tstruct ipcm6_cookie ipc6;\n\tint iif = 0;\n\tint addr_type = 0;\n\tint len;\n\tint err = 0;\n\tu32 mark = IP6_REPLY_MARK(net, skb->mark);\n\n\tif ((u8 *)hdr < skb->head ||\n\t (skb_network_header(skb) + sizeof(*hdr)) > skb_tail_pointer(skb))\n\t\treturn;\n\n\t/*\n\t *\tMake sure we respect the rules\n\t *\ti.e. RFC 1885 2.4(e)\n\t *\tRule (e.1) is enforced by not using icmp6_send\n\t *\tin any code that processes icmp errors.\n\t */\n\taddr_type = ipv6_addr_type(&hdr->daddr);\n\n\tif (ipv6_chk_addr(net, &hdr->daddr, skb->dev, 0) ||\n\t ipv6_chk_acast_addr_src(net, skb->dev, &hdr->daddr))\n\t\tsaddr = &hdr->daddr;\n\n\t/*\n\t *\tDest addr check\n\t */\n\n\tif (addr_type & IPV6_ADDR_MULTICAST || skb->pkt_type != PACKET_HOST) {\n\t\tif (type != ICMPV6_PKT_TOOBIG &&\n\t\t !(type == ICMPV6_PARAMPROB &&\n\t\t code == ICMPV6_UNK_OPTION &&\n\t\t (opt_unrec(skb, info))))\n\t\t\treturn;\n\n\t\tsaddr = NULL;\n\t}\n\n\taddr_type = ipv6_addr_type(&hdr->saddr);\n\n\t/*\n\t *\tSource addr check\n\t */\n \n \tif (__ipv6_addr_needs_scope_id(addr_type))\n \t\tiif = skb->dev->ifindex;\n\telse\n\t\tiif = l3mdev_master_ifindex(skb_dst(skb)->dev);\n \n \t/*\n \t *\tMust not send error if the source does not uniquely\n\t *\tidentify a single node (RFC2463 Section 2.4).\n\t *\tWe check unspecified / multicast addresses here,\n\t *\tand anycast addresses will be checked later.\n\t */\n\tif ((addr_type == IPV6_ADDR_ANY) || (addr_type & IPV6_ADDR_MULTICAST)) {\n\t\tnet_dbg_ratelimited(\"icmp6_send: addr_any/mcast source [%pI6c > %pI6c]\\n\",\n\t\t\t\t &hdr->saddr, &hdr->daddr);\n\t\treturn;\n\t}\n\n\t/*\n\t *\tNever answer to a ICMP packet.\n\t */\n\tif (is_ineligible(skb)) {\n\t\tnet_dbg_ratelimited(\"icmp6_send: no reply to icmp error [%pI6c > %pI6c]\\n\",\n\t\t\t\t &hdr->saddr, &hdr->daddr);\n\t\treturn;\n\t}\n\n\tmip6_addr_swap(skb);\n\n\tmemset(&fl6, 0, sizeof(fl6));\n\tfl6.flowi6_proto = IPPROTO_ICMPV6;\n\tfl6.daddr = hdr->saddr;\n\tif (force_saddr)\n\t\tsaddr = force_saddr;\n\tif (saddr)\n\t\tfl6.saddr = *saddr;\n\tfl6.flowi6_mark = mark;\n\tfl6.flowi6_oif = iif;\n\tfl6.fl6_icmp_type = type;\n\tfl6.fl6_icmp_code = code;\n\tsecurity_skb_classify_flow(skb, flowi6_to_flowi(&fl6));\n\n\tsk = icmpv6_xmit_lock(net);\n\tif (!sk)\n\t\treturn;\n\tsk->sk_mark = mark;\n\tnp = inet6_sk(sk);\n\n\tif (!icmpv6_xrlim_allow(sk, type, &fl6))\n\t\tgoto out;\n\n\ttmp_hdr.icmp6_type = type;\n\ttmp_hdr.icmp6_code = code;\n\ttmp_hdr.icmp6_cksum = 0;\n\ttmp_hdr.icmp6_pointer = htonl(info);\n\n\tif (!fl6.flowi6_oif && ipv6_addr_is_multicast(&fl6.daddr))\n\t\tfl6.flowi6_oif = np->mcast_oif;\n\telse if (!fl6.flowi6_oif)\n\t\tfl6.flowi6_oif = np->ucast_oif;\n\n\tipc6.tclass = np->tclass;\n\tfl6.flowlabel = ip6_make_flowinfo(ipc6.tclass, fl6.flowlabel);\n\n\tdst = icmpv6_route_lookup(net, skb, sk, &fl6);\n\tif (IS_ERR(dst))\n\t\tgoto out;\n\n\tipc6.hlimit = ip6_sk_dst_hoplimit(np, &fl6, dst);\n\tipc6.dontfrag = np->dontfrag;\n\tipc6.opt = NULL;\n\n\tmsg.skb = skb;\n\tmsg.offset = skb_network_offset(skb);\n\tmsg.type = type;\n\n\tlen = skb->len - msg.offset;\n\tlen = min_t(unsigned int, len, IPV6_MIN_MTU - sizeof(struct ipv6hdr) - sizeof(struct icmp6hdr));\n\tif (len < 0) {\n\t\tnet_dbg_ratelimited(\"icmp: len problem [%pI6c > %pI6c]\\n\",\n\t\t\t\t &hdr->saddr, &hdr->daddr);\n\t\tgoto out_dst_release;\n\t}\n\n\trcu_read_lock();\n\tidev = __in6_dev_get(skb->dev);\n\n\terr = ip6_append_data(sk, icmpv6_getfrag, &msg,\n\t\t\t len + sizeof(struct icmp6hdr),\n\t\t\t sizeof(struct icmp6hdr),\n\t\t\t &ipc6, &fl6, (struct rt6_info *)dst,\n\t\t\t MSG_DONTWAIT, &sockc_unused);\n\tif (err) {\n\t\tICMP6_INC_STATS(net, idev, ICMP6_MIB_OUTERRORS);\n\t\tip6_flush_pending_frames(sk);\n\t} else {\n\t\terr = icmpv6_push_pending_frames(sk, &fl6, &tmp_hdr,\n\t\t\t\t\t\t len + sizeof(struct icmp6hdr));\n\t}\n\trcu_read_unlock();\nout_dst_release:\n\tdst_release(dst);\nout:\n\ticmpv6_xmit_unlock(sk);\n}\n", + "line": "\telse\n\t\tiif = l3mdev_master_ifindex(skb_dst(skb)->dev);\n", + "label": 1, + "cwe": "CWE-20", + "cve": "CVE-2016-9919", + "length": 1360 + }, + { + "index": 38062, + "code": "magiccheck(struct magic_set *ms, struct magic *m)\n{\n\tuint64_t l = m->value.q;\n\tuint64_t v;\n\tfloat fl, fv;\n\tdouble dl, dv;\n\tint matched;\n\tunion VALUETYPE *p = &ms->ms_value;\n\n\tswitch (m->type) {\n\tcase FILE_BYTE:\n\t\tv = p->b;\n\t\tbreak;\n\n\tcase FILE_SHORT:\n\tcase FILE_BESHORT:\n\tcase FILE_LESHORT:\n\t\tv = p->h;\n\t\tbreak;\n\n\tcase FILE_LONG:\n\tcase FILE_BELONG:\n\tcase FILE_LELONG:\n\tcase FILE_MELONG:\n\tcase FILE_DATE:\n\tcase FILE_BEDATE:\n\tcase FILE_LEDATE:\n\tcase FILE_MEDATE:\n\tcase FILE_LDATE:\n\tcase FILE_BELDATE:\n\tcase FILE_LELDATE:\n\tcase FILE_MELDATE:\n\t\tv = p->l;\n\t\tbreak;\n\n\tcase FILE_QUAD:\n\tcase FILE_LEQUAD:\n\tcase FILE_BEQUAD:\n\tcase FILE_QDATE:\n\tcase FILE_BEQDATE:\n\tcase FILE_LEQDATE:\n\tcase FILE_QLDATE:\n\tcase FILE_BEQLDATE:\n\tcase FILE_LEQLDATE:\n\tcase FILE_QWDATE:\n\tcase FILE_BEQWDATE:\n\tcase FILE_LEQWDATE:\n\t\tv = p->q;\n\t\tbreak;\n\n\tcase FILE_FLOAT:\n\tcase FILE_BEFLOAT:\n\tcase FILE_LEFLOAT:\n\t\tfl = m->value.f;\n\t\tfv = p->f;\n\t\tswitch (m->reln) {\n\t\tcase 'x':\n\t\t\tmatched = 1;\n\t\t\tbreak;\n\n\t\tcase '!':\n\t\t\tmatched = fv != fl;\n\t\t\tbreak;\n\n\t\tcase '=':\n\t\t\tmatched = fv == fl;\n\t\t\tbreak;\n\n\t\tcase '>':\n\t\t\tmatched = fv > fl;\n\t\t\tbreak;\n\n\t\tcase '<':\n\t\t\tmatched = fv < fl;\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\tfile_magerror(ms, \"cannot happen with float: invalid relation `%c'\",\n\t\t\t m->reln);\n\t\t\treturn -1;\n\t\t}\n\t\treturn matched;\n\n\tcase FILE_DOUBLE:\n\tcase FILE_BEDOUBLE:\n\tcase FILE_LEDOUBLE:\n\t\tdl = m->value.d;\n\t\tdv = p->d;\n\t\tswitch (m->reln) {\n\t\tcase 'x':\n\t\t\tmatched = 1;\n\t\t\tbreak;\n\n\t\tcase '!':\n\t\t\tmatched = dv != dl;\n\t\t\tbreak;\n\n\t\tcase '=':\n\t\t\tmatched = dv == dl;\n\t\t\tbreak;\n\n\t\tcase '>':\n\t\t\tmatched = dv > dl;\n\t\t\tbreak;\n\n\t\tcase '<':\n\t\t\tmatched = dv < dl;\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\tfile_magerror(ms, \"cannot happen with double: invalid relation `%c'\", m->reln);\n\t\t\treturn -1;\n\t\t}\n\t\treturn matched;\n\n\tcase FILE_DEFAULT:\n\tcase FILE_CLEAR:\n\t\tl = 0;\n\t\tv = 0;\n\t\tbreak;\n\n\tcase FILE_STRING:\n\tcase FILE_PSTRING:\n\t\tl = 0;\n\t\tv = file_strncmp(m->value.s, p->s, (size_t)m->vallen, m->str_flags);\n\t\tbreak;\n\n\tcase FILE_BESTRING16:\n\tcase FILE_LESTRING16:\n\t\tl = 0;\n\t\tv = file_strncmp16(m->value.s, p->s, (size_t)m->vallen, m->str_flags);\n\t\tbreak;\n\n\tcase FILE_SEARCH: { /* search ms->search.s for the string m->value.s */\n\t\tsize_t slen;\n\t\tsize_t idx;\n\n\t\tif (ms->search.s == NULL)\n\t\t\treturn 0;\n\n\t\tslen = MIN(m->vallen, sizeof(m->value.s));\n\t\tl = 0;\n\t\tv = 0;\n\n\t\tfor (idx = 0; m->str_range == 0 || idx < m->str_range; idx++) {\n\t\t\tif (slen + idx > ms->search.s_len)\n\t\t\t\tbreak;\n\n\t\t\tv = file_strncmp(m->value.s, ms->search.s + idx, slen,\n\t\t\t m->str_flags);\n\t\t\tif (v == 0) {\t/* found match */\n\t\t\t\tms->search.offset += idx;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tbreak;\n\t}\n\tcase FILE_REGEX: {\n\t\tint rc;\n\t\tfile_regex_t rx;\n\n\t\tif (ms->search.s == NULL)\n\t\t\treturn 0;\n\n\t\tl = 0;\n\t\trc = file_regcomp(&rx, m->value.s,\n\t\t REG_EXTENDED|REG_NEWLINE|\n\t\t ((m->str_flags & STRING_IGNORE_CASE) ? REG_ICASE : 0));\n\t\tif (rc) {\n\t\t\tfile_regerror(&rx, rc, ms);\n\t\t\tv = (uint64_t)-1;\n\t\t} else {\n\t\t\tregmatch_t pmatch[1];\n\t\t\tsize_t slen = ms->search.s_len;\n#ifndef REG_STARTEND\n#define\tREG_STARTEND\t0\n\t\t\tchar c;\n\t\t\tif (slen != 0)\n\t\t\t\tslen--;\n\t\t\tc = ms->search.s[slen];\n\t\t\t((char *)(intptr_t)ms->search.s)[slen] = '\\0';\n#else\n\t\t\tpmatch[0].rm_so = 0;\n\t\t\tpmatch[0].rm_eo = slen;\n#endif\n\t\t\trc = file_regexec(&rx, (const char *)ms->search.s,\n\t\t\t 1, pmatch, REG_STARTEND);\n#if REG_STARTEND == 0\n\t\t\t((char *)(intptr_t)ms->search.s)[l] = c;\n#endif\n\t\t\tswitch (rc) {\n\t\t\tcase 0:\n\t\t\t\tms->search.s += (int)pmatch[0].rm_so;\n\t\t\t\tms->search.offset += (size_t)pmatch[0].rm_so;\n\t\t\t\tms->search.rm_len =\n\t\t\t\t (size_t)(pmatch[0].rm_eo - pmatch[0].rm_so);\n\t\t\t\tv = 0;\n\t\t\t\tbreak;\n\n\t\t\tcase REG_NOMATCH:\n\t\t\t\tv = 1;\n\t\t\t\tbreak;\n\n\t\t\tdefault:\n\t\t\t\tfile_regerror(&rx, rc, ms);\n\t\t\t\tv = (uint64_t)-1;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tfile_regfree(&rx);\n\t\tif (v == (uint64_t)-1)\n\t\t\treturn -1;\n\t\tbreak;\n\t}\n\tcase FILE_INDIRECT:\n\tcase FILE_USE:\n\tcase FILE_NAME:\n\t\treturn 1;\n\tdefault:\n\t\tfile_magerror(ms, \"invalid type %d in magiccheck()\", m->type);\n\t\treturn -1;\n\t}\n\n\tv = file_signextend(ms, m, v);\n\n\tswitch (m->reln) {\n\tcase 'x':\n\t\tif ((ms->flags & MAGIC_DEBUG) != 0)\n\t\t\t(void) fprintf(stderr, \"%\" INT64_T_FORMAT\n\t\t\t \"u == *any* = 1\\n\", (unsigned long long)v);\n\t\tmatched = 1;\n\t\tbreak;\n\n\tcase '!':\n\t\tmatched = v != l;\n\t\tif ((ms->flags & MAGIC_DEBUG) != 0)\n\t\t\t(void) fprintf(stderr, \"%\" INT64_T_FORMAT \"u != %\"\n\t\t\t INT64_T_FORMAT \"u = %d\\n\", (unsigned long long)v,\n\t\t\t (unsigned long long)l, matched);\n\t\tbreak;\n\n\tcase '=':\n\t\tmatched = v == l;\n\t\tif ((ms->flags & MAGIC_DEBUG) != 0)\n\t\t\t(void) fprintf(stderr, \"%\" INT64_T_FORMAT \"u == %\"\n\t\t\t INT64_T_FORMAT \"u = %d\\n\", (unsigned long long)v,\n\t\t\t (unsigned long long)l, matched);\n\t\tbreak;\n\n\tcase '>':\n\t\tif (m->flag & UNSIGNED) {\n\t\t\tmatched = v > l;\n\t\t\tif ((ms->flags & MAGIC_DEBUG) != 0)\n\t\t\t\t(void) fprintf(stderr, \"%\" INT64_T_FORMAT\n\t\t\t\t \"u > %\" INT64_T_FORMAT \"u = %d\\n\",\n\t\t\t\t (unsigned long long)v,\n\t\t\t\t (unsigned long long)l, matched);\n\t\t}\n\t\telse {\n\t\t\tmatched = (int64_t) v > (int64_t) l;\n\t\t\tif ((ms->flags & MAGIC_DEBUG) != 0)\n\t\t\t\t(void) fprintf(stderr, \"%\" INT64_T_FORMAT\n\t\t\t\t \"d > %\" INT64_T_FORMAT \"d = %d\\n\",\n\t\t\t\t (long long)v, (long long)l, matched);\n\t\t}\n\t\tbreak;\n\n\tcase '<':\n\t\tif (m->flag & UNSIGNED) {\n\t\t\tmatched = v < l;\n\t\t\tif ((ms->flags & MAGIC_DEBUG) != 0)\n\t\t\t\t(void) fprintf(stderr, \"%\" INT64_T_FORMAT\n\t\t\t\t \"u < %\" INT64_T_FORMAT \"u = %d\\n\",\n\t\t\t\t (unsigned long long)v,\n\t\t\t\t (unsigned long long)l, matched);\n\t\t}\n\t\telse {\n\t\t\tmatched = (int64_t) v < (int64_t) l;\n\t\t\tif ((ms->flags & MAGIC_DEBUG) != 0)\n\t\t\t\t(void) fprintf(stderr, \"%\" INT64_T_FORMAT\n\t\t\t\t \"d < %\" INT64_T_FORMAT \"d = %d\\n\",\n\t\t\t\t (long long)v, (long long)l, matched);\n\t\t}\n\t\tbreak;\n\n\tcase '&':\n\t\tmatched = (v & l) == l;\n\t\tif ((ms->flags & MAGIC_DEBUG) != 0)\n\t\t\t(void) fprintf(stderr, \"((%\" INT64_T_FORMAT \"x & %\"\n\t\t\t INT64_T_FORMAT \"x) == %\" INT64_T_FORMAT\n\t\t\t \"x) = %d\\n\", (unsigned long long)v,\n\t\t\t (unsigned long long)l, (unsigned long long)l,\n\t\t\t matched);\n\t\tbreak;\n\n\tcase '^':\n\t\tmatched = (v & l) != l;\n\t\tif ((ms->flags & MAGIC_DEBUG) != 0)\n\t\t\t(void) fprintf(stderr, \"((%\" INT64_T_FORMAT \"x & %\"\n\t\t\t INT64_T_FORMAT \"x) != %\" INT64_T_FORMAT\n\t\t\t \"x) = %d\\n\", (unsigned long long)v,\n\t\t\t (unsigned long long)l, (unsigned long long)l,\n\t\t\t matched);\n\t\tbreak;\n\n\tdefault:\n\t\tfile_magerror(ms, \"cannot happen: invalid relation `%c'\",\n\t\t m->reln);\n\t\treturn -1;\n\t}\n\n\treturn matched;\n}\n", + "line": null, + "label": 0, + "cwe": "CWE-119", + "cve": "CVE-2014-3478", + "length": 2140 + }, + { + "index": 83532, + "code": "static void nsc_encode_argb_to_aycocg_sse2(NSC_CONTEXT* context,\n const BYTE* data, UINT32 scanline)\n{\n\tUINT16 x;\n\tUINT16 y;\n\tUINT16 rw;\n\tBYTE ccl;\n\tconst BYTE* src;\n\tBYTE* yplane = NULL;\n\tBYTE* coplane = NULL;\n\tBYTE* cgplane = NULL;\n\tBYTE* aplane = NULL;\n\t__m128i r_val;\n\t__m128i g_val;\n\t__m128i b_val;\n\t__m128i a_val;\n\t__m128i y_val;\n\t__m128i co_val;\n\t__m128i cg_val;\n\tUINT32 tempWidth;\n\ttempWidth = ROUND_UP_TO(context->width, 8);\n\trw = (context->ChromaSubsamplingLevel > 0 ? tempWidth : context->width);\n\tccl = context->ColorLossLevel;\n\n\tfor (y = 0; y < context->height; y++)\n\t{\n\t\tsrc = data + (context->height - 1 - y) * scanline;\n\t\typlane = context->priv->PlaneBuffers[0] + y * rw;\n\t\tcoplane = context->priv->PlaneBuffers[1] + y * rw;\n\t\tcgplane = context->priv->PlaneBuffers[2] + y * rw;\n\t\taplane = context->priv->PlaneBuffers[3] + y * context->width;\n\n\t\tfor (x = 0; x < context->width; x += 8)\n\t\t{\n\t\t\tswitch (context->format)\n\t\t\t{\n\t\t\t\tcase PIXEL_FORMAT_BGRX32:\n\t\t\t\t\tb_val = _mm_set_epi16(*(src + 28), *(src + 24), *(src + 20), *(src + 16),\n\t\t\t\t\t *(src + 12), *(src + 8), *(src + 4), *src);\n\t\t\t\t\tg_val = _mm_set_epi16(*(src + 29), *(src + 25), *(src + 21), *(src + 17),\n\t\t\t\t\t *(src + 13), *(src + 9), *(src + 5), *(src + 1));\n\t\t\t\t\tr_val = _mm_set_epi16(*(src + 30), *(src + 26), *(src + 22), *(src + 18),\n\t\t\t\t\t *(src + 14), *(src + 10), *(src + 6), *(src + 2));\n\t\t\t\t\ta_val = _mm_set1_epi16(0xFF);\n\t\t\t\t\tsrc += 32;\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase PIXEL_FORMAT_BGRA32:\n\t\t\t\t\tb_val = _mm_set_epi16(*(src + 28), *(src + 24), *(src + 20), *(src + 16),\n\t\t\t\t\t *(src + 12), *(src + 8), *(src + 4), *src);\n\t\t\t\t\tg_val = _mm_set_epi16(*(src + 29), *(src + 25), *(src + 21), *(src + 17),\n\t\t\t\t\t *(src + 13), *(src + 9), *(src + 5), *(src + 1));\n\t\t\t\t\tr_val = _mm_set_epi16(*(src + 30), *(src + 26), *(src + 22), *(src + 18),\n\t\t\t\t\t *(src + 14), *(src + 10), *(src + 6), *(src + 2));\n\t\t\t\t\ta_val = _mm_set_epi16(*(src + 31), *(src + 27), *(src + 23), *(src + 19),\n\t\t\t\t\t *(src + 15), *(src + 11), *(src + 7), *(src + 3));\n\t\t\t\t\tsrc += 32;\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase PIXEL_FORMAT_RGBX32:\n\t\t\t\t\tr_val = _mm_set_epi16(*(src + 28), *(src + 24), *(src + 20), *(src + 16),\n\t\t\t\t\t *(src + 12), *(src + 8), *(src + 4), *src);\n\t\t\t\t\tg_val = _mm_set_epi16(*(src + 29), *(src + 25), *(src + 21), *(src + 17),\n\t\t\t\t\t *(src + 13), *(src + 9), *(src + 5), *(src + 1));\n\t\t\t\t\tb_val = _mm_set_epi16(*(src + 30), *(src + 26), *(src + 22), *(src + 18),\n\t\t\t\t\t *(src + 14), *(src + 10), *(src + 6), *(src + 2));\n\t\t\t\t\ta_val = _mm_set1_epi16(0xFF);\n\t\t\t\t\tsrc += 32;\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase PIXEL_FORMAT_RGBA32:\n\t\t\t\t\tr_val = _mm_set_epi16(*(src + 28), *(src + 24), *(src + 20), *(src + 16),\n\t\t\t\t\t *(src + 12), *(src + 8), *(src + 4), *src);\n\t\t\t\t\tg_val = _mm_set_epi16(*(src + 29), *(src + 25), *(src + 21), *(src + 17),\n\t\t\t\t\t *(src + 13), *(src + 9), *(src + 5), *(src + 1));\n\t\t\t\t\tb_val = _mm_set_epi16(*(src + 30), *(src + 26), *(src + 22), *(src + 18),\n\t\t\t\t\t *(src + 14), *(src + 10), *(src + 6), *(src + 2));\n\t\t\t\t\ta_val = _mm_set_epi16(*(src + 31), *(src + 27), *(src + 23), *(src + 19),\n\t\t\t\t\t *(src + 15), *(src + 11), *(src + 7), *(src + 3));\n\t\t\t\t\tsrc += 32;\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase PIXEL_FORMAT_BGR24:\n\t\t\t\t\tb_val = _mm_set_epi16(*(src + 21), *(src + 18), *(src + 15), *(src + 12),\n\t\t\t\t\t *(src + 9), *(src + 6), *(src + 3), *src);\n\t\t\t\t\tg_val = _mm_set_epi16(*(src + 22), *(src + 19), *(src + 16), *(src + 13),\n\t\t\t\t\t *(src + 10), *(src + 7), *(src + 4), *(src + 1));\n\t\t\t\t\tr_val = _mm_set_epi16(*(src + 23), *(src + 20), *(src + 17), *(src + 14),\n\t\t\t\t\t *(src + 11), *(src + 8), *(src + 5), *(src + 2));\n\t\t\t\t\ta_val = _mm_set1_epi16(0xFF);\n\t\t\t\t\tsrc += 24;\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase PIXEL_FORMAT_RGB24:\n\t\t\t\t\tr_val = _mm_set_epi16(*(src + 21), *(src + 18), *(src + 15), *(src + 12),\n\t\t\t\t\t *(src + 9), *(src + 6), *(src + 3), *src);\n\t\t\t\t\tg_val = _mm_set_epi16(*(src + 22), *(src + 19), *(src + 16), *(src + 13),\n\t\t\t\t\t *(src + 10), *(src + 7), *(src + 4), *(src + 1));\n\t\t\t\t\tb_val = _mm_set_epi16(*(src + 23), *(src + 20), *(src + 17), *(src + 14),\n\t\t\t\t\t *(src + 11), *(src + 8), *(src + 5), *(src + 2));\n\t\t\t\t\ta_val = _mm_set1_epi16(0xFF);\n\t\t\t\t\tsrc += 24;\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase PIXEL_FORMAT_BGR16:\n\t\t\t\t\tb_val = _mm_set_epi16(\n\t\t\t\t\t (((*(src + 15)) & 0xF8) | ((*(src + 15)) >> 5)),\n\t\t\t\t\t (((*(src + 13)) & 0xF8) | ((*(src + 13)) >> 5)),\n\t\t\t\t\t (((*(src + 11)) & 0xF8) | ((*(src + 11)) >> 5)),\n\t\t\t\t\t (((*(src + 9)) & 0xF8) | ((*(src + 9)) >> 5)),\n\t\t\t\t\t (((*(src + 7)) & 0xF8) | ((*(src + 7)) >> 5)),\n\t\t\t\t\t (((*(src + 5)) & 0xF8) | ((*(src + 5)) >> 5)),\n\t\t\t\t\t (((*(src + 3)) & 0xF8) | ((*(src + 3)) >> 5)),\n\t\t\t\t\t (((*(src + 1)) & 0xF8) | ((*(src + 1)) >> 5)));\n\t\t\t\t\tg_val = _mm_set_epi16(\n\t\t\t\t\t ((((*(src + 15)) & 0x07) << 5) | (((*(src + 14)) & 0xE0) >> 3)),\n\t\t\t\t\t ((((*(src + 13)) & 0x07) << 5) | (((*(src + 12)) & 0xE0) >> 3)),\n\t\t\t\t\t ((((*(src + 11)) & 0x07) << 5) | (((*(src + 10)) & 0xE0) >> 3)),\n\t\t\t\t\t ((((*(src + 9)) & 0x07) << 5) | (((*(src + 8)) & 0xE0) >> 3)),\n\t\t\t\t\t ((((*(src + 7)) & 0x07) << 5) | (((*(src + 6)) & 0xE0) >> 3)),\n\t\t\t\t\t ((((*(src + 5)) & 0x07) << 5) | (((*(src + 4)) & 0xE0) >> 3)),\n\t\t\t\t\t ((((*(src + 3)) & 0x07) << 5) | (((*(src + 2)) & 0xE0) >> 3)),\n\t\t\t\t\t ((((*(src + 1)) & 0x07) << 5) | (((*src) & 0xE0) >> 3)));\n\t\t\t\t\tr_val = _mm_set_epi16(\n\t\t\t\t\t ((((*(src + 14)) & 0x1F) << 3) | (((*(src + 14)) >> 2) & 0x07)),\n\t\t\t\t\t ((((*(src + 12)) & 0x1F) << 3) | (((*(src + 12)) >> 2) & 0x07)),\n\t\t\t\t\t ((((*(src + 10)) & 0x1F) << 3) | (((*(src + 10)) >> 2) & 0x07)),\n\t\t\t\t\t ((((*(src + 8)) & 0x1F) << 3) | (((*(src + 8)) >> 2) & 0x07)),\n\t\t\t\t\t ((((*(src + 6)) & 0x1F) << 3) | (((*(src + 6)) >> 2) & 0x07)),\n\t\t\t\t\t ((((*(src + 4)) & 0x1F) << 3) | (((*(src + 4)) >> 2) & 0x07)),\n\t\t\t\t\t ((((*(src + 2)) & 0x1F) << 3) | (((*(src + 2)) >> 2) & 0x07)),\n\t\t\t\t\t ((((*src) & 0x1F) << 3) | (((*src) >> 2) & 0x07)));\n\t\t\t\t\ta_val = _mm_set1_epi16(0xFF);\n\t\t\t\t\tsrc += 16;\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase PIXEL_FORMAT_RGB16:\n\t\t\t\t\tr_val = _mm_set_epi16(\n\t\t\t\t\t (((*(src + 15)) & 0xF8) | ((*(src + 15)) >> 5)),\n\t\t\t\t\t (((*(src + 13)) & 0xF8) | ((*(src + 13)) >> 5)),\n\t\t\t\t\t (((*(src + 11)) & 0xF8) | ((*(src + 11)) >> 5)),\n\t\t\t\t\t (((*(src + 9)) & 0xF8) | ((*(src + 9)) >> 5)),\n\t\t\t\t\t (((*(src + 7)) & 0xF8) | ((*(src + 7)) >> 5)),\n\t\t\t\t\t (((*(src + 5)) & 0xF8) | ((*(src + 5)) >> 5)),\n\t\t\t\t\t (((*(src + 3)) & 0xF8) | ((*(src + 3)) >> 5)),\n\t\t\t\t\t (((*(src + 1)) & 0xF8) | ((*(src + 1)) >> 5)));\n\t\t\t\t\tg_val = _mm_set_epi16(\n\t\t\t\t\t ((((*(src + 15)) & 0x07) << 5) | (((*(src + 14)) & 0xE0) >> 3)),\n\t\t\t\t\t ((((*(src + 13)) & 0x07) << 5) | (((*(src + 12)) & 0xE0) >> 3)),\n\t\t\t\t\t ((((*(src + 11)) & 0x07) << 5) | (((*(src + 10)) & 0xE0) >> 3)),\n\t\t\t\t\t ((((*(src + 9)) & 0x07) << 5) | (((*(src + 8)) & 0xE0) >> 3)),\n\t\t\t\t\t ((((*(src + 7)) & 0x07) << 5) | (((*(src + 6)) & 0xE0) >> 3)),\n\t\t\t\t\t ((((*(src + 5)) & 0x07) << 5) | (((*(src + 4)) & 0xE0) >> 3)),\n\t\t\t\t\t ((((*(src + 3)) & 0x07) << 5) | (((*(src + 2)) & 0xE0) >> 3)),\n\t\t\t\t\t ((((*(src + 1)) & 0x07) << 5) | (((*src) & 0xE0) >> 3)));\n\t\t\t\t\tb_val = _mm_set_epi16(\n\t\t\t\t\t ((((*(src + 14)) & 0x1F) << 3) | (((*(src + 14)) >> 2) & 0x07)),\n\t\t\t\t\t ((((*(src + 12)) & 0x1F) << 3) | (((*(src + 12)) >> 2) & 0x07)),\n\t\t\t\t\t ((((*(src + 10)) & 0x1F) << 3) | (((*(src + 10)) >> 2) & 0x07)),\n\t\t\t\t\t ((((*(src + 8)) & 0x1F) << 3) | (((*(src + 8)) >> 2) & 0x07)),\n\t\t\t\t\t ((((*(src + 6)) & 0x1F) << 3) | (((*(src + 6)) >> 2) & 0x07)),\n\t\t\t\t\t ((((*(src + 4)) & 0x1F) << 3) | (((*(src + 4)) >> 2) & 0x07)),\n\t\t\t\t\t ((((*(src + 2)) & 0x1F) << 3) | (((*(src + 2)) >> 2) & 0x07)),\n\t\t\t\t\t ((((*src) & 0x1F) << 3) | (((*src) >> 2) & 0x07)));\n\t\t\t\t\ta_val = _mm_set1_epi16(0xFF);\n\t\t\t\t\tsrc += 16;\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase PIXEL_FORMAT_A4:\n\t\t\t\t\t{\n\t\t\t\t\t\tint shift;\n\t\t\t\t\t\tBYTE idx[8];\n\n\t\t\t\t\t\tfor (shift = 7; shift >= 0; shift--)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tidx[shift] = ((*src) >> shift) & 1;\n\t\t\t\t\t\t\tidx[shift] |= (((*(src + 1)) >> shift) & 1) << 1;\n\t\t\t\t\t\t\tidx[shift] |= (((*(src + 2)) >> shift) & 1) << 2;\n\t\t\t\t\t\t\tidx[shift] |= (((*(src + 3)) >> shift) & 1) << 3;\n\t\t\t\t\t\t\tidx[shift] *= 3;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tr_val = _mm_set_epi16(\n\t\t\t\t\t\t context->palette[idx[0]],\n\t\t\t\t\t\t context->palette[idx[1]],\n\t\t\t\t\t\t context->palette[idx[2]],\n\t\t\t\t\t\t context->palette[idx[3]],\n\t\t\t\t\t\t context->palette[idx[4]],\n\t\t\t\t\t\t context->palette[idx[5]],\n\t\t\t\t\t\t context->palette[idx[6]],\n\t\t\t\t\t\t context->palette[idx[7]]);\n\t\t\t\t\t\tg_val = _mm_set_epi16(\n\t\t\t\t\t\t context->palette[idx[0] + 1],\n\t\t\t\t\t\t context->palette[idx[1] + 1],\n\t\t\t\t\t\t context->palette[idx[2] + 1],\n\t\t\t\t\t\t context->palette[idx[3] + 1],\n\t\t\t\t\t\t context->palette[idx[4] + 1],\n\t\t\t\t\t\t context->palette[idx[5] + 1],\n\t\t\t\t\t\t context->palette[idx[6] + 1],\n\t\t\t\t\t\t context->palette[idx[7] + 1]);\n\t\t\t\t\t\tb_val = _mm_set_epi16(\n\t\t\t\t\t\t context->palette[idx[0] + 2],\n\t\t\t\t\t\t context->palette[idx[1] + 2],\n\t\t\t\t\t\t context->palette[idx[2] + 2],\n\t\t\t\t\t\t context->palette[idx[3] + 2],\n\t\t\t\t\t\t context->palette[idx[4] + 2],\n\t\t\t\t\t\t context->palette[idx[5] + 2],\n\t\t\t\t\t\t context->palette[idx[6] + 2],\n\t\t\t\t\t\t context->palette[idx[7] + 2]);\n\t\t\t\t\t\tsrc += 4;\n\t\t\t\t\t}\n\n\t\t\t\t\ta_val = _mm_set1_epi16(0xFF);\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase PIXEL_FORMAT_RGB8:\n\t\t\t\t\t{\n\t\t\t\t\t\tr_val = _mm_set_epi16(\n\t\t\t\t\t\t context->palette[(*(src + 7)) * 3],\n\t\t\t\t\t\t context->palette[(*(src + 6)) * 3],\n\t\t\t\t\t\t context->palette[(*(src + 5)) * 3],\n\t\t\t\t\t\t context->palette[(*(src + 4)) * 3],\n\t\t\t\t\t\t context->palette[(*(src + 3)) * 3],\n\t\t\t\t\t\t context->palette[(*(src + 2)) * 3],\n\t\t\t\t\t\t context->palette[(*(src + 1)) * 3],\n\t\t\t\t\t\t context->palette[(*src) * 3]);\n\t\t\t\t\t\tg_val = _mm_set_epi16(\n\t\t\t\t\t\t context->palette[(*(src + 7)) * 3 + 1],\n\t\t\t\t\t\t context->palette[(*(src + 6)) * 3 + 1],\n\t\t\t\t\t\t context->palette[(*(src + 5)) * 3 + 1],\n\t\t\t\t\t\t context->palette[(*(src + 4)) * 3 + 1],\n\t\t\t\t\t\t context->palette[(*(src + 3)) * 3 + 1],\n\t\t\t\t\t\t context->palette[(*(src + 2)) * 3 + 1],\n\t\t\t\t\t\t context->palette[(*(src + 1)) * 3 + 1],\n\t\t\t\t\t\t context->palette[(*src) * 3 + 1]);\n\t\t\t\t\t\tb_val = _mm_set_epi16(\n\t\t\t\t\t\t context->palette[(*(src + 7)) * 3 + 2],\n\t\t\t\t\t\t context->palette[(*(src + 6)) * 3 + 2],\n\t\t\t\t\t\t context->palette[(*(src + 5)) * 3 + 2],\n\t\t\t\t\t\t context->palette[(*(src + 4)) * 3 + 2],\n\t\t\t\t\t\t context->palette[(*(src + 3)) * 3 + 2],\n\t\t\t\t\t\t context->palette[(*(src + 2)) * 3 + 2],\n\t\t\t\t\t\t context->palette[(*(src + 1)) * 3 + 2],\n\t\t\t\t\t\t context->palette[(*src) * 3 + 2]);\n\t\t\t\t\t\tsrc += 8;\n\t\t\t\t\t}\n\n\t\t\t\t\ta_val = _mm_set1_epi16(0xFF);\n\t\t\t\t\tbreak;\n\n\t\t\t\tdefault:\n\t\t\t\t\tr_val = g_val = b_val = a_val = _mm_set1_epi16(0);\n\t\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\ty_val = _mm_srai_epi16(r_val, 2);\n\t\t\ty_val = _mm_add_epi16(y_val, _mm_srai_epi16(g_val, 1));\n\t\t\ty_val = _mm_add_epi16(y_val, _mm_srai_epi16(b_val, 2));\n\t\t\tco_val = _mm_sub_epi16(r_val, b_val);\n\t\t\tco_val = _mm_srai_epi16(co_val, ccl);\n\t\t\tcg_val = _mm_sub_epi16(g_val, _mm_srai_epi16(r_val, 1));\n\t\t\tcg_val = _mm_sub_epi16(cg_val, _mm_srai_epi16(b_val, 1));\n\t\t\tcg_val = _mm_srai_epi16(cg_val, ccl);\n\t\t\ty_val = _mm_packus_epi16(y_val, y_val);\n\t\t\t_mm_storeu_si128((__m128i*) yplane, y_val);\n\t\t\tco_val = _mm_packs_epi16(co_val, co_val);\n\t\t\t_mm_storeu_si128((__m128i*) coplane, co_val);\n\t\t\tcg_val = _mm_packs_epi16(cg_val, cg_val);\n\t\t\t_mm_storeu_si128((__m128i*) cgplane, cg_val);\n\t\t\ta_val = _mm_packus_epi16(a_val, a_val);\n\t\t\t_mm_storeu_si128((__m128i*) aplane, a_val);\n\t\t\typlane += 8;\n\t\t\tcoplane += 8;\n\t\t\tcgplane += 8;\n\t\t\taplane += 8;\n\t\t}\n\n\t\tif (context->ChromaSubsamplingLevel > 0 && (context->width % 2) == 1)\n\t\t{\n\t\t\tcontext->priv->PlaneBuffers[0][y * rw + context->width] =\n\t\t\t context->priv->PlaneBuffers[0][y * rw + context->width - 1];\n\t\t\tcontext->priv->PlaneBuffers[1][y * rw + context->width] =\n\t\t\t context->priv->PlaneBuffers[1][y * rw + context->width - 1];\n\t\t\tcontext->priv->PlaneBuffers[2][y * rw + context->width] =\n\t\t\t context->priv->PlaneBuffers[2][y * rw + context->width - 1];\n\t\t}\n\t}\n\n\tif (context->ChromaSubsamplingLevel > 0 && (y % 2) == 1)\n\t{\n\t\typlane = context->priv->PlaneBuffers[0] + y * rw;\n\t\tcoplane = context->priv->PlaneBuffers[1] + y * rw;\n\t\tcgplane = context->priv->PlaneBuffers[2] + y * rw;\n\t\tCopyMemory(yplane, yplane - rw, rw);\n\t\tCopyMemory(coplane, coplane - rw, rw);\n\t\tCopyMemory(cgplane, cgplane - rw, rw);\n\t}\n}\n", + "line": null, + "label": 0, + "cwe": "CWE-787", + "cve": "CVE-2018-8788", + "length": 4997 + }, + { + "index": 68018, + "code": "static Image *ReadPSDImage(const ImageInfo *image_info,ExceptionInfo *exception)\n{\n Image\n *image;\n\n MagickBooleanType\n has_merged_image,\n skip_layers;\n\n MagickOffsetType\n offset;\n\n MagickSizeType\n length;\n\n MagickBooleanType\n status;\n\n PSDInfo\n psd_info;\n\n register ssize_t\n i;\n\n ssize_t\n count;\n\n unsigned char\n *data;\n\n /*\n Open image file.\n */\n assert(image_info != (const ImageInfo *) NULL);\n assert(image_info->signature == MagickSignature);\n if (image_info->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",\n image_info->filename);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickSignature);\n\n image=AcquireImage(image_info);\n status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);\n if (status == MagickFalse)\n {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n /*\n Read image header.\n */\n image->endian=MSBEndian;\n count=ReadBlob(image,4,(unsigned char *) psd_info.signature);\n psd_info.version=ReadBlobMSBShort(image);\n if ((count == 0) || (LocaleNCompare(psd_info.signature,\"8BPS\",4) != 0) ||\n ((psd_info.version != 1) && (psd_info.version != 2)))\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n (void) ReadBlob(image,6,psd_info.reserved);\n psd_info.channels=ReadBlobMSBShort(image);\n if (psd_info.channels > MaxPSDChannels)\n ThrowReaderException(CorruptImageError,\"MaximumChannelsExceeded\");\n psd_info.rows=ReadBlobMSBLong(image);\n psd_info.columns=ReadBlobMSBLong(image);\n if ((psd_info.version == 1) && ((psd_info.rows > 30000) ||\n (psd_info.columns > 30000)))\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n psd_info.depth=ReadBlobMSBShort(image);\n if ((psd_info.depth != 1) && (psd_info.depth != 8) && (psd_info.depth != 16))\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n psd_info.mode=ReadBlobMSBShort(image);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Image is %.20g x %.20g with channels=%.20g, depth=%.20g, mode=%s\",\n (double) psd_info.columns,(double) psd_info.rows,(double)\n psd_info.channels,(double) psd_info.depth,ModeToString((PSDImageType)\n psd_info.mode));\n /*\n Initialize image.\n */\n image->depth=psd_info.depth;\n image->columns=psd_info.columns;\n image->rows=psd_info.rows;\n status=SetImageExtent(image,image->columns,image->rows);\n if (status == MagickFalse)\n {\n InheritException(exception,&image->exception);\n return(DestroyImageList(image));\n }\n if (SetImageBackgroundColor(image) == MagickFalse)\n {\n InheritException(exception,&image->exception);\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n if (psd_info.mode == LabMode)\n SetImageColorspace(image,LabColorspace);\n if (psd_info.mode == CMYKMode)\n {\n SetImageColorspace(image,CMYKColorspace);\n image->matte=psd_info.channels > 4 ? MagickTrue : MagickFalse;\n }\n else if ((psd_info.mode == BitmapMode) || (psd_info.mode == GrayscaleMode) ||\n (psd_info.mode == DuotoneMode))\n {\n status=AcquireImageColormap(image,psd_info.depth != 16 ? 256 : 65536);\n if (status == MagickFalse)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Image colormap allocated\");\n SetImageColorspace(image,GRAYColorspace);\n image->matte=psd_info.channels > 1 ? MagickTrue : MagickFalse;\n }\n else\n image->matte=psd_info.channels > 3 ? MagickTrue : MagickFalse;\n /*\n Read PSD raster colormap only present for indexed and duotone images.\n */\n length=ReadBlobMSBLong(image);\n if (length != 0)\n {\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" reading colormap\");\n if (psd_info.mode == DuotoneMode)\n {\n /*\n Duotone image data; the format of this data is undocumented.\n */\n data=(unsigned char *) AcquireQuantumMemory((size_t) length,\n sizeof(*data));\n if (data == (unsigned char *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n (void) ReadBlob(image,(size_t) length,data);\n data=(unsigned char *) RelinquishMagickMemory(data);\n }\n else\n {\n size_t\n number_colors;\n\n /*\n Read PSD raster colormap.\n */\n number_colors=length/3;\n if (number_colors > 65536)\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n if (AcquireImageColormap(image,number_colors) == MagickFalse)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n for (i=0; i < (ssize_t) image->colors; i++)\n image->colormap[i].red=ScaleCharToQuantum((unsigned char)\n ReadBlobByte(image));\n for (i=0; i < (ssize_t) image->colors; i++)\n image->colormap[i].green=ScaleCharToQuantum((unsigned char)\n ReadBlobByte(image));\n for (i=0; i < (ssize_t) image->colors; i++)\n image->colormap[i].blue=ScaleCharToQuantum((unsigned char)\n ReadBlobByte(image));\n image->matte=MagickFalse;\n }\n }\n if ((image->depth == 1) && (image->storage_class != PseudoClass))\n ThrowReaderException(CorruptImageError, \"ImproperImageHeader\");\n has_merged_image=MagickTrue;\n length=ReadBlobMSBLong(image);\n if (length != 0)\n {\n unsigned char\n *blocks;\n\n /*\n Image resources block.\n */\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" reading image resource blocks - %.20g bytes\",(double)\n ((MagickOffsetType) length));\n blocks=(unsigned char *) AcquireQuantumMemory((size_t) length,\n sizeof(*blocks));\n if (blocks == (unsigned char *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n count=ReadBlob(image,(size_t) length,blocks);\n if ((count != (ssize_t) length) || (length < 4) ||\n (LocaleNCompare((char *) blocks,\"8BIM\",4) != 0))\n {\n blocks=(unsigned char *) RelinquishMagickMemory(blocks);\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n }\n ParseImageResourceBlocks(image,blocks,(size_t) length,&has_merged_image);\n blocks=(unsigned char *) RelinquishMagickMemory(blocks);\n }\n /*\n Layer and mask block.\n */\n length=GetPSDSize(&psd_info,image);\n if (length == 8)\n {\n length=ReadBlobMSBLong(image);\n length=ReadBlobMSBLong(image);\n }\n offset=TellBlob(image);\n skip_layers=MagickFalse;\n if ((image_info->number_scenes == 1) && (image_info->scene == 0) &&\n (has_merged_image != MagickFalse))\n {\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" read composite only\");\n skip_layers=MagickTrue;\n }\n if (length == 0)\n {\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" image has no layers\");\n }\n else\n {\n if (ReadPSDLayers(image,image_info,&psd_info,skip_layers,exception) !=\n MagickTrue)\n {\n (void) CloseBlob(image);\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n /*\n Skip the rest of the layer and mask information.\n */\n SeekBlob(image,offset+length,SEEK_SET);\n }\n /*\n If we are only \"pinging\" the image, then we're done - so return.\n */\n if (image_info->ping != MagickFalse)\n {\n (void) CloseBlob(image);\n return(GetFirstImageInList(image));\n }\n /*\n Read the precombined layer, present for PSD < 4 compatibility.\n */\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" reading the precombined layer\");\n if (has_merged_image != MagickFalse || GetImageListLength(image) == 1)\n has_merged_image=(MagickBooleanType) ReadPSDMergedImage(image_info,image,\n &psd_info,exception);\n if ((has_merged_image == MagickFalse) && (GetImageListLength(image) == 1) &&\n (length != 0))\n {\n SeekBlob(image,offset,SEEK_SET);\n status=ReadPSDLayers(image,image_info,&psd_info,MagickFalse,exception);\n if (status != MagickTrue)\n {\n (void) CloseBlob(image);\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n }\n if (has_merged_image == MagickFalse)\n {\n Image\n *merged;\n\n if (GetImageListLength(image) == 1)\n ThrowReaderException(CorruptImageError,\"InsufficientImageDataInFile\");\n SetImageAlphaChannel(image,TransparentAlphaChannel);\n image->background_color.opacity=TransparentOpacity;\n merged=MergeImageLayers(image,FlattenLayer,exception);\n ReplaceImageInList(&image,merged);\n }\n (void) CloseBlob(image);\n return(GetFirstImageInList(image));\n}\n", + "line": null, + "label": 0, + "cwe": "CWE-476", + "cve": "CVE-2017-6497", + "length": 2381 + }, + { + "index": 19148, + "code": "static int tcp_v6_rcv(struct sk_buff *skb)\n{\n\tstruct tcphdr *th;\n\tconst struct ipv6hdr *hdr;\n\tstruct sock *sk;\n\tint ret;\n\tstruct net *net = dev_net(skb->dev);\n\n\tif (skb->pkt_type != PACKET_HOST)\n\t\tgoto discard_it;\n\n\t/*\n\t *\tCount it even if it's bad.\n\t */\n\tTCP_INC_STATS_BH(net, TCP_MIB_INSEGS);\n\n\tif (!pskb_may_pull(skb, sizeof(struct tcphdr)))\n\t\tgoto discard_it;\n\n\tth = tcp_hdr(skb);\n\n\tif (th->doff < sizeof(struct tcphdr)/4)\n\t\tgoto bad_packet;\n\tif (!pskb_may_pull(skb, th->doff*4))\n\t\tgoto discard_it;\n\n\tif (!skb_csum_unnecessary(skb) && tcp_v6_checksum_init(skb))\n\t\tgoto bad_packet;\n\n\tth = tcp_hdr(skb);\n\thdr = ipv6_hdr(skb);\n\tTCP_SKB_CB(skb)->seq = ntohl(th->seq);\n\tTCP_SKB_CB(skb)->end_seq = (TCP_SKB_CB(skb)->seq + th->syn + th->fin +\n\t\t\t\t skb->len - th->doff*4);\n\tTCP_SKB_CB(skb)->ack_seq = ntohl(th->ack_seq);\n\tTCP_SKB_CB(skb)->when = 0;\n\tTCP_SKB_CB(skb)->flags = ipv6_get_dsfield(hdr);\n\tTCP_SKB_CB(skb)->sacked = 0;\n\n\tsk = __inet6_lookup_skb(&tcp_hashinfo, skb, th->source, th->dest);\n\tif (!sk)\n\t\tgoto no_tcp_socket;\n\nprocess:\n\tif (sk->sk_state == TCP_TIME_WAIT)\n\t\tgoto do_time_wait;\n\n\tif (hdr->hop_limit < inet6_sk(sk)->min_hopcount) {\n\t\tNET_INC_STATS_BH(net, LINUX_MIB_TCPMINTTLDROP);\n\t\tgoto discard_and_relse;\n\t}\n\n\tif (!xfrm6_policy_check(sk, XFRM_POLICY_IN, skb))\n\t\tgoto discard_and_relse;\n\n\tif (sk_filter(sk, skb))\n\t\tgoto discard_and_relse;\n\n\tskb->dev = NULL;\n\n\tbh_lock_sock_nested(sk);\n\tret = 0;\n\tif (!sock_owned_by_user(sk)) {\n#ifdef CONFIG_NET_DMA\n\t\tstruct tcp_sock *tp = tcp_sk(sk);\n\t\tif (!tp->ucopy.dma_chan && tp->ucopy.pinned_list)\n\t\t\ttp->ucopy.dma_chan = dma_find_channel(DMA_MEMCPY);\n\t\tif (tp->ucopy.dma_chan)\n\t\t\tret = tcp_v6_do_rcv(sk, skb);\n\t\telse\n#endif\n\t\t{\n\t\t\tif (!tcp_prequeue(sk, skb))\n\t\t\t\tret = tcp_v6_do_rcv(sk, skb);\n\t\t}\n\t} else if (unlikely(sk_add_backlog(sk, skb))) {\n\t\tbh_unlock_sock(sk);\n\t\tNET_INC_STATS_BH(net, LINUX_MIB_TCPBACKLOGDROP);\n\t\tgoto discard_and_relse;\n\t}\n\tbh_unlock_sock(sk);\n\n\tsock_put(sk);\n\treturn ret ? -1 : 0;\n\nno_tcp_socket:\n\tif (!xfrm6_policy_check(NULL, XFRM_POLICY_IN, skb))\n\t\tgoto discard_it;\n\n\tif (skb->len < (th->doff<<2) || tcp_checksum_complete(skb)) {\nbad_packet:\n\t\tTCP_INC_STATS_BH(net, TCP_MIB_INERRS);\n\t} else {\n\t\ttcp_v6_send_reset(NULL, skb);\n\t}\n\ndiscard_it:\n\n\t/*\n\t *\tDiscard frame\n\t */\n\n\tkfree_skb(skb);\n\treturn 0;\n\ndiscard_and_relse:\n\tsock_put(sk);\n\tgoto discard_it;\n\ndo_time_wait:\n\tif (!xfrm6_policy_check(NULL, XFRM_POLICY_IN, skb)) {\n\t\tinet_twsk_put(inet_twsk(sk));\n\t\tgoto discard_it;\n\t}\n\n\tif (skb->len < (th->doff<<2) || tcp_checksum_complete(skb)) {\n\t\tTCP_INC_STATS_BH(net, TCP_MIB_INERRS);\n\t\tinet_twsk_put(inet_twsk(sk));\n\t\tgoto discard_it;\n\t}\n\n\tswitch (tcp_timewait_state_process(inet_twsk(sk), skb, th)) {\n\tcase TCP_TW_SYN:\n\t{\n\t\tstruct sock *sk2;\n\n\t\tsk2 = inet6_lookup_listener(dev_net(skb->dev), &tcp_hashinfo,\n\t\t\t\t\t &ipv6_hdr(skb)->daddr,\n\t\t\t\t\t ntohs(th->dest), inet6_iif(skb));\n\t\tif (sk2 != NULL) {\n\t\t\tstruct inet_timewait_sock *tw = inet_twsk(sk);\n\t\t\tinet_twsk_deschedule(tw, &tcp_death_row);\n\t\t\tinet_twsk_put(tw);\n\t\t\tsk = sk2;\n\t\t\tgoto process;\n\t\t}\n\t\t/* Fall through to ACK */\n\t}\n\tcase TCP_TW_ACK:\n\t\ttcp_v6_timewait_ack(sk, skb);\n\t\tbreak;\n\tcase TCP_TW_RST:\n\t\tgoto no_tcp_socket;\n\tcase TCP_TW_SUCCESS:;\n\t}\n\tgoto discard_it;\n}\n", + "line": null, + "label": 0, + "cwe": "CWE-362", + "cve": "CVE-2012-3552", + "length": 1056 + }, + { + "index": 178364, + "code": "expand_string_internal(uschar *string, BOOL ket_ends, uschar **left,\n BOOL skipping, BOOL honour_dollar, BOOL *resetok_p)\n{\nint ptr = 0;\nint size = Ustrlen(string)+ 64;\nint item_type;\nuschar *yield = store_get(size);\nuschar *s = string;\nuschar *save_expand_nstring[EXPAND_MAXN+1];\nint save_expand_nlength[EXPAND_MAXN+1];\nBOOL resetok = TRUE;\n\nexpand_string_forcedfail = FALSE;\nexpand_string_message = US\"\";\n\nwhile (*s != 0)\n {\n uschar *value;\n uschar name[256];\n\n /* \\ escapes the next character, which must exist, or else\n the expansion fails. There's a special escape, \\N, which causes\n copying of the subject verbatim up to the next \\N. Otherwise,\n the escapes are the standard set. */\n\n if (*s == '\\\\')\n {\n if (s[1] == 0)\n {\n expand_string_message = US\"\\\\ at end of string\";\n goto EXPAND_FAILED;\n }\n\n if (s[1] == 'N')\n {\n uschar *t = s + 2;\n for (s = t; *s != 0; s++) if (*s == '\\\\' && s[1] == 'N') break;\n yield = string_cat(yield, &size, &ptr, t, s - t);\n if (*s != 0) s += 2;\n }\n\n else\n {\n uschar ch[1];\n ch[0] = string_interpret_escape(&s);\n s++;\n yield = string_cat(yield, &size, &ptr, ch, 1);\n }\n\n continue;\n }\n\n /*{*/\n /* Anything other than $ is just copied verbatim, unless we are\n looking for a terminating } character. */\n\n /*{*/\n if (ket_ends && *s == '}') break;\n\n if (*s != '$' || !honour_dollar)\n {\n yield = string_cat(yield, &size, &ptr, s++, 1);\n continue;\n }\n\n /* No { after the $ - must be a plain name or a number for string\n match variable. There has to be a fudge for variables that are the\n names of header fields preceded by \"$header_\" because header field\n names can contain any printing characters except space and colon.\n For those that don't like typing this much, \"$h_\" is a synonym for\n \"$header_\". A non-existent header yields a NULL value; nothing is\n inserted. */\t/*}*/\n\n if (isalpha((*(++s))))\n {\n int len;\n int newsize = 0;\n\n s = read_name(name, sizeof(name), s, US\"_\");\n\n /* If this is the first thing to be expanded, release the pre-allocated\n buffer. */\n\n if (ptr == 0 && yield != NULL)\n {\n if (resetok) store_reset(yield);\n yield = NULL;\n size = 0;\n }\n\n /* Header */\n\n if (Ustrncmp(name, \"h_\", 2) == 0 ||\n Ustrncmp(name, \"rh_\", 3) == 0 ||\n Ustrncmp(name, \"bh_\", 3) == 0 ||\n Ustrncmp(name, \"header_\", 7) == 0 ||\n Ustrncmp(name, \"rheader_\", 8) == 0 ||\n Ustrncmp(name, \"bheader_\", 8) == 0)\n {\n BOOL want_raw = (name[0] == 'r')? TRUE : FALSE;\n uschar *charset = (name[0] == 'b')? NULL : headers_charset;\n s = read_header_name(name, sizeof(name), s);\n value = find_header(name, FALSE, &newsize, want_raw, charset);\n\n /* If we didn't find the header, and the header contains a closing brace\n character, this may be a user error where the terminating colon\n has been omitted. Set a flag to adjust the error message in this case.\n But there is no error here - nothing gets inserted. */\n\n if (value == NULL)\n {\n if (Ustrchr(name, '}') != NULL) malformed_header = TRUE;\n continue;\n }\n }\n\n /* Variable */\n\n else\n {\n value = find_variable(name, FALSE, skipping, &newsize);\n if (value == NULL)\n {\n expand_string_message =\n string_sprintf(\"unknown variable name \\\"%s\\\"\", name);\n check_variable_error_message(name);\n goto EXPAND_FAILED;\n }\n }\n\n /* If the data is known to be in a new buffer, newsize will be set to the\n size of that buffer. If this is the first thing in an expansion string,\n yield will be NULL; just point it at the new store instead of copying. Many\n expansion strings contain just one reference, so this is a useful\n optimization, especially for humungous headers. */\n\n len = Ustrlen(value);\n if (yield == NULL && newsize != 0)\n {\n yield = value;\n size = newsize;\n ptr = len;\n }\n else yield = string_cat(yield, &size, &ptr, value, len);\n\n continue;\n }\n\n if (isdigit(*s))\n {\n int n;\n s = read_number(&n, s);\n if (n >= 0 && n <= expand_nmax)\n yield = string_cat(yield, &size, &ptr, expand_nstring[n],\n expand_nlength[n]);\n continue;\n }\n\n /* Otherwise, if there's no '{' after $ it's an error. */\t\t/*}*/\n\n if (*s != '{')\t\t\t\t\t\t\t/*}*/\n {\n expand_string_message = US\"$ not followed by letter, digit, or {\";\t/*}*/\n goto EXPAND_FAILED;\n }\n\n /* After { there can be various things, but they all start with\n an initial word, except for a number for a string match variable. */\n\n if (isdigit((*(++s))))\n {\n int n;\n s = read_number(&n, s);\t\t/*{*/\n if (*s++ != '}')\n {\t\t\t\t\t/*{*/\n expand_string_message = US\"} expected after number\";\n goto EXPAND_FAILED;\n }\n if (n >= 0 && n <= expand_nmax)\n yield = string_cat(yield, &size, &ptr, expand_nstring[n],\n expand_nlength[n]);\n continue;\n }\n\n if (!isalpha(*s))\n {\n expand_string_message = US\"letter or digit expected after ${\";\t/*}*/\n goto EXPAND_FAILED;\n }\n\n /* Allow \"-\" in names to cater for substrings with negative\n arguments. Since we are checking for known names after { this is\n OK. */\n\n s = read_name(name, sizeof(name), s, US\"_-\");\n item_type = chop_match(name, item_table, sizeof(item_table)/sizeof(uschar *));\n\n switch(item_type)\n {\n /* Call an ACL from an expansion. We feed data in via $acl_arg1 - $acl_arg9.\n If the ACL returns accept or reject we return content set by \"message =\"\n There is currently no limit on recursion; this would have us call\n acl_check_internal() directly and get a current level from somewhere.\n See also the acl expansion condition ECOND_ACL and the traditional\n acl modifier ACLC_ACL.\n Assume that the function has side-effects on the store that must be preserved.\n */\n\n case EITEM_ACL:\n /* ${acl {name} {arg1}{arg2}...} */\n {\n uschar *sub[10];\t/* name + arg1-arg9 (which must match number of acl_arg[]) */\n uschar *user_msg;\n\n switch(read_subs(sub, 10, 1, &s, skipping, TRUE, US\"acl\", &resetok))\n {\n case 1: goto EXPAND_FAILED_CURLY;\n case 2:\n case 3: goto EXPAND_FAILED;\n }\n if (skipping) continue;\n\n resetok = FALSE;\n switch(eval_acl(sub, sizeof(sub)/sizeof(*sub), &user_msg))\n\t{\n\tcase OK:\n\tcase FAIL:\n\t DEBUG(D_expand)\n\t debug_printf(\"acl expansion yield: %s\\n\", user_msg);\n\t if (user_msg)\n yield = string_cat(yield, &size, &ptr, user_msg, Ustrlen(user_msg));\n\t continue;\n\n\tcase DEFER:\n expand_string_forcedfail = TRUE;\n\tdefault:\n expand_string_message = string_sprintf(\"error from acl \\\"%s\\\"\", sub[0]);\n\t goto EXPAND_FAILED;\n\t}\n }\n\n /* Handle conditionals - preserve the values of the numerical expansion\n variables in case they get changed by a regular expression match in the\n condition. If not, they retain their external settings. At the end\n of this \"if\" section, they get restored to their previous values. */\n\n case EITEM_IF:\n {\n BOOL cond = FALSE;\n uschar *next_s;\n int save_expand_nmax =\n save_expand_strings(save_expand_nstring, save_expand_nlength);\n\n while (isspace(*s)) s++;\n next_s = eval_condition(s, &resetok, skipping? NULL : &cond);\n if (next_s == NULL) goto EXPAND_FAILED; /* message already set */\n\n DEBUG(D_expand)\n debug_printf(\"condition: %.*s\\n result: %s\\n\", (int)(next_s - s), s,\n cond? \"true\" : \"false\");\n\n s = next_s;\n\n /* The handling of \"yes\" and \"no\" result strings is now in a separate\n function that is also used by ${lookup} and ${extract} and ${run}. */\n\n switch(process_yesno(\n skipping, /* were previously skipping */\n cond, /* success/failure indicator */\n lookup_value, /* value to reset for string2 */\n &s, /* input pointer */\n &yield, /* output pointer */\n &size, /* output size */\n &ptr, /* output current point */\n US\"if\", /* condition type */\n\t &resetok))\n {\n case 1: goto EXPAND_FAILED; /* when all is well, the */\n case 2: goto EXPAND_FAILED_CURLY; /* returned value is 0 */\n }\n\n /* Restore external setting of expansion variables for continuation\n at this level. */\n\n restore_expand_strings(save_expand_nmax, save_expand_nstring,\n save_expand_nlength);\n continue;\n }\n\n /* Handle database lookups unless locked out. If \"skipping\" is TRUE, we are\n expanding an internal string that isn't actually going to be used. All we\n need to do is check the syntax, so don't do a lookup at all. Preserve the\n values of the numerical expansion variables in case they get changed by a\n partial lookup. If not, they retain their external settings. At the end\n of this \"lookup\" section, they get restored to their previous values. */\n\n case EITEM_LOOKUP:\n {\n int stype, partial, affixlen, starflags;\n int expand_setup = 0;\n int nameptr = 0;\n uschar *key, *filename, *affix;\n uschar *save_lookup_value = lookup_value;\n int save_expand_nmax =\n save_expand_strings(save_expand_nstring, save_expand_nlength);\n\n if ((expand_forbid & RDO_LOOKUP) != 0)\n {\n expand_string_message = US\"lookup expansions are not permitted\";\n goto EXPAND_FAILED;\n }\n\n /* Get the key we are to look up for single-key+file style lookups.\n Otherwise set the key NULL pro-tem. */\n\n while (isspace(*s)) s++;\n if (*s == '{')\t\t\t\t\t/*}*/\n {\n key = expand_string_internal(s+1, TRUE, &s, skipping, TRUE, &resetok);\n if (key == NULL) goto EXPAND_FAILED;\t\t/*{*/\n if (*s++ != '}') goto EXPAND_FAILED_CURLY;\n while (isspace(*s)) s++;\n }\n else key = NULL;\n\n /* Find out the type of database */\n\n if (!isalpha(*s))\n {\n expand_string_message = US\"missing lookup type\";\n goto EXPAND_FAILED;\n }\n\n /* The type is a string that may contain special characters of various\n kinds. Allow everything except space or { to appear; the actual content\n is checked by search_findtype_partial. */\t\t/*}*/\n\n while (*s != 0 && *s != '{' && !isspace(*s))\t/*}*/\n {\n if (nameptr < sizeof(name) - 1) name[nameptr++] = *s;\n s++;\n }\n name[nameptr] = 0;\n while (isspace(*s)) s++;\n\n /* Now check for the individual search type and any partial or default\n options. Only those types that are actually in the binary are valid. */\n\n stype = search_findtype_partial(name, &partial, &affix, &affixlen,\n &starflags);\n if (stype < 0)\n {\n expand_string_message = search_error_message;\n goto EXPAND_FAILED;\n }\n\n /* Check that a key was provided for those lookup types that need it,\n and was not supplied for those that use the query style. */\n\n if (!mac_islookup(stype, lookup_querystyle|lookup_absfilequery))\n {\n if (key == NULL)\n {\n expand_string_message = string_sprintf(\"missing {key} for single-\"\n \"key \\\"%s\\\" lookup\", name);\n goto EXPAND_FAILED;\n }\n }\n else\n {\n if (key != NULL)\n {\n expand_string_message = string_sprintf(\"a single key was given for \"\n \"lookup type \\\"%s\\\", which is not a single-key lookup type\", name);\n goto EXPAND_FAILED;\n }\n }\n\n /* Get the next string in brackets and expand it. It is the file name for\n single-key+file lookups, and the whole query otherwise. In the case of\n queries that also require a file name (e.g. sqlite), the file name comes\n first. */\n\n if (*s != '{') goto EXPAND_FAILED_CURLY;\n filename = expand_string_internal(s+1, TRUE, &s, skipping, TRUE, &resetok);\n if (filename == NULL) goto EXPAND_FAILED;\n if (*s++ != '}') goto EXPAND_FAILED_CURLY;\n while (isspace(*s)) s++;\n\n /* If this isn't a single-key+file lookup, re-arrange the variables\n to be appropriate for the search_ functions. For query-style lookups,\n there is just a \"key\", and no file name. For the special query-style +\n file types, the query (i.e. \"key\") starts with a file name. */\n\n if (key == NULL)\n {\n while (isspace(*filename)) filename++;\n key = filename;\n\n if (mac_islookup(stype, lookup_querystyle))\n {\n filename = NULL;\n }\n else\n {\n if (*filename != '/')\n {\n expand_string_message = string_sprintf(\n \"absolute file name expected for \\\"%s\\\" lookup\", name);\n goto EXPAND_FAILED;\n }\n while (*key != 0 && !isspace(*key)) key++;\n if (*key != 0) *key++ = 0;\n }\n }\n\n /* If skipping, don't do the next bit - just lookup_value == NULL, as if\n the entry was not found. Note that there is no search_close() function.\n Files are left open in case of re-use. At suitable places in higher logic,\n search_tidyup() is called to tidy all open files. This can save opening\n the same file several times. However, files may also get closed when\n others are opened, if too many are open at once. The rule is that a\n handle should not be used after a second search_open().\n\n Request that a partial search sets up $1 and maybe $2 by passing\n expand_setup containing zero. If its value changes, reset expand_nmax,\n since new variables will have been set. Note that at the end of this\n \"lookup\" section, the old numeric variables are restored. */\n\n if (skipping)\n lookup_value = NULL;\n else\n {\n void *handle = search_open(filename, stype, 0, NULL, NULL);\n if (handle == NULL)\n {\n expand_string_message = search_error_message;\n goto EXPAND_FAILED;\n }\n lookup_value = search_find(handle, filename, key, partial, affix,\n affixlen, starflags, &expand_setup);\n if (search_find_defer)\n {\n expand_string_message =\n string_sprintf(\"lookup of \\\"%s\\\" gave DEFER: %s\",\n string_printing2(key, FALSE), search_error_message);\n goto EXPAND_FAILED;\n }\n if (expand_setup > 0) expand_nmax = expand_setup;\n }\n\n /* The handling of \"yes\" and \"no\" result strings is now in a separate\n function that is also used by ${if} and ${extract}. */\n\n switch(process_yesno(\n skipping, /* were previously skipping */\n lookup_value != NULL, /* success/failure indicator */\n save_lookup_value, /* value to reset for string2 */\n &s, /* input pointer */\n &yield, /* output pointer */\n &size, /* output size */\n &ptr, /* output current point */\n US\"lookup\", /* condition type */\n\t &resetok))\n {\n case 1: goto EXPAND_FAILED; /* when all is well, the */\n case 2: goto EXPAND_FAILED_CURLY; /* returned value is 0 */\n }\n\n /* Restore external setting of expansion variables for carrying on\n at this level, and continue. */\n\n restore_expand_strings(save_expand_nmax, save_expand_nstring,\n save_expand_nlength);\n continue;\n }\n\n /* If Perl support is configured, handle calling embedded perl subroutines,\n unless locked out at this time. Syntax is ${perl{sub}} or ${perl{sub}{arg}}\n or ${perl{sub}{arg1}{arg2}} or up to a maximum of EXIM_PERL_MAX_ARGS\n arguments (defined below). */\n\n #define EXIM_PERL_MAX_ARGS 8\n\n case EITEM_PERL:\n #ifndef EXIM_PERL\n expand_string_message = US\"\\\"${perl\\\" encountered, but this facility \"\t/*}*/\n \"is not included in this binary\";\n goto EXPAND_FAILED;\n\n #else /* EXIM_PERL */\n {\n uschar *sub_arg[EXIM_PERL_MAX_ARGS + 2];\n uschar *new_yield;\n\n if ((expand_forbid & RDO_PERL) != 0)\n {\n expand_string_message = US\"Perl calls are not permitted\";\n goto EXPAND_FAILED;\n }\n\n switch(read_subs(sub_arg, EXIM_PERL_MAX_ARGS + 1, 1, &s, skipping, TRUE,\n US\"perl\", &resetok))\n {\n case 1: goto EXPAND_FAILED_CURLY;\n case 2:\n case 3: goto EXPAND_FAILED;\n }\n\n /* If skipping, we don't actually do anything */\n\n if (skipping) continue;\n\n /* Start the interpreter if necessary */\n\n if (!opt_perl_started)\n {\n uschar *initerror;\n if (opt_perl_startup == NULL)\n {\n expand_string_message = US\"A setting of perl_startup is needed when \"\n \"using the Perl interpreter\";\n goto EXPAND_FAILED;\n }\n DEBUG(D_any) debug_printf(\"Starting Perl interpreter\\n\");\n initerror = init_perl(opt_perl_startup);\n if (initerror != NULL)\n {\n expand_string_message =\n string_sprintf(\"error in perl_startup code: %s\\n\", initerror);\n goto EXPAND_FAILED;\n }\n opt_perl_started = TRUE;\n }\n\n /* Call the function */\n\n sub_arg[EXIM_PERL_MAX_ARGS + 1] = NULL;\n new_yield = call_perl_cat(yield, &size, &ptr, &expand_string_message,\n sub_arg[0], sub_arg + 1);\n\n /* NULL yield indicates failure; if the message pointer has been set to\n NULL, the yield was undef, indicating a forced failure. Otherwise the\n message will indicate some kind of Perl error. */\n\n if (new_yield == NULL)\n {\n if (expand_string_message == NULL)\n {\n expand_string_message =\n string_sprintf(\"Perl subroutine \\\"%s\\\" returned undef to force \"\n \"failure\", sub_arg[0]);\n expand_string_forcedfail = TRUE;\n }\n goto EXPAND_FAILED;\n }\n\n /* Yield succeeded. Ensure forcedfail is unset, just in case it got\n set during a callback from Perl. */\n\n expand_string_forcedfail = FALSE;\n yield = new_yield;\n continue;\n }\n #endif /* EXIM_PERL */\n\n /* Transform email address to \"prvs\" scheme to use\n as BATV-signed return path */\n\n case EITEM_PRVS:\n {\n uschar *sub_arg[3];\n uschar *p,*domain;\n\n switch(read_subs(sub_arg, 3, 2, &s, skipping, TRUE, US\"prvs\", &resetok))\n {\n case 1: goto EXPAND_FAILED_CURLY;\n case 2:\n case 3: goto EXPAND_FAILED;\n }\n\n /* If skipping, we don't actually do anything */\n if (skipping) continue;\n\n /* sub_arg[0] is the address */\n domain = Ustrrchr(sub_arg[0],'@');\n if ( (domain == NULL) || (domain == sub_arg[0]) || (Ustrlen(domain) == 1) )\n {\n expand_string_message = US\"prvs first argument must be a qualified email address\";\n goto EXPAND_FAILED;\n }\n\n /* Calculate the hash. The second argument must be a single-digit\n key number, or unset. */\n\n if (sub_arg[2] != NULL &&\n (!isdigit(sub_arg[2][0]) || sub_arg[2][1] != 0))\n {\n expand_string_message = US\"prvs second argument must be a single digit\";\n goto EXPAND_FAILED;\n }\n\n p = prvs_hmac_sha1(sub_arg[0],sub_arg[1],sub_arg[2],prvs_daystamp(7));\n if (p == NULL)\n {\n expand_string_message = US\"prvs hmac-sha1 conversion failed\";\n goto EXPAND_FAILED;\n }\n\n /* Now separate the domain from the local part */\n *domain++ = '\\0';\n\n yield = string_cat(yield,&size,&ptr,US\"prvs=\",5);\n string_cat(yield,&size,&ptr,(sub_arg[2] != NULL) ? sub_arg[2] : US\"0\", 1);\n string_cat(yield,&size,&ptr,prvs_daystamp(7),3);\n string_cat(yield,&size,&ptr,p,6);\n string_cat(yield,&size,&ptr,US\"=\",1);\n string_cat(yield,&size,&ptr,sub_arg[0],Ustrlen(sub_arg[0]));\n string_cat(yield,&size,&ptr,US\"@\",1);\n string_cat(yield,&size,&ptr,domain,Ustrlen(domain));\n\n continue;\n }\n\n /* Check a prvs-encoded address for validity */\n\n case EITEM_PRVSCHECK:\n {\n uschar *sub_arg[3];\n int mysize = 0, myptr = 0;\n const pcre *re;\n uschar *p;\n\n /* TF: Ugliness: We want to expand parameter 1 first, then set\n up expansion variables that are used in the expansion of\n parameter 2. So we clone the string for the first\n expansion, where we only expand parameter 1.\n\n PH: Actually, that isn't necessary. The read_subs() function is\n designed to work this way for the ${if and ${lookup expansions. I've\n tidied the code.\n */\n\n /* Reset expansion variables */\n prvscheck_result = NULL;\n prvscheck_address = NULL;\n prvscheck_keynum = NULL;\n\n switch(read_subs(sub_arg, 1, 1, &s, skipping, FALSE, US\"prvs\", &resetok))\n {\n case 1: goto EXPAND_FAILED_CURLY;\n case 2:\n case 3: goto EXPAND_FAILED;\n }\n\n re = regex_must_compile(US\"^prvs\\\\=([0-9])([0-9]{3})([A-F0-9]{6})\\\\=(.+)\\\\@(.+)$\",\n TRUE,FALSE);\n\n if (regex_match_and_setup(re,sub_arg[0],0,-1))\n {\n uschar *local_part = string_copyn(expand_nstring[4],expand_nlength[4]);\n uschar *key_num = string_copyn(expand_nstring[1],expand_nlength[1]);\n uschar *daystamp = string_copyn(expand_nstring[2],expand_nlength[2]);\n uschar *hash = string_copyn(expand_nstring[3],expand_nlength[3]);\n uschar *domain = string_copyn(expand_nstring[5],expand_nlength[5]);\n\n DEBUG(D_expand) debug_printf(\"prvscheck localpart: %s\\n\", local_part);\n DEBUG(D_expand) debug_printf(\"prvscheck key number: %s\\n\", key_num);\n DEBUG(D_expand) debug_printf(\"prvscheck daystamp: %s\\n\", daystamp);\n DEBUG(D_expand) debug_printf(\"prvscheck hash: %s\\n\", hash);\n DEBUG(D_expand) debug_printf(\"prvscheck domain: %s\\n\", domain);\n\n /* Set up expansion variables */\n prvscheck_address = string_cat(NULL, &mysize, &myptr, local_part, Ustrlen(local_part));\n string_cat(prvscheck_address,&mysize,&myptr,US\"@\",1);\n string_cat(prvscheck_address,&mysize,&myptr,domain,Ustrlen(domain));\n prvscheck_address[myptr] = '\\0';\n prvscheck_keynum = string_copy(key_num);\n\n /* Now expand the second argument */\n switch(read_subs(sub_arg, 1, 1, &s, skipping, FALSE, US\"prvs\", &resetok))\n {\n case 1: goto EXPAND_FAILED_CURLY;\n case 2:\n case 3: goto EXPAND_FAILED;\n }\n\n /* Now we have the key and can check the address. */\n\n p = prvs_hmac_sha1(prvscheck_address, sub_arg[0], prvscheck_keynum,\n daystamp);\n\n if (p == NULL)\n {\n expand_string_message = US\"hmac-sha1 conversion failed\";\n goto EXPAND_FAILED;\n }\n\n DEBUG(D_expand) debug_printf(\"prvscheck: received hash is %s\\n\", hash);\n DEBUG(D_expand) debug_printf(\"prvscheck: own hash is %s\\n\", p);\n\n if (Ustrcmp(p,hash) == 0)\n {\n /* Success, valid BATV address. Now check the expiry date. */\n uschar *now = prvs_daystamp(0);\n unsigned int inow = 0,iexpire = 1;\n\n (void)sscanf(CS now,\"%u\",&inow);\n (void)sscanf(CS daystamp,\"%u\",&iexpire);\n\n /* When \"iexpire\" is < 7, a \"flip\" has occured.\n Adjust \"inow\" accordingly. */\n if ( (iexpire < 7) && (inow >= 993) ) inow = 0;\n\n if (iexpire >= inow)\n {\n prvscheck_result = US\"1\";\n DEBUG(D_expand) debug_printf(\"prvscheck: success, $pvrs_result set to 1\\n\");\n }\n else\n {\n prvscheck_result = NULL;\n DEBUG(D_expand) debug_printf(\"prvscheck: signature expired, $pvrs_result unset\\n\");\n }\n }\n else\n {\n prvscheck_result = NULL;\n DEBUG(D_expand) debug_printf(\"prvscheck: hash failure, $pvrs_result unset\\n\");\n }\n\n /* Now expand the final argument. We leave this till now so that\n it can include $prvscheck_result. */\n\n switch(read_subs(sub_arg, 1, 0, &s, skipping, TRUE, US\"prvs\", &resetok))\n {\n case 1: goto EXPAND_FAILED_CURLY;\n case 2:\n case 3: goto EXPAND_FAILED;\n }\n\n if (sub_arg[0] == NULL || *sub_arg[0] == '\\0')\n yield = string_cat(yield,&size,&ptr,prvscheck_address,Ustrlen(prvscheck_address));\n else\n yield = string_cat(yield,&size,&ptr,sub_arg[0],Ustrlen(sub_arg[0]));\n\n /* Reset the \"internal\" variables afterwards, because they are in\n dynamic store that will be reclaimed if the expansion succeeded. */\n\n prvscheck_address = NULL;\n prvscheck_keynum = NULL;\n }\n else\n {\n /* Does not look like a prvs encoded address, return the empty string.\n We need to make sure all subs are expanded first, so as to skip over\n the entire item. */\n\n switch(read_subs(sub_arg, 2, 1, &s, skipping, TRUE, US\"prvs\", &resetok))\n {\n case 1: goto EXPAND_FAILED_CURLY;\n case 2:\n case 3: goto EXPAND_FAILED;\n }\n }\n\n continue;\n }\n\n /* Handle \"readfile\" to insert an entire file */\n\n case EITEM_READFILE:\n {\n FILE *f;\n uschar *sub_arg[2];\n\n if ((expand_forbid & RDO_READFILE) != 0)\n {\n expand_string_message = US\"file insertions are not permitted\";\n goto EXPAND_FAILED;\n }\n\n switch(read_subs(sub_arg, 2, 1, &s, skipping, TRUE, US\"readfile\", &resetok))\n {\n case 1: goto EXPAND_FAILED_CURLY;\n case 2:\n case 3: goto EXPAND_FAILED;\n }\n\n /* If skipping, we don't actually do anything */\n\n if (skipping) continue;\n\n /* Open the file and read it */\n\n f = Ufopen(sub_arg[0], \"rb\");\n if (f == NULL)\n {\n expand_string_message = string_open_failed(errno, \"%s\", sub_arg[0]);\n goto EXPAND_FAILED;\n }\n\n yield = cat_file(f, yield, &size, &ptr, sub_arg[1]);\n (void)fclose(f);\n continue;\n }\n\n /* Handle \"readsocket\" to insert data from a Unix domain socket */\n\n case EITEM_READSOCK:\n {\n int fd;\n int timeout = 5;\n int save_ptr = ptr;\n FILE *f;\n struct sockaddr_un sockun; /* don't call this \"sun\" ! */\n uschar *arg;\n uschar *sub_arg[4];\n\n if ((expand_forbid & RDO_READSOCK) != 0)\n {\n expand_string_message = US\"socket insertions are not permitted\";\n goto EXPAND_FAILED;\n }\n\n /* Read up to 4 arguments, but don't do the end of item check afterwards,\n because there may be a string for expansion on failure. */\n\n switch(read_subs(sub_arg, 4, 2, &s, skipping, FALSE, US\"readsocket\", &resetok))\n {\n case 1: goto EXPAND_FAILED_CURLY;\n case 2: /* Won't occur: no end check */\n case 3: goto EXPAND_FAILED;\n }\n\n /* Sort out timeout, if given */\n\n if (sub_arg[2] != NULL)\n {\n timeout = readconf_readtime(sub_arg[2], 0, FALSE);\n if (timeout < 0)\n {\n expand_string_message = string_sprintf(\"bad time value %s\",\n sub_arg[2]);\n goto EXPAND_FAILED;\n }\n }\n else sub_arg[3] = NULL; /* No eol if no timeout */\n\n /* If skipping, we don't actually do anything. Otherwise, arrange to\n connect to either an IP or a Unix socket. */\n\n if (!skipping)\n {\n /* Handle an IP (internet) domain */\n\n if (Ustrncmp(sub_arg[0], \"inet:\", 5) == 0)\n {\n int port;\n uschar *server_name = sub_arg[0] + 5;\n uschar *port_name = Ustrrchr(server_name, ':');\n\n /* Sort out the port */\n\n if (port_name == NULL)\n {\n expand_string_message =\n string_sprintf(\"missing port for readsocket %s\", sub_arg[0]);\n goto EXPAND_FAILED;\n }\n *port_name++ = 0; /* Terminate server name */\n\n if (isdigit(*port_name))\n {\n uschar *end;\n port = Ustrtol(port_name, &end, 0);\n if (end != port_name + Ustrlen(port_name))\n {\n expand_string_message =\n string_sprintf(\"invalid port number %s\", port_name);\n goto EXPAND_FAILED;\n }\n }\n else\n {\n struct servent *service_info = getservbyname(CS port_name, \"tcp\");\n if (service_info == NULL)\n {\n expand_string_message = string_sprintf(\"unknown port \\\"%s\\\"\",\n port_name);\n goto EXPAND_FAILED;\n }\n port = ntohs(service_info->s_port);\n }\n\n\t if ((fd = ip_connectedsocket(SOCK_STREAM, server_name, port, port,\n\t\t timeout, NULL, &expand_string_message)) < 0)\n goto SOCK_FAIL;\n }\n\n /* Handle a Unix domain socket */\n\n else\n {\n int rc;\n if ((fd = socket(PF_UNIX, SOCK_STREAM, 0)) == -1)\n {\n expand_string_message = string_sprintf(\"failed to create socket: %s\",\n strerror(errno));\n goto SOCK_FAIL;\n }\n\n sockun.sun_family = AF_UNIX;\n sprintf(sockun.sun_path, \"%.*s\", (int)(sizeof(sockun.sun_path)-1),\n sub_arg[0]);\n\n sigalrm_seen = FALSE;\n alarm(timeout);\n rc = connect(fd, (struct sockaddr *)(&sockun), sizeof(sockun));\n alarm(0);\n if (sigalrm_seen)\n {\n expand_string_message = US \"socket connect timed out\";\n goto SOCK_FAIL;\n }\n if (rc < 0)\n {\n expand_string_message = string_sprintf(\"failed to connect to socket \"\n \"%s: %s\", sub_arg[0], strerror(errno));\n goto SOCK_FAIL;\n }\n }\n\n DEBUG(D_expand) debug_printf(\"connected to socket %s\\n\", sub_arg[0]);\n\n\t/* Allow sequencing of test actions */\n\tif (running_in_test_harness) millisleep(100);\n\n /* Write the request string, if not empty */\n\n if (sub_arg[1][0] != 0)\n {\n int len = Ustrlen(sub_arg[1]);\n DEBUG(D_expand) debug_printf(\"writing \\\"%s\\\" to socket\\n\",\n sub_arg[1]);\n if (write(fd, sub_arg[1], len) != len)\n {\n expand_string_message = string_sprintf(\"request write to socket \"\n \"failed: %s\", strerror(errno));\n goto SOCK_FAIL;\n }\n }\n\n /* Shut down the sending side of the socket. This helps some servers to\n recognise that it is their turn to do some work. Just in case some\n system doesn't have this function, make it conditional. */\n\n #ifdef SHUT_WR\n shutdown(fd, SHUT_WR);\n #endif\n\n\tif (running_in_test_harness) millisleep(100);\n\n /* Now we need to read from the socket, under a timeout. The function\n that reads a file can be used. */\n\n f = fdopen(fd, \"rb\");\n sigalrm_seen = FALSE;\n alarm(timeout);\n yield = cat_file(f, yield, &size, &ptr, sub_arg[3]);\n alarm(0);\n (void)fclose(f);\n\n /* After a timeout, we restore the pointer in the result, that is,\n make sure we add nothing from the socket. */\n\n if (sigalrm_seen)\n {\n ptr = save_ptr;\n expand_string_message = US \"socket read timed out\";\n goto SOCK_FAIL;\n }\n }\n\n /* The whole thing has worked (or we were skipping). If there is a\n failure string following, we need to skip it. */\n\n if (*s == '{')\n {\n if (expand_string_internal(s+1, TRUE, &s, TRUE, TRUE, &resetok) == NULL)\n goto EXPAND_FAILED;\n if (*s++ != '}') goto EXPAND_FAILED_CURLY;\n while (isspace(*s)) s++;\n }\n if (*s++ != '}') goto EXPAND_FAILED_CURLY;\n continue;\n\n /* Come here on failure to create socket, connect socket, write to the\n socket, or timeout on reading. If another substring follows, expand and\n use it. Otherwise, those conditions give expand errors. */\n\n SOCK_FAIL:\n if (*s != '{') goto EXPAND_FAILED;\n DEBUG(D_any) debug_printf(\"%s\\n\", expand_string_message);\n arg = expand_string_internal(s+1, TRUE, &s, FALSE, TRUE, &resetok);\n if (arg == NULL) goto EXPAND_FAILED;\n yield = string_cat(yield, &size, &ptr, arg, Ustrlen(arg));\n if (*s++ != '}') goto EXPAND_FAILED_CURLY;\n while (isspace(*s)) s++;\n if (*s++ != '}') goto EXPAND_FAILED_CURLY;\n continue;\n }\n\n /* Handle \"run\" to execute a program. */\n\n case EITEM_RUN:\n {\n FILE *f;\n uschar *arg;\n uschar **argv;\n pid_t pid;\n int fd_in, fd_out;\n int lsize = 0;\n int lptr = 0;\n\n if ((expand_forbid & RDO_RUN) != 0)\n {\n expand_string_message = US\"running a command is not permitted\";\n goto EXPAND_FAILED;\n }\n\n while (isspace(*s)) s++;\n if (*s != '{') goto EXPAND_FAILED_CURLY;\n arg = expand_string_internal(s+1, TRUE, &s, skipping, TRUE, &resetok);\n if (arg == NULL) goto EXPAND_FAILED;\n while (isspace(*s)) s++;\n if (*s++ != '}') goto EXPAND_FAILED_CURLY;\n\n if (skipping) /* Just pretend it worked when we're skipping */\n {\n runrc = 0;\n }\n else\n {\n if (!transport_set_up_command(&argv, /* anchor for arg list */\n arg, /* raw command */\n FALSE, /* don't expand the arguments */\n 0, /* not relevant when... */\n NULL, /* no transporting address */\n US\"${run} expansion\", /* for error messages */\n &expand_string_message)) /* where to put error message */\n {\n goto EXPAND_FAILED;\n }\n\n /* Create the child process, making it a group leader. */\n\n pid = child_open(argv, NULL, 0077, &fd_in, &fd_out, TRUE);\n\n if (pid < 0)\n {\n expand_string_message =\n string_sprintf(\"couldn't create child process: %s\", strerror(errno));\n goto EXPAND_FAILED;\n }\n\n /* Nothing is written to the standard input. */\n\n (void)close(fd_in);\n\n /* Read the pipe to get the command's output into $value (which is kept\n in lookup_value). Read during execution, so that if the output exceeds\n the OS pipe buffer limit, we don't block forever. */\n\n f = fdopen(fd_out, \"rb\");\n sigalrm_seen = FALSE;\n alarm(60);\n lookup_value = cat_file(f, lookup_value, &lsize, &lptr, NULL);\n alarm(0);\n (void)fclose(f);\n\n /* Wait for the process to finish, applying the timeout, and inspect its\n return code for serious disasters. Simple non-zero returns are passed on.\n */\n\n if (sigalrm_seen == TRUE || (runrc = child_close(pid, 30)) < 0)\n {\n if (sigalrm_seen == TRUE || runrc == -256)\n {\n expand_string_message = string_sprintf(\"command timed out\");\n killpg(pid, SIGKILL); /* Kill the whole process group */\n }\n\n else if (runrc == -257)\n expand_string_message = string_sprintf(\"wait() failed: %s\",\n strerror(errno));\n\n else\n expand_string_message = string_sprintf(\"command killed by signal %d\",\n -runrc);\n\n goto EXPAND_FAILED;\n }\n }\n\n /* Process the yes/no strings; $value may be useful in both cases */\n\n switch(process_yesno(\n skipping, /* were previously skipping */\n runrc == 0, /* success/failure indicator */\n lookup_value, /* value to reset for string2 */\n &s, /* input pointer */\n &yield, /* output pointer */\n &size, /* output size */\n &ptr, /* output current point */\n US\"run\", /* condition type */\n\t &resetok))\n {\n case 1: goto EXPAND_FAILED; /* when all is well, the */\n case 2: goto EXPAND_FAILED_CURLY; /* returned value is 0 */\n }\n\n continue;\n }\n\n /* Handle character translation for \"tr\" */\n\n case EITEM_TR:\n {\n int oldptr = ptr;\n int o2m;\n uschar *sub[3];\n\n switch(read_subs(sub, 3, 3, &s, skipping, TRUE, US\"tr\", &resetok))\n {\n case 1: goto EXPAND_FAILED_CURLY;\n case 2:\n case 3: goto EXPAND_FAILED;\n }\n\n yield = string_cat(yield, &size, &ptr, sub[0], Ustrlen(sub[0]));\n o2m = Ustrlen(sub[2]) - 1;\n\n if (o2m >= 0) for (; oldptr < ptr; oldptr++)\n {\n uschar *m = Ustrrchr(sub[1], yield[oldptr]);\n if (m != NULL)\n {\n int o = m - sub[1];\n yield[oldptr] = sub[2][(o < o2m)? o : o2m];\n }\n }\n\n continue;\n }\n\n /* Handle \"hash\", \"length\", \"nhash\", and \"substr\" when they are given with\n expanded arguments. */\n\n case EITEM_HASH:\n case EITEM_LENGTH:\n case EITEM_NHASH:\n case EITEM_SUBSTR:\n {\n int i;\n int len;\n uschar *ret;\n int val[2] = { 0, -1 };\n uschar *sub[3];\n\n /* \"length\" takes only 2 arguments whereas the others take 2 or 3.\n Ensure that sub[2] is set in the ${length } case. */\n\n sub[2] = NULL;\n switch(read_subs(sub, (item_type == EITEM_LENGTH)? 2:3, 2, &s, skipping,\n TRUE, name, &resetok))\n {\n case 1: goto EXPAND_FAILED_CURLY;\n case 2:\n case 3: goto EXPAND_FAILED;\n }\n\n /* Juggle the arguments if there are only two of them: always move the\n string to the last position and make ${length{n}{str}} equivalent to\n ${substr{0}{n}{str}}. See the defaults for val[] above. */\n\n if (sub[2] == NULL)\n {\n sub[2] = sub[1];\n sub[1] = NULL;\n if (item_type == EITEM_LENGTH)\n {\n sub[1] = sub[0];\n sub[0] = NULL;\n }\n }\n\n for (i = 0; i < 2; i++)\n {\n if (sub[i] == NULL) continue;\n val[i] = (int)Ustrtol(sub[i], &ret, 10);\n if (*ret != 0 || (i != 0 && val[i] < 0))\n {\n expand_string_message = string_sprintf(\"\\\"%s\\\" is not a%s number \"\n \"(in \\\"%s\\\" expansion)\", sub[i], (i != 0)? \" positive\" : \"\", name);\n goto EXPAND_FAILED;\n }\n }\n\n ret =\n (item_type == EITEM_HASH)?\n compute_hash(sub[2], val[0], val[1], &len) :\n (item_type == EITEM_NHASH)?\n compute_nhash(sub[2], val[0], val[1], &len) :\n extract_substr(sub[2], val[0], val[1], &len);\n\n if (ret == NULL) goto EXPAND_FAILED;\n yield = string_cat(yield, &size, &ptr, ret, len);\n continue;\n }\n\n /* Handle HMAC computation: ${hmac{}{}{}}\n This code originally contributed by Steve Haslam. It currently supports\n the use of MD5 and SHA-1 hashes.\n\n We need some workspace that is large enough to handle all the supported\n hash types. Use macros to set the sizes rather than be too elaborate. */\n\n #define MAX_HASHLEN 20\n #define MAX_HASHBLOCKLEN 64\n\n case EITEM_HMAC:\n {\n uschar *sub[3];\n md5 md5_base;\n sha1 sha1_base;\n void *use_base;\n int type, i;\n int hashlen; /* Number of octets for the hash algorithm's output */\n int hashblocklen; /* Number of octets the hash algorithm processes */\n uschar *keyptr, *p;\n unsigned int keylen;\n\n uschar keyhash[MAX_HASHLEN];\n uschar innerhash[MAX_HASHLEN];\n uschar finalhash[MAX_HASHLEN];\n uschar finalhash_hex[2*MAX_HASHLEN];\n uschar innerkey[MAX_HASHBLOCKLEN];\n uschar outerkey[MAX_HASHBLOCKLEN];\n\n switch (read_subs(sub, 3, 3, &s, skipping, TRUE, name, &resetok))\n {\n case 1: goto EXPAND_FAILED_CURLY;\n case 2:\n case 3: goto EXPAND_FAILED;\n }\n\n if (Ustrcmp(sub[0], \"md5\") == 0)\n {\n type = HMAC_MD5;\n use_base = &md5_base;\n hashlen = 16;\n hashblocklen = 64;\n }\n else if (Ustrcmp(sub[0], \"sha1\") == 0)\n {\n type = HMAC_SHA1;\n use_base = &sha1_base;\n hashlen = 20;\n hashblocklen = 64;\n }\n else\n {\n expand_string_message =\n string_sprintf(\"hmac algorithm \\\"%s\\\" is not recognised\", sub[0]);\n goto EXPAND_FAILED;\n }\n\n keyptr = sub[1];\n keylen = Ustrlen(keyptr);\n\n /* If the key is longer than the hash block length, then hash the key\n first */\n\n if (keylen > hashblocklen)\n {\n chash_start(type, use_base);\n chash_end(type, use_base, keyptr, keylen, keyhash);\n keyptr = keyhash;\n keylen = hashlen;\n }\n\n /* Now make the inner and outer key values */\n\n memset(innerkey, 0x36, hashblocklen);\n memset(outerkey, 0x5c, hashblocklen);\n\n for (i = 0; i < keylen; i++)\n {\n innerkey[i] ^= keyptr[i];\n outerkey[i] ^= keyptr[i];\n }\n\n /* Now do the hashes */\n\n chash_start(type, use_base);\n chash_mid(type, use_base, innerkey);\n chash_end(type, use_base, sub[2], Ustrlen(sub[2]), innerhash);\n\n chash_start(type, use_base);\n chash_mid(type, use_base, outerkey);\n chash_end(type, use_base, innerhash, hashlen, finalhash);\n\n /* Encode the final hash as a hex string */\n\n p = finalhash_hex;\n for (i = 0; i < hashlen; i++)\n {\n *p++ = hex_digits[(finalhash[i] & 0xf0) >> 4];\n *p++ = hex_digits[finalhash[i] & 0x0f];\n }\n\n DEBUG(D_any) debug_printf(\"HMAC[%s](%.*s,%.*s)=%.*s\\n\", sub[0],\n (int)keylen, keyptr, Ustrlen(sub[2]), sub[2], hashlen*2, finalhash_hex);\n\n yield = string_cat(yield, &size, &ptr, finalhash_hex, hashlen*2);\n }\n\n continue;\n\n /* Handle global substitution for \"sg\" - like Perl's s/xxx/yyy/g operator.\n We have to save the numerical variables and restore them afterwards. */\n\n case EITEM_SG:\n {\n const pcre *re;\n int moffset, moffsetextra, slen;\n int roffset;\n int emptyopt;\n const uschar *rerror;\n uschar *subject;\n uschar *sub[3];\n int save_expand_nmax =\n save_expand_strings(save_expand_nstring, save_expand_nlength);\n\n switch(read_subs(sub, 3, 3, &s, skipping, TRUE, US\"sg\", &resetok))\n {\n case 1: goto EXPAND_FAILED_CURLY;\n case 2:\n case 3: goto EXPAND_FAILED;\n }\n\n /* Compile the regular expression */\n\n re = pcre_compile(CS sub[1], PCRE_COPT, (const char **)&rerror, &roffset,\n NULL);\n\n if (re == NULL)\n {\n expand_string_message = string_sprintf(\"regular expression error in \"\n \"\\\"%s\\\": %s at offset %d\", sub[1], rerror, roffset);\n goto EXPAND_FAILED;\n }\n\n /* Now run a loop to do the substitutions as often as necessary. It ends\n when there are no more matches. Take care over matches of the null string;\n do the same thing as Perl does. */\n\n subject = sub[0];\n slen = Ustrlen(sub[0]);\n moffset = moffsetextra = 0;\n emptyopt = 0;\n\n for (;;)\n {\n int ovector[3*(EXPAND_MAXN+1)];\n int n = pcre_exec(re, NULL, CS subject, slen, moffset + moffsetextra,\n PCRE_EOPT | emptyopt, ovector, sizeof(ovector)/sizeof(int));\n int nn;\n uschar *insert;\n\n /* No match - if we previously set PCRE_NOTEMPTY after a null match, this\n is not necessarily the end. We want to repeat the match from one\n character further along, but leaving the basic offset the same (for\n copying below). We can't be at the end of the string - that was checked\n before setting PCRE_NOTEMPTY. If PCRE_NOTEMPTY is not set, we are\n finished; copy the remaining string and end the loop. */\n\n if (n < 0)\n {\n if (emptyopt != 0)\n {\n moffsetextra = 1;\n emptyopt = 0;\n continue;\n }\n yield = string_cat(yield, &size, &ptr, subject+moffset, slen-moffset);\n break;\n }\n\n /* Match - set up for expanding the replacement. */\n\n if (n == 0) n = EXPAND_MAXN + 1;\n expand_nmax = 0;\n for (nn = 0; nn < n*2; nn += 2)\n {\n expand_nstring[expand_nmax] = subject + ovector[nn];\n expand_nlength[expand_nmax++] = ovector[nn+1] - ovector[nn];\n }\n expand_nmax--;\n\n /* Copy the characters before the match, plus the expanded insertion. */\n\n yield = string_cat(yield, &size, &ptr, subject + moffset,\n ovector[0] - moffset);\n insert = expand_string(sub[2]);\n if (insert == NULL) goto EXPAND_FAILED;\n yield = string_cat(yield, &size, &ptr, insert, Ustrlen(insert));\n\n moffset = ovector[1];\n moffsetextra = 0;\n emptyopt = 0;\n\n /* If we have matched an empty string, first check to see if we are at\n the end of the subject. If so, the loop is over. Otherwise, mimic\n what Perl's /g options does. This turns out to be rather cunning. First\n we set PCRE_NOTEMPTY and PCRE_ANCHORED and try the match a non-empty\n string at the same point. If this fails (picked up above) we advance to\n the next character. */\n\n if (ovector[0] == ovector[1])\n {\n if (ovector[0] == slen) break;\n emptyopt = PCRE_NOTEMPTY | PCRE_ANCHORED;\n }\n }\n\n /* All done - restore numerical variables. */\n\n restore_expand_strings(save_expand_nmax, save_expand_nstring,\n save_expand_nlength);\n continue;\n }\n\n /* Handle keyed and numbered substring extraction. If the first argument\n consists entirely of digits, then a numerical extraction is assumed. */\n\n case EITEM_EXTRACT:\n {\n int i;\n int j = 2;\n int field_number = 1;\n BOOL field_number_set = FALSE;\n uschar *save_lookup_value = lookup_value;\n uschar *sub[3];\n int save_expand_nmax =\n save_expand_strings(save_expand_nstring, save_expand_nlength);\n\n /* Read the arguments */\n\n for (i = 0; i < j; i++)\n {\n while (isspace(*s)) s++;\n if (*s == '{') \t\t\t\t\t\t/*}*/\n {\n sub[i] = expand_string_internal(s+1, TRUE, &s, skipping, TRUE, &resetok);\n if (sub[i] == NULL) goto EXPAND_FAILED;\t\t/*{*/\n if (*s++ != '}') goto EXPAND_FAILED_CURLY;\n\n /* After removal of leading and trailing white space, the first\n argument must not be empty; if it consists entirely of digits\n (optionally preceded by a minus sign), this is a numerical\n extraction, and we expect 3 arguments. */\n\n if (i == 0)\n {\n int len;\n int x = 0;\n uschar *p = sub[0];\n\n while (isspace(*p)) p++;\n sub[0] = p;\n\n len = Ustrlen(p);\n while (len > 0 && isspace(p[len-1])) len--;\n p[len] = 0;\n\n if (*p == 0 && !skipping)\n {\n expand_string_message = US\"first argument of \\\"extract\\\" must \"\n \"not be empty\";\n goto EXPAND_FAILED;\n }\n\n if (*p == '-')\n {\n field_number = -1;\n p++;\n }\n while (*p != 0 && isdigit(*p)) x = x * 10 + *p++ - '0';\n if (*p == 0)\n {\n field_number *= x;\n j = 3; /* Need 3 args */\n field_number_set = TRUE;\n }\n }\n }\n else goto EXPAND_FAILED_CURLY;\n }\n\n /* Extract either the numbered or the keyed substring into $value. If\n skipping, just pretend the extraction failed. */\n\n lookup_value = skipping? NULL : field_number_set?\n expand_gettokened(field_number, sub[1], sub[2]) :\n expand_getkeyed(sub[0], sub[1]);\n\n /* If no string follows, $value gets substituted; otherwise there can\n be yes/no strings, as for lookup or if. */\n\n switch(process_yesno(\n skipping, /* were previously skipping */\n lookup_value != NULL, /* success/failure indicator */\n save_lookup_value, /* value to reset for string2 */\n &s, /* input pointer */\n &yield, /* output pointer */\n &size, /* output size */\n &ptr, /* output current point */\n US\"extract\", /* condition type */\n\t &resetok))\n {\n case 1: goto EXPAND_FAILED; /* when all is well, the */\n case 2: goto EXPAND_FAILED_CURLY; /* returned value is 0 */\n }\n\n /* All done - restore numerical variables. */\n\n restore_expand_strings(save_expand_nmax, save_expand_nstring,\n save_expand_nlength);\n\n continue;\n }\n\n /* return the Nth item from a list */\n\n case EITEM_LISTEXTRACT:\n {\n int i;\n int field_number = 1;\n uschar *save_lookup_value = lookup_value;\n uschar *sub[2];\n int save_expand_nmax =\n save_expand_strings(save_expand_nstring, save_expand_nlength);\n\n /* Read the field & list arguments */\n\n for (i = 0; i < 2; i++)\n {\n while (isspace(*s)) s++;\n if (*s != '{')\t\t\t\t\t/*}*/\n\t goto EXPAND_FAILED_CURLY;\n\n\tsub[i] = expand_string_internal(s+1, TRUE, &s, skipping, TRUE, &resetok);\n\tif (!sub[i]) goto EXPAND_FAILED;\t\t/*{*/\n\tif (*s++ != '}') goto EXPAND_FAILED_CURLY;\n\n\t/* After removal of leading and trailing white space, the first\n\targument must be numeric and nonempty. */\n\n\tif (i == 0)\n\t {\n\t int len;\n\t int x = 0;\n\t uschar *p = sub[0];\n\n\t while (isspace(*p)) p++;\n\t sub[0] = p;\n\n\t len = Ustrlen(p);\n\t while (len > 0 && isspace(p[len-1])) len--;\n\t p[len] = 0;\n\n\t if (!*p && !skipping)\n\t {\n\t expand_string_message = US\"first argument of \\\"listextract\\\" must \"\n\t \"not be empty\";\n\t goto EXPAND_FAILED;\n\t }\n\n\t if (*p == '-')\n\t {\n\t field_number = -1;\n\t p++;\n\t }\n\t while (*p && isdigit(*p)) x = x * 10 + *p++ - '0';\n\t if (*p)\n\t {\n\t expand_string_message = US\"first argument of \\\"listextract\\\" must \"\n\t \"be numeric\";\n\t goto EXPAND_FAILED;\n\t }\n\t field_number *= x;\n\t }\n }\n\n /* Extract the numbered element into $value. If\n skipping, just pretend the extraction failed. */\n\n lookup_value = skipping? NULL : expand_getlistele(field_number, sub[1]);\n\n /* If no string follows, $value gets substituted; otherwise there can\n be yes/no strings, as for lookup or if. */\n\n switch(process_yesno(\n skipping, /* were previously skipping */\n lookup_value != NULL, /* success/failure indicator */\n save_lookup_value, /* value to reset for string2 */\n &s, /* input pointer */\n &yield, /* output pointer */\n &size, /* output size */\n &ptr, /* output current point */\n US\"extract\", /* condition type */\n\t &resetok))\n {\n case 1: goto EXPAND_FAILED; /* when all is well, the */\n case 2: goto EXPAND_FAILED_CURLY; /* returned value is 0 */\n }\n\n /* All done - restore numerical variables. */\n\n restore_expand_strings(save_expand_nmax, save_expand_nstring,\n save_expand_nlength);\n\n continue;\n }\n\n#ifdef SUPPORT_TLS\n case EITEM_CERTEXTRACT:\n {\n uschar *save_lookup_value = lookup_value;\n uschar *sub[2];\n int save_expand_nmax =\n save_expand_strings(save_expand_nstring, save_expand_nlength);\n\n /* Read the field argument */\n while (isspace(*s)) s++;\n if (*s != '{')\t\t\t\t\t/*}*/\n\tgoto EXPAND_FAILED_CURLY;\n sub[0] = expand_string_internal(s+1, TRUE, &s, skipping, TRUE, &resetok);\n if (!sub[0]) goto EXPAND_FAILED;\t\t/*{*/\n if (*s++ != '}') goto EXPAND_FAILED_CURLY;\n /* strip spaces fore & aft */\n {\n int len;\n uschar *p = sub[0];\n\n while (isspace(*p)) p++;\n sub[0] = p;\n\n len = Ustrlen(p);\n while (len > 0 && isspace(p[len-1])) len--;\n p[len] = 0;\n }\n\n /* inspect the cert argument */\n while (isspace(*s)) s++;\n if (*s != '{')\t\t\t\t\t/*}*/\n\tgoto EXPAND_FAILED_CURLY;\n if (*++s != '$')\n {\n\texpand_string_message = US\"second argument of \\\"certextract\\\" must \"\n\t \"be a certificate variable\";\n\tgoto EXPAND_FAILED;\n\t}\n sub[1] = expand_string_internal(s+1, TRUE, &s, skipping, FALSE, &resetok);\n if (!sub[1]) goto EXPAND_FAILED;\t\t/*{*/\n if (*s++ != '}') goto EXPAND_FAILED_CURLY;\n\n if (skipping)\n\tlookup_value = NULL;\n else\n\t{\n\tlookup_value = expand_getcertele(sub[0], sub[1]);\n\tif (*expand_string_message) goto EXPAND_FAILED;\n\t}\n switch(process_yesno(\n skipping, /* were previously skipping */\n lookup_value != NULL, /* success/failure indicator */\n save_lookup_value, /* value to reset for string2 */\n &s, /* input pointer */\n &yield, /* output pointer */\n &size, /* output size */\n &ptr, /* output current point */\n US\"extract\", /* condition type */\n\t &resetok))\n {\n case 1: goto EXPAND_FAILED; /* when all is well, the */\n case 2: goto EXPAND_FAILED_CURLY; /* returned value is 0 */\n }\n\n restore_expand_strings(save_expand_nmax, save_expand_nstring,\n save_expand_nlength);\n continue;\n }\n#endif\t/*SUPPORT_TLS*/\n\n /* Handle list operations */\n\n case EITEM_FILTER:\n case EITEM_MAP:\n case EITEM_REDUCE:\n {\n int sep = 0;\n int save_ptr = ptr;\n uschar outsep[2] = { '\\0', '\\0' };\n uschar *list, *expr, *temp;\n uschar *save_iterate_item = iterate_item;\n uschar *save_lookup_value = lookup_value;\n\n while (isspace(*s)) s++;\n if (*s++ != '{') goto EXPAND_FAILED_CURLY;\n\n list = expand_string_internal(s, TRUE, &s, skipping, TRUE, &resetok);\n if (list == NULL) goto EXPAND_FAILED;\n if (*s++ != '}') goto EXPAND_FAILED_CURLY;\n\n if (item_type == EITEM_REDUCE)\n {\n while (isspace(*s)) s++;\n if (*s++ != '{') goto EXPAND_FAILED_CURLY;\n temp = expand_string_internal(s, TRUE, &s, skipping, TRUE, &resetok);\n if (temp == NULL) goto EXPAND_FAILED;\n lookup_value = temp;\n if (*s++ != '}') goto EXPAND_FAILED_CURLY;\n }\n\n while (isspace(*s)) s++;\n if (*s++ != '{') goto EXPAND_FAILED_CURLY;\n\n expr = s;\n\n /* For EITEM_FILTER, call eval_condition once, with result discarded (as\n if scanning a \"false\" part). This allows us to find the end of the\n condition, because if the list is empty, we won't actually evaluate the\n condition for real. For EITEM_MAP and EITEM_REDUCE, do the same, using\n the normal internal expansion function. */\n\n if (item_type == EITEM_FILTER)\n {\n temp = eval_condition(expr, &resetok, NULL);\n if (temp != NULL) s = temp;\n }\n else\n {\n temp = expand_string_internal(s, TRUE, &s, TRUE, TRUE, &resetok);\n }\n\n if (temp == NULL)\n {\n expand_string_message = string_sprintf(\"%s inside \\\"%s\\\" item\",\n expand_string_message, name);\n goto EXPAND_FAILED;\n }\n\n while (isspace(*s)) s++;\n if (*s++ != '}')\n {\t\t\t\t\t\t/*{*/\n expand_string_message = string_sprintf(\"missing } at end of condition \"\n \"or expression inside \\\"%s\\\"\", name);\n goto EXPAND_FAILED;\n }\n\n while (isspace(*s)) s++;\t\t\t\t/*{*/\n if (*s++ != '}')\n {\t\t\t\t\t\t/*{*/\n expand_string_message = string_sprintf(\"missing } at end of \\\"%s\\\"\",\n name);\n goto EXPAND_FAILED;\n }\n\n /* If we are skipping, we can now just move on to the next item. When\n processing for real, we perform the iteration. */\n\n if (skipping) continue;\n while ((iterate_item = string_nextinlist(&list, &sep, NULL, 0)) != NULL)\n {\n *outsep = (uschar)sep; /* Separator as a string */\n\n DEBUG(D_expand) debug_printf(\"%s: $item = \\\"%s\\\"\\n\", name, iterate_item);\n\n if (item_type == EITEM_FILTER)\n {\n BOOL condresult;\n if (eval_condition(expr, &resetok, &condresult) == NULL)\n {\n iterate_item = save_iterate_item;\n lookup_value = save_lookup_value;\n expand_string_message = string_sprintf(\"%s inside \\\"%s\\\" condition\",\n expand_string_message, name);\n goto EXPAND_FAILED;\n }\n DEBUG(D_expand) debug_printf(\"%s: condition is %s\\n\", name,\n condresult? \"true\":\"false\");\n if (condresult)\n temp = iterate_item; /* TRUE => include this item */\n else\n continue; /* FALSE => skip this item */\n }\n\n /* EITEM_MAP and EITEM_REDUCE */\n\n else\n {\n temp = expand_string_internal(expr, TRUE, NULL, skipping, TRUE, &resetok);\n if (temp == NULL)\n {\n iterate_item = save_iterate_item;\n expand_string_message = string_sprintf(\"%s inside \\\"%s\\\" item\",\n expand_string_message, name);\n goto EXPAND_FAILED;\n }\n if (item_type == EITEM_REDUCE)\n {\n lookup_value = temp; /* Update the value of $value */\n continue; /* and continue the iteration */\n }\n }\n\n /* We reach here for FILTER if the condition is true, always for MAP,\n and never for REDUCE. The value in \"temp\" is to be added to the output\n list that is being created, ensuring that any occurrences of the\n separator character are doubled. Unless we are dealing with the first\n item of the output list, add in a space if the new item begins with the\n separator character, or is an empty string. */\n\n if (ptr != save_ptr && (temp[0] == *outsep || temp[0] == 0))\n yield = string_cat(yield, &size, &ptr, US\" \", 1);\n\n /* Add the string in \"temp\" to the output list that we are building,\n This is done in chunks by searching for the separator character. */\n\n for (;;)\n {\n size_t seglen = Ustrcspn(temp, outsep);\n yield = string_cat(yield, &size, &ptr, temp, seglen + 1);\n\n /* If we got to the end of the string we output one character\n too many; backup and end the loop. Otherwise arrange to double the\n separator. */\n\n if (temp[seglen] == '\\0') { ptr--; break; }\n yield = string_cat(yield, &size, &ptr, outsep, 1);\n temp += seglen + 1;\n }\n\n /* Output a separator after the string: we will remove the redundant\n final one at the end. */\n\n yield = string_cat(yield, &size, &ptr, outsep, 1);\n } /* End of iteration over the list loop */\n\n /* REDUCE has generated no output above: output the final value of\n $value. */\n\n if (item_type == EITEM_REDUCE)\n {\n yield = string_cat(yield, &size, &ptr, lookup_value,\n Ustrlen(lookup_value));\n lookup_value = save_lookup_value; /* Restore $value */\n }\n\n /* FILTER and MAP generate lists: if they have generated anything, remove\n the redundant final separator. Even though an empty item at the end of a\n list does not count, this is tidier. */\n\n else if (ptr != save_ptr) ptr--;\n\n /* Restore preserved $item */\n\n iterate_item = save_iterate_item;\n continue;\n }\n\n\n /* If ${dlfunc } support is configured, handle calling dynamically-loaded\n functions, unless locked out at this time. Syntax is ${dlfunc{file}{func}}\n or ${dlfunc{file}{func}{arg}} or ${dlfunc{file}{func}{arg1}{arg2}} or up to\n a maximum of EXPAND_DLFUNC_MAX_ARGS arguments (defined below). */\n\n #define EXPAND_DLFUNC_MAX_ARGS 8\n\n case EITEM_DLFUNC:\n #ifndef EXPAND_DLFUNC\n expand_string_message = US\"\\\"${dlfunc\\\" encountered, but this facility \"\t/*}*/\n \"is not included in this binary\";\n goto EXPAND_FAILED;\n\n #else /* EXPAND_DLFUNC */\n {\n tree_node *t;\n exim_dlfunc_t *func;\n uschar *result;\n int status, argc;\n uschar *argv[EXPAND_DLFUNC_MAX_ARGS + 3];\n\n if ((expand_forbid & RDO_DLFUNC) != 0)\n {\n expand_string_message =\n US\"dynamically-loaded functions are not permitted\";\n goto EXPAND_FAILED;\n }\n\n switch(read_subs(argv, EXPAND_DLFUNC_MAX_ARGS + 2, 2, &s, skipping,\n TRUE, US\"dlfunc\", &resetok))\n {\n case 1: goto EXPAND_FAILED_CURLY;\n case 2:\n case 3: goto EXPAND_FAILED;\n }\n\n /* If skipping, we don't actually do anything */\n\n if (skipping) continue;\n\n /* Look up the dynamically loaded object handle in the tree. If it isn't\n found, dlopen() the file and put the handle in the tree for next time. */\n\n t = tree_search(dlobj_anchor, argv[0]);\n if (t == NULL)\n {\n void *handle = dlopen(CS argv[0], RTLD_LAZY);\n if (handle == NULL)\n {\n expand_string_message = string_sprintf(\"dlopen \\\"%s\\\" failed: %s\",\n argv[0], dlerror());\n log_write(0, LOG_MAIN|LOG_PANIC, \"%s\", expand_string_message);\n goto EXPAND_FAILED;\n }\n t = store_get_perm(sizeof(tree_node) + Ustrlen(argv[0]));\n Ustrcpy(t->name, argv[0]);\n t->data.ptr = handle;\n (void)tree_insertnode(&dlobj_anchor, t);\n }\n\n /* Having obtained the dynamically loaded object handle, look up the\n function pointer. */\n\n func = (exim_dlfunc_t *)dlsym(t->data.ptr, CS argv[1]);\n if (func == NULL)\n {\n expand_string_message = string_sprintf(\"dlsym \\\"%s\\\" in \\\"%s\\\" failed: \"\n \"%s\", argv[1], argv[0], dlerror());\n log_write(0, LOG_MAIN|LOG_PANIC, \"%s\", expand_string_message);\n goto EXPAND_FAILED;\n }\n\n /* Call the function and work out what to do with the result. If it\n returns OK, we have a replacement string; if it returns DEFER then\n expansion has failed in a non-forced manner; if it returns FAIL then\n failure was forced; if it returns ERROR or any other value there's a\n problem, so panic slightly. In any case, assume that the function has\n side-effects on the store that must be preserved. */\n\n resetok = FALSE;\n result = NULL;\n for (argc = 0; argv[argc] != NULL; argc++);\n status = func(&result, argc - 2, &argv[2]);\n if(status == OK)\n {\n if (result == NULL) result = US\"\";\n yield = string_cat(yield, &size, &ptr, result, Ustrlen(result));\n continue;\n }\n else\n {\n expand_string_message = result == NULL ? US\"(no message)\" : result;\n if(status == FAIL_FORCED) expand_string_forcedfail = TRUE;\n else if(status != FAIL)\n log_write(0, LOG_MAIN|LOG_PANIC, \"dlfunc{%s}{%s} failed (%d): %s\",\n argv[0], argv[1], status, expand_string_message);\n goto EXPAND_FAILED;\n }\n }\n #endif /* EXPAND_DLFUNC */\n }\t/* EITEM_* switch */\n\n /* Control reaches here if the name is not recognized as one of the more\n complicated expansion items. Check for the \"operator\" syntax (name terminated\n by a colon). Some of the operators have arguments, separated by _ from the\n name. */\n\n if (*s == ':')\n {\n int c;\n uschar *arg = NULL;\n uschar *sub;\n var_entry *vp = NULL;\n\n /* Owing to an historical mis-design, an underscore may be part of the\n operator name, or it may introduce arguments. We therefore first scan the\n table of names that contain underscores. If there is no match, we cut off\n the arguments and then scan the main table. */\n\n if ((c = chop_match(name, op_table_underscore,\n\tsizeof(op_table_underscore)/sizeof(uschar *))) < 0)\n {\n arg = Ustrchr(name, '_');\n if (arg != NULL) *arg = 0;\n c = chop_match(name, op_table_main,\n sizeof(op_table_main)/sizeof(uschar *));\n if (c >= 0) c += sizeof(op_table_underscore)/sizeof(uschar *);\n if (arg != NULL) *arg++ = '_'; /* Put back for error messages */\n }\n\n /* Deal specially with operators that might take a certificate variable\n as we do not want to do the usual expansion. For most, expand the string.*/\n switch(c)\n {\n#ifdef SUPPORT_TLS\n case EOP_MD5:\n case EOP_SHA1:\n case EOP_SHA256:\n\tif (s[1] == '$')\n\t {\n\t uschar * s1 = s;\n\t sub = expand_string_internal(s+2, TRUE, &s1, skipping,\n\t\t FALSE, &resetok);\n\t if (!sub) goto EXPAND_FAILED;\t\t/*{*/\n\t if (*s1 != '}') goto EXPAND_FAILED_CURLY;\n\t if ((vp = find_var_ent(sub)) && vp->type == vtype_cert)\n\t {\n\t s = s1+1;\n\t break;\n\t }\n\t vp = NULL;\n\t }\n /*FALLTHROUGH*/\n#endif\n default:\n\tsub = expand_string_internal(s+1, TRUE, &s, skipping, TRUE, &resetok);\n\tif (!sub) goto EXPAND_FAILED;\n\ts++;\n\tbreak;\n }\n\n /* If we are skipping, we don't need to perform the operation at all.\n This matters for operations like \"mask\", because the data may not be\n in the correct format when skipping. For example, the expression may test\n for the existence of $sender_host_address before trying to mask it. For\n other operations, doing them may not fail, but it is a waste of time. */\n\n if (skipping && c >= 0) continue;\n\n /* Otherwise, switch on the operator type */\n\n switch(c)\n {\n case EOP_BASE62:\n {\n uschar *t;\n unsigned long int n = Ustrtoul(sub, &t, 10);\n if (*t != 0)\n {\n expand_string_message = string_sprintf(\"argument for base62 \"\n \"operator is \\\"%s\\\", which is not a decimal number\", sub);\n goto EXPAND_FAILED;\n }\n t = string_base62(n);\n yield = string_cat(yield, &size, &ptr, t, Ustrlen(t));\n continue;\n }\n\n /* Note that for Darwin and Cygwin, BASE_62 actually has the value 36 */\n\n case EOP_BASE62D:\n {\n uschar buf[16];\n uschar *tt = sub;\n unsigned long int n = 0;\n while (*tt != 0)\n {\n uschar *t = Ustrchr(base62_chars, *tt++);\n if (t == NULL)\n {\n expand_string_message = string_sprintf(\"argument for base62d \"\n \"operator is \\\"%s\\\", which is not a base %d number\", sub,\n BASE_62);\n goto EXPAND_FAILED;\n }\n n = n * BASE_62 + (t - base62_chars);\n }\n (void)sprintf(CS buf, \"%ld\", n);\n yield = string_cat(yield, &size, &ptr, buf, Ustrlen(buf));\n continue;\n }\n\n case EOP_EXPAND:\n {\n uschar *expanded = expand_string_internal(sub, FALSE, NULL, skipping, TRUE, &resetok);\n if (expanded == NULL)\n {\n expand_string_message =\n string_sprintf(\"internal expansion of \\\"%s\\\" failed: %s\", sub,\n expand_string_message);\n goto EXPAND_FAILED;\n }\n yield = string_cat(yield, &size, &ptr, expanded, Ustrlen(expanded));\n continue;\n }\n\n case EOP_LC:\n {\n int count = 0;\n uschar *t = sub - 1;\n while (*(++t) != 0) { *t = tolower(*t); count++; }\n yield = string_cat(yield, &size, &ptr, sub, count);\n continue;\n }\n\n case EOP_UC:\n {\n int count = 0;\n uschar *t = sub - 1;\n while (*(++t) != 0) { *t = toupper(*t); count++; }\n yield = string_cat(yield, &size, &ptr, sub, count);\n continue;\n }\n\n case EOP_MD5:\n#ifdef SUPPORT_TLS\n\tif (vp && *(void **)vp->value)\n\t {\n\t uschar * cp = tls_cert_fprt_md5(*(void **)vp->value);\n\t yield = string_cat(yield, &size, &ptr, cp, Ustrlen(cp));\n\t }\n\telse\n#endif\n\t {\n\t md5 base;\n\t uschar digest[16];\n\t int j;\n\t char st[33];\n\t md5_start(&base);\n\t md5_end(&base, sub, Ustrlen(sub), digest);\n\t for(j = 0; j < 16; j++) sprintf(st+2*j, \"%02x\", digest[j]);\n\t yield = string_cat(yield, &size, &ptr, US st, (int)strlen(st));\n\t }\n continue;\n\n case EOP_SHA1:\n#ifdef SUPPORT_TLS\n\tif (vp && *(void **)vp->value)\n\t {\n\t uschar * cp = tls_cert_fprt_sha1(*(void **)vp->value);\n\t yield = string_cat(yield, &size, &ptr, cp, Ustrlen(cp));\n\t }\n\telse\n#endif\n\t {\n\t sha1 base;\n\t uschar digest[20];\n\t int j;\n\t char st[41];\n\t sha1_start(&base);\n\t sha1_end(&base, sub, Ustrlen(sub), digest);\n\t for(j = 0; j < 20; j++) sprintf(st+2*j, \"%02X\", digest[j]);\n\t yield = string_cat(yield, &size, &ptr, US st, (int)strlen(st));\n\t }\n continue;\n\n case EOP_SHA256:\n#ifdef SUPPORT_TLS\n\tif (vp && *(void **)vp->value)\n\t {\n\t uschar * cp = tls_cert_fprt_sha256(*(void **)vp->value);\n\t yield = string_cat(yield, &size, &ptr, cp, (int)Ustrlen(cp));\n\t }\n\telse\n#endif\n\t expand_string_message = US\"sha256 only supported for certificates\";\n continue;\n\n /* Convert hex encoding to base64 encoding */\n\n case EOP_HEX2B64:\n {\n int c = 0;\n int b = -1;\n uschar *in = sub;\n uschar *out = sub;\n uschar *enc;\n\n for (enc = sub; *enc != 0; enc++)\n {\n if (!isxdigit(*enc))\n {\n expand_string_message = string_sprintf(\"\\\"%s\\\" is not a hex \"\n \"string\", sub);\n goto EXPAND_FAILED;\n }\n c++;\n }\n\n if ((c & 1) != 0)\n {\n expand_string_message = string_sprintf(\"\\\"%s\\\" contains an odd \"\n \"number of characters\", sub);\n goto EXPAND_FAILED;\n }\n\n while ((c = *in++) != 0)\n {\n if (isdigit(c)) c -= '0';\n else c = toupper(c) - 'A' + 10;\n if (b == -1)\n {\n b = c << 4;\n }\n else\n {\n *out++ = b | c;\n b = -1;\n }\n }\n\n enc = auth_b64encode(sub, out - sub);\n yield = string_cat(yield, &size, &ptr, enc, Ustrlen(enc));\n continue;\n }\n\n /* Convert octets outside 0x21..0x7E to \\xXX form */\n\n case EOP_HEXQUOTE:\n\t{\n uschar *t = sub - 1;\n while (*(++t) != 0)\n {\n if (*t < 0x21 || 0x7E < *t)\n yield = string_cat(yield, &size, &ptr,\n\t string_sprintf(\"\\\\x%02x\", *t), 4);\n\t else\n\t yield = string_cat(yield, &size, &ptr, t, 1);\n }\n\tcontinue;\n\t}\n\n /* count the number of list elements */\n\n case EOP_LISTCOUNT:\n {\n\tint cnt = 0;\n\tint sep = 0;\n\tuschar * cp;\n\tuschar buffer[256];\n\n\twhile (string_nextinlist(&sub, &sep, buffer, sizeof(buffer)) != NULL) cnt++;\n\tcp = string_sprintf(\"%d\", cnt);\n yield = string_cat(yield, &size, &ptr, cp, Ustrlen(cp));\n continue;\n }\n\n /* expand a named list given the name */\n /* handles nested named lists; requotes as colon-sep list */\n\n case EOP_LISTNAMED:\n\t{\n\ttree_node *t = NULL;\n\tuschar * list;\n\tint sep = 0;\n\tuschar * item;\n\tuschar * suffix = US\"\";\n\tBOOL needsep = FALSE;\n\tuschar buffer[256];\n\n\tif (*sub == '+') sub++;\n\tif (arg == NULL)\t/* no-argument version */\n\t {\n\t if (!(t = tree_search(addresslist_anchor, sub)) &&\n\t !(t = tree_search(domainlist_anchor, sub)) &&\n\t !(t = tree_search(hostlist_anchor, sub)))\n\t t = tree_search(localpartlist_anchor, sub);\n\t }\n\telse switch(*arg)\t/* specific list-type version */\n\t {\n\t case 'a': t = tree_search(addresslist_anchor, sub); suffix = US\"_a\"; break;\n\t case 'd': t = tree_search(domainlist_anchor, sub); suffix = US\"_d\"; break;\n\t case 'h': t = tree_search(hostlist_anchor, sub); suffix = US\"_h\"; break;\n\t case 'l': t = tree_search(localpartlist_anchor, sub); suffix = US\"_l\"; break;\n\t default:\n expand_string_message = string_sprintf(\"bad suffix on \\\"list\\\" operator\");\n\t goto EXPAND_FAILED;\n\t }\n\n\tif(!t)\n\t {\n expand_string_message = string_sprintf(\"\\\"%s\\\" is not a %snamed list\",\n sub, !arg?\"\"\n\t : *arg=='a'?\"address \"\n\t : *arg=='d'?\"domain \"\n\t : *arg=='h'?\"host \"\n\t : *arg=='l'?\"localpart \"\n\t : 0);\n\t goto EXPAND_FAILED;\n\t }\n\n\tlist = ((namedlist_block *)(t->data.ptr))->string;\n\n\twhile ((item = string_nextinlist(&list, &sep, buffer, sizeof(buffer))) != NULL)\n\t {\n\t uschar * buf = US\" : \";\n\t if (needsep)\n\t yield = string_cat(yield, &size, &ptr, buf, 3);\n\t else\n\t needsep = TRUE;\n\n\t if (*item == '+')\t/* list item is itself a named list */\n\t {\n\t uschar * sub = string_sprintf(\"${listnamed%s:%s}\", suffix, item);\n\t item = expand_string_internal(sub, FALSE, NULL, FALSE, TRUE, &resetok);\n\t }\n\t else if (sep != ':')\t/* item from non-colon-sep list, re-quote for colon list-separator */\n\t {\n\t char * cp;\n\t char tok[3];\n\t tok[0] = sep; tok[1] = ':'; tok[2] = 0;\n\t while ((cp= strpbrk((const char *)item, tok)))\n\t {\n yield = string_cat(yield, &size, &ptr, item, cp-(char *)item);\n\t if (*cp++ == ':')\t/* colon in a non-colon-sep list item, needs doubling */\n\t {\n yield = string_cat(yield, &size, &ptr, US\"::\", 2);\n\t item = (uschar *)cp;\n\t\t}\n\t else\t\t/* sep in item; should already be doubled; emit once */\n\t {\n yield = string_cat(yield, &size, &ptr, (uschar *)tok, 1);\n\t\tif (*cp == sep) cp++;\n\t item = (uschar *)cp;\n\t\t}\n\t }\n\t }\n yield = string_cat(yield, &size, &ptr, item, Ustrlen(item));\n\t }\n continue;\n\t}\n\n /* mask applies a mask to an IP address; for example the result of\n ${mask:131.111.10.206/28} is 131.111.10.192/28. */\n\n case EOP_MASK:\n {\n int count;\n uschar *endptr;\n int binary[4];\n int mask, maskoffset;\n int type = string_is_ip_address(sub, &maskoffset);\n uschar buffer[64];\n\n if (type == 0)\n {\n expand_string_message = string_sprintf(\"\\\"%s\\\" is not an IP address\",\n sub);\n goto EXPAND_FAILED;\n }\n\n if (maskoffset == 0)\n {\n expand_string_message = string_sprintf(\"missing mask value in \\\"%s\\\"\",\n sub);\n goto EXPAND_FAILED;\n }\n\n mask = Ustrtol(sub + maskoffset + 1, &endptr, 10);\n\n if (*endptr != 0 || mask < 0 || mask > ((type == 4)? 32 : 128))\n {\n expand_string_message = string_sprintf(\"mask value too big in \\\"%s\\\"\",\n sub);\n goto EXPAND_FAILED;\n }\n\n /* Convert the address to binary integer(s) and apply the mask */\n\n sub[maskoffset] = 0;\n count = host_aton(sub, binary);\n host_mask(count, binary, mask);\n\n /* Convert to masked textual format and add to output. */\n\n yield = string_cat(yield, &size, &ptr, buffer,\n host_nmtoa(count, binary, mask, buffer, '.'));\n continue;\n }\n\n case EOP_ADDRESS:\n case EOP_LOCAL_PART:\n case EOP_DOMAIN:\n {\n uschar *error;\n int start, end, domain;\n uschar *t = parse_extract_address(sub, &error, &start, &end, &domain,\n FALSE);\n if (t != NULL)\n {\n if (c != EOP_DOMAIN)\n {\n if (c == EOP_LOCAL_PART && domain != 0) end = start + domain - 1;\n yield = string_cat(yield, &size, &ptr, sub+start, end-start);\n }\n else if (domain != 0)\n {\n domain += start;\n yield = string_cat(yield, &size, &ptr, sub+domain, end-domain);\n }\n }\n continue;\n }\n\n case EOP_ADDRESSES:\n {\n uschar outsep[2] = { ':', '\\0' };\n uschar *address, *error;\n int save_ptr = ptr;\n int start, end, domain; /* Not really used */\n\n while (isspace(*sub)) sub++;\n if (*sub == '>') { *outsep = *++sub; ++sub; }\n parse_allow_group = TRUE;\n\n for (;;)\n {\n uschar *p = parse_find_address_end(sub, FALSE);\n uschar saveend = *p;\n *p = '\\0';\n address = parse_extract_address(sub, &error, &start, &end, &domain,\n FALSE);\n *p = saveend;\n\n /* Add the address to the output list that we are building. This is\n done in chunks by searching for the separator character. At the\n start, unless we are dealing with the first address of the output\n list, add in a space if the new address begins with the separator\n character, or is an empty string. */\n\n if (address != NULL)\n {\n if (ptr != save_ptr && address[0] == *outsep)\n yield = string_cat(yield, &size, &ptr, US\" \", 1);\n\n for (;;)\n {\n size_t seglen = Ustrcspn(address, outsep);\n yield = string_cat(yield, &size, &ptr, address, seglen + 1);\n\n /* If we got to the end of the string we output one character\n too many. */\n\n if (address[seglen] == '\\0') { ptr--; break; }\n yield = string_cat(yield, &size, &ptr, outsep, 1);\n address += seglen + 1;\n }\n\n /* Output a separator after the string: we will remove the\n redundant final one at the end. */\n\n yield = string_cat(yield, &size, &ptr, outsep, 1);\n }\n\n if (saveend == '\\0') break;\n sub = p + 1;\n }\n\n /* If we have generated anything, remove the redundant final\n separator. */\n\n if (ptr != save_ptr) ptr--;\n parse_allow_group = FALSE;\n continue;\n }\n\n\n /* quote puts a string in quotes if it is empty or contains anything\n other than alphamerics, underscore, dot, or hyphen.\n\n quote_local_part puts a string in quotes if RFC 2821/2822 requires it to\n be quoted in order to be a valid local part.\n\n In both cases, newlines and carriage returns are converted into \\n and \\r\n respectively */\n\n case EOP_QUOTE:\n case EOP_QUOTE_LOCAL_PART:\n if (arg == NULL)\n {\n BOOL needs_quote = (*sub == 0); /* TRUE for empty string */\n uschar *t = sub - 1;\n\n if (c == EOP_QUOTE)\n {\n while (!needs_quote && *(++t) != 0)\n needs_quote = !isalnum(*t) && !strchr(\"_-.\", *t);\n }\n else /* EOP_QUOTE_LOCAL_PART */\n {\n while (!needs_quote && *(++t) != 0)\n needs_quote = !isalnum(*t) &&\n strchr(\"!#$%&'*+-/=?^_`{|}~\", *t) == NULL &&\n (*t != '.' || t == sub || t[1] == 0);\n }\n\n if (needs_quote)\n {\n yield = string_cat(yield, &size, &ptr, US\"\\\"\", 1);\n t = sub - 1;\n while (*(++t) != 0)\n {\n if (*t == '\\n')\n yield = string_cat(yield, &size, &ptr, US\"\\\\n\", 2);\n else if (*t == '\\r')\n yield = string_cat(yield, &size, &ptr, US\"\\\\r\", 2);\n else\n {\n if (*t == '\\\\' || *t == '\"')\n yield = string_cat(yield, &size, &ptr, US\"\\\\\", 1);\n yield = string_cat(yield, &size, &ptr, t, 1);\n }\n }\n yield = string_cat(yield, &size, &ptr, US\"\\\"\", 1);\n }\n else yield = string_cat(yield, &size, &ptr, sub, Ustrlen(sub));\n continue;\n }\n\n /* quote_lookuptype does lookup-specific quoting */\n\n else\n {\n int n;\n uschar *opt = Ustrchr(arg, '_');\n\n if (opt != NULL) *opt++ = 0;\n\n n = search_findtype(arg, Ustrlen(arg));\n if (n < 0)\n {\n expand_string_message = search_error_message;\n goto EXPAND_FAILED;\n }\n\n if (lookup_list[n]->quote != NULL)\n sub = (lookup_list[n]->quote)(sub, opt);\n else if (opt != NULL) sub = NULL;\n\n if (sub == NULL)\n {\n expand_string_message = string_sprintf(\n \"\\\"%s\\\" unrecognized after \\\"${quote_%s\\\"\",\n opt, arg);\n goto EXPAND_FAILED;\n }\n\n yield = string_cat(yield, &size, &ptr, sub, Ustrlen(sub));\n continue;\n }\n\n /* rx quote sticks in \\ before any non-alphameric character so that\n the insertion works in a regular expression. */\n\n case EOP_RXQUOTE:\n {\n uschar *t = sub - 1;\n while (*(++t) != 0)\n {\n if (!isalnum(*t))\n yield = string_cat(yield, &size, &ptr, US\"\\\\\", 1);\n yield = string_cat(yield, &size, &ptr, t, 1);\n }\n continue;\n }\n\n /* RFC 2047 encodes, assuming headers_charset (default ISO 8859-1) as\n prescribed by the RFC, if there are characters that need to be encoded */\n\n case EOP_RFC2047:\n {\n uschar buffer[2048];\n uschar *string = parse_quote_2047(sub, Ustrlen(sub), headers_charset,\n buffer, sizeof(buffer), FALSE);\n yield = string_cat(yield, &size, &ptr, string, Ustrlen(string));\n continue;\n }\n\n /* RFC 2047 decode */\n\n case EOP_RFC2047D:\n {\n int len;\n uschar *error;\n uschar *decoded = rfc2047_decode(sub, check_rfc2047_length,\n headers_charset, '?', &len, &error);\n if (error != NULL)\n {\n expand_string_message = error;\n goto EXPAND_FAILED;\n }\n yield = string_cat(yield, &size, &ptr, decoded, len);\n continue;\n }\n\n /* from_utf8 converts UTF-8 to 8859-1, turning non-existent chars into\n underscores */\n\n case EOP_FROM_UTF8:\n {\n while (*sub != 0)\n {\n int c;\n uschar buff[4];\n GETUTF8INC(c, sub);\n if (c > 255) c = '_';\n buff[0] = c;\n yield = string_cat(yield, &size, &ptr, buff, 1);\n }\n continue;\n }\n\n\t /* replace illegal UTF-8 sequences by replacement character */\n\t \n #define UTF8_REPLACEMENT_CHAR US\"?\"\n\n case EOP_UTF8CLEAN:\n {\n int seq_len, index = 0;\n int bytes_left = 0;\n uschar seq_buff[4];\t\t\t/* accumulate utf-8 here */\n \n while (*sub != 0)\n\t {\n\t int complete;\n\t long codepoint;\n\t uschar c;\n\n\t complete = 0;\n\t c = *sub++;\n\t if (bytes_left)\n\t {\n\t if ((c & 0xc0) != 0x80)\n\t {\n\t\t /* wrong continuation byte; invalidate all bytes */\n\t complete = 1; /* error */\n\t }\n\t else\n\t {\n\t codepoint = (codepoint << 6) | (c & 0x3f);\n\t seq_buff[index++] = c;\n\t if (--bytes_left == 0)\t\t/* codepoint complete */\n\t\t{\n\t\tif(codepoint > 0x10FFFF)\t/* is it too large? */\n\t\t complete = -1;\t/* error */\n\t\telse\n\t\t {\t\t/* finished; output utf-8 sequence */\n\t\t yield = string_cat(yield, &size, &ptr, seq_buff, seq_len);\n\t\t index = 0;\n\t\t }\n\t\t}\n\t }\n\t }\n\t else\t/* no bytes left: new sequence */\n\t {\n\t if((c & 0x80) == 0)\t/* 1-byte sequence, US-ASCII, keep it */\n\t {\n\t yield = string_cat(yield, &size, &ptr, &c, 1);\n\t continue;\n\t }\n\t if((c & 0xe0) == 0xc0)\t\t/* 2-byte sequence */\n\t {\n\t if(c == 0xc0 || c == 0xc1)\t/* 0xc0 and 0xc1 are illegal */\n\t\tcomplete = -1;\n\t else\n\t\t{\n\t\t bytes_left = 1;\n\t\t codepoint = c & 0x1f;\n\t\t}\n\t }\n\t else if((c & 0xf0) == 0xe0)\t\t/* 3-byte sequence */\n\t {\n\t bytes_left = 2;\n\t codepoint = c & 0x0f;\n\t }\n\t else if((c & 0xf8) == 0xf0)\t\t/* 4-byte sequence */\n\t {\n\t bytes_left = 3;\n\t codepoint = c & 0x07;\n\t }\n\t else\t/* invalid or too long (RFC3629 allows only 4 bytes) */\n\t complete = -1;\n\n\t seq_buff[index++] = c;\n\t seq_len = bytes_left + 1;\n\t }\t\t/* if(bytes_left) */\n\n\t if (complete != 0)\n\t {\n\t bytes_left = index = 0;\n\t yield = string_cat(yield, &size, &ptr, UTF8_REPLACEMENT_CHAR, 1);\n\t }\n\t if ((complete == 1) && ((c & 0x80) == 0))\n\t { /* ASCII character follows incomplete sequence */\n\t yield = string_cat(yield, &size, &ptr, &c, 1);\n\t }\n\t }\n continue;\n }\n\n /* escape turns all non-printing characters into escape sequences. */\n\n case EOP_ESCAPE:\n {\n uschar *t = string_printing(sub);\n yield = string_cat(yield, &size, &ptr, t, Ustrlen(t));\n continue;\n }\n\n /* Handle numeric expression evaluation */\n\n case EOP_EVAL:\n case EOP_EVAL10:\n {\n uschar *save_sub = sub;\n uschar *error = NULL;\n int_eximarith_t n = eval_expr(&sub, (c == EOP_EVAL10), &error, FALSE);\n if (error != NULL)\n {\n expand_string_message = string_sprintf(\"error in expression \"\n \"evaluation: %s (after processing \\\"%.*s\\\")\", error, sub-save_sub,\n save_sub);\n goto EXPAND_FAILED;\n }\n sprintf(CS var_buffer, PR_EXIM_ARITH, n);\n yield = string_cat(yield, &size, &ptr, var_buffer, Ustrlen(var_buffer));\n continue;\n }\n\n /* Handle time period formating */\n\n case EOP_TIME_EVAL:\n {\n int n = readconf_readtime(sub, 0, FALSE);\n if (n < 0)\n {\n expand_string_message = string_sprintf(\"string \\\"%s\\\" is not an \"\n \"Exim time interval in \\\"%s\\\" operator\", sub, name);\n goto EXPAND_FAILED;\n }\n sprintf(CS var_buffer, \"%d\", n);\n yield = string_cat(yield, &size, &ptr, var_buffer, Ustrlen(var_buffer));\n continue;\n }\n\n case EOP_TIME_INTERVAL:\n {\n int n;\n uschar *t = read_number(&n, sub);\n if (*t != 0) /* Not A Number*/\n {\n expand_string_message = string_sprintf(\"string \\\"%s\\\" is not a \"\n \"positive number in \\\"%s\\\" operator\", sub, name);\n goto EXPAND_FAILED;\n }\n t = readconf_printtime(n);\n yield = string_cat(yield, &size, &ptr, t, Ustrlen(t));\n continue;\n }\n\n /* Convert string to base64 encoding */\n\n case EOP_STR2B64:\n {\n uschar *encstr = auth_b64encode(sub, Ustrlen(sub));\n yield = string_cat(yield, &size, &ptr, encstr, Ustrlen(encstr));\n continue;\n }\n\n /* strlen returns the length of the string */\n\n case EOP_STRLEN:\n {\n uschar buff[24];\n (void)sprintf(CS buff, \"%d\", Ustrlen(sub));\n yield = string_cat(yield, &size, &ptr, buff, Ustrlen(buff));\n continue;\n }\n\n /* length_n or l_n takes just the first n characters or the whole string,\n whichever is the shorter;\n\n substr_m_n, and s_m_n take n characters from offset m; negative m take\n from the end; l_n is synonymous with s_0_n. If n is omitted in substr it\n takes the rest, either to the right or to the left.\n\n hash_n or h_n makes a hash of length n from the string, yielding n\n characters from the set a-z; hash_n_m makes a hash of length n, but\n uses m characters from the set a-zA-Z0-9.\n\n nhash_n returns a single number between 0 and n-1 (in text form), while\n nhash_n_m returns a div/mod hash as two numbers \"a/b\". The first lies\n between 0 and n-1 and the second between 0 and m-1. */\n\n case EOP_LENGTH:\n case EOP_L:\n case EOP_SUBSTR:\n case EOP_S:\n case EOP_HASH:\n case EOP_H:\n case EOP_NHASH:\n case EOP_NH:\n {\n int sign = 1;\n int value1 = 0;\n int value2 = -1;\n int *pn;\n int len;\n uschar *ret;\n\n if (arg == NULL)\n {\n expand_string_message = string_sprintf(\"missing values after %s\",\n name);\n goto EXPAND_FAILED;\n }\n\n /* \"length\" has only one argument, effectively being synonymous with\n substr_0_n. */\n\n if (c == EOP_LENGTH || c == EOP_L)\n {\n pn = &value2;\n value2 = 0;\n }\n\n /* The others have one or two arguments; for \"substr\" the first may be\n negative. The second being negative means \"not supplied\". */\n\n else\n {\n pn = &value1;\n if (name[0] == 's' && *arg == '-') { sign = -1; arg++; }\n }\n\n /* Read up to two numbers, separated by underscores */\n\n ret = arg;\n while (*arg != 0)\n {\n if (arg != ret && *arg == '_' && pn == &value1)\n {\n pn = &value2;\n value2 = 0;\n if (arg[1] != 0) arg++;\n }\n else if (!isdigit(*arg))\n {\n expand_string_message =\n string_sprintf(\"non-digit after underscore in \\\"%s\\\"\", name);\n goto EXPAND_FAILED;\n }\n else *pn = (*pn)*10 + *arg++ - '0';\n }\n value1 *= sign;\n\n /* Perform the required operation */\n\n ret =\n (c == EOP_HASH || c == EOP_H)?\n compute_hash(sub, value1, value2, &len) :\n (c == EOP_NHASH || c == EOP_NH)?\n compute_nhash(sub, value1, value2, &len) :\n extract_substr(sub, value1, value2, &len);\n\n if (ret == NULL) goto EXPAND_FAILED;\n yield = string_cat(yield, &size, &ptr, ret, len);\n continue;\n }\n\n /* Stat a path */\n\n case EOP_STAT:\n {\n uschar *s;\n uschar smode[12];\n uschar **modetable[3];\n int i;\n mode_t mode;\n struct stat st;\n\n if ((expand_forbid & RDO_EXISTS) != 0)\n {\n expand_string_message = US\"Use of the stat() expansion is not permitted\";\n goto EXPAND_FAILED;\n }\n\n if (stat(CS sub, &st) < 0)\n {\n expand_string_message = string_sprintf(\"stat(%s) failed: %s\",\n sub, strerror(errno));\n goto EXPAND_FAILED;\n }\n mode = st.st_mode;\n switch (mode & S_IFMT)\n {\n case S_IFIFO: smode[0] = 'p'; break;\n case S_IFCHR: smode[0] = 'c'; break;\n case S_IFDIR: smode[0] = 'd'; break;\n case S_IFBLK: smode[0] = 'b'; break;\n case S_IFREG: smode[0] = '-'; break;\n default: smode[0] = '?'; break;\n }\n\n modetable[0] = ((mode & 01000) == 0)? mtable_normal : mtable_sticky;\n modetable[1] = ((mode & 02000) == 0)? mtable_normal : mtable_setid;\n modetable[2] = ((mode & 04000) == 0)? mtable_normal : mtable_setid;\n\n for (i = 0; i < 3; i++)\n {\n memcpy(CS(smode + 7 - i*3), CS(modetable[i][mode & 7]), 3);\n mode >>= 3;\n }\n\n smode[10] = 0;\n s = string_sprintf(\"mode=%04lo smode=%s inode=%ld device=%ld links=%ld \"\n \"uid=%ld gid=%ld size=\" OFF_T_FMT \" atime=%ld mtime=%ld ctime=%ld\",\n (long)(st.st_mode & 077777), smode, (long)st.st_ino,\n (long)st.st_dev, (long)st.st_nlink, (long)st.st_uid,\n (long)st.st_gid, st.st_size, (long)st.st_atime,\n (long)st.st_mtime, (long)st.st_ctime);\n yield = string_cat(yield, &size, &ptr, s, Ustrlen(s));\n continue;\n }\n\n /* vaguely random number less than N */\n\n case EOP_RANDINT:\n {\n int_eximarith_t max;\n uschar *s;\n \n max = expand_string_integer(sub, TRUE);\n if (expand_string_message != NULL)\n goto EXPAND_FAILED;\n s = string_sprintf(\"%d\", vaguely_random_number((int)max));\n yield = string_cat(yield, &size, &ptr, s, Ustrlen(s));\n continue;\n }\n\n /* Reverse IP, including IPv6 to dotted-nibble */\n\n case EOP_REVERSE_IP:\n {\n int family, maskptr;\n uschar reversed[128];\n\n family = string_is_ip_address(sub, &maskptr);\n if (family == 0)\n {\n expand_string_message = string_sprintf(\n \"reverse_ip() not given an IP address [%s]\", sub);\n goto EXPAND_FAILED;\n }\n invert_address(reversed, sub);\n yield = string_cat(yield, &size, &ptr, reversed, Ustrlen(reversed));\n continue;\n }\n\n /* Unknown operator */\n\n default:\n expand_string_message =\n string_sprintf(\"unknown expansion operator \\\"%s\\\"\", name);\n goto EXPAND_FAILED;\n }\n }\n\n /* Handle a plain name. If this is the first thing in the expansion, release\n the pre-allocated buffer. If the result data is known to be in a new buffer,\n newsize will be set to the size of that buffer, and we can just point at that\n store instead of copying. Many expansion strings contain just one reference,\n so this is a useful optimization, especially for humungous headers\n ($message_headers). */\n\t\t\t\t\t\t/*{*/\n if (*s++ == '}')\n {\n int len;\n int newsize = 0;\n if (ptr == 0)\n {\n if (resetok) store_reset(yield);\n yield = NULL;\n size = 0;\n }\n value = find_variable(name, FALSE, skipping, &newsize);\n if (value == NULL)\n {\n expand_string_message =\n string_sprintf(\"unknown variable in \\\"${%s}\\\"\", name);\n check_variable_error_message(name);\n goto EXPAND_FAILED;\n }\n len = Ustrlen(value);\n if (yield == NULL && newsize != 0)\n {\n yield = value;\n size = newsize;\n ptr = len;\n }\n else yield = string_cat(yield, &size, &ptr, value, len);\n continue;\n }\n\n /* Else there's something wrong */\n\n expand_string_message =\n string_sprintf(\"\\\"${%s\\\" is not a known operator (or a } is missing \"\n \"in a variable reference)\", name);\n goto EXPAND_FAILED;\n }\n\n/* If we hit the end of the string when ket_ends is set, there is a missing\nterminating brace. */\n\nif (ket_ends && *s == 0)\n {\n expand_string_message = malformed_header?\n US\"missing } at end of string - could be header name not terminated by colon\"\n :\n US\"missing } at end of string\";\n goto EXPAND_FAILED;\n }\n\n/* Expansion succeeded; yield may still be NULL here if nothing was actually\nadded to the string. If so, set up an empty string. Add a terminating zero. If\nleft != NULL, return a pointer to the terminator. */\n\nif (yield == NULL) yield = store_get(1);\nyield[ptr] = 0;\nif (left != NULL) *left = s;\n\n/* Any stacking store that was used above the final string is no longer needed.\nIn many cases the final string will be the first one that was got and so there\nwill be optimal store usage. */\n\nif (resetok) store_reset(yield + ptr + 1);\nelse if (resetok_p) *resetok_p = FALSE;\n\nDEBUG(D_expand)\n {\n debug_printf(\"expanding: %.*s\\n result: %s\\n\", (int)(s - string), string,\n yield);\n if (skipping) debug_printf(\"skipping: result is not used\\n\");\n }\nreturn yield;\n\n/* This is the failure exit: easiest to program with a goto. We still need\nto update the pointer to the terminator, for cases of nested calls with \"fail\".\n*/\n\nEXPAND_FAILED_CURLY:\nexpand_string_message = malformed_header?\n US\"missing or misplaced { or } - could be header name not terminated by colon\"\n :\n US\"missing or misplaced { or }\";\n\n/* At one point, Exim reset the store to yield (if yield was not NULL), but\nthat is a bad idea, because expand_string_message is in dynamic store. */\n\nEXPAND_FAILED:\nif (left != NULL) *left = s;\nDEBUG(D_expand)\n {\n debug_printf(\"failed to expand: %s\\n\", string);\n debug_printf(\" error message: %s\\n\", expand_string_message);\n if (expand_string_forcedfail) debug_printf(\"failure was forced\\n\");\n }\nif (resetok_p) *resetok_p = resetok;\nreturn NULL;\n}\n", + "line": " max = expand_string_integer(sub, TRUE);\n", + "label": 1, + "cwe": "CWE-189", + "cve": "CVE-2014-2972", + "length": 25026 + }, + { + "index": 51529, + "code": "int tcp_conn_request(struct request_sock_ops *rsk_ops,\n\t\t const struct tcp_request_sock_ops *af_ops,\n\t\t struct sock *sk, struct sk_buff *skb)\n{\n\tstruct tcp_fastopen_cookie foc = { .len = -1 };\n\t__u32 isn = TCP_SKB_CB(skb)->tcp_tw_isn;\n\tstruct tcp_options_received tmp_opt;\n\tstruct tcp_sock *tp = tcp_sk(sk);\n\tstruct net *net = sock_net(sk);\n\tstruct sock *fastopen_sk = NULL;\n\tstruct dst_entry *dst = NULL;\n\tstruct request_sock *req;\n\tbool want_cookie = false;\n\tstruct flowi fl;\n\n\t/* TW buckets are converted to open requests without\n\t * limitations, they conserve resources and peer is\n\t * evidently real one.\n\t */\n\tif ((net->ipv4.sysctl_tcp_syncookies == 2 ||\n\t inet_csk_reqsk_queue_is_full(sk)) && !isn) {\n\t\twant_cookie = tcp_syn_flood_action(sk, skb, rsk_ops->slab_name);\n\t\tif (!want_cookie)\n\t\t\tgoto drop;\n\t}\n\n\n\t/* Accept backlog is full. If we have already queued enough\n\t * of warm entries in syn queue, drop request. It is better than\n\t * clogging syn queue with openreqs with exponentially increasing\n\t * timeout.\n\t */\n\tif (sk_acceptq_is_full(sk) && inet_csk_reqsk_queue_young(sk) > 1) {\n\t\tNET_INC_STATS(sock_net(sk), LINUX_MIB_LISTENOVERFLOWS);\n\t\tgoto drop;\n\t}\n\n\treq = inet_reqsk_alloc(rsk_ops, sk, !want_cookie);\n\tif (!req)\n\t\tgoto drop;\n\n\ttcp_rsk(req)->af_specific = af_ops;\n\n\ttcp_clear_options(&tmp_opt);\n\ttmp_opt.mss_clamp = af_ops->mss_clamp;\n\ttmp_opt.user_mss = tp->rx_opt.user_mss;\n\ttcp_parse_options(skb, &tmp_opt, 0, want_cookie ? NULL : &foc);\n\n\tif (want_cookie && !tmp_opt.saw_tstamp)\n\t\ttcp_clear_options(&tmp_opt);\n\n\ttmp_opt.tstamp_ok = tmp_opt.saw_tstamp;\n\ttcp_openreq_init(req, &tmp_opt, skb, sk);\n\n\t/* Note: tcp_v6_init_req() might override ir_iif for link locals */\n\tinet_rsk(req)->ir_iif = inet_request_bound_dev_if(sk, skb);\n\n\taf_ops->init_req(req, sk, skb);\n\n\tif (security_inet_conn_request(sk, skb, req))\n\t\tgoto drop_and_free;\n\n\tif (!want_cookie && !isn) {\n\t\t/* VJ's idea. We save last timestamp seen\n\t\t * from the destination in peer table, when entering\n\t\t * state TIME-WAIT, and check against it before\n\t\t * accepting new connection request.\n\t\t *\n\t\t * If \"isn\" is not zero, this request hit alive\n\t\t * timewait bucket, so that all the necessary checks\n\t\t * are made in the function processing timewait state.\n\t\t */\n\t\tif (tcp_death_row.sysctl_tw_recycle) {\n\t\t\tbool strict;\n\n\t\t\tdst = af_ops->route_req(sk, &fl, req, &strict);\n\n\t\t\tif (dst && strict &&\n\t\t\t !tcp_peer_is_proven(req, dst, true,\n\t\t\t\t\t\ttmp_opt.saw_tstamp)) {\n\t\t\t\tNET_INC_STATS(sock_net(sk), LINUX_MIB_PAWSPASSIVEREJECTED);\n\t\t\t\tgoto drop_and_release;\n\t\t\t}\n\t\t}\n\t\t/* Kill the following clause, if you dislike this way. */\n\t\telse if (!net->ipv4.sysctl_tcp_syncookies &&\n\t\t\t (sysctl_max_syn_backlog - inet_csk_reqsk_queue_len(sk) <\n\t\t\t (sysctl_max_syn_backlog >> 2)) &&\n\t\t\t !tcp_peer_is_proven(req, dst, false,\n\t\t\t\t\t tmp_opt.saw_tstamp)) {\n\t\t\t/* Without syncookies last quarter of\n\t\t\t * backlog is filled with destinations,\n\t\t\t * proven to be alive.\n\t\t\t * It means that we continue to communicate\n\t\t\t * to destinations, already remembered\n\t\t\t * to the moment of synflood.\n\t\t\t */\n\t\t\tpr_drop_req(req, ntohs(tcp_hdr(skb)->source),\n\t\t\t\t rsk_ops->family);\n\t\t\tgoto drop_and_release;\n\t\t}\n\n\t\tisn = af_ops->init_seq(skb);\n\t}\n\tif (!dst) {\n\t\tdst = af_ops->route_req(sk, &fl, req, NULL);\n\t\tif (!dst)\n\t\t\tgoto drop_and_free;\n\t}\n\n\ttcp_ecn_create_request(req, skb, sk, dst);\n\n\tif (want_cookie) {\n\t\tisn = cookie_init_sequence(af_ops, sk, skb, &req->mss);\n\t\treq->cookie_ts = tmp_opt.tstamp_ok;\n\t\tif (!tmp_opt.tstamp_ok)\n\t\t\tinet_rsk(req)->ecn_ok = 0;\n\t}\n\n\ttcp_rsk(req)->snt_isn = isn;\n\ttcp_rsk(req)->txhash = net_tx_rndhash();\n\ttcp_openreq_init_rwin(req, sk, dst);\n\tif (!want_cookie) {\n\t\ttcp_reqsk_record_syn(sk, req, skb);\n\t\tfastopen_sk = tcp_try_fastopen(sk, skb, req, &foc, dst);\n\t}\n\tif (fastopen_sk) {\n\t\taf_ops->send_synack(fastopen_sk, dst, &fl, req,\n\t\t\t\t &foc, TCP_SYNACK_FASTOPEN);\n\t\t/* Add the child socket directly into the accept queue */\n\t\tinet_csk_reqsk_queue_add(sk, req, fastopen_sk);\n\t\tsk->sk_data_ready(sk);\n\t\tbh_unlock_sock(fastopen_sk);\n\t\tsock_put(fastopen_sk);\n\t} else {\n\t\ttcp_rsk(req)->tfo_listener = false;\n\t\tif (!want_cookie)\n\t\t\tinet_csk_reqsk_queue_hash_add(sk, req, TCP_TIMEOUT_INIT);\n\t\taf_ops->send_synack(sk, dst, &fl, req, &foc,\n\t\t\t\t !want_cookie ? TCP_SYNACK_NORMAL :\n\t\t\t\t\t\t TCP_SYNACK_COOKIE);\n\t\tif (want_cookie) {\n\t\t\treqsk_free(req);\n\t\t\treturn 0;\n\t\t}\n\t}\n\treqsk_put(req);\n\treturn 0;\n\ndrop_and_release:\n\tdst_release(dst);\ndrop_and_free:\n\treqsk_free(req);\ndrop:\n\ttcp_listendrop(sk);\n\treturn 0;\n}\n", + "line": null, + "label": 0, + "cwe": "CWE-200", + "cve": "CVE-2016-5696", + "length": 1351 + }, + { + "index": 63368, + "code": "static void JPEGSetImageQuality(struct jpeg_decompress_struct *jpeg_info,\n Image *image)\n{\n image->quality=UndefinedCompressionQuality;\n#if defined(D_PROGRESSIVE_SUPPORTED)\n if (image->compression == LosslessJPEGCompression)\n {\n image->quality=100;\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \"Quality: 100 (lossless)\");\n }\n else\n#endif\n {\n ssize_t\n j,\n qvalue,\n sum;\n\n register ssize_t\n i;\n\n /*\n Determine the JPEG compression quality from the quantization tables.\n */\n sum=0;\n for (i=0; i < NUM_QUANT_TBLS; i++)\n {\n if (jpeg_info->quant_tbl_ptrs[i] != NULL)\n for (j=0; j < DCTSIZE2; j++)\n sum+=jpeg_info->quant_tbl_ptrs[i]->quantval[j];\n }\n if ((jpeg_info->quant_tbl_ptrs[0] != NULL) &&\n (jpeg_info->quant_tbl_ptrs[1] != NULL))\n {\n ssize_t\n hash[101] =\n {\n 1020, 1015, 932, 848, 780, 735, 702, 679, 660, 645,\n 632, 623, 613, 607, 600, 594, 589, 585, 581, 571,\n 555, 542, 529, 514, 494, 474, 457, 439, 424, 410,\n 397, 386, 373, 364, 351, 341, 334, 324, 317, 309,\n 299, 294, 287, 279, 274, 267, 262, 257, 251, 247,\n 243, 237, 232, 227, 222, 217, 213, 207, 202, 198,\n 192, 188, 183, 177, 173, 168, 163, 157, 153, 148,\n 143, 139, 132, 128, 125, 119, 115, 108, 104, 99,\n 94, 90, 84, 79, 74, 70, 64, 59, 55, 49,\n 45, 40, 34, 30, 25, 20, 15, 11, 6, 4,\n 0\n },\n sums[101] =\n {\n 32640, 32635, 32266, 31495, 30665, 29804, 29146, 28599, 28104,\n 27670, 27225, 26725, 26210, 25716, 25240, 24789, 24373, 23946,\n 23572, 22846, 21801, 20842, 19949, 19121, 18386, 17651, 16998,\n 16349, 15800, 15247, 14783, 14321, 13859, 13535, 13081, 12702,\n 12423, 12056, 11779, 11513, 11135, 10955, 10676, 10392, 10208,\n 9928, 9747, 9564, 9369, 9193, 9017, 8822, 8639, 8458,\n 8270, 8084, 7896, 7710, 7527, 7347, 7156, 6977, 6788,\n 6607, 6422, 6236, 6054, 5867, 5684, 5495, 5305, 5128,\n 4945, 4751, 4638, 4442, 4248, 4065, 3888, 3698, 3509,\n 3326, 3139, 2957, 2775, 2586, 2405, 2216, 2037, 1846,\n 1666, 1483, 1297, 1109, 927, 735, 554, 375, 201,\n 128, 0\n };\n\n qvalue=(ssize_t) (jpeg_info->quant_tbl_ptrs[0]->quantval[2]+\n jpeg_info->quant_tbl_ptrs[0]->quantval[53]+\n jpeg_info->quant_tbl_ptrs[1]->quantval[0]+\n jpeg_info->quant_tbl_ptrs[1]->quantval[DCTSIZE2-1]);\n for (i=0; i < 100; i++)\n {\n if ((qvalue < hash[i]) && (sum < sums[i]))\n continue;\n if (((qvalue <= hash[i]) && (sum <= sums[i])) || (i >= 50))\n image->quality=(size_t) i+1;\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \"Quality: %.20g (%s)\",(double) i+1,(qvalue <= hash[i]) &&\n (sum <= sums[i]) ? \"exact\" : \"approximate\");\n break;\n }\n }\n else\n if (jpeg_info->quant_tbl_ptrs[0] != NULL)\n {\n ssize_t\n hash[101] =\n {\n 510, 505, 422, 380, 355, 338, 326, 318, 311, 305,\n 300, 297, 293, 291, 288, 286, 284, 283, 281, 280,\n 279, 278, 277, 273, 262, 251, 243, 233, 225, 218,\n 211, 205, 198, 193, 186, 181, 177, 172, 168, 164,\n 158, 156, 152, 148, 145, 142, 139, 136, 133, 131,\n 129, 126, 123, 120, 118, 115, 113, 110, 107, 105,\n 102, 100, 97, 94, 92, 89, 87, 83, 81, 79,\n 76, 74, 70, 68, 66, 63, 61, 57, 55, 52,\n 50, 48, 44, 42, 39, 37, 34, 31, 29, 26,\n 24, 21, 18, 16, 13, 11, 8, 6, 3, 2,\n 0\n },\n sums[101] =\n {\n 16320, 16315, 15946, 15277, 14655, 14073, 13623, 13230, 12859,\n 12560, 12240, 11861, 11456, 11081, 10714, 10360, 10027, 9679,\n 9368, 9056, 8680, 8331, 7995, 7668, 7376, 7084, 6823,\n 6562, 6345, 6125, 5939, 5756, 5571, 5421, 5240, 5086,\n 4976, 4829, 4719, 4616, 4463, 4393, 4280, 4166, 4092,\n 3980, 3909, 3835, 3755, 3688, 3621, 3541, 3467, 3396,\n 3323, 3247, 3170, 3096, 3021, 2952, 2874, 2804, 2727,\n 2657, 2583, 2509, 2437, 2362, 2290, 2211, 2136, 2068,\n 1996, 1915, 1858, 1773, 1692, 1620, 1552, 1477, 1398,\n 1326, 1251, 1179, 1109, 1031, 961, 884, 814, 736,\n 667, 592, 518, 441, 369, 292, 221, 151, 86,\n 64, 0\n };\n\n qvalue=(ssize_t) (jpeg_info->quant_tbl_ptrs[0]->quantval[2]+\n jpeg_info->quant_tbl_ptrs[0]->quantval[53]);\n for (i=0; i < 100; i++)\n {\n if ((qvalue < hash[i]) && (sum < sums[i]))\n continue;\n if (((qvalue <= hash[i]) && (sum <= sums[i])) || (i >= 50))\n image->quality=(size_t) i+1;\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \"Quality: %.20g (%s)\",(double) i+1,(qvalue <= hash[i]) &&\n (sum <= sums[i]) ? \"exact\" : \"approximate\");\n break;\n }\n }\n }\n}\n", + "line": null, + "label": 0, + "cwe": "CWE-20", + "cve": "CVE-2017-11450", + "length": 2449 + }, + { + "index": 35948, + "code": "xfs_da3_path_shift(\n\tstruct xfs_da_state\t*state,\n\tstruct xfs_da_state_path *path,\n\tint\t\t\tforward,\n\tint\t\t\trelease,\n\tint\t\t\t*result)\n{\n\tstruct xfs_da_state_blk\t*blk;\n\tstruct xfs_da_blkinfo\t*info;\n\tstruct xfs_da_intnode\t*node;\n\tstruct xfs_da_args\t*args;\n\tstruct xfs_da_node_entry *btree;\n\tstruct xfs_da3_icnode_hdr nodehdr;\n\txfs_dablk_t\t\tblkno = 0;\n\tint\t\t\tlevel;\n\tint\t\t\terror;\n\tstruct xfs_inode\t*dp = state->args->dp;\n\n\ttrace_xfs_da_path_shift(state->args);\n\n\t/*\n\t * Roll up the Btree looking for the first block where our\n\t * current index is not at the edge of the block. Note that\n\t * we skip the bottom layer because we want the sibling block.\n\t */\n\targs = state->args;\n\tASSERT(args != NULL);\n\tASSERT(path != NULL);\n\tASSERT((path->active > 0) && (path->active < XFS_DA_NODE_MAXDEPTH));\n\tlevel = (path->active-1) - 1;\t/* skip bottom layer in path */\n\tfor (blk = &path->blk[level]; level >= 0; blk--, level--) {\n\t\tnode = blk->bp->b_addr;\n\t\tdp->d_ops->node_hdr_from_disk(&nodehdr, node);\n\t\tbtree = dp->d_ops->node_tree_p(node);\n\n\t\tif (forward && (blk->index < nodehdr.count - 1)) {\n\t\t\tblk->index++;\n\t\t\tblkno = be32_to_cpu(btree[blk->index].before);\n\t\t\tbreak;\n\t\t} else if (!forward && (blk->index > 0)) {\n\t\t\tblk->index--;\n\t\t\tblkno = be32_to_cpu(btree[blk->index].before);\n\t\t\tbreak;\n\t\t}\n\t}\n\tif (level < 0) {\n\t\t*result = XFS_ERROR(ENOENT);\t/* we're out of our tree */\n\t\tASSERT(args->op_flags & XFS_DA_OP_OKNOENT);\n\t\treturn(0);\n\t}\n\n\t/*\n\t * Roll down the edge of the subtree until we reach the\n\t * same depth we were at originally.\n\t */\n\tfor (blk++, level++; level < path->active; blk++, level++) {\n\t\t/*\n\t\t * Release the old block.\n\t\t * (if it's dirty, trans won't actually let go)\n\t\t */\n\t\tif (release)\n\t\t\txfs_trans_brelse(args->trans, blk->bp);\n\n\t\t/*\n\t\t * Read the next child block.\n\t\t */\n\t\tblk->blkno = blkno;\n\t\terror = xfs_da3_node_read(args->trans, dp, blkno, -1,\n\t\t\t\t\t&blk->bp, args->whichfork);\n\t\tif (error)\n\t\t\treturn(error);\n\t\tinfo = blk->bp->b_addr;\n\t\tASSERT(info->magic == cpu_to_be16(XFS_DA_NODE_MAGIC) ||\n\t\t info->magic == cpu_to_be16(XFS_DA3_NODE_MAGIC) ||\n\t\t info->magic == cpu_to_be16(XFS_DIR2_LEAFN_MAGIC) ||\n\t\t info->magic == cpu_to_be16(XFS_DIR3_LEAFN_MAGIC) ||\n\t\t info->magic == cpu_to_be16(XFS_ATTR_LEAF_MAGIC) ||\n\t\t info->magic == cpu_to_be16(XFS_ATTR3_LEAF_MAGIC));\n\n\n\t\t/*\n\t\t * Note: we flatten the magic number to a single type so we\n\t\t * don't have to compare against crc/non-crc types elsewhere.\n\t\t */\n\t\tswitch (be16_to_cpu(info->magic)) {\n\t\tcase XFS_DA_NODE_MAGIC:\n\t\tcase XFS_DA3_NODE_MAGIC:\n\t\t\tblk->magic = XFS_DA_NODE_MAGIC;\n\t\t\tnode = (xfs_da_intnode_t *)info;\n\t\t\tdp->d_ops->node_hdr_from_disk(&nodehdr, node);\n\t\t\tbtree = dp->d_ops->node_tree_p(node);\n\t\t\tblk->hashval = be32_to_cpu(btree[nodehdr.count - 1].hashval);\n\t\t\tif (forward)\n\t\t\t\tblk->index = 0;\n\t\t\telse\n\t\t\t\tblk->index = nodehdr.count - 1;\n\t\t\tblkno = be32_to_cpu(btree[blk->index].before);\n\t\t\tbreak;\n\t\tcase XFS_ATTR_LEAF_MAGIC:\n\t\tcase XFS_ATTR3_LEAF_MAGIC:\n\t\t\tblk->magic = XFS_ATTR_LEAF_MAGIC;\n\t\t\tASSERT(level == path->active-1);\n\t\t\tblk->index = 0;\n\t\t\tblk->hashval = xfs_attr_leaf_lasthash(blk->bp, NULL);\n\t\t\tbreak;\n\t\tcase XFS_DIR2_LEAFN_MAGIC:\n\t\tcase XFS_DIR3_LEAFN_MAGIC:\n\t\t\tblk->magic = XFS_DIR2_LEAFN_MAGIC;\n\t\t\tASSERT(level == path->active-1);\n\t\t\tblk->index = 0;\n\t\t\tblk->hashval = xfs_dir2_leafn_lasthash(args->dp,\n\t\t\t\t\t\t\t blk->bp, NULL);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tASSERT(0);\n\t\t\tbreak;\n\t\t}\n\t}\n\t*result = 0;\n\treturn 0;\n}\n", + "line": null, + "label": 0, + "cwe": "CWE-399", + "cve": "CVE-2014-7283", + "length": 1117 + }, + { + "index": 122401, + "code": "void HTMLSelectElement::listBoxDefaultEventHandler(Event* event)\n{\n const Vector& listItems = this->listItems();\n bool dragSelection = false;\n if (event->type() == EventTypeNames::mousedown && event->isMouseEvent() && toMouseEvent(event)->button() == LeftButton) {\n focus();\n if (!renderer())\n return;\n\n MouseEvent* mouseEvent = toMouseEvent(event);\n IntPoint localOffset = roundedIntPoint(renderer()->absoluteToLocal(mouseEvent->absoluteLocation(), UseTransforms));\n int listIndex = toRenderListBox(renderer())->listIndexAtOffset(toIntSize(localOffset));\n if (listIndex >= 0) {\n if (!isDisabledFormControl()) {\n#if OS(MACOSX)\n updateSelectedState(listIndex, mouseEvent->metaKey(), mouseEvent->shiftKey());\n#else\n updateSelectedState(listIndex, mouseEvent->ctrlKey(), mouseEvent->shiftKey());\n#endif\n }\n if (Frame* frame = document().frame())\n frame->eventHandler().setMouseDownMayStartAutoscroll();\n\n event->setDefaultHandled();\n }\n } else if (event->type() == EventTypeNames::mousemove && event->isMouseEvent() && !toRenderBox(renderer())->canBeScrolledAndHasScrollableArea()) {\n MouseEvent* mouseEvent = toMouseEvent(event);\n if (mouseEvent->button() != LeftButton || !mouseEvent->buttonDown())\n return;\n\n IntPoint localOffset = roundedIntPoint(renderer()->absoluteToLocal(mouseEvent->absoluteLocation(), UseTransforms));\n int listIndex = toRenderListBox(renderer())->listIndexAtOffset(toIntSize(localOffset));\n if (listIndex >= 0) {\n if (!isDisabledFormControl()) {\n if (m_multiple) {\n if (m_activeSelectionAnchorIndex < 0)\n return;\n\n setActiveSelectionEndIndex(listIndex);\n updateListBoxSelection(false);\n } else {\n setActiveSelectionAnchorIndex(listIndex);\n setActiveSelectionEndIndex(listIndex);\n updateListBoxSelection(true);\n }\n }\n dragSelection = true;\n }\n } else if (event->type() == EventTypeNames::mouseup && event->isMouseEvent() && toMouseEvent(event)->button() == LeftButton && renderer() && !toRenderBox(renderer())->autoscrollInProgress()) {\n if (m_lastOnChangeSelection.isEmpty())\n return;\n if (!dragSelection) {\n listBoxOnChange();\n }\n } else if (event->type() == EventTypeNames::keydown) {\n if (!event->isKeyboardEvent())\n return;\n const String& keyIdentifier = toKeyboardEvent(event)->keyIdentifier();\n\n bool handled = false;\n int endIndex = 0;\n if (m_activeSelectionEndIndex < 0) {\n if (keyIdentifier == \"Down\" || keyIdentifier == \"PageDown\") {\n int startIndex = lastSelectedListIndex();\n handled = true;\n if (keyIdentifier == \"Down\")\n endIndex = nextSelectableListIndex(startIndex);\n else\n endIndex = nextSelectableListIndexPageAway(startIndex, SkipForwards);\n } else if (keyIdentifier == \"Up\" || keyIdentifier == \"PageUp\") {\n int startIndex = optionToListIndex(selectedIndex());\n handled = true;\n if (keyIdentifier == \"Up\")\n endIndex = previousSelectableListIndex(startIndex);\n else\n endIndex = nextSelectableListIndexPageAway(startIndex, SkipBackwards);\n }\n } else {\n if (keyIdentifier == \"Down\") {\n endIndex = nextSelectableListIndex(m_activeSelectionEndIndex);\n handled = true;\n } else if (keyIdentifier == \"Up\") {\n endIndex = previousSelectableListIndex(m_activeSelectionEndIndex);\n handled = true;\n } else if (keyIdentifier == \"PageDown\") {\n endIndex = nextSelectableListIndexPageAway(m_activeSelectionEndIndex, SkipForwards);\n handled = true;\n } else if (keyIdentifier == \"PageUp\") {\n endIndex = nextSelectableListIndexPageAway(m_activeSelectionEndIndex, SkipBackwards);\n handled = true;\n }\n }\n if (keyIdentifier == \"Home\") {\n endIndex = firstSelectableListIndex();\n handled = true;\n } else if (keyIdentifier == \"End\") {\n endIndex = lastSelectableListIndex();\n handled = true;\n }\n\n if (isSpatialNavigationEnabled(document().frame()))\n if (keyIdentifier == \"Left\" || keyIdentifier == \"Right\" || ((keyIdentifier == \"Down\" || keyIdentifier == \"Up\") && endIndex == m_activeSelectionEndIndex))\n return;\n\n if (endIndex >= 0 && handled) {\n saveLastSelection();\n\n ASSERT_UNUSED(listItems, !listItems.size() || static_cast(endIndex) < listItems.size());\n setActiveSelectionEndIndex(endIndex);\n\n bool selectNewItem = !m_multiple || toKeyboardEvent(event)->shiftKey() || !isSpatialNavigationEnabled(document().frame());\n if (selectNewItem)\n m_activeSelectionState = true;\n bool deselectOthers = !m_multiple || (!toKeyboardEvent(event)->shiftKey() && selectNewItem);\n if (m_activeSelectionAnchorIndex < 0 || deselectOthers) {\n if (deselectOthers)\n deselectItemsWithoutValidation();\n setActiveSelectionAnchorIndex(m_activeSelectionEndIndex);\n }\n\n toRenderListBox(renderer())->scrollToRevealElementAtListIndex(endIndex);\n if (selectNewItem) {\n updateListBoxSelection(deselectOthers);\n listBoxOnChange();\n } else\n scrollToSelection();\n\n event->setDefaultHandled();\n }\n } else if (event->type() == EventTypeNames::keypress) {\n if (!event->isKeyboardEvent())\n return;\n int keyCode = toKeyboardEvent(event)->keyCode();\n\n if (keyCode == '\\r') {\n if (form())\n form()->submitImplicitly(event, false);\n event->setDefaultHandled();\n } else if (m_multiple && keyCode == ' ' && isSpatialNavigationEnabled(document().frame())) {\n m_activeSelectionState = !m_activeSelectionState;\n updateSelectedState(listToOptionIndex(m_activeSelectionEndIndex), true /*multi*/, false /*shift*/);\n listBoxOnChange();\n event->setDefaultHandled();\n }\n }\n}\n", + "line": null, + "label": 0, + "cwe": "CWE-119", + "cve": "CVE-2013-0882", + "length": 1313 + }, + { + "index": 176132, + "code": "VOID ixheaacd_radix4bfly(const WORD16 *w, WORD32 *x, WORD32 index1,\n WORD32 index) {\n int i;\n WORD32 l1, l2, h2, fft_jmp;\n WORD32 xt0_0, yt0_0, xt1_0, yt1_0, xt2_0, yt2_0;\n WORD32 xh0_0, xh1_0, xh20_0, xh21_0, xl0_0, xl1_0, xl20_0, xl21_0;\n WORD32 x_0, x_1, x_l1_0, x_l1_1, x_l2_0, x_l2_1;\n WORD32 x_h2_0, x_h2_1;\n WORD16 si10, si20, si30, co10, co20, co30;\n\n WORD32 mul_1, mul_2, mul_3, mul_4, mul_5, mul_6;\n WORD32 mul_7, mul_8, mul_9, mul_10, mul_11, mul_12;\n WORD32 *x_l1;\n WORD32 *x_l2;\n WORD32 *x_h2;\n const WORD16 *w_ptr = w;\n WORD32 i1;\n\n h2 = index << 1;\n l1 = index << 2;\n l2 = (index << 2) + (index << 1);\n\n x_l1 = &(x[l1]);\n x_l2 = &(x[l2]);\n x_h2 = &(x[h2]);\n\n fft_jmp = 6 * (index);\n\n for (i1 = 0; i1 < index1; i1++) {\n for (i = 0; i < index; i++) {\n si10 = (*w_ptr++);\n co10 = (*w_ptr++);\n si20 = (*w_ptr++);\n co20 = (*w_ptr++);\n si30 = (*w_ptr++);\n co30 = (*w_ptr++);\n\n x_0 = x[0];\n x_h2_0 = x[h2];\n x_l1_0 = x[l1];\n x_l2_0 = x[l2];\n\n xh0_0 = x_0 + x_l1_0;\n xl0_0 = x_0 - x_l1_0;\n\n xh20_0 = x_h2_0 + x_l2_0;\n xl20_0 = x_h2_0 - x_l2_0;\n\n x[0] = xh0_0 + xh20_0;\n xt0_0 = xh0_0 - xh20_0;\n\n x_1 = x[1];\n x_h2_1 = x[h2 + 1];\n x_l1_1 = x[l1 + 1];\n x_l2_1 = x[l2 + 1];\n\n xh1_0 = x_1 + x_l1_1;\n xl1_0 = x_1 - x_l1_1;\n\n xh21_0 = x_h2_1 + x_l2_1;\n xl21_0 = x_h2_1 - x_l2_1;\n\n x[1] = xh1_0 + xh21_0;\n yt0_0 = xh1_0 - xh21_0;\n\n xt1_0 = xl0_0 + xl21_0;\n xt2_0 = xl0_0 - xl21_0;\n\n yt2_0 = xl1_0 + xl20_0;\n yt1_0 = xl1_0 - xl20_0;\n\n mul_11 = ixheaacd_mult32x16in32(xt2_0, co30);\n mul_3 = ixheaacd_mult32x16in32(yt2_0, si30);\n x[l2] = (mul_3 + mul_11) << RADIXSHIFT;\n\n mul_5 = ixheaacd_mult32x16in32(xt2_0, si30);\n mul_9 = ixheaacd_mult32x16in32(yt2_0, co30);\n x[l2 + 1] = (mul_9 - mul_5) << RADIXSHIFT;\n\n mul_12 = ixheaacd_mult32x16in32(xt0_0, co20);\n mul_2 = ixheaacd_mult32x16in32(yt0_0, si20);\n x[l1] = (mul_2 + mul_12) << RADIXSHIFT;\n\n mul_6 = ixheaacd_mult32x16in32(xt0_0, si20);\n mul_8 = ixheaacd_mult32x16in32(yt0_0, co20);\n x[l1 + 1] = (mul_8 - mul_6) << RADIXSHIFT;\n\n mul_4 = ixheaacd_mult32x16in32(xt1_0, co10);\n mul_1 = ixheaacd_mult32x16in32(yt1_0, si10);\n x[h2] = (mul_1 + mul_4) << RADIXSHIFT;\n\n mul_10 = ixheaacd_mult32x16in32(xt1_0, si10);\n mul_7 = ixheaacd_mult32x16in32(yt1_0, co10);\n x[h2 + 1] = (mul_7 - mul_10) << RADIXSHIFT;\n\n x += 2;\n }\n x += fft_jmp;\n w_ptr = w_ptr - fft_jmp;\n }\n}\n", + "line": null, + "label": 0, + "cwe": "CWE-787", + "cve": "CVE-2018-9496", + "length": 1253 + }, + { + "index": 100054, + "code": "std::wstring FormatUrl(const GURL& url,\n const std::wstring& languages,\n bool omit_username_password,\n UnescapeRule::Type unescape_rules,\n url_parse::Parsed* new_parsed,\n size_t* prefix_end,\n size_t* offset_for_adjustment) {\n url_parse::Parsed parsed_temp;\n if (!new_parsed)\n new_parsed = &parsed_temp;\n size_t offset_temp = std::wstring::npos;\n if (!offset_for_adjustment)\n offset_for_adjustment = &offset_temp;\n\n std::wstring url_string;\n\n if (url.is_empty()) {\n if (prefix_end)\n *prefix_end = 0;\n *offset_for_adjustment = std::wstring::npos;\n return url_string;\n }\n\n const char* const kViewSource = \"view-source\";\n const char* const kViewSourceTwice = \"view-source:view-source:\";\n if (url.SchemeIs(kViewSource) &&\n !StartsWithASCII(url.possibly_invalid_spec(), kViewSourceTwice, false)) {\n return FormatViewSourceUrl(url, languages, omit_username_password,\n unescape_rules, new_parsed, prefix_end, offset_for_adjustment);\n }\n\n const std::string& spec = url.possibly_invalid_spec();\n const url_parse::Parsed& parsed = url.parsed_for_possibly_invalid_spec();\n if (*offset_for_adjustment >= spec.length())\n *offset_for_adjustment = std::wstring::npos;\n\n std::copy(spec.begin(),\n spec.begin() + parsed.CountCharactersBefore(url_parse::Parsed::USERNAME,\n true),\n std::back_inserter(url_string));\n new_parsed->scheme = parsed.scheme;\n\n if (omit_username_password) {\n new_parsed->username.reset();\n new_parsed->password.reset();\n if ((*offset_for_adjustment != std::wstring::npos) &&\n (parsed.username.is_nonempty() || parsed.password.is_nonempty())) {\n if (parsed.username.is_nonempty() && parsed.password.is_nonempty()) {\n if (*offset_for_adjustment >\n static_cast(parsed.password.end())) {\n *offset_for_adjustment -=\n (parsed.username.len + parsed.password.len + 2);\n } else if (*offset_for_adjustment >\n static_cast(parsed.username.begin)) {\n *offset_for_adjustment = std::wstring::npos;\n }\n } else {\n const url_parse::Component* nonempty_component =\n parsed.username.is_nonempty() ? &parsed.username : &parsed.password;\n if (*offset_for_adjustment >\n static_cast(nonempty_component->end())) {\n *offset_for_adjustment -= (nonempty_component->len + 1);\n } else if (*offset_for_adjustment >\n static_cast(nonempty_component->begin)) {\n *offset_for_adjustment = std::wstring::npos;\n }\n }\n }\n } else {\n AppendFormattedComponent(spec, parsed.username, unescape_rules, &url_string,\n &new_parsed->username, offset_for_adjustment);\n if (parsed.password.is_valid()) {\n url_string.push_back(':');\n }\n AppendFormattedComponent(spec, parsed.password, unescape_rules, &url_string,\n &new_parsed->password, offset_for_adjustment);\n if (parsed.username.is_valid() || parsed.password.is_valid()) {\n url_string.push_back('@');\n }\n }\n if (prefix_end)\n *prefix_end = static_cast(url_string.length());\n\n AppendFormattedHost(url, languages, &url_string, new_parsed,\n offset_for_adjustment);\n\n if (parsed.port.is_nonempty()) {\n url_string.push_back(':');\n new_parsed->port.begin = url_string.length();\n std::copy(spec.begin() + parsed.port.begin,\n spec.begin() + parsed.port.end(), std::back_inserter(url_string));\n new_parsed->port.len = url_string.length() - new_parsed->port.begin;\n } else {\n new_parsed->port.reset();\n }\n\n AppendFormattedComponent(spec, parsed.path, unescape_rules, &url_string,\n &new_parsed->path, offset_for_adjustment);\n if (parsed.query.is_valid())\n url_string.push_back('?');\n AppendFormattedComponent(spec, parsed.query, unescape_rules, &url_string,\n &new_parsed->query, offset_for_adjustment);\n\n if (parsed.ref.is_valid()) {\n url_string.push_back('#');\n new_parsed->ref.begin = url_string.length();\n size_t offset_past_current_output =\n ((*offset_for_adjustment == std::wstring::npos) ||\n (*offset_for_adjustment < url_string.length())) ?\n std::wstring::npos : (*offset_for_adjustment - url_string.length());\n size_t* offset_into_ref =\n (offset_past_current_output >= static_cast(parsed.ref.len)) ?\n NULL : &offset_past_current_output;\n if (parsed.ref.len > 0) {\n url_string.append(UTF8ToWideAndAdjustOffset(spec.substr(parsed.ref.begin,\n parsed.ref.len),\n offset_into_ref));\n }\n new_parsed->ref.len = url_string.length() - new_parsed->ref.begin;\n if (offset_into_ref) {\n *offset_for_adjustment = (*offset_into_ref == std::wstring::npos) ?\n std::wstring::npos : (new_parsed->ref.begin + *offset_into_ref);\n } else if (offset_past_current_output != std::wstring::npos) {\n *offset_for_adjustment = std::wstring::npos;\n }\n }\n\n return url_string;\n}\n", + "line": null, + "label": 0, + "cwe": null, + "cve": null, + "length": 1180 + }, + { + "index": 174686, + "code": "WORD32 ih264d_ref_idx_reordering(dec_struct_t *ps_dec, UWORD8 uc_lx)\n{\n dpb_manager_t *ps_dpb_mgr = ps_dec->ps_dpb_mgr;\n UWORD16 u4_cur_pic_num = ps_dec->ps_cur_slice->u2_frame_num;\n /*< Maximum Picture Number Minus 1 */\n UWORD16 ui_max_frame_num =\n ps_dec->ps_cur_sps->u2_u4_max_pic_num_minus1 + 1;\n\n WORD32 i;\n UWORD32 ui_remapIdc, ui_nextUev;\n WORD16 u2_pred_frame_num = u4_cur_pic_num;\n WORD32 i_temp;\n UWORD16 u2_def_mod_flag = 0; /* Flag to keep track of which indices have been remapped */\n UWORD8 modCount = 0;\n UWORD32 *pu4_bitstrm_buf = ps_dec->ps_bitstrm->pu4_buffer;\n UWORD32 *pu4_bitstrm_ofst = &ps_dec->ps_bitstrm->u4_ofst;\n dec_slice_params_t *ps_cur_slice = ps_dec->ps_cur_slice;\n UWORD8 u1_field_pic_flag = ps_cur_slice->u1_field_pic_flag;\n\n if(u1_field_pic_flag)\n {\n u4_cur_pic_num = u4_cur_pic_num * 2 + 1;\n ui_max_frame_num = ui_max_frame_num * 2;\n }\n\n u2_pred_frame_num = u4_cur_pic_num;\n\n ui_remapIdc = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf);\n\n while(ui_remapIdc != 3)\n {\n ui_nextUev = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf);\n if(ui_remapIdc != 2)\n {\n ui_nextUev = ui_nextUev + 1;\n if(ui_remapIdc == 0)\n {\n i_temp = u2_pred_frame_num - ui_nextUev;\n if(i_temp < 0)\n i_temp += ui_max_frame_num;\n }\n else\n {\n i_temp = u2_pred_frame_num + ui_nextUev;\n if(i_temp >= ui_max_frame_num)\n i_temp -= ui_max_frame_num;\n }\n /* Find the dpb with the matching picNum (picNum==frameNum for framePic) */\n\n if(i_temp > u4_cur_pic_num)\n i_temp = i_temp - ui_max_frame_num;\n\n for(i = 0; i < (ps_cur_slice->u1_initial_list_size[uc_lx]); i++)\n {\n if(ps_dpb_mgr->ps_init_dpb[uc_lx][i]->i4_pic_num == i_temp)\n break;\n }\n if(i == (ps_cur_slice->u1_initial_list_size[uc_lx]))\n {\n UWORD32 i4_error_code;\n i4_error_code = ERROR_DBP_MANAGER_T;\n return i4_error_code;\n }\n\n u2_def_mod_flag |= (1 << i);\n ps_dpb_mgr->ps_mod_dpb[uc_lx][modCount++] =\n ps_dpb_mgr->ps_init_dpb[uc_lx][i];\n u2_pred_frame_num = i_temp; //update predictor to be the picNum just obtained\n }\n else //2\n {\n UWORD8 u1_lt_idx = (UWORD8)ui_nextUev;\n\n for(i = 0; i < (ps_cur_slice->u1_initial_list_size[uc_lx]); i++)\n {\n if(!ps_dpb_mgr->ps_init_dpb[uc_lx][i]->u1_is_short)\n {\n if(ps_dpb_mgr->ps_init_dpb[uc_lx][i]->u1_long_term_pic_num\n == u1_lt_idx)\n break;\n }\n }\n if(i == (ps_cur_slice->u1_initial_list_size[uc_lx]))\n {\n UWORD32 i4_error_code;\n i4_error_code = ERROR_DBP_MANAGER_T;\n return i4_error_code;\n }\n\n u2_def_mod_flag |= (1 << i);\n ps_dpb_mgr->ps_mod_dpb[uc_lx][modCount++] =\n ps_dpb_mgr->ps_init_dpb[uc_lx][i];\n }\n\n ui_remapIdc = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf);\n /* Get the remapping_idc - 0/1/2/3 */\n }\n\n for(i = 0; i < (ps_cur_slice->u1_num_ref_idx_lx_active[uc_lx]); i++)\n {\n if(!(u2_def_mod_flag & (1 << i)))\n ps_dpb_mgr->ps_mod_dpb[uc_lx][modCount++] =\n ps_dpb_mgr->ps_init_dpb[uc_lx][i];\n }\n return OK;\n}\n", + "line": null, + "label": 0, + "cwe": "CWE-119", + "cve": "CVE-2016-0842", + "length": 1043 + }, + { + "index": 182706, + "code": "xfs_setattr_nonsize(\n\tstruct xfs_inode\t*ip,\n\tstruct iattr\t\t*iattr,\n\tint\t\t\tflags)\n{\n\txfs_mount_t\t\t*mp = ip->i_mount;\n\tstruct inode\t\t*inode = VFS_I(ip);\n\tint\t\t\tmask = iattr->ia_valid;\n\txfs_trans_t\t\t*tp;\n\tint\t\t\terror;\n\tkuid_t\t\t\tuid = GLOBAL_ROOT_UID, iuid = GLOBAL_ROOT_UID;\n\tkgid_t\t\t\tgid = GLOBAL_ROOT_GID, igid = GLOBAL_ROOT_GID;\n\tstruct xfs_dquot\t*udqp = NULL, *gdqp = NULL;\n\tstruct xfs_dquot\t*olddquot1 = NULL, *olddquot2 = NULL;\n\n\tASSERT((mask & ATTR_SIZE) == 0);\n\n\t/*\n\t * If disk quotas is on, we make sure that the dquots do exist on disk,\n\t * before we start any other transactions. Trying to do this later\n\t * is messy. We don't care to take a readlock to look at the ids\n\t * in inode here, because we can't hold it across the trans_reserve.\n\t * If the IDs do change before we take the ilock, we're covered\n\t * because the i_*dquot fields will get updated anyway.\n\t */\n\tif (XFS_IS_QUOTA_ON(mp) && (mask & (ATTR_UID|ATTR_GID))) {\n\t\tuint\tqflags = 0;\n\n\t\tif ((mask & ATTR_UID) && XFS_IS_UQUOTA_ON(mp)) {\n\t\t\tuid = iattr->ia_uid;\n\t\t\tqflags |= XFS_QMOPT_UQUOTA;\n\t\t} else {\n\t\t\tuid = inode->i_uid;\n\t\t}\n\t\tif ((mask & ATTR_GID) && XFS_IS_GQUOTA_ON(mp)) {\n\t\t\tgid = iattr->ia_gid;\n\t\t\tqflags |= XFS_QMOPT_GQUOTA;\n\t\t} else {\n\t\t\tgid = inode->i_gid;\n\t\t}\n\n\t\t/*\n\t\t * We take a reference when we initialize udqp and gdqp,\n\t\t * so it is important that we never blindly double trip on\n\t\t * the same variable. See xfs_create() for an example.\n\t\t */\n\t\tASSERT(udqp == NULL);\n\t\tASSERT(gdqp == NULL);\n\t\terror = xfs_qm_vop_dqalloc(ip, xfs_kuid_to_uid(uid),\n\t\t\t\t\t xfs_kgid_to_gid(gid),\n\t\t\t\t\t xfs_get_projid(ip),\n\t\t\t\t\t qflags, &udqp, &gdqp, NULL);\n\t\tif (error)\n\t\t\treturn error;\n\t}\n\n\terror = xfs_trans_alloc(mp, &M_RES(mp)->tr_ichange, 0, 0, 0, &tp);\n\tif (error)\n\t\tgoto out_dqrele;\n\n\txfs_ilock(ip, XFS_ILOCK_EXCL);\n\txfs_trans_ijoin(tp, ip, 0);\n\n\t/*\n\t * Change file ownership. Must be the owner or privileged.\n\t */\n\tif (mask & (ATTR_UID|ATTR_GID)) {\n\t\t/*\n\t\t * These IDs could have changed since we last looked at them.\n\t\t * But, we're assured that if the ownership did change\n\t\t * while we didn't have the inode locked, inode's dquot(s)\n\t\t * would have changed also.\n\t\t */\n\t\tiuid = inode->i_uid;\n\t\tigid = inode->i_gid;\n\t\tgid = (mask & ATTR_GID) ? iattr->ia_gid : igid;\n\t\tuid = (mask & ATTR_UID) ? iattr->ia_uid : iuid;\n\n\t\t/*\n\t\t * Do a quota reservation only if uid/gid is actually\n\t\t * going to change.\n\t\t */\n\t\tif (XFS_IS_QUOTA_RUNNING(mp) &&\n\t\t ((XFS_IS_UQUOTA_ON(mp) && !uid_eq(iuid, uid)) ||\n\t\t (XFS_IS_GQUOTA_ON(mp) && !gid_eq(igid, gid)))) {\n\t\t\tASSERT(tp);\n\t\t\terror = xfs_qm_vop_chown_reserve(tp, ip, udqp, gdqp,\n\t\t\t\t\t\tNULL, capable(CAP_FOWNER) ?\n\t\t\t\t\t\tXFS_QMOPT_FORCE_RES : 0);\n\t\t\tif (error)\t/* out of quota */\n\t\t\t\tgoto out_cancel;\n\t\t}\n\t}\n\n\t/*\n\t * Change file ownership. Must be the owner or privileged.\n\t */\n\tif (mask & (ATTR_UID|ATTR_GID)) {\n\t\t/*\n\t\t * CAP_FSETID overrides the following restrictions:\n\t\t *\n\t\t * The set-user-ID and set-group-ID bits of a file will be\n\t\t * cleared upon successful return from chown()\n\t\t */\n\t\tif ((inode->i_mode & (S_ISUID|S_ISGID)) &&\n\t\t !capable(CAP_FSETID))\n\t\t\tinode->i_mode &= ~(S_ISUID|S_ISGID);\n\n\t\t/*\n\t\t * Change the ownerships and register quota modifications\n\t\t * in the transaction.\n\t\t */\n\t\tif (!uid_eq(iuid, uid)) {\n\t\t\tif (XFS_IS_QUOTA_RUNNING(mp) && XFS_IS_UQUOTA_ON(mp)) {\n\t\t\t\tASSERT(mask & ATTR_UID);\n\t\t\t\tASSERT(udqp);\n\t\t\t\tolddquot1 = xfs_qm_vop_chown(tp, ip,\n\t\t\t\t\t\t\t&ip->i_udquot, udqp);\n\t\t\t}\n\t\t\tip->i_d.di_uid = xfs_kuid_to_uid(uid);\n\t\t\tinode->i_uid = uid;\n\t\t}\n\t\tif (!gid_eq(igid, gid)) {\n\t\t\tif (XFS_IS_QUOTA_RUNNING(mp) && XFS_IS_GQUOTA_ON(mp)) {\n\t\t\t\tASSERT(xfs_sb_version_has_pquotino(&mp->m_sb) ||\n\t\t\t\t !XFS_IS_PQUOTA_ON(mp));\n\t\t\t\tASSERT(mask & ATTR_GID);\n\t\t\t\tASSERT(gdqp);\n\t\t\t\tolddquot2 = xfs_qm_vop_chown(tp, ip,\n\t\t\t\t\t\t\t&ip->i_gdquot, gdqp);\n\t\t\t}\n\t\t\tip->i_d.di_gid = xfs_kgid_to_gid(gid);\n\t\t\tinode->i_gid = gid;\n\t\t}\n\t}\n\n\tif (mask & ATTR_MODE)\n\t\txfs_setattr_mode(ip, iattr);\n\tif (mask & (ATTR_ATIME|ATTR_CTIME|ATTR_MTIME))\n\t\txfs_setattr_time(ip, iattr);\n\n\txfs_trans_log_inode(tp, ip, XFS_ILOG_CORE);\n\n\tXFS_STATS_INC(mp, xs_ig_attrchg);\n\n\tif (mp->m_flags & XFS_MOUNT_WSYNC)\n\t\txfs_trans_set_sync(tp);\n\terror = xfs_trans_commit(tp);\n\n\txfs_iunlock(ip, XFS_ILOCK_EXCL);\n\n\t/*\n\t * Release any dquot(s) the inode had kept before chown.\n\t */\n\txfs_qm_dqrele(olddquot1);\n\txfs_qm_dqrele(olddquot2);\n\txfs_qm_dqrele(udqp);\n\txfs_qm_dqrele(gdqp);\n\n\tif (error)\n\t\treturn error;\n\n\t/*\n\t * XXX(hch): Updating the ACL entries is not atomic vs the i_mode\n\t * \t update. We could avoid this with linked transactions\n\t * \t and passing down the transaction pointer all the way\n\t *\t to attr_set. No previous user of the generic\n\t * \t Posix ACL code seems to care about this issue either.\n\t */\n\tif ((mask & ATTR_MODE) && !(flags & XFS_ATTR_NOACL)) {\n\t\terror = posix_acl_chmod(inode, inode->i_mode);\n\t\tif (error)\n\t\t\treturn error;\n\t}\n\n\treturn 0;\n \n out_cancel:\n \txfs_trans_cancel(tp);\n out_dqrele:\n \txfs_qm_dqrele(udqp);\n \txfs_qm_dqrele(gdqp);\n\treturn error;\n}\n", + "line": null, + "label": 1, + "cwe": "CWE-399", + "cve": "CVE-2019-15538", + "length": 1684 + }, + { + "index": 148733, + "code": "void V4L2JpegEncodeAccelerator::EncodedInstanceDmaBuf::PrepareJpegMarkers(\n gfx::Size coded_size) {\n DCHECK(parent_->encoder_task_runner_->BelongsToCurrentThread());\n const int kNumDQT = 2;\n for (size_t i = 0; i < kNumDQT; ++i) {\n const uint8_t kQuantSegment[] = {\n 0xFF, JPEG_DQT, 0x00,\n 0x03 + kDctSize, // Segment length:67 (2-byte).\n static_cast(i) // Precision (4-bit high) = 0,\n };\n for (size_t j = 0; j < sizeof(kQuantSegment); ++j) {\n jpeg_markers_.push_back(kQuantSegment[j]);\n }\n\n for (size_t j = 0; j < kDctSize; ++j) {\n jpeg_markers_.push_back(quantization_table_[i].value[j]);\n }\n }\n\n const int kNumOfComponents = 3;\n const uint8_t kStartOfFrame[] = {\n 0xFF,\n JPEG_SOF0, // Baseline.\n 0x00,\n 0x11, // Segment length:17 (2-byte).\n 8, // Data precision.\n static_cast((coded_size.height() >> 8) & 0xFF),\n static_cast(coded_size.height() & 0xFF),\n static_cast((coded_size.width() >> 8) & 0xFF),\n static_cast(coded_size.width() & 0xFF),\n kNumOfComponents,\n };\n for (size_t i = 0; i < sizeof(kStartOfFrame); ++i) {\n jpeg_markers_.push_back(kStartOfFrame[i]);\n }\n for (size_t i = 0; i < kNumOfComponents; ++i) {\n uint8_t h_sample_factor = 1;\n uint8_t v_sample_factor = 1;\n uint8_t quant_table_number = 1;\n if (!i) {\n h_sample_factor = 2;\n v_sample_factor = 2;\n quant_table_number = 0;\n }\n\n jpeg_markers_.push_back(i + 1);\n jpeg_markers_.push_back((h_sample_factor << 4) | v_sample_factor);\n jpeg_markers_.push_back(quant_table_number);\n }\n\n static const uint8_t kDcSegment[] = {\n 0xFF, JPEG_DHT, 0x00,\n 0x1F, // Segment length:31 (2-byte).\n };\n static const uint8_t kAcSegment[] = {\n 0xFF, JPEG_DHT, 0x00,\n 0xB5, // Segment length:181 (2-byte).\n };\n\n const int kNumHuffmanTables = 2;\n for (size_t i = 0; i < kNumHuffmanTables; ++i) {\n for (size_t j = 0; j < sizeof(kDcSegment); ++j) {\n jpeg_markers_.push_back(kDcSegment[j]);\n }\n\n jpeg_markers_.push_back(static_cast(i));\n\n const JpegHuffmanTable& dcTable = kDefaultDcTable[i];\n for (size_t j = 0; j < kNumDcRunSizeBits; ++j)\n jpeg_markers_.push_back(dcTable.code_length[j]);\n for (size_t j = 0; j < kNumDcCodeWordsHuffVal; ++j)\n jpeg_markers_.push_back(dcTable.code_value[j]);\n\n for (size_t j = 0; j < sizeof(kAcSegment); ++j) {\n jpeg_markers_.push_back(kAcSegment[j]);\n }\n\n jpeg_markers_.push_back(0x10 | static_cast(i));\n\n const JpegHuffmanTable& acTable = kDefaultAcTable[i];\n for (size_t j = 0; j < kNumAcRunSizeBits; ++j)\n jpeg_markers_.push_back(acTable.code_length[j]);\n for (size_t j = 0; j < kNumAcCodeWordsHuffVal; ++j)\n jpeg_markers_.push_back(acTable.code_value[j]);\n }\n\n static const uint8_t kStartOfScan[] = {\n 0xFF, JPEG_SOS, 0x00,\n 0x0C, // Segment Length:12 (2-byte).\n 0x03 // Number of components in scan.\n };\n for (size_t i = 0; i < sizeof(kStartOfScan); ++i) {\n jpeg_markers_.push_back(kStartOfScan[i]);\n }\n\n for (uint8_t i = 0; i < kNumOfComponents; ++i) {\n uint8_t dc_table_number = 1;\n uint8_t ac_table_number = 1;\n if (!i) {\n dc_table_number = 0;\n ac_table_number = 0;\n }\n\n jpeg_markers_.push_back(i + 1);\n jpeg_markers_.push_back((dc_table_number << 4) | ac_table_number);\n }\n jpeg_markers_.push_back(0x00); // 0 for Baseline.\n jpeg_markers_.push_back(0x3F); // 63 for Baseline.\n jpeg_markers_.push_back(0x00); // 0 for Baseline.\n}\n", + "line": null, + "label": 0, + "cwe": "CWE-20", + "cve": "CVE-2017-5101", + "length": 1195 + }, + { + "index": 62441, + "code": "interp_reply(netdissect_options *ndo,\n const struct sunrpc_msg *rp, uint32_t proc, uint32_t vers, int length)\n{\n\tregister const uint32_t *dp;\n\tregister int v3;\n\tint er;\n\n\tv3 = (vers == NFS_VER3);\n\n\tif (!v3 && proc < NFS_NPROCS)\n\t\tproc = nfsv3_procid[proc];\n\n\tND_PRINT((ndo, \" %s\", tok2str(nfsproc_str, \"proc-%u\", proc)));\n\tswitch (proc) {\n\n\tcase NFSPROC_GETATTR:\n\t\tdp = parserep(ndo, rp, length);\n\t\tif (dp != NULL && parseattrstat(ndo, dp, !ndo->ndo_qflag, v3) != 0)\n\t\t\treturn;\n\t\tbreak;\n\n\tcase NFSPROC_SETATTR:\n\t\tif (!(dp = parserep(ndo, rp, length)))\n\t\t\treturn;\n\t\tif (v3) {\n\t\t\tif (parsewccres(ndo, dp, ndo->ndo_vflag))\n\t\t\t\treturn;\n\t\t} else {\n\t\t\tif (parseattrstat(ndo, dp, !ndo->ndo_qflag, 0) != 0)\n\t\t\t\treturn;\n\t\t}\n\t\tbreak;\n\n\tcase NFSPROC_LOOKUP:\n\t\tif (!(dp = parserep(ndo, rp, length)))\n\t\t\tbreak;\n\t\tif (v3) {\n\t\t\tif (!(dp = parsestatus(ndo, dp, &er)))\n\t\t\t\tbreak;\n\t\t\tif (er) {\n\t\t\t\tif (ndo->ndo_vflag > 1) {\n\t\t\t\t\tND_PRINT((ndo, \" post dattr:\"));\n\t\t\t\t\tdp = parse_post_op_attr(ndo, dp, ndo->ndo_vflag);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif (!(dp = parsefh(ndo, dp, v3)))\n\t\t\t\t\tbreak;\n\t\t\t\tif ((dp = parse_post_op_attr(ndo, dp, ndo->ndo_vflag)) &&\n\t\t\t\t ndo->ndo_vflag > 1) {\n\t\t\t\t\tND_PRINT((ndo, \" post dattr:\"));\n\t\t\t\t\tdp = parse_post_op_attr(ndo, dp, ndo->ndo_vflag);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (dp)\n\t\t\t\treturn;\n\t\t} else {\n\t\t\tif (parsediropres(ndo, dp) != 0)\n\t\t\t\treturn;\n\t\t}\n\t\tbreak;\n\n\tcase NFSPROC_ACCESS:\n\t\tif (!(dp = parserep(ndo, rp, length)))\n\t\t\tbreak;\n\t\tif (!(dp = parsestatus(ndo, dp, &er)))\n\t\t\tbreak;\n\t\tif (ndo->ndo_vflag)\n\t\t\tND_PRINT((ndo, \" attr:\"));\n\t\tif (!(dp = parse_post_op_attr(ndo, dp, ndo->ndo_vflag)))\n\t\t\tbreak;\n\t\tif (!er) {\n\t\t\tND_TCHECK(dp[0]);\n\t\t\tND_PRINT((ndo, \" c %04x\", EXTRACT_32BITS(&dp[0])));\n\t\t}\n\t\treturn;\n\n\tcase NFSPROC_READLINK:\n\t\tdp = parserep(ndo, rp, length);\n\t\tif (dp != NULL && parselinkres(ndo, dp, v3) != 0)\n\t\t\treturn;\n\t\tbreak;\n\n\tcase NFSPROC_READ:\n\t\tif (!(dp = parserep(ndo, rp, length)))\n\t\t\tbreak;\n\t\tif (v3) {\n\t\t\tif (!(dp = parsestatus(ndo, dp, &er)))\n\t\t\t\tbreak;\n\t\t\tif (!(dp = parse_post_op_attr(ndo, dp, ndo->ndo_vflag)))\n\t\t\t\tbreak;\n\t\t\tif (er)\n\t\t\t\treturn;\n\t\t\tif (ndo->ndo_vflag) {\n\t\t\t\tND_TCHECK(dp[1]);\n\t\t\t\tND_PRINT((ndo, \" %u bytes\", EXTRACT_32BITS(&dp[0])));\n\t\t\t\tif (EXTRACT_32BITS(&dp[1]))\n\t\t\t\t\tND_PRINT((ndo, \" EOF\"));\n\t\t\t}\n\t\t\treturn;\n\t\t} else {\n\t\t\tif (parseattrstat(ndo, dp, ndo->ndo_vflag, 0) != 0)\n\t\t\t\treturn;\n\t\t}\n\t\tbreak;\n\n\tcase NFSPROC_WRITE:\n\t\tif (!(dp = parserep(ndo, rp, length)))\n\t\t\tbreak;\n\t\tif (v3) {\n\t\t\tif (!(dp = parsestatus(ndo, dp, &er)))\n\t\t\t\tbreak;\n\t\t\tif (!(dp = parse_wcc_data(ndo, dp, ndo->ndo_vflag)))\n\t\t\t\tbreak;\n\t\t\tif (er)\n\t\t\t\treturn;\n\t\t\tif (ndo->ndo_vflag) {\n\t\t\t\tND_TCHECK(dp[0]);\n\t\t\t\tND_PRINT((ndo, \" %u bytes\", EXTRACT_32BITS(&dp[0])));\n\t\t\t\tif (ndo->ndo_vflag > 1) {\n\t\t\t\t\tND_TCHECK(dp[1]);\n\t\t\t\t\tND_PRINT((ndo, \" <%s>\",\n\t\t\t\t\t\ttok2str(nfsv3_writemodes,\n\t\t\t\t\t\t\tNULL, EXTRACT_32BITS(&dp[1]))));\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\t\t} else {\n\t\t\tif (parseattrstat(ndo, dp, ndo->ndo_vflag, v3) != 0)\n\t\t\t\treturn;\n\t\t}\n\t\tbreak;\n\n\tcase NFSPROC_CREATE:\n\tcase NFSPROC_MKDIR:\n\t\tif (!(dp = parserep(ndo, rp, length)))\n\t\t\tbreak;\n\t\tif (v3) {\n\t\t\tif (parsecreateopres(ndo, dp, ndo->ndo_vflag) != NULL)\n\t\t\t\treturn;\n\t\t} else {\n\t\t\tif (parsediropres(ndo, dp) != 0)\n\t\t\t\treturn;\n\t\t}\n\t\tbreak;\n\n\tcase NFSPROC_SYMLINK:\n\t\tif (!(dp = parserep(ndo, rp, length)))\n\t\t\tbreak;\n\t\tif (v3) {\n\t\t\tif (parsecreateopres(ndo, dp, ndo->ndo_vflag) != NULL)\n\t\t\t\treturn;\n\t\t} else {\n\t\t\tif (parsestatus(ndo, dp, &er) != NULL)\n\t\t\t\treturn;\n\t\t}\n\t\tbreak;\n\n\tcase NFSPROC_MKNOD:\n\t\tif (!(dp = parserep(ndo, rp, length)))\n\t\t\tbreak;\n\t\tif (parsecreateopres(ndo, dp, ndo->ndo_vflag) != NULL)\n\t\t\treturn;\n\t\tbreak;\n\n\tcase NFSPROC_REMOVE:\n\tcase NFSPROC_RMDIR:\n\t\tif (!(dp = parserep(ndo, rp, length)))\n\t\t\tbreak;\n\t\tif (v3) {\n\t\t\tif (parsewccres(ndo, dp, ndo->ndo_vflag))\n\t\t\t\treturn;\n\t\t} else {\n\t\t\tif (parsestatus(ndo, dp, &er) != NULL)\n\t\t\t\treturn;\n\t\t}\n\t\tbreak;\n\n\tcase NFSPROC_RENAME:\n\t\tif (!(dp = parserep(ndo, rp, length)))\n\t\t\tbreak;\n\t\tif (v3) {\n\t\t\tif (!(dp = parsestatus(ndo, dp, &er)))\n\t\t\t\tbreak;\n\t\t\tif (ndo->ndo_vflag) {\n\t\t\t\tND_PRINT((ndo, \" from:\"));\n\t\t\t\tif (!(dp = parse_wcc_data(ndo, dp, ndo->ndo_vflag)))\n\t\t\t\t\tbreak;\n\t\t\t\tND_PRINT((ndo, \" to:\"));\n\t\t\t\tif (!(dp = parse_wcc_data(ndo, dp, ndo->ndo_vflag)))\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\treturn;\n\t\t} else {\n\t\t\tif (parsestatus(ndo, dp, &er) != NULL)\n\t\t\t\treturn;\n\t\t}\n\t\tbreak;\n\n\tcase NFSPROC_LINK:\n\t\tif (!(dp = parserep(ndo, rp, length)))\n\t\t\tbreak;\n\t\tif (v3) {\n\t\t\tif (!(dp = parsestatus(ndo, dp, &er)))\n\t\t\t\tbreak;\n\t\t\tif (ndo->ndo_vflag) {\n\t\t\t\tND_PRINT((ndo, \" file POST:\"));\n\t\t\t\tif (!(dp = parse_post_op_attr(ndo, dp, ndo->ndo_vflag)))\n\t\t\t\t\tbreak;\n\t\t\t\tND_PRINT((ndo, \" dir:\"));\n\t\t\t\tif (!(dp = parse_wcc_data(ndo, dp, ndo->ndo_vflag)))\n\t\t\t\t\tbreak;\n\t\t\t\treturn;\n\t\t\t}\n\t\t} else {\n\t\t\tif (parsestatus(ndo, dp, &er) != NULL)\n\t\t\t\treturn;\n\t\t}\n\t\tbreak;\n\n\tcase NFSPROC_READDIR:\n\t\tif (!(dp = parserep(ndo, rp, length)))\n\t\t\tbreak;\n\t\tif (v3) {\n\t\t\tif (parsev3rddirres(ndo, dp, ndo->ndo_vflag))\n\t\t\t\treturn;\n\t\t} else {\n\t\t\tif (parserddires(ndo, dp) != 0)\n\t\t\t\treturn;\n\t\t}\n\t\tbreak;\n\n\tcase NFSPROC_READDIRPLUS:\n\t\tif (!(dp = parserep(ndo, rp, length)))\n\t\t\tbreak;\n\t\tif (parsev3rddirres(ndo, dp, ndo->ndo_vflag))\n\t\t\treturn;\n\t\tbreak;\n\n\tcase NFSPROC_FSSTAT:\n\t\tdp = parserep(ndo, rp, length);\n\t\tif (dp != NULL && parsestatfs(ndo, dp, v3) != 0)\n\t\t\treturn;\n\t\tbreak;\n\n\tcase NFSPROC_FSINFO:\n\t\tdp = parserep(ndo, rp, length);\n\t\tif (dp != NULL && parsefsinfo(ndo, dp) != 0)\n\t\t\treturn;\n\t\tbreak;\n\n\tcase NFSPROC_PATHCONF:\n\t\tdp = parserep(ndo, rp, length);\n\t\tif (dp != NULL && parsepathconf(ndo, dp) != 0)\n\t\t\treturn;\n\t\tbreak;\n\n\tcase NFSPROC_COMMIT:\n\t\tdp = parserep(ndo, rp, length);\n\t\tif (dp != NULL && parsewccres(ndo, dp, ndo->ndo_vflag) != 0)\n\t\t\treturn;\n\t\tbreak;\n\n\tdefault:\n\t\treturn;\n\t}\ntrunc:\n\tif (!nfserr)\n\t\tND_PRINT((ndo, \"%s\", tstr));\n}\n", + "line": null, + "label": 0, + "cwe": "CWE-125", + "cve": "CVE-2017-13005", + "length": 2116 + }, + { + "index": 4968, + "code": "qtdemux_parse_trak (GstQTDemux * qtdemux, GNode * trak)\n{\n int offset;\n GNode *tkhd;\n GNode *mdia;\n GNode *mdhd;\n GNode *hdlr;\n GNode *minf;\n GNode *stbl;\n GNode *stsd;\n GNode *mp4a;\n GNode *mp4v;\n GNode *wave;\n GNode *esds;\n QtDemuxStream *stream;\n GstTagList *list = NULL;\n gchar *codec = NULL;\n const guint8 *stsd_data;\n guint32 version;\n\n stream = g_new0 (QtDemuxStream, 1);\n /* new streams always need a discont */\n stream->discont = TRUE;\n /* we enable clipping for raw audio/video streams */\n stream->need_clip = FALSE;\n stream->segment_index = -1;\n stream->time_position = 0;\n stream->sample_index = -1;\n stream->last_ret = GST_FLOW_OK;\n\n if (!(tkhd = qtdemux_tree_get_child_by_type (trak, FOURCC_tkhd)))\n goto corrupt_file;\n\n GST_LOG_OBJECT (qtdemux, \"track[tkhd] version/flags: 0x%08x\",\n QT_UINT32 ((guint8 *) tkhd->data + 8));\n\n if (!(mdia = qtdemux_tree_get_child_by_type (trak, FOURCC_mdia)))\n goto corrupt_file;\n\n if (!(mdhd = qtdemux_tree_get_child_by_type (mdia, FOURCC_mdhd))) {\n /* be nice for some crooked mjp2 files that use mhdr for mdhd */\n if (qtdemux->major_brand != FOURCC_mjp2 ||\n !(mdhd = qtdemux_tree_get_child_by_type (mdia, FOURCC_mhdr)))\n goto corrupt_file;\n }\n\n version = QT_UINT32 ((guint8 *) mdhd->data + 8);\n GST_LOG_OBJECT (qtdemux, \"track version/flags: %08x\", version);\n if (version == 0x01000000) {\n stream->timescale = QT_UINT32 ((guint8 *) mdhd->data + 28);\n stream->duration = QT_UINT64 ((guint8 *) mdhd->data + 32);\n } else {\n stream->timescale = QT_UINT32 ((guint8 *) mdhd->data + 20);\n stream->duration = QT_UINT32 ((guint8 *) mdhd->data + 24);\n }\n\n GST_LOG_OBJECT (qtdemux, \"track timescale: %\" G_GUINT32_FORMAT,\n stream->timescale);\n GST_LOG_OBJECT (qtdemux, \"track duration: %\" G_GUINT64_FORMAT,\n stream->duration);\n\n if (qtdemux->duration != G_MAXINT32 && stream->duration != G_MAXINT32) {\n guint64 tdur1, tdur2;\n\n /* don't overflow */\n tdur1 = stream->timescale * (guint64) qtdemux->duration;\n tdur2 = qtdemux->timescale * (guint64) stream->duration;\n\n /* HACK:\n * some of those trailers, nowadays, have prologue images that are\n * themselves vide tracks as well. I haven't really found a way to\n * identify those yet, except for just looking at their duration. */\n if (tdur1 != 0 && (tdur2 * 10 / tdur1) < 2) {\n GST_WARNING_OBJECT (qtdemux,\n \"Track shorter than 20%% (%\" G_GUINT64_FORMAT \"/%\" G_GUINT32_FORMAT\n \" vs. %\" G_GUINT32_FORMAT \"/%\" G_GUINT32_FORMAT \") of the stream \"\n \"found, assuming preview image or something; skipping track\",\n stream->duration, stream->timescale, qtdemux->duration,\n qtdemux->timescale);\n g_free (stream);\n return TRUE;\n }\n }\n\n if (!(hdlr = qtdemux_tree_get_child_by_type (mdia, FOURCC_hdlr)))\n goto corrupt_file;\n\n GST_LOG_OBJECT (qtdemux, \"track type: %\" GST_FOURCC_FORMAT,\n GST_FOURCC_ARGS (QT_FOURCC ((guint8 *) hdlr->data + 12)));\n\n stream->subtype = QT_FOURCC ((guint8 *) hdlr->data + 16);\n GST_LOG_OBJECT (qtdemux, \"track subtype: %\" GST_FOURCC_FORMAT,\n GST_FOURCC_ARGS (stream->subtype));\n\n if (!(minf = qtdemux_tree_get_child_by_type (mdia, FOURCC_minf)))\n goto corrupt_file;\n\n if (!(stbl = qtdemux_tree_get_child_by_type (minf, FOURCC_stbl)))\n goto corrupt_file;\n\n /* parse stsd */\n if (!(stsd = qtdemux_tree_get_child_by_type (stbl, FOURCC_stsd)))\n goto corrupt_file;\n stsd_data = (const guint8 *) stsd->data;\n\n if (stream->subtype == FOURCC_vide) {\n guint32 fourcc;\n\n stream->sampled = TRUE;\n\n offset = 16;\n stream->fourcc = fourcc = QT_FOURCC (stsd_data + offset + 4);\n GST_LOG_OBJECT (qtdemux, \"st type: %\" GST_FOURCC_FORMAT,\n GST_FOURCC_ARGS (fourcc));\n\n stream->width = QT_UINT16 (stsd_data + offset + 32);\n stream->height = QT_UINT16 (stsd_data + offset + 34);\n stream->fps_n = 0; /* this is filled in later */\n stream->fps_d = 0; /* this is filled in later */\n stream->bits_per_sample = QT_UINT16 (stsd_data + offset + 82);\n stream->color_table_id = QT_UINT16 (stsd_data + offset + 84);\n\n GST_LOG_OBJECT (qtdemux, \"frame count: %u\",\n QT_UINT16 (stsd_data + offset + 48));\n\n if (fourcc == FOURCC_drms)\n goto error_encrypted;\n\n stream->caps =\n qtdemux_video_caps (qtdemux, stream, fourcc, stsd_data, &codec);\n if (codec) {\n list = gst_tag_list_new ();\n gst_tag_list_add (list, GST_TAG_MERGE_REPLACE,\n GST_TAG_VIDEO_CODEC, codec, NULL);\n g_free (codec);\n codec = NULL;\n }\n\n esds = NULL;\n mp4v = qtdemux_tree_get_child_by_type (stsd, FOURCC_mp4v);\n if (mp4v)\n esds = qtdemux_tree_get_child_by_type (mp4v, FOURCC_esds);\n\n if (esds) {\n gst_qtdemux_handle_esds (qtdemux, stream, esds, list);\n } else {\n switch (fourcc) {\n case FOURCC_avc1:\n {\n gint len = QT_UINT32 (stsd_data) - 0x66;\n const guint8 *avc_data = stsd_data + 0x66;\n\n /* find avcC */\n while (len >= 0x8 &&\n QT_FOURCC (avc_data + 0x4) != FOURCC_avcC &&\n QT_UINT32 (avc_data) < len) {\n len -= QT_UINT32 (avc_data);\n avc_data += QT_UINT32 (avc_data);\n }\n\n /* parse, if found */\n if (len > 0x8 && QT_FOURCC (avc_data + 0x4) == FOURCC_avcC) {\n GstBuffer *buf;\n gint size;\n\n if (QT_UINT32 (avc_data) < len)\n size = QT_UINT32 (avc_data) - 0x8;\n else\n size = len - 0x8;\n\n GST_DEBUG_OBJECT (qtdemux, \"found avcC codec_data in stsd\");\n\n buf = gst_buffer_new_and_alloc (size);\n memcpy (GST_BUFFER_DATA (buf), avc_data + 0x8, size);\n gst_caps_set_simple (stream->caps,\n \"codec_data\", GST_TYPE_BUFFER, buf, NULL);\n gst_buffer_unref (buf);\n }\n break;\n }\n case FOURCC_mjp2:\n {\n GNode *jp2h, *colr, *mjp2, *field, *prefix;\n const guint8 *data;\n guint32 fourcc = 0;\n\n GST_DEBUG_OBJECT (qtdemux, \"found mjp2\");\n /* some required atoms */\n mjp2 = qtdemux_tree_get_child_by_type (stsd, FOURCC_mjp2);\n if (!mjp2)\n break;\n jp2h = qtdemux_tree_get_child_by_type (mjp2, FOURCC_jp2h);\n if (!jp2h)\n break;\n colr = qtdemux_tree_get_child_by_type (jp2h, FOURCC_colr);\n if (!colr)\n break;\n GST_DEBUG_OBJECT (qtdemux, \"found colr\");\n /* try to extract colour space info */\n if (QT_UINT8 (colr->data + 8) == 1) {\n switch (QT_UINT32 (colr->data + 11)) {\n case 16:\n fourcc = GST_MAKE_FOURCC ('s', 'R', 'G', 'B');\n break;\n case 17:\n fourcc = GST_MAKE_FOURCC ('G', 'R', 'A', 'Y');\n break;\n case 18:\n fourcc = GST_MAKE_FOURCC ('s', 'Y', 'U', 'V');\n break;\n default:\n break;\n }\n }\n\n if (fourcc)\n gst_caps_set_simple (stream->caps,\n \"fourcc\", GST_TYPE_FOURCC, fourcc, NULL);\n\n /* some optional atoms */\n field = qtdemux_tree_get_child_by_type (mjp2, FOURCC_fiel);\n prefix = qtdemux_tree_get_child_by_type (mjp2, FOURCC_jp2x);\n\n /* indicate possible fields in caps */\n if (field) {\n data = field->data + 8;\n if (*data != 1)\n gst_caps_set_simple (stream->caps, \"fields\", G_TYPE_INT,\n (gint) * data, NULL);\n }\n /* add codec_data if provided */\n if (prefix) {\n GstBuffer *buf;\n gint len;\n\n GST_DEBUG_OBJECT (qtdemux, \"found prefix data in stsd\");\n data = prefix->data;\n len = QT_UINT32 (data);\n if (len > 0x8) {\n len -= 0x8;\n buf = gst_buffer_new_and_alloc (len);\n memcpy (GST_BUFFER_DATA (buf), data + 8, len);\n gst_caps_set_simple (stream->caps,\n \"codec_data\", GST_TYPE_BUFFER, buf, NULL);\n gst_buffer_unref (buf);\n }\n }\n break;\n }\n case FOURCC_SVQ3:\n case FOURCC_VP31:\n {\n GstBuffer *buf;\n gint len = QT_UINT32 (stsd_data);\n\n GST_DEBUG_OBJECT (qtdemux, \"found codec_data in stsd\");\n\n buf = gst_buffer_new_and_alloc (len);\n memcpy (GST_BUFFER_DATA (buf), stsd_data, len);\n gst_caps_set_simple (stream->caps,\n \"codec_data\", GST_TYPE_BUFFER, buf, NULL);\n gst_buffer_unref (buf);\n break;\n }\n case FOURCC_rle_:\n {\n gst_caps_set_simple (stream->caps,\n \"depth\", G_TYPE_INT, QT_UINT16 (stsd_data + offset + 82), NULL);\n break;\n }\n case FOURCC_XiTh:\n {\n GNode *xith, *xdxt;\n\n GST_DEBUG_OBJECT (qtdemux, \"found XiTh\");\n xith = qtdemux_tree_get_child_by_type (stsd, FOURCC_XiTh);\n if (!xith)\n break;\n\n xdxt = qtdemux_tree_get_child_by_type (xith, FOURCC_XdxT);\n if (!xdxt)\n break;\n\n GST_DEBUG_OBJECT (qtdemux, \"found XdxT node\");\n /* collect the headers and store them in a stream list so that we can\n * send them out first */\n qtdemux_parse_theora_extension (qtdemux, stream, xdxt);\n break;\n }\n default:\n break;\n }\n }\n\n GST_INFO_OBJECT (qtdemux,\n \"type %\" GST_FOURCC_FORMAT \" caps %\" GST_PTR_FORMAT,\n GST_FOURCC_ARGS (fourcc), stream->caps);\n\n } else if (stream->subtype == FOURCC_soun) {\n int version, samplesize;\n guint32 fourcc;\n int len;\n guint16 compression_id;\n\n len = QT_UINT32 (stsd_data + 16);\n GST_LOG_OBJECT (qtdemux, \"stsd len: %d\", len);\n\n stream->fourcc = fourcc = QT_FOURCC (stsd_data + 16 + 4);\n GST_LOG_OBJECT (qtdemux, \"stsd type: %\" GST_FOURCC_FORMAT,\n GST_FOURCC_ARGS (stream->fourcc));\n\n offset = 32;\n\n version = QT_UINT32 (stsd_data + offset);\n stream->n_channels = QT_UINT16 (stsd_data + offset + 8);\n samplesize = QT_UINT16 (stsd_data + offset + 10);\n compression_id = QT_UINT16 (stsd_data + offset + 12);\n stream->rate = QT_FP32 (stsd_data + offset + 16);\n\n GST_LOG_OBJECT (qtdemux, \"version/rev: %08x\", version);\n GST_LOG_OBJECT (qtdemux, \"vendor: %08x\",\n QT_UINT32 (stsd_data + offset + 4));\n GST_LOG_OBJECT (qtdemux, \"n_channels: %d\", stream->n_channels);\n GST_LOG_OBJECT (qtdemux, \"sample_size: %d\", samplesize);\n GST_LOG_OBJECT (qtdemux, \"compression_id: %d\", compression_id);\n GST_LOG_OBJECT (qtdemux, \"packet size: %d\",\n QT_UINT16 (stsd_data + offset + 14));\n GST_LOG_OBJECT (qtdemux, \"sample rate: %g\", stream->rate);\n\n if (compression_id == 0xfffe)\n stream->sampled = TRUE;\n\n /* first assume uncompressed audio */\n stream->bytes_per_sample = samplesize / 8;\n stream->samples_per_frame = stream->n_channels;\n stream->bytes_per_frame = stream->n_channels * stream->bytes_per_sample;\n stream->samples_per_packet = stream->samples_per_frame;\n stream->bytes_per_packet = stream->bytes_per_sample;\n\n offset = 52;\n switch (fourcc) {\n /* Yes, these have to be hard-coded */\n case FOURCC_MAC6:\n {\n stream->samples_per_packet = 6;\n stream->bytes_per_packet = 1;\n stream->bytes_per_frame = 1 * stream->n_channels;\n stream->bytes_per_sample = 1;\n stream->samples_per_frame = 6 * stream->n_channels;\n break;\n }\n case FOURCC_MAC3:\n {\n stream->samples_per_packet = 3;\n stream->bytes_per_packet = 1;\n stream->bytes_per_frame = 1 * stream->n_channels;\n stream->bytes_per_sample = 1;\n stream->samples_per_frame = 3 * stream->n_channels;\n break;\n }\n case FOURCC_ima4:\n {\n stream->samples_per_packet = 64;\n stream->bytes_per_packet = 34;\n stream->bytes_per_frame = 34 * stream->n_channels;\n stream->bytes_per_sample = 2;\n stream->samples_per_frame = 64 * stream->n_channels;\n break;\n }\n case FOURCC_ulaw:\n case FOURCC_alaw:\n {\n stream->samples_per_packet = 1;\n stream->bytes_per_packet = 1;\n stream->bytes_per_frame = 1 * stream->n_channels;\n stream->bytes_per_sample = 1;\n stream->samples_per_frame = 1 * stream->n_channels;\n break;\n }\n default:\n break;\n }\n if (version == 0x00010000) {\n switch (fourcc) {\n case FOURCC_twos:\n case FOURCC_sowt:\n case FOURCC_raw_:\n break;\n default:\n {\n /* only parse extra decoding config for non-pcm audio */\n stream->samples_per_packet = QT_UINT32 (stsd_data + offset);\n stream->bytes_per_packet = QT_UINT32 (stsd_data + offset + 4);\n stream->bytes_per_frame = QT_UINT32 (stsd_data + offset + 8);\n stream->bytes_per_sample = QT_UINT32 (stsd_data + offset + 12);\n\n GST_LOG_OBJECT (qtdemux, \"samples/packet: %d\",\n stream->samples_per_packet);\n GST_LOG_OBJECT (qtdemux, \"bytes/packet: %d\",\n stream->bytes_per_packet);\n GST_LOG_OBJECT (qtdemux, \"bytes/frame: %d\",\n stream->bytes_per_frame);\n GST_LOG_OBJECT (qtdemux, \"bytes/sample: %d\",\n stream->bytes_per_sample);\n\n if (!stream->sampled && stream->bytes_per_packet) {\n stream->samples_per_frame = (stream->bytes_per_frame /\n stream->bytes_per_packet) * stream->samples_per_packet;\n GST_LOG_OBJECT (qtdemux, \"samples/frame: %d\",\n stream->samples_per_frame);\n }\n break;\n }\n }\n offset = 68;\n } else if (version == 0x00020000) {\n union\n {\n gdouble fp;\n guint64 val;\n } qtfp;\n\n stream->samples_per_packet = QT_UINT32 (stsd_data + offset);\n qtfp.val = QT_UINT64 (stsd_data + offset + 4);\n stream->rate = qtfp.fp;\n stream->n_channels = QT_UINT32 (stsd_data + offset + 12);\n\n GST_LOG_OBJECT (qtdemux, \"samples/packet: %d\",\n stream->samples_per_packet);\n GST_LOG_OBJECT (qtdemux, \"sample rate: %g\", stream->rate);\n GST_LOG_OBJECT (qtdemux, \"n_channels: %d\", stream->n_channels);\n\n offset = 68;\n } else {\n GST_WARNING_OBJECT (qtdemux, \"unknown version %08x\", version);\n }\n\n if (fourcc == FOURCC_drms)\n goto error_encrypted;\n\n stream->caps = qtdemux_audio_caps (qtdemux, stream, fourcc, NULL, 0,\n &codec);\n\n if (codec) {\n list = gst_tag_list_new ();\n gst_tag_list_add (list, GST_TAG_MERGE_REPLACE,\n GST_TAG_AUDIO_CODEC, codec, NULL);\n g_free (codec);\n codec = NULL;\n }\n\n mp4a = qtdemux_tree_get_child_by_type (stsd, FOURCC_mp4a);\n wave = NULL;\n esds = NULL;\n if (mp4a) {\n wave = qtdemux_tree_get_child_by_type (mp4a, FOURCC_wave);\n if (wave)\n esds = qtdemux_tree_get_child_by_type (wave, FOURCC_esds);\n if (!esds)\n esds = qtdemux_tree_get_child_by_type (mp4a, FOURCC_esds);\n }\n\n if (esds) {\n gst_qtdemux_handle_esds (qtdemux, stream, esds, list);\n } else {\n switch (fourcc) {\n#if 0\n /* FIXME: what is in the chunk? */\n case FOURCC_QDMC:\n {\n gint len = QT_UINT32 (stsd_data);\n\n /* seems to be always = 116 = 0x74 */\n break;\n }\n#endif\n case FOURCC_QDM2:\n {\n gint len = QT_UINT32 (stsd_data);\n\n if (len > 0x4C) {\n GstBuffer *buf = gst_buffer_new_and_alloc (len - 0x4C);\n\n memcpy (GST_BUFFER_DATA (buf), stsd_data + 0x4C, len - 0x4C);\n gst_caps_set_simple (stream->caps,\n \"codec_data\", GST_TYPE_BUFFER, buf, NULL);\n gst_buffer_unref (buf);\n }\n gst_caps_set_simple (stream->caps,\n \"samplesize\", G_TYPE_INT, samplesize, NULL);\n break;\n }\n case FOURCC_alac:\n {\n gint len = QT_UINT32 (stsd_data);\n\n if (len > 0x34) {\n GstBuffer *buf = gst_buffer_new_and_alloc (len - 0x34);\n\n memcpy (GST_BUFFER_DATA (buf), stsd_data + 0x34, len - 0x34);\n gst_caps_set_simple (stream->caps,\n \"codec_data\", GST_TYPE_BUFFER, buf, NULL);\n gst_buffer_unref (buf);\n }\n gst_caps_set_simple (stream->caps,\n \"samplesize\", G_TYPE_INT, samplesize, NULL);\n break;\n }\n case FOURCC_samr:\n {\n gint len = QT_UINT32 (stsd_data);\n\n if (len > 0x34) {\n GstBuffer *buf = gst_buffer_new_and_alloc (len - 0x34);\n\n memcpy (GST_BUFFER_DATA (buf), stsd_data + 0x34, len - 0x34);\n\n gst_caps_set_simple (stream->caps,\n \"codec_data\", GST_TYPE_BUFFER, buf, NULL);\n gst_buffer_unref (buf);\n }\n break;\n }\n default:\n break;\n }\n }\n GST_INFO_OBJECT (qtdemux,\n \"type %\" GST_FOURCC_FORMAT \" caps %\" GST_PTR_FORMAT,\n GST_FOURCC_ARGS (fourcc), stream->caps);\n\n } else if (stream->subtype == FOURCC_strm) {\n guint32 fourcc;\n\n stream->fourcc = fourcc = QT_FOURCC (stsd_data + 16 + 4);\n GST_LOG_OBJECT (qtdemux, \"stsd type: %\" GST_FOURCC_FORMAT,\n GST_FOURCC_ARGS (fourcc));\n\n if (fourcc != FOURCC_rtsp) {\n GST_INFO_OBJECT (qtdemux, \"unhandled stream type %\" GST_FOURCC_FORMAT,\n GST_FOURCC_ARGS (fourcc));\n goto unknown_stream;\n }\n stream->sampled = TRUE;\n } else {\n goto unknown_stream;\n }\n\n /* promote to sampled format */\n if (stream->fourcc == FOURCC_samr) {\n /* force mono 8000 Hz for AMR */\n stream->sampled = TRUE;\n stream->n_channels = 1;\n stream->rate = 8000;\n } else if (stream->fourcc == FOURCC_sawb) {\n /* force mono 16000 Hz for AMR-WB */\n stream->sampled = TRUE;\n stream->n_channels = 1;\n stream->rate = 16000;\n } else if (stream->fourcc == FOURCC_mp4a) {\n stream->sampled = TRUE;\n }\n\n /* collect sample information */\n if (!qtdemux_parse_samples (qtdemux, stream, stbl))\n goto samples_failed;\n\n /* configure segments */\n if (!qtdemux_parse_segments (qtdemux, stream, trak))\n goto segments_failed;\n\n /* now we are ready to add the stream */\n gst_qtdemux_add_stream (qtdemux, stream, list);\n\n return TRUE;\n\n/* ERRORS */\ncorrupt_file:\n {\n GST_ELEMENT_ERROR (qtdemux, STREAM, DECODE,\n (_(\"This file is corrupt and cannot be played.\")), (NULL));\n g_free (stream);\n return FALSE;\n }\nerror_encrypted:\n {\n GST_ELEMENT_ERROR (qtdemux, STREAM, DECRYPT, (NULL), (NULL));\n g_free (stream);\n return FALSE;\n }\nsamples_failed:\n {\n /* we posted an error already */\n g_free (stream);\n return FALSE;\n }\nsegments_failed:\n {\n /* we posted an error already */\n g_free (stream);\n return FALSE;\n }\nunknown_stream:\n {\n GST_INFO_OBJECT (qtdemux, \"unknown subtype %\" GST_FOURCC_FORMAT,\n GST_FOURCC_ARGS (stream->subtype));\n g_free (stream);\n return TRUE;\n }\n}\n", + "line": null, + "label": 0, + "cwe": "CWE-119", + "cve": "CVE-2009-0397", + "length": 5566 + }, + { + "index": 56741, + "code": "static int hub_configure(struct usb_hub *hub,\n\tstruct usb_endpoint_descriptor *endpoint)\n{\n\tstruct usb_hcd *hcd;\n\tstruct usb_device *hdev = hub->hdev;\n\tstruct device *hub_dev = hub->intfdev;\n\tu16 hubstatus, hubchange;\n\tu16 wHubCharacteristics;\n\tunsigned int pipe;\n\tint maxp, ret, i;\n\tchar *message = \"out of memory\";\n\tunsigned unit_load;\n\tunsigned full_load;\n\tunsigned maxchild;\n\n\thub->buffer = kmalloc(sizeof(*hub->buffer), GFP_KERNEL);\n\tif (!hub->buffer) {\n\t\tret = -ENOMEM;\n\t\tgoto fail;\n\t}\n\n\thub->status = kmalloc(sizeof(*hub->status), GFP_KERNEL);\n\tif (!hub->status) {\n\t\tret = -ENOMEM;\n\t\tgoto fail;\n\t}\n\tmutex_init(&hub->status_mutex);\n\n\thub->descriptor = kmalloc(sizeof(*hub->descriptor), GFP_KERNEL);\n\tif (!hub->descriptor) {\n\t\tret = -ENOMEM;\n\t\tgoto fail;\n\t}\n\n\t/* Request the entire hub descriptor.\n\t * hub->descriptor can handle USB_MAXCHILDREN ports,\n\t * but the hub can/will return fewer bytes here.\n\t */\n\tret = get_hub_descriptor(hdev, hub->descriptor);\n\tif (ret < 0) {\n\t\tmessage = \"can't read hub descriptor\";\n\t\tgoto fail;\n\t} else if (hub->descriptor->bNbrPorts > USB_MAXCHILDREN) {\n\t\tmessage = \"hub has too many ports!\";\n\t\tret = -ENODEV;\n\t\tgoto fail;\n\t} else if (hub->descriptor->bNbrPorts == 0) {\n\t\tmessage = \"hub doesn't have any ports!\";\n\t\tret = -ENODEV;\n\t\tgoto fail;\n\t}\n\n\tmaxchild = hub->descriptor->bNbrPorts;\n\tdev_info(hub_dev, \"%d port%s detected\\n\", maxchild,\n\t\t\t(maxchild == 1) ? \"\" : \"s\");\n\n\thub->ports = kzalloc(maxchild * sizeof(struct usb_port *), GFP_KERNEL);\n\tif (!hub->ports) {\n\t\tret = -ENOMEM;\n\t\tgoto fail;\n\t}\n\n\twHubCharacteristics = le16_to_cpu(hub->descriptor->wHubCharacteristics);\n\tif (hub_is_superspeed(hdev)) {\n\t\tunit_load = 150;\n\t\tfull_load = 900;\n\t} else {\n\t\tunit_load = 100;\n\t\tfull_load = 500;\n\t}\n\n\t/* FIXME for USB 3.0, skip for now */\n\tif ((wHubCharacteristics & HUB_CHAR_COMPOUND) &&\n\t\t\t!(hub_is_superspeed(hdev))) {\n\t\tchar\tportstr[USB_MAXCHILDREN + 1];\n\n\t\tfor (i = 0; i < maxchild; i++)\n\t\t\tportstr[i] = hub->descriptor->u.hs.DeviceRemovable\n\t\t\t\t [((i + 1) / 8)] & (1 << ((i + 1) % 8))\n\t\t\t\t? 'F' : 'R';\n\t\tportstr[maxchild] = 0;\n\t\tdev_dbg(hub_dev, \"compound device; port removable status: %s\\n\", portstr);\n\t} else\n\t\tdev_dbg(hub_dev, \"standalone hub\\n\");\n\n\tswitch (wHubCharacteristics & HUB_CHAR_LPSM) {\n\tcase HUB_CHAR_COMMON_LPSM:\n\t\tdev_dbg(hub_dev, \"ganged power switching\\n\");\n\t\tbreak;\n\tcase HUB_CHAR_INDV_PORT_LPSM:\n\t\tdev_dbg(hub_dev, \"individual port power switching\\n\");\n\t\tbreak;\n\tcase HUB_CHAR_NO_LPSM:\n\tcase HUB_CHAR_LPSM:\n\t\tdev_dbg(hub_dev, \"no power switching (usb 1.0)\\n\");\n\t\tbreak;\n\t}\n\n\tswitch (wHubCharacteristics & HUB_CHAR_OCPM) {\n\tcase HUB_CHAR_COMMON_OCPM:\n\t\tdev_dbg(hub_dev, \"global over-current protection\\n\");\n\t\tbreak;\n\tcase HUB_CHAR_INDV_PORT_OCPM:\n\t\tdev_dbg(hub_dev, \"individual port over-current protection\\n\");\n\t\tbreak;\n\tcase HUB_CHAR_NO_OCPM:\n\tcase HUB_CHAR_OCPM:\n\t\tdev_dbg(hub_dev, \"no over-current protection\\n\");\n\t\tbreak;\n\t}\n\n\tspin_lock_init(&hub->tt.lock);\n\tINIT_LIST_HEAD(&hub->tt.clear_list);\n\tINIT_WORK(&hub->tt.clear_work, hub_tt_work);\n\tswitch (hdev->descriptor.bDeviceProtocol) {\n\tcase USB_HUB_PR_FS:\n\t\tbreak;\n\tcase USB_HUB_PR_HS_SINGLE_TT:\n\t\tdev_dbg(hub_dev, \"Single TT\\n\");\n\t\thub->tt.hub = hdev;\n\t\tbreak;\n\tcase USB_HUB_PR_HS_MULTI_TT:\n\t\tret = usb_set_interface(hdev, 0, 1);\n\t\tif (ret == 0) {\n\t\t\tdev_dbg(hub_dev, \"TT per port\\n\");\n\t\t\thub->tt.multi = 1;\n\t\t} else\n\t\t\tdev_err(hub_dev, \"Using single TT (err %d)\\n\",\n\t\t\t\tret);\n\t\thub->tt.hub = hdev;\n\t\tbreak;\n\tcase USB_HUB_PR_SS:\n\t\t/* USB 3.0 hubs don't have a TT */\n\t\tbreak;\n\tdefault:\n\t\tdev_dbg(hub_dev, \"Unrecognized hub protocol %d\\n\",\n\t\t\thdev->descriptor.bDeviceProtocol);\n\t\tbreak;\n\t}\n\n\t/* Note 8 FS bit times == (8 bits / 12000000 bps) ~= 666ns */\n\tswitch (wHubCharacteristics & HUB_CHAR_TTTT) {\n\tcase HUB_TTTT_8_BITS:\n\t\tif (hdev->descriptor.bDeviceProtocol != 0) {\n\t\t\thub->tt.think_time = 666;\n\t\t\tdev_dbg(hub_dev, \"TT requires at most %d \"\n\t\t\t\t\t\"FS bit times (%d ns)\\n\",\n\t\t\t\t8, hub->tt.think_time);\n\t\t}\n\t\tbreak;\n\tcase HUB_TTTT_16_BITS:\n\t\thub->tt.think_time = 666 * 2;\n\t\tdev_dbg(hub_dev, \"TT requires at most %d \"\n\t\t\t\t\"FS bit times (%d ns)\\n\",\n\t\t\t16, hub->tt.think_time);\n\t\tbreak;\n\tcase HUB_TTTT_24_BITS:\n\t\thub->tt.think_time = 666 * 3;\n\t\tdev_dbg(hub_dev, \"TT requires at most %d \"\n\t\t\t\t\"FS bit times (%d ns)\\n\",\n\t\t\t24, hub->tt.think_time);\n\t\tbreak;\n\tcase HUB_TTTT_32_BITS:\n\t\thub->tt.think_time = 666 * 4;\n\t\tdev_dbg(hub_dev, \"TT requires at most %d \"\n\t\t\t\t\"FS bit times (%d ns)\\n\",\n\t\t\t32, hub->tt.think_time);\n\t\tbreak;\n\t}\n\n\t/* probe() zeroes hub->indicator[] */\n\tif (wHubCharacteristics & HUB_CHAR_PORTIND) {\n\t\thub->has_indicators = 1;\n\t\tdev_dbg(hub_dev, \"Port indicators are supported\\n\");\n\t}\n\n\tdev_dbg(hub_dev, \"power on to power good time: %dms\\n\",\n\t\thub->descriptor->bPwrOn2PwrGood * 2);\n\n\t/* power budgeting mostly matters with bus-powered hubs,\n\t * and battery-powered root hubs (may provide just 8 mA).\n\t */\n\tret = usb_get_status(hdev, USB_RECIP_DEVICE, 0, &hubstatus);\n\tif (ret) {\n\t\tmessage = \"can't get hub status\";\n\t\tgoto fail;\n\t}\n\thcd = bus_to_hcd(hdev->bus);\n\tif (hdev == hdev->bus->root_hub) {\n\t\tif (hcd->power_budget > 0)\n\t\t\thdev->bus_mA = hcd->power_budget;\n\t\telse\n\t\t\thdev->bus_mA = full_load * maxchild;\n\t\tif (hdev->bus_mA >= full_load)\n\t\t\thub->mA_per_port = full_load;\n\t\telse {\n\t\t\thub->mA_per_port = hdev->bus_mA;\n\t\t\thub->limited_power = 1;\n\t\t}\n\t} else if ((hubstatus & (1 << USB_DEVICE_SELF_POWERED)) == 0) {\n\t\tint remaining = hdev->bus_mA -\n\t\t\thub->descriptor->bHubContrCurrent;\n\n\t\tdev_dbg(hub_dev, \"hub controller current requirement: %dmA\\n\",\n\t\t\thub->descriptor->bHubContrCurrent);\n\t\thub->limited_power = 1;\n\n\t\tif (remaining < maxchild * unit_load)\n\t\t\tdev_warn(hub_dev,\n\t\t\t\t\t\"insufficient power available \"\n\t\t\t\t\t\"to use all downstream ports\\n\");\n\t\thub->mA_per_port = unit_load;\t/* 7.2.1 */\n\n\t} else {\t/* Self-powered external hub */\n\t\t/* FIXME: What about battery-powered external hubs that\n\t\t * provide less current per port? */\n\t\thub->mA_per_port = full_load;\n\t}\n\tif (hub->mA_per_port < full_load)\n\t\tdev_dbg(hub_dev, \"%umA bus power budget for each child\\n\",\n\t\t\t\thub->mA_per_port);\n\n\tret = hub_hub_status(hub, &hubstatus, &hubchange);\n\tif (ret < 0) {\n\t\tmessage = \"can't get hub status\";\n\t\tgoto fail;\n\t}\n\n\t/* local power status reports aren't always correct */\n\tif (hdev->actconfig->desc.bmAttributes & USB_CONFIG_ATT_SELFPOWER)\n\t\tdev_dbg(hub_dev, \"local power source is %s\\n\",\n\t\t\t(hubstatus & HUB_STATUS_LOCAL_POWER)\n\t\t\t? \"lost (inactive)\" : \"good\");\n\n\tif ((wHubCharacteristics & HUB_CHAR_OCPM) == 0)\n\t\tdev_dbg(hub_dev, \"%sover-current condition exists\\n\",\n\t\t\t(hubstatus & HUB_STATUS_OVERCURRENT) ? \"\" : \"no \");\n\n\t/* set up the interrupt endpoint\n\t * We use the EP's maxpacket size instead of (PORTS+1+7)/8\n\t * bytes as USB2.0[11.12.3] says because some hubs are known\n\t * to send more data (and thus cause overflow). For root hubs,\n\t * maxpktsize is defined in hcd.c's fake endpoint descriptors\n\t * to be big enough for at least USB_MAXCHILDREN ports. */\n\tpipe = usb_rcvintpipe(hdev, endpoint->bEndpointAddress);\n\tmaxp = usb_maxpacket(hdev, pipe, usb_pipeout(pipe));\n\n\tif (maxp > sizeof(*hub->buffer))\n\t\tmaxp = sizeof(*hub->buffer);\n\n\thub->urb = usb_alloc_urb(0, GFP_KERNEL);\n\tif (!hub->urb) {\n\t\tret = -ENOMEM;\n\t\tgoto fail;\n\t}\n\n\tusb_fill_int_urb(hub->urb, hdev, pipe, *hub->buffer, maxp, hub_irq,\n\t\thub, endpoint->bInterval);\n\n\t/* maybe cycle the hub leds */\n\tif (hub->has_indicators && blinkenlights)\n\t\thub->indicator[0] = INDICATOR_CYCLE;\n\n\tmutex_lock(&usb_port_peer_mutex);\n\tfor (i = 0; i < maxchild; i++) {\n\t\tret = usb_hub_create_port_device(hub, i + 1);\n\t\tif (ret < 0) {\n\t\t\tdev_err(hub->intfdev,\n\t\t\t\t\"couldn't create port%d device.\\n\", i + 1);\n\t\t\tbreak;\n\t\t}\n\t}\n\thdev->maxchild = i;\n\tfor (i = 0; i < hdev->maxchild; i++) {\n\t\tstruct usb_port *port_dev = hub->ports[i];\n\n\t\tpm_runtime_put(&port_dev->dev);\n\t}\n\n\tmutex_unlock(&usb_port_peer_mutex);\n\tif (ret < 0)\n\t\tgoto fail;\n\n\t/* Update the HCD's internal representation of this hub before hub_wq\n\t * starts getting port status changes for devices under the hub.\n\t */\n\tif (hcd->driver->update_hub_device) {\n\t\tret = hcd->driver->update_hub_device(hcd, hdev,\n\t\t\t\t&hub->tt, GFP_KERNEL);\n\t\tif (ret < 0) {\n\t\t\tmessage = \"can't update HCD hub info\";\n\t\t\tgoto fail;\n\t\t}\n\t}\n\n\tusb_hub_adjust_deviceremovable(hdev, hub->descriptor);\n\n\thub_activate(hub, HUB_INIT);\n\treturn 0;\n\nfail:\n\tdev_err(hub_dev, \"config failed, %s (err %d)\\n\",\n\t\t\tmessage, ret);\n\t/* hub_disconnect() frees urb and descriptor */\n\treturn ret;\n}\n", + "line": null, + "label": 0, + "cwe": null, + "cve": "CVE-2015-8816", + "length": 2703 + }, + { + "index": 54478, + "code": "int migrate_misplaced_transhuge_page(struct mm_struct *mm,\n\t\t\t\tstruct vm_area_struct *vma,\n\t\t\t\tpmd_t *pmd, pmd_t entry,\n\t\t\t\tunsigned long address,\n\t\t\t\tstruct page *page, int node)\n{\n\tspinlock_t *ptl;\n\tpg_data_t *pgdat = NODE_DATA(node);\n\tint isolated = 0;\n\tstruct page *new_page = NULL;\n\tint page_lru = page_is_file_cache(page);\n\tunsigned long mmun_start = address & HPAGE_PMD_MASK;\n\tunsigned long mmun_end = mmun_start + HPAGE_PMD_SIZE;\n\tpmd_t orig_entry;\n\n\t/*\n\t * Rate-limit the amount of data that is being migrated to a node.\n\t * Optimal placement is no good if the memory bus is saturated and\n\t * all the time is being spent migrating!\n\t */\n\tif (numamigrate_update_ratelimit(pgdat, HPAGE_PMD_NR))\n\t\tgoto out_dropref;\n\n\tnew_page = alloc_pages_node(node,\n\t\t(GFP_TRANSHUGE | __GFP_THISNODE) & ~__GFP_WAIT,\n\t\tHPAGE_PMD_ORDER);\n\tif (!new_page)\n\t\tgoto out_fail;\n\n\tisolated = numamigrate_isolate_page(pgdat, page);\n\tif (!isolated) {\n\t\tput_page(new_page);\n\t\tgoto out_fail;\n\t}\n\n\tif (mm_tlb_flush_pending(mm))\n\t\tflush_tlb_range(vma, mmun_start, mmun_end);\n\n\t/* Prepare a page as a migration target */\n\t__set_page_locked(new_page);\n\tSetPageSwapBacked(new_page);\n\n\t/* anon mapping, we can simply copy page->mapping to the new page: */\n\tnew_page->mapping = page->mapping;\n\tnew_page->index = page->index;\n\tmigrate_page_copy(new_page, page);\n\tWARN_ON(PageLRU(new_page));\n\n\t/* Recheck the target PMD */\n\tmmu_notifier_invalidate_range_start(mm, mmun_start, mmun_end);\n\tptl = pmd_lock(mm, pmd);\n\tif (unlikely(!pmd_same(*pmd, entry) || page_count(page) != 2)) {\nfail_putback:\n\t\tspin_unlock(ptl);\n\t\tmmu_notifier_invalidate_range_end(mm, mmun_start, mmun_end);\n\n\t\t/* Reverse changes made by migrate_page_copy() */\n\t\tif (TestClearPageActive(new_page))\n\t\t\tSetPageActive(page);\n\t\tif (TestClearPageUnevictable(new_page))\n\t\t\tSetPageUnevictable(page);\n\n\t\tunlock_page(new_page);\n\t\tput_page(new_page);\t\t/* Free it */\n\n\t\t/* Retake the callers reference and putback on LRU */\n\t\tget_page(page);\n\t\tputback_lru_page(page);\n\t\tmod_zone_page_state(page_zone(page),\n\t\t\t NR_ISOLATED_ANON + page_lru, -HPAGE_PMD_NR);\n\n\t\tgoto out_unlock;\n\t}\n\n\torig_entry = *pmd;\n\tentry = mk_pmd(new_page, vma->vm_page_prot);\n\tentry = pmd_mkhuge(entry);\n\tentry = maybe_pmd_mkwrite(pmd_mkdirty(entry), vma);\n\n\t/*\n\t * Clear the old entry under pagetable lock and establish the new PTE.\n\t * Any parallel GUP will either observe the old page blocking on the\n\t * page lock, block on the page table lock or observe the new page.\n\t * The SetPageUptodate on the new page and page_add_new_anon_rmap\n\t * guarantee the copy is visible before the pagetable update.\n\t */\n\tflush_cache_range(vma, mmun_start, mmun_end);\n\tpage_add_anon_rmap(new_page, vma, mmun_start);\n\tpmdp_huge_clear_flush_notify(vma, mmun_start, pmd);\n\tset_pmd_at(mm, mmun_start, pmd, entry);\n\tflush_tlb_range(vma, mmun_start, mmun_end);\n\tupdate_mmu_cache_pmd(vma, address, &entry);\n\n\tif (page_count(page) != 2) {\n\t\tset_pmd_at(mm, mmun_start, pmd, orig_entry);\n\t\tflush_tlb_range(vma, mmun_start, mmun_end);\n\t\tmmu_notifier_invalidate_range(mm, mmun_start, mmun_end);\n\t\tupdate_mmu_cache_pmd(vma, address, &entry);\n\t\tpage_remove_rmap(new_page);\n\t\tgoto fail_putback;\n\t}\n\n\tmlock_migrate_page(new_page, page);\n\tset_page_memcg(new_page, page_memcg(page));\n\tset_page_memcg(page, NULL);\n\tpage_remove_rmap(page);\n\n\tspin_unlock(ptl);\n\tmmu_notifier_invalidate_range_end(mm, mmun_start, mmun_end);\n\n\t/* Take an \"isolate\" reference and put new page on the LRU. */\n\tget_page(new_page);\n\tputback_lru_page(new_page);\n\n\tunlock_page(new_page);\n\tunlock_page(page);\n\tput_page(page);\t\t\t/* Drop the rmap reference */\n\tput_page(page);\t\t\t/* Drop the LRU isolation reference */\n\n\tcount_vm_events(PGMIGRATE_SUCCESS, HPAGE_PMD_NR);\n\tcount_vm_numa_events(NUMA_PAGE_MIGRATE, HPAGE_PMD_NR);\n\n\tmod_zone_page_state(page_zone(page),\n\t\t\tNR_ISOLATED_ANON + page_lru,\n\t\t\t-HPAGE_PMD_NR);\n\treturn isolated;\n\nout_fail:\n\tcount_vm_events(PGMIGRATE_FAIL, HPAGE_PMD_NR);\nout_dropref:\n\tptl = pmd_lock(mm, pmd);\n\tif (pmd_same(*pmd, entry)) {\n\t\tentry = pmd_modify(entry, vma->vm_page_prot);\n\t\tset_pmd_at(mm, mmun_start, pmd, entry);\n\t\tupdate_mmu_cache_pmd(vma, address, &entry);\n\t}\n\tspin_unlock(ptl);\n\nout_unlock:\n\tunlock_page(page);\n\tput_page(page);\n\treturn 0;\n}\n", + "line": null, + "label": 0, + "cwe": "CWE-476", + "cve": "CVE-2016-3070", + "length": 1240 + }, + { + "index": 93252, + "code": "rsvp_intserv_print(netdissect_options *ndo,\n const u_char *tptr, u_short obj_tlen)\n{\n int parameter_id,parameter_length;\n union {\n\tfloat f;\n\tuint32_t i;\n } bw;\n\n if (obj_tlen < 4)\n return 0;\n ND_TCHECK_8BITS(tptr);\n parameter_id = *(tptr);\n ND_TCHECK2(*(tptr + 2), 2);\n parameter_length = EXTRACT_16BITS(tptr+2)<<2; /* convert wordcount to bytecount */\n\n ND_PRINT((ndo, \"\\n\\t Parameter ID: %s (%u), length: %u, Flags: [0x%02x]\",\n tok2str(rsvp_intserv_parameter_id_values,\"unknown\",parameter_id),\n parameter_id,\n parameter_length,\n *(tptr + 1)));\n\n if (obj_tlen < parameter_length+4)\n return 0;\n switch(parameter_id) { /* parameter_id */\n\n case 4:\n /*\n * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n * | 4 (e) | (f) | 1 (g) |\n * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n * | IS hop cnt (32-bit unsigned integer) |\n * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n */\n if (parameter_length == 4) {\n\t ND_TCHECK2(*(tptr + 4), 4);\n ND_PRINT((ndo, \"\\n\\t\\tIS hop count: %u\", EXTRACT_32BITS(tptr + 4)));\n }\n break;\n\n case 6:\n /*\n * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n * | 6 (h) | (i) | 1 (j) |\n * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n * | Path b/w estimate (32-bit IEEE floating point number) |\n * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n */\n if (parameter_length == 4) {\n\t ND_TCHECK2(*(tptr + 4), 4);\n bw.i = EXTRACT_32BITS(tptr+4);\n ND_PRINT((ndo, \"\\n\\t\\tPath b/w estimate: %.10g Mbps\", bw.f / 125000));\n }\n break;\n\n case 8:\n /*\n * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n * | 8 (k) | (l) | 1 (m) |\n * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n * | Minimum path latency (32-bit integer) |\n * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n */\n if (parameter_length == 4) {\n\t ND_TCHECK2(*(tptr + 4), 4);\n ND_PRINT((ndo, \"\\n\\t\\tMinimum path latency: \"));\n if (EXTRACT_32BITS(tptr+4) == 0xffffffff)\n ND_PRINT((ndo, \"don't care\"));\n else\n ND_PRINT((ndo, \"%u\", EXTRACT_32BITS(tptr + 4)));\n }\n break;\n\n case 10:\n\n /*\n * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n * | 10 (n) | (o) | 1 (p) |\n * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n * | Composed MTU (32-bit unsigned integer) |\n * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n */\n if (parameter_length == 4) {\n\t ND_TCHECK2(*(tptr + 4), 4);\n ND_PRINT((ndo, \"\\n\\t\\tComposed MTU: %u bytes\", EXTRACT_32BITS(tptr + 4)));\n }\n break;\n case 127:\n /*\n * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n * | 127 (e) | 0 (f) | 5 (g) |\n * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n * | Token Bucket Rate [r] (32-bit IEEE floating point number) |\n * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n * | Token Bucket Size [b] (32-bit IEEE floating point number) |\n * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n * | Peak Data Rate [p] (32-bit IEEE floating point number) |\n * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n * | Minimum Policed Unit [m] (32-bit integer) |\n * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n * | Maximum Packet Size [M] (32-bit integer) |\n * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n */\n\n if (parameter_length == 20) {\n\t ND_TCHECK2(*(tptr + 4), 20);\n bw.i = EXTRACT_32BITS(tptr+4);\n ND_PRINT((ndo, \"\\n\\t\\tToken Bucket Rate: %.10g Mbps\", bw.f / 125000));\n bw.i = EXTRACT_32BITS(tptr+8);\n ND_PRINT((ndo, \"\\n\\t\\tToken Bucket Size: %.10g bytes\", bw.f));\n bw.i = EXTRACT_32BITS(tptr+12);\n ND_PRINT((ndo, \"\\n\\t\\tPeak Data Rate: %.10g Mbps\", bw.f / 125000));\n ND_PRINT((ndo, \"\\n\\t\\tMinimum Policed Unit: %u bytes\", EXTRACT_32BITS(tptr + 16)));\n ND_PRINT((ndo, \"\\n\\t\\tMaximum Packet Size: %u bytes\", EXTRACT_32BITS(tptr + 20)));\n }\n break;\n\n case 130:\n /*\n * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n * | 130 (h) | 0 (i) | 2 (j) |\n * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n * | Rate [R] (32-bit IEEE floating point number) |\n * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n * | Slack Term [S] (32-bit integer) |\n * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n */\n\n if (parameter_length == 8) {\n\t ND_TCHECK2(*(tptr + 4), 8);\n bw.i = EXTRACT_32BITS(tptr+4);\n ND_PRINT((ndo, \"\\n\\t\\tRate: %.10g Mbps\", bw.f / 125000));\n ND_PRINT((ndo, \"\\n\\t\\tSlack Term: %u\", EXTRACT_32BITS(tptr + 8)));\n }\n break;\n\n case 133:\n case 134:\n case 135:\n case 136:\n if (parameter_length == 4) {\n\t ND_TCHECK2(*(tptr + 4), 4);\n ND_PRINT((ndo, \"\\n\\t\\tValue: %u\", EXTRACT_32BITS(tptr + 4)));\n }\n break;\n\n default:\n if (ndo->ndo_vflag <= 1)\n print_unknown_data(ndo, tptr + 4, \"\\n\\t\\t\", parameter_length);\n }\n return (parameter_length+4); /* header length 4 bytes */\n\ntrunc:\n ND_PRINT((ndo, \"%s\", tstr));\n return 0;\n}\n", + "line": null, + "label": 0, + "cwe": "CWE-125", + "cve": "CVE-2018-14465", + "length": 1586 + }, + { + "index": 181742, + "code": "static Image *ReadHDRImage(const ImageInfo *image_info,ExceptionInfo *exception)\n{\n char\n format[MaxTextExtent],\n keyword[MaxTextExtent],\n tag[MaxTextExtent],\n value[MaxTextExtent];\n\n double\n gamma;\n\n Image\n *image;\n\n int\n c;\n\n MagickBooleanType\n status,\n value_expected;\n\n register PixelPacket\n *q;\n\n register unsigned char\n *p;\n\n register ssize_t\n i,\n x;\n\n ssize_t\n count,\n y;\n\n unsigned char\n *end,\n pixel[4],\n *pixels;\n\n /*\n Open image file.\n */\n assert(image_info != (const ImageInfo *) NULL);\n assert(image_info->signature == MagickSignature);\n if (image_info->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",\n image_info->filename);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickSignature);\n image=AcquireImage(image_info);\n status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);\n if (status == MagickFalse)\n {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n /*\n Decode image header.\n */\n image->columns=0;\n image->rows=0;\n *format='\\0';\n c=ReadBlobByte(image);\n if (c == EOF)\n {\n image=DestroyImage(image);\n return((Image *) NULL);\n }\n while (isgraph(c) && (image->columns == 0) && (image->rows == 0))\n {\n if (c == (int) '#')\n {\n char\n *comment;\n\n register char\n *p;\n\n size_t\n length;\n\n /*\n Read comment-- any text between # and end-of-line.\n */\n length=MaxTextExtent;\n comment=AcquireString((char *) NULL);\n for (p=comment; comment != (char *) NULL; p++)\n {\n c=ReadBlobByte(image);\n if ((c == EOF) || (c == (int) '\\n'))\n break;\n if ((size_t) (p-comment+1) >= length)\n {\n *p='\\0';\n length<<=1;\n comment=(char *) ResizeQuantumMemory(comment,length+\n MaxTextExtent,sizeof(*comment));\n if (comment == (char *) NULL)\n break;\n p=comment+strlen(comment);\n }\n *p=(char) c;\n }\n if (comment == (char *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n *p='\\0';\n (void) SetImageProperty(image,\"comment\",comment);\n comment=DestroyString(comment);\n c=ReadBlobByte(image);\n }\n else\n if (isalnum(c) == MagickFalse)\n c=ReadBlobByte(image);\n else\n {\n register char\n *p;\n\n /*\n Determine a keyword and its value.\n */\n p=keyword;\n do\n {\n if ((size_t) (p-keyword) < (MaxTextExtent-1))\n *p++=c;\n c=ReadBlobByte(image);\n } while (isalnum(c) || (c == '_'));\n *p='\\0';\n value_expected=MagickFalse;\n while ((isspace((int) ((unsigned char) c)) != 0) || (c == '='))\n {\n if (c == '=')\n value_expected=MagickTrue;\n c=ReadBlobByte(image);\n }\n if (LocaleCompare(keyword,\"Y\") == 0)\n value_expected=MagickTrue;\n if (value_expected == MagickFalse)\n continue;\n p=value;\n while ((c != '\\n') && (c != '\\0'))\n {\n if ((size_t) (p-value) < (MaxTextExtent-1))\n *p++=c;\n c=ReadBlobByte(image);\n }\n *p='\\0';\n /*\n Assign a value to the specified keyword.\n */\n switch (*keyword)\n {\n case 'F':\n case 'f':\n {\n if (LocaleCompare(keyword,\"format\") == 0)\n {\n (void) CopyMagickString(format,value,MaxTextExtent);\n break;\n }\n (void) FormatLocaleString(tag,MaxTextExtent,\"hdr:%s\",keyword);\n (void) SetImageProperty(image,tag,value);\n break;\n }\n case 'G':\n case 'g':\n {\n if (LocaleCompare(keyword,\"gamma\") == 0)\n {\n image->gamma=StringToDouble(value,(char **) NULL);\n break;\n }\n (void) FormatLocaleString(tag,MaxTextExtent,\"hdr:%s\",keyword);\n (void) SetImageProperty(image,tag,value);\n break;\n }\n case 'P':\n case 'p':\n {\n if (LocaleCompare(keyword,\"primaries\") == 0)\n {\n float\n chromaticity[6],\n white_point[2];\n\n (void) sscanf(value,\"%g %g %g %g %g %g %g %g\",\n &chromaticity[0],&chromaticity[1],&chromaticity[2],\n &chromaticity[3],&chromaticity[4],&chromaticity[5],\n &white_point[0],&white_point[1]);\n image->chromaticity.red_primary.x=chromaticity[0];\n image->chromaticity.red_primary.y=chromaticity[1];\n image->chromaticity.green_primary.x=chromaticity[2];\n image->chromaticity.green_primary.y=chromaticity[3];\n image->chromaticity.blue_primary.x=chromaticity[4];\n image->chromaticity.blue_primary.y=chromaticity[5];\n image->chromaticity.white_point.x=white_point[0],\n image->chromaticity.white_point.y=white_point[1];\n break;\n }\n (void) FormatLocaleString(tag,MaxTextExtent,\"hdr:%s\",keyword);\n (void) SetImageProperty(image,tag,value);\n break;\n }\n case 'Y':\n case 'y':\n {\n if (strcmp(keyword,\"Y\") == 0)\n {\n int\n height,\n width;\n\n (void) sscanf(value,\"%d +X %d\",&height,&width);\n image->columns=(size_t) width;\n image->rows=(size_t) height;\n break;\n }\n (void) FormatLocaleString(tag,MaxTextExtent,\"hdr:%s\",keyword);\n (void) SetImageProperty(image,tag,value);\n break;\n }\n default:\n {\n (void) FormatLocaleString(tag,MaxTextExtent,\"hdr:%s\",keyword);\n (void) SetImageProperty(image,tag,value);\n break;\n }\n }\n }\n if ((image->columns == 0) && (image->rows == 0))\n while (isspace((int) ((unsigned char) c)) != 0)\n c=ReadBlobByte(image);\n }\n if ((LocaleCompare(format,\"32-bit_rle_rgbe\") != 0) &&\n (LocaleCompare(format,\"32-bit_rle_xyze\") != 0))\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n if ((image->columns == 0) || (image->rows == 0))\n ThrowReaderException(CorruptImageError,\"NegativeOrZeroImageSize\");\n (void) SetImageColorspace(image,RGBColorspace);\n if (LocaleCompare(format,\"32-bit_rle_xyze\") == 0)\n (void) SetImageColorspace(image,XYZColorspace);\n image->compression=(image->columns < 8) || (image->columns > 0x7ffff) ?\n NoCompression : RLECompression;\n if (image_info->ping != MagickFalse)\n {\n (void) CloseBlob(image);\n return(GetFirstImageInList(image));\n }\n /*\n Read RGBE (red+green+blue+exponent) pixels.\n */\n pixels=(unsigned char *) AcquireQuantumMemory(image->columns,4*\n sizeof(*pixels));\n if (pixels == (unsigned char *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n if (image->compression != RLECompression)\n {\n count=ReadBlob(image,4*image->columns*sizeof(*pixels),pixels);\n if (count != (ssize_t) (4*image->columns*sizeof(*pixels)))\n break;\n }\n else\n {\n count=ReadBlob(image,4*sizeof(*pixel),pixel);\n if (count != 4)\n break;\n if ((size_t) ((((size_t) pixel[2]) << 8) | pixel[3]) != image->columns)\n {\n (void) memcpy(pixels,pixel,4*sizeof(*pixel));\n count=ReadBlob(image,4*(image->columns-1)*sizeof(*pixels),pixels+4);\n image->compression=NoCompression;\n }\n else\n {\n p=pixels;\n for (i=0; i < 4; i++)\n {\n end=&pixels[(i+1)*image->columns];\n while (p < end)\n {\n count=ReadBlob(image,2*sizeof(*pixel),pixel);\n if (count < 1)\n break;\n if (pixel[0] > 128)\n {\n count=(ssize_t) pixel[0]-128;\n if ((count == 0) || (count > (ssize_t) (end-p)))\n break;\n while (count-- > 0)\n *p++=pixel[1];\n }\n else\n {\n count=(ssize_t) pixel[0];\n if ((count == 0) || (count > (ssize_t) (end-p)))\n break;\n *p++=pixel[1];\n if (--count > 0)\n {\n count=ReadBlob(image,(size_t) count*sizeof(*p),p);\n if (count < 1)\n break;\n p+=count;\n }\n }\n }\n }\n }\n }\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (PixelPacket *) NULL)\n break;\n i=0;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n if (image->compression == RLECompression)\n {\n pixel[0]=pixels[x];\n pixel[1]=pixels[x+image->columns];\n pixel[2]=pixels[x+2*image->columns];\n pixel[3]=pixels[x+3*image->columns];\n }\n else\n {\n pixel[0]=pixels[i++];\n pixel[1]=pixels[i++];\n pixel[2]=pixels[i++];\n pixel[3]=pixels[i++];\n }\n SetPixelRed(q,0);\n SetPixelGreen(q,0);\n SetPixelBlue(q,0);\n if (pixel[3] != 0)\n {\n gamma=pow(2.0,pixel[3]-(128.0+8.0));\n SetPixelRed(q,ClampToQuantum(QuantumRange*gamma*pixel[0]));\n SetPixelGreen(q,ClampToQuantum(QuantumRange*gamma*pixel[1]));\n SetPixelBlue(q,ClampToQuantum(QuantumRange*gamma*pixel[2]));\n }\n q++;\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,\n image->rows);\n if (status == MagickFalse)\n break;\n }\n pixels=(unsigned char *) RelinquishMagickMemory(pixels);\n if (EOFBlob(image) != MagickFalse)\n ThrowFileException(exception,CorruptImageError,\"UnexpectedEndOfFile\",\n image->filename);\n (void) CloseBlob(image);\n return(GetFirstImageInList(image));\n}\n", + "line": null, + "label": 1, + "cwe": "CWE-119", + "cve": "CVE-2016-10066", + "length": 2662 + }, + { + "index": 48327, + "code": "TIFFWriteEncodedTile(TIFF* tif, uint32 tile, void* data, tmsize_t cc)\n{\n\tstatic const char module[] = \"TIFFWriteEncodedTile\";\n\tTIFFDirectory *td;\n\tuint16 sample;\n uint32 howmany32;\n\n\tif (!WRITECHECKTILES(tif, module))\n\t\treturn ((tmsize_t)(-1));\n\ttd = &tif->tif_dir;\n\tif (tile >= td->td_nstrips) {\n\t\tTIFFErrorExt(tif->tif_clientdata, module, \"Tile %lu out of range, max %lu\",\n\t\t (unsigned long) tile, (unsigned long) td->td_nstrips);\n\t\treturn ((tmsize_t)(-1));\n\t}\n\t/*\n\t * Handle delayed allocation of data buffer. This\n\t * permits it to be sized more intelligently (using\n\t * directory information).\n\t */\n\tif (!BUFFERCHECK(tif))\n\t\treturn ((tmsize_t)(-1));\n\n tif->tif_flags |= TIFF_BUF4WRITE;\n\ttif->tif_curtile = tile;\n\n\tif( td->td_stripbytecount[tile] > 0 )\n {\n /* Make sure that at the first attempt of rewriting the tile, we will have */\n /* more bytes available in the output buffer than the previous byte count, */\n /* so that TIFFAppendToStrip() will detect the overflow when it is called the first */\n /* time if the new compressed tile is bigger than the older one. (GDAL #4771) */\n if( tif->tif_rawdatasize <= (tmsize_t) td->td_stripbytecount[tile] )\n {\n if( !(TIFFWriteBufferSetup(tif, NULL,\n (tmsize_t)TIFFroundup_64((uint64)(td->td_stripbytecount[tile] + 1), 1024))) )\n return ((tmsize_t)(-1));\n }\n\n\t /* Force TIFFAppendToStrip() to consider placing data at end\n of file. */\n tif->tif_curoff = 0;\n }\n\n\ttif->tif_rawcc = 0;\n\ttif->tif_rawcp = tif->tif_rawdata;\n\n\t/* \n\t * Compute tiles per row & per column to compute\n\t * current row and column\n\t */\n howmany32=TIFFhowmany_32(td->td_imagelength, td->td_tilelength);\n if (howmany32 == 0) {\n TIFFErrorExt(tif->tif_clientdata,module,\"Zero tiles\");\n return ((tmsize_t)(-1));\n }\n\ttif->tif_row = (tile % howmany32) * td->td_tilelength;\n howmany32=TIFFhowmany_32(td->td_imagewidth, td->td_tilewidth);\n if (howmany32 == 0) {\n TIFFErrorExt(tif->tif_clientdata,module,\"Zero tiles\");\n return ((tmsize_t)(-1));\n }\n\ttif->tif_col = (tile % howmany32) * td->td_tilewidth;\n\n\tif ((tif->tif_flags & TIFF_CODERSETUP) == 0) {\n\t\tif (!(*tif->tif_setupencode)(tif))\n\t\t\treturn ((tmsize_t)(-1));\n\t\ttif->tif_flags |= TIFF_CODERSETUP;\n\t}\n\ttif->tif_flags &= ~TIFF_POSTENCODE;\n\n\t/*\n\t * Clamp write amount to the tile size. This is mostly\n\t * done so that callers can pass in some large number\n\t * (e.g. -1) and have the tile size used instead.\n\t */\n\tif ( cc < 1 || cc > tif->tif_tilesize)\n\t\tcc = tif->tif_tilesize;\n\n /* shortcut to avoid an extra memcpy() */\n if( td->td_compression == COMPRESSION_NONE )\n {\n /* swab if needed - note that source buffer will be altered */\n tif->tif_postdecode( tif, (uint8*) data, cc );\n\n if (!isFillOrder(tif, td->td_fillorder) &&\n (tif->tif_flags & TIFF_NOBITREV) == 0)\n TIFFReverseBits((uint8*) data, cc);\n\n if (cc > 0 &&\n !TIFFAppendToStrip(tif, tile, (uint8*) data, cc))\n return ((tmsize_t) -1);\n return (cc);\n }\n\n sample = (uint16)(tile/td->td_stripsperimage);\n if (!(*tif->tif_preencode)(tif, sample))\n return ((tmsize_t)(-1));\n /* swab if needed - note that source buffer will be altered */\n\ttif->tif_postdecode( tif, (uint8*) data, cc );\n\n\tif (!(*tif->tif_encodetile)(tif, (uint8*) data, cc, sample))\n\t\treturn ((tmsize_t) -1);\n\tif (!(*tif->tif_postencode)(tif))\n\t\treturn ((tmsize_t)(-1));\n\tif (!isFillOrder(tif, td->td_fillorder) &&\n\t (tif->tif_flags & TIFF_NOBITREV) == 0)\n\t\tTIFFReverseBits((uint8*)tif->tif_rawdata, tif->tif_rawcc);\n\tif (tif->tif_rawcc > 0 && !TIFFAppendToStrip(tif, tile,\n\t tif->tif_rawdata, tif->tif_rawcc))\n\t\treturn ((tmsize_t)(-1));\n\ttif->tif_rawcc = 0;\n\ttif->tif_rawcp = tif->tif_rawdata;\n\treturn (cc);\n}\n", + "line": null, + "label": 0, + "cwe": "CWE-787", + "cve": "CVE-2016-9537", + "length": 1216 + }, + { + "index": 38247, + "code": "void sk_decode_filter(struct sock_filter *filt, struct sock_filter *to)\n{\n\tstatic const u16 decodes[] = {\n\t\t[BPF_S_ALU_ADD_K]\t= BPF_ALU|BPF_ADD|BPF_K,\n\t\t[BPF_S_ALU_ADD_X]\t= BPF_ALU|BPF_ADD|BPF_X,\n\t\t[BPF_S_ALU_SUB_K]\t= BPF_ALU|BPF_SUB|BPF_K,\n\t\t[BPF_S_ALU_SUB_X]\t= BPF_ALU|BPF_SUB|BPF_X,\n\t\t[BPF_S_ALU_MUL_K]\t= BPF_ALU|BPF_MUL|BPF_K,\n\t\t[BPF_S_ALU_MUL_X]\t= BPF_ALU|BPF_MUL|BPF_X,\n\t\t[BPF_S_ALU_DIV_X]\t= BPF_ALU|BPF_DIV|BPF_X,\n\t\t[BPF_S_ALU_MOD_K]\t= BPF_ALU|BPF_MOD|BPF_K,\n\t\t[BPF_S_ALU_MOD_X]\t= BPF_ALU|BPF_MOD|BPF_X,\n\t\t[BPF_S_ALU_AND_K]\t= BPF_ALU|BPF_AND|BPF_K,\n\t\t[BPF_S_ALU_AND_X]\t= BPF_ALU|BPF_AND|BPF_X,\n\t\t[BPF_S_ALU_OR_K]\t= BPF_ALU|BPF_OR|BPF_K,\n\t\t[BPF_S_ALU_OR_X]\t= BPF_ALU|BPF_OR|BPF_X,\n\t\t[BPF_S_ALU_XOR_K]\t= BPF_ALU|BPF_XOR|BPF_K,\n\t\t[BPF_S_ALU_XOR_X]\t= BPF_ALU|BPF_XOR|BPF_X,\n\t\t[BPF_S_ALU_LSH_K]\t= BPF_ALU|BPF_LSH|BPF_K,\n\t\t[BPF_S_ALU_LSH_X]\t= BPF_ALU|BPF_LSH|BPF_X,\n\t\t[BPF_S_ALU_RSH_K]\t= BPF_ALU|BPF_RSH|BPF_K,\n\t\t[BPF_S_ALU_RSH_X]\t= BPF_ALU|BPF_RSH|BPF_X,\n\t\t[BPF_S_ALU_NEG]\t\t= BPF_ALU|BPF_NEG,\n\t\t[BPF_S_LD_W_ABS]\t= BPF_LD|BPF_W|BPF_ABS,\n\t\t[BPF_S_LD_H_ABS]\t= BPF_LD|BPF_H|BPF_ABS,\n\t\t[BPF_S_LD_B_ABS]\t= BPF_LD|BPF_B|BPF_ABS,\n\t\t[BPF_S_ANC_PROTOCOL]\t= BPF_LD|BPF_B|BPF_ABS,\n\t\t[BPF_S_ANC_PKTTYPE]\t= BPF_LD|BPF_B|BPF_ABS,\n\t\t[BPF_S_ANC_IFINDEX]\t= BPF_LD|BPF_B|BPF_ABS,\n\t\t[BPF_S_ANC_NLATTR]\t= BPF_LD|BPF_B|BPF_ABS,\n\t\t[BPF_S_ANC_NLATTR_NEST]\t= BPF_LD|BPF_B|BPF_ABS,\n\t\t[BPF_S_ANC_MARK]\t= BPF_LD|BPF_B|BPF_ABS,\n\t\t[BPF_S_ANC_QUEUE]\t= BPF_LD|BPF_B|BPF_ABS,\n\t\t[BPF_S_ANC_HATYPE]\t= BPF_LD|BPF_B|BPF_ABS,\n\t\t[BPF_S_ANC_RXHASH]\t= BPF_LD|BPF_B|BPF_ABS,\n\t\t[BPF_S_ANC_CPU]\t\t= BPF_LD|BPF_B|BPF_ABS,\n\t\t[BPF_S_ANC_ALU_XOR_X]\t= BPF_LD|BPF_B|BPF_ABS,\n\t\t[BPF_S_ANC_SECCOMP_LD_W] = BPF_LD|BPF_B|BPF_ABS,\n\t\t[BPF_S_ANC_VLAN_TAG]\t= BPF_LD|BPF_B|BPF_ABS,\n\t\t[BPF_S_ANC_VLAN_TAG_PRESENT] = BPF_LD|BPF_B|BPF_ABS,\n\t\t[BPF_S_ANC_PAY_OFFSET]\t= BPF_LD|BPF_B|BPF_ABS,\n\t\t[BPF_S_LD_W_LEN]\t= BPF_LD|BPF_W|BPF_LEN,\n\t\t[BPF_S_LD_W_IND]\t= BPF_LD|BPF_W|BPF_IND,\n\t\t[BPF_S_LD_H_IND]\t= BPF_LD|BPF_H|BPF_IND,\n\t\t[BPF_S_LD_B_IND]\t= BPF_LD|BPF_B|BPF_IND,\n\t\t[BPF_S_LD_IMM]\t\t= BPF_LD|BPF_IMM,\n\t\t[BPF_S_LDX_W_LEN]\t= BPF_LDX|BPF_W|BPF_LEN,\n\t\t[BPF_S_LDX_B_MSH]\t= BPF_LDX|BPF_B|BPF_MSH,\n\t\t[BPF_S_LDX_IMM]\t\t= BPF_LDX|BPF_IMM,\n\t\t[BPF_S_MISC_TAX]\t= BPF_MISC|BPF_TAX,\n\t\t[BPF_S_MISC_TXA]\t= BPF_MISC|BPF_TXA,\n\t\t[BPF_S_RET_K]\t\t= BPF_RET|BPF_K,\n\t\t[BPF_S_RET_A]\t\t= BPF_RET|BPF_A,\n\t\t[BPF_S_ALU_DIV_K]\t= BPF_ALU|BPF_DIV|BPF_K,\n\t\t[BPF_S_LD_MEM]\t\t= BPF_LD|BPF_MEM,\n\t\t[BPF_S_LDX_MEM]\t\t= BPF_LDX|BPF_MEM,\n\t\t[BPF_S_ST]\t\t= BPF_ST,\n\t\t[BPF_S_STX]\t\t= BPF_STX,\n\t\t[BPF_S_JMP_JA]\t\t= BPF_JMP|BPF_JA,\n\t\t[BPF_S_JMP_JEQ_K]\t= BPF_JMP|BPF_JEQ|BPF_K,\n\t\t[BPF_S_JMP_JEQ_X]\t= BPF_JMP|BPF_JEQ|BPF_X,\n\t\t[BPF_S_JMP_JGE_K]\t= BPF_JMP|BPF_JGE|BPF_K,\n\t\t[BPF_S_JMP_JGE_X]\t= BPF_JMP|BPF_JGE|BPF_X,\n\t\t[BPF_S_JMP_JGT_K]\t= BPF_JMP|BPF_JGT|BPF_K,\n\t\t[BPF_S_JMP_JGT_X]\t= BPF_JMP|BPF_JGT|BPF_X,\n\t\t[BPF_S_JMP_JSET_K]\t= BPF_JMP|BPF_JSET|BPF_K,\n\t\t[BPF_S_JMP_JSET_X]\t= BPF_JMP|BPF_JSET|BPF_X,\n\t};\n\tu16 code;\n\n\tcode = filt->code;\n\n\tto->code = decodes[code];\n\tto->jt = filt->jt;\n\tto->jf = filt->jf;\n\tto->k = filt->k;\n}\n", + "line": null, + "label": 0, + "cwe": "CWE-189", + "cve": "CVE-2014-3145", + "length": 1611 + }, + { + "index": 182932, + "code": "void color_apply_icc_profile(opj_image_t *image)\n{\n cmsHPROFILE in_prof, out_prof;\n cmsHTRANSFORM transform;\n cmsColorSpaceSignature in_space, out_space;\n cmsUInt32Number intent, in_type, out_type;\n int *r, *g, *b;\n size_t nr_samples, i, max, max_w, max_h;\n int prec, ok = 0;\n OPJ_COLOR_SPACE new_space;\n\n in_prof = cmsOpenProfileFromMem(image->icc_profile_buf, image->icc_profile_len);\n#ifdef DEBUG_PROFILE\n FILE *icm = fopen(\"debug.icm\", \"wb\");\n fwrite(image->icc_profile_buf, 1, image->icc_profile_len, icm);\n fclose(icm);\n#endif\n\n if (in_prof == NULL) {\n return;\n }\n\n in_space = cmsGetPCS(in_prof);\n out_space = cmsGetColorSpace(in_prof);\n intent = cmsGetHeaderRenderingIntent(in_prof);\n\n\n max_w = image->comps[0].w;\n max_h = image->comps[0].h;\n prec = (int)image->comps[0].prec;\n\n if (out_space == cmsSigRgbData) { /* enumCS 16 */\n unsigned int i, nr_comp = image->numcomps;\n\n if (nr_comp > 4) {\n nr_comp = 4;\n }\n for (i = 1; i < nr_comp; ++i) { /* AFL test */\n if (image->comps[0].dx != image->comps[i].dx) {\n break;\n }\n\n if (image->comps[0].dy != image->comps[i].dy) {\n break;\n }\n\n if (image->comps[0].prec != image->comps[i].prec) {\n break;\n }\n\n if (image->comps[0].sgnd != image->comps[i].sgnd) {\n break;\n }\n\n }\n if (i != nr_comp) {\n cmsCloseProfile(in_prof);\n return;\n }\n\n if (prec <= 8) {\n in_type = TYPE_RGB_8;\n out_type = TYPE_RGB_8;\n } else {\n in_type = TYPE_RGB_16;\n out_type = TYPE_RGB_16;\n }\n out_prof = cmsCreate_sRGBProfile();\n new_space = OPJ_CLRSPC_SRGB;\n } else if (out_space == cmsSigGrayData) { /* enumCS 17 */\n in_type = TYPE_GRAY_8;\n out_type = TYPE_RGB_8;\n out_prof = cmsCreate_sRGBProfile();\n new_space = OPJ_CLRSPC_SRGB;\n } else if (out_space == cmsSigYCbCrData) { /* enumCS 18 */\n in_type = TYPE_YCbCr_16;\n out_type = TYPE_RGB_16;\n out_prof = cmsCreate_sRGBProfile();\n new_space = OPJ_CLRSPC_SRGB;\n } else {\n#ifdef DEBUG_PROFILE\n fprintf(stderr, \"%s:%d: color_apply_icc_profile\\n\\tICC Profile has unknown \"\n \"output colorspace(%#x)(%c%c%c%c)\\n\\tICC Profile ignored.\\n\",\n __FILE__, __LINE__, out_space,\n (out_space >> 24) & 0xff, (out_space >> 16) & 0xff,\n (out_space >> 8) & 0xff, out_space & 0xff);\n#endif\n cmsCloseProfile(in_prof);\n\n return;\n }\n if (out_prof == NULL) {\n cmsCloseProfile(in_prof);\n return;\n }\n\n#ifdef DEBUG_PROFILE\n fprintf(stderr,\n \"%s:%d:color_apply_icc_profile\\n\\tchannels(%d) prec(%d) w(%d) h(%d)\"\n \"\\n\\tprofile: in(%p) out(%p)\\n\", __FILE__, __LINE__, image->numcomps, prec,\n max_w, max_h, (void*)in_prof, (void*)out_prof);\n\n fprintf(stderr, \"\\trender_intent (%u)\\n\\t\"\n \"color_space: in(%#x)(%c%c%c%c) out:(%#x)(%c%c%c%c)\\n\\t\"\n \" type: in(%u) out:(%u)\\n\",\n intent,\n in_space,\n (in_space >> 24) & 0xff, (in_space >> 16) & 0xff,\n (in_space >> 8) & 0xff, in_space & 0xff,\n\n out_space,\n (out_space >> 24) & 0xff, (out_space >> 16) & 0xff,\n (out_space >> 8) & 0xff, out_space & 0xff,\n\n in_type, out_type\n );\n#else\n (void)prec;\n (void)in_space;\n#endif /* DEBUG_PROFILE */\n\n transform = cmsCreateTransform(in_prof, in_type, out_prof, out_type, intent, 0);\n\n#ifdef OPJ_HAVE_LIBLCMS2\n /* Possible for: LCMS_VERSION >= 2000 :*/\n cmsCloseProfile(in_prof);\n cmsCloseProfile(out_prof);\n#endif\n\n if (transform == NULL) {\n#ifdef DEBUG_PROFILE\n fprintf(stderr, \"%s:%d:color_apply_icc_profile\\n\\tcmsCreateTransform failed. \"\n \"ICC Profile ignored.\\n\", __FILE__, __LINE__);\n#endif\n\n#ifdef OPJ_HAVE_LIBLCMS1\n cmsCloseProfile(in_prof);\n cmsCloseProfile(out_prof);\n#endif\n return;\n }\n \n if (image->numcomps > 2) { /* RGB, RGBA */\n if (prec <= 8) {\n unsigned char *inbuf, *outbuf, *in, *out;\n max = max_w * max_h;\n nr_samples = (size_t)(max * 3U * sizeof(unsigned char));\n in = inbuf = (unsigned char*)opj_image_data_alloc(nr_samples);\n out = outbuf = (unsigned char*)opj_image_data_alloc(nr_samples);\n if (inbuf == NULL || outbuf == NULL) {\n goto fails0;\n }\n r = image->comps[0].data;\n g = image->comps[1].data;\n b = image->comps[2].data;\n for (i = 0U; i < max; ++i) {\n *in++ = (unsigned char) * r++;\n *in++ = (unsigned char) * g++;\n *in++ = (unsigned char) * b++;\n }\n cmsDoTransform(transform, inbuf, outbuf, (cmsUInt32Number)max);\n r = image->comps[0].data;\n g = image->comps[1].data;\n b = image->comps[2].data;\n for (i = 0U; i < max; ++i) {\n *r++ = (int) * out++;\n *g++ = (int) * out++;\n *b++ = (int) * out++;\n }\n ok = 1;\n \n fails0:\n opj_image_data_free(inbuf);\n opj_image_data_free(outbuf);\n } else { /* prec > 8 */\n unsigned short *inbuf, *outbuf, *in, *out;\n max = max_w * max_h;\n nr_samples = (size_t)(max * 3U * sizeof(unsigned short));\n in = inbuf = (unsigned short*)opj_image_data_alloc(nr_samples);\n out = outbuf = (unsigned short*)opj_image_data_alloc(nr_samples);\n if (inbuf == NULL || outbuf == NULL) {\n goto fails1;\n }\n r = image->comps[0].data;\n g = image->comps[1].data;\n b = image->comps[2].data;\n for (i = 0U ; i < max; ++i) {\n *in++ = (unsigned short) * r++;\n *in++ = (unsigned short) * g++;\n *in++ = (unsigned short) * b++;\n }\n cmsDoTransform(transform, inbuf, outbuf, (cmsUInt32Number)max);\n r = image->comps[0].data;\n g = image->comps[1].data;\n b = image->comps[2].data;\n for (i = 0; i < max; ++i) {\n *r++ = (int) * out++;\n *g++ = (int) * out++;\n *b++ = (int) * out++;\n }\n ok = 1;\n \n fails1:\n opj_image_data_free(inbuf);\n opj_image_data_free(outbuf);\n }\n } else { /* image->numcomps <= 2 : GRAY, GRAYA */\n if (prec <= 8) {\n unsigned char *in, *inbuf, *out, *outbuf;\n opj_image_comp_t *new_comps;\n\n max = max_w * max_h;\n nr_samples = (size_t)(max * 3 * sizeof(unsigned char));\n in = inbuf = (unsigned char*)opj_image_data_alloc(nr_samples);\n out = outbuf = (unsigned char*)opj_image_data_alloc(nr_samples);\n g = (int*)opj_image_data_alloc((size_t)max * sizeof(int));\n b = (int*)opj_image_data_alloc((size_t)max * sizeof(int));\n\n if (inbuf == NULL || outbuf == NULL || g == NULL || b == NULL) {\n goto fails2;\n }\n\n new_comps = (opj_image_comp_t*)realloc(image->comps,\n (image->numcomps + 2) * sizeof(opj_image_comp_t));\n\n if (new_comps == NULL) {\n goto fails2;\n }\n\n image->comps = new_comps;\n\n if (image->numcomps == 2) {\n image->comps[3] = image->comps[1];\n }\n\n image->comps[1] = image->comps[0];\n image->comps[2] = image->comps[0];\n\n image->comps[1].data = g;\n image->comps[2].data = b;\n\n image->numcomps += 2;\n\n r = image->comps[0].data;\n\n for (i = 0U; i < max; ++i) {\n *in++ = (unsigned char) * r++;\n }\n cmsDoTransform(transform, inbuf, outbuf, (cmsUInt32Number)max);\n\n r = image->comps[0].data;\n g = image->comps[1].data;\n b = image->comps[2].data;\n\n for (i = 0U; i < max; ++i) {\n *r++ = (int) * out++;\n *g++ = (int) * out++;\n *b++ = (int) * out++;\n }\n r = g = b = NULL;\n ok = 1;\n\nfails2:\n opj_image_data_free(inbuf);\n opj_image_data_free(outbuf);\n opj_image_data_free(g);\n opj_image_data_free(b);\n } else { /* prec > 8 */\n unsigned short *in, *inbuf, *out, *outbuf;\n opj_image_comp_t *new_comps;\n\n max = max_w * max_h;\n nr_samples = (size_t)(max * 3U * sizeof(unsigned short));\n in = inbuf = (unsigned short*)opj_image_data_alloc(nr_samples);\n out = outbuf = (unsigned short*)opj_image_data_alloc(nr_samples);\n g = (int*)opj_image_data_alloc((size_t)max * sizeof(int));\n b = (int*)opj_image_data_alloc((size_t)max * sizeof(int));\n\n if (inbuf == NULL || outbuf == NULL || g == NULL || b == NULL) {\n goto fails3;\n }\n\n new_comps = (opj_image_comp_t*)realloc(image->comps,\n (image->numcomps + 2) * sizeof(opj_image_comp_t));\n\n if (new_comps == NULL) {\n goto fails3;\n }\n\n image->comps = new_comps;\n\n if (image->numcomps == 2) {\n image->comps[3] = image->comps[1];\n }\n\n image->comps[1] = image->comps[0];\n image->comps[2] = image->comps[0];\n\n image->comps[1].data = g;\n image->comps[2].data = b;\n\n image->numcomps += 2;\n\n r = image->comps[0].data;\n\n for (i = 0U; i < max; ++i) {\n *in++ = (unsigned short) * r++;\n }\n cmsDoTransform(transform, inbuf, outbuf, (cmsUInt32Number)max);\n\n r = image->comps[0].data;\n g = image->comps[1].data;\n b = image->comps[2].data;\n\n for (i = 0; i < max; ++i) {\n *r++ = (int) * out++;\n *g++ = (int) * out++;\n *b++ = (int) * out++;\n }\n r = g = b = NULL;\n ok = 1;\n\nfails3:\n opj_image_data_free(inbuf);\n opj_image_data_free(outbuf);\n opj_image_data_free(g);\n opj_image_data_free(b);\n }\n }/* if(image->numcomps > 2) */\n\n cmsDeleteTransform(transform);\n\n#ifdef OPJ_HAVE_LIBLCMS1\n cmsCloseProfile(in_prof);\n cmsCloseProfile(out_prof);\n#endif\n if (ok) {\n image->color_space = new_space;\n }\n}/* color_apply_icc_profile() */\n", + "line": " if (prec <= 8) {\n unsigned char *inbuf, *outbuf, *in, *out;\n max = max_w * max_h;\n nr_samples = (size_t)(max * 3U * sizeof(unsigned char));\n in = inbuf = (unsigned char*)opj_image_data_alloc(nr_samples);\n out = outbuf = (unsigned char*)opj_image_data_alloc(nr_samples);\n if (inbuf == NULL || outbuf == NULL) {\n goto fails0;\n }\n r = image->comps[0].data;\n g = image->comps[1].data;\n b = image->comps[2].data;\n for (i = 0U; i < max; ++i) {\n *in++ = (unsigned char) * r++;\n *in++ = (unsigned char) * g++;\n *in++ = (unsigned char) * b++;\n }\n cmsDoTransform(transform, inbuf, outbuf, (cmsUInt32Number)max);\n r = image->comps[0].data;\n g = image->comps[1].data;\n b = image->comps[2].data;\n for (i = 0U; i < max; ++i) {\n *r++ = (int) * out++;\n *g++ = (int) * out++;\n *b++ = (int) * out++;\n }\n ok = 1;\n opj_image_data_free(inbuf);\n opj_image_data_free(outbuf);\n } else { /* prec > 8 */\n unsigned short *inbuf, *outbuf, *in, *out;\n max = max_w * max_h;\n nr_samples = (size_t)(max * 3U * sizeof(unsigned short));\n in = inbuf = (unsigned short*)opj_image_data_alloc(nr_samples);\n out = outbuf = (unsigned short*)opj_image_data_alloc(nr_samples);\n if (inbuf == NULL || outbuf == NULL) {\n goto fails1;\n }\n r = image->comps[0].data;\n g = image->comps[1].data;\n b = image->comps[2].data;\n for (i = 0U ; i < max; ++i) {\n *in++ = (unsigned short) * r++;\n *in++ = (unsigned short) * g++;\n *in++ = (unsigned short) * b++;\n }\n cmsDoTransform(transform, inbuf, outbuf, (cmsUInt32Number)max);\n r = image->comps[0].data;\n g = image->comps[1].data;\n b = image->comps[2].data;\n for (i = 0; i < max; ++i) {\n *r++ = (int) * out++;\n *g++ = (int) * out++;\n *b++ = (int) * out++;\n }\n ok = 1;\n opj_image_data_free(inbuf);\n opj_image_data_free(outbuf);\n", + "label": 1, + "cwe": "CWE-119", + "cve": "CVE-2018-21010", + "length": 3071 + }, + { + "index": 178042, + "code": " static char *ps_files_path_create(char *buf, size_t buflen, ps_files *data, const char *key)\n {\n{\n\tsize_t len;\n\tconst char *p;\n\tchar c;\n\tint ret = 1;\n\n\tfor (p = key; (c = *p); p++) {\n\t\t/* valid characters are a..z,A..Z,0..9 */\n\t\tif (!((c >= 'a' && c <= 'z')\n\t\t\t\t|| (c >= 'A' && c <= 'Z')\n\t\t\t\t|| (c >= '0' && c <= '9')\n\t\t\t\t|| c == ','\n\t\t\t\t|| c == '-')) {\n\t\t\tret = 0;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tlen = p - key;\n\n\t/* Somewhat arbitrary length limit here, but should be way more than\n\t anyone needs and avoids file-level warnings later on if we exceed MAX_PATH */\n\tif (len == 0 || len > 128) {\n\t\tret = 0;\n\t}\n\n\treturn ret;\n}\n\nstatic char *ps_files_path_create(char *buf, size_t buflen, ps_files *data, const char *key)\n{\n\tsize_t key_len;\n\tconst char *p;\n\tint i;\n\tint n;\n\n\tkey_len = strlen(key);\n\tif (key_len <= data->dirdepth ||\n\t\tbuflen < (strlen(data->basedir) + 2 * data->dirdepth + key_len + 5 + sizeof(FILE_PREFIX))) {\n\t\treturn NULL;\n\t}\n\n\tp = key;\n\tmemcpy(buf, data->basedir, data->basedir_len);\n\tn = data->basedir_len;\n\tbuf[n++] = PHP_DIR_SEPARATOR;\n\tfor (i = 0; i < (int)data->dirdepth; i++) {\n\t\tbuf[n++] = *p++;\n\t\tbuf[n++] = PHP_DIR_SEPARATOR;\n\t}\n\tmemcpy(buf + n, FILE_PREFIX, sizeof(FILE_PREFIX) - 1);\n\tn += sizeof(FILE_PREFIX) - 1;\n\tmemcpy(buf + n, key, key_len);\n\tn += key_len;\n \n ps_files_close(data);\n \n if (!ps_files_valid_key(key)) {\n php_error_docref(NULL TSRMLS_CC, E_WARNING, \"The session id is too long or contains illegal characters, valid characters are a-z, A-Z, 0-9 and '-,'\");\n PS(invalid_session_id) = 1;\n return;\n }\n if (!ps_files_path_create(buf, sizeof(buf), data, key)) {\n return;\n }\n\tif (data->fd != -1) {\n#ifdef PHP_WIN32\n\t\t/* On Win32 locked files that are closed without being explicitly unlocked\n\t\t will be unlocked only when \"system resources become available\". */\n\t\tflock(data->fd, LOCK_UN);\n#endif\n\t\tclose(data->fd);\n\t\tdata->fd = -1;\n\t}\n}\n\nstatic void ps_files_open(ps_files *data, const char *key TSRMLS_DC)\n{\n\tchar buf[MAXPATHLEN];\n\n\tif (data->fd < 0 || !data->lastkey || strcmp(key, data->lastkey)) {\n\t\tif (data->lastkey) {\n\t\t\tefree(data->lastkey);\n\t\t\tdata->lastkey = NULL;\n\t\t}\n\n\t\tps_files_close(data);\n\n\t\tif (!ps_files_valid_key(key)) {\n\t\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING, \"The session id is too long or contains illegal characters, valid characters are a-z, A-Z, 0-9 and '-,'\");\n\t\t\tPS(invalid_session_id) = 1;\n\t\t\treturn;\n\t\t}\n\t\tif (!ps_files_path_create(buf, sizeof(buf), data, key)) {\n\t\t\treturn;\n\t\t}\n\n\t\tdata->lastkey = estrdup(key);\n\n\t\tdata->fd = VCWD_OPEN_MODE(buf, O_CREAT | O_RDWR | O_BINARY, data->filemode);\n\n\t\tif (data->fd != -1) {\n#ifndef PHP_WIN32\n\t\t\t/* check to make sure that the opened file is not a symlink, linking to data outside of allowable dirs */\n\t\t\tif (PG(open_basedir)) {\n\t\t\t\tstruct stat sbuf;\n\n\t\t\t\tif (fstat(data->fd, &sbuf)) {\n\t\t\t\t\tclose(data->fd);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (S_ISLNK(sbuf.st_mode) && php_check_open_basedir(buf TSRMLS_CC)) {\n\t\t\t\t\tclose(data->fd);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n#endif\n\t\t\tflock(data->fd, LOCK_EX);\n\n#ifdef F_SETFD\n# ifndef FD_CLOEXEC\n# define FD_CLOEXEC 1\n# endif\n\t\t\tif (fcntl(data->fd, F_SETFD, FD_CLOEXEC)) {\n\t\t\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING, \"fcntl(%d, F_SETFD, FD_CLOEXEC) failed: %s (%d)\", data->fd, strerror(errno), errno);\n\t\t\t}\n#endif\n\t\t} else {\n\t\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING, \"open(%s, O_RDWR) failed: %s (%d)\", buf, strerror(errno), errno);\n\t\t}\n\t}\n}\n\nstatic int ps_files_cleanup_dir(const char *dirname, int maxlifetime TSRMLS_DC)\n{\n\tDIR *dir;\n\tchar dentry[sizeof(struct dirent) + MAXPATHLEN];\n\tstruct dirent *entry = (struct dirent *) &dentry;\n\tstruct stat sbuf;\n\tchar buf[MAXPATHLEN];\n\ttime_t now;\n\tint nrdels = 0;\n\tsize_t dirname_len;\n\n\tdir = opendir(dirname);\n\tif (!dir) {\n\t\tphp_error_docref(NULL TSRMLS_CC, E_NOTICE, \"ps_files_cleanup_dir: opendir(%s) failed: %s (%d)\", dirname, strerror(errno), errno);\n\t\treturn (0);\n\t}\n\n\ttime(&now);\n\n return (nrdels);\n }\n \n #define PS_FILES_DATA ps_files *data = PS_GET_MOD_DATA()\n \n PS_OPEN_FUNC(files)\n\t\t\t\t\t\t(now - sbuf.st_mtime) > maxlifetime) {\n\t\t\t\t\tVCWD_UNLINK(buf);\n\t\t\t\t\tnrdels++;\n\t\t\t\t}\n\t\t\t}\n", + "line": " if (!ps_files_valid_key(key)) {\n PS(invalid_session_id) = 1;\n", + "label": 1, + "cwe": "CWE-264", + "cve": "CVE-2011-4718", + "length": 1269 + }, + { + "index": 181852, + "code": "static MagickBooleanType WriteTXTImage(const ImageInfo *image_info,Image *image,\n ExceptionInfo *exception)\n{\n char\n buffer[MagickPathExtent],\n colorspace[MagickPathExtent],\n tuple[MagickPathExtent];\n\n MagickBooleanType\n status;\n\n MagickOffsetType\n scene;\n\n PixelInfo\n pixel;\n\n register const Quantum\n *p;\n\n register ssize_t\n x;\n\n ssize_t\n y;\n\n /*\n Open output image file.\n */\n assert(image_info != (const ImageInfo *) NULL);\n assert(image_info->signature == MagickCoreSignature);\n assert(image != (Image *) NULL);\n assert(image->signature == MagickCoreSignature);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",image->filename);\n status=OpenBlob(image_info,image,WriteBlobMode,exception);\n if (status == MagickFalse)\n return(status);\n scene=0;\n do\n {\n ComplianceType\n compliance;\n\n const char\n *value;\n\n (void) CopyMagickString(colorspace,CommandOptionToMnemonic(\n MagickColorspaceOptions,(ssize_t) image->colorspace),MagickPathExtent);\n LocaleLower(colorspace);\n image->depth=GetImageQuantumDepth(image,MagickTrue);\n if (image->alpha_trait != UndefinedPixelTrait)\n (void) ConcatenateMagickString(colorspace,\"a\",MagickPathExtent);\n compliance=NoCompliance;\n value=GetImageOption(image_info,\"txt:compliance\");\n if (value != (char *) NULL)\n compliance=(ComplianceType) ParseCommandOption(MagickComplianceOptions,\n MagickFalse,value);\n if (LocaleCompare(image_info->magick,\"SPARSE-COLOR\") != 0)\n {\n size_t\n depth;\n\n depth=compliance == SVGCompliance ? image->depth :\n MAGICKCORE_QUANTUM_DEPTH;\n (void) FormatLocaleString(buffer,MagickPathExtent,\n \"# ImageMagick pixel enumeration: %.20g,%.20g,%.20g,%s\\n\",(double)\n image->columns,(double) image->rows,(double) ((MagickOffsetType)\n GetQuantumRange(depth)),colorspace);\n (void) WriteBlobString(image,buffer);\n }\n GetPixelInfo(image,&pixel);\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n p=GetVirtualPixels(image,0,y,image->columns,1,exception);\n if (p == (const Quantum *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n GetPixelInfoPixel(image,p,&pixel);\n if (pixel.colorspace == LabColorspace)\n {\n pixel.green-=(QuantumRange+1)/2.0;\n pixel.blue-=(QuantumRange+1)/2.0;\n }\n if (LocaleCompare(image_info->magick,\"SPARSE-COLOR\") == 0)\n {\n /*\n Sparse-color format.\n */\n if (GetPixelAlpha(image,p) == (Quantum) OpaqueAlpha)\n {\n GetColorTuple(&pixel,MagickFalse,tuple);\n (void) FormatLocaleString(buffer,MagickPathExtent,\n \"%.20g,%.20g,\",(double) x,(double) y);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,tuple);\n (void) WriteBlobString(image,\" \");\n }\n p+=GetPixelChannels(image);\n continue;\n }\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g,%.20g: \",\n (double) x,(double) y);\n (void) WriteBlobString(image,buffer);\n (void) CopyMagickString(tuple,\"(\",MagickPathExtent);\n if (pixel.colorspace == GRAYColorspace)\n ConcatenateColorComponent(&pixel,GrayPixelChannel,compliance,\n tuple);\n else\n {\n ConcatenateColorComponent(&pixel,RedPixelChannel,compliance,tuple);\n (void) ConcatenateMagickString(tuple,\",\",MagickPathExtent);\n ConcatenateColorComponent(&pixel,GreenPixelChannel,compliance,\n tuple);\n (void) ConcatenateMagickString(tuple,\",\",MagickPathExtent);\n ConcatenateColorComponent(&pixel,BluePixelChannel,compliance,tuple);\n }\n if (pixel.colorspace == CMYKColorspace)\n {\n (void) ConcatenateMagickString(tuple,\",\",MagickPathExtent);\n ConcatenateColorComponent(&pixel,BlackPixelChannel,compliance,\n tuple);\n }\n if (pixel.alpha_trait != UndefinedPixelTrait)\n {\n (void) ConcatenateMagickString(tuple,\",\",MagickPathExtent);\n ConcatenateColorComponent(&pixel,AlphaPixelChannel,compliance,\n tuple);\n }\n (void) ConcatenateMagickString(tuple,\")\",MagickPathExtent);\n (void) WriteBlobString(image,tuple);\n (void) WriteBlobString(image,\" \");\n GetColorTuple(&pixel,MagickTrue,tuple);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%s\",tuple);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\" \");\n (void) QueryColorname(image,&pixel,SVGCompliance,tuple,exception);\n (void) WriteBlobString(image,tuple);\n (void) WriteBlobString(image,\"\\n\");\n p+=GetPixelChannels(image);\n }\n status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,\n image->rows);\n if (status == MagickFalse)\n break;\n }\n if (GetNextImageInList(image) == (Image *) NULL)\n break;\n image=SyncNextImageInList(image);\n status=SetImageProgress(image,SaveImagesTag,scene++,\n GetImageListLength(image));\n if (status == MagickFalse)\n break;\n } while (image_info->adjoin != MagickFalse);\n (void) CloseBlob(image);\n return(MagickTrue);\n}\n", + "line": " ConcatenateColorComponent(&pixel,GrayPixelChannel,compliance,\n tuple);\n", + "label": 1, + "cwe": "CWE-476", + "cve": "CVE-2016-9559", + "length": 1349 + }, + { + "index": 21372, + "code": "SYSCALL_DEFINE2(swapon, const char __user *, specialfile, int, swap_flags)\n{\n\tstruct swap_info_struct *p;\n\tchar *name;\n\tstruct file *swap_file = NULL;\n\tstruct address_space *mapping;\n\tint i;\n\tint prio;\n\tint error;\n\tunion swap_header *swap_header;\n\tint nr_extents;\n\tsector_t span;\n\tunsigned long maxpages;\n\tunsigned char *swap_map = NULL;\n\tstruct page *page = NULL;\n\tstruct inode *inode = NULL;\n\n\tif (!capable(CAP_SYS_ADMIN))\n\t\treturn -EPERM;\n\n\tp = alloc_swap_info();\n\tif (IS_ERR(p))\n\t\treturn PTR_ERR(p);\n\n\tname = getname(specialfile);\n\tif (IS_ERR(name)) {\n\t\terror = PTR_ERR(name);\n\t\tname = NULL;\n\t\tgoto bad_swap;\n\t}\n\tswap_file = filp_open(name, O_RDWR|O_LARGEFILE, 0);\n\tif (IS_ERR(swap_file)) {\n\t\terror = PTR_ERR(swap_file);\n\t\tswap_file = NULL;\n\t\tgoto bad_swap;\n\t}\n\n\tp->swap_file = swap_file;\n\tmapping = swap_file->f_mapping;\n\n\tfor (i = 0; i < nr_swapfiles; i++) {\n\t\tstruct swap_info_struct *q = swap_info[i];\n\n\t\tif (q == p || !q->swap_file)\n\t\t\tcontinue;\n\t\tif (mapping == q->swap_file->f_mapping) {\n\t\t\terror = -EBUSY;\n\t\t\tgoto bad_swap;\n\t\t}\n\t}\n\n\tinode = mapping->host;\n\t/* If S_ISREG(inode->i_mode) will do mutex_lock(&inode->i_mutex); */\n\terror = claim_swapfile(p, inode);\n\tif (unlikely(error))\n\t\tgoto bad_swap;\n\n\t/*\n\t * Read the swap header.\n\t */\n\tif (!mapping->a_ops->readpage) {\n\t\terror = -EINVAL;\n\t\tgoto bad_swap;\n\t}\n\tpage = read_mapping_page(mapping, 0, swap_file);\n\tif (IS_ERR(page)) {\n\t\terror = PTR_ERR(page);\n\t\tgoto bad_swap;\n\t}\n\tswap_header = kmap(page);\n\n\tmaxpages = read_swap_header(p, swap_header, inode);\n\tif (unlikely(!maxpages)) {\n\t\terror = -EINVAL;\n\t\tgoto bad_swap;\n\t}\n\n\t/* OK, set up the swap map and apply the bad block list */\n\tswap_map = vzalloc(maxpages);\n\tif (!swap_map) {\n\t\terror = -ENOMEM;\n\t\tgoto bad_swap;\n\t}\n\n\terror = swap_cgroup_swapon(p->type, maxpages);\n\tif (error)\n\t\tgoto bad_swap;\n\n\tnr_extents = setup_swap_map_and_extents(p, swap_header, swap_map,\n\t\tmaxpages, &span);\n\tif (unlikely(nr_extents < 0)) {\n\t\terror = nr_extents;\n\t\tgoto bad_swap;\n\t}\n\n\tif (p->bdev) {\n\t\tif (blk_queue_nonrot(bdev_get_queue(p->bdev))) {\n\t\t\tp->flags |= SWP_SOLIDSTATE;\n\t\t\tp->cluster_next = 1 + (random32() % p->highest_bit);\n\t\t}\n\t\tif (discard_swap(p) == 0 && (swap_flags & SWAP_FLAG_DISCARD))\n\t\t\tp->flags |= SWP_DISCARDABLE;\n\t}\n\n\tmutex_lock(&swapon_mutex);\n\tprio = -1;\n\tif (swap_flags & SWAP_FLAG_PREFER)\n\t\tprio =\n\t\t (swap_flags & SWAP_FLAG_PRIO_MASK) >> SWAP_FLAG_PRIO_SHIFT;\n\tenable_swap_info(p, prio, swap_map);\n\n\tprintk(KERN_INFO \"Adding %uk swap on %s. \"\n\t\t\t\"Priority:%d extents:%d across:%lluk %s%s\\n\",\n\t\tp->pages<<(PAGE_SHIFT-10), name, p->prio,\n\t\tnr_extents, (unsigned long long)span<<(PAGE_SHIFT-10),\n\t\t(p->flags & SWP_SOLIDSTATE) ? \"SS\" : \"\",\n\t\t(p->flags & SWP_DISCARDABLE) ? \"D\" : \"\");\n\n\tmutex_unlock(&swapon_mutex);\n\tatomic_inc(&proc_poll_event);\n\twake_up_interruptible(&proc_poll_wait);\n\n\tif (S_ISREG(inode->i_mode))\n\t\tinode->i_flags |= S_SWAPFILE;\n\terror = 0;\n\tgoto out;\nbad_swap:\n\tif (inode && S_ISBLK(inode->i_mode) && p->bdev) {\n\t\tset_blocksize(p->bdev, p->old_block_size);\n\t\tblkdev_put(p->bdev, FMODE_READ | FMODE_WRITE | FMODE_EXCL);\n\t}\n\tdestroy_swap_extents(p);\n\tswap_cgroup_swapoff(p->type);\n\tspin_lock(&swap_lock);\n\tp->swap_file = NULL;\n\tp->flags = 0;\n\tspin_unlock(&swap_lock);\n\tvfree(swap_map);\n\tif (swap_file) {\n\t\tif (inode && S_ISREG(inode->i_mode)) {\n\t\t\tmutex_unlock(&inode->i_mutex);\n\t\t\tinode = NULL;\n\t\t}\n\t\tfilp_close(swap_file, NULL);\n\t}\nout:\n\tif (page && !IS_ERR(page)) {\n\t\tkunmap(page);\n\t\tpage_cache_release(page);\n\t}\n\tif (name)\n\t\tputname(name);\n\tif (inode && S_ISREG(inode->i_mode))\n\t\tmutex_unlock(&inode->i_mutex);\n\treturn error;\n}\n", + "line": null, + "label": 0, + "cwe": "CWE-264", + "cve": "CVE-2012-1179", + "length": 1113 + }, + { + "index": 180827, + "code": "static void gmc_mmx(uint8_t *dst, uint8_t *src,\n int stride, int h, int ox, int oy,\n int dxx, int dxy, int dyx, int dyy,\n int shift, int r, int width, int height)\n{\n const int w = 8;\n const int ix = ox >> (16 + shift);\n const int iy = oy >> (16 + shift);\n const int oxs = ox >> 4;\n const int oys = oy >> 4;\n const int dxxs = dxx >> 4;\n const int dxys = dxy >> 4;\n const int dyxs = dyx >> 4;\n const int dyys = dyy >> 4;\n const uint16_t r4[4] = { r, r, r, r };\n const uint16_t dxy4[4] = { dxys, dxys, dxys, dxys };\n const uint16_t dyy4[4] = { dyys, dyys, dyys, dyys };\n const uint64_t shift2 = 2 * shift;\n#define MAX_STRIDE 4096U\n#define MAX_H 8U\n uint8_t edge_buf[(MAX_H + 1) * MAX_STRIDE];\n int x, y;\n\n const int dxw = (dxx - (1 << (16 + shift))) * (w - 1);\n const int dyh = (dyy - (1 << (16 + shift))) * (h - 1);\n const int dxh = dxy * (h - 1);\n const int dyw = dyx * (w - 1);\n int need_emu = (unsigned) ix >= width - w ||\n (unsigned) iy >= height - h;\n \n if ( // non-constant fullpel offset (3% of blocks)\n ((ox ^ (ox + dxw)) | (ox ^ (ox + dxh)) | (ox ^ (ox + dxw + dxh)) |\n (oy ^ (oy + dyw)) | (oy ^ (oy + dyh)) | (oy ^ (oy + dyw + dyh))) >> (16 + shift) ||\n (dxx | dxy | dyx | dyy) & 15 ||\n (need_emu && (h > MAX_H || stride > MAX_STRIDE))) {\n ff_gmc_c(dst, src, stride, h, ox, oy, dxx, dxy, dyx, dyy,\n shift, r, width, height);\n return;\n }\n\n src += ix + iy * stride;\n if (need_emu) {\n ff_emulated_edge_mc_8(edge_buf, src, stride, stride, w + 1, h + 1, ix, iy, width, height);\n src = edge_buf;\n }\n\n __asm__ volatile (\n \"movd %0, %%mm6 \\n\\t\"\n \"pxor %%mm7, %%mm7 \\n\\t\"\n \"punpcklwd %%mm6, %%mm6 \\n\\t\"\n \"punpcklwd %%mm6, %%mm6 \\n\\t\"\n :: \"r\" (1 << shift));\n\n for (x = 0; x < w; x += 4) {\n uint16_t dx4[4] = { oxs - dxys + dxxs * (x + 0),\n oxs - dxys + dxxs * (x + 1),\n oxs - dxys + dxxs * (x + 2),\n oxs - dxys + dxxs * (x + 3) };\n uint16_t dy4[4] = { oys - dyys + dyxs * (x + 0),\n oys - dyys + dyxs * (x + 1),\n oys - dyys + dyxs * (x + 2),\n oys - dyys + dyxs * (x + 3) };\n\n for (y = 0; y < h; y++) {\n __asm__ volatile (\n \"movq %0, %%mm4 \\n\\t\"\n \"movq %1, %%mm5 \\n\\t\"\n \"paddw %2, %%mm4 \\n\\t\"\n \"paddw %3, %%mm5 \\n\\t\"\n \"movq %%mm4, %0 \\n\\t\"\n \"movq %%mm5, %1 \\n\\t\"\n \"psrlw $12, %%mm4 \\n\\t\"\n \"psrlw $12, %%mm5 \\n\\t\"\n : \"+m\" (*dx4), \"+m\" (*dy4)\n : \"m\" (*dxy4), \"m\" (*dyy4));\n\n __asm__ volatile (\n \"movq %%mm6, %%mm2 \\n\\t\"\n \"movq %%mm6, %%mm1 \\n\\t\"\n \"psubw %%mm4, %%mm2 \\n\\t\"\n \"psubw %%mm5, %%mm1 \\n\\t\"\n \"movq %%mm2, %%mm0 \\n\\t\"\n \"movq %%mm4, %%mm3 \\n\\t\"\n \"pmullw %%mm1, %%mm0 \\n\\t\" // (s - dx) * (s - dy)\n \"pmullw %%mm5, %%mm3 \\n\\t\" // dx * dy\n \"pmullw %%mm5, %%mm2 \\n\\t\" // (s - dx) * dy\n \"pmullw %%mm4, %%mm1 \\n\\t\" // dx * (s - dy)\n\n \"movd %4, %%mm5 \\n\\t\"\n \"movd %3, %%mm4 \\n\\t\"\n \"punpcklbw %%mm7, %%mm5 \\n\\t\"\n \"punpcklbw %%mm7, %%mm4 \\n\\t\"\n \"pmullw %%mm5, %%mm3 \\n\\t\" // src[1, 1] * dx * dy\n \"pmullw %%mm4, %%mm2 \\n\\t\" // src[0, 1] * (s - dx) * dy\n\n \"movd %2, %%mm5 \\n\\t\"\n \"movd %1, %%mm4 \\n\\t\"\n \"punpcklbw %%mm7, %%mm5 \\n\\t\"\n \"punpcklbw %%mm7, %%mm4 \\n\\t\"\n \"pmullw %%mm5, %%mm1 \\n\\t\" // src[1, 0] * dx * (s - dy)\n \"pmullw %%mm4, %%mm0 \\n\\t\" // src[0, 0] * (s - dx) * (s - dy)\n \"paddw %5, %%mm1 \\n\\t\"\n \"paddw %%mm3, %%mm2 \\n\\t\"\n \"paddw %%mm1, %%mm0 \\n\\t\"\n \"paddw %%mm2, %%mm0 \\n\\t\"\n\n \"psrlw %6, %%mm0 \\n\\t\"\n \"packuswb %%mm0, %%mm0 \\n\\t\"\n \"movd %%mm0, %0 \\n\\t\"\n\n : \"=m\" (dst[x + y * stride])\n : \"m\" (src[0]), \"m\" (src[1]),\n \"m\" (src[stride]), \"m\" (src[stride + 1]),\n \"m\" (*r4), \"m\" (shift2));\n src += stride;\n }\n src += 4 - h * stride;\n }\n}\n", + "line": " int need_emu = (unsigned) ix >= width - w ||\n (unsigned) iy >= height - h;\n", + "label": 1, + "cwe": "CWE-125", + "cve": "CVE-2017-17081", + "length": 1759 + }, + { + "index": 30975, + "code": "int iscsi_create_default_params(struct iscsi_param_list **param_list_ptr)\n{\n\tstruct iscsi_param *param = NULL;\n\tstruct iscsi_param_list *pl;\n\n\tpl = kzalloc(sizeof(struct iscsi_param_list), GFP_KERNEL);\n\tif (!pl) {\n\t\tpr_err(\"Unable to allocate memory for\"\n\t\t\t\t\" struct iscsi_param_list.\\n\");\n\t\treturn -1 ;\n\t}\n\tINIT_LIST_HEAD(&pl->param_list);\n\tINIT_LIST_HEAD(&pl->extra_response_list);\n\n\t/*\n\t * The format for setting the initial parameter definitions are:\n\t *\n\t * Parameter name:\n\t * Initial value:\n\t * Allowable phase:\n\t * Scope:\n\t * Allowable senders:\n\t * Typerange:\n\t * Use:\n\t */\n\tparam = iscsi_set_default_param(pl, AUTHMETHOD, INITIAL_AUTHMETHOD,\n\t\t\tPHASE_SECURITY, SCOPE_CONNECTION_ONLY, SENDER_BOTH,\n\t\t\tTYPERANGE_AUTH, USE_INITIAL_ONLY);\n\tif (!param)\n\t\tgoto out;\n\n\tparam = iscsi_set_default_param(pl, HEADERDIGEST, INITIAL_HEADERDIGEST,\n\t\t\tPHASE_OPERATIONAL, SCOPE_CONNECTION_ONLY, SENDER_BOTH,\n\t\t\tTYPERANGE_DIGEST, USE_INITIAL_ONLY);\n\tif (!param)\n\t\tgoto out;\n\n\tparam = iscsi_set_default_param(pl, DATADIGEST, INITIAL_DATADIGEST,\n\t\t\tPHASE_OPERATIONAL, SCOPE_CONNECTION_ONLY, SENDER_BOTH,\n\t\t\tTYPERANGE_DIGEST, USE_INITIAL_ONLY);\n\tif (!param)\n\t\tgoto out;\n\n\tparam = iscsi_set_default_param(pl, MAXCONNECTIONS,\n\t\t\tINITIAL_MAXCONNECTIONS, PHASE_OPERATIONAL,\n\t\t\tSCOPE_SESSION_WIDE, SENDER_BOTH,\n\t\t\tTYPERANGE_1_TO_65535, USE_LEADING_ONLY);\n\tif (!param)\n\t\tgoto out;\n\n\tparam = iscsi_set_default_param(pl, SENDTARGETS, INITIAL_SENDTARGETS,\n\t\t\tPHASE_FFP0, SCOPE_SESSION_WIDE, SENDER_INITIATOR,\n\t\t\tTYPERANGE_UTF8, 0);\n\tif (!param)\n\t\tgoto out;\n\n\tparam = iscsi_set_default_param(pl, TARGETNAME, INITIAL_TARGETNAME,\n\t\t\tPHASE_DECLARATIVE, SCOPE_SESSION_WIDE, SENDER_BOTH,\n\t\t\tTYPERANGE_ISCSINAME, USE_ALL);\n\tif (!param)\n\t\tgoto out;\n\n\tparam = iscsi_set_default_param(pl, INITIATORNAME,\n\t\t\tINITIAL_INITIATORNAME, PHASE_DECLARATIVE,\n\t\t\tSCOPE_SESSION_WIDE, SENDER_INITIATOR,\n\t\t\tTYPERANGE_ISCSINAME, USE_INITIAL_ONLY);\n\tif (!param)\n\t\tgoto out;\n\n\tparam = iscsi_set_default_param(pl, TARGETALIAS, INITIAL_TARGETALIAS,\n\t\t\tPHASE_DECLARATIVE, SCOPE_SESSION_WIDE, SENDER_TARGET,\n\t\t\tTYPERANGE_UTF8, USE_ALL);\n\tif (!param)\n\t\tgoto out;\n\n\tparam = iscsi_set_default_param(pl, INITIATORALIAS,\n\t\t\tINITIAL_INITIATORALIAS, PHASE_DECLARATIVE,\n\t\t\tSCOPE_SESSION_WIDE, SENDER_INITIATOR, TYPERANGE_UTF8,\n\t\t\tUSE_ALL);\n\tif (!param)\n\t\tgoto out;\n\n\tparam = iscsi_set_default_param(pl, TARGETADDRESS,\n\t\t\tINITIAL_TARGETADDRESS, PHASE_DECLARATIVE,\n\t\t\tSCOPE_SESSION_WIDE, SENDER_TARGET,\n\t\t\tTYPERANGE_TARGETADDRESS, USE_ALL);\n\tif (!param)\n\t\tgoto out;\n\n\tparam = iscsi_set_default_param(pl, TARGETPORTALGROUPTAG,\n\t\t\tINITIAL_TARGETPORTALGROUPTAG,\n\t\t\tPHASE_DECLARATIVE, SCOPE_SESSION_WIDE, SENDER_TARGET,\n\t\t\tTYPERANGE_0_TO_65535, USE_INITIAL_ONLY);\n\tif (!param)\n\t\tgoto out;\n\n\tparam = iscsi_set_default_param(pl, INITIALR2T, INITIAL_INITIALR2T,\n\t\t\tPHASE_OPERATIONAL, SCOPE_SESSION_WIDE, SENDER_BOTH,\n\t\t\tTYPERANGE_BOOL_OR, USE_LEADING_ONLY);\n\tif (!param)\n\t\tgoto out;\n\n\tparam = iscsi_set_default_param(pl, IMMEDIATEDATA,\n\t\t\tINITIAL_IMMEDIATEDATA, PHASE_OPERATIONAL,\n\t\t\tSCOPE_SESSION_WIDE, SENDER_BOTH, TYPERANGE_BOOL_AND,\n\t\t\tUSE_LEADING_ONLY);\n\tif (!param)\n\t\tgoto out;\n\n\tparam = iscsi_set_default_param(pl, MAXXMITDATASEGMENTLENGTH,\n\t\t\tINITIAL_MAXXMITDATASEGMENTLENGTH,\n\t\t\tPHASE_OPERATIONAL, SCOPE_CONNECTION_ONLY, SENDER_BOTH,\n\t\t\tTYPERANGE_512_TO_16777215, USE_ALL);\n\tif (!param)\n\t\tgoto out;\n\n\tparam = iscsi_set_default_param(pl, MAXRECVDATASEGMENTLENGTH,\n\t\t\tINITIAL_MAXRECVDATASEGMENTLENGTH,\n\t\t\tPHASE_OPERATIONAL, SCOPE_CONNECTION_ONLY, SENDER_BOTH,\n\t\t\tTYPERANGE_512_TO_16777215, USE_ALL);\n\tif (!param)\n\t\tgoto out;\n\n\tparam = iscsi_set_default_param(pl, MAXBURSTLENGTH,\n\t\t\tINITIAL_MAXBURSTLENGTH, PHASE_OPERATIONAL,\n\t\t\tSCOPE_SESSION_WIDE, SENDER_BOTH,\n\t\t\tTYPERANGE_512_TO_16777215, USE_LEADING_ONLY);\n\tif (!param)\n\t\tgoto out;\n\n\tparam = iscsi_set_default_param(pl, FIRSTBURSTLENGTH,\n\t\t\tINITIAL_FIRSTBURSTLENGTH,\n\t\t\tPHASE_OPERATIONAL, SCOPE_SESSION_WIDE, SENDER_BOTH,\n\t\t\tTYPERANGE_512_TO_16777215, USE_LEADING_ONLY);\n\tif (!param)\n\t\tgoto out;\n\n\tparam = iscsi_set_default_param(pl, DEFAULTTIME2WAIT,\n\t\t\tINITIAL_DEFAULTTIME2WAIT,\n\t\t\tPHASE_OPERATIONAL, SCOPE_SESSION_WIDE, SENDER_BOTH,\n\t\t\tTYPERANGE_0_TO_3600, USE_LEADING_ONLY);\n\tif (!param)\n\t\tgoto out;\n\n\tparam = iscsi_set_default_param(pl, DEFAULTTIME2RETAIN,\n\t\t\tINITIAL_DEFAULTTIME2RETAIN,\n\t\t\tPHASE_OPERATIONAL, SCOPE_SESSION_WIDE, SENDER_BOTH,\n\t\t\tTYPERANGE_0_TO_3600, USE_LEADING_ONLY);\n\tif (!param)\n\t\tgoto out;\n\n\tparam = iscsi_set_default_param(pl, MAXOUTSTANDINGR2T,\n\t\t\tINITIAL_MAXOUTSTANDINGR2T,\n\t\t\tPHASE_OPERATIONAL, SCOPE_SESSION_WIDE, SENDER_BOTH,\n\t\t\tTYPERANGE_1_TO_65535, USE_LEADING_ONLY);\n\tif (!param)\n\t\tgoto out;\n\n\tparam = iscsi_set_default_param(pl, DATAPDUINORDER,\n\t\t\tINITIAL_DATAPDUINORDER, PHASE_OPERATIONAL,\n\t\t\tSCOPE_SESSION_WIDE, SENDER_BOTH, TYPERANGE_BOOL_OR,\n\t\t\tUSE_LEADING_ONLY);\n\tif (!param)\n\t\tgoto out;\n\n\tparam = iscsi_set_default_param(pl, DATASEQUENCEINORDER,\n\t\t\tINITIAL_DATASEQUENCEINORDER,\n\t\t\tPHASE_OPERATIONAL, SCOPE_SESSION_WIDE, SENDER_BOTH,\n\t\t\tTYPERANGE_BOOL_OR, USE_LEADING_ONLY);\n\tif (!param)\n\t\tgoto out;\n\n\tparam = iscsi_set_default_param(pl, ERRORRECOVERYLEVEL,\n\t\t\tINITIAL_ERRORRECOVERYLEVEL,\n\t\t\tPHASE_OPERATIONAL, SCOPE_SESSION_WIDE, SENDER_BOTH,\n\t\t\tTYPERANGE_0_TO_2, USE_LEADING_ONLY);\n\tif (!param)\n\t\tgoto out;\n\n\tparam = iscsi_set_default_param(pl, SESSIONTYPE, INITIAL_SESSIONTYPE,\n\t\t\tPHASE_DECLARATIVE, SCOPE_SESSION_WIDE, SENDER_INITIATOR,\n\t\t\tTYPERANGE_SESSIONTYPE, USE_LEADING_ONLY);\n\tif (!param)\n\t\tgoto out;\n\n\tparam = iscsi_set_default_param(pl, IFMARKER, INITIAL_IFMARKER,\n\t\t\tPHASE_OPERATIONAL, SCOPE_CONNECTION_ONLY, SENDER_BOTH,\n\t\t\tTYPERANGE_BOOL_AND, USE_INITIAL_ONLY);\n\tif (!param)\n\t\tgoto out;\n\n\tparam = iscsi_set_default_param(pl, OFMARKER, INITIAL_OFMARKER,\n\t\t\tPHASE_OPERATIONAL, SCOPE_CONNECTION_ONLY, SENDER_BOTH,\n\t\t\tTYPERANGE_BOOL_AND, USE_INITIAL_ONLY);\n\tif (!param)\n\t\tgoto out;\n\n\tparam = iscsi_set_default_param(pl, IFMARKINT, INITIAL_IFMARKINT,\n\t\t\tPHASE_OPERATIONAL, SCOPE_CONNECTION_ONLY, SENDER_BOTH,\n\t\t\tTYPERANGE_MARKINT, USE_INITIAL_ONLY);\n\tif (!param)\n\t\tgoto out;\n\n\tparam = iscsi_set_default_param(pl, OFMARKINT, INITIAL_OFMARKINT,\n\t\t\tPHASE_OPERATIONAL, SCOPE_CONNECTION_ONLY, SENDER_BOTH,\n\t\t\tTYPERANGE_MARKINT, USE_INITIAL_ONLY);\n\tif (!param)\n\t\tgoto out;\n\t/*\n\t * Extra parameters for ISER from RFC-5046\n\t */\n\tparam = iscsi_set_default_param(pl, RDMAEXTENSIONS, INITIAL_RDMAEXTENSIONS,\n\t\t\tPHASE_OPERATIONAL, SCOPE_SESSION_WIDE, SENDER_BOTH,\n\t\t\tTYPERANGE_BOOL_AND, USE_LEADING_ONLY);\n\tif (!param)\n\t\tgoto out;\n\n\tparam = iscsi_set_default_param(pl, INITIATORRECVDATASEGMENTLENGTH,\n\t\t\tINITIAL_INITIATORRECVDATASEGMENTLENGTH,\n\t\t\tPHASE_OPERATIONAL, SCOPE_CONNECTION_ONLY, SENDER_BOTH,\n\t\t\tTYPERANGE_512_TO_16777215, USE_ALL);\n\tif (!param)\n\t\tgoto out;\n\n\tparam = iscsi_set_default_param(pl, TARGETRECVDATASEGMENTLENGTH,\n\t\t\tINITIAL_TARGETRECVDATASEGMENTLENGTH,\n\t\t\tPHASE_OPERATIONAL, SCOPE_CONNECTION_ONLY, SENDER_BOTH,\n\t\t\tTYPERANGE_512_TO_16777215, USE_ALL);\n\tif (!param)\n\t\tgoto out;\n\n\t*param_list_ptr = pl;\n\treturn 0;\nout:\n\tiscsi_release_param_list(pl);\n\treturn -1;\n}\n", + "line": null, + "label": 0, + "cwe": "CWE-119", + "cve": "CVE-2013-2850", + "length": 2115 + }, + { + "index": 82851, + "code": "static int parse_thread(struct MACH0_(obj_t)* bin, struct load_command *lc, ut64 off, bool is_first_thread) {\n\tut64 ptr_thread, pc = UT64_MAX, pc_offset = UT64_MAX;\n\tut32 flavor, count;\n\tut8 *arw_ptr = NULL;\n\tint arw_sz, len = 0;\n\tut8 thc[sizeof (struct thread_command)] = {0};\n\tut8 tmp[4];\n\n\tif (off > bin->size || off + sizeof (struct thread_command) > bin->size)\n\t\treturn false;\n\n\tlen = r_buf_read_at (bin->b, off, thc, 8);\n\tif (len < 1) {\n\t\tgoto wrong_read;\n\t}\n\tbin->thread.cmd = r_read_ble32 (&thc[0], bin->big_endian);\n\tbin->thread.cmdsize = r_read_ble32 (&thc[4], bin->big_endian);\n\tif (r_buf_read_at (bin->b, off + sizeof (struct thread_command), tmp, 4) < 4) {\n\t\tgoto wrong_read;\n\t}\n\tflavor = r_read_ble32 (tmp, bin->big_endian);\n\tif (len == -1)\n\t\tgoto wrong_read;\n\n\tif (off + sizeof (struct thread_command) + sizeof (flavor) > bin->size || \\\n\t off + sizeof (struct thread_command) + sizeof (flavor) + sizeof (ut32) > bin->size)\n\t\treturn false;\n\n\tif (r_buf_read_at (bin->b, off + sizeof (struct thread_command) + sizeof (flavor), tmp, 4) < 4) {\n\t\tgoto wrong_read;\n\t}\n\tcount = r_read_ble32 (tmp, bin->big_endian);\n\tptr_thread = off + sizeof (struct thread_command) + sizeof (flavor) + sizeof (count);\n\n\tif (ptr_thread > bin->size)\n\t\treturn false;\n\n\tswitch (bin->hdr.cputype) {\n\tcase CPU_TYPE_I386:\n\tcase CPU_TYPE_X86_64:\n\t\tswitch (flavor) {\n\t\tcase X86_THREAD_STATE32:\n\t\t\tif (ptr_thread + sizeof (struct x86_thread_state32) > bin->size)\n\t\t\t\treturn false;\n\t\t\tif ((len = r_buf_fread_at (bin->b, ptr_thread,\n\t\t\t\t(ut8*)&bin->thread_state.x86_32, \"16i\", 1)) == -1) {\n\t\t\t\tbprintf (\"Error: read (thread state x86_32)\\n\");\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tpc = bin->thread_state.x86_32.eip;\n\t\t\tpc_offset = ptr_thread + r_offsetof(struct x86_thread_state32, eip);\n\t\t\tarw_ptr = (ut8 *)&bin->thread_state.x86_32;\n\t\t\tarw_sz = sizeof (struct x86_thread_state32);\n\t\t\tbreak;\n\t\tcase X86_THREAD_STATE64:\n\t\t\tif (ptr_thread + sizeof (struct x86_thread_state64) > bin->size)\n\t\t\t\treturn false;\n\t\t\tif ((len = r_buf_fread_at (bin->b, ptr_thread,\n\t\t\t\t(ut8*)&bin->thread_state.x86_64, \"32l\", 1)) == -1) {\n\t\t\t\tbprintf (\"Error: read (thread state x86_64)\\n\");\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tpc = bin->thread_state.x86_64.rip;\n\t\t\tpc_offset = ptr_thread + r_offsetof(struct x86_thread_state64, rip);\n\t\t\tarw_ptr = (ut8 *)&bin->thread_state.x86_64;\n\t\t\tarw_sz = sizeof (struct x86_thread_state64);\n\t\t\tbreak;\n\t\t}\n\t\tbreak;\n\tcase CPU_TYPE_POWERPC:\n\tcase CPU_TYPE_POWERPC64:\n\t\tif (flavor == X86_THREAD_STATE32) {\n\t\t\tif (ptr_thread + sizeof (struct ppc_thread_state32) > bin->size)\n\t\t\t\treturn false;\n\t\t\tif ((len = r_buf_fread_at (bin->b, ptr_thread,\n\t\t\t\t(ut8*)&bin->thread_state.ppc_32, bin->big_endian?\"40I\":\"40i\", 1)) == -1) {\n\t\t\t\tbprintf (\"Error: read (thread state ppc_32)\\n\");\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tpc = bin->thread_state.ppc_32.srr0;\n\t\t\tpc_offset = ptr_thread + r_offsetof(struct ppc_thread_state32, srr0);\n\t\t\tarw_ptr = (ut8 *)&bin->thread_state.ppc_32;\n\t\t\tarw_sz = sizeof (struct ppc_thread_state32);\n\t\t} else if (flavor == X86_THREAD_STATE64) {\n\t\t\tif (ptr_thread + sizeof (struct ppc_thread_state64) > bin->size)\n\t\t\t\treturn false;\n\t\t\tif ((len = r_buf_fread_at (bin->b, ptr_thread,\n\t\t\t\t(ut8*)&bin->thread_state.ppc_64, bin->big_endian?\"34LI3LI\":\"34li3li\", 1)) == -1) {\n\t\t\t\tbprintf (\"Error: read (thread state ppc_64)\\n\");\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tpc = bin->thread_state.ppc_64.srr0;\n\t\t\tpc_offset = ptr_thread + r_offsetof(struct ppc_thread_state64, srr0);\n\t\t\tarw_ptr = (ut8 *)&bin->thread_state.ppc_64;\n\t\t\tarw_sz = sizeof (struct ppc_thread_state64);\n\t\t}\n\t\tbreak;\n\tcase CPU_TYPE_ARM:\n\t\tif (ptr_thread + sizeof (struct arm_thread_state32) > bin->size)\n\t\t\treturn false;\n\t\tif ((len = r_buf_fread_at (bin->b, ptr_thread,\n\t\t\t\t(ut8*)&bin->thread_state.arm_32, bin->big_endian?\"17I\":\"17i\", 1)) == -1) {\n\t\t\tbprintf (\"Error: read (thread state arm)\\n\");\n\t\t\treturn false;\n\t\t}\n\t\tpc = bin->thread_state.arm_32.r15;\n\t\tpc_offset = ptr_thread + r_offsetof (struct arm_thread_state32, r15);\n\t\tarw_ptr = (ut8 *)&bin->thread_state.arm_32;\n\t\tarw_sz = sizeof (struct arm_thread_state32);\n\t\tbreak;\n\tcase CPU_TYPE_ARM64:\n\t\tif (ptr_thread + sizeof (struct arm_thread_state64) > bin->size) {\n\t\t\treturn false;\n\t\t}\n\t\tif ((len = r_buf_fread_at(bin->b, ptr_thread,\n\t\t\t\t(ut8*)&bin->thread_state.arm_64, bin->big_endian?\"34LI1I\":\"34Li1i\", 1)) == -1) {\n\t\t\tbprintf (\"Error: read (thread state arm)\\n\");\n\t\t\treturn false;\n\t\t}\n\t\tpc = r_read_be64 (&bin->thread_state.arm_64.pc);\n\t\tpc_offset = ptr_thread + r_offsetof (struct arm_thread_state64, pc);\n\t\tarw_ptr = (ut8*)&bin->thread_state.arm_64;\n\t\tarw_sz = sizeof (struct arm_thread_state64);\n\t\tbreak;\n\tdefault:\n\t\tbprintf (\"Error: read (unknown thread state structure)\\n\");\n\t\treturn false;\n\t}\n\n\tif (arw_ptr && arw_sz > 0) {\n\t\tint i;\n\t\tut8 *p = arw_ptr;\n\t\tbprintf (\"arw \");\n\t\tfor (i = 0; i < arw_sz; i++) {\n\t\t\tbprintf (\"%02x\", 0xff & p[i]);\n\t\t}\n\t\tbprintf (\"\\n\");\n\t}\n\n\tif (is_first_thread) {\n\t\tbin->main_cmd = *lc;\n\t\tif (pc != UT64_MAX) {\n\t\t\tbin->entry = pc;\n\t\t}\n\t\tif (pc_offset != UT64_MAX) {\n\t\t\tsdb_num_set (bin->kv, \"mach0.entry.offset\", pc_offset, 0);\n\t\t}\n\t}\n\n\treturn true;\nwrong_read:\n\tbprintf (\"Error: read (thread)\\n\");\n\treturn false;\n}\n", + "line": null, + "label": 0, + "cwe": "CWE-125", + "cve": "CVE-2018-11380", + "length": 1713 + }, + { + "index": 92903, + "code": "main(int argc, char **argv)\n{\n\tint ch, fflag, tflag, status, n;\n\tchar **newargv;\n\tconst char *errstr;\n\textern char *optarg;\n\textern int optind;\n\n\t/* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */\n\tsanitise_stdfd();\n\n\tmsetlocale();\n\n\t/* Copy argv, because we modify it */\n\tnewargv = xcalloc(MAXIMUM(argc + 1, 1), sizeof(*newargv));\n\tfor (n = 0; n < argc; n++)\n\t\tnewargv[n] = xstrdup(argv[n]);\n\targv = newargv;\n\n\t__progname = ssh_get_progname(argv[0]);\n\n\tmemset(&args, '\\0', sizeof(args));\n\tmemset(&remote_remote_args, '\\0', sizeof(remote_remote_args));\n\targs.list = remote_remote_args.list = NULL;\n\taddargs(&args, \"%s\", ssh_program);\n\taddargs(&args, \"-x\");\n\taddargs(&args, \"-oForwardAgent=no\");\n\taddargs(&args, \"-oPermitLocalCommand=no\");\n\taddargs(&args, \"-oClearAllForwardings=yes\");\n\taddargs(&args, \"-oRemoteCommand=none\");\n\taddargs(&args, \"-oRequestTTY=no\");\n\n\tfflag = tflag = 0;\n\twhile ((ch = getopt(argc, argv, \"dfl:prtvBCc:i:P:q12346S:o:F:\")) != -1)\n\t\tswitch (ch) {\n\t\t/* User-visible flags. */\n\t\tcase '1':\n\t\t\tfatal(\"SSH protocol v.1 is no longer supported\");\n\t\t\tbreak;\n\t\tcase '2':\n\t\t\t/* Ignored */\n\t\t\tbreak;\n\t\tcase '4':\n\t\tcase '6':\n\t\tcase 'C':\n\t\t\taddargs(&args, \"-%c\", ch);\n\t\t\taddargs(&remote_remote_args, \"-%c\", ch);\n\t\t\tbreak;\n\t\tcase '3':\n\t\t\tthroughlocal = 1;\n\t\t\tbreak;\n\t\tcase 'o':\n\t\tcase 'c':\n\t\tcase 'i':\n\t\tcase 'F':\n\t\t\taddargs(&remote_remote_args, \"-%c\", ch);\n\t\t\taddargs(&remote_remote_args, \"%s\", optarg);\n\t\t\taddargs(&args, \"-%c\", ch);\n\t\t\taddargs(&args, \"%s\", optarg);\n\t\t\tbreak;\n\t\tcase 'P':\n\t\t\tsshport = a2port(optarg);\n\t\t\tif (sshport <= 0)\n\t\t\t\tfatal(\"bad port \\\"%s\\\"\\n\", optarg);\n\t\t\tbreak;\n\t\tcase 'B':\n\t\t\taddargs(&remote_remote_args, \"-oBatchmode=yes\");\n\t\t\taddargs(&args, \"-oBatchmode=yes\");\n\t\t\tbreak;\n\t\tcase 'l':\n\t\t\tlimit_kbps = strtonum(optarg, 1, 100 * 1024 * 1024,\n\t\t\t &errstr);\n\t\t\tif (errstr != NULL)\n\t\t\t\tusage();\n\t\t\tlimit_kbps *= 1024; /* kbps */\n\t\t\tbandwidth_limit_init(&bwlimit, limit_kbps, COPY_BUFLEN);\n\t\t\tbreak;\n\t\tcase 'p':\n\t\t\tpflag = 1;\n\t\t\tbreak;\n\t\tcase 'r':\n\t\t\tiamrecursive = 1;\n\t\t\tbreak;\n\t\tcase 'S':\n\t\t\tssh_program = xstrdup(optarg);\n\t\t\tbreak;\n\t\tcase 'v':\n\t\t\taddargs(&args, \"-v\");\n\t\t\taddargs(&remote_remote_args, \"-v\");\n\t\t\tverbose_mode = 1;\n\t\t\tbreak;\n\t\tcase 'q':\n\t\t\taddargs(&args, \"-q\");\n\t\t\taddargs(&remote_remote_args, \"-q\");\n\t\t\tshowprogress = 0;\n\t\t\tbreak;\n\n\t\t/* Server options. */\n\t\tcase 'd':\n\t\t\ttargetshouldbedirectory = 1;\n\t\t\tbreak;\n\t\tcase 'f':\t/* \"from\" */\n\t\t\tiamremote = 1;\n\t\t\tfflag = 1;\n\t\t\tbreak;\n\t\tcase 't':\t/* \"to\" */\n\t\t\tiamremote = 1;\n\t\t\ttflag = 1;\n#ifdef HAVE_CYGWIN\n\t\t\tsetmode(0, O_BINARY);\n#endif\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tusage();\n\t\t}\n\targc -= optind;\n\targv += optind;\n\n\tif ((pwd = getpwuid(userid = getuid())) == NULL)\n\t\tfatal(\"unknown user %u\", (u_int) userid);\n\n\tif (!isatty(STDOUT_FILENO))\n\t\tshowprogress = 0;\n\n\tif (pflag) {\n\t\t/* Cannot pledge: -p allows setuid/setgid files... */\n\t} else {\n\t\tif (pledge(\"stdio rpath wpath cpath fattr tty proc exec\",\n\t\t NULL) == -1) {\n\t\t\tperror(\"pledge\");\n\t\t\texit(1);\n\t\t}\n\t}\n\n\tremin = STDIN_FILENO;\n\tremout = STDOUT_FILENO;\n\n\tif (fflag) {\n\t\t/* Follow \"protocol\", send data. */\n\t\t(void) response();\n\t\tsource(argc, argv);\n\t\texit(errs != 0);\n\t}\n\tif (tflag) {\n\t\t/* Receive data. */\n\t\tsink(argc, argv);\n\t\texit(errs != 0);\n\t}\n\tif (argc < 2)\n\t\tusage();\n\tif (argc > 2)\n\t\ttargetshouldbedirectory = 1;\n\n\tremin = remout = -1;\n\tdo_cmd_pid = -1;\n\t/* Command to be executed on remote system using \"ssh\". */\n\t(void) snprintf(cmd, sizeof cmd, \"scp%s%s%s%s\",\n\t verbose_mode ? \" -v\" : \"\",\n\t iamrecursive ? \" -r\" : \"\", pflag ? \" -p\" : \"\",\n\t targetshouldbedirectory ? \" -d\" : \"\");\n\n\t(void) signal(SIGPIPE, lostconn);\n\n\tif (colon(argv[argc - 1]))\t/* Dest is remote host. */\n\t\ttoremote(argc, argv);\n\telse {\n\t\tif (targetshouldbedirectory)\n\t\t\tverifydir(argv[argc - 1]);\n\t\ttolocal(argc, argv);\t/* Dest is local host. */\n\t}\n\t/*\n\t * Finally check the exit status of the ssh process, if one was forked\n\t * and no error has occurred yet\n\t */\n\tif (do_cmd_pid != -1 && errs == 0) {\n\t\tif (remin != -1)\n\t\t (void) close(remin);\n\t\tif (remout != -1)\n\t\t (void) close(remout);\n\t\tif (waitpid(do_cmd_pid, &status, 0) == -1)\n\t\t\terrs = 1;\n\t\telse {\n\t\t\tif (!WIFEXITED(status) || WEXITSTATUS(status) != 0)\n\t\t\t\terrs = 1;\n\t\t}\n\t}\n\texit(errs != 0);\n}\n", + "line": null, + "label": 0, + "cwe": "CWE-706", + "cve": "CVE-2018-20685", + "length": 1417 + }, + { + "index": 24984, + "code": "CIFSSMBSetEA(const int xid, struct cifs_tcon *tcon, const char *fileName,\n\t const char *ea_name, const void *ea_value,\n\t const __u16 ea_value_len, const struct nls_table *nls_codepage,\n\t int remap)\n{\n\tstruct smb_com_transaction2_spi_req *pSMB = NULL;\n\tstruct smb_com_transaction2_spi_rsp *pSMBr = NULL;\n\tstruct fealist *parm_data;\n\tint name_len;\n\tint rc = 0;\n\tint bytes_returned = 0;\n\t__u16 params, param_offset, byte_count, offset, count;\n\n\tcFYI(1, \"In SetEA\");\nSetEARetry:\n\trc = smb_init(SMB_COM_TRANSACTION2, 15, tcon, (void **) &pSMB,\n\t\t (void **) &pSMBr);\n\tif (rc)\n\t\treturn rc;\n\n\tif (pSMB->hdr.Flags2 & SMBFLG2_UNICODE) {\n\t\tname_len =\n\t\t cifsConvertToUCS((__le16 *) pSMB->FileName, fileName,\n\t\t\t\t PATH_MAX, nls_codepage, remap);\n\t\tname_len++;\t/* trailing null */\n\t\tname_len *= 2;\n\t} else {\t/* BB improve the check for buffer overruns BB */\n\t\tname_len = strnlen(fileName, PATH_MAX);\n\t\tname_len++;\t/* trailing null */\n\t\tstrncpy(pSMB->FileName, fileName, name_len);\n\t}\n\n\tparams = 6 + name_len;\n\n\t/* done calculating parms using name_len of file name,\n\tnow use name_len to calculate length of ea name\n\twe are going to create in the inode xattrs */\n\tif (ea_name == NULL)\n\t\tname_len = 0;\n\telse\n\t\tname_len = strnlen(ea_name, 255);\n\n\tcount = sizeof(*parm_data) + ea_value_len + name_len;\n\tpSMB->MaxParameterCount = cpu_to_le16(2);\n\t/* BB find max SMB PDU from sess */\n\tpSMB->MaxDataCount = cpu_to_le16(1000);\n\tpSMB->MaxSetupCount = 0;\n\tpSMB->Reserved = 0;\n\tpSMB->Flags = 0;\n\tpSMB->Timeout = 0;\n\tpSMB->Reserved2 = 0;\n\tparam_offset = offsetof(struct smb_com_transaction2_spi_req,\n\t\t\t\tInformationLevel) - 4;\n\toffset = param_offset + params;\n\tpSMB->InformationLevel =\n\t\tcpu_to_le16(SMB_SET_FILE_EA);\n\n\tparm_data =\n\t\t(struct fealist *) (((char *) &pSMB->hdr.Protocol) +\n\t\t\t\t offset);\n\tpSMB->ParameterOffset = cpu_to_le16(param_offset);\n\tpSMB->DataOffset = cpu_to_le16(offset);\n\tpSMB->SetupCount = 1;\n\tpSMB->Reserved3 = 0;\n\tpSMB->SubCommand = cpu_to_le16(TRANS2_SET_PATH_INFORMATION);\n\tbyte_count = 3 /* pad */ + params + count;\n\tpSMB->DataCount = cpu_to_le16(count);\n\tparm_data->list_len = cpu_to_le32(count);\n\tparm_data->list[0].EA_flags = 0;\n\t/* we checked above that name len is less than 255 */\n\tparm_data->list[0].name_len = (__u8)name_len;\n\t/* EA names are always ASCII */\n\tif (ea_name)\n\t\tstrncpy(parm_data->list[0].name, ea_name, name_len);\n\tparm_data->list[0].name[name_len] = 0;\n\tparm_data->list[0].value_len = cpu_to_le16(ea_value_len);\n\t/* caller ensures that ea_value_len is less than 64K but\n\twe need to ensure that it fits within the smb */\n\n\t/*BB add length check to see if it would fit in\n\t negotiated SMB buffer size BB */\n\t/* if (ea_value_len > buffer_size - 512 (enough for header)) */\n\tif (ea_value_len)\n\t\tmemcpy(parm_data->list[0].name+name_len+1,\n\t\t ea_value, ea_value_len);\n\n\tpSMB->TotalDataCount = pSMB->DataCount;\n\tpSMB->ParameterCount = cpu_to_le16(params);\n\tpSMB->TotalParameterCount = pSMB->ParameterCount;\n\tpSMB->Reserved4 = 0;\n\tinc_rfc1001_len(pSMB, byte_count);\n\tpSMB->ByteCount = cpu_to_le16(byte_count);\n\trc = SendReceive(xid, tcon->ses, (struct smb_hdr *) pSMB,\n\t\t\t (struct smb_hdr *) pSMBr, &bytes_returned, 0);\n\tif (rc)\n\t\tcFYI(1, \"SetPathInfo (EA) returned %d\", rc);\n\n\tcifs_buf_release(pSMB);\n\n\tif (rc == -EAGAIN)\n\t\tgoto SetEARetry;\n\n\treturn rc;\n}\n", + "line": null, + "label": 0, + "cwe": "CWE-189", + "cve": "CVE-2011-3191", + "length": 1048 + }, + { + "index": 71466, + "code": "static MagickBooleanType WriteCINImage(const ImageInfo *image_info,Image *image)\n{\n char\n timestamp[MaxTextExtent];\n\n const char\n *value;\n\n CINInfo\n cin;\n\n const StringInfo\n *profile;\n\n MagickBooleanType\n status;\n\n MagickOffsetType\n offset;\n\n QuantumInfo\n *quantum_info;\n\n QuantumType\n quantum_type;\n\n register const PixelPacket\n *p;\n\n register ssize_t\n i;\n\n size_t\n length;\n\n ssize_t\n count,\n y;\n\n struct tm\n local_time;\n\n time_t\n seconds;\n\n unsigned char\n *pixels;\n\n /*\n Open output image file.\n */\n assert(image_info != (const ImageInfo *) NULL);\n assert(image_info->signature == MagickSignature);\n assert(image != (Image *) NULL);\n assert(image->signature == MagickSignature);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",image->filename);\n status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);\n if (status == MagickFalse)\n return(status);\n if (image->colorspace != LogColorspace)\n (void) TransformImageColorspace(image,LogColorspace);\n /*\n Write image information.\n */\n (void) ResetMagickMemory(&cin,0,sizeof(cin));\n offset=0;\n cin.file.magic=0x802A5FD7UL;\n offset+=WriteBlobLong(image,(unsigned int) cin.file.magic);\n cin.file.image_offset=0x800;\n offset+=WriteBlobLong(image,(unsigned int) cin.file.image_offset);\n cin.file.generic_length=0x400;\n offset+=WriteBlobLong(image,(unsigned int) cin.file.generic_length);\n cin.file.industry_length=0x400;\n offset+=WriteBlobLong(image,(unsigned int) cin.file.industry_length);\n cin.file.user_length=0x00;\n profile=GetImageProfile(image,\"dpx:user.data\");\n if (profile != (StringInfo *) NULL)\n {\n cin.file.user_length+=(size_t) GetStringInfoLength(profile);\n cin.file.user_length=(((cin.file.user_length+0x2000-1)/0x2000)*0x2000);\n }\n offset+=WriteBlobLong(image,(unsigned int) cin.file.user_length);\n cin.file.file_size=4*image->columns*image->rows+0x2000;\n offset+=WriteBlobLong(image,(unsigned int) cin.file.file_size);\n (void) CopyMagickString(cin.file.version,\"V4.5\",sizeof(cin.file.version));\n offset+=WriteBlob(image,sizeof(cin.file.version),(unsigned char *)\n cin.file.version);\n value=GetCINProperty(image_info,image,\"dpx:file.filename\");\n if (value != (const char *) NULL)\n (void) CopyMagickString(cin.file.filename,value,sizeof(cin.file.filename));\n else\n (void) CopyMagickString(cin.file.filename,image->filename,\n sizeof(cin.file.filename));\n offset+=WriteBlob(image,sizeof(cin.file.filename),(unsigned char *)\n cin.file.filename);\n seconds=time((time_t *) NULL);\n#if defined(MAGICKCORE_HAVE_LOCALTIME_R)\n (void) localtime_r(&seconds,&local_time);\n#else\n (void) memcpy(&local_time,localtime(&seconds),sizeof(local_time));\n#endif\n (void) memset(timestamp,0,sizeof(timestamp));\n (void) strftime(timestamp,MaxTextExtent,\"%Y:%m:%d:%H:%M:%S%Z\",&local_time);\n (void) memset(cin.file.create_date,0,sizeof(cin.file.create_date));\n (void) CopyMagickString(cin.file.create_date,timestamp,11);\n offset+=WriteBlob(image,sizeof(cin.file.create_date),(unsigned char *)\n cin.file.create_date);\n (void) memset(cin.file.create_time,0,sizeof(cin.file.create_time));\n (void) CopyMagickString(cin.file.create_time,timestamp+11,11);\n offset+=WriteBlob(image,sizeof(cin.file.create_time),(unsigned char *)\n cin.file.create_time);\n offset+=WriteBlob(image,sizeof(cin.file.reserve),(unsigned char *)\n cin.file.reserve);\n cin.image.orientation=0x00;\n offset+=WriteBlobByte(image,cin.image.orientation);\n cin.image.number_channels=3;\n offset+=WriteBlobByte(image,cin.image.number_channels);\n offset+=WriteBlob(image,sizeof(cin.image.reserve1),(unsigned char *)\n cin.image.reserve1);\n for (i=0; i < 8; i++)\n {\n cin.image.channel[i].designator[0]=0; /* universal metric */\n offset+=WriteBlobByte(image,cin.image.channel[0].designator[0]);\n cin.image.channel[i].designator[1]=(unsigned char) (i > 3 ? 0 : i+1); /* channel color */;\n offset+=WriteBlobByte(image,cin.image.channel[1].designator[0]);\n cin.image.channel[i].bits_per_pixel=(unsigned char) image->depth;\n offset+=WriteBlobByte(image,cin.image.channel[0].bits_per_pixel);\n offset+=WriteBlobByte(image,cin.image.channel[0].reserve);\n cin.image.channel[i].pixels_per_line=image->columns;\n offset+=WriteBlobLong(image,(unsigned int)\n cin.image.channel[0].pixels_per_line);\n cin.image.channel[i].lines_per_image=image->rows;\n offset+=WriteBlobLong(image,(unsigned int)\n cin.image.channel[0].lines_per_image);\n cin.image.channel[i].min_data=0;\n offset+=WriteBlobFloat(image,cin.image.channel[0].min_data);\n cin.image.channel[i].min_quantity=0.0;\n offset+=WriteBlobFloat(image,cin.image.channel[0].min_quantity);\n cin.image.channel[i].max_data=(float) ((MagickOffsetType)\n GetQuantumRange(image->depth));\n offset+=WriteBlobFloat(image,cin.image.channel[0].max_data);\n cin.image.channel[i].max_quantity=2.048f;\n offset+=WriteBlobFloat(image,cin.image.channel[0].max_quantity);\n }\n offset+=WriteBlobFloat(image,image->chromaticity.white_point.x);\n offset+=WriteBlobFloat(image,image->chromaticity.white_point.y);\n offset+=WriteBlobFloat(image,image->chromaticity.red_primary.x);\n offset+=WriteBlobFloat(image,image->chromaticity.red_primary.y);\n offset+=WriteBlobFloat(image,image->chromaticity.green_primary.x);\n offset+=WriteBlobFloat(image,image->chromaticity.green_primary.y);\n offset+=WriteBlobFloat(image,image->chromaticity.blue_primary.x);\n offset+=WriteBlobFloat(image,image->chromaticity.blue_primary.y);\n value=GetCINProperty(image_info,image,\"dpx:image.label\");\n if (value != (const char *) NULL)\n (void) CopyMagickString(cin.image.label,value,sizeof(cin.image.label));\n offset+=WriteBlob(image,sizeof(cin.image.label),(unsigned char *)\n cin.image.label);\n offset+=WriteBlob(image,sizeof(cin.image.reserve),(unsigned char *)\n cin.image.reserve);\n /*\n Write data format information.\n */\n cin.data_format.interleave=0; /* pixel interleave (rgbrgbr...) */\n offset+=WriteBlobByte(image,cin.data_format.interleave);\n cin.data_format.packing=5; /* packing ssize_tword (32bit) boundaries */\n offset+=WriteBlobByte(image,cin.data_format.packing);\n cin.data_format.sign=0; /* unsigned data */\n offset+=WriteBlobByte(image,cin.data_format.sign);\n cin.data_format.sense=0; /* image sense: positive image */\n offset+=WriteBlobByte(image,cin.data_format.sense);\n cin.data_format.line_pad=0;\n offset+=WriteBlobLong(image,(unsigned int) cin.data_format.line_pad);\n cin.data_format.channel_pad=0;\n offset+=WriteBlobLong(image,(unsigned int) cin.data_format.channel_pad);\n offset+=WriteBlob(image,sizeof(cin.data_format.reserve),(unsigned char *)\n cin.data_format.reserve);\n /*\n Write origination information.\n */\n cin.origination.x_offset=0UL;\n value=GetCINProperty(image_info,image,\"dpx:origination.x_offset\");\n if (value != (const char *) NULL)\n cin.origination.x_offset=(ssize_t) StringToLong(value);\n offset+=WriteBlobLong(image,(unsigned int) cin.origination.x_offset);\n cin.origination.y_offset=0UL;\n value=GetCINProperty(image_info,image,\"dpx:origination.y_offset\");\n if (value != (const char *) NULL)\n cin.origination.y_offset=(ssize_t) StringToLong(value);\n offset+=WriteBlobLong(image,(unsigned int) cin.origination.y_offset);\n value=GetCINProperty(image_info,image,\"dpx:origination.filename\");\n if (value != (const char *) NULL)\n (void) CopyMagickString(cin.origination.filename,value,\n sizeof(cin.origination.filename));\n else\n (void) CopyMagickString(cin.origination.filename,image->filename,\n sizeof(cin.origination.filename));\n offset+=WriteBlob(image,sizeof(cin.origination.filename),(unsigned char *)\n cin.origination.filename);\n seconds=time((time_t *) NULL);\n (void) memset(timestamp,0,sizeof(timestamp));\n (void) strftime(timestamp,MaxTextExtent,\"%Y:%m:%d:%H:%M:%S%Z\",&local_time);\n (void) memset(cin.origination.create_date,0,\n sizeof(cin.origination.create_date));\n (void) CopyMagickString(cin.origination.create_date,timestamp,11);\n offset+=WriteBlob(image,sizeof(cin.origination.create_date),(unsigned char *)\n cin.origination.create_date);\n (void) memset(cin.origination.create_time,0,\n sizeof(cin.origination.create_time));\n (void) CopyMagickString(cin.origination.create_time,timestamp+11,15);\n offset+=WriteBlob(image,sizeof(cin.origination.create_time),(unsigned char *)\n cin.origination.create_time);\n value=GetCINProperty(image_info,image,\"dpx:origination.device\");\n if (value != (const char *) NULL)\n (void) CopyMagickString(cin.origination.device,value,\n sizeof(cin.origination.device));\n offset+=WriteBlob(image,sizeof(cin.origination.device),(unsigned char *)\n cin.origination.device);\n value=GetCINProperty(image_info,image,\"dpx:origination.model\");\n if (value != (const char *) NULL)\n (void) CopyMagickString(cin.origination.model,value,\n sizeof(cin.origination.model));\n offset+=WriteBlob(image,sizeof(cin.origination.model),(unsigned char *)\n cin.origination.model);\n value=GetCINProperty(image_info,image,\"dpx:origination.serial\");\n if (value != (const char *) NULL)\n (void) CopyMagickString(cin.origination.serial,value,\n sizeof(cin.origination.serial));\n offset+=WriteBlob(image,sizeof(cin.origination.serial),(unsigned char *)\n cin.origination.serial);\n cin.origination.x_pitch=0.0f;\n value=GetCINProperty(image_info,image,\"dpx:origination.x_pitch\");\n if (value != (const char *) NULL)\n cin.origination.x_pitch=StringToDouble(value,(char **) NULL);\n offset+=WriteBlobFloat(image,cin.origination.x_pitch);\n cin.origination.y_pitch=0.0f;\n value=GetCINProperty(image_info,image,\"dpx:origination.y_pitch\");\n if (value != (const char *) NULL)\n cin.origination.y_pitch=StringToDouble(value,(char **) NULL);\n offset+=WriteBlobFloat(image,cin.origination.y_pitch);\n cin.origination.gamma=image->gamma;\n offset+=WriteBlobFloat(image,cin.origination.gamma);\n offset+=WriteBlob(image,sizeof(cin.origination.reserve),(unsigned char *)\n cin.origination.reserve);\n /*\n Image film information.\n */\n cin.film.id=0;\n value=GetCINProperty(image_info,image,\"dpx:film.id\");\n if (value != (const char *) NULL)\n cin.film.id=(char) StringToLong(value);\n offset+=WriteBlobByte(image,(unsigned char) cin.film.id);\n cin.film.type=0;\n value=GetCINProperty(image_info,image,\"dpx:film.type\");\n if (value != (const char *) NULL)\n cin.film.type=(char) StringToLong(value);\n offset+=WriteBlobByte(image,(unsigned char) cin.film.type);\n cin.film.offset=0;\n value=GetCINProperty(image_info,image,\"dpx:film.offset\");\n if (value != (const char *) NULL)\n cin.film.offset=(char) StringToLong(value);\n offset+=WriteBlobByte(image,(unsigned char) cin.film.offset);\n offset+=WriteBlobByte(image,(unsigned char) cin.film.reserve1);\n cin.film.prefix=0UL;\n value=GetCINProperty(image_info,image,\"dpx:film.prefix\");\n if (value != (const char *) NULL)\n cin.film.prefix=StringToUnsignedLong(value);\n offset+=WriteBlobLong(image,(unsigned int) cin.film.prefix);\n cin.film.count=0UL;\n value=GetCINProperty(image_info,image,\"dpx:film.count\");\n if (value != (const char *) NULL)\n cin.film.count=StringToUnsignedLong(value);\n offset+=WriteBlobLong(image,(unsigned int) cin.film.count);\n value=GetCINProperty(image_info,image,\"dpx:film.format\");\n if (value != (const char *) NULL)\n (void) CopyMagickString(cin.film.format,value,sizeof(cin.film.format));\n offset+=WriteBlob(image,sizeof(cin.film.format),(unsigned char *)\n cin.film.format);\n cin.film.frame_position=0UL;\n value=GetCINProperty(image_info,image,\"dpx:film.frame_position\");\n if (value != (const char *) NULL)\n cin.film.frame_position=StringToUnsignedLong(value);\n offset+=WriteBlobLong(image,(unsigned int) cin.film.frame_position);\n cin.film.frame_rate=0.0f;\n value=GetCINProperty(image_info,image,\"dpx:film.frame_rate\");\n if (value != (const char *) NULL)\n cin.film.frame_rate=StringToDouble(value,(char **) NULL);\n offset+=WriteBlobFloat(image,cin.film.frame_rate);\n value=GetCINProperty(image_info,image,\"dpx:film.frame_id\");\n if (value != (const char *) NULL)\n (void) CopyMagickString(cin.film.frame_id,value,sizeof(cin.film.frame_id));\n offset+=WriteBlob(image,sizeof(cin.film.frame_id),(unsigned char *)\n cin.film.frame_id);\n value=GetCINProperty(image_info,image,\"dpx:film.slate_info\");\n if (value != (const char *) NULL)\n (void) CopyMagickString(cin.film.slate_info,value,\n sizeof(cin.film.slate_info));\n offset+=WriteBlob(image,sizeof(cin.film.slate_info),(unsigned char *)\n cin.film.slate_info);\n offset+=WriteBlob(image,sizeof(cin.film.reserve),(unsigned char *)\n cin.film.reserve);\n if (profile != (StringInfo *) NULL)\n offset+=WriteBlob(image,GetStringInfoLength(profile),\n GetStringInfoDatum(profile));\n while (offset < (MagickOffsetType) cin.file.image_offset)\n offset+=WriteBlobByte(image,0x00);\n /*\n Convert pixel packets to CIN raster image.\n */\n quantum_info=AcquireQuantumInfo(image_info,image);\n if (quantum_info == (QuantumInfo *) NULL)\n ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\");\n quantum_info->quantum=32;\n quantum_info->pack=MagickFalse;\n quantum_type=RGBQuantum;\n pixels=GetQuantumPixels(quantum_info);\n length=GetBytesPerRow(image->columns,3,image->depth,MagickTrue);\nDisableMSCWarning(4127)\n if (0)\nRestoreMSCWarning\n {\n quantum_type=GrayQuantum;\n length=GetBytesPerRow(image->columns,1UL,image->depth,MagickTrue);\n }\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);\n if (p == (const PixelPacket *) NULL)\n break;\n (void) ExportQuantumPixels(image,(const CacheView *) NULL,quantum_info,\n quantum_type,pixels,&image->exception);\n count=WriteBlob(image,length,pixels);\n if (count != (ssize_t) length)\n break;\n status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,\n image->rows);\n if (status == MagickFalse)\n break;\n }\n quantum_info=DestroyQuantumInfo(quantum_info);\n (void) CloseBlob(image);\n return(status);\n}\n", + "line": null, + "label": 0, + "cwe": "CWE-119", + "cve": "CVE-2016-10066", + "length": 3698 + }, + { + "index": 44885, + "code": "static int ext4_ext_split(handle_t *handle, struct inode *inode,\n\t\t\t unsigned int flags,\n\t\t\t struct ext4_ext_path *path,\n\t\t\t struct ext4_extent *newext, int at)\n{\n\tstruct buffer_head *bh = NULL;\n\tint depth = ext_depth(inode);\n\tstruct ext4_extent_header *neh;\n\tstruct ext4_extent_idx *fidx;\n\tint i = at, k, m, a;\n\text4_fsblk_t newblock, oldblock;\n\t__le32 border;\n\text4_fsblk_t *ablocks = NULL; /* array of allocated blocks */\n\tint err = 0;\n\n\t/* make decision: where to split? */\n\t/* FIXME: now decision is simplest: at current extent */\n\n\t/* if current leaf will be split, then we should use\n\t * border from split point */\n\tif (unlikely(path[depth].p_ext > EXT_MAX_EXTENT(path[depth].p_hdr))) {\n\t\tEXT4_ERROR_INODE(inode, \"p_ext > EXT_MAX_EXTENT!\");\n\t\treturn -EIO;\n\t}\n\tif (path[depth].p_ext != EXT_MAX_EXTENT(path[depth].p_hdr)) {\n\t\tborder = path[depth].p_ext[1].ee_block;\n\t\text_debug(\"leaf will be split.\"\n\t\t\t\t\" next leaf starts at %d\\n\",\n\t\t\t\t le32_to_cpu(border));\n\t} else {\n\t\tborder = newext->ee_block;\n\t\text_debug(\"leaf will be added.\"\n\t\t\t\t\" next leaf starts at %d\\n\",\n\t\t\t\tle32_to_cpu(border));\n\t}\n\n\t/*\n\t * If error occurs, then we break processing\n\t * and mark filesystem read-only. index won't\n\t * be inserted and tree will be in consistent\n\t * state. Next mount will repair buffers too.\n\t */\n\n\t/*\n\t * Get array to track all allocated blocks.\n\t * We need this to handle errors and free blocks\n\t * upon them.\n\t */\n\tablocks = kzalloc(sizeof(ext4_fsblk_t) * depth, GFP_NOFS);\n\tif (!ablocks)\n\t\treturn -ENOMEM;\n\n\t/* allocate all needed blocks */\n\text_debug(\"allocate %d blocks for indexes/leaf\\n\", depth - at);\n\tfor (a = 0; a < depth - at; a++) {\n\t\tnewblock = ext4_ext_new_meta_block(handle, inode, path,\n\t\t\t\t\t\t newext, &err, flags);\n\t\tif (newblock == 0)\n\t\t\tgoto cleanup;\n\t\tablocks[a] = newblock;\n\t}\n\n\t/* initialize new leaf */\n\tnewblock = ablocks[--a];\n\tif (unlikely(newblock == 0)) {\n\t\tEXT4_ERROR_INODE(inode, \"newblock == 0!\");\n\t\terr = -EIO;\n\t\tgoto cleanup;\n\t}\n\tbh = sb_getblk(inode->i_sb, newblock);\n\tif (unlikely(!bh)) {\n\t\terr = -ENOMEM;\n\t\tgoto cleanup;\n\t}\n\tlock_buffer(bh);\n\n\terr = ext4_journal_get_create_access(handle, bh);\n\tif (err)\n\t\tgoto cleanup;\n\n\tneh = ext_block_hdr(bh);\n\tneh->eh_entries = 0;\n\tneh->eh_max = cpu_to_le16(ext4_ext_space_block(inode, 0));\n\tneh->eh_magic = EXT4_EXT_MAGIC;\n\tneh->eh_depth = 0;\n\n\t/* move remainder of path[depth] to the new leaf */\n\tif (unlikely(path[depth].p_hdr->eh_entries !=\n\t\t path[depth].p_hdr->eh_max)) {\n\t\tEXT4_ERROR_INODE(inode, \"eh_entries %d != eh_max %d!\",\n\t\t\t\t path[depth].p_hdr->eh_entries,\n\t\t\t\t path[depth].p_hdr->eh_max);\n\t\terr = -EIO;\n\t\tgoto cleanup;\n\t}\n\t/* start copy from next extent */\n\tm = EXT_MAX_EXTENT(path[depth].p_hdr) - path[depth].p_ext++;\n\text4_ext_show_move(inode, path, newblock, depth);\n\tif (m) {\n\t\tstruct ext4_extent *ex;\n\t\tex = EXT_FIRST_EXTENT(neh);\n\t\tmemmove(ex, path[depth].p_ext, sizeof(struct ext4_extent) * m);\n\t\tle16_add_cpu(&neh->eh_entries, m);\n\t}\n\n\text4_extent_block_csum_set(inode, neh);\n\tset_buffer_uptodate(bh);\n\tunlock_buffer(bh);\n\n\terr = ext4_handle_dirty_metadata(handle, inode, bh);\n\tif (err)\n\t\tgoto cleanup;\n\tbrelse(bh);\n\tbh = NULL;\n\n\t/* correct old leaf */\n\tif (m) {\n\t\terr = ext4_ext_get_access(handle, inode, path + depth);\n\t\tif (err)\n\t\t\tgoto cleanup;\n\t\tle16_add_cpu(&path[depth].p_hdr->eh_entries, -m);\n\t\terr = ext4_ext_dirty(handle, inode, path + depth);\n\t\tif (err)\n\t\t\tgoto cleanup;\n\n\t}\n\n\t/* create intermediate indexes */\n\tk = depth - at - 1;\n\tif (unlikely(k < 0)) {\n\t\tEXT4_ERROR_INODE(inode, \"k %d < 0!\", k);\n\t\terr = -EIO;\n\t\tgoto cleanup;\n\t}\n\tif (k)\n\t\text_debug(\"create %d intermediate indices\\n\", k);\n\t/* insert new index into current index block */\n\t/* current depth stored in i var */\n\ti = depth - 1;\n\twhile (k--) {\n\t\toldblock = newblock;\n\t\tnewblock = ablocks[--a];\n\t\tbh = sb_getblk(inode->i_sb, newblock);\n\t\tif (unlikely(!bh)) {\n\t\t\terr = -ENOMEM;\n\t\t\tgoto cleanup;\n\t\t}\n\t\tlock_buffer(bh);\n\n\t\terr = ext4_journal_get_create_access(handle, bh);\n\t\tif (err)\n\t\t\tgoto cleanup;\n\n\t\tneh = ext_block_hdr(bh);\n\t\tneh->eh_entries = cpu_to_le16(1);\n\t\tneh->eh_magic = EXT4_EXT_MAGIC;\n\t\tneh->eh_max = cpu_to_le16(ext4_ext_space_block_idx(inode, 0));\n\t\tneh->eh_depth = cpu_to_le16(depth - i);\n\t\tfidx = EXT_FIRST_INDEX(neh);\n\t\tfidx->ei_block = border;\n\t\text4_idx_store_pblock(fidx, oldblock);\n\n\t\text_debug(\"int.index at %d (block %llu): %u -> %llu\\n\",\n\t\t\t\ti, newblock, le32_to_cpu(border), oldblock);\n\n\t\t/* move remainder of path[i] to the new index block */\n\t\tif (unlikely(EXT_MAX_INDEX(path[i].p_hdr) !=\n\t\t\t\t\tEXT_LAST_INDEX(path[i].p_hdr))) {\n\t\t\tEXT4_ERROR_INODE(inode,\n\t\t\t\t\t \"EXT_MAX_INDEX != EXT_LAST_INDEX ee_block %d!\",\n\t\t\t\t\t le32_to_cpu(path[i].p_ext->ee_block));\n\t\t\terr = -EIO;\n\t\t\tgoto cleanup;\n\t\t}\n\t\t/* start copy indexes */\n\t\tm = EXT_MAX_INDEX(path[i].p_hdr) - path[i].p_idx++;\n\t\text_debug(\"cur 0x%p, last 0x%p\\n\", path[i].p_idx,\n\t\t\t\tEXT_MAX_INDEX(path[i].p_hdr));\n\t\text4_ext_show_move(inode, path, newblock, i);\n\t\tif (m) {\n\t\t\tmemmove(++fidx, path[i].p_idx,\n\t\t\t\tsizeof(struct ext4_extent_idx) * m);\n\t\t\tle16_add_cpu(&neh->eh_entries, m);\n\t\t}\n\t\text4_extent_block_csum_set(inode, neh);\n\t\tset_buffer_uptodate(bh);\n\t\tunlock_buffer(bh);\n\n\t\terr = ext4_handle_dirty_metadata(handle, inode, bh);\n\t\tif (err)\n\t\t\tgoto cleanup;\n\t\tbrelse(bh);\n\t\tbh = NULL;\n\n\t\t/* correct old index */\n\t\tif (m) {\n\t\t\terr = ext4_ext_get_access(handle, inode, path + i);\n\t\t\tif (err)\n\t\t\t\tgoto cleanup;\n\t\t\tle16_add_cpu(&path[i].p_hdr->eh_entries, -m);\n\t\t\terr = ext4_ext_dirty(handle, inode, path + i);\n\t\t\tif (err)\n\t\t\t\tgoto cleanup;\n\t\t}\n\n\t\ti--;\n\t}\n\n\t/* insert new index */\n\terr = ext4_ext_insert_index(handle, inode, path + at,\n\t\t\t\t le32_to_cpu(border), newblock);\n\ncleanup:\n\tif (bh) {\n\t\tif (buffer_locked(bh))\n\t\t\tunlock_buffer(bh);\n\t\tbrelse(bh);\n\t}\n\n\tif (err) {\n\t\t/* free all allocated blocks in error case */\n\t\tfor (i = 0; i < depth; i++) {\n\t\t\tif (!ablocks[i])\n\t\t\t\tcontinue;\n\t\t\text4_free_blocks(handle, inode, NULL, ablocks[i], 1,\n\t\t\t\t\t EXT4_FREE_BLOCKS_METADATA);\n\t\t}\n\t}\n\tkfree(ablocks);\n\n\treturn err;\n}\n", + "line": null, + "label": 0, + "cwe": "CWE-17", + "cve": "CVE-2015-0275", + "length": 1864 + }, + { + "index": 11719, + "code": "get_property (GObject *object,\n guint prop_id,\n GValue *value,\n GParamSpec *pspec)\n{\n Device *device = DEVICE (object);\n\n switch (prop_id)\n {\n case PROP_NATIVE_PATH:\n g_value_set_string (value, device->priv->native_path);\n break;\n\n case PROP_DEVICE_DETECTION_TIME:\n g_value_set_uint64 (value, device->priv->device_detection_time);\n break;\n case PROP_DEVICE_MEDIA_DETECTION_TIME:\n g_value_set_uint64 (value, device->priv->device_media_detection_time);\n break;\n case PROP_DEVICE_MAJOR:\n g_value_set_int64 (value, major (device->priv->dev));\n break;\n case PROP_DEVICE_MINOR:\n g_value_set_int64 (value, minor (device->priv->dev));\n break;\n case PROP_DEVICE_FILE:\n g_value_set_string (value, device->priv->device_file);\n break;\n case PROP_DEVICE_FILE_PRESENTATION:\n if (device->priv->device_file_presentation != NULL)\n g_value_set_string (value, device->priv->device_file_presentation);\n else\n g_value_set_string (value, device->priv->device_file);\n break;\n case PROP_DEVICE_FILE_BY_ID:\n g_value_set_boxed (value, device->priv->device_file_by_id);\n break;\n case PROP_DEVICE_FILE_BY_PATH:\n g_value_set_boxed (value, device->priv->device_file_by_path);\n break;\n case PROP_DEVICE_IS_SYSTEM_INTERNAL:\n g_value_set_boolean (value, device->priv->device_is_system_internal);\n break;\n case PROP_DEVICE_IS_PARTITION:\n g_value_set_boolean (value, device->priv->device_is_partition);\n break;\n case PROP_DEVICE_IS_PARTITION_TABLE:\n g_value_set_boolean (value, device->priv->device_is_partition_table);\n break;\n case PROP_DEVICE_IS_REMOVABLE:\n g_value_set_boolean (value, device->priv->device_is_removable);\n break;\n case PROP_DEVICE_IS_MEDIA_AVAILABLE:\n g_value_set_boolean (value, device->priv->device_is_media_available);\n break;\n case PROP_DEVICE_IS_MEDIA_CHANGE_DETECTED:\n g_value_set_boolean (value, device->priv->device_is_media_change_detected);\n break;\n case PROP_DEVICE_IS_MEDIA_CHANGE_DETECTION_POLLING:\n g_value_set_boolean (value, device->priv->device_is_media_change_detection_polling);\n break;\n case PROP_DEVICE_IS_MEDIA_CHANGE_DETECTION_INHIBITABLE:\n g_value_set_boolean (value, device->priv->device_is_media_change_detection_inhibitable);\n break;\n case PROP_DEVICE_IS_MEDIA_CHANGE_DETECTION_INHIBITED:\n g_value_set_boolean (value, device->priv->device_is_media_change_detection_inhibited);\n break;\n case PROP_DEVICE_IS_READ_ONLY:\n g_value_set_boolean (value, device->priv->device_is_read_only);\n break;\n case PROP_DEVICE_IS_DRIVE:\n g_value_set_boolean (value, device->priv->device_is_drive);\n break;\n case PROP_DEVICE_IS_OPTICAL_DISC:\n g_value_set_boolean (value, device->priv->device_is_optical_disc);\n break;\n case PROP_DEVICE_IS_LUKS:\n g_value_set_boolean (value, device->priv->device_is_luks);\n break;\n case PROP_DEVICE_IS_LUKS_CLEARTEXT:\n g_value_set_boolean (value, device->priv->device_is_luks_cleartext);\n break;\n case PROP_DEVICE_IS_LINUX_MD_COMPONENT:\n g_value_set_boolean (value, device->priv->device_is_linux_md_component);\n break;\n case PROP_DEVICE_IS_LINUX_MD:\n g_value_set_boolean (value, device->priv->device_is_linux_md);\n break;\n case PROP_DEVICE_IS_LINUX_LVM2_LV:\n g_value_set_boolean (value, device->priv->device_is_linux_lvm2_lv);\n break;\n case PROP_DEVICE_IS_LINUX_LVM2_PV:\n g_value_set_boolean (value, device->priv->device_is_linux_lvm2_pv);\n break;\n case PROP_DEVICE_IS_LINUX_DMMP:\n g_value_set_boolean (value, device->priv->device_is_linux_dmmp);\n break;\n case PROP_DEVICE_IS_LINUX_DMMP_COMPONENT:\n g_value_set_boolean (value, device->priv->device_is_linux_dmmp_component);\n break;\n case PROP_DEVICE_IS_LINUX_LOOP:\n g_value_set_boolean (value, device->priv->device_is_linux_loop);\n break;\n case PROP_DEVICE_SIZE:\n g_value_set_uint64 (value, device->priv->device_size);\n break;\n case PROP_DEVICE_BLOCK_SIZE:\n g_value_set_uint64 (value, device->priv->device_block_size);\n break;\n case PROP_DEVICE_IS_MOUNTED:\n g_value_set_boolean (value, device->priv->device_is_mounted);\n break;\n case PROP_DEVICE_MOUNT_PATHS:\n g_value_set_boxed (value, device->priv->device_mount_paths);\n break;\n case PROP_DEVICE_MOUNTED_BY_UID:\n g_value_set_uint (value, device->priv->device_mounted_by_uid);\n break;\n case PROP_DEVICE_PRESENTATION_HIDE:\n g_value_set_boolean (value, device->priv->device_presentation_hide);\n break;\n case PROP_DEVICE_PRESENTATION_NOPOLICY:\n g_value_set_boolean (value, device->priv->device_presentation_nopolicy);\n break;\n case PROP_DEVICE_PRESENTATION_NAME:\n g_value_set_string (value, device->priv->device_presentation_name);\n break;\n case PROP_DEVICE_PRESENTATION_ICON_NAME:\n g_value_set_string (value, device->priv->device_presentation_icon_name);\n break;\n\n case PROP_JOB_IN_PROGRESS:\n g_value_set_boolean (value, device->priv->job_in_progress);\n break;\n case PROP_JOB_ID:\n g_value_set_string (value, device->priv->job_id);\n break;\n case PROP_JOB_INITIATED_BY_UID:\n g_value_set_uint (value, device->priv->job_initiated_by_uid);\n break;\n case PROP_JOB_IS_CANCELLABLE:\n g_value_set_boolean (value, device->priv->job_is_cancellable);\n break;\n case PROP_JOB_PERCENTAGE:\n g_value_set_double (value, device->priv->job_percentage);\n break;\n\n case PROP_ID_USAGE:\n g_value_set_string (value, device->priv->id_usage);\n break;\n case PROP_ID_TYPE:\n g_value_set_string (value, device->priv->id_type);\n break;\n case PROP_ID_VERSION:\n g_value_set_string (value, device->priv->id_version);\n break;\n case PROP_ID_UUID:\n g_value_set_string (value, device->priv->id_uuid);\n break;\n case PROP_ID_LABEL:\n g_value_set_string (value, device->priv->id_label);\n break;\n\n case PROP_PARTITION_SLAVE:\n if (device->priv->partition_slave != NULL)\n g_value_set_boxed (value, device->priv->partition_slave);\n else\n g_value_set_boxed (value, \"/\");\n break;\n case PROP_PARTITION_SCHEME:\n g_value_set_string (value, device->priv->partition_scheme);\n break;\n case PROP_PARTITION_TYPE:\n g_value_set_string (value, device->priv->partition_type);\n break;\n case PROP_PARTITION_LABEL:\n g_value_set_string (value, device->priv->partition_label);\n break;\n case PROP_PARTITION_UUID:\n g_value_set_string (value, device->priv->partition_uuid);\n break;\n case PROP_PARTITION_FLAGS:\n g_value_set_boxed (value, device->priv->partition_flags);\n break;\n case PROP_PARTITION_NUMBER:\n g_value_set_int (value, device->priv->partition_number);\n break;\n case PROP_PARTITION_OFFSET:\n g_value_set_uint64 (value, device->priv->partition_offset);\n break;\n case PROP_PARTITION_SIZE:\n g_value_set_uint64 (value, device->priv->partition_size);\n break;\n case PROP_PARTITION_ALIGNMENT_OFFSET:\n g_value_set_uint64 (value, device->priv->partition_alignment_offset);\n break;\n\n case PROP_PARTITION_TABLE_SCHEME:\n g_value_set_string (value, device->priv->partition_table_scheme);\n break;\n case PROP_PARTITION_TABLE_COUNT:\n g_value_set_int (value, device->priv->partition_table_count);\n break;\n\n case PROP_LUKS_HOLDER:\n if (device->priv->luks_holder != NULL)\n g_value_set_boxed (value, device->priv->luks_holder);\n else\n g_value_set_boxed (value, \"/\");\n break;\n\n case PROP_LUKS_CLEARTEXT_SLAVE:\n if (device->priv->luks_cleartext_slave != NULL)\n g_value_set_boxed (value, device->priv->luks_cleartext_slave);\n else\n g_value_set_boxed (value, \"/\");\n break;\n case PROP_LUKS_CLEARTEXT_UNLOCKED_BY_UID:\n g_value_set_uint (value, device->priv->luks_cleartext_unlocked_by_uid);\n break;\n\n case PROP_DRIVE_VENDOR:\n g_value_set_string (value, device->priv->drive_vendor);\n break;\n case PROP_DRIVE_MODEL:\n g_value_set_string (value, device->priv->drive_model);\n break;\n case PROP_DRIVE_REVISION:\n g_value_set_string (value, device->priv->drive_revision);\n break;\n case PROP_DRIVE_SERIAL:\n g_value_set_string (value, device->priv->drive_serial);\n break;\n case PROP_DRIVE_WWN:\n g_value_set_string (value, device->priv->drive_wwn);\n break;\n case PROP_DRIVE_CONNECTION_INTERFACE:\n g_value_set_string (value, device->priv->drive_connection_interface);\n break;\n case PROP_DRIVE_CONNECTION_SPEED:\n g_value_set_uint64 (value, device->priv->drive_connection_speed);\n break;\n case PROP_DRIVE_MEDIA_COMPATIBILITY:\n g_value_set_boxed (value, device->priv->drive_media_compatibility);\n break;\n case PROP_DRIVE_MEDIA:\n g_value_set_string (value, device->priv->drive_media);\n break;\n case PROP_DRIVE_IS_MEDIA_EJECTABLE:\n g_value_set_boolean (value, device->priv->drive_is_media_ejectable);\n break;\n case PROP_DRIVE_CAN_DETACH:\n g_value_set_boolean (value, device->priv->drive_can_detach);\n break;\n case PROP_DRIVE_CAN_SPINDOWN:\n g_value_set_boolean (value, device->priv->drive_can_spindown);\n break;\n case PROP_DRIVE_IS_ROTATIONAL:\n g_value_set_boolean (value, device->priv->drive_is_rotational);\n break;\n case PROP_DRIVE_WRITE_CACHE:\n g_value_set_string (value, device->priv->drive_write_cache);\n break;\n case PROP_DRIVE_ROTATION_RATE:\n g_value_set_uint (value, device->priv->drive_rotation_rate);\n break;\n case PROP_DRIVE_ADAPTER:\n if (device->priv->drive_adapter != NULL)\n g_value_set_boxed (value, device->priv->drive_adapter);\n else\n g_value_set_boxed (value, \"/\");\n break;\n case PROP_DRIVE_PORTS:\n g_value_set_boxed (value, device->priv->drive_ports);\n break;\n case PROP_DRIVE_SIMILAR_DEVICES:\n g_value_set_boxed (value, device->priv->drive_similar_devices);\n break;\n\n case PROP_OPTICAL_DISC_IS_BLANK:\n g_value_set_boolean (value, device->priv->optical_disc_is_blank);\n break;\n case PROP_OPTICAL_DISC_IS_APPENDABLE:\n g_value_set_boolean (value, device->priv->optical_disc_is_appendable);\n break;\n case PROP_OPTICAL_DISC_IS_CLOSED:\n g_value_set_boolean (value, device->priv->optical_disc_is_closed);\n break;\n case PROP_OPTICAL_DISC_NUM_TRACKS:\n g_value_set_uint (value, device->priv->optical_disc_num_tracks);\n break;\n case PROP_OPTICAL_DISC_NUM_AUDIO_TRACKS:\n g_value_set_uint (value, device->priv->optical_disc_num_audio_tracks);\n break;\n case PROP_OPTICAL_DISC_NUM_SESSIONS:\n g_value_set_uint (value, device->priv->optical_disc_num_sessions);\n break;\n\n case PROP_DRIVE_ATA_SMART_IS_AVAILABLE:\n g_value_set_boolean (value, device->priv->drive_ata_smart_is_available);\n break;\n case PROP_DRIVE_ATA_SMART_TIME_COLLECTED:\n g_value_set_uint64 (value, device->priv->drive_ata_smart_time_collected);\n break;\n case PROP_DRIVE_ATA_SMART_STATUS:\n {\n const gchar *status;\n if (device->priv->drive_ata_smart_status == (SkSmartOverall) - 1)\n status = \"\";\n else\n status = sk_smart_overall_to_string (device->priv->drive_ata_smart_status);\n g_value_set_string (value, status);\n }\n break;\n case PROP_DRIVE_ATA_SMART_BLOB:\n {\n GArray *a;\n a = g_array_new (FALSE, FALSE, 1);\n if (device->priv->drive_ata_smart_blob != NULL)\n {\n g_array_append_vals (a, device->priv->drive_ata_smart_blob, device->priv->drive_ata_smart_blob_size);\n }\n g_value_set_boxed (value, a);\n g_array_unref (a);\n }\n break;\n\n case PROP_LINUX_MD_COMPONENT_LEVEL:\n g_value_set_string (value, device->priv->linux_md_component_level);\n break;\n case PROP_LINUX_MD_COMPONENT_POSITION:\n g_value_set_int (value, device->priv->linux_md_component_position);\n break;\n case PROP_LINUX_MD_COMPONENT_NUM_RAID_DEVICES:\n g_value_set_int (value, device->priv->linux_md_component_num_raid_devices);\n break;\n case PROP_LINUX_MD_COMPONENT_UUID:\n g_value_set_string (value, device->priv->linux_md_component_uuid);\n break;\n case PROP_LINUX_MD_COMPONENT_HOME_HOST:\n g_value_set_string (value, device->priv->linux_md_component_home_host);\n break;\n case PROP_LINUX_MD_COMPONENT_NAME:\n g_value_set_string (value, device->priv->linux_md_component_name);\n break;\n case PROP_LINUX_MD_COMPONENT_VERSION:\n g_value_set_string (value, device->priv->linux_md_component_version);\n break;\n case PROP_LINUX_MD_COMPONENT_HOLDER:\n if (device->priv->linux_md_component_holder != NULL)\n g_value_set_boxed (value, device->priv->linux_md_component_holder);\n else\n g_value_set_boxed (value, \"/\");\n break;\n case PROP_LINUX_MD_COMPONENT_STATE:\n g_value_set_boxed (value, device->priv->linux_md_component_state);\n break;\n\n case PROP_LINUX_MD_STATE:\n g_value_set_string (value, device->priv->linux_md_state);\n break;\n case PROP_LINUX_MD_LEVEL:\n g_value_set_string (value, device->priv->linux_md_level);\n break;\n case PROP_LINUX_MD_NUM_RAID_DEVICES:\n g_value_set_int (value, device->priv->linux_md_num_raid_devices);\n break;\n case PROP_LINUX_MD_UUID:\n g_value_set_string (value, device->priv->linux_md_uuid);\n break;\n case PROP_LINUX_MD_HOME_HOST:\n g_value_set_string (value, device->priv->linux_md_home_host);\n break;\n case PROP_LINUX_MD_NAME:\n g_value_set_string (value, device->priv->linux_md_name);\n break;\n case PROP_LINUX_MD_VERSION:\n g_value_set_string (value, device->priv->linux_md_version);\n break;\n case PROP_LINUX_MD_SLAVES:\n g_value_set_boxed (value, device->priv->linux_md_slaves);\n break;\n case PROP_LINUX_MD_IS_DEGRADED:\n g_value_set_boolean (value, device->priv->linux_md_is_degraded);\n break;\n case PROP_LINUX_MD_SYNC_ACTION:\n g_value_set_string (value, device->priv->linux_md_sync_action);\n break;\n case PROP_LINUX_MD_SYNC_PERCENTAGE:\n g_value_set_double (value, device->priv->linux_md_sync_percentage);\n break;\n case PROP_LINUX_MD_SYNC_SPEED:\n g_value_set_uint64 (value, device->priv->linux_md_sync_speed);\n break;\n\n case PROP_LINUX_LVM2_LV_NAME:\n g_value_set_string (value, device->priv->linux_lvm2_lv_name);\n break;\n case PROP_LINUX_LVM2_LV_UUID:\n g_value_set_string (value, device->priv->linux_lvm2_lv_uuid);\n break;\n case PROP_LINUX_LVM2_LV_GROUP_NAME:\n g_value_set_string (value, device->priv->linux_lvm2_lv_group_name);\n break;\n case PROP_LINUX_LVM2_LV_GROUP_UUID:\n g_value_set_string (value, device->priv->linux_lvm2_lv_group_uuid);\n break;\n\n case PROP_LINUX_LVM2_PV_UUID:\n g_value_set_string (value, device->priv->linux_lvm2_pv_uuid);\n break;\n case PROP_LINUX_LVM2_PV_NUM_METADATA_AREAS:\n g_value_set_uint (value, device->priv->linux_lvm2_pv_num_metadata_areas);\n break;\n case PROP_LINUX_LVM2_PV_GROUP_NAME:\n g_value_set_string (value, device->priv->linux_lvm2_pv_group_name);\n break;\n case PROP_LINUX_LVM2_PV_GROUP_UUID:\n g_value_set_string (value, device->priv->linux_lvm2_pv_group_uuid);\n break;\n case PROP_LINUX_LVM2_PV_GROUP_SIZE:\n g_value_set_uint64 (value, device->priv->linux_lvm2_pv_group_size);\n break;\n case PROP_LINUX_LVM2_PV_GROUP_UNALLOCATED_SIZE:\n g_value_set_uint64 (value, device->priv->linux_lvm2_pv_group_unallocated_size);\n break;\n case PROP_LINUX_LVM2_PV_GROUP_SEQUENCE_NUMBER:\n g_value_set_uint64 (value, device->priv->linux_lvm2_pv_group_sequence_number);\n break;\n case PROP_LINUX_LVM2_PV_GROUP_EXTENT_SIZE:\n g_value_set_uint64 (value, device->priv->linux_lvm2_pv_group_extent_size);\n break;\n case PROP_LINUX_LVM2_PV_GROUP_PHYSICAL_VOLUMES:\n g_value_set_boxed (value, device->priv->linux_lvm2_pv_group_physical_volumes);\n break;\n case PROP_LINUX_LVM2_PV_GROUP_LOGICAL_VOLUMES:\n g_value_set_boxed (value, device->priv->linux_lvm2_pv_group_logical_volumes);\n break;\n\n case PROP_LINUX_DMMP_COMPONENT_HOLDER:\n if (device->priv->linux_dmmp_component_holder != NULL)\n g_value_set_boxed (value, device->priv->linux_dmmp_component_holder);\n else\n g_value_set_boxed (value, \"/\");\n break;\n\n case PROP_LINUX_DMMP_NAME:\n g_value_set_string (value, device->priv->linux_dmmp_name);\n break;\n\n case PROP_LINUX_DMMP_PARAMETERS:\n g_value_set_string (value, device->priv->linux_dmmp_parameters);\n break;\n\n case PROP_LINUX_DMMP_SLAVES:\n g_value_set_boxed (value, device->priv->linux_dmmp_slaves);\n break;\n\n case PROP_LINUX_LOOP_FILENAME:\n g_value_set_string (value, device->priv->linux_loop_filename);\n break;\n\n default:\n G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);\n break;\n }\n}\n", + "line": null, + "label": 0, + "cwe": "CWE-200", + "cve": "CVE-2010-1149", + "length": 4265 + }, + { + "index": 8891, + "code": "static void vrend_renderer_blit_int(struct vrend_context *ctx,\n struct vrend_resource *src_res,\n struct vrend_resource *dst_res,\n const struct pipe_blit_info *info)\n{\n GLbitfield glmask = 0;\n int src_y1, src_y2, dst_y1, dst_y2;\n GLenum filter;\n int n_layers = 1, i;\n bool use_gl = false;\n\n filter = convert_mag_filter(info->filter);\n\n /* if we can't make FBO's use the fallback path */\n if (!vrend_format_can_render(src_res->base.format) &&\n !vrend_format_is_ds(src_res->base.format))\n use_gl = true;\n if (!vrend_format_can_render(dst_res->base.format) &&\n !vrend_format_is_ds(dst_res->base.format))\n use_gl = true;\n\n /* different depth formats */\n if (vrend_format_is_ds(src_res->base.format) &&\n vrend_format_is_ds(dst_res->base.format)) {\n if (src_res->base.format != dst_res->base.format) {\n if (!(src_res->base.format == PIPE_FORMAT_S8_UINT_Z24_UNORM &&\n (dst_res->base.format == PIPE_FORMAT_Z24X8_UNORM))) {\n use_gl = true;\n }\n }\n }\n /* glBlitFramebuffer - can support depth stencil with NEAREST\n which we use for mipmaps */\n if ((info->mask & (PIPE_MASK_Z | PIPE_MASK_S)) && info->filter == PIPE_TEX_FILTER_LINEAR)\n use_gl = true;\n\n /* for scaled MS blits we either need extensions or hand roll */\n if (src_res->base.nr_samples > 1 &&\n src_res->base.nr_samples != dst_res->base.nr_samples &&\n (info->src.box.width != info->dst.box.width ||\n info->src.box.height != info->dst.box.height)) {\n if (vrend_state.have_ms_scaled_blit)\n filter = GL_SCALED_RESOLVE_NICEST_EXT;\n else\n use_gl = true;\n }\n\n /* for 3D mipmapped blits - hand roll time */\n if (info->src.box.depth != info->dst.box.depth)\n use_gl = true;\n\n if (vrend_format_is_emulated_alpha(info->dst.format) ||\n vrend_format_is_emulated_alpha(info->src.format))\n use_gl = true;\n\n if (use_gl) {\n vrend_renderer_blit_gl(ctx, src_res, dst_res, info);\n vrend_clicbs->make_current(0, ctx->sub->gl_context);\n return;\n }\n\n if (info->mask & PIPE_MASK_Z)\n glmask |= GL_DEPTH_BUFFER_BIT;\n if (info->mask & PIPE_MASK_S)\n glmask |= GL_STENCIL_BUFFER_BIT;\n if (info->mask & PIPE_MASK_RGBA)\n glmask |= GL_COLOR_BUFFER_BIT;\n\n if (!dst_res->y_0_top) {\n dst_y1 = info->dst.box.y + info->dst.box.height;\n dst_y2 = info->dst.box.y;\n } else {\n dst_y1 = dst_res->base.height0 - info->dst.box.y - info->dst.box.height;\n dst_y2 = dst_res->base.height0 - info->dst.box.y;\n }\n\n if (!src_res->y_0_top) {\n src_y1 = info->src.box.y + info->src.box.height;\n src_y2 = info->src.box.y;\n } else {\n src_y1 = src_res->base.height0 - info->src.box.y - info->src.box.height;\n src_y2 = src_res->base.height0 - info->src.box.y;\n }\n\n if (info->scissor_enable) {\n glScissor(info->scissor.minx, info->scissor.miny, info->scissor.maxx - info->scissor.minx, info->scissor.maxy - info->scissor.miny);\n ctx->sub->scissor_state_dirty = (1 << 0);\n glEnable(GL_SCISSOR_TEST);\n } else\n glDisable(GL_SCISSOR_TEST);\n\n glBindFramebuffer(GL_FRAMEBUFFER_EXT, ctx->sub->blit_fb_ids[0]);\n if (info->mask & PIPE_MASK_RGBA)\n glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_STENCIL_ATTACHMENT,\n GL_TEXTURE_2D, 0, 0);\n else\n glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0,\n GL_TEXTURE_2D, 0, 0);\n glBindFramebuffer(GL_FRAMEBUFFER_EXT, ctx->sub->blit_fb_ids[1]);\n if (info->mask & PIPE_MASK_RGBA)\n glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_STENCIL_ATTACHMENT,\n GL_TEXTURE_2D, 0, 0);\n else if (info->mask & (PIPE_MASK_Z | PIPE_MASK_S))\n glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0,\n GL_TEXTURE_2D, 0, 0);\n if (info->src.box.depth == info->dst.box.depth)\n n_layers = info->dst.box.depth;\n for (i = 0; i < n_layers; i++) {\n glBindFramebuffer(GL_FRAMEBUFFER_EXT, ctx->sub->blit_fb_ids[0]);\n glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_STENCIL_ATTACHMENT,\n GL_TEXTURE_2D, 0, 0);\n vrend_fb_bind_texture(src_res, 0, info->src.level, info->src.box.z + i);\n\n glBindFramebuffer(GL_FRAMEBUFFER_EXT, ctx->sub->blit_fb_ids[1]);\n\n vrend_fb_bind_texture(dst_res, 0, info->dst.level, info->dst.box.z + i);\n glBindFramebuffer(GL_DRAW_FRAMEBUFFER, ctx->sub->blit_fb_ids[1]);\n\n glBindFramebuffer(GL_READ_FRAMEBUFFER, ctx->sub->blit_fb_ids[0]);\n\n glBlitFramebuffer(info->src.box.x,\n src_y1,\n info->src.box.x + info->src.box.width,\n src_y2,\n info->dst.box.x,\n dst_y1,\n info->dst.box.x + info->dst.box.width,\n dst_y2,\n glmask, filter);\n }\n\n}\n", + "line": null, + "label": 0, + "cwe": "CWE-772", + "cve": "CVE-2017-6386", + "length": 1358 + }, + { + "index": 73645, + "code": "static MagickBooleanType OpenPixelCache(Image *image,const MapMode mode,\n ExceptionInfo *exception)\n{\n CacheInfo\n *restrict cache_info,\n source_info;\n\n char\n format[MaxTextExtent],\n message[MaxTextExtent];\n\n const char\n *type;\n\n MagickSizeType\n length,\n number_pixels;\n\n MagickStatusType\n status;\n\n size_t\n columns,\n packet_size;\n\n assert(image != (const Image *) NULL);\n assert(image->signature == MagickSignature);\n assert(image->cache != (Cache) NULL);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",image->filename);\n if ((image->columns == 0) || (image->rows == 0))\n ThrowBinaryException(CacheError,\"NoPixelsDefinedInCache\",image->filename);\n cache_info=(CacheInfo *) image->cache;\n assert(cache_info->signature == MagickSignature);\n source_info=(*cache_info);\n source_info.file=(-1);\n (void) FormatLocaleString(cache_info->filename,MaxTextExtent,\"%s[%.20g]\",\n image->filename,(double) GetImageIndexInList(image));\n cache_info->mode=mode;\n cache_info->rows=image->rows;\n cache_info->columns=image->columns;\n cache_info->channels=image->channels;\n cache_info->active_index_channel=((image->storage_class == PseudoClass) ||\n (image->colorspace == CMYKColorspace)) ? MagickTrue : MagickFalse;\n if (image->ping != MagickFalse)\n {\n cache_info->storage_class=image->storage_class;\n cache_info->colorspace=image->colorspace;\n cache_info->type=PingCache;\n cache_info->pixels=(PixelPacket *) NULL;\n cache_info->indexes=(IndexPacket *) NULL;\n cache_info->length=0;\n return(MagickTrue);\n }\n number_pixels=(MagickSizeType) cache_info->columns*cache_info->rows;\n packet_size=sizeof(PixelPacket);\n if (cache_info->active_index_channel != MagickFalse)\n packet_size+=sizeof(IndexPacket);\n length=number_pixels*packet_size;\n columns=(size_t) (length/cache_info->rows/packet_size);\n if ((cache_info->columns != columns) || ((ssize_t) cache_info->columns < 0) ||\n ((ssize_t) cache_info->rows < 0))\n ThrowBinaryException(ResourceLimitError,\"PixelCacheAllocationFailed\",\n image->filename);\n cache_info->length=length;\n status=AcquireMagickResource(AreaResource,cache_info->length);\n length=number_pixels*(sizeof(PixelPacket)+sizeof(IndexPacket));\n if ((status != MagickFalse) && (length == (MagickSizeType) ((size_t) length)))\n {\n status=AcquireMagickResource(MemoryResource,cache_info->length);\n if (((cache_info->type == UndefinedCache) && (status != MagickFalse)) ||\n (cache_info->type == MemoryCache))\n {\n AllocatePixelCachePixels(cache_info);\n if (cache_info->pixels == (PixelPacket *) NULL)\n cache_info->pixels=source_info.pixels;\n else\n {\n /*\n Create memory pixel cache.\n */\n cache_info->colorspace=image->colorspace;\n cache_info->type=MemoryCache;\n cache_info->indexes=(IndexPacket *) NULL;\n if (cache_info->active_index_channel != MagickFalse)\n cache_info->indexes=(IndexPacket *) (cache_info->pixels+\n number_pixels);\n if ((source_info.storage_class != UndefinedClass) &&\n (mode != ReadMode))\n {\n status&=ClonePixelCacheRepository(cache_info,&source_info,\n exception);\n RelinquishPixelCachePixels(&source_info);\n }\n if (image->debug != MagickFalse)\n {\n (void) FormatMagickSize(cache_info->length,MagickTrue,format);\n type=CommandOptionToMnemonic(MagickCacheOptions,(ssize_t)\n cache_info->type);\n (void) FormatLocaleString(message,MaxTextExtent,\n \"open %s (%s %s, %.20gx%.20g %s)\",cache_info->filename,\n cache_info->mapped != MagickFalse ? \"Anonymous\" : \"Heap\",\n type,(double) cache_info->columns,(double) cache_info->rows,\n format);\n (void) LogMagickEvent(CacheEvent,GetMagickModule(),\"%s\",\n message);\n }\n cache_info->storage_class=image->storage_class;\n return(MagickTrue);\n }\n }\n RelinquishMagickResource(MemoryResource,cache_info->length);\n }\n /*\n Create pixel cache on disk.\n */\n status=AcquireMagickResource(DiskResource,cache_info->length);\n if ((status == MagickFalse) || (cache_info->type == DistributedCache))\n {\n DistributeCacheInfo\n *server_info;\n\n if (cache_info->type == DistributedCache)\n RelinquishMagickResource(DiskResource,cache_info->length);\n server_info=AcquireDistributeCacheInfo(exception);\n if (server_info != (DistributeCacheInfo *) NULL)\n {\n status=OpenDistributePixelCache(server_info,image);\n if (status == MagickFalse)\n {\n ThrowFileException(exception,CacheError,\"UnableToOpenPixelCache\",\n GetDistributeCacheHostname(server_info));\n server_info=DestroyDistributeCacheInfo(server_info);\n }\n else\n {\n /*\n Create a distributed pixel cache.\n */\n cache_info->type=DistributedCache;\n cache_info->storage_class=image->storage_class;\n cache_info->colorspace=image->colorspace;\n cache_info->server_info=server_info;\n (void) FormatLocaleString(cache_info->cache_filename,\n MaxTextExtent,\"%s:%d\",GetDistributeCacheHostname(\n (DistributeCacheInfo *) cache_info->server_info),\n GetDistributeCachePort((DistributeCacheInfo *)\n cache_info->server_info));\n if ((source_info.storage_class != UndefinedClass) &&\n (mode != ReadMode))\n {\n status=ClonePixelCacheRepository(cache_info,&source_info,\n exception);\n RelinquishPixelCachePixels(&source_info);\n }\n if (image->debug != MagickFalse)\n {\n (void) FormatMagickSize(cache_info->length,MagickFalse,\n format);\n type=CommandOptionToMnemonic(MagickCacheOptions,(ssize_t)\n cache_info->type);\n (void) FormatLocaleString(message,MaxTextExtent,\n \"open %s (%s[%d], %s, %.20gx%.20g %s)\",cache_info->filename,\n cache_info->cache_filename,GetDistributeCacheFile(\n (DistributeCacheInfo *) cache_info->server_info),type,\n (double) cache_info->columns,(double) cache_info->rows,\n format);\n (void) LogMagickEvent(CacheEvent,GetMagickModule(),\"%s\",\n message);\n }\n return(MagickTrue);\n }\n }\n RelinquishMagickResource(DiskResource,cache_info->length);\n (void) ThrowMagickException(exception,GetMagickModule(),CacheError,\n \"CacheResourcesExhausted\",\"`%s'\",image->filename);\n return(MagickFalse);\n }\n if ((source_info.storage_class != UndefinedClass) && (mode != ReadMode))\n {\n (void) ClosePixelCacheOnDisk(cache_info);\n *cache_info->cache_filename='\\0';\n }\n if (OpenPixelCacheOnDisk(cache_info,mode) == MagickFalse)\n {\n RelinquishMagickResource(DiskResource,cache_info->length);\n ThrowFileException(exception,CacheError,\"UnableToOpenPixelCache\",\n image->filename);\n return(MagickFalse);\n }\n status=SetPixelCacheExtent(image,(MagickSizeType) cache_info->offset+\n cache_info->length);\n if (status == MagickFalse)\n {\n ThrowFileException(exception,CacheError,\"UnableToExtendCache\",\n image->filename);\n return(MagickFalse);\n }\n cache_info->storage_class=image->storage_class;\n cache_info->colorspace=image->colorspace;\n length=number_pixels*(sizeof(PixelPacket)+sizeof(IndexPacket));\n if (length != (MagickSizeType) ((size_t) length))\n cache_info->type=DiskCache;\n else\n {\n status=AcquireMagickResource(MapResource,cache_info->length);\n if ((status == MagickFalse) && (cache_info->type != MapCache) &&\n (cache_info->type != MemoryCache))\n cache_info->type=DiskCache;\n else\n {\n cache_info->pixels=(PixelPacket *) MapBlob(cache_info->file,mode,\n cache_info->offset,(size_t) cache_info->length);\n if (cache_info->pixels == (PixelPacket *) NULL)\n {\n cache_info->pixels=source_info.pixels;\n cache_info->type=DiskCache;\n }\n else\n {\n /*\n Create file-backed memory-mapped pixel cache.\n */\n (void) ClosePixelCacheOnDisk(cache_info);\n cache_info->type=MapCache;\n cache_info->mapped=MagickTrue;\n cache_info->indexes=(IndexPacket *) NULL;\n if (cache_info->active_index_channel != MagickFalse)\n cache_info->indexes=(IndexPacket *) (cache_info->pixels+\n number_pixels);\n if ((source_info.storage_class != UndefinedClass) &&\n (mode != ReadMode))\n {\n status=ClonePixelCacheRepository(cache_info,&source_info,\n exception);\n RelinquishPixelCachePixels(&source_info);\n }\n if (image->debug != MagickFalse)\n {\n (void) FormatMagickSize(cache_info->length,MagickTrue,format);\n type=CommandOptionToMnemonic(MagickCacheOptions,(ssize_t)\n cache_info->type);\n (void) FormatLocaleString(message,MaxTextExtent,\n \"open %s (%s[%d], %s, %.20gx%.20g %s)\",\n cache_info->filename,cache_info->cache_filename,\n cache_info->file,type,(double) cache_info->columns,(double)\n cache_info->rows,format);\n (void) LogMagickEvent(CacheEvent,GetMagickModule(),\"%s\",\n message);\n }\n return(MagickTrue);\n }\n }\n RelinquishMagickResource(MapResource,cache_info->length);\n }\n if ((source_info.storage_class != UndefinedClass) && (mode != ReadMode))\n {\n status=ClonePixelCacheRepository(cache_info,&source_info,exception);\n RelinquishPixelCachePixels(&source_info);\n }\n if (image->debug != MagickFalse)\n {\n (void) FormatMagickSize(cache_info->length,MagickFalse,format);\n type=CommandOptionToMnemonic(MagickCacheOptions,(ssize_t)\n cache_info->type);\n (void) FormatLocaleString(message,MaxTextExtent,\n \"open %s (%s[%d], %s, %.20gx%.20g %s)\",cache_info->filename,\n cache_info->cache_filename,cache_info->file,type,(double)\n cache_info->columns,(double) cache_info->rows,format);\n (void) LogMagickEvent(CacheEvent,GetMagickModule(),\"%s\",message);\n }\n return(MagickTrue);\n}\n", + "line": null, + "label": 0, + "cwe": "CWE-189", + "cve": "CVE-2016-7513", + "length": 2487 + }, + { + "index": 180187, + "code": "static int ovl_rename2(struct inode *olddir, struct dentry *old,\n\t\t struct inode *newdir, struct dentry *new,\n\t\t unsigned int flags)\n{\n\tint err;\n\tenum ovl_path_type old_type;\n\tenum ovl_path_type new_type;\n\tstruct dentry *old_upperdir;\n\tstruct dentry *new_upperdir;\n\tstruct dentry *olddentry;\n\tstruct dentry *newdentry;\n\tstruct dentry *trap;\n\tbool old_opaque;\n\tbool new_opaque;\n\tbool new_create = false;\n\tbool cleanup_whiteout = false;\n\tbool overwrite = !(flags & RENAME_EXCHANGE);\n\tbool is_dir = d_is_dir(old);\n\tbool new_is_dir = false;\n\tstruct dentry *opaquedir = NULL;\n\tconst struct cred *old_cred = NULL;\n\tstruct cred *override_cred = NULL;\n\n\terr = -EINVAL;\n\tif (flags & ~(RENAME_EXCHANGE | RENAME_NOREPLACE))\n\t\tgoto out;\n\n\tflags &= ~RENAME_NOREPLACE;\n\n\terr = ovl_check_sticky(old);\n\tif (err)\n\t\tgoto out;\n\n\t/* Don't copy up directory trees */\n\told_type = ovl_path_type(old);\n\terr = -EXDEV;\n\tif (OVL_TYPE_MERGE_OR_LOWER(old_type) && is_dir)\n\t\tgoto out;\n\n\tif (new->d_inode) {\n\t\terr = ovl_check_sticky(new);\n\t\tif (err)\n\t\t\tgoto out;\n\n\t\tif (d_is_dir(new))\n\t\t\tnew_is_dir = true;\n\n\t\tnew_type = ovl_path_type(new);\n\t\terr = -EXDEV;\n\t\tif (!overwrite && OVL_TYPE_MERGE_OR_LOWER(new_type) && new_is_dir)\n\t\t\tgoto out;\n\n\t\terr = 0;\n\t\tif (!OVL_TYPE_UPPER(new_type) && !OVL_TYPE_UPPER(old_type)) {\n\t\t\tif (ovl_dentry_lower(old)->d_inode ==\n\t\t\t ovl_dentry_lower(new)->d_inode)\n\t\t\t\tgoto out;\n\t\t}\n\t\tif (OVL_TYPE_UPPER(new_type) && OVL_TYPE_UPPER(old_type)) {\n\t\t\tif (ovl_dentry_upper(old)->d_inode ==\n\t\t\t ovl_dentry_upper(new)->d_inode)\n\t\t\t\tgoto out;\n\t\t}\n\t} else {\n\t\tif (ovl_dentry_is_opaque(new))\n\t\t\tnew_type = __OVL_PATH_UPPER;\n\t\telse\n\t\t\tnew_type = __OVL_PATH_UPPER | __OVL_PATH_PURE;\n\t}\n\n\terr = ovl_want_write(old);\n\tif (err)\n\t\tgoto out;\n\n\terr = ovl_copy_up(old);\n\tif (err)\n\t\tgoto out_drop_write;\n\n\terr = ovl_copy_up(new->d_parent);\n\tif (err)\n\t\tgoto out_drop_write;\n\tif (!overwrite) {\n\t\terr = ovl_copy_up(new);\n\t\tif (err)\n\t\t\tgoto out_drop_write;\n\t}\n\n\told_opaque = !OVL_TYPE_PURE_UPPER(old_type);\n\tnew_opaque = !OVL_TYPE_PURE_UPPER(new_type);\n\n\tif (old_opaque || new_opaque) {\n\t\terr = -ENOMEM;\n\t\toverride_cred = prepare_creds();\n\t\tif (!override_cred)\n\t\t\tgoto out_drop_write;\n\n\t\t/*\n\t\t * CAP_SYS_ADMIN for setting xattr on whiteout, opaque dir\n\t\t * CAP_DAC_OVERRIDE for create in workdir\n\t\t * CAP_FOWNER for removing whiteout from sticky dir\n\t\t * CAP_FSETID for chmod of opaque dir\n\t\t * CAP_CHOWN for chown of opaque dir\n\t\t */\n\t\tcap_raise(override_cred->cap_effective, CAP_SYS_ADMIN);\n\t\tcap_raise(override_cred->cap_effective, CAP_DAC_OVERRIDE);\n\t\tcap_raise(override_cred->cap_effective, CAP_FOWNER);\n\t\tcap_raise(override_cred->cap_effective, CAP_FSETID);\n\t\tcap_raise(override_cred->cap_effective, CAP_CHOWN);\n\t\told_cred = override_creds(override_cred);\n\t}\n\n\tif (overwrite && OVL_TYPE_MERGE_OR_LOWER(new_type) && new_is_dir) {\n\t\topaquedir = ovl_check_empty_and_clear(new);\n\t\terr = PTR_ERR(opaquedir);\n\t\tif (IS_ERR(opaquedir)) {\n\t\t\topaquedir = NULL;\n\t\t\tgoto out_revert_creds;\n\t\t}\n\t}\n\n\tif (overwrite) {\n\t\tif (old_opaque) {\n\t\t\tif (new->d_inode || !new_opaque) {\n\t\t\t\t/* Whiteout source */\n\t\t\t\tflags |= RENAME_WHITEOUT;\n\t\t\t} else {\n\t\t\t\t/* Switch whiteouts */\n\t\t\t\tflags |= RENAME_EXCHANGE;\n\t\t\t}\n\t\t} else if (is_dir && !new->d_inode && new_opaque) {\n\t\t\tflags |= RENAME_EXCHANGE;\n\t\t\tcleanup_whiteout = true;\n\t\t}\n\t}\n\n\told_upperdir = ovl_dentry_upper(old->d_parent);\n\tnew_upperdir = ovl_dentry_upper(new->d_parent);\n \n \ttrap = lock_rename(new_upperdir, old_upperdir);\n \n\tolddentry = ovl_dentry_upper(old);\n\tnewdentry = ovl_dentry_upper(new);\n\tif (newdentry) {\n \t\tif (opaquedir) {\n\t\t\tnewdentry = opaquedir;\n\t\t\topaquedir = NULL;\n \t\t} else {\n\t\t\tdget(newdentry);\n \t\t}\n \t} else {\n \t\tnew_create = true;\n\t\tnewdentry = lookup_one_len(new->d_name.name, new_upperdir,\n\t\t\t\t\t new->d_name.len);\n\t\terr = PTR_ERR(newdentry);\n\t\tif (IS_ERR(newdentry))\n\t\t\tgoto out_unlock;\n \t}\n \n\terr = -ESTALE;\n\tif (olddentry->d_parent != old_upperdir)\n\t\tgoto out_dput;\n\tif (newdentry->d_parent != new_upperdir)\n\t\tgoto out_dput;\n \tif (olddentry == trap)\n \t\tgoto out_dput;\n \tif (newdentry == trap)\n\t\tgoto out_dput;\n\n\tif (is_dir && !old_opaque && new_opaque) {\n\t\terr = ovl_set_opaque(olddentry);\n\t\tif (err)\n\t\t\tgoto out_dput;\n\t}\n\tif (!overwrite && new_is_dir && old_opaque && !new_opaque) {\n\t\terr = ovl_set_opaque(newdentry);\n\t\tif (err)\n\t\t\tgoto out_dput;\n\t}\n\n\tif (old_opaque || new_opaque) {\n\t\terr = ovl_do_rename(old_upperdir->d_inode, olddentry,\n\t\t\t\t new_upperdir->d_inode, newdentry,\n\t\t\t\t flags);\n\t} else {\n\t\t/* No debug for the plain case */\n\t\tBUG_ON(flags & ~RENAME_EXCHANGE);\n\t\terr = vfs_rename(old_upperdir->d_inode, olddentry,\n\t\t\t\t new_upperdir->d_inode, newdentry,\n\t\t\t\t NULL, flags);\n\t}\n\n\tif (err) {\n\t\tif (is_dir && !old_opaque && new_opaque)\n\t\t\tovl_remove_opaque(olddentry);\n\t\tif (!overwrite && new_is_dir && old_opaque && !new_opaque)\n\t\t\tovl_remove_opaque(newdentry);\n\t\tgoto out_dput;\n\t}\n\n\tif (is_dir && old_opaque && !new_opaque)\n\t\tovl_remove_opaque(olddentry);\n\tif (!overwrite && new_is_dir && !old_opaque && new_opaque)\n\t\tovl_remove_opaque(newdentry);\n\n\t/*\n\t * Old dentry now lives in different location. Dentries in\n\t * lowerstack are stale. We cannot drop them here because\n\t * access to them is lockless. This could be only pure upper\n\t * or opaque directory - numlower is zero. Or upper non-dir\n\t * entry - its pureness is tracked by flag opaque.\n\t */\n\tif (old_opaque != new_opaque) {\n\t\tovl_dentry_set_opaque(old, new_opaque);\n\t\tif (!overwrite)\n\t\t\tovl_dentry_set_opaque(new, old_opaque);\n\t}\n\n\tif (cleanup_whiteout)\n\t\tovl_cleanup(old_upperdir->d_inode, newdentry);\n\n\tovl_dentry_version_inc(old->d_parent);\n\tovl_dentry_version_inc(new->d_parent);\n \n out_dput:\n \tdput(newdentry);\n out_unlock:\n \tunlock_rename(new_upperdir, old_upperdir);\n out_revert_creds:\n\tif (old_opaque || new_opaque) {\n\t\trevert_creds(old_cred);\n\t\tput_cred(override_cred);\n\t}\nout_drop_write:\n\tovl_drop_write(old);\nout:\n\tdput(opaquedir);\n\treturn err;\n}\n", + "line": "\tolddentry = ovl_dentry_upper(old);\n\tnewdentry = ovl_dentry_upper(new);\n\tif (newdentry) {\n\t\t\tnewdentry = opaquedir;\n\t\t\topaquedir = NULL;\n\t\t\tdget(newdentry);\n\t\tnewdentry = lookup_one_len(new->d_name.name, new_upperdir,\n\t\t\t\t\t new->d_name.len);\n\t\terr = PTR_ERR(newdentry);\n\t\tif (IS_ERR(newdentry))\n\t\t\tgoto out_unlock;\n\terr = -ESTALE;\n\tif (olddentry->d_parent != old_upperdir)\n\t\tgoto out_dput;\n\tif (newdentry->d_parent != new_upperdir)\n\t\tgoto out_dput;\n", + "label": 1, + "cwe": "CWE-20", + "cve": "CVE-2016-6197", + "length": 1813 + }, + { + "index": 117343, + "code": "xmlXPtrStringRangeFunction(xmlXPathParserContextPtr ctxt, int nargs) {\n int i, startindex, endindex = 0, fendindex;\n xmlNodePtr start, end = 0, fend;\n xmlXPathObjectPtr set;\n xmlLocationSetPtr oldset;\n xmlLocationSetPtr newset;\n xmlXPathObjectPtr string;\n xmlXPathObjectPtr position = NULL;\n xmlXPathObjectPtr number = NULL;\n int found, pos = 0, num = 0;\n\n /*\n * Grab the arguments\n */\n if ((nargs < 2) || (nargs > 4))\n\tXP_ERROR(XPATH_INVALID_ARITY);\n\n if (nargs >= 4) {\n\tCHECK_TYPE(XPATH_NUMBER);\n\tnumber = valuePop(ctxt);\n\tif (number != NULL)\n\t num = (int) number->floatval;\n }\n if (nargs >= 3) {\n\tCHECK_TYPE(XPATH_NUMBER);\n\tposition = valuePop(ctxt);\n\tif (position != NULL)\n\t pos = (int) position->floatval;\n }\n CHECK_TYPE(XPATH_STRING);\n string = valuePop(ctxt);\n if ((ctxt->value == NULL) ||\n\t((ctxt->value->type != XPATH_LOCATIONSET) &&\n\t (ctxt->value->type != XPATH_NODESET)))\n XP_ERROR(XPATH_INVALID_TYPE)\n\n set = valuePop(ctxt);\n newset = xmlXPtrLocationSetCreate(NULL);\n if (set->nodesetval == NULL) {\n goto error;\n }\n if (set->type == XPATH_NODESET) {\n\txmlXPathObjectPtr tmp;\n\n\t/*\n\t * First convert to a location set\n\t */\n\ttmp = xmlXPtrNewLocationSetNodeSet(set->nodesetval);\n\txmlXPathFreeObject(set);\n\tset = tmp;\n }\n oldset = (xmlLocationSetPtr) set->user;\n\n /*\n * The loop is to search for each element in the location set\n * the list of location set corresponding to that search\n */\n for (i = 0;i < oldset->locNr;i++) {\n#ifdef DEBUG_RANGES\n\txmlXPathDebugDumpObject(stdout, oldset->locTab[i], 0);\n#endif\n\n\txmlXPtrGetStartPoint(oldset->locTab[i], &start, &startindex);\n\txmlXPtrGetEndPoint(oldset->locTab[i], &end, &endindex);\n\txmlXPtrAdvanceChar(&start, &startindex, 0);\n\txmlXPtrGetLastChar(&end, &endindex);\n\n#ifdef DEBUG_RANGES\n\txmlGenericError(xmlGenericErrorContext,\n\t\t\"from index %d of ->\", startindex);\n\txmlDebugDumpString(stdout, start->content);\n\txmlGenericError(xmlGenericErrorContext, \"\\n\");\n\txmlGenericError(xmlGenericErrorContext,\n\t\t\"to index %d of ->\", endindex);\n\txmlDebugDumpString(stdout, end->content);\n\txmlGenericError(xmlGenericErrorContext, \"\\n\");\n#endif\n\tdo {\n fend = end;\n fendindex = endindex;\n\t found = xmlXPtrSearchString(string->stringval, &start, &startindex,\n\t\t &fend, &fendindex);\n\t if (found == 1) {\n\t\tif (position == NULL) {\n\t\t xmlXPtrLocationSetAdd(newset,\n\t\t\t xmlXPtrNewRange(start, startindex, fend, fendindex));\n\t\t} else if (xmlXPtrAdvanceChar(&start, &startindex,\n\t\t\t pos - 1) == 0) {\n\t\t if ((number != NULL) && (num > 0)) {\n\t\t\tint rindx;\n\t\t\txmlNodePtr rend;\n\t\t\trend = start;\n\t\t\trindx = startindex - 1;\n\t\t\tif (xmlXPtrAdvanceChar(&rend, &rindx,\n\t\t\t\t num) == 0) {\n\t\t\t xmlXPtrLocationSetAdd(newset,\n\t\t\t\t\txmlXPtrNewRange(start, startindex,\n\t\t\t\t\t\t\trend, rindx));\n\t\t\t}\n\t\t } else if ((number != NULL) && (num <= 0)) {\n\t\t\txmlXPtrLocationSetAdd(newset,\n\t\t\t\t xmlXPtrNewRange(start, startindex,\n\t\t\t\t\t\t start, startindex));\n\t\t } else {\n\t\t\txmlXPtrLocationSetAdd(newset,\n\t\t\t\t xmlXPtrNewRange(start, startindex,\n\t\t\t\t\t\t fend, fendindex));\n\t\t }\n\t\t}\n\t\tstart = fend;\n\t\tstartindex = fendindex;\n\t\tif (string->stringval[0] == 0)\n\t\t startindex++;\n\t }\n\t} while (found == 1);\n }\n\n /*\n * Save the new value and cleanup\n */\nerror:\n valuePush(ctxt, xmlXPtrWrapLocationSet(newset));\n xmlXPathFreeObject(set);\n xmlXPathFreeObject(string);\n if (position) xmlXPathFreeObject(position);\n if (number) xmlXPathFreeObject(number);\n}\n", + "line": null, + "label": 0, + "cwe": "CWE-189", + "cve": "CVE-2011-3102", + "length": 1035 + }, + { + "index": 73908, + "code": "int main(int argc, char * * argv)\n{\n\tint ret = 0;\n\tint pid;\n\tstruct sigaction sa;\n\tchar buf[1500];\n\tssize_t n;\n\tint s_ssdp = -1;\t/* udp socket receiving ssdp packets */\n#ifdef ENABLE_IPV6\n\tint s_ssdp6 = -1;\t/* udp socket receiving ssdp packets IPv6*/\n#else\t/* ENABLE_IPV6 */\n#define s_ssdp6 (-1)\n#endif\t/* ENABLE_IPV6 */\n\tint s_unix = -1;\t/* unix socket communicating with clients */\n\tint s_ifacewatch = -1;\t/* socket to receive Route / network interface config changes */\n\tstruct reqelem * req;\n\tstruct reqelem * reqnext;\n\tfd_set readfds;\n\tfd_set writefds;\n\tstruct timeval now;\n\tint max_fd;\n\tstruct lan_addr_s * lan_addr;\n\tint i;\n\tconst char * sockpath = \"/var/run/minissdpd.sock\";\n\tconst char * pidfilename = \"/var/run/minissdpd.pid\";\n\tint debug_flag = 0;\n#ifdef ENABLE_IPV6\n\tint ipv6 = 0;\n#endif /* ENABLE_IPV6 */\n\tint deltadev = 0;\n\tstruct sockaddr_in sendername;\n\tsocklen_t sendername_len;\n#ifdef ENABLE_IPV6\n\tstruct sockaddr_in6 sendername6;\n\tsocklen_t sendername6_len;\n#endif\t/* ENABLE_IPV6 */\n\tunsigned char ttl = 2;\t/* UDA says it should default to 2 */\n\tconst char * searched_device = NULL;\t/* if not NULL, search/filter a specific device type */\n\n\tLIST_INIT(&reqlisthead);\n\tLIST_INIT(&servicelisthead);\n\tLIST_INIT(&lan_addrs);\n\t/* process command line */\n\tfor(i=1; i= argc) {\n\t\t\t\tfprintf(stderr, \"option %s needs an argument.\\n\", argv[i]);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif(0==strcmp(argv[i], \"-i\")) {\n\t\t\t\tlan_addr = malloc(sizeof(struct lan_addr_s));\n\t\t\t\tif(lan_addr == NULL) {\n\t\t\t\t\tfprintf(stderr, \"malloc(%d) FAILED\\n\", (int)sizeof(struct lan_addr_s));\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif(parselanaddr(lan_addr, argv[++i]) != 0) {\n\t\t\t\t\tfprintf(stderr, \"can't parse \\\"%s\\\" as a valid address or interface name\\n\", argv[i]);\n\t\t\t\t\tfree(lan_addr);\n\t\t\t\t} else {\n\t\t\t\t\tLIST_INSERT_HEAD(&lan_addrs, lan_addr, list);\n\t\t\t\t}\n\t\t\t} else if(0==strcmp(argv[i], \"-s\"))\n\t\t\t\tsockpath = argv[++i];\n\t\t\telse if(0==strcmp(argv[i], \"-p\"))\n\t\t\t\tpidfilename = argv[++i];\n\t\t\telse if(0==strcmp(argv[i], \"-t\"))\n\t\t\t\tttl = (unsigned char)atoi(argv[++i]);\n\t\t\telse if(0==strcmp(argv[i], \"-f\"))\n\t\t\t\tsearched_device = argv[++i];\n\t\t\telse\n\t\t\t\tfprintf(stderr, \"unknown commandline option %s.\\n\", argv[i]);\n\t\t}\n\t}\n\tif(lan_addrs.lh_first == NULL)\n\t{\n\t\tfprintf(stderr,\n\t\t \"Usage: %s [-d] \"\n#ifdef ENABLE_IPV6\n\t\t \"[-6] \"\n#endif /* ENABLE_IPV6 */\n\t\t \"[-s socket] [-p pidfile] [-t TTL] \"\n\t\t \"[-f device] \"\n\t\t \"-i [-i ] ...\\n\",\n\t\t argv[0]);\n\t\tfprintf(stderr,\n\t\t \"\\n is either an IPv4 address with mask such as\\n\"\n\t\t \" 192.168.1.42/255.255.255.0, or an interface name such as eth0.\\n\");\n\t\tfprintf(stderr,\n\t\t \"\\n By default, socket will be open as %s\\n\"\n\t\t \" and pid written to file %s\\n\",\n\t\t sockpath, pidfilename);\n\t\treturn 1;\n\t}\n\n\t/* open log */\n\topenlog(\"minissdpd\",\n\t LOG_CONS|LOG_PID|(debug_flag?LOG_PERROR:0),\n\t\t\tLOG_MINISSDPD);\n\tif(!debug_flag) /* speed things up and ignore LOG_INFO and LOG_DEBUG */\n\t\tsetlogmask(LOG_UPTO(LOG_NOTICE));\n\n\tif(checkforrunning(pidfilename) < 0)\n\t{\n\t\tsyslog(LOG_ERR, \"MiniSSDPd is already running. EXITING\");\n\t\treturn 1;\n\t}\n\n\tupnp_bootid = (unsigned int)time(NULL);\n\n\t/* set signal handlers */\n\tmemset(&sa, 0, sizeof(struct sigaction));\n\tsa.sa_handler = sigterm;\n\tif(sigaction(SIGTERM, &sa, NULL))\n\t{\n\t\tsyslog(LOG_ERR, \"Failed to set SIGTERM handler. EXITING\");\n\t\tret = 1;\n\t\tgoto quit;\n\t}\n\tif(sigaction(SIGINT, &sa, NULL))\n\t{\n\t\tsyslog(LOG_ERR, \"Failed to set SIGINT handler. EXITING\");\n\t\tret = 1;\n\t\tgoto quit;\n\t}\n\t/* open route/interface config changes socket */\n\ts_ifacewatch = OpenAndConfInterfaceWatchSocket();\n\t/* open UDP socket(s) for receiving SSDP packets */\n\ts_ssdp = OpenAndConfSSDPReceiveSocket(0, ttl);\n\tif(s_ssdp < 0)\n\t{\n\t\tsyslog(LOG_ERR, \"Cannot open socket for receiving SSDP messages, exiting\");\n\t\tret = 1;\n\t\tgoto quit;\n\t}\n#ifdef ENABLE_IPV6\n\tif(ipv6) {\n\t\ts_ssdp6 = OpenAndConfSSDPReceiveSocket(1, ttl);\n\t\tif(s_ssdp6 < 0)\n\t\t{\n\t\t\tsyslog(LOG_ERR, \"Cannot open socket for receiving SSDP messages (IPv6), exiting\");\n\t\t\tret = 1;\n\t\t\tgoto quit;\n\t\t}\n\t}\n#endif\t/* ENABLE_IPV6 */\n\t/* Open Unix socket to communicate with other programs on\n\t * the same machine */\n\ts_unix = OpenUnixSocket(sockpath);\n\tif(s_unix < 0)\n\t{\n\t\tsyslog(LOG_ERR, \"Cannot open unix socket for communicating with clients. Exiting\");\n\t\tret = 1;\n\t\tgoto quit;\n\t}\n\n\t/* drop privileges */\n#if 0\n\t/* if we drop privileges, how to unlink(/var/run/minissdpd.sock) ? */\n\tif(getuid() == 0) {\n\t\tstruct passwd * user;\n\t\tstruct group * group;\n\t\tuser = getpwnam(\"nobody\");\n\t\tif(!user) {\n\t\t\tsyslog(LOG_ERR, \"getpwnam(\\\"%s\\\") : %m\", \"nobody\");\n\t\t\tret = 1;\n\t\t\tgoto quit;\n\t\t}\n\t\tgroup = getgrnam(\"nogroup\");\n\t\tif(!group) {\n\t\t\tsyslog(LOG_ERR, \"getgrnam(\\\"%s\\\") : %m\", \"nogroup\");\n\t\t\tret = 1;\n\t\t\tgoto quit;\n\t\t}\n\t\tif(setgid(group->gr_gid) < 0) {\n\t\t\tsyslog(LOG_ERR, \"setgit(%d) : %m\", group->gr_gid);\n\t\t\tret = 1;\n\t\t\tgoto quit;\n\t\t}\n\t\tif(setuid(user->pw_uid) < 0) {\n\t\t\tsyslog(LOG_ERR, \"setuid(%d) : %m\", user->pw_uid);\n\t\t\tret = 1;\n\t\t\tgoto quit;\n\t\t}\n\t}\n#endif\n\n\t/* daemonize or in any case get pid ! */\n\tif(debug_flag)\n\t\tpid = getpid();\n\telse {\n#ifdef USE_DAEMON\n\t\tif(daemon(0, 0) < 0)\n\t\t\tperror(\"daemon()\");\n\t\tpid = getpid();\n#else /* USE_DAEMON */\n\t\tpid = daemonize();\n#endif /* USE_DAEMON */\n\t}\n\n\twritepidfile(pidfilename, pid);\n\n\t/* send M-SEARCH ssdp:all Requests */\n\tif(s_ssdp >= 0)\n\t\tssdpDiscover(s_ssdp, 0, searched_device);\n\tif(s_ssdp6 >= 0)\n\t\tssdpDiscover(s_ssdp6, 1, searched_device);\n\n\t/* Main loop */\n\twhile(!quitting) {\n\t\t/* fill readfds fd_set */\n\t\tFD_ZERO(&readfds);\n\t\tFD_ZERO(&writefds);\n\n\t\tFD_SET(s_unix, &readfds);\n\t\tmax_fd = s_unix;\n\t\tif(s_ssdp >= 0) {\n\t\t\tFD_SET(s_ssdp, &readfds);\n\t\t\tSET_MAX(max_fd, s_ssdp);\n\t\t}\n#ifdef ENABLE_IPV6\n\t\tif(s_ssdp6 >= 0) {\n\t\t\tFD_SET(s_ssdp6, &readfds);\n\t\t\tSET_MAX(max_fd, s_ssdp6);\n\t\t}\n#endif /* ENABLE_IPV6 */\n\t\tif(s_ifacewatch >= 0) {\n\t\t\tFD_SET(s_ifacewatch, &readfds);\n\t\t\tSET_MAX(max_fd, s_ifacewatch);\n\t\t}\n\t\tfor(req = reqlisthead.lh_first; req; req = req->entries.le_next) {\n\t\t\tif(req->socket >= 0) {\n\t\t\t\tFD_SET(req->socket, &readfds);\n\t\t\t\tSET_MAX(max_fd, req->socket);\n\t\t\t}\n\t\t\tif(req->output_buffer_len > 0) {\n\t\t\t\tFD_SET(req->socket, &writefds);\n\t\t\t\tSET_MAX(max_fd, req->socket);\n\t\t\t}\n\t\t}\n\t\tgettimeofday(&now, NULL);\n\t\ti = get_sendto_fds(&writefds, &max_fd, &now);\n\t\t/* select call */\n\t\tif(select(max_fd + 1, &readfds, &writefds, 0, 0) < 0) {\n\t\t\tif(errno != EINTR) {\n\t\t\t\tsyslog(LOG_ERR, \"select: %m\");\n\t\t\t\tbreak;\t/* quit */\n\t\t\t}\n\t\t\tcontinue;\t/* try again */\n\t\t}\n\t\tif(try_sendto(&writefds) < 0) {\n\t\t\tsyslog(LOG_ERR, \"try_sendto: %m\");\n\t\t\tbreak;\n\t\t}\n#ifdef ENABLE_IPV6\n\t\tif((s_ssdp6 >= 0) && FD_ISSET(s_ssdp6, &readfds))\n\t\t{\n\t\t\tsendername6_len = sizeof(struct sockaddr_in6);\n\t\t\tn = recvfrom(s_ssdp6, buf, sizeof(buf), 0,\n\t\t\t (struct sockaddr *)&sendername6, &sendername6_len);\n\t\t\tif(n<0)\n\t\t\t{\n\t\t\t\t /* EAGAIN, EWOULDBLOCK, EINTR : silently ignore (try again next time)\n\t\t\t\t * other errors : log to LOG_ERR */\n\t\t\t\tif(errno != EAGAIN && errno != EWOULDBLOCK && errno != EINTR)\n\t\t\t\t\tsyslog(LOG_ERR, \"recvfrom: %m\");\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t/* Parse and process the packet received */\n\t\t\t\t/*printf(\"%.*s\", n, buf);*/\n\t\t\t\ti = ParseSSDPPacket(s_ssdp6, buf, n,\n\t\t\t\t (struct sockaddr *)&sendername6, searched_device);\n\t\t\t\tsyslog(LOG_DEBUG, \"** i=%d deltadev=%d **\", i, deltadev);\n\t\t\t\tif(i==0 || (i*deltadev < 0))\n\t\t\t\t{\n\t\t\t\t\tif(deltadev > 0)\n\t\t\t\t\t\tsyslog(LOG_NOTICE, \"%d new devices added\", deltadev);\n\t\t\t\t\telse if(deltadev < 0)\n\t\t\t\t\t\tsyslog(LOG_NOTICE, \"%d devices removed (good-bye!)\", -deltadev);\n\t\t\t\t\tdeltadev = i;\n\t\t\t\t}\n\t\t\t\telse if((i*deltadev) >= 0)\n\t\t\t\t{\n\t\t\t\t\tdeltadev += i;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n#endif\t/* ENABLE_IPV6 */\n\t\tif((s_ssdp >= 0) && FD_ISSET(s_ssdp, &readfds))\n\t\t{\n\t\t\tsendername_len = sizeof(struct sockaddr_in);\n\t\t\tn = recvfrom(s_ssdp, buf, sizeof(buf), 0,\n\t\t\t (struct sockaddr *)&sendername, &sendername_len);\n\t\t\tif(n<0)\n\t\t\t{\n\t\t\t\t /* EAGAIN, EWOULDBLOCK, EINTR : silently ignore (try again next time)\n\t\t\t\t * other errors : log to LOG_ERR */\n\t\t\t\tif(errno != EAGAIN && errno != EWOULDBLOCK && errno != EINTR)\n\t\t\t\t\tsyslog(LOG_ERR, \"recvfrom: %m\");\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t/* Parse and process the packet received */\n\t\t\t\t/*printf(\"%.*s\", n, buf);*/\n\t\t\t\ti = ParseSSDPPacket(s_ssdp, buf, n,\n\t\t\t\t (struct sockaddr *)&sendername, searched_device);\n\t\t\t\tsyslog(LOG_DEBUG, \"** i=%d deltadev=%d **\", i, deltadev);\n\t\t\t\tif(i==0 || (i*deltadev < 0))\n\t\t\t\t{\n\t\t\t\t\tif(deltadev > 0)\n\t\t\t\t\t\tsyslog(LOG_NOTICE, \"%d new devices added\", deltadev);\n\t\t\t\t\telse if(deltadev < 0)\n\t\t\t\t\t\tsyslog(LOG_NOTICE, \"%d devices removed (good-bye!)\", -deltadev);\n\t\t\t\t\tdeltadev = i;\n\t\t\t\t}\n\t\t\t\telse if((i*deltadev) >= 0)\n\t\t\t\t{\n\t\t\t\t\tdeltadev += i;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t/* processing unix socket requests */\n\t\tfor(req = reqlisthead.lh_first; req;) {\n\t\t\treqnext = req->entries.le_next;\n\t\t\tif((req->socket >= 0) && FD_ISSET(req->socket, &readfds)) {\n\t\t\t\tprocessRequest(req);\n\t\t\t}\n\t\t\tif((req->socket >= 0) && FD_ISSET(req->socket, &writefds)) {\n\t\t\t\twrite_buffer(req);\n\t\t\t}\n\t\t\tif(req->socket < 0) {\n\t\t\t\tLIST_REMOVE(req, entries);\n\t\t\t\tfree(req->output_buffer);\n\t\t\t\tfree(req);\n\t\t\t}\n\t\t\treq = reqnext;\n\t\t}\n\t\t/* processing new requests */\n\t\tif(FD_ISSET(s_unix, &readfds))\n\t\t{\n\t\t\tstruct reqelem * tmp;\n\t\t\tint s = accept(s_unix, NULL, NULL);\n\t\t\tif(s < 0) {\n\t\t\t\tsyslog(LOG_ERR, \"accept(s_unix): %m\");\n\t\t\t} else {\n\t\t\t\tsyslog(LOG_INFO, \"(s=%d) new request connection\", s);\n\t\t\t\tif(!set_non_blocking(s))\n\t\t\t\t\tsyslog(LOG_WARNING, \"Failed to set new socket non blocking : %m\");\n\t\t\t\ttmp = malloc(sizeof(struct reqelem));\n\t\t\t\tif(!tmp) {\n\t\t\t\t\tsyslog(LOG_ERR, \"cannot allocate memory for request\");\n\t\t\t\t\tclose(s);\n\t\t\t\t} else {\n\t\t\t\t\tmemset(tmp, 0, sizeof(struct reqelem));\n\t\t\t\t\ttmp->socket = s;\n\t\t\t\t\tLIST_INSERT_HEAD(&reqlisthead, tmp, entries);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t/* processing route/network interface config changes */\n\t\tif((s_ifacewatch >= 0) && FD_ISSET(s_ifacewatch, &readfds)) {\n\t\t\tProcessInterfaceWatch(s_ifacewatch, s_ssdp, s_ssdp6);\n\t\t}\n\t}\n\tsyslog(LOG_DEBUG, \"quitting...\");\n\tfinalize_sendto();\n\n\t/* closing and cleaning everything */\nquit:\n\tif(s_ssdp >= 0) {\n\t\tclose(s_ssdp);\n\t\ts_ssdp = -1;\n\t}\n#ifdef ENABLE_IPV6\n\tif(s_ssdp6 >= 0) {\n\t\tclose(s_ssdp6);\n\t\ts_ssdp6 = -1;\n\t}\n#endif\t/* ENABLE_IPV6 */\n\tif(s_unix >= 0) {\n\t\tclose(s_unix);\n\t\ts_unix = -1;\n\t\tif(unlink(sockpath) < 0)\n\t\t\tsyslog(LOG_ERR, \"unlink(%s): %m\", sockpath);\n\t}\n\tif(s_ifacewatch >= 0) {\n\t\tclose(s_ifacewatch);\n\t\ts_ifacewatch = -1;\n\t}\n\t/* empty LAN interface/address list */\n\twhile(lan_addrs.lh_first != NULL) {\n\t\tlan_addr = lan_addrs.lh_first;\n\t\tLIST_REMOVE(lan_addrs.lh_first, list);\n\t\tfree(lan_addr);\n\t}\n\t/* empty device list */\n\twhile(devlist != NULL) {\n\t\tstruct device * next = devlist->next;\n\t\tfree(devlist);\n\t\tdevlist = next;\n\t}\n\t/* empty service list */\n\twhile(servicelisthead.lh_first != NULL) {\n\t\tstruct service * serv = servicelisthead.lh_first;\n\t\tLIST_REMOVE(servicelisthead.lh_first, entries);\n\t\tfree(serv->st);\n\t\tfree(serv->usn);\n\t\tfree(serv->server);\n\t\tfree(serv->location);\n\t\tfree(serv);\n\t}\n\tif(unlink(pidfilename) < 0)\n\t\tsyslog(LOG_ERR, \"unlink(%s): %m\", pidfilename);\n\tcloselog();\n\treturn ret;\n}\n", + "line": null, + "label": 0, + "cwe": "CWE-125", + "cve": "CVE-2016-3178", + "length": 3623 + }, + { + "index": 181814, + "code": "static MagickBooleanType GetMagickModulePath(const char *filename,\n MagickModuleType module_type,char *path,ExceptionInfo *exception)\n{\n char\n *module_path;\n\n assert(filename != (const char *) NULL);\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",filename);\n assert(path != (char *) NULL);\n assert(exception != (ExceptionInfo *) NULL);\n (void) CopyMagickString(path,filename,MaxTextExtent);\n module_path=(char *) NULL;\n switch (module_type)\n {\n case MagickImageCoderModule:\n default:\n {\n (void) LogMagickEvent(ModuleEvent,GetMagickModule(),\n \"Searching for coder module file \\\"%s\\\" ...\",filename);\n module_path=GetEnvironmentValue(\"MAGICK_CODER_MODULE_PATH\");\n#if defined(MAGICKCORE_CODER_PATH)\n if (module_path == (char *) NULL)\n module_path=AcquireString(MAGICKCORE_CODER_PATH);\n#endif\n break;\n }\n case MagickImageFilterModule:\n {\n (void) LogMagickEvent(ModuleEvent,GetMagickModule(),\n \"Searching for filter module file \\\"%s\\\" ...\",filename);\n module_path=GetEnvironmentValue(\"MAGICK_CODER_FILTER_PATH\");\n#if defined(MAGICKCORE_FILTER_PATH)\n if (module_path == (char *) NULL)\n module_path=AcquireString(MAGICKCORE_FILTER_PATH);\n#endif\n break;\n }\n }\n if (module_path != (char *) NULL)\n {\n register char\n *p,\n *q;\n\n for (p=module_path-1; p != (char *) NULL; )\n {\n (void) CopyMagickString(path,p+1,MaxTextExtent);\n q=strchr(path,DirectoryListSeparator);\n if (q != (char *) NULL)\n *q='\\0';\n q=path+strlen(path)-1;\n if ((q >= path) && (*q != *DirectorySeparator))\n (void) ConcatenateMagickString(path,DirectorySeparator,MaxTextExtent);\n (void) ConcatenateMagickString(path,filename,MaxTextExtent);\n if (IsPathAccessible(path) != MagickFalse)\n {\n module_path=DestroyString(module_path);\n return(MagickTrue);\n }\n p=strchr(p+1,DirectoryListSeparator);\n }\n module_path=DestroyString(module_path);\n }\n#if defined(MAGICKCORE_INSTALLED_SUPPORT)\n else\n#if defined(MAGICKCORE_CODER_PATH)\n {\n const char\n *directory;\n\n /*\n Search hard coded paths.\n */\n switch (module_type)\n {\n case MagickImageCoderModule:\n default:\n {\n directory=MAGICKCORE_CODER_PATH;\n break;\n }\n case MagickImageFilterModule:\n {\n directory=MAGICKCORE_FILTER_PATH;\n break;\n }\n }\n (void) FormatLocaleString(path,MaxTextExtent,\"%s%s\",directory,filename);\n if (IsPathAccessible(path) == MagickFalse)\n {\n ThrowFileException(exception,ConfigureWarning,\n \"UnableToOpenModuleFile\",path);\n return(MagickFalse);\n }\n return(MagickTrue);\n }\n#else\n#if defined(MAGICKCORE_WINDOWS_SUPPORT)\n {\n const char\n *registery_key;\n\n unsigned char\n *key_value;\n\n /*\n Locate path via registry key.\n */\n switch (module_type)\n {\n case MagickImageCoderModule:\n default:\n {\n registery_key=\"CoderModulesPath\";\n break;\n }\n case MagickImageFilterModule:\n {\n registery_key=\"FilterModulesPath\";\n break;\n }\n }\n key_value=NTRegistryKeyLookup(registery_key);\n if (key_value == (unsigned char *) NULL)\n {\n ThrowMagickException(exception,GetMagickModule(),ConfigureError,\n \"RegistryKeyLookupFailed\",\"`%s'\",registery_key);\n return(MagickFalse);\n }\n (void) FormatLocaleString(path,MaxTextExtent,\"%s%s%s\",(char *) key_value,\n DirectorySeparator,filename);\n key_value=(unsigned char *) RelinquishMagickMemory(key_value);\n if (IsPathAccessible(path) == MagickFalse)\n {\n ThrowFileException(exception,ConfigureWarning,\n \"UnableToOpenModuleFile\",path);\n return(MagickFalse);\n }\n return(MagickTrue);\n }\n#endif\n#endif\n#if !defined(MAGICKCORE_CODER_PATH) && !defined(MAGICKCORE_WINDOWS_SUPPORT)\n# error MAGICKCORE_CODER_PATH or MAGICKCORE_WINDOWS_SUPPORT must be defined when MAGICKCORE_INSTALLED_SUPPORT is defined\n#endif\n#else\n {\n char\n *home;\n\n home=GetEnvironmentValue(\"MAGICK_HOME\");\n if (home != (char *) NULL)\n {\n /*\n Search MAGICK_HOME.\n */\n#if !defined(MAGICKCORE_POSIX_SUPPORT)\n (void) FormatLocaleString(path,MaxTextExtent,\"%s%s%s\",home,\n DirectorySeparator,filename);\n#else\n const char\n *directory;\n\n switch (module_type)\n {\n case MagickImageCoderModule:\n default:\n {\n directory=MAGICKCORE_CODER_RELATIVE_PATH;\n break;\n }\n case MagickImageFilterModule:\n {\n directory=MAGICKCORE_FILTER_RELATIVE_PATH;\n break;\n }\n }\n (void) FormatLocaleString(path,MaxTextExtent,\"%s/lib/%s/%s\",home,\n directory,filename);\n#endif\n home=DestroyString(home);\n if (IsPathAccessible(path) != MagickFalse)\n return(MagickTrue);\n }\n }\n if (*GetClientPath() != '\\0')\n {\n /*\n Search based on executable directory.\n */\n#if !defined(MAGICKCORE_POSIX_SUPPORT)\n (void) FormatLocaleString(path,MaxTextExtent,\"%s%s%s\",GetClientPath(),\n DirectorySeparator,filename);\n#else\n char\n prefix[MaxTextExtent];\n\n const char\n *directory;\n\n switch (module_type)\n {\n case MagickImageCoderModule:\n default:\n {\n directory=\"coders\";\n break;\n }\n case MagickImageFilterModule:\n {\n directory=\"filters\";\n break;\n }\n }\n (void) CopyMagickString(prefix,GetClientPath(),MaxTextExtent);\n ChopPathComponents(prefix,1);\n (void) FormatLocaleString(path,MaxTextExtent,\"%s/lib/%s/%s/%s\",prefix,\n MAGICKCORE_MODULES_RELATIVE_PATH,directory,filename);\n#endif\n if (IsPathAccessible(path) != MagickFalse)\n return(MagickTrue);\n }\n#if defined(MAGICKCORE_WINDOWS_SUPPORT)\n {\n /*\n Search module path.\n */\n if ((NTGetModulePath(\"CORE_RL_magick_.dll\",path) != MagickFalse) ||\n (NTGetModulePath(\"CORE_DB_magick_.dll\",path) != MagickFalse) ||\n (NTGetModulePath(\"Magick.dll\",path) != MagickFalse))\n {\n (void) ConcatenateMagickString(path,DirectorySeparator,MaxTextExtent);\n (void) ConcatenateMagickString(path,filename,MaxTextExtent);\n if (IsPathAccessible(path) != MagickFalse)\n return(MagickTrue);\n }\n }\n#endif\n {\n char\n *home;\n\n home=GetEnvironmentValue(\"XDG_CONFIG_HOME\");\n if (home == (char *) NULL)\n home=GetEnvironmentValue(\"LOCALAPPDATA\");\n if (home == (char *) NULL)\n home=GetEnvironmentValue(\"APPDATA\");\n if (home == (char *) NULL)\n home=GetEnvironmentValue(\"USERPROFILE\");\n if (home != (char *) NULL)\n {\n /*\n Search $XDG_CONFIG_HOME/ImageMagick.\n */\n (void) FormatLocaleString(path,MaxTextExtent,\"%s%sImageMagick%s%s\",\n home,DirectorySeparator,DirectorySeparator,filename);\n home=DestroyString(home);\n if (IsPathAccessible(path) != MagickFalse)\n return(MagickTrue);\n }\n home=GetEnvironmentValue(\"HOME\");\n if (home != (char *) NULL)\n {\n /*\n Search $HOME/.config/ImageMagick.\n */\n (void) FormatLocaleString(path,MaxTextExtent,\n \"%s%s.config%sImageMagick%s%s\",home,DirectorySeparator,\n DirectorySeparator,DirectorySeparator,filename);\n if (IsPathAccessible(path) != MagickFalse)\n {\n home=DestroyString(home);\n return(MagickTrue);\n }\n /*\n Search $HOME/.magick.\n */\n (void) FormatLocaleString(path,MaxTextExtent,\"%s%s.magick%s%s\",home,\n DirectorySeparator,DirectorySeparator,filename);\n home=DestroyString(home);\n if (IsPathAccessible(path) != MagickFalse)\n return(MagickTrue);\n }\n }\n /*\n Search current directory.\n */\n if (IsPathAccessible(path) != MagickFalse)\n return(MagickTrue);\n if (exception->severity < ConfigureError)\n ThrowFileException(exception,ConfigureWarning,\"UnableToOpenModuleFile\",\n path);\n#endif\n return(MagickFalse);\n}\n", + "line": null, + "label": 1, + "cwe": "CWE-22", + "cve": "CVE-2016-10048", + "length": 1993 + }, + { + "index": 103640, + "code": "WebPlugin* ChromeContentRendererClient::CreatePluginImpl(\n RenderView* render_view,\n WebFrame* frame,\n const WebPluginParams& original_params,\n bool* is_default_plugin) {\n bool found = false;\n *is_default_plugin = false;\n CommandLine* cmd = CommandLine::ForCurrentProcess();\n webkit::npapi::WebPluginInfo info;\n GURL url(original_params.url);\n std::string orig_mime_type = original_params.mimeType.utf8();\n std::string actual_mime_type;\n render_view->Send(new ViewHostMsg_GetPluginInfo(\n render_view->routing_id(), url, frame->top()->document().url(),\n orig_mime_type, &found, &info, &actual_mime_type));\n\n if (!found)\n return NULL;\n if (!webkit::npapi::IsPluginEnabled(info))\n return NULL;\n\n *is_default_plugin =\n info.path.value() == webkit::npapi::kDefaultPluginLibraryName;\n\n if (orig_mime_type == actual_mime_type) {\n UMA_HISTOGRAM_ENUMERATION(kPluginTypeMismatch,\n PLUGIN_TYPE_MISMATCH_NONE,\n PLUGIN_TYPE_MISMATCH_NUM_EVENTS);\n } else if (orig_mime_type.empty()) {\n UMA_HISTOGRAM_ENUMERATION(kPluginTypeMismatch,\n PLUGIN_TYPE_MISMATCH_ORIG_EMPTY,\n PLUGIN_TYPE_MISMATCH_NUM_EVENTS);\n } else if (orig_mime_type == kApplicationOctetStream) {\n UMA_HISTOGRAM_ENUMERATION(kPluginTypeMismatch,\n PLUGIN_TYPE_MISMATCH_ORIG_OCTETSTREAM,\n PLUGIN_TYPE_MISMATCH_NUM_EVENTS);\n } else {\n UMA_HISTOGRAM_ENUMERATION(kPluginTypeMismatch,\n PLUGIN_TYPE_MISMATCH_ORIG_OTHER,\n PLUGIN_TYPE_MISMATCH_NUM_EVENTS);\n return NULL;\n }\n\n const webkit::npapi::PluginGroup* group =\n webkit::npapi::PluginList::Singleton()->GetPluginGroup(info);\n DCHECK(group != NULL);\n\n ContentSetting plugin_setting = CONTENT_SETTING_DEFAULT;\n std::string resource;\n if (cmd->HasSwitch(switches::kEnableResourceContentSettings))\n resource = group->identifier();\n render_view->Send(new ViewHostMsg_GetPluginContentSetting(\n frame->top()->document().url(), resource, &plugin_setting));\n DCHECK(plugin_setting != CONTENT_SETTING_DEFAULT);\n\n WebPluginParams params(original_params);\n for (size_t i = 0; i < info.mime_types.size(); ++i) {\n if (info.mime_types[i].mime_type == actual_mime_type) {\n AppendParams(info.mime_types[i].additional_param_names,\n info.mime_types[i].additional_param_values,\n ¶ms.attributeNames,\n ¶ms.attributeValues);\n break;\n }\n }\n\n ContentSetting outdated_policy = CONTENT_SETTING_ASK;\n ContentSetting authorize_policy = CONTENT_SETTING_ASK;\n if (group->IsVulnerable() || group->RequiresAuthorization()) {\n render_view->Send(new ViewHostMsg_GetPluginPolicies(\n &outdated_policy, &authorize_policy));\n }\n\n if (group->IsVulnerable()) {\n if (outdated_policy == CONTENT_SETTING_ASK ||\n outdated_policy == CONTENT_SETTING_BLOCK) {\n if (outdated_policy == CONTENT_SETTING_ASK) {\n render_view->Send(new ViewHostMsg_BlockedOutdatedPlugin(\n render_view->routing_id(), group->GetGroupName(),\n GURL(group->GetUpdateURL())));\n }\n return CreatePluginPlaceholder(\n render_view, frame, params, *group, IDR_BLOCKED_PLUGIN_HTML,\n IDS_PLUGIN_OUTDATED, false, outdated_policy == CONTENT_SETTING_ASK);\n } else {\n DCHECK(outdated_policy == CONTENT_SETTING_ALLOW);\n }\n }\n\n ContentSettingsObserver* observer = ContentSettingsObserver::Get(render_view);\n ContentSetting host_setting =\n observer->GetContentSetting(CONTENT_SETTINGS_TYPE_PLUGINS);\n\n if (group->RequiresAuthorization() &&\n authorize_policy == CONTENT_SETTING_ASK &&\n (plugin_setting == CONTENT_SETTING_ALLOW ||\n plugin_setting == CONTENT_SETTING_ASK) &&\n host_setting == CONTENT_SETTING_DEFAULT) {\n render_view->Send(new ViewHostMsg_BlockedOutdatedPlugin(\n render_view->routing_id(), group->GetGroupName(), GURL()));\n return CreatePluginPlaceholder(\n render_view, frame, params, *group, IDR_BLOCKED_PLUGIN_HTML,\n IDS_PLUGIN_NOT_AUTHORIZED, false, true);\n }\n\n if (info.path.value() == webkit::npapi::kDefaultPluginLibraryName ||\n plugin_setting == CONTENT_SETTING_ALLOW ||\n host_setting == CONTENT_SETTING_ALLOW) {\n if (prerender::PrerenderHelper::IsPrerendering(render_view)) {\n return CreatePluginPlaceholder(\n render_view, frame, params, *group, IDR_CLICK_TO_PLAY_PLUGIN_HTML,\n IDS_PLUGIN_LOAD, true, true);\n }\n\n if (info.name == ASCIIToUTF16(ChromeContentClient::kNaClPluginName)) {\n bool allow_nacl = cmd->HasSwitch(switches::kEnableNaCl);\n if (!allow_nacl) {\n GURL nexe_url;\n if (actual_mime_type == kNaClPluginMimeType) {\n nexe_url = url; // Normal embedded NaCl plugin.\n } else {\n string16 nacl_attr = ASCIIToUTF16(kNaClPluginManifestAttribute);\n for (size_t i = 0; i < info.mime_types.size(); ++i) {\n if (info.mime_types[i].mime_type == actual_mime_type) {\n const webkit::npapi::WebPluginMimeType& content_type =\n info.mime_types[i];\n for (size_t i = 0;\n i < content_type.additional_param_names.size(); ++i) {\n if (content_type.additional_param_names[i] == nacl_attr) {\n nexe_url = GURL(content_type.additional_param_values[i]);\n break;\n }\n }\n break;\n }\n }\n }\n\n const Extension* extension =\n extension_dispatcher_->extensions()->GetByURL(nexe_url);\n allow_nacl = extension &&\n (extension->from_webstore() ||\n extension->location() == Extension::COMPONENT);\n }\n\n if (!allow_nacl) {\n return CreatePluginPlaceholder(\n render_view, frame, params, *group, IDR_BLOCKED_PLUGIN_HTML,\n IDS_PLUGIN_BLOCKED, false, false);\n }\n }\n\n bool pepper_plugin_was_registered = false;\n scoped_refptr pepper_module(\n render_view->pepper_delegate()->CreatePepperPlugin(\n info.path, &pepper_plugin_was_registered));\n if (pepper_plugin_was_registered) {\n if (pepper_module) {\n return render_view->CreatePepperPlugin(\n frame, params, info.path, pepper_module.get());\n }\n return NULL;\n }\n\n return render_view->CreateNPAPIPlugin(\n frame, params, info.path, actual_mime_type);\n }\n\n observer->DidBlockContentType(CONTENT_SETTINGS_TYPE_PLUGINS, resource);\n if (plugin_setting == CONTENT_SETTING_ASK) {\n return CreatePluginPlaceholder(\n render_view, frame, params, *group, IDR_CLICK_TO_PLAY_PLUGIN_HTML,\n IDS_PLUGIN_LOAD, false, true);\n } else {\n return CreatePluginPlaceholder(\n render_view, frame, params, *group, IDR_BLOCKED_PLUGIN_HTML,\n IDS_PLUGIN_BLOCKED, false, true);\n }\n}\n", + "line": null, + "label": 0, + "cwe": "CWE-20", + "cve": "CVE-2011-2861", + "length": 1574 + }, + { + "index": 74050, + "code": "static Image *ReadPICTImage(const ImageInfo *image_info,\n ExceptionInfo *exception)\n{\n char\n geometry[MagickPathExtent],\n header_ole[4];\n\n Image\n *image;\n\n int\n c,\n code;\n\n MagickBooleanType\n jpeg,\n status;\n\n PICTRectangle\n frame;\n\n PICTPixmap\n pixmap;\n\n Quantum\n index;\n\n register Quantum\n *q;\n\n register ssize_t\n i,\n x;\n\n size_t\n extent,\n length;\n\n ssize_t\n count,\n flags,\n j,\n version,\n y;\n\n StringInfo\n *profile;\n\n /*\n Open image file.\n */\n assert(image_info != (const ImageInfo *) NULL);\n assert(image_info->signature == MagickSignature);\n if (image_info->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",\n image_info->filename);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickSignature);\n image=AcquireImage(image_info,exception);\n status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);\n if (status == MagickFalse)\n {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n /*\n Read PICT header.\n */\n pixmap.bits_per_pixel=0;\n pixmap.component_count=0;\n /*\n Skip header : 512 for standard PICT and 4, ie \"PICT\" for OLE2.\n */\n header_ole[0]=ReadBlobByte(image);\n header_ole[1]=ReadBlobByte(image);\n header_ole[2]=ReadBlobByte(image);\n header_ole[3]=ReadBlobByte(image);\n if (!((header_ole[0] == 0x50) && (header_ole[1] == 0x49) &&\n (header_ole[2] == 0x43) && (header_ole[3] == 0x54 )))\n for (i=0; i < 508; i++)\n if (ReadBlobByte(image) == EOF)\n break;\n (void) ReadBlobMSBShort(image); /* skip picture size */\n if (ReadRectangle(image,&frame) == MagickFalse)\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n while ((c=ReadBlobByte(image)) == 0) ;\n if (c != 0x11)\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n version=ReadBlobByte(image);\n if (version == 2)\n {\n c=ReadBlobByte(image);\n if (c != 0xff)\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n }\n else\n if (version != 1)\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n if ((frame.left < 0) || (frame.right < 0) || (frame.top < 0) ||\n (frame.bottom < 0) || (frame.left >= frame.right) ||\n (frame.top >= frame.bottom))\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n /*\n Create black canvas.\n */\n flags=0;\n image->depth=8;\n image->columns=1UL*(frame.right-frame.left);\n image->rows=1UL*(frame.bottom-frame.top);\n image->resolution.x=DefaultResolution;\n image->resolution.y=DefaultResolution;\n image->units=UndefinedResolution;\n if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))\n if (image->scene >= (image_info->scene+image_info->number_scenes-1))\n {\n (void) CloseBlob(image);\n return(GetFirstImageInList(image));\n }\n status=SetImageExtent(image,image->columns,image->rows,exception);\n if (status == MagickFalse)\n return(DestroyImageList(image));\n /*\n Interpret PICT opcodes.\n */\n jpeg=MagickFalse;\n for (code=0; EOFBlob(image) == MagickFalse; )\n {\n if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))\n if (image->scene >= (image_info->scene+image_info->number_scenes-1))\n break;\n if ((version == 1) || ((TellBlob(image) % 2) != 0))\n code=ReadBlobByte(image);\n if (version == 2)\n code=(int) ReadBlobMSBShort(image);\n if (code < 0)\n break;\n if (code > 0xa1)\n {\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\"%04X:\",code);\n }\n else\n {\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" %04X %s: %s\",code,codes[code].name,codes[code].description);\n switch (code)\n {\n case 0x01:\n {\n /*\n Clipping rectangle.\n */\n length=ReadBlobMSBShort(image);\n if (length != 0x000a)\n {\n for (i=0; i < (ssize_t) (length-2); i++)\n if (ReadBlobByte(image) == EOF)\n break;\n break;\n }\n if (ReadRectangle(image,&frame) == MagickFalse)\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n if (((frame.left & 0x8000) != 0) || ((frame.top & 0x8000) != 0))\n break;\n image->columns=1UL*(frame.right-frame.left);\n image->rows=1UL*(frame.bottom-frame.top);\n (void) SetImageBackgroundColor(image,exception);\n break;\n }\n case 0x12:\n case 0x13:\n case 0x14:\n {\n ssize_t\n pattern;\n\n size_t\n height,\n width;\n\n /*\n Skip pattern definition.\n */\n pattern=1L*ReadBlobMSBShort(image);\n for (i=0; i < 8; i++)\n if (ReadBlobByte(image) == EOF)\n break;\n if (pattern == 2)\n {\n for (i=0; i < 5; i++)\n if (ReadBlobByte(image) == EOF)\n break;\n break;\n }\n if (pattern != 1)\n ThrowReaderException(CorruptImageError,\"UnknownPatternType\");\n length=ReadBlobMSBShort(image);\n if (ReadRectangle(image,&frame) == MagickFalse)\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n ReadPixmap(pixmap);\n image->depth=1UL*pixmap.component_size;\n image->resolution.x=1.0*pixmap.horizontal_resolution;\n image->resolution.y=1.0*pixmap.vertical_resolution;\n image->units=PixelsPerInchResolution;\n (void) ReadBlobMSBLong(image);\n flags=1L*ReadBlobMSBShort(image);\n length=ReadBlobMSBShort(image);\n for (i=0; i <= (ssize_t) length; i++)\n (void) ReadBlobMSBLong(image);\n width=1UL*(frame.bottom-frame.top);\n height=1UL*(frame.right-frame.left);\n if (pixmap.bits_per_pixel <= 8)\n length&=0x7fff;\n if (pixmap.bits_per_pixel == 16)\n width<<=1;\n if (length == 0)\n length=width;\n if (length < 8)\n {\n for (i=0; i < (ssize_t) (length*height); i++)\n if (ReadBlobByte(image) == EOF)\n break;\n }\n else\n for (j=0; j < (int) height; j++)\n if (length > 200)\n {\n for (j=0; j < (ssize_t) ReadBlobMSBShort(image); j++)\n if (ReadBlobByte(image) == EOF)\n break;\n }\n else\n for (j=0; j < (ssize_t) ReadBlobByte(image); j++)\n if (ReadBlobByte(image) == EOF)\n break;\n break;\n }\n case 0x1b:\n {\n /*\n Initialize image background color.\n */\n image->background_color.red=(Quantum)\n ScaleShortToQuantum(ReadBlobMSBShort(image));\n image->background_color.green=(Quantum)\n ScaleShortToQuantum(ReadBlobMSBShort(image));\n image->background_color.blue=(Quantum)\n ScaleShortToQuantum(ReadBlobMSBShort(image));\n break;\n }\n case 0x70:\n case 0x71:\n case 0x72:\n case 0x73:\n case 0x74:\n case 0x75:\n case 0x76:\n case 0x77:\n {\n /*\n Skip polygon or region.\n */\n length=ReadBlobMSBShort(image);\n for (i=0; i < (ssize_t) (length-2); i++)\n if (ReadBlobByte(image) == EOF)\n break;\n break;\n }\n case 0x90:\n case 0x91:\n case 0x98:\n case 0x99:\n case 0x9a:\n case 0x9b:\n {\n Image\n *tile_image;\n\n PICTRectangle\n source,\n destination;\n\n register unsigned char\n *p;\n\n size_t\n j;\n\n ssize_t\n bytes_per_line;\n\n unsigned char\n *pixels;\n\n /*\n Pixmap clipped by a rectangle.\n */\n bytes_per_line=0;\n if ((code != 0x9a) && (code != 0x9b))\n bytes_per_line=1L*ReadBlobMSBShort(image);\n else\n {\n (void) ReadBlobMSBShort(image);\n (void) ReadBlobMSBShort(image);\n (void) ReadBlobMSBShort(image);\n }\n if (ReadRectangle(image,&frame) == MagickFalse)\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n /*\n Initialize tile image.\n */\n tile_image=CloneImage(image,1UL*(frame.right-frame.left),\n 1UL*(frame.bottom-frame.top),MagickTrue,exception);\n if (tile_image == (Image *) NULL)\n return((Image *) NULL);\n if ((code == 0x9a) || (code == 0x9b) ||\n ((bytes_per_line & 0x8000) != 0))\n {\n ReadPixmap(pixmap);\n tile_image->depth=1UL*pixmap.component_size;\n tile_image->alpha_trait=pixmap.component_count == 4 ?\n BlendPixelTrait : UndefinedPixelTrait;\n tile_image->resolution.x=(double) pixmap.horizontal_resolution;\n tile_image->resolution.y=(double) pixmap.vertical_resolution;\n tile_image->units=PixelsPerInchResolution;\n if (tile_image->alpha_trait != UndefinedPixelTrait)\n image->alpha_trait=tile_image->alpha_trait;\n }\n if ((code != 0x9a) && (code != 0x9b))\n {\n /*\n Initialize colormap.\n */\n tile_image->colors=2;\n if ((bytes_per_line & 0x8000) != 0)\n {\n (void) ReadBlobMSBLong(image);\n flags=1L*ReadBlobMSBShort(image);\n tile_image->colors=1UL*ReadBlobMSBShort(image)+1;\n }\n status=AcquireImageColormap(tile_image,tile_image->colors,\n exception);\n if (status == MagickFalse)\n {\n tile_image=DestroyImage(tile_image);\n ThrowReaderException(ResourceLimitError,\n \"MemoryAllocationFailed\");\n }\n if ((bytes_per_line & 0x8000) != 0)\n {\n for (i=0; i < (ssize_t) tile_image->colors; i++)\n {\n j=ReadBlobMSBShort(image) % tile_image->colors;\n if ((flags & 0x8000) != 0)\n j=(size_t) i;\n tile_image->colormap[j].red=(Quantum)\n ScaleShortToQuantum(ReadBlobMSBShort(image));\n tile_image->colormap[j].green=(Quantum)\n ScaleShortToQuantum(ReadBlobMSBShort(image));\n tile_image->colormap[j].blue=(Quantum)\n ScaleShortToQuantum(ReadBlobMSBShort(image));\n }\n }\n else\n {\n for (i=0; i < (ssize_t) tile_image->colors; i++)\n {\n tile_image->colormap[i].red=(Quantum) (QuantumRange-\n tile_image->colormap[i].red);\n tile_image->colormap[i].green=(Quantum) (QuantumRange-\n tile_image->colormap[i].green);\n tile_image->colormap[i].blue=(Quantum) (QuantumRange-\n tile_image->colormap[i].blue);\n }\n }\n }\n if (ReadRectangle(image,&source) == MagickFalse)\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n if (ReadRectangle(image,&destination) == MagickFalse)\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n (void) ReadBlobMSBShort(image);\n if ((code == 0x91) || (code == 0x99) || (code == 0x9b))\n {\n /*\n Skip region.\n */\n length=ReadBlobMSBShort(image);\n for (i=0; i < (ssize_t) (length-2); i++)\n if (ReadBlobByte(image) == EOF)\n break;\n }\n if ((code != 0x9a) && (code != 0x9b) &&\n (bytes_per_line & 0x8000) == 0)\n pixels=DecodeImage(image,tile_image,1UL*bytes_per_line,1,&extent,\n exception);\n else\n pixels=DecodeImage(image,tile_image,1UL*bytes_per_line,1U*\n pixmap.bits_per_pixel,&extent,exception);\n if (pixels == (unsigned char *) NULL)\n {\n tile_image=DestroyImage(tile_image);\n ThrowReaderException(ResourceLimitError,\n \"MemoryAllocationFailed\");\n }\n /*\n Convert PICT tile image to pixel packets.\n */\n p=pixels;\n for (y=0; y < (ssize_t) tile_image->rows; y++)\n {\n if (p > (pixels+extent+image->columns))\n ThrowReaderException(CorruptImageError,\"NotEnoughPixelData\");\n q=QueueAuthenticPixels(tile_image,0,y,tile_image->columns,1,\n exception);\n if (q == (Quantum *) NULL)\n break;\n for (x=0; x < (ssize_t) tile_image->columns; x++)\n {\n if (tile_image->storage_class == PseudoClass)\n {\n index=ConstrainColormapIndex(tile_image,*p,exception);\n SetPixelIndex(tile_image,index,q);\n SetPixelRed(tile_image,\n tile_image->colormap[(ssize_t) index].red,q);\n SetPixelGreen(tile_image,\n tile_image->colormap[(ssize_t) index].green,q);\n SetPixelBlue(tile_image,\n tile_image->colormap[(ssize_t) index].blue,q);\n }\n else\n {\n if (pixmap.bits_per_pixel == 16)\n {\n i=(*p++);\n j=(*p);\n SetPixelRed(tile_image,ScaleCharToQuantum(\n (unsigned char) ((i & 0x7c) << 1)),q);\n SetPixelGreen(tile_image,ScaleCharToQuantum(\n (unsigned char) (((i & 0x03) << 6) |\n ((j & 0xe0) >> 2))),q);\n SetPixelBlue(tile_image,ScaleCharToQuantum(\n (unsigned char) ((j & 0x1f) << 3)),q);\n }\n else\n if (tile_image->alpha_trait == UndefinedPixelTrait)\n {\n if (p > (pixels+extent+2*image->columns))\n ThrowReaderException(CorruptImageError,\n \"NotEnoughPixelData\");\n SetPixelRed(tile_image,ScaleCharToQuantum(*p),q);\n SetPixelGreen(tile_image,ScaleCharToQuantum(\n *(p+tile_image->columns)),q);\n SetPixelBlue(tile_image,ScaleCharToQuantum(\n *(p+2*tile_image->columns)),q);\n }\n else\n {\n if (p > (pixels+extent+3*image->columns))\n ThrowReaderException(CorruptImageError,\n \"NotEnoughPixelData\");\n SetPixelAlpha(tile_image,ScaleCharToQuantum(*p),q);\n SetPixelRed(tile_image,ScaleCharToQuantum(\n *(p+tile_image->columns)),q);\n SetPixelGreen(tile_image,ScaleCharToQuantum(\n *(p+2*tile_image->columns)),q);\n SetPixelBlue(tile_image,ScaleCharToQuantum(\n *(p+3*tile_image->columns)),q);\n }\n }\n p++;\n q+=GetPixelChannels(tile_image);\n }\n if (SyncAuthenticPixels(tile_image,exception) == MagickFalse)\n break;\n if ((tile_image->storage_class == DirectClass) &&\n (pixmap.bits_per_pixel != 16))\n {\n p+=(pixmap.component_count-1)*tile_image->columns;\n if (p < pixels)\n break;\n }\n status=SetImageProgress(image,LoadImageTag,y,tile_image->rows);\n if (status == MagickFalse)\n break;\n }\n pixels=(unsigned char *) RelinquishMagickMemory(pixels);\n if (jpeg == MagickFalse)\n if ((code == 0x9a) || (code == 0x9b) ||\n ((bytes_per_line & 0x8000) != 0))\n (void) CompositeImage(image,tile_image,CopyCompositeOp,\n MagickTrue,destination.left,destination.top,exception);\n tile_image=DestroyImage(tile_image);\n break;\n }\n case 0xa1:\n {\n unsigned char\n *info;\n\n size_t\n type;\n\n /*\n Comment.\n */\n type=ReadBlobMSBShort(image);\n length=ReadBlobMSBShort(image);\n if (length == 0)\n break;\n (void) ReadBlobMSBLong(image);\n length-=4;\n if (length == 0)\n break;\n info=(unsigned char *) AcquireQuantumMemory(length,sizeof(*info));\n if (info == (unsigned char *) NULL)\n break;\n count=ReadBlob(image,length,info);\n if (count != (ssize_t) length)\n ThrowReaderException(ResourceLimitError,\"UnableToReadImageData\");\n switch (type)\n {\n case 0xe0:\n {\n if (length == 0)\n break;\n profile=BlobToStringInfo((const void *) NULL,length);\n SetStringInfoDatum(profile,info);\n status=SetImageProfile(image,\"icc\",profile,exception);\n profile=DestroyStringInfo(profile);\n if (status == MagickFalse)\n ThrowReaderException(ResourceLimitError,\n \"MemoryAllocationFailed\");\n break;\n }\n case 0x1f2:\n {\n if (length == 0)\n break;\n profile=BlobToStringInfo((const void *) NULL,length);\n SetStringInfoDatum(profile,info);\n status=SetImageProfile(image,\"iptc\",profile,exception);\n if (status == MagickFalse)\n ThrowReaderException(ResourceLimitError,\n \"MemoryAllocationFailed\");\n profile=DestroyStringInfo(profile);\n break;\n }\n default:\n break;\n }\n info=(unsigned char *) RelinquishMagickMemory(info);\n break;\n }\n default:\n {\n /*\n Skip to next op code.\n */\n if (code < 0)\n break;\n if (codes[code].length == -1)\n (void) ReadBlobMSBShort(image);\n else\n for (i=0; i < (ssize_t) codes[code].length; i++)\n if (ReadBlobByte(image) == EOF)\n break;\n }\n }\n }\n if (code == 0xc00)\n {\n /*\n Skip header.\n */\n for (i=0; i < 24; i++)\n if (ReadBlobByte(image) == EOF)\n break;\n continue;\n }\n if (((code >= 0xb0) && (code <= 0xcf)) ||\n ((code >= 0x8000) && (code <= 0x80ff)))\n continue;\n if (code == 0x8200)\n {\n FILE\n *file;\n\n Image\n *tile_image;\n\n ImageInfo\n *read_info;\n\n int\n unique_file;\n\n /*\n Embedded JPEG.\n */\n jpeg=MagickTrue;\n read_info=CloneImageInfo(image_info);\n SetImageInfoBlob(read_info,(void *) NULL,0);\n file=(FILE *) NULL;\n unique_file=AcquireUniqueFileResource(read_info->filename);\n if (unique_file != -1)\n file=fdopen(unique_file,\"wb\");\n if ((unique_file == -1) || (file == (FILE *) NULL))\n {\n (void) RelinquishUniqueFileResource(read_info->filename);\n (void) CopyMagickString(image->filename,read_info->filename,\n MagickPathExtent);\n ThrowFileException(exception,FileOpenError,\n \"UnableToCreateTemporaryFile\",image->filename);\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n length=ReadBlobMSBLong(image);\n if (length > 154)\n {\n for (i=0; i < 6; i++)\n (void) ReadBlobMSBLong(image);\n if (ReadRectangle(image,&frame) == MagickFalse)\n {\n (void) fclose(file);\n (void) RelinquishUniqueFileResource(read_info->filename);\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n }\n for (i=0; i < 122; i++)\n if (ReadBlobByte(image) == EOF)\n break;\n for (i=0; i < (ssize_t) (length-154); i++)\n {\n c=ReadBlobByte(image);\n if (c == EOF)\n break;\n (void) fputc(c,file);\n }\n }\n (void) fclose(file);\n (void) close(unique_file);\n tile_image=ReadImage(read_info,exception);\n (void) RelinquishUniqueFileResource(read_info->filename);\n read_info=DestroyImageInfo(read_info);\n if (tile_image == (Image *) NULL)\n continue;\n (void) FormatLocaleString(geometry,MagickPathExtent,\"%.20gx%.20g\",\n (double) MagickMax(image->columns,tile_image->columns),\n (double) MagickMax(image->rows,tile_image->rows));\n (void) SetImageExtent(image,\n MagickMax(image->columns,tile_image->columns),\n MagickMax(image->rows,tile_image->rows),exception);\n (void) TransformImageColorspace(image,tile_image->colorspace,exception);\n (void) CompositeImage(image,tile_image,CopyCompositeOp,MagickTrue,\n frame.left,frame.right,exception);\n image->compression=tile_image->compression;\n tile_image=DestroyImage(tile_image);\n continue;\n }\n if ((code == 0xff) || (code == 0xffff))\n break;\n if (((code >= 0xd0) && (code <= 0xfe)) ||\n ((code >= 0x8100) && (code <= 0xffff)))\n {\n /*\n Skip reserved.\n */\n length=ReadBlobMSBShort(image);\n for (i=0; i < (ssize_t) length; i++)\n if (ReadBlobByte(image) == EOF)\n break;\n continue;\n }\n if ((code >= 0x100) && (code <= 0x7fff))\n {\n /*\n Skip reserved.\n */\n length=(size_t) ((code >> 7) & 0xff);\n for (i=0; i < (ssize_t) length; i++)\n if (ReadBlobByte(image) == EOF)\n break;\n continue;\n }\n }\n (void) CloseBlob(image);\n return(GetFirstImageInList(image));\n}\n", + "line": null, + "label": 0, + "cwe": "CWE-189", + "cve": "CVE-2015-8896", + "length": 5468 + }, + { + "index": 12806, + "code": "int ssl_get_new_session(SSL *s, int session)\n{\n /* This gets used by clients and servers. */\n\n unsigned int tmp;\n SSL_SESSION *ss = NULL;\n GEN_SESSION_CB cb = def_generate_session_id;\n\n if ((ss = SSL_SESSION_new()) == NULL)\n return (0);\n\n /* If the context has a default timeout, use it */\n if (s->session_ctx->session_timeout == 0)\n ss->timeout = SSL_get_default_timeout(s);\n else\n ss->timeout = s->session_ctx->session_timeout;\n\n if (s->session != NULL) {\n SSL_SESSION_free(s->session);\n s->session = NULL;\n }\n\n if (session) {\n if (s->version == SSL2_VERSION) {\n ss->ssl_version = SSL2_VERSION;\n ss->session_id_length = SSL2_SSL_SESSION_ID_LENGTH;\n } else if (s->version == SSL3_VERSION) {\n ss->ssl_version = SSL3_VERSION;\n ss->session_id_length = SSL3_SSL_SESSION_ID_LENGTH;\n } else if (s->version == TLS1_VERSION) {\n ss->ssl_version = TLS1_VERSION;\n ss->session_id_length = SSL3_SSL_SESSION_ID_LENGTH;\n } else if (s->version == TLS1_1_VERSION) {\n ss->ssl_version = TLS1_1_VERSION;\n ss->session_id_length = SSL3_SSL_SESSION_ID_LENGTH;\n } else if (s->version == TLS1_2_VERSION) {\n ss->ssl_version = TLS1_2_VERSION;\n ss->session_id_length = SSL3_SSL_SESSION_ID_LENGTH;\n } else if (s->version == DTLS1_BAD_VER) {\n ss->ssl_version = DTLS1_BAD_VER;\n ss->session_id_length = SSL3_SSL_SESSION_ID_LENGTH;\n } else if (s->version == DTLS1_VERSION) {\n ss->ssl_version = DTLS1_VERSION;\n ss->session_id_length = SSL3_SSL_SESSION_ID_LENGTH;\n } else if (s->version == DTLS1_2_VERSION) {\n ss->ssl_version = DTLS1_2_VERSION;\n ss->session_id_length = SSL3_SSL_SESSION_ID_LENGTH;\n } else {\n SSLerr(SSL_F_SSL_GET_NEW_SESSION, SSL_R_UNSUPPORTED_SSL_VERSION);\n SSL_SESSION_free(ss);\n return (0);\n }\n#ifndef OPENSSL_NO_TLSEXT\n /*-\n * If RFC5077 ticket, use empty session ID (as server).\n * Note that:\n * (a) ssl_get_prev_session() does lookahead into the\n * ClientHello extensions to find the session ticket.\n * When ssl_get_prev_session() fails, s3_srvr.c calls\n * ssl_get_new_session() in ssl3_get_client_hello().\n * At that point, it has not yet parsed the extensions,\n * however, because of the lookahead, it already knows\n * whether a ticket is expected or not.\n *\n * (b) s3_clnt.c calls ssl_get_new_session() before parsing\n * ServerHello extensions, and before recording the session\n * ID received from the server, so this block is a noop.\n */\n if (s->tlsext_ticket_expected) {\n ss->session_id_length = 0;\n goto sess_id_done;\n }\n#endif\n /* Choose which callback will set the session ID */\n CRYPTO_r_lock(CRYPTO_LOCK_SSL_CTX);\n if (s->generate_session_id)\n cb = s->generate_session_id;\n else if (s->session_ctx->generate_session_id)\n cb = s->session_ctx->generate_session_id;\n CRYPTO_r_unlock(CRYPTO_LOCK_SSL_CTX);\n /* Choose a session ID */\n tmp = ss->session_id_length;\n if (!cb(s, ss->session_id, &tmp)) {\n /* The callback failed */\n SSLerr(SSL_F_SSL_GET_NEW_SESSION,\n SSL_R_SSL_SESSION_ID_CALLBACK_FAILED);\n SSL_SESSION_free(ss);\n return (0);\n }\n /*\n * Don't allow the callback to set the session length to zero. nor\n * set it higher than it was.\n */\n if (!tmp || (tmp > ss->session_id_length)) {\n /* The callback set an illegal length */\n SSLerr(SSL_F_SSL_GET_NEW_SESSION,\n SSL_R_SSL_SESSION_ID_HAS_BAD_LENGTH);\n SSL_SESSION_free(ss);\n return (0);\n }\n /* If the session length was shrunk and we're SSLv2, pad it */\n if ((tmp < ss->session_id_length) && (s->version == SSL2_VERSION))\n memset(ss->session_id + tmp, 0, ss->session_id_length - tmp);\n else\n ss->session_id_length = tmp;\n /* Finally, check for a conflict */\n if (SSL_has_matching_session_id(s, ss->session_id,\n ss->session_id_length)) {\n SSLerr(SSL_F_SSL_GET_NEW_SESSION, SSL_R_SSL_SESSION_ID_CONFLICT);\n SSL_SESSION_free(ss);\n return (0);\n }\n#ifndef OPENSSL_NO_TLSEXT\n sess_id_done:\n if (s->tlsext_hostname) {\n ss->tlsext_hostname = BUF_strdup(s->tlsext_hostname);\n if (ss->tlsext_hostname == NULL) {\n SSLerr(SSL_F_SSL_GET_NEW_SESSION, ERR_R_INTERNAL_ERROR);\n SSL_SESSION_free(ss);\n return 0;\n }\n }\n#endif\n } else {\n ss->session_id_length = 0;\n }\n\n if (s->sid_ctx_length > sizeof ss->sid_ctx) {\n SSLerr(SSL_F_SSL_GET_NEW_SESSION, ERR_R_INTERNAL_ERROR);\n SSL_SESSION_free(ss);\n return 0;\n }\n memcpy(ss->sid_ctx, s->sid_ctx, s->sid_ctx_length);\n ss->sid_ctx_length = s->sid_ctx_length;\n s->session = ss;\n ss->ssl_version = s->version;\n ss->verify_result = X509_V_OK;\n\n return (1);\n}\n", + "line": null, + "label": 0, + "cwe": "CWE-190", + "cve": "CVE-2016-2177", + "length": 1310 + }, + { + "index": 44196, + "code": "int ssl3_client_hello(SSL *s)\n{\n unsigned char *buf;\n unsigned char *p, *d;\n int i;\n unsigned long l;\n int al = 0;\n#ifndef OPENSSL_NO_COMP\n int j;\n SSL_COMP *comp;\n#endif\n\n buf = (unsigned char *)s->init_buf->data;\n if (s->state == SSL3_ST_CW_CLNT_HELLO_A) {\n SSL_SESSION *sess = s->session;\n\n /* Work out what SSL/TLS/DTLS version to use */\n if (ssl_set_version(s) == 0)\n goto err;\n\n if ((sess == NULL) || (sess->ssl_version != s->version) ||\n /*\n * In the case of EAP-FAST, we can have a pre-shared\n * \"ticket\" without a session ID.\n */\n (!sess->session_id_length && !sess->tlsext_tick) ||\n (sess->not_resumable)) {\n if (!ssl_get_new_session(s, 0))\n goto err;\n }\n /* else use the pre-loaded session */\n\n p = s->s3->client_random;\n\n /*\n * for DTLS if client_random is initialized, reuse it, we are\n * required to use same upon reply to HelloVerify\n */\n if (SSL_IS_DTLS(s)) {\n size_t idx;\n i = 1;\n for (idx = 0; idx < sizeof(s->s3->client_random); idx++) {\n if (p[idx]) {\n i = 0;\n break;\n }\n }\n } else\n i = 1;\n\n if (i && ssl_fill_hello_random(s, 0, p,\n sizeof(s->s3->client_random)) <= 0)\n goto err;\n\n /* Do the message type and length last */\n d = p = ssl_handshake_start(s);\n\n /*-\n * version indicates the negotiated version: for example from\n * an SSLv2/v3 compatible client hello). The client_version\n * field is the maximum version we permit and it is also\n * used in RSA encrypted premaster secrets. Some servers can\n * choke if we initially report a higher version then\n * renegotiate to a lower one in the premaster secret. This\n * didn't happen with TLS 1.0 as most servers supported it\n * but it can with TLS 1.1 or later if the server only supports\n * 1.0.\n *\n * Possible scenario with previous logic:\n * 1. Client hello indicates TLS 1.2\n * 2. Server hello says TLS 1.0\n * 3. RSA encrypted premaster secret uses 1.2.\n * 4. Handhaked proceeds using TLS 1.0.\n * 5. Server sends hello request to renegotiate.\n * 6. Client hello indicates TLS v1.0 as we now\n * know that is maximum server supports.\n * 7. Server chokes on RSA encrypted premaster secret\n * containing version 1.0.\n *\n * For interoperability it should be OK to always use the\n * maximum version we support in client hello and then rely\n * on the checking of version to ensure the servers isn't\n * being inconsistent: for example initially negotiating with\n * TLS 1.0 and renegotiating with TLS 1.2. We do this by using\n * client_version in client hello and not resetting it to\n * the negotiated version.\n */\n *(p++) = s->client_version >> 8;\n *(p++) = s->client_version & 0xff;\n\n /* Random stuff */\n memcpy(p, s->s3->client_random, SSL3_RANDOM_SIZE);\n p += SSL3_RANDOM_SIZE;\n\n /* Session ID */\n if (s->new_session)\n i = 0;\n else\n i = s->session->session_id_length;\n *(p++) = i;\n if (i != 0) {\n if (i > (int)sizeof(s->session->session_id)) {\n SSLerr(SSL_F_SSL3_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);\n goto err;\n }\n memcpy(p, s->session->session_id, i);\n p += i;\n }\n\n /* cookie stuff for DTLS */\n if (SSL_IS_DTLS(s)) {\n if (s->d1->cookie_len > sizeof(s->d1->cookie)) {\n SSLerr(SSL_F_SSL3_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);\n goto err;\n }\n *(p++) = s->d1->cookie_len;\n memcpy(p, s->d1->cookie, s->d1->cookie_len);\n p += s->d1->cookie_len;\n }\n\n /* Ciphers supported */\n i = ssl_cipher_list_to_bytes(s, SSL_get_ciphers(s), &(p[2]), 0);\n if (i == 0) {\n SSLerr(SSL_F_SSL3_CLIENT_HELLO, SSL_R_NO_CIPHERS_AVAILABLE);\n goto err;\n }\n#ifdef OPENSSL_MAX_TLS1_2_CIPHER_LENGTH\n /*\n * Some servers hang if client hello > 256 bytes as hack workaround\n * chop number of supported ciphers to keep it well below this if we\n * use TLS v1.2\n */\n if (TLS1_get_version(s) >= TLS1_2_VERSION\n && i > OPENSSL_MAX_TLS1_2_CIPHER_LENGTH)\n i = OPENSSL_MAX_TLS1_2_CIPHER_LENGTH & ~1;\n#endif\n s2n(i, p);\n p += i;\n\n /* COMPRESSION */\n#ifdef OPENSSL_NO_COMP\n *(p++) = 1;\n#else\n\n if (!ssl_allow_compression(s) || !s->ctx->comp_methods)\n j = 0;\n else\n j = sk_SSL_COMP_num(s->ctx->comp_methods);\n *(p++) = 1 + j;\n for (i = 0; i < j; i++) {\n comp = sk_SSL_COMP_value(s->ctx->comp_methods, i);\n *(p++) = comp->id;\n }\n#endif\n *(p++) = 0; /* Add the NULL method */\n\n /* TLS extensions */\n if (ssl_prepare_clienthello_tlsext(s) <= 0) {\n SSLerr(SSL_F_SSL3_CLIENT_HELLO, SSL_R_CLIENTHELLO_TLSEXT);\n goto err;\n }\n if ((p =\n ssl_add_clienthello_tlsext(s, p, buf + SSL3_RT_MAX_PLAIN_LENGTH,\n &al)) == NULL) {\n ssl3_send_alert(s, SSL3_AL_FATAL, al);\n SSLerr(SSL_F_SSL3_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);\n goto err;\n }\n\n l = p - d;\n if (!ssl_set_handshake_header(s, SSL3_MT_CLIENT_HELLO, l)) {\n ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);\n SSLerr(SSL_F_SSL3_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);\n goto err;\n }\n s->state = SSL3_ST_CW_CLNT_HELLO_B;\n }\n\n /* SSL3_ST_CW_CLNT_HELLO_B */\n return ssl_do_write(s);\n err:\n s->state = SSL_ST_ERR;\n return (-1);\n}\n", + "line": null, + "label": 0, + "cwe": "CWE-362", + "cve": "CVE-2015-1791", + "length": 1613 + }, + { + "index": 158657, + "code": "bool GLES2DecoderImpl::ClearLevel3D(Texture* texture,\n unsigned target,\n int level,\n unsigned format,\n unsigned type,\n int width,\n int height,\n int depth) {\n DCHECK(target == GL_TEXTURE_3D || target == GL_TEXTURE_2D_ARRAY);\n DCHECK(feature_info_->IsWebGL2OrES3Context());\n if (width == 0 || height == 0 || depth == 0)\n return true;\n\n uint32_t size;\n uint32_t padded_row_size;\n uint32_t padding;\n PixelStoreParams params;\n params.alignment = state_.unpack_alignment;\n if (!GLES2Util::ComputeImageDataSizesES3(width, height, depth,\n format, type,\n params,\n &size,\n nullptr,\n &padded_row_size,\n nullptr,\n &padding)) {\n return false;\n }\n const uint32_t kMaxZeroSize = 1024 * 1024 * 2;\n uint32_t buffer_size;\n std::vector subs;\n if (size < kMaxZeroSize) {\n buffer_size = size;\n subs.push_back(TexSubCoord3D(0, 0, 0, width, height, depth));\n } else {\n uint32_t size_per_layer;\n if (!SafeMultiplyUint32(padded_row_size, height, &size_per_layer)) {\n return false;\n }\n if (size_per_layer < kMaxZeroSize) {\n uint32_t depth_step = kMaxZeroSize / size_per_layer;\n uint32_t num_of_slices = depth / depth_step;\n if (num_of_slices * depth_step < static_cast(depth))\n num_of_slices++;\n DCHECK_LT(0u, num_of_slices);\n buffer_size = size_per_layer * depth_step;\n int depth_of_last_slice = depth - (num_of_slices - 1) * depth_step;\n DCHECK_LT(0, depth_of_last_slice);\n for (uint32_t ii = 0; ii < num_of_slices; ++ii) {\n int depth_ii =\n (ii + 1 == num_of_slices ? depth_of_last_slice : depth_step);\n subs.push_back(\n TexSubCoord3D(0, 0, depth_step * ii, width, height, depth_ii));\n }\n } else {\n if (kMaxZeroSize < padded_row_size) {\n return false;\n }\n uint32_t height_step = kMaxZeroSize / padded_row_size;\n uint32_t num_of_slices = height / height_step;\n if (num_of_slices * height_step < static_cast(height))\n num_of_slices++;\n DCHECK_LT(0u, num_of_slices);\n buffer_size = padded_row_size * height_step;\n int height_of_last_slice = height - (num_of_slices - 1) * height_step;\n DCHECK_LT(0, height_of_last_slice);\n for (int zz = 0; zz < depth; ++zz) {\n for (uint32_t ii = 0; ii < num_of_slices; ++ii) {\n int height_ii =\n (ii + 1 == num_of_slices ? height_of_last_slice : height_step);\n subs.push_back(\n TexSubCoord3D(0, height_step * ii, zz, width, height_ii, 1));\n }\n }\n }\n }\n\n TRACE_EVENT1(\"gpu\", \"GLES2DecoderImpl::ClearLevel3D\", \"size\", size);\n\n {\n ScopedPixelUnpackState reset_restore(&state_);\n GLuint buffer_id = 0;\n api()->glGenBuffersARBFn(1, &buffer_id);\n api()->glBindBufferFn(GL_PIXEL_UNPACK_BUFFER, buffer_id);\n {\n buffer_size += padding;\n std::unique_ptr zero(new char[buffer_size]);\n memset(zero.get(), 0, buffer_size);\n api()->glBufferDataFn(GL_PIXEL_UNPACK_BUFFER, buffer_size, zero.get(),\n GL_STATIC_DRAW);\n }\n\n api()->glBindTextureFn(texture->target(), texture->service_id());\n for (size_t ii = 0; ii < subs.size(); ++ii) {\n api()->glTexSubImage3DFn(target, level, subs[ii].xoffset,\n subs[ii].yoffset, subs[ii].zoffset,\n subs[ii].width, subs[ii].height, subs[ii].depth,\n format, type, nullptr);\n }\n api()->glDeleteBuffersARBFn(1, &buffer_id);\n }\n\n TextureRef* bound_texture =\n texture_manager()->GetTextureInfoForTarget(&state_, texture->target());\n api()->glBindTextureFn(texture->target(),\n bound_texture ? bound_texture->service_id() : 0);\n return true;\n}\n", + "line": null, + "label": 0, + "cwe": "CWE-119", + "cve": "CVE-2018-17470", + "length": 1037 + }, + { + "index": 61125, + "code": "report_delete_progress (CommonJob *job,\n SourceInfo *source_info,\n TransferInfo *transfer_info)\n{\n int files_left;\n double elapsed, transfer_rate;\n int remaining_time;\n gint64 now;\n char *details;\n char *status;\n DeleteJob *delete_job;\n\n delete_job = (DeleteJob *) job;\n now = g_get_monotonic_time ();\n files_left = source_info->num_files - transfer_info->num_files;\n\n /* Races and whatnot could cause this to be negative... */\n if (files_left < 0)\n {\n files_left = 0;\n }\n\n /* If the number of files left is 0, we want to update the status without\n * considering this time, since we want to change the status to completed\n * and probably we won't get more calls to this function */\n if (transfer_info->last_report_time != 0 &&\n ABS ((gint64) (transfer_info->last_report_time - now)) < 100 * NSEC_PER_MICROSEC &&\n files_left > 0)\n {\n return;\n }\n\n transfer_info->last_report_time = now;\n\n if (source_info->num_files == 1)\n {\n if (files_left == 0)\n {\n status = _(\"Deleted \u201c%B\u201d\");\n }\n else\n {\n status = _(\"Deleting \u201c%B\u201d\");\n }\n nautilus_progress_info_take_status (job->progress,\n f (status,\n (GFile *) delete_job->files->data));\n }\n else\n {\n if (files_left == 0)\n {\n status = ngettext (\"Deleted %'d file\",\n \"Deleted %'d files\",\n source_info->num_files);\n }\n else\n {\n status = ngettext (\"Deleting %'d file\",\n \"Deleting %'d files\",\n source_info->num_files);\n }\n nautilus_progress_info_take_status (job->progress,\n f (status,\n source_info->num_files));\n }\n\n elapsed = g_timer_elapsed (job->time, NULL);\n transfer_rate = 0;\n remaining_time = INT_MAX;\n if (elapsed > 0)\n {\n transfer_rate = transfer_info->num_files / elapsed;\n if (transfer_rate > 0)\n {\n remaining_time = (source_info->num_files - transfer_info->num_files) / transfer_rate;\n }\n }\n\n if (elapsed < SECONDS_NEEDED_FOR_RELIABLE_TRANSFER_RATE)\n {\n if (files_left > 0)\n {\n /* To translators: %'d is the number of files completed for the operation,\n * so it will be something like 2/14. */\n details = f (_(\"%'d / %'d\"),\n transfer_info->num_files + 1,\n source_info->num_files);\n }\n else\n {\n /* To translators: %'d is the number of files completed for the operation,\n * so it will be something like 2/14. */\n details = f (_(\"%'d / %'d\"),\n transfer_info->num_files,\n source_info->num_files);\n }\n }\n else\n {\n if (files_left > 0)\n {\n gchar *time_left_message;\n gchar *files_per_second_message;\n gchar *concat_detail;\n\n /* To translators: %T will expand to a time duration like \"2 minutes\".\n * So the whole thing will be something like \"1 / 5 -- 2 hours left (4 files/sec)\"\n *\n * The singular/plural form will be used depending on the remaining time (i.e. the %T argument).\n */\n time_left_message = ngettext (\"%'d / %'d \\xE2\\x80\\x94 %T left\",\n \"%'d / %'d \\xE2\\x80\\x94 %T left\",\n seconds_count_format_time_units (remaining_time));\n transfer_rate += 0.5;\n files_per_second_message = ngettext (\"(%d file/sec)\",\n \"(%d files/sec)\",\n (int) transfer_rate);\n concat_detail = g_strconcat (time_left_message, \" \", files_per_second_message, NULL);\n\n details = f (concat_detail,\n transfer_info->num_files + 1, source_info->num_files,\n remaining_time,\n (int) transfer_rate);\n\n g_free (concat_detail);\n }\n else\n {\n /* To translators: %'d is the number of files completed for the operation,\n * so it will be something like 2/14. */\n details = f (_(\"%'d / %'d\"),\n transfer_info->num_files,\n source_info->num_files);\n }\n }\n nautilus_progress_info_take_details (job->progress, details);\n\n if (elapsed > SECONDS_NEEDED_FOR_APROXIMATE_TRANSFER_RATE)\n {\n nautilus_progress_info_set_remaining_time (job->progress,\n remaining_time);\n nautilus_progress_info_set_elapsed_time (job->progress,\n elapsed);\n }\n\n if (source_info->num_files != 0)\n {\n nautilus_progress_info_set_progress (job->progress, transfer_info->num_files, source_info->num_files);\n }\n}\n", + "line": null, + "label": 0, + "cwe": "CWE-20", + "cve": "CVE-2017-14604", + "length": 1128 + }, + { + "index": 28051, + "code": "static int decode_slice(AVCodecContext *c, void *arg)\n{\n FFV1Context *fs = *(void **)arg;\n FFV1Context *f = fs->avctx->priv_data;\n int width, height, x, y, ret;\n const int ps = av_pix_fmt_desc_get(c->pix_fmt)->comp[0].step_minus1 + 1;\n AVFrame * const p = f->cur;\n int i, si;\n\n for( si=0; fs != f->slice_context[si]; si ++)\n ;\n\n if(f->fsrc && !p->key_frame)\n ff_thread_await_progress(&f->last_picture, si, 0);\n\n if(f->fsrc && !p->key_frame) {\n FFV1Context *fssrc = f->fsrc->slice_context[si];\n FFV1Context *fsdst = f->slice_context[si];\n av_assert1(fsdst->plane_count == fssrc->plane_count);\n av_assert1(fsdst == fs);\n\n if (!p->key_frame)\n fsdst->slice_damaged |= fssrc->slice_damaged;\n\n for (i = 0; i < f->plane_count; i++) {\n PlaneContext *psrc = &fssrc->plane[i];\n PlaneContext *pdst = &fsdst->plane[i];\n\n av_free(pdst->state);\n av_free(pdst->vlc_state);\n memcpy(pdst, psrc, sizeof(*pdst));\n pdst->state = NULL;\n pdst->vlc_state = NULL;\n\n if (fssrc->ac) {\n pdst->state = av_malloc(CONTEXT_SIZE * psrc->context_count);\n memcpy(pdst->state, psrc->state, CONTEXT_SIZE * psrc->context_count);\n } else {\n pdst->vlc_state = av_malloc(sizeof(*pdst->vlc_state) * psrc->context_count);\n memcpy(pdst->vlc_state, psrc->vlc_state, sizeof(*pdst->vlc_state) * psrc->context_count);\n }\n }\n }\n\n if (f->version > 2) {\n if (ffv1_init_slice_state(f, fs) < 0)\n return AVERROR(ENOMEM);\n if (decode_slice_header(f, fs) < 0) {\n fs->slice_damaged = 1;\n return AVERROR_INVALIDDATA;\n }\n }\n if ((ret = ffv1_init_slice_state(f, fs)) < 0)\n return ret;\n if (f->cur->key_frame)\n ffv1_clear_slice_state(f, fs);\n\n width = fs->slice_width;\n height = fs->slice_height;\n x = fs->slice_x;\n y = fs->slice_y;\n\n if (!fs->ac) {\n if (f->version == 3 && f->micro_version > 1 || f->version > 3)\n get_rac(&fs->c, (uint8_t[]) { 129 });\n fs->ac_byte_count = f->version > 2 || (!x && !y) ? fs->c.bytestream - fs->c.bytestream_start - 1 : 0;\n init_get_bits(&fs->gb,\n fs->c.bytestream_start + fs->ac_byte_count,\n (fs->c.bytestream_end - fs->c.bytestream_start - fs->ac_byte_count) * 8);\n }\n\n av_assert1(width && height);\n if (f->colorspace == 0) {\n const int chroma_width = FF_CEIL_RSHIFT(width, f->chroma_h_shift);\n const int chroma_height = FF_CEIL_RSHIFT(height, f->chroma_v_shift);\n const int cx = x >> f->chroma_h_shift;\n const int cy = y >> f->chroma_v_shift;\n decode_plane(fs, p->data[0] + ps*x + y*p->linesize[0], width, height, p->linesize[0], 0);\n\n if (f->chroma_planes) {\n decode_plane(fs, p->data[1] + ps*cx+cy*p->linesize[1], chroma_width, chroma_height, p->linesize[1], 1);\n decode_plane(fs, p->data[2] + ps*cx+cy*p->linesize[2], chroma_width, chroma_height, p->linesize[2], 1);\n }\n if (fs->transparency)\n decode_plane(fs, p->data[3] + ps*x + y*p->linesize[3], width, height, p->linesize[3], 2);\n } else {\n uint8_t *planes[3] = { p->data[0] + ps * x + y * p->linesize[0],\n p->data[1] + ps * x + y * p->linesize[1],\n p->data[2] + ps * x + y * p->linesize[2] };\n decode_rgb_frame(fs, planes, width, height, p->linesize);\n }\n if (fs->ac && f->version > 2) {\n int v;\n get_rac(&fs->c, (uint8_t[]) { 129 });\n v = fs->c.bytestream_end - fs->c.bytestream - 2 - 5*f->ec;\n if (v) {\n av_log(f->avctx, AV_LOG_ERROR, \"bytestream end mismatching by %d\\n\", v);\n fs->slice_damaged = 1;\n }\n }\n\n emms_c();\n\n ff_thread_report_progress(&f->picture, si, 0);\n\n return 0;\n}\n", + "line": null, + "label": 0, + "cwe": "CWE-119", + "cve": "CVE-2013-7020", + "length": 1264 + }, + { + "index": 10296, + "code": " gray_convert_glyph( RAS_ARG )\n {\n TBand bands[40];\n TBand* volatile band;\n int volatile n, num_bands;\n TPos volatile min, max, max_y;\n FT_BBox* clip;\n\n\n /* Set up state in the raster object */\n gray_compute_cbox( RAS_VAR );\n\n /* clip to target bitmap, exit if nothing to do */\n clip = &ras.clip_box;\n\n if ( ras.max_ex <= clip->xMin || ras.min_ex >= clip->xMax ||\n ras.max_ey <= clip->yMin || ras.min_ey >= clip->yMax )\n return 0;\n\n if ( ras.min_ex < clip->xMin ) ras.min_ex = clip->xMin;\n if ( ras.min_ey < clip->yMin ) ras.min_ey = clip->yMin;\n\n if ( ras.max_ex > clip->xMax ) ras.max_ex = clip->xMax;\n if ( ras.max_ey > clip->yMax ) ras.max_ey = clip->yMax;\n\n ras.count_ex = ras.max_ex - ras.min_ex;\n ras.count_ey = ras.max_ey - ras.min_ey;\n\n /* simple heuristic used to speed up the bezier decomposition -- see */\n /* the code in gray_render_conic() and gray_render_cubic() for more */\n /* details */\n ras.conic_level = 32;\n ras.cubic_level = 16;\n\n {\n int level = 0;\n\n\n if ( ras.count_ex > 24 || ras.count_ey > 24 )\n level++;\n if ( ras.count_ex > 120 || ras.count_ey > 120 )\n level++;\n\n ras.conic_level <<= level;\n ras.cubic_level <<= level;\n }\n\n /* set up vertical bands */\n num_bands = (int)( ( ras.max_ey - ras.min_ey ) / ras.band_size );\n if ( num_bands == 0 )\n num_bands = 1;\n if ( num_bands >= 39 )\n num_bands = 39;\n\n ras.band_shoot = 0;\n\n min = ras.min_ey;\n max_y = ras.max_ey;\n\n for ( n = 0; n < num_bands; n++, min = max )\n {\n max = min + ras.band_size;\n if ( n == num_bands - 1 || max > max_y )\n max = max_y;\n\n bands[0].min = min;\n bands[0].max = max;\n band = bands;\n\n while ( band >= bands )\n {\n TPos bottom, top, middle;\n int error;\n\n {\n PCell cells_max;\n int yindex;\n long cell_start, cell_end, cell_mod;\n\n\n ras.ycells = (PCell*)ras.buffer;\n ras.ycount = band->max - band->min;\n\n cell_start = sizeof ( PCell ) * ras.ycount;\n cell_mod = cell_start % sizeof ( TCell );\n if ( cell_mod > 0 )\n cell_start += sizeof ( TCell ) - cell_mod;\n\n cell_end = ras.buffer_size;\n cell_end -= cell_end % sizeof( TCell );\n\n cells_max = (PCell)( (char*)ras.buffer + cell_end );\n ras.cells = (PCell)( (char*)ras.buffer + cell_start );\n if ( ras.cells >= cells_max )\n goto ReduceBands;\n\n ras.max_cells = cells_max - ras.cells;\n if ( ras.max_cells < 2 )\n goto ReduceBands;\n\n for ( yindex = 0; yindex < ras.ycount; yindex++ )\n ras.ycells[yindex] = NULL;\n }\n\n ras.num_cells = 0;\n ras.invalid = 1;\n ras.min_ey = band->min;\n ras.max_ey = band->max;\n ras.count_ey = band->max - band->min;\n\n error = gray_convert_glyph_inner( RAS_VAR );\n\n if ( !error )\n {\n gray_sweep( RAS_VAR_ &ras.target );\n band--;\n continue;\n }\n else if ( error != ErrRaster_Memory_Overflow )\n return 1;\n\n ReduceBands:\n /* render pool overflow; we will reduce the render band by half */\n bottom = band->min;\n top = band->max;\n middle = bottom + ( ( top - bottom ) >> 1 );\n\n /* This is too complex for a single scanline; there must */\n /* be some problems. */\n if ( middle == bottom )\n {\n#ifdef FT_DEBUG_LEVEL_TRACE\n FT_TRACE7(( \"gray_convert_glyph: rotten glyph\\n\" ));\n#endif\n return 1;\n }\n\n if ( bottom-top >= ras.band_size )\n ras.band_shoot++;\n\n band[1].min = bottom;\n band[1].max = middle;\n band[0].min = middle;\n band[0].max = top;\n band++;\n }\n }\n\n if ( ras.band_shoot > 8 && ras.band_size > 16 )\n ras.band_size = ras.band_size / 2;\n\n return 0;\n }\n", + "line": null, + "label": 0, + "cwe": "CWE-189", + "cve": "CVE-2010-2500", + "length": 1136 + }, + { + "index": 48232, + "code": "computeInputPixelOffsets(struct crop_mask *crop, struct image_data *image,\n struct offset *off)\n {\n double scale;\n float xres, yres;\n /* Values for these offsets are in pixels from start of image, not bytes,\n * and are indexed from zero to width - 1 or length - 1 */\n uint32 tmargin, bmargin, lmargin, rmargin;\n uint32 startx, endx; /* offsets of first and last columns to extract */\n uint32 starty, endy; /* offsets of first and last row to extract */\n uint32 width, length, crop_width, crop_length; \n uint32 i, max_width, max_length, zwidth, zlength, buffsize;\n uint32 x1, x2, y1, y2;\n\n if (image->res_unit != RESUNIT_INCH && image->res_unit != RESUNIT_CENTIMETER)\n {\n xres = 1.0;\n yres = 1.0;\n }\n else\n {\n if (((image->xres == 0) || (image->yres == 0)) && \n (crop->res_unit != RESUNIT_NONE) &&\n\t((crop->crop_mode & CROP_REGIONS) || (crop->crop_mode & CROP_MARGINS) ||\n \t (crop->crop_mode & CROP_LENGTH) || (crop->crop_mode & CROP_WIDTH)))\n {\n TIFFError(\"computeInputPixelOffsets\", \"Cannot compute margins or fixed size sections without image resolution\");\n TIFFError(\"computeInputPixelOffsets\", \"Specify units in pixels and try again\");\n return (-1);\n }\n xres = image->xres;\n yres = image->yres;\n }\n\n /* Translate user units to image units */\n scale = 1.0;\n switch (crop->res_unit) {\n case RESUNIT_CENTIMETER:\n if (image->res_unit == RESUNIT_INCH)\n\t scale = 1.0/2.54;\n\t break;\n case RESUNIT_INCH:\n\t if (image->res_unit == RESUNIT_CENTIMETER)\n\t scale = 2.54;\n\t break;\n case RESUNIT_NONE: /* Dimensions in pixels */\n default:\n break;\n }\n\n if (crop->crop_mode & CROP_REGIONS)\n {\n max_width = max_length = 0;\n for (i = 0; i < crop->regions; i++)\n {\n if ((crop->res_unit == RESUNIT_INCH) || (crop->res_unit == RESUNIT_CENTIMETER))\n {\n\tx1 = (uint32) (crop->corners[i].X1 * scale * xres);\n\tx2 = (uint32) (crop->corners[i].X2 * scale * xres);\n\ty1 = (uint32) (crop->corners[i].Y1 * scale * yres);\n\ty2 = (uint32) (crop->corners[i].Y2 * scale * yres);\n }\n else\n {\n\tx1 = (uint32) (crop->corners[i].X1);\n\tx2 = (uint32) (crop->corners[i].X2);\n\ty1 = (uint32) (crop->corners[i].Y1);\n\ty2 = (uint32) (crop->corners[i].Y2); \n\t}\n if (x1 < 1)\n crop->regionlist[i].x1 = 0;\n else\n crop->regionlist[i].x1 = (uint32) (x1 - 1);\n\n if (x2 > image->width - 1)\n crop->regionlist[i].x2 = image->width - 1;\n else\n crop->regionlist[i].x2 = (uint32) (x2 - 1);\n zwidth = crop->regionlist[i].x2 - crop->regionlist[i].x1 + 1; \n\n if (y1 < 1)\n crop->regionlist[i].y1 = 0;\n else\n crop->regionlist[i].y1 = (uint32) (y1 - 1);\n\n if (y2 > image->length - 1)\n crop->regionlist[i].y2 = image->length - 1;\n else\n crop->regionlist[i].y2 = (uint32) (y2 - 1);\n\n zlength = crop->regionlist[i].y2 - crop->regionlist[i].y1 + 1; \n\n if (zwidth > max_width)\n max_width = zwidth;\n if (zlength > max_length)\n max_length = zlength;\n\n buffsize = (uint32)\n (((zwidth * image->bps * image->spp + 7 ) / 8) * (zlength + 1));\n\n crop->regionlist[i].buffsize = buffsize;\n crop->bufftotal += buffsize;\n if (crop->img_mode == COMPOSITE_IMAGES)\n {\n switch (crop->edge_ref)\n {\n case EDGE_LEFT:\n case EDGE_RIGHT:\n crop->combined_length = zlength;\n crop->combined_width += zwidth;\n break;\n case EDGE_BOTTOM:\n case EDGE_TOP: /* width from left, length from top */\n default:\n crop->combined_width = zwidth;\n crop->combined_length += zlength;\n\t break;\n }\n\t}\n }\n return (0);\n }\n \n /* Convert crop margins into offsets into image\n * Margins are expressed as pixel rows and columns, not bytes\n */\n if (crop->crop_mode & CROP_MARGINS)\n {\n if (crop->res_unit != RESUNIT_INCH && crop->res_unit != RESUNIT_CENTIMETER)\n { /* User has specified pixels as reference unit */\n tmargin = (uint32)(crop->margins[0]);\n lmargin = (uint32)(crop->margins[1]);\n bmargin = (uint32)(crop->margins[2]);\n rmargin = (uint32)(crop->margins[3]);\n }\n else\n { /* inches or centimeters specified */\n tmargin = (uint32)(crop->margins[0] * scale * yres);\n lmargin = (uint32)(crop->margins[1] * scale * xres);\n bmargin = (uint32)(crop->margins[2] * scale * yres);\n rmargin = (uint32)(crop->margins[3] * scale * xres);\n }\n\n if ((lmargin + rmargin) > image->width)\n {\n TIFFError(\"computeInputPixelOffsets\", \"Combined left and right margins exceed image width\");\n lmargin = (uint32) 0;\n rmargin = (uint32) 0;\n return (-1);\n }\n if ((tmargin + bmargin) > image->length)\n {\n TIFFError(\"computeInputPixelOffsets\", \"Combined top and bottom margins exceed image length\"); \n tmargin = (uint32) 0; \n bmargin = (uint32) 0;\n return (-1);\n }\n }\n else\n { /* no margins requested */\n tmargin = (uint32) 0;\n lmargin = (uint32) 0;\n bmargin = (uint32) 0;\n rmargin = (uint32) 0;\n }\n\n /* Width, height, and margins are expressed as pixel offsets into image */\n if (crop->res_unit != RESUNIT_INCH && crop->res_unit != RESUNIT_CENTIMETER)\n {\n if (crop->crop_mode & CROP_WIDTH)\n width = (uint32)crop->width;\n else\n width = image->width - lmargin - rmargin;\n\n if (crop->crop_mode & CROP_LENGTH)\n length = (uint32)crop->length;\n else\n length = image->length - tmargin - bmargin;\n }\n else\n {\n if (crop->crop_mode & CROP_WIDTH)\n width = (uint32)(crop->width * scale * image->xres);\n else\n width = image->width - lmargin - rmargin;\n\n if (crop->crop_mode & CROP_LENGTH)\n length = (uint32)(crop->length * scale * image->yres);\n else\n length = image->length - tmargin - bmargin;\n }\n\n off->tmargin = tmargin;\n off->bmargin = bmargin;\n off->lmargin = lmargin;\n off->rmargin = rmargin;\n\n /* Calculate regions defined by margins, width, and length. \n * Coordinates expressed as 0 to imagewidth - 1, imagelength - 1,\n * since they are used to compute offsets into buffers */\n switch (crop->edge_ref) {\n case EDGE_BOTTOM:\n startx = lmargin;\n if ((startx + width) >= (image->width - rmargin))\n endx = image->width - rmargin - 1;\n else\n endx = startx + width - 1;\n\n endy = image->length - bmargin - 1;\n if ((endy - length) <= tmargin)\n starty = tmargin;\n else\n starty = endy - length + 1;\n break;\n case EDGE_RIGHT:\n endx = image->width - rmargin - 1;\n if ((endx - width) <= lmargin)\n startx = lmargin;\n else\n startx = endx - width + 1;\n\n starty = tmargin;\n if ((starty + length) >= (image->length - bmargin))\n endy = image->length - bmargin - 1;\n else\n endy = starty + length - 1;\n break;\n case EDGE_TOP: /* width from left, length from top */\n case EDGE_LEFT:\n default:\n startx = lmargin;\n if ((startx + width) >= (image->width - rmargin))\n endx = image->width - rmargin - 1;\n else\n endx = startx + width - 1;\n\n starty = tmargin;\n if ((starty + length) >= (image->length - bmargin))\n endy = image->length - bmargin - 1;\n else\n endy = starty + length - 1;\n break;\n }\n off->startx = startx;\n off->starty = starty;\n off->endx = endx;\n off->endy = endy;\n\n crop_width = endx - startx + 1;\n crop_length = endy - starty + 1;\n\n if (crop_width <= 0)\n {\n TIFFError(\"computeInputPixelOffsets\", \n \"Invalid left/right margins and /or image crop width requested\");\n return (-1);\n }\n if (crop_width > image->width)\n crop_width = image->width;\n\n if (crop_length <= 0)\n {\n TIFFError(\"computeInputPixelOffsets\", \n \"Invalid top/bottom margins and /or image crop length requested\");\n return (-1);\n }\n if (crop_length > image->length)\n crop_length = image->length;\n\n off->crop_width = crop_width;\n off->crop_length = crop_length;\n\n return (0);\n } /* end computeInputPixelOffsets */\n", + "line": null, + "label": 0, + "cwe": "CWE-125", + "cve": "CVE-2016-9539", + "length": 2503 + }, + { + "index": 7077, + "code": " t42_parse_sfnts( T42_Face face,\n T42_Loader loader )\n {\n T42_Parser parser = &loader->parser;\n FT_Memory memory = parser->root.memory;\n FT_Byte* cur;\n FT_Byte* limit = parser->root.limit;\n FT_Error error;\n FT_Int num_tables = 0;\n FT_ULong count, ttf_size = 0;\n\n FT_Long n, string_size, old_string_size, real_size;\n FT_Byte* string_buf = NULL;\n FT_Bool allocated = 0;\n\n T42_Load_Status status;\n\n\n /* The format is */\n /* */\n /* /sfnts [ ... ] def */\n /* */\n /* or */\n /* */\n /* /sfnts [ */\n /* RD */\n /* RD */\n /* ... */\n /* ] def */\n /* */\n /* with exactly one space after the `RD' token. */\n\n T1_Skip_Spaces( parser );\n\n if ( parser->root.cursor >= limit || *parser->root.cursor++ != '[' )\n {\n FT_ERROR(( \"t42_parse_sfnts: can't find begin of sfnts vector\\n\" ));\n error = FT_THROW( Invalid_File_Format );\n goto Fail;\n }\n\n T1_Skip_Spaces( parser );\n status = BEFORE_START;\n string_size = 0;\n old_string_size = 0;\n count = 0;\n\n while ( parser->root.cursor < limit )\n {\n cur = parser->root.cursor;\n\n if ( *cur == ']' )\n {\n parser->root.cursor++;\n goto Exit;\n }\n\n else if ( *cur == '<' )\n {\n T1_Skip_PS_Token( parser );\n if ( parser->root.error )\n goto Exit;\n\n /* don't include delimiters */\n string_size = (FT_Long)( ( parser->root.cursor - cur - 2 + 1 ) / 2 );\n if ( FT_REALLOC( string_buf, old_string_size, string_size ) )\n goto Fail;\n\n allocated = 1;\n\n parser->root.cursor = cur;\n (void)T1_ToBytes( parser, string_buf, string_size, &real_size, 1 );\n old_string_size = string_size;\n string_size = real_size;\n }\n\n else if ( ft_isdigit( *cur ) )\n {\n if ( allocated )\n {\n FT_ERROR(( \"t42_parse_sfnts: \"\n \"can't handle mixed binary and hex strings\\n\" ));\n error = FT_THROW( Invalid_File_Format );\n goto Fail;\n }\n\n string_size = T1_ToInt( parser );\n if ( string_size < 0 )\n {\n FT_ERROR(( \"t42_parse_sfnts: invalid string size\\n\" ));\n error = FT_THROW( Invalid_File_Format );\n goto Fail;\n }\n\n T1_Skip_PS_Token( parser ); /* `RD' */\n if ( parser->root.error )\n return;\n\n string_buf = parser->root.cursor + 1; /* one space after `RD' */\n\n if ( limit - parser->root.cursor < string_size )\n {\n FT_ERROR(( \"t42_parse_sfnts: too many binary data\\n\" ));\n error = FT_THROW( Invalid_File_Format );\n goto Fail;\n }\n else\n parser->root.cursor += string_size + 1;\n }\n\n if ( !string_buf )\n {\n FT_ERROR(( \"t42_parse_sfnts: invalid data in sfnts array\\n\" ));\n error = FT_THROW( Invalid_File_Format );\n goto Fail;\n }\n\n /* A string can have a trailing zero (odd) byte for padding. */\n /* Ignore it. */\n if ( ( string_size & 1 ) && string_buf[string_size - 1] == 0 )\n string_size--;\n\n if ( !string_size )\n {\n FT_ERROR(( \"t42_parse_sfnts: invalid string\\n\" ));\n error = FT_THROW( Invalid_File_Format );\n goto Fail;\n }\n\n for ( n = 0; n < string_size; n++ )\n {\n switch ( status )\n {\n case BEFORE_START:\n /* load offset table, 12 bytes */\n if ( count < 12 )\n {\n face->ttf_data[count++] = string_buf[n];\n continue;\n }\n else\n {\n num_tables = 16 * face->ttf_data[4] + face->ttf_data[5];\n status = BEFORE_TABLE_DIR;\n ttf_size = 12 + 16 * num_tables;\n\n if ( FT_REALLOC( face->ttf_data, 12, ttf_size ) )\n goto Fail;\n }\n /* fall through */\n\n case BEFORE_TABLE_DIR:\n /* the offset table is read; read the table directory */\n if ( count < ttf_size )\n {\n face->ttf_data[count++] = string_buf[n];\n continue;\n }\n else\n {\n int i;\n FT_ULong len;\n\n\n for ( i = 0; i < num_tables; i++ )\n {\n FT_Byte* p = face->ttf_data + 12 + 16 * i + 12;\n\n\n len = FT_PEEK_ULONG( p );\n\n /* Pad to a 4-byte boundary length */\n ttf_size += ( len + 3 ) & ~3;\n }\n\n status = OTHER_TABLES;\n face->ttf_size = ttf_size;\n\n /* there are no more than 256 tables, so no size check here */\n if ( FT_REALLOC( face->ttf_data, 12 + 16 * num_tables,\n ttf_size + 1 ) )\n goto Fail;\n }\n /* fall through */\n\n case OTHER_TABLES:\n /* all other tables are just copied */\n if ( count >= ttf_size )\n {\n FT_ERROR(( \"t42_parse_sfnts: too many binary data\\n\" ));\n error = FT_THROW( Invalid_File_Format );\n goto Fail;\n }\n face->ttf_data[count++] = string_buf[n];\n }\n }\n\n T1_Skip_Spaces( parser );\n }\n\n /* if control reaches this point, the format was not valid */\n error = FT_THROW( Invalid_File_Format );\n\n Fail:\n parser->root.error = error;\n\n Exit:\n if ( allocated )\n FT_FREE( string_buf );\n }\n", + "line": null, + "label": 0, + "cwe": "CWE-119", + "cve": "CVE-2014-9664", + "length": 1445 + }, + { + "index": 182885, + "code": "int treeRead(struct READER *reader, struct DATAOBJECT *data) {\n\n\tint i, j, err, olen, elements, size, x, y, z, b, e, dy, dz, sx, sy, sz, dzy,\n\t\tszy;\n\tchar *input, *output;\n\n\tuint8_t node_type, node_level;\n\tuint16_t entries_used;\n\tuint32_t size_of_chunk;\n\tuint32_t filter_mask;\n\tuint64_t address_of_left_sibling, address_of_right_sibling, start[4],\n\t\tchild_pointer, key, store;\n\n\tchar buf[4];\n\n\tUNUSED(node_level);\n\tUNUSED(address_of_right_sibling);\n\tUNUSED(address_of_left_sibling);\n\tUNUSED(key);\n\n\tif (data->ds.dimensionality > 3) {\n\t\tlog(\"TREE dimensions > 3\");\n\t\treturn MYSOFA_INVALID_FORMAT;\n\t}\n\n\t/* read signature */\n\tif (fread(buf, 1, 4, reader->fhd) != 4 || strncmp(buf, \"TREE\", 4)) {\n\t\tlog(\"cannot read signature of TREE\\n\");\n\t\treturn MYSOFA_INVALID_FORMAT;\n\t} log(\"%08lX %.4s\\n\", (uint64_t )ftell(reader->fhd) - 4, buf);\n\n\tnode_type = (uint8_t)fgetc(reader->fhd);\n\tnode_level = (uint8_t)fgetc(reader->fhd);\n\tentries_used = (uint16_t)readValue(reader, 2);\n\tif(entries_used>0x1000)\n\t\treturn MYSOFA_UNSUPPORTED_FORMAT;\n\taddress_of_left_sibling = readValue(reader,\n\t\t\t\t\t reader->superblock.size_of_offsets);\n\taddress_of_right_sibling = readValue(reader,\n\t\t\t\t\t reader->superblock.size_of_offsets);\n\n\telements = 1;\n\tfor (j = 0; j < data->ds.dimensionality; j++)\n\t\telements *= data->datalayout_chunk[j];\n\tdy = data->datalayout_chunk[1];\n\tdz = data->datalayout_chunk[2];\n\tsx = data->ds.dimension_size[0];\n\tsy = data->ds.dimension_size[1];\n\tsz = data->ds.dimension_size[2];\n\tdzy = dz * dy;\n\tszy = sz * sy;\n\tsize = data->datalayout_chunk[data->ds.dimensionality];\n\n\tlog(\"elements %d size %d\\n\",elements,size);\n\n\tif (!(output = malloc(elements * size))) {\n\t\treturn MYSOFA_NO_MEMORY;\n\t}\n\n\tfor (e = 0; e < entries_used * 2; e++) {\n\t\tif (node_type == 0) {\n\t\t\tkey = readValue(reader, reader->superblock.size_of_lengths);\n\t\t} else {\n\t\t\tsize_of_chunk = (uint32_t)readValue(reader, 4);\n\t\t\tfilter_mask = (uint32_t)readValue(reader, 4);\n\t\t\tif (filter_mask) {\n\t\t\t\tlog(\"TREE all filters must be enabled\\n\");\n\t\t\t\tfree(output);\n\t\t\t\treturn MYSOFA_INVALID_FORMAT;\n\t\t\t}\n\n\t\t\tfor (j = 0; j < data->ds.dimensionality; j++) {\n\t\t\t\tstart[j] = readValue(reader, 8);\n\t\t\t\tlog(\"start %d %lu\\n\",j,start[j]);\n\t\t\t}\n\n\t\t\tif (readValue(reader, 8)) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tchild_pointer = readValue(reader,\n\t\t\t\t\t\t reader->superblock.size_of_offsets);\n\t\t\tlog(\" data at %lX len %u\\n\", child_pointer, size_of_chunk);\n\n\t\t\t/* read data */\n\t\t\tstore = ftell(reader->fhd);\n\t\t\tif (fseek(reader->fhd, child_pointer, SEEK_SET)<0) {\n\t\t\t\tfree(output);\n\t\t\t\treturn errno;\n\t\t\t}\n\n\t\t\tif (!(input = malloc(size_of_chunk))) {\n\t\t\t\tfree(output);\n\t\t\t\treturn MYSOFA_NO_MEMORY;\n\t\t\t}\n\t\t\tif (fread(input, 1, size_of_chunk, reader->fhd) != size_of_chunk) {\n\t\t\t\tfree(output);\n\t\t\t\tfree(input);\n\t\t\t\treturn MYSOFA_INVALID_FORMAT;\n\t\t\t}\n\n\t\t\tolen = elements * size;\n\t\t\terr = gunzip(size_of_chunk, input, &olen, output);\n\t\t\tfree(input);\n\n\t\t\tlog(\" gunzip %d %d %d\\n\",err, olen, elements*size);\n\t\t\tif (err || olen != elements * size) {\n\t\t\t\tfree(output);\n\t\t\t\treturn MYSOFA_INVALID_FORMAT;\n\t\t\t}\n\n\t\t\tswitch (data->ds.dimensionality) {\n\t\t\tcase 1:\n \t\t\t\tfor (i = 0; i < olen; i++) {\n \t\t\t\t\tb = i / elements;\n \t\t\t\t\tx = i % elements + start[0];\n\t\t\t\t\tif (x < sx) {\n\t\t\t\t\t\tj = x * size + b;\n \t\t\t\t\t\t((char*)data->data)[j] = output[i];\n \t\t\t\t\t}\n \t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase 2:\n\t\t\t\tfor (i = 0; i < olen; i++) {\n\t\t\t\t\tb = i / elements;\n \t\t\t\t\tx = i % elements;\n \t\t\t\t\ty = x % dy + start[1];\n \t\t\t\t\tx = x / dy + start[0];\n\t\t\t\t\tif (y < sy && x < sx) {\n\t\t\t\t\t\tj = ((x * sy + y) * size) + b;\n \t\t\t\t\t\t((char*)data->data)[j] = output[i];\n \t\t\t\t\t}\n \t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase 3:\n\t\t\t\tfor (i = 0; i < olen; i++) {\n\t\t\t\t\tb = i / elements;\n\t\t\t\t\tx = i % elements;\n \t\t\t\t\tz = x % dz + start[2];\n \t\t\t\t\ty = (x / dz) % dy + start[1];\n \t\t\t\t\tx = (x / dzy) + start[0];\n\t\t\t\t\tif (z < sz && y < sy && x < sx) {\n\t\t\t\t\t\tj = (x * szy + y * sz + z) * size + b;\n \t\t\t\t\t\t((char*)data->data)[j] = output[i];\n \t\t\t\t\t}\n \t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tlog(\"invalid dim\\n\");\n\t\t\t\treturn MYSOFA_INTERNAL_ERROR;\n\t\t\t}\n\n\t\t\tif(fseek(reader->fhd, store, SEEK_SET)<0) {\n\t\t\t\tfree(output);\n\t\t\t\treturn errno;\n\t\t\t}\n\t\t}\n\t}\n\n\tfree(output);\n\tif(fseek(reader->fhd, 4, SEEK_CUR)<0) /* skip checksum */\n\t\treturn errno;\n\n\treturn MYSOFA_OK;\n}\n", + "line": "\t\t\t\t\tif (x < sx) {\n\t\t\t\t\t\tj = x * size + b;\n\t\t\t\t\tif (y < sy && x < sx) {\n\t\t\t\t\t\tj = ((x * sy + y) * size) + b;\n\t\t\t\t\tif (z < sz && y < sy && x < sx) {\n\t\t\t\t\t\tj = (x * szy + y * sz + z) * size + b;\n", + "label": 1, + "cwe": "CWE-20", + "cve": "CVE-2019-10672", + "length": 1348 + }, + { + "index": 67869, + "code": "aiff_open (SF_PRIVATE *psf)\n{\tCOMM_CHUNK comm_fmt ;\n\tint error, subformat ;\n\n\tmemset (&comm_fmt, 0, sizeof (comm_fmt)) ;\n\n\tsubformat = SF_CODEC (psf->sf.format) ;\n\n\tif ((psf->container_data = calloc (1, sizeof (AIFF_PRIVATE))) == NULL)\n\t\treturn SFE_MALLOC_FAILED ;\n\n\tif (psf->file.mode == SFM_READ || (psf->file.mode == SFM_RDWR && psf->filelength > 0))\n\t{\tif ((error = aiff_read_header (psf, &comm_fmt)))\n\t\t\treturn error ;\n\n\t\tpsf->next_chunk_iterator = aiff_next_chunk_iterator ;\n\t\tpsf->get_chunk_size = aiff_get_chunk_size ;\n\t\tpsf->get_chunk_data = aiff_get_chunk_data ;\n\n\t\tpsf_fseek (psf, psf->dataoffset, SEEK_SET) ;\n\t\t} ;\n\n\tif (psf->file.mode == SFM_WRITE || psf->file.mode == SFM_RDWR)\n\t{\tif (psf->is_pipe)\n\t\t\treturn SFE_NO_PIPE_WRITE ;\n\n\t\tif ((SF_CONTAINER (psf->sf.format)) != SF_FORMAT_AIFF)\n\t\t\treturn SFE_BAD_OPEN_FORMAT ;\n\n\t\tif (psf->file.mode == SFM_WRITE && (subformat == SF_FORMAT_FLOAT || subformat == SF_FORMAT_DOUBLE))\n\t\t{\tif ((psf->peak_info = peak_info_calloc (psf->sf.channels)) == NULL)\n\t\t\t\treturn SFE_MALLOC_FAILED ;\n\t\t\tpsf->peak_info->peak_loc = SF_PEAK_START ;\n\t\t\t} ;\n\n\t\tif (psf->file.mode != SFM_RDWR || psf->filelength < 40)\n\t\t{\tpsf->filelength = 0 ;\n\t\t\tpsf->datalength = 0 ;\n\t\t\tpsf->dataoffset = 0 ;\n\t\t\tpsf->sf.frames = 0 ;\n\t\t\t} ;\n\n\t\tpsf->strings.flags = SF_STR_ALLOW_START | SF_STR_ALLOW_END ;\n\n\t\tif ((error = aiff_write_header (psf, SF_FALSE)))\n\t\t\treturn error ;\n\n\t\tpsf->write_header\t= aiff_write_header ;\n\t\tpsf->set_chunk\t\t= aiff_set_chunk ;\n\t\t} ;\n\n\tpsf->container_close = aiff_close ;\n\tpsf->command = aiff_command ;\n\n\tswitch (SF_CODEC (psf->sf.format))\n\t{\tcase SF_FORMAT_PCM_U8 :\n\t\t\t\terror = pcm_init (psf) ;\n\t\t\t\tbreak ;\n\n\t\tcase SF_FORMAT_PCM_S8 :\n\t\t\t\terror = pcm_init (psf) ;\n\t\t\t\tbreak ;\n\n\t\tcase SF_FORMAT_PCM_16 :\n\t\tcase SF_FORMAT_PCM_24 :\n\t\tcase SF_FORMAT_PCM_32 :\n\t\t\t\terror = pcm_init (psf) ;\n\t\t\t\tbreak ;\n\n\t\tcase SF_FORMAT_ULAW :\n\t\t\t\terror = ulaw_init (psf) ;\n\t\t\t\tbreak ;\n\n\t\tcase SF_FORMAT_ALAW :\n\t\t\t\terror = alaw_init (psf) ;\n\t\t\t\tbreak ;\n\n\t\t/* Lite remove start */\n\t\tcase SF_FORMAT_FLOAT :\n\t\t\t\terror = float32_init (psf) ;\n\t\t\t\tbreak ;\n\n\t\tcase SF_FORMAT_DOUBLE :\n\t\t\t\terror = double64_init (psf) ;\n\t\t\t\tbreak ;\n\n\t\tcase SF_FORMAT_DWVW_12 :\n\t\t\t\tif (psf->sf.frames > comm_fmt.numSampleFrames)\n\t\t\t\t\tpsf->sf.frames = comm_fmt.numSampleFrames ;\n\t\t\t\tbreak ;\n\n\t\tcase SF_FORMAT_DWVW_16 :\n\t\t\t\terror = dwvw_init (psf, 16) ;\n\t\t\t\tif (psf->sf.frames > comm_fmt.numSampleFrames)\n\t\t\t\t\tpsf->sf.frames = comm_fmt.numSampleFrames ;\n\t\t\t\tbreak ;\n\n\t\tcase SF_FORMAT_DWVW_24 :\n\t\t\t\terror = dwvw_init (psf, 24) ;\n\t\t\t\tif (psf->sf.frames > comm_fmt.numSampleFrames)\n\t\t\t\t\tpsf->sf.frames = comm_fmt.numSampleFrames ;\n\t\t\t\tbreak ;\n\n\t\tcase SF_FORMAT_DWVW_N :\n\t\t\t\tif (psf->file.mode != SFM_READ)\n\t\t\t\t{\terror = SFE_DWVW_BAD_BITWIDTH ;\n\t\t\t\t\tbreak ;\n\t\t\t\t\t} ;\n\t\t\t\tif (comm_fmt.sampleSize >= 8 && comm_fmt.sampleSize < 24)\n\t\t\t\t{\terror = dwvw_init (psf, comm_fmt.sampleSize) ;\n\t\t\t\t\tif (psf->sf.frames > comm_fmt.numSampleFrames)\n\t\t\t\t\t\tpsf->sf.frames = comm_fmt.numSampleFrames ;\n\t\t\t\t\tbreak ;\n\t\t\t\t\t} ;\n\t\t\t\tpsf_log_printf (psf, \"AIFC/DWVW : Bad bitwidth %d\\n\", comm_fmt.sampleSize) ;\n\t\t\t\terror = SFE_DWVW_BAD_BITWIDTH ;\n\t\t\t\tbreak ;\n\n\t\tcase SF_FORMAT_IMA_ADPCM :\n\t\t\t\t/*\n\t\t\t\t**\tIMA ADPCM encoded AIFF files always have a block length\n\t\t\t\t**\tof 34 which decodes to 64 samples.\n\t\t\t\t*/\n\t\t\t\terror = aiff_ima_init (psf, AIFC_IMA4_BLOCK_LEN, AIFC_IMA4_SAMPLES_PER_BLOCK) ;\n\t\t\t\tbreak ;\n\t\t/* Lite remove end */\n\n\t\tcase SF_FORMAT_GSM610 :\n\t\t\t\terror = gsm610_init (psf) ;\n\t\t\t\tif (psf->sf.frames > comm_fmt.numSampleFrames)\n\t\t\t\t\tpsf->sf.frames = comm_fmt.numSampleFrames ;\n\t\t\t\tbreak ;\n\n\t\tdefault : return SFE_UNIMPLEMENTED ;\n\t\t} ;\n\n\tif (psf->file.mode != SFM_WRITE && psf->sf.frames - comm_fmt.numSampleFrames != 0)\n\t{\tpsf_log_printf (psf,\n\t\t\t\"*** Frame count read from 'COMM' chunk (%u) not equal to frame count\\n\"\n\t\t\t\"*** calculated from length of 'SSND' chunk (%u).\\n\",\n\t\t\tcomm_fmt.numSampleFrames, (uint32_t) psf->sf.frames) ;\n\t\t} ;\n\n\treturn error ;\n} /* aiff_open */\n", + "line": null, + "label": 0, + "cwe": "CWE-119", + "cve": "CVE-2017-6892", + "length": 1260 + }, + { + "index": 178410, + "code": "XpmCreateDataFromXpmImage(\n char\t***data_return,\n XpmImage\t *image,\n XpmInfo\t *info)\n{\n /* calculation variables */\n int ErrorStatus;\n char buf[BUFSIZ];\n char **header = NULL, **data, **sptr, **sptr2, *s;\n unsigned int header_size, header_nlines;\n unsigned int data_size, data_nlines;\n unsigned int extensions = 0, ext_size = 0, ext_nlines = 0;\n unsigned int offset, l, n;\n\n *data_return = NULL;\n\n extensions = info && (info->valuemask & XpmExtensions)\n\t&& info->nextensions;\n \n /* compute the number of extensions lines and size */\n if (extensions)\n\tCountExtensions(info->extensions, info->nextensions,\n\t\t\t&ext_size, &ext_nlines);\n \n /*\n * alloc a temporary array of char pointer for the header section which\n */\n header_nlines = 1 + image->ncolors; /* this may wrap and/or become 0 */\n\n /* 2nd check superfluous if we do not need header_nlines any further */\n if(header_nlines <= image->ncolors ||\n header_nlines >= UINT_MAX / sizeof(char *))\n \treturn(XpmNoMemory);\n\n header_size = sizeof(char *) * header_nlines;\n if (header_size >= UINT_MAX / sizeof(char *))\n\treturn (XpmNoMemory);\n header = (char **) XpmCalloc(header_size, sizeof(char *)); /* can we trust image->ncolors */\n if (!header)\n\treturn (XpmNoMemory);\n\n /* print the hints line */\n s = buf;\n#ifndef VOID_SPRINTF\n s +=\n#endif\n sprintf(s, \"%d %d %d %d\", image->width, image->height,\n\t image->ncolors, image->cpp);\n#ifdef VOID_SPRINTF\n s += strlen(s);\n#endif\n\n if (info && (info->valuemask & XpmHotspot)) {\n#ifndef VOID_SPRINTF\n\ts +=\n#endif\n\tsprintf(s, \" %d %d\", info->x_hotspot, info->y_hotspot);\n#ifdef VOID_SPRINTF\n\ts += strlen(s);\n#endif\n }\n if (extensions) {\n\tstrcpy(s, \" XPMEXT\");\n\ts += 7;\n }\n l = s - buf + 1;\n *header = (char *) XpmMalloc(l);\n if (!*header)\n\tRETURN(XpmNoMemory);\n header_size += l;\n strcpy(*header, buf);\n\n /* print colors */\n ErrorStatus = CreateColors(header + 1, &header_size,\n\t\t\t image->colorTable, image->ncolors, image->cpp);\n\n if (ErrorStatus != XpmSuccess)\n\tRETURN(ErrorStatus);\n\n /* now we know the size needed, alloc the data and copy the header lines */\n offset = image->width * image->cpp + 1;\n\n if(offset <= image->width || offset <= image->cpp)\n if(offset <= image->width || offset <= image->cpp)\n \tRETURN(XpmNoMemory);\n \n if( (image->height + ext_nlines) >= UINT_MAX / sizeof(char *))\n \tRETURN(XpmNoMemory);\n data_size = (image->height + ext_nlines) * sizeof(char *);\n \n\tRETURN(XpmNoMemory);\n data_size += image->height * offset;\n \tRETURN(XpmNoMemory);\n data_size += image->height * offset;\n \n if( (header_size + ext_size) >= (UINT_MAX - data_size) )\n \tRETURN(XpmNoMemory);\n data_size += header_size + ext_size;\n \n\n data_nlines = header_nlines + image->height + ext_nlines;\n *data = (char *) (data + data_nlines);\n\n /* can header have less elements then n suggests? */\n n = image->ncolors;\n for (l = 0, sptr = data, sptr2 = header; l <= n && sptr && sptr2; l++, sptr++, sptr2++) {\n\tstrcpy(*sptr, *sptr2);\n\t*(sptr + 1) = *sptr + strlen(*sptr2) + 1;\n }\n\n /* print pixels */\n data[header_nlines] = (char *) data + header_size\n\t+ (image->height + ext_nlines) * sizeof(char *);\n\n CreatePixels(data + header_nlines, data_size-header_nlines, image->width, image->height,\n\t\t image->cpp, image->data, image->colorTable);\n\n /* print extensions */\n if (extensions)\n\tCreateExtensions(data + header_nlines + image->height - 1,\n\t\t\t data_size - header_nlines - image->height + 1, offset,\n\t\t\t info->extensions, info->nextensions,\n\t\t\t ext_nlines);\n\n *data_return = data;\n ErrorStatus = XpmSuccess;\n\n/* exit point, free only locally allocated variables */\nexit:\n if (header) {\n\tfor (l = 0; l < header_nlines; l++)\n\t if (header[l])\n\t\tXpmFree(header[l]);\n\t\tXpmFree(header);\n }\n return(ErrorStatus);\n}\n", + "line": "\tCountExtensions(info->extensions, info->nextensions,\n\t\t\t&ext_size, &ext_nlines);\n if( (image->height + ext_nlines) >= UINT_MAX / sizeof(char *))\n if( (header_size + ext_size) >= (UINT_MAX - data_size) )\n", + "label": 1, + "cwe": "CWE-787", + "cve": "CVE-2016-10164", + "length": 1123 + }, + { + "index": 62717, + "code": "MagickExport MagickBooleanType PosterizeImageChannel(Image *image,\n const ChannelType channel,const size_t levels,const MagickBooleanType dither)\n{\n#define PosterizeImageTag \"Posterize/Image\"\n#define PosterizePixel(pixel) (Quantum) (QuantumRange*(MagickRound( \\\n QuantumScale*pixel*(levels-1)))/MagickMax((ssize_t) levels-1,1))\n\n CacheView\n *image_view;\n\n ExceptionInfo\n *exception;\n\n MagickBooleanType\n status;\n\n MagickOffsetType\n progress;\n\n QuantizeInfo\n *quantize_info;\n\n register ssize_t\n i;\n\n ssize_t\n y;\n\n assert(image != (Image *) NULL);\n assert(image->signature == MagickSignature);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",image->filename);\n if (image->storage_class == PseudoClass)\n#if defined(MAGICKCORE_OPENMP_SUPPORT)\n #pragma omp parallel for schedule(static,4) shared(progress,status) \\\n magick_threads(image,image,1,1)\n#endif\n for (i=0; i < (ssize_t) image->colors; i++)\n {\n /*\n Posterize colormap.\n */\n if ((channel & RedChannel) != 0)\n image->colormap[i].red=PosterizePixel(image->colormap[i].red);\n if ((channel & GreenChannel) != 0)\n image->colormap[i].green=PosterizePixel(image->colormap[i].green);\n if ((channel & BlueChannel) != 0)\n image->colormap[i].blue=PosterizePixel(image->colormap[i].blue);\n if ((channel & OpacityChannel) != 0)\n image->colormap[i].opacity=PosterizePixel(image->colormap[i].opacity);\n }\n /*\n Posterize image.\n */\n status=MagickTrue;\n progress=0;\n exception=(&image->exception);\n image_view=AcquireAuthenticCacheView(image,exception);\n#if defined(MAGICKCORE_OPENMP_SUPPORT)\n #pragma omp parallel for schedule(static,4) shared(progress,status) \\\n magick_threads(image,image,image->rows,1)\n#endif\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n register IndexPacket\n *magick_restrict indexes;\n\n register PixelPacket\n *magick_restrict q;\n\n register ssize_t\n x;\n\n if (status == MagickFalse)\n continue;\n q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);\n if (q == (PixelPacket *) NULL)\n {\n status=MagickFalse;\n continue;\n }\n indexes=GetCacheViewAuthenticIndexQueue(image_view);\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n if ((channel & RedChannel) != 0)\n SetPixelRed(q,PosterizePixel(GetPixelRed(q)));\n if ((channel & GreenChannel) != 0)\n SetPixelGreen(q,PosterizePixel(GetPixelGreen(q)));\n if ((channel & BlueChannel) != 0)\n SetPixelBlue(q,PosterizePixel(GetPixelBlue(q)));\n if (((channel & OpacityChannel) != 0) &&\n (image->matte != MagickFalse))\n SetPixelOpacity(q,PosterizePixel(GetPixelOpacity(q)));\n if (((channel & IndexChannel) != 0) &&\n (image->colorspace == CMYKColorspace))\n SetPixelIndex(indexes+x,PosterizePixel(GetPixelIndex(indexes+x)));\n q++;\n }\n if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)\n status=MagickFalse;\n if (image->progress_monitor != (MagickProgressMonitor) NULL)\n {\n MagickBooleanType\n proceed;\n\n#if defined(MAGICKCORE_OPENMP_SUPPORT)\n #pragma omp critical (MagickCore_PosterizeImageChannel)\n#endif\n proceed=SetImageProgress(image,PosterizeImageTag,progress++,\n image->rows);\n if (proceed == MagickFalse)\n status=MagickFalse;\n }\n }\n image_view=DestroyCacheView(image_view);\n quantize_info=AcquireQuantizeInfo((ImageInfo *) NULL);\n quantize_info->number_colors=(size_t) MagickMin((ssize_t) levels*levels*\n levels,MaxColormapSize+1);\n quantize_info->dither=dither;\n quantize_info->tree_depth=MaxTreeDepth;\n status=QuantizeImage(quantize_info,image);\n quantize_info=DestroyQuantizeInfo(quantize_info);\n return(status);\n}\n", + "line": null, + "label": 0, + "cwe": "CWE-772", + "cve": "CVE-2017-12664", + "length": 1031 + }, + { + "index": 164910, + "code": "void ResourceDispatcherHostImpl::BeginNavigationRequest(\n ResourceContext* resource_context,\n net::URLRequestContext* request_context,\n storage::FileSystemContext* upload_file_system_context,\n const NavigationRequestInfo& info,\n std::unique_ptr navigation_ui_data,\n network::mojom::URLLoaderClientPtr url_loader_client,\n network::mojom::URLLoaderRequest url_loader_request,\n ServiceWorkerNavigationHandleCore* service_worker_handle_core,\n AppCacheNavigationHandleCore* appcache_handle_core,\n uint32_t url_loader_options,\n net::RequestPriority net_priority,\n const GlobalRequestID& global_request_id) {\n DCHECK(url_loader_client.is_bound());\n DCHECK(url_loader_request.is_pending());\n\n ResourceType resource_type = info.is_main_frame ?\n RESOURCE_TYPE_MAIN_FRAME : RESOURCE_TYPE_SUB_FRAME;\n\n ChildProcessSecurityPolicyImpl* policy =\n ChildProcessSecurityPolicyImpl::GetInstance();\n bool is_external_protocol =\n info.common_params.url.is_valid() &&\n !request_context->job_factory()->IsHandledProtocol(\n info.common_params.url.scheme());\n bool non_web_url_in_guest =\n info.is_for_guests_only &&\n !policy->IsWebSafeScheme(info.common_params.url.scheme()) &&\n !is_external_protocol;\n\n if (is_shutdown_ || non_web_url_in_guest) {\n url_loader_client->OnComplete(\n network::URLLoaderCompletionStatus(net::ERR_ABORTED));\n return;\n }\n\n std::unique_ptr new_request;\n new_request = request_context->CreateRequest(\n info.common_params.url, net_priority, nullptr, GetTrafficAnnotation());\n\n new_request->set_method(info.common_params.method);\n new_request->set_site_for_cookies(info.site_for_cookies);\n new_request->set_top_frame_origin(info.top_frame_origin);\n new_request->set_initiator(info.common_params.initiator_origin);\n new_request->set_upgrade_if_insecure(info.upgrade_if_insecure);\n if (info.is_main_frame) {\n new_request->set_first_party_url_policy(\n net::URLRequest::UPDATE_FIRST_PARTY_URL_ON_REDIRECT);\n }\n\n std::unique_ptr throttling_token =\n network::ScopedThrottlingToken::MaybeCreate(\n new_request->net_log().source().id, info.devtools_frame_token);\n\n Referrer::SetReferrerForRequest(new_request.get(),\n info.common_params.referrer);\n\n net::HttpRequestHeaders headers;\n headers.AddHeadersFromString(info.begin_params->headers);\n new_request->SetExtraRequestHeaders(headers);\n\n new_request->SetLoadFlags(info.begin_params->load_flags);\n\n storage::BlobStorageContext* blob_context = GetBlobStorageContext(\n GetChromeBlobStorageContextForResourceContext(resource_context));\n\n network::ResourceRequestBody* body = info.common_params.post_data.get();\n BlobHandles blob_handles;\n if (body) {\n if (!GetBodyBlobDataHandles(body, resource_context, &blob_handles)) {\n new_request->CancelWithError(net::ERR_INSUFFICIENT_RESOURCES);\n url_loader_client->OnComplete(\n network::URLLoaderCompletionStatus(net::ERR_ABORTED));\n return;\n }\n new_request->set_upload(UploadDataStreamBuilder::Build(\n body, blob_context, upload_file_system_context,\n base::CreateSingleThreadTaskRunnerWithTraits(\n {base::MayBlock(), base::TaskPriority::USER_VISIBLE})\n .get()));\n }\n\n ResourceRequestInfoImpl* extra_info = new ResourceRequestInfoImpl(\n ResourceRequesterInfo::CreateForBrowserSideNavigation(\n service_worker_handle_core\n ? service_worker_handle_core->context_wrapper()\n : scoped_refptr()),\n -1, // route_id\n info.frame_tree_node_id,\n ChildProcessHost::kInvalidUniqueID, // plugin_child_id\n global_request_id.request_id,\n -1, // request_data.render_frame_id,\n info.is_main_frame, {}, // fetch_window_id\n resource_type, info.common_params.transition,\n false, // is download\n false, // is stream\n IsNavigationDownloadAllowed(info.common_params.download_policy),\n info.common_params.has_user_gesture,\n true, // enable_load_timing\n false, // enable_upload_progress\n false, // do_not_prompt_for_login\n false, // keepalive\n info.common_params.referrer.policy, info.is_prerendering,\n resource_context, info.report_raw_headers,\n info.report_raw_headers,\n true, // is_async\n info.common_params.previews_state, info.common_params.post_data,\n false); // initiated_in_secure_context\n extra_info->SetBlobHandles(std::move(blob_handles));\n extra_info->set_navigation_ui_data(std::move(navigation_ui_data));\n\n extra_info->AssociateWithRequest(new_request.get());\n\n if (new_request->url().SchemeIs(url::kBlobScheme)) {\n storage::BlobProtocolHandler::SetRequestedBlobDataHandle(\n new_request.get(),\n blob_context->GetBlobDataFromPublicURL(new_request->url()));\n }\n\n network::mojom::RequestContextFrameType frame_type =\n info.is_main_frame ? network::mojom::RequestContextFrameType::kTopLevel\n : network::mojom::RequestContextFrameType::kNested;\n ServiceWorkerRequestHandler::InitializeForNavigation(\n new_request.get(), service_worker_handle_core, blob_context,\n info.begin_params->skip_service_worker, resource_type,\n info.begin_params->request_context_type, frame_type,\n info.are_ancestors_secure, info.common_params.post_data,\n extra_info->GetWebContentsGetterForRequest());\n\n if (appcache_handle_core) {\n AppCacheInterceptor::SetExtraRequestInfoForHost(\n new_request.get(), appcache_handle_core->host(), resource_type, false);\n }\n\n std::unique_ptr handler;\n handler = std::make_unique(\n new_request.get(), this, std::move(url_loader_request),\n std::move(url_loader_client), resource_type, url_loader_options);\n\n handler = AddStandardHandlers(\n new_request.get(), resource_type, resource_context,\n network::mojom::FetchRequestMode::kNoCors,\n info.begin_params->request_context_type, url_loader_options,\n appcache_handle_core ? appcache_handle_core->GetAppCacheService()\n : nullptr,\n -1, // child_id\n -1, // route_id\n std::move(handler));\n\n BeginRequestInternal(std::move(new_request), std::move(handler),\n false /* is_initiated_by_fetch_api */,\n std::move(throttling_token));\n}\n", + "line": null, + "label": 0, + "cwe": "CWE-284", + "cve": "CVE-2019-5822", + "length": 1403 + }, + { + "index": 35790, + "code": "int kvm_get_msr_common(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)\n{\n\tu64 data;\n\n\tswitch (msr) {\n\tcase MSR_IA32_PLATFORM_ID:\n\tcase MSR_IA32_EBL_CR_POWERON:\n\tcase MSR_IA32_DEBUGCTLMSR:\n\tcase MSR_IA32_LASTBRANCHFROMIP:\n\tcase MSR_IA32_LASTBRANCHTOIP:\n\tcase MSR_IA32_LASTINTFROMIP:\n\tcase MSR_IA32_LASTINTTOIP:\n\tcase MSR_K8_SYSCFG:\n\tcase MSR_K7_HWCR:\n\tcase MSR_VM_HSAVE_PA:\n\tcase MSR_K7_EVNTSEL0:\n\tcase MSR_K7_EVNTSEL1:\n\tcase MSR_K7_EVNTSEL2:\n\tcase MSR_K7_EVNTSEL3:\n\tcase MSR_K7_PERFCTR0:\n\tcase MSR_K7_PERFCTR1:\n\tcase MSR_K7_PERFCTR2:\n\tcase MSR_K7_PERFCTR3:\n\tcase MSR_K8_INT_PENDING_MSG:\n\tcase MSR_AMD64_NB_CFG:\n\tcase MSR_FAM10H_MMIO_CONF_BASE:\n\tcase MSR_AMD64_BU_CFG2:\n\t\tdata = 0;\n\t\tbreak;\n\tcase MSR_P6_PERFCTR0:\n\tcase MSR_P6_PERFCTR1:\n\tcase MSR_P6_EVNTSEL0:\n\tcase MSR_P6_EVNTSEL1:\n\t\tif (kvm_pmu_msr(vcpu, msr))\n\t\t\treturn kvm_pmu_get_msr(vcpu, msr, pdata);\n\t\tdata = 0;\n\t\tbreak;\n\tcase MSR_IA32_UCODE_REV:\n\t\tdata = 0x100000000ULL;\n\t\tbreak;\n\tcase MSR_MTRRcap:\n\t\tdata = 0x500 | KVM_NR_VAR_MTRR;\n\t\tbreak;\n\tcase 0x200 ... 0x2ff:\n\t\treturn get_msr_mtrr(vcpu, msr, pdata);\n\tcase 0xcd: /* fsb frequency */\n\t\tdata = 3;\n\t\tbreak;\n\t\t/*\n\t\t * MSR_EBC_FREQUENCY_ID\n\t\t * Conservative value valid for even the basic CPU models.\n\t\t * Models 0,1: 000 in bits 23:21 indicating a bus speed of\n\t\t * 100MHz, model 2 000 in bits 18:16 indicating 100MHz,\n\t\t * and 266MHz for model 3, or 4. Set Core Clock\n\t\t * Frequency to System Bus Frequency Ratio to 1 (bits\n\t\t * 31:24) even though these are only valid for CPU\n\t\t * models > 2, however guests may end up dividing or\n\t\t * multiplying by zero otherwise.\n\t\t */\n\tcase MSR_EBC_FREQUENCY_ID:\n\t\tdata = 1 << 24;\n\t\tbreak;\n\tcase MSR_IA32_APICBASE:\n\t\tdata = kvm_get_apic_base(vcpu);\n\t\tbreak;\n\tcase APIC_BASE_MSR ... APIC_BASE_MSR + 0x3ff:\n\t\treturn kvm_x2apic_msr_read(vcpu, msr, pdata);\n\t\tbreak;\n\tcase MSR_IA32_TSCDEADLINE:\n\t\tdata = kvm_get_lapic_tscdeadline_msr(vcpu);\n\t\tbreak;\n\tcase MSR_IA32_TSC_ADJUST:\n\t\tdata = (u64)vcpu->arch.ia32_tsc_adjust_msr;\n\t\tbreak;\n\tcase MSR_IA32_MISC_ENABLE:\n\t\tdata = vcpu->arch.ia32_misc_enable_msr;\n\t\tbreak;\n\tcase MSR_IA32_PERF_STATUS:\n\t\t/* TSC increment by tick */\n\t\tdata = 1000ULL;\n\t\t/* CPU multiplier */\n\t\tdata |= (((uint64_t)4ULL) << 40);\n\t\tbreak;\n\tcase MSR_EFER:\n\t\tdata = vcpu->arch.efer;\n\t\tbreak;\n\tcase MSR_KVM_WALL_CLOCK:\n\tcase MSR_KVM_WALL_CLOCK_NEW:\n\t\tdata = vcpu->kvm->arch.wall_clock;\n\t\tbreak;\n\tcase MSR_KVM_SYSTEM_TIME:\n\tcase MSR_KVM_SYSTEM_TIME_NEW:\n\t\tdata = vcpu->arch.time;\n\t\tbreak;\n\tcase MSR_KVM_ASYNC_PF_EN:\n\t\tdata = vcpu->arch.apf.msr_val;\n\t\tbreak;\n\tcase MSR_KVM_STEAL_TIME:\n\t\tdata = vcpu->arch.st.msr_val;\n\t\tbreak;\n\tcase MSR_KVM_PV_EOI_EN:\n\t\tdata = vcpu->arch.pv_eoi.msr_val;\n\t\tbreak;\n\tcase MSR_IA32_P5_MC_ADDR:\n\tcase MSR_IA32_P5_MC_TYPE:\n\tcase MSR_IA32_MCG_CAP:\n\tcase MSR_IA32_MCG_CTL:\n\tcase MSR_IA32_MCG_STATUS:\n\tcase MSR_IA32_MC0_CTL ... MSR_IA32_MC0_CTL + 4 * KVM_MAX_MCE_BANKS - 1:\n\t\treturn get_msr_mce(vcpu, msr, pdata);\n\tcase MSR_K7_CLK_CTL:\n\t\t/*\n\t\t * Provide expected ramp-up count for K7. All other\n\t\t * are set to zero, indicating minimum divisors for\n\t\t * every field.\n\t\t *\n\t\t * This prevents guest kernels on AMD host with CPU\n\t\t * type 6, model 8 and higher from exploding due to\n\t\t * the rdmsr failing.\n\t\t */\n\t\tdata = 0x20000000;\n\t\tbreak;\n\tcase HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:\n\t\tif (kvm_hv_msr_partition_wide(msr)) {\n\t\t\tint r;\n\t\t\tmutex_lock(&vcpu->kvm->lock);\n\t\t\tr = get_msr_hyperv_pw(vcpu, msr, pdata);\n\t\t\tmutex_unlock(&vcpu->kvm->lock);\n\t\t\treturn r;\n\t\t} else\n\t\t\treturn get_msr_hyperv(vcpu, msr, pdata);\n\t\tbreak;\n\tcase MSR_IA32_BBL_CR_CTL3:\n\t\t/* This legacy MSR exists but isn't fully documented in current\n\t\t * silicon. It is however accessed by winxp in very narrow\n\t\t * scenarios where it sets bit #19, itself documented as\n\t\t * a \"reserved\" bit. Best effort attempt to source coherent\n\t\t * read data here should the balance of the register be\n\t\t * interpreted by the guest:\n\t\t *\n\t\t * L2 cache control register 3: 64GB range, 256KB size,\n\t\t * enabled, latency 0x1, configured\n\t\t */\n\t\tdata = 0xbe702111;\n\t\tbreak;\n\tcase MSR_AMD64_OSVW_ID_LENGTH:\n\t\tif (!guest_cpuid_has_osvw(vcpu))\n\t\t\treturn 1;\n\t\tdata = vcpu->arch.osvw.length;\n\t\tbreak;\n\tcase MSR_AMD64_OSVW_STATUS:\n\t\tif (!guest_cpuid_has_osvw(vcpu))\n\t\t\treturn 1;\n\t\tdata = vcpu->arch.osvw.status;\n\t\tbreak;\n\tdefault:\n\t\tif (kvm_pmu_msr(vcpu, msr))\n\t\t\treturn kvm_pmu_get_msr(vcpu, msr, pdata);\n\t\tif (!ignore_msrs) {\n\t\t\tvcpu_unimpl(vcpu, \"unhandled rdmsr: 0x%x\\n\", msr);\n\t\t\treturn 1;\n\t\t} else {\n\t\t\tvcpu_unimpl(vcpu, \"ignored rdmsr: 0x%x\\n\", msr);\n\t\t\tdata = 0;\n\t\t}\n\t\tbreak;\n\t}\n\t*pdata = data;\n\treturn 0;\n}\n", + "line": null, + "label": 0, + "cwe": "CWE-362", + "cve": "CVE-2014-7842", + "length": 1549 + }, + { + "index": 71754, + "code": "ModuleExport size_t RegisterTIFFImage(void)\n{\n#define TIFFDescription \"Tagged Image File Format\"\n\n char\n version[MaxTextExtent];\n\n MagickInfo\n *entry;\n\n if (tiff_semaphore == (SemaphoreInfo *) NULL)\n ActivateSemaphoreInfo(&tiff_semaphore);\n LockSemaphoreInfo(tiff_semaphore);\n if (instantiate_key == MagickFalse)\n {\n if (MagickCreateThreadKey(&tiff_exception) == MagickFalse)\n ThrowFatalException(ResourceLimitFatalError,\"MemoryAllocationFailed\");\n#if defined(MAGICKCORE_HAVE_TIFFMERGEFIELDINFO) && defined(MAGICKCORE_HAVE_TIFFSETTAGEXTENDER)\n if (tag_extender == (TIFFExtendProc) NULL)\n tag_extender=TIFFSetTagExtender(TIFFTagExtender);\n#endif\n instantiate_key=MagickTrue;\n }\n UnlockSemaphoreInfo(tiff_semaphore);\n *version='\\0';\n#if defined(TIFF_VERSION)\n (void) FormatLocaleString(version,MaxTextExtent,\"%d\",TIFF_VERSION);\n#endif\n#if defined(MAGICKCORE_TIFF_DELEGATE)\n {\n const char\n *p;\n\n register ssize_t\n i;\n\n p=TIFFGetVersion();\n for (i=0; (i < (MaxTextExtent-1)) && (*p != 0) && (*p != '\\n'); i++)\n version[i]=(*p++);\n version[i]='\\0';\n }\n#endif\n\n entry=SetMagickInfo(\"GROUP4\");\n#if defined(MAGICKCORE_TIFF_DELEGATE)\n entry->decoder=(DecodeImageHandler *) ReadGROUP4Image;\n entry->encoder=(EncodeImageHandler *) WriteGROUP4Image;\n#endif\n entry->raw=MagickTrue;\n entry->endian_support=MagickTrue;\n entry->adjoin=MagickFalse;\n entry->format_type=ImplicitFormatType;\n entry->seekable_stream=MagickTrue;\n entry->description=ConstantString(\"Raw CCITT Group4\");\n entry->mime_type=ConstantString(\"image/tiff\");\n entry->module=ConstantString(\"TIFF\");\n (void) RegisterMagickInfo(entry);\n entry=SetMagickInfo(\"PTIF\");\n#if defined(MAGICKCORE_TIFF_DELEGATE)\n entry->decoder=(DecodeImageHandler *) ReadTIFFImage;\n entry->encoder=(EncodeImageHandler *) WritePTIFImage;\n#endif\n entry->endian_support=MagickTrue;\n entry->seekable_stream=MagickTrue;\n entry->description=ConstantString(\"Pyramid encoded TIFF\");\n entry->mime_type=ConstantString(\"image/tiff\");\n entry->module=ConstantString(\"TIFF\");\n (void) RegisterMagickInfo(entry);\n entry=SetMagickInfo(\"TIF\");\n#if defined(MAGICKCORE_TIFF_DELEGATE)\n entry->decoder=(DecodeImageHandler *) ReadTIFFImage;\n entry->encoder=(EncodeImageHandler *) WriteTIFFImage;\n#endif\n entry->endian_support=MagickTrue;\n entry->seekable_stream=MagickTrue;\n entry->stealth=MagickTrue;\n entry->description=ConstantString(TIFFDescription);\n if (*version != '\\0')\n entry->version=ConstantString(version);\n entry->mime_type=ConstantString(\"image/tiff\");\n entry->module=ConstantString(\"TIFF\");\n (void) RegisterMagickInfo(entry);\n entry=SetMagickInfo(\"TIFF\");\n#if defined(MAGICKCORE_TIFF_DELEGATE)\n entry->decoder=(DecodeImageHandler *) ReadTIFFImage;\n entry->encoder=(EncodeImageHandler *) WriteTIFFImage;\n#endif\n entry->magick=(IsImageFormatHandler *) IsTIFF;\n entry->endian_support=MagickTrue;\n entry->seekable_stream=MagickTrue;\n entry->description=ConstantString(TIFFDescription);\n if (*version != '\\0')\n entry->version=ConstantString(version);\n entry->mime_type=ConstantString(\"image/tiff\");\n entry->module=ConstantString(\"TIFF\");\n (void) RegisterMagickInfo(entry);\n entry=SetMagickInfo(\"TIFF64\");\n#if defined(TIFF_VERSION_BIG)\n entry->decoder=(DecodeImageHandler *) ReadTIFFImage;\n entry->encoder=(EncodeImageHandler *) WriteTIFFImage;\n#endif\n entry->adjoin=MagickFalse;\n entry->endian_support=MagickTrue;\n entry->seekable_stream=MagickTrue;\n entry->description=ConstantString(\"Tagged Image File Format (64-bit)\");\n if (*version != '\\0')\n entry->version=ConstantString(version);\n entry->mime_type=ConstantString(\"image/tiff\");\n entry->module=ConstantString(\"TIFF\");\n (void) RegisterMagickInfo(entry);\n return(MagickImageCoderSignature);\n}\n", + "line": null, + "label": 0, + "cwe": "CWE-119", + "cve": "CVE-2016-10066", + "length": 1046 + }, + { + "index": 122705, + "code": "bool Extension::LoadUserScriptHelper(const DictionaryValue* content_script,\n int definition_index,\n string16* error,\n UserScript* result) {\n if (content_script->HasKey(keys::kRunAt)) {\n std::string run_location;\n if (!content_script->GetString(keys::kRunAt, &run_location)) {\n *error = ErrorUtils::FormatErrorMessageUTF16(\n errors::kInvalidRunAt,\n base::IntToString(definition_index));\n return false;\n }\n\n if (run_location == values::kRunAtDocumentStart) {\n result->set_run_location(UserScript::DOCUMENT_START);\n } else if (run_location == values::kRunAtDocumentEnd) {\n result->set_run_location(UserScript::DOCUMENT_END);\n } else if (run_location == values::kRunAtDocumentIdle) {\n result->set_run_location(UserScript::DOCUMENT_IDLE);\n } else {\n *error = ErrorUtils::FormatErrorMessageUTF16(\n errors::kInvalidRunAt,\n base::IntToString(definition_index));\n return false;\n }\n }\n\n if (content_script->HasKey(keys::kAllFrames)) {\n bool all_frames = false;\n if (!content_script->GetBoolean(keys::kAllFrames, &all_frames)) {\n *error = ErrorUtils::FormatErrorMessageUTF16(\n errors::kInvalidAllFrames, base::IntToString(definition_index));\n return false;\n }\n result->set_match_all_frames(all_frames);\n }\n\n const ListValue* matches = NULL;\n if (!content_script->GetList(keys::kMatches, &matches)) {\n *error = ErrorUtils::FormatErrorMessageUTF16(\n errors::kInvalidMatches,\n base::IntToString(definition_index));\n return false;\n }\n\n if (matches->GetSize() == 0) {\n *error = ErrorUtils::FormatErrorMessageUTF16(\n errors::kInvalidMatchCount,\n base::IntToString(definition_index));\n return false;\n }\n for (size_t j = 0; j < matches->GetSize(); ++j) {\n std::string match_str;\n if (!matches->GetString(j, &match_str)) {\n *error = ErrorUtils::FormatErrorMessageUTF16(\n errors::kInvalidMatch,\n base::IntToString(definition_index),\n base::IntToString(j),\n errors::kExpectString);\n return false;\n }\n\n URLPattern pattern(UserScript::kValidUserScriptSchemes);\n if (CanExecuteScriptEverywhere())\n pattern.SetValidSchemes(URLPattern::SCHEME_ALL);\n\n URLPattern::ParseResult parse_result = pattern.Parse(match_str);\n if (parse_result != URLPattern::PARSE_SUCCESS) {\n *error = ErrorUtils::FormatErrorMessageUTF16(\n errors::kInvalidMatch,\n base::IntToString(definition_index),\n base::IntToString(j),\n URLPattern::GetParseResultString(parse_result));\n return false;\n }\n\n if (pattern.MatchesScheme(chrome::kFileScheme) &&\n !CanExecuteScriptEverywhere()) {\n wants_file_access_ = true;\n if (!(creation_flags_ & ALLOW_FILE_ACCESS)) {\n pattern.SetValidSchemes(\n pattern.valid_schemes() & ~URLPattern::SCHEME_FILE);\n }\n }\n\n result->add_url_pattern(pattern);\n }\n\n if (content_script->HasKey(keys::kExcludeMatches)) { // optional\n const ListValue* exclude_matches = NULL;\n if (!content_script->GetList(keys::kExcludeMatches, &exclude_matches)) {\n *error = ErrorUtils::FormatErrorMessageUTF16(\n errors::kInvalidExcludeMatches,\n base::IntToString(definition_index));\n return false;\n }\n\n for (size_t j = 0; j < exclude_matches->GetSize(); ++j) {\n std::string match_str;\n if (!exclude_matches->GetString(j, &match_str)) {\n *error = ErrorUtils::FormatErrorMessageUTF16(\n errors::kInvalidExcludeMatch,\n base::IntToString(definition_index),\n base::IntToString(j),\n errors::kExpectString);\n return false;\n }\n\n URLPattern pattern(UserScript::kValidUserScriptSchemes);\n if (CanExecuteScriptEverywhere())\n pattern.SetValidSchemes(URLPattern::SCHEME_ALL);\n URLPattern::ParseResult parse_result = pattern.Parse(match_str);\n if (parse_result != URLPattern::PARSE_SUCCESS) {\n *error = ErrorUtils::FormatErrorMessageUTF16(\n errors::kInvalidExcludeMatch,\n base::IntToString(definition_index), base::IntToString(j),\n URLPattern::GetParseResultString(parse_result));\n return false;\n }\n\n result->add_exclude_url_pattern(pattern);\n }\n }\n\n if (!LoadGlobsHelper(content_script, definition_index, keys::kIncludeGlobs,\n error, &UserScript::add_glob, result)) {\n return false;\n }\n\n if (!LoadGlobsHelper(content_script, definition_index, keys::kExcludeGlobs,\n error, &UserScript::add_exclude_glob, result)) {\n return false;\n }\n\n const ListValue* js = NULL;\n if (content_script->HasKey(keys::kJs) &&\n !content_script->GetList(keys::kJs, &js)) {\n *error = ErrorUtils::FormatErrorMessageUTF16(\n errors::kInvalidJsList,\n base::IntToString(definition_index));\n return false;\n }\n\n const ListValue* css = NULL;\n if (content_script->HasKey(keys::kCss) &&\n !content_script->GetList(keys::kCss, &css)) {\n *error = ErrorUtils::\n FormatErrorMessageUTF16(errors::kInvalidCssList,\n base::IntToString(definition_index));\n return false;\n }\n\n if (((js ? js->GetSize() : 0) + (css ? css->GetSize() : 0)) == 0) {\n *error = ErrorUtils::FormatErrorMessageUTF16(\n errors::kMissingFile,\n base::IntToString(definition_index));\n return false;\n }\n\n if (js) {\n for (size_t script_index = 0; script_index < js->GetSize();\n ++script_index) {\n const Value* value;\n std::string relative;\n if (!js->Get(script_index, &value) || !value->GetAsString(&relative)) {\n *error = ErrorUtils::FormatErrorMessageUTF16(\n errors::kInvalidJs,\n base::IntToString(definition_index),\n base::IntToString(script_index));\n return false;\n }\n GURL url = GetResourceURL(relative);\n ExtensionResource resource = GetResource(relative);\n result->js_scripts().push_back(UserScript::File(\n resource.extension_root(), resource.relative_path(), url));\n }\n }\n\n if (css) {\n for (size_t script_index = 0; script_index < css->GetSize();\n ++script_index) {\n const Value* value;\n std::string relative;\n if (!css->Get(script_index, &value) || !value->GetAsString(&relative)) {\n *error = ErrorUtils::FormatErrorMessageUTF16(\n errors::kInvalidCss,\n base::IntToString(definition_index),\n base::IntToString(script_index));\n return false;\n }\n GURL url = GetResourceURL(relative);\n ExtensionResource resource = GetResource(relative);\n result->css_scripts().push_back(UserScript::File(\n resource.extension_root(), resource.relative_path(), url));\n }\n }\n\n return true;\n}\n", + "line": null, + "label": 0, + "cwe": "CWE-264", + "cve": "CVE-2013-0885", + "length": 1607 + }, + { + "index": 15475, + "code": "digest_authentication_encode (const char *au, const char *user,\n const char *passwd, const char *method,\n const char *path, uerr_t *auth_err)\n{\n static char *realm, *opaque, *nonce, *qop, *algorithm;\n static struct {\n const char *name;\n char **variable;\n } options[] = {\n { \"realm\", &realm },\n { \"opaque\", &opaque },\n { \"nonce\", &nonce },\n { \"qop\", &qop },\n { \"algorithm\", &algorithm }\n };\n char cnonce[16] = \"\";\n char *res = NULL;\n int res_len;\n size_t res_size;\n param_token name, value;\n\n\n realm = opaque = nonce = algorithm = qop = NULL;\n\n au += 6; /* skip over `Digest' */\n while (extract_param (&au, &name, &value, ',', NULL))\n {\n size_t i;\n size_t namelen = name.e - name.b;\n for (i = 0; i < countof (options); i++)\n if (namelen == strlen (options[i].name)\n && 0 == strncmp (name.b, options[i].name,\n namelen))\n {\n *options[i].variable = strdupdelim (value.b, value.e);\n break;\n }\n }\n\n if (qop && strcmp (qop, \"auth\"))\n {\n logprintf (LOG_NOTQUIET, _(\"Unsupported quality of protection '%s'.\\n\"), qop);\n xfree (qop); /* force freeing mem and continue */\n }\n else if (algorithm && strcmp (algorithm,\"MD5\") && strcmp (algorithm,\"MD5-sess\"))\n {\n logprintf (LOG_NOTQUIET, _(\"Unsupported algorithm '%s'.\\n\"), algorithm);\n xfree (algorithm); /* force freeing mem and continue */\n }\n\n if (!realm || !nonce || !user || !passwd || !path || !method)\n {\n *auth_err = ATTRMISSING;\n goto cleanup;\n }\n\n /* Calculate the digest value. */\n {\n struct md5_ctx ctx;\n unsigned char hash[MD5_DIGEST_SIZE];\n char a1buf[MD5_DIGEST_SIZE * 2 + 1], a2buf[MD5_DIGEST_SIZE * 2 + 1];\n char response_digest[MD5_DIGEST_SIZE * 2 + 1];\n\n /* A1BUF = H(user \":\" realm \":\" password) */\n md5_init_ctx (&ctx);\n md5_process_bytes ((unsigned char *)user, strlen (user), &ctx);\n md5_process_bytes ((unsigned char *)\":\", 1, &ctx);\n md5_process_bytes ((unsigned char *)realm, strlen (realm), &ctx);\n md5_process_bytes ((unsigned char *)\":\", 1, &ctx);\n md5_process_bytes ((unsigned char *)passwd, strlen (passwd), &ctx);\n md5_finish_ctx (&ctx, hash);\n\n dump_hash (a1buf, hash);\n\n if (algorithm && !strcmp (algorithm, \"MD5-sess\"))\n {\n /* A1BUF = H( H(user \":\" realm \":\" password) \":\" nonce \":\" cnonce ) */\n snprintf (cnonce, sizeof (cnonce), \"%08x\",\n (unsigned) random_number (INT_MAX));\n\n md5_init_ctx (&ctx);\n /* md5_process_bytes (hash, MD5_DIGEST_SIZE, &ctx); */\n md5_process_bytes (a1buf, MD5_DIGEST_SIZE * 2, &ctx);\n md5_process_bytes ((unsigned char *)\":\", 1, &ctx);\n md5_process_bytes ((unsigned char *)nonce, strlen (nonce), &ctx);\n md5_process_bytes ((unsigned char *)\":\", 1, &ctx);\n md5_process_bytes ((unsigned char *)cnonce, strlen (cnonce), &ctx);\n md5_finish_ctx (&ctx, hash);\n\n dump_hash (a1buf, hash);\n }\n\n /* A2BUF = H(method \":\" path) */\n md5_init_ctx (&ctx);\n md5_process_bytes ((unsigned char *)method, strlen (method), &ctx);\n md5_process_bytes ((unsigned char *)\":\", 1, &ctx);\n md5_process_bytes ((unsigned char *)path, strlen (path), &ctx);\n md5_finish_ctx (&ctx, hash);\n dump_hash (a2buf, hash);\n\n if (qop && !strcmp (qop, \"auth\"))\n {\n /* RFC 2617 Digest Access Authentication */\n /* generate random hex string */\n if (!*cnonce)\n snprintf (cnonce, sizeof (cnonce), \"%08x\",\n (unsigned) random_number (INT_MAX));\n\n /* RESPONSE_DIGEST = H(A1BUF \":\" nonce \":\" noncecount \":\" clientnonce \":\" qop \": \" A2BUF) */\n md5_init_ctx (&ctx);\n md5_process_bytes ((unsigned char *)a1buf, MD5_DIGEST_SIZE * 2, &ctx);\n md5_process_bytes ((unsigned char *)\":\", 1, &ctx);\n md5_process_bytes ((unsigned char *)nonce, strlen (nonce), &ctx);\n md5_process_bytes ((unsigned char *)\":\", 1, &ctx);\n md5_process_bytes ((unsigned char *)\"00000001\", 8, &ctx); /* TODO: keep track of server nonce values */\n md5_process_bytes ((unsigned char *)\":\", 1, &ctx);\n md5_process_bytes ((unsigned char *)cnonce, strlen (cnonce), &ctx);\n md5_process_bytes ((unsigned char *)\":\", 1, &ctx);\n md5_process_bytes ((unsigned char *)qop, strlen (qop), &ctx);\n md5_process_bytes ((unsigned char *)\":\", 1, &ctx);\n md5_process_bytes ((unsigned char *)a2buf, MD5_DIGEST_SIZE * 2, &ctx);\n md5_finish_ctx (&ctx, hash);\n }\n else\n {\n /* RFC 2069 Digest Access Authentication */\n /* RESPONSE_DIGEST = H(A1BUF \":\" nonce \":\" A2BUF) */\n md5_init_ctx (&ctx);\n md5_process_bytes ((unsigned char *)a1buf, MD5_DIGEST_SIZE * 2, &ctx);\n md5_process_bytes ((unsigned char *)\":\", 1, &ctx);\n md5_process_bytes ((unsigned char *)nonce, strlen (nonce), &ctx);\n md5_process_bytes ((unsigned char *)\":\", 1, &ctx);\n md5_process_bytes ((unsigned char *)a2buf, MD5_DIGEST_SIZE * 2, &ctx);\n md5_finish_ctx (&ctx, hash);\n }\n\n dump_hash (response_digest, hash);\n\n res_size = strlen (user)\n + strlen (realm)\n + strlen (nonce)\n + strlen (path)\n + 2 * MD5_DIGEST_SIZE /*strlen (response_digest)*/\n + (opaque ? strlen (opaque) : 0)\n + (algorithm ? strlen (algorithm) : 0)\n + (qop ? 128: 0)\n + strlen (cnonce)\n + 128;\n\n res = xmalloc (res_size);\n\n if (qop && !strcmp (qop, \"auth\"))\n {\n res_len = snprintf (res, res_size, \"Digest \"\\\n \"username=\\\"%s\\\", realm=\\\"%s\\\", nonce=\\\"%s\\\", uri=\\\"%s\\\", response=\\\"%s\\\"\"\\\n \", qop=auth, nc=00000001, cnonce=\\\"%s\\\"\",\n user, realm, nonce, path, response_digest, cnonce);\n\n }\n else\n {\n res_len = snprintf (res, res_size, \"Digest \"\\\n \"username=\\\"%s\\\", realm=\\\"%s\\\", nonce=\\\"%s\\\", uri=\\\"%s\\\", response=\\\"%s\\\"\",\n user, realm, nonce, path, response_digest);\n }\n\n if (opaque)\n {\n res_len += snprintf (res + res_len, res_size - res_len, \", opaque=\\\"%s\\\"\", opaque);\n }\n\n if (algorithm)\n {\n snprintf (res + res_len, res_size - res_len, \", algorithm=\\\"%s\\\"\", algorithm);\n }\n }\n\ncleanup:\n xfree (realm);\n xfree (opaque);\n xfree (nonce);\n xfree (qop);\n xfree (algorithm);\n\n return res;\n}\n", + "line": null, + "label": 0, + "cwe": "CWE-20", + "cve": "CVE-2018-0494", + "length": 1795 + }, + { + "index": 97046, + "code": "int ip6_forward(struct sk_buff *skb)\n{\n\tstruct dst_entry *dst = skb_dst(skb);\n\tstruct ipv6hdr *hdr = ipv6_hdr(skb);\n\tstruct inet6_skb_parm *opt = IP6CB(skb);\n\tstruct net *net = dev_net(dst->dev);\n\tu32 mtu;\n\n\tif (net->ipv6.devconf_all->forwarding == 0)\n\t\tgoto error;\n\n\tif (skb->pkt_type != PACKET_HOST)\n\t\tgoto drop;\n\n\tif (unlikely(skb->sk))\n\t\tgoto drop;\n\n\tif (skb_warn_if_lro(skb))\n\t\tgoto drop;\n\n\tif (!xfrm6_policy_check(NULL, XFRM_POLICY_FWD, skb)) {\n\t\tIP6_INC_STATS_BH(net, ip6_dst_idev(dst),\n\t\t\t\t IPSTATS_MIB_INDISCARDS);\n\t\tgoto drop;\n\t}\n\n\tskb_forward_csum(skb);\n\n\t/*\n\t *\tWe DO NOT make any processing on\n\t *\tRA packets, pushing them to user level AS IS\n\t *\twithout ane WARRANTY that application will be able\n\t *\tto interpret them. The reason is that we\n\t *\tcannot make anything clever here.\n\t *\n\t *\tWe are not end-node, so that if packet contains\n\t *\tAH/ESP, we cannot make anything.\n\t *\tDefragmentation also would be mistake, RA packets\n\t *\tcannot be fragmented, because there is no warranty\n\t *\tthat different fragments will go along one path. --ANK\n\t */\n\tif (unlikely(opt->flags & IP6SKB_ROUTERALERT)) {\n\t\tif (ip6_call_ra_chain(skb, ntohs(opt->ra)))\n\t\t\treturn 0;\n\t}\n\n\t/*\n\t *\tcheck and decrement ttl\n\t */\n\tif (hdr->hop_limit <= 1) {\n\t\t/* Force OUTPUT device used as source address */\n\t\tskb->dev = dst->dev;\n\t\ticmpv6_send(skb, ICMPV6_TIME_EXCEED, ICMPV6_EXC_HOPLIMIT, 0);\n\t\tIP6_INC_STATS_BH(net, ip6_dst_idev(dst),\n\t\t\t\t IPSTATS_MIB_INHDRERRORS);\n\n\t\tkfree_skb(skb);\n\t\treturn -ETIMEDOUT;\n\t}\n\n\t/* XXX: idev->cnf.proxy_ndp? */\n\tif (net->ipv6.devconf_all->proxy_ndp &&\n\t pneigh_lookup(&nd_tbl, net, &hdr->daddr, skb->dev, 0)) {\n\t\tint proxied = ip6_forward_proxy_check(skb);\n\t\tif (proxied > 0)\n\t\t\treturn ip6_input(skb);\n\t\telse if (proxied < 0) {\n\t\t\tIP6_INC_STATS_BH(net, ip6_dst_idev(dst),\n\t\t\t\t\t IPSTATS_MIB_INDISCARDS);\n\t\t\tgoto drop;\n\t\t}\n\t}\n\n\tif (!xfrm6_route_forward(skb)) {\n\t\tIP6_INC_STATS_BH(net, ip6_dst_idev(dst),\n\t\t\t\t IPSTATS_MIB_INDISCARDS);\n\t\tgoto drop;\n\t}\n\tdst = skb_dst(skb);\n\n\t/* IPv6 specs say nothing about it, but it is clear that we cannot\n\t send redirects to source routed frames.\n\t We don't send redirects to frames decapsulated from IPsec.\n\t */\n\tif (skb->dev == dst->dev && opt->srcrt == 0 && !skb_sec_path(skb)) {\n\t\tstruct in6_addr *target = NULL;\n\t\tstruct inet_peer *peer;\n\t\tstruct rt6_info *rt;\n\n\t\t/*\n\t\t *\tincoming and outgoing devices are the same\n\t\t *\tsend a redirect.\n\t\t */\n\n\t\trt = (struct rt6_info *) dst;\n\t\tif (rt->rt6i_flags & RTF_GATEWAY)\n\t\t\ttarget = &rt->rt6i_gateway;\n\t\telse\n\t\t\ttarget = &hdr->daddr;\n\n\t\tpeer = inet_getpeer_v6(net->ipv6.peers, &rt->rt6i_dst.addr, 1);\n\n\t\t/* Limit redirects both by destination (here)\n\t\t and by source (inside ndisc_send_redirect)\n\t\t */\n\t\tif (inet_peer_xrlim_allow(peer, 1*HZ))\n\t\t\tndisc_send_redirect(skb, target);\n\t\tif (peer)\n\t\t\tinet_putpeer(peer);\n\t} else {\n\t\tint addrtype = ipv6_addr_type(&hdr->saddr);\n\n\t\t/* This check is security critical. */\n\t\tif (addrtype == IPV6_ADDR_ANY ||\n\t\t addrtype & (IPV6_ADDR_MULTICAST | IPV6_ADDR_LOOPBACK))\n\t\t\tgoto error;\n\t\tif (addrtype & IPV6_ADDR_LINKLOCAL) {\n\t\t\ticmpv6_send(skb, ICMPV6_DEST_UNREACH,\n\t\t\t\t ICMPV6_NOT_NEIGHBOUR, 0);\n\t\t\tgoto error;\n\t\t}\n\t}\n\n\tmtu = ip6_dst_mtu_forward(dst);\n\tif (mtu < IPV6_MIN_MTU)\n\t\tmtu = IPV6_MIN_MTU;\n\n\tif (ip6_pkt_too_big(skb, mtu)) {\n\t\t/* Again, force OUTPUT device used as source address */\n\t\tskb->dev = dst->dev;\n\t\ticmpv6_send(skb, ICMPV6_PKT_TOOBIG, 0, mtu);\n\t\tIP6_INC_STATS_BH(net, ip6_dst_idev(dst),\n\t\t\t\t IPSTATS_MIB_INTOOBIGERRORS);\n\t\tIP6_INC_STATS_BH(net, ip6_dst_idev(dst),\n\t\t\t\t IPSTATS_MIB_FRAGFAILS);\n\t\tkfree_skb(skb);\n\t\treturn -EMSGSIZE;\n\t}\n\n\tif (skb_cow(skb, dst->dev->hard_header_len)) {\n\t\tIP6_INC_STATS_BH(net, ip6_dst_idev(dst),\n\t\t\t\t IPSTATS_MIB_OUTDISCARDS);\n\t\tgoto drop;\n\t}\n\n\thdr = ipv6_hdr(skb);\n\n\t/* Mangling hops number delayed to point after skb COW */\n\n\thdr->hop_limit--;\n\n\tIP6_INC_STATS_BH(net, ip6_dst_idev(dst), IPSTATS_MIB_OUTFORWDATAGRAMS);\n\tIP6_ADD_STATS_BH(net, ip6_dst_idev(dst), IPSTATS_MIB_OUTOCTETS, skb->len);\n\treturn NF_HOOK(NFPROTO_IPV6, NF_INET_FORWARD, skb, skb->dev, dst->dev,\n\t\t ip6_forward_finish);\n\nerror:\n\tIP6_INC_STATS_BH(net, ip6_dst_idev(dst), IPSTATS_MIB_INADDRERRORS);\ndrop:\n\tkfree_skb(skb);\n\treturn -EINVAL;\n}\n", + "line": null, + "label": 0, + "cwe": "CWE-200", + "cve": "CVE-2019-10638", + "length": 1389 + }, + { + "index": 63500, + "code": "static MagickBooleanType WriteOneJNGImage(MngInfo *mng_info,\n const ImageInfo *image_info,Image *image,ExceptionInfo *exception)\n{\n Image\n *jpeg_image;\n\n ImageInfo\n *jpeg_image_info;\n\n MagickBooleanType\n logging,\n status;\n\n size_t\n length;\n\n unsigned char\n *blob,\n chunk[80],\n *p;\n\n unsigned int\n jng_alpha_compression_method,\n jng_alpha_sample_depth,\n jng_color_type,\n transparent;\n\n size_t\n jng_alpha_quality,\n jng_quality;\n\n logging=LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Enter WriteOneJNGImage()\");\n\n blob=(unsigned char *) NULL;\n jpeg_image=(Image *) NULL;\n jpeg_image_info=(ImageInfo *) NULL;\n length=0;\n\n status=MagickTrue;\n transparent=image_info->type==GrayscaleAlphaType ||\n image_info->type==TrueColorAlphaType ||\n image->alpha_trait != UndefinedPixelTrait;\n\n jng_alpha_sample_depth = 0;\n\n jng_quality=image_info->quality == 0UL ? 75UL : image_info->quality%1000;\n\n jng_alpha_compression_method=image->compression==JPEGCompression? 8 : 0;\n\n jng_alpha_quality=image_info->quality == 0UL ? 75UL :\n image_info->quality;\n\n if (jng_alpha_quality >= 1000)\n jng_alpha_quality /= 1000;\n\n length=0;\n\n if (transparent != 0)\n {\n jng_color_type=14;\n\n /* Create JPEG blob, image, and image_info */\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Creating jpeg_image_info for alpha.\");\n\n jpeg_image_info=(ImageInfo *) CloneImageInfo(image_info);\n\n if (jpeg_image_info == (ImageInfo *) NULL)\n ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\");\n\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Creating jpeg_image.\");\n\n jpeg_image=SeparateImage(image,AlphaChannel,exception);\n if (jpeg_image == (Image *) NULL)\n ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\");\n (void) CopyMagickString(jpeg_image->magick,\"JPEG\",MagickPathExtent);\n jpeg_image->alpha_trait=UndefinedPixelTrait;\n jpeg_image->quality=jng_alpha_quality;\n jpeg_image_info->type=GrayscaleType;\n (void) SetImageType(jpeg_image,GrayscaleType,exception);\n (void) AcquireUniqueFilename(jpeg_image->filename);\n (void) FormatLocaleString(jpeg_image_info->filename,MagickPathExtent,\n \"%s\",jpeg_image->filename);\n }\n else\n {\n jng_alpha_compression_method=0;\n jng_color_type=10;\n jng_alpha_sample_depth=0;\n }\n\n /* To do: check bit depth of PNG alpha channel */\n\n /* Check if image is grayscale. */\n if (image_info->type != TrueColorAlphaType && image_info->type !=\n TrueColorType && SetImageGray(image,exception))\n jng_color_type-=2;\n\n if (logging != MagickFalse)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" JNG Quality = %d\",(int) jng_quality);\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" JNG Color Type = %d\",jng_color_type);\n if (transparent != 0)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" JNG Alpha Compression = %d\",jng_alpha_compression_method);\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" JNG Alpha Depth = %d\",jng_alpha_sample_depth);\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" JNG Alpha Quality = %d\",(int) jng_alpha_quality);\n }\n }\n\n if (transparent != 0)\n {\n if (jng_alpha_compression_method==0)\n {\n const char\n *value;\n\n /* Encode alpha as a grayscale PNG blob */\n status=OpenBlob(jpeg_image_info,jpeg_image,WriteBinaryBlobMode,\n exception);\n if (status == MagickFalse)\n ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\");\n\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Creating PNG blob.\");\n\n (void) CopyMagickString(jpeg_image_info->magick,\"PNG\",\n MagickPathExtent);\n (void) CopyMagickString(jpeg_image->magick,\"PNG\",MagickPathExtent);\n jpeg_image_info->interlace=NoInterlace;\n\n /* Exclude all ancillary chunks */\n (void) SetImageArtifact(jpeg_image,\"png:exclude-chunks\",\"all\");\n\n blob=(unsigned char *) ImageToBlob(jpeg_image_info,jpeg_image,\n &length,exception);\n\n /* Retrieve sample depth used */\n value=GetImageProperty(jpeg_image,\"png:bit-depth-written\",exception);\n if (value != (char *) NULL)\n jng_alpha_sample_depth= (unsigned int) value[0];\n }\n else\n {\n /* Encode alpha as a grayscale JPEG blob */\n\n status=OpenBlob(jpeg_image_info,jpeg_image,WriteBinaryBlobMode,\n exception);\n if (status == MagickFalse)\n ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\");\n\n (void) CopyMagickString(jpeg_image_info->magick,\"JPEG\",\n MagickPathExtent);\n (void) CopyMagickString(jpeg_image->magick,\"JPEG\",MagickPathExtent);\n jpeg_image_info->interlace=NoInterlace;\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Creating blob.\");\n blob=(unsigned char *) ImageToBlob(jpeg_image_info,\n jpeg_image,&length,\n exception);\n jng_alpha_sample_depth=8;\n\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Successfully read jpeg_image into a blob, length=%.20g.\",\n (double) length);\n\n }\n /* Destroy JPEG image and image_info */\n jpeg_image=DestroyImage(jpeg_image);\n (void) RelinquishUniqueFileResource(jpeg_image_info->filename);\n jpeg_image_info=DestroyImageInfo(jpeg_image_info);\n }\n\n /* Write JHDR chunk */\n (void) WriteBlobMSBULong(image,16L); /* chunk data length=16 */\n PNGType(chunk,mng_JHDR);\n LogPNGChunk(logging,mng_JHDR,16L);\n PNGLong(chunk+4,(png_uint_32) image->columns);\n PNGLong(chunk+8,(png_uint_32) image->rows);\n chunk[12]=jng_color_type;\n chunk[13]=8; /* sample depth */\n chunk[14]=8; /*jng_image_compression_method */\n chunk[15]=(unsigned char) (image_info->interlace == NoInterlace ? 0 : 8);\n chunk[16]=jng_alpha_sample_depth;\n chunk[17]=jng_alpha_compression_method;\n chunk[18]=0; /*jng_alpha_filter_method */\n chunk[19]=0; /*jng_alpha_interlace_method */\n (void) WriteBlob(image,20,chunk);\n (void) WriteBlobMSBULong(image,crc32(0,chunk,20));\n if (logging != MagickFalse)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" JNG width:%15lu\",(unsigned long) image->columns);\n\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" JNG height:%14lu\",(unsigned long) image->rows);\n\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" JNG color type:%10d\",jng_color_type);\n\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" JNG sample depth:%8d\",8);\n\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" JNG compression:%9d\",8);\n\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" JNG interlace:%11d\",0);\n\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" JNG alpha depth:%9d\",jng_alpha_sample_depth);\n\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" JNG alpha compression:%3d\",jng_alpha_compression_method);\n\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" JNG alpha filter:%8d\",0);\n\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" JNG alpha interlace:%5d\",0);\n }\n\n /* Write any JNG-chunk-b profiles */\n (void) Magick_png_write_chunk_from_profile(image,\"JNG-chunk-b\",logging);\n\n /*\n Write leading ancillary chunks\n */\n\n if (transparent != 0)\n {\n /*\n Write JNG bKGD chunk\n */\n\n unsigned char\n blue,\n green,\n red;\n\n ssize_t\n num_bytes;\n\n if (jng_color_type == 8 || jng_color_type == 12)\n num_bytes=6L;\n else\n num_bytes=10L;\n (void) WriteBlobMSBULong(image,(size_t) (num_bytes-4L));\n PNGType(chunk,mng_bKGD);\n LogPNGChunk(logging,mng_bKGD,(size_t) (num_bytes-4L));\n red=ScaleQuantumToChar(image->background_color.red);\n green=ScaleQuantumToChar(image->background_color.green);\n blue=ScaleQuantumToChar(image->background_color.blue);\n *(chunk+4)=0;\n *(chunk+5)=red;\n *(chunk+6)=0;\n *(chunk+7)=green;\n *(chunk+8)=0;\n *(chunk+9)=blue;\n (void) WriteBlob(image,(size_t) num_bytes,chunk);\n (void) WriteBlobMSBULong(image,crc32(0,chunk,(uInt) num_bytes));\n }\n\n if ((image->colorspace == sRGBColorspace || image->rendering_intent))\n {\n /*\n Write JNG sRGB chunk\n */\n (void) WriteBlobMSBULong(image,1L);\n PNGType(chunk,mng_sRGB);\n LogPNGChunk(logging,mng_sRGB,1L);\n\n if (image->rendering_intent != UndefinedIntent)\n chunk[4]=(unsigned char)\n Magick_RenderingIntent_to_PNG_RenderingIntent(\n (image->rendering_intent));\n\n else\n chunk[4]=(unsigned char)\n Magick_RenderingIntent_to_PNG_RenderingIntent(\n (PerceptualIntent));\n\n (void) WriteBlob(image,5,chunk);\n (void) WriteBlobMSBULong(image,crc32(0,chunk,5));\n }\n else\n {\n if (image->gamma != 0.0)\n {\n /*\n Write JNG gAMA chunk\n */\n (void) WriteBlobMSBULong(image,4L);\n PNGType(chunk,mng_gAMA);\n LogPNGChunk(logging,mng_gAMA,4L);\n PNGLong(chunk+4,(png_uint_32) (100000*image->gamma+0.5));\n (void) WriteBlob(image,8,chunk);\n (void) WriteBlobMSBULong(image,crc32(0,chunk,8));\n }\n\n if ((mng_info->equal_chrms == MagickFalse) &&\n (image->chromaticity.red_primary.x != 0.0))\n {\n PrimaryInfo\n primary;\n\n /*\n Write JNG cHRM chunk\n */\n (void) WriteBlobMSBULong(image,32L);\n PNGType(chunk,mng_cHRM);\n LogPNGChunk(logging,mng_cHRM,32L);\n primary=image->chromaticity.white_point;\n PNGLong(chunk+4,(png_uint_32) (100000*primary.x+0.5));\n PNGLong(chunk+8,(png_uint_32) (100000*primary.y+0.5));\n primary=image->chromaticity.red_primary;\n PNGLong(chunk+12,(png_uint_32) (100000*primary.x+0.5));\n PNGLong(chunk+16,(png_uint_32) (100000*primary.y+0.5));\n primary=image->chromaticity.green_primary;\n PNGLong(chunk+20,(png_uint_32) (100000*primary.x+0.5));\n PNGLong(chunk+24,(png_uint_32) (100000*primary.y+0.5));\n primary=image->chromaticity.blue_primary;\n PNGLong(chunk+28,(png_uint_32) (100000*primary.x+0.5));\n PNGLong(chunk+32,(png_uint_32) (100000*primary.y+0.5));\n (void) WriteBlob(image,36,chunk);\n (void) WriteBlobMSBULong(image,crc32(0,chunk,36));\n }\n }\n\n if (image->resolution.x && image->resolution.y && !mng_info->equal_physs)\n {\n /*\n Write JNG pHYs chunk\n */\n (void) WriteBlobMSBULong(image,9L);\n PNGType(chunk,mng_pHYs);\n LogPNGChunk(logging,mng_pHYs,9L);\n if (image->units == PixelsPerInchResolution)\n {\n PNGLong(chunk+4,(png_uint_32)\n (image->resolution.x*100.0/2.54+0.5));\n\n PNGLong(chunk+8,(png_uint_32)\n (image->resolution.y*100.0/2.54+0.5));\n\n chunk[12]=1;\n }\n\n else\n {\n if (image->units == PixelsPerCentimeterResolution)\n {\n PNGLong(chunk+4,(png_uint_32)\n (image->resolution.x*100.0+0.5));\n\n PNGLong(chunk+8,(png_uint_32)\n (image->resolution.y*100.0+0.5));\n\n chunk[12]=1;\n }\n\n else\n {\n PNGLong(chunk+4,(png_uint_32) (image->resolution.x+0.5));\n PNGLong(chunk+8,(png_uint_32) (image->resolution.y+0.5));\n chunk[12]=0;\n }\n }\n (void) WriteBlob(image,13,chunk);\n (void) WriteBlobMSBULong(image,crc32(0,chunk,13));\n }\n\n if (mng_info->write_mng == 0 && (image->page.x || image->page.y))\n {\n /*\n Write JNG oFFs chunk\n */\n (void) WriteBlobMSBULong(image,9L);\n PNGType(chunk,mng_oFFs);\n LogPNGChunk(logging,mng_oFFs,9L);\n PNGsLong(chunk+4,(ssize_t) (image->page.x));\n PNGsLong(chunk+8,(ssize_t) (image->page.y));\n chunk[12]=0;\n (void) WriteBlob(image,13,chunk);\n (void) WriteBlobMSBULong(image,crc32(0,chunk,13));\n }\n if (mng_info->write_mng == 0 && (image->page.width || image->page.height))\n {\n (void) WriteBlobMSBULong(image,9L); /* data length=8 */\n PNGType(chunk,mng_vpAg);\n LogPNGChunk(logging,mng_vpAg,9L);\n PNGLong(chunk+4,(png_uint_32) image->page.width);\n PNGLong(chunk+8,(png_uint_32) image->page.height);\n chunk[12]=0; /* unit = pixels */\n (void) WriteBlob(image,13,chunk);\n (void) WriteBlobMSBULong(image,crc32(0,chunk,13));\n }\n\n if (transparent != 0)\n {\n if (jng_alpha_compression_method==0)\n {\n register ssize_t\n i;\n\n size_t\n len;\n\n /* Write IDAT chunk header */\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Write IDAT chunks from blob, length=%.20g.\",(double)\n length);\n\n /* Copy IDAT chunks */\n len=0;\n p=blob+8;\n for (i=8; i<(ssize_t) length; i+=len+12)\n {\n len=(size_t) (*p) << 24;\n len|=(size_t) (*(p+1)) << 16;\n len|=(size_t) (*(p+2)) << 8;\n len|=(size_t) (*(p+3));\n p+=4;\n\n if (*(p)==73 && *(p+1)==68 && *(p+2)==65 && *(p+3)==84) /* IDAT */\n {\n /* Found an IDAT chunk. */\n (void) WriteBlobMSBULong(image,len);\n LogPNGChunk(logging,mng_IDAT,len);\n (void) WriteBlob(image,len+4,p);\n (void) WriteBlobMSBULong(image, crc32(0,p,(uInt) len+4));\n }\n\n else\n {\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Skipping %c%c%c%c chunk, length=%.20g.\",\n *(p),*(p+1),*(p+2),*(p+3),(double) len);\n }\n p+=(8+len);\n }\n }\n else if (length != 0)\n {\n /* Write JDAA chunk header */\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Write JDAA chunk, length=%.20g.\",(double) length);\n (void) WriteBlobMSBULong(image,(size_t) length);\n PNGType(chunk,mng_JDAA);\n LogPNGChunk(logging,mng_JDAA,length);\n /* Write JDAT chunk(s) data */\n (void) WriteBlob(image,4,chunk);\n (void) WriteBlob(image,length,blob);\n (void) WriteBlobMSBULong(image,crc32(crc32(0,chunk,4),blob,\n (uInt) length));\n }\n blob=(unsigned char *) RelinquishMagickMemory(blob);\n }\n\n /* Encode image as a JPEG blob */\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Creating jpeg_image_info.\");\n jpeg_image_info=(ImageInfo *) CloneImageInfo(image_info);\n if (jpeg_image_info == (ImageInfo *) NULL)\n ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\");\n\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Creating jpeg_image.\");\n\n jpeg_image=CloneImage(image,0,0,MagickTrue,exception);\n if (jpeg_image == (Image *) NULL)\n ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\");\n (void) CopyMagickString(jpeg_image->magick,\"JPEG\",MagickPathExtent);\n\n (void) AcquireUniqueFilename(jpeg_image->filename);\n (void) FormatLocaleString(jpeg_image_info->filename,MagickPathExtent,\"%s\",\n jpeg_image->filename);\n\n status=OpenBlob(jpeg_image_info,jpeg_image,WriteBinaryBlobMode,\n exception);\n\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Created jpeg_image, %.20g x %.20g.\",(double) jpeg_image->columns,\n (double) jpeg_image->rows);\n\n if (status == MagickFalse)\n ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\");\n\n if (jng_color_type == 8 || jng_color_type == 12)\n jpeg_image_info->type=GrayscaleType;\n\n jpeg_image_info->quality=jng_quality;\n jpeg_image->quality=jng_quality;\n (void) CopyMagickString(jpeg_image_info->magick,\"JPEG\",MagickPathExtent);\n (void) CopyMagickString(jpeg_image->magick,\"JPEG\",MagickPathExtent);\n\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Creating blob.\");\n\n blob=(unsigned char *) ImageToBlob(jpeg_image_info,jpeg_image,&length,\n exception);\n\n if (logging != MagickFalse)\n {\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Successfully read jpeg_image into a blob, length=%.20g.\",\n (double) length);\n\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Write JDAT chunk, length=%.20g.\",(double) length);\n }\n\n /* Write JDAT chunk(s) */\n (void) WriteBlobMSBULong(image,(size_t) length);\n PNGType(chunk,mng_JDAT);\n LogPNGChunk(logging,mng_JDAT,length);\n (void) WriteBlob(image,4,chunk);\n (void) WriteBlob(image,length,blob);\n (void) WriteBlobMSBULong(image,crc32(crc32(0,chunk,4),blob,(uInt) length));\n\n jpeg_image=DestroyImage(jpeg_image);\n (void) RelinquishUniqueFileResource(jpeg_image_info->filename);\n jpeg_image_info=DestroyImageInfo(jpeg_image_info);\n blob=(unsigned char *) RelinquishMagickMemory(blob);\n\n /* Write any JNG-chunk-e profiles */\n (void) Magick_png_write_chunk_from_profile(image,\"JNG-chunk-e\",logging);\n\n /* Write IEND chunk */\n (void) WriteBlobMSBULong(image,0L);\n PNGType(chunk,mng_IEND);\n LogPNGChunk(logging,mng_IEND,0);\n (void) WriteBlob(image,4,chunk);\n (void) WriteBlobMSBULong(image,crc32(0,chunk,4));\n\n if (logging != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" exit WriteOneJNGImage()\");\n\n return(status);\n}\n", + "line": null, + "label": 0, + "cwe": "CWE-772", + "cve": "CVE-2017-11310", + "length": 5077 + }, + { + "index": 15577, + "code": "static void vmxnet3_activate_device(VMXNET3State *s)\n{\n int i;\n static const uint32_t VMXNET3_DEF_TX_THRESHOLD = 1;\n hwaddr qdescr_table_pa;\n uint64_t pa;\n uint32_t size;\n\n /* Verify configuration consistency */\n if (!vmxnet3_verify_driver_magic(s->drv_shmem)) {\n VMW_ERPRN(\"Device configuration received from driver is invalid\");\n return;\n }\n\n vmxnet3_adjust_by_guest_type(s);\n vmxnet3_update_features(s);\n vmxnet3_update_pm_state(s);\n vmxnet3_setup_rx_filtering(s);\n /* Cache fields from shared memory */\n s->mtu = VMXNET3_READ_DRV_SHARED32(s->drv_shmem, devRead.misc.mtu);\n VMW_CFPRN(\"MTU is %u\", s->mtu);\n\n s->max_rx_frags =\n VMXNET3_READ_DRV_SHARED16(s->drv_shmem, devRead.misc.maxNumRxSG);\n\n if (s->max_rx_frags == 0) {\n s->max_rx_frags = 1;\n }\n\n VMW_CFPRN(\"Max RX fragments is %u\", s->max_rx_frags);\n\n s->event_int_idx =\n VMXNET3_READ_DRV_SHARED8(s->drv_shmem, devRead.intrConf.eventIntrIdx);\n assert(vmxnet3_verify_intx(s, s->event_int_idx));\n VMW_CFPRN(\"Events interrupt line is %u\", s->event_int_idx);\n\n s->auto_int_masking =\n VMXNET3_READ_DRV_SHARED8(s->drv_shmem, devRead.intrConf.autoMask);\n VMW_CFPRN(\"Automatic interrupt masking is %d\", (int)s->auto_int_masking);\n\n s->txq_num =\n VMXNET3_READ_DRV_SHARED8(s->drv_shmem, devRead.misc.numTxQueues);\n s->rxq_num =\n VMXNET3_READ_DRV_SHARED8(s->drv_shmem, devRead.misc.numRxQueues);\n\n VMW_CFPRN(\"Number of TX/RX queues %u/%u\", s->txq_num, s->rxq_num);\n vmxnet3_validate_queues(s);\n\n qdescr_table_pa =\n VMXNET3_READ_DRV_SHARED64(s->drv_shmem, devRead.misc.queueDescPA);\n VMW_CFPRN(\"TX queues descriptors table is at 0x%\" PRIx64, qdescr_table_pa);\n\n /*\n * Worst-case scenario is a packet that holds all TX rings space so\n * we calculate total size of all TX rings for max TX fragments number\n */\n s->max_tx_frags = 0;\n\n /* TX queues */\n for (i = 0; i < s->txq_num; i++) {\n hwaddr qdescr_pa =\n qdescr_table_pa + i * sizeof(struct Vmxnet3_TxQueueDesc);\n\n /* Read interrupt number for this TX queue */\n s->txq_descr[i].intr_idx =\n VMXNET3_READ_TX_QUEUE_DESCR8(qdescr_pa, conf.intrIdx);\n assert(vmxnet3_verify_intx(s, s->txq_descr[i].intr_idx));\n\n VMW_CFPRN(\"TX Queue %d interrupt: %d\", i, s->txq_descr[i].intr_idx);\n\n /* Read rings memory locations for TX queues */\n pa = VMXNET3_READ_TX_QUEUE_DESCR64(qdescr_pa, conf.txRingBasePA);\n size = VMXNET3_READ_TX_QUEUE_DESCR32(qdescr_pa, conf.txRingSize);\n\n vmxnet3_ring_init(&s->txq_descr[i].tx_ring, pa, size,\n sizeof(struct Vmxnet3_TxDesc), false);\n VMXNET3_RING_DUMP(VMW_CFPRN, \"TX\", i, &s->txq_descr[i].tx_ring);\n\n s->max_tx_frags += size;\n\n /* TXC ring */\n pa = VMXNET3_READ_TX_QUEUE_DESCR64(qdescr_pa, conf.compRingBasePA);\n size = VMXNET3_READ_TX_QUEUE_DESCR32(qdescr_pa, conf.compRingSize);\n vmxnet3_ring_init(&s->txq_descr[i].comp_ring, pa, size,\n sizeof(struct Vmxnet3_TxCompDesc), true);\n VMXNET3_RING_DUMP(VMW_CFPRN, \"TXC\", i, &s->txq_descr[i].comp_ring);\n\n s->txq_descr[i].tx_stats_pa =\n qdescr_pa + offsetof(struct Vmxnet3_TxQueueDesc, stats);\n\n memset(&s->txq_descr[i].txq_stats, 0,\n sizeof(s->txq_descr[i].txq_stats));\n\n /* Fill device-managed parameters for queues */\n VMXNET3_WRITE_TX_QUEUE_DESCR32(qdescr_pa,\n ctrl.txThreshold,\n VMXNET3_DEF_TX_THRESHOLD);\n }\n\n /* Preallocate TX packet wrapper */\n VMW_CFPRN(\"Max TX fragments is %u\", s->max_tx_frags);\n vmxnet_tx_pkt_init(&s->tx_pkt, s->max_tx_frags, s->peer_has_vhdr);\n vmxnet_rx_pkt_init(&s->rx_pkt, s->peer_has_vhdr);\n\n /* Read rings memory locations for RX queues */\n for (i = 0; i < s->rxq_num; i++) {\n int j;\n hwaddr qd_pa =\n qdescr_table_pa + s->txq_num * sizeof(struct Vmxnet3_TxQueueDesc) +\n i * sizeof(struct Vmxnet3_RxQueueDesc);\n\n /* Read interrupt number for this RX queue */\n s->rxq_descr[i].intr_idx =\n VMXNET3_READ_TX_QUEUE_DESCR8(qd_pa, conf.intrIdx);\n assert(vmxnet3_verify_intx(s, s->rxq_descr[i].intr_idx));\n\n VMW_CFPRN(\"RX Queue %d interrupt: %d\", i, s->rxq_descr[i].intr_idx);\n\n /* Read rings memory locations */\n for (j = 0; j < VMXNET3_RX_RINGS_PER_QUEUE; j++) {\n /* RX rings */\n pa = VMXNET3_READ_RX_QUEUE_DESCR64(qd_pa, conf.rxRingBasePA[j]);\n size = VMXNET3_READ_RX_QUEUE_DESCR32(qd_pa, conf.rxRingSize[j]);\n vmxnet3_ring_init(&s->rxq_descr[i].rx_ring[j], pa, size,\n sizeof(struct Vmxnet3_RxDesc), false);\n VMW_CFPRN(\"RX queue %d:%d: Base: %\" PRIx64 \", Size: %d\",\n i, j, pa, size);\n }\n\n /* RXC ring */\n pa = VMXNET3_READ_RX_QUEUE_DESCR64(qd_pa, conf.compRingBasePA);\n size = VMXNET3_READ_RX_QUEUE_DESCR32(qd_pa, conf.compRingSize);\n vmxnet3_ring_init(&s->rxq_descr[i].comp_ring, pa, size,\n sizeof(struct Vmxnet3_RxCompDesc), true);\n VMW_CFPRN(\"RXC queue %d: Base: %\" PRIx64 \", Size: %d\", i, pa, size);\n\n s->rxq_descr[i].rx_stats_pa =\n qd_pa + offsetof(struct Vmxnet3_RxQueueDesc, stats);\n memset(&s->rxq_descr[i].rxq_stats, 0,\n sizeof(s->rxq_descr[i].rxq_stats));\n }\n\n vmxnet3_validate_interrupts(s);\n\n /* Make sure everything is in place before device activation */\n smp_wmb();\n\n vmxnet3_reset_mac(s);\n\n s->device_active = true;\n}\n", + "line": null, + "label": 0, + "cwe": "CWE-20", + "cve": "CVE-2013-4544", + "length": 1712 + }, + { + "index": 117410, + "code": "png_handle_sCAL(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)\n{\n png_charp ep;\n#ifdef PNG_FLOATING_POINT_SUPPORTED\n double width, height;\n png_charp vp;\n#else\n#ifdef PNG_FIXED_POINT_SUPPORTED\n png_charp swidth, sheight;\n#endif\n#endif\n png_size_t slength;\n\n png_debug(1, \"in png_handle_sCAL\");\n\n if (!(png_ptr->mode & PNG_HAVE_IHDR))\n png_error(png_ptr, \"Missing IHDR before sCAL\");\n else if (png_ptr->mode & PNG_HAVE_IDAT)\n {\n png_warning(png_ptr, \"Invalid sCAL after IDAT\");\n png_crc_finish(png_ptr, length);\n return;\n }\n else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sCAL))\n {\n png_warning(png_ptr, \"Duplicate sCAL chunk\");\n png_crc_finish(png_ptr, length);\n return;\n }\n\n /* Need unit type, width, \\0, height: minimum 4 bytes */\n else if (length < 4)\n {\n png_warning(png_ptr, \"sCAL chunk too short\");\n png_crc_finish(png_ptr, length);\n return;\n }\n\n png_debug1(2, \"Allocating and reading sCAL chunk data (%lu bytes)\",\n length + 1);\n png_ptr->chunkdata = (png_charp)png_malloc_warn(png_ptr, length + 1);\n if (png_ptr->chunkdata == NULL)\n {\n png_warning(png_ptr, \"Out of memory while processing sCAL chunk\");\n png_crc_finish(png_ptr, length);\n return;\n }\n slength = (png_size_t)length;\n png_crc_read(png_ptr, (png_bytep)png_ptr->chunkdata, slength);\n\n if (png_crc_finish(png_ptr, 0))\n {\n png_free(png_ptr, png_ptr->chunkdata);\n png_ptr->chunkdata = NULL;\n return;\n }\n\n png_ptr->chunkdata[slength] = 0x00; /* Null terminate the last string */\n\n ep = png_ptr->chunkdata + 1; /* Skip unit byte */\n\n#ifdef PNG_FLOATING_POINT_SUPPORTED\n width = png_strtod(png_ptr, ep, &vp);\n if (*vp)\n {\n png_warning(png_ptr, \"malformed width string in sCAL chunk\");\n png_free(png_ptr, png_ptr->chunkdata);\n png_ptr->chunkdata = NULL;\n return;\n }\n#else\n#ifdef PNG_FIXED_POINT_SUPPORTED\n swidth = (png_charp)png_malloc_warn(png_ptr, png_strlen(ep) + 1);\n if (swidth == NULL)\n {\n png_warning(png_ptr, \"Out of memory while processing sCAL chunk width\");\n png_free(png_ptr, png_ptr->chunkdata);\n png_ptr->chunkdata = NULL;\n return;\n }\n png_memcpy(swidth, ep, (png_size_t)png_strlen(ep));\n#endif\n#endif\n\n for (ep = png_ptr->chunkdata; *ep; ep++)\n /* Empty loop */ ;\n ep++;\n\n if (png_ptr->chunkdata + slength < ep)\n {\n png_warning(png_ptr, \"Truncated sCAL chunk\");\n#if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)\n png_free(png_ptr, swidth);\n#endif\n png_free(png_ptr, png_ptr->chunkdata);\n png_ptr->chunkdata = NULL;\n return;\n }\n\n#ifdef PNG_FLOATING_POINT_SUPPORTED\n height = png_strtod(png_ptr, ep, &vp);\n if (*vp)\n {\n png_warning(png_ptr, \"malformed height string in sCAL chunk\");\n png_free(png_ptr, png_ptr->chunkdata);\n png_ptr->chunkdata = NULL;\n#if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)\n png_free(png_ptr, swidth);\n#endif\n return;\n }\n#else\n#ifdef PNG_FIXED_POINT_SUPPORTED\n sheight = (png_charp)png_malloc_warn(png_ptr, png_strlen(ep) + 1);\n if (sheight == NULL)\n {\n png_warning(png_ptr, \"Out of memory while processing sCAL chunk height\");\n png_free(png_ptr, png_ptr->chunkdata);\n png_ptr->chunkdata = NULL;\n#if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)\n png_free(png_ptr, swidth);\n#endif\n return;\n }\n png_memcpy(sheight, ep, (png_size_t)png_strlen(ep));\n#endif\n#endif\n\n if (png_ptr->chunkdata + slength < ep\n#ifdef PNG_FLOATING_POINT_SUPPORTED\n || width <= 0. || height <= 0.\n#endif\n )\n {\n png_warning(png_ptr, \"Invalid sCAL data\");\n png_free(png_ptr, png_ptr->chunkdata);\n png_ptr->chunkdata = NULL;\n#if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)\n png_free(png_ptr, swidth);\n png_free(png_ptr, sheight);\n#endif\n return;\n }\n\n\n#ifdef PNG_FLOATING_POINT_SUPPORTED\n png_set_sCAL(png_ptr, info_ptr, png_ptr->chunkdata[0], width, height);\n#else\n#ifdef PNG_FIXED_POINT_SUPPORTED\n png_set_sCAL_s(png_ptr, info_ptr, png_ptr->chunkdata[0], swidth, sheight);\n#endif\n#endif\n\n png_free(png_ptr, png_ptr->chunkdata);\n png_ptr->chunkdata = NULL;\n#if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)\n png_free(png_ptr, swidth);\n png_free(png_ptr, sheight);\n#endif\n}\n", + "line": null, + "label": 0, + "cwe": "CWE-189", + "cve": "CVE-2011-3045", + "length": 1232 + }, + { + "index": 44507, + "code": "static struct cgroup_process_info *lxc_cgroupfs_create(const char *name, const char *path_pattern, struct cgroup_meta_data *meta_data, const char *sub_pattern)\n{\n\tchar **cgroup_path_components = NULL;\n\tchar **p = NULL;\n\tchar *path_so_far = NULL;\n\tchar **new_cgroup_paths = NULL;\n\tchar **new_cgroup_paths_sub = NULL;\n\tstruct cgroup_mount_point *mp;\n\tstruct cgroup_hierarchy *h;\n\tstruct cgroup_process_info *base_info = NULL;\n\tstruct cgroup_process_info *info_ptr;\n\tint saved_errno;\n\tint r;\n\tunsigned suffix = 0;\n\tbool had_sub_pattern = false;\n\tsize_t i;\n\n\tif (!is_valid_cgroup(name)) {\n\t\tERROR(\"Invalid cgroup name: '%s'\", name);\n\t\terrno = EINVAL;\n\t\treturn NULL;\n\t}\n\n\tif (!strstr(path_pattern, \"%n\")) {\n\t\tERROR(\"Invalid cgroup path pattern: '%s'; contains no %%n for specifying container name\", path_pattern);\n\t\terrno = EINVAL;\n\t\treturn NULL;\n\t}\n\n\t/* we will modify the result of this operation directly,\n\t * so we don't have to copy the data structure\n\t */\n\tbase_info = (path_pattern[0] == '/') ?\n\t\tlxc_cgroup_process_info_get_init(meta_data) :\n\t\tlxc_cgroup_process_info_get_self(meta_data);\n\tif (!base_info)\n\t\treturn NULL;\n\n\tnew_cgroup_paths = calloc(meta_data->maximum_hierarchy + 1, sizeof(char *));\n\tif (!new_cgroup_paths)\n\t\tgoto out_initial_error;\n\n\tnew_cgroup_paths_sub = calloc(meta_data->maximum_hierarchy + 1, sizeof(char *));\n\tif (!new_cgroup_paths_sub)\n\t\tgoto out_initial_error;\n\n\t/* find mount points we can use */\n\tfor (info_ptr = base_info; info_ptr; info_ptr = info_ptr->next) {\n\t\th = info_ptr->hierarchy;\n\t\tmp = lxc_cgroup_find_mount_point(h, info_ptr->cgroup_path, true);\n\t\tif (!mp) {\n\t\t\tERROR(\"Could not find writable mount point for cgroup hierarchy %d while trying to create cgroup.\", h->index);\n\t\t\tgoto out_initial_error;\n\t\t}\n\t\tinfo_ptr->designated_mount_point = mp;\n\n\t\tif (lxc_string_in_array(\"ns\", (const char **)h->subsystems))\n\t\t\tcontinue;\n\t\tif (handle_cgroup_settings(mp, info_ptr->cgroup_path) < 0) {\n\t\t\tERROR(\"Could not set clone_children to 1 for cpuset hierarchy in parent cgroup.\");\n\t\t\tgoto out_initial_error;\n\t\t}\n\t}\n\n\t/* normalize the path */\n\tcgroup_path_components = lxc_normalize_path(path_pattern);\n\tif (!cgroup_path_components)\n\t\tgoto out_initial_error;\n\n\t/* go through the path components to see if we can create them */\n\tfor (p = cgroup_path_components; *p || (sub_pattern && !had_sub_pattern); p++) {\n\t\t/* we only want to create the same component with -1, -2, etc.\n\t\t * if the component contains the container name itself, otherwise\n\t\t * it's not an error if it already exists\n\t\t */\n\t\tchar *p_eff = *p ? *p : (char *)sub_pattern;\n\t\tbool contains_name = strstr(p_eff, \"%n\");\n\t\tchar *current_component = NULL;\n\t\tchar *current_subpath = NULL;\n\t\tchar *current_entire_path = NULL;\n\t\tchar *parts[3];\n\t\tsize_t j = 0;\n\t\ti = 0;\n\n\t\t/* if we are processing the subpattern, we want to make sure\n\t\t * loop is ended the next time around\n\t\t */\n\t\tif (!*p) {\n\t\t\thad_sub_pattern = true;\n\t\t\tp--;\n\t\t}\n\n\t\tgoto find_name_on_this_level;\n\n\tcleanup_name_on_this_level:\n\t\t/* This is reached if we found a name clash.\n\t\t * In that case, remove the cgroup from all previous hierarchies\n\t\t */\n\t\tfor (j = 0, info_ptr = base_info; j < i && info_ptr; info_ptr = info_ptr->next, j++) {\n\t\t\tr = remove_cgroup(info_ptr->designated_mount_point, info_ptr->created_paths[info_ptr->created_paths_count - 1], false);\n\t\t\tif (r < 0)\n\t\t\t\tWARN(\"could not clean up cgroup we created when trying to create container\");\n\t\t\tfree(info_ptr->created_paths[info_ptr->created_paths_count - 1]);\n\t\t\tinfo_ptr->created_paths[--info_ptr->created_paths_count] = NULL;\n\t\t}\n\t\tif (current_component != current_subpath)\n\t\t\tfree(current_subpath);\n\t\tif (current_component != p_eff)\n\t\t\tfree(current_component);\n\t\tcurrent_component = current_subpath = NULL;\n\t\t/* try again with another suffix */\n\t\t++suffix;\n\n\tfind_name_on_this_level:\n\t\t/* determine name of the path component we should create */\n\t\tif (contains_name && suffix > 0) {\n\t\t\tchar *buf = calloc(strlen(name) + 32, 1);\n\t\t\tif (!buf)\n\t\t\t\tgoto out_initial_error;\n\t\t\tsnprintf(buf, strlen(name) + 32, \"%s-%u\", name, suffix);\n\t\t\tcurrent_component = lxc_string_replace(\"%n\", buf, p_eff);\n\t\t\tfree(buf);\n\t\t} else {\n\t\t\tcurrent_component = contains_name ? lxc_string_replace(\"%n\", name, p_eff) : p_eff;\n\t\t}\n\t\tparts[0] = path_so_far;\n\t\tparts[1] = current_component;\n\t\tparts[2] = NULL;\n\t\tcurrent_subpath = path_so_far ? lxc_string_join(\"/\", (const char **)parts, false) : current_component;\n\n\t\t/* Now go through each hierarchy and try to create the\n\t\t * corresponding cgroup\n\t\t */\n\t\tfor (i = 0, info_ptr = base_info; info_ptr; info_ptr = info_ptr->next, i++) {\n\t\t\tchar *parts2[3];\n\n\t\t\tif (lxc_string_in_array(\"ns\", (const char **)info_ptr->hierarchy->subsystems))\n\t\t\t\tcontinue;\n\t\t\tcurrent_entire_path = NULL;\n\n\t\t\tparts2[0] = !strcmp(info_ptr->cgroup_path, \"/\") ? \"\" : info_ptr->cgroup_path;\n\t\t\tparts2[1] = current_subpath;\n\t\t\tparts2[2] = NULL;\n\t\t\tcurrent_entire_path = lxc_string_join(\"/\", (const char **)parts2, false);\n\n\t\t\tif (!*p) {\n\t\t\t\t/* we are processing the subpath, so only update that one */\n\t\t\t\tfree(new_cgroup_paths_sub[i]);\n\t\t\t\tnew_cgroup_paths_sub[i] = strdup(current_entire_path);\n\t\t\t\tif (!new_cgroup_paths_sub[i])\n\t\t\t\t\tgoto cleanup_from_error;\n\t\t\t} else {\n\t\t\t\t/* remember which path was used on this controller */\n\t\t\t\tfree(new_cgroup_paths[i]);\n\t\t\t\tnew_cgroup_paths[i] = strdup(current_entire_path);\n\t\t\t\tif (!new_cgroup_paths[i])\n\t\t\t\t\tgoto cleanup_from_error;\n\t\t\t}\n\n\t\t\tr = create_cgroup(info_ptr->designated_mount_point, current_entire_path);\n\t\t\tif (r < 0 && errno == EEXIST && contains_name) {\n\t\t\t\t/* name clash => try new name with new suffix */\n\t\t\t\tfree(current_entire_path);\n\t\t\t\tcurrent_entire_path = NULL;\n\t\t\t\tgoto cleanup_name_on_this_level;\n\t\t\t} else if (r < 0 && errno != EEXIST) {\n\t\t\t\tSYSERROR(\"Could not create cgroup '%s' in '%s'.\", current_entire_path, info_ptr->designated_mount_point->mount_point);\n\t\t\t\tgoto cleanup_from_error;\n\t\t\t} else if (r == 0) {\n\t\t\t\t/* successfully created */\n\t\t\t\tr = lxc_grow_array((void ***)&info_ptr->created_paths, &info_ptr->created_paths_capacity, info_ptr->created_paths_count + 1, 8);\n\t\t\t\tif (r < 0)\n\t\t\t\t\tgoto cleanup_from_error;\n\t\t\t\tif (!init_cpuset_if_needed(info_ptr->designated_mount_point, current_entire_path)) {\n\t\t\t\t\tERROR(\"Failed to initialize cpuset for '%s' in '%s'.\", current_entire_path, info_ptr->designated_mount_point->mount_point);\n\t\t\t\t\tgoto cleanup_from_error;\n\t\t\t\t}\n\t\t\t\tinfo_ptr->created_paths[info_ptr->created_paths_count++] = current_entire_path;\n\t\t\t} else {\n\t\t\t\t/* if we didn't create the cgroup, then we have to make sure that\n\t\t\t\t * further cgroups will be created properly\n\t\t\t\t */\n\t\t\t\tif (handle_cgroup_settings(info_ptr->designated_mount_point, info_ptr->cgroup_path) < 0) {\n\t\t\t\t\tERROR(\"Could not set clone_children to 1 for cpuset hierarchy in pre-existing cgroup.\");\n\t\t\t\t\tgoto cleanup_from_error;\n\t\t\t\t}\n\t\t\t\tif (!init_cpuset_if_needed(info_ptr->designated_mount_point, info_ptr->cgroup_path)) {\n\t\t\t\t\tERROR(\"Failed to initialize cpuset in pre-existing '%s'.\", info_ptr->cgroup_path);\n\t\t\t\t\tgoto cleanup_from_error;\n\t\t\t\t}\n\n\t\t\t\t/* already existed but path component of pattern didn't contain '%n',\n\t\t\t\t * so this is not an error; but then we don't need current_entire_path\n\t\t\t\t * anymore...\n\t\t\t\t */\n\t\t\t\tfree(current_entire_path);\n\t\t\t\tcurrent_entire_path = NULL;\n\t\t\t}\n\t\t}\n\n\t\t/* save path so far */\n\t\tfree(path_so_far);\n\t\tpath_so_far = strdup(current_subpath);\n\t\tif (!path_so_far)\n\t\t\tgoto cleanup_from_error;\n\n\t\t/* cleanup */\n\t\tif (current_component != current_subpath)\n\t\t\tfree(current_subpath);\n\t\tif (current_component != p_eff)\n\t\t\tfree(current_component);\n\t\tcurrent_component = current_subpath = NULL;\n\t\tcontinue;\n\n\tcleanup_from_error:\n\t\t/* called if an error occurred in the loop, so we\n\t\t * do some additional cleanup here\n\t\t */\n\t\tsaved_errno = errno;\n\t\tif (current_component != current_subpath)\n\t\t\tfree(current_subpath);\n\t\tif (current_component != p_eff)\n\t\t\tfree(current_component);\n\t\tfree(current_entire_path);\n\t\terrno = saved_errno;\n\t\tgoto out_initial_error;\n\t}\n\n\t/* we're done, now update the paths */\n\tfor (i = 0, info_ptr = base_info; info_ptr; info_ptr = info_ptr->next, i++) {\n\t\t/* ignore legacy 'ns' subsystem here, lxc_cgroup_create_legacy\n\t\t * will take care of it\n\t\t * Since we do a continue in above loop, new_cgroup_paths[i] is\n\t\t * unset anyway, as is new_cgroup_paths_sub[i]\n\t\t */\n\t\tif (lxc_string_in_array(\"ns\", (const char **)info_ptr->hierarchy->subsystems))\n\t\t\tcontinue;\n\t\tfree(info_ptr->cgroup_path);\n\t\tinfo_ptr->cgroup_path = new_cgroup_paths[i];\n\t\tinfo_ptr->cgroup_path_sub = new_cgroup_paths_sub[i];\n\t}\n\t/* don't use lxc_free_array since we used the array members\n\t * to store them in our result...\n\t */\n\tfree(new_cgroup_paths);\n\tfree(new_cgroup_paths_sub);\n\tfree(path_so_far);\n\tlxc_free_array((void **)cgroup_path_components, free);\n\treturn base_info;\n\nout_initial_error:\n\tsaved_errno = errno;\n\tfree(path_so_far);\n\tlxc_cgroup_process_info_free_and_remove(base_info);\n\tlxc_free_array((void **)new_cgroup_paths, free);\n\tlxc_free_array((void **)new_cgroup_paths_sub, free);\n\tlxc_free_array((void **)cgroup_path_components, free);\n\terrno = saved_errno;\n\treturn NULL;\n}\n", + "line": null, + "label": 0, + "cwe": "CWE-59", + "cve": "CVE-2015-1335", + "length": 2468 + }, + { + "index": 71924, + "code": "static MagickBooleanType sixel_encode_impl(unsigned char *pixels, size_t width,size_t height,\n unsigned char *palette, size_t ncolors, int keycolor,\n sixel_output_t *context)\n{\n#define RelinquishNodesAndMap \\\n while ((np = context->node_free) != NULL) { \\\n context->node_free = np->next; \\\n np=(sixel_node_t *) RelinquishMagickMemory(np); \\\n } \\\n map = (unsigned char *) RelinquishMagickMemory(map)\n\n int x, y, i, n, c;\n int left, right;\n int pix;\n size_t len;\n unsigned char *map;\n sixel_node_t *np, *tp, top;\n int nwrite;\n\n context->pos = 0;\n\n if (ncolors < 1) {\n return (MagickFalse);\n }\n len = ncolors * width;\n context->active_palette = (-1);\n\n if ((map = (unsigned char *)AcquireQuantumMemory(len, sizeof(unsigned char))) == NULL) {\n return (MagickFalse);\n }\n (void) ResetMagickMemory(map, 0, len);\n\n if (context->has_8bit_control) {\n nwrite = sprintf((char *)context->buffer, \"\\x90\" \"0;0;0\" \"q\");\n } else {\n nwrite = sprintf((char *)context->buffer, \"\\x1bP\" \"0;0;0\" \"q\");\n }\n if (nwrite <= 0) {\n return (MagickFalse);\n }\n sixel_advance(context, nwrite);\n nwrite = sprintf((char *)context->buffer + context->pos, \"\\\"1;1;%d;%d\", (int) width, (int) height);\n if (nwrite <= 0) {\n RelinquishNodesAndMap;\n return (MagickFalse);\n }\n sixel_advance(context, nwrite);\n\n if (ncolors != 2 || keycolor == -1) {\n for (n = 0; n < (ssize_t) ncolors; n++) {\n /* DECGCI Graphics Color Introducer # Pc ; Pu; Px; Py; Pz */\n nwrite = sprintf((char *)context->buffer + context->pos, \"#%d;2;%d;%d;%d\",\n n,\n (palette[n * 3 + 0] * 100 + 127) / 255,\n (palette[n * 3 + 1] * 100 + 127) / 255,\n (palette[n * 3 + 2] * 100 + 127) / 255);\n if (nwrite <= 0) {\n RelinquishNodesAndMap;\n return (MagickFalse);\n }\n sixel_advance(context, nwrite);\n if (nwrite <= 0) {\n RelinquishNodesAndMap;\n return (MagickFalse);\n }\n }\n }\n\n for (y = i = 0; y < (ssize_t) height; y++) {\n for (x = 0; x < (ssize_t) width; x++) {\n pix = pixels[y * width + x];\n if (pix >= 0 && pix < (ssize_t) ncolors && pix != keycolor) {\n map[pix * width + x] |= (1 << i);\n }\n }\n\n if (++i < 6 && (y + 1) < (ssize_t) height) {\n continue;\n }\n\n for (c = 0; c < (ssize_t) ncolors; c++) {\n for (left = 0; left < (ssize_t) width; left++) {\n if (*(map + c * width + left) == 0) {\n continue;\n }\n\n for (right = left + 1; right < (ssize_t) width; right++) {\n if (*(map + c * width + right) != 0) {\n continue;\n }\n\n for (n = 1; (right + n) < (ssize_t) width; n++) {\n if (*(map + c * width + right + n) != 0) {\n break;\n }\n }\n\n if (n >= 10 || right + n >= (ssize_t) width) {\n break;\n }\n right = right + n - 1;\n }\n\n if ((np = context->node_free) != NULL) {\n context->node_free = np->next;\n } else if ((np = (sixel_node_t *)AcquireMagickMemory(sizeof(sixel_node_t))) == NULL) {\n RelinquishNodesAndMap;\n return (MagickFalse);\n }\n\n np->color = c;\n np->left = left;\n np->right = right;\n np->map = map + c * width;\n\n top.next = context->node_top;\n tp = ⊤\n\n while (tp->next != NULL) {\n if (np->left < tp->next->left) {\n break;\n }\n if (np->left == tp->next->left && np->right > tp->next->right) {\n break;\n }\n tp = tp->next;\n }\n\n np->next = tp->next;\n tp->next = np;\n context->node_top = top.next;\n\n left = right - 1;\n }\n\n }\n\n for (x = 0; (np = context->node_top) != NULL;) {\n if (x > np->left) {\n /* DECGCR Graphics Carriage Return */\n context->buffer[context->pos] = '$';\n sixel_advance(context, 1);\n x = 0;\n }\n\n x = sixel_put_node(context, x, np, (int) ncolors, keycolor);\n sixel_node_del(context, np);\n np = context->node_top;\n\n while (np != NULL) {\n if (np->left < x) {\n np = np->next;\n continue;\n }\n\n x = sixel_put_node(context, x, np, (int) ncolors, keycolor);\n sixel_node_del(context, np);\n np = context->node_top;\n }\n }\n\n /* DECGNL Graphics Next Line */\n context->buffer[context->pos] = '-';\n sixel_advance(context, 1);\n if (nwrite <= 0) {\n RelinquishNodesAndMap;\n return (MagickFalse);\n }\n\n i = 0;\n (void) ResetMagickMemory(map, 0, len);\n }\n\n if (context->has_8bit_control) {\n context->buffer[context->pos] = 0x9c;\n sixel_advance(context, 1);\n } else {\n context->buffer[context->pos] = 0x1b;\n context->buffer[context->pos + 1] = '\\\\';\n sixel_advance(context, 2);\n }\n if (nwrite <= 0) {\n RelinquishNodesAndMap;\n return (MagickFalse);\n }\n\n /* flush buffer */\n if (context->pos > 0) {\n (void) WriteBlob(context->image,context->pos,context->buffer);\n }\n\n RelinquishNodesAndMap;\n\n return(MagickTrue);\n}\n", + "line": null, + "label": 0, + "cwe": "CWE-119", + "cve": "CVE-2016-10057", + "length": 1600 + }, + { + "index": 34143, + "code": "static int l2tp_ip6_sendmsg(struct kiocb *iocb, struct sock *sk,\n\t\t\t struct msghdr *msg, size_t len)\n{\n\tstruct ipv6_txoptions opt_space;\n\tstruct sockaddr_l2tpip6 *lsa =\n\t\t(struct sockaddr_l2tpip6 *) msg->msg_name;\n\tstruct in6_addr *daddr, *final_p, final;\n\tstruct ipv6_pinfo *np = inet6_sk(sk);\n\tstruct ipv6_txoptions *opt = NULL;\n\tstruct ip6_flowlabel *flowlabel = NULL;\n\tstruct dst_entry *dst = NULL;\n\tstruct flowi6 fl6;\n\tint addr_len = msg->msg_namelen;\n\tint hlimit = -1;\n\tint tclass = -1;\n\tint dontfrag = -1;\n\tint transhdrlen = 4; /* zero session-id */\n\tint ulen = len + transhdrlen;\n\tint err;\n\n\t/* Rough check on arithmetic overflow,\n\t better check is made in ip6_append_data().\n\t */\n\tif (len > INT_MAX)\n\t\treturn -EMSGSIZE;\n\n\t/* Mirror BSD error message compatibility */\n\tif (msg->msg_flags & MSG_OOB)\n\t\treturn -EOPNOTSUPP;\n\n\t/*\n\t *\tGet and verify the address.\n\t */\n\tmemset(&fl6, 0, sizeof(fl6));\n\n\tfl6.flowi6_mark = sk->sk_mark;\n\n\tif (lsa) {\n\t\tif (addr_len < SIN6_LEN_RFC2133)\n\t\t\treturn -EINVAL;\n\n\t\tif (lsa->l2tp_family && lsa->l2tp_family != AF_INET6)\n\t\t\treturn -EAFNOSUPPORT;\n\n\t\tdaddr = &lsa->l2tp_addr;\n\t\tif (np->sndflow) {\n\t\t\tfl6.flowlabel = lsa->l2tp_flowinfo & IPV6_FLOWINFO_MASK;\n\t\t\tif (fl6.flowlabel&IPV6_FLOWLABEL_MASK) {\n\t\t\t\tflowlabel = fl6_sock_lookup(sk, fl6.flowlabel);\n\t\t\t\tif (flowlabel == NULL)\n\t\t\t\t\treturn -EINVAL;\n\t\t\t\tdaddr = &flowlabel->dst;\n\t\t\t}\n\t\t}\n\n\t\t/*\n\t\t * Otherwise it will be difficult to maintain\n\t\t * sk->sk_dst_cache.\n\t\t */\n\t\tif (sk->sk_state == TCP_ESTABLISHED &&\n\t\t ipv6_addr_equal(daddr, &np->daddr))\n\t\t\tdaddr = &np->daddr;\n\n\t\tif (addr_len >= sizeof(struct sockaddr_in6) &&\n\t\t lsa->l2tp_scope_id &&\n\t\t ipv6_addr_type(daddr) & IPV6_ADDR_LINKLOCAL)\n\t\t\tfl6.flowi6_oif = lsa->l2tp_scope_id;\n\t} else {\n\t\tif (sk->sk_state != TCP_ESTABLISHED)\n\t\t\treturn -EDESTADDRREQ;\n\n\t\tdaddr = &np->daddr;\n\t\tfl6.flowlabel = np->flow_label;\n\t}\n\n\tif (fl6.flowi6_oif == 0)\n\t\tfl6.flowi6_oif = sk->sk_bound_dev_if;\n\n\tif (msg->msg_controllen) {\n\t\topt = &opt_space;\n\t\tmemset(opt, 0, sizeof(struct ipv6_txoptions));\n\t\topt->tot_len = sizeof(struct ipv6_txoptions);\n\n\t\terr = datagram_send_ctl(sock_net(sk), sk, msg, &fl6, opt,\n\t\t\t\t\t&hlimit, &tclass, &dontfrag);\n\t\tif (err < 0) {\n\t\t\tfl6_sock_release(flowlabel);\n\t\t\treturn err;\n\t\t}\n\t\tif ((fl6.flowlabel & IPV6_FLOWLABEL_MASK) && !flowlabel) {\n\t\t\tflowlabel = fl6_sock_lookup(sk, fl6.flowlabel);\n\t\t\tif (flowlabel == NULL)\n\t\t\t\treturn -EINVAL;\n\t\t}\n\t\tif (!(opt->opt_nflen|opt->opt_flen))\n\t\t\topt = NULL;\n\t}\n\n\tif (opt == NULL)\n\t\topt = np->opt;\n\tif (flowlabel)\n\t\topt = fl6_merge_options(&opt_space, flowlabel, opt);\n\topt = ipv6_fixup_options(&opt_space, opt);\n\n\tfl6.flowi6_proto = sk->sk_protocol;\n\tif (!ipv6_addr_any(daddr))\n\t\tfl6.daddr = *daddr;\n\telse\n\t\tfl6.daddr.s6_addr[15] = 0x1; /* :: means loopback (BSD'ism) */\n\tif (ipv6_addr_any(&fl6.saddr) && !ipv6_addr_any(&np->saddr))\n\t\tfl6.saddr = np->saddr;\n\n\tfinal_p = fl6_update_dst(&fl6, opt, &final);\n\n\tif (!fl6.flowi6_oif && ipv6_addr_is_multicast(&fl6.daddr))\n\t\tfl6.flowi6_oif = np->mcast_oif;\n\telse if (!fl6.flowi6_oif)\n\t\tfl6.flowi6_oif = np->ucast_oif;\n\n\tsecurity_sk_classify_flow(sk, flowi6_to_flowi(&fl6));\n\n\tdst = ip6_dst_lookup_flow(sk, &fl6, final_p, true);\n\tif (IS_ERR(dst)) {\n\t\terr = PTR_ERR(dst);\n\t\tgoto out;\n\t}\n\n\tif (hlimit < 0) {\n\t\tif (ipv6_addr_is_multicast(&fl6.daddr))\n\t\t\thlimit = np->mcast_hops;\n\t\telse\n\t\t\thlimit = np->hop_limit;\n\t\tif (hlimit < 0)\n\t\t\thlimit = ip6_dst_hoplimit(dst);\n\t}\n\n\tif (tclass < 0)\n\t\ttclass = np->tclass;\n\n\tif (dontfrag < 0)\n\t\tdontfrag = np->dontfrag;\n\n\tif (msg->msg_flags & MSG_CONFIRM)\n\t\tgoto do_confirm;\n\nback_from_confirm:\n\tlock_sock(sk);\n\terr = ip6_append_data(sk, ip_generic_getfrag, msg->msg_iov,\n\t\t\t ulen, transhdrlen, hlimit, tclass, opt,\n\t\t\t &fl6, (struct rt6_info *)dst,\n\t\t\t msg->msg_flags, dontfrag);\n\tif (err)\n\t\tip6_flush_pending_frames(sk);\n\telse if (!(msg->msg_flags & MSG_MORE))\n\t\terr = l2tp_ip6_push_pending_frames(sk);\n\trelease_sock(sk);\ndone:\n\tdst_release(dst);\nout:\n\tfl6_sock_release(flowlabel);\n\n\treturn err < 0 ? err : len;\n\ndo_confirm:\n\tdst_confirm(dst);\n\tif (!(msg->msg_flags & MSG_PROBE) || len)\n\t\tgoto back_from_confirm;\n\terr = 0;\n\tgoto done;\n}\n", + "line": null, + "label": 0, + "cwe": "CWE-200", + "cve": "CVE-2012-6543", + "length": 1396 + }, + { + "index": 55378, + "code": "static int tcp_ack(struct sock *sk, const struct sk_buff *skb, int flag)\n{\n\tstruct inet_connection_sock *icsk = inet_csk(sk);\n\tstruct tcp_sock *tp = tcp_sk(sk);\n\tstruct tcp_sacktag_state sack_state;\n\tu32 prior_snd_una = tp->snd_una;\n\tu32 ack_seq = TCP_SKB_CB(skb)->seq;\n\tu32 ack = TCP_SKB_CB(skb)->ack_seq;\n\tbool is_dupack = false;\n\tu32 prior_fackets;\n\tint prior_packets = tp->packets_out;\n\tconst int prior_unsacked = tp->packets_out - tp->sacked_out;\n\tint acked = 0; /* Number of packets newly acked */\n\n\tsack_state.first_sackt.v64 = 0;\n\n\t/* We very likely will need to access write queue head. */\n\tprefetchw(sk->sk_write_queue.next);\n\n\t/* If the ack is older than previous acks\n\t * then we can probably ignore it.\n\t */\n\tif (before(ack, prior_snd_una)) {\n\t\t/* RFC 5961 5.2 [Blind Data Injection Attack].[Mitigation] */\n\t\tif (before(ack, prior_snd_una - tp->max_window)) {\n\t\t\ttcp_send_challenge_ack(sk, skb);\n\t\t\treturn -1;\n\t\t}\n\t\tgoto old_ack;\n\t}\n\n\t/* If the ack includes data we haven't sent yet, discard\n\t * this segment (RFC793 Section 3.9).\n\t */\n\tif (after(ack, tp->snd_nxt))\n\t\tgoto invalid_ack;\n\n\tif (icsk->icsk_pending == ICSK_TIME_EARLY_RETRANS ||\n\t icsk->icsk_pending == ICSK_TIME_LOSS_PROBE)\n\t\ttcp_rearm_rto(sk);\n\n\tif (after(ack, prior_snd_una)) {\n\t\tflag |= FLAG_SND_UNA_ADVANCED;\n\t\ticsk->icsk_retransmits = 0;\n\t}\n\n\tprior_fackets = tp->fackets_out;\n\n\t/* ts_recent update must be made after we are sure that the packet\n\t * is in window.\n\t */\n\tif (flag & FLAG_UPDATE_TS_RECENT)\n\t\ttcp_replace_ts_recent(tp, TCP_SKB_CB(skb)->seq);\n\n\tif (!(flag & FLAG_SLOWPATH) && after(ack, prior_snd_una)) {\n\t\t/* Window is constant, pure forward advance.\n\t\t * No more checks are required.\n\t\t * Note, we use the fact that SND.UNA>=SND.WL2.\n\t\t */\n\t\ttcp_update_wl(tp, ack_seq);\n\t\ttcp_snd_una_update(tp, ack);\n\t\tflag |= FLAG_WIN_UPDATE;\n\n\t\ttcp_in_ack_event(sk, CA_ACK_WIN_UPDATE);\n\n\t\tNET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPHPACKS);\n\t} else {\n\t\tu32 ack_ev_flags = CA_ACK_SLOWPATH;\n\n\t\tif (ack_seq != TCP_SKB_CB(skb)->end_seq)\n\t\t\tflag |= FLAG_DATA;\n\t\telse\n\t\t\tNET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPPUREACKS);\n\n\t\tflag |= tcp_ack_update_window(sk, skb, ack, ack_seq);\n\n\t\tif (TCP_SKB_CB(skb)->sacked)\n\t\t\tflag |= tcp_sacktag_write_queue(sk, skb, prior_snd_una,\n\t\t\t\t\t\t\t&sack_state);\n\n\t\tif (tcp_ecn_rcv_ecn_echo(tp, tcp_hdr(skb))) {\n\t\t\tflag |= FLAG_ECE;\n\t\t\tack_ev_flags |= CA_ACK_ECE;\n\t\t}\n\n\t\tif (flag & FLAG_WIN_UPDATE)\n\t\t\tack_ev_flags |= CA_ACK_WIN_UPDATE;\n\n\t\ttcp_in_ack_event(sk, ack_ev_flags);\n\t}\n\n\t/* We passed data and got it acked, remove any soft error\n\t * log. Something worked...\n\t */\n\tsk->sk_err_soft = 0;\n\ticsk->icsk_probes_out = 0;\n\ttp->rcv_tstamp = tcp_time_stamp;\n\tif (!prior_packets)\n\t\tgoto no_queue;\n\n\t/* See if we can take anything off of the retransmit queue. */\n\tacked = tp->packets_out;\n\tflag |= tcp_clean_rtx_queue(sk, prior_fackets, prior_snd_una,\n\t\t\t\t &sack_state);\n\tacked -= tp->packets_out;\n\n\tif (tcp_ack_is_dubious(sk, flag)) {\n\t\tis_dupack = !(flag & (FLAG_SND_UNA_ADVANCED | FLAG_NOT_DUP));\n\t\ttcp_fastretrans_alert(sk, acked, prior_unsacked,\n\t\t\t\t is_dupack, flag);\n\t}\n\tif (tp->tlp_high_seq)\n\t\ttcp_process_tlp_ack(sk, ack, flag);\n\n\t/* Advance cwnd if state allows */\n\tif (tcp_may_raise_cwnd(sk, flag))\n\t\ttcp_cong_avoid(sk, ack, acked);\n\n\tif ((flag & FLAG_FORWARD_PROGRESS) || !(flag & FLAG_NOT_DUP)) {\n\t\tstruct dst_entry *dst = __sk_dst_get(sk);\n\t\tif (dst)\n\t\t\tdst_confirm(dst);\n\t}\n\n\tif (icsk->icsk_pending == ICSK_TIME_RETRANS)\n\t\ttcp_schedule_loss_probe(sk);\n\ttcp_update_pacing_rate(sk);\n\treturn 1;\n\nno_queue:\n\t/* If data was DSACKed, see if we can undo a cwnd reduction. */\n\tif (flag & FLAG_DSACKING_ACK)\n\t\ttcp_fastretrans_alert(sk, acked, prior_unsacked,\n\t\t\t\t is_dupack, flag);\n\t/* If this ack opens up a zero window, clear backoff. It was\n\t * being used to time the probes, and is probably far higher than\n\t * it needs to be for normal retransmission.\n\t */\n\tif (tcp_send_head(sk))\n\t\ttcp_ack_probe(sk);\n\n\tif (tp->tlp_high_seq)\n\t\ttcp_process_tlp_ack(sk, ack, flag);\n\treturn 1;\n\ninvalid_ack:\n\tSOCK_DEBUG(sk, \"Ack %u after %u:%u\\n\", ack, tp->snd_una, tp->snd_nxt);\n\treturn -1;\n\nold_ack:\n\t/* If data was SACKed, tag it and see if we should send more data.\n\t * If data was DSACKed, see if we can undo a cwnd reduction.\n\t */\n\tif (TCP_SKB_CB(skb)->sacked) {\n\t\tflag |= tcp_sacktag_write_queue(sk, skb, prior_snd_una,\n\t\t\t\t\t\t&sack_state);\n\t\ttcp_fastretrans_alert(sk, acked, prior_unsacked,\n\t\t\t\t is_dupack, flag);\n\t}\n\n\tSOCK_DEBUG(sk, \"Ack %u before %u:%u\\n\", ack, tp->snd_una, tp->snd_nxt);\n\treturn 0;\n}\n", + "line": null, + "label": 0, + "cwe": "CWE-189", + "cve": "CVE-2016-2070", + "length": 1436 + }, + { + "index": 68136, + "code": "static int __sctp_connect(struct sock *sk,\n\t\t\t struct sockaddr *kaddrs,\n\t\t\t int addrs_size,\n\t\t\t sctp_assoc_t *assoc_id)\n{\n\tstruct net *net = sock_net(sk);\n\tstruct sctp_sock *sp;\n\tstruct sctp_endpoint *ep;\n\tstruct sctp_association *asoc = NULL;\n\tstruct sctp_association *asoc2;\n\tstruct sctp_transport *transport;\n\tunion sctp_addr to;\n\tsctp_scope_t scope;\n\tlong timeo;\n\tint err = 0;\n\tint addrcnt = 0;\n\tint walk_size = 0;\n\tunion sctp_addr *sa_addr = NULL;\n\tvoid *addr_buf;\n\tunsigned short port;\n\tunsigned int f_flags = 0;\n\n\tsp = sctp_sk(sk);\n\tep = sp->ep;\n\n\t/* connect() cannot be done on a socket that is already in ESTABLISHED\n\t * state - UDP-style peeled off socket or a TCP-style socket that\n\t * is already connected.\n\t * It cannot be done even on a TCP-style listening socket.\n\t */\n\tif (sctp_sstate(sk, ESTABLISHED) || sctp_sstate(sk, CLOSING) ||\n\t (sctp_style(sk, TCP) && sctp_sstate(sk, LISTENING))) {\n\t\terr = -EISCONN;\n\t\tgoto out_free;\n\t}\n\n\t/* Walk through the addrs buffer and count the number of addresses. */\n\taddr_buf = kaddrs;\n\twhile (walk_size < addrs_size) {\n\t\tstruct sctp_af *af;\n\n\t\tif (walk_size + sizeof(sa_family_t) > addrs_size) {\n\t\t\terr = -EINVAL;\n\t\t\tgoto out_free;\n\t\t}\n\n\t\tsa_addr = addr_buf;\n\t\taf = sctp_get_af_specific(sa_addr->sa.sa_family);\n\n\t\t/* If the address family is not supported or if this address\n\t\t * causes the address buffer to overflow return EINVAL.\n\t\t */\n\t\tif (!af || (walk_size + af->sockaddr_len) > addrs_size) {\n\t\t\terr = -EINVAL;\n\t\t\tgoto out_free;\n\t\t}\n\n\t\tport = ntohs(sa_addr->v4.sin_port);\n\n\t\t/* Save current address so we can work with it */\n\t\tmemcpy(&to, sa_addr, af->sockaddr_len);\n\n\t\terr = sctp_verify_addr(sk, &to, af->sockaddr_len);\n\t\tif (err)\n\t\t\tgoto out_free;\n\n\t\t/* Make sure the destination port is correctly set\n\t\t * in all addresses.\n\t\t */\n\t\tif (asoc && asoc->peer.port && asoc->peer.port != port) {\n\t\t\terr = -EINVAL;\n\t\t\tgoto out_free;\n\t\t}\n\n\t\t/* Check if there already is a matching association on the\n\t\t * endpoint (other than the one created here).\n\t\t */\n\t\tasoc2 = sctp_endpoint_lookup_assoc(ep, &to, &transport);\n\t\tif (asoc2 && asoc2 != asoc) {\n\t\t\tif (asoc2->state >= SCTP_STATE_ESTABLISHED)\n\t\t\t\terr = -EISCONN;\n\t\t\telse\n\t\t\t\terr = -EALREADY;\n\t\t\tgoto out_free;\n\t\t}\n\n\t\t/* If we could not find a matching association on the endpoint,\n\t\t * make sure that there is no peeled-off association matching\n\t\t * the peer address even on another socket.\n\t\t */\n\t\tif (sctp_endpoint_is_peeled_off(ep, &to)) {\n\t\t\terr = -EADDRNOTAVAIL;\n\t\t\tgoto out_free;\n\t\t}\n\n\t\tif (!asoc) {\n\t\t\t/* If a bind() or sctp_bindx() is not called prior to\n\t\t\t * an sctp_connectx() call, the system picks an\n\t\t\t * ephemeral port and will choose an address set\n\t\t\t * equivalent to binding with a wildcard address.\n\t\t\t */\n\t\t\tif (!ep->base.bind_addr.port) {\n\t\t\t\tif (sctp_autobind(sk)) {\n\t\t\t\t\terr = -EAGAIN;\n\t\t\t\t\tgoto out_free;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t/*\n\t\t\t\t * If an unprivileged user inherits a 1-many\n\t\t\t\t * style socket with open associations on a\n\t\t\t\t * privileged port, it MAY be permitted to\n\t\t\t\t * accept new associations, but it SHOULD NOT\n\t\t\t\t * be permitted to open new associations.\n\t\t\t\t */\n\t\t\t\tif (ep->base.bind_addr.port <\n\t\t\t\t inet_prot_sock(net) &&\n\t\t\t\t !ns_capable(net->user_ns,\n\t\t\t\t CAP_NET_BIND_SERVICE)) {\n\t\t\t\t\terr = -EACCES;\n\t\t\t\t\tgoto out_free;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tscope = sctp_scope(&to);\n\t\t\tasoc = sctp_association_new(ep, sk, scope, GFP_KERNEL);\n\t\t\tif (!asoc) {\n\t\t\t\terr = -ENOMEM;\n\t\t\t\tgoto out_free;\n\t\t\t}\n\n\t\t\terr = sctp_assoc_set_bind_addr_from_ep(asoc, scope,\n\t\t\t\t\t\t\t GFP_KERNEL);\n\t\t\tif (err < 0) {\n\t\t\t\tgoto out_free;\n\t\t\t}\n\n\t\t}\n\n\t\t/* Prime the peer's transport structures. */\n\t\ttransport = sctp_assoc_add_peer(asoc, &to, GFP_KERNEL,\n\t\t\t\t\t\tSCTP_UNKNOWN);\n\t\tif (!transport) {\n\t\t\terr = -ENOMEM;\n\t\t\tgoto out_free;\n\t\t}\n\n\t\taddrcnt++;\n\t\taddr_buf += af->sockaddr_len;\n\t\twalk_size += af->sockaddr_len;\n\t}\n\n\t/* In case the user of sctp_connectx() wants an association\n\t * id back, assign one now.\n\t */\n\tif (assoc_id) {\n\t\terr = sctp_assoc_set_id(asoc, GFP_KERNEL);\n\t\tif (err < 0)\n\t\t\tgoto out_free;\n\t}\n\n\terr = sctp_primitive_ASSOCIATE(net, asoc, NULL);\n\tif (err < 0) {\n\t\tgoto out_free;\n\t}\n\n\t/* Initialize sk's dport and daddr for getpeername() */\n\tinet_sk(sk)->inet_dport = htons(asoc->peer.port);\n\tsp->pf->to_sk_daddr(sa_addr, sk);\n\tsk->sk_err = 0;\n\n\t/* in-kernel sockets don't generally have a file allocated to them\n\t * if all they do is call sock_create_kern().\n\t */\n\tif (sk->sk_socket->file)\n\t\tf_flags = sk->sk_socket->file->f_flags;\n\n\ttimeo = sock_sndtimeo(sk, f_flags & O_NONBLOCK);\n\n\tif (assoc_id)\n\t\t*assoc_id = asoc->assoc_id;\n\terr = sctp_wait_for_connect(asoc, &timeo);\n\t/* Note: the asoc may be freed after the return of\n\t * sctp_wait_for_connect.\n\t */\n\n\t/* Don't free association on exit. */\n\tasoc = NULL;\n\nout_free:\n\tpr_debug(\"%s: took out_free path with asoc:%p kaddrs:%p err:%d\\n\",\n\t\t __func__, asoc, kaddrs, err);\n\n\tif (asoc) {\n\t\t/* sctp_primitive_ASSOCIATE may have added this association\n\t\t * To the hash table, try to unhash it, just in case, its a noop\n\t\t * if it wasn't hashed so we're safe\n\t\t */\n\t\tsctp_association_free(asoc);\n\t}\n\treturn err;\n}\n", + "line": null, + "label": 0, + "cwe": "CWE-415", + "cve": "CVE-2017-6353", + "length": 1528 + }, + { + "index": 179866, + "code": "int BN_GF2m_mod_inv(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, BN_CTX *ctx)\n{\n BIGNUM *b, *c = NULL, *u = NULL, *v = NULL, *tmp;\n int ret = 0;\n\n bn_check_top(a);\n bn_check_top(p);\n\n BN_CTX_start(ctx);\n\n if ((b = BN_CTX_get(ctx)) == NULL)\n goto err;\n if ((c = BN_CTX_get(ctx)) == NULL)\n goto err;\n if ((u = BN_CTX_get(ctx)) == NULL)\n goto err;\n if ((v = BN_CTX_get(ctx)) == NULL)\n goto err;\n\n if (!BN_GF2m_mod(u, a, p))\n goto err;\n if (BN_is_zero(u))\n goto err;\n\n if (!BN_copy(v, p))\n goto err;\n# if 0\n if (!BN_one(b))\n goto err;\n\n while (1) {\n while (!BN_is_odd(u)) {\n if (BN_is_zero(u))\n goto err;\n if (!BN_rshift1(u, u))\n goto err;\n if (BN_is_odd(b)) {\n if (!BN_GF2m_add(b, b, p))\n goto err;\n }\n if (!BN_rshift1(b, b))\n goto err;\n }\n\n if (BN_abs_is_word(u, 1))\n break;\n\n if (BN_num_bits(u) < BN_num_bits(v)) {\n tmp = u;\n u = v;\n v = tmp;\n tmp = b;\n b = c;\n c = tmp;\n }\n\n if (!BN_GF2m_add(u, u, v))\n goto err;\n if (!BN_GF2m_add(b, b, c))\n goto err;\n }\n # else\n {\n int i, ubits = BN_num_bits(u), vbits = BN_num_bits(v), /* v is copy\n * of p */\n top = p->top;\n BN_ULONG *udp, *bdp, *vdp, *cdp;\n \n bn_wexpand(u, top);\n udp = u->d;\n for (i = u->top; i < top; i++)\n udp[i] = 0;\n u->top = top;\n bn_wexpand(b, top);\n bdp = b->d;\n bdp[0] = 1;\n for (i = 1; i < top; i++)\n bdp[i] = 0;\n b->top = top;\n bn_wexpand(c, top);\n cdp = c->d;\n for (i = 0; i < top; i++)\n cdp[i] = 0;\n c->top = top;\n vdp = v->d; /* It pays off to \"cache\" *->d pointers,\n * because it allows optimizer to be more\n * aggressive. But we don't have to \"cache\"\n * p->d, because *p is declared 'const'... */\n while (1) {\n while (ubits && !(udp[0] & 1)) {\n BN_ULONG u0, u1, b0, b1, mask;\n\n u0 = udp[0];\n b0 = bdp[0];\n mask = (BN_ULONG)0 - (b0 & 1);\n b0 ^= p->d[0] & mask;\n for (i = 0; i < top - 1; i++) {\n u1 = udp[i + 1];\n udp[i] = ((u0 >> 1) | (u1 << (BN_BITS2 - 1))) & BN_MASK2;\n u0 = u1;\n b1 = bdp[i + 1] ^ (p->d[i + 1] & mask);\n bdp[i] = ((b0 >> 1) | (b1 << (BN_BITS2 - 1))) & BN_MASK2;\n b0 = b1;\n }\n udp[i] = u0 >> 1;\n bdp[i] = b0 >> 1;\n ubits--;\n }\n \n if (ubits <= BN_BITS2 && udp[0] == 1)\n break;\n \n if (ubits < vbits) {\n i = ubits;\n ubits = vbits;\n vbits = i;\n tmp = u;\n u = v;\n v = tmp;\n tmp = b;\n b = c;\n c = tmp;\n udp = vdp;\n vdp = v->d;\n bdp = cdp;\n cdp = c->d;\n }\n for (i = 0; i < top; i++) {\n udp[i] ^= vdp[i];\n bdp[i] ^= cdp[i];\n }\n if (ubits == vbits) {\n BN_ULONG ul;\n int utop = (ubits - 1) / BN_BITS2;\n\n while ((ul = udp[utop]) == 0 && utop)\n utop--;\n ubits = utop * BN_BITS2 + BN_num_bits_word(ul);\n }\n }\n bn_correct_top(b);\n }\n# endif\n\n if (!BN_copy(r, b))\n goto err;\n bn_check_top(r);\n ret = 1;\n\n err:\n# ifdef BN_DEBUG /* BN_CTX_end would complain about the\n * expanded form */\n bn_correct_top(c);\n bn_correct_top(u);\n bn_correct_top(v);\n# endif\n BN_CTX_end(ctx);\n return ret;\n}\n", + "line": " int i, ubits = BN_num_bits(u), vbits = BN_num_bits(v), /* v is copy\n * of p */\n top = p->top;\n if (ubits <= BN_BITS2 && udp[0] == 1)\n break;\n", + "label": 1, + "cwe": "CWE-399", + "cve": "CVE-2015-1788", + "length": 1223 + }, + { + "index": 76535, + "code": "divide (mpn_t a, mpn_t b, mpn_t *q)\n{\n /* Algorithm:\n First normalise a and b: a=[a[m-1],...,a[0]], b=[b[n-1],...,b[0]]\n with m>=0 and n>0 (in base beta = 2^GMP_LIMB_BITS).\n If m=n=1, perform a single-precision division:\n r:=0, j:=m,\n while j>0 do\n {Here (q[m-1]*beta^(m-1)+...+q[j]*beta^j) * b[0] + r*beta^j =\n = a[m-1]*beta^(m-1)+...+a[j]*beta^j und 0<=r=n>1, perform a multiple-precision division:\n We have a/b < beta^(m-n+1).\n s:=intDsize-1-(highest bit in b[n-1]), 0<=s=beta/2.\n For j=m-n,...,0: {Here 0 <= r < b*beta^(j+1).}\n Compute q* :\n q* := floor((r[j+n]*beta+r[j+n-1])/b[n-1]).\n In case of overflow (q* >= beta) set q* := beta-1.\n Compute c2 := ((r[j+n]*beta+r[j+n-1]) - q* * b[n-1])*beta + r[j+n-2]\n and c3 := b[n-2] * q*.\n {We have 0 <= c2 < 2*beta^2, even 0 <= c2 < beta^2 if no overflow\n occurred. Furthermore 0 <= c3 < beta^2.\n If there was overflow and\n r[j+n]*beta+r[j+n-1] - q* * b[n-1] >= beta, i.e. c2 >= beta^2,\n the next test can be skipped.}\n While c3 > c2, {Here 0 <= c2 < c3 < beta^2}\n Put q* := q* - 1, c2 := c2 + b[n-1]*beta, c3 := c3 - b[n-2].\n If q* > 0:\n Put r := r - b * q* * beta^j. In detail:\n [r[n+j],...,r[j]] := [r[n+j],...,r[j]] - q* * [b[n-1],...,b[0]].\n hence: u:=0, for i:=0 to n-1 do\n u := u + q* * b[i],\n r[j+i]:=r[j+i]-(u mod beta) (+ beta, if carry),\n u:=u div beta (+ 1, if carry in subtraction)\n r[n+j]:=r[n+j]-u.\n {Since always u = (q* * [b[i-1],...,b[0]] div beta^i) + 1\n < q* + 1 <= beta,\n the carry u does not overflow.}\n If a negative carry occurs, put q* := q* - 1\n and [r[n+j],...,r[j]] := [r[n+j],...,r[j]] + [0,b[n-1],...,b[0]].\n Set q[j] := q*.\n Normalise [q[m-n],..,q[0]]; this yields the quotient q.\n Shift [r[n-1],...,r[0]] right by s bits and normalise; this yields the\n rest r.\n The room for q[j] can be allocated at the memory location of r[n+j].\n Finally, round-to-even:\n Shift r left by 1 bit.\n If r > b or if r = b and q[0] is odd, q := q+1.\n */\n const mp_limb_t *a_ptr = a.limbs;\n size_t a_len = a.nlimbs;\n const mp_limb_t *b_ptr = b.limbs;\n size_t b_len = b.nlimbs;\n mp_limb_t *roomptr;\n mp_limb_t *tmp_roomptr = NULL;\n mp_limb_t *q_ptr;\n size_t q_len;\n mp_limb_t *r_ptr;\n size_t r_len;\n\n /* Allocate room for a_len+2 digits.\n (Need a_len+1 digits for the real division and 1 more digit for the\n final rounding of q.) */\n roomptr = (mp_limb_t *) malloc ((a_len + 2) * sizeof (mp_limb_t));\n if (roomptr == NULL)\n return NULL;\n\n /* Normalise a. */\n while (a_len > 0 && a_ptr[a_len - 1] == 0)\n a_len--;\n\n /* Normalise b. */\n for (;;)\n {\n if (b_len == 0)\n /* Division by zero. */\n abort ();\n if (b_ptr[b_len - 1] == 0)\n b_len--;\n else\n break;\n }\n\n /* Here m = a_len >= 0 and n = b_len > 0. */\n\n if (a_len < b_len)\n {\n /* m beta^(m-2) <= a/b < beta^m */\n r_ptr = roomptr;\n q_ptr = roomptr + 1;\n {\n mp_limb_t den = b_ptr[0];\n mp_limb_t remainder = 0;\n const mp_limb_t *sourceptr = a_ptr + a_len;\n mp_limb_t *destptr = q_ptr + a_len;\n size_t count;\n for (count = a_len; count > 0; count--)\n {\n mp_twolimb_t num =\n ((mp_twolimb_t) remainder << GMP_LIMB_BITS) | *--sourceptr;\n *--destptr = num / den;\n remainder = num % den;\n }\n /* Normalise and store r. */\n if (remainder > 0)\n {\n r_ptr[0] = remainder;\n r_len = 1;\n }\n else\n r_len = 0;\n /* Normalise q. */\n q_len = a_len;\n if (q_ptr[q_len - 1] == 0)\n q_len--;\n }\n }\n else\n {\n /* n>1: multiple precision division.\n beta^(m-1) <= a < beta^m, beta^(n-1) <= b < beta^n ==>\n beta^(m-n-1) <= a/b < beta^(m-n+1). */\n /* Determine s. */\n size_t s;\n {\n mp_limb_t msd = b_ptr[b_len - 1]; /* = b[n-1], > 0 */\n /* Determine s = GMP_LIMB_BITS - integer_length (msd).\n Code copied from gnulib's integer_length.c. */\n# if __GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)\n s = __builtin_clz (msd);\n# else\n# if defined DBL_EXPBIT0_WORD && defined DBL_EXPBIT0_BIT\n if (GMP_LIMB_BITS <= DBL_MANT_BIT)\n {\n /* Use 'double' operations.\n Assumes an IEEE 754 'double' implementation. */\n# define DBL_EXP_MASK ((DBL_MAX_EXP - DBL_MIN_EXP) | 7)\n# define DBL_EXP_BIAS (DBL_EXP_MASK / 2 - 1)\n# define NWORDS \\\n ((sizeof (double) + sizeof (unsigned int) - 1) / sizeof (unsigned int))\n union { double value; unsigned int word[NWORDS]; } m;\n\n /* Use a single integer to floating-point conversion. */\n m.value = msd;\n\n s = GMP_LIMB_BITS\n - (((m.word[DBL_EXPBIT0_WORD] >> DBL_EXPBIT0_BIT) & DBL_EXP_MASK)\n - DBL_EXP_BIAS);\n }\n else\n# undef NWORDS\n# endif\n {\n s = 31;\n if (msd >= 0x10000)\n {\n msd = msd >> 16;\n s -= 16;\n }\n if (msd >= 0x100)\n {\n msd = msd >> 8;\n s -= 8;\n }\n if (msd >= 0x10)\n {\n msd = msd >> 4;\n s -= 4;\n }\n if (msd >= 0x4)\n {\n msd = msd >> 2;\n s -= 2;\n }\n if (msd >= 0x2)\n {\n msd = msd >> 1;\n s -= 1;\n }\n }\n# endif\n }\n /* 0 <= s < GMP_LIMB_BITS.\n Copy b, shifting it left by s bits. */\n if (s > 0)\n {\n tmp_roomptr = (mp_limb_t *) malloc (b_len * sizeof (mp_limb_t));\n if (tmp_roomptr == NULL)\n {\n free (roomptr);\n return NULL;\n }\n {\n const mp_limb_t *sourceptr = b_ptr;\n mp_limb_t *destptr = tmp_roomptr;\n mp_twolimb_t accu = 0;\n size_t count;\n for (count = b_len; count > 0; count--)\n {\n accu += (mp_twolimb_t) *sourceptr++ << s;\n *destptr++ = (mp_limb_t) accu;\n accu = accu >> GMP_LIMB_BITS;\n }\n /* accu must be zero, since that was how s was determined. */\n if (accu != 0)\n abort ();\n }\n b_ptr = tmp_roomptr;\n }\n /* Copy a, shifting it left by s bits, yields r.\n Memory layout:\n At the beginning: r = roomptr[0..a_len],\n at the end: r = roomptr[0..b_len-1], q = roomptr[b_len..a_len] */\n r_ptr = roomptr;\n if (s == 0)\n {\n memcpy (r_ptr, a_ptr, a_len * sizeof (mp_limb_t));\n r_ptr[a_len] = 0;\n }\n else\n {\n const mp_limb_t *sourceptr = a_ptr;\n mp_limb_t *destptr = r_ptr;\n mp_twolimb_t accu = 0;\n size_t count;\n for (count = a_len; count > 0; count--)\n {\n accu += (mp_twolimb_t) *sourceptr++ << s;\n *destptr++ = (mp_limb_t) accu;\n accu = accu >> GMP_LIMB_BITS;\n }\n *destptr++ = (mp_limb_t) accu;\n }\n q_ptr = roomptr + b_len;\n q_len = a_len - b_len + 1; /* q will have m-n+1 limbs */\n {\n size_t j = a_len - b_len; /* m-n */\n mp_limb_t b_msd = b_ptr[b_len - 1]; /* b[n-1] */\n mp_limb_t b_2msd = b_ptr[b_len - 2]; /* b[n-2] */\n mp_twolimb_t b_msdd = /* b[n-1]*beta+b[n-2] */\n ((mp_twolimb_t) b_msd << GMP_LIMB_BITS) | b_2msd;\n /* Division loop, traversed m-n+1 times.\n j counts down, b is unchanged, beta/2 <= b[n-1] < beta. */\n for (;;)\n {\n mp_limb_t q_star;\n mp_limb_t c1;\n if (r_ptr[j + b_len] < b_msd) /* r[j+n] < b[n-1] ? */\n {\n /* Divide r[j+n]*beta+r[j+n-1] by b[n-1], no overflow. */\n mp_twolimb_t num =\n ((mp_twolimb_t) r_ptr[j + b_len] << GMP_LIMB_BITS)\n | r_ptr[j + b_len - 1];\n q_star = num / b_msd;\n c1 = num % b_msd;\n }\n else\n {\n /* Overflow, hence r[j+n]*beta+r[j+n-1] >= beta*b[n-1]. */\n q_star = (mp_limb_t)~(mp_limb_t)0; /* q* = beta-1 */\n /* Test whether r[j+n]*beta+r[j+n-1] - (beta-1)*b[n-1] >= beta\n <==> r[j+n]*beta+r[j+n-1] + b[n-1] >= beta*b[n-1]+beta\n <==> b[n-1] < floor((r[j+n]*beta+r[j+n-1]+b[n-1])/beta)\n {<= beta !}.\n If yes, jump directly to the subtraction loop.\n (Otherwise, r[j+n]*beta+r[j+n-1] - (beta-1)*b[n-1] < beta\n <==> floor((r[j+n]*beta+r[j+n-1]+b[n-1])/beta) = b[n-1] ) */\n if (r_ptr[j + b_len] > b_msd\n || (c1 = r_ptr[j + b_len - 1] + b_msd) < b_msd)\n /* r[j+n] >= b[n-1]+1 or\n r[j+n] = b[n-1] and the addition r[j+n-1]+b[n-1] gives a\n carry. */\n goto subtract;\n }\n /* q_star = q*,\n c1 = (r[j+n]*beta+r[j+n-1]) - q* * b[n-1] (>=0, 0, decrease it by\n b[n-1]*beta+b[n-2]. Because of b[n-1]*beta+b[n-2] >= beta^2/2\n this can happen only twice. */\n if (c3 > c2)\n {\n q_star = q_star - 1; /* q* := q* - 1 */\n if (c3 - c2 > b_msdd)\n q_star = q_star - 1; /* q* := q* - 1 */\n }\n }\n if (q_star > 0)\n subtract:\n {\n /* Subtract r := r - b * q* * beta^j. */\n mp_limb_t cr;\n {\n const mp_limb_t *sourceptr = b_ptr;\n mp_limb_t *destptr = r_ptr + j;\n mp_twolimb_t carry = 0;\n size_t count;\n for (count = b_len; count > 0; count--)\n {\n /* Here 0 <= carry <= q*. */\n carry =\n carry\n + (mp_twolimb_t) q_star * (mp_twolimb_t) *sourceptr++\n + (mp_limb_t) ~(*destptr);\n /* Here 0 <= carry <= beta*q* + beta-1. */\n *destptr++ = ~(mp_limb_t) carry;\n carry = carry >> GMP_LIMB_BITS; /* <= q* */\n }\n cr = (mp_limb_t) carry;\n }\n /* Subtract cr from r_ptr[j + b_len], then forget about\n r_ptr[j + b_len]. */\n if (cr > r_ptr[j + b_len])\n {\n /* Subtraction gave a carry. */\n q_star = q_star - 1; /* q* := q* - 1 */\n /* Add b back. */\n {\n const mp_limb_t *sourceptr = b_ptr;\n mp_limb_t *destptr = r_ptr + j;\n mp_limb_t carry = 0;\n size_t count;\n for (count = b_len; count > 0; count--)\n {\n mp_limb_t source1 = *sourceptr++;\n mp_limb_t source2 = *destptr;\n *destptr++ = source1 + source2 + carry;\n carry =\n (carry\n ? source1 >= (mp_limb_t) ~source2\n : source1 > (mp_limb_t) ~source2);\n }\n }\n /* Forget about the carry and about r[j+n]. */\n }\n }\n /* q* is determined. Store it as q[j]. */\n q_ptr[j] = q_star;\n if (j == 0)\n break;\n j--;\n }\n }\n r_len = b_len;\n /* Normalise q. */\n if (q_ptr[q_len - 1] == 0)\n q_len--;\n# if 0 /* Not needed here, since we need r only to compare it with b/2, and\n b is shifted left by s bits. */\n /* Shift r right by s bits. */\n if (s > 0)\n {\n mp_limb_t ptr = r_ptr + r_len;\n mp_twolimb_t accu = 0;\n size_t count;\n for (count = r_len; count > 0; count--)\n {\n accu = (mp_twolimb_t) (mp_limb_t) accu << GMP_LIMB_BITS;\n accu += (mp_twolimb_t) *--ptr << (GMP_LIMB_BITS - s);\n *ptr = (mp_limb_t) (accu >> GMP_LIMB_BITS);\n }\n }\n# endif\n /* Normalise r. */\n while (r_len > 0 && r_ptr[r_len - 1] == 0)\n r_len--;\n }\n /* Compare r << 1 with b. */\n if (r_len > b_len)\n goto increment_q;\n {\n size_t i;\n for (i = b_len;;)\n {\n mp_limb_t r_i =\n (i <= r_len && i > 0 ? r_ptr[i - 1] >> (GMP_LIMB_BITS - 1) : 0)\n | (i < r_len ? r_ptr[i] << 1 : 0);\n mp_limb_t b_i = (i < b_len ? b_ptr[i] : 0);\n if (r_i > b_i)\n goto increment_q;\n if (r_i < b_i)\n goto keep_q;\n if (i == 0)\n break;\n i--;\n }\n }\n if (q_len > 0 && ((q_ptr[0] & 1) != 0))\n /* q is odd. */\n increment_q:\n {\n size_t i;\n for (i = 0; i < q_len; i++)\n if (++(q_ptr[i]) != 0)\n goto keep_q;\n q_ptr[q_len++] = 1;\n }\n keep_q:\n if (tmp_roomptr != NULL)\n free (tmp_roomptr);\n q->limbs = q_ptr;\n q->nlimbs = q_len;\n return roomptr;\n}\n", + "line": null, + "label": 0, + "cwe": "CWE-119", + "cve": "CVE-2018-17942", + "length": 4665 + }, + { + "index": 60681, + "code": "static int sctp_init_sock(struct sock *sk)\n{\n\tstruct net *net = sock_net(sk);\n\tstruct sctp_sock *sp;\n\n\tpr_debug(\"%s: sk:%p\\n\", __func__, sk);\n\n\tsp = sctp_sk(sk);\n\n\t/* Initialize the SCTP per socket area. */\n\tswitch (sk->sk_type) {\n\tcase SOCK_SEQPACKET:\n\t\tsp->type = SCTP_SOCKET_UDP;\n\t\tbreak;\n\tcase SOCK_STREAM:\n\t\tsp->type = SCTP_SOCKET_TCP;\n\t\tbreak;\n\tdefault:\n\t\treturn -ESOCKTNOSUPPORT;\n\t}\n\n\tsk->sk_gso_type = SKB_GSO_SCTP;\n\n\t/* Initialize default send parameters. These parameters can be\n\t * modified with the SCTP_DEFAULT_SEND_PARAM socket option.\n\t */\n\tsp->default_stream = 0;\n\tsp->default_ppid = 0;\n\tsp->default_flags = 0;\n\tsp->default_context = 0;\n\tsp->default_timetolive = 0;\n\n\tsp->default_rcv_context = 0;\n\tsp->max_burst = net->sctp.max_burst;\n\n\tsp->sctp_hmac_alg = net->sctp.sctp_hmac_alg;\n\n\t/* Initialize default setup parameters. These parameters\n\t * can be modified with the SCTP_INITMSG socket option or\n\t * overridden by the SCTP_INIT CMSG.\n\t */\n\tsp->initmsg.sinit_num_ostreams = sctp_max_outstreams;\n\tsp->initmsg.sinit_max_instreams = sctp_max_instreams;\n\tsp->initmsg.sinit_max_attempts = net->sctp.max_retrans_init;\n\tsp->initmsg.sinit_max_init_timeo = net->sctp.rto_max;\n\n\t/* Initialize default RTO related parameters. These parameters can\n\t * be modified for with the SCTP_RTOINFO socket option.\n\t */\n\tsp->rtoinfo.srto_initial = net->sctp.rto_initial;\n\tsp->rtoinfo.srto_max = net->sctp.rto_max;\n\tsp->rtoinfo.srto_min = net->sctp.rto_min;\n\n\t/* Initialize default association related parameters. These parameters\n\t * can be modified with the SCTP_ASSOCINFO socket option.\n\t */\n\tsp->assocparams.sasoc_asocmaxrxt = net->sctp.max_retrans_association;\n\tsp->assocparams.sasoc_number_peer_destinations = 0;\n\tsp->assocparams.sasoc_peer_rwnd = 0;\n\tsp->assocparams.sasoc_local_rwnd = 0;\n\tsp->assocparams.sasoc_cookie_life = net->sctp.valid_cookie_life;\n\n\t/* Initialize default event subscriptions. By default, all the\n\t * options are off.\n\t */\n\tmemset(&sp->subscribe, 0, sizeof(struct sctp_event_subscribe));\n\n\t/* Default Peer Address Parameters. These defaults can\n\t * be modified via SCTP_PEER_ADDR_PARAMS\n\t */\n\tsp->hbinterval = net->sctp.hb_interval;\n\tsp->pathmaxrxt = net->sctp.max_retrans_path;\n\tsp->pathmtu = 0; /* allow default discovery */\n\tsp->sackdelay = net->sctp.sack_timeout;\n\tsp->sackfreq\t= 2;\n\tsp->param_flags = SPP_HB_ENABLE |\n\t\t\t SPP_PMTUD_ENABLE |\n\t\t\t SPP_SACKDELAY_ENABLE;\n\n\t/* If enabled no SCTP message fragmentation will be performed.\n\t * Configure through SCTP_DISABLE_FRAGMENTS socket option.\n\t */\n\tsp->disable_fragments = 0;\n\n\t/* Enable Nagle algorithm by default. */\n\tsp->nodelay = 0;\n\n\tsp->recvrcvinfo = 0;\n\tsp->recvnxtinfo = 0;\n\n\t/* Enable by default. */\n\tsp->v4mapped = 1;\n\n\t/* Auto-close idle associations after the configured\n\t * number of seconds. A value of 0 disables this\n\t * feature. Configure through the SCTP_AUTOCLOSE socket option,\n\t * for UDP-style sockets only.\n\t */\n\tsp->autoclose = 0;\n\n\t/* User specified fragmentation limit. */\n\tsp->user_frag = 0;\n\n\tsp->adaptation_ind = 0;\n\n\tsp->pf = sctp_get_pf_specific(sk->sk_family);\n\n\t/* Control variables for partial data delivery. */\n\tatomic_set(&sp->pd_mode, 0);\n\tskb_queue_head_init(&sp->pd_lobby);\n\tsp->frag_interleave = 0;\n\n\t/* Create a per socket endpoint structure. Even if we\n\t * change the data structure relationships, this may still\n\t * be useful for storing pre-connect address information.\n\t */\n\tsp->ep = sctp_endpoint_new(sk, GFP_KERNEL);\n\tif (!sp->ep)\n\t\treturn -ENOMEM;\n\n\tsp->hmac = NULL;\n\n\tsk->sk_destruct = sctp_destruct_sock;\n\n\tSCTP_DBG_OBJCNT_INC(sock);\n\n\tlocal_bh_disable();\n\tpercpu_counter_inc(&sctp_sockets_allocated);\n\tsock_prot_inuse_add(net, sk->sk_prot, 1);\n\n\t/* Nothing can fail after this block, otherwise\n\t * sctp_destroy_sock() will be called without addr_wq_lock held\n\t */\n\tif (net->sctp.default_auto_asconf) {\n\t\tspin_lock(&sock_net(sk)->sctp.addr_wq_lock);\n\t\tlist_add_tail(&sp->auto_asconf_list,\n\t\t &net->sctp.auto_asconf_splist);\n\t\tsp->do_auto_asconf = 1;\n\t\tspin_unlock(&sock_net(sk)->sctp.addr_wq_lock);\n\t} else {\n\t\tsp->do_auto_asconf = 0;\n\t}\n\n\tlocal_bh_enable();\n\n\treturn 0;\n}\n", + "line": null, + "label": 0, + "cwe": "CWE-416", + "cve": "CVE-2017-15115", + "length": 1212 + }, + { + "index": 10762, + "code": "int ssl3_send_client_verify(SSL *s)\n\t{\n\tunsigned char *p,*d;\n\tunsigned char data[MD5_DIGEST_LENGTH+SHA_DIGEST_LENGTH];\n\tEVP_PKEY *pkey;\n\tEVP_PKEY_CTX *pctx=NULL;\n\tEVP_MD_CTX mctx;\n\tunsigned u=0;\n\tunsigned long n;\n\tint j;\n\n\tEVP_MD_CTX_init(&mctx);\n\n\tif (s->state == SSL3_ST_CW_CERT_VRFY_A)\n\t\t{\n\t\td=(unsigned char *)s->init_buf->data;\n\t\tp= &(d[4]);\n\t\tpkey=s->cert->key->privatekey;\n/* Create context from key and test if sha1 is allowed as digest */\n\t\tpctx = EVP_PKEY_CTX_new(pkey,NULL);\n\t\tEVP_PKEY_sign_init(pctx);\n\t\tif (EVP_PKEY_CTX_set_signature_md(pctx, EVP_sha1())>0)\n\t\t\t{\n\t\t\tif (TLS1_get_version(s) < TLS1_2_VERSION)\n\t\t\t\ts->method->ssl3_enc->cert_verify_mac(s,\n\t\t\t\t\t\tNID_sha1,\n\t\t\t\t\t\t&(data[MD5_DIGEST_LENGTH]));\n\t\t\t}\n\t\telse\n\t\t\t{\n\t\t\tERR_clear_error();\n\t\t\t}\n\t\t/* For TLS v1.2 send signature algorithm and signature\n\t\t * using agreed digest and cached handshake records.\n\t\t */\n\t\tif (TLS1_get_version(s) >= TLS1_2_VERSION)\n\t\t\t{\n\t\t\tlong hdatalen = 0;\n\t\t\tvoid *hdata;\n\t\t\tconst EVP_MD *md = s->cert->key->digest;\n\t\t\thdatalen = BIO_get_mem_data(s->s3->handshake_buffer,\n\t\t\t\t\t\t\t\t&hdata);\n\t\t\tif (hdatalen <= 0 || !tls12_get_sigandhash(p, pkey, md))\n\t\t\t\t{\n\t\t\t\tSSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY,\n\t\t\t\t\t\tERR_R_INTERNAL_ERROR);\n\t\t\t\tgoto err;\n\t\t\t\t}\n\t\t\tp += 2;\n#ifdef SSL_DEBUG\n\t\t\tfprintf(stderr, \"Using TLS 1.2 with client alg %s\\n\",\n\t\t\t\t\t\t\tEVP_MD_name(md));\n#endif\n\t\t\tif (!EVP_SignInit_ex(&mctx, md, NULL)\n\t\t\t\t|| !EVP_SignUpdate(&mctx, hdata, hdatalen)\n\t\t\t\t|| !EVP_SignFinal(&mctx, p + 2, &u, pkey))\n\t\t\t\t{\n\t\t\t\tSSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY,\n\t\t\t\t\t\tERR_R_EVP_LIB);\n\t\t\t\tgoto err;\n\t\t\t\t}\n\t\t\ts2n(u,p);\n\t\t\tn = u + 4;\n\t\t\tif (!ssl3_digest_cached_records(s))\n\t\t\t\tgoto err;\n\t\t\t}\n\t\telse\n#ifndef OPENSSL_NO_RSA\n\t\tif (pkey->type == EVP_PKEY_RSA)\n\t\t\t{\n\t\t\ts->method->ssl3_enc->cert_verify_mac(s,\n\t\t\t\tNID_md5,\n\t\t\t \t&(data[0]));\n\t\t\tif (RSA_sign(NID_md5_sha1, data,\n\t\t\t\t\t MD5_DIGEST_LENGTH+SHA_DIGEST_LENGTH,\n\t\t\t\t\t&(p[2]), &u, pkey->pkey.rsa) <= 0 )\n\t\t\t\t{\n\t\t\t\tSSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY,ERR_R_RSA_LIB);\n\t\t\t\tgoto err;\n\t\t\t\t}\n\t\t\ts2n(u,p);\n\t\t\tn=u+2;\n\t\t\t}\n\t\telse\n#endif\n#ifndef OPENSSL_NO_DSA\n\t\t\tif (pkey->type == EVP_PKEY_DSA)\n\t\t\t{\n\t\t\tif (!DSA_sign(pkey->save_type,\n\t\t\t\t&(data[MD5_DIGEST_LENGTH]),\n\t\t\t\tSHA_DIGEST_LENGTH,&(p[2]),\n\t\t\t\t(unsigned int *)&j,pkey->pkey.dsa))\n\t\t\t\t{\n\t\t\t\tSSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY,ERR_R_DSA_LIB);\n\t\t\t\tgoto err;\n\t\t\t\t}\n\t\t\ts2n(j,p);\n\t\t\tn=j+2;\n\t\t\t}\n\t\telse\n#endif\n#ifndef OPENSSL_NO_ECDSA\n\t\t\tif (pkey->type == EVP_PKEY_EC)\n\t\t\t{\n\t\t\tif (!ECDSA_sign(pkey->save_type,\n\t\t\t\t&(data[MD5_DIGEST_LENGTH]),\n\t\t\t\tSHA_DIGEST_LENGTH,&(p[2]),\n\t\t\t\t(unsigned int *)&j,pkey->pkey.ec))\n\t\t\t\t{\n\t\t\t\tSSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY,\n\t\t\t\t ERR_R_ECDSA_LIB);\n\t\t\t\tgoto err;\n\t\t\t\t}\n\t\t\ts2n(j,p);\n\t\t\tn=j+2;\n\t\t\t}\n\t\telse\n#endif\n\t\tif (pkey->type == NID_id_GostR3410_94 || pkey->type == NID_id_GostR3410_2001) \n\t\t{\n\t\tunsigned char signbuf[64];\n\t\tint i;\n\t\tsize_t sigsize=64;\n\t\ts->method->ssl3_enc->cert_verify_mac(s,\n\t\t\tNID_id_GostR3411_94,\n\t\t\tdata);\n\t\tif (EVP_PKEY_sign(pctx, signbuf, &sigsize, data, 32) <= 0) {\n\t\t\tSSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY,\n\t\t\tERR_R_INTERNAL_ERROR);\n\t\t\tgoto err;\n\t\t}\n\t\tfor (i=63,j=0; i>=0; j++, i--) {\n\t\t\tp[2+j]=signbuf[i];\n\t\t}\t\n\t\ts2n(j,p);\n\t\tn=j+2;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tSSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY,ERR_R_INTERNAL_ERROR);\n\t\t\tgoto err;\n\t\t}\n\t\t*(d++)=SSL3_MT_CERTIFICATE_VERIFY;\n\t\tl2n3(n,d);\n\n\t\ts->state=SSL3_ST_CW_CERT_VRFY_B;\n\t\ts->init_num=(int)n+4;\n\t\ts->init_off=0;\n\t\t}\n\tEVP_MD_CTX_cleanup(&mctx);\n\tEVP_PKEY_CTX_free(pctx);\n\treturn(ssl3_do_write(s,SSL3_RT_HANDSHAKE));\nerr:\n\tEVP_MD_CTX_cleanup(&mctx);\n\tEVP_PKEY_CTX_free(pctx);\n\treturn(-1);\n\t}\n", + "line": null, + "label": 0, + "cwe": null, + "cve": "CVE-2014-5139", + "length": 1299 + }, + { + "index": 181841, + "code": "static void php_wddx_pop_element(void *user_data, const XML_Char *name)\n{\n\tst_entry \t\t\t*ent1, *ent2;\n\twddx_stack \t\t\t*stack = (wddx_stack *)user_data;\n\tHashTable \t\t\t*target_hash;\n\tzend_class_entry \t**pce;\n\tzval\t\t\t\t*obj;\n\tzval\t\t\t\t*tmp;\n\tTSRMLS_FETCH();\n\n/* OBJECTS_FIXME */\n\tif (stack->top == 0) {\n\t\treturn;\n\t}\n\n\tif (!strcmp(name, EL_STRING) || !strcmp(name, EL_NUMBER) ||\n\t\t!strcmp(name, EL_BOOLEAN) || !strcmp(name, EL_NULL) ||\n\t \t!strcmp(name, EL_ARRAY) || !strcmp(name, EL_STRUCT) ||\n\t\t!strcmp(name, EL_RECORDSET) || !strcmp(name, EL_BINARY) ||\n\t\t!strcmp(name, EL_DATETIME)) {\n\t\twddx_stack_top(stack, (void**)&ent1);\n\n\t\tif (!ent1->data) {\n\t\t\tif (stack->top > 1) {\n\t\t\t\tstack->top--;\n\t\t\t\tefree(ent1);\n\t\t\t} else {\n\t\t\t\tstack->done = 1;\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\tif (!strcmp(name, EL_BINARY)) {\n\t\t\tint new_len=0;\n\t\t\tunsigned char *new_str;\n\n\t\t\tnew_str = php_base64_decode(Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data), &new_len);\n\t\t\tSTR_FREE(Z_STRVAL_P(ent1->data));\n\t\t\tif (new_str) {\n\t\t\t\tZ_STRVAL_P(ent1->data) = new_str;\n\t\t\t\tZ_STRLEN_P(ent1->data) = new_len;\n\t\t\t} else {\n\t\t\t\tZVAL_EMPTY_STRING(ent1->data);\n\t\t\t}\n\t\t}\n\n\t\t/* Call __wakeup() method on the object. */\n\t\tif (Z_TYPE_P(ent1->data) == IS_OBJECT) {\n\t\t\tzval *fname, *retval = NULL;\n\n\t\t\tMAKE_STD_ZVAL(fname);\n\t\t\tZVAL_STRING(fname, \"__wakeup\", 1);\n\n\t\t\tcall_user_function_ex(NULL, &ent1->data, fname, &retval, 0, 0, 0, NULL TSRMLS_CC);\n\n\t\t\tzval_dtor(fname);\n\t\t\tFREE_ZVAL(fname);\n\t\t\tif (retval) {\n\t\t\t\tzval_ptr_dtor(&retval);\n\t\t\t}\n\t\t}\n\n\t\tif (stack->top > 1) {\n\t\t\tstack->top--;\n\t\t\twddx_stack_top(stack, (void**)&ent2);\n\n\t\t\t/* if non-existent field */\n\t\t\tif (ent2->data == NULL) {\n\t\t\t\tzval_ptr_dtor(&ent1->data);\n\t\t\t\tefree(ent1);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (Z_TYPE_P(ent2->data) == IS_ARRAY || Z_TYPE_P(ent2->data) == IS_OBJECT) {\n\t\t\t\ttarget_hash = HASH_OF(ent2->data);\n\n\t\t\t\tif (ent1->varname) {\n\t\t\t\t\tif (!strcmp(ent1->varname, PHP_CLASS_NAME_VAR) &&\n\t\t\t\t\t\tZ_TYPE_P(ent1->data) == IS_STRING && Z_STRLEN_P(ent1->data) &&\n\t\t\t\t\t\tent2->type == ST_STRUCT && Z_TYPE_P(ent2->data) == IS_ARRAY) {\n\t\t\t\t\t\tzend_bool incomplete_class = 0;\n\n\t\t\t\t\t\tzend_str_tolower(Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data));\n\t\t\t\t\t\tif (zend_hash_find(EG(class_table), Z_STRVAL_P(ent1->data),\n\t\t\t\t\t\t\t\t\t\t Z_STRLEN_P(ent1->data)+1, (void **) &pce)==FAILURE) {\n\t\t\t\t\t\t\tincomplete_class = 1;\n \t\t\t\t\t\t\tpce = &PHP_IC_ENTRY;\n \t\t\t\t\t\t}\n \n\t\t\t\t\t\t/* Initialize target object */\n\t\t\t\t\t\tMAKE_STD_ZVAL(obj);\n\t\t\t\t\t\tobject_init_ex(obj, *pce);\n\t\t\t\t\t\t/* Merge current hashtable with object's default properties */\n\t\t\t\t\t\tzend_hash_merge(Z_OBJPROP_P(obj),\n\t\t\t\t\t\t\t\t\t\tZ_ARRVAL_P(ent2->data),\n\t\t\t\t\t\t\t\t\t\t(void (*)(void *)) zval_add_ref,\n\t\t\t\t\t\t\t\t\t\t(void *) &tmp, sizeof(zval *), 0);\n\t\t\t\t\t\tif (incomplete_class) {\n\t\t\t\t\t\t\tphp_store_class_name(obj, Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data));\n \t\t\t\t\t\t}\n\t\t\t\t\t\t/* Clean up old array entry */\n\t\t\t\t\t\tzval_ptr_dtor(&ent2->data);\n\t\t\t\t\t\t/* Set stack entry to point to the newly created object */\n\t\t\t\t\t\tent2->data = obj;\n \t\t\t\t\t\t/* Clean up class name var entry */\n \t\t\t\t\t\tzval_ptr_dtor(&ent1->data);\n \t\t\t\t\t} else if (Z_TYPE_P(ent2->data) == IS_OBJECT) {\n\t\t\t\t\t\tzend_class_entry *old_scope = EG(scope);\n\n\t\t\t\t\t\tEG(scope) = Z_OBJCE_P(ent2->data);\n\t\t\t\t\t\tZ_DELREF_P(ent1->data);\n\t\t\t\t\t\tadd_property_zval(ent2->data, ent1->varname, ent1->data);\n\t\t\t\t\t\tEG(scope) = old_scope;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tzend_symtable_update(target_hash, ent1->varname, strlen(ent1->varname)+1, &ent1->data, sizeof(zval *), NULL);\n\t\t\t\t\t}\n\t\t\t\t\tefree(ent1->varname);\n\t\t\t\t} else\t{\n\t\t\t\t\tzend_hash_next_index_insert(target_hash, &ent1->data, sizeof(zval *), NULL);\n\t\t\t\t}\n\t\t\t}\n\t\t\tefree(ent1);\n\t\t} else {\n\t\t\tstack->done = 1;\n\t\t}\n\t} else if (!strcmp(name, EL_VAR) && stack->varname) {\n\t\tefree(stack->varname);\n\t\tstack->varname = NULL;\n\t} else if (!strcmp(name, EL_FIELD)) {\n\t\tst_entry *ent;\n\t\twddx_stack_top(stack, (void **)&ent);\n\t\tefree(ent);\n\t\tstack->top--;\n\t}\n}\n", + "line": "\t\t\t\t\t\t/* Initialize target object */\n\t\t\t\t\t\tMAKE_STD_ZVAL(obj);\n\t\t\t\t\t\tobject_init_ex(obj, *pce);\n\t\t\t\t\t\t/* Merge current hashtable with object's default properties */\n\t\t\t\t\t\tzend_hash_merge(Z_OBJPROP_P(obj),\n\t\t\t\t\t\t\t\t\t\tZ_ARRVAL_P(ent2->data),\n\t\t\t\t\t\t\t\t\t\t(void (*)(void *)) zval_add_ref,\n\t\t\t\t\t\t\t\t\t\t(void *) &tmp, sizeof(zval *), 0);\n\t\t\t\t\t\tif (incomplete_class) {\n\t\t\t\t\t\t\tphp_store_class_name(obj, Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data));\n\t\t\t\t\t\t/* Clean up old array entry */\n\t\t\t\t\t\tzval_ptr_dtor(&ent2->data);\n\t\t\t\t\t\t/* Set stack entry to point to the newly created object */\n\t\t\t\t\t\tent2->data = obj;\n", + "label": 1, + "cwe": "CWE-476", + "cve": "CVE-2016-9934", + "length": 1259 + }, + { + "index": 9802, + "code": "int http_process_request(struct session *s, struct channel *req, int an_bit)\n{\n\tstruct http_txn *txn = &s->txn;\n\tstruct http_msg *msg = &txn->req;\n\tstruct connection *cli_conn = objt_conn(req->prod->end);\n\n\tif (unlikely(msg->msg_state < HTTP_MSG_BODY)) {\n\t\t/* we need more data */\n\t\tchannel_dont_connect(req);\n\t\treturn 0;\n\t}\n\n\tDPRINTF(stderr,\"[%u] %s: session=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%d analysers=%02x\\n\",\n\t\tnow_ms, __FUNCTION__,\n\t\ts,\n\t\treq,\n\t\treq->rex, req->wex,\n\t\treq->flags,\n\t\treq->buf->i,\n\t\treq->analysers);\n\n\tif (s->fe->comp || s->be->comp)\n\t\tselect_compression_request_header(s, req->buf);\n\n\t/*\n\t * Right now, we know that we have processed the entire headers\n\t * and that unwanted requests have been filtered out. We can do\n\t * whatever we want with the remaining request. Also, now we\n\t * may have separate values for ->fe, ->be.\n\t */\n\n\t/*\n\t * If HTTP PROXY is set we simply get remote server address parsing\n\t * incoming request. Note that this requires that a connection is\n\t * allocated on the server side.\n\t */\n\tif ((s->be->options & PR_O_HTTP_PROXY) && !(s->flags & SN_ADDR_SET)) {\n\t\tstruct connection *conn;\n\t\tchar *path;\n\n\t\t/* Note that for now we don't reuse existing proxy connections */\n\t\tif (unlikely((conn = si_alloc_conn(req->cons, 0)) == NULL)) {\n\t\t\ttxn->req.msg_state = HTTP_MSG_ERROR;\n\t\t\ttxn->status = 500;\n\t\t\treq->analysers = 0;\n\t\t\tstream_int_retnclose(req->prod, http_error_message(s, HTTP_ERR_500));\n\n\t\t\tif (!(s->flags & SN_ERR_MASK))\n\t\t\t\ts->flags |= SN_ERR_RESOURCE;\n\t\t\tif (!(s->flags & SN_FINST_MASK))\n\t\t\t\ts->flags |= SN_FINST_R;\n\n\t\t\treturn 0;\n\t\t}\n\n\t\tpath = http_get_path(txn);\n\t\turl2sa(req->buf->p + msg->sl.rq.u,\n\t\t path ? path - (req->buf->p + msg->sl.rq.u) : msg->sl.rq.u_l,\n\t\t &conn->addr.to, NULL);\n\t\t/* if the path was found, we have to remove everything between\n\t\t * req->buf->p + msg->sl.rq.u and path (excluded). If it was not\n\t\t * found, we need to replace from req->buf->p + msg->sl.rq.u for\n\t\t * u_l characters by a single \"/\".\n\t\t */\n\t\tif (path) {\n\t\t\tchar *cur_ptr = req->buf->p;\n\t\t\tchar *cur_end = cur_ptr + txn->req.sl.rq.l;\n\t\t\tint delta;\n\n\t\t\tdelta = buffer_replace2(req->buf, req->buf->p + msg->sl.rq.u, path, NULL, 0);\n\t\t\thttp_msg_move_end(&txn->req, delta);\n\t\t\tcur_end += delta;\n\t\t\tif (http_parse_reqline(&txn->req, HTTP_MSG_RQMETH, cur_ptr, cur_end + 1, NULL, NULL) == NULL)\n\t\t\t\tgoto return_bad_req;\n\t\t}\n\t\telse {\n\t\t\tchar *cur_ptr = req->buf->p;\n\t\t\tchar *cur_end = cur_ptr + txn->req.sl.rq.l;\n\t\t\tint delta;\n\n\t\t\tdelta = buffer_replace2(req->buf, req->buf->p + msg->sl.rq.u,\n\t\t\t\t\t\treq->buf->p + msg->sl.rq.u + msg->sl.rq.u_l, \"/\", 1);\n\t\t\thttp_msg_move_end(&txn->req, delta);\n\t\t\tcur_end += delta;\n\t\t\tif (http_parse_reqline(&txn->req, HTTP_MSG_RQMETH, cur_ptr, cur_end + 1, NULL, NULL) == NULL)\n\t\t\t\tgoto return_bad_req;\n\t\t}\n\t}\n\n\t/*\n\t * 7: Now we can work with the cookies.\n\t * Note that doing so might move headers in the request, but\n\t * the fields will stay coherent and the URI will not move.\n\t * This should only be performed in the backend.\n\t */\n\tif ((s->be->cookie_name || s->be->appsession_name || s->fe->capture_name)\n\t && !(txn->flags & (TX_CLDENY|TX_CLTARPIT)))\n\t\tmanage_client_side_cookies(s, req);\n\n\t/*\n\t * 8: the appsession cookie was looked up very early in 1.2,\n\t * so let's do the same now.\n\t */\n\n\t/* It needs to look into the URI unless persistence must be ignored */\n\tif ((txn->sessid == NULL) && s->be->appsession_name && !(s->flags & SN_IGNORE_PRST)) {\n\t\tget_srv_from_appsession(s, req->buf->p + msg->sl.rq.u, msg->sl.rq.u_l);\n\t}\n\n\t/* add unique-id if \"header-unique-id\" is specified */\n\n\tif (!LIST_ISEMPTY(&s->fe->format_unique_id)) {\n\t\tif ((s->unique_id = pool_alloc2(pool2_uniqueid)) == NULL)\n\t\t\tgoto return_bad_req;\n\t\ts->unique_id[0] = '\\0';\n\t\tbuild_logline(s, s->unique_id, UNIQUEID_LEN, &s->fe->format_unique_id);\n\t}\n\n\tif (s->fe->header_unique_id && s->unique_id) {\n\t\tchunk_printf(&trash, \"%s: %s\", s->fe->header_unique_id, s->unique_id);\n\t\tif (trash.len < 0)\n\t\t\tgoto return_bad_req;\n\t\tif (unlikely(http_header_add_tail2(&txn->req, &txn->hdr_idx, trash.str, trash.len) < 0))\n\t\t goto return_bad_req;\n\t}\n\n\t/*\n\t * 9: add X-Forwarded-For if either the frontend or the backend\n\t * asks for it.\n\t */\n\tif ((s->fe->options | s->be->options) & PR_O_FWDFOR) {\n\t\tstruct hdr_ctx ctx = { .idx = 0 };\n\t\tif (!((s->fe->options | s->be->options) & PR_O_FF_ALWAYS) &&\n\t\t\thttp_find_header2(s->be->fwdfor_hdr_len ? s->be->fwdfor_hdr_name : s->fe->fwdfor_hdr_name,\n\t\t\t s->be->fwdfor_hdr_len ? s->be->fwdfor_hdr_len : s->fe->fwdfor_hdr_len,\n\t\t\t req->buf->p, &txn->hdr_idx, &ctx)) {\n\t\t\t/* The header is set to be added only if none is present\n\t\t\t * and we found it, so don't do anything.\n\t\t\t */\n\t\t}\n\t\telse if (cli_conn && cli_conn->addr.from.ss_family == AF_INET) {\n\t\t\t/* Add an X-Forwarded-For header unless the source IP is\n\t\t\t * in the 'except' network range.\n\t\t\t */\n\t\t\tif ((!s->fe->except_mask.s_addr ||\n\t\t\t (((struct sockaddr_in *)&cli_conn->addr.from)->sin_addr.s_addr & s->fe->except_mask.s_addr)\n\t\t\t != s->fe->except_net.s_addr) &&\n\t\t\t (!s->be->except_mask.s_addr ||\n\t\t\t (((struct sockaddr_in *)&cli_conn->addr.from)->sin_addr.s_addr & s->be->except_mask.s_addr)\n\t\t\t != s->be->except_net.s_addr)) {\n\t\t\t\tint len;\n\t\t\t\tunsigned char *pn;\n\t\t\t\tpn = (unsigned char *)&((struct sockaddr_in *)&cli_conn->addr.from)->sin_addr;\n\n\t\t\t\t/* Note: we rely on the backend to get the header name to be used for\n\t\t\t\t * x-forwarded-for, because the header is really meant for the backends.\n\t\t\t\t * However, if the backend did not specify any option, we have to rely\n\t\t\t\t * on the frontend's header name.\n\t\t\t\t */\n\t\t\t\tif (s->be->fwdfor_hdr_len) {\n\t\t\t\t\tlen = s->be->fwdfor_hdr_len;\n\t\t\t\t\tmemcpy(trash.str, s->be->fwdfor_hdr_name, len);\n\t\t\t\t} else {\n\t\t\t\t\tlen = s->fe->fwdfor_hdr_len;\n\t\t\t\t\tmemcpy(trash.str, s->fe->fwdfor_hdr_name, len);\n\t\t\t\t}\n\t\t\t\tlen += snprintf(trash.str + len, trash.size - len, \": %d.%d.%d.%d\", pn[0], pn[1], pn[2], pn[3]);\n\n\t\t\t\tif (unlikely(http_header_add_tail2(&txn->req, &txn->hdr_idx, trash.str, len) < 0))\n\t\t\t\t\tgoto return_bad_req;\n\t\t\t}\n\t\t}\n\t\telse if (cli_conn && cli_conn->addr.from.ss_family == AF_INET6) {\n\t\t\t/* FIXME: for the sake of completeness, we should also support\n\t\t\t * 'except' here, although it is mostly useless in this case.\n\t\t\t */\n\t\t\tint len;\n\t\t\tchar pn[INET6_ADDRSTRLEN];\n\t\t\tinet_ntop(AF_INET6,\n\t\t\t\t (const void *)&((struct sockaddr_in6 *)(&cli_conn->addr.from))->sin6_addr,\n\t\t\t\t pn, sizeof(pn));\n\n\t\t\t/* Note: we rely on the backend to get the header name to be used for\n\t\t\t * x-forwarded-for, because the header is really meant for the backends.\n\t\t\t * However, if the backend did not specify any option, we have to rely\n\t\t\t * on the frontend's header name.\n\t\t\t */\n\t\t\tif (s->be->fwdfor_hdr_len) {\n\t\t\t\tlen = s->be->fwdfor_hdr_len;\n\t\t\t\tmemcpy(trash.str, s->be->fwdfor_hdr_name, len);\n\t\t\t} else {\n\t\t\t\tlen = s->fe->fwdfor_hdr_len;\n\t\t\t\tmemcpy(trash.str, s->fe->fwdfor_hdr_name, len);\n\t\t\t}\n\t\t\tlen += snprintf(trash.str + len, trash.size - len, \": %s\", pn);\n\n\t\t\tif (unlikely(http_header_add_tail2(&txn->req, &txn->hdr_idx, trash.str, len) < 0))\n\t\t\t\tgoto return_bad_req;\n\t\t}\n\t}\n\n\t/*\n\t * 10: add X-Original-To if either the frontend or the backend\n\t * asks for it.\n\t */\n\tif ((s->fe->options | s->be->options) & PR_O_ORGTO) {\n\n\t\t/* FIXME: don't know if IPv6 can handle that case too. */\n\t\tif (cli_conn && cli_conn->addr.from.ss_family == AF_INET) {\n\t\t\t/* Add an X-Original-To header unless the destination IP is\n\t\t\t * in the 'except' network range.\n\t\t\t */\n\t\t\tconn_get_to_addr(cli_conn);\n\n\t\t\tif (cli_conn->addr.to.ss_family == AF_INET &&\n\t\t\t ((!s->fe->except_mask_to.s_addr ||\n\t\t\t (((struct sockaddr_in *)&cli_conn->addr.to)->sin_addr.s_addr & s->fe->except_mask_to.s_addr)\n\t\t\t != s->fe->except_to.s_addr) &&\n\t\t\t (!s->be->except_mask_to.s_addr ||\n\t\t\t (((struct sockaddr_in *)&cli_conn->addr.to)->sin_addr.s_addr & s->be->except_mask_to.s_addr)\n\t\t\t != s->be->except_to.s_addr))) {\n\t\t\t\tint len;\n\t\t\t\tunsigned char *pn;\n\t\t\t\tpn = (unsigned char *)&((struct sockaddr_in *)&cli_conn->addr.to)->sin_addr;\n\n\t\t\t\t/* Note: we rely on the backend to get the header name to be used for\n\t\t\t\t * x-original-to, because the header is really meant for the backends.\n\t\t\t\t * However, if the backend did not specify any option, we have to rely\n\t\t\t\t * on the frontend's header name.\n\t\t\t\t */\n\t\t\t\tif (s->be->orgto_hdr_len) {\n\t\t\t\t\tlen = s->be->orgto_hdr_len;\n\t\t\t\t\tmemcpy(trash.str, s->be->orgto_hdr_name, len);\n\t\t\t\t} else {\n\t\t\t\t\tlen = s->fe->orgto_hdr_len;\n\t\t\t\t\tmemcpy(trash.str, s->fe->orgto_hdr_name, len);\n\t\t\t\t}\n\t\t\t\tlen += snprintf(trash.str + len, trash.size - len, \": %d.%d.%d.%d\", pn[0], pn[1], pn[2], pn[3]);\n\n\t\t\t\tif (unlikely(http_header_add_tail2(&txn->req, &txn->hdr_idx, trash.str, len) < 0))\n\t\t\t\t\tgoto return_bad_req;\n\t\t\t}\n\t\t}\n\t}\n\n\t/* 11: add \"Connection: close\" or \"Connection: keep-alive\" if needed and not yet set.\n\t * If an \"Upgrade\" token is found, the header is left untouched in order not to have\n\t * to deal with some servers bugs : some of them fail an Upgrade if anything but\n\t * \"Upgrade\" is present in the Connection header.\n\t */\n\tif (!(txn->flags & TX_HDR_CONN_UPG) &&\n\t (((txn->flags & TX_CON_WANT_MSK) != TX_CON_WANT_TUN) ||\n\t ((s->fe->options & PR_O_HTTP_MODE) == PR_O_HTTP_PCL ||\n\t (s->be->options & PR_O_HTTP_MODE) == PR_O_HTTP_PCL))) {\n\t\tunsigned int want_flags = 0;\n\n\t\tif (msg->flags & HTTP_MSGF_VER_11) {\n\t\t\tif (((txn->flags & TX_CON_WANT_MSK) >= TX_CON_WANT_SCL ||\n\t\t\t ((s->fe->options & PR_O_HTTP_MODE) == PR_O_HTTP_PCL ||\n\t\t\t (s->be->options & PR_O_HTTP_MODE) == PR_O_HTTP_PCL)) &&\n\t\t\t !((s->fe->options2|s->be->options2) & PR_O2_FAKE_KA))\n\t\t\t\twant_flags |= TX_CON_CLO_SET;\n\t\t} else {\n\t\t\tif (((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_KAL &&\n\t\t\t ((s->fe->options & PR_O_HTTP_MODE) != PR_O_HTTP_PCL &&\n\t\t\t (s->be->options & PR_O_HTTP_MODE) != PR_O_HTTP_PCL)) ||\n\t\t\t ((s->fe->options2|s->be->options2) & PR_O2_FAKE_KA))\n\t\t\t\twant_flags |= TX_CON_KAL_SET;\n\t\t}\n\n\t\tif (want_flags != (txn->flags & (TX_CON_CLO_SET|TX_CON_KAL_SET)))\n\t\t\thttp_change_connection_header(txn, msg, want_flags);\n\t}\n\n\n\t/* If we have no server assigned yet and we're balancing on url_param\n\t * with a POST request, we may be interested in checking the body for\n\t * that parameter. This will be done in another analyser.\n\t */\n\tif (!(s->flags & (SN_ASSIGNED|SN_DIRECT)) &&\n\t s->txn.meth == HTTP_METH_POST && s->be->url_param_name != NULL &&\n\t (msg->flags & (HTTP_MSGF_CNT_LEN|HTTP_MSGF_TE_CHNK))) {\n\t\tchannel_dont_connect(req);\n\t\treq->analysers |= AN_REQ_HTTP_BODY;\n\t}\n\n\tif (msg->flags & HTTP_MSGF_XFER_LEN) {\n\t\treq->analysers |= AN_REQ_HTTP_XFER_BODY;\n#ifdef TCP_QUICKACK\n\t\t/* We expect some data from the client. Unless we know for sure\n\t\t * we already have a full request, we have to re-enable quick-ack\n\t\t * in case we previously disabled it, otherwise we might cause\n\t\t * the client to delay further data.\n\t\t */\n\t\tif ((s->listener->options & LI_O_NOQUICKACK) &&\n\t\t cli_conn && conn_ctrl_ready(cli_conn) &&\n\t\t ((msg->flags & HTTP_MSGF_TE_CHNK) ||\n\t\t (msg->body_len > req->buf->i - txn->req.eoh - 2)))\n\t\t\tsetsockopt(cli_conn->t.sock.fd, IPPROTO_TCP, TCP_QUICKACK, &one, sizeof(one));\n#endif\n\t}\n\n\t/*************************************************************\n\t * OK, that's finished for the headers. We have done what we *\n\t * could. Let's switch to the DATA state. *\n\t ************************************************************/\n\treq->analyse_exp = TICK_ETERNITY;\n\treq->analysers &= ~an_bit;\n\n\t/* if the server closes the connection, we want to immediately react\n\t * and close the socket to save packets and syscalls.\n\t */\n\tif (!(req->analysers & AN_REQ_HTTP_XFER_BODY))\n\t\treq->cons->flags |= SI_FL_NOHALF;\n\n\ts->logs.tv_request = now;\n\t/* OK let's go on with the BODY now */\n\treturn 1;\n\n return_bad_req: /* let's centralize all bad requests */\n\tif (unlikely(msg->msg_state == HTTP_MSG_ERROR) || msg->err_pos >= 0) {\n\t\t/* we detected a parsing error. We want to archive this request\n\t\t * in the dedicated proxy area for later troubleshooting.\n\t\t */\n\t\thttp_capture_bad_message(&s->fe->invalid_req, s, msg, msg->msg_state, s->fe);\n\t}\n\n\ttxn->req.msg_state = HTTP_MSG_ERROR;\n\ttxn->status = 400;\n\treq->analysers = 0;\n\tstream_int_retnclose(req->prod, http_error_message(s, HTTP_ERR_400));\n\n\ts->fe->fe_counters.failed_req++;\n\tif (s->listener->counters)\n\t\ts->listener->counters->failed_req++;\n\n\tif (!(s->flags & SN_ERR_MASK))\n\t\ts->flags |= SN_ERR_PRXCOND;\n\tif (!(s->flags & SN_FINST_MASK))\n\t\ts->flags |= SN_FINST_R;\n\treturn 0;\n}\n", + "line": null, + "label": 0, + "cwe": "CWE-189", + "cve": "CVE-2014-6269", + "length": 3830 + }, + { + "index": 61891, + "code": "int imagetotga(opj_image_t * image, const char *outfile)\n{\n int width, height, bpp, x, y;\n OPJ_BOOL write_alpha;\n unsigned int i;\n int adjustR, adjustG = 0, adjustB = 0, fails;\n unsigned int alpha_channel;\n float r, g, b, a;\n unsigned char value;\n float scale;\n FILE *fdest;\n size_t res;\n fails = 1;\n\n fdest = fopen(outfile, \"wb\");\n if (!fdest) {\n fprintf(stderr, \"ERROR -> failed to open %s for writing\\n\", outfile);\n return 1;\n }\n\n for (i = 0; i < image->numcomps - 1; i++) {\n if ((image->comps[0].dx != image->comps[i + 1].dx)\n || (image->comps[0].dy != image->comps[i + 1].dy)\n || (image->comps[0].prec != image->comps[i + 1].prec)\n || (image->comps[0].sgnd != image->comps[i + 1].sgnd)) {\n fclose(fdest);\n fprintf(stderr,\n \"Unable to create a tga file with such J2K image charateristics.\\n\");\n return 1;\n }\n }\n\n width = (int)image->comps[0].w;\n height = (int)image->comps[0].h;\n\n /* Mono with alpha, or RGB with alpha. */\n write_alpha = (image->numcomps == 2) || (image->numcomps == 4);\n\n /* Write TGA header */\n bpp = write_alpha ? 32 : 24;\n\n if (!tga_writeheader(fdest, bpp, width, height, OPJ_TRUE)) {\n goto fin;\n }\n\n alpha_channel = image->numcomps - 1;\n\n scale = 255.0f / (float)((1 << image->comps[0].prec) - 1);\n\n adjustR = (image->comps[0].sgnd ? 1 << (image->comps[0].prec - 1) : 0);\n if (image->numcomps >= 3) {\n adjustG = (image->comps[1].sgnd ? 1 << (image->comps[1].prec - 1) : 0);\n adjustB = (image->comps[2].sgnd ? 1 << (image->comps[2].prec - 1) : 0);\n }\n\n for (y = 0; y < height; y++) {\n unsigned int index = (unsigned int)(y * width);\n\n for (x = 0; x < width; x++, index++) {\n r = (float)(image->comps[0].data[index] + adjustR);\n\n if (image->numcomps > 2) {\n g = (float)(image->comps[1].data[index] + adjustG);\n b = (float)(image->comps[2].data[index] + adjustB);\n } else {\n /* Greyscale ... */\n g = r;\n b = r;\n }\n\n /* TGA format writes BGR ... */\n if (b > 255.) {\n b = 255.;\n } else if (b < 0.) {\n b = 0.;\n }\n value = (unsigned char)(b * scale);\n res = fwrite(&value, 1, 1, fdest);\n\n if (res < 1) {\n fprintf(stderr, \"failed to write 1 byte for %s\\n\", outfile);\n goto fin;\n }\n if (g > 255.) {\n g = 255.;\n } else if (g < 0.) {\n g = 0.;\n }\n value = (unsigned char)(g * scale);\n res = fwrite(&value, 1, 1, fdest);\n\n if (res < 1) {\n fprintf(stderr, \"failed to write 1 byte for %s\\n\", outfile);\n goto fin;\n }\n if (r > 255.) {\n r = 255.;\n } else if (r < 0.) {\n r = 0.;\n }\n value = (unsigned char)(r * scale);\n res = fwrite(&value, 1, 1, fdest);\n\n if (res < 1) {\n fprintf(stderr, \"failed to write 1 byte for %s\\n\", outfile);\n goto fin;\n }\n\n if (write_alpha) {\n a = (float)(image->comps[alpha_channel].data[index]);\n if (a > 255.) {\n a = 255.;\n } else if (a < 0.) {\n a = 0.;\n }\n value = (unsigned char)(a * scale);\n res = fwrite(&value, 1, 1, fdest);\n\n if (res < 1) {\n fprintf(stderr, \"failed to write 1 byte for %s\\n\", outfile);\n goto fin;\n }\n }\n }\n }\n fails = 0;\nfin:\n fclose(fdest);\n\n return fails;\n}\n", + "line": null, + "label": 0, + "cwe": "CWE-787", + "cve": "CVE-2017-14041", + "length": 1151 + }, + { + "index": 88990, + "code": "MagickExport MagickBooleanType CLAHEImage(Image *image,const size_t width,\n const size_t height,const size_t number_bins,const double clip_limit,\n ExceptionInfo *exception)\n{\n#define CLAHEImageTag \"CLAHE/Image\"\n\n CacheView\n *image_view;\n\n ColorspaceType\n colorspace;\n\n MagickBooleanType\n status;\n\n MagickOffsetType\n progress;\n\n MemoryInfo\n *pixel_cache;\n\n RangeInfo\n range_info;\n\n RectangleInfo\n clahe_info,\n tile_info;\n\n size_t\n n;\n\n ssize_t\n y;\n\n unsigned short\n *pixels;\n\n /*\n Configure CLAHE parameters.\n */\n assert(image != (Image *) NULL);\n assert(image->signature == MagickCoreSignature);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",image->filename);\n range_info.min=0;\n range_info.max=NumberCLAHEGrays-1;\n tile_info.width=width;\n if (tile_info.width == 0)\n tile_info.width=image->columns >> 3;\n tile_info.height=height;\n if (tile_info.height == 0)\n tile_info.height=image->rows >> 3;\n tile_info.x=0;\n if ((image->columns % tile_info.width) != 0)\n tile_info.x=(ssize_t) tile_info.width-(image->columns % tile_info.width);\n tile_info.y=0;\n if ((image->rows % tile_info.height) != 0)\n tile_info.y=(ssize_t) tile_info.height-(image->rows % tile_info.height);\n clahe_info.width=image->columns+tile_info.x;\n clahe_info.height=image->rows+tile_info.y;\n clahe_info.x=(ssize_t) clahe_info.width/tile_info.width;\n clahe_info.y=(ssize_t) clahe_info.height/tile_info.height;\n pixel_cache=AcquireVirtualMemory(clahe_info.width,clahe_info.height*\n sizeof(*pixels));\n if (pixel_cache == (MemoryInfo *) NULL)\n ThrowBinaryException(ResourceLimitError,\"MemoryAllocationFailed\",\n image->filename);\n pixels=(unsigned short *) GetVirtualMemoryBlob(pixel_cache);\n colorspace=image->colorspace;\n if (TransformImageColorspace(image,LabColorspace,exception) == MagickFalse)\n {\n pixel_cache=RelinquishVirtualMemory(pixel_cache);\n return(MagickFalse);\n }\n /*\n Initialize CLAHE pixels.\n */\n image_view=AcquireVirtualCacheView(image,exception);\n progress=0;\n status=MagickTrue;\n n=0;\n for (y=0; y < (ssize_t) clahe_info.height; y++)\n {\n register const Quantum\n *magick_restrict p;\n\n register ssize_t\n x;\n\n if (status == MagickFalse)\n continue;\n p=GetCacheViewVirtualPixels(image_view,-(tile_info.x >> 1),y-\n (tile_info.y >> 1),clahe_info.width,1,exception);\n if (p == (const Quantum *) NULL)\n {\n status=MagickFalse;\n continue;\n }\n for (x=0; x < (ssize_t) clahe_info.width; x++)\n {\n pixels[n++]=ScaleQuantumToShort(p[0]);\n p+=GetPixelChannels(image);\n }\n if (image->progress_monitor != (MagickProgressMonitor) NULL)\n {\n MagickBooleanType\n proceed;\n\n#if defined(MAGICKCORE_OPENMP_SUPPORT)\n #pragma omp atomic\n#endif\n progress++;\n proceed=SetImageProgress(image,CLAHEImageTag,progress,2*\n GetPixelChannels(image));\n if (proceed == MagickFalse)\n status=MagickFalse;\n }\n }\n image_view=DestroyCacheView(image_view);\n status=CLAHE(&clahe_info,&tile_info,&range_info,number_bins == 0 ?\n (size_t) 128 : MagickMin(number_bins,256),clip_limit,pixels);\n if (status == MagickFalse)\n (void) ThrowMagickException(exception,GetMagickModule(),\n ResourceLimitError,\"MemoryAllocationFailed\",\"`%s'\",image->filename);\n /*\n Push CLAHE pixels to CLAHE image.\n */\n image_view=AcquireAuthenticCacheView(image,exception);\n n=clahe_info.width*(tile_info.y >> 1);\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n register Quantum\n *magick_restrict q;\n\n register ssize_t\n x;\n\n if (status == MagickFalse)\n continue;\n q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);\n if (q == (Quantum *) NULL)\n {\n status=MagickFalse;\n continue;\n }\n n+=tile_info.x >> 1;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n q[0]=ScaleShortToQuantum(pixels[n++]);\n q+=GetPixelChannels(image);\n }\n n+=(clahe_info.width-image->columns-(tile_info.x >> 1));\n if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)\n status=MagickFalse;\n if (image->progress_monitor != (MagickProgressMonitor) NULL)\n {\n MagickBooleanType\n proceed;\n\n#if defined(MAGICKCORE_OPENMP_SUPPORT)\n #pragma omp atomic\n#endif\n progress++;\n proceed=SetImageProgress(image,CLAHEImageTag,progress,2*\n GetPixelChannels(image));\n if (proceed == MagickFalse)\n status=MagickFalse;\n }\n }\n image_view=DestroyCacheView(image_view);\n pixel_cache=RelinquishVirtualMemory(pixel_cache);\n if (TransformImageColorspace(image,colorspace,exception) == MagickFalse)\n status=MagickFalse;\n return(status);\n}\n", + "line": null, + "label": 0, + "cwe": "CWE-119", + "cve": "CVE-2019-13298", + "length": 1308 + }, + { + "index": 180512, + "code": "static int tcp_v6_connect(struct sock *sk, struct sockaddr *uaddr,\n\t\t\t int addr_len)\n{\n\tstruct sockaddr_in6 *usin = (struct sockaddr_in6 *) uaddr;\n\tstruct inet_sock *inet = inet_sk(sk);\n\tstruct inet_connection_sock *icsk = inet_csk(sk);\n \tstruct ipv6_pinfo *np = inet6_sk(sk);\n \tstruct tcp_sock *tp = tcp_sk(sk);\n \tstruct in6_addr *saddr = NULL, *final_p, final;\n \tstruct flowi6 fl6;\n \tstruct dst_entry *dst;\n \tint addr_type;\n\tint err;\n\n\tif (addr_len < SIN6_LEN_RFC2133)\n\t\treturn -EINVAL;\n\n\tif (usin->sin6_family != AF_INET6)\n\t\treturn -EAFNOSUPPORT;\n\n\tmemset(&fl6, 0, sizeof(fl6));\n\n\tif (np->sndflow) {\n\t\tfl6.flowlabel = usin->sin6_flowinfo&IPV6_FLOWINFO_MASK;\n\t\tIP6_ECN_flow_init(fl6.flowlabel);\n\t\tif (fl6.flowlabel&IPV6_FLOWLABEL_MASK) {\n\t\t\tstruct ip6_flowlabel *flowlabel;\n\t\t\tflowlabel = fl6_sock_lookup(sk, fl6.flowlabel);\n\t\t\tif (!flowlabel)\n\t\t\t\treturn -EINVAL;\n\t\t\tfl6_sock_release(flowlabel);\n\t\t}\n\t}\n\n\t/*\n\t *\tconnect() to INADDR_ANY means loopback (BSD'ism).\n\t */\n\n\tif (ipv6_addr_any(&usin->sin6_addr))\n\t\tusin->sin6_addr.s6_addr[15] = 0x1;\n\n\taddr_type = ipv6_addr_type(&usin->sin6_addr);\n\n\tif (addr_type & IPV6_ADDR_MULTICAST)\n\t\treturn -ENETUNREACH;\n\n\tif (addr_type&IPV6_ADDR_LINKLOCAL) {\n\t\tif (addr_len >= sizeof(struct sockaddr_in6) &&\n\t\t usin->sin6_scope_id) {\n\t\t\t/* If interface is set while binding, indices\n\t\t\t * must coincide.\n\t\t\t */\n\t\t\tif (sk->sk_bound_dev_if &&\n\t\t\t sk->sk_bound_dev_if != usin->sin6_scope_id)\n\t\t\t\treturn -EINVAL;\n\n\t\t\tsk->sk_bound_dev_if = usin->sin6_scope_id;\n\t\t}\n\n\t\t/* Connect to link-local address requires an interface */\n\t\tif (!sk->sk_bound_dev_if)\n\t\t\treturn -EINVAL;\n\t}\n\n\tif (tp->rx_opt.ts_recent_stamp &&\n\t !ipv6_addr_equal(&sk->sk_v6_daddr, &usin->sin6_addr)) {\n\t\ttp->rx_opt.ts_recent = 0;\n\t\ttp->rx_opt.ts_recent_stamp = 0;\n\t\ttp->write_seq = 0;\n\t}\n\n\tsk->sk_v6_daddr = usin->sin6_addr;\n\tnp->flow_label = fl6.flowlabel;\n\n\t/*\n\t *\tTCP over IPv4\n\t */\n\n\tif (addr_type == IPV6_ADDR_MAPPED) {\n\t\tu32 exthdrlen = icsk->icsk_ext_hdr_len;\n\t\tstruct sockaddr_in sin;\n\n\t\tSOCK_DEBUG(sk, \"connect: ipv4 mapped\\n\");\n\n\t\tif (__ipv6_only_sock(sk))\n\t\t\treturn -ENETUNREACH;\n\n\t\tsin.sin_family = AF_INET;\n\t\tsin.sin_port = usin->sin6_port;\n\t\tsin.sin_addr.s_addr = usin->sin6_addr.s6_addr32[3];\n\n\t\ticsk->icsk_af_ops = &ipv6_mapped;\n\t\tsk->sk_backlog_rcv = tcp_v4_do_rcv;\n#ifdef CONFIG_TCP_MD5SIG\n\t\ttp->af_specific = &tcp_sock_ipv6_mapped_specific;\n#endif\n\n\t\terr = tcp_v4_connect(sk, (struct sockaddr *)&sin, sizeof(sin));\n\n\t\tif (err) {\n\t\t\ticsk->icsk_ext_hdr_len = exthdrlen;\n\t\t\ticsk->icsk_af_ops = &ipv6_specific;\n\t\t\tsk->sk_backlog_rcv = tcp_v6_do_rcv;\n#ifdef CONFIG_TCP_MD5SIG\n\t\t\ttp->af_specific = &tcp_sock_ipv6_specific;\n#endif\n\t\t\tgoto failure;\n\t\t}\n\t\tnp->saddr = sk->sk_v6_rcv_saddr;\n\n\t\treturn err;\n\t}\n\n\tif (!ipv6_addr_any(&sk->sk_v6_rcv_saddr))\n\t\tsaddr = &sk->sk_v6_rcv_saddr;\n\n\tfl6.flowi6_proto = IPPROTO_TCP;\n\tfl6.daddr = sk->sk_v6_daddr;\n\tfl6.saddr = saddr ? *saddr : np->saddr;\n\tfl6.flowi6_oif = sk->sk_bound_dev_if;\n\tfl6.flowi6_mark = sk->sk_mark;\n \tfl6.fl6_dport = usin->sin6_port;\n \tfl6.fl6_sport = inet->inet_sport;\n \n\tfinal_p = fl6_update_dst(&fl6, np->opt, &final);\n \n \tsecurity_sk_classify_flow(sk, flowi6_to_flowi(&fl6));\n \n\tdst = ip6_dst_lookup_flow(sk, &fl6, final_p);\n\tif (IS_ERR(dst)) {\n\t\terr = PTR_ERR(dst);\n\t\tgoto failure;\n\t}\n\n\tif (!saddr) {\n\t\tsaddr = &fl6.saddr;\n\t\tsk->sk_v6_rcv_saddr = *saddr;\n\t}\n\n\t/* set the source address */\n\tnp->saddr = *saddr;\n\tinet->inet_rcv_saddr = LOOPBACK4_IPV6;\n\n\tsk->sk_gso_type = SKB_GSO_TCPV6;\n\t__ip6_dst_store(sk, dst, NULL, NULL);\n\n\tif (tcp_death_row.sysctl_tw_recycle &&\n\t !tp->rx_opt.ts_recent_stamp &&\n\t ipv6_addr_equal(&fl6.daddr, &sk->sk_v6_daddr))\n \t\ttcp_fetch_timewait_stamp(sk, dst);\n \n \ticsk->icsk_ext_hdr_len = 0;\n\tif (np->opt)\n\t\ticsk->icsk_ext_hdr_len = (np->opt->opt_flen +\n\t\t\t\t\t np->opt->opt_nflen);\n \n \ttp->rx_opt.mss_clamp = IPV6_MIN_MTU - sizeof(struct tcphdr) - sizeof(struct ipv6hdr);\n \n\tinet->inet_dport = usin->sin6_port;\n\n\ttcp_set_state(sk, TCP_SYN_SENT);\n\terr = inet6_hash_connect(&tcp_death_row, sk);\n\tif (err)\n\t\tgoto late_failure;\n\n\tsk_set_txhash(sk);\n\n\tif (!tp->write_seq && likely(!tp->repair))\n\t\ttp->write_seq = secure_tcpv6_sequence_number(np->saddr.s6_addr32,\n\t\t\t\t\t\t\t sk->sk_v6_daddr.s6_addr32,\n\t\t\t\t\t\t\t inet->inet_sport,\n\t\t\t\t\t\t\t inet->inet_dport);\n\n\terr = tcp_connect(sk);\n\tif (err)\n\t\tgoto late_failure;\n\n\treturn 0;\n\nlate_failure:\n\ttcp_set_state(sk, TCP_CLOSE);\n\t__sk_dst_reset(sk);\nfailure:\n\tinet->inet_dport = 0;\n\tsk->sk_route_caps = 0;\n\treturn err;\n}\n", + "line": "\tfinal_p = fl6_update_dst(&fl6, np->opt, &final);\n\tif (np->opt)\n\t\ticsk->icsk_ext_hdr_len = (np->opt->opt_flen +\n\t\t\t\t\t np->opt->opt_nflen);\n", + "label": 1, + "cwe": "CWE-416", + "cve": "CVE-2016-3841", + "length": 1533 + }, + { + "index": 3748, + "code": "_dbus_listen_unix_socket (const char *path,\n dbus_bool_t abstract,\n DBusError *error)\n{\n int listen_fd;\n struct sockaddr_un addr;\n size_t path_len;\n unsigned int reuseaddr;\n\n _DBUS_ASSERT_ERROR_IS_CLEAR (error);\n\n _dbus_verbose (\"listening on unix socket %s abstract=%d\\n\",\n path, abstract);\n\n if (!_dbus_open_unix_socket (&listen_fd, error))\n {\n _DBUS_ASSERT_ERROR_IS_SET(error);\n return -1;\n }\n _DBUS_ASSERT_ERROR_IS_CLEAR(error);\n\n _DBUS_ZERO (addr);\n addr.sun_family = AF_UNIX;\n path_len = strlen (path);\n\n if (abstract)\n {\n#ifdef HAVE_ABSTRACT_SOCKETS\n /* remember that abstract names aren't nul-terminated so we rely\n * on sun_path being filled in with zeroes above.\n */\n addr.sun_path[0] = '\\0'; /* this is what says \"use abstract\" */\n path_len++; /* Account for the extra nul byte added to the start of sun_path */\n\n if (path_len > _DBUS_MAX_SUN_PATH_LENGTH)\n {\n dbus_set_error (error, DBUS_ERROR_BAD_ADDRESS,\n \"Abstract socket name too long\\n\");\n _dbus_close (listen_fd, NULL);\n return -1;\n\t}\n\n strncpy (&addr.sun_path[1], path, path_len);\n /* _dbus_verbose_bytes (addr.sun_path, sizeof (addr.sun_path)); */\n#else /* HAVE_ABSTRACT_SOCKETS */\n dbus_set_error (error, DBUS_ERROR_NOT_SUPPORTED,\n \"Operating system does not support abstract socket namespace\\n\");\n _dbus_close (listen_fd, NULL);\n return -1;\n#endif /* ! HAVE_ABSTRACT_SOCKETS */\n }\n else\n {\n /* Discussed security implications of this with Nalin,\n * and we couldn't think of where it would kick our ass, but\n * it still seems a bit sucky. It also has non-security suckage;\n * really we'd prefer to exit if the socket is already in use.\n * But there doesn't seem to be a good way to do this.\n *\n * Just to be extra careful, I threw in the stat() - clearly\n * the stat() can't *fix* any security issue, but it at least\n * avoids inadvertent/accidental data loss.\n */\n {\n struct stat sb;\n\n if (stat (path, &sb) == 0 &&\n S_ISSOCK (sb.st_mode))\n unlink (path);\n }\n\n if (path_len > _DBUS_MAX_SUN_PATH_LENGTH)\n {\n dbus_set_error (error, DBUS_ERROR_BAD_ADDRESS,\n \"Abstract socket name too long\\n\");\n _dbus_close (listen_fd, NULL);\n return -1;\n\t}\n\n strncpy (addr.sun_path, path, path_len);\n }\n\n reuseaddr = 1;\n if (setsockopt (listen_fd, SOL_SOCKET, SO_REUSEADDR, &reuseaddr, sizeof(reuseaddr))==-1)\n {\n _dbus_warn (\"Failed to set socket option\\\"%s\\\": %s\",\n path, _dbus_strerror (errno));\n }\n\n if (bind (listen_fd, (struct sockaddr*) &addr, _DBUS_STRUCT_OFFSET (struct sockaddr_un, sun_path) + path_len) < 0)\n {\n dbus_set_error (error, _dbus_error_from_errno (errno),\n \"Failed to bind socket \\\"%s\\\": %s\",\n path, _dbus_strerror (errno));\n _dbus_close (listen_fd, NULL);\n return -1;\n }\n\n if (listen (listen_fd, 30 /* backlog */) < 0)\n {\n dbus_set_error (error, _dbus_error_from_errno (errno),\n \"Failed to listen on socket \\\"%s\\\": %s\",\n path, _dbus_strerror (errno));\n _dbus_close (listen_fd, NULL);\n return -1;\n }\n\n if (!_dbus_set_local_creds (listen_fd, TRUE))\n {\n dbus_set_error (error, _dbus_error_from_errno (errno),\n \"Failed to enable LOCAL_CREDS on socket \\\"%s\\\": %s\",\n path, _dbus_strerror (errno));\n close (listen_fd);\n return -1;\n }\n\n if (!_dbus_set_fd_nonblocking (listen_fd, error))\n {\n _DBUS_ASSERT_ERROR_IS_SET (error);\n _dbus_close (listen_fd, NULL);\n return -1;\n }\n\n /* Try opening up the permissions, but if we can't, just go ahead\n * and continue, maybe it will be good enough.\n */\n if (!abstract && chmod (path, 0777) < 0)\n _dbus_warn (\"Could not set mode 0777 on socket %s\\n\",\n path);\n\n return listen_fd;\n}\n", + "line": null, + "label": 0, + "cwe": "CWE-20", + "cve": "CVE-2013-2168", + "length": 1043 + }, + { + "index": 3021, + "code": "void vga_mem_writeb(VGACommonState *s, hwaddr addr, uint32_t val)\n{\n int memory_map_mode, plane, write_mode, b, func_select, mask;\n uint32_t write_mask, bit_mask, set_mask;\n\n#ifdef DEBUG_VGA_MEM\n printf(\"vga: [0x\" TARGET_FMT_plx \"] = 0x%02x\\n\", addr, val);\n#endif\n /* convert to VGA memory offset */\n memory_map_mode = (s->gr[VGA_GFX_MISC] >> 2) & 3;\n addr &= 0x1ffff;\n switch(memory_map_mode) {\n case 0:\n break;\n case 1:\n if (addr >= 0x10000)\n return;\n addr += s->bank_offset;\n break;\n case 2:\n addr -= 0x10000;\n if (addr >= 0x8000)\n return;\n break;\n default:\n case 3:\n addr -= 0x18000;\n if (addr >= 0x8000)\n return;\n break;\n }\n\n if (sr(s, VGA_SEQ_MEMORY_MODE) & VGA_SR04_CHN_4M) {\n /* chain 4 mode : simplest access */\n plane = addr & 3;\n mask = (1 << plane);\n if (sr(s, VGA_SEQ_PLANE_WRITE) & mask) {\n assert(addr < s->vram_size);\n s->vram_ptr[addr] = val;\n#ifdef DEBUG_VGA_MEM\n printf(\"vga: chain4: [0x\" TARGET_FMT_plx \"]\\n\", addr);\n#endif\n s->plane_updated |= mask; /* only used to detect font change */\n memory_region_set_dirty(&s->vram, addr, 1);\n }\n } else if (s->gr[VGA_GFX_MODE] & 0x10) {\n /* odd/even mode (aka text mode mapping) */\n plane = (s->gr[VGA_GFX_PLANE_READ] & 2) | (addr & 1);\n mask = (1 << plane);\n if (sr(s, VGA_SEQ_PLANE_WRITE) & mask) {\n addr = ((addr & ~1) << 1) | plane;\n if (addr >= s->vram_size) {\n return;\n }\n s->vram_ptr[addr] = val;\n#ifdef DEBUG_VGA_MEM\n printf(\"vga: odd/even: [0x\" TARGET_FMT_plx \"]\\n\", addr);\n#endif\n s->plane_updated |= mask; /* only used to detect font change */\n memory_region_set_dirty(&s->vram, addr, 1);\n }\n } else {\n /* standard VGA latched access */\n write_mode = s->gr[VGA_GFX_MODE] & 3;\n switch(write_mode) {\n default:\n case 0:\n /* rotate */\n b = s->gr[VGA_GFX_DATA_ROTATE] & 7;\n val = ((val >> b) | (val << (8 - b))) & 0xff;\n val |= val << 8;\n val |= val << 16;\n\n /* apply set/reset mask */\n set_mask = mask16[s->gr[VGA_GFX_SR_ENABLE]];\n val = (val & ~set_mask) |\n (mask16[s->gr[VGA_GFX_SR_VALUE]] & set_mask);\n bit_mask = s->gr[VGA_GFX_BIT_MASK];\n break;\n case 1:\n val = s->latch;\n goto do_write;\n case 2:\n val = mask16[val & 0x0f];\n bit_mask = s->gr[VGA_GFX_BIT_MASK];\n break;\n case 3:\n /* rotate */\n b = s->gr[VGA_GFX_DATA_ROTATE] & 7;\n val = (val >> b) | (val << (8 - b));\n\n bit_mask = s->gr[VGA_GFX_BIT_MASK] & val;\n val = mask16[s->gr[VGA_GFX_SR_VALUE]];\n break;\n }\n\n /* apply logical operation */\n func_select = s->gr[VGA_GFX_DATA_ROTATE] >> 3;\n switch(func_select) {\n case 0:\n default:\n /* nothing to do */\n break;\n case 1:\n /* and */\n val &= s->latch;\n break;\n case 2:\n /* or */\n val |= s->latch;\n break;\n case 3:\n /* xor */\n val ^= s->latch;\n break;\n }\n\n /* apply bit mask */\n bit_mask |= bit_mask << 8;\n bit_mask |= bit_mask << 16;\n val = (val & bit_mask) | (s->latch & ~bit_mask);\n\n do_write:\n /* mask data according to sr[2] */\n mask = sr(s, VGA_SEQ_PLANE_WRITE);\n s->plane_updated |= mask; /* only used to detect font change */\n write_mask = mask16[mask];\n if (addr * sizeof(uint32_t) >= s->vram_size) {\n return;\n }\n ((uint32_t *)s->vram_ptr)[addr] =\n (((uint32_t *)s->vram_ptr)[addr] & ~write_mask) |\n (val & write_mask);\n#ifdef DEBUG_VGA_MEM\n printf(\"vga: latch: [0x\" TARGET_FMT_plx \"] mask=0x%08x val=0x%08x\\n\",\n addr * 4, write_mask, val);\n#endif\n memory_region_set_dirty(&s->vram, addr << 2, sizeof(uint32_t));\n }\n}\n", + "line": null, + "label": 0, + "cwe": "CWE-617", + "cve": "CVE-2017-13673", + "length": 1243 + }, + { + "index": 70035, + "code": "void initServer(void) {\n int j;\n\n signal(SIGHUP, SIG_IGN);\n signal(SIGPIPE, SIG_IGN);\n setupSignalHandlers();\n\n if (server.syslog_enabled) {\n openlog(server.syslog_ident, LOG_PID | LOG_NDELAY | LOG_NOWAIT,\n server.syslog_facility);\n }\n\n server.pid = getpid();\n server.current_client = NULL;\n server.clients = listCreate();\n server.clients_to_close = listCreate();\n server.slaves = listCreate();\n server.monitors = listCreate();\n server.clients_pending_write = listCreate();\n server.slaveseldb = -1; /* Force to emit the first SELECT command. */\n server.unblocked_clients = listCreate();\n server.ready_keys = listCreate();\n server.clients_waiting_acks = listCreate();\n server.get_ack_from_slaves = 0;\n server.clients_paused = 0;\n server.system_memory_size = zmalloc_get_memory_size();\n\n createSharedObjects();\n adjustOpenFilesLimit();\n server.el = aeCreateEventLoop(server.maxclients+CONFIG_FDSET_INCR);\n server.db = zmalloc(sizeof(redisDb)*server.dbnum);\n\n /* Open the TCP listening socket for the user commands. */\n if (server.port != 0 &&\n listenToPort(server.port,server.ipfd,&server.ipfd_count) == C_ERR)\n exit(1);\n\n /* Open the listening Unix domain socket. */\n if (server.unixsocket != NULL) {\n unlink(server.unixsocket); /* don't care if this fails */\n server.sofd = anetUnixServer(server.neterr,server.unixsocket,\n server.unixsocketperm, server.tcp_backlog);\n if (server.sofd == ANET_ERR) {\n serverLog(LL_WARNING, \"Opening Unix socket: %s\", server.neterr);\n exit(1);\n }\n anetNonBlock(NULL,server.sofd);\n }\n\n /* Abort if there are no listening sockets at all. */\n if (server.ipfd_count == 0 && server.sofd < 0) {\n serverLog(LL_WARNING, \"Configured to not listen anywhere, exiting.\");\n exit(1);\n }\n\n /* Create the Redis databases, and initialize other internal state. */\n for (j = 0; j < server.dbnum; j++) {\n server.db[j].dict = dictCreate(&dbDictType,NULL);\n server.db[j].expires = dictCreate(&keyptrDictType,NULL);\n server.db[j].blocking_keys = dictCreate(&keylistDictType,NULL);\n server.db[j].ready_keys = dictCreate(&setDictType,NULL);\n server.db[j].watched_keys = dictCreate(&keylistDictType,NULL);\n server.db[j].eviction_pool = evictionPoolAlloc();\n server.db[j].id = j;\n server.db[j].avg_ttl = 0;\n }\n server.pubsub_channels = dictCreate(&keylistDictType,NULL);\n server.pubsub_patterns = listCreate();\n listSetFreeMethod(server.pubsub_patterns,freePubsubPattern);\n listSetMatchMethod(server.pubsub_patterns,listMatchPubsubPattern);\n server.cronloops = 0;\n server.rdb_child_pid = -1;\n server.aof_child_pid = -1;\n server.rdb_child_type = RDB_CHILD_TYPE_NONE;\n server.rdb_bgsave_scheduled = 0;\n aofRewriteBufferReset();\n server.aof_buf = sdsempty();\n server.lastsave = time(NULL); /* At startup we consider the DB saved. */\n server.lastbgsave_try = 0; /* At startup we never tried to BGSAVE. */\n server.rdb_save_time_last = -1;\n server.rdb_save_time_start = -1;\n server.dirty = 0;\n resetServerStats();\n /* A few stats we don't want to reset: server startup time, and peak mem. */\n server.stat_starttime = time(NULL);\n server.stat_peak_memory = 0;\n server.resident_set_size = 0;\n server.lastbgsave_status = C_OK;\n server.aof_last_write_status = C_OK;\n server.aof_last_write_errno = 0;\n server.repl_good_slaves_count = 0;\n updateCachedTime();\n\n /* Create the serverCron() time event, that's our main way to process\n * background operations. */\n if(aeCreateTimeEvent(server.el, 1, serverCron, NULL, NULL) == AE_ERR) {\n serverPanic(\"Can't create the serverCron time event.\");\n exit(1);\n }\n\n /* Create an event handler for accepting new connections in TCP and Unix\n * domain sockets. */\n for (j = 0; j < server.ipfd_count; j++) {\n if (aeCreateFileEvent(server.el, server.ipfd[j], AE_READABLE,\n acceptTcpHandler,NULL) == AE_ERR)\n {\n serverPanic(\n \"Unrecoverable error creating server.ipfd file event.\");\n }\n }\n if (server.sofd > 0 && aeCreateFileEvent(server.el,server.sofd,AE_READABLE,\n acceptUnixHandler,NULL) == AE_ERR) serverPanic(\"Unrecoverable error creating server.sofd file event.\");\n\n /* Open the AOF file if needed. */\n if (server.aof_state == AOF_ON) {\n server.aof_fd = open(server.aof_filename,\n O_WRONLY|O_APPEND|O_CREAT,0644);\n if (server.aof_fd == -1) {\n serverLog(LL_WARNING, \"Can't open the append-only file: %s\",\n strerror(errno));\n exit(1);\n }\n }\n\n /* 32 bit instances are limited to 4GB of address space, so if there is\n * no explicit limit in the user provided configuration we set a limit\n * at 3 GB using maxmemory with 'noeviction' policy'. This avoids\n * useless crashes of the Redis instance for out of memory. */\n if (server.arch_bits == 32 && server.maxmemory == 0) {\n serverLog(LL_WARNING,\"Warning: 32 bit instance detected but no memory limit set. Setting 3 GB maxmemory limit with 'noeviction' policy now.\");\n server.maxmemory = 3072LL*(1024*1024); /* 3 GB */\n server.maxmemory_policy = MAXMEMORY_NO_EVICTION;\n }\n\n if (server.cluster_enabled) clusterInit();\n replicationScriptCacheInit();\n scriptingInit(1);\n slowlogInit();\n latencyMonitorInit();\n bioInit();\n}\n", + "line": null, + "label": 0, + "cwe": "CWE-254", + "cve": "CVE-2016-10517", + "length": 1424 + }, + { + "index": 97610, + "code": "xmlXPathCompOpEvalPositionalPredicate(xmlXPathParserContextPtr ctxt,\n\t\t\t\t xmlXPathStepOpPtr op,\n\t\t\t\t xmlNodeSetPtr set,\n\t\t\t\t int contextSize,\n\t\t\t\t int minPos,\n\t\t\t\t int maxPos,\n\t\t\t\t int hasNsNodes)\n{\n if (op->ch1 != -1) {\n\txmlXPathCompExprPtr comp = ctxt->comp;\n\tif (comp->steps[op->ch1].op != XPATH_OP_PREDICATE) {\n\t /*\n\t * TODO: raise an internal error.\n\t */\n\t}\n\tcontextSize = xmlXPathCompOpEvalPredicate(ctxt,\n\t &comp->steps[op->ch1], set, contextSize, hasNsNodes);\n\tCHECK_ERROR0;\n\tif (contextSize <= 0)\n\t return(0);\n }\n /*\n * Check if the node set contains a sufficient number of nodes for\n * the requested range.\n */\n if (contextSize < minPos) {\n\txmlXPathNodeSetClear(set, hasNsNodes);\n\treturn(0);\n }\n if (op->ch2 == -1) {\n\t/*\n\t* TODO: Can this ever happen?\n\t*/\n\treturn (contextSize);\n } else {\n\txmlDocPtr oldContextDoc;\n\tint i, pos = 0, newContextSize = 0, contextPos = 0, res;\n\txmlXPathStepOpPtr exprOp;\n\txmlXPathObjectPtr contextObj = NULL, exprRes = NULL;\n\txmlNodePtr oldContextNode, contextNode = NULL;\n\txmlXPathContextPtr xpctxt = ctxt->context;\n\n#ifdef LIBXML_XPTR_ENABLED\n\t /*\n\t * URGENT TODO: Check the following:\n\t * We don't expect location sets if evaluating prediates, right?\n\t * Only filters should expect location sets, right?\n\t*/\n#endif /* LIBXML_XPTR_ENABLED */\n\n\t/*\n\t* Save old context.\n\t*/\n\toldContextNode = xpctxt->node;\n\toldContextDoc = xpctxt->doc;\n\t/*\n\t* Get the expression of this predicate.\n\t*/\n\texprOp = &ctxt->comp->steps[op->ch2];\n\tfor (i = 0; i < set->nodeNr; i++) {\n\t if (set->nodeTab[i] == NULL)\n\t\tcontinue;\n\n\t contextNode = set->nodeTab[i];\n\t xpctxt->node = contextNode;\n\t xpctxt->contextSize = contextSize;\n\t xpctxt->proximityPosition = ++contextPos;\n\n\t /*\n\t * Initialize the new set.\n\t * Also set the xpath document in case things like\n\t * key() evaluation are attempted on the predicate\n\t */\n\t if ((contextNode->type != XML_NAMESPACE_DECL) &&\n\t\t(contextNode->doc != NULL))\n\t\txpctxt->doc = contextNode->doc;\n\t /*\n\t * Evaluate the predicate expression with 1 context node\n\t * at a time; this node is packaged into a node set; this\n\t * node set is handed over to the evaluation mechanism.\n\t */\n\t if (contextObj == NULL)\n\t\tcontextObj = xmlXPathCacheNewNodeSet(xpctxt, contextNode);\n\t else\n\t\txmlXPathNodeSetAddUnique(contextObj->nodesetval,\n\t\t contextNode);\n\n\t valuePush(ctxt, contextObj);\n\t res = xmlXPathCompOpEvalToBoolean(ctxt, exprOp, 1);\n\n\t if ((ctxt->error != XPATH_EXPRESSION_OK) || (res == -1)) {\n\t xmlXPathObjectPtr tmp;\n\t\t/* pop the result */\n\t\ttmp = valuePop(ctxt);\n\t\txmlXPathReleaseObject(xpctxt, tmp);\n\t\t/* then pop off contextObj, which will be freed later */\n\t\tvaluePop(ctxt);\n\t\tgoto evaluation_error;\n\t }\n\n\t if (res)\n\t\tpos++;\n\n\t if (res && (pos >= minPos) && (pos <= maxPos)) {\n\t\t/*\n\t\t* Fits in the requested range.\n\t\t*/\n\t\tnewContextSize++;\n\t\tif (minPos == maxPos) {\n\t\t /*\n\t\t * Only 1 node was requested.\n\t\t */\n\t\t if (contextNode->type == XML_NAMESPACE_DECL) {\n\t\t\t/*\n\t\t\t* As always: take care of those nasty\n\t\t\t* namespace nodes.\n\t\t\t*/\n\t\t\tset->nodeTab[i] = NULL;\n\t\t }\n\t\t xmlXPathNodeSetClear(set, hasNsNodes);\n\t\t set->nodeNr = 1;\n\t\t set->nodeTab[0] = contextNode;\n\t\t goto evaluation_exit;\n\t\t}\n\t\tif (pos == maxPos) {\n\t\t /*\n\t\t * We are done.\n\t\t */\n\t\t xmlXPathNodeSetClearFromPos(set, i +1, hasNsNodes);\n\t\t goto evaluation_exit;\n\t\t}\n\t } else {\n\t\t/*\n\t\t* Remove the entry from the initial node set.\n\t\t*/\n\t\tset->nodeTab[i] = NULL;\n\t\tif (contextNode->type == XML_NAMESPACE_DECL)\n\t\t xmlXPathNodeSetFreeNs((xmlNsPtr) contextNode);\n\t }\n\t if (exprRes != NULL) {\n\t\txmlXPathReleaseObject(ctxt->context, exprRes);\n\t\texprRes = NULL;\n\t }\n\t if (ctxt->value == contextObj) {\n\t\t/*\n\t\t* Don't free the temporary XPath object holding the\n\t\t* context node, in order to avoid massive recreation\n\t\t* inside this loop.\n\t\t*/\n\t\tvaluePop(ctxt);\n\t\txmlXPathNodeSetClear(contextObj->nodesetval, hasNsNodes);\n\t } else {\n\t\t/*\n\t\t* The object was lost in the evaluation machinery.\n\t\t* Can this happen? Maybe in case of internal-errors.\n\t\t*/\n\t\tcontextObj = NULL;\n\t }\n\t}\n\tgoto evaluation_exit;\n\nevaluation_error:\n\txmlXPathNodeSetClear(set, hasNsNodes);\n\tnewContextSize = 0;\n\nevaluation_exit:\n\tif (contextObj != NULL) {\n\t if (ctxt->value == contextObj)\n\t\tvaluePop(ctxt);\n\t xmlXPathReleaseObject(xpctxt, contextObj);\n\t}\n\tif (exprRes != NULL)\n\t xmlXPathReleaseObject(ctxt->context, exprRes);\n\t/*\n\t* Reset/invalidate the context.\n\t*/\n\txpctxt->node = oldContextNode;\n\txpctxt->doc = oldContextDoc;\n\txpctxt->contextSize = -1;\n\txpctxt->proximityPosition = -1;\n\treturn(newContextSize);\n }\n return(contextSize);\n}\n", + "line": null, + "label": 0, + "cwe": null, + "cve": null, + "length": 1345 + }, + { + "index": 24951, + "code": "CIFSGetDFSRefer(const int xid, struct cifs_ses *ses,\n\t\tconst unsigned char *searchName,\n\t\tstruct dfs_info3_param **target_nodes,\n\t\tunsigned int *num_of_nodes,\n\t\tconst struct nls_table *nls_codepage, int remap)\n{\n/* TRANS2_GET_DFS_REFERRAL */\n\tTRANSACTION2_GET_DFS_REFER_REQ *pSMB = NULL;\n\tTRANSACTION2_GET_DFS_REFER_RSP *pSMBr = NULL;\n\tint rc = 0;\n\tint bytes_returned;\n\tint name_len;\n\t__u16 params, byte_count;\n\t*num_of_nodes = 0;\n\t*target_nodes = NULL;\n\n\tcFYI(1, \"In GetDFSRefer the path %s\", searchName);\n\tif (ses == NULL)\n\t\treturn -ENODEV;\ngetDFSRetry:\n\trc = smb_init(SMB_COM_TRANSACTION2, 15, NULL, (void **) &pSMB,\n\t\t (void **) &pSMBr);\n\tif (rc)\n\t\treturn rc;\n\n\t/* server pointer checked in called function,\n\tbut should never be null here anyway */\n\tpSMB->hdr.Mid = GetNextMid(ses->server);\n\tpSMB->hdr.Tid = ses->ipc_tid;\n\tpSMB->hdr.Uid = ses->Suid;\n\tif (ses->capabilities & CAP_STATUS32)\n\t\tpSMB->hdr.Flags2 |= SMBFLG2_ERR_STATUS;\n\tif (ses->capabilities & CAP_DFS)\n\t\tpSMB->hdr.Flags2 |= SMBFLG2_DFS;\n\n\tif (ses->capabilities & CAP_UNICODE) {\n\t\tpSMB->hdr.Flags2 |= SMBFLG2_UNICODE;\n\t\tname_len =\n\t\t cifsConvertToUCS((__le16 *) pSMB->RequestFileName,\n\t\t\t\t searchName, PATH_MAX, nls_codepage, remap);\n\t\tname_len++;\t/* trailing null */\n\t\tname_len *= 2;\n\t} else {\t/* BB improve the check for buffer overruns BB */\n\t\tname_len = strnlen(searchName, PATH_MAX);\n\t\tname_len++;\t/* trailing null */\n\t\tstrncpy(pSMB->RequestFileName, searchName, name_len);\n\t}\n\n\tif (ses->server) {\n\t\tif (ses->server->sec_mode &\n\t\t (SECMODE_SIGN_REQUIRED | SECMODE_SIGN_ENABLED))\n\t\t\tpSMB->hdr.Flags2 |= SMBFLG2_SECURITY_SIGNATURE;\n\t}\n\n\tpSMB->hdr.Uid = ses->Suid;\n\n\tparams = 2 /* level */ + name_len /*includes null */ ;\n\tpSMB->TotalDataCount = 0;\n\tpSMB->DataCount = 0;\n\tpSMB->DataOffset = 0;\n\tpSMB->MaxParameterCount = 0;\n\t/* BB find exact max SMB PDU from sess structure BB */\n\tpSMB->MaxDataCount = cpu_to_le16(4000);\n\tpSMB->MaxSetupCount = 0;\n\tpSMB->Reserved = 0;\n\tpSMB->Flags = 0;\n\tpSMB->Timeout = 0;\n\tpSMB->Reserved2 = 0;\n\tpSMB->ParameterOffset = cpu_to_le16(offsetof(\n\t struct smb_com_transaction2_get_dfs_refer_req, MaxReferralLevel) - 4);\n\tpSMB->SetupCount = 1;\n\tpSMB->Reserved3 = 0;\n\tpSMB->SubCommand = cpu_to_le16(TRANS2_GET_DFS_REFERRAL);\n\tbyte_count = params + 3 /* pad */ ;\n\tpSMB->ParameterCount = cpu_to_le16(params);\n\tpSMB->TotalParameterCount = pSMB->ParameterCount;\n\tpSMB->MaxReferralLevel = cpu_to_le16(3);\n\tinc_rfc1001_len(pSMB, byte_count);\n\tpSMB->ByteCount = cpu_to_le16(byte_count);\n\n\trc = SendReceive(xid, ses, (struct smb_hdr *) pSMB,\n\t\t\t (struct smb_hdr *) pSMBr, &bytes_returned, 0);\n\tif (rc) {\n\t\tcFYI(1, \"Send error in GetDFSRefer = %d\", rc);\n\t\tgoto GetDFSRefExit;\n\t}\n\trc = validate_t2((struct smb_t2_rsp *)pSMBr);\n\n\t/* BB Also check if enough total bytes returned? */\n\tif (rc || get_bcc(&pSMBr->hdr) < 17) {\n\t\trc = -EIO; /* bad smb */\n\t\tgoto GetDFSRefExit;\n\t}\n\n\tcFYI(1, \"Decoding GetDFSRefer response BCC: %d Offset %d\",\n\t\t\t\tget_bcc(&pSMBr->hdr),\n\t\t\t\tle16_to_cpu(pSMBr->t2.DataOffset));\n\n\t/* parse returned result into more usable form */\n\trc = parse_DFS_referrals(pSMBr, num_of_nodes,\n\t\t\t\t target_nodes, nls_codepage, remap,\n\t\t\t\t searchName);\n\nGetDFSRefExit:\n\tcifs_buf_release(pSMB);\n\n\tif (rc == -EAGAIN)\n\t\tgoto getDFSRetry;\n\n\treturn rc;\n}\n", + "line": null, + "label": 0, + "cwe": "CWE-189", + "cve": "CVE-2011-3191", + "length": 1079 + }, + { + "index": 119639, + "code": "InlineIterator RenderBlock::LineBreaker::nextSegmentBreak(InlineBidiResolver& resolver, LineInfo& lineInfo, RenderTextInfo& renderTextInfo, FloatingObject* lastFloatFromPreviousLine, unsigned consecutiveHyphenatedLines, WordMeasurements& wordMeasurements)\n{\n reset();\n\n ASSERT(resolver.position().root() == m_block);\n\n bool appliedStartWidth = resolver.position().m_pos > 0;\n bool includeEndWidth = true;\n LineMidpointState& lineMidpointState = resolver.midpointState();\n\n LineWidth width(m_block, lineInfo.isFirstLine(), requiresIndent(lineInfo.isFirstLine(), lineInfo.previousLineBrokeCleanly(), m_block->style()));\n\n skipLeadingWhitespace(resolver, lineInfo, lastFloatFromPreviousLine, width);\n\n if (resolver.position().atEnd())\n return resolver.position();\n\n bool ignoringSpaces = false;\n InlineIterator ignoreStart;\n\n bool currentCharacterIsSpace = false;\n bool currentCharacterShouldCollapseIfPreWap = false;\n TrailingObjects trailingObjects;\n\n InlineIterator lBreak = resolver.position();\n\n InlineIterator current = resolver.position();\n RenderObject* last = current.m_obj;\n bool atStart = true;\n\n bool startingNewParagraph = lineInfo.previousLineBrokeCleanly();\n lineInfo.setPreviousLineBrokeCleanly(false);\n\n bool autoWrapWasEverTrueOnLine = false;\n bool floatsFitOnLine = true;\n\n RenderStyle* blockStyle = m_block->style();\n bool allowImagesToBreak = !m_block->document().inQuirksMode() || !m_block->isTableCell() || !blockStyle->logicalWidth().isIntrinsicOrAuto();\n\n EWhiteSpace currWS = blockStyle->whiteSpace();\n EWhiteSpace lastWS = currWS;\n while (current.m_obj) {\n RenderStyle* currentStyle = current.m_obj->style();\n RenderObject* next = bidiNextSkippingEmptyInlines(m_block, current.m_obj);\n if (next && next->parent() && !next->parent()->isDescendantOf(current.m_obj->parent()))\n includeEndWidth = true;\n\n currWS = current.m_obj->isReplaced() ? current.m_obj->parent()->style()->whiteSpace() : currentStyle->whiteSpace();\n lastWS = last->isReplaced() ? last->parent()->style()->whiteSpace() : last->style()->whiteSpace();\n\n bool autoWrap = RenderStyle::autoWrap(currWS);\n autoWrapWasEverTrueOnLine = autoWrapWasEverTrueOnLine || autoWrap;\n\n bool preserveNewline = current.m_obj->isSVGInlineText() ? false : RenderStyle::preserveNewline(currWS);\n\n bool collapseWhiteSpace = RenderStyle::collapseWhiteSpace(currWS);\n\n if (current.m_obj->isBR()) {\n if (width.fitsOnLine()) {\n lBreak.moveToStartOf(current.m_obj);\n lBreak.increment();\n\n if (startingNewParagraph)\n lineInfo.setEmpty(false, m_block, &width);\n trailingObjects.clear();\n lineInfo.setPreviousLineBrokeCleanly(true);\n\n if (ignoringSpaces && currentStyle->clear() != CNONE)\n ensureLineBoxInsideIgnoredSpaces(lineMidpointState, current.m_obj);\n\n if (!lineInfo.isEmpty())\n m_clear = currentStyle->clear();\n }\n goto end;\n }\n\n if (current.m_obj->isOutOfFlowPositioned()) {\n RenderBox* box = toRenderBox(current.m_obj);\n bool isInlineType = box->style()->isOriginalDisplayInlineType();\n if (!isInlineType)\n m_block->setStaticInlinePositionForChild(box, m_block->logicalHeight(), m_block->startOffsetForContent(m_block->logicalHeight()));\n else {\n box->layer()->setStaticBlockPosition(m_block->logicalHeight());\n }\n\n if (isInlineType || current.m_obj->container()->isRenderInline()) {\n if (ignoringSpaces)\n ensureLineBoxInsideIgnoredSpaces(lineMidpointState, current.m_obj);\n trailingObjects.appendBoxIfNeeded(box);\n } else\n m_positionedObjects.append(box);\n width.addUncommittedWidth(inlineLogicalWidth(current.m_obj));\n renderTextInfo.m_lineBreakIterator.resetPriorContext();\n } else if (current.m_obj->isFloating()) {\n RenderBox* floatBox = toRenderBox(current.m_obj);\n FloatingObject* f = m_block->insertFloatingObject(floatBox);\n if (floatsFitOnLine && width.fitsOnLine(f->logicalWidth(m_block->isHorizontalWritingMode()))) {\n m_block->positionNewFloatOnLine(f, lastFloatFromPreviousLine, lineInfo, width);\n if (lBreak.m_obj == current.m_obj) {\n ASSERT(!lBreak.m_pos);\n lBreak.increment();\n }\n } else\n floatsFitOnLine = false;\n renderTextInfo.m_lineBreakIterator.updatePriorContext(replacementCharacter);\n } else if (current.m_obj->isRenderInline()) {\n ASSERT(isEmptyInline(current.m_obj));\n\n RenderInline* flowBox = toRenderInline(current.m_obj);\n\n bool requiresLineBox = alwaysRequiresLineBox(current.m_obj);\n if (requiresLineBox || requiresLineBoxForContent(flowBox, lineInfo)) {\n if (requiresLineBox)\n lineInfo.setEmpty(false, m_block, &width);\n if (ignoringSpaces) {\n trailingObjects.clear();\n ensureLineBoxInsideIgnoredSpaces(lineMidpointState, current.m_obj);\n } else if (blockStyle->collapseWhiteSpace() && resolver.position().m_obj == current.m_obj\n && shouldSkipWhitespaceAfterStartObject(m_block, current.m_obj, lineMidpointState)) {\n currentCharacterShouldCollapseIfPreWap = currentCharacterIsSpace = true;\n ignoringSpaces = true;\n }\n }\n\n width.addUncommittedWidth(inlineLogicalWidth(current.m_obj) + borderPaddingMarginStart(flowBox) + borderPaddingMarginEnd(flowBox));\n } else if (current.m_obj->isReplaced()) {\n RenderBox* replacedBox = toRenderBox(current.m_obj);\n\n if (atStart)\n width.updateAvailableWidth(replacedBox->logicalHeight());\n\n if ((autoWrap || RenderStyle::autoWrap(lastWS)) && (!current.m_obj->isImage() || allowImagesToBreak)) {\n width.commit();\n lBreak.moveToStartOf(current.m_obj);\n }\n\n if (ignoringSpaces)\n stopIgnoringSpaces(lineMidpointState, InlineIterator(0, current.m_obj, 0));\n\n lineInfo.setEmpty(false, m_block, &width);\n ignoringSpaces = false;\n currentCharacterShouldCollapseIfPreWap = currentCharacterIsSpace = false;\n trailingObjects.clear();\n\n LayoutUnit replacedLogicalWidth = m_block->logicalWidthForChild(replacedBox) + m_block->marginStartForChild(replacedBox) + m_block->marginEndForChild(replacedBox) + inlineLogicalWidth(current.m_obj);\n if (current.m_obj->isListMarker()) {\n if (blockStyle->collapseWhiteSpace() && shouldSkipWhitespaceAfterStartObject(m_block, current.m_obj, lineMidpointState)) {\n currentCharacterShouldCollapseIfPreWap = currentCharacterIsSpace = true;\n ignoringSpaces = true;\n }\n if (toRenderListMarker(current.m_obj)->isInside())\n width.addUncommittedWidth(replacedLogicalWidth);\n } else\n width.addUncommittedWidth(replacedLogicalWidth);\n if (current.m_obj->isRubyRun())\n width.applyOverhang(toRenderRubyRun(current.m_obj), last, next);\n renderTextInfo.m_lineBreakIterator.updatePriorContext(replacementCharacter);\n } else if (current.m_obj->isText()) {\n if (!current.m_pos)\n appliedStartWidth = false;\n\n RenderText* t = toRenderText(current.m_obj);\n\n bool isSVGText = t->isSVGInlineText();\n\n if (t->style()->hasTextCombine() && current.m_obj->isCombineText() && !toRenderCombineText(current.m_obj)->isCombined()) {\n RenderCombineText* combineRenderer = toRenderCombineText(current.m_obj);\n combineRenderer->combineText();\n if (iteratorIsBeyondEndOfRenderCombineText(lBreak, combineRenderer)) {\n ASSERT(iteratorIsBeyondEndOfRenderCombineText(resolver.position(), combineRenderer));\n lBreak.increment();\n resolver.increment();\n }\n }\n\n RenderStyle* style = t->style(lineInfo.isFirstLine());\n const Font& f = style->font();\n bool isFixedPitch = f.isFixedPitch();\n\n unsigned lastSpace = current.m_pos;\n float wordSpacing = currentStyle->wordSpacing();\n float lastSpaceWordSpacing = 0;\n float wordSpacingForWordMeasurement = 0;\n\n float wrapW = width.uncommittedWidth() + inlineLogicalWidth(current.m_obj, !appliedStartWidth, true);\n float charWidth = 0;\n bool breakWords = currentStyle->breakWords() && ((autoWrap && !width.committedWidth()) || currWS == PRE);\n bool midWordBreak = false;\n bool breakAll = currentStyle->wordBreak() == BreakAllWordBreak && autoWrap;\n float hyphenWidth = 0;\n\n if (isSVGText) {\n breakWords = false;\n breakAll = false;\n }\n\n if (t->isWordBreak()) {\n width.commit();\n lBreak.moveToStartOf(current.m_obj);\n ASSERT(current.m_pos == t->textLength());\n }\n\n if (renderTextInfo.m_text != t) {\n renderTextInfo.m_text = t;\n renderTextInfo.m_font = &f;\n renderTextInfo.m_layout = f.createLayout(t, width.currentWidth(), collapseWhiteSpace);\n renderTextInfo.m_lineBreakIterator.resetStringAndReleaseIterator(t->text(), style->locale());\n } else if (renderTextInfo.m_layout && renderTextInfo.m_font != &f) {\n renderTextInfo.m_font = &f;\n renderTextInfo.m_layout = f.createLayout(t, width.currentWidth(), collapseWhiteSpace);\n }\n\n TextLayout* textLayout = renderTextInfo.m_layout.get();\n\n float wordTrailingSpaceWidth = (f.typesettingFeatures() & Kerning) && !textLayout ? f.width(constructTextRun(t, f, &space, 1, style)) + wordSpacing : 0;\n\n UChar lastCharacter = renderTextInfo.m_lineBreakIterator.lastCharacter();\n UChar secondToLastCharacter = renderTextInfo.m_lineBreakIterator.secondToLastCharacter();\n for (; current.m_pos < t->textLength(); current.fastIncrementInTextNode()) {\n bool previousCharacterIsSpace = currentCharacterIsSpace;\n bool previousCharacterShouldCollapseIfPreWap = currentCharacterShouldCollapseIfPreWap;\n UChar c = current.current();\n currentCharacterShouldCollapseIfPreWap = currentCharacterIsSpace = c == ' ' || c == '\\t' || (!preserveNewline && (c == '\\n'));\n\n if (!collapseWhiteSpace || !currentCharacterIsSpace)\n lineInfo.setEmpty(false, m_block, &width);\n\n if (c == softHyphen && autoWrap && !hyphenWidth) {\n hyphenWidth = measureHyphenWidth(t, f);\n width.addUncommittedWidth(hyphenWidth);\n }\n\n bool applyWordSpacing = false;\n\n if ((breakAll || breakWords) && !midWordBreak) {\n wrapW += charWidth;\n bool midWordBreakIsBeforeSurrogatePair = U16_IS_LEAD(c) && current.m_pos + 1 < t->textLength() && U16_IS_TRAIL((*t)[current.m_pos + 1]);\n charWidth = textWidth(t, current.m_pos, midWordBreakIsBeforeSurrogatePair ? 2 : 1, f, width.committedWidth() + wrapW, isFixedPitch, collapseWhiteSpace, 0, textLayout);\n midWordBreak = width.committedWidth() + wrapW + charWidth > width.availableWidth();\n }\n\n bool betweenWords = c == '\\n' || (currWS != PRE && !atStart && isBreakable(renderTextInfo.m_lineBreakIterator, current.m_pos, current.m_nextBreakablePosition));\n\n if (betweenWords || midWordBreak) {\n bool stoppedIgnoringSpaces = false;\n if (ignoringSpaces) {\n lastSpaceWordSpacing = 0;\n if (!currentCharacterIsSpace) {\n ignoringSpaces = false;\n wordSpacingForWordMeasurement = 0;\n lastSpace = current.m_pos; // e.g., \"Foo goo\", don't add in any of the ignored spaces.\n stopIgnoringSpaces(lineMidpointState, InlineIterator(0, current.m_obj, current.m_pos));\n stoppedIgnoringSpaces = true;\n } else {\n goto nextCharacter;\n }\n }\n\n wordMeasurements.grow(wordMeasurements.size() + 1);\n WordMeasurement& wordMeasurement = wordMeasurements.last();\n\n wordMeasurement.renderer = t;\n wordMeasurement.endOffset = current.m_pos;\n wordMeasurement.startOffset = lastSpace;\n\n float additionalTmpW;\n if (wordTrailingSpaceWidth && c == ' ')\n additionalTmpW = textWidth(t, lastSpace, current.m_pos + 1 - lastSpace, f, width.currentWidth(), isFixedPitch, collapseWhiteSpace, &wordMeasurement.fallbackFonts, textLayout) - wordTrailingSpaceWidth;\n else\n additionalTmpW = textWidth(t, lastSpace, current.m_pos - lastSpace, f, width.currentWidth(), isFixedPitch, collapseWhiteSpace, &wordMeasurement.fallbackFonts, textLayout);\n\n wordMeasurement.width = additionalTmpW + wordSpacingForWordMeasurement;\n additionalTmpW += lastSpaceWordSpacing;\n width.addUncommittedWidth(additionalTmpW);\n if (!appliedStartWidth) {\n width.addUncommittedWidth(inlineLogicalWidth(current.m_obj, true, false));\n appliedStartWidth = true;\n }\n\n applyWordSpacing = wordSpacing && currentCharacterIsSpace;\n\n if (!width.committedWidth() && autoWrap && !width.fitsOnLine())\n width.fitBelowFloats();\n\n if (autoWrap || breakWords) {\n bool lineWasTooWide = false;\n if (width.fitsOnLine() && currentCharacterIsSpace && currentStyle->breakOnlyAfterWhiteSpace() && !midWordBreak) {\n float charWidth = textWidth(t, current.m_pos, 1, f, width.currentWidth(), isFixedPitch, collapseWhiteSpace, &wordMeasurement.fallbackFonts, textLayout) + (applyWordSpacing ? wordSpacing : 0);\n if (!width.fitsOnLine(charWidth)) {\n lineWasTooWide = true;\n lBreak.moveTo(current.m_obj, current.m_pos, current.m_nextBreakablePosition);\n skipTrailingWhitespace(lBreak, lineInfo);\n }\n }\n if (lineWasTooWide || !width.fitsOnLine()) {\n if (lBreak.atTextParagraphSeparator()) {\n if (!stoppedIgnoringSpaces && current.m_pos > 0)\n ensureCharacterGetsLineBox(lineMidpointState, current);\n lBreak.increment();\n lineInfo.setPreviousLineBrokeCleanly(true);\n wordMeasurement.endOffset = lBreak.m_pos;\n }\n if (lBreak.m_obj && lBreak.m_pos && lBreak.m_obj->isText() && toRenderText(lBreak.m_obj)->textLength() && toRenderText(lBreak.m_obj)->characterAt(lBreak.m_pos - 1) == softHyphen)\n m_hyphenated = true;\n if (lBreak.m_pos && lBreak.m_pos != (unsigned)wordMeasurement.endOffset && !wordMeasurement.width) {\n if (charWidth) {\n wordMeasurement.endOffset = lBreak.m_pos;\n wordMeasurement.width = charWidth;\n }\n }\n if (ignoringSpaces || !collapseWhiteSpace || !currentCharacterIsSpace || !previousCharacterIsSpace)\n goto end;\n } else {\n if (!betweenWords || (midWordBreak && !autoWrap))\n width.addUncommittedWidth(-additionalTmpW);\n if (hyphenWidth) {\n width.addUncommittedWidth(-hyphenWidth);\n hyphenWidth = 0;\n }\n }\n }\n\n if (c == '\\n' && preserveNewline) {\n if (!stoppedIgnoringSpaces && current.m_pos > 0)\n ensureCharacterGetsLineBox(lineMidpointState, current);\n lBreak.moveTo(current.m_obj, current.m_pos, current.m_nextBreakablePosition);\n lBreak.increment();\n lineInfo.setPreviousLineBrokeCleanly(true);\n return lBreak;\n }\n\n if (autoWrap && betweenWords) {\n width.commit();\n wrapW = 0;\n lBreak.moveTo(current.m_obj, current.m_pos, current.m_nextBreakablePosition);\n breakWords = false;\n }\n\n if (midWordBreak && !U16_IS_TRAIL(c) && !(category(c) & (Mark_NonSpacing | Mark_Enclosing | Mark_SpacingCombining))) {\n lBreak.moveTo(current.m_obj, current.m_pos, current.m_nextBreakablePosition);\n midWordBreak &= (breakWords || breakAll);\n }\n\n if (betweenWords) {\n lastSpaceWordSpacing = applyWordSpacing ? wordSpacing : 0;\n wordSpacingForWordMeasurement = (applyWordSpacing && wordMeasurement.width) ? wordSpacing : 0;\n lastSpace = current.m_pos;\n }\n\n if (!ignoringSpaces && currentStyle->collapseWhiteSpace()) {\n if (currentCharacterIsSpace && previousCharacterIsSpace) {\n ignoringSpaces = true;\n\n startIgnoringSpaces(lineMidpointState, ignoreStart);\n trailingObjects.updateMidpointsForTrailingBoxes(lineMidpointState, InlineIterator(), TrailingObjects::DoNotCollapseFirstSpace);\n }\n }\n } else if (ignoringSpaces) {\n ignoringSpaces = false;\n lastSpaceWordSpacing = applyWordSpacing ? wordSpacing : 0;\n wordSpacingForWordMeasurement = (applyWordSpacing && wordMeasurements.last().width) ? wordSpacing : 0;\n lastSpace = current.m_pos; // e.g., \"Foo goo\", don't add in any of the ignored spaces.\n stopIgnoringSpaces(lineMidpointState, InlineIterator(0, current.m_obj, current.m_pos));\n }\n\n if (isSVGText && current.m_pos > 0) {\n if (toRenderSVGInlineText(t)->characterStartsNewTextChunk(current.m_pos))\n ensureCharacterGetsLineBox(lineMidpointState, current);\n }\n\n if (currentCharacterIsSpace && !previousCharacterIsSpace) {\n ignoreStart.m_obj = current.m_obj;\n ignoreStart.m_pos = current.m_pos;\n }\n\n if (!currentCharacterIsSpace && previousCharacterShouldCollapseIfPreWap) {\n if (autoWrap && currentStyle->breakOnlyAfterWhiteSpace())\n lBreak.moveTo(current.m_obj, current.m_pos, current.m_nextBreakablePosition);\n }\n\n if (collapseWhiteSpace && currentCharacterIsSpace && !ignoringSpaces)\n trailingObjects.setTrailingWhitespace(toRenderText(current.m_obj));\n else if (!currentStyle->collapseWhiteSpace() || !currentCharacterIsSpace)\n trailingObjects.clear();\n\n atStart = false;\n nextCharacter:\n secondToLastCharacter = lastCharacter;\n lastCharacter = c;\n }\n\n renderTextInfo.m_lineBreakIterator.setPriorContext(lastCharacter, secondToLastCharacter);\n\n wordMeasurements.grow(wordMeasurements.size() + 1);\n WordMeasurement& wordMeasurement = wordMeasurements.last();\n wordMeasurement.renderer = t;\n\n float additionalTmpW = ignoringSpaces ? 0 : textWidth(t, lastSpace, current.m_pos - lastSpace, f, width.currentWidth(), isFixedPitch, collapseWhiteSpace, &wordMeasurement.fallbackFonts, textLayout);\n wordMeasurement.startOffset = lastSpace;\n wordMeasurement.endOffset = current.m_pos;\n wordMeasurement.width = ignoringSpaces ? 0 : additionalTmpW + wordSpacingForWordMeasurement;\n additionalTmpW += lastSpaceWordSpacing;\n width.addUncommittedWidth(additionalTmpW + inlineLogicalWidth(current.m_obj, !appliedStartWidth, includeEndWidth));\n includeEndWidth = false;\n\n if (!width.fitsOnLine()) {\n if (!m_hyphenated && lBreak.previousInSameNode() == softHyphen)\n m_hyphenated = true;\n\n if (m_hyphenated)\n goto end;\n }\n } else\n ASSERT_NOT_REACHED();\n\n bool checkForBreak = autoWrap;\n if (width.committedWidth() && !width.fitsOnLine() && lBreak.m_obj && currWS == NOWRAP)\n checkForBreak = true;\n else if (next && current.m_obj->isText() && next->isText() && !next->isBR() && (autoWrap || next->style()->autoWrap())) {\n if (autoWrap && currentCharacterIsSpace)\n checkForBreak = true;\n else {\n RenderText* nextText = toRenderText(next);\n if (nextText->textLength()) {\n UChar c = nextText->characterAt(0);\n checkForBreak = !currentCharacterIsSpace && (c == ' ' || c == '\\t' || (c == '\\n' && !next->preservesNewline()));\n } else if (nextText->isWordBreak())\n checkForBreak = true;\n\n if (!width.fitsOnLine() && !width.committedWidth())\n width.fitBelowFloats();\n\n bool canPlaceOnLine = width.fitsOnLine() || !autoWrapWasEverTrueOnLine;\n if (canPlaceOnLine && checkForBreak) {\n width.commit();\n lBreak.moveToStartOf(next);\n }\n }\n }\n\n if (checkForBreak && !width.fitsOnLine()) {\n if (currentCharacterIsSpace && !ignoringSpaces && currentStyle->collapseWhiteSpace())\n trailingObjects.clear();\n\n if (width.committedWidth())\n goto end;\n\n width.fitBelowFloats();\n\n if (!width.fitsOnLine())\n goto end;\n } else if (blockStyle->autoWrap() && !width.fitsOnLine() && !width.committedWidth()) {\n width.fitBelowFloats();\n }\n\n if (!current.m_obj->isFloatingOrOutOfFlowPositioned()) {\n last = current.m_obj;\n if (last->isReplaced() && autoWrap && (!last->isImage() || allowImagesToBreak) && (!last->isListMarker() || toRenderListMarker(last)->isInside())) {\n width.commit();\n lBreak.moveToStartOf(next);\n }\n }\n\n if (!collapseWhiteSpace)\n currentCharacterIsSpace = false;\n\n current.moveToStartOf(next);\n atStart = false;\n }\n\n if (width.fitsOnLine() || lastWS == NOWRAP)\n lBreak.clear();\n\n end:\n ShapeInsideInfo* shapeInfo = m_block->layoutShapeInsideInfo();\n bool segmentAllowsOverflow = !shapeInfo || !shapeInfo->hasSegments();\n\n if (lBreak == resolver.position() && (!lBreak.m_obj || !lBreak.m_obj->isBR()) && segmentAllowsOverflow) {\n if (blockStyle->whiteSpace() == PRE && !current.m_pos) {\n lBreak.moveTo(last, last->isText() ? last->length() : 0);\n } else if (lBreak.m_obj) {\n lBreak.moveTo(current.m_obj, current.m_pos);\n }\n }\n\n if (lBreak == resolver.position() && segmentAllowsOverflow)\n lBreak.increment();\n\n checkMidpoints(lineMidpointState, lBreak);\n\n trailingObjects.updateMidpointsForTrailingBoxes(lineMidpointState, lBreak, TrailingObjects::CollapseFirstSpace);\n\n if (lBreak.m_pos > 0) {\n lBreak.m_pos--;\n lBreak.increment();\n }\n\n return lBreak;\n}\n", + "line": null, + "label": 0, + "cwe": "CWE-399", + "cve": "CVE-2013-2909", + "length": 5100 + }, + { + "index": 68128, + "code": "static int oidc_discovery(request_rec *r, oidc_cfg *cfg) {\n\n\toidc_debug(r, \"enter\");\n\n\t/* obtain the URL we're currently accessing, to be stored in the state/session */\n\tchar *current_url = oidc_get_current_url(r);\n\tconst char *method = oidc_original_request_method(r, cfg, FALSE);\n\n\t/* generate CSRF token */\n\tchar *csrf = NULL;\n\tif (oidc_proto_generate_nonce(r, &csrf, 8) == FALSE)\n\t\treturn HTTP_INTERNAL_SERVER_ERROR;\n\n\tchar *discover_url = oidc_cfg_dir_discover_url(r);\n\t/* see if there's an external discovery page configured */\n\tif (discover_url != NULL) {\n\n\t\t/* yes, assemble the parameters for external discovery */\n\t\tchar *url = apr_psprintf(r->pool, \"%s%s%s=%s&%s=%s&%s=%s&%s=%s\",\n\t\t\t\tdiscover_url, strchr(discover_url, '?') != NULL ? \"&\" : \"?\",\n\t\t\t\t\t\tOIDC_DISC_RT_PARAM, oidc_util_escape_string(r, current_url),\n\t\t\t\t\t\tOIDC_DISC_RM_PARAM, method,\n\t\t\t\t\t\tOIDC_DISC_CB_PARAM,\n\t\t\t\t\t\toidc_util_escape_string(r, cfg->redirect_uri),\n\t\t\t\t\t\tOIDC_CSRF_NAME, oidc_util_escape_string(r, csrf));\n\n\t\t/* log what we're about to do */\n\t\toidc_debug(r, \"redirecting to external discovery page: %s\", url);\n\n\t\t/* set CSRF cookie */\n\t\toidc_util_set_cookie(r, OIDC_CSRF_NAME, csrf, -1);\n\n\t\t/* see if we need to preserve POST parameters through Javascript/HTML5 storage */\n\t\tif (oidc_post_preserve_javascript(r, url, NULL, NULL) == TRUE)\n\t\t\treturn DONE;\n\n\t\t/* do the actual redirect to an external discovery page */\n\t\tapr_table_add(r->headers_out, \"Location\", url);\n\t\treturn HTTP_MOVED_TEMPORARILY;\n\t}\n\n\t/* get a list of all providers configured in the metadata directory */\n\tapr_array_header_t *arr = NULL;\n\tif (oidc_metadata_list(r, cfg, &arr) == FALSE)\n\t\treturn oidc_util_html_send_error(r, cfg->error_template,\n\t\t\t\t\"Configuration Error\",\n\t\t\t\t\"No configured providers found, contact your administrator\",\n\t\t\t\tHTTP_UNAUTHORIZED);\n\n\t/* assemble a where-are-you-from IDP discovery HTML page */\n\tconst char *s = \"\t\t\t

Select your OpenID Connect Identity Provider

\\n\";\n\n\t/* list all configured providers in there */\n\tint i;\n\tfor (i = 0; i < arr->nelts; i++) {\n\t\tconst char *issuer = ((const char**) arr->elts)[i];\n\n\t\tchar *display =\n\t\t\t\t(strstr(issuer, \"https://\") == NULL) ?\n\t\t\t\t\t\tapr_pstrdup(r->pool, issuer) :\n\t\t\t\t\t\tapr_pstrdup(r->pool, issuer + strlen(\"https://\"));\n\n\t\t/* strip port number */\n\t\t/* point back to the redirect_uri, where the selection is handled, with an IDP selection and return_to URL */\n\t\ts =\n\t\t\t\tapr_psprintf(r->pool,\n\t\t\t\t\t\t\"%s

%s

\\n\",\n\t\t\t\t\t\ts, cfg->redirect_uri, OIDC_DISC_OP_PARAM,\n\t\t\t\t\t\toidc_util_escape_string(r, issuer),\n\t\t\t\t\t\tOIDC_DISC_RT_PARAM,\n\t\t\t\t\t\toidc_util_escape_string(r, current_url),\n\t\t\t\t\t\tOIDC_DISC_RM_PARAM, method,\n\t\t\t\t\t\tOIDC_CSRF_NAME, csrf, display);\n\t}\n\n\t/* add an option to enter an account or issuer name for dynamic OP discovery */\n\ts = apr_psprintf(r->pool, \"%s
\\n\", s,\n\t\t\tcfg->redirect_uri);\n\ts = apr_psprintf(r->pool,\n\t\t\t\"%s

\\n\", s,\n\t\t\tOIDC_DISC_RT_PARAM, current_url);\n\ts = apr_psprintf(r->pool,\n\t\t\t\"%s

\\n\", s,\n\t\t\tOIDC_DISC_RM_PARAM, method);\n\ts = apr_psprintf(r->pool,\n\t\t\t\"%s

\\n\", s,\n\t\t\tOIDC_CSRF_NAME, csrf);\n\ts =\n\t\t\tapr_psprintf(r->pool,\n\t\t\t\t\t\"%s

Or enter your account name (eg. "mike@seed.gluu.org", or an IDP identifier (eg. "mitreid.org"):

\\n\",\n\t\t\t\t\ts);\n\ts = apr_psprintf(r->pool,\n\t\t\t\"%s

\\n\", s,\n\t\t\tOIDC_DISC_OP_PARAM, \"\");\n\ts = apr_psprintf(r->pool,\n\t\t\t\"%s

\\n\", s);\n\ts = apr_psprintf(r->pool, \"%s
\\n\", s);\n\n\toidc_util_set_cookie(r, OIDC_CSRF_NAME, csrf, -1);\n\n\tchar *javascript = NULL, *javascript_method = NULL;\n\tchar *html_head =\n\t\t\t\"\";\n\tif (oidc_post_preserve_javascript(r, NULL, &javascript,\n\t\t\t&javascript_method) == TRUE)\n\t\thtml_head = apr_psprintf(r->pool, \"%s%s\", html_head, javascript);\n\n\t/* now send the HTML contents to the user agent */\n\treturn oidc_util_html_send(r, \"OpenID Connect Provider Discovery\",\n\t\t\thtml_head, javascript_method, s, DONE);\n}\n", + "line": null, + "label": 0, + "cwe": "CWE-287", + "cve": "CVE-2017-6413", + "length": 1266 + }, + { + "index": 183521, + "code": "bool VaapiVideoDecodeAccelerator::VaapiVP8Accelerator::SubmitDecode(\n const scoped_refptr& pic,\n const media::Vp8FrameHeader* frame_hdr,\n const scoped_refptr& last_frame,\n const scoped_refptr& golden_frame,\n const scoped_refptr& alt_frame) {\n VAIQMatrixBufferVP8 iq_matrix_buf;\n memset(&iq_matrix_buf, 0, sizeof(VAIQMatrixBufferVP8));\n\n const media::Vp8SegmentationHeader& sgmnt_hdr = frame_hdr->segmentation_hdr;\n const media::Vp8QuantizationHeader& quant_hdr = frame_hdr->quantization_hdr;\n static_assert(\n arraysize(iq_matrix_buf.quantization_index) == media::kMaxMBSegments,\n \"incorrect quantization matrix size\");\n for (size_t i = 0; i < media::kMaxMBSegments; ++i) {\n int q = quant_hdr.y_ac_qi;\n\n if (sgmnt_hdr.segmentation_enabled) {\n if (sgmnt_hdr.segment_feature_mode ==\n media::Vp8SegmentationHeader::FEATURE_MODE_ABSOLUTE)\n q = sgmnt_hdr.quantizer_update_value[i];\n else\n q += sgmnt_hdr.quantizer_update_value[i];\n }\n\n#define CLAMP_Q(q) std::min(std::max(q, 0), 127)\n static_assert(arraysize(iq_matrix_buf.quantization_index[i]) == 6,\n \"incorrect quantization matrix size\");\n iq_matrix_buf.quantization_index[i][0] = CLAMP_Q(q);\n iq_matrix_buf.quantization_index[i][1] = CLAMP_Q(q + quant_hdr.y_dc_delta);\n iq_matrix_buf.quantization_index[i][2] = CLAMP_Q(q + quant_hdr.y2_dc_delta);\n iq_matrix_buf.quantization_index[i][3] = CLAMP_Q(q + quant_hdr.y2_ac_delta);\n iq_matrix_buf.quantization_index[i][4] = CLAMP_Q(q + quant_hdr.uv_dc_delta);\n iq_matrix_buf.quantization_index[i][5] = CLAMP_Q(q + quant_hdr.uv_ac_delta);\n#undef CLAMP_Q\n }\n\n if (!vaapi_wrapper_->SubmitBuffer(VAIQMatrixBufferType,\n sizeof(VAIQMatrixBufferVP8),\n &iq_matrix_buf))\n return false;\n\n VAProbabilityDataBufferVP8 prob_buf;\n memset(&prob_buf, 0, sizeof(VAProbabilityDataBufferVP8));\n\n const media::Vp8EntropyHeader& entr_hdr = frame_hdr->entropy_hdr;\n ARRAY_MEMCPY_CHECKED(prob_buf.dct_coeff_probs, entr_hdr.coeff_probs);\n\n if (!vaapi_wrapper_->SubmitBuffer(VAProbabilityBufferType,\n sizeof(VAProbabilityDataBufferVP8),\n &prob_buf))\n return false;\n\n VAPictureParameterBufferVP8 pic_param;\n memset(&pic_param, 0, sizeof(VAPictureParameterBufferVP8));\n pic_param.frame_width = frame_hdr->width;\n pic_param.frame_height = frame_hdr->height;\n\n if (last_frame) {\n scoped_refptr last_frame_surface =\n VP8PictureToVaapiDecodeSurface(last_frame);\n pic_param.last_ref_frame = last_frame_surface->va_surface()->id();\n } else {\n pic_param.last_ref_frame = VA_INVALID_SURFACE;\n }\n\n if (golden_frame) {\n scoped_refptr golden_frame_surface =\n VP8PictureToVaapiDecodeSurface(golden_frame);\n pic_param.golden_ref_frame = golden_frame_surface->va_surface()->id();\n } else {\n pic_param.golden_ref_frame = VA_INVALID_SURFACE;\n }\n\n if (alt_frame) {\n scoped_refptr alt_frame_surface =\n VP8PictureToVaapiDecodeSurface(alt_frame);\n pic_param.alt_ref_frame = alt_frame_surface->va_surface()->id();\n } else {\n pic_param.alt_ref_frame = VA_INVALID_SURFACE;\n }\n\n pic_param.out_of_loop_frame = VA_INVALID_SURFACE;\n \n const media::Vp8LoopFilterHeader& lf_hdr = frame_hdr->loopfilter_hdr;\n \n#define FHDR_TO_PP_PF(a, b) pic_param.pic_fields.bits.a = (b)\n FHDR_TO_PP_PF(key_frame, frame_hdr->IsKeyframe() ? 0 : 1);\n FHDR_TO_PP_PF(version, frame_hdr->version);\n FHDR_TO_PP_PF(segmentation_enabled, sgmnt_hdr.segmentation_enabled);\n FHDR_TO_PP_PF(update_mb_segmentation_map,\n sgmnt_hdr.update_mb_segmentation_map);\n FHDR_TO_PP_PF(update_segment_feature_data,\n sgmnt_hdr.update_segment_feature_data);\n FHDR_TO_PP_PF(filter_type, lf_hdr.type);\n FHDR_TO_PP_PF(sharpness_level, lf_hdr.sharpness_level);\n FHDR_TO_PP_PF(loop_filter_adj_enable, lf_hdr.loop_filter_adj_enable);\n FHDR_TO_PP_PF(mode_ref_lf_delta_update, lf_hdr.mode_ref_lf_delta_update);\n FHDR_TO_PP_PF(sign_bias_golden, frame_hdr->sign_bias_golden);\n FHDR_TO_PP_PF(sign_bias_alternate, frame_hdr->sign_bias_alternate);\n FHDR_TO_PP_PF(mb_no_coeff_skip, frame_hdr->mb_no_skip_coeff);\n FHDR_TO_PP_PF(loop_filter_disable, lf_hdr.level == 0);\n#undef FHDR_TO_PP_PF\n\n ARRAY_MEMCPY_CHECKED(pic_param.mb_segment_tree_probs, sgmnt_hdr.segment_prob);\n\n static_assert(arraysize(sgmnt_hdr.lf_update_value) ==\n arraysize(pic_param.loop_filter_level),\n \"loop filter level arrays mismatch\");\n for (size_t i = 0; i < arraysize(sgmnt_hdr.lf_update_value); ++i) {\n int lf_level = lf_hdr.level;\n if (sgmnt_hdr.segmentation_enabled) {\n if (sgmnt_hdr.segment_feature_mode ==\n media::Vp8SegmentationHeader::FEATURE_MODE_ABSOLUTE)\n lf_level = sgmnt_hdr.lf_update_value[i];\n else\n lf_level += sgmnt_hdr.lf_update_value[i];\n }\n\n lf_level = std::min(std::max(lf_level, 0), 63);\n pic_param.loop_filter_level[i] = lf_level;\n }\n\n static_assert(arraysize(lf_hdr.ref_frame_delta) ==\n arraysize(pic_param.loop_filter_deltas_ref_frame) &&\n arraysize(lf_hdr.mb_mode_delta) ==\n arraysize(pic_param.loop_filter_deltas_mode) &&\n arraysize(lf_hdr.ref_frame_delta) ==\n arraysize(lf_hdr.mb_mode_delta),\n \"loop filter deltas arrays size mismatch\");\n for (size_t i = 0; i < arraysize(lf_hdr.ref_frame_delta); ++i) {\n pic_param.loop_filter_deltas_ref_frame[i] = lf_hdr.ref_frame_delta[i];\n pic_param.loop_filter_deltas_mode[i] = lf_hdr.mb_mode_delta[i];\n }\n \n#define FHDR_TO_PP(a) pic_param.a = frame_hdr->a\n FHDR_TO_PP(prob_skip_false);\n FHDR_TO_PP(prob_intra);\n FHDR_TO_PP(prob_last);\n FHDR_TO_PP(prob_gf);\n#undef FHDR_TO_PP\n\n ARRAY_MEMCPY_CHECKED(pic_param.y_mode_probs, entr_hdr.y_mode_probs);\n ARRAY_MEMCPY_CHECKED(pic_param.uv_mode_probs, entr_hdr.uv_mode_probs);\n ARRAY_MEMCPY_CHECKED(pic_param.mv_probs, entr_hdr.mv_probs);\n\n pic_param.bool_coder_ctx.range = frame_hdr->bool_dec_range;\n pic_param.bool_coder_ctx.value = frame_hdr->bool_dec_value;\n pic_param.bool_coder_ctx.count = frame_hdr->bool_dec_count;\n \n if (!vaapi_wrapper_->SubmitBuffer(VAPictureParameterBufferType,\n sizeof(pic_param), &pic_param))\n return false;\n \n VASliceParameterBufferVP8 slice_param;\n memset(&slice_param, 0, sizeof(slice_param));\n slice_param.slice_data_size = frame_hdr->frame_size;\n slice_param.slice_data_offset = frame_hdr->first_part_offset;\n slice_param.slice_data_flag = VA_SLICE_DATA_FLAG_ALL;\n slice_param.macroblock_offset = frame_hdr->macroblock_bit_offset;\n slice_param.num_of_partitions = frame_hdr->num_of_dct_partitions + 1;\n\n slice_param.partition_size[0] =\n frame_hdr->first_part_size - ((frame_hdr->macroblock_bit_offset + 7) / 8);\n\n for (size_t i = 0; i < frame_hdr->num_of_dct_partitions; ++i)\n slice_param.partition_size[i + 1] = frame_hdr->dct_partition_sizes[i];\n\n if (!vaapi_wrapper_->SubmitBuffer(VASliceParameterBufferType,\n sizeof(VASliceParameterBufferVP8),\n &slice_param))\n return false;\n\n void* non_const_ptr = const_cast(frame_hdr->data);\n if (!vaapi_wrapper_->SubmitBuffer(VASliceDataBufferType,\n frame_hdr->frame_size,\n non_const_ptr))\n return false;\n\n scoped_refptr dec_surface =\n VP8PictureToVaapiDecodeSurface(pic);\n\n return vaapi_dec_->DecodeSurface(dec_surface);\n}\n", + "line": "#define FHDR_TO_PP_PF(a, b) pic_param.pic_fields.bits.a = (b)\n#define FHDR_TO_PP(a) pic_param.a = frame_hdr->a\n sizeof(pic_param), &pic_param))\n memset(&slice_param, 0, sizeof(slice_param));\n", + "label": 1, + "cwe": null, + "cve": null, + "length": 2002 + }, + { + "index": 181676, + "code": "static int process_line(URLContext *h, char *line, int line_count,\n int *new_location)\n{\n HTTPContext *s = h->priv_data;\n const char *auto_method = h->flags & AVIO_FLAG_READ ? \"POST\" : \"GET\";\n char *tag, *p, *end, *method, *resource, *version;\n int ret;\n\n /* end of header */\n if (line[0] == '\\0') {\n s->end_header = 1;\n return 0;\n }\n\n p = line;\n if (line_count == 0) {\n if (s->is_connected_server) {\n method = p;\n while (*p && !av_isspace(*p))\n p++;\n *(p++) = '\\0';\n av_log(h, AV_LOG_TRACE, \"Received method: %s\\n\", method);\n if (s->method) {\n if (av_strcasecmp(s->method, method)) {\n av_log(h, AV_LOG_ERROR, \"Received and expected HTTP method do not match. (%s expected, %s received)\\n\",\n s->method, method);\n return ff_http_averror(400, AVERROR(EIO));\n }\n } else {\n av_log(h, AV_LOG_TRACE, \"Autodetected %s HTTP method\\n\", auto_method);\n if (av_strcasecmp(auto_method, method)) {\n av_log(h, AV_LOG_ERROR, \"Received and autodetected HTTP method did not match \"\n \"(%s autodetected %s received)\\n\", auto_method, method);\n return ff_http_averror(400, AVERROR(EIO));\n }\n if (!(s->method = av_strdup(method)))\n return AVERROR(ENOMEM);\n }\n\n while (av_isspace(*p))\n p++;\n resource = p;\n while (!av_isspace(*p))\n p++;\n *(p++) = '\\0';\n av_log(h, AV_LOG_TRACE, \"Requested resource: %s\\n\", resource);\n if (!(s->resource = av_strdup(resource)))\n return AVERROR(ENOMEM);\n\n while (av_isspace(*p))\n p++;\n version = p;\n while (*p && !av_isspace(*p))\n p++;\n *p = '\\0';\n if (av_strncasecmp(version, \"HTTP/\", 5)) {\n av_log(h, AV_LOG_ERROR, \"Malformed HTTP version string.\\n\");\n return ff_http_averror(400, AVERROR(EIO));\n }\n av_log(h, AV_LOG_TRACE, \"HTTP version string: %s\\n\", version);\n } else {\n while (!av_isspace(*p) && *p != '\\0')\n p++;\n while (av_isspace(*p))\n p++;\n s->http_code = strtol(p, &end, 10);\n\n av_log(h, AV_LOG_TRACE, \"http_code=%d\\n\", s->http_code);\n\n if ((ret = check_http_code(h, s->http_code, end)) < 0)\n return ret;\n }\n } else {\n while (*p != '\\0' && *p != ':')\n p++;\n if (*p != ':')\n return 1;\n\n *p = '\\0';\n tag = line;\n p++;\n while (av_isspace(*p))\n p++;\n if (!av_strcasecmp(tag, \"Location\")) {\n if ((ret = parse_location(s, p)) < 0)\n return ret;\n *new_location = 1;\n } else if (!av_strcasecmp(tag, \"Content-Length\") && s->filesize == -1) {\n s->filesize = strtoll(p, NULL, 10);\n } else if (!av_strcasecmp(tag, \"Content-Range\")) {\n parse_content_range(h, p);\n } else if (!av_strcasecmp(tag, \"Accept-Ranges\") &&\n !strncmp(p, \"bytes\", 5) &&\n s->seekable == -1) {\n h->is_streamed = 0;\n } else if (!av_strcasecmp(tag, \"Transfer-Encoding\") &&\n !av_strncasecmp(p, \"chunked\", 7)) {\n s->filesize = -1;\n s->chunksize = 0;\n } else if (!av_strcasecmp(tag, \"WWW-Authenticate\")) {\n ff_http_auth_handle_header(&s->auth_state, tag, p);\n } else if (!av_strcasecmp(tag, \"Authentication-Info\")) {\n ff_http_auth_handle_header(&s->auth_state, tag, p);\n } else if (!av_strcasecmp(tag, \"Proxy-Authenticate\")) {\n ff_http_auth_handle_header(&s->proxy_auth_state, tag, p);\n } else if (!av_strcasecmp(tag, \"Connection\")) {\n if (!strcmp(p, \"close\"))\n s->willclose = 1;\n } else if (!av_strcasecmp(tag, \"Server\")) {\n if (!av_strcasecmp(p, \"AkamaiGHost\")) {\n s->is_akamai = 1;\n } else if (!av_strncasecmp(p, \"MediaGateway\", 12)) {\n s->is_mediagateway = 1;\n }\n } else if (!av_strcasecmp(tag, \"Content-Type\")) {\n av_free(s->mime_type);\n s->mime_type = av_strdup(p);\n } else if (!av_strcasecmp(tag, \"Set-Cookie\")) {\n if (parse_cookie(s, p, &s->cookie_dict))\n av_log(h, AV_LOG_WARNING, \"Unable to parse '%s'\\n\", p);\n } else if (!av_strcasecmp(tag, \"Icy-MetaInt\")) {\n s->icy_metaint = strtoll(p, NULL, 10);\n } else if (!av_strncasecmp(tag, \"Icy-\", 4)) {\n if ((ret = parse_icy(s, tag, p)) < 0)\n return ret;\n } else if (!av_strcasecmp(tag, \"Content-Encoding\")) {\n if ((ret = parse_content_encoding(h, p)) < 0)\n return ret;\n }\n }\n return 1;\n}\n", + "line": " } else if (!av_strcasecmp(tag, \"Content-Length\") && s->filesize == -1) {\n s->filesize = strtoll(p, NULL, 10);\n s->filesize = -1;\n s->icy_metaint = strtoll(p, NULL, 10);\n", + "label": 1, + "cwe": "CWE-119", + "cve": "CVE-2016-10190", + "length": 1329 + } +] \ No newline at end of file