cwe,func_name,func_src_before,func_src_after,line_changes,char_changes,commit_link,file_name,vul_type,num_tokens cwe-125,php_wddx_push_element," */ static void php_wddx_push_element(void *user_data, const XML_Char *name, const XML_Char **atts) { st_entry ent; wddx_stack *stack = (wddx_stack *)user_data; if (!strcmp(name, EL_PACKET)) { int i; if (atts) for (i=0; atts[i]; i++) { if (!strcmp(atts[i], EL_VERSION)) { /* nothing for now */ } } } else if (!strcmp(name, EL_STRING)) { ent.type = ST_STRING; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); INIT_PZVAL(ent.data); Z_TYPE_P(ent.data) = IS_STRING; Z_STRVAL_P(ent.data) = STR_EMPTY_ALLOC(); Z_STRLEN_P(ent.data) = 0; wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_BINARY)) { ent.type = ST_BINARY; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); INIT_PZVAL(ent.data); Z_TYPE_P(ent.data) = IS_STRING; Z_STRVAL_P(ent.data) = STR_EMPTY_ALLOC(); Z_STRLEN_P(ent.data) = 0; wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_CHAR)) { int i; if (atts) for (i = 0; atts[i]; i++) { if (!strcmp(atts[i], EL_CHAR_CODE) && atts[i+1] && atts[i+1][0]) { char tmp_buf[2]; snprintf(tmp_buf, sizeof(tmp_buf), ""%c"", (char)strtol(atts[i+1], NULL, 16)); php_wddx_process_data(user_data, tmp_buf, strlen(tmp_buf)); break; } } } else if (!strcmp(name, EL_NUMBER)) { ent.type = ST_NUMBER; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); INIT_PZVAL(ent.data); Z_TYPE_P(ent.data) = IS_LONG; Z_LVAL_P(ent.data) = 0; wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_BOOLEAN)) { int i; if (atts) for (i = 0; atts[i]; i++) { if (!strcmp(atts[i], EL_VALUE) && atts[i+1] && atts[i+1][0]) { ent.type = ST_BOOLEAN; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); INIT_PZVAL(ent.data); Z_TYPE_P(ent.data) = IS_BOOL; wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); php_wddx_process_data(user_data, atts[i+1], strlen(atts[i+1])); break; } } } else if (!strcmp(name, EL_NULL)) { ent.type = ST_NULL; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); INIT_PZVAL(ent.data); ZVAL_NULL(ent.data); wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_ARRAY)) { ent.type = ST_ARRAY; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); array_init(ent.data); INIT_PZVAL(ent.data); wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_STRUCT)) { ent.type = ST_STRUCT; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); array_init(ent.data); INIT_PZVAL(ent.data); wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_VAR)) { int i; if (atts) for (i = 0; atts[i]; i++) { if (!strcmp(atts[i], EL_NAME) && atts[i+1] && atts[i+1][0]) { if (stack->varname) efree(stack->varname); stack->varname = estrdup(atts[i+1]); break; } } } else if (!strcmp(name, EL_RECORDSET)) { int i; ent.type = ST_RECORDSET; SET_STACK_VARNAME; MAKE_STD_ZVAL(ent.data); array_init(ent.data); if (atts) for (i = 0; atts[i]; i++) { if (!strcmp(atts[i], ""fieldNames"") && atts[i+1] && atts[i+1][0]) { zval *tmp; char *key; char *p1, *p2, *endp; i++; endp = (char *)atts[i] + strlen(atts[i]); p1 = (char *)atts[i]; while ((p2 = php_memnstr(p1, "","", sizeof("","")-1, endp)) != NULL) { key = estrndup(p1, p2 - p1); MAKE_STD_ZVAL(tmp); array_init(tmp); add_assoc_zval_ex(ent.data, key, p2 - p1 + 1, tmp); p1 = p2 + sizeof("","")-1; efree(key); } if (p1 <= endp) { MAKE_STD_ZVAL(tmp); array_init(tmp); add_assoc_zval_ex(ent.data, p1, endp - p1 + 1, tmp); } break; } } wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_FIELD)) { int i; st_entry ent; ent.type = ST_FIELD; ent.varname = NULL; ent.data = NULL; if (atts) for (i = 0; atts[i]; i++) { if (!strcmp(atts[i], EL_NAME) && atts[i+1] && atts[i+1][0]) { st_entry *recordset; zval **field; if (wddx_stack_top(stack, (void**)&recordset) == SUCCESS && recordset->type == ST_RECORDSET && zend_hash_find(Z_ARRVAL_P(recordset->data), (char*)atts[i+1], strlen(atts[i+1])+1, (void**)&field) == SUCCESS) { ent.data = *field; } break; } } wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_DATETIME)) { ent.type = ST_DATETIME; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); INIT_PZVAL(ent.data); Z_TYPE_P(ent.data) = IS_LONG; wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); }"," */ static void php_wddx_push_element(void *user_data, const XML_Char *name, const XML_Char **atts) { st_entry ent; wddx_stack *stack = (wddx_stack *)user_data; if (!strcmp(name, EL_PACKET)) { int i; if (atts) for (i=0; atts[i]; i++) { if (!strcmp(atts[i], EL_VERSION)) { /* nothing for now */ } } } else if (!strcmp(name, EL_STRING)) { ent.type = ST_STRING; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); INIT_PZVAL(ent.data); Z_TYPE_P(ent.data) = IS_STRING; Z_STRVAL_P(ent.data) = STR_EMPTY_ALLOC(); Z_STRLEN_P(ent.data) = 0; wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_BINARY)) { ent.type = ST_BINARY; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); INIT_PZVAL(ent.data); Z_TYPE_P(ent.data) = IS_STRING; Z_STRVAL_P(ent.data) = STR_EMPTY_ALLOC(); Z_STRLEN_P(ent.data) = 0; wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_CHAR)) { int i; if (atts) for (i = 0; atts[i]; i++) { if (!strcmp(atts[i], EL_CHAR_CODE) && atts[i+1] && atts[i+1][0]) { char tmp_buf[2]; snprintf(tmp_buf, sizeof(tmp_buf), ""%c"", (char)strtol(atts[i+1], NULL, 16)); php_wddx_process_data(user_data, tmp_buf, strlen(tmp_buf)); break; } } } else if (!strcmp(name, EL_NUMBER)) { ent.type = ST_NUMBER; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); INIT_PZVAL(ent.data); Z_TYPE_P(ent.data) = IS_LONG; Z_LVAL_P(ent.data) = 0; wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_BOOLEAN)) { int i; if (atts) for (i = 0; atts[i]; i++) { if (!strcmp(atts[i], EL_VALUE) && atts[i+1] && atts[i+1][0]) { ent.type = ST_BOOLEAN; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); INIT_PZVAL(ent.data); Z_TYPE_P(ent.data) = IS_BOOL; wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); php_wddx_process_data(user_data, atts[i+1], strlen(atts[i+1])); break; } } else { ent.type = ST_BOOLEAN; SET_STACK_VARNAME; ZVAL_FALSE(&ent.data); wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } } else if (!strcmp(name, EL_NULL)) { ent.type = ST_NULL; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); INIT_PZVAL(ent.data); ZVAL_NULL(ent.data); wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_ARRAY)) { ent.type = ST_ARRAY; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); array_init(ent.data); INIT_PZVAL(ent.data); wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_STRUCT)) { ent.type = ST_STRUCT; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); array_init(ent.data); INIT_PZVAL(ent.data); wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_VAR)) { int i; if (atts) for (i = 0; atts[i]; i++) { if (!strcmp(atts[i], EL_NAME) && atts[i+1] && atts[i+1][0]) { if (stack->varname) efree(stack->varname); stack->varname = estrdup(atts[i+1]); break; } } } else if (!strcmp(name, EL_RECORDSET)) { int i; ent.type = ST_RECORDSET; SET_STACK_VARNAME; MAKE_STD_ZVAL(ent.data); array_init(ent.data); if (atts) for (i = 0; atts[i]; i++) { if (!strcmp(atts[i], ""fieldNames"") && atts[i+1] && atts[i+1][0]) { zval *tmp; char *key; char *p1, *p2, *endp; i++; endp = (char *)atts[i] + strlen(atts[i]); p1 = (char *)atts[i]; while ((p2 = php_memnstr(p1, "","", sizeof("","")-1, endp)) != NULL) { key = estrndup(p1, p2 - p1); MAKE_STD_ZVAL(tmp); array_init(tmp); add_assoc_zval_ex(ent.data, key, p2 - p1 + 1, tmp); p1 = p2 + sizeof("","")-1; efree(key); } if (p1 <= endp) { MAKE_STD_ZVAL(tmp); array_init(tmp); add_assoc_zval_ex(ent.data, p1, endp - p1 + 1, tmp); } break; } } wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_FIELD)) { int i; st_entry ent; ent.type = ST_FIELD; ent.varname = NULL; ent.data = NULL; if (atts) for (i = 0; atts[i]; i++) { if (!strcmp(atts[i], EL_NAME) && atts[i+1] && atts[i+1][0]) { st_entry *recordset; zval **field; if (wddx_stack_top(stack, (void**)&recordset) == SUCCESS && recordset->type == ST_RECORDSET && zend_hash_find(Z_ARRVAL_P(recordset->data), (char*)atts[i+1], strlen(atts[i+1])+1, (void**)&field) == SUCCESS) { ent.data = *field; } break; } } wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_DATETIME)) { ent.type = ST_DATETIME; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); INIT_PZVAL(ent.data); Z_TYPE_P(ent.data) = IS_LONG; wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); }","{'deleted': [], 'added': [{'line_no': 71, 'char_start': 1972, 'char_end': 1983, 'line': '\t\t} else {\n'}, {'line_no': 72, 'char_start': 1983, 'char_end': 2009, 'line': '\t\t\tent.type = ST_BOOLEAN;\n'}, {'line_no': 73, 'char_start': 2009, 'char_end': 2031, 'line': '\t\t\tSET_STACK_VARNAME;\n'}, {'line_no': 74, 'char_start': 2031, 'char_end': 2057, 'line': '\t\t\tZVAL_FALSE(&ent.data);\n'}, {'line_no': 75, 'char_start': 2057, 'char_end': 2122, 'line': '\t\t\twddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));\n'}]}","{'deleted': [], 'added': [{'char_start': 1975, 'char_end': 2125, 'chars': ' else {\n\t\t\tent.type = ST_BOOLEAN;\n\t\t\tSET_STACK_VARNAME;\n\t\t\tZVAL_FALSE(&ent.data);\n\t\t\twddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));\n\t\t}'}]}",github.com/php/php-src/commit/66fd44209d5ffcb9b3d1bc1b9fd8e35b485040c0,ext/wddx/wddx.c,cwe-125,1595 cwe-022,_inject_admin_password_into_fs,"def _inject_admin_password_into_fs(admin_passwd, fs, execute=None): """"""Set the root password to admin_passwd admin_password is a root password fs is the path to the base of the filesystem into which to inject the key. This method modifies the instance filesystem directly, and does not require a guest agent running in the instance. """""" # The approach used here is to copy the password and shadow # files from the instance filesystem to local files, make any # necessary changes, and then copy them back. admin_user = 'root' fd, tmp_passwd = tempfile.mkstemp() os.close(fd) fd, tmp_shadow = tempfile.mkstemp() os.close(fd) utils.execute('cp', os.path.join(fs, 'etc', 'passwd'), tmp_passwd, run_as_root=True) utils.execute('cp', os.path.join(fs, 'etc', 'shadow'), tmp_shadow, run_as_root=True) _set_passwd(admin_user, admin_passwd, tmp_passwd, tmp_shadow) utils.execute('cp', tmp_passwd, os.path.join(fs, 'etc', 'passwd'), run_as_root=True) os.unlink(tmp_passwd) utils.execute('cp', tmp_shadow, os.path.join(fs, 'etc', 'shadow'), run_as_root=True) os.unlink(tmp_shadow)","def _inject_admin_password_into_fs(admin_passwd, fs, execute=None): """"""Set the root password to admin_passwd admin_password is a root password fs is the path to the base of the filesystem into which to inject the key. This method modifies the instance filesystem directly, and does not require a guest agent running in the instance. """""" # The approach used here is to copy the password and shadow # files from the instance filesystem to local files, make any # necessary changes, and then copy them back. admin_user = 'root' fd, tmp_passwd = tempfile.mkstemp() os.close(fd) fd, tmp_shadow = tempfile.mkstemp() os.close(fd) passwd_path = _join_and_check_path_within_fs(fs, 'etc', 'passwd') shadow_path = _join_and_check_path_within_fs(fs, 'etc', 'shadow') utils.execute('cp', passwd_path, tmp_passwd, run_as_root=True) utils.execute('cp', shadow_path, tmp_shadow, run_as_root=True) _set_passwd(admin_user, admin_passwd, tmp_passwd, tmp_shadow) utils.execute('cp', tmp_passwd, passwd_path, run_as_root=True) os.unlink(tmp_passwd) utils.execute('cp', tmp_shadow, shadow_path, run_as_root=True) os.unlink(tmp_shadow)","{'deleted': [{'line_no': 23, 'char_start': 689, 'char_end': 760, 'line': "" utils.execute('cp', os.path.join(fs, 'etc', 'passwd'), tmp_passwd,\n""}, {'line_no': 24, 'char_start': 760, 'char_end': 796, 'line': ' run_as_root=True)\n'}, {'line_no': 25, 'char_start': 796, 'char_end': 867, 'line': "" utils.execute('cp', os.path.join(fs, 'etc', 'shadow'), tmp_shadow,\n""}, {'line_no': 26, 'char_start': 867, 'char_end': 903, 'line': ' run_as_root=True)\n'}, {'line_no': 28, 'char_start': 969, 'char_end': 1040, 'line': "" utils.execute('cp', tmp_passwd, os.path.join(fs, 'etc', 'passwd'),\n""}, {'line_no': 29, 'char_start': 1040, 'char_end': 1076, 'line': ' run_as_root=True)\n'}, {'line_no': 31, 'char_start': 1102, 'char_end': 1173, 'line': "" utils.execute('cp', tmp_shadow, os.path.join(fs, 'etc', 'shadow'),\n""}, {'line_no': 32, 'char_start': 1173, 'char_end': 1209, 'line': ' run_as_root=True)\n'}], 'added': [{'line_no': 23, 'char_start': 689, 'char_end': 759, 'line': "" passwd_path = _join_and_check_path_within_fs(fs, 'etc', 'passwd')\n""}, {'line_no': 24, 'char_start': 759, 'char_end': 829, 'line': "" shadow_path = _join_and_check_path_within_fs(fs, 'etc', 'shadow')\n""}, {'line_no': 25, 'char_start': 829, 'char_end': 830, 'line': '\n'}, {'line_no': 26, 'char_start': 830, 'char_end': 897, 'line': "" utils.execute('cp', passwd_path, tmp_passwd, run_as_root=True)\n""}, {'line_no': 27, 'char_start': 897, 'char_end': 964, 'line': "" utils.execute('cp', shadow_path, tmp_shadow, run_as_root=True)\n""}, {'line_no': 29, 'char_start': 1030, 'char_end': 1097, 'line': "" utils.execute('cp', tmp_passwd, passwd_path, run_as_root=True)\n""}, {'line_no': 31, 'char_start': 1123, 'char_end': 1190, 'line': "" utils.execute('cp', tmp_shadow, shadow_path, run_as_root=True)\n""}]}","{'deleted': [{'char_start': 693, 'char_end': 694, 'chars': 'u'}, {'char_start': 696, 'char_end': 701, 'chars': 'ls.ex'}, {'char_start': 703, 'char_end': 704, 'chars': 'u'}, {'char_start': 705, 'char_end': 706, 'chars': 'e'}, {'char_start': 711, 'char_end': 712, 'chars': ','}, {'char_start': 714, 'char_end': 716, 'chars': 's.'}, {'char_start': 720, 'char_end': 721, 'chars': '.'}, {'char_start': 744, 'char_end': 746, 'chars': ""')""}, {'char_start': 759, 'char_end': 777, 'chars': '\n '}, {'char_start': 820, 'char_end': 845, 'chars': ""os.path.join(fs, 'etc', '""}, {'char_start': 851, 'char_end': 853, 'chars': ""')""}, {'char_start': 866, 'char_end': 884, 'chars': '\n '}, {'char_start': 1005, 'char_end': 1030, 'chars': ""os.path.join(fs, 'etc', '""}, {'char_start': 1036, 'char_end': 1038, 'chars': ""')""}, {'char_start': 1039, 'char_end': 1057, 'chars': '\n '}, {'char_start': 1138, 'char_end': 1163, 'chars': ""os.path.join(fs, 'etc', '""}, {'char_start': 1169, 'char_end': 1171, 'chars': ""')""}, {'char_start': 1172, 'char_end': 1190, 'chars': '\n '}], 'added': [{'char_start': 693, 'char_end': 702, 'chars': 'passwd_pa'}, {'char_start': 703, 'char_end': 710, 'chars': 'h = _jo'}, {'char_start': 711, 'char_end': 719, 'chars': 'n_and_ch'}, {'char_start': 721, 'char_end': 725, 'chars': 'k_pa'}, {'char_start': 726, 'char_end': 737, 'chars': 'h_within_fs'}, {'char_start': 738, 'char_end': 742, 'chars': 'fs, '}, {'char_start': 743, 'char_end': 745, 'chars': 'et'}, {'char_start': 749, 'char_end': 752, 'chars': ""'pa""}, {'char_start': 753, 'char_end': 770, 'chars': ""swd')\n shadow_""}, {'char_start': 774, 'char_end': 778, 'chars': ' = _'}, {'char_start': 782, 'char_end': 807, 'chars': '_and_check_path_within_fs'}, {'char_start': 820, 'char_end': 854, 'chars': ""shadow')\n\n utils.execute('cp', ""}, {'char_start': 860, 'char_end': 865, 'chars': '_path'}, {'char_start': 927, 'char_end': 932, 'chars': '_path'}, {'char_start': 1072, 'char_end': 1077, 'chars': '_path'}, {'char_start': 1165, 'char_end': 1170, 'chars': '_path'}]}",github.com/openstack/nova/commit/2427d4a99bed35baefd8f17ba422cb7aae8dcca7,nova/virt/disk/api.py,cwe-022,287 cwe-078,test_create_modify_host," def test_create_modify_host(self): self.flags(lock_path=self.tempdir) #record self.clear_mox() self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, ""get_cpg"", self.fake_get_cpg) self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, ""get_domain"", self.fake_get_domain) _run_ssh = self.mox.CreateMock(hpdriver.hpcommon.HP3PARCommon._run_ssh) self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, ""_run_ssh"", _run_ssh) show_host_cmd = 'showhost -verbose fakehost' _run_ssh(show_host_cmd, False).AndReturn([pack(NO_FC_HOST_RET), '']) create_host_cmd = ('createhost -add fakehost ' '123456789012345 123456789054321') _run_ssh(create_host_cmd, False).AndReturn([CLI_CR, '']) show_host_cmd = 'showhost -verbose fakehost' _run_ssh(show_host_cmd, False).AndReturn([pack(FC_HOST_RET), '']) self.mox.ReplayAll() host = self.driver._create_host(self.volume, self.connector) self.assertEqual(host['name'], self.FAKE_HOST)"," def test_create_modify_host(self): self.flags(lock_path=self.tempdir) #record self.clear_mox() self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, ""get_cpg"", self.fake_get_cpg) self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, ""get_domain"", self.fake_get_domain) _run_ssh = self.mox.CreateMock(hpdriver.hpcommon.HP3PARCommon._run_ssh) self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, ""_run_ssh"", _run_ssh) show_host_cmd = ['showhost', '-verbose', 'fakehost'] _run_ssh(show_host_cmd, False).AndReturn([pack(NO_FC_HOST_RET), '']) create_host_cmd = ['createhost', '-add', 'fakehost', '123456789012345', '123456789054321'] _run_ssh(create_host_cmd, False).AndReturn([CLI_CR, '']) show_host_cmd = ['showhost', '-verbose', 'fakehost'] _run_ssh(show_host_cmd, False).AndReturn([pack(FC_HOST_RET), '']) self.mox.ReplayAll() host = self.driver._create_host(self.volume, self.connector) self.assertEqual(host['name'], self.FAKE_HOST)","{'deleted': [{'line_no': 13, 'char_start': 504, 'char_end': 557, 'line': "" show_host_cmd = 'showhost -verbose fakehost'\n""}, {'line_no': 16, 'char_start': 635, 'char_end': 690, 'line': "" create_host_cmd = ('createhost -add fakehost '\n""}, {'line_no': 17, 'char_start': 690, 'char_end': 752, 'line': "" '123456789012345 123456789054321')\n""}, {'line_no': 20, 'char_start': 818, 'char_end': 871, 'line': "" show_host_cmd = 'showhost -verbose fakehost'\n""}], 'added': [{'line_no': 13, 'char_start': 504, 'char_end': 565, 'line': "" show_host_cmd = ['showhost', '-verbose', 'fakehost']\n""}, {'line_no': 16, 'char_start': 643, 'char_end': 723, 'line': "" create_host_cmd = ['createhost', '-add', 'fakehost', '123456789012345',\n""}, {'line_no': 17, 'char_start': 723, 'char_end': 769, 'line': "" '123456789054321']\n""}, {'line_no': 20, 'char_start': 835, 'char_end': 896, 'line': "" show_host_cmd = ['showhost', '-verbose', 'fakehost']\n""}]}","{'deleted': [{'char_start': 661, 'char_end': 662, 'chars': '('}, {'char_start': 728, 'char_end': 744, 'chars': '12345 1234567890'}, {'char_start': 750, 'char_end': 751, 'chars': ')'}], 'added': [{'char_start': 528, 'char_end': 529, 'chars': '['}, {'char_start': 538, 'char_end': 540, 'chars': ""',""}, {'char_start': 541, 'char_end': 542, 'chars': ""'""}, {'char_start': 550, 'char_end': 552, 'chars': ""',""}, {'char_start': 553, 'char_end': 554, 'chars': ""'""}, {'char_start': 563, 'char_end': 564, 'chars': ']'}, {'char_start': 669, 'char_end': 670, 'chars': '['}, {'char_start': 681, 'char_end': 683, 'chars': ""',""}, {'char_start': 684, 'char_end': 685, 'chars': ""'""}, {'char_start': 689, 'char_end': 691, 'chars': ""',""}, {'char_start': 692, 'char_end': 693, 'chars': ""'""}, {'char_start': 701, 'char_end': 703, 'chars': ""',""}, {'char_start': 705, 'char_end': 722, 'chars': ""123456789012345',""}, {'char_start': 767, 'char_end': 768, 'chars': ']'}, {'char_start': 859, 'char_end': 860, 'chars': '['}, {'char_start': 869, 'char_end': 871, 'chars': ""',""}, {'char_start': 872, 'char_end': 873, 'chars': ""'""}, {'char_start': 881, 'char_end': 883, 'chars': ""',""}, {'char_start': 884, 'char_end': 885, 'chars': ""'""}, {'char_start': 894, 'char_end': 895, 'chars': ']'}]}",github.com/thatsdone/cinder/commit/c55589b131828f3a595903f6796cb2d0babb772f,cinder/tests/test_hp3par.py,cwe-078,296 cwe-476,store_versioninfo_gnu_verdef,"static Sdb *store_versioninfo_gnu_verdef(ELFOBJ *bin, Elf_(Shdr) *shdr, int sz) { const char *section_name = """"; const char *link_section_name = """"; char *end = NULL; Elf_(Shdr) *link_shdr = NULL; ut8 dfs[sizeof (Elf_(Verdef))] = {0}; Sdb *sdb; int cnt, i; if (shdr->sh_link > bin->ehdr.e_shnum) { return false; } link_shdr = &bin->shdr[shdr->sh_link]; if (shdr->sh_size < 1 || shdr->sh_size > SIZE_MAX) { return false; } Elf_(Verdef) *defs = calloc (shdr->sh_size, sizeof (char)); if (!defs) { return false; } if (bin->shstrtab && shdr->sh_name < bin->shstrtab_size) { section_name = &bin->shstrtab[shdr->sh_name]; } if (link_shdr && bin->shstrtab && link_shdr->sh_name < bin->shstrtab_size) { link_section_name = &bin->shstrtab[link_shdr->sh_name]; } if (!defs) { bprintf (""Warning: Cannot allocate memory (Check Elf_(Verdef))\n""); return NULL; } sdb = sdb_new0 (); end = (char *)defs + shdr->sh_size; sdb_set (sdb, ""section_name"", section_name, 0); sdb_num_set (sdb, ""entries"", shdr->sh_info, 0); sdb_num_set (sdb, ""addr"", shdr->sh_addr, 0); sdb_num_set (sdb, ""offset"", shdr->sh_offset, 0); sdb_num_set (sdb, ""link"", shdr->sh_link, 0); sdb_set (sdb, ""link_section_name"", link_section_name, 0); for (cnt = 0, i = 0; i >= 0 && cnt < shdr->sh_info && ((char *)defs + i < end); ++cnt) { Sdb *sdb_verdef = sdb_new0 (); char *vstart = ((char*)defs) + i; char key[32] = {0}; Elf_(Verdef) *verdef = (Elf_(Verdef)*)vstart; Elf_(Verdaux) aux = {0}; int j = 0; int isum = 0; r_buf_read_at (bin->b, shdr->sh_offset + i, dfs, sizeof (Elf_(Verdef))); verdef->vd_version = READ16 (dfs, j) verdef->vd_flags = READ16 (dfs, j) verdef->vd_ndx = READ16 (dfs, j) verdef->vd_cnt = READ16 (dfs, j) verdef->vd_hash = READ32 (dfs, j) verdef->vd_aux = READ32 (dfs, j) verdef->vd_next = READ32 (dfs, j) int vdaux = verdef->vd_aux; if (vdaux < 1) { sdb_free (sdb_verdef); goto out_error; } vstart += vdaux; if (vstart > end || vstart + sizeof (Elf_(Verdaux)) > end) { sdb_free (sdb_verdef); goto out_error; } j = 0; aux.vda_name = READ32 (vstart, j) aux.vda_next = READ32 (vstart, j) isum = i + verdef->vd_aux; if (aux.vda_name > bin->dynstr_size) { sdb_free (sdb_verdef); goto out_error; } sdb_num_set (sdb_verdef, ""idx"", i, 0); sdb_num_set (sdb_verdef, ""vd_version"", verdef->vd_version, 0); sdb_num_set (sdb_verdef, ""vd_ndx"", verdef->vd_ndx, 0); sdb_num_set (sdb_verdef, ""vd_cnt"", verdef->vd_cnt, 0); sdb_set (sdb_verdef, ""vda_name"", &bin->dynstr[aux.vda_name], 0); sdb_set (sdb_verdef, ""flags"", get_ver_flags (verdef->vd_flags), 0); for (j = 1; j < verdef->vd_cnt; ++j) { int k; Sdb *sdb_parent = sdb_new0 (); isum += aux.vda_next; vstart += aux.vda_next; if (vstart > end || vstart + sizeof(Elf_(Verdaux)) > end) { sdb_free (sdb_verdef); sdb_free (sdb_parent); goto out_error; } k = 0; aux.vda_name = READ32 (vstart, k) aux.vda_next = READ32 (vstart, k) if (aux.vda_name > bin->dynstr_size) { sdb_free (sdb_verdef); sdb_free (sdb_parent); goto out_error; } sdb_num_set (sdb_parent, ""idx"", isum, 0); sdb_num_set (sdb_parent, ""parent"", j, 0); sdb_set (sdb_parent, ""vda_name"", &bin->dynstr[aux.vda_name], 0); snprintf (key, sizeof (key), ""parent%d"", j - 1); sdb_ns_set (sdb_verdef, key, sdb_parent); } snprintf (key, sizeof (key), ""verdef%d"", cnt); sdb_ns_set (sdb, key, sdb_verdef); if (!verdef->vd_next) { sdb_free (sdb_verdef); goto out_error; } if ((st32)verdef->vd_next < 1) { eprintf (""Warning: Invalid vd_next in the ELF version\n""); break; } i += verdef->vd_next; } free (defs); return sdb; out_error: free (defs); sdb_free (sdb); return NULL; }","static Sdb *store_versioninfo_gnu_verdef(ELFOBJ *bin, Elf_(Shdr) *shdr, int sz) { const char *section_name = """"; const char *link_section_name = """"; char *end = NULL; Elf_(Shdr) *link_shdr = NULL; ut8 dfs[sizeof (Elf_(Verdef))] = {0}; Sdb *sdb; int cnt, i; if (shdr->sh_link > bin->ehdr.e_shnum) { return false; } link_shdr = &bin->shdr[shdr->sh_link]; if (shdr->sh_size < 1 || shdr->sh_size > SIZE_MAX) { return false; } Elf_(Verdef) *defs = calloc (shdr->sh_size, sizeof (char)); if (!defs) { return false; } if (bin->shstrtab && shdr->sh_name < bin->shstrtab_size) { section_name = &bin->shstrtab[shdr->sh_name]; } if (link_shdr && bin->shstrtab && link_shdr->sh_name < bin->shstrtab_size) { link_section_name = &bin->shstrtab[link_shdr->sh_name]; } if (!defs) { bprintf (""Warning: Cannot allocate memory (Check Elf_(Verdef))\n""); return NULL; } sdb = sdb_new0 (); end = (char *)defs + shdr->sh_size; sdb_set (sdb, ""section_name"", section_name, 0); sdb_num_set (sdb, ""entries"", shdr->sh_info, 0); sdb_num_set (sdb, ""addr"", shdr->sh_addr, 0); sdb_num_set (sdb, ""offset"", shdr->sh_offset, 0); sdb_num_set (sdb, ""link"", shdr->sh_link, 0); sdb_set (sdb, ""link_section_name"", link_section_name, 0); for (cnt = 0, i = 0; i >= 0 && cnt < shdr->sh_info && (end - (char *)defs > i); ++cnt) { Sdb *sdb_verdef = sdb_new0 (); char *vstart = ((char*)defs) + i; char key[32] = {0}; Elf_(Verdef) *verdef = (Elf_(Verdef)*)vstart; Elf_(Verdaux) aux = {0}; int j = 0; int isum = 0; r_buf_read_at (bin->b, shdr->sh_offset + i, dfs, sizeof (Elf_(Verdef))); verdef->vd_version = READ16 (dfs, j) verdef->vd_flags = READ16 (dfs, j) verdef->vd_ndx = READ16 (dfs, j) verdef->vd_cnt = READ16 (dfs, j) verdef->vd_hash = READ32 (dfs, j) verdef->vd_aux = READ32 (dfs, j) verdef->vd_next = READ32 (dfs, j) int vdaux = verdef->vd_aux; if (vdaux < 1 || (char *)UINTPTR_MAX - vstart < vdaux) { sdb_free (sdb_verdef); goto out_error; } vstart += vdaux; if (vstart > end || end - vstart < sizeof (Elf_(Verdaux))) { sdb_free (sdb_verdef); goto out_error; } j = 0; aux.vda_name = READ32 (vstart, j) aux.vda_next = READ32 (vstart, j) isum = i + verdef->vd_aux; if (aux.vda_name > bin->dynstr_size) { sdb_free (sdb_verdef); goto out_error; } sdb_num_set (sdb_verdef, ""idx"", i, 0); sdb_num_set (sdb_verdef, ""vd_version"", verdef->vd_version, 0); sdb_num_set (sdb_verdef, ""vd_ndx"", verdef->vd_ndx, 0); sdb_num_set (sdb_verdef, ""vd_cnt"", verdef->vd_cnt, 0); sdb_set (sdb_verdef, ""vda_name"", &bin->dynstr[aux.vda_name], 0); sdb_set (sdb_verdef, ""flags"", get_ver_flags (verdef->vd_flags), 0); for (j = 1; j < verdef->vd_cnt; ++j) { int k; Sdb *sdb_parent = sdb_new0 (); isum += aux.vda_next; vstart += aux.vda_next; if (vstart > end || end - vstart < sizeof (Elf_(Verdaux))) { sdb_free (sdb_verdef); sdb_free (sdb_parent); goto out_error; } k = 0; aux.vda_name = READ32 (vstart, k) aux.vda_next = READ32 (vstart, k) if (aux.vda_name > bin->dynstr_size) { sdb_free (sdb_verdef); sdb_free (sdb_parent); goto out_error; } sdb_num_set (sdb_parent, ""idx"", isum, 0); sdb_num_set (sdb_parent, ""parent"", j, 0); sdb_set (sdb_parent, ""vda_name"", &bin->dynstr[aux.vda_name], 0); snprintf (key, sizeof (key), ""parent%d"", j - 1); sdb_ns_set (sdb_verdef, key, sdb_parent); } snprintf (key, sizeof (key), ""verdef%d"", cnt); sdb_ns_set (sdb, key, sdb_verdef); if (!verdef->vd_next) { sdb_free (sdb_verdef); goto out_error; } if ((st32)verdef->vd_next < 1) { eprintf (""Warning: Invalid vd_next in the ELF version\n""); break; } i += verdef->vd_next; } free (defs); return sdb; out_error: free (defs); sdb_free (sdb); return NULL; }","{'deleted': [{'line_no': 39, 'char_start': 1241, 'char_end': 1331, 'line': '\tfor (cnt = 0, i = 0; i >= 0 && cnt < shdr->sh_info && ((char *)defs + i < end); ++cnt) {\n'}, {'line_no': 57, 'char_start': 1885, 'char_end': 1904, 'line': '\t\tif (vdaux < 1) {\n'}, {'line_no': 62, 'char_start': 1972, 'char_end': 2035, 'line': '\t\tif (vstart > end || vstart + sizeof (Elf_(Verdaux)) > end) {\n'}, {'line_no': 89, 'char_start': 2782, 'char_end': 2845, 'line': '\t\t\tif (vstart > end || vstart + sizeof(Elf_(Verdaux)) > end) {\n'}], 'added': [{'line_no': 39, 'char_start': 1241, 'char_end': 1331, 'line': '\tfor (cnt = 0, i = 0; i >= 0 && cnt < shdr->sh_info && (end - (char *)defs > i); ++cnt) {\n'}, {'line_no': 57, 'char_start': 1885, 'char_end': 1944, 'line': '\t\tif (vdaux < 1 || (char *)UINTPTR_MAX - vstart < vdaux) {\n'}, {'line_no': 62, 'char_start': 2012, 'char_end': 2075, 'line': '\t\tif (vstart > end || end - vstart < sizeof (Elf_(Verdaux))) {\n'}, {'line_no': 89, 'char_start': 2822, 'char_end': 2886, 'line': '\t\t\tif (vstart > end || end - vstart < sizeof (Elf_(Verdaux))) {\n'}]}","{'deleted': [{'char_start': 1310, 'char_end': 1311, 'chars': '+'}, {'char_start': 1313, 'char_end': 1319, 'chars': ' < end'}, {'char_start': 2001, 'char_end': 2002, 'chars': '+'}, {'char_start': 2025, 'char_end': 2031, 'chars': ' > end'}, {'char_start': 2812, 'char_end': 2813, 'chars': '+'}, {'char_start': 2835, 'char_end': 2841, 'chars': ' > end'}], 'added': [{'char_start': 1297, 'char_end': 1303, 'chars': 'end - '}, {'char_start': 1316, 'char_end': 1317, 'chars': '>'}, {'char_start': 1900, 'char_end': 1940, 'chars': ' || (char *)UINTPTR_MAX - vstart < vdaux'}, {'char_start': 2034, 'char_end': 2040, 'chars': 'end - '}, {'char_start': 2047, 'char_end': 2048, 'chars': '<'}, {'char_start': 2845, 'char_end': 2851, 'chars': 'end - '}, {'char_start': 2858, 'char_end': 2859, 'chars': '<'}, {'char_start': 2866, 'char_end': 2867, 'chars': ' '}]}",github.com/radare/radare2/commit/62e39f34b2705131a2d08aff0c2e542c6a52cf0e,libr/bin/format/elf/elf.c,cwe-476,1452 cwe-078,get_lines,"def get_lines(command: str) -> List[str]: """""" Run a command and return lines of output :param str command: the command to run :returns: list of whitespace-stripped lines output by command """""" stdout = get_output(command) return [line.strip().decode() for line in stdout.splitlines()]","def get_lines(command: List[str]) -> List[str]: """""" Run a command and return lines of output :param str command: the command to run :returns: list of whitespace-stripped lines output by command """""" stdout = get_output(command) return [line.strip() for line in stdout.splitlines()]","{'deleted': [{'line_no': 1, 'char_start': 0, 'char_end': 42, 'line': 'def get_lines(command: str) -> List[str]:\n'}, {'line_no': 9, 'char_start': 246, 'char_end': 312, 'line': ' return [line.strip().decode() for line in stdout.splitlines()]\n'}], 'added': [{'line_no': 1, 'char_start': 0, 'char_end': 48, 'line': 'def get_lines(command: List[str]) -> List[str]:\n'}, {'line_no': 9, 'char_start': 252, 'char_end': 309, 'line': ' return [line.strip() for line in stdout.splitlines()]\n'}]}","{'deleted': [{'char_start': 268, 'char_end': 277, 'chars': '().decode'}], 'added': [{'char_start': 23, 'char_end': 28, 'chars': 'List['}, {'char_start': 31, 'char_end': 32, 'chars': ']'}]}",github.com/timothycrosley/isort/commit/1ab38f4f7840a3c19bf961a24630a992a8373a76,isort/hooks.py,cwe-078,73 cwe-079,get_context_data," def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['comments'] = self.object.comment_set.all().order_by('-time') context['form'] = self.get_form() context['md'] = markdown(self.object.content, extensions=[ 'markdown.extensions.extra', 'markdown.extensions.codehilite', 'markdown.extensions.toc', ]) return context"," def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['comments'] = self.object.comment_set.all().order_by('-time') context['form'] = self.get_form() context['md'] = safe_md(self.object.content) return context","{'deleted': [{'line_no': 5, 'char_start': 215, 'char_end': 269, 'line': "" context['md'] = markdown(self.object.content,\n""}, {'line_no': 6, 'char_start': 269, 'char_end': 315, 'line': ' extensions=[\n'}, {'line_no': 7, 'char_start': 315, 'char_end': 381, 'line': "" 'markdown.extensions.extra',\n""}, {'line_no': 8, 'char_start': 381, 'char_end': 452, 'line': "" 'markdown.extensions.codehilite',\n""}, {'line_no': 9, 'char_start': 452, 'char_end': 516, 'line': "" 'markdown.extensions.toc',\n""}, {'line_no': 10, 'char_start': 516, 'char_end': 552, 'line': ' ])\n'}], 'added': [{'line_no': 5, 'char_start': 215, 'char_end': 268, 'line': "" context['md'] = safe_md(self.object.content)\n""}]}","{'deleted': [{'char_start': 239, 'char_end': 240, 'chars': 'm'}, {'char_start': 241, 'char_end': 243, 'chars': 'rk'}, {'char_start': 244, 'char_end': 247, 'chars': 'own'}, {'char_start': 267, 'char_end': 550, 'chars': "",\n extensions=[\n 'markdown.extensions.extra',\n 'markdown.extensions.codehilite',\n 'markdown.extensions.toc',\n ]""}], 'added': [{'char_start': 239, 'char_end': 240, 'chars': 's'}, {'char_start': 241, 'char_end': 245, 'chars': 'fe_m'}]}",github.com/Cheng-mq1216/production-practice/commit/333dc34f5feada55d1f6ff1255949ca00dec0f9c,app/Index/views.py,cwe-079,88 cwe-125,hid_input_field,"static void hid_input_field(struct hid_device *hid, struct hid_field *field, __u8 *data, int interrupt) { unsigned n; unsigned count = field->report_count; unsigned offset = field->report_offset; unsigned size = field->report_size; __s32 min = field->logical_minimum; __s32 max = field->logical_maximum; __s32 *value; value = kmalloc(sizeof(__s32) * count, GFP_ATOMIC); if (!value) return; for (n = 0; n < count; n++) { value[n] = min < 0 ? snto32(hid_field_extract(hid, data, offset + n * size, size), size) : hid_field_extract(hid, data, offset + n * size, size); /* Ignore report if ErrorRollOver */ if (!(field->flags & HID_MAIN_ITEM_VARIABLE) && value[n] >= min && value[n] <= max && field->usage[value[n] - min].hid == HID_UP_KEYBOARD + 1) goto exit; } for (n = 0; n < count; n++) { if (HID_MAIN_ITEM_VARIABLE & field->flags) { hid_process_event(hid, field, &field->usage[n], value[n], interrupt); continue; } if (field->value[n] >= min && field->value[n] <= max && field->usage[field->value[n] - min].hid && search(value, field->value[n], count)) hid_process_event(hid, field, &field->usage[field->value[n] - min], 0, interrupt); if (value[n] >= min && value[n] <= max && field->usage[value[n] - min].hid && search(field->value, value[n], count)) hid_process_event(hid, field, &field->usage[value[n] - min], 1, interrupt); } memcpy(field->value, value, count * sizeof(__s32)); exit: kfree(value); }","static void hid_input_field(struct hid_device *hid, struct hid_field *field, __u8 *data, int interrupt) { unsigned n; unsigned count = field->report_count; unsigned offset = field->report_offset; unsigned size = field->report_size; __s32 min = field->logical_minimum; __s32 max = field->logical_maximum; __s32 *value; value = kmalloc(sizeof(__s32) * count, GFP_ATOMIC); if (!value) return; for (n = 0; n < count; n++) { value[n] = min < 0 ? snto32(hid_field_extract(hid, data, offset + n * size, size), size) : hid_field_extract(hid, data, offset + n * size, size); /* Ignore report if ErrorRollOver */ if (!(field->flags & HID_MAIN_ITEM_VARIABLE) && value[n] >= min && value[n] <= max && value[n] - min < field->maxusage && field->usage[value[n] - min].hid == HID_UP_KEYBOARD + 1) goto exit; } for (n = 0; n < count; n++) { if (HID_MAIN_ITEM_VARIABLE & field->flags) { hid_process_event(hid, field, &field->usage[n], value[n], interrupt); continue; } if (field->value[n] >= min && field->value[n] <= max && field->value[n] - min < field->maxusage && field->usage[field->value[n] - min].hid && search(value, field->value[n], count)) hid_process_event(hid, field, &field->usage[field->value[n] - min], 0, interrupt); if (value[n] >= min && value[n] <= max && value[n] - min < field->maxusage && field->usage[value[n] - min].hid && search(field->value, value[n], count)) hid_process_event(hid, field, &field->usage[value[n] - min], 1, interrupt); } memcpy(field->value, value, count * sizeof(__s32)); exit: kfree(value); }","{'deleted': [], 'added': [{'line_no': 26, 'char_start': 740, 'char_end': 782, 'line': '\t\t value[n] - min < field->maxusage &&\n'}, {'line_no': 39, 'char_start': 1088, 'char_end': 1134, 'line': '\t\t\t&& field->value[n] - min < field->maxusage\n'}, {'line_no': 45, 'char_start': 1354, 'char_end': 1393, 'line': '\t\t\t&& value[n] - min < field->maxusage\n'}]}","{'deleted': [{'char_start': 803, 'char_end': 803, 'chars': ''}, {'char_start': 1225, 'char_end': 1225, 'chars': ''}], 'added': [{'char_start': 746, 'char_end': 788, 'chars': 'value[n] - min < field->maxusage &&\n\t\t '}, {'char_start': 1088, 'char_end': 1134, 'chars': '\t\t\t&& field->value[n] - min < field->maxusage\n'}, {'char_start': 1353, 'char_end': 1392, 'chars': '\n\t\t\t&& value[n] - min < field->maxusage'}]}",github.com/torvalds/linux/commit/50220dead1650609206efe91f0cc116132d59b3f,drivers/hid/hid-core.c,cwe-125,460 cwe-089,add_input," def add_input(self,data): connection = self.connect() try: query = ""INSERT INTO crimes (description) VALUES ('{}');"".format(data) with connection.cursor() as cursor: cursor.execute(query) connection.commit() finally: connection.close()"," def add_input(self,data): connection = self.connect() try: query = ""INSERT INTO crimes (description) VALUES (%s);"" with connection.cursor() as cursor: cursor.execute(query,data) connection.commit() finally: connection.close()","{'deleted': [{'line_no': 5, 'char_start': 80, 'char_end': 163, 'line': ' query = ""INSERT INTO crimes (description) VALUES (\'{}\');"".format(data)\n'}, {'line_no': 7, 'char_start': 211, 'char_end': 249, 'line': ' cursor.execute(query)\n'}], 'added': [{'line_no': 5, 'char_start': 80, 'char_end': 148, 'line': ' query = ""INSERT INTO crimes (description) VALUES (%s);""\n'}, {'line_no': 7, 'char_start': 196, 'char_end': 239, 'line': ' cursor.execute(query,data)\n'}]}","{'deleted': [{'char_start': 142, 'char_end': 146, 'chars': ""'{}'""}, {'char_start': 149, 'char_end': 162, 'chars': '.format(data)'}], 'added': [{'char_start': 142, 'char_end': 144, 'chars': '%s'}, {'char_start': 232, 'char_end': 237, 'chars': ',data'}]}",github.com/sgnab/crime-map-app/commit/209b23bad13594c9cdf18d8788fcba7c8f68d37b,dbhelper.py,cwe-089,58 cwe-190,choose_volume,"choose_volume(struct archive_read *a, struct iso9660 *iso9660) { struct file_info *file; int64_t skipsize; struct vd *vd; const void *block; char seenJoliet; vd = &(iso9660->primary); if (!iso9660->opt_support_joliet) iso9660->seenJoliet = 0; if (iso9660->seenJoliet && vd->location > iso9660->joliet.location) /* This condition is unlikely; by way of caution. */ vd = &(iso9660->joliet); skipsize = LOGICAL_BLOCK_SIZE * vd->location; skipsize = __archive_read_consume(a, skipsize); if (skipsize < 0) return ((int)skipsize); iso9660->current_position = skipsize; block = __archive_read_ahead(a, vd->size, NULL); if (block == NULL) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, ""Failed to read full block when scanning "" ""ISO9660 directory list""); return (ARCHIVE_FATAL); } /* * While reading Root Directory, flag seenJoliet must be zero to * avoid converting special name 0x00(Current Directory) and * next byte to UCS2. */ seenJoliet = iso9660->seenJoliet;/* Save flag. */ iso9660->seenJoliet = 0; file = parse_file_info(a, NULL, block); if (file == NULL) return (ARCHIVE_FATAL); iso9660->seenJoliet = seenJoliet; /* * If the iso image has both RockRidge and Joliet, we preferentially * use RockRidge Extensions rather than Joliet ones. */ if (vd == &(iso9660->primary) && iso9660->seenRockridge && iso9660->seenJoliet) iso9660->seenJoliet = 0; if (vd == &(iso9660->primary) && !iso9660->seenRockridge && iso9660->seenJoliet) { /* Switch reading data from primary to joliet. */ vd = &(iso9660->joliet); skipsize = LOGICAL_BLOCK_SIZE * vd->location; skipsize -= iso9660->current_position; skipsize = __archive_read_consume(a, skipsize); if (skipsize < 0) return ((int)skipsize); iso9660->current_position += skipsize; block = __archive_read_ahead(a, vd->size, NULL); if (block == NULL) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, ""Failed to read full block when scanning "" ""ISO9660 directory list""); return (ARCHIVE_FATAL); } iso9660->seenJoliet = 0; file = parse_file_info(a, NULL, block); if (file == NULL) return (ARCHIVE_FATAL); iso9660->seenJoliet = seenJoliet; } /* Store the root directory in the pending list. */ if (add_entry(a, iso9660, file) != ARCHIVE_OK) return (ARCHIVE_FATAL); if (iso9660->seenRockridge) { a->archive.archive_format = ARCHIVE_FORMAT_ISO9660_ROCKRIDGE; a->archive.archive_format_name = ""ISO9660 with Rockridge extensions""; } return (ARCHIVE_OK); }","choose_volume(struct archive_read *a, struct iso9660 *iso9660) { struct file_info *file; int64_t skipsize; struct vd *vd; const void *block; char seenJoliet; vd = &(iso9660->primary); if (!iso9660->opt_support_joliet) iso9660->seenJoliet = 0; if (iso9660->seenJoliet && vd->location > iso9660->joliet.location) /* This condition is unlikely; by way of caution. */ vd = &(iso9660->joliet); skipsize = LOGICAL_BLOCK_SIZE * (int64_t)vd->location; skipsize = __archive_read_consume(a, skipsize); if (skipsize < 0) return ((int)skipsize); iso9660->current_position = skipsize; block = __archive_read_ahead(a, vd->size, NULL); if (block == NULL) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, ""Failed to read full block when scanning "" ""ISO9660 directory list""); return (ARCHIVE_FATAL); } /* * While reading Root Directory, flag seenJoliet must be zero to * avoid converting special name 0x00(Current Directory) and * next byte to UCS2. */ seenJoliet = iso9660->seenJoliet;/* Save flag. */ iso9660->seenJoliet = 0; file = parse_file_info(a, NULL, block); if (file == NULL) return (ARCHIVE_FATAL); iso9660->seenJoliet = seenJoliet; /* * If the iso image has both RockRidge and Joliet, we preferentially * use RockRidge Extensions rather than Joliet ones. */ if (vd == &(iso9660->primary) && iso9660->seenRockridge && iso9660->seenJoliet) iso9660->seenJoliet = 0; if (vd == &(iso9660->primary) && !iso9660->seenRockridge && iso9660->seenJoliet) { /* Switch reading data from primary to joliet. */ vd = &(iso9660->joliet); skipsize = LOGICAL_BLOCK_SIZE * (int64_t)vd->location; skipsize -= iso9660->current_position; skipsize = __archive_read_consume(a, skipsize); if (skipsize < 0) return ((int)skipsize); iso9660->current_position += skipsize; block = __archive_read_ahead(a, vd->size, NULL); if (block == NULL) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, ""Failed to read full block when scanning "" ""ISO9660 directory list""); return (ARCHIVE_FATAL); } iso9660->seenJoliet = 0; file = parse_file_info(a, NULL, block); if (file == NULL) return (ARCHIVE_FATAL); iso9660->seenJoliet = seenJoliet; } /* Store the root directory in the pending list. */ if (add_entry(a, iso9660, file) != ARCHIVE_OK) return (ARCHIVE_FATAL); if (iso9660->seenRockridge) { a->archive.archive_format = ARCHIVE_FORMAT_ISO9660_ROCKRIDGE; a->archive.archive_format_name = ""ISO9660 with Rockridge extensions""; } return (ARCHIVE_OK); }","{'deleted': [{'line_no': 17, 'char_start': 407, 'char_end': 454, 'line': '\tskipsize = LOGICAL_BLOCK_SIZE * vd->location;\n'}, {'line_no': 55, 'char_start': 1599, 'char_end': 1647, 'line': '\t\tskipsize = LOGICAL_BLOCK_SIZE * vd->location;\n'}], 'added': [{'line_no': 17, 'char_start': 407, 'char_end': 463, 'line': '\tskipsize = LOGICAL_BLOCK_SIZE * (int64_t)vd->location;\n'}, {'line_no': 55, 'char_start': 1608, 'char_end': 1665, 'line': '\t\tskipsize = LOGICAL_BLOCK_SIZE * (int64_t)vd->location;\n'}]}","{'deleted': [], 'added': [{'char_start': 440, 'char_end': 449, 'chars': '(int64_t)'}, {'char_start': 1642, 'char_end': 1651, 'chars': '(int64_t)'}]}",github.com/libarchive/libarchive/commit/3ad08e01b4d253c66ae56414886089684155af22,libarchive/archive_read_support_format_iso9660.c,cwe-190,862 cwe-022,misc_file_checks," def misc_file_checks(self): print_header(""MISC FILE CHECKS"") # # Check for recommended and mandatory files # filenames = (""manifest.json"", ""LICENSE"", ""README.md"", ""scripts/install"", ""scripts/remove"", ""scripts/upgrade"", ""scripts/backup"", ""scripts/restore"") non_mandatory = (""script/backup"", ""script/restore"") for filename in filenames: if file_exists(self.path + ""/"" + filename): continue elif filename in non_mandatory: print_warning(""Consider adding a file %s"" % filename) else: print_error(""File %s is mandatory"" % filename) # # Deprecated php-fpm.ini thing # if file_exists(self.path + ""/conf/php-fpm.ini""): print_warning( ""Using a separate php-fpm.ini file is deprecated. "" ""Please merge your php-fpm directives directly in the pool file. "" ""(c.f. https://github.com/YunoHost-Apps/nextcloud_ynh/issues/138 )"" ) # # Deprecated usage of 'add_header' in nginx conf # for filename in os.listdir(self.path + ""/conf""): if not os.path.isfile(self.path + ""/conf/"" + filename): continue content = open(self.path + ""/conf/"" + filename).read() if ""location"" in content and ""add_header"" in content: print_warning( ""Do not use 'add_header' in the nginx conf. Use 'more_set_headers' instead. "" ""(See https://www.peterbe.com/plog/be-very-careful-with-your-add_header-in-nginx "" ""and https://github.com/openresty/headers-more-nginx-module#more_set_headers )"" )"," def misc_file_checks(self): print_header(""MISC FILE CHECKS"") # # Check for recommended and mandatory files # filenames = (""manifest.json"", ""LICENSE"", ""README.md"", ""scripts/install"", ""scripts/remove"", ""scripts/upgrade"", ""scripts/backup"", ""scripts/restore"") non_mandatory = (""script/backup"", ""script/restore"") for filename in filenames: if file_exists(self.path + ""/"" + filename): continue elif filename in non_mandatory: print_warning(""Consider adding a file %s"" % filename) else: print_error(""File %s is mandatory"" % filename) # # Deprecated php-fpm.ini thing # if file_exists(self.path + ""/conf/php-fpm.ini""): print_warning( ""Using a separate php-fpm.ini file is deprecated. "" ""Please merge your php-fpm directives directly in the pool file. "" ""(c.f. https://github.com/YunoHost-Apps/nextcloud_ynh/issues/138 )"" ) # # Analyze nginx conf # - Deprecated usage of 'add_header' in nginx conf # - Spot path traversal issue vulnerability # for filename in os.listdir(self.path + ""/conf""): # Ignore subdirs or filename not containing nginx in the name if not os.path.isfile(self.path + ""/conf/"" + filename) or ""nginx"" not in filename: continue # # 'add_header' usage # content = open(self.path + ""/conf/"" + filename).read() if ""location"" in content and ""add_header"" in content: print_warning( ""Do not use 'add_header' in the nginx conf. Use 'more_set_headers' instead. "" ""(See https://www.peterbe.com/plog/be-very-careful-with-your-add_header-in-nginx "" ""and https://github.com/openresty/headers-more-nginx-module#more_set_headers )"" ) # # Path traversal issues # lines = open(self.path + ""/conf/"" + filename).readlines() lines = [line.strip() for line in lines if not line.strip().startswith(""#"")] # Let's find the first location line location_line = None path_traversal_vulnerable = False lines_iter = lines.__iter__() for line in lines_iter: if line.startswith(""location""): location_line = line break # Look at the next lines for an 'alias' directive if location_line is not None: for line in lines_iter: if line.startswith(""location""): # Entering a new location block ... abort here # and assume there's no alias block later... break if line.startswith(""alias""): # We should definitely check for path traversal issue # Does the location target ends with / ? target = location_line.split()[-2] if not target.endswith(""/""): path_traversal_vulnerable = True break if path_traversal_vulnerable: print_warning( ""The nginx configuration appears vulnerable to path traversal as explained in "" ""https://www.acunetix.com/vulnerabilities/web/path-traversal-via-misconfigured-nginx-alias/\n"" ""To fix it, look at the first lines of the nginx conf of the example app : "" ""https://github.com/YunoHost/example_ynh/blob/master/conf/nginx.conf"" )","{'deleted': [{'line_no': 39, 'char_start': 1268, 'char_end': 1336, 'line': ' if not os.path.isfile(self.path + ""/conf/"" + filename):\n'}], 'added': [{'line_no': 42, 'char_start': 1425, 'char_end': 1520, 'line': ' if not os.path.isfile(self.path + ""/conf/"" + filename) or ""nginx"" not in filename:\n'}, {'line_no': 44, 'char_start': 1545, 'char_end': 1546, 'line': '\n'}]}","{'deleted': [], 'added': [{'char_start': 1153, 'char_end': 1184, 'chars': 'Analyze nginx conf\n # - '}, {'char_start': 1240, 'char_end': 1292, 'chars': ' - Spot path traversal issue vulnerability\n #'}, {'char_start': 1363, 'char_end': 1437, 'chars': '# Ignore subdirs or filename not containing nginx in the name\n '}, {'char_start': 1491, 'char_end': 1518, 'chars': ' or ""nginx"" not in filename'}, {'char_start': 1544, 'char_end': 1606, 'chars': ""\n\n #\n # 'add_header' usage\n #""}, {'char_start': 2089, 'char_end': 3888, 'chars': '\n\n #\n # Path traversal issues\n #\n lines = open(self.path + ""/conf/"" + filename).readlines()\n lines = [line.strip() for line in lines if not line.strip().startswith(""#"")]\n # Let\'s find the first location line\n location_line = None\n path_traversal_vulnerable = False\n lines_iter = lines.__iter__()\n for line in lines_iter:\n if line.startswith(""location""):\n location_line = line\n break\n # Look at the next lines for an \'alias\' directive\n if location_line is not None:\n for line in lines_iter:\n if line.startswith(""location""):\n # Entering a new location block ... abort here\n # and assume there\'s no alias block later...\n break\n if line.startswith(""alias""):\n # We should definitely check for path traversal issue\n # Does the location target ends with / ?\n target = location_line.split()[-2]\n if not target.endswith(""/""):\n path_traversal_vulnerable = True\n break\n if path_traversal_vulnerable:\n print_warning(\n ""The nginx configuration appears vulnerable to path traversal as explained in ""\n ""https://www.acunetix.com/vulnerabilities/web/path-traversal-via-misconfigured-nginx-alias/\\n""\n ""To fix it, look at the first lines of the nginx conf of the example app : ""\n ""https://github.com/YunoHost/example_ynh/blob/master/conf/nginx.conf""\n )'}]}",github.com/YunoHost/package_linter/commit/f6e98894cfe841aedaa7efd590937f0255193913,package_linter.py,cwe-022,386 cwe-190,authDigestNonceLink,"authDigestNonceLink(digest_nonce_h * nonce) { assert(nonce != NULL); ++nonce->references; debugs(29, 9, ""nonce '"" << nonce << ""' now at '"" << nonce->references << ""'.""); }","authDigestNonceLink(digest_nonce_h * nonce) { assert(nonce != NULL); ++nonce->references; assert(nonce->references != 0); // no overflows debugs(29, 9, ""nonce '"" << nonce << ""' now at '"" << nonce->references << ""'.""); }","{'deleted': [], 'added': [{'line_no': 5, 'char_start': 98, 'char_end': 150, 'line': ' assert(nonce->references != 0); // no overflows\n'}]}","{'deleted': [], 'added': [{'char_start': 102, 'char_end': 154, 'chars': 'assert(nonce->references != 0); // no overflows\n '}]}",github.com/squid-cache/squid/commit/eeebf0f37a72a2de08348e85ae34b02c34e9a811,src/auth/digest/Config.cc,cwe-190,53 cwe-089,set_state,"def set_state(chat_id, value): settings = sqlite3.connect(os.path.abspath(os.path.dirname(__file__)) + ""\\bases\\settings.db"") conn = settings.cursor() conn.execute(""update users set state ='"" + str(value) + ""' where chat_id = '"" + str(chat_id) + ""'"") settings.commit() settings.close()","def set_state(chat_id, value): settings = sqlite3.connect(os.path.abspath(os.path.dirname(__file__)) + ""\\bases\\settings.db"") conn = settings.cursor() conn.execute(""update users set state = ? where chat_id = ?"", (str(value), str(chat_id))) settings.commit() settings.close()","{'deleted': [{'line_no': 4, 'char_start': 160, 'char_end': 264, 'line': ' conn.execute(""update users set state =\'"" + str(value) + ""\' where chat_id = \'"" + str(chat_id) + ""\'"")\n'}], 'added': [{'line_no': 4, 'char_start': 160, 'char_end': 253, 'line': ' conn.execute(""update users set state = ? where chat_id = ?"", (str(value), str(chat_id)))\n'}]}","{'deleted': [{'char_start': 202, 'char_end': 204, 'chars': '\'""'}, {'char_start': 205, 'char_end': 222, 'chars': '+ str(value) + ""\''}, {'char_start': 239, 'char_end': 240, 'chars': ""'""}, {'char_start': 242, 'char_end': 243, 'chars': '+'}, {'char_start': 256, 'char_end': 262, 'chars': ' + ""\'""'}], 'added': [{'char_start': 203, 'char_end': 204, 'chars': '?'}, {'char_start': 221, 'char_end': 222, 'chars': '?'}, {'char_start': 223, 'char_end': 224, 'chars': ','}, {'char_start': 225, 'char_end': 237, 'chars': '(str(value),'}, {'char_start': 250, 'char_end': 251, 'chars': ')'}]}",github.com/lissrbay/codeforces_bot/commit/cc7f5143445a0030b1149ac60a65b1b1b9c92a90,bot.py,cwe-089,73 cwe-416,snd_pcm_period_elapsed,"void snd_pcm_period_elapsed(struct snd_pcm_substream *substream) { struct snd_pcm_runtime *runtime; unsigned long flags; if (PCM_RUNTIME_CHECK(substream)) return; runtime = substream->runtime; snd_pcm_stream_lock_irqsave(substream, flags); if (!snd_pcm_running(substream) || snd_pcm_update_hw_ptr0(substream, 1) < 0) goto _end; #ifdef CONFIG_SND_PCM_TIMER if (substream->timer_running) snd_timer_interrupt(substream->timer, 1); #endif _end: snd_pcm_stream_unlock_irqrestore(substream, flags); kill_fasync(&runtime->fasync, SIGIO, POLL_IN); }","void snd_pcm_period_elapsed(struct snd_pcm_substream *substream) { struct snd_pcm_runtime *runtime; unsigned long flags; if (PCM_RUNTIME_CHECK(substream)) return; runtime = substream->runtime; snd_pcm_stream_lock_irqsave(substream, flags); if (!snd_pcm_running(substream) || snd_pcm_update_hw_ptr0(substream, 1) < 0) goto _end; #ifdef CONFIG_SND_PCM_TIMER if (substream->timer_running) snd_timer_interrupt(substream->timer, 1); #endif _end: kill_fasync(&runtime->fasync, SIGIO, POLL_IN); snd_pcm_stream_unlock_irqrestore(substream, flags); }","{'deleted': [{'line_no': 20, 'char_start': 463, 'char_end': 516, 'line': '\tsnd_pcm_stream_unlock_irqrestore(substream, flags);\n'}], 'added': [{'line_no': 21, 'char_start': 511, 'char_end': 564, 'line': '\tsnd_pcm_stream_unlock_irqrestore(substream, flags);\n'}]}","{'deleted': [{'char_start': 513, 'char_end': 561, 'chars': ');\n\tkill_fasync(&runtime->fasync, SIGIO, POLL_IN'}], 'added': [{'char_start': 464, 'char_end': 512, 'chars': 'kill_fasync(&runtime->fasync, SIGIO, POLL_IN);\n\t'}]}",github.com/torvalds/linux/commit/3aa02cb664c5fb1042958c8d1aa8c35055a2ebc4,sound/core/pcm_lib.c,cwe-416,150 cwe-089,add_month_data_row," def add_month_data_row(self, inverter_serial, ts, etoday, etotal): y = datetime.fromtimestamp(ts) - timedelta(days=1) y_ts = int(datetime(y.year, y.month, y.day, 23, tzinfo=pytz.utc).timestamp()) query = ''' INSERT INTO MonthData ( TimeStamp, Serial, DayYield, TotalYield ) VALUES ( %s, %s, %s, %s ); ''' % (y_ts, inverter_serial, etoday, etotal) self.c.execute(query)"," def add_month_data_row(self, inverter_serial, ts, etoday, etotal): y = datetime.fromtimestamp(ts) - timedelta(days=1) y_ts = int(datetime(y.year, y.month, y.day, 23, tzinfo=pytz.utc).timestamp()) query = ''' INSERT INTO MonthData ( TimeStamp, Serial, DayYield, TotalYield ) VALUES ( ?, ?, ?, ? ); ''' self.c.execute(query, (y_ts, inverter_serial, etoday, etotal))","{'deleted': [{'line_no': 13, 'char_start': 434, 'char_end': 454, 'line': ' %s,\n'}, {'line_no': 14, 'char_start': 454, 'char_end': 474, 'line': ' %s,\n'}, {'line_no': 15, 'char_start': 474, 'char_end': 494, 'line': ' %s,\n'}, {'line_no': 16, 'char_start': 494, 'char_end': 513, 'line': ' %s\n'}, {'line_no': 18, 'char_start': 528, 'char_end': 582, 'line': "" ''' % (y_ts, inverter_serial, etoday, etotal)\n""}, {'line_no': 19, 'char_start': 582, 'char_end': 611, 'line': ' self.c.execute(query)\n'}], 'added': [{'line_no': 13, 'char_start': 434, 'char_end': 453, 'line': ' ?,\n'}, {'line_no': 14, 'char_start': 453, 'char_end': 472, 'line': ' ?,\n'}, {'line_no': 15, 'char_start': 472, 'char_end': 491, 'line': ' ?,\n'}, {'line_no': 16, 'char_start': 491, 'char_end': 509, 'line': ' ?\n'}, {'line_no': 18, 'char_start': 524, 'char_end': 536, 'line': "" '''\n""}, {'line_no': 19, 'char_start': 536, 'char_end': 606, 'line': ' self.c.execute(query, (y_ts, inverter_serial, etoday, etotal))\n'}]}","{'deleted': [{'char_start': 450, 'char_end': 452, 'chars': '%s'}, {'char_start': 470, 'char_end': 472, 'chars': '%s'}, {'char_start': 490, 'char_end': 492, 'chars': '%s'}, {'char_start': 510, 'char_end': 512, 'chars': '%s'}, {'char_start': 540, 'char_end': 541, 'chars': '%'}, {'char_start': 581, 'char_end': 610, 'chars': '\n self.c.execute(query'}], 'added': [{'char_start': 450, 'char_end': 451, 'chars': '?'}, {'char_start': 469, 'char_end': 470, 'chars': '?'}, {'char_start': 488, 'char_end': 489, 'chars': '?'}, {'char_start': 507, 'char_end': 508, 'chars': '?'}, {'char_start': 535, 'char_end': 541, 'chars': '\n '}, {'char_start': 542, 'char_end': 565, 'chars': ' self.c.execute(query,'}]}",github.com/philipptrenz/s0-bridge/commit/269b48caa05377b7c58c3e6d1622a4429cb5ba65,util/database.py,cwe-089,135 cwe-125,read_quant_matrix_ext,"static void read_quant_matrix_ext(MpegEncContext *s, GetBitContext *gb) { int i, j, v; if (get_bits1(gb)) { /* intra_quantiser_matrix */ for (i = 0; i < 64; i++) { v = get_bits(gb, 8); j = s->idsp.idct_permutation[ff_zigzag_direct[i]]; s->intra_matrix[j] = v; s->chroma_intra_matrix[j] = v; } } if (get_bits1(gb)) { /* non_intra_quantiser_matrix */ for (i = 0; i < 64; i++) { get_bits(gb, 8); } } if (get_bits1(gb)) { /* chroma_intra_quantiser_matrix */ for (i = 0; i < 64; i++) { v = get_bits(gb, 8); j = s->idsp.idct_permutation[ff_zigzag_direct[i]]; s->chroma_intra_matrix[j] = v; } } if (get_bits1(gb)) { /* chroma_non_intra_quantiser_matrix */ for (i = 0; i < 64; i++) { get_bits(gb, 8); } } next_start_code_studio(gb); }","static int read_quant_matrix_ext(MpegEncContext *s, GetBitContext *gb) { int i, j, v; if (get_bits1(gb)) { if (get_bits_left(gb) < 64*8) return AVERROR_INVALIDDATA; /* intra_quantiser_matrix */ for (i = 0; i < 64; i++) { v = get_bits(gb, 8); j = s->idsp.idct_permutation[ff_zigzag_direct[i]]; s->intra_matrix[j] = v; s->chroma_intra_matrix[j] = v; } } if (get_bits1(gb)) { if (get_bits_left(gb) < 64*8) return AVERROR_INVALIDDATA; /* non_intra_quantiser_matrix */ for (i = 0; i < 64; i++) { get_bits(gb, 8); } } if (get_bits1(gb)) { if (get_bits_left(gb) < 64*8) return AVERROR_INVALIDDATA; /* chroma_intra_quantiser_matrix */ for (i = 0; i < 64; i++) { v = get_bits(gb, 8); j = s->idsp.idct_permutation[ff_zigzag_direct[i]]; s->chroma_intra_matrix[j] = v; } } if (get_bits1(gb)) { if (get_bits_left(gb) < 64*8) return AVERROR_INVALIDDATA; /* chroma_non_intra_quantiser_matrix */ for (i = 0; i < 64; i++) { get_bits(gb, 8); } } next_start_code_studio(gb); return 0; }","{'deleted': [{'line_no': 1, 'char_start': 0, 'char_end': 72, 'line': 'static void read_quant_matrix_ext(MpegEncContext *s, GetBitContext *gb)\n'}], 'added': [{'line_no': 1, 'char_start': 0, 'char_end': 71, 'line': 'static int read_quant_matrix_ext(MpegEncContext *s, GetBitContext *gb)\n'}, {'line_no': 6, 'char_start': 116, 'char_end': 154, 'line': ' if (get_bits_left(gb) < 64*8)\n'}, {'line_no': 7, 'char_start': 154, 'char_end': 194, 'line': ' return AVERROR_INVALIDDATA;\n'}, {'line_no': 18, 'char_start': 490, 'char_end': 528, 'line': ' if (get_bits_left(gb) < 64*8)\n'}, {'line_no': 19, 'char_start': 528, 'char_end': 568, 'line': ' return AVERROR_INVALIDDATA;\n'}, {'line_no': 27, 'char_start': 715, 'char_end': 753, 'line': ' if (get_bits_left(gb) < 64*8)\n'}, {'line_no': 28, 'char_start': 753, 'char_end': 793, 'line': ' return AVERROR_INVALIDDATA;\n'}, {'line_no': 38, 'char_start': 1053, 'char_end': 1091, 'line': ' if (get_bits_left(gb) < 64*8)\n'}, {'line_no': 39, 'char_start': 1091, 'char_end': 1131, 'line': ' return AVERROR_INVALIDDATA;\n'}, {'line_no': 47, 'char_start': 1292, 'char_end': 1306, 'line': ' return 0;\n'}]}","{'deleted': [{'char_start': 7, 'char_end': 9, 'chars': 'vo'}, {'char_start': 10, 'char_end': 11, 'chars': 'd'}], 'added': [{'char_start': 8, 'char_end': 10, 'chars': 'nt'}, {'char_start': 115, 'char_end': 193, 'chars': '\n if (get_bits_left(gb) < 64*8)\n return AVERROR_INVALIDDATA;'}, {'char_start': 490, 'char_end': 568, 'chars': ' if (get_bits_left(gb) < 64*8)\n return AVERROR_INVALIDDATA;\n'}, {'char_start': 715, 'char_end': 793, 'chars': ' if (get_bits_left(gb) < 64*8)\n return AVERROR_INVALIDDATA;\n'}, {'char_start': 1053, 'char_end': 1131, 'chars': ' if (get_bits_left(gb) < 64*8)\n return AVERROR_INVALIDDATA;\n'}, {'char_start': 1290, 'char_end': 1304, 'chars': ';\n return 0'}]}",github.com/FFmpeg/FFmpeg/commit/5aba5b89d0b1d73164d3b81764828bb8b20ff32a,libavcodec/mpeg4videodec.c,cwe-125,315 cwe-078,_get_least_used_nsp," def _get_least_used_nsp(self, nspss): """"""""Return the nsp that has the fewest active vluns."""""" # return only the nsp (node:server:port) result = self.common._cli_run('showvlun -a -showcols Port', None) # count the number of nsps (there is 1 for each active vlun) nsp_counts = {} for nsp in nspss: # initialize counts to zero nsp_counts[nsp] = 0 current_least_used_nsp = None if result: # first line is header result = result[1:] for line in result: nsp = line.strip() if nsp in nsp_counts: nsp_counts[nsp] = nsp_counts[nsp] + 1 # identify key (nsp) of least used nsp current_smallest_count = sys.maxint for (nsp, count) in nsp_counts.iteritems(): if count < current_smallest_count: current_least_used_nsp = nsp current_smallest_count = count return current_least_used_nsp"," def _get_least_used_nsp(self, nspss): """"""""Return the nsp that has the fewest active vluns."""""" # return only the nsp (node:server:port) result = self.common._cli_run(['showvlun', '-a', '-showcols', 'Port']) # count the number of nsps (there is 1 for each active vlun) nsp_counts = {} for nsp in nspss: # initialize counts to zero nsp_counts[nsp] = 0 current_least_used_nsp = None if result: # first line is header result = result[1:] for line in result: nsp = line.strip() if nsp in nsp_counts: nsp_counts[nsp] = nsp_counts[nsp] + 1 # identify key (nsp) of least used nsp current_smallest_count = sys.maxint for (nsp, count) in nsp_counts.iteritems(): if count < current_smallest_count: current_least_used_nsp = nsp current_smallest_count = count return current_least_used_nsp","{'deleted': [{'line_no': 4, 'char_start': 155, 'char_end': 229, 'line': "" result = self.common._cli_run('showvlun -a -showcols Port', None)\n""}], 'added': [{'line_no': 4, 'char_start': 155, 'char_end': 234, 'line': "" result = self.common._cli_run(['showvlun', '-a', '-showcols', 'Port'])\n""}]}","{'deleted': [{'char_start': 221, 'char_end': 227, 'chars': ', None'}], 'added': [{'char_start': 193, 'char_end': 194, 'chars': '['}, {'char_start': 203, 'char_end': 205, 'chars': ""',""}, {'char_start': 206, 'char_end': 207, 'chars': ""'""}, {'char_start': 209, 'char_end': 211, 'chars': ""',""}, {'char_start': 212, 'char_end': 213, 'chars': ""'""}, {'char_start': 222, 'char_end': 224, 'chars': ""',""}, {'char_start': 225, 'char_end': 226, 'chars': ""'""}, {'char_start': 231, 'char_end': 232, 'chars': ']'}]}",github.com/thatsdone/cinder/commit/c55589b131828f3a595903f6796cb2d0babb772f,cinder/volume/drivers/san/hp/hp_3par_iscsi.py,cwe-078,256 cwe-078,verify," def verify(self, data): credentials = self._formatCredentials(data, name='current') command = '{} rclone lsjson current:'.format(credentials) try: result = self._execute(command) return { 'result': True, 'message': 'Success', } except subprocess.CalledProcessError as e: returncode = e.returncode return { 'result': False, 'message': 'Exit status {}'.format(returncode), }"," def verify(self, data): credentials = self._formatCredentials(data, name='current') command = [ 'rclone', 'lsjson', 'current:', ] try: result = self._execute(command, credentials) return { 'result': True, 'message': 'Success', } except subprocess.CalledProcessError as e: returncode = e.returncode return { 'result': False, 'message': 'Exit status {}'.format(returncode), }","{'deleted': [{'line_no': 3, 'char_start': 96, 'char_end': 162, 'line': "" command = '{} rclone lsjson current:'.format(credentials)\n""}, {'line_no': 6, 'char_start': 176, 'char_end': 220, 'line': ' result = self._execute(command)\n'}], 'added': [{'line_no': 3, 'char_start': 96, 'char_end': 116, 'line': ' command = [\n'}, {'line_no': 4, 'char_start': 116, 'char_end': 138, 'line': "" 'rclone',\n""}, {'line_no': 5, 'char_start': 138, 'char_end': 160, 'line': "" 'lsjson',\n""}, {'line_no': 6, 'char_start': 160, 'char_end': 184, 'line': "" 'current:',\n""}, {'line_no': 7, 'char_start': 184, 'char_end': 194, 'line': ' ]\n'}, {'line_no': 10, 'char_start': 208, 'char_end': 265, 'line': ' result = self._execute(command, credentials)\n'}]}","{'deleted': [{'char_start': 115, 'char_end': 118, 'chars': '{} '}, {'char_start': 141, 'char_end': 161, 'chars': '.format(credentials)'}], 'added': [{'char_start': 114, 'char_end': 123, 'chars': '[\n '}, {'char_start': 124, 'char_end': 129, 'chars': "" '""}, {'char_start': 135, 'char_end': 141, 'chars': ""',\n ""}, {'char_start': 142, 'char_end': 151, 'chars': "" '""}, {'char_start': 157, 'char_end': 171, 'chars': ""',\n ""}, {'char_start': 172, 'char_end': 173, 'chars': ""'""}, {'char_start': 182, 'char_end': 193, 'chars': ',\n ]'}, {'char_start': 250, 'char_end': 263, 'chars': ', credentials'}]}",github.com/FredHutch/motuz/commit/045468cb9bff47bb3bb72268b6d5a3fe44e383db,src/backend/api/utils/rclone_connection.py,cwe-078,104 cwe-078,start,"def start(): print(""[*] Starting backdoor process"") print(""[*] Decompressing target to tmp directory..."") #subprocess.call(""jar -x %s"" % target, shell=True) with zipfile.ZipFile(target, 'r') as zip: zip.extractall(""tmp"") print(""[*] Target dumped to tmp directory"") print(""[*] Modifying manifest file..."") oldmain="""" man = open(""tmp/META-INF/MANIFEST.MF"",""r"").read() with open(""tmp/META-INF/MANIFEST.MF"",""w"") as f: for l in man.split(""\n""): if ""Main-Class"" in l: oldmain=l[12:] f.write(""Main-Class: %s\n"" % ""Backdoor"") else: f.write(""%s\n"" % l) print(""[*] Manifest file modified"") print(""[*] Modifying provided backdoor..."") inmain=False level=0 bd=open(backdoor, ""r"").read() with open(""tmp/%s"" % backdoor,'w') as f: for l in bd.split(""\n""): if ""main("" in l: inmain=True f.write(l) elif ""}"" in l and level<2 and inmain: f.write(""%s.main(args);}"" % oldmain) inmain=False elif ""}"" in l and level>1 and inmain: level-=1 f.write(l) elif ""{"" in l and inmain: level+=1 f.write(l) else: f.write(l) print(""[*] Provided backdoor successfully modified"") print(""[*] Compiling modified backdoor..."") if subprocess.call(""javac -cp tmp/ tmp/%s"" % backdoor, shell=True) != 0: print(""[!] Error compiling %s"" % backdoor) print(""[*] Compiled modified backdoor"") if(len(oldmain)<1): print(""[!] Main-Class manifest attribute not found"") else: print(""[*] Repackaging target jar file..."") createZip(""tmp"",outfile) print(""[*] Target jar successfully repackaged"") shutil.rmtree('tmp/')","def start(): print(""[*] Starting backdoor process"") print(""[*] Decompressing target to tmp directory..."") #subprocess.call(""jar -x %s"" % target, shell=True) with zipfile.ZipFile(target, 'r') as zip: zip.extractall(""tmp"") print(""[*] Target dumped to tmp directory"") print(""[*] Modifying manifest file..."") oldmain="""" man = open(""tmp/META-INF/MANIFEST.MF"",""r"").read() with open(""tmp/META-INF/MANIFEST.MF"",""w"") as f: for l in man.split(""\n""): if ""Main-Class"" in l: oldmain=l[12:] f.write(""Main-Class: %s\n"" % ""Backdoor"") else: f.write(""%s\n"" % l) print(""[*] Manifest file modified"") print(""[*] Modifying provided backdoor..."") inmain=False level=0 bd=open(backdoor, ""r"").read() with open(""tmp/%s"" % backdoor,'w') as f: for l in bd.split(""\n""): if ""main("" in l: inmain=True f.write(l) elif ""}"" in l and level<2 and inmain: f.write(""%s.main(args);}"" % oldmain) inmain=False elif ""}"" in l and level>1 and inmain: level-=1 f.write(l) elif ""{"" in l and inmain: level+=1 f.write(l) else: f.write(l) print(""[*] Provided backdoor successfully modified"") print(""[*] Compiling modified backdoor..."") #if subprocess.call(""javac -cp tmp/ tmp/%s"" % backdoor, shell=True) != 0: if subprocess.call(['javac','-cp','tmp/','tmp/%s'%backdoor],shell=False) != 0: print(""[!] Error compiling %s"" % backdoor) print(""[*] Compiled modified backdoor"") if(len(oldmain)<1): print(""[!] Main-Class manifest attribute not found"") else: print(""[*] Repackaging target jar file..."") createZip(""tmp"",outfile) print(""[*] Target jar successfully repackaged"") shutil.rmtree('tmp/')","{'deleted': [{'line_no': 44, 'char_start': 1462, 'char_end': 1539, 'line': ' if subprocess.call(""javac -cp tmp/ tmp/%s"" % backdoor, shell=True) != 0:\n'}], 'added': [{'line_no': 45, 'char_start': 1540, 'char_end': 1623, 'line': "" if subprocess.call(['javac','-cp','tmp/','tmp/%s'%backdoor],shell=False) != 0:\n""}]}","{'deleted': [], 'added': [{'char_start': 1466, 'char_end': 1467, 'chars': '#'}, {'char_start': 1531, 'char_end': 1614, 'chars': ""e) != 0:\n if subprocess.call(['javac','-cp','tmp/','tmp/%s'%backdoor],shell=Fals""}]}",github.com/Atticuss/ajar/commit/5ed8aba271ad20e6168f2e3bd6c25ba89b84484f,ajar.py,cwe-078,483 cwe-787,idn2_to_ascii_4i,"idn2_to_ascii_4i (const uint32_t * input, size_t inlen, char * output, int flags) { uint32_t *input_u32; uint8_t *input_u8, *output_u8; size_t length; int rc; if (!input) { if (output) *output = 0; return IDN2_OK; } input_u32 = (uint32_t *) malloc ((inlen + 1) * sizeof(uint32_t)); if (!input_u32) return IDN2_MALLOC; u32_cpy (input_u32, input, inlen); input_u32[inlen] = 0; input_u8 = u32_to_u8 (input_u32, inlen + 1, NULL, &length); free (input_u32); if (!input_u8) { if (errno == ENOMEM) return IDN2_MALLOC; return IDN2_ENCODING_ERROR; } rc = idn2_lookup_u8 (input_u8, &output_u8, flags); free (input_u8); if (rc == IDN2_OK) { /* wow, this is ugly, but libidn manpage states: * char * out output zero terminated string that must have room for at * least 63 characters plus the terminating zero. */ if (output) strcpy (output, (const char *) output_u8); free(output_u8); } return rc; }","idn2_to_ascii_4i (const uint32_t * input, size_t inlen, char * output, int flags) { uint32_t *input_u32; uint8_t *input_u8, *output_u8; size_t length; int rc; if (!input) { if (output) *output = 0; return IDN2_OK; } input_u32 = (uint32_t *) malloc ((inlen + 1) * sizeof(uint32_t)); if (!input_u32) return IDN2_MALLOC; u32_cpy (input_u32, input, inlen); input_u32[inlen] = 0; input_u8 = u32_to_u8 (input_u32, inlen + 1, NULL, &length); free (input_u32); if (!input_u8) { if (errno == ENOMEM) return IDN2_MALLOC; return IDN2_ENCODING_ERROR; } rc = idn2_lookup_u8 (input_u8, &output_u8, flags); free (input_u8); if (rc == IDN2_OK) { /* wow, this is ugly, but libidn manpage states: * char * out output zero terminated string that must have room for at * least 63 characters plus the terminating zero. */ size_t len = strlen ((char *) output_u8); if (len > 63) { free (output_u8); return IDN2_TOO_BIG_DOMAIN; } if (output) strcpy (output, (char *) output_u8); free (output_u8); } return rc; }","{'deleted': [{'line_no': 41, 'char_start': 933, 'char_end': 977, 'line': '\tstrcpy (output, (const char *) output_u8);\n'}, {'line_no': 43, 'char_start': 978, 'char_end': 1001, 'line': ' free(output_u8);\n'}], 'added': [{'line_no': 40, 'char_start': 915, 'char_end': 963, 'line': ' size_t len = strlen ((char *) output_u8);\n'}, {'line_no': 41, 'char_start': 963, 'char_end': 964, 'line': '\n'}, {'line_no': 42, 'char_start': 964, 'char_end': 984, 'line': ' if (len > 63)\n'}, {'line_no': 43, 'char_start': 984, 'char_end': 994, 'line': ' {\n'}, {'line_no': 44, 'char_start': 994, 'char_end': 1015, 'line': '\t free (output_u8);\n'}, {'line_no': 45, 'char_start': 1015, 'char_end': 1046, 'line': '\t return IDN2_TOO_BIG_DOMAIN;\n'}, {'line_no': 46, 'char_start': 1046, 'char_end': 1056, 'line': ' }\n'}, {'line_no': 47, 'char_start': 1056, 'char_end': 1057, 'line': '\n'}, {'line_no': 49, 'char_start': 1075, 'char_end': 1113, 'line': '\tstrcpy (output, (char *) output_u8);\n'}, {'line_no': 51, 'char_start': 1114, 'char_end': 1138, 'line': ' free (output_u8);\n'}]}","{'deleted': [{'char_start': 951, 'char_end': 957, 'chars': 'const '}], 'added': [{'char_start': 921, 'char_end': 1063, 'chars': 'size_t len = strlen ((char *) output_u8);\n\n if (len > 63)\n {\n\t free (output_u8);\n\t return IDN2_TOO_BIG_DOMAIN;\n }\n\n '}, {'char_start': 1124, 'char_end': 1125, 'chars': ' '}]}",github.com/libidn/libidn2/commit/e4d1558aa2c1c04a05066ee8600f37603890ba8c,lib/lookup.c,cwe-787,349 cwe-416,r_anal_bb_free,"R_API void r_anal_bb_free(RAnalBlock *bb) { if (!bb) { return; } r_anal_cond_free (bb->cond); R_FREE (bb->fingerprint); r_anal_diff_free (bb->diff); bb->diff = NULL; R_FREE (bb->op_bytes); r_anal_switch_op_free (bb->switch_op); bb->switch_op = NULL; bb->fingerprint = NULL; bb->cond = NULL; R_FREE (bb->label); R_FREE (bb->op_pos); R_FREE (bb->parent_reg_arena); if (bb->prev) { if (bb->prev->jumpbb == bb) { bb->prev->jumpbb = NULL; } if (bb->prev->failbb == bb) { bb->prev->failbb = NULL; } bb->prev = NULL; } if (bb->jumpbb) { bb->jumpbb->prev = NULL; bb->jumpbb = NULL; } if (bb->failbb) { bb->failbb->prev = NULL; bb->failbb = NULL; } R_FREE (bb); }","R_API void r_anal_bb_free(RAnalBlock *bb) { if (!bb) { return; } r_anal_cond_free (bb->cond); R_FREE (bb->fingerprint); r_anal_diff_free (bb->diff); bb->diff = NULL; R_FREE (bb->op_bytes); r_anal_switch_op_free (bb->switch_op); bb->switch_op = NULL; bb->fingerprint = NULL; bb->cond = NULL; R_FREE (bb->label); R_FREE (bb->op_pos); R_FREE (bb->parent_reg_arena); if (bb->prev) { if (bb->prev->jumpbb == bb) { bb->prev->jumpbb = NULL; } if (bb->prev->failbb == bb) { bb->prev->failbb = NULL; } bb->prev = NULL; } if (bb->jumpbb) { bb->jumpbb->prev = NULL; bb->jumpbb = NULL; } if (bb->failbb) { bb->failbb->prev = NULL; bb->failbb = NULL; } if (bb->next) { // avoid double free bb->next->prev = NULL; } R_FREE (bb); // double free }","{'deleted': [{'line_no': 34, 'char_start': 686, 'char_end': 700, 'line': '\tR_FREE (bb);\n'}], 'added': [{'line_no': 34, 'char_start': 686, 'char_end': 703, 'line': '\tif (bb->next) {\n'}, {'line_no': 36, 'char_start': 726, 'char_end': 751, 'line': '\t\tbb->next->prev = NULL;\n'}, {'line_no': 37, 'char_start': 751, 'char_end': 754, 'line': '\t}\n'}, {'line_no': 38, 'char_start': 754, 'char_end': 783, 'line': '\tR_FREE (bb); // double free\n'}]}","{'deleted': [], 'added': [{'char_start': 687, 'char_end': 755, 'chars': 'if (bb->next) {\n\t\t// avoid double free\n\t\tbb->next->prev = NULL;\n\t}\n\t'}, {'char_start': 767, 'char_end': 782, 'chars': ' // double free'}]}",github.com/radare/radare2/commit/90b71c017a7fa9732fe45fd21b245ee051b1f548,libr/anal/bb.c,cwe-416,265 cwe-416,TraceBezier,"static MagickBooleanType TraceBezier(MVGInfo *mvg_info, const size_t number_coordinates) { double alpha, *coefficients, weight; PointInfo end, point, *points; PrimitiveInfo *primitive_info; register PrimitiveInfo *p; register ssize_t i, j; size_t control_points, quantum; /* Allocate coefficients. */ primitive_info=(*mvg_info->primitive_info)+mvg_info->offset; quantum=number_coordinates; for (i=0; i < (ssize_t) number_coordinates; i++) { for (j=i+1; j < (ssize_t) number_coordinates; j++) { alpha=fabs(primitive_info[j].point.x-primitive_info[i].point.x); if (alpha > (double) SSIZE_MAX) { (void) ThrowMagickException(mvg_info->exception,GetMagickModule(), ResourceLimitError,""MemoryAllocationFailed"",""`%s'"",""""); return(MagickFalse); } if (alpha > (double) quantum) quantum=(size_t) alpha; alpha=fabs(primitive_info[j].point.y-primitive_info[i].point.y); if (alpha > (double) SSIZE_MAX) { (void) ThrowMagickException(mvg_info->exception,GetMagickModule(), ResourceLimitError,""MemoryAllocationFailed"",""`%s'"",""""); return(MagickFalse); } if (alpha > (double) quantum) quantum=(size_t) alpha; } } quantum=MagickMin(quantum/number_coordinates,BezierQuantum); primitive_info=(*mvg_info->primitive_info)+mvg_info->offset; coefficients=(double *) AcquireQuantumMemory(number_coordinates, sizeof(*coefficients)); points=(PointInfo *) AcquireQuantumMemory(quantum,number_coordinates* sizeof(*points)); if ((coefficients == (double *) NULL) || (points == (PointInfo *) NULL)) { if (points != (PointInfo *) NULL) points=(PointInfo *) RelinquishMagickMemory(points); if (coefficients != (double *) NULL) coefficients=(double *) RelinquishMagickMemory(coefficients); (void) ThrowMagickException(mvg_info->exception,GetMagickModule(), ResourceLimitError,""MemoryAllocationFailed"",""`%s'"",""""); return(MagickFalse); } control_points=quantum*number_coordinates; if (CheckPrimitiveExtent(mvg_info,control_points+1) == MagickFalse) { points=(PointInfo *) RelinquishMagickMemory(points); coefficients=(double *) RelinquishMagickMemory(coefficients); return(MagickFalse); } /* Compute bezier points. */ end=primitive_info[number_coordinates-1].point; for (i=0; i < (ssize_t) number_coordinates; i++) coefficients[i]=Permutate((ssize_t) number_coordinates-1,i); weight=0.0; for (i=0; i < (ssize_t) control_points; i++) { p=primitive_info; point.x=0.0; point.y=0.0; alpha=pow((double) (1.0-weight),(double) number_coordinates-1.0); for (j=0; j < (ssize_t) number_coordinates; j++) { point.x+=alpha*coefficients[j]*p->point.x; point.y+=alpha*coefficients[j]*p->point.y; alpha*=weight/(1.0-weight); p++; } points[i]=point; weight+=1.0/control_points; } /* Bezier curves are just short segmented polys. */ p=primitive_info; for (i=0; i < (ssize_t) control_points; i++) { if (TracePoint(p,points[i]) == MagickFalse) { points=(PointInfo *) RelinquishMagickMemory(points); coefficients=(double *) RelinquishMagickMemory(coefficients); return(MagickFalse); } p+=p->coordinates; } if (TracePoint(p,end) == MagickFalse) { points=(PointInfo *) RelinquishMagickMemory(points); coefficients=(double *) RelinquishMagickMemory(coefficients); return(MagickFalse); } p+=p->coordinates; primitive_info->coordinates=(size_t) (p-primitive_info); primitive_info->closed_subpath=MagickFalse; for (i=0; i < (ssize_t) primitive_info->coordinates; i++) { p->primitive=primitive_info->primitive; p--; } points=(PointInfo *) RelinquishMagickMemory(points); coefficients=(double *) RelinquishMagickMemory(coefficients); return(MagickTrue); }","static MagickBooleanType TraceBezier(MVGInfo *mvg_info, const size_t number_coordinates) { double alpha, *coefficients, weight; PointInfo end, point, *points; PrimitiveInfo *primitive_info; register PrimitiveInfo *p; register ssize_t i, j; size_t control_points, quantum; /* Allocate coefficients. */ primitive_info=(*mvg_info->primitive_info)+mvg_info->offset; quantum=number_coordinates; for (i=0; i < (ssize_t) number_coordinates; i++) { for (j=i+1; j < (ssize_t) number_coordinates; j++) { alpha=fabs(primitive_info[j].point.x-primitive_info[i].point.x); if (alpha > (double) SSIZE_MAX) { (void) ThrowMagickException(mvg_info->exception,GetMagickModule(), ResourceLimitError,""MemoryAllocationFailed"",""`%s'"",""""); return(MagickFalse); } if (alpha > (double) quantum) quantum=(size_t) alpha; alpha=fabs(primitive_info[j].point.y-primitive_info[i].point.y); if (alpha > (double) SSIZE_MAX) { (void) ThrowMagickException(mvg_info->exception,GetMagickModule(), ResourceLimitError,""MemoryAllocationFailed"",""`%s'"",""""); return(MagickFalse); } if (alpha > (double) quantum) quantum=(size_t) alpha; } } primitive_info=(*mvg_info->primitive_info)+mvg_info->offset; quantum=MagickMin(quantum/number_coordinates,BezierQuantum); coefficients=(double *) AcquireQuantumMemory(number_coordinates, sizeof(*coefficients)); points=(PointInfo *) AcquireQuantumMemory(quantum,number_coordinates* sizeof(*points)); if ((coefficients == (double *) NULL) || (points == (PointInfo *) NULL)) { if (points != (PointInfo *) NULL) points=(PointInfo *) RelinquishMagickMemory(points); if (coefficients != (double *) NULL) coefficients=(double *) RelinquishMagickMemory(coefficients); (void) ThrowMagickException(mvg_info->exception,GetMagickModule(), ResourceLimitError,""MemoryAllocationFailed"",""`%s'"",""""); return(MagickFalse); } control_points=quantum*number_coordinates; if (CheckPrimitiveExtent(mvg_info,control_points+1) == MagickFalse) { points=(PointInfo *) RelinquishMagickMemory(points); coefficients=(double *) RelinquishMagickMemory(coefficients); return(MagickFalse); } primitive_info=(*mvg_info->primitive_info)+mvg_info->offset; /* Compute bezier points. */ end=primitive_info[number_coordinates-1].point; for (i=0; i < (ssize_t) number_coordinates; i++) coefficients[i]=Permutate((ssize_t) number_coordinates-1,i); weight=0.0; for (i=0; i < (ssize_t) control_points; i++) { p=primitive_info; point.x=0.0; point.y=0.0; alpha=pow((double) (1.0-weight),(double) number_coordinates-1.0); for (j=0; j < (ssize_t) number_coordinates; j++) { point.x+=alpha*coefficients[j]*p->point.x; point.y+=alpha*coefficients[j]*p->point.y; alpha*=weight/(1.0-weight); p++; } points[i]=point; weight+=1.0/control_points; } /* Bezier curves are just short segmented polys. */ p=primitive_info; for (i=0; i < (ssize_t) control_points; i++) { if (TracePoint(p,points[i]) == MagickFalse) { points=(PointInfo *) RelinquishMagickMemory(points); coefficients=(double *) RelinquishMagickMemory(coefficients); return(MagickFalse); } p+=p->coordinates; } if (TracePoint(p,end) == MagickFalse) { points=(PointInfo *) RelinquishMagickMemory(points); coefficients=(double *) RelinquishMagickMemory(coefficients); return(MagickFalse); } p+=p->coordinates; primitive_info->coordinates=(size_t) (p-primitive_info); primitive_info->closed_subpath=MagickFalse; for (i=0; i < (ssize_t) primitive_info->coordinates; i++) { p->primitive=primitive_info->primitive; p--; } points=(PointInfo *) RelinquishMagickMemory(points); coefficients=(double *) RelinquishMagickMemory(coefficients); return(MagickTrue); }","{'deleted': [{'line_no': 57, 'char_start': 1342, 'char_end': 1405, 'line': ' quantum=MagickMin(quantum/number_coordinates,BezierQuantum);\n'}], 'added': [{'line_no': 58, 'char_start': 1405, 'char_end': 1468, 'line': ' quantum=MagickMin(quantum/number_coordinates,BezierQuantum);\n'}, {'line_no': 80, 'char_start': 2403, 'char_end': 2466, 'line': ' primitive_info=(*mvg_info->primitive_info)+mvg_info->offset;\n'}]}","{'deleted': [{'char_start': 1344, 'char_end': 1407, 'chars': 'quantum=MagickMin(quantum/number_coordinates,BezierQuantum);\n '}], 'added': [{'char_start': 1344, 'char_end': 1407, 'chars': 'primitive_info=(*mvg_info->primitive_info)+mvg_info->offset;\n '}, {'char_start': 2402, 'char_end': 2465, 'chars': '\n primitive_info=(*mvg_info->primitive_info)+mvg_info->offset;'}]}",github.com/ImageMagick/ImageMagick/commit/ecf7c6b288e11e7e7f75387c5e9e93e423b98397,MagickCore/draw.c,cwe-416,1081 cwe-089,login," def login(self, username, password): select_query = """""" SELECT client_id, username, balance, message FROM Clients WHERE username = '{}' AND password = '{}' LIMIT 1 """""".format(username, password) cursor = self.__conn.cursor() cursor.execute(select_query) user = cursor.fetchone() if(user): return Client(user[0], user[1], user[2], user[3]) else: return False"," def login(self, username, password): select_query = """""" SELECT client_id, username, balance, message FROM Clients WHERE username = ? AND password = ? LIMIT 1 """""" cursor = self.__conn.cursor() cursor.execute(select_query, (username, password)) user = cursor.fetchone() if(user): return Client(user[0], user[1], user[2], user[3]) else: return False","{'deleted': [{'line_no': 5, 'char_start': 150, 'char_end': 204, 'line': "" WHERE username = '{}' AND password = '{}'\n""}, {'line_no': 7, 'char_start': 224, 'char_end': 263, 'line': ' """""".format(username, password)\n'}, {'line_no': 11, 'char_start': 303, 'char_end': 340, 'line': ' cursor.execute(select_query)\n'}], 'added': [{'line_no': 5, 'char_start': 150, 'char_end': 198, 'line': ' WHERE username = ? AND password = ?\n'}, {'line_no': 7, 'char_start': 218, 'char_end': 230, 'line': ' """"""\n'}, {'line_no': 11, 'char_start': 270, 'char_end': 329, 'line': ' cursor.execute(select_query, (username, password))\n'}]}","{'deleted': [{'char_start': 179, 'char_end': 183, 'chars': ""'{}'""}, {'char_start': 199, 'char_end': 203, 'chars': ""'{}'""}, {'char_start': 235, 'char_end': 262, 'chars': '.format(username, password)'}], 'added': [{'char_start': 179, 'char_end': 180, 'chars': '?'}, {'char_start': 196, 'char_end': 197, 'chars': '?'}, {'char_start': 305, 'char_end': 327, 'chars': ', (username, password)'}]}",github.com/AnetaStoycheva/Programming101_HackBulgaria/commit/c0d6f4b8fe83a375832845a45952b5153e4c34f3,Week_9/sql_manager.py,cwe-089,100 cwe-089,get_secrets," def get_secrets(self, from_date_added=0): secrets = [] for row in self.cursor.execute('SELECT encrypted, json_id, date_added FROM secret WHERE date_added > %s ORDER BY date_added DESC' % from_date_added): aes_key, json_id, date_added = cryptlib.eciesDecrypt(row[0], self.privkey), row[1], row[2] if aes_key != None: secrets.append([aes_key, json_id]) from_date_added = max(from_date_added, date_added) return (secrets, from_date_added)"," def get_secrets(self, from_date_added=0): secrets = [] for row in self.cursor.execute('SELECT encrypted, json_id, date_added FROM secret WHERE date_added > ? ORDER BY date_added DESC', (from_date_added,)): aes_key, json_id, date_added = cryptlib.eciesDecrypt(row[0], self.privkey), row[1], row[2] if aes_key != None: secrets.append([aes_key, json_id]) from_date_added = max(from_date_added, date_added) return (secrets, from_date_added)","{'deleted': [{'line_no': 3, 'char_start': 58, 'char_end': 210, 'line': ""\t\tfor row in self.cursor.execute('SELECT encrypted, json_id, date_added FROM secret WHERE date_added > %s ORDER BY date_added DESC' % from_date_added):\n""}], 'added': [{'line_no': 3, 'char_start': 58, 'char_end': 211, 'line': ""\t\tfor row in self.cursor.execute('SELECT encrypted, json_id, date_added FROM secret WHERE date_added > ? ORDER BY date_added DESC', (from_date_added,)):\n""}]}","{'deleted': [{'char_start': 161, 'char_end': 163, 'chars': '%s'}, {'char_start': 189, 'char_end': 191, 'chars': ' %'}], 'added': [{'char_start': 161, 'char_end': 162, 'chars': '?'}, {'char_start': 188, 'char_end': 189, 'chars': ','}, {'char_start': 190, 'char_end': 191, 'chars': '('}, {'char_start': 206, 'char_end': 208, 'chars': ',)'}]}",github.com/imachug/ZeroMailProxy/commit/8f62d024c6c4c957079d147e59f26d15c07dc888,zeromail.py,cwe-089,125 cwe-476,open_ssl_connection,"open_ssl_connection (rfbClient *client, int sockfd, rfbBool anonTLS, rfbCredential *cred) { SSL_CTX *ssl_ctx = NULL; SSL *ssl = NULL; int n, finished = 0; X509_VERIFY_PARAM *param; uint8_t verify_crls = cred->x509Credential.x509CrlVerifyMode; if (!(ssl_ctx = SSL_CTX_new(SSLv23_client_method()))) { rfbClientLog(""Could not create new SSL context.\n""); return NULL; } param = X509_VERIFY_PARAM_new(); /* Setup verification if not anonymous */ if (!anonTLS) { if (cred->x509Credential.x509CACertFile) { if (!SSL_CTX_load_verify_locations(ssl_ctx, cred->x509Credential.x509CACertFile, NULL)) { rfbClientLog(""Failed to load CA certificate from %s.\n"", cred->x509Credential.x509CACertFile); goto error_free_ctx; } } else { rfbClientLog(""Using default paths for certificate verification.\n""); SSL_CTX_set_default_verify_paths (ssl_ctx); } if (cred->x509Credential.x509CACrlFile) { if (!load_crls_from_file(cred->x509Credential.x509CACrlFile, ssl_ctx)) { rfbClientLog(""CRLs could not be loaded.\n""); goto error_free_ctx; } if (verify_crls == rfbX509CrlVerifyNone) verify_crls = rfbX509CrlVerifyAll; } if (cred->x509Credential.x509ClientCertFile && cred->x509Credential.x509ClientKeyFile) { if (SSL_CTX_use_certificate_chain_file(ssl_ctx, cred->x509Credential.x509ClientCertFile) != 1) { rfbClientLog(""Client certificate could not be loaded.\n""); goto error_free_ctx; } if (SSL_CTX_use_PrivateKey_file(ssl_ctx, cred->x509Credential.x509ClientKeyFile, SSL_FILETYPE_PEM) != 1) { rfbClientLog(""Client private key could not be loaded.\n""); goto error_free_ctx; } if (SSL_CTX_check_private_key(ssl_ctx) == 0) { rfbClientLog(""Client certificate and private key do not match.\n""); goto error_free_ctx; } } SSL_CTX_set_verify(ssl_ctx, SSL_VERIFY_PEER, NULL); if (verify_crls == rfbX509CrlVerifyClient) X509_VERIFY_PARAM_set_flags(param, X509_V_FLAG_CRL_CHECK); else if (verify_crls == rfbX509CrlVerifyAll) X509_VERIFY_PARAM_set_flags(param, X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL); if(!X509_VERIFY_PARAM_set1_host(param, client->serverHost, strlen(client->serverHost))) { rfbClientLog(""Could not set server name for verification.\n""); goto error_free_ctx; } SSL_CTX_set1_param(ssl_ctx, param); } if (!(ssl = SSL_new (ssl_ctx))) { rfbClientLog(""Could not create a new SSL session.\n""); goto error_free_ctx; } /* TODO: finetune this list, take into account anonTLS bool */ SSL_set_cipher_list(ssl, ""ALL""); SSL_set_fd (ssl, sockfd); SSL_CTX_set_app_data (ssl_ctx, client); do { n = SSL_connect(ssl); if (n != 1) { if (wait_for_data(ssl, n, 1) != 1) { finished = 1; SSL_shutdown(ssl); goto error_free_ssl; } } } while( n != 1 && finished != 1 ); X509_VERIFY_PARAM_free(param); return ssl; error_free_ssl: SSL_free(ssl); error_free_ctx: X509_VERIFY_PARAM_free(param); SSL_CTX_free(ssl_ctx); return NULL; }","open_ssl_connection (rfbClient *client, int sockfd, rfbBool anonTLS, rfbCredential *cred) { SSL_CTX *ssl_ctx = NULL; SSL *ssl = NULL; int n, finished = 0; X509_VERIFY_PARAM *param; uint8_t verify_crls; if (!(ssl_ctx = SSL_CTX_new(SSLv23_client_method()))) { rfbClientLog(""Could not create new SSL context.\n""); return NULL; } param = X509_VERIFY_PARAM_new(); /* Setup verification if not anonymous */ if (!anonTLS) { verify_crls = cred->x509Credential.x509CrlVerifyMode; if (cred->x509Credential.x509CACertFile) { if (!SSL_CTX_load_verify_locations(ssl_ctx, cred->x509Credential.x509CACertFile, NULL)) { rfbClientLog(""Failed to load CA certificate from %s.\n"", cred->x509Credential.x509CACertFile); goto error_free_ctx; } } else { rfbClientLog(""Using default paths for certificate verification.\n""); SSL_CTX_set_default_verify_paths (ssl_ctx); } if (cred->x509Credential.x509CACrlFile) { if (!load_crls_from_file(cred->x509Credential.x509CACrlFile, ssl_ctx)) { rfbClientLog(""CRLs could not be loaded.\n""); goto error_free_ctx; } if (verify_crls == rfbX509CrlVerifyNone) verify_crls = rfbX509CrlVerifyAll; } if (cred->x509Credential.x509ClientCertFile && cred->x509Credential.x509ClientKeyFile) { if (SSL_CTX_use_certificate_chain_file(ssl_ctx, cred->x509Credential.x509ClientCertFile) != 1) { rfbClientLog(""Client certificate could not be loaded.\n""); goto error_free_ctx; } if (SSL_CTX_use_PrivateKey_file(ssl_ctx, cred->x509Credential.x509ClientKeyFile, SSL_FILETYPE_PEM) != 1) { rfbClientLog(""Client private key could not be loaded.\n""); goto error_free_ctx; } if (SSL_CTX_check_private_key(ssl_ctx) == 0) { rfbClientLog(""Client certificate and private key do not match.\n""); goto error_free_ctx; } } SSL_CTX_set_verify(ssl_ctx, SSL_VERIFY_PEER, NULL); if (verify_crls == rfbX509CrlVerifyClient) X509_VERIFY_PARAM_set_flags(param, X509_V_FLAG_CRL_CHECK); else if (verify_crls == rfbX509CrlVerifyAll) X509_VERIFY_PARAM_set_flags(param, X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL); if(!X509_VERIFY_PARAM_set1_host(param, client->serverHost, strlen(client->serverHost))) { rfbClientLog(""Could not set server name for verification.\n""); goto error_free_ctx; } SSL_CTX_set1_param(ssl_ctx, param); } if (!(ssl = SSL_new (ssl_ctx))) { rfbClientLog(""Could not create a new SSL session.\n""); goto error_free_ctx; } /* TODO: finetune this list, take into account anonTLS bool */ SSL_set_cipher_list(ssl, ""ALL""); SSL_set_fd (ssl, sockfd); SSL_CTX_set_app_data (ssl_ctx, client); do { n = SSL_connect(ssl); if (n != 1) { if (wait_for_data(ssl, n, 1) != 1) { finished = 1; SSL_shutdown(ssl); goto error_free_ssl; } } } while( n != 1 && finished != 1 ); X509_VERIFY_PARAM_free(param); return ssl; error_free_ssl: SSL_free(ssl); error_free_ctx: X509_VERIFY_PARAM_free(param); SSL_CTX_free(ssl_ctx); return NULL; }","{'deleted': [{'line_no': 7, 'char_start': 189, 'char_end': 253, 'line': ' uint8_t verify_crls = cred->x509Credential.x509CrlVerifyMode;\n'}], 'added': [{'line_no': 7, 'char_start': 189, 'char_end': 212, 'line': ' uint8_t verify_crls;\n'}, {'line_no': 20, 'char_start': 452, 'char_end': 510, 'line': ' verify_crls = cred->x509Credential.x509CrlVerifyMode;\n'}]}","{'deleted': [{'char_start': 210, 'char_end': 251, 'chars': ' = cred->x509Credential.x509CrlVerifyMode'}], 'added': [{'char_start': 451, 'char_end': 509, 'chars': '\n verify_crls = cred->x509Credential.x509CrlVerifyMode;'}]}",github.com/LibVNC/libvncserver/commit/33441d90a506d5f3ae9388f2752901227e430553,libvncclient/tls_openssl.c,cwe-476,981 cwe-089,get_top_author,"def get_top_author(top_num): """""" query the top(top_num) popular author top_num => list of [author, count] """""" cmd = """"""SELECT authors.name,author_result.num FROM authors JOIN (SELECT SUM(article_result.num) as num, article_result.author from (SELECT articles.title, articles.author, SUM(log.views) AS num FROM articles INNER JOIN ( SELECT path, count(path) AS views FROM log GROUP BY log.path ) AS log ON log.path = '/article/' || articles.slug GROUP BY articles.title, articles.author) AS article_result GROUP BY article_result.author) as author_result ON authors.id = author_result.author ORDER BY num DESC LIMIT {}"""""".format(top_num) return execute_query(cmd)","def get_top_author(top_num): """""" query the top(top_num) popular author top_num => list of [author, count] """""" cmd = """"""SELECT authors.name,author_result.num FROM authors JOIN (SELECT SUM(article_result.num) as num, article_result.author from (SELECT articles.title, articles.author, SUM(log.views) AS num FROM articles INNER JOIN ( SELECT path, count(path) AS views FROM log GROUP BY log.path ) AS log ON log.path = '/article/' || articles.slug GROUP BY articles.title, articles.author) AS article_result GROUP BY article_result.author) as author_result ON authors.id = author_result.author ORDER BY num DESC LIMIT %s"""""" data = [top_num, ] return execute_query(cmd, data)","{'deleted': [{'line_no': 21, 'char_start': 931, 'char_end': 998, 'line': ' ORDER BY num DESC LIMIT {}"""""".format(top_num)\r\n'}, {'line_no': 22, 'char_start': 998, 'char_end': 1027, 'line': ' return execute_query(cmd)\r\n'}], 'added': [{'line_no': 21, 'char_start': 931, 'char_end': 982, 'line': ' ORDER BY num DESC LIMIT %s""""""\r\n'}, {'line_no': 22, 'char_start': 982, 'char_end': 1006, 'line': ' data = [top_num, ]\r\n'}, {'line_no': 23, 'char_start': 1006, 'char_end': 1041, 'line': ' return execute_query(cmd, data)\r\n'}]}","{'deleted': [{'char_start': 975, 'char_end': 977, 'chars': '{}'}, {'char_start': 980, 'char_end': 985, 'chars': '.form'}, {'char_start': 987, 'char_end': 988, 'chars': '('}, {'char_start': 995, 'char_end': 996, 'chars': ')'}], 'added': [{'char_start': 975, 'char_end': 977, 'chars': '%s'}, {'char_start': 980, 'char_end': 987, 'chars': '\r\n d'}, {'char_start': 989, 'char_end': 994, 'chars': 'a = ['}, {'char_start': 1001, 'char_end': 1004, 'chars': ', ]'}, {'char_start': 1034, 'char_end': 1040, 'chars': ', data'}]}",github.com/thugasin/udacity-homework-logAnalyzer/commit/506f25f9a1caee7f17034adf7c75e0efbc88082b,logAnalyzerDb.py,cwe-089,177 cwe-022,render," def render(self, request): action = ""download"" if ""action"" in request.args: action = request.args[""action""][0] if ""file"" in request.args: filename = request.args[""file""][0].decode('utf-8', 'ignore').encode('utf-8') filename = re.sub(""^/+"", ""/"", os.path.realpath(filename)) if not os.path.exists(filename): return ""File '%s' not found"" % (filename) if action == ""stream"": name = ""stream"" if ""name"" in request.args: name = request.args[""name""][0] port = config.OpenWebif.port.value proto = 'http' if request.isSecure(): port = config.OpenWebif.https_port.value proto = 'https' ourhost = request.getHeader('host') m = re.match('.+\:(\d+)$', ourhost) if m is not None: port = m.group(1) response = ""#EXTM3U\n#EXTVLCOPT--http-reconnect=true\n#EXTINF:-1,%s\n%s://%s:%s/file?action=download&file=%s"" % (name, proto, request.getRequestHostname(), port, quote(filename)) request.setHeader(""Content-Disposition"", 'attachment;filename=""%s.m3u""' % name) request.setHeader(""Content-Type"", ""application/x-mpegurl"") return response elif action == ""delete"": request.setResponseCode(http.OK) return ""TODO: DELETE FILE: %s"" % (filename) elif action == ""download"": request.setHeader(""Content-Disposition"", ""attachment;filename=\""%s\"""" % (filename.split('/')[-1])) rfile = static.File(filename, defaultType = ""application/octet-stream"") return rfile.render(request) else: return ""wrong action parameter"" if ""dir"" in request.args: path = request.args[""dir""][0] pattern = '*' data = [] if ""pattern"" in request.args: pattern = request.args[""pattern""][0] directories = [] files = [] if fileExists(path): try: files = glob.glob(path+'/'+pattern) except: files = [] files.sort() tmpfiles = files[:] for x in tmpfiles: if os.path.isdir(x): directories.append(x + '/') files.remove(x) data.append({""result"": True,""dirs"": directories,""files"": files}) else: data.append({""result"": False,""message"": ""path %s not exits"" % (path)}) request.setHeader(""content-type"", ""application/json; charset=utf-8"") return json.dumps(data, indent=2)"," def render(self, request): action = ""download"" if ""action"" in request.args: action = request.args[""action""][0] if ""file"" in request.args: filename = lenient_force_utf_8(request.args[""file""][0]) filename = sanitise_filename_slashes(os.path.realpath(filename)) if not os.path.exists(filename): return ""File '%s' not found"" % (filename) if action == ""stream"": name = ""stream"" if ""name"" in request.args: name = request.args[""name""][0] port = config.OpenWebif.port.value proto = 'http' if request.isSecure(): port = config.OpenWebif.https_port.value proto = 'https' ourhost = request.getHeader('host') m = re.match('.+\:(\d+)$', ourhost) if m is not None: port = m.group(1) response = ""#EXTM3U\n#EXTVLCOPT--http-reconnect=true\n#EXTINF:-1,%s\n%s://%s:%s/file?action=download&file=%s"" % (name, proto, request.getRequestHostname(), port, quote(filename)) request.setHeader(""Content-Disposition"", 'attachment;filename=""%s.m3u""' % name) request.setHeader(""Content-Type"", ""application/x-mpegurl"") return response elif action == ""delete"": request.setResponseCode(http.OK) return ""TODO: DELETE FILE: %s"" % (filename) elif action == ""download"": request.setHeader(""Content-Disposition"", ""attachment;filename=\""%s\"""" % (filename.split('/')[-1])) rfile = static.File(filename, defaultType = ""application/octet-stream"") return rfile.render(request) else: return ""wrong action parameter"" if ""dir"" in request.args: path = request.args[""dir""][0] pattern = '*' data = [] if ""pattern"" in request.args: pattern = request.args[""pattern""][0] directories = [] files = [] if fileExists(path): try: files = glob.glob(path+'/'+pattern) except: files = [] files.sort() tmpfiles = files[:] for x in tmpfiles: if os.path.isdir(x): directories.append(x + '/') files.remove(x) data.append({""result"": True,""dirs"": directories,""files"": files}) else: data.append({""result"": False,""message"": ""path %s not exits"" % (path)}) request.setHeader(""content-type"", ""application/json; charset=utf-8"") return json.dumps(data, indent=2)","{'deleted': [{'line_no': 7, 'char_start': 149, 'char_end': 229, 'line': '\t\t\tfilename = request.args[""file""][0].decode(\'utf-8\', \'ignore\').encode(\'utf-8\')\n'}, {'line_no': 8, 'char_start': 229, 'char_end': 290, 'line': '\t\t\tfilename = re.sub(""^/+"", ""/"", os.path.realpath(filename))\n'}], 'added': [{'line_no': 7, 'char_start': 149, 'char_end': 208, 'line': '\t\t\tfilename = lenient_force_utf_8(request.args[""file""][0])\n'}, {'line_no': 8, 'char_start': 208, 'char_end': 276, 'line': '\t\t\tfilename = sanitise_filename_slashes(os.path.realpath(filename))\n'}]}","{'deleted': [{'char_start': 186, 'char_end': 227, 'chars': "".decode('utf-8', 'ignore').encode('utf-8'""}, {'char_start': 243, 'char_end': 244, 'chars': 'r'}, {'char_start': 245, 'char_end': 246, 'chars': '.'}, {'char_start': 247, 'char_end': 249, 'chars': 'ub'}, {'char_start': 250, 'char_end': 262, 'chars': '""^/+"", ""/"", '}], 'added': [{'char_start': 163, 'char_end': 183, 'chars': 'lenient_force_utf_8('}, {'char_start': 222, 'char_end': 238, 'chars': 'sanitise_filenam'}, {'char_start': 239, 'char_end': 240, 'chars': '_'}, {'char_start': 241, 'char_end': 247, 'chars': 'lashes'}]}",github.com/E2OpenPlugins/e2openplugin-OpenWebif/commit/a846b7664eda3a4c51a452e00638cf7337dc2013,plugin/controllers/file.py,cwe-022,590 cwe-089,update_theory_base,"def update_theory_base(tag, link): theory = sqlite3.connect(os.path.abspath(os.path.dirname(__file__)) + ""\\theory.db"") conn = theory.cursor() conn.execute(""insert into "" + str(tag) + "" values (?)"", (str(link), )) theory.commit() theory.close()","def update_theory_base(tag, link): theory = sqlite3.connect(os.path.abspath(os.path.dirname(__file__)) + ""\\theory.db"") conn = theory.cursor() conn.execute(""insert into ? values (?)"", (tag, str(link))) theory.commit() theory.close()","{'deleted': [{'line_no': 4, 'char_start': 151, 'char_end': 226, 'line': ' conn.execute(""insert into "" + str(tag) + "" values (?)"", (str(link), ))\n'}], 'added': [{'line_no': 4, 'char_start': 151, 'char_end': 214, 'line': ' conn.execute(""insert into ? values (?)"", (tag, str(link)))\n'}]}","{'deleted': [{'char_start': 181, 'char_end': 197, 'chars': '"" + str(tag) + ""'}, {'char_start': 221, 'char_end': 223, 'chars': ', '}], 'added': [{'char_start': 181, 'char_end': 182, 'chars': '?'}, {'char_start': 197, 'char_end': 202, 'chars': 'tag, '}]}",github.com/lissrbay/codeforces_bot/commit/cc7f5143445a0030b1149ac60a65b1b1b9c92a90,bases/update.py,cwe-089,64 cwe-125,ReadSUNImage,"static Image *ReadSUNImage(const ImageInfo *image_info,ExceptionInfo *exception) { #define RMT_EQUAL_RGB 1 #define RMT_NONE 0 #define RMT_RAW 2 #define RT_STANDARD 1 #define RT_ENCODED 2 #define RT_FORMAT_RGB 3 typedef struct _SUNInfo { unsigned int magic, width, height, depth, length, type, maptype, maplength; } SUNInfo; Image *image; int bit; MagickBooleanType status; MagickSizeType number_pixels; register Quantum *q; register ssize_t i, x; register unsigned char *p; size_t bytes_per_line, extent, height, length; ssize_t count, y; SUNInfo sun_info; unsigned char *sun_data, *sun_pixels; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),""%s"", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read SUN raster header. */ (void) ResetMagickMemory(&sun_info,0,sizeof(sun_info)); sun_info.magic=ReadBlobMSBLong(image); do { /* Verify SUN identifier. */ if (sun_info.magic != 0x59a66a95) ThrowReaderException(CorruptImageError,""ImproperImageHeader""); sun_info.width=ReadBlobMSBLong(image); sun_info.height=ReadBlobMSBLong(image); sun_info.depth=ReadBlobMSBLong(image); sun_info.length=ReadBlobMSBLong(image); sun_info.type=ReadBlobMSBLong(image); sun_info.maptype=ReadBlobMSBLong(image); sun_info.maplength=ReadBlobMSBLong(image); extent=sun_info.height*sun_info.width; if ((sun_info.height != 0) && (sun_info.width != extent/sun_info.height)) ThrowReaderException(CorruptImageError,""ImproperImageHeader""); if ((sun_info.type != RT_STANDARD) && (sun_info.type != RT_ENCODED) && (sun_info.type != RT_FORMAT_RGB)) ThrowReaderException(CorruptImageError,""ImproperImageHeader""); if ((sun_info.maptype == RMT_NONE) && (sun_info.maplength != 0)) ThrowReaderException(CorruptImageError,""ImproperImageHeader""); if ((sun_info.depth == 0) || (sun_info.depth > 32)) ThrowReaderException(CorruptImageError,""ImproperImageHeader""); if ((sun_info.maptype != RMT_NONE) && (sun_info.maptype != RMT_EQUAL_RGB) && (sun_info.maptype != RMT_RAW)) ThrowReaderException(CoderError,""ColormapTypeNotSupported""); image->columns=sun_info.width; image->rows=sun_info.height; image->depth=sun_info.depth <= 8 ? sun_info.depth : MAGICKCORE_QUANTUM_DEPTH; if (sun_info.depth < 24) { size_t one; image->colors=sun_info.maplength; one=1; if (sun_info.maptype == RMT_NONE) image->colors=one << sun_info.depth; if (sun_info.maptype == RMT_EQUAL_RGB) image->colors=sun_info.maplength/3; if (AcquireImageColormap(image,image->colors,exception) == MagickFalse) ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); } switch (sun_info.maptype) { case RMT_NONE: break; case RMT_EQUAL_RGB: { unsigned char *sun_colormap; /* Read SUN raster colormap. */ sun_colormap=(unsigned char *) AcquireQuantumMemory(image->colors, sizeof(*sun_colormap)); if (sun_colormap == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); count=ReadBlob(image,image->colors,sun_colormap); if (count != (ssize_t) image->colors) ThrowReaderException(CorruptImageError,""UnexpectedEndOfFile""); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].red=(MagickRealType) ScaleCharToQuantum( sun_colormap[i]); count=ReadBlob(image,image->colors,sun_colormap); if (count != (ssize_t) image->colors) ThrowReaderException(CorruptImageError,""UnexpectedEndOfFile""); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].green=(MagickRealType) ScaleCharToQuantum( sun_colormap[i]); count=ReadBlob(image,image->colors,sun_colormap); if (count != (ssize_t) image->colors) ThrowReaderException(CorruptImageError,""UnexpectedEndOfFile""); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].blue=(MagickRealType) ScaleCharToQuantum( sun_colormap[i]); sun_colormap=(unsigned char *) RelinquishMagickMemory(sun_colormap); break; } case RMT_RAW: { unsigned char *sun_colormap; /* Read SUN raster colormap. */ sun_colormap=(unsigned char *) AcquireQuantumMemory(sun_info.maplength, sizeof(*sun_colormap)); if (sun_colormap == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); count=ReadBlob(image,sun_info.maplength,sun_colormap); if (count != (ssize_t) sun_info.maplength) ThrowReaderException(CorruptImageError,""UnexpectedEndOfFile""); sun_colormap=(unsigned char *) RelinquishMagickMemory(sun_colormap); break; } default: ThrowReaderException(CoderError,""ColormapTypeNotSupported""); } image->alpha_trait=sun_info.depth == 32 ? BlendPixelTrait : UndefinedPixelTrait; image->columns=sun_info.width; image->rows=sun_info.height; if (image_info->ping != MagickFalse) { (void) CloseBlob(image); return(GetFirstImageInList(image)); } status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); if ((sun_info.length*sizeof(*sun_data))/sizeof(*sun_data) != sun_info.length || !sun_info.length) ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); number_pixels=(MagickSizeType) image->columns*image->rows; if ((sun_info.type != RT_ENCODED) && ((number_pixels*sun_info.depth) > (8*sun_info.length))) ThrowReaderException(CorruptImageError,""ImproperImageHeader""); bytes_per_line=sun_info.width*sun_info.depth; sun_data=(unsigned char *) AcquireQuantumMemory((size_t) MagickMax( sun_info.length,bytes_per_line*sun_info.width),sizeof(*sun_data)); if (sun_data == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); count=(ssize_t) ReadBlob(image,sun_info.length,sun_data); if (count != (ssize_t) sun_info.length) ThrowReaderException(CorruptImageError,""UnableToReadImageData""); height=sun_info.height; if ((height == 0) || (sun_info.width == 0) || (sun_info.depth == 0) || ((bytes_per_line/sun_info.depth) != sun_info.width)) ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); bytes_per_line+=15; bytes_per_line<<=1; if ((bytes_per_line >> 1) != (sun_info.width*sun_info.depth+15)) ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); bytes_per_line>>=4; sun_pixels=(unsigned char *) AcquireQuantumMemory(height, bytes_per_line*sizeof(*sun_pixels)); if (sun_pixels == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); if (sun_info.type == RT_ENCODED) (void) DecodeImage(sun_data,sun_info.length,sun_pixels,bytes_per_line* height); sun_data=(unsigned char *) RelinquishMagickMemory(sun_data); /* Convert SUN raster image to pixel packets. */ p=sun_pixels; if (sun_info.depth == 1) for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < ((ssize_t) image->columns-7); x+=8) { for (bit=7; bit >= 0; bit--) { SetPixelIndex(image,(Quantum) ((*p) & (0x01 << bit) ? 0x00 : 0x01), q); q+=GetPixelChannels(image); } p++; } if ((image->columns % 8) != 0) { for (bit=7; bit >= (int) (8-(image->columns % 8)); bit--) { SetPixelIndex(image,(Quantum) ((*p) & (0x01 << bit) ? 0x00 : 0x01),q); q+=GetPixelChannels(image); } p++; } if ((((image->columns/8)+(image->columns % 8 ? 1 : 0)) % 2) != 0) p++; if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } else if (image->storage_class == PseudoClass) { if (bytes_per_line == 0) bytes_per_line=image->columns; length=image->rows*(image->columns+image->columns % 2); if (((sun_info.type == RT_ENCODED) && (length > (bytes_per_line*image->rows))) || ((sun_info.type != RT_ENCODED) && (length > sun_info.length))) ThrowReaderException(CorruptImageError,""UnableToReadImageData""); for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelIndex(image,*p++,q); q+=GetPixelChannels(image); } if ((image->columns % 2) != 0) p++; if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } } else { size_t bytes_per_pixel; bytes_per_pixel=3; if (image->alpha_trait != UndefinedPixelTrait) bytes_per_pixel++; if (bytes_per_line == 0) bytes_per_line=bytes_per_pixel*image->columns; length=image->rows*(bytes_per_line+bytes_per_line % 2); if (((sun_info.type == RT_ENCODED) && (length > (bytes_per_line*image->rows))) || ((sun_info.type != RT_ENCODED) && (length > sun_info.length))) ThrowReaderException(CorruptImageError,""UnableToReadImageData""); for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(image,ScaleCharToQuantum(*p++),q); if (sun_info.type == RT_STANDARD) { SetPixelBlue(image,ScaleCharToQuantum(*p++),q); SetPixelGreen(image,ScaleCharToQuantum(*p++),q); SetPixelRed(image,ScaleCharToQuantum(*p++),q); } else { SetPixelRed(image,ScaleCharToQuantum(*p++),q); SetPixelGreen(image,ScaleCharToQuantum(*p++),q); SetPixelBlue(image,ScaleCharToQuantum(*p++),q); } if (image->colors != 0) { SetPixelRed(image,ClampToQuantum(image->colormap[(ssize_t) GetPixelRed(image,q)].red),q); SetPixelGreen(image,ClampToQuantum(image->colormap[(ssize_t) GetPixelGreen(image,q)].green),q); SetPixelBlue(image,ClampToQuantum(image->colormap[(ssize_t) GetPixelBlue(image,q)].blue),q); } q+=GetPixelChannels(image); } if (((bytes_per_pixel*image->columns) % 2) != 0) p++; if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } } if (image->storage_class == PseudoClass) (void) SyncImage(image,exception); sun_pixels=(unsigned char *) RelinquishMagickMemory(sun_pixels); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,""UnexpectedEndOfFile"", image->filename); break; } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; sun_info.magic=ReadBlobMSBLong(image); if (sun_info.magic == 0x59a66a95) { /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } while (sun_info.magic == 0x59a66a95); (void) CloseBlob(image); return(GetFirstImageInList(image)); }","static Image *ReadSUNImage(const ImageInfo *image_info,ExceptionInfo *exception) { #define RMT_EQUAL_RGB 1 #define RMT_NONE 0 #define RMT_RAW 2 #define RT_STANDARD 1 #define RT_ENCODED 2 #define RT_FORMAT_RGB 3 typedef struct _SUNInfo { unsigned int magic, width, height, depth, length, type, maptype, maplength; } SUNInfo; Image *image; int bit; MagickBooleanType status; MagickSizeType number_pixels; register Quantum *q; register ssize_t i, x; register unsigned char *p; size_t bytes_per_line, extent, height, length; ssize_t count, y; SUNInfo sun_info; unsigned char *sun_data, *sun_pixels; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),""%s"", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read SUN raster header. */ (void) ResetMagickMemory(&sun_info,0,sizeof(sun_info)); sun_info.magic=ReadBlobMSBLong(image); do { /* Verify SUN identifier. */ if (sun_info.magic != 0x59a66a95) ThrowReaderException(CorruptImageError,""ImproperImageHeader""); sun_info.width=ReadBlobMSBLong(image); sun_info.height=ReadBlobMSBLong(image); sun_info.depth=ReadBlobMSBLong(image); sun_info.length=ReadBlobMSBLong(image); sun_info.type=ReadBlobMSBLong(image); sun_info.maptype=ReadBlobMSBLong(image); sun_info.maplength=ReadBlobMSBLong(image); extent=sun_info.height*sun_info.width; if ((sun_info.height != 0) && (sun_info.width != extent/sun_info.height)) ThrowReaderException(CorruptImageError,""ImproperImageHeader""); if ((sun_info.type != RT_STANDARD) && (sun_info.type != RT_ENCODED) && (sun_info.type != RT_FORMAT_RGB)) ThrowReaderException(CorruptImageError,""ImproperImageHeader""); if ((sun_info.maptype == RMT_NONE) && (sun_info.maplength != 0)) ThrowReaderException(CorruptImageError,""ImproperImageHeader""); if ((sun_info.depth == 0) || (sun_info.depth > 32)) ThrowReaderException(CorruptImageError,""ImproperImageHeader""); if ((sun_info.maptype != RMT_NONE) && (sun_info.maptype != RMT_EQUAL_RGB) && (sun_info.maptype != RMT_RAW)) ThrowReaderException(CoderError,""ColormapTypeNotSupported""); image->columns=sun_info.width; image->rows=sun_info.height; image->depth=sun_info.depth <= 8 ? sun_info.depth : MAGICKCORE_QUANTUM_DEPTH; if (sun_info.depth < 24) { size_t one; image->colors=sun_info.maplength; one=1; if (sun_info.maptype == RMT_NONE) image->colors=one << sun_info.depth; if (sun_info.maptype == RMT_EQUAL_RGB) image->colors=sun_info.maplength/3; if (AcquireImageColormap(image,image->colors,exception) == MagickFalse) ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); } switch (sun_info.maptype) { case RMT_NONE: break; case RMT_EQUAL_RGB: { unsigned char *sun_colormap; /* Read SUN raster colormap. */ sun_colormap=(unsigned char *) AcquireQuantumMemory(image->colors, sizeof(*sun_colormap)); if (sun_colormap == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); count=ReadBlob(image,image->colors,sun_colormap); if (count != (ssize_t) image->colors) ThrowReaderException(CorruptImageError,""UnexpectedEndOfFile""); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].red=(MagickRealType) ScaleCharToQuantum( sun_colormap[i]); count=ReadBlob(image,image->colors,sun_colormap); if (count != (ssize_t) image->colors) ThrowReaderException(CorruptImageError,""UnexpectedEndOfFile""); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].green=(MagickRealType) ScaleCharToQuantum( sun_colormap[i]); count=ReadBlob(image,image->colors,sun_colormap); if (count != (ssize_t) image->colors) ThrowReaderException(CorruptImageError,""UnexpectedEndOfFile""); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].blue=(MagickRealType) ScaleCharToQuantum( sun_colormap[i]); sun_colormap=(unsigned char *) RelinquishMagickMemory(sun_colormap); break; } case RMT_RAW: { unsigned char *sun_colormap; /* Read SUN raster colormap. */ sun_colormap=(unsigned char *) AcquireQuantumMemory(sun_info.maplength, sizeof(*sun_colormap)); if (sun_colormap == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); count=ReadBlob(image,sun_info.maplength,sun_colormap); if (count != (ssize_t) sun_info.maplength) ThrowReaderException(CorruptImageError,""UnexpectedEndOfFile""); sun_colormap=(unsigned char *) RelinquishMagickMemory(sun_colormap); break; } default: ThrowReaderException(CoderError,""ColormapTypeNotSupported""); } image->alpha_trait=sun_info.depth == 32 ? BlendPixelTrait : UndefinedPixelTrait; image->columns=sun_info.width; image->rows=sun_info.height; if (image_info->ping != MagickFalse) { (void) CloseBlob(image); return(GetFirstImageInList(image)); } status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); if ((sun_info.length*sizeof(*sun_data))/sizeof(*sun_data) != sun_info.length || !sun_info.length) ThrowReaderException(ResourceLimitError,""ImproperImageHeader""); number_pixels=(MagickSizeType) image->columns*image->rows; if ((sun_info.type != RT_ENCODED) && ((number_pixels*sun_info.depth) > (8*sun_info.length))) ThrowReaderException(CorruptImageError,""ImproperImageHeader""); bytes_per_line=sun_info.width*sun_info.depth; sun_data=(unsigned char *) AcquireQuantumMemory((size_t) MagickMax( sun_info.length,bytes_per_line*sun_info.width),sizeof(*sun_data)); if (sun_data == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); count=(ssize_t) ReadBlob(image,sun_info.length,sun_data); if (count != (ssize_t) sun_info.length) ThrowReaderException(CorruptImageError,""UnableToReadImageData""); height=sun_info.height; if ((height == 0) || (sun_info.width == 0) || (sun_info.depth == 0) || ((bytes_per_line/sun_info.depth) != sun_info.width)) ThrowReaderException(ResourceLimitError,""ImproperImageHeader""); bytes_per_line+=15; bytes_per_line<<=1; if ((bytes_per_line >> 1) != (sun_info.width*sun_info.depth+15)) ThrowReaderException(ResourceLimitError,""ImproperImageHeader""); bytes_per_line>>=4; sun_pixels=(unsigned char *) AcquireQuantumMemory(height, bytes_per_line*sizeof(*sun_pixels)); if (sun_pixels == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); if (sun_info.type == RT_ENCODED) (void) DecodeImage(sun_data,sun_info.length,sun_pixels,bytes_per_line* height); else { if (sun_info.length > (height*bytes_per_line)) ThrowReaderException(ResourceLimitError,""ImproperImageHeader""); (void) CopyMagickMemory(sun_pixels,sun_data,sun_info.length); } sun_data=(unsigned char *) RelinquishMagickMemory(sun_data); /* Convert SUN raster image to pixel packets. */ p=sun_pixels; if (sun_info.depth == 1) for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < ((ssize_t) image->columns-7); x+=8) { for (bit=7; bit >= 0; bit--) { SetPixelIndex(image,(Quantum) ((*p) & (0x01 << bit) ? 0x00 : 0x01), q); q+=GetPixelChannels(image); } p++; } if ((image->columns % 8) != 0) { for (bit=7; bit >= (int) (8-(image->columns % 8)); bit--) { SetPixelIndex(image,(Quantum) ((*p) & (0x01 << bit) ? 0x00 : 0x01),q); q+=GetPixelChannels(image); } p++; } if ((((image->columns/8)+(image->columns % 8 ? 1 : 0)) % 2) != 0) p++; if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } else if (image->storage_class == PseudoClass) { if (bytes_per_line == 0) bytes_per_line=image->columns; length=image->rows*(image->columns+image->columns % 2); if (((sun_info.type == RT_ENCODED) && (length > (bytes_per_line*image->rows))) || ((sun_info.type != RT_ENCODED) && (length > sun_info.length))) ThrowReaderException(CorruptImageError,""UnableToReadImageData""); for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelIndex(image,*p++,q); q+=GetPixelChannels(image); } if ((image->columns % 2) != 0) p++; if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } } else { size_t bytes_per_pixel; bytes_per_pixel=3; if (image->alpha_trait != UndefinedPixelTrait) bytes_per_pixel++; if (bytes_per_line == 0) bytes_per_line=bytes_per_pixel*image->columns; length=image->rows*(bytes_per_line+bytes_per_line % 2); if (((sun_info.type == RT_ENCODED) && (length > (bytes_per_line*image->rows))) || ((sun_info.type != RT_ENCODED) && (length > sun_info.length))) ThrowReaderException(CorruptImageError,""UnableToReadImageData""); for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(image,ScaleCharToQuantum(*p++),q); if (sun_info.type == RT_STANDARD) { SetPixelBlue(image,ScaleCharToQuantum(*p++),q); SetPixelGreen(image,ScaleCharToQuantum(*p++),q); SetPixelRed(image,ScaleCharToQuantum(*p++),q); } else { SetPixelRed(image,ScaleCharToQuantum(*p++),q); SetPixelGreen(image,ScaleCharToQuantum(*p++),q); SetPixelBlue(image,ScaleCharToQuantum(*p++),q); } if (image->colors != 0) { SetPixelRed(image,ClampToQuantum(image->colormap[(ssize_t) GetPixelRed(image,q)].red),q); SetPixelGreen(image,ClampToQuantum(image->colormap[(ssize_t) GetPixelGreen(image,q)].green),q); SetPixelBlue(image,ClampToQuantum(image->colormap[(ssize_t) GetPixelBlue(image,q)].blue),q); } q+=GetPixelChannels(image); } if (((bytes_per_pixel*image->columns) % 2) != 0) p++; if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } } if (image->storage_class == PseudoClass) (void) SyncImage(image,exception); sun_pixels=(unsigned char *) RelinquishMagickMemory(sun_pixels); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,""UnexpectedEndOfFile"", image->filename); break; } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; sun_info.magic=ReadBlobMSBLong(image); if (sun_info.magic == 0x59a66a95) { /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } while (sun_info.magic == 0x59a66a95); (void) CloseBlob(image); return(GetFirstImageInList(image)); }","{'deleted': [{'line_no': 201, 'char_start': 6237, 'char_end': 6310, 'line': ' ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed"");\n'}, {'line_no': 217, 'char_start': 7201, 'char_end': 7274, 'line': ' ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed"");\n'}, {'line_no': 221, 'char_start': 7391, 'char_end': 7464, 'line': ' ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed"");\n'}], 'added': [{'line_no': 201, 'char_start': 6237, 'char_end': 6307, 'line': ' ThrowReaderException(ResourceLimitError,""ImproperImageHeader"");\n'}, {'line_no': 217, 'char_start': 7198, 'char_end': 7268, 'line': ' ThrowReaderException(ResourceLimitError,""ImproperImageHeader"");\n'}, {'line_no': 221, 'char_start': 7385, 'char_end': 7455, 'line': ' ThrowReaderException(ResourceLimitError,""ImproperImageHeader"");\n'}, {'line_no': 230, 'char_start': 7834, 'char_end': 7843, 'line': ' else\n'}, {'line_no': 231, 'char_start': 7843, 'char_end': 7851, 'line': ' {\n'}, {'line_no': 232, 'char_start': 7851, 'char_end': 7906, 'line': ' if (sun_info.length > (height*bytes_per_line))\n'}, {'line_no': 233, 'char_start': 7906, 'char_end': 7980, 'line': ' ThrowReaderException(ResourceLimitError,""ImproperImageHeader"");\n'}, {'line_no': 234, 'char_start': 7980, 'char_end': 8050, 'line': ' (void) CopyMagickMemory(sun_pixels,sun_data,sun_info.length);\n'}, {'line_no': 235, 'char_start': 8050, 'char_end': 8058, 'line': ' }\n'}]}","{'deleted': [{'char_start': 6284, 'char_end': 6286, 'chars': 'Me'}, {'char_start': 6289, 'char_end': 6295, 'chars': 'yAlloc'}, {'char_start': 6296, 'char_end': 6304, 'chars': 'tionFail'}, {'char_start': 7248, 'char_end': 7250, 'chars': 'Me'}, {'char_start': 7253, 'char_end': 7259, 'chars': 'yAlloc'}, {'char_start': 7260, 'char_end': 7268, 'chars': 'tionFail'}, {'char_start': 7438, 'char_end': 7440, 'chars': 'Me'}, {'char_start': 7443, 'char_end': 7449, 'chars': 'yAlloc'}, {'char_start': 7450, 'char_end': 7458, 'chars': 'tionFail'}, {'char_start': 7826, 'char_end': 7826, 'chars': ''}], 'added': [{'char_start': 6284, 'char_end': 6285, 'chars': 'I'}, {'char_start': 6286, 'char_end': 6287, 'chars': 'p'}, {'char_start': 6289, 'char_end': 6294, 'chars': 'perIm'}, {'char_start': 6295, 'char_end': 6298, 'chars': 'geH'}, {'char_start': 6299, 'char_end': 6300, 'chars': 'a'}, {'char_start': 6301, 'char_end': 6303, 'chars': 'er'}, {'char_start': 7245, 'char_end': 7246, 'chars': 'I'}, {'char_start': 7247, 'char_end': 7248, 'chars': 'p'}, {'char_start': 7250, 'char_end': 7255, 'chars': 'perIm'}, {'char_start': 7256, 'char_end': 7259, 'chars': 'geH'}, {'char_start': 7260, 'char_end': 7261, 'chars': 'a'}, {'char_start': 7262, 'char_end': 7264, 'chars': 'er'}, {'char_start': 7432, 'char_end': 7433, 'chars': 'I'}, {'char_start': 7434, 'char_end': 7435, 'chars': 'p'}, {'char_start': 7437, 'char_end': 7442, 'chars': 'perIm'}, {'char_start': 7443, 'char_end': 7446, 'chars': 'geH'}, {'char_start': 7447, 'char_end': 7448, 'chars': 'a'}, {'char_start': 7449, 'char_end': 7451, 'chars': 'er'}, {'char_start': 7833, 'char_end': 8057, 'chars': '\n else\n {\n if (sun_info.length > (height*bytes_per_line))\n ThrowReaderException(ResourceLimitError,""ImproperImageHeader"");\n (void) CopyMagickMemory(sun_pixels,sun_data,sun_info.length);\n }'}]}",github.com/ImageMagick/ImageMagick/commit/6b4aff0f117b978502ee5bcd6e753c17aec5a961,coders/sun.c,cwe-125,3541 cwe-476,hash_accept,"static int hash_accept(struct socket *sock, struct socket *newsock, int flags) { struct sock *sk = sock->sk; struct alg_sock *ask = alg_sk(sk); struct hash_ctx *ctx = ask->private; struct ahash_request *req = &ctx->req; char state[crypto_ahash_statesize(crypto_ahash_reqtfm(req))]; struct sock *sk2; struct alg_sock *ask2; struct hash_ctx *ctx2; int err; err = crypto_ahash_export(req, state); if (err) return err; err = af_alg_accept(ask->parent, newsock); if (err) return err; sk2 = newsock->sk; ask2 = alg_sk(sk2); ctx2 = ask2->private; ctx2->more = 1; err = crypto_ahash_import(&ctx2->req, state); if (err) { sock_orphan(sk2); sock_put(sk2); } return err; }","static int hash_accept(struct socket *sock, struct socket *newsock, int flags) { struct sock *sk = sock->sk; struct alg_sock *ask = alg_sk(sk); struct hash_ctx *ctx = ask->private; struct ahash_request *req = &ctx->req; char state[crypto_ahash_statesize(crypto_ahash_reqtfm(req))]; struct sock *sk2; struct alg_sock *ask2; struct hash_ctx *ctx2; bool more; int err; lock_sock(sk); more = ctx->more; err = more ? crypto_ahash_export(req, state) : 0; release_sock(sk); if (err) return err; err = af_alg_accept(ask->parent, newsock); if (err) return err; sk2 = newsock->sk; ask2 = alg_sk(sk2); ctx2 = ask2->private; ctx2->more = more; if (!more) return err; err = crypto_ahash_import(&ctx2->req, state); if (err) { sock_orphan(sk2); sock_put(sk2); } return err; }","{'deleted': [{'line_no': 13, 'char_start': 365, 'char_end': 405, 'line': '\terr = crypto_ahash_export(req, state);\n'}, {'line_no': 24, 'char_start': 563, 'char_end': 580, 'line': '\tctx2->more = 1;\n'}], 'added': [{'line_no': 11, 'char_start': 354, 'char_end': 366, 'line': '\tbool more;\n'}, {'line_no': 14, 'char_start': 377, 'char_end': 393, 'line': '\tlock_sock(sk);\n'}, {'line_no': 15, 'char_start': 393, 'char_end': 412, 'line': '\tmore = ctx->more;\n'}, {'line_no': 16, 'char_start': 412, 'char_end': 463, 'line': '\terr = more ? crypto_ahash_export(req, state) : 0;\n'}, {'line_no': 17, 'char_start': 463, 'char_end': 482, 'line': '\trelease_sock(sk);\n'}, {'line_no': 18, 'char_start': 482, 'char_end': 483, 'line': '\n'}, {'line_no': 29, 'char_start': 641, 'char_end': 661, 'line': '\tctx2->more = more;\n'}, {'line_no': 30, 'char_start': 661, 'char_end': 662, 'line': '\n'}, {'line_no': 31, 'char_start': 662, 'char_end': 674, 'line': '\tif (!more)\n'}, {'line_no': 32, 'char_start': 674, 'char_end': 688, 'line': '\t\treturn err;\n'}]}","{'deleted': [{'char_start': 577, 'char_end': 578, 'chars': '1'}], 'added': [{'char_start': 355, 'char_end': 367, 'chars': 'bool more;\n\t'}, {'char_start': 378, 'char_end': 413, 'chars': 'lock_sock(sk);\n\tmore = ctx->more;\n\t'}, {'char_start': 418, 'char_end': 425, 'chars': ' more ?'}, {'char_start': 457, 'char_end': 461, 'chars': ' : 0'}, {'char_start': 462, 'char_end': 482, 'chars': '\n\trelease_sock(sk);\n'}, {'char_start': 655, 'char_end': 686, 'chars': 'more;\n\n\tif (!more)\n\t\treturn err'}]}",github.com/torvalds/linux/commit/4afa5f9617927453ac04b24b584f6c718dfb4f45,crypto/algif_hash.c,cwe-476,215 cwe-125,ape_decode_frame,"static int ape_decode_frame(AVCodecContext *avctx, void *data, int *got_frame_ptr, AVPacket *avpkt) { AVFrame *frame = data; const uint8_t *buf = avpkt->data; APEContext *s = avctx->priv_data; uint8_t *sample8; int16_t *sample16; int32_t *sample24; int i, ch, ret; int blockstodecode; /* this should never be negative, but bad things will happen if it is, so check it just to make sure. */ av_assert0(s->samples >= 0); if(!s->samples){ uint32_t nblocks, offset; int buf_size; if (!avpkt->size) { *got_frame_ptr = 0; return 0; } if (avpkt->size < 8) { av_log(avctx, AV_LOG_ERROR, ""Packet is too small\n""); return AVERROR_INVALIDDATA; } buf_size = avpkt->size & ~3; if (buf_size != avpkt->size) { av_log(avctx, AV_LOG_WARNING, ""packet size is not a multiple of 4. "" ""extra bytes at the end will be skipped.\n""); } if (s->fileversion < 3950) // previous versions overread two bytes buf_size += 2; av_fast_padded_malloc(&s->data, &s->data_size, buf_size); if (!s->data) return AVERROR(ENOMEM); s->bdsp.bswap_buf((uint32_t *) s->data, (const uint32_t *) buf, buf_size >> 2); memset(s->data + (buf_size & ~3), 0, buf_size & 3); s->ptr = s->data; s->data_end = s->data + buf_size; nblocks = bytestream_get_be32(&s->ptr); offset = bytestream_get_be32(&s->ptr); if (s->fileversion >= 3900) { if (offset > 3) { av_log(avctx, AV_LOG_ERROR, ""Incorrect offset passed\n""); s->data = NULL; return AVERROR_INVALIDDATA; } if (s->data_end - s->ptr < offset) { av_log(avctx, AV_LOG_ERROR, ""Packet is too small\n""); return AVERROR_INVALIDDATA; } s->ptr += offset; } else { if ((ret = init_get_bits8(&s->gb, s->ptr, s->data_end - s->ptr)) < 0) return ret; if (s->fileversion > 3800) skip_bits_long(&s->gb, offset * 8); else skip_bits_long(&s->gb, offset); } if (!nblocks || nblocks > INT_MAX) { av_log(avctx, AV_LOG_ERROR, ""Invalid sample count: %""PRIu32"".\n"", nblocks); return AVERROR_INVALIDDATA; } /* Initialize the frame decoder */ if (init_frame_decoder(s) < 0) { av_log(avctx, AV_LOG_ERROR, ""Error reading frame header\n""); return AVERROR_INVALIDDATA; } s->samples = nblocks; } if (!s->data) { *got_frame_ptr = 0; return avpkt->size; } blockstodecode = FFMIN(s->blocks_per_loop, s->samples); // for old files coefficients were not interleaved, // so we need to decode all of them at once if (s->fileversion < 3930) blockstodecode = s->samples; /* reallocate decoded sample buffer if needed */ av_fast_malloc(&s->decoded_buffer, &s->decoded_size, 2 * FFALIGN(blockstodecode, 8) * sizeof(*s->decoded_buffer)); if (!s->decoded_buffer) return AVERROR(ENOMEM); memset(s->decoded_buffer, 0, s->decoded_size); s->decoded[0] = s->decoded_buffer; s->decoded[1] = s->decoded_buffer + FFALIGN(blockstodecode, 8); /* get output buffer */ frame->nb_samples = blockstodecode; if ((ret = ff_get_buffer(avctx, frame, 0)) < 0) return ret; s->error=0; if ((s->channels == 1) || (s->frameflags & APE_FRAMECODE_PSEUDO_STEREO)) ape_unpack_mono(s, blockstodecode); else ape_unpack_stereo(s, blockstodecode); emms_c(); if (s->error) { s->samples=0; av_log(avctx, AV_LOG_ERROR, ""Error decoding frame\n""); return AVERROR_INVALIDDATA; } switch (s->bps) { case 8: for (ch = 0; ch < s->channels; ch++) { sample8 = (uint8_t *)frame->data[ch]; for (i = 0; i < blockstodecode; i++) *sample8++ = (s->decoded[ch][i] + 0x80) & 0xff; } break; case 16: for (ch = 0; ch < s->channels; ch++) { sample16 = (int16_t *)frame->data[ch]; for (i = 0; i < blockstodecode; i++) *sample16++ = s->decoded[ch][i]; } break; case 24: for (ch = 0; ch < s->channels; ch++) { sample24 = (int32_t *)frame->data[ch]; for (i = 0; i < blockstodecode; i++) *sample24++ = s->decoded[ch][i] << 8; } break; } s->samples -= blockstodecode; *got_frame_ptr = 1; return !s->samples ? avpkt->size : 0; }","static int ape_decode_frame(AVCodecContext *avctx, void *data, int *got_frame_ptr, AVPacket *avpkt) { AVFrame *frame = data; const uint8_t *buf = avpkt->data; APEContext *s = avctx->priv_data; uint8_t *sample8; int16_t *sample16; int32_t *sample24; int i, ch, ret; int blockstodecode; uint64_t decoded_buffer_size; /* this should never be negative, but bad things will happen if it is, so check it just to make sure. */ av_assert0(s->samples >= 0); if(!s->samples){ uint32_t nblocks, offset; int buf_size; if (!avpkt->size) { *got_frame_ptr = 0; return 0; } if (avpkt->size < 8) { av_log(avctx, AV_LOG_ERROR, ""Packet is too small\n""); return AVERROR_INVALIDDATA; } buf_size = avpkt->size & ~3; if (buf_size != avpkt->size) { av_log(avctx, AV_LOG_WARNING, ""packet size is not a multiple of 4. "" ""extra bytes at the end will be skipped.\n""); } if (s->fileversion < 3950) // previous versions overread two bytes buf_size += 2; av_fast_padded_malloc(&s->data, &s->data_size, buf_size); if (!s->data) return AVERROR(ENOMEM); s->bdsp.bswap_buf((uint32_t *) s->data, (const uint32_t *) buf, buf_size >> 2); memset(s->data + (buf_size & ~3), 0, buf_size & 3); s->ptr = s->data; s->data_end = s->data + buf_size; nblocks = bytestream_get_be32(&s->ptr); offset = bytestream_get_be32(&s->ptr); if (s->fileversion >= 3900) { if (offset > 3) { av_log(avctx, AV_LOG_ERROR, ""Incorrect offset passed\n""); s->data = NULL; return AVERROR_INVALIDDATA; } if (s->data_end - s->ptr < offset) { av_log(avctx, AV_LOG_ERROR, ""Packet is too small\n""); return AVERROR_INVALIDDATA; } s->ptr += offset; } else { if ((ret = init_get_bits8(&s->gb, s->ptr, s->data_end - s->ptr)) < 0) return ret; if (s->fileversion > 3800) skip_bits_long(&s->gb, offset * 8); else skip_bits_long(&s->gb, offset); } if (!nblocks || nblocks > INT_MAX / 2 / sizeof(*s->decoded_buffer) - 8) { av_log(avctx, AV_LOG_ERROR, ""Invalid sample count: %""PRIu32"".\n"", nblocks); return AVERROR_INVALIDDATA; } /* Initialize the frame decoder */ if (init_frame_decoder(s) < 0) { av_log(avctx, AV_LOG_ERROR, ""Error reading frame header\n""); return AVERROR_INVALIDDATA; } s->samples = nblocks; } if (!s->data) { *got_frame_ptr = 0; return avpkt->size; } blockstodecode = FFMIN(s->blocks_per_loop, s->samples); // for old files coefficients were not interleaved, // so we need to decode all of them at once if (s->fileversion < 3930) blockstodecode = s->samples; /* reallocate decoded sample buffer if needed */ decoded_buffer_size = 2LL * FFALIGN(blockstodecode, 8) * sizeof(*s->decoded_buffer); av_assert0(decoded_buffer_size <= INT_MAX); av_fast_malloc(&s->decoded_buffer, &s->decoded_size, decoded_buffer_size); if (!s->decoded_buffer) return AVERROR(ENOMEM); memset(s->decoded_buffer, 0, s->decoded_size); s->decoded[0] = s->decoded_buffer; s->decoded[1] = s->decoded_buffer + FFALIGN(blockstodecode, 8); /* get output buffer */ frame->nb_samples = blockstodecode; if ((ret = ff_get_buffer(avctx, frame, 0)) < 0) return ret; s->error=0; if ((s->channels == 1) || (s->frameflags & APE_FRAMECODE_PSEUDO_STEREO)) ape_unpack_mono(s, blockstodecode); else ape_unpack_stereo(s, blockstodecode); emms_c(); if (s->error) { s->samples=0; av_log(avctx, AV_LOG_ERROR, ""Error decoding frame\n""); return AVERROR_INVALIDDATA; } switch (s->bps) { case 8: for (ch = 0; ch < s->channels; ch++) { sample8 = (uint8_t *)frame->data[ch]; for (i = 0; i < blockstodecode; i++) *sample8++ = (s->decoded[ch][i] + 0x80) & 0xff; } break; case 16: for (ch = 0; ch < s->channels; ch++) { sample16 = (int16_t *)frame->data[ch]; for (i = 0; i < blockstodecode; i++) *sample16++ = s->decoded[ch][i]; } break; case 24: for (ch = 0; ch < s->channels; ch++) { sample24 = (int32_t *)frame->data[ch]; for (i = 0; i < blockstodecode; i++) *sample24++ = s->decoded[ch][i] << 8; } break; } s->samples -= blockstodecode; *got_frame_ptr = 1; return !s->samples ? avpkt->size : 0; }","{'deleted': [{'line_no': 67, 'char_start': 2347, 'char_end': 2392, 'line': ' if (!nblocks || nblocks > INT_MAX) {\n'}, {'line_no': 93, 'char_start': 3163, 'char_end': 3220, 'line': ' av_fast_malloc(&s->decoded_buffer, &s->decoded_size,\n'}, {'line_no': 94, 'char_start': 3220, 'char_end': 3301, 'line': ' 2 * FFALIGN(blockstodecode, 8) * sizeof(*s->decoded_buffer));\n'}], 'added': [{'line_no': 12, 'char_start': 349, 'char_end': 383, 'line': ' uint64_t decoded_buffer_size;\n'}, {'line_no': 68, 'char_start': 2381, 'char_end': 2463, 'line': ' if (!nblocks || nblocks > INT_MAX / 2 / sizeof(*s->decoded_buffer) - 8) {\n'}, {'line_no': 94, 'char_start': 3234, 'char_end': 3323, 'line': ' decoded_buffer_size = 2LL * FFALIGN(blockstodecode, 8) * sizeof(*s->decoded_buffer);\n'}, {'line_no': 95, 'char_start': 3323, 'char_end': 3371, 'line': ' av_assert0(decoded_buffer_size <= INT_MAX);\n'}, {'line_no': 96, 'char_start': 3371, 'char_end': 3450, 'line': ' av_fast_malloc(&s->decoded_buffer, &s->decoded_size, decoded_buffer_size);\n'}]}","{'deleted': [{'char_start': 3167, 'char_end': 3186, 'chars': 'av_fast_malloc(&s->'}, {'char_start': 3200, 'char_end': 3213, 'chars': ', &s->decoded'}, {'char_start': 3218, 'char_end': 3231, 'chars': ',\n '}, {'char_start': 3232, 'char_end': 3238, 'chars': ' '}], 'added': [{'char_start': 349, 'char_end': 383, 'chars': ' uint64_t decoded_buffer_size;\n'}, {'char_start': 2422, 'char_end': 2459, 'chars': ' / 2 / sizeof(*s->decoded_buffer) - 8'}, {'char_start': 3258, 'char_end': 3259, 'chars': '='}, {'char_start': 3261, 'char_end': 3263, 'chars': 'LL'}, {'char_start': 3321, 'char_end': 3447, 'chars': ';\n av_assert0(decoded_buffer_size <= INT_MAX);\n av_fast_malloc(&s->decoded_buffer, &s->decoded_size, decoded_buffer_size'}]}",github.com/FFmpeg/FFmpeg/commit/ba4beaf6149f7241c8bd85fe853318c2f6837ad0,libavcodec/apedec.c,cwe-125,1396 cwe-078,test_create_host," def test_create_host(self): self.flags(lock_path=self.tempdir) #record self.clear_mox() self.stubs.Set(hpfcdriver.hpcommon.HP3PARCommon, ""get_cpg"", self.fake_get_cpg) self.stubs.Set(hpfcdriver.hpcommon.HP3PARCommon, ""get_domain"", self.fake_get_domain) _run_ssh = self.mox.CreateMock(hpdriver.hpcommon.HP3PARCommon._run_ssh) self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, ""_run_ssh"", _run_ssh) show_host_cmd = 'showhost -verbose fakehost' _run_ssh(show_host_cmd, False).AndReturn([pack('no hosts listed'), '']) create_host_cmd = ('createhost -persona 1 -domain (\'OpenStack\',) ' 'fakehost 123456789012345 123456789054321') _run_ssh(create_host_cmd, False).AndReturn([CLI_CR, '']) _run_ssh(show_host_cmd, False).AndReturn([pack(FC_HOST_RET), '']) self.mox.ReplayAll() host = self.driver._create_host(self.volume, self.connector) self.assertEqual(host['name'], self.FAKE_HOST)"," def test_create_host(self): self.flags(lock_path=self.tempdir) #record self.clear_mox() self.stubs.Set(hpfcdriver.hpcommon.HP3PARCommon, ""get_cpg"", self.fake_get_cpg) self.stubs.Set(hpfcdriver.hpcommon.HP3PARCommon, ""get_domain"", self.fake_get_domain) _run_ssh = self.mox.CreateMock(hpdriver.hpcommon.HP3PARCommon._run_ssh) self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, ""_run_ssh"", _run_ssh) show_host_cmd = ['showhost', '-verbose', 'fakehost'] _run_ssh(show_host_cmd, False).AndReturn([pack('no hosts listed'), '']) create_host_cmd = (['createhost', '-persona', '1', '-domain', ('OpenStack',), 'fakehost', '123456789012345', '123456789054321']) _run_ssh(create_host_cmd, False).AndReturn([CLI_CR, '']) _run_ssh(show_host_cmd, False).AndReturn([pack(FC_HOST_RET), '']) self.mox.ReplayAll() host = self.driver._create_host(self.volume, self.connector) self.assertEqual(host['name'], self.FAKE_HOST)","{'deleted': [{'line_no': 13, 'char_start': 501, 'char_end': 554, 'line': "" show_host_cmd = 'showhost -verbose fakehost'\n""}, {'line_no': 16, 'char_start': 635, 'char_end': 712, 'line': "" create_host_cmd = ('createhost -persona 1 -domain (\\'OpenStack\\',) '\n""}, {'line_no': 17, 'char_start': 712, 'char_end': 783, 'line': "" 'fakehost 123456789012345 123456789054321')\n""}], 'added': [{'line_no': 13, 'char_start': 501, 'char_end': 562, 'line': "" show_host_cmd = ['showhost', '-verbose', 'fakehost']\n""}, {'line_no': 16, 'char_start': 643, 'char_end': 713, 'line': "" create_host_cmd = (['createhost', '-persona', '1', '-domain',\n""}, {'line_no': 17, 'char_start': 713, 'char_end': 788, 'line': "" ('OpenStack',), 'fakehost', '123456789012345',\n""}, {'line_no': 18, 'char_start': 788, 'char_end': 836, 'line': "" '123456789054321'])\n""}]}","{'deleted': [{'char_start': 692, 'char_end': 706, 'chars': "" (\\'OpenStack\\""}, {'char_start': 708, 'char_end': 711, 'chars': "") '""}], 'added': [{'char_start': 525, 'char_end': 526, 'chars': '['}, {'char_start': 535, 'char_end': 537, 'chars': ""',""}, {'char_start': 538, 'char_end': 539, 'chars': ""'""}, {'char_start': 547, 'char_end': 549, 'chars': ""',""}, {'char_start': 550, 'char_end': 551, 'chars': ""'""}, {'char_start': 560, 'char_end': 561, 'chars': ']'}, {'char_start': 670, 'char_end': 671, 'chars': '['}, {'char_start': 682, 'char_end': 684, 'chars': ""',""}, {'char_start': 685, 'char_end': 686, 'chars': ""'""}, {'char_start': 694, 'char_end': 696, 'chars': ""',""}, {'char_start': 697, 'char_end': 698, 'chars': ""'""}, {'char_start': 699, 'char_end': 701, 'chars': ""',""}, {'char_start': 702, 'char_end': 703, 'chars': ""'""}, {'char_start': 740, 'char_end': 757, 'chars': "" ('OpenStack',), ""}, {'char_start': 766, 'char_end': 768, 'chars': ""',""}, {'char_start': 769, 'char_end': 770, 'chars': ""'""}, {'char_start': 785, 'char_end': 798, 'chars': ""',\n ""}, {'char_start': 799, 'char_end': 817, 'chars': "" '""}, {'char_start': 833, 'char_end': 834, 'chars': ']'}]}",github.com/thatsdone/cinder/commit/c55589b131828f3a595903f6796cb2d0babb772f,cinder/tests/test_hp3par.py,cwe-078,295 cwe-079,handle_file,"def handle_file(u: Profile, headline: str, category: str, text: str, file): m: Media = Media() upload_base_path: str = 'uploads/' + str(date.today().year) high_res_file_name = upload_base_path + '/HIGHRES_' + ntpath.basename(file.name.replace("" "", ""_"")) low_res_file_name = upload_base_path + '/LOWRES_' + ntpath.basename(file.name.replace("" "", ""_"")) if not os.path.exists(PATH_TO_UPLOAD_FOLDER_ON_DISK + upload_base_path): os.makedirs(PATH_TO_UPLOAD_FOLDER_ON_DISK + upload_base_path) with open(high_res_file_name, 'wb+') as destination: for chunk in file.chunks(): destination.write(chunk) # TODO crop image original = Image.open(high_res_file_name) width, height = original.size diameter = math.sqrt(math.pow(width, 2) + math.pow(height, 2)) width /= diameter height /= diameter width *= IMAGE_SCALE height *= IMAGE_SCALE cropped = original.resize((int(width), int(height)), PIL.Image.LANCZOS) cropped.save(low_res_file_name) m.text = text m.cachedText = compile_markdown(text) m.category = category m.highResFile = ""/"" + high_res_file_name m.lowResFile = ""/"" + low_res_file_name m.headline = headline m.save() mu: MediaUpload = MediaUpload() mu.UID = u mu.MID = m mu.save() logging.info(""Uploaded file '"" + str(file.name) + ""' and cropped it. The resulting PK is "" + str(m.pk))","def handle_file(u: Profile, headline: str, category: str, text: str, file): m: Media = Media() upload_base_path: str = 'uploads/' + str(date.today().year) high_res_file_name = upload_base_path + '/HIGHRES_' + ntpath.basename(file.name.replace("" "", ""_"")) low_res_file_name = upload_base_path + '/LOWRES_' + ntpath.basename(file.name.replace("" "", ""_"")) if not os.path.exists(PATH_TO_UPLOAD_FOLDER_ON_DISK + upload_base_path): os.makedirs(PATH_TO_UPLOAD_FOLDER_ON_DISK + upload_base_path) with open(high_res_file_name, 'wb+') as destination: for chunk in file.chunks(): destination.write(chunk) # TODO crop image original = Image.open(high_res_file_name) width, height = original.size diameter = math.sqrt(math.pow(width, 2) + math.pow(height, 2)) width /= diameter height /= diameter width *= IMAGE_SCALE height *= IMAGE_SCALE cropped = original.resize((int(width), int(height)), PIL.Image.LANCZOS) cropped.save(low_res_file_name) m.text = escape(text) m.cachedText = compile_markdown(escape(text)) m.category = escape(category) m.highResFile = ""/"" + high_res_file_name m.lowResFile = ""/"" + low_res_file_name m.headline = escape(headline) m.save() mu: MediaUpload = MediaUpload() mu.UID = u mu.MID = m mu.save() logging.info(""Uploaded file '"" + str(file.name) + ""' and cropped it. The resulting PK is "" + str(m.pk))","{'deleted': [{'line_no': 21, 'char_start': 1021, 'char_end': 1039, 'line': ' m.text = text\n'}, {'line_no': 22, 'char_start': 1039, 'char_end': 1081, 'line': ' m.cachedText = compile_markdown(text)\n'}, {'line_no': 23, 'char_start': 1081, 'char_end': 1107, 'line': ' m.category = category\n'}, {'line_no': 26, 'char_start': 1195, 'char_end': 1221, 'line': ' m.headline = headline\n'}], 'added': [{'line_no': 21, 'char_start': 1021, 'char_end': 1047, 'line': ' m.text = escape(text)\n'}, {'line_no': 22, 'char_start': 1047, 'char_end': 1097, 'line': ' m.cachedText = compile_markdown(escape(text))\n'}, {'line_no': 23, 'char_start': 1097, 'char_end': 1131, 'line': ' m.category = escape(category)\n'}, {'line_no': 26, 'char_start': 1219, 'char_end': 1253, 'line': ' m.headline = escape(headline)\n'}]}","{'deleted': [], 'added': [{'char_start': 1034, 'char_end': 1041, 'chars': 'escape('}, {'char_start': 1045, 'char_end': 1046, 'chars': ')'}, {'char_start': 1083, 'char_end': 1090, 'chars': 'escape('}, {'char_start': 1094, 'char_end': 1095, 'chars': ')'}, {'char_start': 1114, 'char_end': 1121, 'chars': 'escape('}, {'char_start': 1129, 'char_end': 1130, 'chars': ')'}, {'char_start': 1236, 'char_end': 1243, 'chars': 'escape('}, {'char_start': 1251, 'char_end': 1252, 'chars': ')'}]}",github.com/Technikradio/C3FOCSite/commit/6e330d4d44bbfdfce9993dffea97008276771600,c3shop/frontpage/management/mediatools/media_actions.py,cwe-079,363 cwe-190,futex_requeue,"static int futex_requeue(u32 __user *uaddr1, unsigned int flags, u32 __user *uaddr2, int nr_wake, int nr_requeue, u32 *cmpval, int requeue_pi) { union futex_key key1 = FUTEX_KEY_INIT, key2 = FUTEX_KEY_INIT; int drop_count = 0, task_count = 0, ret; struct futex_pi_state *pi_state = NULL; struct futex_hash_bucket *hb1, *hb2; struct futex_q *this, *next; DEFINE_WAKE_Q(wake_q); /* * When PI not supported: return -ENOSYS if requeue_pi is true, * consequently the compiler knows requeue_pi is always false past * this point which will optimize away all the conditional code * further down. */ if (!IS_ENABLED(CONFIG_FUTEX_PI) && requeue_pi) return -ENOSYS; if (requeue_pi) { /* * Requeue PI only works on two distinct uaddrs. This * check is only valid for private futexes. See below. */ if (uaddr1 == uaddr2) return -EINVAL; /* * requeue_pi requires a pi_state, try to allocate it now * without any locks in case it fails. */ if (refill_pi_state_cache()) return -ENOMEM; /* * requeue_pi must wake as many tasks as it can, up to nr_wake * + nr_requeue, since it acquires the rt_mutex prior to * returning to userspace, so as to not leave the rt_mutex with * waiters and no owner. However, second and third wake-ups * cannot be predicted as they involve race conditions with the * first wake and a fault while looking up the pi_state. Both * pthread_cond_signal() and pthread_cond_broadcast() should * use nr_wake=1. */ if (nr_wake != 1) return -EINVAL; } retry: ret = get_futex_key(uaddr1, flags & FLAGS_SHARED, &key1, VERIFY_READ); if (unlikely(ret != 0)) goto out; ret = get_futex_key(uaddr2, flags & FLAGS_SHARED, &key2, requeue_pi ? VERIFY_WRITE : VERIFY_READ); if (unlikely(ret != 0)) goto out_put_key1; /* * The check above which compares uaddrs is not sufficient for * shared futexes. We need to compare the keys: */ if (requeue_pi && match_futex(&key1, &key2)) { ret = -EINVAL; goto out_put_keys; } hb1 = hash_futex(&key1); hb2 = hash_futex(&key2); retry_private: hb_waiters_inc(hb2); double_lock_hb(hb1, hb2); if (likely(cmpval != NULL)) { u32 curval; ret = get_futex_value_locked(&curval, uaddr1); if (unlikely(ret)) { double_unlock_hb(hb1, hb2); hb_waiters_dec(hb2); ret = get_user(curval, uaddr1); if (ret) goto out_put_keys; if (!(flags & FLAGS_SHARED)) goto retry_private; put_futex_key(&key2); put_futex_key(&key1); goto retry; } if (curval != *cmpval) { ret = -EAGAIN; goto out_unlock; } } if (requeue_pi && (task_count - nr_wake < nr_requeue)) { /* * Attempt to acquire uaddr2 and wake the top waiter. If we * intend to requeue waiters, force setting the FUTEX_WAITERS * bit. We force this here where we are able to easily handle * faults rather in the requeue loop below. */ ret = futex_proxy_trylock_atomic(uaddr2, hb1, hb2, &key1, &key2, &pi_state, nr_requeue); /* * At this point the top_waiter has either taken uaddr2 or is * waiting on it. If the former, then the pi_state will not * exist yet, look it up one more time to ensure we have a * reference to it. If the lock was taken, ret contains the * vpid of the top waiter task. * If the lock was not taken, we have pi_state and an initial * refcount on it. In case of an error we have nothing. */ if (ret > 0) { WARN_ON(pi_state); drop_count++; task_count++; /* * If we acquired the lock, then the user space value * of uaddr2 should be vpid. It cannot be changed by * the top waiter as it is blocked on hb2 lock if it * tries to do so. If something fiddled with it behind * our back the pi state lookup might unearth it. So * we rather use the known value than rereading and * handing potential crap to lookup_pi_state. * * If that call succeeds then we have pi_state and an * initial refcount on it. */ ret = lookup_pi_state(uaddr2, ret, hb2, &key2, &pi_state); } switch (ret) { case 0: /* We hold a reference on the pi state. */ break; /* If the above failed, then pi_state is NULL */ case -EFAULT: double_unlock_hb(hb1, hb2); hb_waiters_dec(hb2); put_futex_key(&key2); put_futex_key(&key1); ret = fault_in_user_writeable(uaddr2); if (!ret) goto retry; goto out; case -EAGAIN: /* * Two reasons for this: * - Owner is exiting and we just wait for the * exit to complete. * - The user space value changed. */ double_unlock_hb(hb1, hb2); hb_waiters_dec(hb2); put_futex_key(&key2); put_futex_key(&key1); cond_resched(); goto retry; default: goto out_unlock; } } plist_for_each_entry_safe(this, next, &hb1->chain, list) { if (task_count - nr_wake >= nr_requeue) break; if (!match_futex(&this->key, &key1)) continue; /* * FUTEX_WAIT_REQEUE_PI and FUTEX_CMP_REQUEUE_PI should always * be paired with each other and no other futex ops. * * We should never be requeueing a futex_q with a pi_state, * which is awaiting a futex_unlock_pi(). */ if ((requeue_pi && !this->rt_waiter) || (!requeue_pi && this->rt_waiter) || this->pi_state) { ret = -EINVAL; break; } /* * Wake nr_wake waiters. For requeue_pi, if we acquired the * lock, we already woke the top_waiter. If not, it will be * woken by futex_unlock_pi(). */ if (++task_count <= nr_wake && !requeue_pi) { mark_wake_futex(&wake_q, this); continue; } /* Ensure we requeue to the expected futex for requeue_pi. */ if (requeue_pi && !match_futex(this->requeue_pi_key, &key2)) { ret = -EINVAL; break; } /* * Requeue nr_requeue waiters and possibly one more in the case * of requeue_pi if we couldn't acquire the lock atomically. */ if (requeue_pi) { /* * Prepare the waiter to take the rt_mutex. Take a * refcount on the pi_state and store the pointer in * the futex_q object of the waiter. */ get_pi_state(pi_state); this->pi_state = pi_state; ret = rt_mutex_start_proxy_lock(&pi_state->pi_mutex, this->rt_waiter, this->task); if (ret == 1) { /* * We got the lock. We do neither drop the * refcount on pi_state nor clear * this->pi_state because the waiter needs the * pi_state for cleaning up the user space * value. It will drop the refcount after * doing so. */ requeue_pi_wake_futex(this, &key2, hb2); drop_count++; continue; } else if (ret) { /* * rt_mutex_start_proxy_lock() detected a * potential deadlock when we tried to queue * that waiter. Drop the pi_state reference * which we took above and remove the pointer * to the state from the waiters futex_q * object. */ this->pi_state = NULL; put_pi_state(pi_state); /* * We stop queueing more waiters and let user * space deal with the mess. */ break; } } requeue_futex(this, hb1, hb2, &key2); drop_count++; } /* * We took an extra initial reference to the pi_state either * in futex_proxy_trylock_atomic() or in lookup_pi_state(). We * need to drop it here again. */ put_pi_state(pi_state); out_unlock: double_unlock_hb(hb1, hb2); wake_up_q(&wake_q); hb_waiters_dec(hb2); /* * drop_futex_key_refs() must be called outside the spinlocks. During * the requeue we moved futex_q's from the hash bucket at key1 to the * one at key2 and updated their key pointer. We no longer need to * hold the references to key1. */ while (--drop_count >= 0) drop_futex_key_refs(&key1); out_put_keys: put_futex_key(&key2); out_put_key1: put_futex_key(&key1); out: return ret ? ret : task_count; }","static int futex_requeue(u32 __user *uaddr1, unsigned int flags, u32 __user *uaddr2, int nr_wake, int nr_requeue, u32 *cmpval, int requeue_pi) { union futex_key key1 = FUTEX_KEY_INIT, key2 = FUTEX_KEY_INIT; int drop_count = 0, task_count = 0, ret; struct futex_pi_state *pi_state = NULL; struct futex_hash_bucket *hb1, *hb2; struct futex_q *this, *next; DEFINE_WAKE_Q(wake_q); if (nr_wake < 0 || nr_requeue < 0) return -EINVAL; /* * When PI not supported: return -ENOSYS if requeue_pi is true, * consequently the compiler knows requeue_pi is always false past * this point which will optimize away all the conditional code * further down. */ if (!IS_ENABLED(CONFIG_FUTEX_PI) && requeue_pi) return -ENOSYS; if (requeue_pi) { /* * Requeue PI only works on two distinct uaddrs. This * check is only valid for private futexes. See below. */ if (uaddr1 == uaddr2) return -EINVAL; /* * requeue_pi requires a pi_state, try to allocate it now * without any locks in case it fails. */ if (refill_pi_state_cache()) return -ENOMEM; /* * requeue_pi must wake as many tasks as it can, up to nr_wake * + nr_requeue, since it acquires the rt_mutex prior to * returning to userspace, so as to not leave the rt_mutex with * waiters and no owner. However, second and third wake-ups * cannot be predicted as they involve race conditions with the * first wake and a fault while looking up the pi_state. Both * pthread_cond_signal() and pthread_cond_broadcast() should * use nr_wake=1. */ if (nr_wake != 1) return -EINVAL; } retry: ret = get_futex_key(uaddr1, flags & FLAGS_SHARED, &key1, VERIFY_READ); if (unlikely(ret != 0)) goto out; ret = get_futex_key(uaddr2, flags & FLAGS_SHARED, &key2, requeue_pi ? VERIFY_WRITE : VERIFY_READ); if (unlikely(ret != 0)) goto out_put_key1; /* * The check above which compares uaddrs is not sufficient for * shared futexes. We need to compare the keys: */ if (requeue_pi && match_futex(&key1, &key2)) { ret = -EINVAL; goto out_put_keys; } hb1 = hash_futex(&key1); hb2 = hash_futex(&key2); retry_private: hb_waiters_inc(hb2); double_lock_hb(hb1, hb2); if (likely(cmpval != NULL)) { u32 curval; ret = get_futex_value_locked(&curval, uaddr1); if (unlikely(ret)) { double_unlock_hb(hb1, hb2); hb_waiters_dec(hb2); ret = get_user(curval, uaddr1); if (ret) goto out_put_keys; if (!(flags & FLAGS_SHARED)) goto retry_private; put_futex_key(&key2); put_futex_key(&key1); goto retry; } if (curval != *cmpval) { ret = -EAGAIN; goto out_unlock; } } if (requeue_pi && (task_count - nr_wake < nr_requeue)) { /* * Attempt to acquire uaddr2 and wake the top waiter. If we * intend to requeue waiters, force setting the FUTEX_WAITERS * bit. We force this here where we are able to easily handle * faults rather in the requeue loop below. */ ret = futex_proxy_trylock_atomic(uaddr2, hb1, hb2, &key1, &key2, &pi_state, nr_requeue); /* * At this point the top_waiter has either taken uaddr2 or is * waiting on it. If the former, then the pi_state will not * exist yet, look it up one more time to ensure we have a * reference to it. If the lock was taken, ret contains the * vpid of the top waiter task. * If the lock was not taken, we have pi_state and an initial * refcount on it. In case of an error we have nothing. */ if (ret > 0) { WARN_ON(pi_state); drop_count++; task_count++; /* * If we acquired the lock, then the user space value * of uaddr2 should be vpid. It cannot be changed by * the top waiter as it is blocked on hb2 lock if it * tries to do so. If something fiddled with it behind * our back the pi state lookup might unearth it. So * we rather use the known value than rereading and * handing potential crap to lookup_pi_state. * * If that call succeeds then we have pi_state and an * initial refcount on it. */ ret = lookup_pi_state(uaddr2, ret, hb2, &key2, &pi_state); } switch (ret) { case 0: /* We hold a reference on the pi state. */ break; /* If the above failed, then pi_state is NULL */ case -EFAULT: double_unlock_hb(hb1, hb2); hb_waiters_dec(hb2); put_futex_key(&key2); put_futex_key(&key1); ret = fault_in_user_writeable(uaddr2); if (!ret) goto retry; goto out; case -EAGAIN: /* * Two reasons for this: * - Owner is exiting and we just wait for the * exit to complete. * - The user space value changed. */ double_unlock_hb(hb1, hb2); hb_waiters_dec(hb2); put_futex_key(&key2); put_futex_key(&key1); cond_resched(); goto retry; default: goto out_unlock; } } plist_for_each_entry_safe(this, next, &hb1->chain, list) { if (task_count - nr_wake >= nr_requeue) break; if (!match_futex(&this->key, &key1)) continue; /* * FUTEX_WAIT_REQEUE_PI and FUTEX_CMP_REQUEUE_PI should always * be paired with each other and no other futex ops. * * We should never be requeueing a futex_q with a pi_state, * which is awaiting a futex_unlock_pi(). */ if ((requeue_pi && !this->rt_waiter) || (!requeue_pi && this->rt_waiter) || this->pi_state) { ret = -EINVAL; break; } /* * Wake nr_wake waiters. For requeue_pi, if we acquired the * lock, we already woke the top_waiter. If not, it will be * woken by futex_unlock_pi(). */ if (++task_count <= nr_wake && !requeue_pi) { mark_wake_futex(&wake_q, this); continue; } /* Ensure we requeue to the expected futex for requeue_pi. */ if (requeue_pi && !match_futex(this->requeue_pi_key, &key2)) { ret = -EINVAL; break; } /* * Requeue nr_requeue waiters and possibly one more in the case * of requeue_pi if we couldn't acquire the lock atomically. */ if (requeue_pi) { /* * Prepare the waiter to take the rt_mutex. Take a * refcount on the pi_state and store the pointer in * the futex_q object of the waiter. */ get_pi_state(pi_state); this->pi_state = pi_state; ret = rt_mutex_start_proxy_lock(&pi_state->pi_mutex, this->rt_waiter, this->task); if (ret == 1) { /* * We got the lock. We do neither drop the * refcount on pi_state nor clear * this->pi_state because the waiter needs the * pi_state for cleaning up the user space * value. It will drop the refcount after * doing so. */ requeue_pi_wake_futex(this, &key2, hb2); drop_count++; continue; } else if (ret) { /* * rt_mutex_start_proxy_lock() detected a * potential deadlock when we tried to queue * that waiter. Drop the pi_state reference * which we took above and remove the pointer * to the state from the waiters futex_q * object. */ this->pi_state = NULL; put_pi_state(pi_state); /* * We stop queueing more waiters and let user * space deal with the mess. */ break; } } requeue_futex(this, hb1, hb2, &key2); drop_count++; } /* * We took an extra initial reference to the pi_state either * in futex_proxy_trylock_atomic() or in lookup_pi_state(). We * need to drop it here again. */ put_pi_state(pi_state); out_unlock: double_unlock_hb(hb1, hb2); wake_up_q(&wake_q); hb_waiters_dec(hb2); /* * drop_futex_key_refs() must be called outside the spinlocks. During * the requeue we moved futex_q's from the hash bucket at key1 to the * one at key2 and updated their key pointer. We no longer need to * hold the references to key1. */ while (--drop_count >= 0) drop_futex_key_refs(&key1); out_put_keys: put_futex_key(&key2); out_put_key1: put_futex_key(&key1); out: return ret ? ret : task_count; }","{'deleted': [], 'added': [{'line_no': 12, 'char_start': 392, 'char_end': 428, 'line': '\tif (nr_wake < 0 || nr_requeue < 0)\n'}, {'line_no': 13, 'char_start': 428, 'char_end': 446, 'line': '\t\treturn -EINVAL;\n'}, {'line_no': 14, 'char_start': 446, 'char_end': 447, 'line': '\n'}]}","{'deleted': [], 'added': [{'char_start': 393, 'char_end': 448, 'chars': 'if (nr_wake < 0 || nr_requeue < 0)\n\t\treturn -EINVAL;\n\n\t'}]}",github.com/torvalds/linux/commit/fbe0e839d1e22d88810f3ee3e2f1479be4c0aa4a,kernel/futex.c,cwe-190,2348 cwe-022,list," def list(self, keyfilter='/'): path = os.path.join(self.namespace, keyfilter) if path != '/': path = path.rstrip('/') try: result = self.etcd.read(path, recursive=True) except etcd.EtcdKeyNotFound: return None except etcd.EtcdException as err: log_error(""Error listing %s: [%r]"" % (keyfilter, repr(err))) raise CSStoreError('Error occurred while trying to list keys') value = set() for entry in result.get_subtree(): if entry.key == path: continue name = entry.key[len(path):] if entry.dir and not name.endswith('/'): name += '/' value.add(name.lstrip('/')) return sorted(value)"," def list(self, keyfilter='/'): path = self._absolute_key(keyfilter) if path != '/': path = path.rstrip('/') try: result = self.etcd.read(path, recursive=True) except etcd.EtcdKeyNotFound: return None except etcd.EtcdException as err: log_error(""Error listing %s: [%r]"" % (keyfilter, repr(err))) raise CSStoreError('Error occurred while trying to list keys') value = set() for entry in result.get_subtree(): if entry.key == path: continue name = entry.key[len(path):] if entry.dir and not name.endswith('/'): name += '/' value.add(name.lstrip('/')) return sorted(value)","{'deleted': [{'line_no': 2, 'char_start': 35, 'char_end': 90, 'line': ' path = os.path.join(self.namespace, keyfilter)\n'}], 'added': [{'line_no': 2, 'char_start': 35, 'char_end': 80, 'line': ' path = self._absolute_key(keyfilter)\n'}]}","{'deleted': [{'char_start': 50, 'char_end': 63, 'chars': 'os.path.join('}, {'char_start': 68, 'char_end': 69, 'chars': 'n'}, {'char_start': 70, 'char_end': 72, 'chars': 'me'}, {'char_start': 73, 'char_end': 76, 'chars': 'pac'}, {'char_start': 77, 'char_end': 79, 'chars': ', '}], 'added': [{'char_start': 55, 'char_end': 56, 'chars': '_'}, {'char_start': 57, 'char_end': 63, 'chars': 'bsolut'}, {'char_start': 64, 'char_end': 66, 'chars': '_k'}, {'char_start': 67, 'char_end': 69, 'chars': 'y('}]}",github.com/latchset/custodia/commit/785fc87f38b4811bc4ce43a0a9b2267ee7d500b4,custodia/store/etcdstore.py,cwe-022,167 cwe-089,delete_playlist,"def delete_playlist(id, db): db.execute(""DELETE FROM playlist where id={id};"".format(id=id))","def delete_playlist(id, db): db.execute(""DELETE FROM playlist where id=%s;"", (id,))","{'deleted': [{'line_no': 2, 'char_start': 29, 'char_end': 96, 'line': ' db.execute(""DELETE FROM playlist where id={id};"".format(id=id))\n'}], 'added': [{'line_no': 2, 'char_start': 29, 'char_end': 87, 'line': ' db.execute(""DELETE FROM playlist where id=%s;"", (id,))\n'}]}","{'deleted': [{'char_start': 75, 'char_end': 79, 'chars': '{id}'}, {'char_start': 81, 'char_end': 88, 'chars': '.format'}, {'char_start': 91, 'char_end': 94, 'chars': '=id'}], 'added': [{'char_start': 75, 'char_end': 77, 'chars': '%s'}, {'char_start': 79, 'char_end': 81, 'chars': ', '}, {'char_start': 84, 'char_end': 85, 'chars': ','}]}",github.com/Madmous/playlist/commit/666e52c5f0b8c1f4296e84471637033d9542a7a6,playlist/playlist_repository.py,cwe-089,24 cwe-787,handle_PORT,"static void handle_PORT(ctrl_t *ctrl, char *str) { int a, b, c, d, e, f; char addr[INET_ADDRSTRLEN]; struct sockaddr_in sin; if (ctrl->data_sd > 0) { uev_io_stop(&ctrl->data_watcher); close(ctrl->data_sd); ctrl->data_sd = -1; } /* Convert PORT command's argument to IP address + port */ sscanf(str, ""%d,%d,%d,%d,%d,%d"", &a, &b, &c, &d, &e, &f); sprintf(addr, ""%d.%d.%d.%d"", a, b, c, d); /* Check IPv4 address using inet_aton(), throw away converted result */ if (!inet_aton(addr, &(sin.sin_addr))) { ERR(0, ""Invalid address '%s' given to PORT command"", addr); send_msg(ctrl->sd, ""500 Illegal PORT command.\r\n""); return; } strlcpy(ctrl->data_address, addr, sizeof(ctrl->data_address)); ctrl->data_port = e * 256 + f; DBG(""Client PORT command accepted for %s:%d"", ctrl->data_address, ctrl->data_port); send_msg(ctrl->sd, ""200 PORT command successful.\r\n""); }","static void handle_PORT(ctrl_t *ctrl, char *str) { int a, b, c, d, e, f; char addr[INET_ADDRSTRLEN]; struct sockaddr_in sin; if (ctrl->data_sd > 0) { uev_io_stop(&ctrl->data_watcher); close(ctrl->data_sd); ctrl->data_sd = -1; } /* Convert PORT command's argument to IP address + port */ sscanf(str, ""%d,%d,%d,%d,%d,%d"", &a, &b, &c, &d, &e, &f); snprintf(addr, sizeof(addr), ""%d.%d.%d.%d"", a, b, c, d); /* Check IPv4 address using inet_aton(), throw away converted result */ if (!inet_aton(addr, &(sin.sin_addr))) { ERR(0, ""Invalid address '%s' given to PORT command"", addr); send_msg(ctrl->sd, ""500 Illegal PORT command.\r\n""); return; } strlcpy(ctrl->data_address, addr, sizeof(ctrl->data_address)); ctrl->data_port = e * 256 + f; DBG(""Client PORT command accepted for %s:%d"", ctrl->data_address, ctrl->data_port); send_msg(ctrl->sd, ""200 PORT command successful.\r\n""); }","{'deleted': [{'line_no': 15, 'char_start': 360, 'char_end': 403, 'line': '\tsprintf(addr, ""%d.%d.%d.%d"", a, b, c, d);\n'}], 'added': [{'line_no': 15, 'char_start': 360, 'char_end': 418, 'line': '\tsnprintf(addr, sizeof(addr), ""%d.%d.%d.%d"", a, b, c, d);\n'}]}","{'deleted': [], 'added': [{'char_start': 362, 'char_end': 363, 'chars': 'n'}, {'char_start': 374, 'char_end': 388, 'chars': ', sizeof(addr)'}]}",github.com/troglobit/uftpd/commit/0fb2c031ce0ace07cc19cd2cb2143c4b5a63c9dd,src/ftpcmd.c,cwe-787,290 cwe-089,all_deposits," def all_deposits(self,coin): sql = ""SELECT * FROM deposits WHERE coin='%s'"" % coin self.cursor.execute(sql) return self.cursor.fetchall()"," def all_deposits(self,coin): sql = ""SELECT * FROM deposits WHERE coin='%s'"" self.cursor.execute(sql, (coin,)) return self.cursor.fetchall()","{'deleted': [{'line_no': 2, 'char_start': 33, 'char_end': 95, 'line': ' sql = ""SELECT * FROM deposits WHERE coin=\'%s\'"" % coin\n'}, {'line_no': 3, 'char_start': 95, 'char_end': 128, 'line': ' self.cursor.execute(sql)\n'}], 'added': [{'line_no': 2, 'char_start': 33, 'char_end': 88, 'line': ' sql = ""SELECT * FROM deposits WHERE coin=\'%s\'""\n'}, {'line_no': 3, 'char_start': 88, 'char_end': 130, 'line': ' self.cursor.execute(sql, (coin,))\n'}]}","{'deleted': [{'char_start': 87, 'char_end': 94, 'chars': ' % coin'}], 'added': [{'char_start': 119, 'char_end': 128, 'chars': ', (coin,)'}]}",github.com/ktechmidas/garlictipsbot/commit/7c262255f933cb721109ac4be752b5b7599275aa,deposit.py,cwe-089,38 cwe-089,followFriends," def followFriends(self,userid,friendid): sqlText=""insert into friends values(%d,%d);""%(friendid,userid) result=sql.insertDB(self.conn,sqlText) return result;"," def followFriends(self,userid,friendid): sqlText=""insert into friends values(%s,%s);"" params=[friendid,userid] result=sql.insertDB(self.conn,sqlText,params) return result;","{'deleted': [{'line_no': 2, 'char_start': 45, 'char_end': 116, 'line': ' sqlText=""insert into friends values(%d,%d);""%(friendid,userid)\n'}, {'line_no': 3, 'char_start': 116, 'char_end': 163, 'line': ' result=sql.insertDB(self.conn,sqlText)\n'}], 'added': [{'line_no': 2, 'char_start': 45, 'char_end': 98, 'line': ' sqlText=""insert into friends values(%s,%s);""\n'}, {'line_no': 3, 'char_start': 98, 'char_end': 131, 'line': ' params=[friendid,userid]\n'}, {'line_no': 4, 'char_start': 131, 'char_end': 185, 'line': ' result=sql.insertDB(self.conn,sqlText,params)\n'}]}","{'deleted': [{'char_start': 90, 'char_end': 91, 'chars': 'd'}, {'char_start': 93, 'char_end': 94, 'chars': 'd'}, {'char_start': 97, 'char_end': 99, 'chars': '%('}, {'char_start': 114, 'char_end': 115, 'chars': ')'}], 'added': [{'char_start': 90, 'char_end': 91, 'chars': 's'}, {'char_start': 93, 'char_end': 94, 'chars': 's'}, {'char_start': 97, 'char_end': 114, 'chars': '\n params=['}, {'char_start': 129, 'char_end': 130, 'chars': ']'}, {'char_start': 176, 'char_end': 183, 'chars': ',params'}]}",github.com/ShaominLi/Twitter_project/commit/5329d91f9e569c95184053c8e7ef596949c33ce9,modules/users.py,cwe-089,46 cwe-125,parallel_process_irp_create,"static UINT parallel_process_irp_create(PARALLEL_DEVICE* parallel, IRP* irp) { char* path = NULL; int status; UINT32 PathLength; Stream_Seek(irp->input, 28); /* DesiredAccess(4) AllocationSize(8), FileAttributes(4) */ /* SharedAccess(4) CreateDisposition(4), CreateOptions(4) */ Stream_Read_UINT32(irp->input, PathLength); status = ConvertFromUnicode(CP_UTF8, 0, (WCHAR*)Stream_Pointer(irp->input), PathLength / 2, &path, 0, NULL, NULL); if (status < 1) if (!(path = (char*)calloc(1, 1))) { WLog_ERR(TAG, ""calloc failed!""); return CHANNEL_RC_NO_MEMORY; } parallel->id = irp->devman->id_sequence++; parallel->file = open(parallel->path, O_RDWR); if (parallel->file < 0) { irp->IoStatus = STATUS_ACCESS_DENIED; parallel->id = 0; } else { /* all read and write operations should be non-blocking */ if (fcntl(parallel->file, F_SETFL, O_NONBLOCK) == -1) { } } Stream_Write_UINT32(irp->output, parallel->id); Stream_Write_UINT8(irp->output, 0); free(path); return irp->Complete(irp); }","static UINT parallel_process_irp_create(PARALLEL_DEVICE* parallel, IRP* irp) { char* path = NULL; int status; WCHAR* ptr; UINT32 PathLength; if (!Stream_SafeSeek(irp->input, 28)) return ERROR_INVALID_DATA; /* DesiredAccess(4) AllocationSize(8), FileAttributes(4) */ /* SharedAccess(4) CreateDisposition(4), CreateOptions(4) */ if (Stream_GetRemainingLength(irp->input) < 4) return ERROR_INVALID_DATA; Stream_Read_UINT32(irp->input, PathLength); ptr = (WCHAR*)Stream_Pointer(irp->input); if (!Stream_SafeSeek(irp->input, PathLength)) return ERROR_INVALID_DATA; status = ConvertFromUnicode(CP_UTF8, 0, ptr, PathLength / 2, &path, 0, NULL, NULL); if (status < 1) if (!(path = (char*)calloc(1, 1))) { WLog_ERR(TAG, ""calloc failed!""); return CHANNEL_RC_NO_MEMORY; } parallel->id = irp->devman->id_sequence++; parallel->file = open(parallel->path, O_RDWR); if (parallel->file < 0) { irp->IoStatus = STATUS_ACCESS_DENIED; parallel->id = 0; } else { /* all read and write operations should be non-blocking */ if (fcntl(parallel->file, F_SETFL, O_NONBLOCK) == -1) { } } Stream_Write_UINT32(irp->output, parallel->id); Stream_Write_UINT8(irp->output, 0); free(path); return irp->Complete(irp); }","{'deleted': [{'line_no': 6, 'char_start': 132, 'char_end': 162, 'line': '\tStream_Seek(irp->input, 28);\n'}, {'line_no': 10, 'char_start': 330, 'char_end': 423, 'line': '\tstatus = ConvertFromUnicode(CP_UTF8, 0, (WCHAR*)Stream_Pointer(irp->input), PathLength / 2,\n'}, {'line_no': 11, 'char_start': 423, 'char_end': 475, 'line': '\t &path, 0, NULL, NULL);\n'}], 'added': [{'line_no': 5, 'char_start': 112, 'char_end': 125, 'line': '\tWCHAR* ptr;\n'}, {'line_no': 7, 'char_start': 145, 'char_end': 184, 'line': '\tif (!Stream_SafeSeek(irp->input, 28))\n'}, {'line_no': 8, 'char_start': 184, 'char_end': 213, 'line': '\t\treturn ERROR_INVALID_DATA;\n'}, {'line_no': 11, 'char_start': 336, 'char_end': 384, 'line': '\tif (Stream_GetRemainingLength(irp->input) < 4)\n'}, {'line_no': 12, 'char_start': 384, 'char_end': 413, 'line': '\t\treturn ERROR_INVALID_DATA;\n'}, {'line_no': 14, 'char_start': 458, 'char_end': 501, 'line': '\tptr = (WCHAR*)Stream_Pointer(irp->input);\n'}, {'line_no': 15, 'char_start': 501, 'char_end': 548, 'line': '\tif (!Stream_SafeSeek(irp->input, PathLength))\n'}, {'line_no': 16, 'char_start': 548, 'char_end': 577, 'line': '\t\treturn ERROR_INVALID_DATA;\n'}, {'line_no': 17, 'char_start': 577, 'char_end': 662, 'line': '\tstatus = ConvertFromUnicode(CP_UTF8, 0, ptr, PathLength / 2, &path, 0, NULL, NULL);\n'}]}","{'deleted': [{'char_start': 331, 'char_end': 332, 'chars': 's'}, {'char_start': 333, 'char_end': 345, 'chars': 'atus = Conve'}, {'char_start': 346, 'char_end': 367, 'chars': 'tFromUnicode(CP_UTF8,'}, {'char_start': 368, 'char_end': 370, 'chars': '0,'}, {'char_start': 417, 'char_end': 422, 'chars': ' / 2,'}, {'char_start': 424, 'char_end': 443, 'chars': ' '}], 'added': [{'char_start': 113, 'char_end': 126, 'chars': 'WCHAR* ptr;\n\t'}, {'char_start': 146, 'char_end': 151, 'chars': 'if (!'}, {'char_start': 158, 'char_end': 162, 'chars': 'Safe'}, {'char_start': 182, 'char_end': 211, 'chars': ')\n\t\treturn ERROR_INVALID_DATA'}, {'char_start': 337, 'char_end': 414, 'chars': 'if (Stream_GetRemainingLength(irp->input) < 4)\n\t\treturn ERROR_INVALID_DATA;\n\t'}, {'char_start': 459, 'char_end': 460, 'chars': 'p'}, {'char_start': 461, 'char_end': 462, 'chars': 'r'}, {'char_start': 499, 'char_end': 533, 'chars': ';\n\tif (!Stream_SafeSeek(irp->input'}, {'char_start': 545, 'char_end': 556, 'chars': '))\n\t\treturn'}, {'char_start': 557, 'char_end': 576, 'chars': 'ERROR_INVALID_DATA;'}, {'char_start': 578, 'char_end': 584, 'chars': 'status'}, {'char_start': 585, 'char_end': 586, 'chars': '='}, {'char_start': 587, 'char_end': 614, 'chars': 'ConvertFromUnicode(CP_UTF8,'}, {'char_start': 615, 'char_end': 617, 'chars': '0,'}, {'char_start': 618, 'char_end': 622, 'chars': 'ptr,'}, {'char_start': 623, 'char_end': 633, 'chars': 'PathLength'}, {'char_start': 634, 'char_end': 635, 'chars': '/'}, {'char_start': 636, 'char_end': 638, 'chars': '2,'}]}",github.com/FreeRDP/FreeRDP/commit/795842f4096501fcefc1a7f535ccc8132feb31d7,channels/parallel/client/parallel_main.c,cwe-125,334 cwe-476,filter_session_io,"filter_session_io(struct io *io, int evt, void *arg) { struct filter_session *fs = arg; char *line = NULL; ssize_t len; log_trace(TRACE_IO, ""filter session: %p: %s %s"", fs, io_strevent(evt), io_strio(io)); switch (evt) { case IO_DATAIN: nextline: line = io_getline(fs->io, &len); /* No complete line received */ if (line == NULL) return; filter_data(fs->id, line); goto nextline; case IO_DISCONNECTED: io_free(fs->io); fs->io = NULL; break; } }","filter_session_io(struct io *io, int evt, void *arg) { struct filter_session *fs = arg; char *line = NULL; ssize_t len; log_trace(TRACE_IO, ""filter session: %p: %s %s"", fs, io_strevent(evt), io_strio(io)); switch (evt) { case IO_DATAIN: nextline: line = io_getline(fs->io, &len); /* No complete line received */ if (line == NULL) return; filter_data(fs->id, line); goto nextline; } }","{'deleted': [{'line_no': 21, 'char_start': 409, 'char_end': 410, 'line': '\n'}, {'line_no': 22, 'char_start': 410, 'char_end': 433, 'line': '\tcase IO_DISCONNECTED:\n'}, {'line_no': 23, 'char_start': 433, 'char_end': 452, 'line': '\t\tio_free(fs->io);\n'}, {'line_no': 24, 'char_start': 452, 'char_end': 469, 'line': '\t\tfs->io = NULL;\n'}, {'line_no': 25, 'char_start': 469, 'char_end': 478, 'line': '\t\tbreak;\n'}], 'added': []}","{'deleted': [{'char_start': 409, 'char_end': 478, 'chars': '\n\tcase IO_DISCONNECTED:\n\t\tio_free(fs->io);\n\t\tfs->io = NULL;\n\t\tbreak;\n'}], 'added': []}",github.com/openbsd/src/commit/6c3220444ed06b5796dedfd53a0f4becd903c0d1,usr.sbin/smtpd/lka_filter.c,cwe-476,150 cwe-125,mpeg4_decode_studio_block,"static int mpeg4_decode_studio_block(MpegEncContext *s, int32_t block[64], int n) { Mpeg4DecContext *ctx = s->avctx->priv_data; int cc, dct_dc_size, dct_diff, code, j, idx = 1, group = 0, run = 0, additional_code_len, sign, mismatch; VLC *cur_vlc = &ctx->studio_intra_tab[0]; uint8_t *const scantable = s->intra_scantable.permutated; const uint16_t *quant_matrix; uint32_t flc; const int min = -1 * (1 << (s->avctx->bits_per_raw_sample + 6)); const int max = ((1 << (s->avctx->bits_per_raw_sample + 6)) - 1); mismatch = 1; memset(block, 0, 64 * sizeof(int32_t)); if (n < 4) { cc = 0; dct_dc_size = get_vlc2(&s->gb, ctx->studio_luma_dc.table, STUDIO_INTRA_BITS, 2); quant_matrix = s->intra_matrix; } else { cc = (n & 1) + 1; if (ctx->rgb) dct_dc_size = get_vlc2(&s->gb, ctx->studio_luma_dc.table, STUDIO_INTRA_BITS, 2); else dct_dc_size = get_vlc2(&s->gb, ctx->studio_chroma_dc.table, STUDIO_INTRA_BITS, 2); quant_matrix = s->chroma_intra_matrix; } if (dct_dc_size < 0) { av_log(s->avctx, AV_LOG_ERROR, ""illegal dct_dc_size vlc\n""); return AVERROR_INVALIDDATA; } else if (dct_dc_size == 0) { dct_diff = 0; } else { dct_diff = get_xbits(&s->gb, dct_dc_size); if (dct_dc_size > 8) { if(!check_marker(s->avctx, &s->gb, ""dct_dc_size > 8"")) return AVERROR_INVALIDDATA; } } s->last_dc[cc] += dct_diff; if (s->mpeg_quant) block[0] = s->last_dc[cc] * (8 >> s->intra_dc_precision); else block[0] = s->last_dc[cc] * (8 >> s->intra_dc_precision) * (8 >> s->dct_precision); /* TODO: support mpeg_quant for AC coefficients */ block[0] = av_clip(block[0], min, max); mismatch ^= block[0]; /* AC Coefficients */ while (1) { group = get_vlc2(&s->gb, cur_vlc->table, STUDIO_INTRA_BITS, 2); if (group < 0) { av_log(s->avctx, AV_LOG_ERROR, ""illegal ac coefficient group vlc\n""); return AVERROR_INVALIDDATA; } additional_code_len = ac_state_tab[group][0]; cur_vlc = &ctx->studio_intra_tab[ac_state_tab[group][1]]; if (group == 0) { /* End of Block */ break; } else if (group >= 1 && group <= 6) { /* Zero run length (Table B.47) */ run = 1 << additional_code_len; if (additional_code_len) run += get_bits(&s->gb, additional_code_len); idx += run; continue; } else if (group >= 7 && group <= 12) { /* Zero run length and +/-1 level (Table B.48) */ code = get_bits(&s->gb, additional_code_len); sign = code & 1; code >>= 1; run = (1 << (additional_code_len - 1)) + code; idx += run; j = scantable[idx++]; block[j] = sign ? 1 : -1; } else if (group >= 13 && group <= 20) { /* Level value (Table B.49) */ j = scantable[idx++]; block[j] = get_xbits(&s->gb, additional_code_len); } else if (group == 21) { /* Escape */ j = scantable[idx++]; additional_code_len = s->avctx->bits_per_raw_sample + s->dct_precision + 4; flc = get_bits(&s->gb, additional_code_len); if (flc >> (additional_code_len-1)) block[j] = -1 * (( flc ^ ((1 << additional_code_len) -1)) + 1); else block[j] = flc; } block[j] = ((8 * 2 * block[j] * quant_matrix[j] * s->qscale) >> s->dct_precision) / 32; block[j] = av_clip(block[j], min, max); mismatch ^= block[j]; } block[63] ^= mismatch & 1; return 0; }","static int mpeg4_decode_studio_block(MpegEncContext *s, int32_t block[64], int n) { Mpeg4DecContext *ctx = s->avctx->priv_data; int cc, dct_dc_size, dct_diff, code, j, idx = 1, group = 0, run = 0, additional_code_len, sign, mismatch; VLC *cur_vlc = &ctx->studio_intra_tab[0]; uint8_t *const scantable = s->intra_scantable.permutated; const uint16_t *quant_matrix; uint32_t flc; const int min = -1 * (1 << (s->avctx->bits_per_raw_sample + 6)); const int max = ((1 << (s->avctx->bits_per_raw_sample + 6)) - 1); mismatch = 1; memset(block, 0, 64 * sizeof(int32_t)); if (n < 4) { cc = 0; dct_dc_size = get_vlc2(&s->gb, ctx->studio_luma_dc.table, STUDIO_INTRA_BITS, 2); quant_matrix = s->intra_matrix; } else { cc = (n & 1) + 1; if (ctx->rgb) dct_dc_size = get_vlc2(&s->gb, ctx->studio_luma_dc.table, STUDIO_INTRA_BITS, 2); else dct_dc_size = get_vlc2(&s->gb, ctx->studio_chroma_dc.table, STUDIO_INTRA_BITS, 2); quant_matrix = s->chroma_intra_matrix; } if (dct_dc_size < 0) { av_log(s->avctx, AV_LOG_ERROR, ""illegal dct_dc_size vlc\n""); return AVERROR_INVALIDDATA; } else if (dct_dc_size == 0) { dct_diff = 0; } else { dct_diff = get_xbits(&s->gb, dct_dc_size); if (dct_dc_size > 8) { if(!check_marker(s->avctx, &s->gb, ""dct_dc_size > 8"")) return AVERROR_INVALIDDATA; } } s->last_dc[cc] += dct_diff; if (s->mpeg_quant) block[0] = s->last_dc[cc] * (8 >> s->intra_dc_precision); else block[0] = s->last_dc[cc] * (8 >> s->intra_dc_precision) * (8 >> s->dct_precision); /* TODO: support mpeg_quant for AC coefficients */ block[0] = av_clip(block[0], min, max); mismatch ^= block[0]; /* AC Coefficients */ while (1) { group = get_vlc2(&s->gb, cur_vlc->table, STUDIO_INTRA_BITS, 2); if (group < 0) { av_log(s->avctx, AV_LOG_ERROR, ""illegal ac coefficient group vlc\n""); return AVERROR_INVALIDDATA; } additional_code_len = ac_state_tab[group][0]; cur_vlc = &ctx->studio_intra_tab[ac_state_tab[group][1]]; if (group == 0) { /* End of Block */ break; } else if (group >= 1 && group <= 6) { /* Zero run length (Table B.47) */ run = 1 << additional_code_len; if (additional_code_len) run += get_bits(&s->gb, additional_code_len); idx += run; continue; } else if (group >= 7 && group <= 12) { /* Zero run length and +/-1 level (Table B.48) */ code = get_bits(&s->gb, additional_code_len); sign = code & 1; code >>= 1; run = (1 << (additional_code_len - 1)) + code; idx += run; if (idx > 63) return AVERROR_INVALIDDATA; j = scantable[idx++]; block[j] = sign ? 1 : -1; } else if (group >= 13 && group <= 20) { /* Level value (Table B.49) */ if (idx > 63) return AVERROR_INVALIDDATA; j = scantable[idx++]; block[j] = get_xbits(&s->gb, additional_code_len); } else if (group == 21) { /* Escape */ if (idx > 63) return AVERROR_INVALIDDATA; j = scantable[idx++]; additional_code_len = s->avctx->bits_per_raw_sample + s->dct_precision + 4; flc = get_bits(&s->gb, additional_code_len); if (flc >> (additional_code_len-1)) block[j] = -1 * (( flc ^ ((1 << additional_code_len) -1)) + 1); else block[j] = flc; } block[j] = ((8 * 2 * block[j] * quant_matrix[j] * s->qscale) >> s->dct_precision) / 32; block[j] = av_clip(block[j], min, max); mismatch ^= block[j]; } block[63] ^= mismatch & 1; return 0; }","{'deleted': [], 'added': [{'line_no': 86, 'char_start': 2920, 'char_end': 2946, 'line': ' if (idx > 63)\n'}, {'line_no': 87, 'char_start': 2946, 'char_end': 2990, 'line': ' return AVERROR_INVALIDDATA;\n'}, {'line_no': 92, 'char_start': 3154, 'char_end': 3180, 'line': ' if (idx > 63)\n'}, {'line_no': 93, 'char_start': 3180, 'char_end': 3224, 'line': ' return AVERROR_INVALIDDATA;\n'}, {'line_no': 98, 'char_start': 3380, 'char_end': 3406, 'line': ' if (idx > 63)\n'}, {'line_no': 99, 'char_start': 3406, 'char_end': 3450, 'line': ' return AVERROR_INVALIDDATA;\n'}]}","{'deleted': [{'char_start': 2954, 'char_end': 2954, 'chars': ''}, {'char_start': 3215, 'char_end': 3215, 'chars': ''}], 'added': [{'char_start': 2932, 'char_end': 3002, 'chars': 'if (idx > 63)\n return AVERROR_INVALIDDATA;\n '}, {'char_start': 3154, 'char_end': 3224, 'chars': ' if (idx > 63)\n return AVERROR_INVALIDDATA;\n'}, {'char_start': 3379, 'char_end': 3449, 'chars': '\n if (idx > 63)\n return AVERROR_INVALIDDATA;'}]}",github.com/FFmpeg/FFmpeg/commit/d227ed5d598340e719eff7156b1aa0a4469e9a6a,libavcodec/mpeg4videodec.c,cwe-125,1165 cwe-125,Cipher::blowfishECB,"QByteArray Cipher::blowfishECB(QByteArray cipherText, bool direction) { QCA::Initializer init; QByteArray temp = cipherText; //do padding ourselves if (direction) { while ((temp.length() % 8) != 0) temp.append('\0'); } else { temp = b64ToByte(temp); while ((temp.length() % 8) != 0) temp.append('\0'); } QCA::Direction dir = (direction) ? QCA::Encode : QCA::Decode; QCA::Cipher cipher(m_type, QCA::Cipher::ECB, QCA::Cipher::NoPadding, dir, m_key); QByteArray temp2 = cipher.update(QCA::MemoryRegion(temp)).toByteArray(); temp2 += cipher.final().toByteArray(); if (!cipher.ok()) return cipherText; if (direction) temp2 = byteToB64(temp2); return temp2; }","QByteArray Cipher::blowfishECB(QByteArray cipherText, bool direction) { QCA::Initializer init; QByteArray temp = cipherText; //do padding ourselves if (direction) { while ((temp.length() % 8) != 0) temp.append('\0'); } else { // ECB Blowfish encodes in blocks of 12 chars, so anything else is malformed input if ((temp.length() % 12) != 0) return cipherText; temp = b64ToByte(temp); while ((temp.length() % 8) != 0) temp.append('\0'); } QCA::Direction dir = (direction) ? QCA::Encode : QCA::Decode; QCA::Cipher cipher(m_type, QCA::Cipher::ECB, QCA::Cipher::NoPadding, dir, m_key); QByteArray temp2 = cipher.update(QCA::MemoryRegion(temp)).toByteArray(); temp2 += cipher.final().toByteArray(); if (!cipher.ok()) return cipherText; if (direction) { // Sanity check if ((temp2.length() % 8) != 0) return cipherText; temp2 = byteToB64(temp2); } return temp2; }","{'deleted': [{'line_no': 25, 'char_start': 689, 'char_end': 708, 'line': ' if (direction)\n'}], 'added': [{'line_no': 14, 'char_start': 358, 'char_end': 397, 'line': ' if ((temp.length() % 12) != 0)\n'}, {'line_no': 15, 'char_start': 397, 'char_end': 428, 'line': ' return cipherText;\n'}, {'line_no': 16, 'char_start': 428, 'char_end': 429, 'line': '\n'}, {'line_no': 29, 'char_start': 851, 'char_end': 872, 'line': ' if (direction) {\n'}, {'line_no': 31, 'char_start': 896, 'char_end': 935, 'line': ' if ((temp2.length() % 8) != 0)\n'}, {'line_no': 32, 'char_start': 935, 'char_end': 966, 'line': ' return cipherText;\n'}, {'line_no': 33, 'char_start': 966, 'char_end': 967, 'line': '\n'}, {'line_no': 35, 'char_start': 1001, 'char_end': 1007, 'line': ' }\n'}]}","{'deleted': [], 'added': [{'char_start': 275, 'char_end': 437, 'chars': '// ECB Blowfish encodes in blocks of 12 chars, so anything else is malformed input\n if ((temp.length() % 12) != 0)\n return cipherText;\n\n '}, {'char_start': 869, 'char_end': 966, 'chars': ' {\n // Sanity check\n if ((temp2.length() % 8) != 0)\n return cipherText;\n'}, {'char_start': 1000, 'char_end': 1006, 'chars': '\n }'}]}",github.com/quassel/quassel/commit/8b5ecd226f9208af3074b33d3b7cf5e14f55b138,src/core/cipher.cpp,cwe-125,214 cwe-476,formUpdateBuffer,"formUpdateBuffer(Anchor *a, Buffer *buf, FormItemList *form) { Buffer save; char *p; int spos, epos, rows, c_rows, pos, col = 0; Line *l; copyBuffer(&save, buf); gotoLine(buf, a->start.line); switch (form->type) { case FORM_TEXTAREA: case FORM_INPUT_TEXT: case FORM_INPUT_FILE: case FORM_INPUT_PASSWORD: case FORM_INPUT_CHECKBOX: case FORM_INPUT_RADIO: #ifdef MENU_SELECT case FORM_SELECT: #endif /* MENU_SELECT */ spos = a->start.pos; epos = a->end.pos; break; default: spos = a->start.pos + 1; epos = a->end.pos - 1; } switch (form->type) { case FORM_INPUT_CHECKBOX: case FORM_INPUT_RADIO: if (buf->currentLine == NULL || spos >= buf->currentLine->len || spos < 0) break; if (form->checked) buf->currentLine->lineBuf[spos] = '*'; else buf->currentLine->lineBuf[spos] = ' '; break; case FORM_INPUT_TEXT: case FORM_INPUT_FILE: case FORM_INPUT_PASSWORD: case FORM_TEXTAREA: #ifdef MENU_SELECT case FORM_SELECT: if (form->type == FORM_SELECT) { p = form->label->ptr; updateSelectOption(form, form->select_option); } else #endif /* MENU_SELECT */ { if (!form->value) break; p = form->value->ptr; } l = buf->currentLine; if (!l) break; if (form->type == FORM_TEXTAREA) { int n = a->y - buf->currentLine->linenumber; if (n > 0) for (; l && n; l = l->prev, n--) ; else if (n < 0) for (; l && n; l = l->prev, n++) ; if (!l) break; } rows = form->rows ? form->rows : 1; col = COLPOS(l, a->start.pos); for (c_rows = 0; c_rows < rows; c_rows++, l = l->next) { if (rows > 1) { pos = columnPos(l, col); a = retrieveAnchor(buf->formitem, l->linenumber, pos); if (a == NULL) break; spos = a->start.pos; epos = a->end.pos; } if (a->start.line != a->end.line || spos > epos || epos >= l->len || spos < 0 || epos < 0 || COLPOS(l, epos) < col) break; pos = form_update_line(l, &p, spos, epos, COLPOS(l, epos) - col, rows > 1, form->type == FORM_INPUT_PASSWORD); if (pos != epos) { shiftAnchorPosition(buf->href, buf->hmarklist, a->start.line, spos, pos - epos); shiftAnchorPosition(buf->name, buf->hmarklist, a->start.line, spos, pos - epos); shiftAnchorPosition(buf->img, buf->hmarklist, a->start.line, spos, pos - epos); shiftAnchorPosition(buf->formitem, buf->hmarklist, a->start.line, spos, pos - epos); } } break; } copyBuffer(buf, &save); arrangeLine(buf); }","formUpdateBuffer(Anchor *a, Buffer *buf, FormItemList *form) { Buffer save; char *p; int spos, epos, rows, c_rows, pos, col = 0; Line *l; copyBuffer(&save, buf); gotoLine(buf, a->start.line); switch (form->type) { case FORM_TEXTAREA: case FORM_INPUT_TEXT: case FORM_INPUT_FILE: case FORM_INPUT_PASSWORD: case FORM_INPUT_CHECKBOX: case FORM_INPUT_RADIO: #ifdef MENU_SELECT case FORM_SELECT: #endif /* MENU_SELECT */ spos = a->start.pos; epos = a->end.pos; break; default: spos = a->start.pos + 1; epos = a->end.pos - 1; } switch (form->type) { case FORM_INPUT_CHECKBOX: case FORM_INPUT_RADIO: if (buf->currentLine == NULL || spos >= buf->currentLine->len || spos < 0) break; if (form->checked) buf->currentLine->lineBuf[spos] = '*'; else buf->currentLine->lineBuf[spos] = ' '; break; case FORM_INPUT_TEXT: case FORM_INPUT_FILE: case FORM_INPUT_PASSWORD: case FORM_TEXTAREA: #ifdef MENU_SELECT case FORM_SELECT: if (form->type == FORM_SELECT) { p = form->label->ptr; updateSelectOption(form, form->select_option); } else #endif /* MENU_SELECT */ { if (!form->value) break; p = form->value->ptr; } l = buf->currentLine; if (!l) break; if (form->type == FORM_TEXTAREA) { int n = a->y - buf->currentLine->linenumber; if (n > 0) for (; l && n; l = l->prev, n--) ; else if (n < 0) for (; l && n; l = l->prev, n++) ; if (!l) break; } rows = form->rows ? form->rows : 1; col = COLPOS(l, a->start.pos); for (c_rows = 0; c_rows < rows; c_rows++, l = l->next) { if (l == NULL) break; if (rows > 1) { pos = columnPos(l, col); a = retrieveAnchor(buf->formitem, l->linenumber, pos); if (a == NULL) break; spos = a->start.pos; epos = a->end.pos; } if (a->start.line != a->end.line || spos > epos || epos >= l->len || spos < 0 || epos < 0 || COLPOS(l, epos) < col) break; pos = form_update_line(l, &p, spos, epos, COLPOS(l, epos) - col, rows > 1, form->type == FORM_INPUT_PASSWORD); if (pos != epos) { shiftAnchorPosition(buf->href, buf->hmarklist, a->start.line, spos, pos - epos); shiftAnchorPosition(buf->name, buf->hmarklist, a->start.line, spos, pos - epos); shiftAnchorPosition(buf->img, buf->hmarklist, a->start.line, spos, pos - epos); shiftAnchorPosition(buf->formitem, buf->hmarklist, a->start.line, spos, pos - epos); } } break; } copyBuffer(buf, &save); arrangeLine(buf); }","{'deleted': [], 'added': [{'line_no': 70, 'char_start': 1647, 'char_end': 1667, 'line': '\t if (l == NULL)\n'}, {'line_no': 71, 'char_start': 1667, 'char_end': 1676, 'line': '\t\tbreak;\n'}]}","{'deleted': [], 'added': [{'char_start': 1656, 'char_end': 1685, 'chars': 'l == NULL)\n\t\tbreak;\n\t if ('}]}",github.com/tats/w3m/commit/7fdc83b0364005a0b5ed869230dd81752ba022e8,form.c,cwe-476,808 cwe-089,get_markets,"@app.route('/get_markets') def get_markets(): asset_id = request.args.get('asset_id') if not isObject(asset_id): ws.send('{""id"":1, ""method"":""call"", ""params"":[0,""lookup_asset_symbols"",[[""' + asset_id + '""], 0]]}') result_l = ws.recv() j_l = json.loads(result_l) asset_id = j_l[""result""][0][""id""] con = psycopg2.connect(**config.POSTGRES) cur = con.cursor() query = ""SELECT * FROM markets WHERE aid='""+asset_id+""'"" cur.execute(query) results = cur.fetchall() con.close() return jsonify(results)","@app.route('/get_markets') def get_markets(): asset_id = request.args.get('asset_id') if not isObject(asset_id): ws.send('{""id"":1, ""method"":""call"", ""params"":[0,""lookup_asset_symbols"",[[""' + asset_id + '""], 0]]}') result_l = ws.recv() j_l = json.loads(result_l) asset_id = j_l[""result""][0][""id""] con = psycopg2.connect(**config.POSTGRES) cur = con.cursor() query = ""SELECT * FROM markets WHERE aid=%s"" cur.execute(query, (asset_id,)) results = cur.fetchall() con.close() return jsonify(results)","{'deleted': [{'line_no': 15, 'char_start': 408, 'char_end': 469, 'line': ' query = ""SELECT * FROM markets WHERE aid=\'""+asset_id+""\'""\n'}, {'line_no': 16, 'char_start': 469, 'char_end': 492, 'line': ' cur.execute(query)\n'}], 'added': [{'line_no': 15, 'char_start': 408, 'char_end': 457, 'line': ' query = ""SELECT * FROM markets WHERE aid=%s""\n'}, {'line_no': 16, 'char_start': 457, 'char_end': 493, 'line': ' cur.execute(query, (asset_id,))\n'}]}","{'deleted': [{'char_start': 453, 'char_end': 457, 'chars': '\'""+a'}, {'char_start': 458, 'char_end': 467, 'chars': 'set_id+""\''}], 'added': [{'char_start': 453, 'char_end': 454, 'chars': '%'}, {'char_start': 478, 'char_end': 491, 'chars': ', (asset_id,)'}]}",github.com/VinChain/vinchain-python-api-backend/commit/b78088a551fbb712121269c6eb7f43ede120ff60,api.py,cwe-089,148 cwe-089,markTokenUsedExternal,"def markTokenUsedExternal(token, optStr=""""): conn, c = connectDB() req = ""UPDATE {} SET \""options_selected\""='{}' WHERE token='{}'"".format(CFG(""tokens_table_name""), \ optStr, token) c.execute(req) closeDB(conn)","def markTokenUsedExternal(token, optStr=""""): conn, c = connectDB() req = ""UPDATE {} SET \""options_selected\""=? WHERE token=?"".format(CFG(""tokens_table_name"")) c.execute(req, (optStr, token,)) closeDB(conn)","{'deleted': [{'line_no': 3, 'char_start': 71, 'char_end': 175, 'line': ' req = ""UPDATE {} SET \\""options_selected\\""=\'{}\' WHERE token=\'{}\'"".format(CFG(""tokens_table_name""), \\\n'}, {'line_no': 4, 'char_start': 175, 'char_end': 210, 'line': ' optStr, token)\n'}, {'line_no': 5, 'char_start': 210, 'char_end': 229, 'line': ' c.execute(req)\n'}], 'added': [{'line_no': 3, 'char_start': 71, 'char_end': 167, 'line': ' req = ""UPDATE {} SET \\""options_selected\\""=? WHERE token=?"".format(CFG(""tokens_table_name""))\n'}, {'line_no': 4, 'char_start': 167, 'char_end': 204, 'line': ' c.execute(req, (optStr, token,))\n'}]}","{'deleted': [{'char_start': 117, 'char_end': 121, 'chars': ""'{}'""}, {'char_start': 134, 'char_end': 138, 'chars': ""'{}'""}, {'char_start': 171, 'char_end': 174, 'chars': ', \\'}, {'char_start': 175, 'char_end': 177, 'chars': ' '}, {'char_start': 181, 'char_end': 182, 'chars': ' '}, {'char_start': 183, 'char_end': 195, 'chars': ' '}, {'char_start': 209, 'char_end': 227, 'chars': '\n c.execute(req'}], 'added': [{'char_start': 117, 'char_end': 118, 'chars': '?'}, {'char_start': 131, 'char_end': 132, 'chars': '?'}, {'char_start': 165, 'char_end': 166, 'chars': ')'}, {'char_start': 171, 'char_end': 185, 'chars': 'c.execute(req,'}, {'char_start': 186, 'char_end': 187, 'chars': '('}, {'char_start': 200, 'char_end': 201, 'chars': ','}]}",github.com/FAUSheppy/simple-python-poll/commit/186c5ff5cdf58272e253a1bb432419ee50d93109,database.py,cwe-089,64 cwe-125,DecodePSDPixels,"static ssize_t DecodePSDPixels(const size_t number_compact_pixels, const unsigned char *compact_pixels,const ssize_t depth, const size_t number_pixels,unsigned char *pixels) { #define CheckNumberCompactPixels \ if (packets == 0) \ return(i); \ packets-- #define CheckNumberPixels(count) \ if (((ssize_t) i + count) > (ssize_t) number_pixels) \ return(i); \ i+=count int pixel; register ssize_t i, j; size_t length; ssize_t packets; packets=(ssize_t) number_compact_pixels; for (i=0; (packets > 1) && (i < (ssize_t) number_pixels); ) { packets--; length=(size_t) (*compact_pixels++); if (length == 128) continue; if (length > 128) { length=256-length+1; CheckNumberCompactPixels; pixel=(*compact_pixels++); for (j=0; j < (ssize_t) length; j++) { switch (depth) { case 1: { CheckNumberPixels(8); *pixels++=(pixel >> 7) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 6) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 5) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 4) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 3) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 2) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 1) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 0) & 0x01 ? 0U : 255U; break; } case 2: { CheckNumberPixels(4); *pixels++=(unsigned char) ((pixel >> 6) & 0x03); *pixels++=(unsigned char) ((pixel >> 4) & 0x03); *pixels++=(unsigned char) ((pixel >> 2) & 0x03); *pixels++=(unsigned char) ((pixel & 0x03) & 0x03); break; } case 4: { CheckNumberPixels(2); *pixels++=(unsigned char) ((pixel >> 4) & 0xff); *pixels++=(unsigned char) ((pixel & 0x0f) & 0xff); break; } default: { CheckNumberPixels(1); *pixels++=(unsigned char) pixel; break; } } } continue; } length++; for (j=0; j < (ssize_t) length; j++) { switch (depth) { case 1: { CheckNumberPixels(8); *pixels++=(*compact_pixels >> 7) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 6) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 5) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 4) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 3) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 2) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 1) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 0) & 0x01 ? 0U : 255U; break; } case 2: { CheckNumberPixels(4); *pixels++=(*compact_pixels >> 6) & 0x03; *pixels++=(*compact_pixels >> 4) & 0x03; *pixels++=(*compact_pixels >> 2) & 0x03; *pixels++=(*compact_pixels & 0x03) & 0x03; break; } case 4: { CheckNumberPixels(2); *pixels++=(*compact_pixels >> 4) & 0xff; *pixels++=(*compact_pixels & 0x0f) & 0xff; break; } default: { CheckNumberPixels(1); *pixels++=(*compact_pixels); break; } } CheckNumberCompactPixels; compact_pixels++; } } return(i); }","static ssize_t DecodePSDPixels(const size_t number_compact_pixels, const unsigned char *compact_pixels,const ssize_t depth, const size_t number_pixels,unsigned char *pixels) { #define CheckNumberCompactPixels \ if (packets == 0) \ return(i); \ packets-- #define CheckNumberPixels(count) \ if (((ssize_t) i + count) > (ssize_t) number_pixels) \ return(i); \ i+=count int pixel; register ssize_t i, j; size_t length; ssize_t packets; packets=(ssize_t) number_compact_pixels; for (i=0; (packets > 1) && (i < (ssize_t) number_pixels); ) { packets--; length=(size_t) (*compact_pixels++); if (length == 128) continue; if (length > 128) { length=256-length+1; CheckNumberCompactPixels; pixel=(*compact_pixels++); for (j=0; j < (ssize_t) length; j++) { switch (depth) { case 1: { CheckNumberPixels(8); *pixels++=(pixel >> 7) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 6) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 5) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 4) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 3) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 2) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 1) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 0) & 0x01 ? 0U : 255U; break; } case 2: { CheckNumberPixels(4); *pixels++=(unsigned char) ((pixel >> 6) & 0x03); *pixels++=(unsigned char) ((pixel >> 4) & 0x03); *pixels++=(unsigned char) ((pixel >> 2) & 0x03); *pixels++=(unsigned char) ((pixel & 0x03) & 0x03); break; } case 4: { CheckNumberPixels(2); *pixels++=(unsigned char) ((pixel >> 4) & 0xff); *pixels++=(unsigned char) ((pixel & 0x0f) & 0xff); break; } default: { CheckNumberPixels(1); *pixels++=(unsigned char) pixel; break; } } } continue; } length++; for (j=0; j < (ssize_t) length; j++) { CheckNumberCompactPixels; switch (depth) { case 1: { CheckNumberPixels(8); *pixels++=(*compact_pixels >> 7) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 6) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 5) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 4) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 3) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 2) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 1) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 0) & 0x01 ? 0U : 255U; break; } case 2: { CheckNumberPixels(4); *pixels++=(*compact_pixels >> 6) & 0x03; *pixels++=(*compact_pixels >> 4) & 0x03; *pixels++=(*compact_pixels >> 2) & 0x03; *pixels++=(*compact_pixels & 0x03) & 0x03; break; } case 4: { CheckNumberPixels(2); *pixels++=(*compact_pixels >> 4) & 0xff; *pixels++=(*compact_pixels & 0x0f) & 0xff; break; } default: { CheckNumberPixels(1); *pixels++=(*compact_pixels); break; } } compact_pixels++; } } return(i); }","{'deleted': [{'line_no': 124, 'char_start': 3556, 'char_end': 3588, 'line': ' CheckNumberCompactPixels;\n'}], 'added': [{'line_no': 86, 'char_start': 2325, 'char_end': 2357, 'line': ' CheckNumberCompactPixels;\n'}]}","{'deleted': [{'char_start': 3555, 'char_end': 3587, 'chars': '\n CheckNumberCompactPixels;'}], 'added': [{'char_start': 2331, 'char_end': 2363, 'chars': 'CheckNumberCompactPixels;\n '}]}",github.com/ImageMagick/ImageMagick/commit/30eec879c8b446b0ea9a3bb0da1a441cc8482bc4,coders/psd.c,cwe-125,1174 cwe-079,mode_close," def mode_close(self, request): """""" This is called by render_POST when the client is signalling that it is about to be closed. Args: request (Request): Incoming request. """""" csessid = request.args.get('csessid')[0] try: sess = self.sessionhandler.sessions_from_csessid(csessid)[0] sess.sessionhandler.disconnect(sess) except IndexError: self.client_disconnect(csessid) return '""""'"," def mode_close(self, request): """""" This is called by render_POST when the client is signalling that it is about to be closed. Args: request (Request): Incoming request. """""" csessid = cgi.escape(request.args['csessid'][0]) try: sess = self.sessionhandler.sessions_from_csessid(csessid)[0] sess.sessionhandler.disconnect(sess) except IndexError: self.client_disconnect(csessid) return '""""'","{'deleted': [{'line_no': 10, 'char_start': 231, 'char_end': 280, 'line': "" csessid = request.args.get('csessid')[0]\n""}], 'added': [{'line_no': 10, 'char_start': 231, 'char_end': 288, 'line': "" csessid = cgi.escape(request.args['csessid'][0])\n""}]}","{'deleted': [{'char_start': 261, 'char_end': 266, 'chars': '.get('}, {'char_start': 275, 'char_end': 276, 'chars': ')'}], 'added': [{'char_start': 249, 'char_end': 260, 'chars': 'cgi.escape('}, {'char_start': 272, 'char_end': 273, 'chars': '['}, {'char_start': 282, 'char_end': 283, 'chars': ']'}, {'char_start': 286, 'char_end': 287, 'chars': ')'}]}",github.com/evennia/evennia/commit/300261529b82f95414c9d1d7150d6eda4695bb93,evennia/server/portal/webclient_ajax.py,cwe-079,104 cwe-089,delete_event," def delete_event(self, event_id): sql = """"""DELETE FROM events WHERE event_id = {0} """""".format(event_id) affected_count = self.cur.execute(sql) self.conn.commit() return affected_count"," def delete_event(self, event_id): sql = """""" DELETE FROM events WHERE event_id = %s """""" affected_count = self.cur.execute(sql, (event_id,)) self.conn.commit() return affected_count","{'deleted': [{'line_no': 2, 'char_start': 38, 'char_end': 74, 'line': ' sql = """"""DELETE FROM events\n'}, {'line_no': 3, 'char_start': 74, 'char_end': 112, 'line': ' WHERE event_id = {0}\n'}, {'line_no': 4, 'char_start': 112, 'char_end': 150, 'line': ' """""".format(event_id)\n'}, {'line_no': 5, 'char_start': 150, 'char_end': 197, 'line': ' affected_count = self.cur.execute(sql)\n'}], 'added': [{'line_no': 2, 'char_start': 38, 'char_end': 56, 'line': ' sql = """"""\n'}, {'line_no': 3, 'char_start': 56, 'char_end': 89, 'line': ' DELETE FROM events\n'}, {'line_no': 4, 'char_start': 89, 'char_end': 123, 'line': ' WHERE event_id = %s\n'}, {'line_no': 5, 'char_start': 123, 'char_end': 141, 'line': ' """"""\n'}, {'line_no': 6, 'char_start': 141, 'char_end': 201, 'line': ' affected_count = self.cur.execute(sql, (event_id,))\n'}]}","{'deleted': [{'char_start': 88, 'char_end': 91, 'chars': ' '}, {'char_start': 108, 'char_end': 111, 'chars': '{0}'}, {'char_start': 112, 'char_end': 115, 'chars': ' '}, {'char_start': 132, 'char_end': 149, 'chars': '.format(event_id)'}], 'added': [{'char_start': 55, 'char_end': 70, 'chars': '\n '}, {'char_start': 120, 'char_end': 122, 'chars': '%s'}, {'char_start': 186, 'char_end': 199, 'chars': ', (event_id,)'}]}",github.com/jgayfer/spirit/commit/01c846c534c8d3cf6763f8b7444a0efe2caa3799,db/dbase.py,cwe-089,49 cwe-125,ReadSGIImage,"static Image *ReadSGIImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *image; MagickBooleanType status; MagickSizeType number_pixels; MemoryInfo *pixel_info; register Quantum *q; register ssize_t i, x; register unsigned char *p; SGIInfo iris_info; size_t bytes_per_pixel, quantum; ssize_t count, y, z; unsigned char *pixels; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),""%s"", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read SGI raster header. */ iris_info.magic=ReadBlobMSBShort(image); do { /* Verify SGI identifier. */ if (iris_info.magic != 0x01DA) ThrowReaderException(CorruptImageError,""ImproperImageHeader""); iris_info.storage=(unsigned char) ReadBlobByte(image); switch (iris_info.storage) { case 0x00: image->compression=NoCompression; break; case 0x01: image->compression=RLECompression; break; default: ThrowReaderException(CorruptImageError,""ImproperImageHeader""); } iris_info.bytes_per_pixel=(unsigned char) ReadBlobByte(image); if ((iris_info.bytes_per_pixel == 0) || (iris_info.bytes_per_pixel > 2)) ThrowReaderException(CorruptImageError,""ImproperImageHeader""); iris_info.dimension=ReadBlobMSBShort(image); iris_info.columns=ReadBlobMSBShort(image); iris_info.rows=ReadBlobMSBShort(image); iris_info.depth=ReadBlobMSBShort(image); if ((iris_info.depth == 0) || (iris_info.depth > 4)) ThrowReaderException(CorruptImageError,""ImproperImageHeader""); iris_info.minimum_value=ReadBlobMSBLong(image); iris_info.maximum_value=ReadBlobMSBLong(image); iris_info.sans=ReadBlobMSBLong(image); (void) ReadBlob(image,sizeof(iris_info.name),(unsigned char *) iris_info.name); iris_info.name[sizeof(iris_info.name)-1]='\0'; if (*iris_info.name != '\0') (void) SetImageProperty(image,""label"",iris_info.name,exception); iris_info.pixel_format=ReadBlobMSBLong(image); if (iris_info.pixel_format != 0) ThrowReaderException(CorruptImageError,""ImproperImageHeader""); count=ReadBlob(image,sizeof(iris_info.filler),iris_info.filler); (void) count; image->columns=iris_info.columns; image->rows=iris_info.rows; image->depth=(size_t) MagickMin(iris_info.depth,MAGICKCORE_QUANTUM_DEPTH); if (iris_info.pixel_format == 0) image->depth=(size_t) MagickMin((size_t) 8* iris_info.bytes_per_pixel,MAGICKCORE_QUANTUM_DEPTH); if (iris_info.depth < 3) { image->storage_class=PseudoClass; image->colors=iris_info.bytes_per_pixel > 1 ? 65535 : 256; } if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); /* Allocate SGI pixels. */ bytes_per_pixel=(size_t) iris_info.bytes_per_pixel; number_pixels=(MagickSizeType) iris_info.columns*iris_info.rows; if ((4*bytes_per_pixel*number_pixels) != ((MagickSizeType) (size_t) (4*bytes_per_pixel*number_pixels))) ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); pixel_info=AcquireVirtualMemory(iris_info.columns,iris_info.rows*4* bytes_per_pixel*sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); if ((int) iris_info.storage != 0x01) { unsigned char *scanline; /* Read standard image format. */ scanline=(unsigned char *) AcquireQuantumMemory(iris_info.columns, bytes_per_pixel*sizeof(*scanline)); if (scanline == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); for (z=0; z < (ssize_t) iris_info.depth; z++) { p=pixels+bytes_per_pixel*z; for (y=0; y < (ssize_t) iris_info.rows; y++) { count=ReadBlob(image,bytes_per_pixel*iris_info.columns,scanline); if (EOFBlob(image) != MagickFalse) break; if (bytes_per_pixel == 2) for (x=0; x < (ssize_t) iris_info.columns; x++) { *p=scanline[2*x]; *(p+1)=scanline[2*x+1]; p+=8; } else for (x=0; x < (ssize_t) iris_info.columns; x++) { *p=scanline[x]; p+=4; } } } scanline=(unsigned char *) RelinquishMagickMemory(scanline); } else { MemoryInfo *packet_info; size_t *runlength; ssize_t offset, *offsets; unsigned char *packets; unsigned int data_order; /* Read runlength-encoded image format. */ offsets=(ssize_t *) AcquireQuantumMemory((size_t) iris_info.rows, iris_info.depth*sizeof(*offsets)); runlength=(size_t *) AcquireQuantumMemory(iris_info.rows, iris_info.depth*sizeof(*runlength)); packet_info=AcquireVirtualMemory((size_t) iris_info.columns+10UL,4UL* sizeof(*packets)); if ((offsets == (ssize_t *) NULL) || (runlength == (size_t *) NULL) || (packet_info == (MemoryInfo *) NULL)) { if (offsets == (ssize_t *) NULL) offsets=(ssize_t *) RelinquishMagickMemory(offsets); if (runlength == (size_t *) NULL) runlength=(size_t *) RelinquishMagickMemory(runlength); if (packet_info == (MemoryInfo *) NULL) packet_info=RelinquishVirtualMemory(packet_info); ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); } packets=(unsigned char *) GetVirtualMemoryBlob(packet_info); for (i=0; i < (ssize_t) (iris_info.rows*iris_info.depth); i++) offsets[i]=ReadBlobMSBSignedLong(image); for (i=0; i < (ssize_t) (iris_info.rows*iris_info.depth); i++) { runlength[i]=ReadBlobMSBLong(image); if (runlength[i] > (4*(size_t) iris_info.columns+10)) ThrowReaderException(CorruptImageError,""ImproperImageHeader""); } /* Check data order. */ offset=0; data_order=0; for (y=0; ((y < (ssize_t) iris_info.rows) && (data_order == 0)); y++) for (z=0; ((z < (ssize_t) iris_info.depth) && (data_order == 0)); z++) { if (offsets[y+z*iris_info.rows] < offset) data_order=1; offset=offsets[y+z*iris_info.rows]; } offset=(ssize_t) TellBlob(image); if (data_order == 1) { for (z=0; z < (ssize_t) iris_info.depth; z++) { p=pixels; for (y=0; y < (ssize_t) iris_info.rows; y++) { if (offset != offsets[y+z*iris_info.rows]) { offset=offsets[y+z*iris_info.rows]; offset=(ssize_t) SeekBlob(image,(ssize_t) offset,SEEK_SET); } count=ReadBlob(image,(size_t) runlength[y+z*iris_info.rows], packets); if (EOFBlob(image) != MagickFalse) break; offset+=(ssize_t) runlength[y+z*iris_info.rows]; status=SGIDecode(bytes_per_pixel,(ssize_t) (runlength[y+z*iris_info.rows]/bytes_per_pixel),packets, 1L*iris_info.columns,p+bytes_per_pixel*z); if (status == MagickFalse) ThrowReaderException(CorruptImageError,""ImproperImageHeader""); p+=(iris_info.columns*4*bytes_per_pixel); } } } else { MagickOffsetType position; position=TellBlob(image); p=pixels; for (y=0; y < (ssize_t) iris_info.rows; y++) { for (z=0; z < (ssize_t) iris_info.depth; z++) { if (offset != offsets[y+z*iris_info.rows]) { offset=offsets[y+z*iris_info.rows]; offset=(ssize_t) SeekBlob(image,(ssize_t) offset,SEEK_SET); } count=ReadBlob(image,(size_t) runlength[y+z*iris_info.rows], packets); if (EOFBlob(image) != MagickFalse) break; offset+=(ssize_t) runlength[y+z*iris_info.rows]; status=SGIDecode(bytes_per_pixel,(ssize_t) (runlength[y+z*iris_info.rows]/bytes_per_pixel),packets, 1L*iris_info.columns,p+bytes_per_pixel*z); if (status == MagickFalse) ThrowReaderException(CorruptImageError,""ImproperImageHeader""); } p+=(iris_info.columns*4*bytes_per_pixel); } offset=(ssize_t) SeekBlob(image,position,SEEK_SET); } packet_info=RelinquishVirtualMemory(packet_info); runlength=(size_t *) RelinquishMagickMemory(runlength); offsets=(ssize_t *) RelinquishMagickMemory(offsets); } /* Initialize image structure. */ image->alpha_trait=iris_info.depth == 4 ? BlendPixelTrait : UndefinedPixelTrait; image->columns=iris_info.columns; image->rows=iris_info.rows; /* Convert SGI raster image to pixel packets. */ if (image->storage_class == DirectClass) { /* Convert SGI image to DirectClass pixel packets. */ if (bytes_per_pixel == 2) { for (y=0; y < (ssize_t) image->rows; y++) { p=pixels+(image->rows-y-1)*8*image->columns; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(image,ScaleShortToQuantum((unsigned short) ((*(p+0) << 8) | (*(p+1)))),q); SetPixelGreen(image,ScaleShortToQuantum((unsigned short) ((*(p+2) << 8) | (*(p+3)))),q); SetPixelBlue(image,ScaleShortToQuantum((unsigned short) ((*(p+4) << 8) | (*(p+5)))),q); SetPixelAlpha(image,OpaqueAlpha,q); if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(image,ScaleShortToQuantum((unsigned short) ((*(p+6) << 8) | (*(p+7)))),q); p+=8; q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } } else for (y=0; y < (ssize_t) image->rows; y++) { p=pixels+(image->rows-y-1)*4*image->columns; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(image,ScaleCharToQuantum(*p),q); SetPixelGreen(image,ScaleCharToQuantum(*(p+1)),q); SetPixelBlue(image,ScaleCharToQuantum(*(p+2)),q); SetPixelAlpha(image,OpaqueAlpha,q); if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(image,ScaleCharToQuantum(*(p+3)),q); p+=4; q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } } else { /* Create grayscale map. */ if (AcquireImageColormap(image,image->colors,exception) == MagickFalse) ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); /* Convert SGI image to PseudoClass pixel packets. */ if (bytes_per_pixel == 2) { for (y=0; y < (ssize_t) image->rows; y++) { p=pixels+(image->rows-y-1)*8*image->columns; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { quantum=(*p << 8); quantum|=(*(p+1)); SetPixelIndex(image,(Quantum) quantum,q); p+=8; q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } } else for (y=0; y < (ssize_t) image->rows; y++) { p=pixels+(image->rows-y-1)*4*image->columns; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelIndex(image,*p,q); p+=4; q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } (void) SyncImage(image,exception); } pixel_info=RelinquishVirtualMemory(pixel_info); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,""UnexpectedEndOfFile"", image->filename); break; } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; iris_info.magic=ReadBlobMSBShort(image); if (iris_info.magic == 0x01DA) { /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } while (iris_info.magic == 0x01DA); (void) CloseBlob(image); return(GetFirstImageInList(image)); }","static Image *ReadSGIImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *image; MagickBooleanType status; MagickSizeType number_pixels; MemoryInfo *pixel_info; register Quantum *q; register ssize_t i, x; register unsigned char *p; SGIInfo iris_info; size_t bytes_per_pixel, quantum; ssize_t count, y, z; unsigned char *pixels; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),""%s"", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read SGI raster header. */ iris_info.magic=ReadBlobMSBShort(image); do { /* Verify SGI identifier. */ if (iris_info.magic != 0x01DA) ThrowReaderException(CorruptImageError,""ImproperImageHeader""); iris_info.storage=(unsigned char) ReadBlobByte(image); switch (iris_info.storage) { case 0x00: image->compression=NoCompression; break; case 0x01: image->compression=RLECompression; break; default: ThrowReaderException(CorruptImageError,""ImproperImageHeader""); } iris_info.bytes_per_pixel=(unsigned char) ReadBlobByte(image); if ((iris_info.bytes_per_pixel == 0) || (iris_info.bytes_per_pixel > 2)) ThrowReaderException(CorruptImageError,""ImproperImageHeader""); iris_info.dimension=ReadBlobMSBShort(image); iris_info.columns=ReadBlobMSBShort(image); iris_info.rows=ReadBlobMSBShort(image); iris_info.depth=ReadBlobMSBShort(image); if ((iris_info.depth == 0) || (iris_info.depth > 4)) ThrowReaderException(CorruptImageError,""ImproperImageHeader""); iris_info.minimum_value=ReadBlobMSBLong(image); iris_info.maximum_value=ReadBlobMSBLong(image); iris_info.sans=ReadBlobMSBLong(image); (void) ReadBlob(image,sizeof(iris_info.name),(unsigned char *) iris_info.name); iris_info.name[sizeof(iris_info.name)-1]='\0'; if (*iris_info.name != '\0') (void) SetImageProperty(image,""label"",iris_info.name,exception); iris_info.pixel_format=ReadBlobMSBLong(image); if (iris_info.pixel_format != 0) ThrowReaderException(CorruptImageError,""ImproperImageHeader""); count=ReadBlob(image,sizeof(iris_info.filler),iris_info.filler); (void) count; image->columns=iris_info.columns; image->rows=iris_info.rows; image->depth=(size_t) MagickMin(iris_info.depth,MAGICKCORE_QUANTUM_DEPTH); if (iris_info.pixel_format == 0) image->depth=(size_t) MagickMin((size_t) 8*iris_info.bytes_per_pixel, MAGICKCORE_QUANTUM_DEPTH); if (iris_info.depth < 3) { image->storage_class=PseudoClass; image->colors=iris_info.bytes_per_pixel > 1 ? 65535 : 256; } if (EOFBlob(image) != MagickFalse) ThrowReaderException(CorruptImageError,""ImproperImageHeader""); if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); /* Allocate SGI pixels. */ bytes_per_pixel=(size_t) iris_info.bytes_per_pixel; number_pixels=(MagickSizeType) iris_info.columns*iris_info.rows; if ((4*bytes_per_pixel*number_pixels) != ((MagickSizeType) (size_t) (4*bytes_per_pixel*number_pixels))) ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); pixel_info=AcquireVirtualMemory(iris_info.columns,iris_info.rows*4* bytes_per_pixel*sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); if ((int) iris_info.storage != 0x01) { unsigned char *scanline; /* Read standard image format. */ scanline=(unsigned char *) AcquireQuantumMemory(iris_info.columns, bytes_per_pixel*sizeof(*scanline)); if (scanline == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); for (z=0; z < (ssize_t) iris_info.depth; z++) { p=pixels+bytes_per_pixel*z; for (y=0; y < (ssize_t) iris_info.rows; y++) { count=ReadBlob(image,bytes_per_pixel*iris_info.columns,scanline); if (EOFBlob(image) != MagickFalse) break; if (bytes_per_pixel == 2) for (x=0; x < (ssize_t) iris_info.columns; x++) { *p=scanline[2*x]; *(p+1)=scanline[2*x+1]; p+=8; } else for (x=0; x < (ssize_t) iris_info.columns; x++) { *p=scanline[x]; p+=4; } } } scanline=(unsigned char *) RelinquishMagickMemory(scanline); } else { MemoryInfo *packet_info; size_t *runlength; ssize_t offset, *offsets; unsigned char *packets; unsigned int data_order; /* Read runlength-encoded image format. */ offsets=(ssize_t *) AcquireQuantumMemory((size_t) iris_info.rows, iris_info.depth*sizeof(*offsets)); runlength=(size_t *) AcquireQuantumMemory(iris_info.rows, iris_info.depth*sizeof(*runlength)); packet_info=AcquireVirtualMemory((size_t) iris_info.columns+10UL,4UL* sizeof(*packets)); if ((offsets == (ssize_t *) NULL) || (runlength == (size_t *) NULL) || (packet_info == (MemoryInfo *) NULL)) { if (offsets == (ssize_t *) NULL) offsets=(ssize_t *) RelinquishMagickMemory(offsets); if (runlength == (size_t *) NULL) runlength=(size_t *) RelinquishMagickMemory(runlength); if (packet_info == (MemoryInfo *) NULL) packet_info=RelinquishVirtualMemory(packet_info); ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); } packets=(unsigned char *) GetVirtualMemoryBlob(packet_info); for (i=0; i < (ssize_t) (iris_info.rows*iris_info.depth); i++) offsets[i]=ReadBlobMSBSignedLong(image); for (i=0; i < (ssize_t) (iris_info.rows*iris_info.depth); i++) { runlength[i]=ReadBlobMSBLong(image); if (runlength[i] > (4*(size_t) iris_info.columns+10)) ThrowReaderException(CorruptImageError,""ImproperImageHeader""); } /* Check data order. */ offset=0; data_order=0; for (y=0; ((y < (ssize_t) iris_info.rows) && (data_order == 0)); y++) for (z=0; ((z < (ssize_t) iris_info.depth) && (data_order == 0)); z++) { if (offsets[y+z*iris_info.rows] < offset) data_order=1; offset=offsets[y+z*iris_info.rows]; } offset=(ssize_t) TellBlob(image); if (data_order == 1) { for (z=0; z < (ssize_t) iris_info.depth; z++) { p=pixels; for (y=0; y < (ssize_t) iris_info.rows; y++) { if (offset != offsets[y+z*iris_info.rows]) { offset=offsets[y+z*iris_info.rows]; offset=(ssize_t) SeekBlob(image,(ssize_t) offset,SEEK_SET); } count=ReadBlob(image,(size_t) runlength[y+z*iris_info.rows], packets); if (EOFBlob(image) != MagickFalse) break; offset+=(ssize_t) runlength[y+z*iris_info.rows]; status=SGIDecode(bytes_per_pixel,(ssize_t) (runlength[y+z*iris_info.rows]/bytes_per_pixel),packets, 1L*iris_info.columns,p+bytes_per_pixel*z); if (status == MagickFalse) ThrowReaderException(CorruptImageError,""ImproperImageHeader""); p+=(iris_info.columns*4*bytes_per_pixel); } } } else { MagickOffsetType position; position=TellBlob(image); p=pixels; for (y=0; y < (ssize_t) iris_info.rows; y++) { for (z=0; z < (ssize_t) iris_info.depth; z++) { if (offset != offsets[y+z*iris_info.rows]) { offset=offsets[y+z*iris_info.rows]; offset=(ssize_t) SeekBlob(image,(ssize_t) offset,SEEK_SET); } count=ReadBlob(image,(size_t) runlength[y+z*iris_info.rows], packets); if (EOFBlob(image) != MagickFalse) break; offset+=(ssize_t) runlength[y+z*iris_info.rows]; status=SGIDecode(bytes_per_pixel,(ssize_t) (runlength[y+z*iris_info.rows]/bytes_per_pixel),packets, 1L*iris_info.columns,p+bytes_per_pixel*z); if (status == MagickFalse) ThrowReaderException(CorruptImageError,""ImproperImageHeader""); } p+=(iris_info.columns*4*bytes_per_pixel); } offset=(ssize_t) SeekBlob(image,position,SEEK_SET); } packet_info=RelinquishVirtualMemory(packet_info); runlength=(size_t *) RelinquishMagickMemory(runlength); offsets=(ssize_t *) RelinquishMagickMemory(offsets); } /* Initialize image structure. */ image->alpha_trait=iris_info.depth == 4 ? BlendPixelTrait : UndefinedPixelTrait; image->columns=iris_info.columns; image->rows=iris_info.rows; /* Convert SGI raster image to pixel packets. */ if (image->storage_class == DirectClass) { /* Convert SGI image to DirectClass pixel packets. */ if (bytes_per_pixel == 2) { for (y=0; y < (ssize_t) image->rows; y++) { p=pixels+(image->rows-y-1)*8*image->columns; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(image,ScaleShortToQuantum((unsigned short) ((*(p+0) << 8) | (*(p+1)))),q); SetPixelGreen(image,ScaleShortToQuantum((unsigned short) ((*(p+2) << 8) | (*(p+3)))),q); SetPixelBlue(image,ScaleShortToQuantum((unsigned short) ((*(p+4) << 8) | (*(p+5)))),q); SetPixelAlpha(image,OpaqueAlpha,q); if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(image,ScaleShortToQuantum((unsigned short) ((*(p+6) << 8) | (*(p+7)))),q); p+=8; q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } } else for (y=0; y < (ssize_t) image->rows; y++) { p=pixels+(image->rows-y-1)*4*image->columns; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(image,ScaleCharToQuantum(*p),q); SetPixelGreen(image,ScaleCharToQuantum(*(p+1)),q); SetPixelBlue(image,ScaleCharToQuantum(*(p+2)),q); SetPixelAlpha(image,OpaqueAlpha,q); if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(image,ScaleCharToQuantum(*(p+3)),q); p+=4; q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } } else { /* Create grayscale map. */ if (AcquireImageColormap(image,image->colors,exception) == MagickFalse) ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); /* Convert SGI image to PseudoClass pixel packets. */ if (bytes_per_pixel == 2) { for (y=0; y < (ssize_t) image->rows; y++) { p=pixels+(image->rows-y-1)*8*image->columns; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { quantum=(*p << 8); quantum|=(*(p+1)); SetPixelIndex(image,(Quantum) quantum,q); p+=8; q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } } else for (y=0; y < (ssize_t) image->rows; y++) { p=pixels+(image->rows-y-1)*4*image->columns; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelIndex(image,*p,q); p+=4; q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } (void) SyncImage(image,exception); } pixel_info=RelinquishVirtualMemory(pixel_info); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,""UnexpectedEndOfFile"", image->filename); break; } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; iris_info.magic=ReadBlobMSBShort(image); if (iris_info.magic == 0x01DA) { /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } while (iris_info.magic == 0x01DA); (void) CloseBlob(image); return(GetFirstImageInList(image)); }","{'deleted': [{'line_no': 102, 'char_start': 2912, 'char_end': 2962, 'line': ' image->depth=(size_t) MagickMin((size_t) 8*\n'}, {'line_no': 103, 'char_start': 2962, 'char_end': 3023, 'line': ' iris_info.bytes_per_pixel,MAGICKCORE_QUANTUM_DEPTH);\n'}], 'added': [{'line_no': 102, 'char_start': 2912, 'char_end': 2988, 'line': ' image->depth=(size_t) MagickMin((size_t) 8*iris_info.bytes_per_pixel,\n'}, {'line_no': 103, 'char_start': 2988, 'char_end': 3023, 'line': ' MAGICKCORE_QUANTUM_DEPTH);\n'}, {'line_no': 109, 'char_start': 3177, 'char_end': 3216, 'line': ' if (EOFBlob(image) != MagickFalse)\n'}, {'line_no': 110, 'char_start': 3216, 'char_end': 3285, 'line': ' ThrowReaderException(CorruptImageError,""ImproperImageHeader"");\n'}]}","{'deleted': [{'char_start': 2961, 'char_end': 2970, 'chars': '\n '}], 'added': [{'char_start': 2987, 'char_end': 2996, 'chars': '\n '}, {'char_start': 3176, 'char_end': 3284, 'chars': '\n if (EOFBlob(image) != MagickFalse)\n ThrowReaderException(CorruptImageError,""ImproperImageHeader"");'}]}",github.com/ImageMagick/ImageMagick/commit/7afcf9f71043df15508e46f079387bd4689a738d,coders/sgi.c,cwe-125,3922 cwe-078,_delete_3par_host," def _delete_3par_host(self, hostname): self._cli_run('removehost %s' % hostname, None)"," def _delete_3par_host(self, hostname): self._cli_run(['removehost', hostname])","{'deleted': [{'line_no': 2, 'char_start': 43, 'char_end': 98, 'line': "" self._cli_run('removehost %s' % hostname, None)\n""}], 'added': [{'line_no': 2, 'char_start': 43, 'char_end': 90, 'line': "" self._cli_run(['removehost', hostname])\n""}]}","{'deleted': [{'char_start': 76, 'char_end': 79, 'chars': ' %s'}, {'char_start': 80, 'char_end': 82, 'chars': ' %'}, {'char_start': 91, 'char_end': 97, 'chars': ', None'}], 'added': [{'char_start': 65, 'char_end': 66, 'chars': '['}, {'char_start': 78, 'char_end': 79, 'chars': ','}, {'char_start': 88, 'char_end': 89, 'chars': ']'}]}",github.com/thatsdone/cinder/commit/c55589b131828f3a595903f6796cb2d0babb772f,cinder/volume/drivers/san/hp/hp_3par_common.py,cwe-078,28 cwe-089,getFileCacheID," def getFileCacheID(self, pth): """""" Returns ID of a cached file on Telegram from DB. None if file doesn't exist or has no cached ID. :param pth: :return: """""" command = ""SELECT file_id FROM {0} WHERE path='{1}'"".format(TABLE_NAME, pth) data = self._run_command(command) try: data = data[0][0] except IndexError: data = None return data"," def getFileCacheID(self, pth): """""" Returns ID of a cached file on Telegram from DB. None if file doesn't exist or has no cached ID. :param pth: :return: """""" command = ""SELECT file_id FROM {0} WHERE path=?;"".format(TABLE_NAME) params = (pth,) data = self._run_command(command, params) try: data = data[0][0] except IndexError: data = None return data","{'deleted': [{'line_no': 7, 'char_start': 168, 'char_end': 247, 'line': '\t\tcommand = ""SELECT file_id FROM {0} WHERE path=\'{1}\'"".format(TABLE_NAME, pth)\n'}, {'line_no': 8, 'char_start': 247, 'char_end': 283, 'line': '\t\tdata = self._run_command(command)\n'}], 'added': [{'line_no': 7, 'char_start': 168, 'char_end': 239, 'line': '\t\tcommand = ""SELECT file_id FROM {0} WHERE path=?;"".format(TABLE_NAME)\n'}, {'line_no': 8, 'char_start': 239, 'char_end': 257, 'line': '\t\tparams = (pth,)\n'}, {'line_no': 9, 'char_start': 257, 'char_end': 301, 'line': '\t\tdata = self._run_command(command, params)\n'}]}","{'deleted': [{'char_start': 216, 'char_end': 221, 'chars': ""'{1}'""}, {'char_start': 240, 'char_end': 241, 'chars': ','}], 'added': [{'char_start': 216, 'char_end': 218, 'chars': '?;'}, {'char_start': 237, 'char_end': 247, 'chars': ')\n\t\tparams'}, {'char_start': 248, 'char_end': 251, 'chars': '= ('}, {'char_start': 254, 'char_end': 255, 'chars': ','}, {'char_start': 291, 'char_end': 299, 'chars': ', params'}]}",github.com/Highstaker/Picture-sender-telegram-bot/commit/db4bc6adb41e086418761426ff4958a81c30adca,file_db.py,cwe-089,106 cwe-787,keycompare_mb,"keycompare_mb (const struct line *a, const struct line *b) { struct keyfield *key = keylist; /* For the first iteration only, the key positions have been precomputed for us. */ char *texta = a->keybeg; char *textb = b->keybeg; char *lima = a->keylim; char *limb = b->keylim; size_t mblength_a, mblength_b; wchar_t wc_a, wc_b; mbstate_t state_a, state_b; int diff = 0; memset (&state_a, '\0', sizeof(mbstate_t)); memset (&state_b, '\0', sizeof(mbstate_t)); /* Ignore keys with start after end. */ if (a->keybeg - a->keylim > 0) return 0; /* Ignore and/or translate chars before comparing. */ # define IGNORE_CHARS(NEW_LEN, LEN, TEXT, COPY, WC, MBLENGTH, STATE) \ do \ { \ wchar_t uwc; \ char mbc[MB_LEN_MAX]; \ mbstate_t state_wc; \ \ for (NEW_LEN = i = 0; i < LEN;) \ { \ mbstate_t state_bak; \ \ state_bak = STATE; \ MBLENGTH = mbrtowc (&WC, TEXT + i, LEN - i, &STATE); \ \ if (MBLENGTH == (size_t)-2 || MBLENGTH == (size_t)-1 \ || MBLENGTH == 0) \ { \ if (MBLENGTH == (size_t)-2 || MBLENGTH == (size_t)-1) \ STATE = state_bak; \ if (!ignore) \ COPY[NEW_LEN++] = TEXT[i]; \ i++; \ continue; \ } \ \ if (ignore) \ { \ if ((ignore == nonprinting && !iswprint (WC)) \ || (ignore == nondictionary \ && !iswalnum (WC) && !iswblank (WC))) \ { \ i += MBLENGTH; \ continue; \ } \ } \ \ if (translate) \ { \ \ uwc = towupper(WC); \ if (WC == uwc) \ { \ memcpy (mbc, TEXT + i, MBLENGTH); \ i += MBLENGTH; \ } \ else \ { \ i += MBLENGTH; \ WC = uwc; \ memset (&state_wc, '\0', sizeof (mbstate_t)); \ \ MBLENGTH = wcrtomb (mbc, WC, &state_wc); \ assert (MBLENGTH != (size_t)-1 && MBLENGTH != 0); \ } \ \ for (j = 0; j < MBLENGTH; j++) \ COPY[NEW_LEN++] = mbc[j]; \ } \ else \ for (j = 0; j < MBLENGTH; j++) \ COPY[NEW_LEN++] = TEXT[i++]; \ } \ COPY[NEW_LEN] = '\0'; \ } \ while (0) /* Actually compare the fields. */ for (;;) { /* Find the lengths. */ size_t lena = lima <= texta ? 0 : lima - texta; size_t lenb = limb <= textb ? 0 : limb - textb; char enda IF_LINT (= 0); char endb IF_LINT (= 0); char const *translate = key->translate; bool const *ignore = key->ignore; if (ignore || translate) { char *copy_a = (char *) xmalloc (lena + 1 + lenb + 1); char *copy_b = copy_a + lena + 1; size_t new_len_a, new_len_b; size_t i, j; IGNORE_CHARS (new_len_a, lena, texta, copy_a, wc_a, mblength_a, state_a); IGNORE_CHARS (new_len_b, lenb, textb, copy_b, wc_b, mblength_b, state_b); texta = copy_a; textb = copy_b; lena = new_len_a; lenb = new_len_b; } else { /* Use the keys in-place, temporarily null-terminated. */ enda = texta[lena]; texta[lena] = '\0'; endb = textb[lenb]; textb[lenb] = '\0'; } if (key->random) diff = compare_random (texta, lena, textb, lenb); else if (key->numeric | key->general_numeric | key->human_numeric) { char savea = *lima, saveb = *limb; *lima = *limb = '\0'; diff = (key->numeric ? numcompare (texta, textb) : key->general_numeric ? general_numcompare (texta, textb) : human_numcompare (texta, textb)); *lima = savea, *limb = saveb; } else if (key->version) diff = filevercmp (texta, textb); else if (key->month) diff = getmonth (texta, lena, NULL) - getmonth (textb, lenb, NULL); else if (lena == 0) diff = - NONZERO (lenb); else if (lenb == 0) diff = 1; else if (hard_LC_COLLATE && !folding) { diff = xmemcoll0 (texta, lena + 1, textb, lenb + 1); } else { diff = memcmp (texta, textb, MIN (lena, lenb)); if (diff == 0) diff = lena < lenb ? -1 : lena != lenb; } if (ignore || translate) free (texta); else { texta[lena] = enda; textb[lenb] = endb; } if (diff) goto not_equal; key = key->next; if (! key) break; /* Find the beginning and limit of the next field. */ if (key->eword != -1) lima = limfield (a, key), limb = limfield (b, key); else lima = a->text + a->length - 1, limb = b->text + b->length - 1; if (key->sword != -1) texta = begfield (a, key), textb = begfield (b, key); else { texta = a->text, textb = b->text; if (key->skipsblanks) { while (texta < lima && ismbblank (texta, lima - texta, &mblength_a)) texta += mblength_a; while (textb < limb && ismbblank (textb, limb - textb, &mblength_b)) textb += mblength_b; } } } not_equal: if (key && key->reverse) return -diff; else return diff; }","keycompare_mb (const struct line *a, const struct line *b) { struct keyfield *key = keylist; /* For the first iteration only, the key positions have been precomputed for us. */ char *texta = a->keybeg; char *textb = b->keybeg; char *lima = a->keylim; char *limb = b->keylim; size_t mblength_a, mblength_b; wchar_t wc_a, wc_b; mbstate_t state_a, state_b; int diff = 0; memset (&state_a, '\0', sizeof(mbstate_t)); memset (&state_b, '\0', sizeof(mbstate_t)); /* Ignore keys with start after end. */ if (a->keybeg - a->keylim > 0) return 0; /* Ignore and/or translate chars before comparing. */ # define IGNORE_CHARS(NEW_LEN, LEN, TEXT, COPY, WC, MBLENGTH, STATE) \ do \ { \ wchar_t uwc; \ char mbc[MB_LEN_MAX]; \ mbstate_t state_wc; \ \ for (NEW_LEN = i = 0; i < LEN;) \ { \ mbstate_t state_bak; \ \ state_bak = STATE; \ MBLENGTH = mbrtowc (&WC, TEXT + i, LEN - i, &STATE); \ \ if (MBLENGTH == (size_t)-2 || MBLENGTH == (size_t)-1 \ || MBLENGTH == 0) \ { \ if (MBLENGTH == (size_t)-2 || MBLENGTH == (size_t)-1) \ STATE = state_bak; \ if (!ignore) \ COPY[NEW_LEN++] = TEXT[i]; \ i++; \ continue; \ } \ \ if (ignore) \ { \ if ((ignore == nonprinting && !iswprint (WC)) \ || (ignore == nondictionary \ && !iswalnum (WC) && !iswblank (WC))) \ { \ i += MBLENGTH; \ continue; \ } \ } \ \ if (translate) \ { \ \ uwc = towupper(WC); \ if (WC == uwc) \ { \ memcpy (mbc, TEXT + i, MBLENGTH); \ i += MBLENGTH; \ } \ else \ { \ i += MBLENGTH; \ WC = uwc; \ memset (&state_wc, '\0', sizeof (mbstate_t)); \ \ MBLENGTH = wcrtomb (mbc, WC, &state_wc); \ assert (MBLENGTH != (size_t)-1 && MBLENGTH != 0); \ } \ \ for (j = 0; j < MBLENGTH; j++) \ COPY[NEW_LEN++] = mbc[j]; \ } \ else \ for (j = 0; j < MBLENGTH; j++) \ COPY[NEW_LEN++] = TEXT[i++]; \ } \ COPY[NEW_LEN] = '\0'; \ } \ while (0) /* Actually compare the fields. */ for (;;) { /* Find the lengths. */ size_t lena = lima <= texta ? 0 : lima - texta; size_t lenb = limb <= textb ? 0 : limb - textb; char enda IF_LINT (= 0); char endb IF_LINT (= 0); char const *translate = key->translate; bool const *ignore = key->ignore; if (ignore || translate) { if (SIZE_MAX - lenb - 2 < lena) xalloc_die (); char *copy_a = (char *) xnmalloc (lena + lenb + 2, MB_CUR_MAX); char *copy_b = copy_a + lena * MB_CUR_MAX + 1; size_t new_len_a, new_len_b; size_t i, j; IGNORE_CHARS (new_len_a, lena, texta, copy_a, wc_a, mblength_a, state_a); IGNORE_CHARS (new_len_b, lenb, textb, copy_b, wc_b, mblength_b, state_b); texta = copy_a; textb = copy_b; lena = new_len_a; lenb = new_len_b; } else { /* Use the keys in-place, temporarily null-terminated. */ enda = texta[lena]; texta[lena] = '\0'; endb = textb[lenb]; textb[lenb] = '\0'; } if (key->random) diff = compare_random (texta, lena, textb, lenb); else if (key->numeric | key->general_numeric | key->human_numeric) { char savea = *lima, saveb = *limb; *lima = *limb = '\0'; diff = (key->numeric ? numcompare (texta, textb) : key->general_numeric ? general_numcompare (texta, textb) : human_numcompare (texta, textb)); *lima = savea, *limb = saveb; } else if (key->version) diff = filevercmp (texta, textb); else if (key->month) diff = getmonth (texta, lena, NULL) - getmonth (textb, lenb, NULL); else if (lena == 0) diff = - NONZERO (lenb); else if (lenb == 0) diff = 1; else if (hard_LC_COLLATE && !folding) { diff = xmemcoll0 (texta, lena + 1, textb, lenb + 1); } else { diff = memcmp (texta, textb, MIN (lena, lenb)); if (diff == 0) diff = lena < lenb ? -1 : lena != lenb; } if (ignore || translate) free (texta); else { texta[lena] = enda; textb[lenb] = endb; } if (diff) goto not_equal; key = key->next; if (! key) break; /* Find the beginning and limit of the next field. */ if (key->eword != -1) lima = limfield (a, key), limb = limfield (b, key); else lima = a->text + a->length - 1, limb = b->text + b->length - 1; if (key->sword != -1) texta = begfield (a, key), textb = begfield (b, key); else { texta = a->text, textb = b->text; if (key->skipsblanks) { while (texta < lima && ismbblank (texta, lima - texta, &mblength_a)) texta += mblength_a; while (textb < limb && ismbblank (textb, limb - textb, &mblength_b)) textb += mblength_b; } } } not_equal: if (key && key->reverse) return -diff; else return diff; }","{'deleted': [{'line_no': 108, 'char_start': 5967, 'char_end': 6032, 'line': ' char *copy_a = (char *) xmalloc (lena + 1 + lenb + 1);\n'}, {'line_no': 109, 'char_start': 6032, 'char_end': 6076, 'line': ' char *copy_b = copy_a + lena + 1;\n'}], 'added': [{'line_no': 108, 'char_start': 5967, 'char_end': 6009, 'line': ' if (SIZE_MAX - lenb - 2 < lena)\n'}, {'line_no': 109, 'char_start': 6009, 'char_end': 6036, 'line': ' xalloc_die ();\n'}, {'line_no': 110, 'char_start': 6036, 'char_end': 6110, 'line': ' char *copy_a = (char *) xnmalloc (lena + lenb + 2, MB_CUR_MAX);\n'}, {'line_no': 111, 'char_start': 6110, 'char_end': 6167, 'line': ' char *copy_b = copy_a + lena * MB_CUR_MAX + 1;\n'}]}","{'deleted': [{'char_start': 6017, 'char_end': 6021, 'chars': '1 + '}, {'char_start': 6028, 'char_end': 6029, 'chars': '1'}], 'added': [{'char_start': 5977, 'char_end': 6046, 'chars': 'if (SIZE_MAX - lenb - 2 < lena)\n xalloc_die ();\n '}, {'char_start': 6071, 'char_end': 6072, 'chars': 'n'}, {'char_start': 6094, 'char_end': 6107, 'chars': '2, MB_CUR_MAX'}, {'char_start': 6148, 'char_end': 6161, 'chars': ' * MB_CUR_MAX'}]}",github.com/pixelb/coreutils/commit/bea5e36cc876ed627bb5e0eca36fdfaa6465e940,src/sort.c,cwe-787,1707 cwe-079,edit_coordinator,"@check_document_access_permission() def edit_coordinator(request): coordinator_id = request.GET.get('coordinator') doc = None if coordinator_id: doc = Document2.objects.get(id=coordinator_id) coordinator = Coordinator(document=doc) else: coordinator = Coordinator() api = get_oozie(request.user) credentials = Credentials() try: credentials.fetch(api) except Exception, e: LOG.error(smart_str(e)) workflows = [dict([('uuid', d.content_object.uuid), ('name', d.content_object.name)]) for d in Document.objects.get_docs(request.user, Document2, extra='workflow2')] if coordinator_id and not filter(lambda a: a['uuid'] == coordinator.data['properties']['workflow'], workflows): raise PopupException(_('You don\'t have access to the workflow of this coordinator.')) return render('editor/coordinator_editor.mako', request, { 'coordinator_json': coordinator.json, 'credentials_json': json.dumps(credentials.credentials.keys()), 'workflows_json': json.dumps(workflows), 'doc1_id': doc.doc.get().id if doc else -1, 'can_edit_json': json.dumps(doc is None or doc.doc.get().is_editable(request.user)) })","@check_document_access_permission() def edit_coordinator(request): coordinator_id = request.GET.get('coordinator') doc = None if coordinator_id: doc = Document2.objects.get(id=coordinator_id) coordinator = Coordinator(document=doc) else: coordinator = Coordinator() api = get_oozie(request.user) credentials = Credentials() try: credentials.fetch(api) except Exception, e: LOG.error(smart_str(e)) workflows = [dict([('uuid', d.content_object.uuid), ('name', d.content_object.name)]) for d in Document.objects.get_docs(request.user, Document2, extra='workflow2')] if coordinator_id and not filter(lambda a: a['uuid'] == coordinator.data['properties']['workflow'], workflows): raise PopupException(_('You don\'t have access to the workflow of this coordinator.')) return render('editor/coordinator_editor.mako', request, { 'coordinator_json': coordinator.json_for_html(), 'credentials_json': json.dumps(credentials.credentials.keys(), cls=JSONEncoderForHTML), 'workflows_json': json.dumps(workflows, cls=JSONEncoderForHTML), 'doc1_id': doc.doc.get().id if doc else -1, 'can_edit_json': json.dumps(doc is None or doc.doc.get().is_editable(request.user)) })","{'deleted': [{'line_no': 27, 'char_start': 915, 'char_end': 959, 'line': "" 'coordinator_json': coordinator.json,\n""}, {'line_no': 28, 'char_start': 959, 'char_end': 1029, 'line': "" 'credentials_json': json.dumps(credentials.credentials.keys()),\n""}, {'line_no': 29, 'char_start': 1029, 'char_end': 1076, 'line': "" 'workflows_json': json.dumps(workflows),\n""}], 'added': [{'line_no': 27, 'char_start': 915, 'char_end': 970, 'line': "" 'coordinator_json': coordinator.json_for_html(),\n""}, {'line_no': 28, 'char_start': 970, 'char_end': 1064, 'line': "" 'credentials_json': json.dumps(credentials.credentials.keys(), cls=JSONEncoderForHTML),\n""}, {'line_no': 29, 'char_start': 1064, 'char_end': 1135, 'line': "" 'workflows_json': json.dumps(workflows, cls=JSONEncoderForHTML),\n""}]}","{'deleted': [], 'added': [{'char_start': 957, 'char_end': 968, 'chars': '_for_html()'}, {'char_start': 1037, 'char_end': 1061, 'chars': ', cls=JSONEncoderForHTML'}, {'char_start': 1108, 'char_end': 1132, 'chars': ', cls=JSONEncoderForHTML'}]}",github.com/gethue/hue/commit/6641c62beaa1468082e47d82da5ed758d11c7735,apps/oozie/src/oozie/views/editor2.py,cwe-079,271 cwe-089,retrieve_video,"def retrieve_video(id, playlist_id, db): db.execute(""SELECT id, position from video WHERE id={id} and playlist_id={playlist_id};"".format( id=id, playlist_id=playlist_id)) row = db.fetchone() return row","def retrieve_video(id, playlist_id, db): db.execute( ""SELECT id, position from video WHERE id=%s and playlist_id=%s;"", (id, playlist_id)) row = db.fetchone() return row","{'deleted': [{'line_no': 2, 'char_start': 41, 'char_end': 142, 'line': ' db.execute(""SELECT id, position from video WHERE id={id} and playlist_id={playlist_id};"".format(\n'}, {'line_no': 3, 'char_start': 142, 'char_end': 183, 'line': ' id=id, playlist_id=playlist_id))\n'}], 'added': [{'line_no': 2, 'char_start': 41, 'char_end': 57, 'line': ' db.execute(\n'}, {'line_no': 3, 'char_start': 57, 'char_end': 150, 'line': ' ""SELECT id, position from video WHERE id=%s and playlist_id=%s;"", (id, playlist_id))\n'}]}","{'deleted': [{'char_start': 97, 'char_end': 101, 'chars': '{id}'}, {'char_start': 118, 'char_end': 125, 'chars': '{playli'}, {'char_start': 126, 'char_end': 131, 'chars': 't_id}'}, {'char_start': 133, 'char_end': 140, 'chars': '.format'}, {'char_start': 141, 'char_end': 153, 'chars': '\n id='}, {'char_start': 157, 'char_end': 169, 'chars': 'playlist_id='}], 'added': [{'char_start': 56, 'char_end': 65, 'chars': '\n '}, {'char_start': 106, 'char_end': 108, 'chars': '%s'}, {'char_start': 125, 'char_end': 126, 'chars': '%'}, {'char_start': 129, 'char_end': 130, 'chars': ','}, {'char_start': 131, 'char_end': 132, 'chars': '('}]}",github.com/Madmous/playlist/commit/666e52c5f0b8c1f4296e84471637033d9542a7a6,video/video_repository.py,cwe-089,54 cwe-476,IRC_PROTOCOL_CALLBACK,"IRC_PROTOCOL_CALLBACK(352) { char *pos_attr, *pos_hopcount, *pos_realname, *str_host; int arg_start, length; struct t_irc_channel *ptr_channel; struct t_irc_nick *ptr_nick; IRC_PROTOCOL_MIN_ARGS(5); /* silently ignore malformed 352 message (missing infos) */ if (argc < 8) return WEECHAT_RC_OK; pos_attr = NULL; pos_hopcount = NULL; pos_realname = NULL; if (argc > 8) { arg_start = (strcmp (argv[8], ""*"") == 0) ? 9 : 8; if (argv[arg_start][0] == ':') { pos_attr = NULL; pos_hopcount = (argc > arg_start) ? argv[arg_start] + 1 : NULL; pos_realname = (argc > arg_start + 1) ? argv_eol[arg_start + 1] : NULL; } else { pos_attr = argv[arg_start]; pos_hopcount = (argc > arg_start + 1) ? argv[arg_start + 1] + 1 : NULL; pos_realname = (argc > arg_start + 2) ? argv_eol[arg_start + 2] : NULL; } } ptr_channel = irc_channel_search (server, argv[3]); ptr_nick = (ptr_channel) ? irc_nick_search (server, ptr_channel, argv[7]) : NULL; /* update host in nick */ if (ptr_nick) { length = strlen (argv[4]) + 1 + strlen (argv[5]) + 1; str_host = malloc (length); if (str_host) { snprintf (str_host, length, ""%s@%s"", argv[4], argv[5]); irc_nick_set_host (ptr_nick, str_host); free (str_host); } } /* update away flag in nick */ if (ptr_channel && ptr_nick && pos_attr) { irc_nick_set_away (server, ptr_channel, ptr_nick, (pos_attr[0] == 'G') ? 1 : 0); } /* update realname in nick */ if (ptr_channel && ptr_nick && pos_realname) { if (ptr_nick->realname) free (ptr_nick->realname); if (pos_realname && weechat_hashtable_has_key (server->cap_list, ""extended-join"")) { ptr_nick->realname = strdup (pos_realname); } else { ptr_nick->realname = NULL; } } /* display output of who (manual who from user) */ if (!ptr_channel || (ptr_channel->checking_whox <= 0)) { weechat_printf_date_tags ( irc_msgbuffer_get_target_buffer ( server, NULL, command, ""who"", NULL), date, irc_protocol_tags (command, ""irc_numeric"", NULL, NULL), ""%s%s[%s%s%s] %s%s %s(%s%s@%s%s)%s %s%s%s%s(%s)"", weechat_prefix (""network""), IRC_COLOR_CHAT_DELIMITERS, IRC_COLOR_CHAT_CHANNEL, argv[3], IRC_COLOR_CHAT_DELIMITERS, irc_nick_color_for_msg (server, 1, NULL, argv[7]), argv[7], IRC_COLOR_CHAT_DELIMITERS, IRC_COLOR_CHAT_HOST, argv[4], argv[5], IRC_COLOR_CHAT_DELIMITERS, IRC_COLOR_RESET, (pos_attr) ? pos_attr : """", (pos_attr) ? "" "" : """", (pos_hopcount) ? pos_hopcount : """", (pos_hopcount) ? "" "" : """", (pos_realname) ? pos_realname : """"); } return WEECHAT_RC_OK; }","IRC_PROTOCOL_CALLBACK(352) { char *pos_attr, *pos_hopcount, *pos_realname, *str_host; int arg_start, length; struct t_irc_channel *ptr_channel; struct t_irc_nick *ptr_nick; IRC_PROTOCOL_MIN_ARGS(5); /* silently ignore malformed 352 message (missing infos) */ if (argc < 8) return WEECHAT_RC_OK; pos_attr = NULL; pos_hopcount = NULL; pos_realname = NULL; if (argc > 8) { arg_start = ((argc > 9) && (strcmp (argv[8], ""*"") == 0)) ? 9 : 8; if (argv[arg_start][0] == ':') { pos_attr = NULL; pos_hopcount = (argc > arg_start) ? argv[arg_start] + 1 : NULL; pos_realname = (argc > arg_start + 1) ? argv_eol[arg_start + 1] : NULL; } else { pos_attr = argv[arg_start]; pos_hopcount = (argc > arg_start + 1) ? argv[arg_start + 1] + 1 : NULL; pos_realname = (argc > arg_start + 2) ? argv_eol[arg_start + 2] : NULL; } } ptr_channel = irc_channel_search (server, argv[3]); ptr_nick = (ptr_channel) ? irc_nick_search (server, ptr_channel, argv[7]) : NULL; /* update host in nick */ if (ptr_nick) { length = strlen (argv[4]) + 1 + strlen (argv[5]) + 1; str_host = malloc (length); if (str_host) { snprintf (str_host, length, ""%s@%s"", argv[4], argv[5]); irc_nick_set_host (ptr_nick, str_host); free (str_host); } } /* update away flag in nick */ if (ptr_channel && ptr_nick && pos_attr) { irc_nick_set_away (server, ptr_channel, ptr_nick, (pos_attr[0] == 'G') ? 1 : 0); } /* update realname in nick */ if (ptr_channel && ptr_nick && pos_realname) { if (ptr_nick->realname) free (ptr_nick->realname); if (pos_realname && weechat_hashtable_has_key (server->cap_list, ""extended-join"")) { ptr_nick->realname = strdup (pos_realname); } else { ptr_nick->realname = NULL; } } /* display output of who (manual who from user) */ if (!ptr_channel || (ptr_channel->checking_whox <= 0)) { weechat_printf_date_tags ( irc_msgbuffer_get_target_buffer ( server, NULL, command, ""who"", NULL), date, irc_protocol_tags (command, ""irc_numeric"", NULL, NULL), ""%s%s[%s%s%s] %s%s %s(%s%s@%s%s)%s %s%s%s%s(%s)"", weechat_prefix (""network""), IRC_COLOR_CHAT_DELIMITERS, IRC_COLOR_CHAT_CHANNEL, argv[3], IRC_COLOR_CHAT_DELIMITERS, irc_nick_color_for_msg (server, 1, NULL, argv[7]), argv[7], IRC_COLOR_CHAT_DELIMITERS, IRC_COLOR_CHAT_HOST, argv[4], argv[5], IRC_COLOR_CHAT_DELIMITERS, IRC_COLOR_RESET, (pos_attr) ? pos_attr : """", (pos_attr) ? "" "" : """", (pos_hopcount) ? pos_hopcount : """", (pos_hopcount) ? "" "" : """", (pos_realname) ? pos_realname : """"); } return WEECHAT_RC_OK; }","{'deleted': [{'line_no': 20, 'char_start': 430, 'char_end': 488, 'line': ' arg_start = (strcmp (argv[8], ""*"") == 0) ? 9 : 8;\n'}], 'added': [{'line_no': 20, 'char_start': 430, 'char_end': 504, 'line': ' arg_start = ((argc > 9) && (strcmp (argv[8], ""*"") == 0)) ? 9 : 8;\n'}]}","{'deleted': [], 'added': [{'char_start': 451, 'char_end': 466, 'chars': '(argc > 9) && ('}, {'char_start': 492, 'char_end': 493, 'chars': ')'}]}",github.com/weechat/weechat/commit/9904cb6d2eb40f679d8ff6557c22d53a3e3dc75a,src/plugins/irc/irc-protocol.c,cwe-476,859 cwe-125,tflite::GetOptionalInputTensor,"const TfLiteTensor* GetOptionalInputTensor(const TfLiteContext* context, const TfLiteNode* node, int index) { const bool use_tensor = index < node->inputs->size && node->inputs->data[index] != kTfLiteOptionalTensor; if (use_tensor) { return GetMutableInput(context, node, index); } return nullptr; }","const TfLiteTensor* GetOptionalInputTensor(const TfLiteContext* context, const TfLiteNode* node, int index) { return GetInput(context, node, index); }","{'deleted': [{'line_no': 3, 'char_start': 153, 'char_end': 209, 'line': ' const bool use_tensor = index < node->inputs->size &&\n'}, {'line_no': 4, 'char_start': 209, 'char_end': 287, 'line': ' node->inputs->data[index] != kTfLiteOptionalTensor;\n'}, {'line_no': 5, 'char_start': 287, 'char_end': 307, 'line': ' if (use_tensor) {\n'}, {'line_no': 6, 'char_start': 307, 'char_end': 357, 'line': ' return GetMutableInput(context, node, index);\n'}, {'line_no': 7, 'char_start': 357, 'char_end': 361, 'line': ' }\n'}, {'line_no': 8, 'char_start': 361, 'char_end': 379, 'line': ' return nullptr;\n'}], 'added': [{'line_no': 3, 'char_start': 153, 'char_end': 194, 'line': ' return GetInput(context, node, index);\n'}]}","{'deleted': [{'char_start': 155, 'char_end': 311, 'chars': 'const bool use_tensor = index < node->inputs->size &&\n node->inputs->data[index] != kTfLiteOptionalTensor;\n if (use_tensor) {\n '}, {'char_start': 321, 'char_end': 328, 'chars': 'Mutable'}, {'char_start': 355, 'char_end': 377, 'chars': ';\n }\n return nullptr'}], 'added': []}",github.com/tensorflow/tensorflow/commit/00302787b788c5ff04cb6f62aed5a74d936e86c0,tensorflow/lite/kernels/kernel_util.cc,cwe-125,83 cwe-416,rm_read_multi,"static int rm_read_multi(AVFormatContext *s, AVIOContext *pb, AVStream *st, char *mime) { int number_of_streams = avio_rb16(pb); int number_of_mdpr; int i, ret; unsigned size2; for (i = 0; i 0) { st2 = avformat_new_stream(s, NULL); if (!st2) { ret = AVERROR(ENOMEM); return ret; } st2->id = st->id + (i<<16); st2->codecpar->bit_rate = st->codecpar->bit_rate; st2->start_time = st->start_time; st2->duration = st->duration; st2->codecpar->codec_type = AVMEDIA_TYPE_DATA; st2->priv_data = ff_rm_alloc_rmstream(); if (!st2->priv_data) return AVERROR(ENOMEM); } else st2 = st; size2 = avio_rb32(pb); ret = ff_rm_read_mdpr_codecdata(s, s->pb, st2, st2->priv_data, size2, mime); if (ret < 0) return ret; } return 0; }","static int rm_read_multi(AVFormatContext *s, AVIOContext *pb, AVStream *st, char *mime) { int number_of_streams = avio_rb16(pb); int number_of_mdpr; int i, ret; unsigned size2; for (i = 0; i 0) { st2 = avformat_new_stream(s, NULL); if (!st2) { ret = AVERROR(ENOMEM); return ret; } st2->id = st->id + (i<<16); st2->codecpar->bit_rate = st->codecpar->bit_rate; st2->start_time = st->start_time; st2->duration = st->duration; st2->codecpar->codec_type = AVMEDIA_TYPE_DATA; st2->priv_data = ff_rm_alloc_rmstream(); if (!st2->priv_data) return AVERROR(ENOMEM); } else st2 = st; size2 = avio_rb32(pb); ret = ff_rm_read_mdpr_codecdata(s, s->pb, st2, st2->priv_data, size2, NULL); if (ret < 0) return ret; } return 0; }","{'deleted': [{'line_no': 35, 'char_start': 1195, 'char_end': 1249, 'line': ' size2, mime);\n'}], 'added': [{'line_no': 35, 'char_start': 1195, 'char_end': 1249, 'line': ' size2, NULL);\n'}]}","{'deleted': [{'char_start': 1242, 'char_end': 1246, 'chars': 'mime'}], 'added': [{'char_start': 1242, 'char_end': 1246, 'chars': 'NULL'}]}",github.com/FFmpeg/FFmpeg/commit/a7e032a277452366771951e29fd0bf2bd5c029f0,libavformat/rmdec.c,cwe-416,374 cwe-125,saa7164_bus_get,"int saa7164_bus_get(struct saa7164_dev *dev, struct tmComResInfo* msg, void *buf, int peekonly) { struct tmComResBusInfo *bus = &dev->bus; u32 bytes_to_read, write_distance, curr_grp, curr_gwp, new_grp, buf_size, space_rem; struct tmComResInfo msg_tmp; int ret = SAA_ERR_BAD_PARAMETER; saa7164_bus_verify(dev); if (msg == NULL) return ret; if (msg->size > dev->bus.m_wMaxReqSize) { printk(KERN_ERR ""%s() Exceeded dev->bus.m_wMaxReqSize\n"", __func__); return ret; } if ((peekonly == 0) && (msg->size > 0) && (buf == NULL)) { printk(KERN_ERR ""%s() Missing msg buf, size should be %d bytes\n"", __func__, msg->size); return ret; } mutex_lock(&bus->lock); /* Peek the bus to see if a msg exists, if it's not what we're expecting * then return cleanly else read the message from the bus. */ curr_gwp = saa7164_readl(bus->m_dwGetWritePos); curr_grp = saa7164_readl(bus->m_dwGetReadPos); if (curr_gwp == curr_grp) { ret = SAA_ERR_EMPTY; goto out; } bytes_to_read = sizeof(*msg); /* Calculate write distance to current read position */ write_distance = 0; if (curr_gwp >= curr_grp) /* Write doesn't wrap around the ring */ write_distance = curr_gwp - curr_grp; else /* Write wraps around the ring */ write_distance = curr_gwp + bus->m_dwSizeGetRing - curr_grp; if (bytes_to_read > write_distance) { printk(KERN_ERR ""%s() No message/response found\n"", __func__); ret = SAA_ERR_INVALID_COMMAND; goto out; } /* Calculate the new read position */ new_grp = curr_grp + bytes_to_read; if (new_grp > bus->m_dwSizeGetRing) { /* Ring wraps */ new_grp -= bus->m_dwSizeGetRing; space_rem = bus->m_dwSizeGetRing - curr_grp; memcpy_fromio(&msg_tmp, bus->m_pdwGetRing + curr_grp, space_rem); memcpy_fromio((u8 *)&msg_tmp + space_rem, bus->m_pdwGetRing, bytes_to_read - space_rem); } else { /* No wrapping */ memcpy_fromio(&msg_tmp, bus->m_pdwGetRing + curr_grp, bytes_to_read); } /* Convert from little endian to CPU */ msg_tmp.size = le16_to_cpu((__force __le16)msg_tmp.size); msg_tmp.command = le32_to_cpu((__force __le32)msg_tmp.command); msg_tmp.controlselector = le16_to_cpu((__force __le16)msg_tmp.controlselector); /* No need to update the read positions, because this was a peek */ /* If the caller specifically want to peek, return */ if (peekonly) { memcpy(msg, &msg_tmp, sizeof(*msg)); goto peekout; } /* Check if the command/response matches what is expected */ if ((msg_tmp.id != msg->id) || (msg_tmp.command != msg->command) || (msg_tmp.controlselector != msg->controlselector) || (msg_tmp.seqno != msg->seqno) || (msg_tmp.size != msg->size)) { printk(KERN_ERR ""%s() Unexpected msg miss-match\n"", __func__); saa7164_bus_dumpmsg(dev, msg, buf); saa7164_bus_dumpmsg(dev, &msg_tmp, NULL); ret = SAA_ERR_INVALID_COMMAND; goto out; } /* Get the actual command and response from the bus */ buf_size = msg->size; bytes_to_read = sizeof(*msg) + msg->size; /* Calculate write distance to current read position */ write_distance = 0; if (curr_gwp >= curr_grp) /* Write doesn't wrap around the ring */ write_distance = curr_gwp - curr_grp; else /* Write wraps around the ring */ write_distance = curr_gwp + bus->m_dwSizeGetRing - curr_grp; if (bytes_to_read > write_distance) { printk(KERN_ERR ""%s() Invalid bus state, missing msg or mangled ring, faulty H/W / bad code?\n"", __func__); ret = SAA_ERR_INVALID_COMMAND; goto out; } /* Calculate the new read position */ new_grp = curr_grp + bytes_to_read; if (new_grp > bus->m_dwSizeGetRing) { /* Ring wraps */ new_grp -= bus->m_dwSizeGetRing; space_rem = bus->m_dwSizeGetRing - curr_grp; if (space_rem < sizeof(*msg)) { /* msg wraps around the ring */ memcpy_fromio(msg, bus->m_pdwGetRing + curr_grp, space_rem); memcpy_fromio((u8 *)msg + space_rem, bus->m_pdwGetRing, sizeof(*msg) - space_rem); if (buf) memcpy_fromio(buf, bus->m_pdwGetRing + sizeof(*msg) - space_rem, buf_size); } else if (space_rem == sizeof(*msg)) { memcpy_fromio(msg, bus->m_pdwGetRing + curr_grp, sizeof(*msg)); if (buf) memcpy_fromio(buf, bus->m_pdwGetRing, buf_size); } else { /* Additional data wraps around the ring */ memcpy_fromio(msg, bus->m_pdwGetRing + curr_grp, sizeof(*msg)); if (buf) { memcpy_fromio(buf, bus->m_pdwGetRing + curr_grp + sizeof(*msg), space_rem - sizeof(*msg)); memcpy_fromio(buf + space_rem - sizeof(*msg), bus->m_pdwGetRing, bytes_to_read - space_rem); } } } else { /* No wrapping */ memcpy_fromio(msg, bus->m_pdwGetRing + curr_grp, sizeof(*msg)); if (buf) memcpy_fromio(buf, bus->m_pdwGetRing + curr_grp + sizeof(*msg), buf_size); } /* Convert from little endian to CPU */ msg->size = le16_to_cpu((__force __le16)msg->size); msg->command = le32_to_cpu((__force __le32)msg->command); msg->controlselector = le16_to_cpu((__force __le16)msg->controlselector); /* Update the read positions, adjusting the ring */ saa7164_writel(bus->m_dwGetReadPos, new_grp); peekout: ret = SAA_OK; out: mutex_unlock(&bus->lock); saa7164_bus_verify(dev); return ret; }","int saa7164_bus_get(struct saa7164_dev *dev, struct tmComResInfo* msg, void *buf, int peekonly) { struct tmComResBusInfo *bus = &dev->bus; u32 bytes_to_read, write_distance, curr_grp, curr_gwp, new_grp, buf_size, space_rem; struct tmComResInfo msg_tmp; int ret = SAA_ERR_BAD_PARAMETER; saa7164_bus_verify(dev); if (msg == NULL) return ret; if (msg->size > dev->bus.m_wMaxReqSize) { printk(KERN_ERR ""%s() Exceeded dev->bus.m_wMaxReqSize\n"", __func__); return ret; } if ((peekonly == 0) && (msg->size > 0) && (buf == NULL)) { printk(KERN_ERR ""%s() Missing msg buf, size should be %d bytes\n"", __func__, msg->size); return ret; } mutex_lock(&bus->lock); /* Peek the bus to see if a msg exists, if it's not what we're expecting * then return cleanly else read the message from the bus. */ curr_gwp = saa7164_readl(bus->m_dwGetWritePos); curr_grp = saa7164_readl(bus->m_dwGetReadPos); if (curr_gwp == curr_grp) { ret = SAA_ERR_EMPTY; goto out; } bytes_to_read = sizeof(*msg); /* Calculate write distance to current read position */ write_distance = 0; if (curr_gwp >= curr_grp) /* Write doesn't wrap around the ring */ write_distance = curr_gwp - curr_grp; else /* Write wraps around the ring */ write_distance = curr_gwp + bus->m_dwSizeGetRing - curr_grp; if (bytes_to_read > write_distance) { printk(KERN_ERR ""%s() No message/response found\n"", __func__); ret = SAA_ERR_INVALID_COMMAND; goto out; } /* Calculate the new read position */ new_grp = curr_grp + bytes_to_read; if (new_grp > bus->m_dwSizeGetRing) { /* Ring wraps */ new_grp -= bus->m_dwSizeGetRing; space_rem = bus->m_dwSizeGetRing - curr_grp; memcpy_fromio(&msg_tmp, bus->m_pdwGetRing + curr_grp, space_rem); memcpy_fromio((u8 *)&msg_tmp + space_rem, bus->m_pdwGetRing, bytes_to_read - space_rem); } else { /* No wrapping */ memcpy_fromio(&msg_tmp, bus->m_pdwGetRing + curr_grp, bytes_to_read); } /* Convert from little endian to CPU */ msg_tmp.size = le16_to_cpu((__force __le16)msg_tmp.size); msg_tmp.command = le32_to_cpu((__force __le32)msg_tmp.command); msg_tmp.controlselector = le16_to_cpu((__force __le16)msg_tmp.controlselector); memcpy(msg, &msg_tmp, sizeof(*msg)); /* No need to update the read positions, because this was a peek */ /* If the caller specifically want to peek, return */ if (peekonly) { goto peekout; } /* Check if the command/response matches what is expected */ if ((msg_tmp.id != msg->id) || (msg_tmp.command != msg->command) || (msg_tmp.controlselector != msg->controlselector) || (msg_tmp.seqno != msg->seqno) || (msg_tmp.size != msg->size)) { printk(KERN_ERR ""%s() Unexpected msg miss-match\n"", __func__); saa7164_bus_dumpmsg(dev, msg, buf); saa7164_bus_dumpmsg(dev, &msg_tmp, NULL); ret = SAA_ERR_INVALID_COMMAND; goto out; } /* Get the actual command and response from the bus */ buf_size = msg->size; bytes_to_read = sizeof(*msg) + msg->size; /* Calculate write distance to current read position */ write_distance = 0; if (curr_gwp >= curr_grp) /* Write doesn't wrap around the ring */ write_distance = curr_gwp - curr_grp; else /* Write wraps around the ring */ write_distance = curr_gwp + bus->m_dwSizeGetRing - curr_grp; if (bytes_to_read > write_distance) { printk(KERN_ERR ""%s() Invalid bus state, missing msg or mangled ring, faulty H/W / bad code?\n"", __func__); ret = SAA_ERR_INVALID_COMMAND; goto out; } /* Calculate the new read position */ new_grp = curr_grp + bytes_to_read; if (new_grp > bus->m_dwSizeGetRing) { /* Ring wraps */ new_grp -= bus->m_dwSizeGetRing; space_rem = bus->m_dwSizeGetRing - curr_grp; if (space_rem < sizeof(*msg)) { if (buf) memcpy_fromio(buf, bus->m_pdwGetRing + sizeof(*msg) - space_rem, buf_size); } else if (space_rem == sizeof(*msg)) { if (buf) memcpy_fromio(buf, bus->m_pdwGetRing, buf_size); } else { /* Additional data wraps around the ring */ if (buf) { memcpy_fromio(buf, bus->m_pdwGetRing + curr_grp + sizeof(*msg), space_rem - sizeof(*msg)); memcpy_fromio(buf + space_rem - sizeof(*msg), bus->m_pdwGetRing, bytes_to_read - space_rem); } } } else { /* No wrapping */ if (buf) memcpy_fromio(buf, bus->m_pdwGetRing + curr_grp + sizeof(*msg), buf_size); } /* Update the read positions, adjusting the ring */ saa7164_writel(bus->m_dwGetReadPos, new_grp); peekout: ret = SAA_OK; out: mutex_unlock(&bus->lock); saa7164_bus_verify(dev); return ret; }","{'deleted': [{'line_no': 82, 'char_start': 2348, 'char_end': 2387, 'line': '\t\tmemcpy(msg, &msg_tmp, sizeof(*msg));\n'}, {'line_no': 127, 'char_start': 3732, 'char_end': 3767, 'line': '\t\t\t/* msg wraps around the ring */\n'}, {'line_no': 128, 'char_start': 3767, 'char_end': 3831, 'line': '\t\t\tmemcpy_fromio(msg, bus->m_pdwGetRing + curr_grp, space_rem);\n'}, {'line_no': 129, 'char_start': 3831, 'char_end': 3890, 'line': '\t\t\tmemcpy_fromio((u8 *)msg + space_rem, bus->m_pdwGetRing,\n'}, {'line_no': 130, 'char_start': 3890, 'char_end': 3921, 'line': '\t\t\t\tsizeof(*msg) - space_rem);\n'}, {'line_no': 136, 'char_start': 4061, 'char_end': 4128, 'line': '\t\t\tmemcpy_fromio(msg, bus->m_pdwGetRing + curr_grp, sizeof(*msg));\n'}, {'line_no': 141, 'char_start': 4251, 'char_end': 4318, 'line': '\t\t\tmemcpy_fromio(msg, bus->m_pdwGetRing + curr_grp, sizeof(*msg));\n'}, {'line_no': 154, 'char_start': 4580, 'char_end': 4646, 'line': '\t\tmemcpy_fromio(msg, bus->m_pdwGetRing + curr_grp, sizeof(*msg));\n'}, {'line_no': 159, 'char_start': 4742, 'char_end': 4783, 'line': '\t/* Convert from little endian to CPU */\n'}, {'line_no': 160, 'char_start': 4783, 'char_end': 4836, 'line': '\tmsg->size = le16_to_cpu((__force __le16)msg->size);\n'}, {'line_no': 161, 'char_start': 4836, 'char_end': 4895, 'line': '\tmsg->command = le32_to_cpu((__force __le32)msg->command);\n'}, {'line_no': 162, 'char_start': 4895, 'char_end': 4970, 'line': '\tmsg->controlselector = le16_to_cpu((__force __le16)msg->controlselector);\n'}], 'added': [{'line_no': 78, 'char_start': 2206, 'char_end': 2244, 'line': '\tmemcpy(msg, &msg_tmp, sizeof(*msg));\n'}]}","{'deleted': [{'char_start': 2348, 'char_end': 2387, 'chars': '\t\tmemcpy(msg, &msg_tmp, sizeof(*msg));\n'}, {'char_start': 3732, 'char_end': 3921, 'chars': '\t\t\t/* msg wraps around the ring */\n\t\t\tmemcpy_fromio(msg, bus->m_pdwGetRing + curr_grp, space_rem);\n\t\t\tmemcpy_fromio((u8 *)msg + space_rem, bus->m_pdwGetRing,\n\t\t\t\tsizeof(*msg) - space_rem);\n'}, {'char_start': 4061, 'char_end': 4128, 'chars': '\t\t\tmemcpy_fromio(msg, bus->m_pdwGetRing + curr_grp, sizeof(*msg));\n'}, {'char_start': 4251, 'char_end': 4318, 'chars': '\t\t\tmemcpy_fromio(msg, bus->m_pdwGetRing + curr_grp, sizeof(*msg));\n'}, {'char_start': 4580, 'char_end': 4646, 'chars': '\t\tmemcpy_fromio(msg, bus->m_pdwGetRing + curr_grp, sizeof(*msg));\n'}, {'char_start': 4741, 'char_end': 4969, 'chars': '\n\t/* Convert from little endian to CPU */\n\tmsg->size = le16_to_cpu((__force __le16)msg->size);\n\tmsg->command = le32_to_cpu((__force __le32)msg->command);\n\tmsg->controlselector = le16_to_cpu((__force __le16)msg->controlselector);'}], 'added': [{'char_start': 2206, 'char_end': 2244, 'chars': '\tmemcpy(msg, &msg_tmp, sizeof(*msg));\n'}, {'char_start': 4349, 'char_end': 4349, 'chars': ''}]}",github.com/stoth68000/media-tree/commit/354dd3924a2e43806774953de536257548b5002c,drivers/media/pci/saa7164/saa7164-bus.c,cwe-125,1559 cwe-089,get_all_referrers,"@app.route('/get_all_referrers') def get_all_referrers(): account_id = request.args.get('account_id') if not isObject(account_id): ws.send('{""id"":1, ""method"":""call"", ""params"":[0,""lookup_account_names"",[[""' + account_id + '""], 0]]}') result_l = ws.recv() j_l = json.loads(result_l) account_id = j_l[""result""][0][""id""] con = psycopg2.connect(**config.POSTGRES) cur = con.cursor() query = ""select * from referrers where referrer='""+account_id+""'"" cur.execute(query) results = cur.fetchall() return jsonify(results)","@app.route('/get_all_referrers') def get_all_referrers(): account_id = request.args.get('account_id') if not isObject(account_id): ws.send('{""id"":1, ""method"":""call"", ""params"":[0,""lookup_account_names"",[[""' + account_id + '""], 0]]}') result_l = ws.recv() j_l = json.loads(result_l) account_id = j_l[""result""][0][""id""] con = psycopg2.connect(**config.POSTGRES) cur = con.cursor() query = ""select * from referrers where referrer=%s"" cur.execute(query, (account_id,)) results = cur.fetchall() return jsonify(results)","{'deleted': [{'line_no': 15, 'char_start': 430, 'char_end': 500, 'line': ' query = ""select * from referrers where referrer=\'""+account_id+""\'""\n'}, {'line_no': 16, 'char_start': 500, 'char_end': 523, 'line': ' cur.execute(query)\n'}], 'added': [{'line_no': 15, 'char_start': 430, 'char_end': 486, 'line': ' query = ""select * from referrers where referrer=%s""\n'}, {'line_no': 16, 'char_start': 486, 'char_end': 524, 'line': ' cur.execute(query, (account_id,))\n'}]}","{'deleted': [{'char_start': 482, 'char_end': 498, 'chars': '\'""+account_id+""\''}], 'added': [{'char_start': 482, 'char_end': 484, 'chars': '%s'}, {'char_start': 507, 'char_end': 522, 'chars': ', (account_id,)'}]}",github.com/VinChain/vinchain-python-api-backend/commit/b78088a551fbb712121269c6eb7f43ede120ff60,api.py,cwe-089,150 cwe-190,PyImaging_MapBuffer,"PyImaging_MapBuffer(PyObject* self, PyObject* args) { Py_ssize_t y, size; Imaging im; PyObject* target; Py_buffer view; char* mode; char* codec; PyObject* bbox; Py_ssize_t offset; int xsize, ysize; int stride; int ystep; if (!PyArg_ParseTuple(args, ""O(ii)sOn(sii)"", &target, &xsize, &ysize, &codec, &bbox, &offset, &mode, &stride, &ystep)) return NULL; if (!PyImaging_CheckBuffer(target)) { PyErr_SetString(PyExc_TypeError, ""expected string or buffer""); return NULL; } if (stride <= 0) { if (!strcmp(mode, ""L"") || !strcmp(mode, ""P"")) stride = xsize; else if (!strncmp(mode, ""I;16"", 4)) stride = xsize * 2; else stride = xsize * 4; } size = (Py_ssize_t) ysize * stride; /* check buffer size */ if (PyImaging_GetBuffer(target, &view) < 0) return NULL; if (view.len < 0) { PyErr_SetString(PyExc_ValueError, ""buffer has negative size""); return NULL; } if (offset + size > view.len) { PyErr_SetString(PyExc_ValueError, ""buffer is not large enough""); return NULL; } im = ImagingNewPrologueSubtype( mode, xsize, ysize, sizeof(ImagingBufferInstance) ); if (!im) return NULL; /* setup file pointers */ if (ystep > 0) for (y = 0; y < ysize; y++) im->image[y] = (char*)view.buf + offset + y * stride; else for (y = 0; y < ysize; y++) im->image[ysize-y-1] = (char*)view.buf + offset + y * stride; im->destroy = mapping_destroy_buffer; Py_INCREF(target); ((ImagingBufferInstance*) im)->target = target; ((ImagingBufferInstance*) im)->view = view; if (!ImagingNewEpilogue(im)) return NULL; return PyImagingNew(im); }","PyImaging_MapBuffer(PyObject* self, PyObject* args) { Py_ssize_t y, size; Imaging im; PyObject* target; Py_buffer view; char* mode; char* codec; PyObject* bbox; Py_ssize_t offset; int xsize, ysize; int stride; int ystep; if (!PyArg_ParseTuple(args, ""O(ii)sOn(sii)"", &target, &xsize, &ysize, &codec, &bbox, &offset, &mode, &stride, &ystep)) return NULL; if (!PyImaging_CheckBuffer(target)) { PyErr_SetString(PyExc_TypeError, ""expected string or buffer""); return NULL; } if (stride <= 0) { if (!strcmp(mode, ""L"") || !strcmp(mode, ""P"")) stride = xsize; else if (!strncmp(mode, ""I;16"", 4)) stride = xsize * 2; else stride = xsize * 4; } if (ysize > INT_MAX / stride) { PyErr_SetString(PyExc_MemoryError, ""Integer overflow in ysize""); return NULL; } size = (Py_ssize_t) ysize * stride; if (offset > SIZE_MAX - size) { PyErr_SetString(PyExc_MemoryError, ""Integer overflow in offset""); return NULL; } /* check buffer size */ if (PyImaging_GetBuffer(target, &view) < 0) return NULL; if (view.len < 0) { PyErr_SetString(PyExc_ValueError, ""buffer has negative size""); return NULL; } if (offset + size > view.len) { PyErr_SetString(PyExc_ValueError, ""buffer is not large enough""); return NULL; } im = ImagingNewPrologueSubtype( mode, xsize, ysize, sizeof(ImagingBufferInstance) ); if (!im) return NULL; /* setup file pointers */ if (ystep > 0) for (y = 0; y < ysize; y++) im->image[y] = (char*)view.buf + offset + y * stride; else for (y = 0; y < ysize; y++) im->image[ysize-y-1] = (char*)view.buf + offset + y * stride; im->destroy = mapping_destroy_buffer; Py_INCREF(target); ((ImagingBufferInstance*) im)->target = target; ((ImagingBufferInstance*) im)->view = view; if (!ImagingNewEpilogue(im)) return NULL; return PyImagingNew(im); }","{'deleted': [], 'added': [{'line_no': 34, 'char_start': 812, 'char_end': 848, 'line': ' if (ysize > INT_MAX / stride) {\n'}, {'line_no': 35, 'char_start': 848, 'char_end': 921, 'line': ' PyErr_SetString(PyExc_MemoryError, ""Integer overflow in ysize"");\n'}, {'line_no': 36, 'char_start': 921, 'char_end': 942, 'line': ' return NULL;\n'}, {'line_no': 37, 'char_start': 942, 'char_end': 948, 'line': ' }\n'}, {'line_no': 38, 'char_start': 948, 'char_end': 949, 'line': '\n'}, {'line_no': 41, 'char_start': 990, 'char_end': 1026, 'line': ' if (offset > SIZE_MAX - size) {\n'}, {'line_no': 42, 'char_start': 1026, 'char_end': 1100, 'line': ' PyErr_SetString(PyExc_MemoryError, ""Integer overflow in offset"");\n'}, {'line_no': 43, 'char_start': 1100, 'char_end': 1121, 'line': ' return NULL;\n'}, {'line_no': 44, 'char_start': 1121, 'char_end': 1135, 'line': ' } \n'}, {'line_no': 45, 'char_start': 1135, 'char_end': 1136, 'line': '\n'}]}","{'deleted': [], 'added': [{'char_start': 816, 'char_end': 953, 'chars': 'if (ysize > INT_MAX / stride) {\n PyErr_SetString(PyExc_MemoryError, ""Integer overflow in ysize"");\n return NULL;\n }\n\n '}, {'char_start': 988, 'char_end': 1134, 'chars': '\n\n if (offset > SIZE_MAX - size) {\n PyErr_SetString(PyExc_MemoryError, ""Integer overflow in offset"");\n return NULL;\n } '}]}",github.com/python-pillow/Pillow/commit/c50ebe6459a131a1ea8ca531f10da616d3ceaa0f,map.c,cwe-190,525 cwe-078,openscript,"openscript( char_u *name, int directly) /* when TRUE execute directly */ { if (curscript + 1 == NSCRIPT) { emsg(_(e_nesting)); return; } #ifdef FEAT_EVAL if (ignore_script) /* Not reading from script, also don't open one. Warning message? */ return; #endif if (scriptin[curscript] != NULL) /* already reading script */ ++curscript; /* use NameBuff for expanded name */ expand_env(name, NameBuff, MAXPATHL); if ((scriptin[curscript] = mch_fopen((char *)NameBuff, READBIN)) == NULL) { semsg(_(e_notopen), name); if (curscript) --curscript; return; } if (save_typebuf() == FAIL) return; /* * Execute the commands from the file right now when using "":source!"" * after "":global"" or "":argdo"" or in a loop. Also when another command * follows. This means the display won't be updated. Don't do this * always, ""make test"" would fail. */ if (directly) { oparg_T oa; int oldcurscript; int save_State = State; int save_restart_edit = restart_edit; int save_insertmode = p_im; int save_finish_op = finish_op; int save_msg_scroll = msg_scroll; State = NORMAL; msg_scroll = FALSE; /* no msg scrolling in Normal mode */ restart_edit = 0; /* don't go to Insert mode */ p_im = FALSE; /* don't use 'insertmode' */ clear_oparg(&oa); finish_op = FALSE; oldcurscript = curscript; do { update_topline_cursor(); // update cursor position and topline normal_cmd(&oa, FALSE); // execute one command vpeekc(); // check for end of file } while (scriptin[oldcurscript] != NULL); State = save_State; msg_scroll = save_msg_scroll; restart_edit = save_restart_edit; p_im = save_insertmode; finish_op = save_finish_op; } }","openscript( char_u *name, int directly) /* when TRUE execute directly */ { if (curscript + 1 == NSCRIPT) { emsg(_(e_nesting)); return; } // Disallow sourcing a file in the sandbox, the commands would be executed // later, possibly outside of the sandbox. if (check_secure()) return; #ifdef FEAT_EVAL if (ignore_script) /* Not reading from script, also don't open one. Warning message? */ return; #endif if (scriptin[curscript] != NULL) /* already reading script */ ++curscript; /* use NameBuff for expanded name */ expand_env(name, NameBuff, MAXPATHL); if ((scriptin[curscript] = mch_fopen((char *)NameBuff, READBIN)) == NULL) { semsg(_(e_notopen), name); if (curscript) --curscript; return; } if (save_typebuf() == FAIL) return; /* * Execute the commands from the file right now when using "":source!"" * after "":global"" or "":argdo"" or in a loop. Also when another command * follows. This means the display won't be updated. Don't do this * always, ""make test"" would fail. */ if (directly) { oparg_T oa; int oldcurscript; int save_State = State; int save_restart_edit = restart_edit; int save_insertmode = p_im; int save_finish_op = finish_op; int save_msg_scroll = msg_scroll; State = NORMAL; msg_scroll = FALSE; /* no msg scrolling in Normal mode */ restart_edit = 0; /* don't go to Insert mode */ p_im = FALSE; /* don't use 'insertmode' */ clear_oparg(&oa); finish_op = FALSE; oldcurscript = curscript; do { update_topline_cursor(); // update cursor position and topline normal_cmd(&oa, FALSE); // execute one command vpeekc(); // check for end of file } while (scriptin[oldcurscript] != NULL); State = save_State; msg_scroll = save_msg_scroll; restart_edit = save_restart_edit; p_im = save_insertmode; finish_op = save_finish_op; } }","{'deleted': [], 'added': [{'line_no': 10, 'char_start': 160, 'char_end': 161, 'line': '\n'}, {'line_no': 13, 'char_start': 287, 'char_end': 311, 'line': ' if (check_secure())\n'}, {'line_no': 14, 'char_start': 311, 'char_end': 320, 'line': '\treturn;\n'}, {'line_no': 15, 'char_start': 320, 'char_end': 321, 'line': '\n'}]}","{'deleted': [], 'added': [{'char_start': 160, 'char_end': 321, 'chars': '\n // Disallow sourcing a file in the sandbox, the commands would be executed\n // later, possibly outside of the sandbox.\n if (check_secure())\n\treturn;\n\n'}]}",github.com/vim/vim/commit/53575521406739cf20bbe4e384d88e7dca11f040,src/getchar.c,cwe-078,498 cwe-078,test_settings_path_skip_issue_909,"def test_settings_path_skip_issue_909(tmpdir): base_dir = tmpdir.mkdir('project') config_dir = base_dir.mkdir('conf') config_dir.join('.isort.cfg').write('[isort]\n' 'skip =\n' ' file_to_be_skipped.py\n' 'skip_glob =\n' ' *glob_skip*\n') base_dir.join('file_glob_skip.py').write('import os\n' '\n' 'print(""Hello World"")\n' '\n' 'import sys\n') base_dir.join('file_to_be_skipped.py').write('import os\n' '\n' 'print(""Hello World"")' '\n' 'import sys\n') test_run_directory = os.getcwd() os.chdir(str(base_dir)) with pytest.raises(Exception): # without the settings path provided: the command should not skip & identify errors check_output(['isort', '--check-only']) results = check_output(['isort', '--check-only', '--settings-path=conf/.isort.cfg']) os.chdir(str(test_run_directory)) assert b'skipped 2' in results.lower()","def test_settings_path_skip_issue_909(tmpdir): base_dir = tmpdir.mkdir('project') config_dir = base_dir.mkdir('conf') config_dir.join('.isort.cfg').write('[isort]\n' 'skip =\n' ' file_to_be_skipped.py\n' 'skip_glob =\n' ' *glob_skip*\n') base_dir.join('file_glob_skip.py').write('import os\n' '\n' 'print(""Hello World"")\n' '\n' 'import sys\n') base_dir.join('file_to_be_skipped.py').write('import os\n' '\n' 'print(""Hello World"")' '\n' 'import sys\n') test_run_directory = os.getcwd() os.chdir(str(base_dir)) with pytest.raises(Exception): # without the settings path provided: the command should not skip & identify errors subprocess.run(['isort', '--check-only'], check=True) result = subprocess.run( ['isort', '--check-only', '--settings-path=conf/.isort.cfg'], stdout=subprocess.PIPE, check=True ) os.chdir(str(test_run_directory)) assert b'skipped 2' in result.stdout.lower()","{'deleted': [{'line_no': 24, 'char_start': 1201, 'char_end': 1249, 'line': "" check_output(['isort', '--check-only'])\n""}, {'line_no': 25, 'char_start': 1249, 'char_end': 1338, 'line': "" results = check_output(['isort', '--check-only', '--settings-path=conf/.isort.cfg'])\n""}, {'line_no': 28, 'char_start': 1377, 'char_end': 1419, 'line': "" assert b'skipped 2' in results.lower()\n""}], 'added': [{'line_no': 24, 'char_start': 1201, 'char_end': 1263, 'line': "" subprocess.run(['isort', '--check-only'], check=True)\n""}, {'line_no': 25, 'char_start': 1263, 'char_end': 1292, 'line': ' result = subprocess.run(\n'}, {'line_no': 26, 'char_start': 1292, 'char_end': 1362, 'line': "" ['isort', '--check-only', '--settings-path=conf/.isort.cfg'],\n""}, {'line_no': 27, 'char_start': 1362, 'char_end': 1394, 'line': ' stdout=subprocess.PIPE,\n'}, {'line_no': 28, 'char_start': 1394, 'char_end': 1413, 'line': ' check=True\n'}, {'line_no': 29, 'char_start': 1413, 'char_end': 1419, 'line': ' )\n'}, {'line_no': 32, 'char_start': 1458, 'char_end': 1506, 'line': "" assert b'skipped 2' in result.stdout.lower()\n""}]}","{'deleted': [{'char_start': 1209, 'char_end': 1216, 'chars': 'check_o'}, {'char_start': 1217, 'char_end': 1218, 'chars': 't'}, {'char_start': 1220, 'char_end': 1221, 'chars': 't'}, {'char_start': 1259, 'char_end': 1260, 'chars': 's'}, {'char_start': 1264, 'char_end': 1265, 'chars': 'h'}, {'char_start': 1266, 'char_end': 1273, 'chars': 'ck_outp'}, {'char_start': 1274, 'char_end': 1275, 'chars': 't'}], 'added': [{'char_start': 1209, 'char_end': 1215, 'chars': 'subpro'}, {'char_start': 1217, 'char_end': 1221, 'chars': 'ss.r'}, {'char_start': 1222, 'char_end': 1223, 'chars': 'n'}, {'char_start': 1249, 'char_end': 1261, 'chars': ', check=True'}, {'char_start': 1276, 'char_end': 1282, 'chars': 'subpro'}, {'char_start': 1284, 'char_end': 1288, 'chars': 'ss.r'}, {'char_start': 1289, 'char_end': 1290, 'chars': 'n'}, {'char_start': 1291, 'char_end': 1300, 'chars': '\n '}, {'char_start': 1360, 'char_end': 1417, 'chars': ',\n stdout=subprocess.PIPE,\n check=True\n '}, {'char_start': 1491, 'char_end': 1492, 'chars': '.'}, {'char_start': 1493, 'char_end': 1498, 'chars': 'tdout'}]}",github.com/timothycrosley/isort/commit/1ab38f4f7840a3c19bf961a24630a992a8373a76,test_isort.py,cwe-078,257 cwe-787,next_state_val,"next_state_val(CClassNode* cc, OnigCodePoint *vs, OnigCodePoint v, int* vs_israw, int v_israw, enum CCVALTYPE intype, enum CCVALTYPE* type, enum CCSTATE* state, ScanEnv* env) { int r; switch (*state) { case CCS_VALUE: if (*type == CCV_SB) { BITSET_SET_BIT(cc->bs, (int )(*vs)); } else if (*type == CCV_CODE_POINT) { r = add_code_range(&(cc->mbuf), env, *vs, *vs); if (r < 0) return r; } break; case CCS_RANGE: if (intype == *type) { if (intype == CCV_SB) { if (*vs > 0xff || v > 0xff) return ONIGERR_INVALID_CODE_POINT_VALUE; if (*vs > v) { if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_ALLOW_EMPTY_RANGE_IN_CC)) goto ccs_range_end; else return ONIGERR_EMPTY_RANGE_IN_CHAR_CLASS; } bitset_set_range(cc->bs, (int )*vs, (int )v); } else { r = add_code_range(&(cc->mbuf), env, *vs, v); if (r < 0) return r; } } else { #if 0 if (intype == CCV_CODE_POINT && *type == CCV_SB) { #endif if (*vs > v) { if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_ALLOW_EMPTY_RANGE_IN_CC)) goto ccs_range_end; else return ONIGERR_EMPTY_RANGE_IN_CHAR_CLASS; } bitset_set_range(cc->bs, (int )*vs, (int )(v < 0xff ? v : 0xff)); r = add_code_range(&(cc->mbuf), env, (OnigCodePoint )*vs, v); if (r < 0) return r; #if 0 } else return ONIGERR_MISMATCH_CODE_LENGTH_IN_CLASS_RANGE; #endif } ccs_range_end: *state = CCS_COMPLETE; break; case CCS_COMPLETE: case CCS_START: *state = CCS_VALUE; break; default: break; } *vs_israw = v_israw; *vs = v; *type = intype; return 0; }","next_state_val(CClassNode* cc, OnigCodePoint *vs, OnigCodePoint v, int* vs_israw, int v_israw, enum CCVALTYPE intype, enum CCVALTYPE* type, enum CCSTATE* state, ScanEnv* env) { int r; switch (*state) { case CCS_VALUE: if (*type == CCV_SB) { if (*vs > 0xff) return ONIGERR_INVALID_CODE_POINT_VALUE; BITSET_SET_BIT(cc->bs, (int )(*vs)); } else if (*type == CCV_CODE_POINT) { r = add_code_range(&(cc->mbuf), env, *vs, *vs); if (r < 0) return r; } break; case CCS_RANGE: if (intype == *type) { if (intype == CCV_SB) { if (*vs > 0xff || v > 0xff) return ONIGERR_INVALID_CODE_POINT_VALUE; if (*vs > v) { if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_ALLOW_EMPTY_RANGE_IN_CC)) goto ccs_range_end; else return ONIGERR_EMPTY_RANGE_IN_CHAR_CLASS; } bitset_set_range(cc->bs, (int )*vs, (int )v); } else { r = add_code_range(&(cc->mbuf), env, *vs, v); if (r < 0) return r; } } else { #if 0 if (intype == CCV_CODE_POINT && *type == CCV_SB) { #endif if (*vs > v) { if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_ALLOW_EMPTY_RANGE_IN_CC)) goto ccs_range_end; else return ONIGERR_EMPTY_RANGE_IN_CHAR_CLASS; } bitset_set_range(cc->bs, (int )*vs, (int )(v < 0xff ? v : 0xff)); r = add_code_range(&(cc->mbuf), env, (OnigCodePoint )*vs, v); if (r < 0) return r; #if 0 } else return ONIGERR_MISMATCH_CODE_LENGTH_IN_CLASS_RANGE; #endif } ccs_range_end: *state = CCS_COMPLETE; break; case CCS_COMPLETE: case CCS_START: *state = CCS_VALUE; break; default: break; } *vs_israw = v_israw; *vs = v; *type = intype; return 0; }","{'deleted': [], 'added': [{'line_no': 11, 'char_start': 276, 'char_end': 298, 'line': ' if (*vs > 0xff)\n'}, {'line_no': 12, 'char_start': 298, 'char_end': 349, 'line': ' return ONIGERR_INVALID_CODE_POINT_VALUE;\n'}, {'line_no': 13, 'char_start': 349, 'char_end': 350, 'line': '\n'}]}","{'deleted': [], 'added': [{'char_start': 282, 'char_end': 356, 'chars': 'if (*vs > 0xff)\n return ONIGERR_INVALID_CODE_POINT_VALUE;\n\n '}]}",github.com/kkos/oniguruma/commit/b4bf968ad52afe14e60a2dc8a95d3555c543353a,src/regparse.c,cwe-787,558 cwe-089,__init__.view_grocery_list," def view_grocery_list(): print(""grocery== list"") groceryListFrame = Frame(self) groceryListFrame.rowconfigure(0, weight=1) groceryListFrame.columnconfigure(0, weight=1) groceryListFrame.rowconfigure(1, weight=3) groceryListFrame.columnconfigure(1, weight=3) groceryListFrame.pack() menu.pack_forget() groceryButton.pack_forget() label.configure(text=""Grocery List"") i = 0 database_file = ""meal_planner.db"" item_array = [] with sqlite3.connect(database_file) as conn: cursor = conn.cursor() tableName = ""ingredients_"" + str(weekNumber) selection = cursor.execute(""""""SELECT * FROM """""" + tableName) for result in [selection]: for row in result.fetchall(): print(row) for ingredient in row: print(ingredient) item_array.append(str(ingredient).split()) i = i +1 Label(groceryListFrame, text=ingredient, font=MEDIUM_FONT, justify=LEFT).grid(row=i, column=0, sticky=""w"") j = 0 for item in item_array: print(item) returnButton = Button(menuFrame, text = ""Return to Menu"", highlightbackground=""#e7e7e7"", command=lambda: [groceryListFrame.pack_forget(), menu.pack(), returnButton.pack_forget(), label.configure(text=""Meal Planer""), groceryButton.pack(side=RIGHT)]) returnButton.pack(side=RIGHT)"," def view_grocery_list(): print(""grocery== list"") groceryListFrame = Frame(self) groceryListFrame.rowconfigure(0, weight=1) groceryListFrame.columnconfigure(0, weight=1) groceryListFrame.rowconfigure(1, weight=3) groceryListFrame.columnconfigure(1, weight=3) groceryListFrame.pack() menu.pack_forget() groceryButton.pack_forget() label.configure(text=""Grocery List"") i = 0 database_file = ""meal_planner.db"" item_array = [] with sqlite3.connect(database_file) as conn: cursor = conn.cursor() tableName = ""ingredients_"" + str(weekNumber) selection = cursor.execute(""""""SELECT * FROM ?;"""""", (tableName, )) for result in [selection]: for row in result.fetchall(): print(row) for ingredient in row: print(ingredient) item_array.append(str(ingredient).split()) i = i +1 Label(groceryListFrame, text=ingredient, font=MEDIUM_FONT, justify=LEFT).grid(row=i, column=0, sticky=""w"") j = 0 for item in item_array: print(item) returnButton = Button(menuFrame, text = ""Return to Menu"", highlightbackground=""#e7e7e7"", command=lambda: [groceryListFrame.pack_forget(), menu.pack(), returnButton.pack_forget(), label.configure(text=""Meal Planer""), groceryButton.pack(side=RIGHT)]) returnButton.pack(side=RIGHT)","{'deleted': [{'line_no': 20, 'char_start': 745, 'char_end': 822, 'line': ' selection = cursor.execute(""""""SELECT * FROM """""" + tableName)\n'}], 'added': [{'line_no': 20, 'char_start': 745, 'char_end': 827, 'line': ' selection = cursor.execute(""""""SELECT * FROM ?;"""""", (tableName, ))\n'}]}","{'deleted': [{'char_start': 809, 'char_end': 811, 'chars': '+ '}], 'added': [{'char_start': 805, 'char_end': 807, 'chars': '?;'}, {'char_start': 810, 'char_end': 811, 'chars': ','}, {'char_start': 812, 'char_end': 813, 'chars': '('}, {'char_start': 822, 'char_end': 825, 'chars': ', )'}]}",github.com/trishamoyer/RecipePlanner-Python/commit/44d2ce370715d9344fad34b3b749322ab095a925,mealPlan.py,cwe-089,336 cwe-476,upnp_redirect,"upnp_redirect(const char * rhost, unsigned short eport, const char * iaddr, unsigned short iport, const char * protocol, const char * desc, unsigned int leaseduration) { int proto, r; char iaddr_old[32]; char rhost_old[32]; unsigned short iport_old; struct in_addr address; unsigned int timestamp; proto = proto_atoi(protocol); if(inet_aton(iaddr, &address) <= 0) { syslog(LOG_ERR, ""inet_aton(%s) FAILED"", iaddr); return -1; } if(!check_upnp_rule_against_permissions(upnppermlist, num_upnpperm, eport, address, iport)) { syslog(LOG_INFO, ""redirection permission check failed for "" ""%hu->%s:%hu %s"", eport, iaddr, iport, protocol); return -3; } /* IGDv1 (WANIPConnection:1 Service Template Version 1.01 / Nov 12, 2001) * - 2.2.20.PortMappingDescription : * Overwriting Previous / Existing Port Mappings: * If the RemoteHost, ExternalPort, PortMappingProtocol and InternalClient * are exactly the same as an existing mapping, the existing mapping values * for InternalPort, PortMappingDescription, PortMappingEnabled and * PortMappingLeaseDuration are overwritten. * Rejecting a New Port Mapping: * In cases where the RemoteHost, ExternalPort and PortMappingProtocol * are the same as an existing mapping, but the InternalClient is * different, the action is rejected with an appropriate error. * Add or Reject New Port Mapping behavior based on vendor implementation: * In cases where the ExternalPort, PortMappingProtocol and InternalClient * are the same, but RemoteHost is different, the vendor can choose to * support both mappings simultaneously, or reject the second mapping * with an appropriate error. * * - 2.4.16.AddPortMapping * This action creates a new port mapping or overwrites an existing * mapping with the same internal client. If the ExternalPort and * PortMappingProtocol pair is already mapped to another internal client, * an error is returned. * * IGDv2 (WANIPConnection:2 Service Standardized DCP (SDCP) Sep 10, 2010) * Protocol ExternalPort RemoteHost InternalClient Result * = = ≠ ≠ Failure * = = ≠ = Failure or success * (vendor specific) * = = = ≠ Failure * = = = = Success (overwrite) */ rhost_old[0] = '\0'; r = get_redirect_rule(ext_if_name, eport, proto, iaddr_old, sizeof(iaddr_old), &iport_old, 0, 0, rhost_old, sizeof(rhost_old), ×tamp, 0, 0); if(r == 0) { if(strcmp(iaddr, iaddr_old)==0 && ((rhost == NULL && rhost_old[0]=='\0') || (rhost && (strcmp(rhost, ""*"") == 0) && rhost_old[0]=='\0') || (rhost && (strcmp(rhost, rhost_old) == 0)))) { syslog(LOG_INFO, ""updating existing port mapping %hu %s (rhost '%s') => %s:%hu"", eport, protocol, rhost_old, iaddr_old, iport_old); timestamp = (leaseduration > 0) ? upnp_time() + leaseduration : 0; if(iport != iport_old) { r = update_portmapping(ext_if_name, eport, proto, iport, desc, timestamp); } else { r = update_portmapping_desc_timestamp(ext_if_name, eport, proto, desc, timestamp); } #ifdef ENABLE_LEASEFILE if(r == 0) { lease_file_remove(eport, proto); lease_file_add(eport, iaddr, iport, proto, desc, timestamp); } #endif /* ENABLE_LEASEFILE */ return r; } else { syslog(LOG_INFO, ""port %hu %s (rhost '%s') already redirected to %s:%hu"", eport, protocol, rhost_old, iaddr_old, iport_old); return -2; } #ifdef CHECK_PORTINUSE } else if (port_in_use(ext_if_name, eport, proto, iaddr, iport) > 0) { syslog(LOG_INFO, ""port %hu protocol %s already in use"", eport, protocol); return -4; #endif /* CHECK_PORTINUSE */ } else { timestamp = (leaseduration > 0) ? upnp_time() + leaseduration : 0; syslog(LOG_INFO, ""redirecting port %hu to %s:%hu protocol %s for: %s"", eport, iaddr, iport, protocol, desc); return upnp_redirect_internal(rhost, eport, iaddr, iport, proto, desc, timestamp); } }","upnp_redirect(const char * rhost, unsigned short eport, const char * iaddr, unsigned short iport, const char * protocol, const char * desc, unsigned int leaseduration) { int proto, r; char iaddr_old[32]; char rhost_old[32]; unsigned short iport_old; struct in_addr address; unsigned int timestamp; proto = proto_atoi(protocol); if(inet_aton(iaddr, &address) <= 0) { syslog(LOG_ERR, ""inet_aton(%s) FAILED"", iaddr); return -1; } if(!check_upnp_rule_against_permissions(upnppermlist, num_upnpperm, eport, address, iport)) { syslog(LOG_INFO, ""redirection permission check failed for "" ""%hu->%s:%hu %s"", eport, iaddr, iport, protocol); return -3; } if (desc == NULL) desc = """"; /* assume empty description */ /* IGDv1 (WANIPConnection:1 Service Template Version 1.01 / Nov 12, 2001) * - 2.2.20.PortMappingDescription : * Overwriting Previous / Existing Port Mappings: * If the RemoteHost, ExternalPort, PortMappingProtocol and InternalClient * are exactly the same as an existing mapping, the existing mapping values * for InternalPort, PortMappingDescription, PortMappingEnabled and * PortMappingLeaseDuration are overwritten. * Rejecting a New Port Mapping: * In cases where the RemoteHost, ExternalPort and PortMappingProtocol * are the same as an existing mapping, but the InternalClient is * different, the action is rejected with an appropriate error. * Add or Reject New Port Mapping behavior based on vendor implementation: * In cases where the ExternalPort, PortMappingProtocol and InternalClient * are the same, but RemoteHost is different, the vendor can choose to * support both mappings simultaneously, or reject the second mapping * with an appropriate error. * * - 2.4.16.AddPortMapping * This action creates a new port mapping or overwrites an existing * mapping with the same internal client. If the ExternalPort and * PortMappingProtocol pair is already mapped to another internal client, * an error is returned. * * IGDv2 (WANIPConnection:2 Service Standardized DCP (SDCP) Sep 10, 2010) * Protocol ExternalPort RemoteHost InternalClient Result * = = ≠ ≠ Failure * = = ≠ = Failure or success * (vendor specific) * = = = ≠ Failure * = = = = Success (overwrite) */ rhost_old[0] = '\0'; r = get_redirect_rule(ext_if_name, eport, proto, iaddr_old, sizeof(iaddr_old), &iport_old, 0, 0, rhost_old, sizeof(rhost_old), ×tamp, 0, 0); if(r == 0) { if(strcmp(iaddr, iaddr_old)==0 && ((rhost == NULL && rhost_old[0]=='\0') || (rhost && (strcmp(rhost, ""*"") == 0) && rhost_old[0]=='\0') || (rhost && (strcmp(rhost, rhost_old) == 0)))) { syslog(LOG_INFO, ""updating existing port mapping %hu %s (rhost '%s') => %s:%hu"", eport, protocol, rhost_old, iaddr_old, iport_old); timestamp = (leaseduration > 0) ? upnp_time() + leaseduration : 0; if(iport != iport_old) { r = update_portmapping(ext_if_name, eport, proto, iport, desc, timestamp); } else { r = update_portmapping_desc_timestamp(ext_if_name, eport, proto, desc, timestamp); } #ifdef ENABLE_LEASEFILE if(r == 0) { lease_file_remove(eport, proto); lease_file_add(eport, iaddr, iport, proto, desc, timestamp); } #endif /* ENABLE_LEASEFILE */ return r; } else { syslog(LOG_INFO, ""port %hu %s (rhost '%s') already redirected to %s:%hu"", eport, protocol, rhost_old, iaddr_old, iport_old); return -2; } #ifdef CHECK_PORTINUSE } else if (port_in_use(ext_if_name, eport, proto, iaddr, iport) > 0) { syslog(LOG_INFO, ""port %hu protocol %s already in use"", eport, protocol); return -4; #endif /* CHECK_PORTINUSE */ } else { timestamp = (leaseduration > 0) ? upnp_time() + leaseduration : 0; syslog(LOG_INFO, ""redirecting port %hu to %s:%hu protocol %s for: %s"", eport, iaddr, iport, protocol, desc); return upnp_redirect_internal(rhost, eport, iaddr, iport, proto, desc, timestamp); } }","{'deleted': [], 'added': [{'line_no': 25, 'char_start': 767, 'char_end': 768, 'line': '\n'}, {'line_no': 26, 'char_start': 768, 'char_end': 787, 'line': '\tif (desc == NULL)\n'}, {'line_no': 27, 'char_start': 787, 'char_end': 831, 'line': '\t\tdesc = """";\t/* assume empty description */\n'}, {'line_no': 28, 'char_start': 831, 'char_end': 832, 'line': '\n'}]}","{'deleted': [], 'added': [{'char_start': 767, 'char_end': 832, 'chars': '\n\tif (desc == NULL)\n\t\tdesc = """";\t/* assume empty description */\n\n'}]}",github.com/miniupnp/miniupnp/commit/f321c2066b96d18afa5158dfa2d2873a2957ef38,miniupnpd/upnpredirect.c,cwe-476,1182 cwe-125,opmov,"static int opmov(RAsm *a, ut8 *data, const Opcode *op) { int l = 0; st64 offset = 0; int mod = 0; int base = 0; int rex = 0; ut64 immediate = 0; if (op->operands[1].type & OT_CONSTANT) { if (!op->operands[1].is_good_flag) { return -1; } if (op->operands[1].immediate == -1) { return -1; } immediate = op->operands[1].immediate * op->operands[1].sign; if (op->operands[0].type & OT_GPREG && !(op->operands[0].type & OT_MEMORY)) { if (a->bits == 64 && ((op->operands[0].type & OT_QWORD) | (op->operands[1].type & OT_QWORD))) { if (!(op->operands[1].type & OT_CONSTANT) && op->operands[1].extended) { data[l++] = 0x49; } else { data[l++] = 0x48; } } else if (op->operands[0].extended) { data[l++] = 0x41; } if (op->operands[0].type & OT_WORD) { if (a->bits > 16) { data[l++] = 0x66; } } if (op->operands[0].type & OT_BYTE) { data[l++] = 0xb0 | op->operands[0].reg; data[l++] = immediate; } else { if (a->bits == 64 && ((op->operands[0].type & OT_QWORD) | (op->operands[1].type & OT_QWORD)) && immediate < UT32_MAX) { data[l++] = 0xc7; data[l++] = 0xc0 | op->operands[0].reg; } else { data[l++] = 0xb8 | op->operands[0].reg; } data[l++] = immediate; data[l++] = immediate >> 8; if (!(op->operands[0].type & OT_WORD)) { data[l++] = immediate >> 16; data[l++] = immediate >> 24; } if (a->bits == 64 && immediate > UT32_MAX) { data[l++] = immediate >> 32; data[l++] = immediate >> 40; data[l++] = immediate >> 48; data[l++] = immediate >> 56; } } } else if (op->operands[0].type & OT_MEMORY) { if (!op->operands[0].explicit_size) { if (op->operands[0].type & OT_GPREG) { ((Opcode *)op)->operands[0].dest_size = op->operands[0].reg_size; } else { return -1; } } int dest_bits = 8 * ((op->operands[0].dest_size & ALL_SIZE) >> OPSIZE_SHIFT); int reg_bits = 8 * ((op->operands[0].reg_size & ALL_SIZE) >> OPSIZE_SHIFT); int offset = op->operands[0].offset * op->operands[0].offset_sign; //addr_size_override prefix bool use_aso = false; if (reg_bits < a->bits) { use_aso = true; } //op_size_override prefix bool use_oso = false; if (dest_bits == 16) { use_oso = true; } bool rip_rel = op->operands[0].regs[0] == X86R_RIP; //rex prefix int rex = 1 << 6; bool use_rex = false; if (dest_bits == 64) { //W field use_rex = true; rex |= 1 << 3; } if (op->operands[0].extended) { //B field use_rex = true; rex |= 1; } //opcode selection int opcode; if (dest_bits == 8) { opcode = 0xc6; } else { opcode = 0xc7; } //modrm and SIB selection int modrm = 0; int mod; int reg = 0; int rm; bool use_sib = false; int sib; //mod if (offset == 0) { mod = 0; } else if (offset < 128 && offset > -129) { mod = 1; } else { mod = 2; } if (reg_bits == 16) { if (op->operands[0].regs[0] == X86R_BX && op->operands[0].regs[1] == X86R_SI) { rm = B0000; } else if (op->operands[0].regs[0] == X86R_BX && op->operands[0].regs[1] == X86R_DI) { rm = B0001; } else if (op->operands[0].regs[0] == X86R_BP && op->operands[0].regs[1] == X86R_SI) { rm = B0010; } else if (op->operands[0].regs[0] == X86R_BP && op->operands[0].regs[1] == X86R_DI) { rm = B0011; } else if (op->operands[0].regs[0] == X86R_SI && op->operands[0].regs[1] == -1) { rm = B0100; } else if (op->operands[0].regs[0] == X86R_DI && op->operands[0].regs[1] == -1) { rm = B0101; } else if (op->operands[0].regs[0] == X86R_BX && op->operands[0].regs[1] == -1) { rm = B0111; } else { //TODO allow for displacement only when parser is reworked return -1; } modrm = (mod << 6) | (reg << 3) | rm; } else { //rm if (op->operands[0].extended) { rm = op->operands[0].reg; } else { rm = op->operands[0].regs[0]; } //[epb] alone is illegal, so we need to fake a [ebp+0] if (rm == 5 && mod == 0) { mod = 1; } //sib int index = op->operands[0].regs[1]; int scale = getsib(op->operands[0].scale[1]); if (index != -1) { use_sib = true; sib = (scale << 6) | (index << 3) | rm; } else if (rm == 4) { use_sib = true; sib = 0x24; } if (use_sib) { rm = B0100; } if (rip_rel) { modrm = (B0000 << 6) | (reg << 3) | B0101; sib = (scale << 6) | (B0100 << 3) | B0101; } else { modrm = (mod << 6) | (reg << 3) | rm; } } //build the final result if (use_aso) { data[l++] = 0x67; } if (use_oso) { data[l++] = 0x66; } if (use_rex) { data[l++] = rex; } data[l++] = opcode; data[l++] = modrm; if (use_sib) { data[l++] = sib; } //offset if (mod == 1) { data[l++] = offset; } else if (reg_bits == 16 && mod == 2) { data[l++] = offset; data[l++] = offset >> 8; } else if (mod == 2 || rip_rel) { data[l++] = offset; data[l++] = offset >> 8; data[l++] = offset >> 16; data[l++] = offset >> 24; } //immediate int byte; for (byte = 0; byte < dest_bits && byte < 32; byte += 8) { data[l++] = (immediate >> byte); } } } else if (op->operands[1].type & OT_REGALL && !(op->operands[1].type & OT_MEMORY)) { if (op->operands[0].type & OT_CONSTANT) { return -1; } if (op->operands[0].type & OT_REGTYPE & OT_SEGMENTREG && op->operands[1].type & OT_REGTYPE & OT_SEGMENTREG) { return -1; } // Check reg sizes match if (op->operands[0].type & OT_REGTYPE && op->operands[1].type & OT_REGTYPE) { if (!((op->operands[0].type & ALL_SIZE) & (op->operands[1].type & ALL_SIZE))) { return -1; } } if (a->bits == 64) { if (op->operands[0].extended) { rex = 1; } if (op->operands[1].extended) { rex += 4; } if (op->operands[1].type & OT_QWORD) { if (!(op->operands[0].type & OT_QWORD)) { data[l++] = 0x67; data[l++] = 0x48; } } if (op->operands[1].type & OT_QWORD && op->operands[0].type & OT_QWORD) { data[l++] = 0x48 | rex; } if (op->operands[1].type & OT_DWORD && op->operands[0].type & OT_DWORD) { data[l++] = 0x40 | rex; } } else if (op->operands[0].extended && op->operands[1].extended) { data[l++] = 0x45; } offset = op->operands[0].offset * op->operands[0].offset_sign; if (op->operands[1].type & OT_REGTYPE & OT_SEGMENTREG) { data[l++] = 0x8c; } else { if (op->operands[0].type & OT_WORD) { data[l++] = 0x66; } data[l++] = (op->operands[0].type & OT_BYTE) ? 0x88 : 0x89; } if (op->operands[0].scale[0] > 1) { data[l++] = op->operands[1].reg << 3 | 4; data[l++] = getsib (op->operands[0].scale[0]) << 6 | op->operands[0].regs[0] << 3 | 5; data[l++] = offset; data[l++] = offset >> 8; data[l++] = offset >> 16; data[l++] = offset >> 24; return l; } if (!(op->operands[0].type & OT_MEMORY)) { if (op->operands[0].reg == X86R_UNDEFINED || op->operands[1].reg == X86R_UNDEFINED) { return -1; } mod = 0x3; data[l++] = mod << 6 | op->operands[1].reg << 3 | op->operands[0].reg; } else if (op->operands[0].regs[0] == X86R_UNDEFINED) { data[l++] = op->operands[1].reg << 3 | 0x5; data[l++] = offset; data[l++] = offset >> 8; data[l++] = offset >> 16; data[l++] = offset >> 24; } else { if (op->operands[0].type & OT_MEMORY) { if (op->operands[0].regs[1] != X86R_UNDEFINED) { data[l++] = op->operands[1].reg << 3 | 0x4; data[l++] = op->operands[0].regs[1] << 3 | op->operands[0].regs[0]; return l; } if (offset) { mod = (offset > 128 || offset < -129) ? 0x2 : 0x1; } if (op->operands[0].regs[0] == X86R_EBP) { mod = 0x2; } data[l++] = mod << 6 | op->operands[1].reg << 3 | op->operands[0].regs[0]; if (op->operands[0].regs[0] == X86R_ESP) { data[l++] = 0x24; } if (offset) { data[l++] = offset; } if (mod == 2) { // warning C4293: '>>': shift count negative or too big, undefined behavior data[l++] = offset >> 8; data[l++] = offset >> 16; data[l++] = offset >> 24; } } } } else if (op->operands[1].type & OT_MEMORY) { if (op->operands[0].type & OT_MEMORY) { return -1; } offset = op->operands[1].offset * op->operands[1].offset_sign; if (op->operands[0].reg == X86R_EAX && op->operands[1].regs[0] == X86R_UNDEFINED) { if (a->bits == 64) { data[l++] = 0x48; } if (op->operands[0].type & OT_BYTE) { data[l++] = 0xa0; } else { data[l++] = 0xa1; } data[l++] = offset; data[l++] = offset >> 8; data[l++] = offset >> 16; data[l++] = offset >> 24; if (a->bits == 64) { data[l++] = offset >> 32; data[l++] = offset >> 40; data[l++] = offset >> 48; data[l++] = offset >> 54; } return l; } if (op->operands[0].type & OT_BYTE && a->bits == 64 && op->operands[1].regs[0]) { if (op->operands[1].regs[0] >= X86R_R8 && op->operands[0].reg < 4) { data[l++] = 0x41; data[l++] = 0x8a; data[l++] = op->operands[0].reg << 3 | (op->operands[1].regs[0] - 8); return l; } return -1; } if (op->operands[1].type & OT_REGTYPE & OT_SEGMENTREG) { if (op->operands[1].scale[0] == 0) { return -1; } data[l++] = SEG_REG_PREFIXES[op->operands[1].regs[0]]; data[l++] = 0x8b; data[l++] = op->operands[0].reg << 3 | 0x5; data[l++] = offset; data[l++] = offset >> 8; data[l++] = offset >> 16; data[l++] = offset >> 24; return l; } if (a->bits == 64) { if (op->operands[0].type & OT_QWORD) { if (!(op->operands[1].type & OT_QWORD)) { if (op->operands[1].regs[0] != -1) { data[l++] = 0x67; } data[l++] = 0x48; } } else if (op->operands[1].type & OT_DWORD) { data[l++] = 0x44; } else if (!(op->operands[1].type & OT_QWORD)) { data[l++] = 0x67; } if (op->operands[1].type & OT_QWORD && op->operands[0].type & OT_QWORD) { data[l++] = 0x48; } } if (op->operands[0].type & OT_WORD) { data[l++] = 0x66; data[l++] = op->operands[1].type & OT_BYTE ? 0x8a : 0x8b; } else { data[l++] = (op->operands[1].type & OT_BYTE || op->operands[0].type & OT_BYTE) ? 0x8a : 0x8b; } if (op->operands[1].regs[0] == X86R_UNDEFINED) { if (a->bits == 64) { data[l++] = op->operands[0].reg << 3 | 0x4; data[l++] = 0x25; } else { data[l++] = op->operands[0].reg << 3 | 0x5; } data[l++] = offset; data[l++] = offset >> 8; data[l++] = offset >> 16; data[l++] = offset >> 24; } else { if (op->operands[1].scale[0] > 1) { data[l++] = op->operands[0].reg << 3 | 4; if (op->operands[1].scale[0] >= 2) { base = 5; } if (base) { data[l++] = getsib (op->operands[1].scale[0]) << 6 | op->operands[1].regs[0] << 3 | base; } else { data[l++] = getsib (op->operands[1].scale[0]) << 3 | op->operands[1].regs[0]; } if (offset || base) { data[l++] = offset; data[l++] = offset >> 8; data[l++] = offset >> 16; data[l++] = offset >> 24; } return l; } if (op->operands[1].regs[1] != X86R_UNDEFINED) { data[l++] = op->operands[0].reg << 3 | 0x4; data[l++] = op->operands[1].regs[1] << 3 | op->operands[1].regs[0]; return l; } if (offset || op->operands[1].regs[0] == X86R_EBP) { mod = 0x2; if (op->operands[1].offset > 127) { mod = 0x4; } } if (a->bits == 64 && offset && op->operands[0].type & OT_QWORD) { if (op->operands[1].regs[0] == X86R_RIP) { data[l++] = 0x5; } else { if (op->operands[1].offset > 127) { data[l++] = 0x80 | op->operands[0].reg << 3 | op->operands[1].regs[0]; } else { data[l++] = 0x40 | op->operands[1].regs[0]; } } if (op->operands[1].offset > 127) { mod = 0x1; } } else { if (op->operands[1].regs[0] == X86R_EIP && (op->operands[0].type & OT_DWORD)) { data[l++] = 0x0d; } else if (op->operands[1].regs[0] == X86R_RIP && (op->operands[0].type & OT_QWORD)) { data[l++] = 0x05; } else { data[l++] = mod << 5 | op->operands[0].reg << 3 | op->operands[1].regs[0]; } } if (op->operands[1].regs[0] == X86R_ESP) { data[l++] = 0x24; } if (mod >= 0x2) { data[l++] = offset; if (op->operands[1].offset > 128 || op->operands[1].regs[0] == X86R_EIP) { data[l++] = offset >> 8; data[l++] = offset >> 16; data[l++] = offset >> 24; } } else if (a->bits == 64 && (offset || op->operands[1].regs[0] == X86R_RIP)) { data[l++] = offset; if (op->operands[1].offset > 127 || op->operands[1].regs[0] == X86R_RIP) { data[l++] = offset >> 8; data[l++] = offset >> 16; data[l++] = offset >> 24; } } } } return l; }","static int opmov(RAsm *a, ut8 *data, const Opcode *op) { int l = 0; st64 offset = 0; int mod = 0; int base = 0; int rex = 0; ut64 immediate = 0; if (op->operands[1].type & OT_CONSTANT) { if (!op->operands[1].is_good_flag) { return -1; } if (op->operands[1].immediate == -1) { return -1; } immediate = op->operands[1].immediate * op->operands[1].sign; if (op->operands[0].type & OT_GPREG && !(op->operands[0].type & OT_MEMORY)) { if (a->bits == 64 && ((op->operands[0].type & OT_QWORD) | (op->operands[1].type & OT_QWORD))) { if (!(op->operands[1].type & OT_CONSTANT) && op->operands[1].extended) { data[l++] = 0x49; } else { data[l++] = 0x48; } } else if (op->operands[0].extended) { data[l++] = 0x41; } if (op->operands[0].type & OT_WORD) { if (a->bits > 16) { data[l++] = 0x66; } } if (op->operands[0].type & OT_BYTE) { data[l++] = 0xb0 | op->operands[0].reg; data[l++] = immediate; } else { if (a->bits == 64 && ((op->operands[0].type & OT_QWORD) | (op->operands[1].type & OT_QWORD)) && immediate < UT32_MAX) { data[l++] = 0xc7; data[l++] = 0xc0 | op->operands[0].reg; } else { data[l++] = 0xb8 | op->operands[0].reg; } data[l++] = immediate; data[l++] = immediate >> 8; if (!(op->operands[0].type & OT_WORD)) { data[l++] = immediate >> 16; data[l++] = immediate >> 24; } if (a->bits == 64 && immediate > UT32_MAX) { data[l++] = immediate >> 32; data[l++] = immediate >> 40; data[l++] = immediate >> 48; data[l++] = immediate >> 56; } } } else if (op->operands[0].type & OT_MEMORY) { if (!op->operands[0].explicit_size) { if (op->operands[0].type & OT_GPREG) { ((Opcode *)op)->operands[0].dest_size = op->operands[0].reg_size; } else { return -1; } } int dest_bits = 8 * ((op->operands[0].dest_size & ALL_SIZE) >> OPSIZE_SHIFT); int reg_bits = 8 * ((op->operands[0].reg_size & ALL_SIZE) >> OPSIZE_SHIFT); int offset = op->operands[0].offset * op->operands[0].offset_sign; //addr_size_override prefix bool use_aso = false; if (reg_bits < a->bits) { use_aso = true; } //op_size_override prefix bool use_oso = false; if (dest_bits == 16) { use_oso = true; } bool rip_rel = op->operands[0].regs[0] == X86R_RIP; //rex prefix int rex = 1 << 6; bool use_rex = false; if (dest_bits == 64) { //W field use_rex = true; rex |= 1 << 3; } if (op->operands[0].extended) { //B field use_rex = true; rex |= 1; } //opcode selection int opcode; if (dest_bits == 8) { opcode = 0xc6; } else { opcode = 0xc7; } //modrm and SIB selection int modrm = 0; int mod; int reg = 0; int rm; bool use_sib = false; int sib; //mod if (offset == 0) { mod = 0; } else if (offset < 128 && offset > -129) { mod = 1; } else { mod = 2; } if (reg_bits == 16) { if (op->operands[0].regs[0] == X86R_BX && op->operands[0].regs[1] == X86R_SI) { rm = B0000; } else if (op->operands[0].regs[0] == X86R_BX && op->operands[0].regs[1] == X86R_DI) { rm = B0001; } else if (op->operands[0].regs[0] == X86R_BP && op->operands[0].regs[1] == X86R_SI) { rm = B0010; } else if (op->operands[0].regs[0] == X86R_BP && op->operands[0].regs[1] == X86R_DI) { rm = B0011; } else if (op->operands[0].regs[0] == X86R_SI && op->operands[0].regs[1] == -1) { rm = B0100; } else if (op->operands[0].regs[0] == X86R_DI && op->operands[0].regs[1] == -1) { rm = B0101; } else if (op->operands[0].regs[0] == X86R_BX && op->operands[0].regs[1] == -1) { rm = B0111; } else { //TODO allow for displacement only when parser is reworked return -1; } modrm = (mod << 6) | (reg << 3) | rm; } else { //rm if (op->operands[0].extended) { rm = op->operands[0].reg; } else { rm = op->operands[0].regs[0]; } //[epb] alone is illegal, so we need to fake a [ebp+0] if (rm == 5 && mod == 0) { mod = 1; } //sib int index = op->operands[0].regs[1]; int scale = getsib(op->operands[0].scale[1]); if (index != -1) { use_sib = true; sib = (scale << 6) | (index << 3) | rm; } else if (rm == 4) { use_sib = true; sib = 0x24; } if (use_sib) { rm = B0100; } if (rip_rel) { modrm = (B0000 << 6) | (reg << 3) | B0101; sib = (scale << 6) | (B0100 << 3) | B0101; } else { modrm = (mod << 6) | (reg << 3) | rm; } } //build the final result if (use_aso) { data[l++] = 0x67; } if (use_oso) { data[l++] = 0x66; } if (use_rex) { data[l++] = rex; } data[l++] = opcode; data[l++] = modrm; if (use_sib) { data[l++] = sib; } //offset if (mod == 1) { data[l++] = offset; } else if (reg_bits == 16 && mod == 2) { data[l++] = offset; data[l++] = offset >> 8; } else if (mod == 2 || rip_rel) { data[l++] = offset; data[l++] = offset >> 8; data[l++] = offset >> 16; data[l++] = offset >> 24; } //immediate int byte; for (byte = 0; byte < dest_bits && byte < 32; byte += 8) { data[l++] = (immediate >> byte); } } } else if (op->operands[1].type & OT_REGALL && !(op->operands[1].type & OT_MEMORY)) { if (op->operands[0].type & OT_CONSTANT) { return -1; } if (op->operands[0].type & OT_REGTYPE & OT_SEGMENTREG && op->operands[1].type & OT_REGTYPE & OT_SEGMENTREG) { return -1; } // Check reg sizes match if (op->operands[0].type & OT_REGTYPE && op->operands[1].type & OT_REGTYPE) { if (!((op->operands[0].type & ALL_SIZE) & (op->operands[1].type & ALL_SIZE))) { return -1; } } if (a->bits == 64) { if (op->operands[0].extended) { rex = 1; } if (op->operands[1].extended) { rex += 4; } if (op->operands[1].type & OT_QWORD) { if (!(op->operands[0].type & OT_QWORD)) { data[l++] = 0x67; data[l++] = 0x48; } } if (op->operands[1].type & OT_QWORD && op->operands[0].type & OT_QWORD) { data[l++] = 0x48 | rex; } if (op->operands[1].type & OT_DWORD && op->operands[0].type & OT_DWORD) { data[l++] = 0x40 | rex; } } else if (op->operands[0].extended && op->operands[1].extended) { data[l++] = 0x45; } offset = op->operands[0].offset * op->operands[0].offset_sign; if (op->operands[1].type & OT_REGTYPE & OT_SEGMENTREG) { data[l++] = 0x8c; } else { if (op->operands[0].type & OT_WORD) { data[l++] = 0x66; } data[l++] = (op->operands[0].type & OT_BYTE) ? 0x88 : 0x89; } if (op->operands[0].scale[0] > 1) { data[l++] = op->operands[1].reg << 3 | 4; data[l++] = getsib (op->operands[0].scale[0]) << 6 | op->operands[0].regs[0] << 3 | 5; data[l++] = offset; data[l++] = offset >> 8; data[l++] = offset >> 16; data[l++] = offset >> 24; return l; } if (!(op->operands[0].type & OT_MEMORY)) { if (op->operands[0].reg == X86R_UNDEFINED || op->operands[1].reg == X86R_UNDEFINED) { return -1; } mod = 0x3; data[l++] = mod << 6 | op->operands[1].reg << 3 | op->operands[0].reg; } else if (op->operands[0].regs[0] == X86R_UNDEFINED) { data[l++] = op->operands[1].reg << 3 | 0x5; data[l++] = offset; data[l++] = offset >> 8; data[l++] = offset >> 16; data[l++] = offset >> 24; } else { if (op->operands[0].type & OT_MEMORY) { if (op->operands[0].regs[1] != X86R_UNDEFINED) { data[l++] = op->operands[1].reg << 3 | 0x4; data[l++] = op->operands[0].regs[1] << 3 | op->operands[0].regs[0]; return l; } if (offset) { mod = (offset > 128 || offset < -129) ? 0x2 : 0x1; } if (op->operands[0].regs[0] == X86R_EBP) { mod = 0x2; } data[l++] = mod << 6 | op->operands[1].reg << 3 | op->operands[0].regs[0]; if (op->operands[0].regs[0] == X86R_ESP) { data[l++] = 0x24; } if (offset) { data[l++] = offset; } if (mod == 2) { // warning C4293: '>>': shift count negative or too big, undefined behavior data[l++] = offset >> 8; data[l++] = offset >> 16; data[l++] = offset >> 24; } } } } else if (op->operands[1].type & OT_MEMORY) { if (op->operands[0].type & OT_MEMORY) { return -1; } offset = op->operands[1].offset * op->operands[1].offset_sign; if (op->operands[0].reg == X86R_EAX && op->operands[1].regs[0] == X86R_UNDEFINED) { if (a->bits == 64) { data[l++] = 0x48; } if (op->operands[0].type & OT_BYTE) { data[l++] = 0xa0; } else { data[l++] = 0xa1; } data[l++] = offset; data[l++] = offset >> 8; data[l++] = offset >> 16; data[l++] = offset >> 24; if (a->bits == 64) { data[l++] = offset >> 32; data[l++] = offset >> 40; data[l++] = offset >> 48; data[l++] = offset >> 54; } return l; } if (op->operands[0].type & OT_BYTE && a->bits == 64 && op->operands[1].regs[0]) { if (op->operands[1].regs[0] >= X86R_R8 && op->operands[0].reg < 4) { data[l++] = 0x41; data[l++] = 0x8a; data[l++] = op->operands[0].reg << 3 | (op->operands[1].regs[0] - 8); return l; } return -1; } if (op->operands[1].type & OT_REGTYPE & OT_SEGMENTREG) { if (op->operands[1].scale[0] == 0) { return -1; } data[l++] = SEG_REG_PREFIXES[op->operands[1].regs[0] % 6]; data[l++] = 0x8b; data[l++] = (((ut32)op->operands[0].reg) << 3) | 0x5; data[l++] = offset; data[l++] = offset >> 8; data[l++] = offset >> 16; data[l++] = offset >> 24; return l; } if (a->bits == 64) { if (op->operands[0].type & OT_QWORD) { if (!(op->operands[1].type & OT_QWORD)) { if (op->operands[1].regs[0] != -1) { data[l++] = 0x67; } data[l++] = 0x48; } } else if (op->operands[1].type & OT_DWORD) { data[l++] = 0x44; } else if (!(op->operands[1].type & OT_QWORD)) { data[l++] = 0x67; } if (op->operands[1].type & OT_QWORD && op->operands[0].type & OT_QWORD) { data[l++] = 0x48; } } if (op->operands[0].type & OT_WORD) { data[l++] = 0x66; data[l++] = op->operands[1].type & OT_BYTE ? 0x8a : 0x8b; } else { data[l++] = (op->operands[1].type & OT_BYTE || op->operands[0].type & OT_BYTE) ? 0x8a : 0x8b; } if (op->operands[1].regs[0] == X86R_UNDEFINED) { if (a->bits == 64) { data[l++] = op->operands[0].reg << 3 | 0x4; data[l++] = 0x25; } else { data[l++] = op->operands[0].reg << 3 | 0x5; } data[l++] = offset; data[l++] = offset >> 8; data[l++] = offset >> 16; data[l++] = offset >> 24; } else { if (op->operands[1].scale[0] > 1) { data[l++] = op->operands[0].reg << 3 | 4; if (op->operands[1].scale[0] >= 2) { base = 5; } if (base) { data[l++] = getsib (op->operands[1].scale[0]) << 6 | op->operands[1].regs[0] << 3 | base; } else { data[l++] = getsib (op->operands[1].scale[0]) << 3 | op->operands[1].regs[0]; } if (offset || base) { data[l++] = offset; data[l++] = offset >> 8; data[l++] = offset >> 16; data[l++] = offset >> 24; } return l; } if (op->operands[1].regs[1] != X86R_UNDEFINED) { data[l++] = op->operands[0].reg << 3 | 0x4; data[l++] = op->operands[1].regs[1] << 3 | op->operands[1].regs[0]; return l; } if (offset || op->operands[1].regs[0] == X86R_EBP) { mod = 0x2; if (op->operands[1].offset > 127) { mod = 0x4; } } if (a->bits == 64 && offset && op->operands[0].type & OT_QWORD) { if (op->operands[1].regs[0] == X86R_RIP) { data[l++] = 0x5; } else { if (op->operands[1].offset > 127) { data[l++] = 0x80 | op->operands[0].reg << 3 | op->operands[1].regs[0]; } else { data[l++] = 0x40 | op->operands[1].regs[0]; } } if (op->operands[1].offset > 127) { mod = 0x1; } } else { if (op->operands[1].regs[0] == X86R_EIP && (op->operands[0].type & OT_DWORD)) { data[l++] = 0x0d; } else if (op->operands[1].regs[0] == X86R_RIP && (op->operands[0].type & OT_QWORD)) { data[l++] = 0x05; } else { data[l++] = mod << 5 | op->operands[0].reg << 3 | op->operands[1].regs[0]; } } if (op->operands[1].regs[0] == X86R_ESP) { data[l++] = 0x24; } if (mod >= 0x2) { data[l++] = offset; if (op->operands[1].offset > 128 || op->operands[1].regs[0] == X86R_EIP) { data[l++] = offset >> 8; data[l++] = offset >> 16; data[l++] = offset >> 24; } } else if (a->bits == 64 && (offset || op->operands[1].regs[0] == X86R_RIP)) { data[l++] = offset; if (op->operands[1].offset > 127 || op->operands[1].regs[0] == X86R_RIP) { data[l++] = offset >> 8; data[l++] = offset >> 16; data[l++] = offset >> 24; } } } } return l; }","{'deleted': [{'line_no': 352, 'char_start': 9435, 'char_end': 9493, 'line': '\t\t\tdata[l++] = SEG_REG_PREFIXES[op->operands[1].regs[0]];\n'}, {'line_no': 354, 'char_start': 9514, 'char_end': 9561, 'line': '\t\t\tdata[l++] = op->operands[0].reg << 3 | 0x5;\n'}], 'added': [{'line_no': 352, 'char_start': 9435, 'char_end': 9497, 'line': '\t\t\tdata[l++] = SEG_REG_PREFIXES[op->operands[1].regs[0] % 6];\n'}, {'line_no': 354, 'char_start': 9518, 'char_end': 9575, 'line': '\t\t\tdata[l++] = (((ut32)op->operands[0].reg) << 3) | 0x5;\n'}]}","{'deleted': [], 'added': [{'char_start': 9490, 'char_end': 9494, 'chars': ' % 6'}, {'char_start': 9533, 'char_end': 9541, 'chars': '(((ut32)'}, {'char_start': 9560, 'char_end': 9561, 'chars': ')'}, {'char_start': 9566, 'char_end': 9567, 'chars': ')'}]}",github.com/radare/radare2/commit/f17bfd9f1da05f30f23a4dd05e9d2363e1406948,libr/asm/p/asm_x86_nz.c,cwe-125,5165 cwe-078,IsBlacklistedArg,"bool IsBlacklistedArg(const base::CommandLine::CharType* arg) { #if defined(OS_WIN) const auto converted = base::WideToUTF8(arg); const char* a = converted.c_str(); #else const char* a = arg; #endif static const char* prefixes[] = {""--"", ""-"", ""/""}; int prefix_length = 0; for (auto& prefix : prefixes) { if (base::StartsWith(a, prefix, base::CompareCase::SENSITIVE)) { prefix_length = strlen(prefix); break; } } if (prefix_length > 0) { a += prefix_length; std::string switch_name(a, strcspn(a, ""="")); auto* iter = std::lower_bound(std::begin(kBlacklist), std::end(kBlacklist), switch_name); if (iter != std::end(kBlacklist) && switch_name == *iter) { return true; } } return false; }","bool IsBlacklistedArg(const base::CommandLine::CharType* arg) { #if defined(OS_WIN) const auto converted = base::WideToUTF8(arg); const char* a = converted.c_str(); #else const char* a = arg; #endif static const char* prefixes[] = {""--"", ""-"", ""/""}; int prefix_length = 0; for (auto& prefix : prefixes) { if (base::StartsWith(a, prefix, base::CompareCase::SENSITIVE)) { prefix_length = strlen(prefix); break; } } if (prefix_length > 0) { a += prefix_length; std::string switch_name = base::ToLowerASCII(base::StringPiece(a, strcspn(a, ""=""))); auto* iter = std::lower_bound(std::begin(kBlacklist), std::end(kBlacklist), switch_name); if (iter != std::end(kBlacklist) && switch_name == *iter) { return true; } } return false; }","{'deleted': [{'line_no': 21, 'char_start': 500, 'char_end': 549, 'line': ' std::string switch_name(a, strcspn(a, ""=""));\n'}], 'added': [{'line_no': 21, 'char_start': 500, 'char_end': 530, 'line': ' std::string switch_name =\n'}, {'line_no': 22, 'char_start': 530, 'char_end': 597, 'line': ' base::ToLowerASCII(base::StringPiece(a, strcspn(a, ""="")));\n'}]}","{'deleted': [], 'added': [{'char_start': 527, 'char_end': 574, 'chars': ' =\n base::ToLowerASCII(base::StringPiece'}, {'char_start': 592, 'char_end': 593, 'chars': ')'}]}",github.com/electron/electron/commit/ce361a12e355f9e1e99c989f1ea056c9e502dbe7,atom/app/command_line_args.cc,cwe-078,214 cwe-022,cut," def cut(self, key): try: self.etcd.delete(os.path.join(self.namespace, key)) except etcd.EtcdKeyNotFound: return False except etcd.EtcdException as err: log_error(""Error removing key %s: [%r]"" % (key, repr(err))) raise CSStoreError('Error occurred while trying to cut key') return True"," def cut(self, key): try: self.etcd.delete(self._absolute_key(key)) except etcd.EtcdKeyNotFound: return False except etcd.EtcdException as err: log_error(""Error removing key %s: [%r]"" % (key, repr(err))) raise CSStoreError('Error occurred while trying to cut key') return True","{'deleted': [{'line_no': 3, 'char_start': 37, 'char_end': 101, 'line': ' self.etcd.delete(os.path.join(self.namespace, key))\n'}], 'added': [{'line_no': 3, 'char_start': 37, 'char_end': 91, 'line': ' self.etcd.delete(self._absolute_key(key))\n'}]}","{'deleted': [{'char_start': 66, 'char_end': 79, 'chars': 'os.path.join('}, {'char_start': 84, 'char_end': 85, 'chars': 'n'}, {'char_start': 86, 'char_end': 88, 'chars': 'me'}, {'char_start': 89, 'char_end': 92, 'chars': 'pac'}, {'char_start': 93, 'char_end': 95, 'chars': ', '}], 'added': [{'char_start': 71, 'char_end': 72, 'chars': '_'}, {'char_start': 73, 'char_end': 79, 'chars': 'bsolut'}, {'char_start': 80, 'char_end': 82, 'chars': '_k'}, {'char_start': 83, 'char_end': 85, 'chars': 'y('}]}",github.com/latchset/custodia/commit/785fc87f38b4811bc4ce43a0a9b2267ee7d500b4,custodia/store/etcdstore.py,cwe-022,85 cwe-078,mkdir," def mkdir(self, data, path): credentials = self._formatCredentials(data, name='current') command = ( '{credentials} ' 'rclone touch current:{path}/.keep' ).format( credentials=credentials, path=path, ) try: result = self._execute(command) return { 'message': 'Success', } except subprocess.CalledProcessError as e: raise RcloneException(sanitize(str(e)))"," def mkdir(self, data, path): credentials = self._formatCredentials(data, name='current') command = [ 'rclone', 'touch', 'current:{}/.keep'.format(path), ] try: result = self._execute(command, credentials) return { 'message': 'Success', } except subprocess.CalledProcessError as e: raise RcloneException(sanitize(str(e)))","{'deleted': [{'line_no': 3, 'char_start': 101, 'char_end': 102, 'line': '\n'}, {'line_no': 4, 'char_start': 102, 'char_end': 122, 'line': ' command = (\n'}, {'line_no': 5, 'char_start': 122, 'char_end': 151, 'line': "" '{credentials} '\n""}, {'line_no': 6, 'char_start': 151, 'char_end': 199, 'line': "" 'rclone touch current:{path}/.keep'\n""}, {'line_no': 7, 'char_start': 199, 'char_end': 217, 'line': ' ).format(\n'}, {'line_no': 8, 'char_start': 217, 'char_end': 254, 'line': ' credentials=credentials,\n'}, {'line_no': 9, 'char_start': 254, 'char_end': 277, 'line': ' path=path,\n'}, {'line_no': 10, 'char_start': 277, 'char_end': 287, 'line': ' )\n'}, {'line_no': 13, 'char_start': 301, 'char_end': 345, 'line': ' result = self._execute(command)\n'}], 'added': [{'line_no': 3, 'char_start': 101, 'char_end': 121, 'line': ' command = [\n'}, {'line_no': 4, 'char_start': 121, 'char_end': 143, 'line': "" 'rclone',\n""}, {'line_no': 5, 'char_start': 143, 'char_end': 164, 'line': "" 'touch',\n""}, {'line_no': 6, 'char_start': 164, 'char_end': 209, 'line': "" 'current:{}/.keep'.format(path),\n""}, {'line_no': 7, 'char_start': 209, 'char_end': 219, 'line': ' ]\n'}, {'line_no': 10, 'char_start': 233, 'char_end': 290, 'line': ' result = self._execute(command, credentials)\n'}]}","{'deleted': [{'char_start': 101, 'char_end': 102, 'chars': '\n'}, {'char_start': 120, 'char_end': 121, 'chars': '('}, {'char_start': 135, 'char_end': 137, 'chars': '{c'}, {'char_start': 138, 'char_end': 145, 'chars': 'edentia'}, {'char_start': 146, 'char_end': 149, 'chars': 's} '}, {'char_start': 164, 'char_end': 171, 'chars': 'rclone '}, {'char_start': 186, 'char_end': 190, 'chars': 'path'}, {'char_start': 198, 'char_end': 208, 'chars': '\n )'}, {'char_start': 216, 'char_end': 266, 'chars': '\n credentials=credentials,\n '}, {'char_start': 270, 'char_end': 275, 'chars': '=path'}, {'char_start': 285, 'char_end': 286, 'chars': ')'}], 'added': [{'char_start': 119, 'char_end': 120, 'chars': '['}, {'char_start': 134, 'char_end': 135, 'chars': 'r'}, {'char_start': 136, 'char_end': 139, 'chars': 'lon'}, {'char_start': 141, 'char_end': 142, 'chars': ','}, {'char_start': 161, 'char_end': 166, 'chars': ""',\n ""}, {'char_start': 167, 'char_end': 177, 'chars': "" '""}, {'char_start': 206, 'char_end': 207, 'chars': ')'}, {'char_start': 217, 'char_end': 218, 'chars': ']'}, {'char_start': 275, 'char_end': 288, 'chars': ', credentials'}]}",github.com/FredHutch/motuz/commit/045468cb9bff47bb3bb72268b6d5a3fe44e383db,src/backend/api/utils/rclone_connection.py,cwe-078,101 cwe-416,Magick::Image::read,"void Magick::Image::read(MagickCore::Image *image, MagickCore::ExceptionInfo *exceptionInfo) { // Ensure that multiple image frames were not read. if (image != (MagickCore::Image *) NULL && image->next != (MagickCore::Image *) NULL) { MagickCore::Image *next; // Destroy any extra image frames next=image->next; image->next=(MagickCore::Image *) NULL; next->previous=(MagickCore::Image *) NULL; DestroyImageList(next); } replaceImage(image); if (exceptionInfo->severity == MagickCore::UndefinedException && image == (MagickCore::Image *) NULL) { (void) MagickCore::DestroyExceptionInfo(exceptionInfo); if (!quiet()) throwExceptionExplicit(MagickCore::ImageWarning, ""No image was loaded.""); } ThrowImageException; }","void Magick::Image::read(MagickCore::Image *image, MagickCore::ExceptionInfo *exceptionInfo) { // Ensure that multiple image frames were not read. if (image != (MagickCore::Image *) NULL && image->next != (MagickCore::Image *) NULL) { MagickCore::Image *next; // Destroy any extra image frames next=image->next; image->next=(MagickCore::Image *) NULL; next->previous=(MagickCore::Image *) NULL; DestroyImageList(next); } replaceImage(image); if (exceptionInfo->severity == MagickCore::UndefinedException && image == (MagickCore::Image *) NULL) { (void) MagickCore::DestroyExceptionInfo(exceptionInfo); if (!quiet()) throwExceptionExplicit(MagickCore::ImageWarning, ""No image was loaded.""); return; } ThrowImageException; }","{'deleted': [], 'added': [{'line_no': 25, 'char_start': 799, 'char_end': 813, 'line': ' return;\n'}]}","{'deleted': [], 'added': [{'char_start': 803, 'char_end': 817, 'chars': ' return;\n '}]}",github.com/ImageMagick/ImageMagick/commit/8c35502217c1879cb8257c617007282eee3fe1cc,Magick++/lib/Image.cpp,cwe-416,203 cwe-787,WritePSDChannel,"static size_t WritePSDChannel(const PSDInfo *psd_info, const ImageInfo *image_info,Image *image,Image *next_image, const QuantumType quantum_type, unsigned char *compact_pixels, MagickOffsetType size_offset,const MagickBooleanType separate, ExceptionInfo *exception) { int y; MagickBooleanType monochrome; QuantumInfo *quantum_info; register const Quantum *p; register ssize_t i; size_t count, length; unsigned char *pixels; #ifdef MAGICKCORE_ZLIB_DELEGATE #define CHUNK 16384 int flush, level; unsigned char *compressed_pixels; z_stream stream; compressed_pixels=(unsigned char *) NULL; flush=Z_NO_FLUSH; #endif count=0; if (separate != MagickFalse) { size_offset=TellBlob(image)+2; count+=WriteCompressionStart(psd_info,image,next_image,1); } if (next_image->depth > 8) next_image->depth=16; monochrome=IsImageMonochrome(image) && (image->depth == 1) ? MagickTrue : MagickFalse; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) return(0); pixels=(unsigned char *) GetQuantumPixels(quantum_info); #ifdef MAGICKCORE_ZLIB_DELEGATE if (next_image->compression == ZipCompression) { compressed_pixels=(unsigned char *) AcquireQuantumMemory(CHUNK, sizeof(*compressed_pixels)); if (compressed_pixels == (unsigned char *) NULL) { quantum_info=DestroyQuantumInfo(quantum_info); return(0); } ResetMagickMemory(&stream,0,sizeof(stream)); stream.data_type=Z_BINARY; level=Z_DEFAULT_COMPRESSION; if ((image_info->quality > 0 && image_info->quality < 10)) level=(int) image_info->quality; if (deflateInit(&stream,level) != Z_OK) { quantum_info=DestroyQuantumInfo(quantum_info); return(0); } } #endif for (y=0; y < (ssize_t) next_image->rows; y++) { p=GetVirtualPixels(next_image,0,y,next_image->columns,1,exception); if (p == (const Quantum *) NULL) break; length=ExportQuantumPixels(next_image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); if (monochrome != MagickFalse) for (i=0; i < (ssize_t) length; i++) pixels[i]=(~pixels[i]); if (next_image->compression == RLECompression) { length=PSDPackbitsEncodeImage(image,length,pixels,compact_pixels, exception); count+=WriteBlob(image,length,compact_pixels); size_offset+=WritePSDOffset(psd_info,image,length,size_offset); } #ifdef MAGICKCORE_ZLIB_DELEGATE else if (next_image->compression == ZipCompression) { stream.avail_in=(uInt) length; stream.next_in=(Bytef *) pixels; if (y == (ssize_t) next_image->rows-1) flush=Z_FINISH; do { stream.avail_out=(uInt) CHUNK; stream.next_out=(Bytef *) compressed_pixels; if (deflate(&stream,flush) == Z_STREAM_ERROR) break; length=(size_t) CHUNK-stream.avail_out; if (length > 0) count+=WriteBlob(image,length,compressed_pixels); } while (stream.avail_out == 0); } #endif else count+=WriteBlob(image,length,pixels); } #ifdef MAGICKCORE_ZLIB_DELEGATE if (next_image->compression == ZipCompression) { (void) deflateEnd(&stream); compressed_pixels=(unsigned char *) RelinquishMagickMemory( compressed_pixels); } #endif quantum_info=DestroyQuantumInfo(quantum_info); return(count); }","static size_t WritePSDChannel(const PSDInfo *psd_info, const ImageInfo *image_info,Image *image,Image *next_image, const QuantumType quantum_type, unsigned char *compact_pixels, MagickOffsetType size_offset,const MagickBooleanType separate, ExceptionInfo *exception) { int y; MagickBooleanType monochrome; QuantumInfo *quantum_info; register const Quantum *p; register ssize_t i; size_t count, length; unsigned char *pixels; #ifdef MAGICKCORE_ZLIB_DELEGATE #define CHUNK 16384 int flush, level; unsigned char *compressed_pixels; z_stream stream; compressed_pixels=(unsigned char *) NULL; flush=Z_NO_FLUSH; #endif count=0; if (separate != MagickFalse) { size_offset=TellBlob(image)+2; count+=WriteCompressionStart(psd_info,image,next_image,1); } if (next_image->depth > 8) next_image->depth=16; monochrome=IsImageMonochrome(image) && (image->depth == 1) ? MagickTrue : MagickFalse; quantum_info=AcquireQuantumInfo(image_info,next_image); if (quantum_info == (QuantumInfo *) NULL) return(0); pixels=(unsigned char *) GetQuantumPixels(quantum_info); #ifdef MAGICKCORE_ZLIB_DELEGATE if (next_image->compression == ZipCompression) { compressed_pixels=(unsigned char *) AcquireQuantumMemory(CHUNK, sizeof(*compressed_pixels)); if (compressed_pixels == (unsigned char *) NULL) { quantum_info=DestroyQuantumInfo(quantum_info); return(0); } ResetMagickMemory(&stream,0,sizeof(stream)); stream.data_type=Z_BINARY; level=Z_DEFAULT_COMPRESSION; if ((image_info->quality > 0 && image_info->quality < 10)) level=(int) image_info->quality; if (deflateInit(&stream,level) != Z_OK) { quantum_info=DestroyQuantumInfo(quantum_info); return(0); } } #endif for (y=0; y < (ssize_t) next_image->rows; y++) { p=GetVirtualPixels(next_image,0,y,next_image->columns,1,exception); if (p == (const Quantum *) NULL) break; length=ExportQuantumPixels(next_image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); if (monochrome != MagickFalse) for (i=0; i < (ssize_t) length; i++) pixels[i]=(~pixels[i]); if (next_image->compression == RLECompression) { length=PSDPackbitsEncodeImage(image,length,pixels,compact_pixels, exception); count+=WriteBlob(image,length,compact_pixels); size_offset+=WritePSDOffset(psd_info,image,length,size_offset); } #ifdef MAGICKCORE_ZLIB_DELEGATE else if (next_image->compression == ZipCompression) { stream.avail_in=(uInt) length; stream.next_in=(Bytef *) pixels; if (y == (ssize_t) next_image->rows-1) flush=Z_FINISH; do { stream.avail_out=(uInt) CHUNK; stream.next_out=(Bytef *) compressed_pixels; if (deflate(&stream,flush) == Z_STREAM_ERROR) break; length=(size_t) CHUNK-stream.avail_out; if (length > 0) count+=WriteBlob(image,length,compressed_pixels); } while (stream.avail_out == 0); } #endif else count+=WriteBlob(image,length,pixels); } #ifdef MAGICKCORE_ZLIB_DELEGATE if (next_image->compression == ZipCompression) { (void) deflateEnd(&stream); compressed_pixels=(unsigned char *) RelinquishMagickMemory( compressed_pixels); } #endif quantum_info=DestroyQuantumInfo(quantum_info); return(count); }","{'deleted': [{'line_no': 56, 'char_start': 1009, 'char_end': 1062, 'line': ' quantum_info=AcquireQuantumInfo(image_info,image);\n'}], 'added': [{'line_no': 56, 'char_start': 1009, 'char_end': 1067, 'line': ' quantum_info=AcquireQuantumInfo(image_info,next_image);\n'}]}","{'deleted': [], 'added': [{'char_start': 1054, 'char_end': 1059, 'chars': 'next_'}]}",github.com/ImageMagick/ImageMagick/commit/91cc3f36f2ccbd485a0456bab9aebe63b635da88,coders/psd.c,cwe-787,924 cwe-190,SWFInput_readSBits,"SWFInput_readSBits(SWFInput input, int number) { int num = SWFInput_readBits(input, number); if ( num & (1<<(number-1)) ) return num - (1<=szd || !CLI_ISCONTAINED(exe, exesz, ucur, 1)) error=1; else *ucur++=*ccur++; continue; } BITS(2); if(bits==3) { /* WORD backcopy */ uint8_t shifted, subbed = 31; BITS(2); shifted = bits + 5; if(bits>=2) { shifted++; subbed += 0x80; } backbytes = (1< exesz || pe+7 > exesz || pe+0x28 > exesz || pe+0x50 > exesz || pe+0x14 > exesz) return CL_EFORMAT; exe[pe+6]=(uint8_t)scount; exe[pe+7]=(uint8_t)(scount>>8); cli_writeint32(&exe[pe+0x28], cli_readint32(wwsect+0x295)+sects[scount].rva+0x299); cli_writeint32(&exe[pe+0x50], cli_readint32(&exe[pe+0x50])-sects[scount].vsz); structs = &exe[(0xffff&cli_readint32(&exe[pe+0x14]))+pe+0x18]; for(i=0 ; i=szd || !CLI_ISCONTAINED(exe, exesz, ucur, 1)) error=1; else *ucur++=*ccur++; continue; } BITS(2); if(bits==3) { /* WORD backcopy */ uint8_t shifted, subbed = 31; BITS(2); shifted = bits + 5; if(bits>=2) { shifted++; subbed += 0x80; } backbytes = (1< exesz || pe+7 > exesz || pe+0x28 > exesz || pe+0x50 > exesz || pe+0x14 > exesz) return CL_EFORMAT; exe[pe+6]=(uint8_t)scount; exe[pe+7]=(uint8_t)(scount>>8); if (!CLI_ISCONTAINED(wwsect, sects[scount].rsz, wwsect+0x295, 4) || !CLI_ISCONTAINED(wwsect, sects[scount].rsz, wwsect+0x295+sects[scount].rva, 4) || !CLI_ISCONTAINED(wwsect, sects[scount].rsz, wwsect+0x295+sects[scount].rva+0x299, 4)) { cli_dbgmsg(""WWPack: unpack memory address out of bounds.\n""); return CL_EFORMAT; } cli_writeint32(&exe[pe+0x28], cli_readint32(wwsect+0x295)+sects[scount].rva+0x299); cli_writeint32(&exe[pe+0x50], cli_readint32(&exe[pe+0x50])-sects[scount].vsz); structs = &exe[(0xffff&cli_readint32(&exe[pe+0x14]))+pe+0x18]; for(i=0 ; ifd = mrb_dup(mrb, fptr_orig->fd, &failed); if (failed) { mrb_sys_fail(mrb, 0); } mrb_fd_cloexec(mrb, fptr_copy->fd); if (fptr_orig->fd2 != -1) { fptr_copy->fd2 = mrb_dup(mrb, fptr_orig->fd2, &failed); if (failed) { close(fptr_copy->fd); mrb_sys_fail(mrb, 0); } mrb_fd_cloexec(mrb, fptr_copy->fd2); } fptr_copy->pid = fptr_orig->pid; fptr_copy->readable = fptr_orig->readable; fptr_copy->writable = fptr_orig->writable; fptr_copy->sync = fptr_orig->sync; fptr_copy->is_socket = fptr_orig->is_socket; return copy; }","mrb_io_initialize_copy(mrb_state *mrb, mrb_value copy) { mrb_value orig; mrb_value buf; struct mrb_io *fptr_copy; struct mrb_io *fptr_orig; mrb_bool failed = TRUE; mrb_get_args(mrb, ""o"", &orig); fptr_orig = io_get_open_fptr(mrb, orig); fptr_copy = (struct mrb_io *)DATA_PTR(copy); if (fptr_copy != NULL) { fptr_finalize(mrb, fptr_copy, FALSE); mrb_free(mrb, fptr_copy); } fptr_copy = (struct mrb_io *)mrb_io_alloc(mrb); DATA_TYPE(copy) = &mrb_io_type; DATA_PTR(copy) = fptr_copy; buf = mrb_iv_get(mrb, orig, mrb_intern_cstr(mrb, ""@buf"")); mrb_iv_set(mrb, copy, mrb_intern_cstr(mrb, ""@buf""), buf); fptr_copy->fd = mrb_dup(mrb, fptr_orig->fd, &failed); if (failed) { mrb_sys_fail(mrb, 0); } mrb_fd_cloexec(mrb, fptr_copy->fd); if (fptr_orig->fd2 != -1) { fptr_copy->fd2 = mrb_dup(mrb, fptr_orig->fd2, &failed); if (failed) { close(fptr_copy->fd); mrb_sys_fail(mrb, 0); } mrb_fd_cloexec(mrb, fptr_copy->fd2); } fptr_copy->pid = fptr_orig->pid; fptr_copy->readable = fptr_orig->readable; fptr_copy->writable = fptr_orig->writable; fptr_copy->sync = fptr_orig->sync; fptr_copy->is_socket = fptr_orig->is_socket; return copy; }","{'deleted': [{'line_no': 16, 'char_start': 408, 'char_end': 451, 'line': ' fptr_orig = io_get_open_fptr(mrb, orig);\n'}], 'added': [{'line_no': 10, 'char_start': 208, 'char_end': 251, 'line': ' fptr_orig = io_get_open_fptr(mrb, orig);\n'}]}","{'deleted': [{'char_start': 405, 'char_end': 448, 'chars': ');\n fptr_orig = io_get_open_fptr(mrb, orig'}], 'added': [{'char_start': 215, 'char_end': 258, 'chars': 'orig = io_get_open_fptr(mrb, orig);\n fptr_'}]}",github.com/mruby/mruby/commit/b51b21fc63c9805862322551387d9036f2b63433,mrbgems/mruby-io/src/io.c,cwe-416,423 cwe-787,opj_pi_create_decode,"opj_pi_iterator_t *opj_pi_create_decode(opj_image_t *p_image, opj_cp_t *p_cp, OPJ_UINT32 p_tile_no) { /* loop */ OPJ_UINT32 pino; OPJ_UINT32 compno, resno; /* to store w, h, dx and dy fro all components and resolutions */ OPJ_UINT32 * l_tmp_data; OPJ_UINT32 ** l_tmp_ptr; /* encoding prameters to set */ OPJ_UINT32 l_max_res; OPJ_UINT32 l_max_prec; OPJ_INT32 l_tx0,l_tx1,l_ty0,l_ty1; OPJ_UINT32 l_dx_min,l_dy_min; OPJ_UINT32 l_bound; OPJ_UINT32 l_step_p , l_step_c , l_step_r , l_step_l ; OPJ_UINT32 l_data_stride; /* pointers */ opj_pi_iterator_t *l_pi = 00; opj_tcp_t *l_tcp = 00; const opj_tccp_t *l_tccp = 00; opj_pi_comp_t *l_current_comp = 00; opj_image_comp_t * l_img_comp = 00; opj_pi_iterator_t * l_current_pi = 00; OPJ_UINT32 * l_encoding_value_ptr = 00; /* preconditions in debug */ assert(p_cp != 00); assert(p_image != 00); assert(p_tile_no < p_cp->tw * p_cp->th); /* initializations */ l_tcp = &p_cp->tcps[p_tile_no]; l_bound = l_tcp->numpocs+1; l_data_stride = 4 * OPJ_J2K_MAXRLVLS; l_tmp_data = (OPJ_UINT32*)opj_malloc( l_data_stride * p_image->numcomps * sizeof(OPJ_UINT32)); if (! l_tmp_data) { return 00; } l_tmp_ptr = (OPJ_UINT32**)opj_malloc( p_image->numcomps * sizeof(OPJ_UINT32 *)); if (! l_tmp_ptr) { opj_free(l_tmp_data); return 00; } /* memory allocation for pi */ l_pi = opj_pi_create(p_image, p_cp, p_tile_no); if (!l_pi) { opj_free(l_tmp_data); opj_free(l_tmp_ptr); return 00; } l_encoding_value_ptr = l_tmp_data; /* update pointer array */ for (compno = 0; compno < p_image->numcomps; ++compno) { l_tmp_ptr[compno] = l_encoding_value_ptr; l_encoding_value_ptr += l_data_stride; } /* get encoding parameters */ opj_get_all_encoding_parameters(p_image,p_cp,p_tile_no,&l_tx0,&l_tx1,&l_ty0,&l_ty1,&l_dx_min,&l_dy_min,&l_max_prec,&l_max_res,l_tmp_ptr); /* step calculations */ l_step_p = 1; l_step_c = l_max_prec * l_step_p; l_step_r = p_image->numcomps * l_step_c; l_step_l = l_max_res * l_step_r; /* set values for first packet iterator */ l_current_pi = l_pi; /* memory allocation for include */ l_current_pi->include = (OPJ_INT16*) opj_calloc((l_tcp->numlayers +1) * l_step_l, sizeof(OPJ_INT16)); if (!l_current_pi->include) { opj_free(l_tmp_data); opj_free(l_tmp_ptr); opj_pi_destroy(l_pi, l_bound); return 00; } /* special treatment for the first packet iterator */ l_current_comp = l_current_pi->comps; l_img_comp = p_image->comps; l_tccp = l_tcp->tccps; l_current_pi->tx0 = l_tx0; l_current_pi->ty0 = l_ty0; l_current_pi->tx1 = l_tx1; l_current_pi->ty1 = l_ty1; /*l_current_pi->dx = l_img_comp->dx;*/ /*l_current_pi->dy = l_img_comp->dy;*/ l_current_pi->step_p = l_step_p; l_current_pi->step_c = l_step_c; l_current_pi->step_r = l_step_r; l_current_pi->step_l = l_step_l; /* allocation for components and number of components has already been calculated by opj_pi_create */ for (compno = 0; compno < l_current_pi->numcomps; ++compno) { opj_pi_resolution_t *l_res = l_current_comp->resolutions; l_encoding_value_ptr = l_tmp_ptr[compno]; l_current_comp->dx = l_img_comp->dx; l_current_comp->dy = l_img_comp->dy; /* resolutions have already been initialized */ for (resno = 0; resno < l_current_comp->numresolutions; resno++) { l_res->pdx = *(l_encoding_value_ptr++); l_res->pdy = *(l_encoding_value_ptr++); l_res->pw = *(l_encoding_value_ptr++); l_res->ph = *(l_encoding_value_ptr++); ++l_res; } ++l_current_comp; ++l_img_comp; ++l_tccp; } ++l_current_pi; for (pino = 1 ; pinocomps; l_img_comp = p_image->comps; l_tccp = l_tcp->tccps; l_current_pi->tx0 = l_tx0; l_current_pi->ty0 = l_ty0; l_current_pi->tx1 = l_tx1; l_current_pi->ty1 = l_ty1; /*l_current_pi->dx = l_dx_min;*/ /*l_current_pi->dy = l_dy_min;*/ l_current_pi->step_p = l_step_p; l_current_pi->step_c = l_step_c; l_current_pi->step_r = l_step_r; l_current_pi->step_l = l_step_l; /* allocation for components and number of components has already been calculated by opj_pi_create */ for (compno = 0; compno < l_current_pi->numcomps; ++compno) { opj_pi_resolution_t *l_res = l_current_comp->resolutions; l_encoding_value_ptr = l_tmp_ptr[compno]; l_current_comp->dx = l_img_comp->dx; l_current_comp->dy = l_img_comp->dy; /* resolutions have already been initialized */ for (resno = 0; resno < l_current_comp->numresolutions; resno++) { l_res->pdx = *(l_encoding_value_ptr++); l_res->pdy = *(l_encoding_value_ptr++); l_res->pw = *(l_encoding_value_ptr++); l_res->ph = *(l_encoding_value_ptr++); ++l_res; } ++l_current_comp; ++l_img_comp; ++l_tccp; } /* special treatment*/ l_current_pi->include = (l_current_pi-1)->include; ++l_current_pi; } opj_free(l_tmp_data); l_tmp_data = 00; opj_free(l_tmp_ptr); l_tmp_ptr = 00; if (l_tcp->POC) { opj_pi_update_decode_poc (l_pi,l_tcp,l_max_prec,l_max_res); } else { opj_pi_update_decode_not_poc(l_pi,l_tcp,l_max_prec,l_max_res); } return l_pi; }","opj_pi_iterator_t *opj_pi_create_decode(opj_image_t *p_image, opj_cp_t *p_cp, OPJ_UINT32 p_tile_no) { /* loop */ OPJ_UINT32 pino; OPJ_UINT32 compno, resno; /* to store w, h, dx and dy fro all components and resolutions */ OPJ_UINT32 * l_tmp_data; OPJ_UINT32 ** l_tmp_ptr; /* encoding prameters to set */ OPJ_UINT32 l_max_res; OPJ_UINT32 l_max_prec; OPJ_INT32 l_tx0,l_tx1,l_ty0,l_ty1; OPJ_UINT32 l_dx_min,l_dy_min; OPJ_UINT32 l_bound; OPJ_UINT32 l_step_p , l_step_c , l_step_r , l_step_l ; OPJ_UINT32 l_data_stride; /* pointers */ opj_pi_iterator_t *l_pi = 00; opj_tcp_t *l_tcp = 00; const opj_tccp_t *l_tccp = 00; opj_pi_comp_t *l_current_comp = 00; opj_image_comp_t * l_img_comp = 00; opj_pi_iterator_t * l_current_pi = 00; OPJ_UINT32 * l_encoding_value_ptr = 00; /* preconditions in debug */ assert(p_cp != 00); assert(p_image != 00); assert(p_tile_no < p_cp->tw * p_cp->th); /* initializations */ l_tcp = &p_cp->tcps[p_tile_no]; l_bound = l_tcp->numpocs+1; l_data_stride = 4 * OPJ_J2K_MAXRLVLS; l_tmp_data = (OPJ_UINT32*)opj_malloc( l_data_stride * p_image->numcomps * sizeof(OPJ_UINT32)); if (! l_tmp_data) { return 00; } l_tmp_ptr = (OPJ_UINT32**)opj_malloc( p_image->numcomps * sizeof(OPJ_UINT32 *)); if (! l_tmp_ptr) { opj_free(l_tmp_data); return 00; } /* memory allocation for pi */ l_pi = opj_pi_create(p_image, p_cp, p_tile_no); if (!l_pi) { opj_free(l_tmp_data); opj_free(l_tmp_ptr); return 00; } l_encoding_value_ptr = l_tmp_data; /* update pointer array */ for (compno = 0; compno < p_image->numcomps; ++compno) { l_tmp_ptr[compno] = l_encoding_value_ptr; l_encoding_value_ptr += l_data_stride; } /* get encoding parameters */ opj_get_all_encoding_parameters(p_image,p_cp,p_tile_no,&l_tx0,&l_tx1,&l_ty0,&l_ty1,&l_dx_min,&l_dy_min,&l_max_prec,&l_max_res,l_tmp_ptr); /* step calculations */ l_step_p = 1; l_step_c = l_max_prec * l_step_p; l_step_r = p_image->numcomps * l_step_c; l_step_l = l_max_res * l_step_r; /* set values for first packet iterator */ l_current_pi = l_pi; /* memory allocation for include */ /* prevent an integer overflow issue */ l_current_pi->include = 00; if (l_step_l <= (SIZE_MAX / (l_tcp->numlayers + 1U))) { l_current_pi->include = (OPJ_INT16*) opj_calloc((l_tcp->numlayers +1) * l_step_l, sizeof(OPJ_INT16)); } if (!l_current_pi->include) { opj_free(l_tmp_data); opj_free(l_tmp_ptr); opj_pi_destroy(l_pi, l_bound); return 00; } /* special treatment for the first packet iterator */ l_current_comp = l_current_pi->comps; l_img_comp = p_image->comps; l_tccp = l_tcp->tccps; l_current_pi->tx0 = l_tx0; l_current_pi->ty0 = l_ty0; l_current_pi->tx1 = l_tx1; l_current_pi->ty1 = l_ty1; /*l_current_pi->dx = l_img_comp->dx;*/ /*l_current_pi->dy = l_img_comp->dy;*/ l_current_pi->step_p = l_step_p; l_current_pi->step_c = l_step_c; l_current_pi->step_r = l_step_r; l_current_pi->step_l = l_step_l; /* allocation for components and number of components has already been calculated by opj_pi_create */ for (compno = 0; compno < l_current_pi->numcomps; ++compno) { opj_pi_resolution_t *l_res = l_current_comp->resolutions; l_encoding_value_ptr = l_tmp_ptr[compno]; l_current_comp->dx = l_img_comp->dx; l_current_comp->dy = l_img_comp->dy; /* resolutions have already been initialized */ for (resno = 0; resno < l_current_comp->numresolutions; resno++) { l_res->pdx = *(l_encoding_value_ptr++); l_res->pdy = *(l_encoding_value_ptr++); l_res->pw = *(l_encoding_value_ptr++); l_res->ph = *(l_encoding_value_ptr++); ++l_res; } ++l_current_comp; ++l_img_comp; ++l_tccp; } ++l_current_pi; for (pino = 1 ; pinocomps; l_img_comp = p_image->comps; l_tccp = l_tcp->tccps; l_current_pi->tx0 = l_tx0; l_current_pi->ty0 = l_ty0; l_current_pi->tx1 = l_tx1; l_current_pi->ty1 = l_ty1; /*l_current_pi->dx = l_dx_min;*/ /*l_current_pi->dy = l_dy_min;*/ l_current_pi->step_p = l_step_p; l_current_pi->step_c = l_step_c; l_current_pi->step_r = l_step_r; l_current_pi->step_l = l_step_l; /* allocation for components and number of components has already been calculated by opj_pi_create */ for (compno = 0; compno < l_current_pi->numcomps; ++compno) { opj_pi_resolution_t *l_res = l_current_comp->resolutions; l_encoding_value_ptr = l_tmp_ptr[compno]; l_current_comp->dx = l_img_comp->dx; l_current_comp->dy = l_img_comp->dy; /* resolutions have already been initialized */ for (resno = 0; resno < l_current_comp->numresolutions; resno++) { l_res->pdx = *(l_encoding_value_ptr++); l_res->pdy = *(l_encoding_value_ptr++); l_res->pw = *(l_encoding_value_ptr++); l_res->ph = *(l_encoding_value_ptr++); ++l_res; } ++l_current_comp; ++l_img_comp; ++l_tccp; } /* special treatment*/ l_current_pi->include = (l_current_pi-1)->include; ++l_current_pi; } opj_free(l_tmp_data); l_tmp_data = 00; opj_free(l_tmp_ptr); l_tmp_ptr = 00; if (l_tcp->POC) { opj_pi_update_decode_poc (l_pi,l_tcp,l_max_prec,l_max_res); } else { opj_pi_update_decode_not_poc(l_pi,l_tcp,l_max_prec,l_max_res); } return l_pi; }","{'deleted': [{'line_no': 86, 'char_start': 2139, 'char_end': 2242, 'line': '\tl_current_pi->include = (OPJ_INT16*) opj_calloc((l_tcp->numlayers +1) * l_step_l, sizeof(OPJ_INT16));\n'}], 'added': [{'line_no': 86, 'char_start': 2139, 'char_end': 2180, 'line': '\t/* prevent an integer overflow issue */\n'}, {'line_no': 87, 'char_start': 2180, 'char_end': 2209, 'line': '\tl_current_pi->include = 00;\n'}, {'line_no': 88, 'char_start': 2209, 'char_end': 2264, 'line': '\tif (l_step_l <= (SIZE_MAX / (l_tcp->numlayers + 1U)))\n'}, {'line_no': 89, 'char_start': 2264, 'char_end': 2267, 'line': '\t{\n'}, {'line_no': 90, 'char_start': 2267, 'char_end': 2371, 'line': '\t\tl_current_pi->include = (OPJ_INT16*) opj_calloc((l_tcp->numlayers +1) * l_step_l, sizeof(OPJ_INT16));\n'}, {'line_no': 91, 'char_start': 2371, 'char_end': 2374, 'line': '\t}\n'}, {'line_no': 92, 'char_start': 2374, 'char_end': 2375, 'line': '\n'}]}","{'deleted': [], 'added': [{'char_start': 2140, 'char_end': 2269, 'chars': '/* prevent an integer overflow issue */\n\tl_current_pi->include = 00;\n\tif (l_step_l <= (SIZE_MAX / (l_tcp->numlayers + 1U)))\n\t{\n\t\t'}, {'char_start': 2370, 'char_end': 2374, 'chars': '\n\t}\n'}]}",github.com/uclouvain/openjpeg/commit/c16bc057ba3f125051c9966cf1f5b68a05681de4,src/lib/openjp2/pi.c,cwe-787,1762 cwe-078,fetch,"def fetch(url): '''Download and verify a package url.''' base = os.path.basename(url) print('Fetching %s...' % base) fetch_file(url + '.asc') fetch_file(url) fetch_file(url + '.sha256') fetch_file(url + '.asc.sha256') print('Verifying %s...' % base) # TODO: check for verification failure. os.system('shasum -c %s.sha256' % base) os.system('shasum -c %s.asc.sha256' % base) os.system('gpg --verify %s.asc %s' % (base, base)) os.system('keybase verify %s.asc' % base)","def fetch(url): '''Download and verify a package url.''' base = os.path.basename(url) print('Fetching %s...' % base) fetch_file(url + '.asc') fetch_file(url) fetch_file(url + '.sha256') fetch_file(url + '.asc.sha256') print('Verifying %s...' % base) # TODO: check for verification failure. subprocess.check_call(['shasum', '-c', base + '.sha256']) subprocess.check_call(['shasum', '-c', base + '.asc.sha256']) subprocess.check_call(['gpg', '--verify', base + '.asc', base]) subprocess.check_call(['keybase', 'verify', base + '.asc'])","{'deleted': [{'line_no': 11, 'char_start': 308, 'char_end': 350, 'line': "" os.system('shasum -c %s.sha256' % base)\n""}, {'line_no': 12, 'char_start': 350, 'char_end': 396, 'line': "" os.system('shasum -c %s.asc.sha256' % base)\n""}, {'line_no': 13, 'char_start': 396, 'char_end': 449, 'line': "" os.system('gpg --verify %s.asc %s' % (base, base))\n""}, {'line_no': 14, 'char_start': 449, 'char_end': 492, 'line': "" os.system('keybase verify %s.asc' % base)\n""}], 'added': [{'line_no': 11, 'char_start': 308, 'char_end': 368, 'line': "" subprocess.check_call(['shasum', '-c', base + '.sha256'])\n""}, {'line_no': 12, 'char_start': 368, 'char_end': 432, 'line': "" subprocess.check_call(['shasum', '-c', base + '.asc.sha256'])\n""}, {'line_no': 13, 'char_start': 432, 'char_end': 498, 'line': "" subprocess.check_call(['gpg', '--verify', base + '.asc', base])\n""}, {'line_no': 14, 'char_start': 498, 'char_end': 559, 'line': "" subprocess.check_call(['keybase', 'verify', base + '.asc'])\n""}]}","{'deleted': [{'char_start': 312, 'char_end': 313, 'chars': '.'}, {'char_start': 314, 'char_end': 317, 'chars': 'yst'}, {'char_start': 318, 'char_end': 319, 'chars': 'm'}, {'char_start': 331, 'char_end': 332, 'chars': '%'}, {'char_start': 341, 'char_end': 348, 'chars': ' % base'}, {'char_start': 353, 'char_end': 355, 'chars': 's.'}, {'char_start': 356, 'char_end': 357, 'chars': 'y'}, {'char_start': 358, 'char_end': 359, 'chars': 't'}, {'char_start': 360, 'char_end': 361, 'chars': 'm'}, {'char_start': 373, 'char_end': 374, 'chars': '%'}, {'char_start': 387, 'char_end': 394, 'chars': ' % base'}, {'char_start': 400, 'char_end': 401, 'chars': '.'}, {'char_start': 402, 'char_end': 405, 'chars': 'yst'}, {'char_start': 406, 'char_end': 407, 'chars': 'm'}, {'char_start': 422, 'char_end': 425, 'chars': '%s.'}, {'char_start': 427, 'char_end': 432, 'chars': ""c %s'""}, {'char_start': 433, 'char_end': 434, 'chars': '%'}, {'char_start': 435, 'char_end': 437, 'chars': '(b'}, {'char_start': 439, 'char_end': 440, 'chars': 'e'}, {'char_start': 446, 'char_end': 447, 'chars': ')'}, {'char_start': 453, 'char_end': 454, 'chars': '.'}, {'char_start': 455, 'char_end': 458, 'chars': 'yst'}, {'char_start': 459, 'char_end': 460, 'chars': 'm'}, {'char_start': 477, 'char_end': 480, 'chars': '%s.'}, {'char_start': 482, 'char_end': 484, 'chars': ""c'""}, {'char_start': 485, 'char_end': 486, 'chars': '%'}, {'char_start': 487, 'char_end': 488, 'chars': 'b'}, {'char_start': 490, 'char_end': 491, 'chars': 'e'}], 'added': [{'char_start': 310, 'char_end': 315, 'chars': 'subpr'}, {'char_start': 316, 'char_end': 319, 'chars': 'ces'}, {'char_start': 321, 'char_end': 323, 'chars': 'ch'}, {'char_start': 324, 'char_end': 331, 'chars': 'ck_call'}, {'char_start': 332, 'char_end': 333, 'chars': '['}, {'char_start': 340, 'char_end': 342, 'chars': ""',""}, {'char_start': 343, 'char_end': 344, 'chars': ""'""}, {'char_start': 346, 'char_end': 348, 'chars': ""',""}, {'char_start': 349, 'char_end': 351, 'chars': 'ba'}, {'char_start': 352, 'char_end': 357, 'chars': ""e + '""}, {'char_start': 365, 'char_end': 366, 'chars': ']'}, {'char_start': 371, 'char_end': 378, 'chars': 'ubproce'}, {'char_start': 380, 'char_end': 383, 'chars': '.ch'}, {'char_start': 384, 'char_end': 391, 'chars': 'ck_call'}, {'char_start': 392, 'char_end': 393, 'chars': '['}, {'char_start': 400, 'char_end': 402, 'chars': ""',""}, {'char_start': 403, 'char_end': 404, 'chars': ""'""}, {'char_start': 406, 'char_end': 408, 'chars': ""',""}, {'char_start': 409, 'char_end': 411, 'chars': 'ba'}, {'char_start': 412, 'char_end': 417, 'chars': ""e + '""}, {'char_start': 429, 'char_end': 430, 'chars': ']'}, {'char_start': 435, 'char_end': 442, 'chars': 'ubproce'}, {'char_start': 444, 'char_end': 447, 'chars': '.ch'}, {'char_start': 448, 'char_end': 455, 'chars': 'ck_call'}, {'char_start': 456, 'char_end': 457, 'chars': '['}, {'char_start': 461, 'char_end': 463, 'chars': ""',""}, {'char_start': 464, 'char_end': 465, 'chars': ""'""}, {'char_start': 473, 'char_end': 475, 'chars': ""',""}, {'char_start': 476, 'char_end': 478, 'chars': 'ba'}, {'char_start': 479, 'char_end': 484, 'chars': ""e + '""}, {'char_start': 495, 'char_end': 496, 'chars': ']'}, {'char_start': 500, 'char_end': 505, 'chars': 'subpr'}, {'char_start': 506, 'char_end': 508, 'chars': 'ce'}, {'char_start': 510, 'char_end': 513, 'chars': '.ch'}, {'char_start': 514, 'char_end': 521, 'chars': 'ck_call'}, {'char_start': 522, 'char_end': 523, 'chars': '['}, {'char_start': 531, 'char_end': 533, 'chars': ""',""}, {'char_start': 534, 'char_end': 535, 'chars': ""'""}, {'char_start': 541, 'char_end': 543, 'chars': ""',""}, {'char_start': 544, 'char_end': 546, 'chars': 'ba'}, {'char_start': 547, 'char_end': 552, 'chars': ""e + '""}, {'char_start': 557, 'char_end': 558, 'chars': ']'}]}",github.com/rillian/rust-build/commit/b8af51e5811fcb35eff9e1e3e91c98490e7a7dcb,repack_rust.py,cwe-078,160 cwe-022,create_dump_dir_from_problem_data,"struct dump_dir *create_dump_dir_from_problem_data(problem_data_t *problem_data, const char *base_dir_name) { INITIALIZE_LIBREPORT(); char *type = problem_data_get_content_or_NULL(problem_data, FILENAME_ANALYZER); if (!type) { error_msg(_(""Missing required item: '%s'""), FILENAME_ANALYZER); return NULL; } uid_t uid = (uid_t)-1L; char *uid_str = problem_data_get_content_or_NULL(problem_data, FILENAME_UID); if (uid_str) { char *endptr; errno = 0; long val = strtol(uid_str, &endptr, 10); if (errno != 0 || endptr == uid_str || *endptr != '\0' || INT_MAX < val) { error_msg(_(""uid value is not valid: '%s'""), uid_str); return NULL; } uid = (uid_t)val; } struct timeval tv; if (gettimeofday(&tv, NULL) < 0) { perror_msg(""gettimeofday()""); return NULL; } char *problem_id = xasprintf(""%s-%s.%ld-%lu""NEW_PD_SUFFIX, type, iso_date_string(&(tv.tv_sec)), (long)tv.tv_usec, (long)getpid()); log_info(""Saving to %s/%s with uid %d"", base_dir_name, problem_id, uid); struct dump_dir *dd; if (base_dir_name) dd = try_dd_create(base_dir_name, problem_id, uid); else { /* Try /var/run/abrt */ dd = try_dd_create(LOCALSTATEDIR""/run/abrt"", problem_id, uid); /* Try $HOME/tmp */ if (!dd) { char *home = getenv(""HOME""); if (home && home[0]) { home = concat_path_file(home, ""tmp""); /*mkdir(home, 0777); - do we want this? */ dd = try_dd_create(home, problem_id, uid); free(home); } } //TODO: try user's home dir obtained by getpwuid(getuid())? /* Try system temporary directory */ if (!dd) dd = try_dd_create(LARGE_DATA_TMP_DIR, problem_id, uid); } if (!dd) /* try_dd_create() already emitted the error message */ goto ret; GHashTableIter iter; char *name; struct problem_item *value; g_hash_table_iter_init(&iter, problem_data); while (g_hash_table_iter_next(&iter, (void**)&name, (void**)&value)) { if (value->flags & CD_FLAG_BIN) { char *dest = concat_path_file(dd->dd_dirname, name); log_info(""copying '%s' to '%s'"", value->content, dest); off_t copied = copy_file(value->content, dest, DEFAULT_DUMP_DIR_MODE | S_IROTH); if (copied < 0) error_msg(""Can't copy %s to %s"", value->content, dest); else log_info(""copied %li bytes"", (unsigned long)copied); free(dest); continue; } /* only files should contain '/' and those are handled earlier */ if (name[0] == '.' || strchr(name, '/')) { error_msg(""Problem data field name contains disallowed chars: '%s'"", name); continue; } dd_save_text(dd, name, value->content); } /* need to create basic files AFTER we save the pd to dump_dir * otherwise we can't skip already created files like in case when * reporting from anaconda where we can't read /etc/{system,redhat}-release * and os_release is taken from anaconda */ dd_create_basic_files(dd, uid, NULL); problem_id[strlen(problem_id) - strlen(NEW_PD_SUFFIX)] = '\0'; char* new_path = concat_path_file(base_dir_name, problem_id); log_info(""Renaming from '%s' to '%s'"", dd->dd_dirname, new_path); dd_rename(dd, new_path); ret: free(problem_id); return dd; }","struct dump_dir *create_dump_dir_from_problem_data(problem_data_t *problem_data, const char *base_dir_name) { INITIALIZE_LIBREPORT(); char *type = problem_data_get_content_or_NULL(problem_data, FILENAME_ANALYZER); if (!type) { error_msg(_(""Missing required item: '%s'""), FILENAME_ANALYZER); return NULL; } if (!str_is_correct_filename(type)) { error_msg(_(""'%s' is not correct file name""), FILENAME_ANALYZER); return NULL; } uid_t uid = (uid_t)-1L; char *uid_str = problem_data_get_content_or_NULL(problem_data, FILENAME_UID); if (uid_str) { char *endptr; errno = 0; long val = strtol(uid_str, &endptr, 10); if (errno != 0 || endptr == uid_str || *endptr != '\0' || INT_MAX < val) { error_msg(_(""uid value is not valid: '%s'""), uid_str); return NULL; } uid = (uid_t)val; } struct timeval tv; if (gettimeofday(&tv, NULL) < 0) { perror_msg(""gettimeofday()""); return NULL; } char *problem_id = xasprintf(""%s-%s.%ld-%lu""NEW_PD_SUFFIX, type, iso_date_string(&(tv.tv_sec)), (long)tv.tv_usec, (long)getpid()); log_info(""Saving to %s/%s with uid %d"", base_dir_name, problem_id, uid); struct dump_dir *dd; if (base_dir_name) dd = try_dd_create(base_dir_name, problem_id, uid); else { /* Try /var/run/abrt */ dd = try_dd_create(LOCALSTATEDIR""/run/abrt"", problem_id, uid); /* Try $HOME/tmp */ if (!dd) { char *home = getenv(""HOME""); if (home && home[0]) { home = concat_path_file(home, ""tmp""); /*mkdir(home, 0777); - do we want this? */ dd = try_dd_create(home, problem_id, uid); free(home); } } //TODO: try user's home dir obtained by getpwuid(getuid())? /* Try system temporary directory */ if (!dd) dd = try_dd_create(LARGE_DATA_TMP_DIR, problem_id, uid); } if (!dd) /* try_dd_create() already emitted the error message */ goto ret; GHashTableIter iter; char *name; struct problem_item *value; g_hash_table_iter_init(&iter, problem_data); while (g_hash_table_iter_next(&iter, (void**)&name, (void**)&value)) { if (!str_is_correct_filename(name)) { error_msg(""Problem data field name contains disallowed chars: '%s'"", name); continue; } if (value->flags & CD_FLAG_BIN) { char *dest = concat_path_file(dd->dd_dirname, name); log_info(""copying '%s' to '%s'"", value->content, dest); off_t copied = copy_file(value->content, dest, DEFAULT_DUMP_DIR_MODE | S_IROTH); if (copied < 0) error_msg(""Can't copy %s to %s"", value->content, dest); else log_info(""copied %li bytes"", (unsigned long)copied); free(dest); continue; } dd_save_text(dd, name, value->content); } /* need to create basic files AFTER we save the pd to dump_dir * otherwise we can't skip already created files like in case when * reporting from anaconda where we can't read /etc/{system,redhat}-release * and os_release is taken from anaconda */ dd_create_basic_files(dd, uid, NULL); problem_id[strlen(problem_id) - strlen(NEW_PD_SUFFIX)] = '\0'; char* new_path = concat_path_file(base_dir_name, problem_id); log_info(""Renaming from '%s' to '%s'"", dd->dd_dirname, new_path); dd_rename(dd, new_path); ret: free(problem_id); return dd; }","{'deleted': [{'line_no': 90, 'char_start': 2743, 'char_end': 2817, 'line': "" /* only files should contain '/' and those are handled earlier */\n""}, {'line_no': 91, 'char_start': 2817, 'char_end': 2866, 'line': "" if (name[0] == '.' || strchr(name, '/'))\n""}, {'line_no': 92, 'char_start': 2866, 'char_end': 2876, 'line': ' {\n'}, {'line_no': 93, 'char_start': 2876, 'char_end': 2964, 'line': ' error_msg(""Problem data field name contains disallowed chars: \'%s\'"", name);\n'}, {'line_no': 94, 'char_start': 2964, 'char_end': 2986, 'line': ' continue;\n'}, {'line_no': 95, 'char_start': 2986, 'char_end': 2996, 'line': ' }\n'}, {'line_no': 96, 'char_start': 2996, 'char_end': 2997, 'line': '\n'}], 'added': [{'line_no': 13, 'char_start': 345, 'char_end': 385, 'line': ' if (!str_is_correct_filename(type))\n'}, {'line_no': 14, 'char_start': 385, 'char_end': 391, 'line': ' {\n'}, {'line_no': 15, 'char_start': 391, 'char_end': 465, 'line': ' error_msg(_(""\'%s\' is not correct file name""), FILENAME_ANALYZER);\n'}, {'line_no': 16, 'char_start': 465, 'char_end': 486, 'line': ' return NULL;\n'}, {'line_no': 17, 'char_start': 486, 'char_end': 492, 'line': ' }\n'}, {'line_no': 18, 'char_start': 492, 'char_end': 493, 'line': '\n'}, {'line_no': 82, 'char_start': 2371, 'char_end': 2415, 'line': ' if (!str_is_correct_filename(name))\n'}, {'line_no': 83, 'char_start': 2415, 'char_end': 2425, 'line': ' {\n'}, {'line_no': 84, 'char_start': 2425, 'char_end': 2513, 'line': ' error_msg(""Problem data field name contains disallowed chars: \'%s\'"", name);\n'}, {'line_no': 85, 'char_start': 2513, 'char_end': 2535, 'line': ' continue;\n'}, {'line_no': 86, 'char_start': 2535, 'char_end': 2545, 'line': ' }\n'}, {'line_no': 87, 'char_start': 2545, 'char_end': 2546, 'line': '\n'}]}","{'deleted': [{'char_start': 2709, 'char_end': 2963, 'chars': '\n continue;\n }\n\n /* only files should contain \'/\' and those are handled earlier */\n if (name[0] == \'.\' || strchr(name, \'/\'))\n {\n error_msg(""Problem data field name contains disallowed chars: \'%s\'"", name);'}], 'added': [{'char_start': 349, 'char_end': 497, 'chars': 'if (!str_is_correct_filename(type))\n {\n error_msg(_(""\'%s\' is not correct file name""), FILENAME_ANALYZER);\n return NULL;\n }\n\n '}, {'char_start': 2383, 'char_end': 2558, 'chars': '!str_is_correct_filename(name))\n {\n error_msg(""Problem data field name contains disallowed chars: \'%s\'"", name);\n continue;\n }\n\n if ('}]}",github.com/abrt/libreport/commit/239c4f7d1f47265526b39ad70106767d00805277,src/lib/create_dump_dir.c,cwe-022,933 cwe-022,compose_path,"char *compose_path(ctrl_t *ctrl, char *path) { struct stat st; static char rpath[PATH_MAX]; char *name, *ptr; char dir[PATH_MAX] = { 0 }; strlcpy(dir, ctrl->cwd, sizeof(dir)); DBG(""Compose path from cwd: %s, arg: %s"", ctrl->cwd, path ?: """"); if (!path || !strlen(path)) goto check; if (path) { if (path[0] != '/') { if (dir[strlen(dir) - 1] != '/') strlcat(dir, ""/"", sizeof(dir)); } strlcat(dir, path, sizeof(dir)); } check: while ((ptr = strstr(dir, ""//""))) memmove(ptr, &ptr[1], strlen(&ptr[1]) + 1); if (!chrooted) { size_t len = strlen(home); DBG(""Server path from CWD: %s"", dir); if (len > 0 && home[len - 1] == '/') len--; memmove(dir + len, dir, strlen(dir) + 1); memcpy(dir, home, len); DBG(""Resulting non-chroot path: %s"", dir); } /* * Handle directories slightly differently, since dirname() on a * directory returns the parent directory. So, just squash .. */ if (!stat(dir, &st) && S_ISDIR(st.st_mode)) { if (!realpath(dir, rpath)) return NULL; } else { /* * Check realpath() of directory containing the file, a * STOR may want to save a new file. Then append the * file and return it. */ name = basename(path); ptr = dirname(dir); memset(rpath, 0, sizeof(rpath)); if (!realpath(ptr, rpath)) { INFO(""Failed realpath(%s): %m"", ptr); return NULL; } if (rpath[1] != 0) strlcat(rpath, ""/"", sizeof(rpath)); strlcat(rpath, name, sizeof(rpath)); } if (!chrooted && strncmp(dir, home, strlen(home))) { DBG(""Failed non-chroot dir:%s vs home:%s"", dir, home); return NULL; } return rpath; }","char *compose_path(ctrl_t *ctrl, char *path) { struct stat st; static char rpath[PATH_MAX]; char *name, *ptr; char dir[PATH_MAX] = { 0 }; strlcpy(dir, ctrl->cwd, sizeof(dir)); DBG(""Compose path from cwd: %s, arg: %s"", ctrl->cwd, path ?: """"); if (!path || !strlen(path)) goto check; if (path) { if (path[0] != '/') { if (dir[strlen(dir) - 1] != '/') strlcat(dir, ""/"", sizeof(dir)); } strlcat(dir, path, sizeof(dir)); } check: while ((ptr = strstr(dir, ""//""))) memmove(ptr, &ptr[1], strlen(&ptr[1]) + 1); if (!chrooted) { size_t len = strlen(home); DBG(""Server path from CWD: %s"", dir); if (len > 0 && home[len - 1] == '/') len--; memmove(dir + len, dir, strlen(dir) + 1); memcpy(dir, home, len); DBG(""Resulting non-chroot path: %s"", dir); } /* * Handle directories slightly differently, since dirname() on a * directory returns the parent directory. So, just squash .. */ if (!stat(dir, &st) && S_ISDIR(st.st_mode)) { if (!realpath(dir, rpath)) return NULL; } else { /* * Check realpath() of directory containing the file, a * STOR may want to save a new file. Then append the * file and return it. */ name = basename(path); ptr = dirname(dir); memset(rpath, 0, sizeof(rpath)); if (!realpath(ptr, rpath)) { INFO(""Failed realpath(%s): %m"", ptr); return NULL; } if (rpath[1] != 0) strlcat(rpath, ""/"", sizeof(rpath)); strlcat(rpath, name, sizeof(rpath)); } if (!chrooted && strncmp(rpath, home, strlen(home))) { DBG(""Failed non-chroot dir:%s vs home:%s"", dir, home); return NULL; } return rpath; }","{'deleted': [{'line_no': 63, 'char_start': 1460, 'char_end': 1514, 'line': '\tif (!chrooted && strncmp(dir, home, strlen(home))) {\n'}], 'added': [{'line_no': 63, 'char_start': 1460, 'char_end': 1516, 'line': '\tif (!chrooted && strncmp(rpath, home, strlen(home))) {\n'}]}","{'deleted': [{'char_start': 1486, 'char_end': 1488, 'chars': 'di'}], 'added': [{'char_start': 1487, 'char_end': 1491, 'chars': 'path'}]}",github.com/troglobit/uftpd/commit/455b47d3756aed162d2d0ef7f40b549f3b5b30fe,src/common.c,cwe-022,512 cwe-022,get_paths,"def get_paths(base_path: pathlib.Path): data_file = pathlib.Path(str(base_path) + "".data"") metadata_file = pathlib.Path(str(base_path) + "".meta"") return data_file, metadata_file","def get_paths(root: str, sub_path: str) \ -> typing.Tuple[pathlib.Path, pathlib.Path]: base_path = flask.safe_join(root, sub_path) data_file = pathlib.Path(base_path + "".data"") metadata_file = pathlib.Path(base_path + "".meta"") return data_file, metadata_file","{'deleted': [{'line_no': 1, 'char_start': 0, 'char_end': 40, 'line': 'def get_paths(base_path: pathlib.Path):\n'}], 'added': [{'line_no': 1, 'char_start': 0, 'char_end': 42, 'line': 'def get_paths(root: str, sub_path: str) \\\n'}, {'line_no': 2, 'char_start': 42, 'char_end': 95, 'line': ' -> typing.Tuple[pathlib.Path, pathlib.Path]:\n'}, {'line_no': 3, 'char_start': 95, 'char_end': 143, 'line': ' base_path = flask.safe_join(root, sub_path)\n'}, {'line_no': 4, 'char_start': 143, 'char_end': 193, 'line': ' data_file = pathlib.Path(base_path + "".data"")\n'}, {'line_no': 5, 'char_start': 193, 'char_end': 247, 'line': ' metadata_file = pathlib.Path(base_path + "".meta"")\n'}]}","{'deleted': [{'char_start': 18, 'char_end': 19, 'chars': '_'}, {'char_start': 23, 'char_end': 24, 'chars': ':'}, {'char_start': 38, 'char_end': 39, 'chars': ':'}, {'char_start': 69, 'char_end': 73, 'chars': 'str('}, {'char_start': 82, 'char_end': 83, 'chars': ')'}, {'char_start': 128, 'char_end': 132, 'chars': 'str('}, {'char_start': 141, 'char_end': 142, 'chars': ')'}], 'added': [{'char_start': 14, 'char_end': 27, 'chars': 'root: str, su'}, {'char_start': 28, 'char_end': 30, 'chars': '_p'}, {'char_start': 31, 'char_end': 35, 'chars': 'th: '}, {'char_start': 36, 'char_end': 64, 'chars': 'tr) \\\n -> typing.Tupl'}, {'char_start': 65, 'char_end': 66, 'chars': '['}, {'char_start': 70, 'char_end': 79, 'chars': 'lib.Path,'}, {'char_start': 92, 'char_end': 93, 'chars': ']'}, {'char_start': 99, 'char_end': 147, 'chars': 'base_path = flask.safe_join(root, sub_path)\n '}]}",github.com/horazont/xmpp-http-upload/commit/82056540191e89f0cd697c81f57714c00962ed75,xhu.py,cwe-022,44 cwe-078,test_initialize_connection," def test_initialize_connection(self): self.driver._eql_execute = self.mox.\ CreateMock(self.driver._eql_execute) volume = {'name': self.volume_name} self.stubs.Set(self.driver, ""_get_iscsi_properties"", self._fake_get_iscsi_properties) self.driver._eql_execute('volume', 'select', volume['name'], 'access', 'create', 'initiator', self.connector['initiator'], 'authmethod chap', 'username', self.configuration.eqlx_chap_login) self.mox.ReplayAll() iscsi_properties = self.driver.initialize_connection(volume, self.connector) self.assertEqual(iscsi_properties['data'], self._fake_get_iscsi_properties(volume))"," def test_initialize_connection(self): self.driver._eql_execute = self.mox.\ CreateMock(self.driver._eql_execute) volume = {'name': self.volume_name} self.stubs.Set(self.driver, ""_get_iscsi_properties"", self._fake_get_iscsi_properties) self.driver._eql_execute('volume', 'select', volume['name'], 'access', 'create', 'initiator', self.connector['initiator'], 'authmethod', 'chap', 'username', self.configuration.eqlx_chap_login) self.mox.ReplayAll() iscsi_properties = self.driver.initialize_connection(volume, self.connector) self.assertEqual(iscsi_properties['data'], self._fake_get_iscsi_properties(volume))","{'deleted': [{'line_no': 10, 'char_start': 495, 'char_end': 547, 'line': "" 'authmethod chap',\n""}], 'added': [{'line_no': 10, 'char_start': 495, 'char_end': 550, 'line': "" 'authmethod', 'chap',\n""}]}","{'deleted': [], 'added': [{'char_start': 539, 'char_end': 541, 'chars': ""',""}, {'char_start': 542, 'char_end': 543, 'chars': ""'""}]}",github.com/thatsdone/cinder/commit/9e858bebb89de05b1c9ecc27f5bd9fbff95a728e,cinder/tests/test_eqlx.py,cwe-078,163 cwe-079,mode_keepalive," def mode_keepalive(self, request): """""" This is called by render_POST when the client is replying to the keepalive. """""" csessid = request.args.get('csessid')[0] self.last_alive[csessid] = (time.time(), False) return '""""'"," def mode_keepalive(self, request): """""" This is called by render_POST when the client is replying to the keepalive. """""" csessid = cgi.escape(request.args['csessid'][0]) self.last_alive[csessid] = (time.time(), False) return '""""'","{'deleted': [{'line_no': 6, 'char_start': 155, 'char_end': 204, 'line': "" csessid = request.args.get('csessid')[0]\n""}], 'added': [{'line_no': 6, 'char_start': 155, 'char_end': 212, 'line': "" csessid = cgi.escape(request.args['csessid'][0])\n""}]}","{'deleted': [{'char_start': 185, 'char_end': 190, 'chars': '.get('}, {'char_start': 199, 'char_end': 200, 'chars': ')'}], 'added': [{'char_start': 173, 'char_end': 184, 'chars': 'cgi.escape('}, {'char_start': 196, 'char_end': 197, 'chars': '['}, {'char_start': 206, 'char_end': 207, 'chars': ']'}, {'char_start': 210, 'char_end': 211, 'chars': ')'}]}",github.com/evennia/evennia/commit/300261529b82f95414c9d1d7150d6eda4695bb93,evennia/server/portal/webclient_ajax.py,cwe-079,69 cwe-416,ip4_datagram_release_cb,"void ip4_datagram_release_cb(struct sock *sk) { const struct inet_sock *inet = inet_sk(sk); const struct ip_options_rcu *inet_opt; __be32 daddr = inet->inet_daddr; struct flowi4 fl4; struct rtable *rt; if (! __sk_dst_get(sk) || __sk_dst_check(sk, 0)) return; rcu_read_lock(); inet_opt = rcu_dereference(inet->inet_opt); if (inet_opt && inet_opt->opt.srr) daddr = inet_opt->opt.faddr; rt = ip_route_output_ports(sock_net(sk), &fl4, sk, daddr, inet->inet_saddr, inet->inet_dport, inet->inet_sport, sk->sk_protocol, RT_CONN_FLAGS(sk), sk->sk_bound_dev_if); if (!IS_ERR(rt)) __sk_dst_set(sk, &rt->dst); rcu_read_unlock(); }","void ip4_datagram_release_cb(struct sock *sk) { const struct inet_sock *inet = inet_sk(sk); const struct ip_options_rcu *inet_opt; __be32 daddr = inet->inet_daddr; struct dst_entry *dst; struct flowi4 fl4; struct rtable *rt; rcu_read_lock(); dst = __sk_dst_get(sk); if (!dst || !dst->obsolete || dst->ops->check(dst, 0)) { rcu_read_unlock(); return; } inet_opt = rcu_dereference(inet->inet_opt); if (inet_opt && inet_opt->opt.srr) daddr = inet_opt->opt.faddr; rt = ip_route_output_ports(sock_net(sk), &fl4, sk, daddr, inet->inet_saddr, inet->inet_dport, inet->inet_sport, sk->sk_protocol, RT_CONN_FLAGS(sk), sk->sk_bound_dev_if); dst = !IS_ERR(rt) ? &rt->dst : NULL; sk_dst_set(sk, dst); rcu_read_unlock(); }","{'deleted': [{'line_no': 9, 'char_start': 208, 'char_end': 258, 'line': '\tif (! __sk_dst_get(sk) || __sk_dst_check(sk, 0))\n'}, {'line_no': 10, 'char_start': 258, 'char_end': 268, 'line': '\t\treturn;\n'}, {'line_no': 11, 'char_start': 268, 'char_end': 269, 'line': '\n'}, {'line_no': 20, 'char_start': 591, 'char_end': 609, 'line': '\tif (!IS_ERR(rt))\n'}, {'line_no': 21, 'char_start': 609, 'char_end': 639, 'line': '\t\t__sk_dst_set(sk, &rt->dst);\n'}], 'added': [{'line_no': 6, 'char_start': 167, 'char_end': 191, 'line': '\tstruct dst_entry *dst;\n'}, {'line_no': 11, 'char_start': 250, 'char_end': 251, 'line': '\n'}, {'line_no': 12, 'char_start': 251, 'char_end': 276, 'line': '\tdst = __sk_dst_get(sk);\n'}, {'line_no': 13, 'char_start': 276, 'char_end': 334, 'line': '\tif (!dst || !dst->obsolete || dst->ops->check(dst, 0)) {\n'}, {'line_no': 14, 'char_start': 334, 'char_end': 355, 'line': '\t\trcu_read_unlock();\n'}, {'line_no': 15, 'char_start': 355, 'char_end': 365, 'line': '\t\treturn;\n'}, {'line_no': 16, 'char_start': 365, 'char_end': 368, 'line': '\t}\n'}, {'line_no': 24, 'char_start': 672, 'char_end': 673, 'line': '\n'}, {'line_no': 25, 'char_start': 673, 'char_end': 711, 'line': '\tdst = !IS_ERR(rt) ? &rt->dst : NULL;\n'}, {'line_no': 26, 'char_start': 711, 'char_end': 733, 'line': '\tsk_dst_set(sk, dst);\n'}, {'line_no': 27, 'char_start': 733, 'char_end': 734, 'line': '\n'}]}","{'deleted': [{'char_start': 209, 'char_end': 212, 'chars': 'if '}, {'char_start': 213, 'char_end': 214, 'chars': '!'}, {'char_start': 235, 'char_end': 237, 'chars': '__'}, {'char_start': 238, 'char_end': 240, 'chars': 'k_'}, {'char_start': 243, 'char_end': 244, 'chars': '_'}, {'char_start': 251, 'char_end': 252, 'chars': 'k'}, {'char_start': 259, 'char_end': 269, 'chars': '\treturn;\n\n'}, {'char_start': 592, 'char_end': 594, 'chars': 'if'}, {'char_start': 595, 'char_end': 596, 'chars': '('}, {'char_start': 607, 'char_end': 608, 'chars': ')'}, {'char_start': 610, 'char_end': 613, 'chars': '\t__'}, {'char_start': 628, 'char_end': 633, 'chars': '&rt->'}], 'added': [{'char_start': 175, 'char_end': 199, 'chars': 'dst_entry *dst;\n\tstruct '}, {'char_start': 233, 'char_end': 246, 'chars': 'rcu_read_lock'}, {'char_start': 247, 'char_end': 257, 'chars': ');\n\n\tdst ='}, {'char_start': 274, 'char_end': 285, 'chars': ';\n\tif (!dst'}, {'char_start': 289, 'char_end': 291, 'chars': '!d'}, {'char_start': 292, 'char_end': 307, 'chars': 't->obsolete || '}, {'char_start': 310, 'char_end': 317, 'chars': '->ops->'}, {'char_start': 323, 'char_end': 324, 'chars': 'd'}, {'char_start': 325, 'char_end': 326, 'chars': 't'}, {'char_start': 331, 'char_end': 333, 'chars': ' {'}, {'char_start': 345, 'char_end': 347, 'chars': 'un'}, {'char_start': 354, 'char_end': 367, 'chars': '\n\t\treturn;\n\t}'}, {'char_start': 672, 'char_end': 673, 'chars': '\n'}, {'char_start': 674, 'char_end': 677, 'chars': 'dst'}, {'char_start': 678, 'char_end': 680, 'chars': '= '}, {'char_start': 691, 'char_end': 710, 'chars': ' ? &rt->dst : NULL;'}, {'char_start': 732, 'char_end': 733, 'chars': '\n'}]}",github.com/torvalds/linux/commit/9709674e68646cee5a24e3000b3558d25412203a,net/ipv4/datagram.c,cwe-416,207 cwe-476,mpeg4video_probe,"static int mpeg4video_probe(AVProbeData *probe_packet) { uint32_t temp_buffer = -1; int VO = 0, VOL = 0, VOP = 0, VISO = 0, res = 0; int i; for (i = 0; i < probe_packet->buf_size; i++) { temp_buffer = (temp_buffer << 8) + probe_packet->buf[i]; if ((temp_buffer & 0xffffff00) != 0x100) continue; if (temp_buffer == VOP_START_CODE) VOP++; else if (temp_buffer == VISUAL_OBJECT_START_CODE) VISO++; else if (temp_buffer < 0x120) VO++; else if (temp_buffer < 0x130) VOL++; else if (!(0x1AF < temp_buffer && temp_buffer < 0x1B7) && !(0x1B9 < temp_buffer && temp_buffer < 0x1C4)) res++; } if (VOP >= VISO && VOP >= VOL && VO >= VOL && VOL > 0 && res == 0) return AVPROBE_SCORE_EXTENSION; return 0; }","static int mpeg4video_probe(AVProbeData *probe_packet) { uint32_t temp_buffer = -1; int VO = 0, VOL = 0, VOP = 0, VISO = 0, res = 0; int i; for (i = 0; i < probe_packet->buf_size; i++) { temp_buffer = (temp_buffer << 8) + probe_packet->buf[i]; if (temp_buffer & 0xfffffe00) continue; if (temp_buffer < 2) continue; if (temp_buffer == VOP_START_CODE) VOP++; else if (temp_buffer == VISUAL_OBJECT_START_CODE) VISO++; else if (temp_buffer >= 0x100 && temp_buffer < 0x120) VO++; else if (temp_buffer >= 0x120 && temp_buffer < 0x130) VOL++; else if (!(0x1AF < temp_buffer && temp_buffer < 0x1B7) && !(0x1B9 < temp_buffer && temp_buffer < 0x1C4)) res++; } if (VOP >= VISO && VOP >= VOL && VO >= VOL && VOL > 0 && res == 0) return AVPROBE_SCORE_EXTENSION; return 0; }","{'deleted': [{'line_no': 9, 'char_start': 269, 'char_end': 318, 'line': ' if ((temp_buffer & 0xffffff00) != 0x100)\n'}, {'line_no': 16, 'char_start': 481, 'char_end': 519, 'line': ' else if (temp_buffer < 0x120)\n'}, {'line_no': 18, 'char_start': 537, 'char_end': 575, 'line': ' else if (temp_buffer < 0x130)\n'}], 'added': [{'line_no': 9, 'char_start': 269, 'char_end': 307, 'line': ' if (temp_buffer & 0xfffffe00)\n'}, {'line_no': 10, 'char_start': 307, 'char_end': 329, 'line': ' continue;\n'}, {'line_no': 11, 'char_start': 329, 'char_end': 358, 'line': ' if (temp_buffer < 2)\n'}, {'line_no': 18, 'char_start': 521, 'char_end': 583, 'line': ' else if (temp_buffer >= 0x100 && temp_buffer < 0x120)\n'}, {'line_no': 20, 'char_start': 601, 'char_end': 663, 'line': ' else if (temp_buffer >= 0x120 && temp_buffer < 0x130)\n'}]}","{'deleted': [{'char_start': 281, 'char_end': 282, 'chars': '('}, {'char_start': 303, 'char_end': 304, 'chars': 'f'}, {'char_start': 308, 'char_end': 310, 'chars': '!='}, {'char_start': 311, 'char_end': 316, 'chars': '0x100'}], 'added': [{'char_start': 302, 'char_end': 303, 'chars': 'e'}, {'char_start': 306, 'char_end': 332, 'chars': '\n continue;\n '}, {'char_start': 333, 'char_end': 334, 'chars': ' '}, {'char_start': 335, 'char_end': 356, 'chars': ' if (temp_buffer < 2'}, {'char_start': 550, 'char_end': 574, 'chars': '>= 0x100 && temp_buffer '}, {'char_start': 618, 'char_end': 642, 'chars': 'temp_buffer >= 0x120 && '}]}",github.com/libav/libav/commit/e5b019725f53b79159931d3a7317107cbbfd0860,libavformat/m4vdec.c,cwe-476,277 cwe-078,extend_volume," def extend_volume(self, volume, new_size): LOG.debug(_('enter: extend_volume: volume %s') % volume['id']) ret = self._ensure_vdisk_no_fc_mappings(volume['name'], allow_snaps=False) if not ret: exception_message = (_('extend_volume: Extending a volume with ' 'snapshots is not supported.')) raise exception.VolumeBackendAPIException(data=exception_message) extend_amt = int(new_size) - volume['size'] ssh_cmd = ('svctask expandvdisksize -size %(amt)d -unit gb %(name)s' % {'amt': extend_amt, 'name': volume['name']}) out, err = self._run_ssh(ssh_cmd) # No output should be returned from expandvdisksize self._assert_ssh_return(len(out.strip()) == 0, 'extend_volume', ssh_cmd, out, err) LOG.debug(_('leave: extend_volume: volume %s') % volume['id'])"," def extend_volume(self, volume, new_size): LOG.debug(_('enter: extend_volume: volume %s') % volume['id']) ret = self._ensure_vdisk_no_fc_mappings(volume['name'], allow_snaps=False) if not ret: exception_message = (_('extend_volume: Extending a volume with ' 'snapshots is not supported.')) raise exception.VolumeBackendAPIException(data=exception_message) extend_amt = int(new_size) - volume['size'] ssh_cmd = (['svctask', 'expandvdisksize', '-size', str(extend_amt), '-unit', 'gb', volume['name']]) out, err = self._run_ssh(ssh_cmd) # No output should be returned from expandvdisksize self._assert_ssh_return(len(out.strip()) == 0, 'extend_volume', ssh_cmd, out, err) LOG.debug(_('leave: extend_volume: volume %s') % volume['id'])","{'deleted': [{'line_no': 11, 'char_start': 544, 'char_end': 621, 'line': "" ssh_cmd = ('svctask expandvdisksize -size %(amt)d -unit gb %(name)s'\n""}, {'line_no': 12, 'char_start': 621, 'char_end': 687, 'line': "" % {'amt': extend_amt, 'name': volume['name']})\n""}], 'added': [{'line_no': 11, 'char_start': 544, 'char_end': 620, 'line': "" ssh_cmd = (['svctask', 'expandvdisksize', '-size', str(extend_amt),\n""}, {'line_no': 12, 'char_start': 620, 'char_end': 672, 'line': "" '-unit', 'gb', volume['name']])\n""}]}","{'deleted': [{'char_start': 594, 'char_end': 595, 'chars': '%'}, {'char_start': 596, 'char_end': 598, 'chars': 'am'}, {'char_start': 599, 'char_end': 600, 'chars': ')'}, {'char_start': 601, 'char_end': 614, 'chars': ' -unit gb %(n'}, {'char_start': 616, 'char_end': 617, 'chars': 'e'}, {'char_start': 618, 'char_end': 620, 'chars': ""s'""}, {'char_start': 640, 'char_end': 641, 'chars': '%'}, {'char_start': 642, 'char_end': 643, 'chars': '{'}, {'char_start': 644, 'char_end': 654, 'chars': ""amt': exte""}, {'char_start': 655, 'char_end': 659, 'chars': 'd_am'}, {'char_start': 663, 'char_end': 667, 'chars': 'name'}, {'char_start': 668, 'char_end': 669, 'chars': ':'}, {'char_start': 684, 'char_end': 685, 'chars': '}'}], 'added': [{'char_start': 563, 'char_end': 564, 'chars': '['}, {'char_start': 572, 'char_end': 574, 'chars': ""',""}, {'char_start': 575, 'char_end': 576, 'chars': ""'""}, {'char_start': 591, 'char_end': 593, 'chars': ""',""}, {'char_start': 594, 'char_end': 595, 'chars': ""'""}, {'char_start': 600, 'char_end': 602, 'chars': ""',""}, {'char_start': 603, 'char_end': 604, 'chars': 's'}, {'char_start': 605, 'char_end': 606, 'chars': 'r'}, {'char_start': 607, 'char_end': 611, 'chars': 'exte'}, {'char_start': 612, 'char_end': 614, 'chars': 'd_'}, {'char_start': 616, 'char_end': 617, 'chars': 't'}, {'char_start': 618, 'char_end': 619, 'chars': ','}, {'char_start': 641, 'char_end': 645, 'chars': '-uni'}, {'char_start': 650, 'char_end': 652, 'chars': 'gb'}, {'char_start': 653, 'char_end': 654, 'chars': ','}, {'char_start': 669, 'char_end': 670, 'chars': ']'}]}",github.com/thatsdone/cinder/commit/f752302d181583a95cf44354aea607ce9d9283f4,cinder/volume/drivers/storwize_svc.py,cwe-078,214 cwe-022,create_basename_core,"def create_basename_core(basename): try: basename = basename.casefold() except Exception: basename = basename.lower() basename = basename.replace(' ', '-') basename = re.sub(r'<[^>]*>', r'', basename) basename = re.sub(r'[^a-z0-9\-]', r'', basename) basename = re.sub(r'\-\-', r'-', basename) basename = urllib.parse.quote_plus(basename) return basename","def create_basename_core(basename): try: basename = basename.casefold() except Exception: basename = basename.lower() basename = re.sub(r'[ \./]', r'-', basename) basename = re.sub(r'<[^>]*>', r'', basename) basename = re.sub(r'[^a-z0-9\-]', r'', basename) basename = re.sub(r'\-\-', r'-', basename) basename = urllib.parse.quote_plus(basename) return basename","{'deleted': [{'line_no': 7, 'char_start': 143, 'char_end': 185, 'line': "" basename = basename.replace(' ', '-')\n""}], 'added': [{'line_no': 7, 'char_start': 143, 'char_end': 192, 'line': "" basename = re.sub(r'[ \\./]', r'-', basename)\n""}]}","{'deleted': [{'char_start': 158, 'char_end': 165, 'chars': 'basenam'}, {'char_start': 168, 'char_end': 175, 'chars': 'eplace('}], 'added': [{'char_start': 158, 'char_end': 159, 'chars': 'r'}, {'char_start': 161, 'char_end': 164, 'chars': 'sub'}, {'char_start': 165, 'char_end': 166, 'chars': 'r'}, {'char_start': 167, 'char_end': 168, 'chars': '['}, {'char_start': 169, 'char_end': 173, 'chars': '\\./]'}, {'char_start': 176, 'char_end': 177, 'chars': 'r'}, {'char_start': 180, 'char_end': 190, 'chars': ', basename'}]}",github.com/syegulalp/mercury/commit/3f7c7442fa49aec37577dbdb47ce11a848e7bd03,MeTal/core/utils.py,cwe-022,96 cwe-089,init_user,"def init_user(username, chat_id): conn = sqlite3.connect(os.path.abspath(os.path.dirname(__file__)) + ""\\users\\"" + username + '.db') conn2 = sqlite3.connect(os.path.abspath(os.path.dirname(__file__)) + '\\cf.db') cursor = conn.cursor() cursor2 = conn2.cursor() cursor.execute(""CREATE TABLE result (problem INTEGER, diff STRING, verdict STRING)"") cursor2.execute(""SELECT * FROM problems"") x = cursor2.fetchone() while x != None: cursor.execute(""insert into result values (?, ?, ? )"", (x[0], x[1], ""NULL"")) x = cursor2.fetchone() url = 'http://codeforces.com/submissions/' + username r = requests.get(url) max_page = 1 soup = BeautifulSoup(r.text, ""lxml"") for link in soup.find_all(attrs={""class"": ""page-index""}): s = link.find('a') s2 = s.get(""href"").split('/') max_page = max(max_page, int(s2[4])) old = """" r = requests.get('http://codeforces.com/submissions/' + username + '/page/0') soup = BeautifulSoup(r.text, ""lxml"") last_try = soup.find(attrs={""class"":""status-small""}) if not last_try == None: last_try = str(last_try).split() last_try = str(last_try[2]) + str(last_try[3]) for i in range(1, max_page + 1): r = requests.get('http://codeforces.com/submissions/' + username + '/page/' + str(i)) soup = BeautifulSoup(r.text, ""lxml"") count = 0 ver = soup.find_all(attrs={""class"": ""submissionVerdictWrapper""}) for link in soup.find_all('a'): s = link.get('href') if s != None and s.find('/problemset') != -1: s = s.split('/') if len(s) == 5: s2 = str(ver[count]).split() s2 = s2[5].split('\""') count += 1 cursor.execute(""select * from result where problem = '"" + s[3] + ""'and diff = '"" + s[4] + ""'"") x = cursor.fetchone() if s2[1] == 'OK' and x != None: cursor.execute(""update result set verdict = '"" + s2[1] + ""' where problem = '"" + s[3] + ""' and diff = '"" + s[4] + ""'"") if x != None and x[2] != 'OK': cursor.execute(""update result set verdict = '"" + s2[1] +""' where problem = '"" + s[3] + ""' and diff = '"" + s[4] + ""'"") conn.commit() conn.close() conn2.close() settings = sqlite3.connect(os.path.abspath(os.path.dirname(__file__)) + ""\\settings.db"") conn = settings.cursor() conn.execute(""select * from last_update_problemset"") last_problem = conn.fetchone() conn.execute(""select * from users where chat_id = '"" + str(chat_id) + ""'"") x = conn.fetchone() if x == None: conn.execute(""insert into users values (?, ?, ?, ?, ?)"", (chat_id, username, str(last_try), str(last_problem[0]), 1)) else: conn.execute(""update users set username = '"" + str(username) + ""' where chat_id = '"" + str(chat_id) + ""'"") conn.execute(""update users set last_update = '"" + str(last_try) + ""' where chat_id = '"" + str(chat_id) + ""'"") conn.execute(""update users set last_problem = '"" + str(last_problem[0]) + ""' where chat_id = '"" + str(chat_id) + ""'"") conn.execute(""update users set state = '"" + str(1) + ""' where chat_id = '"" + str(chat_id) + ""'"") settings.commit() settings.close()","def init_user(username, chat_id): conn = sqlite3.connect(os.path.abspath(os.path.dirname(__file__)) + ""\\users\\"" + username + '.db') conn2 = sqlite3.connect(os.path.abspath(os.path.dirname(__file__)) + '\\cf.db') cursor = conn.cursor() cursor2 = conn2.cursor() cursor.execute(""CREATE TABLE result (problem INTEGER, diff STRING, verdict STRING)"") cursor2.execute(""SELECT * FROM problems"") x = cursor2.fetchone() while x != None: cursor.execute(""insert into result values (?, ?, ? )"", (x[0], x[1], ""NULL"")) x = cursor2.fetchone() url = 'http://codeforces.com/submissions/' + username r = requests.get(url) max_page = 1 soup = BeautifulSoup(r.text, ""lxml"") for link in soup.find_all(attrs={""class"": ""page-index""}): s = link.find('a') s2 = s.get(""href"").split('/') max_page = max(max_page, int(s2[4])) r = requests.get('http://codeforces.com/submissions/' + username + '/page/0') soup = BeautifulSoup(r.text, ""lxml"") last_try = soup.find(attrs={""class"":""status-small""}) if not last_try == None: last_try = str(last_try).split() last_try = str(last_try[2]) + str(last_try[3]) for i in range(1, max_page + 1): r = requests.get('http://codeforces.com/submissions/' + username + '/page/' + str(i)) soup = BeautifulSoup(r.text, ""lxml"") count = 0 ver = soup.find_all(attrs={""class"": ""submissionVerdictWrapper""}) for link in soup.find_all('a'): s = link.get('href') if s != None and s.find('/problemset') != -1: s = s.split('/') if len(s) == 5: s2 = str(ver[count]).split() s2 = s2[5].split('\""') count += 1 cursor.execute(""select * from result where problem = ? and diff = ?"", (s[3], s[4])) x = cursor.fetchone() if s2[1] == 'OK' and x != None: cursor.execute(""update result set verdict = ? where problem = ? and diff = ?"", (s2[1], s[3], s[4])) if x != None and x[2] != 'OK': cursor.execute(""update result set verdict = ? where problem = ? and diff = ?"", (s2[1], s[3], s[4])) conn.commit() conn.close() conn2.close() settings = sqlite3.connect(os.path.abspath(os.path.dirname(__file__)) + ""\\settings.db"") conn = settings.cursor() conn.execute(""select * from last_update_problemset"") last_problem = conn.fetchone() conn.execute(""select * from users where chat_id = ?"", (str(chat_id),)) x = conn.fetchone() if x == None: conn.execute(""insert into users values (?, ?, ?, ?, ?)"", (chat_id, username, str(last_try), str(last_problem[0]), 1)) else: conn.execute(""update users set username = ? where chat_id = ?"", (str(username), str(chat_id))) conn.execute(""update users set last_update = ? where chat_id = ?"", (str(last_try), str(chat_id))) conn.execute(""update users set last_problem = ? where chat_id = ?"", (str(last_problem[0]), str(chat_id))) conn.execute(""update users set state = ? where chat_id = ?"", (str(1), str(chat_id))) settings.commit() settings.close()","{'deleted': [{'line_no': 22, 'char_start': 893, 'char_end': 894, 'line': '\n'}, {'line_no': 23, 'char_start': 894, 'char_end': 907, 'line': ' old = """"\n'}, {'line_no': 44, 'char_start': 1799, 'char_end': 1914, 'line': ' cursor.execute(""select * from result where problem = \'"" + s[3] + ""\'and diff = \'"" + s[4] + ""\'"")\n'}, {'line_no': 47, 'char_start': 2008, 'char_end': 2151, 'line': ' cursor.execute(""update result set verdict = \'"" + s2[1] + ""\' where problem = \'"" + s[3] + ""\' and diff = \'"" + s[4] + ""\'"")\n'}, {'line_no': 49, 'char_start': 2202, 'char_end': 2344, 'line': ' cursor.execute(""update result set verdict = \'"" + s2[1] +""\' where problem = \'"" + s[3] + ""\' and diff = \'"" + s[4] + ""\'"")\n'}, {'line_no': 50, 'char_start': 2344, 'char_end': 2345, 'line': '\n'}, {'line_no': 54, 'char_start': 2398, 'char_end': 2399, 'line': '\n'}, {'line_no': 59, 'char_start': 2613, 'char_end': 2692, 'line': ' conn.execute(""select * from users where chat_id = \'"" + str(chat_id) + ""\'"")\n'}, {'line_no': 64, 'char_start': 2870, 'char_end': 2985, 'line': ' conn.execute(""update users set username = \'"" + str(username) + ""\' where chat_id = \'"" + str(chat_id) + ""\'"")\n'}, {'line_no': 65, 'char_start': 2985, 'char_end': 3103, 'line': ' conn.execute(""update users set last_update = \'"" + str(last_try) + ""\' where chat_id = \'"" + str(chat_id) + ""\'"")\n'}, {'line_no': 66, 'char_start': 3103, 'char_end': 3229, 'line': ' conn.execute(""update users set last_problem = \'"" + str(last_problem[0]) + ""\' where chat_id = \'"" + str(chat_id) + ""\'"")\n'}, {'line_no': 67, 'char_start': 3229, 'char_end': 3334, 'line': ' conn.execute(""update users set state = \'"" + str(1) + ""\' where chat_id = \'"" + str(chat_id) + ""\'"")\n'}], 'added': [{'line_no': 42, 'char_start': 1785, 'char_end': 1889, 'line': ' cursor.execute(""select * from result where problem = ? and diff = ?"", (s[3], s[4]))\n'}, {'line_no': 45, 'char_start': 1983, 'char_end': 2107, 'line': ' cursor.execute(""update result set verdict = ? where problem = ? and diff = ?"", (s2[1], s[3], s[4]))\n'}, {'line_no': 47, 'char_start': 2158, 'char_end': 2282, 'line': ' cursor.execute(""update result set verdict = ? where problem = ? and diff = ?"", (s2[1], s[3], s[4]))\n'}, {'line_no': 55, 'char_start': 2549, 'char_end': 2624, 'line': ' conn.execute(""select * from users where chat_id = ?"", (str(chat_id),))\n'}, {'line_no': 60, 'char_start': 2802, 'char_end': 2905, 'line': ' conn.execute(""update users set username = ? where chat_id = ?"", (str(username), str(chat_id)))\n'}, {'line_no': 61, 'char_start': 2905, 'char_end': 3011, 'line': ' conn.execute(""update users set last_update = ? where chat_id = ?"", (str(last_try), str(chat_id)))\n'}, {'line_no': 62, 'char_start': 3011, 'char_end': 3125, 'line': ' conn.execute(""update users set last_problem = ? where chat_id = ?"", (str(last_problem[0]), str(chat_id)))\n'}, {'line_no': 63, 'char_start': 3125, 'char_end': 3218, 'line': ' conn.execute(""update users set state = ? where chat_id = ?"", (str(1), str(chat_id)))\n'}]}","{'deleted': [{'char_start': 893, 'char_end': 907, 'chars': '\n old = """"\n'}, {'char_start': 1872, 'char_end': 1883, 'chars': '\'"" + s[3] +'}, {'char_start': 1884, 'char_end': 1886, 'chars': '""\''}, {'char_start': 1897, 'char_end': 1898, 'chars': ""'""}, {'char_start': 1900, 'char_end': 1901, 'chars': '+'}, {'char_start': 1906, 'char_end': 1912, 'chars': ' + ""\'""'}, {'char_start': 2076, 'char_end': 2091, 'chars': '\'"" + s2[1] + ""\''}, {'char_start': 2108, 'char_end': 2122, 'chars': '\'"" + s[3] + ""\''}, {'char_start': 2134, 'char_end': 2135, 'chars': ""'""}, {'char_start': 2137, 'char_end': 2138, 'chars': '+'}, {'char_start': 2143, 'char_end': 2149, 'chars': ' + ""\'""'}, {'char_start': 2270, 'char_end': 2284, 'chars': '\'"" + s2[1] +""\''}, {'char_start': 2301, 'char_end': 2315, 'chars': '\'"" + s[3] + ""\''}, {'char_start': 2327, 'char_end': 2328, 'chars': ""'""}, {'char_start': 2330, 'char_end': 2331, 'chars': '+'}, {'char_start': 2336, 'char_end': 2342, 'chars': ' + ""\'""'}, {'char_start': 2343, 'char_end': 2344, 'chars': '\n'}, {'char_start': 2398, 'char_end': 2399, 'chars': '\n'}, {'char_start': 2667, 'char_end': 2668, 'chars': ""'""}, {'char_start': 2669, 'char_end': 2671, 'chars': ' +'}, {'char_start': 2684, 'char_end': 2690, 'chars': ' + ""\'""'}, {'char_start': 2920, 'char_end': 2943, 'chars': '\'"" + str(username) + ""\''}, {'char_start': 2960, 'char_end': 2961, 'chars': ""'""}, {'char_start': 2963, 'char_end': 2964, 'chars': '+'}, {'char_start': 2977, 'char_end': 2983, 'chars': ' + ""\'""'}, {'char_start': 3038, 'char_end': 3061, 'chars': '\'"" + str(last_try) + ""\''}, {'char_start': 3078, 'char_end': 3079, 'chars': ""'""}, {'char_start': 3081, 'char_end': 3082, 'chars': '+'}, {'char_start': 3095, 'char_end': 3101, 'chars': ' + ""\'""'}, {'char_start': 3157, 'char_end': 3158, 'chars': ""'""}, {'char_start': 3159, 'char_end': 3161, 'chars': ' +'}, {'char_start': 3182, 'char_end': 3208, 'chars': ' + ""\' where chat_id = \'"" +'}, {'char_start': 3221, 'char_end': 3227, 'chars': ' + ""\'""'}, {'char_start': 3276, 'char_end': 3292, 'chars': '\'"" + str(1) + ""\''}, {'char_start': 3309, 'char_end': 3310, 'chars': ""'""}, {'char_start': 3312, 'char_end': 3313, 'chars': '+'}, {'char_start': 3326, 'char_end': 3332, 'chars': ' + ""\'""'}], 'added': [{'char_start': 1858, 'char_end': 1859, 'chars': '?'}, {'char_start': 1871, 'char_end': 1872, 'chars': '?'}, {'char_start': 1873, 'char_end': 1874, 'chars': ','}, {'char_start': 1875, 'char_end': 1881, 'chars': '(s[3],'}, {'char_start': 1886, 'char_end': 1887, 'chars': ')'}, {'char_start': 2051, 'char_end': 2052, 'chars': '?'}, {'char_start': 2069, 'char_end': 2070, 'chars': '?'}, {'char_start': 2082, 'char_end': 2083, 'chars': '?'}, {'char_start': 2084, 'char_end': 2085, 'chars': ','}, {'char_start': 2086, 'char_end': 2087, 'chars': '('}, {'char_start': 2088, 'char_end': 2089, 'chars': '2'}, {'char_start': 2090, 'char_end': 2091, 'chars': '1'}, {'char_start': 2092, 'char_end': 2093, 'chars': ','}, {'char_start': 2094, 'char_end': 2099, 'chars': 's[3],'}, {'char_start': 2100, 'char_end': 2105, 'chars': 's[4])'}, {'char_start': 2226, 'char_end': 2227, 'chars': '?'}, {'char_start': 2244, 'char_end': 2245, 'chars': '?'}, {'char_start': 2257, 'char_end': 2258, 'chars': '?'}, {'char_start': 2259, 'char_end': 2260, 'chars': ','}, {'char_start': 2261, 'char_end': 2262, 'chars': '('}, {'char_start': 2263, 'char_end': 2264, 'chars': '2'}, {'char_start': 2265, 'char_end': 2266, 'chars': '1'}, {'char_start': 2267, 'char_end': 2268, 'chars': ','}, {'char_start': 2269, 'char_end': 2274, 'chars': 's[3],'}, {'char_start': 2275, 'char_end': 2279, 'chars': 's[4]'}, {'char_start': 2280, 'char_end': 2281, 'chars': ')'}, {'char_start': 2603, 'char_end': 2604, 'chars': '?'}, {'char_start': 2605, 'char_end': 2606, 'chars': ','}, {'char_start': 2607, 'char_end': 2608, 'chars': '('}, {'char_start': 2620, 'char_end': 2622, 'chars': ',)'}, {'char_start': 2852, 'char_end': 2853, 'chars': '?'}, {'char_start': 2870, 'char_end': 2871, 'chars': '?'}, {'char_start': 2872, 'char_end': 2873, 'chars': ','}, {'char_start': 2874, 'char_end': 2889, 'chars': '(str(username),'}, {'char_start': 2902, 'char_end': 2903, 'chars': ')'}, {'char_start': 2958, 'char_end': 2959, 'chars': '?'}, {'char_start': 2976, 'char_end': 2977, 'chars': '?'}, {'char_start': 2978, 'char_end': 2979, 'chars': ','}, {'char_start': 2980, 'char_end': 2995, 'chars': '(str(last_try),'}, {'char_start': 3008, 'char_end': 3009, 'chars': ')'}, {'char_start': 3065, 'char_end': 3084, 'chars': '? where chat_id = ?'}, {'char_start': 3085, 'char_end': 3086, 'chars': ','}, {'char_start': 3087, 'char_end': 3088, 'chars': '('}, {'char_start': 3108, 'char_end': 3109, 'chars': ','}, {'char_start': 3122, 'char_end': 3123, 'chars': ')'}, {'char_start': 3172, 'char_end': 3173, 'chars': '?'}, {'char_start': 3190, 'char_end': 3191, 'chars': '?'}, {'char_start': 3192, 'char_end': 3193, 'chars': ','}, {'char_start': 3194, 'char_end': 3202, 'chars': '(str(1),'}, {'char_start': 3215, 'char_end': 3216, 'chars': ')'}]}",github.com/lissrbay/codeforces_bot/commit/cc7f5143445a0030b1149ac60a65b1b1b9c92a90,bases/createuserbase.py,cwe-089,870 cwe-416,mrb_vm_exec,"mrb_vm_exec(mrb_state *mrb, struct RProc *proc, mrb_code *pc) { /* mrb_assert(mrb_proc_cfunc_p(proc)) */ mrb_irep *irep = proc->body.irep; mrb_value *pool = irep->pool; mrb_sym *syms = irep->syms; mrb_code i; int ai = mrb_gc_arena_save(mrb); struct mrb_jmpbuf *prev_jmp = mrb->jmp; struct mrb_jmpbuf c_jmp; #ifdef DIRECT_THREADED static void *optable[] = { &&L_OP_NOP, &&L_OP_MOVE, &&L_OP_LOADL, &&L_OP_LOADI, &&L_OP_LOADSYM, &&L_OP_LOADNIL, &&L_OP_LOADSELF, &&L_OP_LOADT, &&L_OP_LOADF, &&L_OP_GETGLOBAL, &&L_OP_SETGLOBAL, &&L_OP_GETSPECIAL, &&L_OP_SETSPECIAL, &&L_OP_GETIV, &&L_OP_SETIV, &&L_OP_GETCV, &&L_OP_SETCV, &&L_OP_GETCONST, &&L_OP_SETCONST, &&L_OP_GETMCNST, &&L_OP_SETMCNST, &&L_OP_GETUPVAR, &&L_OP_SETUPVAR, &&L_OP_JMP, &&L_OP_JMPIF, &&L_OP_JMPNOT, &&L_OP_ONERR, &&L_OP_RESCUE, &&L_OP_POPERR, &&L_OP_RAISE, &&L_OP_EPUSH, &&L_OP_EPOP, &&L_OP_SEND, &&L_OP_SENDB, &&L_OP_FSEND, &&L_OP_CALL, &&L_OP_SUPER, &&L_OP_ARGARY, &&L_OP_ENTER, &&L_OP_KARG, &&L_OP_KDICT, &&L_OP_RETURN, &&L_OP_TAILCALL, &&L_OP_BLKPUSH, &&L_OP_ADD, &&L_OP_ADDI, &&L_OP_SUB, &&L_OP_SUBI, &&L_OP_MUL, &&L_OP_DIV, &&L_OP_EQ, &&L_OP_LT, &&L_OP_LE, &&L_OP_GT, &&L_OP_GE, &&L_OP_ARRAY, &&L_OP_ARYCAT, &&L_OP_ARYPUSH, &&L_OP_AREF, &&L_OP_ASET, &&L_OP_APOST, &&L_OP_STRING, &&L_OP_STRCAT, &&L_OP_HASH, &&L_OP_LAMBDA, &&L_OP_RANGE, &&L_OP_OCLASS, &&L_OP_CLASS, &&L_OP_MODULE, &&L_OP_EXEC, &&L_OP_METHOD, &&L_OP_SCLASS, &&L_OP_TCLASS, &&L_OP_DEBUG, &&L_OP_STOP, &&L_OP_ERR, }; #endif mrb_bool exc_catched = FALSE; RETRY_TRY_BLOCK: MRB_TRY(&c_jmp) { if (exc_catched) { exc_catched = FALSE; if (mrb->exc && mrb->exc->tt == MRB_TT_BREAK) goto L_BREAK; goto L_RAISE; } mrb->jmp = &c_jmp; mrb->c->ci->proc = proc; mrb->c->ci->nregs = irep->nregs; #define regs (mrb->c->stack) INIT_DISPATCH { CASE(OP_NOP) { /* do nothing */ NEXT; } CASE(OP_MOVE) { /* A B R(A) := R(B) */ int a = GETARG_A(i); int b = GETARG_B(i); regs[a] = regs[b]; NEXT; } CASE(OP_LOADL) { /* A Bx R(A) := Pool(Bx) */ int a = GETARG_A(i); int bx = GETARG_Bx(i); #ifdef MRB_WORD_BOXING mrb_value val = pool[bx]; #ifndef MRB_WITHOUT_FLOAT if (mrb_float_p(val)) { val = mrb_float_value(mrb, mrb_float(val)); } #endif regs[a] = val; #else regs[a] = pool[bx]; #endif NEXT; } CASE(OP_LOADI) { /* A sBx R(A) := sBx */ int a = GETARG_A(i); mrb_int bx = GETARG_sBx(i); SET_INT_VALUE(regs[a], bx); NEXT; } CASE(OP_LOADSYM) { /* A Bx R(A) := Syms(Bx) */ int a = GETARG_A(i); int bx = GETARG_Bx(i); SET_SYM_VALUE(regs[a], syms[bx]); NEXT; } CASE(OP_LOADSELF) { /* A R(A) := self */ int a = GETARG_A(i); regs[a] = regs[0]; NEXT; } CASE(OP_LOADT) { /* A R(A) := true */ int a = GETARG_A(i); SET_TRUE_VALUE(regs[a]); NEXT; } CASE(OP_LOADF) { /* A R(A) := false */ int a = GETARG_A(i); SET_FALSE_VALUE(regs[a]); NEXT; } CASE(OP_GETGLOBAL) { /* A Bx R(A) := getglobal(Syms(Bx)) */ int a = GETARG_A(i); int bx = GETARG_Bx(i); mrb_value val = mrb_gv_get(mrb, syms[bx]); regs[a] = val; NEXT; } CASE(OP_SETGLOBAL) { /* A Bx setglobal(Syms(Bx), R(A)) */ int a = GETARG_A(i); int bx = GETARG_Bx(i); mrb_gv_set(mrb, syms[bx], regs[a]); NEXT; } CASE(OP_GETSPECIAL) { /* A Bx R(A) := Special[Bx] */ int a = GETARG_A(i); int bx = GETARG_Bx(i); mrb_value val = mrb_vm_special_get(mrb, bx); regs[a] = val; NEXT; } CASE(OP_SETSPECIAL) { /* A Bx Special[Bx] := R(A) */ int a = GETARG_A(i); int bx = GETARG_Bx(i); mrb_vm_special_set(mrb, bx, regs[a]); NEXT; } CASE(OP_GETIV) { /* A Bx R(A) := ivget(Bx) */ int a = GETARG_A(i); int bx = GETARG_Bx(i); mrb_value val = mrb_vm_iv_get(mrb, syms[bx]); regs[a] = val; NEXT; } CASE(OP_SETIV) { /* A Bx ivset(Syms(Bx),R(A)) */ int a = GETARG_A(i); int bx = GETARG_Bx(i); mrb_vm_iv_set(mrb, syms[bx], regs[a]); NEXT; } CASE(OP_GETCV) { /* A Bx R(A) := cvget(Syms(Bx)) */ int a = GETARG_A(i); int bx = GETARG_Bx(i); mrb_value val; ERR_PC_SET(mrb, pc); val = mrb_vm_cv_get(mrb, syms[bx]); ERR_PC_CLR(mrb); regs[a] = val; NEXT; } CASE(OP_SETCV) { /* A Bx cvset(Syms(Bx),R(A)) */ int a = GETARG_A(i); int bx = GETARG_Bx(i); mrb_vm_cv_set(mrb, syms[bx], regs[a]); NEXT; } CASE(OP_GETCONST) { /* A Bx R(A) := constget(Syms(Bx)) */ mrb_value val; int a = GETARG_A(i); int bx = GETARG_Bx(i); mrb_sym sym = syms[bx]; ERR_PC_SET(mrb, pc); val = mrb_vm_const_get(mrb, sym); ERR_PC_CLR(mrb); regs[a] = val; NEXT; } CASE(OP_SETCONST) { /* A Bx constset(Syms(Bx),R(A)) */ int a = GETARG_A(i); int bx = GETARG_Bx(i); mrb_vm_const_set(mrb, syms[bx], regs[a]); NEXT; } CASE(OP_GETMCNST) { /* A Bx R(A) := R(A)::Syms(Bx) */ mrb_value val; int a = GETARG_A(i); int bx = GETARG_Bx(i); ERR_PC_SET(mrb, pc); val = mrb_const_get(mrb, regs[a], syms[bx]); ERR_PC_CLR(mrb); regs[a] = val; NEXT; } CASE(OP_SETMCNST) { /* A Bx R(A+1)::Syms(Bx) := R(A) */ int a = GETARG_A(i); int bx = GETARG_Bx(i); mrb_const_set(mrb, regs[a+1], syms[bx], regs[a]); NEXT; } CASE(OP_GETUPVAR) { /* A B C R(A) := uvget(B,C) */ int a = GETARG_A(i); int b = GETARG_B(i); int c = GETARG_C(i); mrb_value *regs_a = regs + a; struct REnv *e = uvenv(mrb, c); if (!e) { *regs_a = mrb_nil_value(); } else { *regs_a = e->stack[b]; } NEXT; } CASE(OP_SETUPVAR) { /* A B C uvset(B,C,R(A)) */ int a = GETARG_A(i); int b = GETARG_B(i); int c = GETARG_C(i); struct REnv *e = uvenv(mrb, c); if (e) { mrb_value *regs_a = regs + a; if (b < MRB_ENV_STACK_LEN(e)) { e->stack[b] = *regs_a; mrb_write_barrier(mrb, (struct RBasic*)e); } } NEXT; } CASE(OP_JMP) { /* sBx pc+=sBx */ int sbx = GETARG_sBx(i); pc += sbx; JUMP; } CASE(OP_JMPIF) { /* A sBx if R(A) pc+=sBx */ int a = GETARG_A(i); int sbx = GETARG_sBx(i); if (mrb_test(regs[a])) { pc += sbx; JUMP; } NEXT; } CASE(OP_JMPNOT) { /* A sBx if !R(A) pc+=sBx */ int a = GETARG_A(i); int sbx = GETARG_sBx(i); if (!mrb_test(regs[a])) { pc += sbx; JUMP; } NEXT; } CASE(OP_ONERR) { /* sBx pc+=sBx on exception */ int sbx = GETARG_sBx(i); if (mrb->c->rsize <= mrb->c->ci->ridx) { if (mrb->c->rsize == 0) mrb->c->rsize = RESCUE_STACK_INIT_SIZE; else mrb->c->rsize *= 2; mrb->c->rescue = (mrb_code **)mrb_realloc(mrb, mrb->c->rescue, sizeof(mrb_code*) * mrb->c->rsize); } mrb->c->rescue[mrb->c->ci->ridx++] = pc + sbx; NEXT; } CASE(OP_RESCUE) { /* A B R(A) := exc; clear(exc); R(B) := matched (bool) */ int a = GETARG_A(i); int b = GETARG_B(i); int c = GETARG_C(i); mrb_value exc; if (c == 0) { exc = mrb_obj_value(mrb->exc); mrb->exc = 0; } else { /* continued; exc taken from R(A) */ exc = regs[a]; } if (b != 0) { mrb_value e = regs[b]; struct RClass *ec; switch (mrb_type(e)) { case MRB_TT_CLASS: case MRB_TT_MODULE: break; default: { mrb_value exc; exc = mrb_exc_new_str_lit(mrb, E_TYPE_ERROR, ""class or module required for rescue clause""); mrb_exc_set(mrb, exc); goto L_RAISE; } } ec = mrb_class_ptr(e); regs[b] = mrb_bool_value(mrb_obj_is_kind_of(mrb, exc, ec)); } if (a != 0 && c == 0) { regs[a] = exc; } NEXT; } CASE(OP_POPERR) { /* A A.times{rescue_pop()} */ int a = GETARG_A(i); mrb->c->ci->ridx -= a; NEXT; } CASE(OP_RAISE) { /* A raise(R(A)) */ int a = GETARG_A(i); mrb_exc_set(mrb, regs[a]); goto L_RAISE; } CASE(OP_EPUSH) { /* Bx ensure_push(SEQ[Bx]) */ int bx = GETARG_Bx(i); struct RProc *p; p = mrb_closure_new(mrb, irep->reps[bx]); /* push ensure_stack */ if (mrb->c->esize <= mrb->c->eidx+1) { if (mrb->c->esize == 0) mrb->c->esize = ENSURE_STACK_INIT_SIZE; else mrb->c->esize *= 2; mrb->c->ensure = (struct RProc **)mrb_realloc(mrb, mrb->c->ensure, sizeof(struct RProc*) * mrb->c->esize); } mrb->c->ensure[mrb->c->eidx++] = p; mrb->c->ensure[mrb->c->eidx] = NULL; mrb_gc_arena_restore(mrb, ai); NEXT; } CASE(OP_EPOP) { /* A A.times{ensure_pop().call} */ int a = GETARG_A(i); mrb_callinfo *ci = mrb->c->ci; int n, epos = ci->epos; mrb_value self = regs[0]; struct RClass *target_class = ci->target_class; if (mrb->c->eidx <= epos) { NEXT; } if (a > mrb->c->eidx - epos) a = mrb->c->eidx - epos; pc = pc + 1; for (n=0; nc->ensure[epos+n]; mrb->c->ensure[epos+n] = NULL; if (proc == NULL) continue; irep = proc->body.irep; ci = cipush(mrb); ci->mid = ci[-1].mid; ci->argc = 0; ci->proc = proc; ci->stackent = mrb->c->stack; ci->nregs = irep->nregs; ci->target_class = target_class; ci->pc = pc; ci->acc = ci[-1].nregs; mrb->c->stack += ci->acc; stack_extend(mrb, ci->nregs); regs[0] = self; pc = irep->iseq; } pool = irep->pool; syms = irep->syms; mrb->c->eidx = epos; JUMP; } CASE(OP_LOADNIL) { /* A R(A) := nil */ int a = GETARG_A(i); SET_NIL_VALUE(regs[a]); NEXT; } CASE(OP_SENDB) { /* A B C R(A) := call(R(A),Syms(B),R(A+1),...,R(A+C),&R(A+C+1))*/ /* fall through */ }; L_SEND: CASE(OP_SEND) { /* A B C R(A) := call(R(A),Syms(B),R(A+1),...,R(A+C)) */ int a = GETARG_A(i); int n = GETARG_C(i); int argc = (n == CALL_MAXARGS) ? -1 : n; int bidx = (argc < 0) ? a+2 : a+n+1; mrb_method_t m; struct RClass *c; mrb_callinfo *ci = mrb->c->ci; mrb_value recv, blk; mrb_sym mid = syms[GETARG_B(i)]; mrb_assert(bidx < ci->nregs); recv = regs[a]; if (GET_OPCODE(i) != OP_SENDB) { SET_NIL_VALUE(regs[bidx]); blk = regs[bidx]; } else { blk = regs[bidx]; if (!mrb_nil_p(blk) && mrb_type(blk) != MRB_TT_PROC) { blk = mrb_convert_type(mrb, blk, MRB_TT_PROC, ""Proc"", ""to_proc""); /* The stack might have been reallocated during mrb_convert_type(), see #3622 */ regs[bidx] = blk; } } c = mrb_class(mrb, recv); m = mrb_method_search_vm(mrb, &c, mid); if (MRB_METHOD_UNDEF_P(m)) { mrb_sym missing = mrb_intern_lit(mrb, ""method_missing""); m = mrb_method_search_vm(mrb, &c, missing); if (MRB_METHOD_UNDEF_P(m) || (missing == mrb->c->ci->mid && mrb_obj_eq(mrb, regs[0], recv))) { mrb_value args = (argc < 0) ? regs[a+1] : mrb_ary_new_from_values(mrb, n, regs+a+1); ERR_PC_SET(mrb, pc); mrb_method_missing(mrb, mid, recv, args); } if (argc >= 0) { if (a+2 >= irep->nregs) { stack_extend(mrb, a+3); } regs[a+1] = mrb_ary_new_from_values(mrb, n, regs+a+1); regs[a+2] = blk; argc = -1; } mrb_ary_unshift(mrb, regs[a+1], mrb_symbol_value(mid)); mid = missing; } /* push callinfo */ ci = cipush(mrb); ci->mid = mid; ci->stackent = mrb->c->stack; ci->target_class = c; ci->argc = argc; ci->pc = pc + 1; ci->acc = a; /* prepare stack */ mrb->c->stack += a; if (MRB_METHOD_CFUNC_P(m)) { ci->nregs = (argc < 0) ? 3 : n+2; if (MRB_METHOD_PROC_P(m)) { struct RProc *p = MRB_METHOD_PROC(m); ci->proc = p; recv = p->body.func(mrb, recv); } else { recv = MRB_METHOD_FUNC(m)(mrb, recv); } mrb_gc_arena_restore(mrb, ai); mrb_gc_arena_shrink(mrb, ai); if (mrb->exc) goto L_RAISE; ci = mrb->c->ci; if (GET_OPCODE(i) == OP_SENDB) { if (mrb_type(blk) == MRB_TT_PROC) { struct RProc *p = mrb_proc_ptr(blk); if (p && !MRB_PROC_STRICT_P(p) && MRB_PROC_ENV(p) == ci[-1].env) { p->flags |= MRB_PROC_ORPHAN; } } } if (!ci->target_class) { /* return from context modifying method (resume/yield) */ if (ci->acc == CI_ACC_RESUMED) { mrb->jmp = prev_jmp; return recv; } else { mrb_assert(!MRB_PROC_CFUNC_P(ci[-1].proc)); proc = ci[-1].proc; irep = proc->body.irep; pool = irep->pool; syms = irep->syms; } } mrb->c->stack[0] = recv; /* pop stackpos */ mrb->c->stack = ci->stackent; pc = ci->pc; cipop(mrb); JUMP; } else { /* setup environment for calling method */ proc = ci->proc = MRB_METHOD_PROC(m); irep = proc->body.irep; pool = irep->pool; syms = irep->syms; ci->nregs = irep->nregs; stack_extend(mrb, (argc < 0 && ci->nregs < 3) ? 3 : ci->nregs); pc = irep->iseq; JUMP; } } CASE(OP_FSEND) { /* A B C R(A) := fcall(R(A),Syms(B),R(A+1),... ,R(A+C-1)) */ /* not implemented yet */ NEXT; } CASE(OP_CALL) { /* A R(A) := self.call(frame.argc, frame.argv) */ mrb_callinfo *ci; mrb_value recv = mrb->c->stack[0]; struct RProc *m = mrb_proc_ptr(recv); /* replace callinfo */ ci = mrb->c->ci; ci->target_class = MRB_PROC_TARGET_CLASS(m); ci->proc = m; if (MRB_PROC_ENV_P(m)) { mrb_sym mid; struct REnv *e = MRB_PROC_ENV(m); mid = e->mid; if (mid) ci->mid = mid; if (!e->stack) { e->stack = mrb->c->stack; } } /* prepare stack */ if (MRB_PROC_CFUNC_P(m)) { recv = MRB_PROC_CFUNC(m)(mrb, recv); mrb_gc_arena_restore(mrb, ai); mrb_gc_arena_shrink(mrb, ai); if (mrb->exc) goto L_RAISE; /* pop stackpos */ ci = mrb->c->ci; mrb->c->stack = ci->stackent; regs[ci->acc] = recv; pc = ci->pc; cipop(mrb); irep = mrb->c->ci->proc->body.irep; pool = irep->pool; syms = irep->syms; JUMP; } else { /* setup environment for calling method */ proc = m; irep = m->body.irep; if (!irep) { mrb->c->stack[0] = mrb_nil_value(); goto L_RETURN; } pool = irep->pool; syms = irep->syms; ci->nregs = irep->nregs; stack_extend(mrb, ci->nregs); if (ci->argc < 0) { if (irep->nregs > 3) { stack_clear(regs+3, irep->nregs-3); } } else if (ci->argc+2 < irep->nregs) { stack_clear(regs+ci->argc+2, irep->nregs-ci->argc-2); } if (MRB_PROC_ENV_P(m)) { regs[0] = MRB_PROC_ENV(m)->stack[0]; } pc = irep->iseq; JUMP; } } CASE(OP_SUPER) { /* A C R(A) := super(R(A+1),... ,R(A+C+1)) */ int a = GETARG_A(i); int n = GETARG_C(i); int argc = (n == CALL_MAXARGS) ? -1 : n; int bidx = (argc < 0) ? a+2 : a+n+1; mrb_method_t m; struct RClass *c; mrb_callinfo *ci = mrb->c->ci; mrb_value recv, blk; mrb_sym mid = ci->mid; struct RClass* target_class = MRB_PROC_TARGET_CLASS(ci->proc); mrb_assert(bidx < ci->nregs); if (mid == 0 || !target_class) { mrb_value exc = mrb_exc_new_str_lit(mrb, E_NOMETHOD_ERROR, ""super called outside of method""); mrb_exc_set(mrb, exc); goto L_RAISE; } if (target_class->tt == MRB_TT_MODULE) { target_class = ci->target_class; if (target_class->tt != MRB_TT_ICLASS) { mrb_value exc = mrb_exc_new_str_lit(mrb, E_RUNTIME_ERROR, ""superclass info lost [mruby limitations]""); mrb_exc_set(mrb, exc); goto L_RAISE; } } recv = regs[0]; if (!mrb_obj_is_kind_of(mrb, recv, target_class)) { mrb_value exc = mrb_exc_new_str_lit(mrb, E_TYPE_ERROR, ""self has wrong type to call super in this context""); mrb_exc_set(mrb, exc); goto L_RAISE; } blk = regs[bidx]; if (!mrb_nil_p(blk) && mrb_type(blk) != MRB_TT_PROC) { blk = mrb_convert_type(mrb, blk, MRB_TT_PROC, ""Proc"", ""to_proc""); /* The stack or ci stack might have been reallocated during mrb_convert_type(), see #3622 and #3784 */ regs[bidx] = blk; ci = mrb->c->ci; } c = target_class->super; m = mrb_method_search_vm(mrb, &c, mid); if (MRB_METHOD_UNDEF_P(m)) { mrb_sym missing = mrb_intern_lit(mrb, ""method_missing""); if (mid != missing) { c = mrb_class(mrb, recv); } m = mrb_method_search_vm(mrb, &c, missing); if (MRB_METHOD_UNDEF_P(m)) { mrb_value args = (argc < 0) ? regs[a+1] : mrb_ary_new_from_values(mrb, n, regs+a+1); ERR_PC_SET(mrb, pc); mrb_method_missing(mrb, mid, recv, args); } mid = missing; if (argc >= 0) { if (a+2 >= ci->nregs) { stack_extend(mrb, a+3); } regs[a+1] = mrb_ary_new_from_values(mrb, n, regs+a+1); regs[a+2] = blk; argc = -1; } mrb_ary_unshift(mrb, regs[a+1], mrb_symbol_value(ci->mid)); } /* push callinfo */ ci = cipush(mrb); ci->mid = mid; ci->stackent = mrb->c->stack; ci->target_class = c; ci->pc = pc + 1; ci->argc = argc; /* prepare stack */ mrb->c->stack += a; mrb->c->stack[0] = recv; if (MRB_METHOD_CFUNC_P(m)) { mrb_value v; ci->nregs = (argc < 0) ? 3 : n+2; if (MRB_METHOD_PROC_P(m)) { ci->proc = MRB_METHOD_PROC(m); } v = MRB_METHOD_CFUNC(m)(mrb, recv); mrb_gc_arena_restore(mrb, ai); if (mrb->exc) goto L_RAISE; ci = mrb->c->ci; if (!ci->target_class) { /* return from context modifying method (resume/yield) */ if (ci->acc == CI_ACC_RESUMED) { mrb->jmp = prev_jmp; return v; } else { mrb_assert(!MRB_PROC_CFUNC_P(ci[-1].proc)); proc = ci[-1].proc; irep = proc->body.irep; pool = irep->pool; syms = irep->syms; } } mrb->c->stack[0] = v; /* pop stackpos */ mrb->c->stack = ci->stackent; pc = ci->pc; cipop(mrb); JUMP; } else { /* fill callinfo */ ci->acc = a; /* setup environment for calling method */ proc = ci->proc = MRB_METHOD_PROC(m); irep = proc->body.irep; pool = irep->pool; syms = irep->syms; ci->nregs = irep->nregs; stack_extend(mrb, (argc < 0 && ci->nregs < 3) ? 3 : ci->nregs); pc = irep->iseq; JUMP; } } CASE(OP_ARGARY) { /* A Bx R(A) := argument array (16=6:1:5:4) */ int a = GETARG_A(i); int bx = GETARG_Bx(i); int m1 = (bx>>10)&0x3f; int r = (bx>>9)&0x1; int m2 = (bx>>4)&0x1f; int lv = (bx>>0)&0xf; mrb_value *stack; if (mrb->c->ci->mid == 0 || mrb->c->ci->target_class == NULL) { mrb_value exc; L_NOSUPER: exc = mrb_exc_new_str_lit(mrb, E_NOMETHOD_ERROR, ""super called outside of method""); mrb_exc_set(mrb, exc); goto L_RAISE; } if (lv == 0) stack = regs + 1; else { struct REnv *e = uvenv(mrb, lv-1); if (!e) goto L_NOSUPER; if (MRB_ENV_STACK_LEN(e) <= m1+r+m2+1) goto L_NOSUPER; stack = e->stack + 1; } if (r == 0) { regs[a] = mrb_ary_new_from_values(mrb, m1+m2, stack); } else { mrb_value *pp = NULL; struct RArray *rest; int len = 0; if (mrb_array_p(stack[m1])) { struct RArray *ary = mrb_ary_ptr(stack[m1]); pp = ARY_PTR(ary); len = (int)ARY_LEN(ary); } regs[a] = mrb_ary_new_capa(mrb, m1+len+m2); rest = mrb_ary_ptr(regs[a]); if (m1 > 0) { stack_copy(ARY_PTR(rest), stack, m1); } if (len > 0) { stack_copy(ARY_PTR(rest)+m1, pp, len); } if (m2 > 0) { stack_copy(ARY_PTR(rest)+m1+len, stack+m1+1, m2); } ARY_SET_LEN(rest, m1+len+m2); } regs[a+1] = stack[m1+r+m2]; mrb_gc_arena_restore(mrb, ai); NEXT; } CASE(OP_ENTER) { /* Ax arg setup according to flags (23=5:5:1:5:5:1:1) */ /* number of optional arguments times OP_JMP should follow */ mrb_aspec ax = GETARG_Ax(i); int m1 = MRB_ASPEC_REQ(ax); int o = MRB_ASPEC_OPT(ax); int r = MRB_ASPEC_REST(ax); int m2 = MRB_ASPEC_POST(ax); /* unused int k = MRB_ASPEC_KEY(ax); int kd = MRB_ASPEC_KDICT(ax); int b = MRB_ASPEC_BLOCK(ax); */ int argc = mrb->c->ci->argc; mrb_value *argv = regs+1; mrb_value *argv0 = argv; int len = m1 + o + r + m2; mrb_value *blk = &argv[argc < 0 ? 1 : argc]; if (argc < 0) { struct RArray *ary = mrb_ary_ptr(regs[1]); argv = ARY_PTR(ary); argc = (int)ARY_LEN(ary); mrb_gc_protect(mrb, regs[1]); } if (mrb->c->ci->proc && MRB_PROC_STRICT_P(mrb->c->ci->proc)) { if (argc >= 0) { if (argc < m1 + m2 || (r == 0 && argc > len)) { argnum_error(mrb, m1+m2); goto L_RAISE; } } } else if (len > 1 && argc == 1 && mrb_array_p(argv[0])) { mrb_gc_protect(mrb, argv[0]); argc = (int)RARRAY_LEN(argv[0]); argv = RARRAY_PTR(argv[0]); } if (argc < len) { int mlen = m2; if (argc < m1+m2) { if (m1 < argc) mlen = argc - m1; else mlen = 0; } regs[len+1] = *blk; /* move block */ SET_NIL_VALUE(regs[argc+1]); if (argv0 != argv) { value_move(®s[1], argv, argc-mlen); /* m1 + o */ } if (argc < m1) { stack_clear(®s[argc+1], m1-argc); } if (mlen) { value_move(®s[len-m2+1], &argv[argc-mlen], mlen); } if (mlen < m2) { stack_clear(®s[len-m2+mlen+1], m2-mlen); } if (r) { regs[m1+o+1] = mrb_ary_new_capa(mrb, 0); } if (o == 0 || argc < m1+m2) pc++; else pc += argc - m1 - m2 + 1; } else { int rnum = 0; if (argv0 != argv) { regs[len+1] = *blk; /* move block */ value_move(®s[1], argv, m1+o); } if (r) { rnum = argc-m1-o-m2; regs[m1+o+1] = mrb_ary_new_from_values(mrb, rnum, argv+m1+o); } if (m2) { if (argc-m2 > m1) { value_move(®s[m1+o+r+1], &argv[m1+o+rnum], m2); } } if (argv0 == argv) { regs[len+1] = *blk; /* move block */ } pc += o + 1; } mrb->c->ci->argc = len; /* clear local (but non-argument) variables */ if (irep->nlocals-len-2 > 0) { stack_clear(®s[len+2], irep->nlocals-len-2); } JUMP; } CASE(OP_KARG) { /* A B C R(A) := kdict[Syms(B)]; if C kdict.rm(Syms(B)) */ /* if C == 2; raise unless kdict.empty? */ /* OP_JMP should follow to skip init code */ NEXT; } CASE(OP_KDICT) { /* A C R(A) := kdict */ NEXT; } L_RETURN: i = MKOP_AB(OP_RETURN, GETARG_A(i), OP_R_NORMAL); /* fall through */ CASE(OP_RETURN) { /* A B return R(A) (B=normal,in-block return/break) */ mrb_callinfo *ci; #define ecall_adjust() do {\ ptrdiff_t cioff = ci - mrb->c->cibase;\ ecall(mrb);\ ci = mrb->c->cibase + cioff;\ } while (0) ci = mrb->c->ci; if (ci->mid) { mrb_value blk; if (ci->argc < 0) { blk = regs[2]; } else { blk = regs[ci->argc+1]; } if (mrb_type(blk) == MRB_TT_PROC) { struct RProc *p = mrb_proc_ptr(blk); if (!MRB_PROC_STRICT_P(p) && ci > mrb->c->cibase && MRB_PROC_ENV(p) == ci[-1].env) { p->flags |= MRB_PROC_ORPHAN; } } } if (mrb->exc) { mrb_callinfo *ci0; L_RAISE: ci0 = ci = mrb->c->ci; if (ci == mrb->c->cibase) { if (ci->ridx == 0) goto L_FTOP; goto L_RESCUE; } while (ci[0].ridx == ci[-1].ridx) { cipop(mrb); mrb->c->stack = ci->stackent; if (ci->acc == CI_ACC_SKIP && prev_jmp) { mrb->jmp = prev_jmp; MRB_THROW(prev_jmp); } ci = mrb->c->ci; if (ci == mrb->c->cibase) { if (ci->ridx == 0) { L_FTOP: /* fiber top */ if (mrb->c == mrb->root_c) { mrb->c->stack = mrb->c->stbase; goto L_STOP; } else { struct mrb_context *c = mrb->c; while (c->eidx > ci->epos) { ecall_adjust(); } if (c->fib) { mrb_write_barrier(mrb, (struct RBasic*)c->fib); } mrb->c->status = MRB_FIBER_TERMINATED; mrb->c = c->prev; c->prev = NULL; goto L_RAISE; } } break; } /* call ensure only when we skip this callinfo */ if (ci[0].ridx == ci[-1].ridx) { while (mrb->c->eidx > ci->epos) { ecall_adjust(); } } } L_RESCUE: if (ci->ridx == 0) goto L_STOP; proc = ci->proc; irep = proc->body.irep; pool = irep->pool; syms = irep->syms; if (ci < ci0) { mrb->c->stack = ci[1].stackent; } stack_extend(mrb, irep->nregs); pc = mrb->c->rescue[--ci->ridx]; } else { int acc; mrb_value v; struct RProc *dst; ci = mrb->c->ci; v = regs[GETARG_A(i)]; mrb_gc_protect(mrb, v); switch (GETARG_B(i)) { case OP_R_RETURN: /* Fall through to OP_R_NORMAL otherwise */ if (ci->acc >=0 && MRB_PROC_ENV_P(proc) && !MRB_PROC_STRICT_P(proc)) { mrb_callinfo *cibase = mrb->c->cibase; dst = top_proc(mrb, proc); if (MRB_PROC_ENV_P(dst)) { struct REnv *e = MRB_PROC_ENV(dst); if (!MRB_ENV_STACK_SHARED_P(e) || e->cxt != mrb->c) { localjump_error(mrb, LOCALJUMP_ERROR_RETURN); goto L_RAISE; } } while (cibase <= ci && ci->proc != dst) { if (ci->acc < 0) { localjump_error(mrb, LOCALJUMP_ERROR_RETURN); goto L_RAISE; } ci--; } if (ci <= cibase) { localjump_error(mrb, LOCALJUMP_ERROR_RETURN); goto L_RAISE; } break; } case OP_R_NORMAL: NORMAL_RETURN: if (ci == mrb->c->cibase) { struct mrb_context *c; if (!mrb->c->prev) { /* toplevel return */ localjump_error(mrb, LOCALJUMP_ERROR_RETURN); goto L_RAISE; } if (mrb->c->prev->ci == mrb->c->prev->cibase) { mrb_value exc = mrb_exc_new_str_lit(mrb, E_FIBER_ERROR, ""double resume""); mrb_exc_set(mrb, exc); goto L_RAISE; } while (mrb->c->eidx > 0) { ecall(mrb); } /* automatic yield at the end */ c = mrb->c; c->status = MRB_FIBER_TERMINATED; mrb->c = c->prev; c->prev = NULL; mrb->c->status = MRB_FIBER_RUNNING; ci = mrb->c->ci; } break; case OP_R_BREAK: if (MRB_PROC_STRICT_P(proc)) goto NORMAL_RETURN; if (MRB_PROC_ORPHAN_P(proc)) { mrb_value exc; L_BREAK_ERROR: exc = mrb_exc_new_str_lit(mrb, E_LOCALJUMP_ERROR, ""break from proc-closure""); mrb_exc_set(mrb, exc); goto L_RAISE; } if (!MRB_PROC_ENV_P(proc) || !MRB_ENV_STACK_SHARED_P(MRB_PROC_ENV(proc))) { goto L_BREAK_ERROR; } else { struct REnv *e = MRB_PROC_ENV(proc); if (e == mrb->c->cibase->env && proc != mrb->c->cibase->proc) { goto L_BREAK_ERROR; } if (e->cxt != mrb->c) { goto L_BREAK_ERROR; } } while (mrb->c->eidx > mrb->c->ci->epos) { ecall_adjust(); } /* break from fiber block */ if (ci == mrb->c->cibase && ci->pc) { struct mrb_context *c = mrb->c; mrb->c = c->prev; c->prev = NULL; ci = mrb->c->ci; } if (ci->acc < 0) { mrb_gc_arena_restore(mrb, ai); mrb->c->vmexec = FALSE; mrb->exc = (struct RObject*)break_new(mrb, proc, v); mrb->jmp = prev_jmp; MRB_THROW(prev_jmp); } if (FALSE) { L_BREAK: v = ((struct RBreak*)mrb->exc)->val; proc = ((struct RBreak*)mrb->exc)->proc; mrb->exc = NULL; ci = mrb->c->ci; } mrb->c->stack = ci->stackent; proc = proc->upper; while (mrb->c->cibase < ci && ci[-1].proc != proc) { if (ci[-1].acc == CI_ACC_SKIP) { while (ci < mrb->c->ci) { cipop(mrb); } goto L_BREAK_ERROR; } ci--; } if (ci == mrb->c->cibase) { goto L_BREAK_ERROR; } break; default: /* cannot happen */ break; } while (ci < mrb->c->ci) { cipop(mrb); } ci[0].ridx = ci[-1].ridx; while (mrb->c->eidx > ci->epos) { ecall_adjust(); } if (mrb->c->vmexec && !ci->target_class) { mrb_gc_arena_restore(mrb, ai); mrb->c->vmexec = FALSE; mrb->jmp = prev_jmp; return v; } acc = ci->acc; mrb->c->stack = ci->stackent; cipop(mrb); if (acc == CI_ACC_SKIP || acc == CI_ACC_DIRECT) { mrb_gc_arena_restore(mrb, ai); mrb->jmp = prev_jmp; return v; } pc = ci->pc; ci = mrb->c->ci; DEBUG(fprintf(stderr, ""from :%s\n"", mrb_sym2name(mrb, ci->mid))); proc = mrb->c->ci->proc; irep = proc->body.irep; pool = irep->pool; syms = irep->syms; regs[acc] = v; mrb_gc_arena_restore(mrb, ai); } JUMP; } CASE(OP_TAILCALL) { /* A B C return call(R(A),Syms(B),R(A+1),... ,R(A+C+1)) */ int a = GETARG_A(i); int b = GETARG_B(i); int n = GETARG_C(i); mrb_method_t m; struct RClass *c; mrb_callinfo *ci; mrb_value recv; mrb_sym mid = syms[b]; recv = regs[a]; c = mrb_class(mrb, recv); m = mrb_method_search_vm(mrb, &c, mid); if (MRB_METHOD_UNDEF_P(m)) { mrb_value sym = mrb_symbol_value(mid); mrb_sym missing = mrb_intern_lit(mrb, ""method_missing""); m = mrb_method_search_vm(mrb, &c, missing); if (MRB_METHOD_UNDEF_P(m)) { mrb_value args; if (n == CALL_MAXARGS) { args = regs[a+1]; } else { args = mrb_ary_new_from_values(mrb, n, regs+a+1); } ERR_PC_SET(mrb, pc); mrb_method_missing(mrb, mid, recv, args); } mid = missing; if (n == CALL_MAXARGS) { mrb_ary_unshift(mrb, regs[a+1], sym); } else { value_move(regs+a+2, regs+a+1, ++n); regs[a+1] = sym; } } /* replace callinfo */ ci = mrb->c->ci; ci->mid = mid; ci->target_class = c; if (n == CALL_MAXARGS) { ci->argc = -1; } else { ci->argc = n; } /* move stack */ value_move(mrb->c->stack, ®s[a], ci->argc+1); if (MRB_METHOD_CFUNC_P(m)) { mrb_value v = MRB_METHOD_CFUNC(m)(mrb, recv); mrb->c->stack[0] = v; mrb_gc_arena_restore(mrb, ai); goto L_RETURN; } else { /* setup environment for calling method */ struct RProc *p = MRB_METHOD_PROC(m); irep = p->body.irep; pool = irep->pool; syms = irep->syms; if (ci->argc < 0) { stack_extend(mrb, (irep->nregs < 3) ? 3 : irep->nregs); } else { stack_extend(mrb, irep->nregs); } pc = irep->iseq; } JUMP; } CASE(OP_BLKPUSH) { /* A Bx R(A) := block (16=6:1:5:4) */ int a = GETARG_A(i); int bx = GETARG_Bx(i); int m1 = (bx>>10)&0x3f; int r = (bx>>9)&0x1; int m2 = (bx>>4)&0x1f; int lv = (bx>>0)&0xf; mrb_value *stack; if (lv == 0) stack = regs + 1; else { struct REnv *e = uvenv(mrb, lv-1); if (!e || (!MRB_ENV_STACK_SHARED_P(e) && e->mid == 0) || MRB_ENV_STACK_LEN(e) <= m1+r+m2+1) { localjump_error(mrb, LOCALJUMP_ERROR_YIELD); goto L_RAISE; } stack = e->stack + 1; } if (mrb_nil_p(stack[m1+r+m2])) { localjump_error(mrb, LOCALJUMP_ERROR_YIELD); goto L_RAISE; } regs[a] = stack[m1+r+m2]; NEXT; } #define TYPES2(a,b) ((((uint16_t)(a))<<8)|(((uint16_t)(b))&0xff)) #define OP_MATH_BODY(op,v1,v2) do {\ v1(regs[a]) = v1(regs[a]) op v2(regs[a+1]);\ } while(0) CASE(OP_ADD) { /* A B C R(A) := R(A)+R(A+1) (Syms[B]=:+,C=1)*/ int a = GETARG_A(i); /* need to check if op is overridden */ switch (TYPES2(mrb_type(regs[a]),mrb_type(regs[a+1]))) { case TYPES2(MRB_TT_FIXNUM,MRB_TT_FIXNUM): { mrb_int x, y, z; mrb_value *regs_a = regs + a; x = mrb_fixnum(regs_a[0]); y = mrb_fixnum(regs_a[1]); if (mrb_int_add_overflow(x, y, &z)) { #ifndef MRB_WITHOUT_FLOAT SET_FLOAT_VALUE(mrb, regs_a[0], (mrb_float)x + (mrb_float)y); break; #endif } SET_INT_VALUE(regs[a], z); } break; #ifndef MRB_WITHOUT_FLOAT case TYPES2(MRB_TT_FIXNUM,MRB_TT_FLOAT): { mrb_int x = mrb_fixnum(regs[a]); mrb_float y = mrb_float(regs[a+1]); SET_FLOAT_VALUE(mrb, regs[a], (mrb_float)x + y); } break; case TYPES2(MRB_TT_FLOAT,MRB_TT_FIXNUM): #ifdef MRB_WORD_BOXING { mrb_float x = mrb_float(regs[a]); mrb_int y = mrb_fixnum(regs[a+1]); SET_FLOAT_VALUE(mrb, regs[a], x + y); } #else OP_MATH_BODY(+,mrb_float,mrb_fixnum); #endif break; case TYPES2(MRB_TT_FLOAT,MRB_TT_FLOAT): #ifdef MRB_WORD_BOXING { mrb_float x = mrb_float(regs[a]); mrb_float y = mrb_float(regs[a+1]); SET_FLOAT_VALUE(mrb, regs[a], x + y); } #else OP_MATH_BODY(+,mrb_float,mrb_float); #endif break; #endif case TYPES2(MRB_TT_STRING,MRB_TT_STRING): regs[a] = mrb_str_plus(mrb, regs[a], regs[a+1]); break; default: goto L_SEND; } mrb_gc_arena_restore(mrb, ai); NEXT; } CASE(OP_SUB) { /* A B C R(A) := R(A)-R(A+1) (Syms[B]=:-,C=1)*/ int a = GETARG_A(i); /* need to check if op is overridden */ switch (TYPES2(mrb_type(regs[a]),mrb_type(regs[a+1]))) { case TYPES2(MRB_TT_FIXNUM,MRB_TT_FIXNUM): { mrb_int x, y, z; x = mrb_fixnum(regs[a]); y = mrb_fixnum(regs[a+1]); if (mrb_int_sub_overflow(x, y, &z)) { #ifndef MRB_WITHOUT_FLOAT SET_FLOAT_VALUE(mrb, regs[a], (mrb_float)x - (mrb_float)y); break; #endif } SET_INT_VALUE(regs[a], z); } break; #ifndef MRB_WITHOUT_FLOAT case TYPES2(MRB_TT_FIXNUM,MRB_TT_FLOAT): { mrb_int x = mrb_fixnum(regs[a]); mrb_float y = mrb_float(regs[a+1]); SET_FLOAT_VALUE(mrb, regs[a], (mrb_float)x - y); } break; case TYPES2(MRB_TT_FLOAT,MRB_TT_FIXNUM): #ifdef MRB_WORD_BOXING { mrb_float x = mrb_float(regs[a]); mrb_int y = mrb_fixnum(regs[a+1]); SET_FLOAT_VALUE(mrb, regs[a], x - y); } #else OP_MATH_BODY(-,mrb_float,mrb_fixnum); #endif break; case TYPES2(MRB_TT_FLOAT,MRB_TT_FLOAT): #ifdef MRB_WORD_BOXING { mrb_float x = mrb_float(regs[a]); mrb_float y = mrb_float(regs[a+1]); SET_FLOAT_VALUE(mrb, regs[a], x - y); } #else OP_MATH_BODY(-,mrb_float,mrb_float); #endif break; #endif default: goto L_SEND; } NEXT; } CASE(OP_MUL) { /* A B C R(A) := R(A)*R(A+1) (Syms[B]=:*,C=1)*/ int a = GETARG_A(i); /* need to check if op is overridden */ switch (TYPES2(mrb_type(regs[a]),mrb_type(regs[a+1]))) { case TYPES2(MRB_TT_FIXNUM,MRB_TT_FIXNUM): { mrb_int x, y, z; x = mrb_fixnum(regs[a]); y = mrb_fixnum(regs[a+1]); if (mrb_int_mul_overflow(x, y, &z)) { #ifndef MRB_WITHOUT_FLOAT SET_FLOAT_VALUE(mrb, regs[a], (mrb_float)x * (mrb_float)y); break; #endif } SET_INT_VALUE(regs[a], z); } break; #ifndef MRB_WITHOUT_FLOAT case TYPES2(MRB_TT_FIXNUM,MRB_TT_FLOAT): { mrb_int x = mrb_fixnum(regs[a]); mrb_float y = mrb_float(regs[a+1]); SET_FLOAT_VALUE(mrb, regs[a], (mrb_float)x * y); } break; case TYPES2(MRB_TT_FLOAT,MRB_TT_FIXNUM): #ifdef MRB_WORD_BOXING { mrb_float x = mrb_float(regs[a]); mrb_int y = mrb_fixnum(regs[a+1]); SET_FLOAT_VALUE(mrb, regs[a], x * y); } #else OP_MATH_BODY(*,mrb_float,mrb_fixnum); #endif break; case TYPES2(MRB_TT_FLOAT,MRB_TT_FLOAT): #ifdef MRB_WORD_BOXING { mrb_float x = mrb_float(regs[a]); mrb_float y = mrb_float(regs[a+1]); SET_FLOAT_VALUE(mrb, regs[a], x * y); } #else OP_MATH_BODY(*,mrb_float,mrb_float); #endif break; #endif default: goto L_SEND; } NEXT; } CASE(OP_DIV) { /* A B C R(A) := R(A)/R(A+1) (Syms[B]=:/,C=1)*/ int a = GETARG_A(i); #ifndef MRB_WITHOUT_FLOAT double x, y, f; #endif /* need to check if op is overridden */ switch (TYPES2(mrb_type(regs[a]),mrb_type(regs[a+1]))) { case TYPES2(MRB_TT_FIXNUM,MRB_TT_FIXNUM): #ifdef MRB_WITHOUT_FLOAT { mrb_int x = mrb_fixnum(regs[a]); mrb_int y = mrb_fixnum(regs[a+1]); SET_INT_VALUE(regs[a], y ? x / y : 0); } break; #else x = (mrb_float)mrb_fixnum(regs[a]); y = (mrb_float)mrb_fixnum(regs[a+1]); break; case TYPES2(MRB_TT_FIXNUM,MRB_TT_FLOAT): x = (mrb_float)mrb_fixnum(regs[a]); y = mrb_float(regs[a+1]); break; case TYPES2(MRB_TT_FLOAT,MRB_TT_FIXNUM): x = mrb_float(regs[a]); y = (mrb_float)mrb_fixnum(regs[a+1]); break; case TYPES2(MRB_TT_FLOAT,MRB_TT_FLOAT): x = mrb_float(regs[a]); y = mrb_float(regs[a+1]); break; #endif default: goto L_SEND; } #ifndef MRB_WITHOUT_FLOAT if (y == 0) { if (x > 0) f = INFINITY; else if (x < 0) f = -INFINITY; else /* if (x == 0) */ f = NAN; } else { f = x / y; } SET_FLOAT_VALUE(mrb, regs[a], f); #endif NEXT; } CASE(OP_ADDI) { /* A B C R(A) := R(A)+C (Syms[B]=:+)*/ int a = GETARG_A(i); /* need to check if + is overridden */ switch (mrb_type(regs[a])) { case MRB_TT_FIXNUM: { mrb_int x = mrb_fixnum(regs[a]); mrb_int y = GETARG_C(i); mrb_int z; if (mrb_int_add_overflow(x, y, &z)) { #ifndef MRB_WITHOUT_FLOAT SET_FLOAT_VALUE(mrb, regs[a], (mrb_float)x + (mrb_float)y); break; #endif } SET_INT_VALUE(regs[a], z); } break; #ifndef MRB_WITHOUT_FLOAT case MRB_TT_FLOAT: #ifdef MRB_WORD_BOXING { mrb_float x = mrb_float(regs[a]); SET_FLOAT_VALUE(mrb, regs[a], x + GETARG_C(i)); } #else mrb_float(regs[a]) += GETARG_C(i); #endif break; #endif default: SET_INT_VALUE(regs[a+1], GETARG_C(i)); i = MKOP_ABC(OP_SEND, a, GETARG_B(i), 1); goto L_SEND; } NEXT; } CASE(OP_SUBI) { /* A B C R(A) := R(A)-C (Syms[B]=:-)*/ int a = GETARG_A(i); mrb_value *regs_a = regs + a; /* need to check if + is overridden */ switch (mrb_type(regs_a[0])) { case MRB_TT_FIXNUM: { mrb_int x = mrb_fixnum(regs_a[0]); mrb_int y = GETARG_C(i); mrb_int z; if (mrb_int_sub_overflow(x, y, &z)) { #ifndef MRB_WITHOUT_FLOAT SET_FLOAT_VALUE(mrb, regs_a[0], (mrb_float)x - (mrb_float)y); break; #endif } SET_INT_VALUE(regs_a[0], z); } break; #ifndef MRB_WITHOUT_FLOAT case MRB_TT_FLOAT: #ifdef MRB_WORD_BOXING { mrb_float x = mrb_float(regs[a]); SET_FLOAT_VALUE(mrb, regs[a], x - GETARG_C(i)); } #else mrb_float(regs_a[0]) -= GETARG_C(i); #endif break; #endif default: SET_INT_VALUE(regs_a[1], GETARG_C(i)); i = MKOP_ABC(OP_SEND, a, GETARG_B(i), 1); goto L_SEND; } NEXT; } #define OP_CMP_BODY(op,v1,v2) (v1(regs[a]) op v2(regs[a+1])) #ifdef MRB_WITHOUT_FLOAT #define OP_CMP(op) do {\ int result;\ /* need to check if - is overridden */\ switch (TYPES2(mrb_type(regs[a]),mrb_type(regs[a+1]))) {\ case TYPES2(MRB_TT_FIXNUM,MRB_TT_FIXNUM):\ result = OP_CMP_BODY(op,mrb_fixnum,mrb_fixnum);\ break;\ default:\ goto L_SEND;\ }\ if (result) {\ SET_TRUE_VALUE(regs[a]);\ }\ else {\ SET_FALSE_VALUE(regs[a]);\ }\ } while(0) #else #define OP_CMP(op) do {\ int result;\ /* need to check if - is overridden */\ switch (TYPES2(mrb_type(regs[a]),mrb_type(regs[a+1]))) {\ case TYPES2(MRB_TT_FIXNUM,MRB_TT_FIXNUM):\ result = OP_CMP_BODY(op,mrb_fixnum,mrb_fixnum);\ break;\ case TYPES2(MRB_TT_FIXNUM,MRB_TT_FLOAT):\ result = OP_CMP_BODY(op,mrb_fixnum,mrb_float);\ break;\ case TYPES2(MRB_TT_FLOAT,MRB_TT_FIXNUM):\ result = OP_CMP_BODY(op,mrb_float,mrb_fixnum);\ break;\ case TYPES2(MRB_TT_FLOAT,MRB_TT_FLOAT):\ result = OP_CMP_BODY(op,mrb_float,mrb_float);\ break;\ default:\ goto L_SEND;\ }\ if (result) {\ SET_TRUE_VALUE(regs[a]);\ }\ else {\ SET_FALSE_VALUE(regs[a]);\ }\ } while(0) #endif CASE(OP_EQ) { /* A B C R(A) := R(A)==R(A+1) (Syms[B]=:==,C=1)*/ int a = GETARG_A(i); if (mrb_obj_eq(mrb, regs[a], regs[a+1])) { SET_TRUE_VALUE(regs[a]); } else { OP_CMP(==); } NEXT; } CASE(OP_LT) { /* A B C R(A) := R(A)R(A+1) (Syms[B]=:>,C=1)*/ int a = GETARG_A(i); OP_CMP(>); NEXT; } CASE(OP_GE) { /* A B C R(A) := R(A)>=R(A+1) (Syms[B]=:>=,C=1)*/ int a = GETARG_A(i); OP_CMP(>=); NEXT; } CASE(OP_ARRAY) { /* A B C R(A) := ary_new(R(B),R(B+1)..R(B+C)) */ int a = GETARG_A(i); int b = GETARG_B(i); int c = GETARG_C(i); mrb_value v = mrb_ary_new_from_values(mrb, c, ®s[b]); regs[a] = v; mrb_gc_arena_restore(mrb, ai); NEXT; } CASE(OP_ARYCAT) { /* A B mrb_ary_concat(R(A),R(B)) */ int a = GETARG_A(i); int b = GETARG_B(i); mrb_value splat = mrb_ary_splat(mrb, regs[b]); mrb_ary_concat(mrb, regs[a], splat); mrb_gc_arena_restore(mrb, ai); NEXT; } CASE(OP_ARYPUSH) { /* A B R(A).push(R(B)) */ int a = GETARG_A(i); int b = GETARG_B(i); mrb_ary_push(mrb, regs[a], regs[b]); NEXT; } CASE(OP_AREF) { /* A B C R(A) := R(B)[C] */ int a = GETARG_A(i); int b = GETARG_B(i); int c = GETARG_C(i); mrb_value v = regs[b]; if (!mrb_array_p(v)) { if (c == 0) { regs[a] = v; } else { SET_NIL_VALUE(regs[a]); } } else { v = mrb_ary_ref(mrb, v, c); regs[a] = v; } NEXT; } CASE(OP_ASET) { /* A B C R(B)[C] := R(A) */ int a = GETARG_A(i); int b = GETARG_B(i); int c = GETARG_C(i); mrb_ary_set(mrb, regs[b], c, regs[a]); NEXT; } CASE(OP_APOST) { /* A B C *R(A),R(A+1)..R(A+C) := R(A) */ int a = GETARG_A(i); mrb_value v = regs[a]; int pre = GETARG_B(i); int post = GETARG_C(i); struct RArray *ary; int len, idx; if (!mrb_array_p(v)) { v = mrb_ary_new_from_values(mrb, 1, ®s[a]); } ary = mrb_ary_ptr(v); len = (int)ARY_LEN(ary); if (len > pre + post) { v = mrb_ary_new_from_values(mrb, len - pre - post, ARY_PTR(ary)+pre); regs[a++] = v; while (post--) { regs[a++] = ARY_PTR(ary)[len-post-1]; } } else { v = mrb_ary_new_capa(mrb, 0); regs[a++] = v; for (idx=0; idx+prereps[b]; if (c & OP_L_CAPTURE) { p = mrb_closure_new(mrb, nirep); } else { p = mrb_proc_new(mrb, nirep); p->flags |= MRB_PROC_SCOPE; } if (c & OP_L_STRICT) p->flags |= MRB_PROC_STRICT; regs[a] = mrb_obj_value(p); mrb_gc_arena_restore(mrb, ai); NEXT; } CASE(OP_OCLASS) { /* A R(A) := ::Object */ regs[GETARG_A(i)] = mrb_obj_value(mrb->object_class); NEXT; } CASE(OP_CLASS) { /* A B R(A) := newclass(R(A),Syms(B),R(A+1)) */ struct RClass *c = 0, *baseclass; int a = GETARG_A(i); mrb_value base, super; mrb_sym id = syms[GETARG_B(i)]; base = regs[a]; super = regs[a+1]; if (mrb_nil_p(base)) { baseclass = MRB_PROC_TARGET_CLASS(mrb->c->ci->proc); base = mrb_obj_value(baseclass); } c = mrb_vm_define_class(mrb, base, super, id); regs[a] = mrb_obj_value(c); mrb_gc_arena_restore(mrb, ai); NEXT; } CASE(OP_MODULE) { /* A B R(A) := newmodule(R(A),Syms(B)) */ struct RClass *c = 0, *baseclass; int a = GETARG_A(i); mrb_value base; mrb_sym id = syms[GETARG_B(i)]; base = regs[a]; if (mrb_nil_p(base)) { baseclass = MRB_PROC_TARGET_CLASS(mrb->c->ci->proc); base = mrb_obj_value(baseclass); } c = mrb_vm_define_module(mrb, base, id); regs[a] = mrb_obj_value(c); mrb_gc_arena_restore(mrb, ai); NEXT; } CASE(OP_EXEC) { /* A Bx R(A) := blockexec(R(A),SEQ[Bx]) */ int a = GETARG_A(i); int bx = GETARG_Bx(i); mrb_callinfo *ci; mrb_value recv = regs[a]; struct RProc *p; mrb_irep *nirep = irep->reps[bx]; /* prepare closure */ p = mrb_proc_new(mrb, nirep); p->c = NULL; mrb_field_write_barrier(mrb, (struct RBasic*)p, (struct RBasic*)proc); MRB_PROC_SET_TARGET_CLASS(p, mrb_class_ptr(recv)); p->flags |= MRB_PROC_SCOPE; /* prepare call stack */ ci = cipush(mrb); ci->pc = pc + 1; ci->acc = a; ci->mid = 0; ci->stackent = mrb->c->stack; ci->argc = 0; ci->target_class = mrb_class_ptr(recv); /* prepare stack */ mrb->c->stack += a; /* setup block to call */ ci->proc = p; irep = p->body.irep; pool = irep->pool; syms = irep->syms; ci->nregs = irep->nregs; stack_extend(mrb, ci->nregs); stack_clear(regs+1, ci->nregs-1); pc = irep->iseq; JUMP; } CASE(OP_METHOD) { /* A B R(A).newmethod(Syms(B),R(A+1)) */ int a = GETARG_A(i); struct RClass *c = mrb_class_ptr(regs[a]); struct RProc *p = mrb_proc_ptr(regs[a+1]); mrb_method_t m; MRB_METHOD_FROM_PROC(m, p); mrb_define_method_raw(mrb, c, syms[GETARG_B(i)], m); mrb_gc_arena_restore(mrb, ai); NEXT; } CASE(OP_SCLASS) { /* A B R(A) := R(B).singleton_class */ int a = GETARG_A(i); int b = GETARG_B(i); regs[a] = mrb_singleton_class(mrb, regs[b]); mrb_gc_arena_restore(mrb, ai); NEXT; } CASE(OP_TCLASS) { /* A R(A) := target_class */ if (!mrb->c->ci->target_class) { mrb_value exc = mrb_exc_new_str_lit(mrb, E_TYPE_ERROR, ""no target class or module""); mrb_exc_set(mrb, exc); goto L_RAISE; } regs[GETARG_A(i)] = mrb_obj_value(mrb->c->ci->target_class); NEXT; } CASE(OP_RANGE) { /* A B C R(A) := range_new(R(B),R(B+1),C) */ int b = GETARG_B(i); mrb_value val = mrb_range_new(mrb, regs[b], regs[b+1], GETARG_C(i)); regs[GETARG_A(i)] = val; mrb_gc_arena_restore(mrb, ai); NEXT; } CASE(OP_DEBUG) { /* A B C debug print R(A),R(B),R(C) */ #ifdef MRB_ENABLE_DEBUG_HOOK mrb->debug_op_hook(mrb, irep, pc, regs); #else #ifndef MRB_DISABLE_STDIO printf(""OP_DEBUG %d %d %d\n"", GETARG_A(i), GETARG_B(i), GETARG_C(i)); #else abort(); #endif #endif NEXT; } CASE(OP_STOP) { /* stop VM */ L_STOP: while (mrb->c->eidx > 0) { ecall(mrb); } ERR_PC_CLR(mrb); mrb->jmp = prev_jmp; if (mrb->exc) { return mrb_obj_value(mrb->exc); } return regs[irep->nlocals]; } CASE(OP_ERR) { /* Bx raise RuntimeError with message Lit(Bx) */ mrb_value msg = mrb_str_dup(mrb, pool[GETARG_Bx(i)]); mrb_value exc; if (GETARG_A(i) == 0) { exc = mrb_exc_new_str(mrb, E_RUNTIME_ERROR, msg); } else { exc = mrb_exc_new_str(mrb, E_LOCALJUMP_ERROR, msg); } ERR_PC_SET(mrb, pc); mrb_exc_set(mrb, exc); goto L_RAISE; } } END_DISPATCH; #undef regs } MRB_CATCH(&c_jmp) { exc_catched = TRUE; goto RETRY_TRY_BLOCK; } MRB_END_EXC(&c_jmp); }","mrb_vm_exec(mrb_state *mrb, struct RProc *proc, mrb_code *pc) { /* mrb_assert(mrb_proc_cfunc_p(proc)) */ mrb_irep *irep = proc->body.irep; mrb_value *pool = irep->pool; mrb_sym *syms = irep->syms; mrb_code i; int ai = mrb_gc_arena_save(mrb); struct mrb_jmpbuf *prev_jmp = mrb->jmp; struct mrb_jmpbuf c_jmp; #ifdef DIRECT_THREADED static void *optable[] = { &&L_OP_NOP, &&L_OP_MOVE, &&L_OP_LOADL, &&L_OP_LOADI, &&L_OP_LOADSYM, &&L_OP_LOADNIL, &&L_OP_LOADSELF, &&L_OP_LOADT, &&L_OP_LOADF, &&L_OP_GETGLOBAL, &&L_OP_SETGLOBAL, &&L_OP_GETSPECIAL, &&L_OP_SETSPECIAL, &&L_OP_GETIV, &&L_OP_SETIV, &&L_OP_GETCV, &&L_OP_SETCV, &&L_OP_GETCONST, &&L_OP_SETCONST, &&L_OP_GETMCNST, &&L_OP_SETMCNST, &&L_OP_GETUPVAR, &&L_OP_SETUPVAR, &&L_OP_JMP, &&L_OP_JMPIF, &&L_OP_JMPNOT, &&L_OP_ONERR, &&L_OP_RESCUE, &&L_OP_POPERR, &&L_OP_RAISE, &&L_OP_EPUSH, &&L_OP_EPOP, &&L_OP_SEND, &&L_OP_SENDB, &&L_OP_FSEND, &&L_OP_CALL, &&L_OP_SUPER, &&L_OP_ARGARY, &&L_OP_ENTER, &&L_OP_KARG, &&L_OP_KDICT, &&L_OP_RETURN, &&L_OP_TAILCALL, &&L_OP_BLKPUSH, &&L_OP_ADD, &&L_OP_ADDI, &&L_OP_SUB, &&L_OP_SUBI, &&L_OP_MUL, &&L_OP_DIV, &&L_OP_EQ, &&L_OP_LT, &&L_OP_LE, &&L_OP_GT, &&L_OP_GE, &&L_OP_ARRAY, &&L_OP_ARYCAT, &&L_OP_ARYPUSH, &&L_OP_AREF, &&L_OP_ASET, &&L_OP_APOST, &&L_OP_STRING, &&L_OP_STRCAT, &&L_OP_HASH, &&L_OP_LAMBDA, &&L_OP_RANGE, &&L_OP_OCLASS, &&L_OP_CLASS, &&L_OP_MODULE, &&L_OP_EXEC, &&L_OP_METHOD, &&L_OP_SCLASS, &&L_OP_TCLASS, &&L_OP_DEBUG, &&L_OP_STOP, &&L_OP_ERR, }; #endif mrb_bool exc_catched = FALSE; RETRY_TRY_BLOCK: MRB_TRY(&c_jmp) { if (exc_catched) { exc_catched = FALSE; if (mrb->exc && mrb->exc->tt == MRB_TT_BREAK) goto L_BREAK; goto L_RAISE; } mrb->jmp = &c_jmp; mrb->c->ci->proc = proc; mrb->c->ci->nregs = irep->nregs; #define regs (mrb->c->stack) INIT_DISPATCH { CASE(OP_NOP) { /* do nothing */ NEXT; } CASE(OP_MOVE) { /* A B R(A) := R(B) */ int a = GETARG_A(i); int b = GETARG_B(i); regs[a] = regs[b]; NEXT; } CASE(OP_LOADL) { /* A Bx R(A) := Pool(Bx) */ int a = GETARG_A(i); int bx = GETARG_Bx(i); #ifdef MRB_WORD_BOXING mrb_value val = pool[bx]; #ifndef MRB_WITHOUT_FLOAT if (mrb_float_p(val)) { val = mrb_float_value(mrb, mrb_float(val)); } #endif regs[a] = val; #else regs[a] = pool[bx]; #endif NEXT; } CASE(OP_LOADI) { /* A sBx R(A) := sBx */ int a = GETARG_A(i); mrb_int bx = GETARG_sBx(i); SET_INT_VALUE(regs[a], bx); NEXT; } CASE(OP_LOADSYM) { /* A Bx R(A) := Syms(Bx) */ int a = GETARG_A(i); int bx = GETARG_Bx(i); SET_SYM_VALUE(regs[a], syms[bx]); NEXT; } CASE(OP_LOADSELF) { /* A R(A) := self */ int a = GETARG_A(i); regs[a] = regs[0]; NEXT; } CASE(OP_LOADT) { /* A R(A) := true */ int a = GETARG_A(i); SET_TRUE_VALUE(regs[a]); NEXT; } CASE(OP_LOADF) { /* A R(A) := false */ int a = GETARG_A(i); SET_FALSE_VALUE(regs[a]); NEXT; } CASE(OP_GETGLOBAL) { /* A Bx R(A) := getglobal(Syms(Bx)) */ int a = GETARG_A(i); int bx = GETARG_Bx(i); mrb_value val = mrb_gv_get(mrb, syms[bx]); regs[a] = val; NEXT; } CASE(OP_SETGLOBAL) { /* A Bx setglobal(Syms(Bx), R(A)) */ int a = GETARG_A(i); int bx = GETARG_Bx(i); mrb_gv_set(mrb, syms[bx], regs[a]); NEXT; } CASE(OP_GETSPECIAL) { /* A Bx R(A) := Special[Bx] */ int a = GETARG_A(i); int bx = GETARG_Bx(i); mrb_value val = mrb_vm_special_get(mrb, bx); regs[a] = val; NEXT; } CASE(OP_SETSPECIAL) { /* A Bx Special[Bx] := R(A) */ int a = GETARG_A(i); int bx = GETARG_Bx(i); mrb_vm_special_set(mrb, bx, regs[a]); NEXT; } CASE(OP_GETIV) { /* A Bx R(A) := ivget(Bx) */ int a = GETARG_A(i); int bx = GETARG_Bx(i); mrb_value val = mrb_vm_iv_get(mrb, syms[bx]); regs[a] = val; NEXT; } CASE(OP_SETIV) { /* A Bx ivset(Syms(Bx),R(A)) */ int a = GETARG_A(i); int bx = GETARG_Bx(i); mrb_vm_iv_set(mrb, syms[bx], regs[a]); NEXT; } CASE(OP_GETCV) { /* A Bx R(A) := cvget(Syms(Bx)) */ int a = GETARG_A(i); int bx = GETARG_Bx(i); mrb_value val; ERR_PC_SET(mrb, pc); val = mrb_vm_cv_get(mrb, syms[bx]); ERR_PC_CLR(mrb); regs[a] = val; NEXT; } CASE(OP_SETCV) { /* A Bx cvset(Syms(Bx),R(A)) */ int a = GETARG_A(i); int bx = GETARG_Bx(i); mrb_vm_cv_set(mrb, syms[bx], regs[a]); NEXT; } CASE(OP_GETCONST) { /* A Bx R(A) := constget(Syms(Bx)) */ mrb_value val; int a = GETARG_A(i); int bx = GETARG_Bx(i); mrb_sym sym = syms[bx]; ERR_PC_SET(mrb, pc); val = mrb_vm_const_get(mrb, sym); ERR_PC_CLR(mrb); regs[a] = val; NEXT; } CASE(OP_SETCONST) { /* A Bx constset(Syms(Bx),R(A)) */ int a = GETARG_A(i); int bx = GETARG_Bx(i); mrb_vm_const_set(mrb, syms[bx], regs[a]); NEXT; } CASE(OP_GETMCNST) { /* A Bx R(A) := R(A)::Syms(Bx) */ mrb_value val; int a = GETARG_A(i); int bx = GETARG_Bx(i); ERR_PC_SET(mrb, pc); val = mrb_const_get(mrb, regs[a], syms[bx]); ERR_PC_CLR(mrb); regs[a] = val; NEXT; } CASE(OP_SETMCNST) { /* A Bx R(A+1)::Syms(Bx) := R(A) */ int a = GETARG_A(i); int bx = GETARG_Bx(i); mrb_const_set(mrb, regs[a+1], syms[bx], regs[a]); NEXT; } CASE(OP_GETUPVAR) { /* A B C R(A) := uvget(B,C) */ int a = GETARG_A(i); int b = GETARG_B(i); int c = GETARG_C(i); mrb_value *regs_a = regs + a; struct REnv *e = uvenv(mrb, c); if (e && b < MRB_ENV_STACK_LEN(e)) { *regs_a = e->stack[b]; } else { *regs_a = mrb_nil_value(); } NEXT; } CASE(OP_SETUPVAR) { /* A B C uvset(B,C,R(A)) */ int a = GETARG_A(i); int b = GETARG_B(i); int c = GETARG_C(i); struct REnv *e = uvenv(mrb, c); if (e) { mrb_value *regs_a = regs + a; if (b < MRB_ENV_STACK_LEN(e)) { e->stack[b] = *regs_a; mrb_write_barrier(mrb, (struct RBasic*)e); } } NEXT; } CASE(OP_JMP) { /* sBx pc+=sBx */ int sbx = GETARG_sBx(i); pc += sbx; JUMP; } CASE(OP_JMPIF) { /* A sBx if R(A) pc+=sBx */ int a = GETARG_A(i); int sbx = GETARG_sBx(i); if (mrb_test(regs[a])) { pc += sbx; JUMP; } NEXT; } CASE(OP_JMPNOT) { /* A sBx if !R(A) pc+=sBx */ int a = GETARG_A(i); int sbx = GETARG_sBx(i); if (!mrb_test(regs[a])) { pc += sbx; JUMP; } NEXT; } CASE(OP_ONERR) { /* sBx pc+=sBx on exception */ int sbx = GETARG_sBx(i); if (mrb->c->rsize <= mrb->c->ci->ridx) { if (mrb->c->rsize == 0) mrb->c->rsize = RESCUE_STACK_INIT_SIZE; else mrb->c->rsize *= 2; mrb->c->rescue = (mrb_code **)mrb_realloc(mrb, mrb->c->rescue, sizeof(mrb_code*) * mrb->c->rsize); } mrb->c->rescue[mrb->c->ci->ridx++] = pc + sbx; NEXT; } CASE(OP_RESCUE) { /* A B R(A) := exc; clear(exc); R(B) := matched (bool) */ int a = GETARG_A(i); int b = GETARG_B(i); int c = GETARG_C(i); mrb_value exc; if (c == 0) { exc = mrb_obj_value(mrb->exc); mrb->exc = 0; } else { /* continued; exc taken from R(A) */ exc = regs[a]; } if (b != 0) { mrb_value e = regs[b]; struct RClass *ec; switch (mrb_type(e)) { case MRB_TT_CLASS: case MRB_TT_MODULE: break; default: { mrb_value exc; exc = mrb_exc_new_str_lit(mrb, E_TYPE_ERROR, ""class or module required for rescue clause""); mrb_exc_set(mrb, exc); goto L_RAISE; } } ec = mrb_class_ptr(e); regs[b] = mrb_bool_value(mrb_obj_is_kind_of(mrb, exc, ec)); } if (a != 0 && c == 0) { regs[a] = exc; } NEXT; } CASE(OP_POPERR) { /* A A.times{rescue_pop()} */ int a = GETARG_A(i); mrb->c->ci->ridx -= a; NEXT; } CASE(OP_RAISE) { /* A raise(R(A)) */ int a = GETARG_A(i); mrb_exc_set(mrb, regs[a]); goto L_RAISE; } CASE(OP_EPUSH) { /* Bx ensure_push(SEQ[Bx]) */ int bx = GETARG_Bx(i); struct RProc *p; p = mrb_closure_new(mrb, irep->reps[bx]); /* push ensure_stack */ if (mrb->c->esize <= mrb->c->eidx+1) { if (mrb->c->esize == 0) mrb->c->esize = ENSURE_STACK_INIT_SIZE; else mrb->c->esize *= 2; mrb->c->ensure = (struct RProc **)mrb_realloc(mrb, mrb->c->ensure, sizeof(struct RProc*) * mrb->c->esize); } mrb->c->ensure[mrb->c->eidx++] = p; mrb->c->ensure[mrb->c->eidx] = NULL; mrb_gc_arena_restore(mrb, ai); NEXT; } CASE(OP_EPOP) { /* A A.times{ensure_pop().call} */ int a = GETARG_A(i); mrb_callinfo *ci = mrb->c->ci; int n, epos = ci->epos; mrb_value self = regs[0]; struct RClass *target_class = ci->target_class; if (mrb->c->eidx <= epos) { NEXT; } if (a > mrb->c->eidx - epos) a = mrb->c->eidx - epos; pc = pc + 1; for (n=0; nc->ensure[epos+n]; mrb->c->ensure[epos+n] = NULL; if (proc == NULL) continue; irep = proc->body.irep; ci = cipush(mrb); ci->mid = ci[-1].mid; ci->argc = 0; ci->proc = proc; ci->stackent = mrb->c->stack; ci->nregs = irep->nregs; ci->target_class = target_class; ci->pc = pc; ci->acc = ci[-1].nregs; mrb->c->stack += ci->acc; stack_extend(mrb, ci->nregs); regs[0] = self; pc = irep->iseq; } pool = irep->pool; syms = irep->syms; mrb->c->eidx = epos; JUMP; } CASE(OP_LOADNIL) { /* A R(A) := nil */ int a = GETARG_A(i); SET_NIL_VALUE(regs[a]); NEXT; } CASE(OP_SENDB) { /* A B C R(A) := call(R(A),Syms(B),R(A+1),...,R(A+C),&R(A+C+1))*/ /* fall through */ }; L_SEND: CASE(OP_SEND) { /* A B C R(A) := call(R(A),Syms(B),R(A+1),...,R(A+C)) */ int a = GETARG_A(i); int n = GETARG_C(i); int argc = (n == CALL_MAXARGS) ? -1 : n; int bidx = (argc < 0) ? a+2 : a+n+1; mrb_method_t m; struct RClass *c; mrb_callinfo *ci = mrb->c->ci; mrb_value recv, blk; mrb_sym mid = syms[GETARG_B(i)]; mrb_assert(bidx < ci->nregs); recv = regs[a]; if (GET_OPCODE(i) != OP_SENDB) { SET_NIL_VALUE(regs[bidx]); blk = regs[bidx]; } else { blk = regs[bidx]; if (!mrb_nil_p(blk) && mrb_type(blk) != MRB_TT_PROC) { blk = mrb_convert_type(mrb, blk, MRB_TT_PROC, ""Proc"", ""to_proc""); /* The stack might have been reallocated during mrb_convert_type(), see #3622 */ regs[bidx] = blk; } } c = mrb_class(mrb, recv); m = mrb_method_search_vm(mrb, &c, mid); if (MRB_METHOD_UNDEF_P(m)) { mrb_sym missing = mrb_intern_lit(mrb, ""method_missing""); m = mrb_method_search_vm(mrb, &c, missing); if (MRB_METHOD_UNDEF_P(m) || (missing == mrb->c->ci->mid && mrb_obj_eq(mrb, regs[0], recv))) { mrb_value args = (argc < 0) ? regs[a+1] : mrb_ary_new_from_values(mrb, n, regs+a+1); ERR_PC_SET(mrb, pc); mrb_method_missing(mrb, mid, recv, args); } if (argc >= 0) { if (a+2 >= irep->nregs) { stack_extend(mrb, a+3); } regs[a+1] = mrb_ary_new_from_values(mrb, n, regs+a+1); regs[a+2] = blk; argc = -1; } mrb_ary_unshift(mrb, regs[a+1], mrb_symbol_value(mid)); mid = missing; } /* push callinfo */ ci = cipush(mrb); ci->mid = mid; ci->stackent = mrb->c->stack; ci->target_class = c; ci->argc = argc; ci->pc = pc + 1; ci->acc = a; /* prepare stack */ mrb->c->stack += a; if (MRB_METHOD_CFUNC_P(m)) { ci->nregs = (argc < 0) ? 3 : n+2; if (MRB_METHOD_PROC_P(m)) { struct RProc *p = MRB_METHOD_PROC(m); ci->proc = p; recv = p->body.func(mrb, recv); } else { recv = MRB_METHOD_FUNC(m)(mrb, recv); } mrb_gc_arena_restore(mrb, ai); mrb_gc_arena_shrink(mrb, ai); if (mrb->exc) goto L_RAISE; ci = mrb->c->ci; if (GET_OPCODE(i) == OP_SENDB) { if (mrb_type(blk) == MRB_TT_PROC) { struct RProc *p = mrb_proc_ptr(blk); if (p && !MRB_PROC_STRICT_P(p) && MRB_PROC_ENV(p) == ci[-1].env) { p->flags |= MRB_PROC_ORPHAN; } } } if (!ci->target_class) { /* return from context modifying method (resume/yield) */ if (ci->acc == CI_ACC_RESUMED) { mrb->jmp = prev_jmp; return recv; } else { mrb_assert(!MRB_PROC_CFUNC_P(ci[-1].proc)); proc = ci[-1].proc; irep = proc->body.irep; pool = irep->pool; syms = irep->syms; } } mrb->c->stack[0] = recv; /* pop stackpos */ mrb->c->stack = ci->stackent; pc = ci->pc; cipop(mrb); JUMP; } else { /* setup environment for calling method */ proc = ci->proc = MRB_METHOD_PROC(m); irep = proc->body.irep; pool = irep->pool; syms = irep->syms; ci->nregs = irep->nregs; stack_extend(mrb, (argc < 0 && ci->nregs < 3) ? 3 : ci->nregs); pc = irep->iseq; JUMP; } } CASE(OP_FSEND) { /* A B C R(A) := fcall(R(A),Syms(B),R(A+1),... ,R(A+C-1)) */ /* not implemented yet */ NEXT; } CASE(OP_CALL) { /* A R(A) := self.call(frame.argc, frame.argv) */ mrb_callinfo *ci; mrb_value recv = mrb->c->stack[0]; struct RProc *m = mrb_proc_ptr(recv); /* replace callinfo */ ci = mrb->c->ci; ci->target_class = MRB_PROC_TARGET_CLASS(m); ci->proc = m; if (MRB_PROC_ENV_P(m)) { mrb_sym mid; struct REnv *e = MRB_PROC_ENV(m); mid = e->mid; if (mid) ci->mid = mid; if (!e->stack) { e->stack = mrb->c->stack; } } /* prepare stack */ if (MRB_PROC_CFUNC_P(m)) { recv = MRB_PROC_CFUNC(m)(mrb, recv); mrb_gc_arena_restore(mrb, ai); mrb_gc_arena_shrink(mrb, ai); if (mrb->exc) goto L_RAISE; /* pop stackpos */ ci = mrb->c->ci; mrb->c->stack = ci->stackent; regs[ci->acc] = recv; pc = ci->pc; cipop(mrb); irep = mrb->c->ci->proc->body.irep; pool = irep->pool; syms = irep->syms; JUMP; } else { /* setup environment for calling method */ proc = m; irep = m->body.irep; if (!irep) { mrb->c->stack[0] = mrb_nil_value(); goto L_RETURN; } pool = irep->pool; syms = irep->syms; ci->nregs = irep->nregs; stack_extend(mrb, ci->nregs); if (ci->argc < 0) { if (irep->nregs > 3) { stack_clear(regs+3, irep->nregs-3); } } else if (ci->argc+2 < irep->nregs) { stack_clear(regs+ci->argc+2, irep->nregs-ci->argc-2); } if (MRB_PROC_ENV_P(m)) { regs[0] = MRB_PROC_ENV(m)->stack[0]; } pc = irep->iseq; JUMP; } } CASE(OP_SUPER) { /* A C R(A) := super(R(A+1),... ,R(A+C+1)) */ int a = GETARG_A(i); int n = GETARG_C(i); int argc = (n == CALL_MAXARGS) ? -1 : n; int bidx = (argc < 0) ? a+2 : a+n+1; mrb_method_t m; struct RClass *c; mrb_callinfo *ci = mrb->c->ci; mrb_value recv, blk; mrb_sym mid = ci->mid; struct RClass* target_class = MRB_PROC_TARGET_CLASS(ci->proc); mrb_assert(bidx < ci->nregs); if (mid == 0 || !target_class) { mrb_value exc = mrb_exc_new_str_lit(mrb, E_NOMETHOD_ERROR, ""super called outside of method""); mrb_exc_set(mrb, exc); goto L_RAISE; } if (target_class->tt == MRB_TT_MODULE) { target_class = ci->target_class; if (target_class->tt != MRB_TT_ICLASS) { mrb_value exc = mrb_exc_new_str_lit(mrb, E_RUNTIME_ERROR, ""superclass info lost [mruby limitations]""); mrb_exc_set(mrb, exc); goto L_RAISE; } } recv = regs[0]; if (!mrb_obj_is_kind_of(mrb, recv, target_class)) { mrb_value exc = mrb_exc_new_str_lit(mrb, E_TYPE_ERROR, ""self has wrong type to call super in this context""); mrb_exc_set(mrb, exc); goto L_RAISE; } blk = regs[bidx]; if (!mrb_nil_p(blk) && mrb_type(blk) != MRB_TT_PROC) { blk = mrb_convert_type(mrb, blk, MRB_TT_PROC, ""Proc"", ""to_proc""); /* The stack or ci stack might have been reallocated during mrb_convert_type(), see #3622 and #3784 */ regs[bidx] = blk; ci = mrb->c->ci; } c = target_class->super; m = mrb_method_search_vm(mrb, &c, mid); if (MRB_METHOD_UNDEF_P(m)) { mrb_sym missing = mrb_intern_lit(mrb, ""method_missing""); if (mid != missing) { c = mrb_class(mrb, recv); } m = mrb_method_search_vm(mrb, &c, missing); if (MRB_METHOD_UNDEF_P(m)) { mrb_value args = (argc < 0) ? regs[a+1] : mrb_ary_new_from_values(mrb, n, regs+a+1); ERR_PC_SET(mrb, pc); mrb_method_missing(mrb, mid, recv, args); } mid = missing; if (argc >= 0) { if (a+2 >= ci->nregs) { stack_extend(mrb, a+3); } regs[a+1] = mrb_ary_new_from_values(mrb, n, regs+a+1); regs[a+2] = blk; argc = -1; } mrb_ary_unshift(mrb, regs[a+1], mrb_symbol_value(ci->mid)); } /* push callinfo */ ci = cipush(mrb); ci->mid = mid; ci->stackent = mrb->c->stack; ci->target_class = c; ci->pc = pc + 1; ci->argc = argc; /* prepare stack */ mrb->c->stack += a; mrb->c->stack[0] = recv; if (MRB_METHOD_CFUNC_P(m)) { mrb_value v; ci->nregs = (argc < 0) ? 3 : n+2; if (MRB_METHOD_PROC_P(m)) { ci->proc = MRB_METHOD_PROC(m); } v = MRB_METHOD_CFUNC(m)(mrb, recv); mrb_gc_arena_restore(mrb, ai); if (mrb->exc) goto L_RAISE; ci = mrb->c->ci; if (!ci->target_class) { /* return from context modifying method (resume/yield) */ if (ci->acc == CI_ACC_RESUMED) { mrb->jmp = prev_jmp; return v; } else { mrb_assert(!MRB_PROC_CFUNC_P(ci[-1].proc)); proc = ci[-1].proc; irep = proc->body.irep; pool = irep->pool; syms = irep->syms; } } mrb->c->stack[0] = v; /* pop stackpos */ mrb->c->stack = ci->stackent; pc = ci->pc; cipop(mrb); JUMP; } else { /* fill callinfo */ ci->acc = a; /* setup environment for calling method */ proc = ci->proc = MRB_METHOD_PROC(m); irep = proc->body.irep; pool = irep->pool; syms = irep->syms; ci->nregs = irep->nregs; stack_extend(mrb, (argc < 0 && ci->nregs < 3) ? 3 : ci->nregs); pc = irep->iseq; JUMP; } } CASE(OP_ARGARY) { /* A Bx R(A) := argument array (16=6:1:5:4) */ int a = GETARG_A(i); int bx = GETARG_Bx(i); int m1 = (bx>>10)&0x3f; int r = (bx>>9)&0x1; int m2 = (bx>>4)&0x1f; int lv = (bx>>0)&0xf; mrb_value *stack; if (mrb->c->ci->mid == 0 || mrb->c->ci->target_class == NULL) { mrb_value exc; L_NOSUPER: exc = mrb_exc_new_str_lit(mrb, E_NOMETHOD_ERROR, ""super called outside of method""); mrb_exc_set(mrb, exc); goto L_RAISE; } if (lv == 0) stack = regs + 1; else { struct REnv *e = uvenv(mrb, lv-1); if (!e) goto L_NOSUPER; if (MRB_ENV_STACK_LEN(e) <= m1+r+m2+1) goto L_NOSUPER; stack = e->stack + 1; } if (r == 0) { regs[a] = mrb_ary_new_from_values(mrb, m1+m2, stack); } else { mrb_value *pp = NULL; struct RArray *rest; int len = 0; if (mrb_array_p(stack[m1])) { struct RArray *ary = mrb_ary_ptr(stack[m1]); pp = ARY_PTR(ary); len = (int)ARY_LEN(ary); } regs[a] = mrb_ary_new_capa(mrb, m1+len+m2); rest = mrb_ary_ptr(regs[a]); if (m1 > 0) { stack_copy(ARY_PTR(rest), stack, m1); } if (len > 0) { stack_copy(ARY_PTR(rest)+m1, pp, len); } if (m2 > 0) { stack_copy(ARY_PTR(rest)+m1+len, stack+m1+1, m2); } ARY_SET_LEN(rest, m1+len+m2); } regs[a+1] = stack[m1+r+m2]; mrb_gc_arena_restore(mrb, ai); NEXT; } CASE(OP_ENTER) { /* Ax arg setup according to flags (23=5:5:1:5:5:1:1) */ /* number of optional arguments times OP_JMP should follow */ mrb_aspec ax = GETARG_Ax(i); int m1 = MRB_ASPEC_REQ(ax); int o = MRB_ASPEC_OPT(ax); int r = MRB_ASPEC_REST(ax); int m2 = MRB_ASPEC_POST(ax); /* unused int k = MRB_ASPEC_KEY(ax); int kd = MRB_ASPEC_KDICT(ax); int b = MRB_ASPEC_BLOCK(ax); */ int argc = mrb->c->ci->argc; mrb_value *argv = regs+1; mrb_value *argv0 = argv; int len = m1 + o + r + m2; mrb_value *blk = &argv[argc < 0 ? 1 : argc]; if (argc < 0) { struct RArray *ary = mrb_ary_ptr(regs[1]); argv = ARY_PTR(ary); argc = (int)ARY_LEN(ary); mrb_gc_protect(mrb, regs[1]); } if (mrb->c->ci->proc && MRB_PROC_STRICT_P(mrb->c->ci->proc)) { if (argc >= 0) { if (argc < m1 + m2 || (r == 0 && argc > len)) { argnum_error(mrb, m1+m2); goto L_RAISE; } } } else if (len > 1 && argc == 1 && mrb_array_p(argv[0])) { mrb_gc_protect(mrb, argv[0]); argc = (int)RARRAY_LEN(argv[0]); argv = RARRAY_PTR(argv[0]); } if (argc < len) { int mlen = m2; if (argc < m1+m2) { if (m1 < argc) mlen = argc - m1; else mlen = 0; } regs[len+1] = *blk; /* move block */ SET_NIL_VALUE(regs[argc+1]); if (argv0 != argv) { value_move(®s[1], argv, argc-mlen); /* m1 + o */ } if (argc < m1) { stack_clear(®s[argc+1], m1-argc); } if (mlen) { value_move(®s[len-m2+1], &argv[argc-mlen], mlen); } if (mlen < m2) { stack_clear(®s[len-m2+mlen+1], m2-mlen); } if (r) { regs[m1+o+1] = mrb_ary_new_capa(mrb, 0); } if (o == 0 || argc < m1+m2) pc++; else pc += argc - m1 - m2 + 1; } else { int rnum = 0; if (argv0 != argv) { regs[len+1] = *blk; /* move block */ value_move(®s[1], argv, m1+o); } if (r) { rnum = argc-m1-o-m2; regs[m1+o+1] = mrb_ary_new_from_values(mrb, rnum, argv+m1+o); } if (m2) { if (argc-m2 > m1) { value_move(®s[m1+o+r+1], &argv[m1+o+rnum], m2); } } if (argv0 == argv) { regs[len+1] = *blk; /* move block */ } pc += o + 1; } mrb->c->ci->argc = len; /* clear local (but non-argument) variables */ if (irep->nlocals-len-2 > 0) { stack_clear(®s[len+2], irep->nlocals-len-2); } JUMP; } CASE(OP_KARG) { /* A B C R(A) := kdict[Syms(B)]; if C kdict.rm(Syms(B)) */ /* if C == 2; raise unless kdict.empty? */ /* OP_JMP should follow to skip init code */ NEXT; } CASE(OP_KDICT) { /* A C R(A) := kdict */ NEXT; } L_RETURN: i = MKOP_AB(OP_RETURN, GETARG_A(i), OP_R_NORMAL); /* fall through */ CASE(OP_RETURN) { /* A B return R(A) (B=normal,in-block return/break) */ mrb_callinfo *ci; #define ecall_adjust() do {\ ptrdiff_t cioff = ci - mrb->c->cibase;\ ecall(mrb);\ ci = mrb->c->cibase + cioff;\ } while (0) ci = mrb->c->ci; if (ci->mid) { mrb_value blk; if (ci->argc < 0) { blk = regs[2]; } else { blk = regs[ci->argc+1]; } if (mrb_type(blk) == MRB_TT_PROC) { struct RProc *p = mrb_proc_ptr(blk); if (!MRB_PROC_STRICT_P(p) && ci > mrb->c->cibase && MRB_PROC_ENV(p) == ci[-1].env) { p->flags |= MRB_PROC_ORPHAN; } } } if (mrb->exc) { mrb_callinfo *ci0; L_RAISE: ci0 = ci = mrb->c->ci; if (ci == mrb->c->cibase) { if (ci->ridx == 0) goto L_FTOP; goto L_RESCUE; } while (ci[0].ridx == ci[-1].ridx) { cipop(mrb); mrb->c->stack = ci->stackent; if (ci->acc == CI_ACC_SKIP && prev_jmp) { mrb->jmp = prev_jmp; MRB_THROW(prev_jmp); } ci = mrb->c->ci; if (ci == mrb->c->cibase) { if (ci->ridx == 0) { L_FTOP: /* fiber top */ if (mrb->c == mrb->root_c) { mrb->c->stack = mrb->c->stbase; goto L_STOP; } else { struct mrb_context *c = mrb->c; while (c->eidx > ci->epos) { ecall_adjust(); } if (c->fib) { mrb_write_barrier(mrb, (struct RBasic*)c->fib); } mrb->c->status = MRB_FIBER_TERMINATED; mrb->c = c->prev; c->prev = NULL; goto L_RAISE; } } break; } /* call ensure only when we skip this callinfo */ if (ci[0].ridx == ci[-1].ridx) { while (mrb->c->eidx > ci->epos) { ecall_adjust(); } } } L_RESCUE: if (ci->ridx == 0) goto L_STOP; proc = ci->proc; irep = proc->body.irep; pool = irep->pool; syms = irep->syms; if (ci < ci0) { mrb->c->stack = ci[1].stackent; } stack_extend(mrb, irep->nregs); pc = mrb->c->rescue[--ci->ridx]; } else { int acc; mrb_value v; struct RProc *dst; ci = mrb->c->ci; v = regs[GETARG_A(i)]; mrb_gc_protect(mrb, v); switch (GETARG_B(i)) { case OP_R_RETURN: /* Fall through to OP_R_NORMAL otherwise */ if (ci->acc >=0 && MRB_PROC_ENV_P(proc) && !MRB_PROC_STRICT_P(proc)) { mrb_callinfo *cibase = mrb->c->cibase; dst = top_proc(mrb, proc); if (MRB_PROC_ENV_P(dst)) { struct REnv *e = MRB_PROC_ENV(dst); if (!MRB_ENV_STACK_SHARED_P(e) || e->cxt != mrb->c) { localjump_error(mrb, LOCALJUMP_ERROR_RETURN); goto L_RAISE; } } while (cibase <= ci && ci->proc != dst) { if (ci->acc < 0) { localjump_error(mrb, LOCALJUMP_ERROR_RETURN); goto L_RAISE; } ci--; } if (ci <= cibase) { localjump_error(mrb, LOCALJUMP_ERROR_RETURN); goto L_RAISE; } break; } case OP_R_NORMAL: NORMAL_RETURN: if (ci == mrb->c->cibase) { struct mrb_context *c; if (!mrb->c->prev) { /* toplevel return */ localjump_error(mrb, LOCALJUMP_ERROR_RETURN); goto L_RAISE; } if (mrb->c->prev->ci == mrb->c->prev->cibase) { mrb_value exc = mrb_exc_new_str_lit(mrb, E_FIBER_ERROR, ""double resume""); mrb_exc_set(mrb, exc); goto L_RAISE; } while (mrb->c->eidx > 0) { ecall(mrb); } /* automatic yield at the end */ c = mrb->c; c->status = MRB_FIBER_TERMINATED; mrb->c = c->prev; c->prev = NULL; mrb->c->status = MRB_FIBER_RUNNING; ci = mrb->c->ci; } break; case OP_R_BREAK: if (MRB_PROC_STRICT_P(proc)) goto NORMAL_RETURN; if (MRB_PROC_ORPHAN_P(proc)) { mrb_value exc; L_BREAK_ERROR: exc = mrb_exc_new_str_lit(mrb, E_LOCALJUMP_ERROR, ""break from proc-closure""); mrb_exc_set(mrb, exc); goto L_RAISE; } if (!MRB_PROC_ENV_P(proc) || !MRB_ENV_STACK_SHARED_P(MRB_PROC_ENV(proc))) { goto L_BREAK_ERROR; } else { struct REnv *e = MRB_PROC_ENV(proc); if (e == mrb->c->cibase->env && proc != mrb->c->cibase->proc) { goto L_BREAK_ERROR; } if (e->cxt != mrb->c) { goto L_BREAK_ERROR; } } while (mrb->c->eidx > mrb->c->ci->epos) { ecall_adjust(); } /* break from fiber block */ if (ci == mrb->c->cibase && ci->pc) { struct mrb_context *c = mrb->c; mrb->c = c->prev; c->prev = NULL; ci = mrb->c->ci; } if (ci->acc < 0) { mrb_gc_arena_restore(mrb, ai); mrb->c->vmexec = FALSE; mrb->exc = (struct RObject*)break_new(mrb, proc, v); mrb->jmp = prev_jmp; MRB_THROW(prev_jmp); } if (FALSE) { L_BREAK: v = ((struct RBreak*)mrb->exc)->val; proc = ((struct RBreak*)mrb->exc)->proc; mrb->exc = NULL; ci = mrb->c->ci; } mrb->c->stack = ci->stackent; proc = proc->upper; while (mrb->c->cibase < ci && ci[-1].proc != proc) { if (ci[-1].acc == CI_ACC_SKIP) { while (ci < mrb->c->ci) { cipop(mrb); } goto L_BREAK_ERROR; } ci--; } if (ci == mrb->c->cibase) { goto L_BREAK_ERROR; } break; default: /* cannot happen */ break; } while (ci < mrb->c->ci) { cipop(mrb); } ci[0].ridx = ci[-1].ridx; while (mrb->c->eidx > ci->epos) { ecall_adjust(); } if (mrb->c->vmexec && !ci->target_class) { mrb_gc_arena_restore(mrb, ai); mrb->c->vmexec = FALSE; mrb->jmp = prev_jmp; return v; } acc = ci->acc; mrb->c->stack = ci->stackent; cipop(mrb); if (acc == CI_ACC_SKIP || acc == CI_ACC_DIRECT) { mrb_gc_arena_restore(mrb, ai); mrb->jmp = prev_jmp; return v; } pc = ci->pc; ci = mrb->c->ci; DEBUG(fprintf(stderr, ""from :%s\n"", mrb_sym2name(mrb, ci->mid))); proc = mrb->c->ci->proc; irep = proc->body.irep; pool = irep->pool; syms = irep->syms; regs[acc] = v; mrb_gc_arena_restore(mrb, ai); } JUMP; } CASE(OP_TAILCALL) { /* A B C return call(R(A),Syms(B),R(A+1),... ,R(A+C+1)) */ int a = GETARG_A(i); int b = GETARG_B(i); int n = GETARG_C(i); mrb_method_t m; struct RClass *c; mrb_callinfo *ci; mrb_value recv; mrb_sym mid = syms[b]; recv = regs[a]; c = mrb_class(mrb, recv); m = mrb_method_search_vm(mrb, &c, mid); if (MRB_METHOD_UNDEF_P(m)) { mrb_value sym = mrb_symbol_value(mid); mrb_sym missing = mrb_intern_lit(mrb, ""method_missing""); m = mrb_method_search_vm(mrb, &c, missing); if (MRB_METHOD_UNDEF_P(m)) { mrb_value args; if (n == CALL_MAXARGS) { args = regs[a+1]; } else { args = mrb_ary_new_from_values(mrb, n, regs+a+1); } ERR_PC_SET(mrb, pc); mrb_method_missing(mrb, mid, recv, args); } mid = missing; if (n == CALL_MAXARGS) { mrb_ary_unshift(mrb, regs[a+1], sym); } else { value_move(regs+a+2, regs+a+1, ++n); regs[a+1] = sym; } } /* replace callinfo */ ci = mrb->c->ci; ci->mid = mid; ci->target_class = c; if (n == CALL_MAXARGS) { ci->argc = -1; } else { ci->argc = n; } /* move stack */ value_move(mrb->c->stack, ®s[a], ci->argc+1); if (MRB_METHOD_CFUNC_P(m)) { mrb_value v = MRB_METHOD_CFUNC(m)(mrb, recv); mrb->c->stack[0] = v; mrb_gc_arena_restore(mrb, ai); goto L_RETURN; } else { /* setup environment for calling method */ struct RProc *p = MRB_METHOD_PROC(m); irep = p->body.irep; pool = irep->pool; syms = irep->syms; if (ci->argc < 0) { stack_extend(mrb, (irep->nregs < 3) ? 3 : irep->nregs); } else { stack_extend(mrb, irep->nregs); } pc = irep->iseq; } JUMP; } CASE(OP_BLKPUSH) { /* A Bx R(A) := block (16=6:1:5:4) */ int a = GETARG_A(i); int bx = GETARG_Bx(i); int m1 = (bx>>10)&0x3f; int r = (bx>>9)&0x1; int m2 = (bx>>4)&0x1f; int lv = (bx>>0)&0xf; mrb_value *stack; if (lv == 0) stack = regs + 1; else { struct REnv *e = uvenv(mrb, lv-1); if (!e || (!MRB_ENV_STACK_SHARED_P(e) && e->mid == 0) || MRB_ENV_STACK_LEN(e) <= m1+r+m2+1) { localjump_error(mrb, LOCALJUMP_ERROR_YIELD); goto L_RAISE; } stack = e->stack + 1; } if (mrb_nil_p(stack[m1+r+m2])) { localjump_error(mrb, LOCALJUMP_ERROR_YIELD); goto L_RAISE; } regs[a] = stack[m1+r+m2]; NEXT; } #define TYPES2(a,b) ((((uint16_t)(a))<<8)|(((uint16_t)(b))&0xff)) #define OP_MATH_BODY(op,v1,v2) do {\ v1(regs[a]) = v1(regs[a]) op v2(regs[a+1]);\ } while(0) CASE(OP_ADD) { /* A B C R(A) := R(A)+R(A+1) (Syms[B]=:+,C=1)*/ int a = GETARG_A(i); /* need to check if op is overridden */ switch (TYPES2(mrb_type(regs[a]),mrb_type(regs[a+1]))) { case TYPES2(MRB_TT_FIXNUM,MRB_TT_FIXNUM): { mrb_int x, y, z; mrb_value *regs_a = regs + a; x = mrb_fixnum(regs_a[0]); y = mrb_fixnum(regs_a[1]); if (mrb_int_add_overflow(x, y, &z)) { #ifndef MRB_WITHOUT_FLOAT SET_FLOAT_VALUE(mrb, regs_a[0], (mrb_float)x + (mrb_float)y); break; #endif } SET_INT_VALUE(regs[a], z); } break; #ifndef MRB_WITHOUT_FLOAT case TYPES2(MRB_TT_FIXNUM,MRB_TT_FLOAT): { mrb_int x = mrb_fixnum(regs[a]); mrb_float y = mrb_float(regs[a+1]); SET_FLOAT_VALUE(mrb, regs[a], (mrb_float)x + y); } break; case TYPES2(MRB_TT_FLOAT,MRB_TT_FIXNUM): #ifdef MRB_WORD_BOXING { mrb_float x = mrb_float(regs[a]); mrb_int y = mrb_fixnum(regs[a+1]); SET_FLOAT_VALUE(mrb, regs[a], x + y); } #else OP_MATH_BODY(+,mrb_float,mrb_fixnum); #endif break; case TYPES2(MRB_TT_FLOAT,MRB_TT_FLOAT): #ifdef MRB_WORD_BOXING { mrb_float x = mrb_float(regs[a]); mrb_float y = mrb_float(regs[a+1]); SET_FLOAT_VALUE(mrb, regs[a], x + y); } #else OP_MATH_BODY(+,mrb_float,mrb_float); #endif break; #endif case TYPES2(MRB_TT_STRING,MRB_TT_STRING): regs[a] = mrb_str_plus(mrb, regs[a], regs[a+1]); break; default: goto L_SEND; } mrb_gc_arena_restore(mrb, ai); NEXT; } CASE(OP_SUB) { /* A B C R(A) := R(A)-R(A+1) (Syms[B]=:-,C=1)*/ int a = GETARG_A(i); /* need to check if op is overridden */ switch (TYPES2(mrb_type(regs[a]),mrb_type(regs[a+1]))) { case TYPES2(MRB_TT_FIXNUM,MRB_TT_FIXNUM): { mrb_int x, y, z; x = mrb_fixnum(regs[a]); y = mrb_fixnum(regs[a+1]); if (mrb_int_sub_overflow(x, y, &z)) { #ifndef MRB_WITHOUT_FLOAT SET_FLOAT_VALUE(mrb, regs[a], (mrb_float)x - (mrb_float)y); break; #endif } SET_INT_VALUE(regs[a], z); } break; #ifndef MRB_WITHOUT_FLOAT case TYPES2(MRB_TT_FIXNUM,MRB_TT_FLOAT): { mrb_int x = mrb_fixnum(regs[a]); mrb_float y = mrb_float(regs[a+1]); SET_FLOAT_VALUE(mrb, regs[a], (mrb_float)x - y); } break; case TYPES2(MRB_TT_FLOAT,MRB_TT_FIXNUM): #ifdef MRB_WORD_BOXING { mrb_float x = mrb_float(regs[a]); mrb_int y = mrb_fixnum(regs[a+1]); SET_FLOAT_VALUE(mrb, regs[a], x - y); } #else OP_MATH_BODY(-,mrb_float,mrb_fixnum); #endif break; case TYPES2(MRB_TT_FLOAT,MRB_TT_FLOAT): #ifdef MRB_WORD_BOXING { mrb_float x = mrb_float(regs[a]); mrb_float y = mrb_float(regs[a+1]); SET_FLOAT_VALUE(mrb, regs[a], x - y); } #else OP_MATH_BODY(-,mrb_float,mrb_float); #endif break; #endif default: goto L_SEND; } NEXT; } CASE(OP_MUL) { /* A B C R(A) := R(A)*R(A+1) (Syms[B]=:*,C=1)*/ int a = GETARG_A(i); /* need to check if op is overridden */ switch (TYPES2(mrb_type(regs[a]),mrb_type(regs[a+1]))) { case TYPES2(MRB_TT_FIXNUM,MRB_TT_FIXNUM): { mrb_int x, y, z; x = mrb_fixnum(regs[a]); y = mrb_fixnum(regs[a+1]); if (mrb_int_mul_overflow(x, y, &z)) { #ifndef MRB_WITHOUT_FLOAT SET_FLOAT_VALUE(mrb, regs[a], (mrb_float)x * (mrb_float)y); break; #endif } SET_INT_VALUE(regs[a], z); } break; #ifndef MRB_WITHOUT_FLOAT case TYPES2(MRB_TT_FIXNUM,MRB_TT_FLOAT): { mrb_int x = mrb_fixnum(regs[a]); mrb_float y = mrb_float(regs[a+1]); SET_FLOAT_VALUE(mrb, regs[a], (mrb_float)x * y); } break; case TYPES2(MRB_TT_FLOAT,MRB_TT_FIXNUM): #ifdef MRB_WORD_BOXING { mrb_float x = mrb_float(regs[a]); mrb_int y = mrb_fixnum(regs[a+1]); SET_FLOAT_VALUE(mrb, regs[a], x * y); } #else OP_MATH_BODY(*,mrb_float,mrb_fixnum); #endif break; case TYPES2(MRB_TT_FLOAT,MRB_TT_FLOAT): #ifdef MRB_WORD_BOXING { mrb_float x = mrb_float(regs[a]); mrb_float y = mrb_float(regs[a+1]); SET_FLOAT_VALUE(mrb, regs[a], x * y); } #else OP_MATH_BODY(*,mrb_float,mrb_float); #endif break; #endif default: goto L_SEND; } NEXT; } CASE(OP_DIV) { /* A B C R(A) := R(A)/R(A+1) (Syms[B]=:/,C=1)*/ int a = GETARG_A(i); #ifndef MRB_WITHOUT_FLOAT double x, y, f; #endif /* need to check if op is overridden */ switch (TYPES2(mrb_type(regs[a]),mrb_type(regs[a+1]))) { case TYPES2(MRB_TT_FIXNUM,MRB_TT_FIXNUM): #ifdef MRB_WITHOUT_FLOAT { mrb_int x = mrb_fixnum(regs[a]); mrb_int y = mrb_fixnum(regs[a+1]); SET_INT_VALUE(regs[a], y ? x / y : 0); } break; #else x = (mrb_float)mrb_fixnum(regs[a]); y = (mrb_float)mrb_fixnum(regs[a+1]); break; case TYPES2(MRB_TT_FIXNUM,MRB_TT_FLOAT): x = (mrb_float)mrb_fixnum(regs[a]); y = mrb_float(regs[a+1]); break; case TYPES2(MRB_TT_FLOAT,MRB_TT_FIXNUM): x = mrb_float(regs[a]); y = (mrb_float)mrb_fixnum(regs[a+1]); break; case TYPES2(MRB_TT_FLOAT,MRB_TT_FLOAT): x = mrb_float(regs[a]); y = mrb_float(regs[a+1]); break; #endif default: goto L_SEND; } #ifndef MRB_WITHOUT_FLOAT if (y == 0) { if (x > 0) f = INFINITY; else if (x < 0) f = -INFINITY; else /* if (x == 0) */ f = NAN; } else { f = x / y; } SET_FLOAT_VALUE(mrb, regs[a], f); #endif NEXT; } CASE(OP_ADDI) { /* A B C R(A) := R(A)+C (Syms[B]=:+)*/ int a = GETARG_A(i); /* need to check if + is overridden */ switch (mrb_type(regs[a])) { case MRB_TT_FIXNUM: { mrb_int x = mrb_fixnum(regs[a]); mrb_int y = GETARG_C(i); mrb_int z; if (mrb_int_add_overflow(x, y, &z)) { #ifndef MRB_WITHOUT_FLOAT SET_FLOAT_VALUE(mrb, regs[a], (mrb_float)x + (mrb_float)y); break; #endif } SET_INT_VALUE(regs[a], z); } break; #ifndef MRB_WITHOUT_FLOAT case MRB_TT_FLOAT: #ifdef MRB_WORD_BOXING { mrb_float x = mrb_float(regs[a]); SET_FLOAT_VALUE(mrb, regs[a], x + GETARG_C(i)); } #else mrb_float(regs[a]) += GETARG_C(i); #endif break; #endif default: SET_INT_VALUE(regs[a+1], GETARG_C(i)); i = MKOP_ABC(OP_SEND, a, GETARG_B(i), 1); goto L_SEND; } NEXT; } CASE(OP_SUBI) { /* A B C R(A) := R(A)-C (Syms[B]=:-)*/ int a = GETARG_A(i); mrb_value *regs_a = regs + a; /* need to check if + is overridden */ switch (mrb_type(regs_a[0])) { case MRB_TT_FIXNUM: { mrb_int x = mrb_fixnum(regs_a[0]); mrb_int y = GETARG_C(i); mrb_int z; if (mrb_int_sub_overflow(x, y, &z)) { #ifndef MRB_WITHOUT_FLOAT SET_FLOAT_VALUE(mrb, regs_a[0], (mrb_float)x - (mrb_float)y); break; #endif } SET_INT_VALUE(regs_a[0], z); } break; #ifndef MRB_WITHOUT_FLOAT case MRB_TT_FLOAT: #ifdef MRB_WORD_BOXING { mrb_float x = mrb_float(regs[a]); SET_FLOAT_VALUE(mrb, regs[a], x - GETARG_C(i)); } #else mrb_float(regs_a[0]) -= GETARG_C(i); #endif break; #endif default: SET_INT_VALUE(regs_a[1], GETARG_C(i)); i = MKOP_ABC(OP_SEND, a, GETARG_B(i), 1); goto L_SEND; } NEXT; } #define OP_CMP_BODY(op,v1,v2) (v1(regs[a]) op v2(regs[a+1])) #ifdef MRB_WITHOUT_FLOAT #define OP_CMP(op) do {\ int result;\ /* need to check if - is overridden */\ switch (TYPES2(mrb_type(regs[a]),mrb_type(regs[a+1]))) {\ case TYPES2(MRB_TT_FIXNUM,MRB_TT_FIXNUM):\ result = OP_CMP_BODY(op,mrb_fixnum,mrb_fixnum);\ break;\ default:\ goto L_SEND;\ }\ if (result) {\ SET_TRUE_VALUE(regs[a]);\ }\ else {\ SET_FALSE_VALUE(regs[a]);\ }\ } while(0) #else #define OP_CMP(op) do {\ int result;\ /* need to check if - is overridden */\ switch (TYPES2(mrb_type(regs[a]),mrb_type(regs[a+1]))) {\ case TYPES2(MRB_TT_FIXNUM,MRB_TT_FIXNUM):\ result = OP_CMP_BODY(op,mrb_fixnum,mrb_fixnum);\ break;\ case TYPES2(MRB_TT_FIXNUM,MRB_TT_FLOAT):\ result = OP_CMP_BODY(op,mrb_fixnum,mrb_float);\ break;\ case TYPES2(MRB_TT_FLOAT,MRB_TT_FIXNUM):\ result = OP_CMP_BODY(op,mrb_float,mrb_fixnum);\ break;\ case TYPES2(MRB_TT_FLOAT,MRB_TT_FLOAT):\ result = OP_CMP_BODY(op,mrb_float,mrb_float);\ break;\ default:\ goto L_SEND;\ }\ if (result) {\ SET_TRUE_VALUE(regs[a]);\ }\ else {\ SET_FALSE_VALUE(regs[a]);\ }\ } while(0) #endif CASE(OP_EQ) { /* A B C R(A) := R(A)==R(A+1) (Syms[B]=:==,C=1)*/ int a = GETARG_A(i); if (mrb_obj_eq(mrb, regs[a], regs[a+1])) { SET_TRUE_VALUE(regs[a]); } else { OP_CMP(==); } NEXT; } CASE(OP_LT) { /* A B C R(A) := R(A)R(A+1) (Syms[B]=:>,C=1)*/ int a = GETARG_A(i); OP_CMP(>); NEXT; } CASE(OP_GE) { /* A B C R(A) := R(A)>=R(A+1) (Syms[B]=:>=,C=1)*/ int a = GETARG_A(i); OP_CMP(>=); NEXT; } CASE(OP_ARRAY) { /* A B C R(A) := ary_new(R(B),R(B+1)..R(B+C)) */ int a = GETARG_A(i); int b = GETARG_B(i); int c = GETARG_C(i); mrb_value v = mrb_ary_new_from_values(mrb, c, ®s[b]); regs[a] = v; mrb_gc_arena_restore(mrb, ai); NEXT; } CASE(OP_ARYCAT) { /* A B mrb_ary_concat(R(A),R(B)) */ int a = GETARG_A(i); int b = GETARG_B(i); mrb_value splat = mrb_ary_splat(mrb, regs[b]); mrb_ary_concat(mrb, regs[a], splat); mrb_gc_arena_restore(mrb, ai); NEXT; } CASE(OP_ARYPUSH) { /* A B R(A).push(R(B)) */ int a = GETARG_A(i); int b = GETARG_B(i); mrb_ary_push(mrb, regs[a], regs[b]); NEXT; } CASE(OP_AREF) { /* A B C R(A) := R(B)[C] */ int a = GETARG_A(i); int b = GETARG_B(i); int c = GETARG_C(i); mrb_value v = regs[b]; if (!mrb_array_p(v)) { if (c == 0) { regs[a] = v; } else { SET_NIL_VALUE(regs[a]); } } else { v = mrb_ary_ref(mrb, v, c); regs[a] = v; } NEXT; } CASE(OP_ASET) { /* A B C R(B)[C] := R(A) */ int a = GETARG_A(i); int b = GETARG_B(i); int c = GETARG_C(i); mrb_ary_set(mrb, regs[b], c, regs[a]); NEXT; } CASE(OP_APOST) { /* A B C *R(A),R(A+1)..R(A+C) := R(A) */ int a = GETARG_A(i); mrb_value v = regs[a]; int pre = GETARG_B(i); int post = GETARG_C(i); struct RArray *ary; int len, idx; if (!mrb_array_p(v)) { v = mrb_ary_new_from_values(mrb, 1, ®s[a]); } ary = mrb_ary_ptr(v); len = (int)ARY_LEN(ary); if (len > pre + post) { v = mrb_ary_new_from_values(mrb, len - pre - post, ARY_PTR(ary)+pre); regs[a++] = v; while (post--) { regs[a++] = ARY_PTR(ary)[len-post-1]; } } else { v = mrb_ary_new_capa(mrb, 0); regs[a++] = v; for (idx=0; idx+prereps[b]; if (c & OP_L_CAPTURE) { p = mrb_closure_new(mrb, nirep); } else { p = mrb_proc_new(mrb, nirep); p->flags |= MRB_PROC_SCOPE; } if (c & OP_L_STRICT) p->flags |= MRB_PROC_STRICT; regs[a] = mrb_obj_value(p); mrb_gc_arena_restore(mrb, ai); NEXT; } CASE(OP_OCLASS) { /* A R(A) := ::Object */ regs[GETARG_A(i)] = mrb_obj_value(mrb->object_class); NEXT; } CASE(OP_CLASS) { /* A B R(A) := newclass(R(A),Syms(B),R(A+1)) */ struct RClass *c = 0, *baseclass; int a = GETARG_A(i); mrb_value base, super; mrb_sym id = syms[GETARG_B(i)]; base = regs[a]; super = regs[a+1]; if (mrb_nil_p(base)) { baseclass = MRB_PROC_TARGET_CLASS(mrb->c->ci->proc); base = mrb_obj_value(baseclass); } c = mrb_vm_define_class(mrb, base, super, id); regs[a] = mrb_obj_value(c); mrb_gc_arena_restore(mrb, ai); NEXT; } CASE(OP_MODULE) { /* A B R(A) := newmodule(R(A),Syms(B)) */ struct RClass *c = 0, *baseclass; int a = GETARG_A(i); mrb_value base; mrb_sym id = syms[GETARG_B(i)]; base = regs[a]; if (mrb_nil_p(base)) { baseclass = MRB_PROC_TARGET_CLASS(mrb->c->ci->proc); base = mrb_obj_value(baseclass); } c = mrb_vm_define_module(mrb, base, id); regs[a] = mrb_obj_value(c); mrb_gc_arena_restore(mrb, ai); NEXT; } CASE(OP_EXEC) { /* A Bx R(A) := blockexec(R(A),SEQ[Bx]) */ int a = GETARG_A(i); int bx = GETARG_Bx(i); mrb_callinfo *ci; mrb_value recv = regs[a]; struct RProc *p; mrb_irep *nirep = irep->reps[bx]; /* prepare closure */ p = mrb_proc_new(mrb, nirep); p->c = NULL; mrb_field_write_barrier(mrb, (struct RBasic*)p, (struct RBasic*)proc); MRB_PROC_SET_TARGET_CLASS(p, mrb_class_ptr(recv)); p->flags |= MRB_PROC_SCOPE; /* prepare call stack */ ci = cipush(mrb); ci->pc = pc + 1; ci->acc = a; ci->mid = 0; ci->stackent = mrb->c->stack; ci->argc = 0; ci->target_class = mrb_class_ptr(recv); /* prepare stack */ mrb->c->stack += a; /* setup block to call */ ci->proc = p; irep = p->body.irep; pool = irep->pool; syms = irep->syms; ci->nregs = irep->nregs; stack_extend(mrb, ci->nregs); stack_clear(regs+1, ci->nregs-1); pc = irep->iseq; JUMP; } CASE(OP_METHOD) { /* A B R(A).newmethod(Syms(B),R(A+1)) */ int a = GETARG_A(i); struct RClass *c = mrb_class_ptr(regs[a]); struct RProc *p = mrb_proc_ptr(regs[a+1]); mrb_method_t m; MRB_METHOD_FROM_PROC(m, p); mrb_define_method_raw(mrb, c, syms[GETARG_B(i)], m); mrb_gc_arena_restore(mrb, ai); NEXT; } CASE(OP_SCLASS) { /* A B R(A) := R(B).singleton_class */ int a = GETARG_A(i); int b = GETARG_B(i); regs[a] = mrb_singleton_class(mrb, regs[b]); mrb_gc_arena_restore(mrb, ai); NEXT; } CASE(OP_TCLASS) { /* A R(A) := target_class */ if (!mrb->c->ci->target_class) { mrb_value exc = mrb_exc_new_str_lit(mrb, E_TYPE_ERROR, ""no target class or module""); mrb_exc_set(mrb, exc); goto L_RAISE; } regs[GETARG_A(i)] = mrb_obj_value(mrb->c->ci->target_class); NEXT; } CASE(OP_RANGE) { /* A B C R(A) := range_new(R(B),R(B+1),C) */ int b = GETARG_B(i); mrb_value val = mrb_range_new(mrb, regs[b], regs[b+1], GETARG_C(i)); regs[GETARG_A(i)] = val; mrb_gc_arena_restore(mrb, ai); NEXT; } CASE(OP_DEBUG) { /* A B C debug print R(A),R(B),R(C) */ #ifdef MRB_ENABLE_DEBUG_HOOK mrb->debug_op_hook(mrb, irep, pc, regs); #else #ifndef MRB_DISABLE_STDIO printf(""OP_DEBUG %d %d %d\n"", GETARG_A(i), GETARG_B(i), GETARG_C(i)); #else abort(); #endif #endif NEXT; } CASE(OP_STOP) { /* stop VM */ L_STOP: while (mrb->c->eidx > 0) { ecall(mrb); } ERR_PC_CLR(mrb); mrb->jmp = prev_jmp; if (mrb->exc) { return mrb_obj_value(mrb->exc); } return regs[irep->nlocals]; } CASE(OP_ERR) { /* Bx raise RuntimeError with message Lit(Bx) */ mrb_value msg = mrb_str_dup(mrb, pool[GETARG_Bx(i)]); mrb_value exc; if (GETARG_A(i) == 0) { exc = mrb_exc_new_str(mrb, E_RUNTIME_ERROR, msg); } else { exc = mrb_exc_new_str(mrb, E_LOCALJUMP_ERROR, msg); } ERR_PC_SET(mrb, pc); mrb_exc_set(mrb, exc); goto L_RAISE; } } END_DISPATCH; #undef regs } MRB_CATCH(&c_jmp) { exc_catched = TRUE; goto RETRY_TRY_BLOCK; } MRB_END_EXC(&c_jmp); }","{'deleted': [{'line_no': 244, 'char_start': 6049, 'char_end': 6065, 'line': ' if (!e) {\n'}, {'line_no': 245, 'char_start': 6065, 'char_end': 6100, 'line': ' *regs_a = mrb_nil_value();\n'}, {'line_no': 248, 'char_start': 6121, 'char_end': 6152, 'line': ' *regs_a = e->stack[b];\n'}], 'added': [{'line_no': 244, 'char_start': 6049, 'char_end': 6092, 'line': ' if (e && b < MRB_ENV_STACK_LEN(e)) {\n'}, {'line_no': 245, 'char_start': 6092, 'char_end': 6123, 'line': ' *regs_a = e->stack[b];\n'}, {'line_no': 248, 'char_start': 6144, 'char_end': 6179, 'line': ' *regs_a = mrb_nil_value();\n'}]}","{'deleted': [{'char_start': 6059, 'char_end': 6060, 'chars': '!'}, {'char_start': 6083, 'char_end': 6085, 'chars': 'mr'}, {'char_start': 6086, 'char_end': 6098, 'chars': '_nil_value()'}, {'char_start': 6139, 'char_end': 6148, 'chars': 'e->stack['}, {'char_start': 6149, 'char_end': 6150, 'chars': ']'}], 'added': [{'char_start': 6060, 'char_end': 6088, 'chars': ' && b < MRB_ENV_STACK_LEN(e)'}, {'char_start': 6111, 'char_end': 6121, 'chars': '->stack[b]'}, {'char_start': 6162, 'char_end': 6174, 'chars': 'mrb_nil_valu'}, {'char_start': 6175, 'char_end': 6177, 'chars': '()'}]}",github.com/mruby/mruby/commit/1905091634a6a2925c911484434448e568330626,src/vm.c,cwe-416,16994 cwe-079,screenshotcommentcounts,"@register.tag @basictag(takes_context=True) def screenshotcommentcounts(context, screenshot): """""" Returns a JSON array of current comments for a screenshot. Each entry in the array has a dictionary containing the following keys: =========== ================================================== Key Description =========== ================================================== text The text of the comment localdraft True if this is the current user's draft comment x The X location of the comment's region y The Y location of the comment's region w The width of the comment's region h The height of the comment's region =========== ================================================== """""" comments = {} user = context.get('user', None) for comment in screenshot.comments.all(): review = get_object_or_none(comment.review) if review and (review.public or review.user == user): position = '%dx%d+%d+%d' % (comment.w, comment.h, \ comment.x, comment.y) comments.setdefault(position, []).append({ 'id': comment.id, 'text': comment.text, 'user': { 'username': review.user.username, 'name': review.user.get_full_name() or review.user.username, }, 'url': comment.get_review_url(), 'localdraft' : review.user == user and \ not review.public, 'x' : comment.x, 'y' : comment.y, 'w' : comment.w, 'h' : comment.h, }) return simplejson.dumps(comments)","@register.tag @basictag(takes_context=True) def screenshotcommentcounts(context, screenshot): """""" Returns a JSON array of current comments for a screenshot. Each entry in the array has a dictionary containing the following keys: =========== ================================================== Key Description =========== ================================================== text The text of the comment localdraft True if this is the current user's draft comment x The X location of the comment's region y The Y location of the comment's region w The width of the comment's region h The height of the comment's region =========== ================================================== """""" comments = {} user = context.get('user', None) for comment in screenshot.comments.all(): review = get_object_or_none(comment.review) if review and (review.public or review.user == user): position = '%dx%d+%d+%d' % (comment.w, comment.h, \ comment.x, comment.y) comments.setdefault(position, []).append({ 'id': comment.id, 'text': escape(comment.text), 'user': { 'username': review.user.username, 'name': review.user.get_full_name() or review.user.username, }, 'url': comment.get_review_url(), 'localdraft' : review.user == user and \ not review.public, 'x' : comment.x, 'y' : comment.y, 'w' : comment.w, 'h' : comment.h, }) return simplejson.dumps(comments)","{'deleted': [{'line_no': 32, 'char_start': 1249, 'char_end': 1287, 'line': "" 'text': comment.text,\n""}], 'added': [{'line_no': 32, 'char_start': 1249, 'char_end': 1295, 'line': "" 'text': escape(comment.text),\n""}]}","{'deleted': [], 'added': [{'char_start': 1273, 'char_end': 1280, 'chars': 'escape('}, {'char_start': 1292, 'char_end': 1293, 'chars': ')'}]}",github.com/reviewboard/reviewboard/commit/7a0a9d94555502278534dedcf2d75e9fccce8c3d,reviewboard/reviews/templatetags/reviewtags.py,cwe-079,332 cwe-089,render_page_edit,"@app.route('//edit') def render_page_edit(page_name): query = db.query(""select page_content.content from page, page_content where page.id = page_content.page_id and page.page_name = '%s' order by page_content.id desc limit 1"" % page_name) wiki_page = query.namedresult() if len(wiki_page) > 0: content = wiki_page[0].content else: content = """" return render_template( 'edit_page.html', page_name = page_name, content = content )","@app.route('//edit') def render_page_edit(page_name): query = db.query(""select page_content.content from page, page_content where page.id = page_content.page_id and page.page_name = $1 order by page_content.id desc limit 1"", page_name) wiki_page = query.namedresult() if len(wiki_page) > 0: content = wiki_page[0].content else: content = """" return render_template( 'edit_page.html', page_name = page_name, content = content )","{'deleted': [{'line_no': 3, 'char_start': 65, 'char_end': 254, 'line': ' query = db.query(""select page_content.content from page, page_content where page.id = page_content.page_id and page.page_name = \'%s\' order by page_content.id desc limit 1"" % page_name)\n'}], 'added': [{'line_no': 3, 'char_start': 65, 'char_end': 251, 'line': ' query = db.query(""select page_content.content from page, page_content where page.id = page_content.page_id and page.page_name = $1 order by page_content.id desc limit 1"", page_name)\n'}]}","{'deleted': [{'char_start': 197, 'char_end': 201, 'chars': ""'%s'""}, {'char_start': 240, 'char_end': 242, 'chars': ' %'}], 'added': [{'char_start': 197, 'char_end': 199, 'chars': '$1'}, {'char_start': 238, 'char_end': 239, 'chars': ','}]}",github.com/Pumala/python_wiki_app_redo/commit/65d60747cd8efb05970304234d3bd949d2088e8b,server.py,cwe-089,122 cwe-416,ap_limit_section,"AP_CORE_DECLARE_NONSTD(const char *) ap_limit_section(cmd_parms *cmd, void *dummy, const char *arg) { const char *endp = ap_strrchr_c(arg, '>'); const char *limited_methods; void *tog = cmd->cmd->cmd_data; apr_int64_t limited = 0; apr_int64_t old_limited = cmd->limited; const char *errmsg; if (endp == NULL) { return unclosed_directive(cmd); } limited_methods = apr_pstrmemdup(cmd->temp_pool, arg, endp - arg); if (!limited_methods[0]) { return missing_container_arg(cmd); } while (limited_methods[0]) { char *method = ap_getword_conf(cmd->temp_pool, &limited_methods); int methnum; /* check for builtin or module registered method number */ methnum = ap_method_number_of(method); if (methnum == M_TRACE && !tog) { return ""TRACE cannot be controlled by , see TraceEnable""; } else if (methnum == M_INVALID) { /* method has not been registered yet, but resource restriction * is always checked before method handling, so register it. */ methnum = ap_method_register(cmd->pool, apr_pstrdup(cmd->pool, method)); } limited |= (AP_METHOD_BIT << methnum); } /* Killing two features with one function, * if (tog == NULL) , else */ limited = tog ? ~limited : limited; if (!(old_limited & limited)) { return apr_pstrcat(cmd->pool, cmd->cmd->name, ""> directive excludes all methods"", NULL); } else if ((old_limited & limited) == old_limited) { return apr_pstrcat(cmd->pool, cmd->cmd->name, ""> directive specifies methods already excluded"", NULL); } cmd->limited &= limited; errmsg = ap_walk_config(cmd->directive->first_child, cmd, cmd->context); cmd->limited = old_limited; return errmsg; }","AP_CORE_DECLARE_NONSTD(const char *) ap_limit_section(cmd_parms *cmd, void *dummy, const char *arg) { const char *endp = ap_strrchr_c(arg, '>'); const char *limited_methods; void *tog = cmd->cmd->cmd_data; apr_int64_t limited = 0; apr_int64_t old_limited = cmd->limited; const char *errmsg; if (endp == NULL) { return unclosed_directive(cmd); } limited_methods = apr_pstrmemdup(cmd->temp_pool, arg, endp - arg); if (!limited_methods[0]) { return missing_container_arg(cmd); } while (limited_methods[0]) { char *method = ap_getword_conf(cmd->temp_pool, &limited_methods); int methnum; /* check for builtin or module registered method number */ methnum = ap_method_number_of(method); if (methnum == M_TRACE && !tog) { return ""TRACE cannot be controlled by , see TraceEnable""; } else if (methnum == M_INVALID) { /* method has not been registered yet, but resource restriction * is always checked before method handling, so register it. */ if (cmd->pool == cmd->temp_pool) { /* In .htaccess, we can't globally register new methods. */ return apr_psprintf(cmd->pool, ""Could not register method '%s' "" ""for %s from .htaccess configuration"", method, cmd->cmd->name); } methnum = ap_method_register(cmd->pool, apr_pstrdup(cmd->pool, method)); } limited |= (AP_METHOD_BIT << methnum); } /* Killing two features with one function, * if (tog == NULL) , else */ limited = tog ? ~limited : limited; if (!(old_limited & limited)) { return apr_pstrcat(cmd->pool, cmd->cmd->name, ""> directive excludes all methods"", NULL); } else if ((old_limited & limited) == old_limited) { return apr_pstrcat(cmd->pool, cmd->cmd->name, ""> directive specifies methods already excluded"", NULL); } cmd->limited &= limited; errmsg = ap_walk_config(cmd->directive->first_child, cmd, cmd->context); cmd->limited = old_limited; return errmsg; }","{'deleted': [], 'added': [{'line_no': 36, 'char_start': 1227, 'char_end': 1274, 'line': ' if (cmd->pool == cmd->temp_pool) {\n'}, {'line_no': 37, 'char_start': 1274, 'char_end': 1350, 'line': "" /* In .htaccess, we can't globally register new methods. */\n""}, {'line_no': 38, 'char_start': 1350, 'char_end': 1431, 'line': ' return apr_psprintf(cmd->pool, ""Could not register method \'%s\' ""\n'}, {'line_no': 39, 'char_start': 1431, 'char_end': 1505, 'line': ' ""for %s from .htaccess configuration"",\n'}, {'line_no': 40, 'char_start': 1505, 'char_end': 1566, 'line': ' method, cmd->cmd->name);\n'}, {'line_no': 41, 'char_start': 1566, 'char_end': 1580, 'line': ' }\n'}]}","{'deleted': [], 'added': [{'char_start': 1239, 'char_end': 1592, 'chars': 'if (cmd->pool == cmd->temp_pool) {\n /* In .htaccess, we can\'t globally register new methods. */\n return apr_psprintf(cmd->pool, ""Could not register method \'%s\' ""\n ""for %s from .htaccess configuration"",\n method, cmd->cmd->name);\n }\n '}]}",github.com/apache/httpd/commit/29afdd2550b3d30a8defece2b95ae81edcf66ac9,server/core.c,cwe-416,470 cwe-125,ntlm_read_NegotiateMessage,"SECURITY_STATUS ntlm_read_NegotiateMessage(NTLM_CONTEXT* context, PSecBuffer buffer) { wStream* s; size_t length; NTLM_NEGOTIATE_MESSAGE* message; message = &context->NEGOTIATE_MESSAGE; ZeroMemory(message, sizeof(NTLM_NEGOTIATE_MESSAGE)); s = Stream_New((BYTE*)buffer->pvBuffer, buffer->cbBuffer); if (!s) return SEC_E_INTERNAL_ERROR; if (ntlm_read_message_header(s, (NTLM_MESSAGE_HEADER*)message) < 0) { Stream_Free(s, FALSE); return SEC_E_INVALID_TOKEN; } if (message->MessageType != MESSAGE_TYPE_NEGOTIATE) { Stream_Free(s, FALSE); return SEC_E_INVALID_TOKEN; } Stream_Read_UINT32(s, message->NegotiateFlags); /* NegotiateFlags (4 bytes) */ if (!((message->NegotiateFlags & NTLMSSP_REQUEST_TARGET) && (message->NegotiateFlags & NTLMSSP_NEGOTIATE_NTLM) && (message->NegotiateFlags & NTLMSSP_NEGOTIATE_UNICODE))) { Stream_Free(s, FALSE); return SEC_E_INVALID_TOKEN; } context->NegotiateFlags = message->NegotiateFlags; /* only set if NTLMSSP_NEGOTIATE_DOMAIN_SUPPLIED is set */ if (ntlm_read_message_fields(s, &(message->DomainName)) < 0) /* DomainNameFields (8 bytes) */ { Stream_Free(s, FALSE); return SEC_E_INVALID_TOKEN; } /* only set if NTLMSSP_NEGOTIATE_WORKSTATION_SUPPLIED is set */ if (ntlm_read_message_fields(s, &(message->Workstation)) < 0) /* WorkstationFields (8 bytes) */ { Stream_Free(s, FALSE); return SEC_E_INVALID_TOKEN; } if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION) { if (ntlm_read_version_info(s, &(message->Version)) < 0) /* Version (8 bytes) */ { Stream_Free(s, FALSE); return SEC_E_INVALID_TOKEN; } } length = Stream_GetPosition(s); buffer->cbBuffer = length; if (!sspi_SecBufferAlloc(&context->NegotiateMessage, length)) { Stream_Free(s, FALSE); return SEC_E_INTERNAL_ERROR; } CopyMemory(context->NegotiateMessage.pvBuffer, buffer->pvBuffer, buffer->cbBuffer); context->NegotiateMessage.BufferType = buffer->BufferType; #ifdef WITH_DEBUG_NTLM WLog_DBG(TAG, ""NEGOTIATE_MESSAGE (length = %"" PRIu32 "")"", context->NegotiateMessage.cbBuffer); winpr_HexDump(TAG, WLOG_DEBUG, context->NegotiateMessage.pvBuffer, context->NegotiateMessage.cbBuffer); ntlm_print_negotiate_flags(message->NegotiateFlags); if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION) ntlm_print_version_info(&(message->Version)); #endif context->state = NTLM_STATE_CHALLENGE; Stream_Free(s, FALSE); return SEC_I_CONTINUE_NEEDED; }","SECURITY_STATUS ntlm_read_NegotiateMessage(NTLM_CONTEXT* context, PSecBuffer buffer) { wStream* s; size_t length; NTLM_NEGOTIATE_MESSAGE* message; message = &context->NEGOTIATE_MESSAGE; ZeroMemory(message, sizeof(NTLM_NEGOTIATE_MESSAGE)); s = Stream_New((BYTE*)buffer->pvBuffer, buffer->cbBuffer); if (!s) return SEC_E_INTERNAL_ERROR; if (ntlm_read_message_header(s, (NTLM_MESSAGE_HEADER*)message) < 0) { Stream_Free(s, FALSE); return SEC_E_INVALID_TOKEN; } if (message->MessageType != MESSAGE_TYPE_NEGOTIATE) { Stream_Free(s, FALSE); return SEC_E_INVALID_TOKEN; } if (Stream_GetRemainingLength(s) < 4) { Stream_Free(s, FALSE); return SEC_E_INVALID_TOKEN; } Stream_Read_UINT32(s, message->NegotiateFlags); /* NegotiateFlags (4 bytes) */ if (!((message->NegotiateFlags & NTLMSSP_REQUEST_TARGET) && (message->NegotiateFlags & NTLMSSP_NEGOTIATE_NTLM) && (message->NegotiateFlags & NTLMSSP_NEGOTIATE_UNICODE))) { Stream_Free(s, FALSE); return SEC_E_INVALID_TOKEN; } context->NegotiateFlags = message->NegotiateFlags; /* only set if NTLMSSP_NEGOTIATE_DOMAIN_SUPPLIED is set */ if (ntlm_read_message_fields(s, &(message->DomainName)) < 0) /* DomainNameFields (8 bytes) */ { Stream_Free(s, FALSE); return SEC_E_INVALID_TOKEN; } /* only set if NTLMSSP_NEGOTIATE_WORKSTATION_SUPPLIED is set */ if (ntlm_read_message_fields(s, &(message->Workstation)) < 0) /* WorkstationFields (8 bytes) */ { Stream_Free(s, FALSE); return SEC_E_INVALID_TOKEN; } if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION) { if (ntlm_read_version_info(s, &(message->Version)) < 0) /* Version (8 bytes) */ { Stream_Free(s, FALSE); return SEC_E_INVALID_TOKEN; } } length = Stream_GetPosition(s); buffer->cbBuffer = length; if (!sspi_SecBufferAlloc(&context->NegotiateMessage, length)) { Stream_Free(s, FALSE); return SEC_E_INTERNAL_ERROR; } CopyMemory(context->NegotiateMessage.pvBuffer, buffer->pvBuffer, buffer->cbBuffer); context->NegotiateMessage.BufferType = buffer->BufferType; #ifdef WITH_DEBUG_NTLM WLog_DBG(TAG, ""NEGOTIATE_MESSAGE (length = %"" PRIu32 "")"", context->NegotiateMessage.cbBuffer); winpr_HexDump(TAG, WLOG_DEBUG, context->NegotiateMessage.pvBuffer, context->NegotiateMessage.cbBuffer); ntlm_print_negotiate_flags(message->NegotiateFlags); if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION) ntlm_print_version_info(&(message->Version)); #endif context->state = NTLM_STATE_CHALLENGE; Stream_Free(s, FALSE); return SEC_I_CONTINUE_NEEDED; }","{'deleted': [], 'added': [{'line_no': 25, 'char_start': 592, 'char_end': 631, 'line': '\tif (Stream_GetRemainingLength(s) < 4)\n'}, {'line_no': 26, 'char_start': 631, 'char_end': 634, 'line': '\t{\n'}, {'line_no': 27, 'char_start': 634, 'char_end': 659, 'line': '\t\tStream_Free(s, FALSE);\n'}, {'line_no': 28, 'char_start': 659, 'char_end': 689, 'line': '\t\treturn SEC_E_INVALID_TOKEN;\n'}, {'line_no': 29, 'char_start': 689, 'char_end': 692, 'line': '\t}\n'}]}","{'deleted': [], 'added': [{'char_start': 593, 'char_end': 693, 'chars': 'if (Stream_GetRemainingLength(s) < 4)\n\t{\n\t\tStream_Free(s, FALSE);\n\t\treturn SEC_E_INVALID_TOKEN;\n\t}\n\t'}]}",github.com/FreeRDP/FreeRDP/commit/8fa38359634a9910b91719818ab02f23c320dbae,winpr/libwinpr/sspi/NTLM/ntlm_message.c,cwe-125,717 cwe-787,xdp_umem_reg,"static int xdp_umem_reg(struct xdp_umem *umem, struct xdp_umem_reg *mr) { bool unaligned_chunks = mr->flags & XDP_UMEM_UNALIGNED_CHUNK_FLAG; u32 chunk_size = mr->chunk_size, headroom = mr->headroom; unsigned int chunks, chunks_per_page; u64 addr = mr->addr, size = mr->len; int size_chk, err; if (chunk_size < XDP_UMEM_MIN_CHUNK_SIZE || chunk_size > PAGE_SIZE) { /* Strictly speaking we could support this, if: * - huge pages, or* * - using an IOMMU, or * - making sure the memory area is consecutive * but for now, we simply say ""computer says no"". */ return -EINVAL; } if (mr->flags & ~(XDP_UMEM_UNALIGNED_CHUNK_FLAG | XDP_UMEM_USES_NEED_WAKEUP)) return -EINVAL; if (!unaligned_chunks && !is_power_of_2(chunk_size)) return -EINVAL; if (!PAGE_ALIGNED(addr)) { /* Memory area has to be page size aligned. For * simplicity, this might change. */ return -EINVAL; } if ((addr + size) < addr) return -EINVAL; chunks = (unsigned int)div_u64(size, chunk_size); if (chunks == 0) return -EINVAL; if (!unaligned_chunks) { chunks_per_page = PAGE_SIZE / chunk_size; if (chunks < chunks_per_page || chunks % chunks_per_page) return -EINVAL; } size_chk = chunk_size - headroom - XDP_PACKET_HEADROOM; if (size_chk < 0) return -EINVAL; umem->address = (unsigned long)addr; umem->chunk_mask = unaligned_chunks ? XSK_UNALIGNED_BUF_ADDR_MASK : ~((u64)chunk_size - 1); umem->size = size; umem->headroom = headroom; umem->chunk_size_nohr = chunk_size - headroom; umem->npgs = size / PAGE_SIZE; umem->pgs = NULL; umem->user = NULL; umem->flags = mr->flags; INIT_LIST_HEAD(&umem->xsk_list); spin_lock_init(&umem->xsk_list_lock); refcount_set(&umem->users, 1); err = xdp_umem_account_pages(umem); if (err) return err; err = xdp_umem_pin_pages(umem); if (err) goto out_account; umem->pages = kvcalloc(umem->npgs, sizeof(*umem->pages), GFP_KERNEL_ACCOUNT); if (!umem->pages) { err = -ENOMEM; goto out_pin; } err = xdp_umem_map_pages(umem); if (!err) return 0; kvfree(umem->pages); out_pin: xdp_umem_unpin_pages(umem); out_account: xdp_umem_unaccount_pages(umem); return err; }","static int xdp_umem_reg(struct xdp_umem *umem, struct xdp_umem_reg *mr) { bool unaligned_chunks = mr->flags & XDP_UMEM_UNALIGNED_CHUNK_FLAG; u32 chunk_size = mr->chunk_size, headroom = mr->headroom; unsigned int chunks, chunks_per_page; u64 addr = mr->addr, size = mr->len; int err; if (chunk_size < XDP_UMEM_MIN_CHUNK_SIZE || chunk_size > PAGE_SIZE) { /* Strictly speaking we could support this, if: * - huge pages, or* * - using an IOMMU, or * - making sure the memory area is consecutive * but for now, we simply say ""computer says no"". */ return -EINVAL; } if (mr->flags & ~(XDP_UMEM_UNALIGNED_CHUNK_FLAG | XDP_UMEM_USES_NEED_WAKEUP)) return -EINVAL; if (!unaligned_chunks && !is_power_of_2(chunk_size)) return -EINVAL; if (!PAGE_ALIGNED(addr)) { /* Memory area has to be page size aligned. For * simplicity, this might change. */ return -EINVAL; } if ((addr + size) < addr) return -EINVAL; chunks = (unsigned int)div_u64(size, chunk_size); if (chunks == 0) return -EINVAL; if (!unaligned_chunks) { chunks_per_page = PAGE_SIZE / chunk_size; if (chunks < chunks_per_page || chunks % chunks_per_page) return -EINVAL; } if (headroom >= chunk_size - XDP_PACKET_HEADROOM) return -EINVAL; umem->address = (unsigned long)addr; umem->chunk_mask = unaligned_chunks ? XSK_UNALIGNED_BUF_ADDR_MASK : ~((u64)chunk_size - 1); umem->size = size; umem->headroom = headroom; umem->chunk_size_nohr = chunk_size - headroom; umem->npgs = size / PAGE_SIZE; umem->pgs = NULL; umem->user = NULL; umem->flags = mr->flags; INIT_LIST_HEAD(&umem->xsk_list); spin_lock_init(&umem->xsk_list_lock); refcount_set(&umem->users, 1); err = xdp_umem_account_pages(umem); if (err) return err; err = xdp_umem_pin_pages(umem); if (err) goto out_account; umem->pages = kvcalloc(umem->npgs, sizeof(*umem->pages), GFP_KERNEL_ACCOUNT); if (!umem->pages) { err = -ENOMEM; goto out_pin; } err = xdp_umem_map_pages(umem); if (!err) return 0; kvfree(umem->pages); out_pin: xdp_umem_unpin_pages(umem); out_account: xdp_umem_unaccount_pages(umem); return err; }","{'deleted': [{'line_no': 7, 'char_start': 278, 'char_end': 298, 'line': '\tint size_chk, err;\n'}, {'line_no': 46, 'char_start': 1202, 'char_end': 1259, 'line': '\tsize_chk = chunk_size - headroom - XDP_PACKET_HEADROOM;\n'}, {'line_no': 47, 'char_start': 1259, 'char_end': 1278, 'line': '\tif (size_chk < 0)\n'}], 'added': [{'line_no': 7, 'char_start': 278, 'char_end': 288, 'line': '\tint err;\n'}, {'line_no': 46, 'char_start': 1192, 'char_end': 1243, 'line': '\tif (headroom >= chunk_size - XDP_PACKET_HEADROOM)\n'}]}","{'deleted': [{'char_start': 283, 'char_end': 293, 'chars': 'size_chk, '}, {'char_start': 1203, 'char_end': 1204, 'chars': 's'}, {'char_start': 1205, 'char_end': 1209, 'chars': 'ze_c'}, {'char_start': 1210, 'char_end': 1211, 'chars': 'k'}, {'char_start': 1227, 'char_end': 1238, 'chars': 'headroom - '}, {'char_start': 1257, 'char_end': 1276, 'chars': ';\n\tif (size_chk < 0'}], 'added': [{'char_start': 1194, 'char_end': 1198, 'chars': 'f (h'}, {'char_start': 1199, 'char_end': 1205, 'chars': 'adroom'}, {'char_start': 1206, 'char_end': 1207, 'chars': '>'}]}",github.com/torvalds/linux/commit/99e3a236dd43d06c65af0a2ef9cb44306aef6e02,net/xdp/xdp_umem.c,cwe-787,697 cwe-125,enc_untrusted_read,"ssize_t enc_untrusted_read(int fd, void *buf, size_t count) { return static_cast(EnsureInitializedAndDispatchSyscall( asylo::system_call::kSYS_read, fd, buf, count)); }","ssize_t enc_untrusted_read(int fd, void *buf, size_t count) { ssize_t ret = static_cast(EnsureInitializedAndDispatchSyscall( asylo::system_call::kSYS_read, fd, buf, count)); if (ret != -1 && ret > count) { ::asylo::primitives::TrustedPrimitives::BestEffortAbort( ""enc_untrusted_read: read result exceeds requested""); } return ret; }","{'deleted': [{'line_no': 2, 'char_start': 62, 'char_end': 129, 'line': ' return static_cast(EnsureInitializedAndDispatchSyscall(\n'}], 'added': [{'line_no': 2, 'char_start': 62, 'char_end': 136, 'line': ' ssize_t ret = static_cast(EnsureInitializedAndDispatchSyscall(\n'}, {'line_no': 4, 'char_start': 191, 'char_end': 225, 'line': ' if (ret != -1 && ret > count) {\n'}, {'line_no': 5, 'char_start': 225, 'char_end': 286, 'line': ' ::asylo::primitives::TrustedPrimitives::BestEffortAbort(\n'}, {'line_no': 6, 'char_start': 286, 'char_end': 348, 'line': ' ""enc_untrusted_read: read result exceeds requested"");\n'}, {'line_no': 7, 'char_start': 348, 'char_end': 352, 'line': ' }\n'}, {'line_no': 8, 'char_start': 352, 'char_end': 366, 'line': ' return ret;\n'}]}","{'deleted': [{'char_start': 67, 'char_end': 70, 'chars': 'urn'}], 'added': [{'char_start': 64, 'char_end': 68, 'chars': 'ssiz'}, {'char_start': 69, 'char_end': 70, 'chars': '_'}, {'char_start': 71, 'char_end': 72, 'chars': ' '}, {'char_start': 73, 'char_end': 77, 'chars': 'et ='}, {'char_start': 189, 'char_end': 364, 'chars': ';\n if (ret != -1 && ret > count) {\n ::asylo::primitives::TrustedPrimitives::BestEffortAbort(\n ""enc_untrusted_read: read result exceeds requested"");\n }\n return ret'}]}",github.com/google/asylo/commit/b1d120a2c7d7446d2cc58d517e20a1b184b82200,asylo/platform/host_call/trusted/host_calls.cc,cwe-125,52 cwe-079,get_queryset," def get_queryset(self, **kwargs): queryset = Article.objects.order_by('-time') for i in queryset: i.md = markdown(i.content, extensions=[ 'markdown.extensions.extra', 'markdown.extensions.codehilite', 'markdown.extensions.toc', ]) return queryset"," def get_queryset(self, **kwargs): queryset = Article.objects.order_by('-time') for i in queryset: i.md = safe_md(i.content) return queryset","{'deleted': [{'line_no': 4, 'char_start': 118, 'char_end': 170, 'line': ' i.md = markdown(i.content, extensions=[\n'}, {'line_no': 5, 'char_start': 170, 'char_end': 215, 'line': "" 'markdown.extensions.extra',\n""}, {'line_no': 6, 'char_start': 215, 'char_end': 265, 'line': "" 'markdown.extensions.codehilite',\n""}, {'line_no': 7, 'char_start': 265, 'char_end': 308, 'line': "" 'markdown.extensions.toc',\n""}, {'line_no': 8, 'char_start': 308, 'char_end': 323, 'line': ' ])\n'}], 'added': [{'line_no': 4, 'char_start': 118, 'char_end': 156, 'line': ' i.md = safe_md(i.content)\n'}]}","{'deleted': [{'char_start': 137, 'char_end': 162, 'chars': 'markdown(i.content, exten'}, {'char_start': 163, 'char_end': 188, 'chars': ""ions=[\n 'm""}, {'char_start': 189, 'char_end': 196, 'chars': 'rkdown.'}, {'char_start': 197, 'char_end': 232, 'chars': ""xtensions.extra',\n '""}, {'char_start': 233, 'char_end': 236, 'chars': 'ark'}, {'char_start': 237, 'char_end': 247, 'chars': 'own.extens'}, {'char_start': 248, 'char_end': 251, 'chars': 'ons'}, {'char_start': 254, 'char_end': 289, 'chars': ""dehilite',\n 'markdow""}, {'char_start': 290, 'char_end': 293, 'chars': '.ex'}, {'char_start': 296, 'char_end': 302, 'chars': 'sions.'}, {'char_start': 303, 'char_end': 321, 'chars': ""oc',\n ]""}], 'added': [{'char_start': 139, 'char_end': 140, 'chars': 'f'}, {'char_start': 141, 'char_end': 142, 'chars': '_'}, {'char_start': 144, 'char_end': 145, 'chars': '('}]}",github.com/Cheng-mq1216/production-practice/commit/333dc34f5feada55d1f6ff1255949ca00dec0f9c,app/Index/views.py,cwe-079,61 cwe-190,UnicodeString::doAppend,"UnicodeString::doAppend(const UChar *srcChars, int32_t srcStart, int32_t srcLength) { if(!isWritable() || srcLength == 0 || srcChars == NULL) { return *this; } // Perform all remaining operations relative to srcChars + srcStart. // From this point forward, do not use srcStart. srcChars += srcStart; if(srcLength < 0) { // get the srcLength if necessary if((srcLength = u_strlen(srcChars)) == 0) { return *this; } } int32_t oldLength = length(); int32_t newLength = oldLength + srcLength; // Check for append onto ourself const UChar* oldArray = getArrayStart(); if (isBufferWritable() && oldArray < srcChars + srcLength && srcChars < oldArray + oldLength) { // Copy into a new UnicodeString and start over UnicodeString copy(srcChars, srcLength); if (copy.isBogus()) { setToBogus(); return *this; } return doAppend(copy.getArrayStart(), 0, srcLength); } // optimize append() onto a large-enough, owned string if((newLength <= getCapacity() && isBufferWritable()) || cloneArrayIfNeeded(newLength, getGrowCapacity(newLength))) { UChar *newArray = getArrayStart(); // Do not copy characters when // UChar *buffer=str.getAppendBuffer(...); // is followed by // str.append(buffer, length); // or // str.appendString(buffer, length) // or similar. if(srcChars != newArray + oldLength) { us_arrayCopy(srcChars, 0, newArray, oldLength, srcLength); } setLength(newLength); } return *this; }","UnicodeString::doAppend(const UChar *srcChars, int32_t srcStart, int32_t srcLength) { if(!isWritable() || srcLength == 0 || srcChars == NULL) { return *this; } // Perform all remaining operations relative to srcChars + srcStart. // From this point forward, do not use srcStart. srcChars += srcStart; if(srcLength < 0) { // get the srcLength if necessary if((srcLength = u_strlen(srcChars)) == 0) { return *this; } } int32_t oldLength = length(); int32_t newLength; if (uprv_add32_overflow(oldLength, srcLength, &newLength)) { setToBogus(); return *this; } // Check for append onto ourself const UChar* oldArray = getArrayStart(); if (isBufferWritable() && oldArray < srcChars + srcLength && srcChars < oldArray + oldLength) { // Copy into a new UnicodeString and start over UnicodeString copy(srcChars, srcLength); if (copy.isBogus()) { setToBogus(); return *this; } return doAppend(copy.getArrayStart(), 0, srcLength); } // optimize append() onto a large-enough, owned string if((newLength <= getCapacity() && isBufferWritable()) || cloneArrayIfNeeded(newLength, getGrowCapacity(newLength))) { UChar *newArray = getArrayStart(); // Do not copy characters when // UChar *buffer=str.getAppendBuffer(...); // is followed by // str.append(buffer, length); // or // str.appendString(buffer, length) // or similar. if(srcChars != newArray + oldLength) { us_arrayCopy(srcChars, 0, newArray, oldLength, srcLength); } setLength(newLength); } return *this; }","{'deleted': [{'line_no': 18, 'char_start': 487, 'char_end': 532, 'line': ' int32_t newLength = oldLength + srcLength;\n'}], 'added': [{'line_no': 18, 'char_start': 487, 'char_end': 508, 'line': ' int32_t newLength;\n'}, {'line_no': 19, 'char_start': 508, 'char_end': 571, 'line': ' if (uprv_add32_overflow(oldLength, srcLength, &newLength)) {\n'}, {'line_no': 20, 'char_start': 571, 'char_end': 589, 'line': ' setToBogus();\n'}, {'line_no': 21, 'char_start': 589, 'char_end': 607, 'line': ' return *this;\n'}, {'line_no': 22, 'char_start': 607, 'char_end': 611, 'line': ' }\n'}]}","{'deleted': [{'char_start': 507, 'char_end': 508, 'chars': '='}, {'char_start': 518, 'char_end': 520, 'chars': ' +'}], 'added': [{'char_start': 506, 'char_end': 509, 'chars': ';\n '}, {'char_start': 510, 'char_end': 512, 'chars': 'if'}, {'char_start': 513, 'char_end': 534, 'chars': '(uprv_add32_overflow('}, {'char_start': 543, 'char_end': 544, 'chars': ','}, {'char_start': 554, 'char_end': 587, 'chars': ', &newLength)) {\n setToBogus()'}, {'char_start': 588, 'char_end': 610, 'chars': '\n return *this;\n }'}]}",github.com/unicode-org/icu/commit/b7d08bc04a4296982fcef8b6b8a354a9e4e7afca,icu4c/source/common/unistr.cpp,cwe-190,421 cwe-476,ExprResolveLhs,"ExprResolveLhs(struct xkb_context *ctx, const ExprDef *expr, const char **elem_rtrn, const char **field_rtrn, ExprDef **index_rtrn) { switch (expr->expr.op) { case EXPR_IDENT: *elem_rtrn = NULL; *field_rtrn = xkb_atom_text(ctx, expr->ident.ident); *index_rtrn = NULL; return (*field_rtrn != NULL); case EXPR_FIELD_REF: *elem_rtrn = xkb_atom_text(ctx, expr->field_ref.element); *field_rtrn = xkb_atom_text(ctx, expr->field_ref.field); *index_rtrn = NULL; return true; case EXPR_ARRAY_REF: *elem_rtrn = xkb_atom_text(ctx, expr->array_ref.element); *field_rtrn = xkb_atom_text(ctx, expr->array_ref.field); *index_rtrn = expr->array_ref.entry; return true; default: break; } log_wsgo(ctx, ""Unexpected operator %d in ResolveLhs\n"", expr->expr.op); return false; }","ExprResolveLhs(struct xkb_context *ctx, const ExprDef *expr, const char **elem_rtrn, const char **field_rtrn, ExprDef **index_rtrn) { switch (expr->expr.op) { case EXPR_IDENT: *elem_rtrn = NULL; *field_rtrn = xkb_atom_text(ctx, expr->ident.ident); *index_rtrn = NULL; return (*field_rtrn != NULL); case EXPR_FIELD_REF: *elem_rtrn = xkb_atom_text(ctx, expr->field_ref.element); *field_rtrn = xkb_atom_text(ctx, expr->field_ref.field); *index_rtrn = NULL; return (*elem_rtrn != NULL && *field_rtrn != NULL); case EXPR_ARRAY_REF: *elem_rtrn = xkb_atom_text(ctx, expr->array_ref.element); *field_rtrn = xkb_atom_text(ctx, expr->array_ref.field); *index_rtrn = expr->array_ref.entry; if (expr->array_ref.element != XKB_ATOM_NONE && *elem_rtrn == NULL) return false; if (*field_rtrn == NULL) return false; return true; default: break; } log_wsgo(ctx, ""Unexpected operator %d in ResolveLhs\n"", expr->expr.op); return false; }","{'deleted': [{'line_no': 15, 'char_start': 552, 'char_end': 573, 'line': ' return true;\n'}], 'added': [{'line_no': 15, 'char_start': 552, 'char_end': 612, 'line': ' return (*elem_rtrn != NULL && *field_rtrn != NULL);\n'}, {'line_no': 20, 'char_start': 813, 'char_end': 882, 'line': '\tif (expr->array_ref.element != XKB_ATOM_NONE && *elem_rtrn == NULL)\n'}, {'line_no': 21, 'char_start': 882, 'char_end': 898, 'line': '\t\treturn false;\n'}, {'line_no': 22, 'char_start': 898, 'char_end': 924, 'line': '\tif (*field_rtrn == NULL)\n'}, {'line_no': 23, 'char_start': 924, 'char_end': 940, 'line': '\t\treturn false;\n'}]}","{'deleted': [{'char_start': 569, 'char_end': 570, 'chars': 'u'}], 'added': [{'char_start': 567, 'char_end': 575, 'chars': '(*elem_r'}, {'char_start': 577, 'char_end': 593, 'chars': 'n != NULL && *fi'}, {'char_start': 594, 'char_end': 610, 'chars': 'ld_rtrn != NULL)'}, {'char_start': 811, 'char_end': 938, 'chars': ';\n\tif (expr->array_ref.element != XKB_ATOM_NONE && *elem_rtrn == NULL)\n\t\treturn false;\n\tif (*field_rtrn == NULL)\n\t\treturn false'}]}",github.com/xkbcommon/libxkbcommon/commit/bb4909d2d8fa6b08155e449986a478101e2b2634,src/xkbcomp/expr.c,cwe-476,261 cwe-078,add_extra_args," def add_extra_args(self, args=None): """"""Add more args depending on how known args are set."""""" parsed = vars(self.parse_known_args(nohelp=True)[0]) # find which image mode specified if any, and add additional arguments image_mode = parsed.get('image_mode', None) if image_mode is not None and image_mode != 'none': self.add_image_args(image_mode) # find which task specified if any, and add its specific arguments task = parsed.get('task', None) if task is not None: self.add_task_args(task) evaltask = parsed.get('evaltask', None) if evaltask is not None: self.add_task_args(evaltask) # find which model specified if any, and add its specific arguments model = parsed.get('model', None) if model is not None: self.add_model_subargs(model) # reset parser-level defaults over any model-level defaults try: self.set_defaults(**self._defaults) except AttributeError: raise RuntimeError('Please file an issue on github that argparse ' 'got an attribute error when parsing.')"," def add_extra_args(self, args=None): """"""Add more args depending on how known args are set."""""" parsed = vars(self.parse_known_args(args, nohelp=True)[0]) # find which image mode specified if any, and add additional arguments image_mode = parsed.get('image_mode', None) if image_mode is not None and image_mode != 'none': self.add_image_args(image_mode) # find which task specified if any, and add its specific arguments task = parsed.get('task', None) if task is not None: self.add_task_args(task) evaltask = parsed.get('evaltask', None) if evaltask is not None: self.add_task_args(evaltask) # find which model specified if any, and add its specific arguments model = parsed.get('model', None) if model is not None: self.add_model_subargs(model) # reset parser-level defaults over any model-level defaults try: self.set_defaults(**self._defaults) except AttributeError: raise RuntimeError('Please file an issue on github that argparse ' 'got an attribute error when parsing.')","{'deleted': [{'line_no': 3, 'char_start': 106, 'char_end': 167, 'line': ' parsed = vars(self.parse_known_args(nohelp=True)[0])\n'}], 'added': [{'line_no': 3, 'char_start': 106, 'char_end': 173, 'line': ' parsed = vars(self.parse_known_args(args, nohelp=True)[0])\n'}]}","{'deleted': [], 'added': [{'char_start': 150, 'char_end': 156, 'chars': 'args, '}]}",github.com/freedombenLiu/ParlAI/commit/601668d569e1276e0b8bf2bf8fb43e391e10d170,parlai/core/params.py,cwe-078,244 cwe-089,render_page_name,"@app.route('/') def render_page_name(page_name): query = db.query(""select page_content.content, page.id as page_id, page_content.id as content_id from page, page_content where page.id = page_content.page_id and page.page_name = '%s' order by page_content.id desc limit 1"" % page_name) wiki_page = query.namedresult() has_content = False page_is_taken = False if len(wiki_page) < 1: content = """" else: page_is_taken = True content = wiki_page[0].content if len(content) > 0: has_content = True else: pass content = markdown.markdown(wiki_linkify(content)) return render_template( 'pageholder.html', page_is_taken = page_is_taken, page_name = page_name, markdown = markdown, wiki_linkify = wiki_linkify, has_content = has_content, content = content )","@app.route('/') def render_page_name(page_name): query = db.query(""select page_content.content, page.id as page_id, page_content.id as content_id from page, page_content where page.id = page_content.page_id and page.page_name = $1 order by page_content.id desc limit 1"", page_name) wiki_page = query.namedresult() has_content = False page_is_taken = False if len(wiki_page) < 1: content = """" else: page_is_taken = True content = wiki_page[0].content if len(content) > 0: has_content = True else: pass content = markdown.markdown(wiki_linkify(content)) return render_template( 'pageholder.html', page_is_taken = page_is_taken, page_name = page_name, markdown = markdown, wiki_linkify = wiki_linkify, has_content = has_content, content = content )","{'deleted': [{'line_no': 3, 'char_start': 60, 'char_end': 300, 'line': ' query = db.query(""select page_content.content, page.id as page_id, page_content.id as content_id from page, page_content where page.id = page_content.page_id and page.page_name = \'%s\' order by page_content.id desc limit 1"" % page_name)\n'}], 'added': [{'line_no': 3, 'char_start': 60, 'char_end': 297, 'line': ' query = db.query(""select page_content.content, page.id as page_id, page_content.id as content_id from page, page_content where page.id = page_content.page_id and page.page_name = $1 order by page_content.id desc limit 1"", page_name)\n'}]}","{'deleted': [{'char_start': 243, 'char_end': 247, 'chars': ""'%s'""}, {'char_start': 286, 'char_end': 288, 'chars': ' %'}], 'added': [{'char_start': 243, 'char_end': 245, 'chars': '$1'}, {'char_start': 284, 'char_end': 285, 'chars': ','}]}",github.com/Pumala/python_wiki_app_redo/commit/65d60747cd8efb05970304234d3bd949d2088e8b,server.py,cwe-089,216 cwe-125,modbus_reply,"int modbus_reply(modbus_t *ctx, const uint8_t *req, int req_length, modbus_mapping_t *mb_mapping) { int offset; int slave; int function; uint16_t address; uint8_t rsp[MAX_MESSAGE_LENGTH]; int rsp_length = 0; sft_t sft; if (ctx == NULL) { errno = EINVAL; return -1; } offset = ctx->backend->header_length; slave = req[offset - 1]; function = req[offset]; address = (req[offset + 1] << 8) + req[offset + 2]; sft.slave = slave; sft.function = function; sft.t_id = ctx->backend->prepare_response_tid(req, &req_length); /* Data are flushed on illegal number of values errors. */ switch (function) { case MODBUS_FC_READ_COILS: case MODBUS_FC_READ_DISCRETE_INPUTS: { unsigned int is_input = (function == MODBUS_FC_READ_DISCRETE_INPUTS); int start_bits = is_input ? mb_mapping->start_input_bits : mb_mapping->start_bits; int nb_bits = is_input ? mb_mapping->nb_input_bits : mb_mapping->nb_bits; uint8_t *tab_bits = is_input ? mb_mapping->tab_input_bits : mb_mapping->tab_bits; const char * const name = is_input ? ""read_input_bits"" : ""read_bits""; int nb = (req[offset + 3] << 8) + req[offset + 4]; /* The mapping can be shifted to reduce memory consumption and it doesn't always start at address zero. */ int mapping_address = address - start_bits; if (nb < 1 || MODBUS_MAX_READ_BITS < nb) { rsp_length = response_exception( ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_VALUE, rsp, TRUE, ""Illegal nb of values %d in %s (max %d)\n"", nb, name, MODBUS_MAX_READ_BITS); } else if (mapping_address < 0 || (mapping_address + nb) > nb_bits) { rsp_length = response_exception( ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp, FALSE, ""Illegal data address 0x%0X in %s\n"", mapping_address < 0 ? address : address + nb, name); } else { rsp_length = ctx->backend->build_response_basis(&sft, rsp); rsp[rsp_length++] = (nb / 8) + ((nb % 8) ? 1 : 0); rsp_length = response_io_status(tab_bits, mapping_address, nb, rsp, rsp_length); } } break; case MODBUS_FC_READ_HOLDING_REGISTERS: case MODBUS_FC_READ_INPUT_REGISTERS: { unsigned int is_input = (function == MODBUS_FC_READ_INPUT_REGISTERS); int start_registers = is_input ? mb_mapping->start_input_registers : mb_mapping->start_registers; int nb_registers = is_input ? mb_mapping->nb_input_registers : mb_mapping->nb_registers; uint16_t *tab_registers = is_input ? mb_mapping->tab_input_registers : mb_mapping->tab_registers; const char * const name = is_input ? ""read_input_registers"" : ""read_registers""; int nb = (req[offset + 3] << 8) + req[offset + 4]; /* The mapping can be shifted to reduce memory consumption and it doesn't always start at address zero. */ int mapping_address = address - start_registers; if (nb < 1 || MODBUS_MAX_READ_REGISTERS < nb) { rsp_length = response_exception( ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_VALUE, rsp, TRUE, ""Illegal nb of values %d in %s (max %d)\n"", nb, name, MODBUS_MAX_READ_REGISTERS); } else if (mapping_address < 0 || (mapping_address + nb) > nb_registers) { rsp_length = response_exception( ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp, FALSE, ""Illegal data address 0x%0X in %s\n"", mapping_address < 0 ? address : address + nb, name); } else { int i; rsp_length = ctx->backend->build_response_basis(&sft, rsp); rsp[rsp_length++] = nb << 1; for (i = mapping_address; i < mapping_address + nb; i++) { rsp[rsp_length++] = tab_registers[i] >> 8; rsp[rsp_length++] = tab_registers[i] & 0xFF; } } } break; case MODBUS_FC_WRITE_SINGLE_COIL: { int mapping_address = address - mb_mapping->start_bits; if (mapping_address < 0 || mapping_address >= mb_mapping->nb_bits) { rsp_length = response_exception( ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp, FALSE, ""Illegal data address 0x%0X in write_bit\n"", address); } else { int data = (req[offset + 3] << 8) + req[offset + 4]; if (data == 0xFF00 || data == 0x0) { mb_mapping->tab_bits[mapping_address] = data ? ON : OFF; memcpy(rsp, req, req_length); rsp_length = req_length; } else { rsp_length = response_exception( ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_VALUE, rsp, FALSE, ""Illegal data value 0x%0X in write_bit request at address %0X\n"", data, address); } } } break; case MODBUS_FC_WRITE_SINGLE_REGISTER: { int mapping_address = address - mb_mapping->start_registers; if (mapping_address < 0 || mapping_address >= mb_mapping->nb_registers) { rsp_length = response_exception( ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp, FALSE, ""Illegal data address 0x%0X in write_register\n"", address); } else { int data = (req[offset + 3] << 8) + req[offset + 4]; mb_mapping->tab_registers[mapping_address] = data; memcpy(rsp, req, req_length); rsp_length = req_length; } } break; case MODBUS_FC_WRITE_MULTIPLE_COILS: { int nb = (req[offset + 3] << 8) + req[offset + 4]; int mapping_address = address - mb_mapping->start_bits; if (nb < 1 || MODBUS_MAX_WRITE_BITS < nb) { /* May be the indication has been truncated on reading because of * invalid address (eg. nb is 0 but the request contains values to * write) so it's necessary to flush. */ rsp_length = response_exception( ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_VALUE, rsp, TRUE, ""Illegal number of values %d in write_bits (max %d)\n"", nb, MODBUS_MAX_WRITE_BITS); } else if (mapping_address < 0 || (mapping_address + nb) > mb_mapping->nb_bits) { rsp_length = response_exception( ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp, FALSE, ""Illegal data address 0x%0X in write_bits\n"", mapping_address < 0 ? address : address + nb); } else { /* 6 = byte count */ modbus_set_bits_from_bytes(mb_mapping->tab_bits, mapping_address, nb, &req[offset + 6]); rsp_length = ctx->backend->build_response_basis(&sft, rsp); /* 4 to copy the bit address (2) and the quantity of bits */ memcpy(rsp + rsp_length, req + rsp_length, 4); rsp_length += 4; } } break; case MODBUS_FC_WRITE_MULTIPLE_REGISTERS: { int nb = (req[offset + 3] << 8) + req[offset + 4]; int mapping_address = address - mb_mapping->start_registers; if (nb < 1 || MODBUS_MAX_WRITE_REGISTERS < nb) { rsp_length = response_exception( ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_VALUE, rsp, TRUE, ""Illegal number of values %d in write_registers (max %d)\n"", nb, MODBUS_MAX_WRITE_REGISTERS); } else if (mapping_address < 0 || (mapping_address + nb) > mb_mapping->nb_registers) { rsp_length = response_exception( ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp, FALSE, ""Illegal data address 0x%0X in write_registers\n"", mapping_address < 0 ? address : address + nb); } else { int i, j; for (i = mapping_address, j = 6; i < mapping_address + nb; i++, j += 2) { /* 6 and 7 = first value */ mb_mapping->tab_registers[i] = (req[offset + j] << 8) + req[offset + j + 1]; } rsp_length = ctx->backend->build_response_basis(&sft, rsp); /* 4 to copy the address (2) and the no. of registers */ memcpy(rsp + rsp_length, req + rsp_length, 4); rsp_length += 4; } } break; case MODBUS_FC_REPORT_SLAVE_ID: { int str_len; int byte_count_pos; rsp_length = ctx->backend->build_response_basis(&sft, rsp); /* Skip byte count for now */ byte_count_pos = rsp_length++; rsp[rsp_length++] = _REPORT_SLAVE_ID; /* Run indicator status to ON */ rsp[rsp_length++] = 0xFF; /* LMB + length of LIBMODBUS_VERSION_STRING */ str_len = 3 + strlen(LIBMODBUS_VERSION_STRING); memcpy(rsp + rsp_length, ""LMB"" LIBMODBUS_VERSION_STRING, str_len); rsp_length += str_len; rsp[byte_count_pos] = rsp_length - byte_count_pos - 1; } break; case MODBUS_FC_READ_EXCEPTION_STATUS: if (ctx->debug) { fprintf(stderr, ""FIXME Not implemented\n""); } errno = ENOPROTOOPT; return -1; break; case MODBUS_FC_MASK_WRITE_REGISTER: { int mapping_address = address - mb_mapping->start_registers; if (mapping_address < 0 || mapping_address >= mb_mapping->nb_registers) { rsp_length = response_exception( ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp, FALSE, ""Illegal data address 0x%0X in write_register\n"", address); } else { uint16_t data = mb_mapping->tab_registers[mapping_address]; uint16_t and = (req[offset + 3] << 8) + req[offset + 4]; uint16_t or = (req[offset + 5] << 8) + req[offset + 6]; data = (data & and) | (or & (~and)); mb_mapping->tab_registers[mapping_address] = data; memcpy(rsp, req, req_length); rsp_length = req_length; } } break; case MODBUS_FC_WRITE_AND_READ_REGISTERS: { int nb = (req[offset + 3] << 8) + req[offset + 4]; uint16_t address_write = (req[offset + 5] << 8) + req[offset + 6]; int nb_write = (req[offset + 7] << 8) + req[offset + 8]; int nb_write_bytes = req[offset + 9]; int mapping_address = address - mb_mapping->start_registers; int mapping_address_write = address_write - mb_mapping->start_registers; if (nb_write < 1 || MODBUS_MAX_WR_WRITE_REGISTERS < nb_write || nb < 1 || MODBUS_MAX_WR_READ_REGISTERS < nb || nb_write_bytes != nb_write * 2) { rsp_length = response_exception( ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_VALUE, rsp, TRUE, ""Illegal nb of values (W%d, R%d) in write_and_read_registers (max W%d, R%d)\n"", nb_write, nb, MODBUS_MAX_WR_WRITE_REGISTERS, MODBUS_MAX_WR_READ_REGISTERS); } else if (mapping_address < 0 || (mapping_address + nb) > mb_mapping->nb_registers || mapping_address < 0 || (mapping_address_write + nb_write) > mb_mapping->nb_registers) { rsp_length = response_exception( ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp, FALSE, ""Illegal data read address 0x%0X or write address 0x%0X write_and_read_registers\n"", mapping_address < 0 ? address : address + nb, mapping_address_write < 0 ? address_write : address_write + nb_write); } else { int i, j; rsp_length = ctx->backend->build_response_basis(&sft, rsp); rsp[rsp_length++] = nb << 1; /* Write first. 10 and 11 are the offset of the first values to write */ for (i = mapping_address_write, j = 10; i < mapping_address_write + nb_write; i++, j += 2) { mb_mapping->tab_registers[i] = (req[offset + j] << 8) + req[offset + j + 1]; } /* and read the data for the response */ for (i = mapping_address; i < mapping_address + nb; i++) { rsp[rsp_length++] = mb_mapping->tab_registers[i] >> 8; rsp[rsp_length++] = mb_mapping->tab_registers[i] & 0xFF; } } } break; default: rsp_length = response_exception( ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_FUNCTION, rsp, TRUE, ""Unknown Modbus function code: 0x%0X\n"", function); break; } /* Suppress any responses when the request was a broadcast */ return (ctx->backend->backend_type == _MODBUS_BACKEND_TYPE_RTU && slave == MODBUS_BROADCAST_ADDRESS) ? 0 : send_msg(ctx, rsp, rsp_length); }","int modbus_reply(modbus_t *ctx, const uint8_t *req, int req_length, modbus_mapping_t *mb_mapping) { int offset; int slave; int function; uint16_t address; uint8_t rsp[MAX_MESSAGE_LENGTH]; int rsp_length = 0; sft_t sft; if (ctx == NULL) { errno = EINVAL; return -1; } offset = ctx->backend->header_length; slave = req[offset - 1]; function = req[offset]; address = (req[offset + 1] << 8) + req[offset + 2]; sft.slave = slave; sft.function = function; sft.t_id = ctx->backend->prepare_response_tid(req, &req_length); /* Data are flushed on illegal number of values errors. */ switch (function) { case MODBUS_FC_READ_COILS: case MODBUS_FC_READ_DISCRETE_INPUTS: { unsigned int is_input = (function == MODBUS_FC_READ_DISCRETE_INPUTS); int start_bits = is_input ? mb_mapping->start_input_bits : mb_mapping->start_bits; int nb_bits = is_input ? mb_mapping->nb_input_bits : mb_mapping->nb_bits; uint8_t *tab_bits = is_input ? mb_mapping->tab_input_bits : mb_mapping->tab_bits; const char * const name = is_input ? ""read_input_bits"" : ""read_bits""; int nb = (req[offset + 3] << 8) + req[offset + 4]; /* The mapping can be shifted to reduce memory consumption and it doesn't always start at address zero. */ int mapping_address = address - start_bits; if (nb < 1 || MODBUS_MAX_READ_BITS < nb) { rsp_length = response_exception( ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_VALUE, rsp, TRUE, ""Illegal nb of values %d in %s (max %d)\n"", nb, name, MODBUS_MAX_READ_BITS); } else if (mapping_address < 0 || (mapping_address + nb) > nb_bits) { rsp_length = response_exception( ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp, FALSE, ""Illegal data address 0x%0X in %s\n"", mapping_address < 0 ? address : address + nb, name); } else { rsp_length = ctx->backend->build_response_basis(&sft, rsp); rsp[rsp_length++] = (nb / 8) + ((nb % 8) ? 1 : 0); rsp_length = response_io_status(tab_bits, mapping_address, nb, rsp, rsp_length); } } break; case MODBUS_FC_READ_HOLDING_REGISTERS: case MODBUS_FC_READ_INPUT_REGISTERS: { unsigned int is_input = (function == MODBUS_FC_READ_INPUT_REGISTERS); int start_registers = is_input ? mb_mapping->start_input_registers : mb_mapping->start_registers; int nb_registers = is_input ? mb_mapping->nb_input_registers : mb_mapping->nb_registers; uint16_t *tab_registers = is_input ? mb_mapping->tab_input_registers : mb_mapping->tab_registers; const char * const name = is_input ? ""read_input_registers"" : ""read_registers""; int nb = (req[offset + 3] << 8) + req[offset + 4]; /* The mapping can be shifted to reduce memory consumption and it doesn't always start at address zero. */ int mapping_address = address - start_registers; if (nb < 1 || MODBUS_MAX_READ_REGISTERS < nb) { rsp_length = response_exception( ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_VALUE, rsp, TRUE, ""Illegal nb of values %d in %s (max %d)\n"", nb, name, MODBUS_MAX_READ_REGISTERS); } else if (mapping_address < 0 || (mapping_address + nb) > nb_registers) { rsp_length = response_exception( ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp, FALSE, ""Illegal data address 0x%0X in %s\n"", mapping_address < 0 ? address : address + nb, name); } else { int i; rsp_length = ctx->backend->build_response_basis(&sft, rsp); rsp[rsp_length++] = nb << 1; for (i = mapping_address; i < mapping_address + nb; i++) { rsp[rsp_length++] = tab_registers[i] >> 8; rsp[rsp_length++] = tab_registers[i] & 0xFF; } } } break; case MODBUS_FC_WRITE_SINGLE_COIL: { int mapping_address = address - mb_mapping->start_bits; if (mapping_address < 0 || mapping_address >= mb_mapping->nb_bits) { rsp_length = response_exception( ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp, FALSE, ""Illegal data address 0x%0X in write_bit\n"", address); } else { int data = (req[offset + 3] << 8) + req[offset + 4]; if (data == 0xFF00 || data == 0x0) { mb_mapping->tab_bits[mapping_address] = data ? ON : OFF; memcpy(rsp, req, req_length); rsp_length = req_length; } else { rsp_length = response_exception( ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_VALUE, rsp, FALSE, ""Illegal data value 0x%0X in write_bit request at address %0X\n"", data, address); } } } break; case MODBUS_FC_WRITE_SINGLE_REGISTER: { int mapping_address = address - mb_mapping->start_registers; if (mapping_address < 0 || mapping_address >= mb_mapping->nb_registers) { rsp_length = response_exception( ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp, FALSE, ""Illegal data address 0x%0X in write_register\n"", address); } else { int data = (req[offset + 3] << 8) + req[offset + 4]; mb_mapping->tab_registers[mapping_address] = data; memcpy(rsp, req, req_length); rsp_length = req_length; } } break; case MODBUS_FC_WRITE_MULTIPLE_COILS: { int nb = (req[offset + 3] << 8) + req[offset + 4]; int nb_bits = req[offset + 5]; int mapping_address = address - mb_mapping->start_bits; if (nb < 1 || MODBUS_MAX_WRITE_BITS < nb || nb_bits * 8 < nb) { /* May be the indication has been truncated on reading because of * invalid address (eg. nb is 0 but the request contains values to * write) so it's necessary to flush. */ rsp_length = response_exception( ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_VALUE, rsp, TRUE, ""Illegal number of values %d in write_bits (max %d)\n"", nb, MODBUS_MAX_WRITE_BITS); } else if (mapping_address < 0 || (mapping_address + nb) > mb_mapping->nb_bits) { rsp_length = response_exception( ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp, FALSE, ""Illegal data address 0x%0X in write_bits\n"", mapping_address < 0 ? address : address + nb); } else { /* 6 = byte count */ modbus_set_bits_from_bytes(mb_mapping->tab_bits, mapping_address, nb, &req[offset + 6]); rsp_length = ctx->backend->build_response_basis(&sft, rsp); /* 4 to copy the bit address (2) and the quantity of bits */ memcpy(rsp + rsp_length, req + rsp_length, 4); rsp_length += 4; } } break; case MODBUS_FC_WRITE_MULTIPLE_REGISTERS: { int nb = (req[offset + 3] << 8) + req[offset + 4]; int nb_bytes = req[offset + 5]; int mapping_address = address - mb_mapping->start_registers; if (nb < 1 || MODBUS_MAX_WRITE_REGISTERS < nb || nb_bytes * 8 < nb) { rsp_length = response_exception( ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_VALUE, rsp, TRUE, ""Illegal number of values %d in write_registers (max %d)\n"", nb, MODBUS_MAX_WRITE_REGISTERS); } else if (mapping_address < 0 || (mapping_address + nb) > mb_mapping->nb_registers) { rsp_length = response_exception( ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp, FALSE, ""Illegal data address 0x%0X in write_registers\n"", mapping_address < 0 ? address : address + nb); } else { int i, j; for (i = mapping_address, j = 6; i < mapping_address + nb; i++, j += 2) { /* 6 and 7 = first value */ mb_mapping->tab_registers[i] = (req[offset + j] << 8) + req[offset + j + 1]; } rsp_length = ctx->backend->build_response_basis(&sft, rsp); /* 4 to copy the address (2) and the no. of registers */ memcpy(rsp + rsp_length, req + rsp_length, 4); rsp_length += 4; } } break; case MODBUS_FC_REPORT_SLAVE_ID: { int str_len; int byte_count_pos; rsp_length = ctx->backend->build_response_basis(&sft, rsp); /* Skip byte count for now */ byte_count_pos = rsp_length++; rsp[rsp_length++] = _REPORT_SLAVE_ID; /* Run indicator status to ON */ rsp[rsp_length++] = 0xFF; /* LMB + length of LIBMODBUS_VERSION_STRING */ str_len = 3 + strlen(LIBMODBUS_VERSION_STRING); memcpy(rsp + rsp_length, ""LMB"" LIBMODBUS_VERSION_STRING, str_len); rsp_length += str_len; rsp[byte_count_pos] = rsp_length - byte_count_pos - 1; } break; case MODBUS_FC_READ_EXCEPTION_STATUS: if (ctx->debug) { fprintf(stderr, ""FIXME Not implemented\n""); } errno = ENOPROTOOPT; return -1; break; case MODBUS_FC_MASK_WRITE_REGISTER: { int mapping_address = address - mb_mapping->start_registers; if (mapping_address < 0 || mapping_address >= mb_mapping->nb_registers) { rsp_length = response_exception( ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp, FALSE, ""Illegal data address 0x%0X in write_register\n"", address); } else { uint16_t data = mb_mapping->tab_registers[mapping_address]; uint16_t and = (req[offset + 3] << 8) + req[offset + 4]; uint16_t or = (req[offset + 5] << 8) + req[offset + 6]; data = (data & and) | (or & (~and)); mb_mapping->tab_registers[mapping_address] = data; memcpy(rsp, req, req_length); rsp_length = req_length; } } break; case MODBUS_FC_WRITE_AND_READ_REGISTERS: { int nb = (req[offset + 3] << 8) + req[offset + 4]; uint16_t address_write = (req[offset + 5] << 8) + req[offset + 6]; int nb_write = (req[offset + 7] << 8) + req[offset + 8]; int nb_write_bytes = req[offset + 9]; int mapping_address = address - mb_mapping->start_registers; int mapping_address_write = address_write - mb_mapping->start_registers; if (nb_write < 1 || MODBUS_MAX_WR_WRITE_REGISTERS < nb_write || nb < 1 || MODBUS_MAX_WR_READ_REGISTERS < nb || nb_write_bytes != nb_write * 2) { rsp_length = response_exception( ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_VALUE, rsp, TRUE, ""Illegal nb of values (W%d, R%d) in write_and_read_registers (max W%d, R%d)\n"", nb_write, nb, MODBUS_MAX_WR_WRITE_REGISTERS, MODBUS_MAX_WR_READ_REGISTERS); } else if (mapping_address < 0 || (mapping_address + nb) > mb_mapping->nb_registers || mapping_address < 0 || (mapping_address_write + nb_write) > mb_mapping->nb_registers) { rsp_length = response_exception( ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp, FALSE, ""Illegal data read address 0x%0X or write address 0x%0X write_and_read_registers\n"", mapping_address < 0 ? address : address + nb, mapping_address_write < 0 ? address_write : address_write + nb_write); } else { int i, j; rsp_length = ctx->backend->build_response_basis(&sft, rsp); rsp[rsp_length++] = nb << 1; /* Write first. 10 and 11 are the offset of the first values to write */ for (i = mapping_address_write, j = 10; i < mapping_address_write + nb_write; i++, j += 2) { mb_mapping->tab_registers[i] = (req[offset + j] << 8) + req[offset + j + 1]; } /* and read the data for the response */ for (i = mapping_address; i < mapping_address + nb; i++) { rsp[rsp_length++] = mb_mapping->tab_registers[i] >> 8; rsp[rsp_length++] = mb_mapping->tab_registers[i] & 0xFF; } } } break; default: rsp_length = response_exception( ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_FUNCTION, rsp, TRUE, ""Unknown Modbus function code: 0x%0X\n"", function); break; } /* Suppress any responses when the request was a broadcast */ return (ctx->backend->backend_type == _MODBUS_BACKEND_TYPE_RTU && slave == MODBUS_BROADCAST_ADDRESS) ? 0 : send_msg(ctx, rsp, rsp_length); }","{'deleted': [{'line_no': 140, 'char_start': 6054, 'char_end': 6106, 'line': ' if (nb < 1 || MODBUS_MAX_WRITE_BITS < nb) {\n'}, {'line_no': 171, 'char_start': 7556, 'char_end': 7613, 'line': ' if (nb < 1 || MODBUS_MAX_WRITE_REGISTERS < nb) {\n'}], 'added': [{'line_no': 138, 'char_start': 5989, 'char_end': 6028, 'line': ' int nb_bits = req[offset + 5];\n'}, {'line_no': 141, 'char_start': 6093, 'char_end': 6165, 'line': ' if (nb < 1 || MODBUS_MAX_WRITE_BITS < nb || nb_bits * 8 < nb) {\n'}, {'line_no': 170, 'char_start': 7545, 'char_end': 7585, 'line': ' int nb_bytes = req[offset + 5];\n'}, {'line_no': 173, 'char_start': 7655, 'char_end': 7733, 'line': ' if (nb < 1 || MODBUS_MAX_WRITE_REGISTERS < nb || nb_bytes * 8 < nb) {\n'}]}","{'deleted': [], 'added': [{'char_start': 6001, 'char_end': 6040, 'chars': 'nb_bits = req[offset + 5];\n int '}, {'char_start': 6136, 'char_end': 6156, 'chars': ' < nb || nb_bits * 8'}, {'char_start': 7557, 'char_end': 7597, 'chars': 'nb_bytes = req[offset + 5];\n int '}, {'char_start': 7703, 'char_end': 7724, 'chars': ' < nb || nb_bytes * 8'}]}",github.com/stephane/libmodbus/commit/5ccdf5ef79d742640355d1132fa9e2abc7fbaefc,src/modbus.c,cwe-125,3226 cwe-190,_gd2GetHeader,"static int _gd2GetHeader(gdIOCtxPtr in, int *sx, int *sy, int *cs, int *vers, int *fmt, int *ncx, int *ncy, t_chunk_info ** chunkIdx) { int i; int ch; char id[5]; t_chunk_info *cidx; int sidx; int nc; GD2_DBG(php_gd_error(""Reading gd2 header info"")); for (i = 0; i < 4; i++) { ch = gdGetC(in); if (ch == EOF) { goto fail1; } id[i] = ch; } id[4] = 0; GD2_DBG(php_gd_error(""Got file code: %s"", id)); /* Equiv. of 'magick'. */ if (strcmp(id, GD2_ID) != 0) { GD2_DBG(php_gd_error(""Not a valid gd2 file"")); goto fail1; } /* Version */ if (gdGetWord(vers, in) != 1) { goto fail1; } GD2_DBG(php_gd_error(""Version: %d"", *vers)); if ((*vers != 1) && (*vers != 2)) { GD2_DBG(php_gd_error(""Bad version: %d"", *vers)); goto fail1; } /* Image Size */ if (!gdGetWord(sx, in)) { GD2_DBG(php_gd_error(""Could not get x-size"")); goto fail1; } if (!gdGetWord(sy, in)) { GD2_DBG(php_gd_error(""Could not get y-size"")); goto fail1; } GD2_DBG(php_gd_error(""Image is %dx%d"", *sx, *sy)); /* Chunk Size (pixels, not bytes!) */ if (gdGetWord(cs, in) != 1) { goto fail1; } GD2_DBG(php_gd_error(""ChunkSize: %d"", *cs)); if ((*cs < GD2_CHUNKSIZE_MIN) || (*cs > GD2_CHUNKSIZE_MAX)) { GD2_DBG(php_gd_error(""Bad chunk size: %d"", *cs)); goto fail1; } /* Data Format */ if (gdGetWord(fmt, in) != 1) { goto fail1; } GD2_DBG(php_gd_error(""Format: %d"", *fmt)); if ((*fmt != GD2_FMT_RAW) && (*fmt != GD2_FMT_COMPRESSED) && (*fmt != GD2_FMT_TRUECOLOR_RAW) && (*fmt != GD2_FMT_TRUECOLOR_COMPRESSED)) { GD2_DBG(php_gd_error(""Bad data format: %d"", *fmt)); goto fail1; } /* # of chunks wide */ if (gdGetWord(ncx, in) != 1) { goto fail1; } GD2_DBG(php_gd_error(""%d Chunks Wide"", *ncx)); /* # of chunks high */ if (gdGetWord(ncy, in) != 1) { goto fail1; } GD2_DBG(php_gd_error(""%d Chunks vertically"", *ncy)); if (gd2_compressed(*fmt)) { nc = (*ncx) * (*ncy); GD2_DBG(php_gd_error(""Reading %d chunk index entries"", nc)); sidx = sizeof(t_chunk_info) * nc; if (sidx <= 0) { goto fail1; } cidx = gdCalloc(sidx, 1); for (i = 0; i < nc; i++) { if (gdGetInt(&cidx[i].offset, in) != 1) { gdFree(cidx); goto fail1; } if (gdGetInt(&cidx[i].size, in) != 1) { gdFree(cidx); goto fail1; } if (cidx[i].offset < 0 || cidx[i].size < 0) { gdFree(cidx); goto fail1; } } *chunkIdx = cidx; } GD2_DBG(php_gd_error(""gd2 header complete"")); return 1; fail1: return 0; }","static int _gd2GetHeader(gdIOCtxPtr in, int *sx, int *sy, int *cs, int *vers, int *fmt, int *ncx, int *ncy, t_chunk_info ** chunkIdx) { int i; int ch; char id[5]; t_chunk_info *cidx; int sidx; int nc; GD2_DBG(php_gd_error(""Reading gd2 header info"")); for (i = 0; i < 4; i++) { ch = gdGetC(in); if (ch == EOF) { goto fail1; } id[i] = ch; } id[4] = 0; GD2_DBG(php_gd_error(""Got file code: %s"", id)); /* Equiv. of 'magick'. */ if (strcmp(id, GD2_ID) != 0) { GD2_DBG(php_gd_error(""Not a valid gd2 file"")); goto fail1; } /* Version */ if (gdGetWord(vers, in) != 1) { goto fail1; } GD2_DBG(php_gd_error(""Version: %d"", *vers)); if ((*vers != 1) && (*vers != 2)) { GD2_DBG(php_gd_error(""Bad version: %d"", *vers)); goto fail1; } /* Image Size */ if (!gdGetWord(sx, in)) { GD2_DBG(php_gd_error(""Could not get x-size"")); goto fail1; } if (!gdGetWord(sy, in)) { GD2_DBG(php_gd_error(""Could not get y-size"")); goto fail1; } GD2_DBG(php_gd_error(""Image is %dx%d"", *sx, *sy)); /* Chunk Size (pixels, not bytes!) */ if (gdGetWord(cs, in) != 1) { goto fail1; } GD2_DBG(php_gd_error(""ChunkSize: %d"", *cs)); if ((*cs < GD2_CHUNKSIZE_MIN) || (*cs > GD2_CHUNKSIZE_MAX)) { GD2_DBG(php_gd_error(""Bad chunk size: %d"", *cs)); goto fail1; } /* Data Format */ if (gdGetWord(fmt, in) != 1) { goto fail1; } GD2_DBG(php_gd_error(""Format: %d"", *fmt)); if ((*fmt != GD2_FMT_RAW) && (*fmt != GD2_FMT_COMPRESSED) && (*fmt != GD2_FMT_TRUECOLOR_RAW) && (*fmt != GD2_FMT_TRUECOLOR_COMPRESSED)) { GD2_DBG(php_gd_error(""Bad data format: %d"", *fmt)); goto fail1; } /* # of chunks wide */ if (gdGetWord(ncx, in) != 1) { goto fail1; } GD2_DBG(php_gd_error(""%d Chunks Wide"", *ncx)); /* # of chunks high */ if (gdGetWord(ncy, in) != 1) { goto fail1; } GD2_DBG(php_gd_error(""%d Chunks vertically"", *ncy)); if (gd2_compressed(*fmt)) { nc = (*ncx) * (*ncy); GD2_DBG(php_gd_error(""Reading %d chunk index entries"", nc)); if (overflow2(sidx, nc)) { goto fail1; } sidx = sizeof(t_chunk_info) * nc; if (sidx <= 0) { goto fail1; } cidx = gdCalloc(sidx, 1); if (cidx == NULL) { goto fail1; } for (i = 0; i < nc; i++) { if (gdGetInt(&cidx[i].offset, in) != 1) { gdFree(cidx); goto fail1; } if (gdGetInt(&cidx[i].size, in) != 1) { gdFree(cidx); goto fail1; } if (cidx[i].offset < 0 || cidx[i].size < 0) { gdFree(cidx); goto fail1; } } *chunkIdx = cidx; } GD2_DBG(php_gd_error(""gd2 header complete"")); return 1; fail1: return 0; }","{'deleted': [], 'added': [{'line_no': 88, 'char_start': 1983, 'char_end': 2012, 'line': '\t\tif (overflow2(sidx, nc)) {\n'}, {'line_no': 89, 'char_start': 2012, 'char_end': 2027, 'line': '\t\t\tgoto fail1;\n'}, {'line_no': 90, 'char_start': 2027, 'char_end': 2031, 'line': '\t\t}\n'}, {'line_no': 96, 'char_start': 2133, 'char_end': 2155, 'line': '\t\tif (cidx == NULL) {\n'}, {'line_no': 97, 'char_start': 2155, 'char_end': 2170, 'line': '\t\t\tgoto fail1;\n'}, {'line_no': 98, 'char_start': 2170, 'char_end': 2174, 'line': '\t\t}\n'}, {'line_no': 99, 'char_start': 2174, 'char_end': 2175, 'line': '\n'}]}","{'deleted': [], 'added': [{'char_start': 1985, 'char_end': 2033, 'chars': 'if (overflow2(sidx, nc)) {\n\t\t\tgoto fail1;\n\t\t}\n\t\t'}, {'char_start': 2132, 'char_end': 2174, 'chars': '\n\t\tif (cidx == NULL) {\n\t\t\tgoto fail1;\n\t\t}\n'}]}",github.com/php/php-src/commit/7722455726bec8c53458a32851d2a87982cf0eac,ext/gd/libgd/gd_gd2.c,cwe-190,957 cwe-125,ImagingFliDecode,"ImagingFliDecode(Imaging im, ImagingCodecState state, UINT8* buf, Py_ssize_t bytes) { UINT8* ptr; int framesize; int c, chunks, advance; int l, lines; int i, j, x = 0, y, ymax; /* If not even the chunk size is present, we'd better leave */ if (bytes < 4) return 0; /* We don't decode anything unless we have a full chunk in the input buffer (on the other hand, the Python part of the driver makes sure this is always the case) */ ptr = buf; framesize = I32(ptr); if (framesize < I32(ptr)) return 0; /* Make sure this is a frame chunk. The Python driver takes case of other chunk types. */ if (I16(ptr+4) != 0xF1FA) { state->errcode = IMAGING_CODEC_UNKNOWN; return -1; } chunks = I16(ptr+6); ptr += 16; bytes -= 16; /* Process subchunks */ for (c = 0; c < chunks; c++) { UINT8* data; if (bytes < 10) { state->errcode = IMAGING_CODEC_OVERRUN; return -1; } data = ptr + 6; switch (I16(ptr+4)) { case 4: case 11: /* FLI COLOR chunk */ break; /* ignored; handled by Python code */ case 7: /* FLI SS2 chunk (word delta) */ lines = I16(data); data += 2; for (l = y = 0; l < lines && y < state->ysize; l++, y++) { UINT8* buf = (UINT8*) im->image[y]; int p, packets; packets = I16(data); data += 2; while (packets & 0x8000) { /* flag word */ if (packets & 0x4000) { y += 65536 - packets; /* skip lines */ if (y >= state->ysize) { state->errcode = IMAGING_CODEC_OVERRUN; return -1; } buf = (UINT8*) im->image[y]; } else { /* store last byte (used if line width is odd) */ buf[state->xsize-1] = (UINT8) packets; } packets = I16(data); data += 2; } for (p = x = 0; p < packets; p++) { x += data[0]; /* pixel skip */ if (data[1] >= 128) { i = 256-data[1]; /* run */ if (x + i + i > state->xsize) break; for (j = 0; j < i; j++) { buf[x++] = data[2]; buf[x++] = data[3]; } data += 2 + 2; } else { i = 2 * (int) data[1]; /* chunk */ if (x + i > state->xsize) break; memcpy(buf + x, data + 2, i); data += 2 + i; x += i; } } if (p < packets) break; /* didn't process all packets */ } if (l < lines) { /* didn't process all lines */ state->errcode = IMAGING_CODEC_OVERRUN; return -1; } break; case 12: /* FLI LC chunk (byte delta) */ y = I16(data); ymax = y + I16(data+2); data += 4; for (; y < ymax && y < state->ysize; y++) { UINT8* out = (UINT8*) im->image[y]; int p, packets = *data++; for (p = x = 0; p < packets; p++, x += i) { x += data[0]; /* skip pixels */ if (data[1] & 0x80) { i = 256-data[1]; /* run */ if (x + i > state->xsize) break; memset(out + x, data[2], i); data += 3; } else { i = data[1]; /* chunk */ if (x + i > state->xsize) break; memcpy(out + x, data + 2, i); data += i + 2; } } if (p < packets) break; /* didn't process all packets */ } if (y < ymax) { /* didn't process all lines */ state->errcode = IMAGING_CODEC_OVERRUN; return -1; } break; case 13: /* FLI BLACK chunk */ for (y = 0; y < state->ysize; y++) memset(im->image[y], 0, state->xsize); break; case 15: /* FLI BRUN chunk */ for (y = 0; y < state->ysize; y++) { UINT8* out = (UINT8*) im->image[y]; data += 1; /* ignore packetcount byte */ for (x = 0; x < state->xsize; x += i) { if (data[0] & 0x80) { i = 256 - data[0]; if (x + i > state->xsize) break; /* safety first */ memcpy(out + x, data + 1, i); data += i + 1; } else { i = data[0]; if (x + i > state->xsize) break; /* safety first */ memset(out + x, data[1], i); data += 2; } } if (x != state->xsize) { /* didn't unpack whole line */ state->errcode = IMAGING_CODEC_OVERRUN; return -1; } } break; case 16: /* COPY chunk */ for (y = 0; y < state->ysize; y++) { UINT8* buf = (UINT8*) im->image[y]; memcpy(buf, data, state->xsize); data += state->xsize; } break; case 18: /* PSTAMP chunk */ break; /* ignored */ default: /* unknown chunk */ /* printf(""unknown FLI/FLC chunk: %d\n"", I16(ptr+4)); */ state->errcode = IMAGING_CODEC_UNKNOWN; return -1; } advance = I32(ptr); ptr += advance; bytes -= advance; } return -1; /* end of frame */ }","ImagingFliDecode(Imaging im, ImagingCodecState state, UINT8* buf, Py_ssize_t bytes) { UINT8* ptr; int framesize; int c, chunks, advance; int l, lines; int i, j, x = 0, y, ymax; /* If not even the chunk size is present, we'd better leave */ if (bytes < 4) return 0; /* We don't decode anything unless we have a full chunk in the input buffer */ ptr = buf; framesize = I32(ptr); if (framesize < I32(ptr)) return 0; /* Make sure this is a frame chunk. The Python driver takes case of other chunk types. */ if (bytes < 8) { state->errcode = IMAGING_CODEC_OVERRUN; return -1; } if (I16(ptr+4) != 0xF1FA) { state->errcode = IMAGING_CODEC_UNKNOWN; return -1; } chunks = I16(ptr+6); ptr += 16; bytes -= 16; /* Process subchunks */ for (c = 0; c < chunks; c++) { UINT8* data; if (bytes < 10) { state->errcode = IMAGING_CODEC_OVERRUN; return -1; } data = ptr + 6; switch (I16(ptr+4)) { case 4: case 11: /* FLI COLOR chunk */ break; /* ignored; handled by Python code */ case 7: /* FLI SS2 chunk (word delta) */ lines = I16(data); data += 2; for (l = y = 0; l < lines && y < state->ysize; l++, y++) { UINT8* buf = (UINT8*) im->image[y]; int p, packets; packets = I16(data); data += 2; while (packets & 0x8000) { /* flag word */ if (packets & 0x4000) { y += 65536 - packets; /* skip lines */ if (y >= state->ysize) { state->errcode = IMAGING_CODEC_OVERRUN; return -1; } buf = (UINT8*) im->image[y]; } else { /* store last byte (used if line width is odd) */ buf[state->xsize-1] = (UINT8) packets; } packets = I16(data); data += 2; } for (p = x = 0; p < packets; p++) { x += data[0]; /* pixel skip */ if (data[1] >= 128) { i = 256-data[1]; /* run */ if (x + i + i > state->xsize) break; for (j = 0; j < i; j++) { buf[x++] = data[2]; buf[x++] = data[3]; } data += 2 + 2; } else { i = 2 * (int) data[1]; /* chunk */ if (x + i > state->xsize) break; memcpy(buf + x, data + 2, i); data += 2 + i; x += i; } } if (p < packets) break; /* didn't process all packets */ } if (l < lines) { /* didn't process all lines */ state->errcode = IMAGING_CODEC_OVERRUN; return -1; } break; case 12: /* FLI LC chunk (byte delta) */ y = I16(data); ymax = y + I16(data+2); data += 4; for (; y < ymax && y < state->ysize; y++) { UINT8* out = (UINT8*) im->image[y]; int p, packets = *data++; for (p = x = 0; p < packets; p++, x += i) { x += data[0]; /* skip pixels */ if (data[1] & 0x80) { i = 256-data[1]; /* run */ if (x + i > state->xsize) break; memset(out + x, data[2], i); data += 3; } else { i = data[1]; /* chunk */ if (x + i > state->xsize) break; memcpy(out + x, data + 2, i); data += i + 2; } } if (p < packets) break; /* didn't process all packets */ } if (y < ymax) { /* didn't process all lines */ state->errcode = IMAGING_CODEC_OVERRUN; return -1; } break; case 13: /* FLI BLACK chunk */ for (y = 0; y < state->ysize; y++) memset(im->image[y], 0, state->xsize); break; case 15: /* FLI BRUN chunk */ for (y = 0; y < state->ysize; y++) { UINT8* out = (UINT8*) im->image[y]; data += 1; /* ignore packetcount byte */ for (x = 0; x < state->xsize; x += i) { if (data[0] & 0x80) { i = 256 - data[0]; if (x + i > state->xsize) break; /* safety first */ memcpy(out + x, data + 1, i); data += i + 1; } else { i = data[0]; if (x + i > state->xsize) break; /* safety first */ memset(out + x, data[1], i); data += 2; } } if (x != state->xsize) { /* didn't unpack whole line */ state->errcode = IMAGING_CODEC_OVERRUN; return -1; } } break; case 16: /* COPY chunk */ for (y = 0; y < state->ysize; y++) { UINT8* buf = (UINT8*) im->image[y]; memcpy(buf, data, state->xsize); data += state->xsize; } break; case 18: /* PSTAMP chunk */ break; /* ignored */ default: /* unknown chunk */ /* printf(""unknown FLI/FLC chunk: %d\n"", I16(ptr+4)); */ state->errcode = IMAGING_CODEC_UNKNOWN; return -1; } advance = I32(ptr); ptr += advance; bytes -= advance; } return -1; /* end of frame */ }","{'deleted': [{'line_no': 15, 'char_start': 364, 'char_end': 434, 'line': ' input buffer (on the other hand, the Python part of the driver\n'}, {'line_no': 16, 'char_start': 434, 'char_end': 480, 'line': ' makes sure this is always the case) */\n'}], 'added': [{'line_no': 15, 'char_start': 364, 'char_end': 387, 'line': ' input buffer */\n'}, {'line_no': 26, 'char_start': 575, 'char_end': 596, 'line': ' if (bytes < 8) {\n'}, {'line_no': 27, 'char_start': 596, 'char_end': 644, 'line': ' state->errcode = IMAGING_CODEC_OVERRUN;\n'}, {'line_no': 28, 'char_start': 644, 'char_end': 663, 'line': ' return -1;\n'}, {'line_no': 29, 'char_start': 663, 'char_end': 669, 'line': ' }\n'}]}","{'deleted': [{'char_start': 384, 'char_end': 477, 'chars': '(on the other hand, the Python part of the driver\n makes sure this is always the case) '}], 'added': [{'char_start': 574, 'char_end': 668, 'chars': '\n if (bytes < 8) {\n state->errcode = IMAGING_CODEC_OVERRUN;\n return -1;\n }'}]}",github.com/python-pillow/Pillow/commit/a09acd0decd8a87ccce939d5ff65dab59e7d365b,src/libImaging/FliDecode.c,cwe-125,1563 cwe-476,unimac_mdio_probe,"static int unimac_mdio_probe(struct platform_device *pdev) { struct unimac_mdio_pdata *pdata = pdev->dev.platform_data; struct unimac_mdio_priv *priv; struct device_node *np; struct mii_bus *bus; struct resource *r; int ret; np = pdev->dev.of_node; priv = devm_kzalloc(&pdev->dev, sizeof(*priv), GFP_KERNEL); if (!priv) return -ENOMEM; r = platform_get_resource(pdev, IORESOURCE_MEM, 0); /* Just ioremap, as this MDIO block is usually integrated into an * Ethernet MAC controller register range */ priv->base = devm_ioremap(&pdev->dev, r->start, resource_size(r)); if (!priv->base) { dev_err(&pdev->dev, ""failed to remap register\n""); return -ENOMEM; } priv->mii_bus = mdiobus_alloc(); if (!priv->mii_bus) return -ENOMEM; bus = priv->mii_bus; bus->priv = priv; if (pdata) { bus->name = pdata->bus_name; priv->wait_func = pdata->wait_func; priv->wait_func_data = pdata->wait_func_data; bus->phy_mask = ~pdata->phy_mask; } else { bus->name = ""unimac MII bus""; priv->wait_func_data = priv; priv->wait_func = unimac_mdio_poll; } bus->parent = &pdev->dev; bus->read = unimac_mdio_read; bus->write = unimac_mdio_write; bus->reset = unimac_mdio_reset; snprintf(bus->id, MII_BUS_ID_SIZE, ""%s-%d"", pdev->name, pdev->id); ret = of_mdiobus_register(bus, np); if (ret) { dev_err(&pdev->dev, ""MDIO bus registration failed\n""); goto out_mdio_free; } platform_set_drvdata(pdev, priv); dev_info(&pdev->dev, ""Broadcom UniMAC MDIO bus at 0x%p\n"", priv->base); return 0; out_mdio_free: mdiobus_free(bus); return ret; }","static int unimac_mdio_probe(struct platform_device *pdev) { struct unimac_mdio_pdata *pdata = pdev->dev.platform_data; struct unimac_mdio_priv *priv; struct device_node *np; struct mii_bus *bus; struct resource *r; int ret; np = pdev->dev.of_node; priv = devm_kzalloc(&pdev->dev, sizeof(*priv), GFP_KERNEL); if (!priv) return -ENOMEM; r = platform_get_resource(pdev, IORESOURCE_MEM, 0); if (!r) return -EINVAL; /* Just ioremap, as this MDIO block is usually integrated into an * Ethernet MAC controller register range */ priv->base = devm_ioremap(&pdev->dev, r->start, resource_size(r)); if (!priv->base) { dev_err(&pdev->dev, ""failed to remap register\n""); return -ENOMEM; } priv->mii_bus = mdiobus_alloc(); if (!priv->mii_bus) return -ENOMEM; bus = priv->mii_bus; bus->priv = priv; if (pdata) { bus->name = pdata->bus_name; priv->wait_func = pdata->wait_func; priv->wait_func_data = pdata->wait_func_data; bus->phy_mask = ~pdata->phy_mask; } else { bus->name = ""unimac MII bus""; priv->wait_func_data = priv; priv->wait_func = unimac_mdio_poll; } bus->parent = &pdev->dev; bus->read = unimac_mdio_read; bus->write = unimac_mdio_write; bus->reset = unimac_mdio_reset; snprintf(bus->id, MII_BUS_ID_SIZE, ""%s-%d"", pdev->name, pdev->id); ret = of_mdiobus_register(bus, np); if (ret) { dev_err(&pdev->dev, ""MDIO bus registration failed\n""); goto out_mdio_free; } platform_set_drvdata(pdev, priv); dev_info(&pdev->dev, ""Broadcom UniMAC MDIO bus at 0x%p\n"", priv->base); return 0; out_mdio_free: mdiobus_free(bus); return ret; }","{'deleted': [], 'added': [{'line_no': 17, 'char_start': 403, 'char_end': 412, 'line': '\tif (!r)\n'}, {'line_no': 18, 'char_start': 412, 'char_end': 430, 'line': '\t\treturn -EINVAL;\n'}]}","{'deleted': [], 'added': [{'char_start': 403, 'char_end': 430, 'chars': '\tif (!r)\n\t\treturn -EINVAL;\n'}]}",github.com/torvalds/linux/commit/297a6961ffb8ff4dc66c9fbf53b924bd1dda05d5,drivers/net/phy/mdio-bcm-unimac.c,cwe-476,490 cwe-476,lys_restr_dup,"lys_restr_dup(struct lys_module *mod, struct lys_restr *old, int size, int shallow, struct unres_schema *unres) { struct lys_restr *result; int i; if (!size) { return NULL; } result = calloc(size, sizeof *result); LY_CHECK_ERR_RETURN(!result, LOGMEM(mod->ctx), NULL); for (i = 0; i < size; i++) { result[i].ext_size = old[i].ext_size; lys_ext_dup(mod->ctx, mod, old[i].ext, old[i].ext_size, &result[i], LYEXT_PAR_RESTR, &result[i].ext, shallow, unres); result[i].expr = lydict_insert(mod->ctx, old[i].expr, 0); result[i].dsc = lydict_insert(mod->ctx, old[i].dsc, 0); result[i].ref = lydict_insert(mod->ctx, old[i].ref, 0); result[i].eapptag = lydict_insert(mod->ctx, old[i].eapptag, 0); result[i].emsg = lydict_insert(mod->ctx, old[i].emsg, 0); } return result; }","lys_restr_dup(struct lys_module *mod, struct lys_restr *old, int size, int shallow, struct unres_schema *unres) { struct lys_restr *result; int i; if (!size) { return NULL; } result = calloc(size, sizeof *result); LY_CHECK_ERR_RETURN(!result, LOGMEM(mod->ctx), NULL); for (i = 0; i < size; i++) { /* copying unresolved extensions is not supported */ if (unres_schema_find(unres, -1, (void *)&old[i].ext, UNRES_EXT) == -1) { result[i].ext_size = old[i].ext_size; lys_ext_dup(mod->ctx, mod, old[i].ext, old[i].ext_size, &result[i], LYEXT_PAR_RESTR, &result[i].ext, shallow, unres); } result[i].expr = lydict_insert(mod->ctx, old[i].expr, 0); result[i].dsc = lydict_insert(mod->ctx, old[i].dsc, 0); result[i].ref = lydict_insert(mod->ctx, old[i].ref, 0); result[i].eapptag = lydict_insert(mod->ctx, old[i].eapptag, 0); result[i].emsg = lydict_insert(mod->ctx, old[i].emsg, 0); } return result; }","{'deleted': [{'line_no': 14, 'char_start': 336, 'char_end': 382, 'line': ' result[i].ext_size = old[i].ext_size;\n'}, {'line_no': 15, 'char_start': 382, 'char_end': 508, 'line': ' lys_ext_dup(mod->ctx, mod, old[i].ext, old[i].ext_size, &result[i], LYEXT_PAR_RESTR, &result[i].ext, shallow, unres);\n'}], 'added': [{'line_no': 14, 'char_start': 336, 'char_end': 397, 'line': ' /* copying unresolved extensions is not supported */\n'}, {'line_no': 15, 'char_start': 397, 'char_end': 479, 'line': ' if (unres_schema_find(unres, -1, (void *)&old[i].ext, UNRES_EXT) == -1) {\n'}, {'line_no': 16, 'char_start': 479, 'char_end': 529, 'line': ' result[i].ext_size = old[i].ext_size;\n'}, {'line_no': 17, 'char_start': 529, 'char_end': 659, 'line': ' lys_ext_dup(mod->ctx, mod, old[i].ext, old[i].ext_size, &result[i], LYEXT_PAR_RESTR, &result[i].ext, shallow, unres);\n'}, {'line_no': 18, 'char_start': 659, 'char_end': 669, 'line': ' }\n'}]}","{'deleted': [], 'added': [{'char_start': 344, 'char_end': 491, 'chars': '/* copying unresolved extensions is not supported */\n if (unres_schema_find(unres, -1, (void *)&old[i].ext, UNRES_EXT) == -1) {\n '}, {'char_start': 529, 'char_end': 533, 'chars': ' '}, {'char_start': 658, 'char_end': 668, 'chars': '\n }'}]}",github.com/CESNET/libyang/commit/7852b272ef77f8098c35deea6c6f09cb78176f08,src/tree_schema.c,cwe-476,274 cwe-125,_bson_iter_next_internal,"_bson_iter_next_internal (bson_iter_t *iter, /* INOUT */ uint32_t next_keylen, /* IN */ const char **key, /* OUT */ uint32_t *bson_type, /* OUT */ bool *unsupported) /* OUT */ { const uint8_t *data; uint32_t o; unsigned int len; BSON_ASSERT (iter); *unsupported = false; if (!iter->raw) { *key = NULL; *bson_type = BSON_TYPE_EOD; return false; } data = iter->raw; len = iter->len; iter->off = iter->next_off; iter->type = iter->off; iter->key = iter->off + 1; iter->d1 = 0; iter->d2 = 0; iter->d3 = 0; iter->d4 = 0; if (next_keylen == 0) { /* iterate from start to end of NULL-terminated key string */ for (o = iter->key; o < len; o++) { if (!data[o]) { iter->d1 = ++o; goto fill_data_fields; } } } else { o = iter->key + next_keylen + 1; iter->d1 = o; goto fill_data_fields; } goto mark_invalid; fill_data_fields: *key = bson_iter_key_unsafe (iter); *bson_type = ITER_TYPE (iter); switch (*bson_type) { case BSON_TYPE_DATE_TIME: case BSON_TYPE_DOUBLE: case BSON_TYPE_INT64: case BSON_TYPE_TIMESTAMP: iter->next_off = o + 8; break; case BSON_TYPE_CODE: case BSON_TYPE_SYMBOL: case BSON_TYPE_UTF8: { uint32_t l; if ((o + 4) >= len) { iter->err_off = o; goto mark_invalid; } iter->d2 = o + 4; memcpy (&l, iter->raw + iter->d1, sizeof (l)); l = BSON_UINT32_FROM_LE (l); if (l > (len - (o + 4))) { iter->err_off = o; goto mark_invalid; } iter->next_off = o + 4 + l; /* * Make sure the string length includes the NUL byte. */ if (BSON_UNLIKELY ((l == 0) || (iter->next_off >= len))) { iter->err_off = o; goto mark_invalid; } /* * Make sure the last byte is a NUL byte. */ if (BSON_UNLIKELY ((iter->raw + iter->d2)[l - 1] != '\0')) { iter->err_off = o + 4 + l - 1; goto mark_invalid; } } break; case BSON_TYPE_BINARY: { bson_subtype_t subtype; uint32_t l; if (o >= (len - 4)) { iter->err_off = o; goto mark_invalid; } iter->d2 = o + 4; iter->d3 = o + 5; memcpy (&l, iter->raw + iter->d1, sizeof (l)); l = BSON_UINT32_FROM_LE (l); if (l >= (len - o)) { iter->err_off = o; goto mark_invalid; } subtype = *(iter->raw + iter->d2); if (subtype == BSON_SUBTYPE_BINARY_DEPRECATED) { int32_t binary_len; if (l < 4) { iter->err_off = o; goto mark_invalid; } /* subtype 2 has a redundant length header in the data */ memcpy (&binary_len, (iter->raw + iter->d3), sizeof (binary_len)); binary_len = BSON_UINT32_FROM_LE (binary_len); if (binary_len + 4 != l) { iter->err_off = iter->d3; goto mark_invalid; } } iter->next_off = o + 5 + l; } break; case BSON_TYPE_ARRAY: case BSON_TYPE_DOCUMENT: { uint32_t l; if (o >= (len - 4)) { iter->err_off = o; goto mark_invalid; } memcpy (&l, iter->raw + iter->d1, sizeof (l)); l = BSON_UINT32_FROM_LE (l); if ((l > len) || (l > (len - o))) { iter->err_off = o; goto mark_invalid; } iter->next_off = o + l; } break; case BSON_TYPE_OID: iter->next_off = o + 12; break; case BSON_TYPE_BOOL: { char val; if (iter->d1 >= len) { iter->err_off = o; goto mark_invalid; } memcpy (&val, iter->raw + iter->d1, 1); if (val != 0x00 && val != 0x01) { iter->err_off = o; goto mark_invalid; } iter->next_off = o + 1; } break; case BSON_TYPE_REGEX: { bool eor = false; bool eoo = false; for (; o < len; o++) { if (!data[o]) { iter->d2 = ++o; eor = true; break; } } if (!eor) { iter->err_off = iter->next_off; goto mark_invalid; } for (; o < len; o++) { if (!data[o]) { eoo = true; break; } } if (!eoo) { iter->err_off = iter->next_off; goto mark_invalid; } iter->next_off = o + 1; } break; case BSON_TYPE_DBPOINTER: { uint32_t l; if (o >= (len - 4)) { iter->err_off = o; goto mark_invalid; } iter->d2 = o + 4; memcpy (&l, iter->raw + iter->d1, sizeof (l)); l = BSON_UINT32_FROM_LE (l); /* Check valid string length. l counts '\0' but not 4 bytes for itself. */ if (l == 0 || l > (len - o - 4)) { iter->err_off = o; goto mark_invalid; } if (*(iter->raw + o + l + 3)) { /* not null terminated */ iter->err_off = o + l + 3; goto mark_invalid; } iter->d3 = o + 4 + l; iter->next_off = o + 4 + l + 12; } break; case BSON_TYPE_CODEWSCOPE: { uint32_t l; uint32_t doclen; if ((len < 19) || (o >= (len - 14))) { iter->err_off = o; goto mark_invalid; } iter->d2 = o + 4; iter->d3 = o + 8; memcpy (&l, iter->raw + iter->d1, sizeof (l)); l = BSON_UINT32_FROM_LE (l); if ((l < 14) || (l >= (len - o))) { iter->err_off = o; goto mark_invalid; } iter->next_off = o + l; if (iter->next_off >= len) { iter->err_off = o; goto mark_invalid; } memcpy (&l, iter->raw + iter->d2, sizeof (l)); l = BSON_UINT32_FROM_LE (l); if (l == 0 || l >= (len - o - 4 - 4)) { iter->err_off = o; goto mark_invalid; } if ((o + 4 + 4 + l + 4) >= iter->next_off) { iter->err_off = o + 4; goto mark_invalid; } iter->d4 = o + 4 + 4 + l; memcpy (&doclen, iter->raw + iter->d4, sizeof (doclen)); doclen = BSON_UINT32_FROM_LE (doclen); if ((o + 4 + 4 + l + doclen) != iter->next_off) { iter->err_off = o + 4 + 4 + l; goto mark_invalid; } } break; case BSON_TYPE_INT32: iter->next_off = o + 4; break; case BSON_TYPE_DECIMAL128: iter->next_off = o + 16; break; case BSON_TYPE_MAXKEY: case BSON_TYPE_MINKEY: case BSON_TYPE_NULL: case BSON_TYPE_UNDEFINED: iter->next_off = o; break; default: *unsupported = true; /* FALL THROUGH */ case BSON_TYPE_EOD: iter->err_off = o; goto mark_invalid; } /* * Check to see if any of the field locations would overflow the * current BSON buffer. If so, set the error location to the offset * of where the field starts. */ if (iter->next_off >= len) { iter->err_off = o; goto mark_invalid; } iter->err_off = 0; return true; mark_invalid: iter->raw = NULL; iter->len = 0; iter->next_off = 0; return false; }","_bson_iter_next_internal (bson_iter_t *iter, /* INOUT */ uint32_t next_keylen, /* IN */ const char **key, /* OUT */ uint32_t *bson_type, /* OUT */ bool *unsupported) /* OUT */ { const uint8_t *data; uint32_t o; unsigned int len; BSON_ASSERT (iter); *unsupported = false; if (!iter->raw) { *key = NULL; *bson_type = BSON_TYPE_EOD; return false; } data = iter->raw; len = iter->len; iter->off = iter->next_off; iter->type = iter->off; iter->key = iter->off + 1; iter->d1 = 0; iter->d2 = 0; iter->d3 = 0; iter->d4 = 0; if (next_keylen == 0) { /* iterate from start to end of NULL-terminated key string */ for (o = iter->key; o < len; o++) { if (!data[o]) { iter->d1 = ++o; goto fill_data_fields; } } } else { o = iter->key + next_keylen + 1; iter->d1 = o; goto fill_data_fields; } goto mark_invalid; fill_data_fields: *key = bson_iter_key_unsafe (iter); *bson_type = ITER_TYPE (iter); switch (*bson_type) { case BSON_TYPE_DATE_TIME: case BSON_TYPE_DOUBLE: case BSON_TYPE_INT64: case BSON_TYPE_TIMESTAMP: iter->next_off = o + 8; break; case BSON_TYPE_CODE: case BSON_TYPE_SYMBOL: case BSON_TYPE_UTF8: { uint32_t l; if ((o + 4) >= len) { iter->err_off = o; goto mark_invalid; } iter->d2 = o + 4; memcpy (&l, iter->raw + iter->d1, sizeof (l)); l = BSON_UINT32_FROM_LE (l); if (l > (len - (o + 4))) { iter->err_off = o; goto mark_invalid; } iter->next_off = o + 4 + l; /* * Make sure the string length includes the NUL byte. */ if (BSON_UNLIKELY ((l == 0) || (iter->next_off >= len))) { iter->err_off = o; goto mark_invalid; } /* * Make sure the last byte is a NUL byte. */ if (BSON_UNLIKELY ((iter->raw + iter->d2)[l - 1] != '\0')) { iter->err_off = o + 4 + l - 1; goto mark_invalid; } } break; case BSON_TYPE_BINARY: { bson_subtype_t subtype; uint32_t l; if (o >= (len - 4)) { iter->err_off = o; goto mark_invalid; } iter->d2 = o + 4; iter->d3 = o + 5; memcpy (&l, iter->raw + iter->d1, sizeof (l)); l = BSON_UINT32_FROM_LE (l); if (l >= (len - o - 4)) { iter->err_off = o; goto mark_invalid; } subtype = *(iter->raw + iter->d2); if (subtype == BSON_SUBTYPE_BINARY_DEPRECATED) { int32_t binary_len; if (l < 4) { iter->err_off = o; goto mark_invalid; } /* subtype 2 has a redundant length header in the data */ memcpy (&binary_len, (iter->raw + iter->d3), sizeof (binary_len)); binary_len = BSON_UINT32_FROM_LE (binary_len); if (binary_len + 4 != l) { iter->err_off = iter->d3; goto mark_invalid; } } iter->next_off = o + 5 + l; } break; case BSON_TYPE_ARRAY: case BSON_TYPE_DOCUMENT: { uint32_t l; if (o >= (len - 4)) { iter->err_off = o; goto mark_invalid; } memcpy (&l, iter->raw + iter->d1, sizeof (l)); l = BSON_UINT32_FROM_LE (l); if ((l > len) || (l > (len - o))) { iter->err_off = o; goto mark_invalid; } iter->next_off = o + l; } break; case BSON_TYPE_OID: iter->next_off = o + 12; break; case BSON_TYPE_BOOL: { char val; if (iter->d1 >= len) { iter->err_off = o; goto mark_invalid; } memcpy (&val, iter->raw + iter->d1, 1); if (val != 0x00 && val != 0x01) { iter->err_off = o; goto mark_invalid; } iter->next_off = o + 1; } break; case BSON_TYPE_REGEX: { bool eor = false; bool eoo = false; for (; o < len; o++) { if (!data[o]) { iter->d2 = ++o; eor = true; break; } } if (!eor) { iter->err_off = iter->next_off; goto mark_invalid; } for (; o < len; o++) { if (!data[o]) { eoo = true; break; } } if (!eoo) { iter->err_off = iter->next_off; goto mark_invalid; } iter->next_off = o + 1; } break; case BSON_TYPE_DBPOINTER: { uint32_t l; if (o >= (len - 4)) { iter->err_off = o; goto mark_invalid; } iter->d2 = o + 4; memcpy (&l, iter->raw + iter->d1, sizeof (l)); l = BSON_UINT32_FROM_LE (l); /* Check valid string length. l counts '\0' but not 4 bytes for itself. */ if (l == 0 || l > (len - o - 4)) { iter->err_off = o; goto mark_invalid; } if (*(iter->raw + o + l + 3)) { /* not null terminated */ iter->err_off = o + l + 3; goto mark_invalid; } iter->d3 = o + 4 + l; iter->next_off = o + 4 + l + 12; } break; case BSON_TYPE_CODEWSCOPE: { uint32_t l; uint32_t doclen; if ((len < 19) || (o >= (len - 14))) { iter->err_off = o; goto mark_invalid; } iter->d2 = o + 4; iter->d3 = o + 8; memcpy (&l, iter->raw + iter->d1, sizeof (l)); l = BSON_UINT32_FROM_LE (l); if ((l < 14) || (l >= (len - o))) { iter->err_off = o; goto mark_invalid; } iter->next_off = o + l; if (iter->next_off >= len) { iter->err_off = o; goto mark_invalid; } memcpy (&l, iter->raw + iter->d2, sizeof (l)); l = BSON_UINT32_FROM_LE (l); if (l == 0 || l >= (len - o - 4 - 4)) { iter->err_off = o; goto mark_invalid; } if ((o + 4 + 4 + l + 4) >= iter->next_off) { iter->err_off = o + 4; goto mark_invalid; } iter->d4 = o + 4 + 4 + l; memcpy (&doclen, iter->raw + iter->d4, sizeof (doclen)); doclen = BSON_UINT32_FROM_LE (doclen); if ((o + 4 + 4 + l + doclen) != iter->next_off) { iter->err_off = o + 4 + 4 + l; goto mark_invalid; } } break; case BSON_TYPE_INT32: iter->next_off = o + 4; break; case BSON_TYPE_DECIMAL128: iter->next_off = o + 16; break; case BSON_TYPE_MAXKEY: case BSON_TYPE_MINKEY: case BSON_TYPE_NULL: case BSON_TYPE_UNDEFINED: iter->next_off = o; break; default: *unsupported = true; /* FALL THROUGH */ case BSON_TYPE_EOD: iter->err_off = o; goto mark_invalid; } /* * Check to see if any of the field locations would overflow the * current BSON buffer. If so, set the error location to the offset * of where the field starts. */ if (iter->next_off >= len) { iter->err_off = o; goto mark_invalid; } iter->err_off = 0; return true; mark_invalid: iter->raw = NULL; iter->len = 0; iter->next_off = 0; return false; }","{'deleted': [{'line_no': 112, 'char_start': 2519, 'char_end': 2547, 'line': ' if (l >= (len - o)) {\n'}], 'added': [{'line_no': 112, 'char_start': 2519, 'char_end': 2551, 'line': ' if (l >= (len - o - 4)) {\n'}]}","{'deleted': [], 'added': [{'char_start': 2542, 'char_end': 2546, 'chars': ' - 4'}]}",github.com/mongodb/mongo-c-driver/commit/0d9a4d98bfdf4acd2c0138d4aaeb4e2e0934bd84,src/libbson/src/bson/bson-iter.c,cwe-125,2171 cwe-078,_get_fc_wwpns," def _get_fc_wwpns(self): for key in self._storage_nodes: node = self._storage_nodes[key] ssh_cmd = 'svcinfo lsnode -delim ! %s' % node['id'] raw = self._run_ssh(ssh_cmd) resp = CLIResponse(raw, delim='!', with_header=False) wwpns = set(node['WWPN']) for i, s in resp.select('port_id', 'port_status'): if 'unconfigured' != s: wwpns.add(i) node['WWPN'] = list(wwpns) LOG.info(_('WWPN on node %(node)s: %(wwpn)s') % {'node': node['id'], 'wwpn': node['WWPN']})"," def _get_fc_wwpns(self): for key in self._storage_nodes: node = self._storage_nodes[key] ssh_cmd = ['svcinfo', 'lsnode', '-delim', '!', node['id']] raw = self._run_ssh(ssh_cmd) resp = CLIResponse(raw, delim='!', with_header=False) wwpns = set(node['WWPN']) for i, s in resp.select('port_id', 'port_status'): if 'unconfigured' != s: wwpns.add(i) node['WWPN'] = list(wwpns) LOG.info(_('WWPN on node %(node)s: %(wwpn)s') % {'node': node['id'], 'wwpn': node['WWPN']})","{'deleted': [{'line_no': 4, 'char_start': 113, 'char_end': 177, 'line': "" ssh_cmd = 'svcinfo lsnode -delim ! %s' % node['id']\n""}], 'added': [{'line_no': 4, 'char_start': 113, 'char_end': 184, 'line': "" ssh_cmd = ['svcinfo', 'lsnode', '-delim', '!', node['id']]\n""}]}","{'deleted': [{'char_start': 159, 'char_end': 162, 'chars': ' %s'}, {'char_start': 163, 'char_end': 165, 'chars': ' %'}], 'added': [{'char_start': 135, 'char_end': 136, 'chars': '['}, {'char_start': 144, 'char_end': 146, 'chars': ""',""}, {'char_start': 147, 'char_end': 148, 'chars': ""'""}, {'char_start': 154, 'char_end': 156, 'chars': ""',""}, {'char_start': 157, 'char_end': 158, 'chars': ""'""}, {'char_start': 164, 'char_end': 166, 'chars': ""',""}, {'char_start': 167, 'char_end': 168, 'chars': ""'""}, {'char_start': 170, 'char_end': 171, 'chars': ','}, {'char_start': 181, 'char_end': 182, 'chars': ']'}]}",github.com/thatsdone/cinder/commit/f752302d181583a95cf44354aea607ce9d9283f4,cinder/volume/drivers/storwize_svc.py,cwe-078,167 cwe-022,dd_save_text,"void dd_save_text(struct dump_dir *dd, const char *name, const char *data) { if (!dd->locked) error_msg_and_die(""dump_dir is not opened""); /* bug */ char *full_path = concat_path_file(dd->dd_dirname, name); save_binary_file(full_path, data, strlen(data), dd->dd_uid, dd->dd_gid, dd->mode); free(full_path); }","void dd_save_text(struct dump_dir *dd, const char *name, const char *data) { if (!dd->locked) error_msg_and_die(""dump_dir is not opened""); /* bug */ if (!str_is_correct_filename(name)) error_msg_and_die(""Cannot save text. '%s' is not a valid file name"", name); char *full_path = concat_path_file(dd->dd_dirname, name); save_binary_file(full_path, data, strlen(data), dd->dd_uid, dd->dd_gid, dd->mode); free(full_path); }","{'deleted': [], 'added': [{'line_no': 6, 'char_start': 162, 'char_end': 202, 'line': ' if (!str_is_correct_filename(name))\n'}, {'line_no': 7, 'char_start': 202, 'char_end': 286, 'line': ' error_msg_and_die(""Cannot save text. \'%s\' is not a valid file name"", name);\n'}, {'line_no': 8, 'char_start': 286, 'char_end': 287, 'line': '\n'}]}","{'deleted': [], 'added': [{'char_start': 166, 'char_end': 291, 'chars': 'if (!str_is_correct_filename(name))\n error_msg_and_die(""Cannot save text. \'%s\' is not a valid file name"", name);\n\n '}]}",github.com/abrt/libreport/commit/239c4f7d1f47265526b39ad70106767d00805277,src/lib/dump_dir.c,cwe-022,92 cwe-022,get_files," def get_files(self, submit_id, password=None, astree=False): """""" Returns files from a submitted analysis. @param password: The password to unlock container archives with @param astree: sflock option; determines the format in which the files are returned @return: A tree of files """""" submit = Database().view_submit(submit_id) files, duplicates = [], [] for data in submit.data[""data""]: if data[""type""] == ""file"": filename = Storage.get_filename_from_path(data[""data""]) filepath = os.path.join(submit.tmp_path, data[""data""]) filedata = open(filepath, ""rb"").read() unpacked = sflock.unpack( filepath=filename, contents=filedata, password=password, duplicates=duplicates ) if astree: unpacked = unpacked.astree() files.append(unpacked) elif data[""type""] == ""url"": files.append({ ""filename"": data[""data""], ""filepath"": """", ""relapath"": """", ""selected"": True, ""size"": 0, ""type"": ""url"", ""package"": ""ie"", ""extrpath"": [], ""duplicate"": False, ""children"": [], ""mime"": ""text/html"", ""finger"": { ""magic_human"": ""url"", ""magic"": ""url"" } }) else: raise RuntimeError( ""Unknown data entry type: %s"" % data[""type""] ) return { ""files"": files, ""path"": submit.tmp_path, }"," def get_files(self, submit_id, password=None, astree=False): """""" Returns files from a submitted analysis. @param password: The password to unlock container archives with @param astree: sflock option; determines the format in which the files are returned @return: A tree of files """""" submit = Database().view_submit(submit_id) files, duplicates = [], [] for data in submit.data[""data""]: if data[""type""] == ""file"": filename = Storage.get_filename_from_path(data[""data""]) filepath = os.path.join(submit.tmp_path, filename) unpacked = sflock.unpack( filepath=filepath, password=password, duplicates=duplicates ) if astree: unpacked = unpacked.astree(sanitize=True) files.append(unpacked) elif data[""type""] == ""url"": files.append({ ""filename"": data[""data""], ""filepath"": """", ""relapath"": """", ""selected"": True, ""size"": 0, ""type"": ""url"", ""package"": ""ie"", ""extrpath"": [], ""duplicate"": False, ""children"": [], ""mime"": ""text/html"", ""finger"": { ""magic_human"": ""url"", ""magic"": ""url"" } }) else: raise RuntimeError( ""Unknown data entry type: %s"" % data[""type""] ) return files","{'deleted': [{'line_no': 14, 'char_start': 574, 'char_end': 645, 'line': ' filepath = os.path.join(submit.tmp_path, data[""data""])\n'}, {'line_no': 15, 'char_start': 645, 'char_end': 700, 'line': ' filedata = open(filepath, ""rb"").read()\n'}, {'line_no': 18, 'char_start': 743, 'char_end': 801, 'line': ' filepath=filename, contents=filedata,\n'}, {'line_no': 19, 'char_start': 801, 'char_end': 862, 'line': ' password=password, duplicates=duplicates\n'}, {'line_no': 23, 'char_start': 908, 'char_end': 957, 'line': ' unpacked = unpacked.astree()\n'}, {'line_no': 49, 'char_start': 1776, 'char_end': 1793, 'line': ' return {\n'}, {'line_no': 50, 'char_start': 1793, 'char_end': 1821, 'line': ' ""files"": files,\n'}, {'line_no': 51, 'char_start': 1821, 'char_end': 1858, 'line': ' ""path"": submit.tmp_path,\n'}, {'line_no': 52, 'char_start': 1858, 'char_end': 1867, 'line': ' }\n'}], 'added': [{'line_no': 14, 'char_start': 574, 'char_end': 641, 'line': ' filepath = os.path.join(submit.tmp_path, filename)\n'}, {'line_no': 17, 'char_start': 684, 'char_end': 764, 'line': ' filepath=filepath, password=password, duplicates=duplicates\n'}, {'line_no': 21, 'char_start': 810, 'char_end': 872, 'line': ' unpacked = unpacked.astree(sanitize=True)\n'}, {'line_no': 47, 'char_start': 1691, 'char_end': 1711, 'line': ' return files\n'}]}","{'deleted': [{'char_start': 631, 'char_end': 661, 'chars': 'data[""data""])\n '}, {'char_start': 665, 'char_end': 675, 'chars': 'data = ope'}, {'char_start': 676, 'char_end': 682, 'chars': '(filep'}, {'char_start': 683, 'char_end': 694, 'chars': 'th, ""rb"").r'}, {'char_start': 695, 'char_end': 698, 'chars': 'ad('}, {'char_start': 776, 'char_end': 796, 'chars': 'name, contents=filed'}, {'char_start': 798, 'char_end': 799, 'chars': 'a'}, {'char_start': 800, 'char_end': 820, 'chars': '\n '}, {'char_start': 1791, 'char_end': 1806, 'chars': '{\n ""'}, {'char_start': 1811, 'char_end': 1867, 'chars': '"": files,\n ""path"": submit.tmp_path,\n }'}], 'added': [{'char_start': 637, 'char_end': 638, 'chars': 'm'}, {'char_start': 717, 'char_end': 718, 'chars': 'p'}, {'char_start': 720, 'char_end': 721, 'chars': 'h'}, {'char_start': 857, 'char_end': 870, 'chars': 'sanitize=True'}]}",github.com/cuckoosandbox/cuckoo/commit/168cabf86730d56b7fa319278bf0f0034052666a,cuckoo/core/submit.py,cwe-022,346 cwe-125,match_at,"match_at(regex_t* reg, const UChar* str, const UChar* end, #ifdef USE_MATCH_RANGE_MUST_BE_INSIDE_OF_SPECIFIED_RANGE const UChar* right_range, #endif const UChar* sstart, UChar* sprev, OnigMatchArg* msa) { static UChar FinishCode[] = { OP_FINISH }; int i, n, num_mem, best_len, pop_level; LengthType tlen, tlen2; MemNumType mem; RelAddrType addr; UChar *s, *q, *sbegin; int is_alloca; char *alloc_base; OnigStackType *stk_base, *stk, *stk_end; OnigStackType *stkp; /* used as any purpose. */ OnigStackIndex si; OnigStackIndex *repeat_stk; OnigStackIndex *mem_start_stk, *mem_end_stk; #ifdef USE_COMBINATION_EXPLOSION_CHECK int scv; unsigned char* state_check_buff = msa->state_check_buff; int num_comb_exp_check = reg->num_comb_exp_check; #endif UChar *p = reg->p; OnigOptionType option = reg->options; OnigEncoding encode = reg->enc; OnigCaseFoldType case_fold_flag = reg->case_fold_flag; //n = reg->num_repeat + reg->num_mem * 2; pop_level = reg->stack_pop_level; num_mem = reg->num_mem; STACK_INIT(INIT_MATCH_STACK_SIZE); UPDATE_FOR_STACK_REALLOC; for (i = 1; i <= num_mem; i++) { mem_start_stk[i] = mem_end_stk[i] = INVALID_STACK_INDEX; } #ifdef ONIG_DEBUG_MATCH fprintf(stderr, ""match_at: str: %d, end: %d, start: %d, sprev: %d\n"", (int )str, (int )end, (int )sstart, (int )sprev); fprintf(stderr, ""size: %d, start offset: %d\n"", (int )(end - str), (int )(sstart - str)); #endif STACK_PUSH_ENSURED(STK_ALT, FinishCode); /* bottom stack */ best_len = ONIG_MISMATCH; s = (UChar* )sstart; while (1) { #ifdef ONIG_DEBUG_MATCH { UChar *q, *bp, buf[50]; int len; fprintf(stderr, ""%4d> \"""", (int )(s - str)); bp = buf; for (i = 0, q = s; i < 7 && q < end; i++) { len = enclen(encode, q); while (len-- > 0) *bp++ = *q++; } if (q < end) { xmemcpy(bp, ""...\"""", 4); bp += 4; } else { xmemcpy(bp, ""\"""", 1); bp += 1; } *bp = 0; fputs((char* )buf, stderr); for (i = 0; i < 20 - (bp - buf); i++) fputc(' ', stderr); onig_print_compiled_byte_code(stderr, p, NULL, encode); fprintf(stderr, ""\n""); } #endif sbegin = s; switch (*p++) { case OP_END: MOP_IN(OP_END); n = s - sstart; if (n > best_len) { OnigRegion* region; #ifdef USE_FIND_LONGEST_SEARCH_ALL_OF_RANGE if (IS_FIND_LONGEST(option)) { if (n > msa->best_len) { msa->best_len = n; msa->best_s = (UChar* )sstart; } else goto end_best_len; } #endif best_len = n; region = msa->region; if (region) { #ifdef USE_POSIX_API_REGION_OPTION if (IS_POSIX_REGION(msa->options)) { posix_regmatch_t* rmt = (posix_regmatch_t* )region; rmt[0].rm_so = sstart - str; rmt[0].rm_eo = s - str; for (i = 1; i <= num_mem; i++) { if (mem_end_stk[i] != INVALID_STACK_INDEX) { if (BIT_STATUS_AT(reg->bt_mem_start, i)) rmt[i].rm_so = STACK_AT(mem_start_stk[i])->u.mem.pstr - str; else rmt[i].rm_so = (UChar* )((void* )(mem_start_stk[i])) - str; rmt[i].rm_eo = (BIT_STATUS_AT(reg->bt_mem_end, i) ? STACK_AT(mem_end_stk[i])->u.mem.pstr : (UChar* )((void* )mem_end_stk[i])) - str; } else { rmt[i].rm_so = rmt[i].rm_eo = ONIG_REGION_NOTPOS; } } } else { #endif /* USE_POSIX_API_REGION_OPTION */ region->beg[0] = sstart - str; region->end[0] = s - str; for (i = 1; i <= num_mem; i++) { if (mem_end_stk[i] != INVALID_STACK_INDEX) { if (BIT_STATUS_AT(reg->bt_mem_start, i)) region->beg[i] = STACK_AT(mem_start_stk[i])->u.mem.pstr - str; else region->beg[i] = (UChar* )((void* )mem_start_stk[i]) - str; region->end[i] = (BIT_STATUS_AT(reg->bt_mem_end, i) ? STACK_AT(mem_end_stk[i])->u.mem.pstr : (UChar* )((void* )mem_end_stk[i])) - str; } else { region->beg[i] = region->end[i] = ONIG_REGION_NOTPOS; } } #ifdef USE_CAPTURE_HISTORY if (reg->capture_history != 0) { int r; OnigCaptureTreeNode* node; if (IS_NULL(region->history_root)) { region->history_root = node = history_node_new(); CHECK_NULL_RETURN_MEMERR(node); } else { node = region->history_root; history_tree_clear(node); } node->group = 0; node->beg = sstart - str; node->end = s - str; stkp = stk_base; r = make_capture_history_tree(region->history_root, &stkp, stk, (UChar* )str, reg); if (r < 0) { best_len = r; /* error code */ goto finish; } } #endif /* USE_CAPTURE_HISTORY */ #ifdef USE_POSIX_API_REGION_OPTION } /* else IS_POSIX_REGION() */ #endif } /* if (region) */ } /* n > best_len */ #ifdef USE_FIND_LONGEST_SEARCH_ALL_OF_RANGE end_best_len: #endif MOP_OUT; if (IS_FIND_CONDITION(option)) { if (IS_FIND_NOT_EMPTY(option) && s == sstart) { best_len = ONIG_MISMATCH; goto fail; /* for retry */ } if (IS_FIND_LONGEST(option) && DATA_ENSURE_CHECK1) { goto fail; /* for retry */ } } /* default behavior: return first-matching result. */ goto finish; break; case OP_EXACT1: MOP_IN(OP_EXACT1); #if 0 DATA_ENSURE(1); if (*p != *s) goto fail; p++; s++; #endif if (*p != *s++) goto fail; DATA_ENSURE(0); p++; MOP_OUT; break; case OP_EXACT1_IC: MOP_IN(OP_EXACT1_IC); { int len; UChar *q, lowbuf[ONIGENC_MBC_CASE_FOLD_MAXLEN]; DATA_ENSURE(1); len = ONIGENC_MBC_CASE_FOLD(encode, /* DISABLE_CASE_FOLD_MULTI_CHAR(case_fold_flag), */ case_fold_flag, &s, end, lowbuf); DATA_ENSURE(0); q = lowbuf; while (len-- > 0) { if (*p != *q) { goto fail; } p++; q++; } } MOP_OUT; break; case OP_EXACT2: MOP_IN(OP_EXACT2); DATA_ENSURE(2); if (*p != *s) goto fail; p++; s++; if (*p != *s) goto fail; sprev = s; p++; s++; MOP_OUT; continue; break; case OP_EXACT3: MOP_IN(OP_EXACT3); DATA_ENSURE(3); if (*p != *s) goto fail; p++; s++; if (*p != *s) goto fail; p++; s++; if (*p != *s) goto fail; sprev = s; p++; s++; MOP_OUT; continue; break; case OP_EXACT4: MOP_IN(OP_EXACT4); DATA_ENSURE(4); if (*p != *s) goto fail; p++; s++; if (*p != *s) goto fail; p++; s++; if (*p != *s) goto fail; p++; s++; if (*p != *s) goto fail; sprev = s; p++; s++; MOP_OUT; continue; break; case OP_EXACT5: MOP_IN(OP_EXACT5); DATA_ENSURE(5); if (*p != *s) goto fail; p++; s++; if (*p != *s) goto fail; p++; s++; if (*p != *s) goto fail; p++; s++; if (*p != *s) goto fail; p++; s++; if (*p != *s) goto fail; sprev = s; p++; s++; MOP_OUT; continue; break; case OP_EXACTN: MOP_IN(OP_EXACTN); GET_LENGTH_INC(tlen, p); DATA_ENSURE(tlen); while (tlen-- > 0) { if (*p++ != *s++) goto fail; } sprev = s - 1; MOP_OUT; continue; break; case OP_EXACTN_IC: MOP_IN(OP_EXACTN_IC); { int len; UChar *q, *endp, lowbuf[ONIGENC_MBC_CASE_FOLD_MAXLEN]; GET_LENGTH_INC(tlen, p); endp = p + tlen; while (p < endp) { sprev = s; DATA_ENSURE(1); len = ONIGENC_MBC_CASE_FOLD(encode, /* DISABLE_CASE_FOLD_MULTI_CHAR(case_fold_flag), */ case_fold_flag, &s, end, lowbuf); DATA_ENSURE(0); q = lowbuf; while (len-- > 0) { if (*p != *q) goto fail; p++; q++; } } } MOP_OUT; continue; break; case OP_EXACTMB2N1: MOP_IN(OP_EXACTMB2N1); DATA_ENSURE(2); if (*p != *s) goto fail; p++; s++; if (*p != *s) goto fail; p++; s++; MOP_OUT; break; case OP_EXACTMB2N2: MOP_IN(OP_EXACTMB2N2); DATA_ENSURE(4); if (*p != *s) goto fail; p++; s++; if (*p != *s) goto fail; p++; s++; sprev = s; if (*p != *s) goto fail; p++; s++; if (*p != *s) goto fail; p++; s++; MOP_OUT; continue; break; case OP_EXACTMB2N3: MOP_IN(OP_EXACTMB2N3); DATA_ENSURE(6); if (*p != *s) goto fail; p++; s++; if (*p != *s) goto fail; p++; s++; if (*p != *s) goto fail; p++; s++; if (*p != *s) goto fail; p++; s++; sprev = s; if (*p != *s) goto fail; p++; s++; if (*p != *s) goto fail; p++; s++; MOP_OUT; continue; break; case OP_EXACTMB2N: MOP_IN(OP_EXACTMB2N); GET_LENGTH_INC(tlen, p); DATA_ENSURE(tlen * 2); while (tlen-- > 0) { if (*p != *s) goto fail; p++; s++; if (*p != *s) goto fail; p++; s++; } sprev = s - 2; MOP_OUT; continue; break; case OP_EXACTMB3N: MOP_IN(OP_EXACTMB3N); GET_LENGTH_INC(tlen, p); DATA_ENSURE(tlen * 3); while (tlen-- > 0) { if (*p != *s) goto fail; p++; s++; if (*p != *s) goto fail; p++; s++; if (*p != *s) goto fail; p++; s++; } sprev = s - 3; MOP_OUT; continue; break; case OP_EXACTMBN: MOP_IN(OP_EXACTMBN); GET_LENGTH_INC(tlen, p); /* mb-len */ GET_LENGTH_INC(tlen2, p); /* string len */ tlen2 *= tlen; DATA_ENSURE(tlen2); while (tlen2-- > 0) { if (*p != *s) goto fail; p++; s++; } sprev = s - tlen; MOP_OUT; continue; break; case OP_CCLASS: MOP_IN(OP_CCLASS); DATA_ENSURE(1); if (BITSET_AT(((BitSetRef )p), *s) == 0) goto fail; p += SIZE_BITSET; s += enclen(encode, s); /* OP_CCLASS can match mb-code. \D, \S */ MOP_OUT; break; case OP_CCLASS_MB: MOP_IN(OP_CCLASS_MB); if (! ONIGENC_IS_MBC_HEAD(encode, s)) goto fail; cclass_mb: GET_LENGTH_INC(tlen, p); { OnigCodePoint code; UChar *ss; int mb_len; DATA_ENSURE(1); mb_len = enclen(encode, s); DATA_ENSURE(mb_len); ss = s; s += mb_len; code = ONIGENC_MBC_TO_CODE(encode, ss, s); #ifdef PLATFORM_UNALIGNED_WORD_ACCESS if (! onig_is_in_code_range(p, code)) goto fail; #else q = p; ALIGNMENT_RIGHT(q); if (! onig_is_in_code_range(q, code)) goto fail; #endif } p += tlen; MOP_OUT; break; case OP_CCLASS_MIX: MOP_IN(OP_CCLASS_MIX); DATA_ENSURE(1); if (ONIGENC_IS_MBC_HEAD(encode, s)) { p += SIZE_BITSET; goto cclass_mb; } else { if (BITSET_AT(((BitSetRef )p), *s) == 0) goto fail; p += SIZE_BITSET; GET_LENGTH_INC(tlen, p); p += tlen; s++; } MOP_OUT; break; case OP_CCLASS_NOT: MOP_IN(OP_CCLASS_NOT); DATA_ENSURE(1); if (BITSET_AT(((BitSetRef )p), *s) != 0) goto fail; p += SIZE_BITSET; s += enclen(encode, s); MOP_OUT; break; case OP_CCLASS_MB_NOT: MOP_IN(OP_CCLASS_MB_NOT); DATA_ENSURE(1); if (! ONIGENC_IS_MBC_HEAD(encode, s)) { s++; GET_LENGTH_INC(tlen, p); p += tlen; goto cc_mb_not_success; } cclass_mb_not: GET_LENGTH_INC(tlen, p); { OnigCodePoint code; UChar *ss; int mb_len = enclen(encode, s); if (! DATA_ENSURE_CHECK(mb_len)) { DATA_ENSURE(1); s = (UChar* )end; p += tlen; goto cc_mb_not_success; } ss = s; s += mb_len; code = ONIGENC_MBC_TO_CODE(encode, ss, s); #ifdef PLATFORM_UNALIGNED_WORD_ACCESS if (onig_is_in_code_range(p, code)) goto fail; #else q = p; ALIGNMENT_RIGHT(q); if (onig_is_in_code_range(q, code)) goto fail; #endif } p += tlen; cc_mb_not_success: MOP_OUT; break; case OP_CCLASS_MIX_NOT: MOP_IN(OP_CCLASS_MIX_NOT); DATA_ENSURE(1); if (ONIGENC_IS_MBC_HEAD(encode, s)) { p += SIZE_BITSET; goto cclass_mb_not; } else { if (BITSET_AT(((BitSetRef )p), *s) != 0) goto fail; p += SIZE_BITSET; GET_LENGTH_INC(tlen, p); p += tlen; s++; } MOP_OUT; break; case OP_CCLASS_NODE: MOP_IN(OP_CCLASS_NODE); { OnigCodePoint code; void *node; int mb_len; UChar *ss; DATA_ENSURE(1); GET_POINTER_INC(node, p); mb_len = enclen(encode, s); ss = s; s += mb_len; DATA_ENSURE(0); code = ONIGENC_MBC_TO_CODE(encode, ss, s); if (onig_is_code_in_cc_len(mb_len, code, node) == 0) goto fail; } MOP_OUT; break; case OP_ANYCHAR: MOP_IN(OP_ANYCHAR); DATA_ENSURE(1); n = enclen(encode, s); DATA_ENSURE(n); if (ONIGENC_IS_MBC_NEWLINE(encode, s, end)) goto fail; s += n; MOP_OUT; break; case OP_ANYCHAR_ML: MOP_IN(OP_ANYCHAR_ML); DATA_ENSURE(1); n = enclen(encode, s); DATA_ENSURE(n); s += n; MOP_OUT; break; case OP_ANYCHAR_STAR: MOP_IN(OP_ANYCHAR_STAR); while (DATA_ENSURE_CHECK1) { STACK_PUSH_ALT(p, s, sprev); n = enclen(encode, s); DATA_ENSURE(n); if (ONIGENC_IS_MBC_NEWLINE(encode, s, end)) goto fail; sprev = s; s += n; } MOP_OUT; break; case OP_ANYCHAR_ML_STAR: MOP_IN(OP_ANYCHAR_ML_STAR); while (DATA_ENSURE_CHECK1) { STACK_PUSH_ALT(p, s, sprev); n = enclen(encode, s); if (n > 1) { DATA_ENSURE(n); sprev = s; s += n; } else { sprev = s; s++; } } MOP_OUT; break; case OP_ANYCHAR_STAR_PEEK_NEXT: MOP_IN(OP_ANYCHAR_STAR_PEEK_NEXT); while (DATA_ENSURE_CHECK1) { if (*p == *s) { STACK_PUSH_ALT(p + 1, s, sprev); } n = enclen(encode, s); DATA_ENSURE(n); if (ONIGENC_IS_MBC_NEWLINE(encode, s, end)) goto fail; sprev = s; s += n; } p++; MOP_OUT; break; case OP_ANYCHAR_ML_STAR_PEEK_NEXT:MOP_IN(OP_ANYCHAR_ML_STAR_PEEK_NEXT); while (DATA_ENSURE_CHECK1) { if (*p == *s) { STACK_PUSH_ALT(p + 1, s, sprev); } n = enclen(encode, s); if (n > 1) { DATA_ENSURE(n); sprev = s; s += n; } else { sprev = s; s++; } } p++; MOP_OUT; break; #ifdef USE_COMBINATION_EXPLOSION_CHECK case OP_STATE_CHECK_ANYCHAR_STAR: MOP_IN(OP_STATE_CHECK_ANYCHAR_STAR); GET_STATE_CHECK_NUM_INC(mem, p); while (DATA_ENSURE_CHECK1) { STATE_CHECK_VAL(scv, mem); if (scv) goto fail; STACK_PUSH_ALT_WITH_STATE_CHECK(p, s, sprev, mem); n = enclen(encode, s); DATA_ENSURE(n); if (ONIGENC_IS_MBC_NEWLINE(encode, s, end)) goto fail; sprev = s; s += n; } MOP_OUT; break; case OP_STATE_CHECK_ANYCHAR_ML_STAR: MOP_IN(OP_STATE_CHECK_ANYCHAR_ML_STAR); GET_STATE_CHECK_NUM_INC(mem, p); while (DATA_ENSURE_CHECK1) { STATE_CHECK_VAL(scv, mem); if (scv) goto fail; STACK_PUSH_ALT_WITH_STATE_CHECK(p, s, sprev, mem); n = enclen(encode, s); if (n > 1) { DATA_ENSURE(n); sprev = s; s += n; } else { sprev = s; s++; } } MOP_OUT; break; #endif /* USE_COMBINATION_EXPLOSION_CHECK */ case OP_WORD: MOP_IN(OP_WORD); DATA_ENSURE(1); if (! ONIGENC_IS_MBC_WORD(encode, s, end)) goto fail; s += enclen(encode, s); MOP_OUT; break; case OP_NOT_WORD: MOP_IN(OP_NOT_WORD); DATA_ENSURE(1); if (ONIGENC_IS_MBC_WORD(encode, s, end)) goto fail; s += enclen(encode, s); MOP_OUT; break; case OP_WORD_BOUND: MOP_IN(OP_WORD_BOUND); if (ON_STR_BEGIN(s)) { DATA_ENSURE(1); if (! ONIGENC_IS_MBC_WORD(encode, s, end)) goto fail; } else if (ON_STR_END(s)) { if (! ONIGENC_IS_MBC_WORD(encode, sprev, end)) goto fail; } else { if (ONIGENC_IS_MBC_WORD(encode, s, end) == ONIGENC_IS_MBC_WORD(encode, sprev, end)) goto fail; } MOP_OUT; continue; break; case OP_NOT_WORD_BOUND: MOP_IN(OP_NOT_WORD_BOUND); if (ON_STR_BEGIN(s)) { if (DATA_ENSURE_CHECK1 && ONIGENC_IS_MBC_WORD(encode, s, end)) goto fail; } else if (ON_STR_END(s)) { if (ONIGENC_IS_MBC_WORD(encode, sprev, end)) goto fail; } else { if (ONIGENC_IS_MBC_WORD(encode, s, end) != ONIGENC_IS_MBC_WORD(encode, sprev, end)) goto fail; } MOP_OUT; continue; break; #ifdef USE_WORD_BEGIN_END case OP_WORD_BEGIN: MOP_IN(OP_WORD_BEGIN); if (DATA_ENSURE_CHECK1 && ONIGENC_IS_MBC_WORD(encode, s, end)) { if (ON_STR_BEGIN(s) || !ONIGENC_IS_MBC_WORD(encode, sprev, end)) { MOP_OUT; continue; } } goto fail; break; case OP_WORD_END: MOP_IN(OP_WORD_END); if (!ON_STR_BEGIN(s) && ONIGENC_IS_MBC_WORD(encode, sprev, end)) { if (ON_STR_END(s) || !ONIGENC_IS_MBC_WORD(encode, s, end)) { MOP_OUT; continue; } } goto fail; break; #endif case OP_BEGIN_BUF: MOP_IN(OP_BEGIN_BUF); if (! ON_STR_BEGIN(s)) goto fail; MOP_OUT; continue; break; case OP_END_BUF: MOP_IN(OP_END_BUF); if (! ON_STR_END(s)) goto fail; MOP_OUT; continue; break; case OP_BEGIN_LINE: MOP_IN(OP_BEGIN_LINE); if (ON_STR_BEGIN(s)) { if (IS_NOTBOL(msa->options)) goto fail; MOP_OUT; continue; } else if (ONIGENC_IS_MBC_NEWLINE(encode, sprev, end) && !ON_STR_END(s)) { MOP_OUT; continue; } goto fail; break; case OP_END_LINE: MOP_IN(OP_END_LINE); if (ON_STR_END(s)) { #ifndef USE_NEWLINE_AT_END_OF_STRING_HAS_EMPTY_LINE if (IS_EMPTY_STR || !ONIGENC_IS_MBC_NEWLINE(encode, sprev, end)) { #endif if (IS_NOTEOL(msa->options)) goto fail; MOP_OUT; continue; #ifndef USE_NEWLINE_AT_END_OF_STRING_HAS_EMPTY_LINE } #endif } else if (ONIGENC_IS_MBC_NEWLINE(encode, s, end)) { MOP_OUT; continue; } #ifdef USE_CRNL_AS_LINE_TERMINATOR else if (ONIGENC_IS_MBC_CRNL(encode, s, end)) { MOP_OUT; continue; } #endif goto fail; break; case OP_SEMI_END_BUF: MOP_IN(OP_SEMI_END_BUF); if (ON_STR_END(s)) { #ifndef USE_NEWLINE_AT_END_OF_STRING_HAS_EMPTY_LINE if (IS_EMPTY_STR || !ONIGENC_IS_MBC_NEWLINE(encode, sprev, end)) { #endif if (IS_NOTEOL(msa->options)) goto fail; MOP_OUT; continue; #ifndef USE_NEWLINE_AT_END_OF_STRING_HAS_EMPTY_LINE } #endif } else if (ONIGENC_IS_MBC_NEWLINE(encode, s, end) && ON_STR_END(s + enclen(encode, s))) { MOP_OUT; continue; } #ifdef USE_CRNL_AS_LINE_TERMINATOR else if (ONIGENC_IS_MBC_CRNL(encode, s, end)) { UChar* ss = s + enclen(encode, s); ss += enclen(encode, ss); if (ON_STR_END(ss)) { MOP_OUT; continue; } } #endif goto fail; break; case OP_BEGIN_POSITION: MOP_IN(OP_BEGIN_POSITION); if (s != msa->start) goto fail; MOP_OUT; continue; break; case OP_MEMORY_START_PUSH: MOP_IN(OP_MEMORY_START_PUSH); GET_MEMNUM_INC(mem, p); STACK_PUSH_MEM_START(mem, s); MOP_OUT; continue; break; case OP_MEMORY_START: MOP_IN(OP_MEMORY_START); GET_MEMNUM_INC(mem, p); mem_start_stk[mem] = (OnigStackIndex )((void* )s); MOP_OUT; continue; break; case OP_MEMORY_END_PUSH: MOP_IN(OP_MEMORY_END_PUSH); GET_MEMNUM_INC(mem, p); STACK_PUSH_MEM_END(mem, s); MOP_OUT; continue; break; case OP_MEMORY_END: MOP_IN(OP_MEMORY_END); GET_MEMNUM_INC(mem, p); mem_end_stk[mem] = (OnigStackIndex )((void* )s); MOP_OUT; continue; break; #ifdef USE_SUBEXP_CALL case OP_MEMORY_END_PUSH_REC: MOP_IN(OP_MEMORY_END_PUSH_REC); GET_MEMNUM_INC(mem, p); STACK_GET_MEM_START(mem, stkp); /* should be before push mem-end. */ STACK_PUSH_MEM_END(mem, s); mem_start_stk[mem] = GET_STACK_INDEX(stkp); MOP_OUT; continue; break; case OP_MEMORY_END_REC: MOP_IN(OP_MEMORY_END_REC); GET_MEMNUM_INC(mem, p); mem_end_stk[mem] = (OnigStackIndex )((void* )s); STACK_GET_MEM_START(mem, stkp); if (BIT_STATUS_AT(reg->bt_mem_start, mem)) mem_start_stk[mem] = GET_STACK_INDEX(stkp); else mem_start_stk[mem] = (OnigStackIndex )((void* )stkp->u.mem.pstr); STACK_PUSH_MEM_END_MARK(mem); MOP_OUT; continue; break; #endif case OP_BACKREF1: MOP_IN(OP_BACKREF1); mem = 1; goto backref; break; case OP_BACKREF2: MOP_IN(OP_BACKREF2); mem = 2; goto backref; break; case OP_BACKREFN: MOP_IN(OP_BACKREFN); GET_MEMNUM_INC(mem, p); backref: { int len; UChar *pstart, *pend; /* if you want to remove following line, you should check in parse and compile time. */ if (mem > num_mem) goto fail; if (mem_end_stk[mem] == INVALID_STACK_INDEX) goto fail; if (mem_start_stk[mem] == INVALID_STACK_INDEX) goto fail; if (BIT_STATUS_AT(reg->bt_mem_start, mem)) pstart = STACK_AT(mem_start_stk[mem])->u.mem.pstr; else pstart = (UChar* )((void* )mem_start_stk[mem]); pend = (BIT_STATUS_AT(reg->bt_mem_end, mem) ? STACK_AT(mem_end_stk[mem])->u.mem.pstr : (UChar* )((void* )mem_end_stk[mem])); n = pend - pstart; DATA_ENSURE(n); sprev = s; STRING_CMP(pstart, s, n); while (sprev + (len = enclen(encode, sprev)) < s) sprev += len; MOP_OUT; continue; } break; case OP_BACKREFN_IC: MOP_IN(OP_BACKREFN_IC); GET_MEMNUM_INC(mem, p); { int len; UChar *pstart, *pend; /* if you want to remove following line, you should check in parse and compile time. */ if (mem > num_mem) goto fail; if (mem_end_stk[mem] == INVALID_STACK_INDEX) goto fail; if (mem_start_stk[mem] == INVALID_STACK_INDEX) goto fail; if (BIT_STATUS_AT(reg->bt_mem_start, mem)) pstart = STACK_AT(mem_start_stk[mem])->u.mem.pstr; else pstart = (UChar* )((void* )mem_start_stk[mem]); pend = (BIT_STATUS_AT(reg->bt_mem_end, mem) ? STACK_AT(mem_end_stk[mem])->u.mem.pstr : (UChar* )((void* )mem_end_stk[mem])); n = pend - pstart; DATA_ENSURE(n); sprev = s; STRING_CMP_IC(case_fold_flag, pstart, &s, n); while (sprev + (len = enclen(encode, sprev)) < s) sprev += len; MOP_OUT; continue; } break; case OP_BACKREF_MULTI: MOP_IN(OP_BACKREF_MULTI); { int len, is_fail; UChar *pstart, *pend, *swork; GET_LENGTH_INC(tlen, p); for (i = 0; i < tlen; i++) { GET_MEMNUM_INC(mem, p); if (mem_end_stk[mem] == INVALID_STACK_INDEX) continue; if (mem_start_stk[mem] == INVALID_STACK_INDEX) continue; if (BIT_STATUS_AT(reg->bt_mem_start, mem)) pstart = STACK_AT(mem_start_stk[mem])->u.mem.pstr; else pstart = (UChar* )((void* )mem_start_stk[mem]); pend = (BIT_STATUS_AT(reg->bt_mem_end, mem) ? STACK_AT(mem_end_stk[mem])->u.mem.pstr : (UChar* )((void* )mem_end_stk[mem])); n = pend - pstart; DATA_ENSURE(n); sprev = s; swork = s; STRING_CMP_VALUE(pstart, swork, n, is_fail); if (is_fail) continue; s = swork; while (sprev + (len = enclen(encode, sprev)) < s) sprev += len; p += (SIZE_MEMNUM * (tlen - i - 1)); break; /* success */ } if (i == tlen) goto fail; MOP_OUT; continue; } break; case OP_BACKREF_MULTI_IC: MOP_IN(OP_BACKREF_MULTI_IC); { int len, is_fail; UChar *pstart, *pend, *swork; GET_LENGTH_INC(tlen, p); for (i = 0; i < tlen; i++) { GET_MEMNUM_INC(mem, p); if (mem_end_stk[mem] == INVALID_STACK_INDEX) continue; if (mem_start_stk[mem] == INVALID_STACK_INDEX) continue; if (BIT_STATUS_AT(reg->bt_mem_start, mem)) pstart = STACK_AT(mem_start_stk[mem])->u.mem.pstr; else pstart = (UChar* )((void* )mem_start_stk[mem]); pend = (BIT_STATUS_AT(reg->bt_mem_end, mem) ? STACK_AT(mem_end_stk[mem])->u.mem.pstr : (UChar* )((void* )mem_end_stk[mem])); n = pend - pstart; DATA_ENSURE(n); sprev = s; swork = s; STRING_CMP_VALUE_IC(case_fold_flag, pstart, &swork, n, is_fail); if (is_fail) continue; s = swork; while (sprev + (len = enclen(encode, sprev)) < s) sprev += len; p += (SIZE_MEMNUM * (tlen - i - 1)); break; /* success */ } if (i == tlen) goto fail; MOP_OUT; continue; } break; #ifdef USE_BACKREF_WITH_LEVEL case OP_BACKREF_WITH_LEVEL: { int len; OnigOptionType ic; LengthType level; GET_OPTION_INC(ic, p); GET_LENGTH_INC(level, p); GET_LENGTH_INC(tlen, p); sprev = s; if (backref_match_at_nested_level(reg, stk, stk_base, ic , case_fold_flag, (int )level, (int )tlen, p, &s, end)) { while (sprev + (len = enclen(encode, sprev)) < s) sprev += len; p += (SIZE_MEMNUM * tlen); } else goto fail; MOP_OUT; continue; } break; #endif #if 0 /* no need: IS_DYNAMIC_OPTION() == 0 */ case OP_SET_OPTION_PUSH: MOP_IN(OP_SET_OPTION_PUSH); GET_OPTION_INC(option, p); STACK_PUSH_ALT(p, s, sprev); p += SIZE_OP_SET_OPTION + SIZE_OP_FAIL; MOP_OUT; continue; break; case OP_SET_OPTION: MOP_IN(OP_SET_OPTION); GET_OPTION_INC(option, p); MOP_OUT; continue; break; #endif case OP_NULL_CHECK_START: MOP_IN(OP_NULL_CHECK_START); GET_MEMNUM_INC(mem, p); /* mem: null check id */ STACK_PUSH_NULL_CHECK_START(mem, s); MOP_OUT; continue; break; case OP_NULL_CHECK_END: MOP_IN(OP_NULL_CHECK_END); { int isnull; GET_MEMNUM_INC(mem, p); /* mem: null check id */ STACK_NULL_CHECK(isnull, mem, s); if (isnull) { #ifdef ONIG_DEBUG_MATCH fprintf(stderr, ""NULL_CHECK_END: skip id:%d, s:%d\n"", (int )mem, (int )s); #endif null_check_found: /* empty loop founded, skip next instruction */ switch (*p++) { case OP_JUMP: case OP_PUSH: p += SIZE_RELADDR; break; case OP_REPEAT_INC: case OP_REPEAT_INC_NG: case OP_REPEAT_INC_SG: case OP_REPEAT_INC_NG_SG: p += SIZE_MEMNUM; break; default: goto unexpected_bytecode_error; break; } } } MOP_OUT; continue; break; #ifdef USE_MONOMANIAC_CHECK_CAPTURES_IN_ENDLESS_REPEAT case OP_NULL_CHECK_END_MEMST: MOP_IN(OP_NULL_CHECK_END_MEMST); { int isnull; GET_MEMNUM_INC(mem, p); /* mem: null check id */ STACK_NULL_CHECK_MEMST(isnull, mem, s, reg); if (isnull) { #ifdef ONIG_DEBUG_MATCH fprintf(stderr, ""NULL_CHECK_END_MEMST: skip id:%d, s:%d\n"", (int )mem, (int )s); #endif if (isnull == -1) goto fail; goto null_check_found; } } MOP_OUT; continue; break; #endif #ifdef USE_SUBEXP_CALL case OP_NULL_CHECK_END_MEMST_PUSH: MOP_IN(OP_NULL_CHECK_END_MEMST_PUSH); { int isnull; GET_MEMNUM_INC(mem, p); /* mem: null check id */ #ifdef USE_MONOMANIAC_CHECK_CAPTURES_IN_ENDLESS_REPEAT STACK_NULL_CHECK_MEMST_REC(isnull, mem, s, reg); #else STACK_NULL_CHECK_REC(isnull, mem, s); #endif if (isnull) { #ifdef ONIG_DEBUG_MATCH fprintf(stderr, ""NULL_CHECK_END_MEMST_PUSH: skip id:%d, s:%d\n"", (int )mem, (int )s); #endif if (isnull == -1) goto fail; goto null_check_found; } else { STACK_PUSH_NULL_CHECK_END(mem); } } MOP_OUT; continue; break; #endif case OP_JUMP: MOP_IN(OP_JUMP); GET_RELADDR_INC(addr, p); p += addr; MOP_OUT; CHECK_INTERRUPT_IN_MATCH_AT; continue; break; case OP_PUSH: MOP_IN(OP_PUSH); GET_RELADDR_INC(addr, p); STACK_PUSH_ALT(p + addr, s, sprev); MOP_OUT; continue; break; #ifdef USE_COMBINATION_EXPLOSION_CHECK case OP_STATE_CHECK_PUSH: MOP_IN(OP_STATE_CHECK_PUSH); GET_STATE_CHECK_NUM_INC(mem, p); STATE_CHECK_VAL(scv, mem); if (scv) goto fail; GET_RELADDR_INC(addr, p); STACK_PUSH_ALT_WITH_STATE_CHECK(p + addr, s, sprev, mem); MOP_OUT; continue; break; case OP_STATE_CHECK_PUSH_OR_JUMP: MOP_IN(OP_STATE_CHECK_PUSH_OR_JUMP); GET_STATE_CHECK_NUM_INC(mem, p); GET_RELADDR_INC(addr, p); STATE_CHECK_VAL(scv, mem); if (scv) { p += addr; } else { STACK_PUSH_ALT_WITH_STATE_CHECK(p + addr, s, sprev, mem); } MOP_OUT; continue; break; case OP_STATE_CHECK: MOP_IN(OP_STATE_CHECK); GET_STATE_CHECK_NUM_INC(mem, p); STATE_CHECK_VAL(scv, mem); if (scv) goto fail; STACK_PUSH_STATE_CHECK(s, mem); MOP_OUT; continue; break; #endif /* USE_COMBINATION_EXPLOSION_CHECK */ case OP_POP: MOP_IN(OP_POP); STACK_POP_ONE; MOP_OUT; continue; break; case OP_PUSH_OR_JUMP_EXACT1: MOP_IN(OP_PUSH_OR_JUMP_EXACT1); GET_RELADDR_INC(addr, p); if (*p == *s && DATA_ENSURE_CHECK1) { p++; STACK_PUSH_ALT(p + addr, s, sprev); MOP_OUT; continue; } p += (addr + 1); MOP_OUT; continue; break; case OP_PUSH_IF_PEEK_NEXT: MOP_IN(OP_PUSH_IF_PEEK_NEXT); GET_RELADDR_INC(addr, p); if (*p == *s) { p++; STACK_PUSH_ALT(p + addr, s, sprev); MOP_OUT; continue; } p++; MOP_OUT; continue; break; case OP_REPEAT: MOP_IN(OP_REPEAT); { GET_MEMNUM_INC(mem, p); /* mem: OP_REPEAT ID */ GET_RELADDR_INC(addr, p); STACK_ENSURE(1); repeat_stk[mem] = GET_STACK_INDEX(stk); STACK_PUSH_REPEAT(mem, p); if (reg->repeat_range[mem].lower == 0) { STACK_PUSH_ALT(p + addr, s, sprev); } } MOP_OUT; continue; break; case OP_REPEAT_NG: MOP_IN(OP_REPEAT_NG); { GET_MEMNUM_INC(mem, p); /* mem: OP_REPEAT ID */ GET_RELADDR_INC(addr, p); STACK_ENSURE(1); repeat_stk[mem] = GET_STACK_INDEX(stk); STACK_PUSH_REPEAT(mem, p); if (reg->repeat_range[mem].lower == 0) { STACK_PUSH_ALT(p, s, sprev); p += addr; } } MOP_OUT; continue; break; case OP_REPEAT_INC: MOP_IN(OP_REPEAT_INC); GET_MEMNUM_INC(mem, p); /* mem: OP_REPEAT ID */ si = repeat_stk[mem]; stkp = STACK_AT(si); repeat_inc: stkp->u.repeat.count++; if (stkp->u.repeat.count >= reg->repeat_range[mem].upper) { /* end of repeat. Nothing to do. */ } else if (stkp->u.repeat.count >= reg->repeat_range[mem].lower) { STACK_PUSH_ALT(p, s, sprev); p = STACK_AT(si)->u.repeat.pcode; /* Don't use stkp after PUSH. */ } else { p = stkp->u.repeat.pcode; } STACK_PUSH_REPEAT_INC(si); MOP_OUT; CHECK_INTERRUPT_IN_MATCH_AT; continue; break; case OP_REPEAT_INC_SG: MOP_IN(OP_REPEAT_INC_SG); GET_MEMNUM_INC(mem, p); /* mem: OP_REPEAT ID */ STACK_GET_REPEAT(mem, stkp); si = GET_STACK_INDEX(stkp); goto repeat_inc; break; case OP_REPEAT_INC_NG: MOP_IN(OP_REPEAT_INC_NG); GET_MEMNUM_INC(mem, p); /* mem: OP_REPEAT ID */ si = repeat_stk[mem]; stkp = STACK_AT(si); repeat_inc_ng: stkp->u.repeat.count++; if (stkp->u.repeat.count < reg->repeat_range[mem].upper) { if (stkp->u.repeat.count >= reg->repeat_range[mem].lower) { UChar* pcode = stkp->u.repeat.pcode; STACK_PUSH_REPEAT_INC(si); STACK_PUSH_ALT(pcode, s, sprev); } else { p = stkp->u.repeat.pcode; STACK_PUSH_REPEAT_INC(si); } } else if (stkp->u.repeat.count == reg->repeat_range[mem].upper) { STACK_PUSH_REPEAT_INC(si); } MOP_OUT; CHECK_INTERRUPT_IN_MATCH_AT; continue; break; case OP_REPEAT_INC_NG_SG: MOP_IN(OP_REPEAT_INC_NG_SG); GET_MEMNUM_INC(mem, p); /* mem: OP_REPEAT ID */ STACK_GET_REPEAT(mem, stkp); si = GET_STACK_INDEX(stkp); goto repeat_inc_ng; break; case OP_PUSH_POS: MOP_IN(OP_PUSH_POS); STACK_PUSH_POS(s, sprev); MOP_OUT; continue; break; case OP_POP_POS: MOP_IN(OP_POP_POS); { STACK_POS_END(stkp); s = stkp->u.state.pstr; sprev = stkp->u.state.pstr_prev; } MOP_OUT; continue; break; case OP_PUSH_POS_NOT: MOP_IN(OP_PUSH_POS_NOT); GET_RELADDR_INC(addr, p); STACK_PUSH_POS_NOT(p + addr, s, sprev); MOP_OUT; continue; break; case OP_FAIL_POS: MOP_IN(OP_FAIL_POS); STACK_POP_TIL_POS_NOT; goto fail; break; case OP_PUSH_STOP_BT: MOP_IN(OP_PUSH_STOP_BT); STACK_PUSH_STOP_BT; MOP_OUT; continue; break; case OP_POP_STOP_BT: MOP_IN(OP_POP_STOP_BT); STACK_STOP_BT_END; MOP_OUT; continue; break; case OP_LOOK_BEHIND: MOP_IN(OP_LOOK_BEHIND); GET_LENGTH_INC(tlen, p); s = (UChar* )ONIGENC_STEP_BACK(encode, str, s, (int )tlen); if (IS_NULL(s)) goto fail; sprev = (UChar* )onigenc_get_prev_char_head(encode, str, s); MOP_OUT; continue; break; case OP_PUSH_LOOK_BEHIND_NOT: MOP_IN(OP_PUSH_LOOK_BEHIND_NOT); GET_RELADDR_INC(addr, p); GET_LENGTH_INC(tlen, p); q = (UChar* )ONIGENC_STEP_BACK(encode, str, s, (int )tlen); if (IS_NULL(q)) { /* too short case -> success. ex. /(?p + addr; MOP_OUT; continue; break; case OP_RETURN: MOP_IN(OP_RETURN); STACK_RETURN(p); STACK_PUSH_RETURN; MOP_OUT; continue; break; #endif case OP_FINISH: goto finish; break; fail: MOP_OUT; /* fall */ case OP_FAIL: MOP_IN(OP_FAIL); STACK_POP; p = stk->u.state.pcode; s = stk->u.state.pstr; sprev = stk->u.state.pstr_prev; #ifdef USE_COMBINATION_EXPLOSION_CHECK if (stk->u.state.state_check != 0) { stk->type = STK_STATE_CHECK_MARK; stk++; } #endif MOP_OUT; continue; break; default: goto bytecode_error; } /* end of switch */ sprev = sbegin; } /* end of while(1) */ finish: STACK_SAVE; return best_len; #ifdef ONIG_DEBUG stack_error: STACK_SAVE; return ONIGERR_STACK_BUG; #endif bytecode_error: STACK_SAVE; return ONIGERR_UNDEFINED_BYTECODE; unexpected_bytecode_error: STACK_SAVE; return ONIGERR_UNEXPECTED_BYTECODE; }","match_at(regex_t* reg, const UChar* str, const UChar* end, #ifdef USE_MATCH_RANGE_MUST_BE_INSIDE_OF_SPECIFIED_RANGE const UChar* right_range, #endif const UChar* sstart, UChar* sprev, OnigMatchArg* msa) { static UChar FinishCode[] = { OP_FINISH }; int i, n, num_mem, best_len, pop_level; LengthType tlen, tlen2; MemNumType mem; RelAddrType addr; UChar *s, *q, *sbegin; int is_alloca; char *alloc_base; OnigStackType *stk_base, *stk, *stk_end; OnigStackType *stkp; /* used as any purpose. */ OnigStackIndex si; OnigStackIndex *repeat_stk; OnigStackIndex *mem_start_stk, *mem_end_stk; #ifdef USE_COMBINATION_EXPLOSION_CHECK int scv; unsigned char* state_check_buff = msa->state_check_buff; int num_comb_exp_check = reg->num_comb_exp_check; #endif UChar *p = reg->p; OnigOptionType option = reg->options; OnigEncoding encode = reg->enc; OnigCaseFoldType case_fold_flag = reg->case_fold_flag; //n = reg->num_repeat + reg->num_mem * 2; pop_level = reg->stack_pop_level; num_mem = reg->num_mem; STACK_INIT(INIT_MATCH_STACK_SIZE); UPDATE_FOR_STACK_REALLOC; for (i = 1; i <= num_mem; i++) { mem_start_stk[i] = mem_end_stk[i] = INVALID_STACK_INDEX; } #ifdef ONIG_DEBUG_MATCH fprintf(stderr, ""match_at: str: %d, end: %d, start: %d, sprev: %d\n"", (int )str, (int )end, (int )sstart, (int )sprev); fprintf(stderr, ""size: %d, start offset: %d\n"", (int )(end - str), (int )(sstart - str)); #endif STACK_PUSH_ENSURED(STK_ALT, FinishCode); /* bottom stack */ best_len = ONIG_MISMATCH; s = (UChar* )sstart; while (1) { #ifdef ONIG_DEBUG_MATCH { UChar *q, *bp, buf[50]; int len; fprintf(stderr, ""%4d> \"""", (int )(s - str)); bp = buf; for (i = 0, q = s; i < 7 && q < end; i++) { len = enclen(encode, q); while (len-- > 0) *bp++ = *q++; } if (q < end) { xmemcpy(bp, ""...\"""", 4); bp += 4; } else { xmemcpy(bp, ""\"""", 1); bp += 1; } *bp = 0; fputs((char* )buf, stderr); for (i = 0; i < 20 - (bp - buf); i++) fputc(' ', stderr); onig_print_compiled_byte_code(stderr, p, NULL, encode); fprintf(stderr, ""\n""); } #endif sbegin = s; switch (*p++) { case OP_END: MOP_IN(OP_END); n = s - sstart; if (n > best_len) { OnigRegion* region; #ifdef USE_FIND_LONGEST_SEARCH_ALL_OF_RANGE if (IS_FIND_LONGEST(option)) { if (n > msa->best_len) { msa->best_len = n; msa->best_s = (UChar* )sstart; } else goto end_best_len; } #endif best_len = n; region = msa->region; if (region) { #ifdef USE_POSIX_API_REGION_OPTION if (IS_POSIX_REGION(msa->options)) { posix_regmatch_t* rmt = (posix_regmatch_t* )region; rmt[0].rm_so = sstart - str; rmt[0].rm_eo = s - str; for (i = 1; i <= num_mem; i++) { if (mem_end_stk[i] != INVALID_STACK_INDEX) { if (BIT_STATUS_AT(reg->bt_mem_start, i)) rmt[i].rm_so = STACK_AT(mem_start_stk[i])->u.mem.pstr - str; else rmt[i].rm_so = (UChar* )((void* )(mem_start_stk[i])) - str; rmt[i].rm_eo = (BIT_STATUS_AT(reg->bt_mem_end, i) ? STACK_AT(mem_end_stk[i])->u.mem.pstr : (UChar* )((void* )mem_end_stk[i])) - str; } else { rmt[i].rm_so = rmt[i].rm_eo = ONIG_REGION_NOTPOS; } } } else { #endif /* USE_POSIX_API_REGION_OPTION */ region->beg[0] = sstart - str; region->end[0] = s - str; for (i = 1; i <= num_mem; i++) { if (mem_end_stk[i] != INVALID_STACK_INDEX) { if (BIT_STATUS_AT(reg->bt_mem_start, i)) region->beg[i] = STACK_AT(mem_start_stk[i])->u.mem.pstr - str; else region->beg[i] = (UChar* )((void* )mem_start_stk[i]) - str; region->end[i] = (BIT_STATUS_AT(reg->bt_mem_end, i) ? STACK_AT(mem_end_stk[i])->u.mem.pstr : (UChar* )((void* )mem_end_stk[i])) - str; } else { region->beg[i] = region->end[i] = ONIG_REGION_NOTPOS; } } #ifdef USE_CAPTURE_HISTORY if (reg->capture_history != 0) { int r; OnigCaptureTreeNode* node; if (IS_NULL(region->history_root)) { region->history_root = node = history_node_new(); CHECK_NULL_RETURN_MEMERR(node); } else { node = region->history_root; history_tree_clear(node); } node->group = 0; node->beg = sstart - str; node->end = s - str; stkp = stk_base; r = make_capture_history_tree(region->history_root, &stkp, stk, (UChar* )str, reg); if (r < 0) { best_len = r; /* error code */ goto finish; } } #endif /* USE_CAPTURE_HISTORY */ #ifdef USE_POSIX_API_REGION_OPTION } /* else IS_POSIX_REGION() */ #endif } /* if (region) */ } /* n > best_len */ #ifdef USE_FIND_LONGEST_SEARCH_ALL_OF_RANGE end_best_len: #endif MOP_OUT; if (IS_FIND_CONDITION(option)) { if (IS_FIND_NOT_EMPTY(option) && s == sstart) { best_len = ONIG_MISMATCH; goto fail; /* for retry */ } if (IS_FIND_LONGEST(option) && DATA_ENSURE_CHECK1) { goto fail; /* for retry */ } } /* default behavior: return first-matching result. */ goto finish; break; case OP_EXACT1: MOP_IN(OP_EXACT1); DATA_ENSURE(1); if (*p != *s) goto fail; p++; s++; MOP_OUT; break; case OP_EXACT1_IC: MOP_IN(OP_EXACT1_IC); { int len; UChar *q, lowbuf[ONIGENC_MBC_CASE_FOLD_MAXLEN]; DATA_ENSURE(1); len = ONIGENC_MBC_CASE_FOLD(encode, /* DISABLE_CASE_FOLD_MULTI_CHAR(case_fold_flag), */ case_fold_flag, &s, end, lowbuf); DATA_ENSURE(0); q = lowbuf; while (len-- > 0) { if (*p != *q) { goto fail; } p++; q++; } } MOP_OUT; break; case OP_EXACT2: MOP_IN(OP_EXACT2); DATA_ENSURE(2); if (*p != *s) goto fail; p++; s++; if (*p != *s) goto fail; sprev = s; p++; s++; MOP_OUT; continue; break; case OP_EXACT3: MOP_IN(OP_EXACT3); DATA_ENSURE(3); if (*p != *s) goto fail; p++; s++; if (*p != *s) goto fail; p++; s++; if (*p != *s) goto fail; sprev = s; p++; s++; MOP_OUT; continue; break; case OP_EXACT4: MOP_IN(OP_EXACT4); DATA_ENSURE(4); if (*p != *s) goto fail; p++; s++; if (*p != *s) goto fail; p++; s++; if (*p != *s) goto fail; p++; s++; if (*p != *s) goto fail; sprev = s; p++; s++; MOP_OUT; continue; break; case OP_EXACT5: MOP_IN(OP_EXACT5); DATA_ENSURE(5); if (*p != *s) goto fail; p++; s++; if (*p != *s) goto fail; p++; s++; if (*p != *s) goto fail; p++; s++; if (*p != *s) goto fail; p++; s++; if (*p != *s) goto fail; sprev = s; p++; s++; MOP_OUT; continue; break; case OP_EXACTN: MOP_IN(OP_EXACTN); GET_LENGTH_INC(tlen, p); DATA_ENSURE(tlen); while (tlen-- > 0) { if (*p++ != *s++) goto fail; } sprev = s - 1; MOP_OUT; continue; break; case OP_EXACTN_IC: MOP_IN(OP_EXACTN_IC); { int len; UChar *q, *endp, lowbuf[ONIGENC_MBC_CASE_FOLD_MAXLEN]; GET_LENGTH_INC(tlen, p); endp = p + tlen; while (p < endp) { sprev = s; DATA_ENSURE(1); len = ONIGENC_MBC_CASE_FOLD(encode, /* DISABLE_CASE_FOLD_MULTI_CHAR(case_fold_flag), */ case_fold_flag, &s, end, lowbuf); DATA_ENSURE(0); q = lowbuf; while (len-- > 0) { if (*p != *q) goto fail; p++; q++; } } } MOP_OUT; continue; break; case OP_EXACTMB2N1: MOP_IN(OP_EXACTMB2N1); DATA_ENSURE(2); if (*p != *s) goto fail; p++; s++; if (*p != *s) goto fail; p++; s++; MOP_OUT; break; case OP_EXACTMB2N2: MOP_IN(OP_EXACTMB2N2); DATA_ENSURE(4); if (*p != *s) goto fail; p++; s++; if (*p != *s) goto fail; p++; s++; sprev = s; if (*p != *s) goto fail; p++; s++; if (*p != *s) goto fail; p++; s++; MOP_OUT; continue; break; case OP_EXACTMB2N3: MOP_IN(OP_EXACTMB2N3); DATA_ENSURE(6); if (*p != *s) goto fail; p++; s++; if (*p != *s) goto fail; p++; s++; if (*p != *s) goto fail; p++; s++; if (*p != *s) goto fail; p++; s++; sprev = s; if (*p != *s) goto fail; p++; s++; if (*p != *s) goto fail; p++; s++; MOP_OUT; continue; break; case OP_EXACTMB2N: MOP_IN(OP_EXACTMB2N); GET_LENGTH_INC(tlen, p); DATA_ENSURE(tlen * 2); while (tlen-- > 0) { if (*p != *s) goto fail; p++; s++; if (*p != *s) goto fail; p++; s++; } sprev = s - 2; MOP_OUT; continue; break; case OP_EXACTMB3N: MOP_IN(OP_EXACTMB3N); GET_LENGTH_INC(tlen, p); DATA_ENSURE(tlen * 3); while (tlen-- > 0) { if (*p != *s) goto fail; p++; s++; if (*p != *s) goto fail; p++; s++; if (*p != *s) goto fail; p++; s++; } sprev = s - 3; MOP_OUT; continue; break; case OP_EXACTMBN: MOP_IN(OP_EXACTMBN); GET_LENGTH_INC(tlen, p); /* mb-len */ GET_LENGTH_INC(tlen2, p); /* string len */ tlen2 *= tlen; DATA_ENSURE(tlen2); while (tlen2-- > 0) { if (*p != *s) goto fail; p++; s++; } sprev = s - tlen; MOP_OUT; continue; break; case OP_CCLASS: MOP_IN(OP_CCLASS); DATA_ENSURE(1); if (BITSET_AT(((BitSetRef )p), *s) == 0) goto fail; p += SIZE_BITSET; s += enclen(encode, s); /* OP_CCLASS can match mb-code. \D, \S */ MOP_OUT; break; case OP_CCLASS_MB: MOP_IN(OP_CCLASS_MB); if (! ONIGENC_IS_MBC_HEAD(encode, s)) goto fail; cclass_mb: GET_LENGTH_INC(tlen, p); { OnigCodePoint code; UChar *ss; int mb_len; DATA_ENSURE(1); mb_len = enclen(encode, s); DATA_ENSURE(mb_len); ss = s; s += mb_len; code = ONIGENC_MBC_TO_CODE(encode, ss, s); #ifdef PLATFORM_UNALIGNED_WORD_ACCESS if (! onig_is_in_code_range(p, code)) goto fail; #else q = p; ALIGNMENT_RIGHT(q); if (! onig_is_in_code_range(q, code)) goto fail; #endif } p += tlen; MOP_OUT; break; case OP_CCLASS_MIX: MOP_IN(OP_CCLASS_MIX); DATA_ENSURE(1); if (ONIGENC_IS_MBC_HEAD(encode, s)) { p += SIZE_BITSET; goto cclass_mb; } else { if (BITSET_AT(((BitSetRef )p), *s) == 0) goto fail; p += SIZE_BITSET; GET_LENGTH_INC(tlen, p); p += tlen; s++; } MOP_OUT; break; case OP_CCLASS_NOT: MOP_IN(OP_CCLASS_NOT); DATA_ENSURE(1); if (BITSET_AT(((BitSetRef )p), *s) != 0) goto fail; p += SIZE_BITSET; s += enclen(encode, s); MOP_OUT; break; case OP_CCLASS_MB_NOT: MOP_IN(OP_CCLASS_MB_NOT); DATA_ENSURE(1); if (! ONIGENC_IS_MBC_HEAD(encode, s)) { s++; GET_LENGTH_INC(tlen, p); p += tlen; goto cc_mb_not_success; } cclass_mb_not: GET_LENGTH_INC(tlen, p); { OnigCodePoint code; UChar *ss; int mb_len = enclen(encode, s); if (! DATA_ENSURE_CHECK(mb_len)) { DATA_ENSURE(1); s = (UChar* )end; p += tlen; goto cc_mb_not_success; } ss = s; s += mb_len; code = ONIGENC_MBC_TO_CODE(encode, ss, s); #ifdef PLATFORM_UNALIGNED_WORD_ACCESS if (onig_is_in_code_range(p, code)) goto fail; #else q = p; ALIGNMENT_RIGHT(q); if (onig_is_in_code_range(q, code)) goto fail; #endif } p += tlen; cc_mb_not_success: MOP_OUT; break; case OP_CCLASS_MIX_NOT: MOP_IN(OP_CCLASS_MIX_NOT); DATA_ENSURE(1); if (ONIGENC_IS_MBC_HEAD(encode, s)) { p += SIZE_BITSET; goto cclass_mb_not; } else { if (BITSET_AT(((BitSetRef )p), *s) != 0) goto fail; p += SIZE_BITSET; GET_LENGTH_INC(tlen, p); p += tlen; s++; } MOP_OUT; break; case OP_CCLASS_NODE: MOP_IN(OP_CCLASS_NODE); { OnigCodePoint code; void *node; int mb_len; UChar *ss; DATA_ENSURE(1); GET_POINTER_INC(node, p); mb_len = enclen(encode, s); ss = s; s += mb_len; DATA_ENSURE(0); code = ONIGENC_MBC_TO_CODE(encode, ss, s); if (onig_is_code_in_cc_len(mb_len, code, node) == 0) goto fail; } MOP_OUT; break; case OP_ANYCHAR: MOP_IN(OP_ANYCHAR); DATA_ENSURE(1); n = enclen(encode, s); DATA_ENSURE(n); if (ONIGENC_IS_MBC_NEWLINE(encode, s, end)) goto fail; s += n; MOP_OUT; break; case OP_ANYCHAR_ML: MOP_IN(OP_ANYCHAR_ML); DATA_ENSURE(1); n = enclen(encode, s); DATA_ENSURE(n); s += n; MOP_OUT; break; case OP_ANYCHAR_STAR: MOP_IN(OP_ANYCHAR_STAR); while (DATA_ENSURE_CHECK1) { STACK_PUSH_ALT(p, s, sprev); n = enclen(encode, s); DATA_ENSURE(n); if (ONIGENC_IS_MBC_NEWLINE(encode, s, end)) goto fail; sprev = s; s += n; } MOP_OUT; break; case OP_ANYCHAR_ML_STAR: MOP_IN(OP_ANYCHAR_ML_STAR); while (DATA_ENSURE_CHECK1) { STACK_PUSH_ALT(p, s, sprev); n = enclen(encode, s); if (n > 1) { DATA_ENSURE(n); sprev = s; s += n; } else { sprev = s; s++; } } MOP_OUT; break; case OP_ANYCHAR_STAR_PEEK_NEXT: MOP_IN(OP_ANYCHAR_STAR_PEEK_NEXT); while (DATA_ENSURE_CHECK1) { if (*p == *s) { STACK_PUSH_ALT(p + 1, s, sprev); } n = enclen(encode, s); DATA_ENSURE(n); if (ONIGENC_IS_MBC_NEWLINE(encode, s, end)) goto fail; sprev = s; s += n; } p++; MOP_OUT; break; case OP_ANYCHAR_ML_STAR_PEEK_NEXT:MOP_IN(OP_ANYCHAR_ML_STAR_PEEK_NEXT); while (DATA_ENSURE_CHECK1) { if (*p == *s) { STACK_PUSH_ALT(p + 1, s, sprev); } n = enclen(encode, s); if (n > 1) { DATA_ENSURE(n); sprev = s; s += n; } else { sprev = s; s++; } } p++; MOP_OUT; break; #ifdef USE_COMBINATION_EXPLOSION_CHECK case OP_STATE_CHECK_ANYCHAR_STAR: MOP_IN(OP_STATE_CHECK_ANYCHAR_STAR); GET_STATE_CHECK_NUM_INC(mem, p); while (DATA_ENSURE_CHECK1) { STATE_CHECK_VAL(scv, mem); if (scv) goto fail; STACK_PUSH_ALT_WITH_STATE_CHECK(p, s, sprev, mem); n = enclen(encode, s); DATA_ENSURE(n); if (ONIGENC_IS_MBC_NEWLINE(encode, s, end)) goto fail; sprev = s; s += n; } MOP_OUT; break; case OP_STATE_CHECK_ANYCHAR_ML_STAR: MOP_IN(OP_STATE_CHECK_ANYCHAR_ML_STAR); GET_STATE_CHECK_NUM_INC(mem, p); while (DATA_ENSURE_CHECK1) { STATE_CHECK_VAL(scv, mem); if (scv) goto fail; STACK_PUSH_ALT_WITH_STATE_CHECK(p, s, sprev, mem); n = enclen(encode, s); if (n > 1) { DATA_ENSURE(n); sprev = s; s += n; } else { sprev = s; s++; } } MOP_OUT; break; #endif /* USE_COMBINATION_EXPLOSION_CHECK */ case OP_WORD: MOP_IN(OP_WORD); DATA_ENSURE(1); if (! ONIGENC_IS_MBC_WORD(encode, s, end)) goto fail; s += enclen(encode, s); MOP_OUT; break; case OP_NOT_WORD: MOP_IN(OP_NOT_WORD); DATA_ENSURE(1); if (ONIGENC_IS_MBC_WORD(encode, s, end)) goto fail; s += enclen(encode, s); MOP_OUT; break; case OP_WORD_BOUND: MOP_IN(OP_WORD_BOUND); if (ON_STR_BEGIN(s)) { DATA_ENSURE(1); if (! ONIGENC_IS_MBC_WORD(encode, s, end)) goto fail; } else if (ON_STR_END(s)) { if (! ONIGENC_IS_MBC_WORD(encode, sprev, end)) goto fail; } else { if (ONIGENC_IS_MBC_WORD(encode, s, end) == ONIGENC_IS_MBC_WORD(encode, sprev, end)) goto fail; } MOP_OUT; continue; break; case OP_NOT_WORD_BOUND: MOP_IN(OP_NOT_WORD_BOUND); if (ON_STR_BEGIN(s)) { if (DATA_ENSURE_CHECK1 && ONIGENC_IS_MBC_WORD(encode, s, end)) goto fail; } else if (ON_STR_END(s)) { if (ONIGENC_IS_MBC_WORD(encode, sprev, end)) goto fail; } else { if (ONIGENC_IS_MBC_WORD(encode, s, end) != ONIGENC_IS_MBC_WORD(encode, sprev, end)) goto fail; } MOP_OUT; continue; break; #ifdef USE_WORD_BEGIN_END case OP_WORD_BEGIN: MOP_IN(OP_WORD_BEGIN); if (DATA_ENSURE_CHECK1 && ONIGENC_IS_MBC_WORD(encode, s, end)) { if (ON_STR_BEGIN(s) || !ONIGENC_IS_MBC_WORD(encode, sprev, end)) { MOP_OUT; continue; } } goto fail; break; case OP_WORD_END: MOP_IN(OP_WORD_END); if (!ON_STR_BEGIN(s) && ONIGENC_IS_MBC_WORD(encode, sprev, end)) { if (ON_STR_END(s) || !ONIGENC_IS_MBC_WORD(encode, s, end)) { MOP_OUT; continue; } } goto fail; break; #endif case OP_BEGIN_BUF: MOP_IN(OP_BEGIN_BUF); if (! ON_STR_BEGIN(s)) goto fail; MOP_OUT; continue; break; case OP_END_BUF: MOP_IN(OP_END_BUF); if (! ON_STR_END(s)) goto fail; MOP_OUT; continue; break; case OP_BEGIN_LINE: MOP_IN(OP_BEGIN_LINE); if (ON_STR_BEGIN(s)) { if (IS_NOTBOL(msa->options)) goto fail; MOP_OUT; continue; } else if (ONIGENC_IS_MBC_NEWLINE(encode, sprev, end) && !ON_STR_END(s)) { MOP_OUT; continue; } goto fail; break; case OP_END_LINE: MOP_IN(OP_END_LINE); if (ON_STR_END(s)) { #ifndef USE_NEWLINE_AT_END_OF_STRING_HAS_EMPTY_LINE if (IS_EMPTY_STR || !ONIGENC_IS_MBC_NEWLINE(encode, sprev, end)) { #endif if (IS_NOTEOL(msa->options)) goto fail; MOP_OUT; continue; #ifndef USE_NEWLINE_AT_END_OF_STRING_HAS_EMPTY_LINE } #endif } else if (ONIGENC_IS_MBC_NEWLINE(encode, s, end)) { MOP_OUT; continue; } #ifdef USE_CRNL_AS_LINE_TERMINATOR else if (ONIGENC_IS_MBC_CRNL(encode, s, end)) { MOP_OUT; continue; } #endif goto fail; break; case OP_SEMI_END_BUF: MOP_IN(OP_SEMI_END_BUF); if (ON_STR_END(s)) { #ifndef USE_NEWLINE_AT_END_OF_STRING_HAS_EMPTY_LINE if (IS_EMPTY_STR || !ONIGENC_IS_MBC_NEWLINE(encode, sprev, end)) { #endif if (IS_NOTEOL(msa->options)) goto fail; MOP_OUT; continue; #ifndef USE_NEWLINE_AT_END_OF_STRING_HAS_EMPTY_LINE } #endif } else if (ONIGENC_IS_MBC_NEWLINE(encode, s, end) && ON_STR_END(s + enclen(encode, s))) { MOP_OUT; continue; } #ifdef USE_CRNL_AS_LINE_TERMINATOR else if (ONIGENC_IS_MBC_CRNL(encode, s, end)) { UChar* ss = s + enclen(encode, s); ss += enclen(encode, ss); if (ON_STR_END(ss)) { MOP_OUT; continue; } } #endif goto fail; break; case OP_BEGIN_POSITION: MOP_IN(OP_BEGIN_POSITION); if (s != msa->start) goto fail; MOP_OUT; continue; break; case OP_MEMORY_START_PUSH: MOP_IN(OP_MEMORY_START_PUSH); GET_MEMNUM_INC(mem, p); STACK_PUSH_MEM_START(mem, s); MOP_OUT; continue; break; case OP_MEMORY_START: MOP_IN(OP_MEMORY_START); GET_MEMNUM_INC(mem, p); mem_start_stk[mem] = (OnigStackIndex )((void* )s); MOP_OUT; continue; break; case OP_MEMORY_END_PUSH: MOP_IN(OP_MEMORY_END_PUSH); GET_MEMNUM_INC(mem, p); STACK_PUSH_MEM_END(mem, s); MOP_OUT; continue; break; case OP_MEMORY_END: MOP_IN(OP_MEMORY_END); GET_MEMNUM_INC(mem, p); mem_end_stk[mem] = (OnigStackIndex )((void* )s); MOP_OUT; continue; break; #ifdef USE_SUBEXP_CALL case OP_MEMORY_END_PUSH_REC: MOP_IN(OP_MEMORY_END_PUSH_REC); GET_MEMNUM_INC(mem, p); STACK_GET_MEM_START(mem, stkp); /* should be before push mem-end. */ STACK_PUSH_MEM_END(mem, s); mem_start_stk[mem] = GET_STACK_INDEX(stkp); MOP_OUT; continue; break; case OP_MEMORY_END_REC: MOP_IN(OP_MEMORY_END_REC); GET_MEMNUM_INC(mem, p); mem_end_stk[mem] = (OnigStackIndex )((void* )s); STACK_GET_MEM_START(mem, stkp); if (BIT_STATUS_AT(reg->bt_mem_start, mem)) mem_start_stk[mem] = GET_STACK_INDEX(stkp); else mem_start_stk[mem] = (OnigStackIndex )((void* )stkp->u.mem.pstr); STACK_PUSH_MEM_END_MARK(mem); MOP_OUT; continue; break; #endif case OP_BACKREF1: MOP_IN(OP_BACKREF1); mem = 1; goto backref; break; case OP_BACKREF2: MOP_IN(OP_BACKREF2); mem = 2; goto backref; break; case OP_BACKREFN: MOP_IN(OP_BACKREFN); GET_MEMNUM_INC(mem, p); backref: { int len; UChar *pstart, *pend; /* if you want to remove following line, you should check in parse and compile time. */ if (mem > num_mem) goto fail; if (mem_end_stk[mem] == INVALID_STACK_INDEX) goto fail; if (mem_start_stk[mem] == INVALID_STACK_INDEX) goto fail; if (BIT_STATUS_AT(reg->bt_mem_start, mem)) pstart = STACK_AT(mem_start_stk[mem])->u.mem.pstr; else pstart = (UChar* )((void* )mem_start_stk[mem]); pend = (BIT_STATUS_AT(reg->bt_mem_end, mem) ? STACK_AT(mem_end_stk[mem])->u.mem.pstr : (UChar* )((void* )mem_end_stk[mem])); n = pend - pstart; DATA_ENSURE(n); sprev = s; STRING_CMP(pstart, s, n); while (sprev + (len = enclen(encode, sprev)) < s) sprev += len; MOP_OUT; continue; } break; case OP_BACKREFN_IC: MOP_IN(OP_BACKREFN_IC); GET_MEMNUM_INC(mem, p); { int len; UChar *pstart, *pend; /* if you want to remove following line, you should check in parse and compile time. */ if (mem > num_mem) goto fail; if (mem_end_stk[mem] == INVALID_STACK_INDEX) goto fail; if (mem_start_stk[mem] == INVALID_STACK_INDEX) goto fail; if (BIT_STATUS_AT(reg->bt_mem_start, mem)) pstart = STACK_AT(mem_start_stk[mem])->u.mem.pstr; else pstart = (UChar* )((void* )mem_start_stk[mem]); pend = (BIT_STATUS_AT(reg->bt_mem_end, mem) ? STACK_AT(mem_end_stk[mem])->u.mem.pstr : (UChar* )((void* )mem_end_stk[mem])); n = pend - pstart; DATA_ENSURE(n); sprev = s; STRING_CMP_IC(case_fold_flag, pstart, &s, n); while (sprev + (len = enclen(encode, sprev)) < s) sprev += len; MOP_OUT; continue; } break; case OP_BACKREF_MULTI: MOP_IN(OP_BACKREF_MULTI); { int len, is_fail; UChar *pstart, *pend, *swork; GET_LENGTH_INC(tlen, p); for (i = 0; i < tlen; i++) { GET_MEMNUM_INC(mem, p); if (mem_end_stk[mem] == INVALID_STACK_INDEX) continue; if (mem_start_stk[mem] == INVALID_STACK_INDEX) continue; if (BIT_STATUS_AT(reg->bt_mem_start, mem)) pstart = STACK_AT(mem_start_stk[mem])->u.mem.pstr; else pstart = (UChar* )((void* )mem_start_stk[mem]); pend = (BIT_STATUS_AT(reg->bt_mem_end, mem) ? STACK_AT(mem_end_stk[mem])->u.mem.pstr : (UChar* )((void* )mem_end_stk[mem])); n = pend - pstart; DATA_ENSURE(n); sprev = s; swork = s; STRING_CMP_VALUE(pstart, swork, n, is_fail); if (is_fail) continue; s = swork; while (sprev + (len = enclen(encode, sprev)) < s) sprev += len; p += (SIZE_MEMNUM * (tlen - i - 1)); break; /* success */ } if (i == tlen) goto fail; MOP_OUT; continue; } break; case OP_BACKREF_MULTI_IC: MOP_IN(OP_BACKREF_MULTI_IC); { int len, is_fail; UChar *pstart, *pend, *swork; GET_LENGTH_INC(tlen, p); for (i = 0; i < tlen; i++) { GET_MEMNUM_INC(mem, p); if (mem_end_stk[mem] == INVALID_STACK_INDEX) continue; if (mem_start_stk[mem] == INVALID_STACK_INDEX) continue; if (BIT_STATUS_AT(reg->bt_mem_start, mem)) pstart = STACK_AT(mem_start_stk[mem])->u.mem.pstr; else pstart = (UChar* )((void* )mem_start_stk[mem]); pend = (BIT_STATUS_AT(reg->bt_mem_end, mem) ? STACK_AT(mem_end_stk[mem])->u.mem.pstr : (UChar* )((void* )mem_end_stk[mem])); n = pend - pstart; DATA_ENSURE(n); sprev = s; swork = s; STRING_CMP_VALUE_IC(case_fold_flag, pstart, &swork, n, is_fail); if (is_fail) continue; s = swork; while (sprev + (len = enclen(encode, sprev)) < s) sprev += len; p += (SIZE_MEMNUM * (tlen - i - 1)); break; /* success */ } if (i == tlen) goto fail; MOP_OUT; continue; } break; #ifdef USE_BACKREF_WITH_LEVEL case OP_BACKREF_WITH_LEVEL: { int len; OnigOptionType ic; LengthType level; GET_OPTION_INC(ic, p); GET_LENGTH_INC(level, p); GET_LENGTH_INC(tlen, p); sprev = s; if (backref_match_at_nested_level(reg, stk, stk_base, ic , case_fold_flag, (int )level, (int )tlen, p, &s, end)) { while (sprev + (len = enclen(encode, sprev)) < s) sprev += len; p += (SIZE_MEMNUM * tlen); } else goto fail; MOP_OUT; continue; } break; #endif #if 0 /* no need: IS_DYNAMIC_OPTION() == 0 */ case OP_SET_OPTION_PUSH: MOP_IN(OP_SET_OPTION_PUSH); GET_OPTION_INC(option, p); STACK_PUSH_ALT(p, s, sprev); p += SIZE_OP_SET_OPTION + SIZE_OP_FAIL; MOP_OUT; continue; break; case OP_SET_OPTION: MOP_IN(OP_SET_OPTION); GET_OPTION_INC(option, p); MOP_OUT; continue; break; #endif case OP_NULL_CHECK_START: MOP_IN(OP_NULL_CHECK_START); GET_MEMNUM_INC(mem, p); /* mem: null check id */ STACK_PUSH_NULL_CHECK_START(mem, s); MOP_OUT; continue; break; case OP_NULL_CHECK_END: MOP_IN(OP_NULL_CHECK_END); { int isnull; GET_MEMNUM_INC(mem, p); /* mem: null check id */ STACK_NULL_CHECK(isnull, mem, s); if (isnull) { #ifdef ONIG_DEBUG_MATCH fprintf(stderr, ""NULL_CHECK_END: skip id:%d, s:%d\n"", (int )mem, (int )s); #endif null_check_found: /* empty loop founded, skip next instruction */ switch (*p++) { case OP_JUMP: case OP_PUSH: p += SIZE_RELADDR; break; case OP_REPEAT_INC: case OP_REPEAT_INC_NG: case OP_REPEAT_INC_SG: case OP_REPEAT_INC_NG_SG: p += SIZE_MEMNUM; break; default: goto unexpected_bytecode_error; break; } } } MOP_OUT; continue; break; #ifdef USE_MONOMANIAC_CHECK_CAPTURES_IN_ENDLESS_REPEAT case OP_NULL_CHECK_END_MEMST: MOP_IN(OP_NULL_CHECK_END_MEMST); { int isnull; GET_MEMNUM_INC(mem, p); /* mem: null check id */ STACK_NULL_CHECK_MEMST(isnull, mem, s, reg); if (isnull) { #ifdef ONIG_DEBUG_MATCH fprintf(stderr, ""NULL_CHECK_END_MEMST: skip id:%d, s:%d\n"", (int )mem, (int )s); #endif if (isnull == -1) goto fail; goto null_check_found; } } MOP_OUT; continue; break; #endif #ifdef USE_SUBEXP_CALL case OP_NULL_CHECK_END_MEMST_PUSH: MOP_IN(OP_NULL_CHECK_END_MEMST_PUSH); { int isnull; GET_MEMNUM_INC(mem, p); /* mem: null check id */ #ifdef USE_MONOMANIAC_CHECK_CAPTURES_IN_ENDLESS_REPEAT STACK_NULL_CHECK_MEMST_REC(isnull, mem, s, reg); #else STACK_NULL_CHECK_REC(isnull, mem, s); #endif if (isnull) { #ifdef ONIG_DEBUG_MATCH fprintf(stderr, ""NULL_CHECK_END_MEMST_PUSH: skip id:%d, s:%d\n"", (int )mem, (int )s); #endif if (isnull == -1) goto fail; goto null_check_found; } else { STACK_PUSH_NULL_CHECK_END(mem); } } MOP_OUT; continue; break; #endif case OP_JUMP: MOP_IN(OP_JUMP); GET_RELADDR_INC(addr, p); p += addr; MOP_OUT; CHECK_INTERRUPT_IN_MATCH_AT; continue; break; case OP_PUSH: MOP_IN(OP_PUSH); GET_RELADDR_INC(addr, p); STACK_PUSH_ALT(p + addr, s, sprev); MOP_OUT; continue; break; #ifdef USE_COMBINATION_EXPLOSION_CHECK case OP_STATE_CHECK_PUSH: MOP_IN(OP_STATE_CHECK_PUSH); GET_STATE_CHECK_NUM_INC(mem, p); STATE_CHECK_VAL(scv, mem); if (scv) goto fail; GET_RELADDR_INC(addr, p); STACK_PUSH_ALT_WITH_STATE_CHECK(p + addr, s, sprev, mem); MOP_OUT; continue; break; case OP_STATE_CHECK_PUSH_OR_JUMP: MOP_IN(OP_STATE_CHECK_PUSH_OR_JUMP); GET_STATE_CHECK_NUM_INC(mem, p); GET_RELADDR_INC(addr, p); STATE_CHECK_VAL(scv, mem); if (scv) { p += addr; } else { STACK_PUSH_ALT_WITH_STATE_CHECK(p + addr, s, sprev, mem); } MOP_OUT; continue; break; case OP_STATE_CHECK: MOP_IN(OP_STATE_CHECK); GET_STATE_CHECK_NUM_INC(mem, p); STATE_CHECK_VAL(scv, mem); if (scv) goto fail; STACK_PUSH_STATE_CHECK(s, mem); MOP_OUT; continue; break; #endif /* USE_COMBINATION_EXPLOSION_CHECK */ case OP_POP: MOP_IN(OP_POP); STACK_POP_ONE; MOP_OUT; continue; break; case OP_PUSH_OR_JUMP_EXACT1: MOP_IN(OP_PUSH_OR_JUMP_EXACT1); GET_RELADDR_INC(addr, p); if (*p == *s && DATA_ENSURE_CHECK1) { p++; STACK_PUSH_ALT(p + addr, s, sprev); MOP_OUT; continue; } p += (addr + 1); MOP_OUT; continue; break; case OP_PUSH_IF_PEEK_NEXT: MOP_IN(OP_PUSH_IF_PEEK_NEXT); GET_RELADDR_INC(addr, p); if (*p == *s) { p++; STACK_PUSH_ALT(p + addr, s, sprev); MOP_OUT; continue; } p++; MOP_OUT; continue; break; case OP_REPEAT: MOP_IN(OP_REPEAT); { GET_MEMNUM_INC(mem, p); /* mem: OP_REPEAT ID */ GET_RELADDR_INC(addr, p); STACK_ENSURE(1); repeat_stk[mem] = GET_STACK_INDEX(stk); STACK_PUSH_REPEAT(mem, p); if (reg->repeat_range[mem].lower == 0) { STACK_PUSH_ALT(p + addr, s, sprev); } } MOP_OUT; continue; break; case OP_REPEAT_NG: MOP_IN(OP_REPEAT_NG); { GET_MEMNUM_INC(mem, p); /* mem: OP_REPEAT ID */ GET_RELADDR_INC(addr, p); STACK_ENSURE(1); repeat_stk[mem] = GET_STACK_INDEX(stk); STACK_PUSH_REPEAT(mem, p); if (reg->repeat_range[mem].lower == 0) { STACK_PUSH_ALT(p, s, sprev); p += addr; } } MOP_OUT; continue; break; case OP_REPEAT_INC: MOP_IN(OP_REPEAT_INC); GET_MEMNUM_INC(mem, p); /* mem: OP_REPEAT ID */ si = repeat_stk[mem]; stkp = STACK_AT(si); repeat_inc: stkp->u.repeat.count++; if (stkp->u.repeat.count >= reg->repeat_range[mem].upper) { /* end of repeat. Nothing to do. */ } else if (stkp->u.repeat.count >= reg->repeat_range[mem].lower) { STACK_PUSH_ALT(p, s, sprev); p = STACK_AT(si)->u.repeat.pcode; /* Don't use stkp after PUSH. */ } else { p = stkp->u.repeat.pcode; } STACK_PUSH_REPEAT_INC(si); MOP_OUT; CHECK_INTERRUPT_IN_MATCH_AT; continue; break; case OP_REPEAT_INC_SG: MOP_IN(OP_REPEAT_INC_SG); GET_MEMNUM_INC(mem, p); /* mem: OP_REPEAT ID */ STACK_GET_REPEAT(mem, stkp); si = GET_STACK_INDEX(stkp); goto repeat_inc; break; case OP_REPEAT_INC_NG: MOP_IN(OP_REPEAT_INC_NG); GET_MEMNUM_INC(mem, p); /* mem: OP_REPEAT ID */ si = repeat_stk[mem]; stkp = STACK_AT(si); repeat_inc_ng: stkp->u.repeat.count++; if (stkp->u.repeat.count < reg->repeat_range[mem].upper) { if (stkp->u.repeat.count >= reg->repeat_range[mem].lower) { UChar* pcode = stkp->u.repeat.pcode; STACK_PUSH_REPEAT_INC(si); STACK_PUSH_ALT(pcode, s, sprev); } else { p = stkp->u.repeat.pcode; STACK_PUSH_REPEAT_INC(si); } } else if (stkp->u.repeat.count == reg->repeat_range[mem].upper) { STACK_PUSH_REPEAT_INC(si); } MOP_OUT; CHECK_INTERRUPT_IN_MATCH_AT; continue; break; case OP_REPEAT_INC_NG_SG: MOP_IN(OP_REPEAT_INC_NG_SG); GET_MEMNUM_INC(mem, p); /* mem: OP_REPEAT ID */ STACK_GET_REPEAT(mem, stkp); si = GET_STACK_INDEX(stkp); goto repeat_inc_ng; break; case OP_PUSH_POS: MOP_IN(OP_PUSH_POS); STACK_PUSH_POS(s, sprev); MOP_OUT; continue; break; case OP_POP_POS: MOP_IN(OP_POP_POS); { STACK_POS_END(stkp); s = stkp->u.state.pstr; sprev = stkp->u.state.pstr_prev; } MOP_OUT; continue; break; case OP_PUSH_POS_NOT: MOP_IN(OP_PUSH_POS_NOT); GET_RELADDR_INC(addr, p); STACK_PUSH_POS_NOT(p + addr, s, sprev); MOP_OUT; continue; break; case OP_FAIL_POS: MOP_IN(OP_FAIL_POS); STACK_POP_TIL_POS_NOT; goto fail; break; case OP_PUSH_STOP_BT: MOP_IN(OP_PUSH_STOP_BT); STACK_PUSH_STOP_BT; MOP_OUT; continue; break; case OP_POP_STOP_BT: MOP_IN(OP_POP_STOP_BT); STACK_STOP_BT_END; MOP_OUT; continue; break; case OP_LOOK_BEHIND: MOP_IN(OP_LOOK_BEHIND); GET_LENGTH_INC(tlen, p); s = (UChar* )ONIGENC_STEP_BACK(encode, str, s, (int )tlen); if (IS_NULL(s)) goto fail; sprev = (UChar* )onigenc_get_prev_char_head(encode, str, s); MOP_OUT; continue; break; case OP_PUSH_LOOK_BEHIND_NOT: MOP_IN(OP_PUSH_LOOK_BEHIND_NOT); GET_RELADDR_INC(addr, p); GET_LENGTH_INC(tlen, p); q = (UChar* )ONIGENC_STEP_BACK(encode, str, s, (int )tlen); if (IS_NULL(q)) { /* too short case -> success. ex. /(?p + addr; MOP_OUT; continue; break; case OP_RETURN: MOP_IN(OP_RETURN); STACK_RETURN(p); STACK_PUSH_RETURN; MOP_OUT; continue; break; #endif case OP_FINISH: goto finish; break; fail: MOP_OUT; /* fall */ case OP_FAIL: MOP_IN(OP_FAIL); STACK_POP; p = stk->u.state.pcode; s = stk->u.state.pstr; sprev = stk->u.state.pstr_prev; #ifdef USE_COMBINATION_EXPLOSION_CHECK if (stk->u.state.state_check != 0) { stk->type = STK_STATE_CHECK_MARK; stk++; } #endif MOP_OUT; continue; break; default: goto bytecode_error; } /* end of switch */ sprev = sbegin; } /* end of while(1) */ finish: STACK_SAVE; return best_len; #ifdef ONIG_DEBUG stack_error: STACK_SAVE; return ONIGERR_STACK_BUG; #endif bytecode_error: STACK_SAVE; return ONIGERR_UNDEFINED_BYTECODE; unexpected_bytecode_error: STACK_SAVE; return ONIGERR_UNEXPECTED_BYTECODE; }","{'deleted': [{'line_no': 190, 'char_start': 6067, 'char_end': 6100, 'line': ' if (*p != *s++) goto fail;\n'}, {'line_no': 191, 'char_start': 6100, 'char_end': 6122, 'line': ' DATA_ENSURE(0);\n'}, {'line_no': 192, 'char_start': 6122, 'char_end': 6133, 'line': ' p++;\n'}], 'added': []}","{'deleted': [{'char_start': 5985, 'char_end': 5991, 'chars': '#if 0\n'}, {'char_start': 6056, 'char_end': 6129, 'chars': '++;\n#endif\n if (*p != *s++) goto fail;\n DATA_ENSURE(0);\n p'}], 'added': []}",github.com/kkos/oniguruma/commit/690313a061f7a4fa614ec5cc8368b4f2284e059b,src/regexec.c,cwe-125,11033 cwe-125,TNEFParse,"int TNEFParse(TNEFStruct *TNEF) { WORD key; DWORD type; DWORD size; DWORD signature; BYTE *data; WORD checksum, header_checksum; int i; if (TNEF->IO.ReadProc == NULL) { printf(""ERROR: Setup incorrectly: No ReadProc\n""); return YTNEF_INCORRECT_SETUP; } if (TNEF->IO.InitProc != NULL) { DEBUG(TNEF->Debug, 2, ""About to initialize""); if (TNEF->IO.InitProc(&TNEF->IO) != 0) { return YTNEF_CANNOT_INIT_DATA; } DEBUG(TNEF->Debug, 2, ""Initialization finished""); } DEBUG(TNEF->Debug, 2, ""Reading Signature""); if (TNEF->IO.ReadProc(&TNEF->IO, sizeof(DWORD), 1, &signature) < 1) { printf(""ERROR: Error reading signature\n""); if (TNEF->IO.CloseProc != NULL) { TNEF->IO.CloseProc(&TNEF->IO); } return YTNEF_ERROR_READING_DATA; } DEBUG(TNEF->Debug, 2, ""Checking Signature""); if (TNEFCheckForSignature(signature) < 0) { printf(""ERROR: Signature does not match. Not TNEF.\n""); if (TNEF->IO.CloseProc != NULL) { TNEF->IO.CloseProc(&TNEF->IO); } return YTNEF_NOT_TNEF_STREAM; } DEBUG(TNEF->Debug, 2, ""Reading Key.""); if (TNEFGetKey(TNEF, &key) < 0) { printf(""ERROR: Unable to retrieve key.\n""); if (TNEF->IO.CloseProc != NULL) { TNEF->IO.CloseProc(&TNEF->IO); } return YTNEF_NO_KEY; } DEBUG(TNEF->Debug, 2, ""Starting Full Processing.""); while (TNEFGetHeader(TNEF, &type, &size) == 0) { DEBUG2(TNEF->Debug, 2, ""Header says type=0x%X, size=%u"", type, size); DEBUG2(TNEF->Debug, 2, ""Header says type=%u, size=%u"", type, size); data = calloc(size, sizeof(BYTE)); ALLOCCHECK(data); if (TNEFRawRead(TNEF, data, size, &header_checksum) < 0) { printf(""ERROR: Unable to read data.\n""); if (TNEF->IO.CloseProc != NULL) { TNEF->IO.CloseProc(&TNEF->IO); } free(data); return YTNEF_ERROR_READING_DATA; } if (TNEFRawRead(TNEF, (BYTE *)&checksum, 2, NULL) < 0) { printf(""ERROR: Unable to read checksum.\n""); if (TNEF->IO.CloseProc != NULL) { TNEF->IO.CloseProc(&TNEF->IO); } free(data); return YTNEF_ERROR_READING_DATA; } checksum = SwapWord((BYTE *)&checksum, sizeof(WORD)); if (checksum != header_checksum) { printf(""ERROR: Checksum mismatch. Data corruption?:\n""); if (TNEF->IO.CloseProc != NULL) { TNEF->IO.CloseProc(&TNEF->IO); } free(data); return YTNEF_BAD_CHECKSUM; } for (i = 0; i < (sizeof(TNEFList) / sizeof(TNEFHandler)); i++) { if (TNEFList[i].id == type) { if (TNEFList[i].handler != NULL) { if (TNEFList[i].handler(TNEF, i, (char*)data, size) < 0) { free(data); if (TNEF->IO.CloseProc != NULL) { TNEF->IO.CloseProc(&TNEF->IO); } return YTNEF_ERROR_IN_HANDLER; } else { // Found our handler and processed it. now time to get out break; } } else { DEBUG2(TNEF->Debug, 1, ""No handler for %s: %u bytes"", TNEFList[i].name, size); } } } free(data); } if (TNEF->IO.CloseProc != NULL) { TNEF->IO.CloseProc(&TNEF->IO); } return 0; }","int TNEFParse(TNEFStruct *TNEF) { WORD key; DWORD type; DWORD size; DWORD signature; BYTE *data; WORD checksum, header_checksum; int i; if (TNEF->IO.ReadProc == NULL) { printf(""ERROR: Setup incorrectly: No ReadProc\n""); return YTNEF_INCORRECT_SETUP; } if (TNEF->IO.InitProc != NULL) { DEBUG(TNEF->Debug, 2, ""About to initialize""); if (TNEF->IO.InitProc(&TNEF->IO) != 0) { return YTNEF_CANNOT_INIT_DATA; } DEBUG(TNEF->Debug, 2, ""Initialization finished""); } DEBUG(TNEF->Debug, 2, ""Reading Signature""); if (TNEF->IO.ReadProc(&TNEF->IO, sizeof(DWORD), 1, &signature) < 1) { printf(""ERROR: Error reading signature\n""); if (TNEF->IO.CloseProc != NULL) { TNEF->IO.CloseProc(&TNEF->IO); } return YTNEF_ERROR_READING_DATA; } DEBUG(TNEF->Debug, 2, ""Checking Signature""); if (TNEFCheckForSignature(signature) < 0) { printf(""ERROR: Signature does not match. Not TNEF.\n""); if (TNEF->IO.CloseProc != NULL) { TNEF->IO.CloseProc(&TNEF->IO); } return YTNEF_NOT_TNEF_STREAM; } DEBUG(TNEF->Debug, 2, ""Reading Key.""); if (TNEFGetKey(TNEF, &key) < 0) { printf(""ERROR: Unable to retrieve key.\n""); if (TNEF->IO.CloseProc != NULL) { TNEF->IO.CloseProc(&TNEF->IO); } return YTNEF_NO_KEY; } DEBUG(TNEF->Debug, 2, ""Starting Full Processing.""); while (TNEFGetHeader(TNEF, &type, &size) == 0) { DEBUG2(TNEF->Debug, 2, ""Header says type=0x%X, size=%u"", type, size); DEBUG2(TNEF->Debug, 2, ""Header says type=%u, size=%u"", type, size); if(size == 0) { printf(""ERROR: Field with size of 0\n""); return YTNEF_ERROR_READING_DATA; } data = calloc(size, sizeof(BYTE)); ALLOCCHECK(data); if (TNEFRawRead(TNEF, data, size, &header_checksum) < 0) { printf(""ERROR: Unable to read data.\n""); if (TNEF->IO.CloseProc != NULL) { TNEF->IO.CloseProc(&TNEF->IO); } free(data); return YTNEF_ERROR_READING_DATA; } if (TNEFRawRead(TNEF, (BYTE *)&checksum, 2, NULL) < 0) { printf(""ERROR: Unable to read checksum.\n""); if (TNEF->IO.CloseProc != NULL) { TNEF->IO.CloseProc(&TNEF->IO); } free(data); return YTNEF_ERROR_READING_DATA; } checksum = SwapWord((BYTE *)&checksum, sizeof(WORD)); if (checksum != header_checksum) { printf(""ERROR: Checksum mismatch. Data corruption?:\n""); if (TNEF->IO.CloseProc != NULL) { TNEF->IO.CloseProc(&TNEF->IO); } free(data); return YTNEF_BAD_CHECKSUM; } for (i = 0; i < (sizeof(TNEFList) / sizeof(TNEFHandler)); i++) { if (TNEFList[i].id == type) { if (TNEFList[i].handler != NULL) { if (TNEFList[i].handler(TNEF, i, (char*)data, size) < 0) { free(data); if (TNEF->IO.CloseProc != NULL) { TNEF->IO.CloseProc(&TNEF->IO); } return YTNEF_ERROR_IN_HANDLER; } else { // Found our handler and processed it. now time to get out break; } } else { DEBUG2(TNEF->Debug, 1, ""No handler for %s: %u bytes"", TNEFList[i].name, size); } } } free(data); } if (TNEF->IO.CloseProc != NULL) { TNEF->IO.CloseProc(&TNEF->IO); } return 0; }","{'deleted': [], 'added': [{'line_no': 56, 'char_start': 1563, 'char_end': 1583, 'line': ' if(size == 0) {\n'}, {'line_no': 57, 'char_start': 1583, 'char_end': 1630, 'line': ' printf(""ERROR: Field with size of 0\\n"");\n'}, {'line_no': 58, 'char_start': 1630, 'char_end': 1669, 'line': ' return YTNEF_ERROR_READING_DATA;\n'}, {'line_no': 59, 'char_start': 1669, 'char_end': 1675, 'line': ' }\n'}]}","{'deleted': [], 'added': [{'char_start': 1567, 'char_end': 1679, 'chars': 'if(size == 0) {\n printf(""ERROR: Field with size of 0\\n"");\n return YTNEF_ERROR_READING_DATA;\n }\n '}]}",github.com/Yeraze/ytnef/commit/3cb0f914d6427073f262e1b2b5fd973e3043cdf7,lib/ytnef.c,cwe-125,1051 cwe-089,getSeriesDateFromDatabase,"def getSeriesDateFromDatabase(submission): database = sqlite3.connect('database.db') cursor = database.cursor() return cursor.execute(""SELECT StartDate FROM SeriesTracking WHERE SeriesTitle = '"" + str(getTitle(submission)) + ""'"").fetchone()[0] database.close()","def getSeriesDateFromDatabase(submission): database = sqlite3.connect('database.db') cursor = database.cursor() return cursor.execute(""SELECT StartDate FROM SeriesTracking WHERE SeriesTitle = ?"", [getTitle(submission)]).fetchone()[0] database.close()","{'deleted': [{'line_no': 4, 'char_start': 120, 'char_end': 256, 'line': ' return cursor.execute(""SELECT StartDate FROM SeriesTracking WHERE SeriesTitle = \'"" + str(getTitle(submission)) + ""\'"").fetchone()[0]\n'}], 'added': [{'line_no': 4, 'char_start': 120, 'char_end': 246, 'line': ' return cursor.execute(""SELECT StartDate FROM SeriesTracking WHERE SeriesTitle = ?"", [getTitle(submission)]).fetchone()[0]\n'}]}","{'deleted': [{'char_start': 204, 'char_end': 205, 'chars': ""'""}, {'char_start': 206, 'char_end': 208, 'chars': ' +'}, {'char_start': 209, 'char_end': 213, 'chars': 'str('}, {'char_start': 233, 'char_end': 240, 'chars': ') + ""\'""'}], 'added': [{'char_start': 204, 'char_end': 205, 'chars': '?'}, {'char_start': 206, 'char_end': 207, 'chars': ','}, {'char_start': 208, 'char_end': 209, 'chars': '['}, {'char_start': 229, 'char_end': 230, 'chars': ']'}]}",github.com/LiquidFun/Reddit-GeoGuessr-Tracking-Bot/commit/0cad2d52e24b05da32789fbc8face7a9999a71f9,CheckAndPostForSeriesSubmissions.py,cwe-089,60 cwe-089,getPlayer,"def getPlayer(player): db.execute(""SELECT * FROM players WHERE Name = '%s' COLLATE NOCASE"" % player) playerstats = dict(db.fetchone()) return playerstats","def getPlayer(player): db.execute(""SELECT * FROM players WHERE Name = ? COLLATE NOCASE"", player) playerstats = dict(db.fetchone()) return playerstats","{'deleted': [{'line_no': 2, 'char_start': 23, 'char_end': 102, 'line': '\tdb.execute(""SELECT * FROM players WHERE Name = \'%s\' COLLATE NOCASE"" % player)\n'}], 'added': [{'line_no': 2, 'char_start': 23, 'char_end': 98, 'line': '\tdb.execute(""SELECT * FROM players WHERE Name = ? COLLATE NOCASE"", player)\n'}]}","{'deleted': [{'char_start': 71, 'char_end': 75, 'chars': ""'%s'""}, {'char_start': 91, 'char_end': 93, 'chars': ' %'}], 'added': [{'char_start': 71, 'char_end': 72, 'chars': '?'}, {'char_start': 88, 'char_end': 89, 'chars': ','}]}",github.com/iScrE4m/XLeague/commit/59cab6e5fd8bd5e47f2418a7c71cb1d4e3cad0d2,plugins/database.py,cwe-089,35 cwe-089,addTags,"def addTags(tag_list, listing_id): """""" Adds a list of tags tag_list for a given listing with listing_id to the database """""" cur = conn.cursor() for x in tag_list: sql = ""INSERT INTO {} VALUES {}"".format(listing_tags_table_name, str((listing_id, x))) cur.execute(sql)","def addTags(tag_list, listing_id): """""" Adds a list of tags tag_list for a given listing with listing_id to the database """""" cur = conn.cursor() for x in tag_list: sql = ""INSERT INTO %s VALUES (%s %s)"" cur.execute(sql, (listing_tags_table_name, listing_id, x))","{'deleted': [{'line_no': 7, 'char_start': 183, 'char_end': 278, 'line': ' sql = ""INSERT INTO {} VALUES {}"".format(listing_tags_table_name, str((listing_id, x)))\n'}, {'line_no': 8, 'char_start': 278, 'char_end': 302, 'line': ' cur.execute(sql)\n'}], 'added': [{'line_no': 7, 'char_start': 183, 'char_end': 229, 'line': ' sql = ""INSERT INTO %s VALUES (%s %s)""\n'}, {'line_no': 8, 'char_start': 229, 'char_end': 295, 'line': ' cur.execute(sql, (listing_tags_table_name, listing_id, x))\n'}]}","{'deleted': [{'char_start': 210, 'char_end': 212, 'chars': '{}'}, {'char_start': 220, 'char_end': 222, 'chars': '{}'}, {'char_start': 223, 'char_end': 226, 'chars': '.fo'}, {'char_start': 227, 'char_end': 229, 'chars': 'ma'}, {'char_start': 256, 'char_end': 261, 'chars': 'str(('}, {'char_start': 276, 'char_end': 302, 'chars': ')\n cur.execute(sql)'}], 'added': [{'char_start': 210, 'char_end': 212, 'chars': '%s'}, {'char_start': 220, 'char_end': 227, 'chars': '(%s %s)'}, {'char_start': 228, 'char_end': 239, 'chars': '\n cu'}, {'char_start': 240, 'char_end': 246, 'chars': '.execu'}, {'char_start': 247, 'char_end': 254, 'chars': 'e(sql, '}]}",github.com/tasbir49/BreadWinner/commit/332a9f2c619be399ae94244bb8bd0977fc62bc16,backend-api/backend-api.py,cwe-089,73 cwe-190,PHP_FUNCTION,"PHPAPI PHP_FUNCTION(fread) { zval *arg1; long len; php_stream *stream; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, ""rl"", &arg1, &len) == FAILURE) { RETURN_FALSE; } PHP_STREAM_TO_ZVAL(stream, &arg1); if (len <= 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, ""Length parameter must be greater than 0""); RETURN_FALSE; } Z_STRVAL_P(return_value) = emalloc(len + 1); Z_STRLEN_P(return_value) = php_stream_read(stream, Z_STRVAL_P(return_value), len); /* needed because recv/read/gzread doesnt put a null at the end*/ Z_STRVAL_P(return_value)[Z_STRLEN_P(return_value)] = 0; Z_TYPE_P(return_value) = IS_STRING; }","PHPAPI PHP_FUNCTION(fread) { zval *arg1; long len; php_stream *stream; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, ""rl"", &arg1, &len) == FAILURE) { RETURN_FALSE; } PHP_STREAM_TO_ZVAL(stream, &arg1); if (len <= 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, ""Length parameter must be greater than 0""); RETURN_FALSE; } if (len > INT_MAX) { /* string length is int in 5.x so we can not read more than int */ php_error_docref(NULL TSRMLS_CC, E_WARNING, ""Length parameter must be no more than %d"", INT_MAX); RETURN_FALSE; } Z_STRVAL_P(return_value) = emalloc(len + 1); Z_STRLEN_P(return_value) = php_stream_read(stream, Z_STRVAL_P(return_value), len); /* needed because recv/read/gzread doesnt put a null at the end*/ Z_STRVAL_P(return_value)[Z_STRLEN_P(return_value)] = 0; Z_TYPE_P(return_value) = IS_STRING; }","{'deleted': [], 'added': [{'line_no': 18, 'char_start': 346, 'char_end': 368, 'line': '\tif (len > INT_MAX) {\n'}, {'line_no': 19, 'char_start': 368, 'char_end': 437, 'line': '\t\t/* string length is int in 5.x so we can not read more than int */\n'}, {'line_no': 20, 'char_start': 437, 'char_end': 537, 'line': '\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING, ""Length parameter must be no more than %d"", INT_MAX);\n'}, {'line_no': 21, 'char_start': 537, 'char_end': 553, 'line': '\t\tRETURN_FALSE;\n'}, {'line_no': 22, 'char_start': 553, 'char_end': 556, 'line': '\t}\n'}, {'line_no': 23, 'char_start': 556, 'char_end': 557, 'line': '\n'}]}","{'deleted': [], 'added': [{'char_start': 347, 'char_end': 558, 'chars': 'if (len > INT_MAX) {\n\t\t/* string length is int in 5.x so we can not read more than int */\n\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING, ""Length parameter must be no more than %d"", INT_MAX);\n\t\tRETURN_FALSE;\n\t}\n\n\t'}]}",github.com/php/php-src/commit/abd159cce48f3e34f08e4751c568e09677d5ec9c,ext/standard/file.c,cwe-190,188 cwe-125,ReadWPGImage,"static Image *ReadWPGImage(const ImageInfo *image_info, ExceptionInfo *exception) { typedef struct { size_t FileId; MagickOffsetType DataOffset; unsigned int ProductType; unsigned int FileType; unsigned char MajorVersion; unsigned char MinorVersion; unsigned int EncryptKey; unsigned int Reserved; } WPGHeader; typedef struct { unsigned char RecType; size_t RecordLength; } WPGRecord; typedef struct { unsigned char Class; unsigned char RecType; size_t Extension; size_t RecordLength; } WPG2Record; typedef struct { unsigned HorizontalUnits; unsigned VerticalUnits; unsigned char PosSizePrecision; } WPG2Start; typedef struct { unsigned int Width; unsigned int Height; unsigned int Depth; unsigned int HorzRes; unsigned int VertRes; } WPGBitmapType1; typedef struct { unsigned int Width; unsigned int Height; unsigned char Depth; unsigned char Compression; } WPG2BitmapType1; typedef struct { unsigned int RotAngle; unsigned int LowLeftX; unsigned int LowLeftY; unsigned int UpRightX; unsigned int UpRightY; unsigned int Width; unsigned int Height; unsigned int Depth; unsigned int HorzRes; unsigned int VertRes; } WPGBitmapType2; typedef struct { unsigned int StartIndex; unsigned int NumOfEntries; } WPGColorMapRec; /* typedef struct { size_t PS_unknown1; unsigned int PS_unknown2; unsigned int PS_unknown3; } WPGPSl1Record; */ Image *image; unsigned int status; WPGHeader Header; WPGRecord Rec; WPG2Record Rec2; WPG2Start StartWPG; WPGBitmapType1 BitmapHeader1; WPG2BitmapType1 Bitmap2Header1; WPGBitmapType2 BitmapHeader2; WPGColorMapRec WPG_Palette; int i, bpp, WPG2Flags; ssize_t ldblk; size_t one; unsigned char *BImgBuff; tCTM CTM; /*current transform matrix*/ /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); one=1; image=AcquireImage(image_info,exception); image->depth=8; status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read WPG image. */ Header.FileId=ReadBlobLSBLong(image); Header.DataOffset=(MagickOffsetType) ReadBlobLSBLong(image); Header.ProductType=ReadBlobLSBShort(image); Header.FileType=ReadBlobLSBShort(image); Header.MajorVersion=ReadBlobByte(image); Header.MinorVersion=ReadBlobByte(image); Header.EncryptKey=ReadBlobLSBShort(image); Header.Reserved=ReadBlobLSBShort(image); if (Header.FileId!=0x435057FF || (Header.ProductType>>8)!=0x16) ThrowReaderException(CorruptImageError,""ImproperImageHeader""); if (Header.EncryptKey!=0) ThrowReaderException(CoderError,""EncryptedWPGImageFileNotSupported""); image->columns = 1; image->rows = 1; image->colors = 0; bpp=0; BitmapHeader2.RotAngle=0; switch(Header.FileType) { case 1: /* WPG level 1 */ while(!EOFBlob(image)) /* object parser loop */ { (void) SeekBlob(image,Header.DataOffset,SEEK_SET); if(EOFBlob(image)) break; Rec.RecType=(i=ReadBlobByte(image)); if(i==EOF) break; Rd_WP_DWORD(image,&Rec.RecordLength); if(EOFBlob(image)) break; Header.DataOffset=TellBlob(image)+Rec.RecordLength; switch(Rec.RecType) { case 0x0B: /* bitmap type 1 */ BitmapHeader1.Width=ReadBlobLSBShort(image); BitmapHeader1.Height=ReadBlobLSBShort(image); if ((BitmapHeader1.Width == 0) || (BitmapHeader1.Height == 0)) ThrowReaderException(CorruptImageError,""ImproperImageHeader""); BitmapHeader1.Depth=ReadBlobLSBShort(image); BitmapHeader1.HorzRes=ReadBlobLSBShort(image); BitmapHeader1.VertRes=ReadBlobLSBShort(image); if(BitmapHeader1.HorzRes && BitmapHeader1.VertRes) { image->units=PixelsPerCentimeterResolution; image->resolution.x=BitmapHeader1.HorzRes/470.0; image->resolution.y=BitmapHeader1.VertRes/470.0; } image->columns=BitmapHeader1.Width; image->rows=BitmapHeader1.Height; bpp=BitmapHeader1.Depth; goto UnpackRaster; case 0x0E: /*Color palette */ WPG_Palette.StartIndex=ReadBlobLSBShort(image); WPG_Palette.NumOfEntries=ReadBlobLSBShort(image); image->colors=WPG_Palette.NumOfEntries; if (!AcquireImageColormap(image,image->colors,exception)) goto NoMemory; for (i=WPG_Palette.StartIndex; i < (int)WPG_Palette.NumOfEntries; i++) { image->colormap[i].red=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); image->colormap[i].green=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); image->colormap[i].blue=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); } break; case 0x11: /* Start PS l1 */ if(Rec.RecordLength > 8) image=ExtractPostscript(image,image_info, TellBlob(image)+8, /* skip PS header in the wpg */ (ssize_t) Rec.RecordLength-8,exception); break; case 0x14: /* bitmap type 2 */ BitmapHeader2.RotAngle=ReadBlobLSBShort(image); BitmapHeader2.LowLeftX=ReadBlobLSBShort(image); BitmapHeader2.LowLeftY=ReadBlobLSBShort(image); BitmapHeader2.UpRightX=ReadBlobLSBShort(image); BitmapHeader2.UpRightY=ReadBlobLSBShort(image); BitmapHeader2.Width=ReadBlobLSBShort(image); BitmapHeader2.Height=ReadBlobLSBShort(image); if ((BitmapHeader2.Width == 0) || (BitmapHeader2.Height == 0)) ThrowReaderException(CorruptImageError,""ImproperImageHeader""); BitmapHeader2.Depth=ReadBlobLSBShort(image); BitmapHeader2.HorzRes=ReadBlobLSBShort(image); BitmapHeader2.VertRes=ReadBlobLSBShort(image); image->units=PixelsPerCentimeterResolution; image->page.width=(unsigned int) ((BitmapHeader2.LowLeftX-BitmapHeader2.UpRightX)/470.0); image->page.height=(unsigned int) ((BitmapHeader2.LowLeftX-BitmapHeader2.UpRightY)/470.0); image->page.x=(int) (BitmapHeader2.LowLeftX/470.0); image->page.y=(int) (BitmapHeader2.LowLeftX/470.0); if(BitmapHeader2.HorzRes && BitmapHeader2.VertRes) { image->resolution.x=BitmapHeader2.HorzRes/470.0; image->resolution.y=BitmapHeader2.VertRes/470.0; } image->columns=BitmapHeader2.Width; image->rows=BitmapHeader2.Height; bpp=BitmapHeader2.Depth; UnpackRaster: if ((image->colors == 0) && (bpp != 24)) { image->colors=one << bpp; if (!AcquireImageColormap(image,image->colors,exception)) { NoMemory: ThrowReaderException(ResourceLimitError, ""MemoryAllocationFailed""); } /* printf(""Load default colormap \n""); */ for (i=0; (i < (int) image->colors) && (i < 256); i++) { image->colormap[i].red=ScaleCharToQuantum(WPG1_Palette[i].Red); image->colormap[i].green=ScaleCharToQuantum(WPG1_Palette[i].Green); image->colormap[i].blue=ScaleCharToQuantum(WPG1_Palette[i].Blue); } } else { if (bpp < 24) if ( (image->colors < (one << bpp)) && (bpp != 24) ) image->colormap=(PixelInfo *) ResizeQuantumMemory( image->colormap,(size_t) (one << bpp), sizeof(*image->colormap)); } if (bpp == 1) { if(image->colormap[0].red==0 && image->colormap[0].green==0 && image->colormap[0].blue==0 && image->colormap[1].red==0 && image->colormap[1].green==0 && image->colormap[1].blue==0) { /* fix crippled monochrome palette */ image->colormap[1].red = image->colormap[1].green = image->colormap[1].blue = QuantumRange; } } if(UnpackWPGRaster(image,bpp,exception) < 0) /* The raster cannot be unpacked */ { DecompressionFailed: ThrowReaderException(CoderError,""UnableToDecompressImage""); } if(Rec.RecType==0x14 && BitmapHeader2.RotAngle!=0 && !image_info->ping) { /* flop command */ if(BitmapHeader2.RotAngle & 0x8000) { Image *flop_image; flop_image = FlopImage(image, exception); if (flop_image != (Image *) NULL) { DuplicateBlob(flop_image,image); (void) RemoveLastImageFromList(&image); AppendImageToList(&image,flop_image); } } /* flip command */ if(BitmapHeader2.RotAngle & 0x2000) { Image *flip_image; flip_image = FlipImage(image, exception); if (flip_image != (Image *) NULL) { DuplicateBlob(flip_image,image); (void) RemoveLastImageFromList(&image); AppendImageToList(&image,flip_image); } } /* rotate command */ if(BitmapHeader2.RotAngle & 0x0FFF) { Image *rotate_image; rotate_image=RotateImage(image,(BitmapHeader2.RotAngle & 0x0FFF), exception); if (rotate_image != (Image *) NULL) { DuplicateBlob(rotate_image,image); (void) RemoveLastImageFromList(&image); AppendImageToList(&image,rotate_image); } } } /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); image->depth=8; if (image->next == (Image *) NULL) goto Finish; image=SyncNextImageInList(image); image->columns=image->rows=0; image->colors=0; break; case 0x1B: /* Postscript l2 */ if(Rec.RecordLength>0x3C) image=ExtractPostscript(image,image_info, TellBlob(image)+0x3C, /* skip PS l2 header in the wpg */ (ssize_t) Rec.RecordLength-0x3C,exception); break; } } break; case 2: /* WPG level 2 */ (void) memset(CTM,0,sizeof(CTM)); StartWPG.PosSizePrecision = 0; while(!EOFBlob(image)) /* object parser loop */ { (void) SeekBlob(image,Header.DataOffset,SEEK_SET); if(EOFBlob(image)) break; Rec2.Class=(i=ReadBlobByte(image)); if(i==EOF) break; Rec2.RecType=(i=ReadBlobByte(image)); if(i==EOF) break; Rd_WP_DWORD(image,&Rec2.Extension); Rd_WP_DWORD(image,&Rec2.RecordLength); if(EOFBlob(image)) break; Header.DataOffset=TellBlob(image)+Rec2.RecordLength; switch(Rec2.RecType) { case 1: StartWPG.HorizontalUnits=ReadBlobLSBShort(image); StartWPG.VerticalUnits=ReadBlobLSBShort(image); StartWPG.PosSizePrecision=ReadBlobByte(image); break; case 0x0C: /* Color palette */ WPG_Palette.StartIndex=ReadBlobLSBShort(image); WPG_Palette.NumOfEntries=ReadBlobLSBShort(image); image->colors=WPG_Palette.NumOfEntries; if (AcquireImageColormap(image,image->colors,exception) == MagickFalse) ThrowReaderException(ResourceLimitError, ""MemoryAllocationFailed""); for (i=WPG_Palette.StartIndex; i < (int)WPG_Palette.NumOfEntries; i++) { image->colormap[i].red=ScaleCharToQuantum((char) ReadBlobByte(image)); image->colormap[i].green=ScaleCharToQuantum((char) ReadBlobByte(image)); image->colormap[i].blue=ScaleCharToQuantum((char) ReadBlobByte(image)); (void) ReadBlobByte(image); /*Opacity??*/ } break; case 0x0E: Bitmap2Header1.Width=ReadBlobLSBShort(image); Bitmap2Header1.Height=ReadBlobLSBShort(image); if ((Bitmap2Header1.Width == 0) || (Bitmap2Header1.Height == 0)) ThrowReaderException(CorruptImageError,""ImproperImageHeader""); Bitmap2Header1.Depth=ReadBlobByte(image); Bitmap2Header1.Compression=ReadBlobByte(image); if(Bitmap2Header1.Compression > 1) continue; /*Unknown compression method */ switch(Bitmap2Header1.Depth) { case 1: bpp=1; break; case 2: bpp=2; break; case 3: bpp=4; break; case 4: bpp=8; break; case 8: bpp=24; break; default: continue; /*Ignore raster with unknown depth*/ } image->columns=Bitmap2Header1.Width; image->rows=Bitmap2Header1.Height; if ((image->colors == 0) && (bpp != 24)) { size_t one; one=1; image->colors=one << bpp; if (!AcquireImageColormap(image,image->colors,exception)) goto NoMemory; } else { if(bpp < 24) if( image->colors<(one << bpp) && bpp!=24 ) image->colormap=(PixelInfo *) ResizeQuantumMemory( image->colormap,(size_t) (one << bpp), sizeof(*image->colormap)); } switch(Bitmap2Header1.Compression) { case 0: /*Uncompressed raster*/ { ldblk=(ssize_t) ((bpp*image->columns+7)/8); BImgBuff=(unsigned char *) AcquireQuantumMemory((size_t) ldblk,sizeof(*BImgBuff)); if (BImgBuff == (unsigned char *) NULL) goto NoMemory; for(i=0; i< (ssize_t) image->rows; i++) { (void) ReadBlob(image,ldblk,BImgBuff); InsertRow(image,BImgBuff,i,bpp,exception); } if(BImgBuff) BImgBuff=(unsigned char *) RelinquishMagickMemory(BImgBuff);; break; } case 1: /*RLE for WPG2 */ { if( UnpackWPG2Raster(image,bpp,exception) < 0) goto DecompressionFailed; break; } } if(CTM[0][0]<0 && !image_info->ping) { /*?? RotAngle=360-RotAngle;*/ Image *flop_image; flop_image = FlopImage(image, exception); if (flop_image != (Image *) NULL) { DuplicateBlob(flop_image,image); (void) RemoveLastImageFromList(&image); AppendImageToList(&image,flop_image); } /* Try to change CTM according to Flip - I am not sure, must be checked. Tx(0,0)=-1; Tx(1,0)=0; Tx(2,0)=0; Tx(0,1)= 0; Tx(1,1)=1; Tx(2,1)=0; Tx(0,2)=(WPG._2Rect.X_ur+WPG._2Rect.X_ll); Tx(1,2)=0; Tx(2,2)=1; */ } if(CTM[1][1]<0 && !image_info->ping) { /*?? RotAngle=360-RotAngle;*/ Image *flip_image; flip_image = FlipImage(image, exception); if (flip_image != (Image *) NULL) { DuplicateBlob(flip_image,image); (void) RemoveLastImageFromList(&image); AppendImageToList(&image,flip_image); } /* Try to change CTM according to Flip - I am not sure, must be checked. float_matrix Tx(3,3); Tx(0,0)= 1; Tx(1,0)= 0; Tx(2,0)=0; Tx(0,1)= 0; Tx(1,1)=-1; Tx(2,1)=0; Tx(0,2)= 0; Tx(1,2)=(WPG._2Rect.Y_ur+WPG._2Rect.Y_ll); Tx(2,2)=1; */ } /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); image->depth=8; if (image->next == (Image *) NULL) goto Finish; image=SyncNextImageInList(image); image->columns=image->rows=1; image->colors=0; break; case 0x12: /* Postscript WPG2*/ i=ReadBlobLSBShort(image); if(Rec2.RecordLength > (unsigned int) i) image=ExtractPostscript(image,image_info, TellBlob(image)+i, /*skip PS header in the wpg2*/ (ssize_t) (Rec2.RecordLength-i-2),exception); break; case 0x1B: /*bitmap rectangle*/ WPG2Flags = LoadWPG2Flags(image,StartWPG.PosSizePrecision,NULL,&CTM); (void) WPG2Flags; break; } } break; default: { ThrowReaderException(CoderError,""DataEncodingSchemeIsNotSupported""); } } status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); Finish: (void) CloseBlob(image); { Image *p; ssize_t scene=0; /* Rewind list, removing any empty images while rewinding. */ p=image; image=NULL; while (p != (Image *) NULL) { Image *tmp=p; if ((p->rows == 0) || (p->columns == 0)) { p=p->previous; DeleteImageFromList(&tmp); } else { image=p; p=p->previous; } } /* Fix scene numbers. */ for (p=image; p != (Image *) NULL; p=p->next) p->scene=(size_t) scene++; } if (image == (Image *) NULL) ThrowReaderException(CorruptImageError, ""ImageFileDoesNotContainAnyImageData""); return(image); }","static Image *ReadWPGImage(const ImageInfo *image_info, ExceptionInfo *exception) { typedef struct { size_t FileId; MagickOffsetType DataOffset; unsigned int ProductType; unsigned int FileType; unsigned char MajorVersion; unsigned char MinorVersion; unsigned int EncryptKey; unsigned int Reserved; } WPGHeader; typedef struct { unsigned char RecType; size_t RecordLength; } WPGRecord; typedef struct { unsigned char Class; unsigned char RecType; size_t Extension; size_t RecordLength; } WPG2Record; typedef struct { unsigned HorizontalUnits; unsigned VerticalUnits; unsigned char PosSizePrecision; } WPG2Start; typedef struct { unsigned int Width; unsigned int Height; unsigned int Depth; unsigned int HorzRes; unsigned int VertRes; } WPGBitmapType1; typedef struct { unsigned int Width; unsigned int Height; unsigned char Depth; unsigned char Compression; } WPG2BitmapType1; typedef struct { unsigned int RotAngle; unsigned int LowLeftX; unsigned int LowLeftY; unsigned int UpRightX; unsigned int UpRightY; unsigned int Width; unsigned int Height; unsigned int Depth; unsigned int HorzRes; unsigned int VertRes; } WPGBitmapType2; typedef struct { unsigned int StartIndex; unsigned int NumOfEntries; } WPGColorMapRec; /* typedef struct { size_t PS_unknown1; unsigned int PS_unknown2; unsigned int PS_unknown3; } WPGPSl1Record; */ Image *image; unsigned int status; WPGHeader Header; WPGRecord Rec; WPG2Record Rec2; WPG2Start StartWPG; WPGBitmapType1 BitmapHeader1; WPG2BitmapType1 Bitmap2Header1; WPGBitmapType2 BitmapHeader2; WPGColorMapRec WPG_Palette; int i, bpp, WPG2Flags; ssize_t ldblk; size_t one; unsigned char *BImgBuff; tCTM CTM; /*current transform matrix*/ /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); one=1; image=AcquireImage(image_info,exception); image->depth=8; status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read WPG image. */ Header.FileId=ReadBlobLSBLong(image); Header.DataOffset=(MagickOffsetType) ReadBlobLSBLong(image); Header.ProductType=ReadBlobLSBShort(image); Header.FileType=ReadBlobLSBShort(image); Header.MajorVersion=ReadBlobByte(image); Header.MinorVersion=ReadBlobByte(image); Header.EncryptKey=ReadBlobLSBShort(image); Header.Reserved=ReadBlobLSBShort(image); if (Header.FileId!=0x435057FF || (Header.ProductType>>8)!=0x16) ThrowReaderException(CorruptImageError,""ImproperImageHeader""); if (Header.EncryptKey!=0) ThrowReaderException(CoderError,""EncryptedWPGImageFileNotSupported""); image->columns = 1; image->rows = 1; image->colors = 0; bpp=0; BitmapHeader2.RotAngle=0; switch(Header.FileType) { case 1: /* WPG level 1 */ while(!EOFBlob(image)) /* object parser loop */ { (void) SeekBlob(image,Header.DataOffset,SEEK_SET); if(EOFBlob(image)) break; Rec.RecType=(i=ReadBlobByte(image)); if(i==EOF) break; Rd_WP_DWORD(image,&Rec.RecordLength); if(EOFBlob(image)) break; Header.DataOffset=TellBlob(image)+Rec.RecordLength; switch(Rec.RecType) { case 0x0B: /* bitmap type 1 */ BitmapHeader1.Width=ReadBlobLSBShort(image); BitmapHeader1.Height=ReadBlobLSBShort(image); if ((BitmapHeader1.Width == 0) || (BitmapHeader1.Height == 0)) ThrowReaderException(CorruptImageError,""ImproperImageHeader""); BitmapHeader1.Depth=ReadBlobLSBShort(image); BitmapHeader1.HorzRes=ReadBlobLSBShort(image); BitmapHeader1.VertRes=ReadBlobLSBShort(image); if(BitmapHeader1.HorzRes && BitmapHeader1.VertRes) { image->units=PixelsPerCentimeterResolution; image->resolution.x=BitmapHeader1.HorzRes/470.0; image->resolution.y=BitmapHeader1.VertRes/470.0; } image->columns=BitmapHeader1.Width; image->rows=BitmapHeader1.Height; bpp=BitmapHeader1.Depth; goto UnpackRaster; case 0x0E: /*Color palette */ WPG_Palette.StartIndex=ReadBlobLSBShort(image); WPG_Palette.NumOfEntries=ReadBlobLSBShort(image); image->colors=WPG_Palette.NumOfEntries; if (!AcquireImageColormap(image,image->colors,exception)) goto NoMemory; for (i=WPG_Palette.StartIndex; i < (int)WPG_Palette.NumOfEntries; i++) { image->colormap[i].red=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); image->colormap[i].green=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); image->colormap[i].blue=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); } break; case 0x11: /* Start PS l1 */ if(Rec.RecordLength > 8) image=ExtractPostscript(image,image_info, TellBlob(image)+8, /* skip PS header in the wpg */ (ssize_t) Rec.RecordLength-8,exception); break; case 0x14: /* bitmap type 2 */ BitmapHeader2.RotAngle=ReadBlobLSBShort(image); BitmapHeader2.LowLeftX=ReadBlobLSBShort(image); BitmapHeader2.LowLeftY=ReadBlobLSBShort(image); BitmapHeader2.UpRightX=ReadBlobLSBShort(image); BitmapHeader2.UpRightY=ReadBlobLSBShort(image); BitmapHeader2.Width=ReadBlobLSBShort(image); BitmapHeader2.Height=ReadBlobLSBShort(image); if ((BitmapHeader2.Width == 0) || (BitmapHeader2.Height == 0)) ThrowReaderException(CorruptImageError,""ImproperImageHeader""); BitmapHeader2.Depth=ReadBlobLSBShort(image); BitmapHeader2.HorzRes=ReadBlobLSBShort(image); BitmapHeader2.VertRes=ReadBlobLSBShort(image); image->units=PixelsPerCentimeterResolution; image->page.width=(unsigned int) ((BitmapHeader2.LowLeftX-BitmapHeader2.UpRightX)/470.0); image->page.height=(unsigned int) ((BitmapHeader2.LowLeftX-BitmapHeader2.UpRightY)/470.0); image->page.x=(int) (BitmapHeader2.LowLeftX/470.0); image->page.y=(int) (BitmapHeader2.LowLeftX/470.0); if(BitmapHeader2.HorzRes && BitmapHeader2.VertRes) { image->resolution.x=BitmapHeader2.HorzRes/470.0; image->resolution.y=BitmapHeader2.VertRes/470.0; } image->columns=BitmapHeader2.Width; image->rows=BitmapHeader2.Height; bpp=BitmapHeader2.Depth; UnpackRaster: if ((image->colors == 0) && (bpp != 24)) { image->colors=one << bpp; if (!AcquireImageColormap(image,image->colors,exception)) { NoMemory: ThrowReaderException(ResourceLimitError, ""MemoryAllocationFailed""); } /* printf(""Load default colormap \n""); */ for (i=0; (i < (int) image->colors) && (i < 256); i++) { image->colormap[i].red=ScaleCharToQuantum(WPG1_Palette[i].Red); image->colormap[i].green=ScaleCharToQuantum(WPG1_Palette[i].Green); image->colormap[i].blue=ScaleCharToQuantum(WPG1_Palette[i].Blue); } } else { if (bpp < 24) if ( (image->colors < (one << bpp)) && (bpp != 24) ) image->colormap=(PixelInfo *) ResizeQuantumMemory( image->colormap,(size_t) (one << bpp), sizeof(*image->colormap)); } if (bpp == 1) { if(image->colormap[0].red==0 && image->colormap[0].green==0 && image->colormap[0].blue==0 && image->colormap[1].red==0 && image->colormap[1].green==0 && image->colormap[1].blue==0) { /* fix crippled monochrome palette */ image->colormap[1].red = image->colormap[1].green = image->colormap[1].blue = QuantumRange; } } if(UnpackWPGRaster(image,bpp,exception) < 0) /* The raster cannot be unpacked */ { DecompressionFailed: ThrowReaderException(CoderError,""UnableToDecompressImage""); } if(Rec.RecType==0x14 && BitmapHeader2.RotAngle!=0 && !image_info->ping) { /* flop command */ if(BitmapHeader2.RotAngle & 0x8000) { Image *flop_image; flop_image = FlopImage(image, exception); if (flop_image != (Image *) NULL) { DuplicateBlob(flop_image,image); (void) RemoveLastImageFromList(&image); AppendImageToList(&image,flop_image); } } /* flip command */ if(BitmapHeader2.RotAngle & 0x2000) { Image *flip_image; flip_image = FlipImage(image, exception); if (flip_image != (Image *) NULL) { DuplicateBlob(flip_image,image); (void) RemoveLastImageFromList(&image); AppendImageToList(&image,flip_image); } } /* rotate command */ if(BitmapHeader2.RotAngle & 0x0FFF) { Image *rotate_image; rotate_image=RotateImage(image,(BitmapHeader2.RotAngle & 0x0FFF), exception); if (rotate_image != (Image *) NULL) { DuplicateBlob(rotate_image,image); (void) RemoveLastImageFromList(&image); AppendImageToList(&image,rotate_image); } } } /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); image->depth=8; if (image->next == (Image *) NULL) goto Finish; image=SyncNextImageInList(image); image->columns=image->rows=0; image->colors=0; break; case 0x1B: /* Postscript l2 */ if(Rec.RecordLength>0x3C) image=ExtractPostscript(image,image_info, TellBlob(image)+0x3C, /* skip PS l2 header in the wpg */ (ssize_t) Rec.RecordLength-0x3C,exception); break; } } break; case 2: /* WPG level 2 */ (void) memset(CTM,0,sizeof(CTM)); StartWPG.PosSizePrecision = 0; while(!EOFBlob(image)) /* object parser loop */ { (void) SeekBlob(image,Header.DataOffset,SEEK_SET); if(EOFBlob(image)) break; Rec2.Class=(i=ReadBlobByte(image)); if(i==EOF) break; Rec2.RecType=(i=ReadBlobByte(image)); if(i==EOF) break; Rd_WP_DWORD(image,&Rec2.Extension); Rd_WP_DWORD(image,&Rec2.RecordLength); if(EOFBlob(image)) break; Header.DataOffset=TellBlob(image)+Rec2.RecordLength; switch(Rec2.RecType) { case 1: StartWPG.HorizontalUnits=ReadBlobLSBShort(image); StartWPG.VerticalUnits=ReadBlobLSBShort(image); StartWPG.PosSizePrecision=ReadBlobByte(image); break; case 0x0C: /* Color palette */ WPG_Palette.StartIndex=ReadBlobLSBShort(image); WPG_Palette.NumOfEntries=ReadBlobLSBShort(image); image->colors=WPG_Palette.NumOfEntries; if (AcquireImageColormap(image,image->colors,exception) == MagickFalse) ThrowReaderException(ResourceLimitError, ""MemoryAllocationFailed""); for (i=WPG_Palette.StartIndex; i < (int)WPG_Palette.NumOfEntries; i++) { image->colormap[i].red=ScaleCharToQuantum((char) ReadBlobByte(image)); image->colormap[i].green=ScaleCharToQuantum((char) ReadBlobByte(image)); image->colormap[i].blue=ScaleCharToQuantum((char) ReadBlobByte(image)); (void) ReadBlobByte(image); /*Opacity??*/ } break; case 0x0E: Bitmap2Header1.Width=ReadBlobLSBShort(image); Bitmap2Header1.Height=ReadBlobLSBShort(image); if ((Bitmap2Header1.Width == 0) || (Bitmap2Header1.Height == 0)) ThrowReaderException(CorruptImageError,""ImproperImageHeader""); Bitmap2Header1.Depth=ReadBlobByte(image); Bitmap2Header1.Compression=ReadBlobByte(image); if(Bitmap2Header1.Compression > 1) continue; /*Unknown compression method */ switch(Bitmap2Header1.Depth) { case 1: bpp=1; break; case 2: bpp=2; break; case 3: bpp=4; break; case 4: bpp=8; break; case 8: bpp=24; break; default: continue; /*Ignore raster with unknown depth*/ } image->columns=Bitmap2Header1.Width; image->rows=Bitmap2Header1.Height; if ((image->colors == 0) && (bpp != 24)) { size_t one; one=1; image->colors=one << bpp; if (!AcquireImageColormap(image,image->colors,exception)) goto NoMemory; } else { if(bpp < 24) if( image->colors<(one << bpp) && bpp!=24 ) image->colormap=(PixelInfo *) ResizeQuantumMemory( image->colormap,(size_t) (one << bpp), sizeof(*image->colormap)); } switch(Bitmap2Header1.Compression) { case 0: /*Uncompressed raster*/ { ldblk=(ssize_t) ((bpp*image->columns+7)/8); BImgBuff=(unsigned char *) AcquireQuantumMemory((size_t) ldblk+1,sizeof(*BImgBuff)); if (BImgBuff == (unsigned char *) NULL) goto NoMemory; for(i=0; i< (ssize_t) image->rows; i++) { (void) ReadBlob(image,ldblk,BImgBuff); InsertRow(image,BImgBuff,i,bpp,exception); } if(BImgBuff) BImgBuff=(unsigned char *) RelinquishMagickMemory(BImgBuff);; break; } case 1: /*RLE for WPG2 */ { if( UnpackWPG2Raster(image,bpp,exception) < 0) goto DecompressionFailed; break; } } if(CTM[0][0]<0 && !image_info->ping) { /*?? RotAngle=360-RotAngle;*/ Image *flop_image; flop_image = FlopImage(image, exception); if (flop_image != (Image *) NULL) { DuplicateBlob(flop_image,image); (void) RemoveLastImageFromList(&image); AppendImageToList(&image,flop_image); } /* Try to change CTM according to Flip - I am not sure, must be checked. Tx(0,0)=-1; Tx(1,0)=0; Tx(2,0)=0; Tx(0,1)= 0; Tx(1,1)=1; Tx(2,1)=0; Tx(0,2)=(WPG._2Rect.X_ur+WPG._2Rect.X_ll); Tx(1,2)=0; Tx(2,2)=1; */ } if(CTM[1][1]<0 && !image_info->ping) { /*?? RotAngle=360-RotAngle;*/ Image *flip_image; flip_image = FlipImage(image, exception); if (flip_image != (Image *) NULL) { DuplicateBlob(flip_image,image); (void) RemoveLastImageFromList(&image); AppendImageToList(&image,flip_image); } /* Try to change CTM according to Flip - I am not sure, must be checked. float_matrix Tx(3,3); Tx(0,0)= 1; Tx(1,0)= 0; Tx(2,0)=0; Tx(0,1)= 0; Tx(1,1)=-1; Tx(2,1)=0; Tx(0,2)= 0; Tx(1,2)=(WPG._2Rect.Y_ur+WPG._2Rect.Y_ll); Tx(2,2)=1; */ } /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); image->depth=8; if (image->next == (Image *) NULL) goto Finish; image=SyncNextImageInList(image); image->columns=image->rows=1; image->colors=0; break; case 0x12: /* Postscript WPG2*/ i=ReadBlobLSBShort(image); if(Rec2.RecordLength > (unsigned int) i) image=ExtractPostscript(image,image_info, TellBlob(image)+i, /*skip PS header in the wpg2*/ (ssize_t) (Rec2.RecordLength-i-2),exception); break; case 0x1B: /*bitmap rectangle*/ WPG2Flags = LoadWPG2Flags(image,StartWPG.PosSizePrecision,NULL,&CTM); (void) WPG2Flags; break; } } break; default: { ThrowReaderException(CoderError,""DataEncodingSchemeIsNotSupported""); } } status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); Finish: (void) CloseBlob(image); { Image *p; ssize_t scene=0; /* Rewind list, removing any empty images while rewinding. */ p=image; image=NULL; while (p != (Image *) NULL) { Image *tmp=p; if ((p->rows == 0) || (p->columns == 0)) { p=p->previous; DeleteImageFromList(&tmp); } else { image=p; p=p->previous; } } /* Fix scene numbers. */ for (p=image; p != (Image *) NULL; p=p->next) p->scene=(size_t) scene++; } if (image == (Image *) NULL) ThrowReaderException(CorruptImageError, ""ImageFileDoesNotContainAnyImageData""); return(image); }","{'deleted': [{'line_no': 485, 'char_start': 16143, 'char_end': 16191, 'line': ' ldblk,sizeof(*BImgBuff));\n'}], 'added': [{'line_no': 485, 'char_start': 16143, 'char_end': 16193, 'line': ' ldblk+1,sizeof(*BImgBuff));\n'}]}","{'deleted': [], 'added': [{'char_start': 16170, 'char_end': 16172, 'chars': '+1'}]}",github.com/ImageMagick/ImageMagick/commit/bef1e4f637d8f665bc133a9c6d30df08d983bc3a,coders/wpg.c,cwe-125,4723 cwe-089,get_error_days,"def get_error_days(cur, error_percent): """"""Fetches the days in which requests led to errors. Fetches the days in which the specified percentage of requests led to errors. Args: cur(obj): The cursor to execute the query. error_percent(int): The percentage of requests that led to errors. Return: True if success, False otherwise. """""" query = '''SELECT to_char(log_errors.date, 'Mon DD YYYY'), round((log_errors.errors * 100 / log_requests.total::numeric), 2) as percent FROM log_errors, log_requests WHERE log_errors.date = log_requests.date AND log_errors.errors * 100 / log_requests.total::numeric > {} ORDER BY log_errors.date'''.format(error_percent) rows = get_data(cur, query) # Write data to txt file. if rows is not None: file = open(""error_report.txt"", ""w"") for row in rows: file.write(""{} - {}% errors \n"".format(row[0], row[1])) file.close() return True else: return False","def get_error_days(cur, error_percent): """"""Fetches the days in which requests led to errors. Fetches the days in which the specified percentage of requests led to errors. Args: cur(obj): The cursor to execute the query. error_percent(int): The percentage of requests that led to errors. Return: True if success, False otherwise. """""" data = (error_percent, ) query = '''SELECT to_char(log_errors.date, 'Mon DD YYYY'), round((log_errors.errors * 100 / log_requests.total::numeric), 2) as percent FROM log_errors, log_requests WHERE log_errors.date = log_requests.date AND log_errors.errors * 100 / log_requests.total::numeric > %s ORDER BY log_errors.date''' rows = get_data(cur, query, data) # Write data to txt file. if rows is not None: file = open(""error_report.txt"", ""w"") for row in rows: file.write(""{} - {}% errors \n"".format(row[0], row[1])) file.close() return True else: return False","{'deleted': [{'line_no': 20, 'char_start': 684, 'char_end': 731, 'line': ' / log_requests.total::numeric > {}\n'}, {'line_no': 21, 'char_start': 731, 'char_end': 793, 'line': "" ORDER BY log_errors.date'''.format(error_percent)\n""}, {'line_no': 22, 'char_start': 793, 'char_end': 825, 'line': ' rows = get_data(cur, query)\n'}], 'added': [{'line_no': 14, 'char_start': 384, 'char_end': 413, 'line': ' data = (error_percent, )\n'}, {'line_no': 21, 'char_start': 713, 'char_end': 760, 'line': ' / log_requests.total::numeric > %s\n'}, {'line_no': 22, 'char_start': 760, 'char_end': 800, 'line': "" ORDER BY log_errors.date'''\n""}, {'line_no': 23, 'char_start': 800, 'char_end': 838, 'line': ' rows = get_data(cur, query, data)\n'}]}","{'deleted': [{'char_start': 728, 'char_end': 730, 'chars': '{}'}, {'char_start': 770, 'char_end': 792, 'chars': '.format(error_percent)'}], 'added': [{'char_start': 388, 'char_end': 417, 'chars': 'data = (error_percent, )\n '}, {'char_start': 757, 'char_end': 759, 'chars': '%s'}, {'char_start': 830, 'char_end': 836, 'chars': ', data'}]}",github.com/rrbiz662/log-analysis/commit/20fefbde3738088586a3c5679f743493d0a504f6,news_data_analysis.py,cwe-089,249 cwe-125,set_fdc,"static void set_fdc(int drive) { if (drive >= 0 && drive < N_DRIVE) { fdc = FDC(drive); current_drive = drive; } if (fdc != 1 && fdc != 0) { pr_info(""bad fdc value\n""); return; } set_dor(fdc, ~0, 8); #if N_FDC > 1 set_dor(1 - fdc, ~8, 0); #endif if (FDCS->rawcmd == 2) reset_fdc_info(1); if (fd_inb(FD_STATUS) != STATUS_READY) FDCS->reset = 1; }","static void set_fdc(int drive) { unsigned int new_fdc = fdc; if (drive >= 0 && drive < N_DRIVE) { new_fdc = FDC(drive); current_drive = drive; } if (new_fdc >= N_FDC) { pr_info(""bad fdc value\n""); return; } fdc = new_fdc; set_dor(fdc, ~0, 8); #if N_FDC > 1 set_dor(1 - fdc, ~8, 0); #endif if (FDCS->rawcmd == 2) reset_fdc_info(1); if (fd_inb(FD_STATUS) != STATUS_READY) FDCS->reset = 1; }","{'deleted': [{'line_no': 4, 'char_start': 71, 'char_end': 91, 'line': '\t\tfdc = FDC(drive);\n'}, {'line_no': 7, 'char_start': 119, 'char_end': 148, 'line': '\tif (fdc != 1 && fdc != 0) {\n'}], 'added': [{'line_no': 3, 'char_start': 33, 'char_end': 62, 'line': '\tunsigned int new_fdc = fdc;\n'}, {'line_no': 4, 'char_start': 62, 'char_end': 63, 'line': '\n'}, {'line_no': 6, 'char_start': 101, 'char_end': 125, 'line': '\t\tnew_fdc = FDC(drive);\n'}, {'line_no': 9, 'char_start': 153, 'char_end': 178, 'line': '\tif (new_fdc >= N_FDC) {\n'}, {'line_no': 13, 'char_start': 221, 'char_end': 237, 'line': '\tfdc = new_fdc;\n'}]}","{'deleted': [{'char_start': 128, 'char_end': 129, 'chars': '!'}, {'char_start': 131, 'char_end': 144, 'chars': '1 && fdc != 0'}], 'added': [{'char_start': 34, 'char_end': 64, 'chars': 'unsigned int new_fdc = fdc;\n\n\t'}, {'char_start': 103, 'char_end': 107, 'chars': 'new_'}, {'char_start': 158, 'char_end': 162, 'chars': 'new_'}, {'char_start': 166, 'char_end': 167, 'chars': '>'}, {'char_start': 169, 'char_end': 174, 'chars': 'N_FDC'}, {'char_start': 220, 'char_end': 236, 'chars': '\n\tfdc = new_fdc;'}]}",github.com/torvalds/linux/commit/2e90ca68b0d2f5548804f22f0dd61145516171e3,drivers/block/floppy.c,cwe-125,149 cwe-089,change_message," def change_message(self, new_message, logged_user): update_sql = """""" UPDATE Clients SET message = '{}' WHERE client_id = '{}' """""".format(new_message, logged_user.get_client_id()) cursor = self.__conn.cursor() cursor.execute(update_sql) self.__conn.commit() logged_user.set_message(new_message)"," def change_message(self, new_message, logged_user): update_sql = """""" UPDATE Clients SET message = ? WHERE client_id = ? """""" cursor = self.__conn.cursor() cursor.execute(update_sql, (new_message, logged_user.get_client_id())) self.__conn.commit() logged_user.set_message(new_message)","{'deleted': [{'line_no': 4, 'char_start': 108, 'char_end': 139, 'line': "" SET message = '{}'\n""}, {'line_no': 5, 'char_start': 139, 'char_end': 174, 'line': "" WHERE client_id = '{}'\n""}, {'line_no': 6, 'char_start': 174, 'char_end': 235, 'line': ' """""".format(new_message, logged_user.get_client_id())\n'}, {'line_no': 10, 'char_start': 275, 'char_end': 310, 'line': ' cursor.execute(update_sql)\n'}], 'added': [{'line_no': 4, 'char_start': 108, 'char_end': 136, 'line': ' SET message = ?\n'}, {'line_no': 5, 'char_start': 136, 'char_end': 168, 'line': ' WHERE client_id = ?\n'}, {'line_no': 6, 'char_start': 168, 'char_end': 180, 'line': ' """"""\n'}, {'line_no': 10, 'char_start': 220, 'char_end': 299, 'line': ' cursor.execute(update_sql, (new_message, logged_user.get_client_id()))\n'}]}","{'deleted': [{'char_start': 134, 'char_end': 138, 'chars': ""'{}'""}, {'char_start': 169, 'char_end': 173, 'chars': ""'{}'""}, {'char_start': 185, 'char_end': 234, 'chars': '.format(new_message, logged_user.get_client_id())'}], 'added': [{'char_start': 134, 'char_end': 135, 'chars': '?'}, {'char_start': 166, 'char_end': 167, 'chars': '?'}, {'char_start': 253, 'char_end': 297, 'chars': ', (new_message, logged_user.get_client_id())'}]}",github.com/AnetaStoycheva/Programming101_HackBulgaria/commit/c0d6f4b8fe83a375832845a45952b5153e4c34f3,Week_9/sql_manager.py,cwe-089,74 cwe-089,get_bracket_graph_data,"def get_bracket_graph_data(db, tag): # First, we have to find out which scenes this player has brackets in sql = ""SELECT DISTINCT scene FROM ranks WHERE player='{}'"".format(tag) scenes = db.exec(sql) scenes = [s[0] for s in scenes] bracket_placings_by_scene = {s: get_bracket_placings_in_scene(db, s, tag) for s in scenes} return bracket_placings_by_scene","def get_bracket_graph_data(db, tag): # First, we have to find out which scenes this player has brackets in sql = ""SELECT DISTINCT scene FROM ranks WHERE player='{tag}'"" args = {'tag': tag} scenes = db.exec(sql, args) scenes = [s[0] for s in scenes] bracket_placings_by_scene = {s: get_bracket_placings_in_scene(db, s, tag) for s in scenes} return bracket_placings_by_scene","{'deleted': [{'line_no': 3, 'char_start': 111, 'char_end': 186, 'line': ' sql = ""SELECT DISTINCT scene FROM ranks WHERE player=\'{}\'"".format(tag)\n'}, {'line_no': 4, 'char_start': 186, 'char_end': 212, 'line': ' scenes = db.exec(sql)\n'}], 'added': [{'line_no': 3, 'char_start': 111, 'char_end': 177, 'line': ' sql = ""SELECT DISTINCT scene FROM ranks WHERE player=\'{tag}\'""\n'}, {'line_no': 4, 'char_start': 177, 'char_end': 201, 'line': "" args = {'tag': tag}\n""}, {'line_no': 5, 'char_start': 201, 'char_end': 233, 'line': ' scenes = db.exec(sql, args)\n'}]}","{'deleted': [{'char_start': 173, 'char_end': 176, 'chars': '.fo'}, {'char_start': 177, 'char_end': 178, 'chars': 'm'}, {'char_start': 179, 'char_end': 181, 'chars': 't('}, {'char_start': 184, 'char_end': 185, 'chars': ')'}], 'added': [{'char_start': 170, 'char_end': 173, 'chars': 'tag'}, {'char_start': 176, 'char_end': 182, 'chars': '\n a'}, {'char_start': 183, 'char_end': 190, 'chars': ""gs = {'""}, {'char_start': 191, 'char_end': 196, 'chars': ""ag': ""}, {'char_start': 199, 'char_end': 200, 'chars': '}'}, {'char_start': 225, 'char_end': 231, 'chars': ', args'}]}",github.com/DKelle/Smash_stats/commit/4bb83f3f6ce7d6bebbeb512cd015f9e72cf36d63,bracket_utils.py,cwe-089,103 cwe-125,DecompressRTF,"BYTE *DecompressRTF(variableLength *p, int *size) { BYTE *dst; // destination for uncompressed bytes BYTE *src; unsigned int in; unsigned int out; variableLength comp_Prebuf; ULONG compressedSize, uncompressedSize, magic; comp_Prebuf.size = strlen(RTF_PREBUF); comp_Prebuf.data = calloc(comp_Prebuf.size+1, 1); ALLOCCHECK_CHAR(comp_Prebuf.data); memcpy(comp_Prebuf.data, RTF_PREBUF, comp_Prebuf.size); src = p->data; in = 0; if (p->size < 20) { printf(""File too small\n""); return(NULL); } compressedSize = (ULONG)SwapDWord((BYTE*)src + in, 4); in += 4; uncompressedSize = (ULONG)SwapDWord((BYTE*)src + in, 4); in += 4; magic = SwapDWord((BYTE*)src + in, 4); in += 4; in += 4; // check size excluding the size field itself if (compressedSize != p->size - 4) { printf("" Size Mismatch: %u != %i\n"", compressedSize, p->size - 4); free(comp_Prebuf.data); return NULL; } // process the data if (magic == 0x414c454d) { // magic number that identifies the stream as a uncompressed stream dst = calloc(uncompressedSize, 1); ALLOCCHECK_CHAR(dst); memcpy(dst, src + 4, uncompressedSize); } else if (magic == 0x75465a4c) { // magic number that identifies the stream as a compressed stream int flagCount = 0; int flags = 0; // Prevent overflow on 32 Bit Systems if (comp_Prebuf.size >= INT_MAX - uncompressedSize) { printf(""Corrupted file\n""); exit(-1); } dst = calloc(comp_Prebuf.size + uncompressedSize, 1); ALLOCCHECK_CHAR(dst); memcpy(dst, comp_Prebuf.data, comp_Prebuf.size); out = comp_Prebuf.size; while (out < (comp_Prebuf.size + uncompressedSize)) { // each flag byte flags 8 literals/references, 1 per bit flags = (flagCount++ % 8 == 0) ? src[in++] : flags >> 1; if ((flags & 1) == 1) { // each flag bit is 1 for reference, 0 for literal unsigned int offset = src[in++]; unsigned int length = src[in++]; unsigned int end; offset = (offset << 4) | (length >> 4); // the offset relative to block start length = (length & 0xF) + 2; // the number of bytes to copy // the decompression buffer is supposed to wrap around back // to the beginning when the end is reached. we save the // need for such a buffer by pointing straight into the data // buffer, and simulating this behaviour by modifying the // pointers appropriately. offset = (out / 4096) * 4096 + offset; if (offset >= out) // take from previous block offset -= 4096; // note: can't use System.arraycopy, because the referenced // bytes can cross through the current out position. end = offset + length; while ((offset < end) && (out < (comp_Prebuf.size + uncompressedSize)) && (offset < (comp_Prebuf.size + uncompressedSize))) dst[out++] = dst[offset++]; } else { // literal if ((out >= (comp_Prebuf.size + uncompressedSize)) || (in >= p->size)) { printf(""Corrupted stream\n""); exit(-1); } dst[out++] = src[in++]; } } // copy it back without the prebuffered data src = dst; dst = calloc(uncompressedSize, 1); ALLOCCHECK_CHAR(dst); memcpy(dst, src + comp_Prebuf.size, uncompressedSize); free(src); *size = uncompressedSize; free(comp_Prebuf.data); return dst; } else { // unknown magic number printf(""Unknown compression type (magic number %x)\n"", magic); } free(comp_Prebuf.data); return NULL; }","BYTE *DecompressRTF(variableLength *p, int *size) { BYTE *dst; // destination for uncompressed bytes BYTE *src; unsigned int in; unsigned int out; variableLength comp_Prebuf; ULONG compressedSize, uncompressedSize, magic; comp_Prebuf.size = strlen(RTF_PREBUF); comp_Prebuf.data = calloc(comp_Prebuf.size+1, 1); ALLOCCHECK_CHAR(comp_Prebuf.data); memcpy(comp_Prebuf.data, RTF_PREBUF, comp_Prebuf.size); src = p->data; in = 0; if (p->size < 20) { printf(""File too small\n""); return(NULL); } compressedSize = (ULONG)SwapDWord((BYTE*)src + in, 4); in += 4; uncompressedSize = (ULONG)SwapDWord((BYTE*)src + in, 4); in += 4; magic = SwapDWord((BYTE*)src + in, 4); in += 4; in += 4; // check size excluding the size field itself if (compressedSize != p->size - 4) { printf("" Size Mismatch: %u != %i\n"", compressedSize, p->size - 4); free(comp_Prebuf.data); return NULL; } // process the data if (magic == 0x414c454d) { // magic number that identifies the stream as a uncompressed stream dst = calloc(uncompressedSize, 1); ALLOCCHECK_CHAR(dst); memcpy(dst, src + 4, uncompressedSize); } else if (magic == 0x75465a4c) { // magic number that identifies the stream as a compressed stream int flagCount = 0; int flags = 0; // Prevent overflow on 32 Bit Systems if (comp_Prebuf.size >= INT_MAX - uncompressedSize) { printf(""Corrupted file\n""); exit(-1); } dst = calloc(comp_Prebuf.size + uncompressedSize, 1); ALLOCCHECK_CHAR(dst); memcpy(dst, comp_Prebuf.data, comp_Prebuf.size); out = comp_Prebuf.size; while ((out < (comp_Prebuf.size + uncompressedSize)) && (in < p->size)) { // each flag byte flags 8 literals/references, 1 per bit flags = (flagCount++ % 8 == 0) ? src[in++] : flags >> 1; if ((flags & 1) == 1) { // each flag bit is 1 for reference, 0 for literal unsigned int offset = src[in++]; unsigned int length = src[in++]; unsigned int end; offset = (offset << 4) | (length >> 4); // the offset relative to block start length = (length & 0xF) + 2; // the number of bytes to copy // the decompression buffer is supposed to wrap around back // to the beginning when the end is reached. we save the // need for such a buffer by pointing straight into the data // buffer, and simulating this behaviour by modifying the // pointers appropriately. offset = (out / 4096) * 4096 + offset; if (offset >= out) // take from previous block offset -= 4096; // note: can't use System.arraycopy, because the referenced // bytes can cross through the current out position. end = offset + length; while ((offset < end) && (out < (comp_Prebuf.size + uncompressedSize)) && (offset < (comp_Prebuf.size + uncompressedSize))) dst[out++] = dst[offset++]; } else { // literal if ((out >= (comp_Prebuf.size + uncompressedSize)) || (in >= p->size)) { printf(""Corrupted stream\n""); exit(-1); } dst[out++] = src[in++]; } } // copy it back without the prebuffered data src = dst; dst = calloc(uncompressedSize, 1); ALLOCCHECK_CHAR(dst); memcpy(dst, src + comp_Prebuf.size, uncompressedSize); free(src); *size = uncompressedSize; free(comp_Prebuf.data); return dst; } else { // unknown magic number printf(""Unknown compression type (magic number %x)\n"", magic); } free(comp_Prebuf.data); return NULL; }","{'deleted': [{'line_no': 55, 'char_start': 1641, 'char_end': 1699, 'line': ' while (out < (comp_Prebuf.size + uncompressedSize)) {\n'}], 'added': [{'line_no': 55, 'char_start': 1641, 'char_end': 1719, 'line': ' while ((out < (comp_Prebuf.size + uncompressedSize)) && (in < p->size)) {\n'}]}","{'deleted': [], 'added': [{'char_start': 1652, 'char_end': 1653, 'chars': '('}, {'char_start': 1692, 'char_end': 1711, 'chars': 'ize)) && (in < p->s'}]}",github.com/Yeraze/ytnef/commit/22f8346c8d4f0020a40d9f258fdb3bfc097359cc,lib/ytnef.c,cwe-125,996 cwe-022,candidate_paths_for_url," def candidate_paths_for_url(self, url): for root, prefix in self.directories: if url.startswith(prefix): yield os.path.join(root, url[len(prefix):])"," def candidate_paths_for_url(self, url): for root, prefix in self.directories: if url.startswith(prefix): path = os.path.join(root, url[len(prefix):]) if os.path.commonprefix((root, path)) == root: yield path","{'deleted': [{'line_no': 4, 'char_start': 129, 'char_end': 188, 'line': ' yield os.path.join(root, url[len(prefix):])\n'}], 'added': [{'line_no': 4, 'char_start': 129, 'char_end': 190, 'line': ' path = os.path.join(root, url[len(prefix):])\n'}, {'line_no': 5, 'char_start': 190, 'char_end': 253, 'line': ' if os.path.commonprefix((root, path)) == root:\n'}, {'line_no': 6, 'char_start': 253, 'char_end': 283, 'line': ' yield path\n'}]}","{'deleted': [{'char_start': 145, 'char_end': 150, 'chars': 'yield'}], 'added': [{'char_start': 145, 'char_end': 151, 'chars': 'path ='}, {'char_start': 189, 'char_end': 283, 'chars': '\n if os.path.commonprefix((root, path)) == root:\n yield path'}]}",github.com/evansd/whitenoise/commit/4d8a3ab1e97d7ddb18b3fa8b4909c92bad5529c6,whitenoise/base.py,cwe-022,38 cwe-089,login,"@app.route('/', methods=['POST']) def login(): print('login') user = str(request.form['username']) password = str(request.form['password']) cur.execute('SELECT * FROM users WHERE name = \'{}\' AND password = \'{}\';'.format(user, password)) response = cur.fetchone() if response != None: print(response, 'OK') return redirect(url_for('enter_test_point')) else: print(response, 'not OK') flash('Invalid login or password') return render_template('login.html')","@app.route('/', methods=['POST']) def login(): print('login') user = str(request.form['username']) password = str(request.form['password']) cur.execute(""SELECT * FROM users WHERE name = ? AND password = ?;"", [user, password]) response = cur.fetchone() if response != None: print(response, 'OK') return redirect(url_for('enter_test_point')) else: print(response, 'not OK') flash('Invalid login or password') return render_template('login.html')","{'deleted': [{'line_no': 6, 'char_start': 152, 'char_end': 257, 'line': "" cur.execute('SELECT * FROM users WHERE name = \\'{}\\' AND password = \\'{}\\';'.format(user, password))\n""}], 'added': [{'line_no': 6, 'char_start': 152, 'char_end': 242, 'line': ' cur.execute(""SELECT * FROM users WHERE name = ? AND password = ?;"", [user, password])\n'}]}","{'deleted': [{'char_start': 168, 'char_end': 169, 'chars': ""'""}, {'char_start': 202, 'char_end': 208, 'chars': ""\\'{}\\'""}, {'char_start': 224, 'char_end': 230, 'chars': ""\\'{}\\'""}, {'char_start': 231, 'char_end': 240, 'chars': ""'.format(""}, {'char_start': 254, 'char_end': 255, 'chars': ')'}], 'added': [{'char_start': 168, 'char_end': 169, 'chars': '""'}, {'char_start': 202, 'char_end': 203, 'chars': '?'}, {'char_start': 219, 'char_end': 220, 'chars': '?'}, {'char_start': 221, 'char_end': 225, 'chars': '"", ['}, {'char_start': 239, 'char_end': 240, 'chars': ']'}]}",github.com/ChemiKyle/Waterspots/commit/3f9d5099496336f3f34c48abf0cf55acaaa29011,app.py,cwe-089,115 cwe-022,addKey,"def addKey(client): """"""Adds a new key with the specified name and contents. Returns an error if a key with the specified name already exists. """""" global BAD_REQUEST global CREATED validateClient(client) client_pub_key = loadClientRSAKey(client) token_data = decodeRequestToken(request.data, client_pub_key) validateNewKeyData(token_data) # Use 'x' flag so we can throw an error if a key with this name already exists try: with open('keys/%s/%s.key' % (client, token_data['name']), 'x') as f: f.write(token_data['key']) except FileExistsError: raise FoxlockError(BAD_REQUEST, ""Key '%s' already exists"" % token_data['name']) return 'Key successfully created', CREATED","def addKey(client): """"""Adds a new key with the specified name and contents. Returns an error if a key with the specified name already exists. """""" global BAD_REQUEST global CREATED validateClient(client) client_pub_key = loadClientRSAKey(client) token_data = decodeRequestToken(request.data, client_pub_key) validateNewKeyData(token_data) validateKeyName(token_data['name']) # Use 'x' flag so we can throw an error if a key with this name already exists try: with open('keys/%s/%s.key' % (client, token_data['name']), 'x') as f: f.write(token_data['key']) except FileExistsError: raise FoxlockError(BAD_REQUEST, ""Key '%s' already exists"" % token_data['name']) return 'Key successfully created', CREATED","{'deleted': [{'line_no': 9, 'char_start': 210, 'char_end': 211, 'line': '\n'}], 'added': [{'line_no': 12, 'char_start': 348, 'char_end': 385, 'line': ""\tvalidateKeyName(token_data['name'])\n""}]}","{'deleted': [{'char_start': 210, 'char_end': 211, 'chars': '\n'}], 'added': [{'char_start': 346, 'char_end': 383, 'chars': "")\n\tvalidateKeyName(token_data['name']""}]}",github.com/Mimickal/FoxLock/commit/7c665e556987f4e2c1a75e143a1e80ae066ad833,impl.py,cwe-022,169 cwe-089,top_karma,"def top_karma(bot, trigger): """""" Show karma status for the top n number of IRC users. """""" try: top_limit = int(trigger.group(2).strip()) except ValueError: top_limit = 5 query = ""SELECT slug, value FROM nick_values NATURAL JOIN nicknames \ WHERE key = 'karma' ORDER BY value DESC LIMIT %d"" karmalist = bot.db.execute(query % top_limit).fetchall() for user in karmalist: bot.say(""%s == %s"" % (user[0], user[1]))","def top_karma(bot, trigger): """""" Show karma status for the top n number of IRC users. """""" try: top_limit = int(trigger.group(2).strip()) except ValueError: top_limit = 5 query = ""SELECT slug, value FROM nick_values NATURAL JOIN nicknames \ WHERE key = 'karma' ORDER BY value DESC LIMIT ?"" karmalist = bot.db.execute(query, str(top_limit)).fetchall() for user in karmalist: bot.say(""%s == %s"" % (user[0], user[1]))","{'deleted': [{'line_no': 11, 'char_start': 281, 'char_end': 339, 'line': ' WHERE key = \'karma\' ORDER BY value DESC LIMIT %d""\n'}, {'line_no': 12, 'char_start': 339, 'char_end': 400, 'line': ' karmalist = bot.db.execute(query % top_limit).fetchall()\n'}], 'added': [{'line_no': 11, 'char_start': 281, 'char_end': 338, 'line': ' WHERE key = \'karma\' ORDER BY value DESC LIMIT ?""\n'}, {'line_no': 12, 'char_start': 338, 'char_end': 403, 'line': ' karmalist = bot.db.execute(query, str(top_limit)).fetchall()\n'}]}","{'deleted': [{'char_start': 335, 'char_end': 337, 'chars': '%d'}, {'char_start': 376, 'char_end': 378, 'chars': '% '}], 'added': [{'char_start': 335, 'char_end': 336, 'chars': '?'}, {'char_start': 374, 'char_end': 375, 'chars': ','}, {'char_start': 376, 'char_end': 380, 'chars': 'str('}, {'char_start': 389, 'char_end': 390, 'chars': ')'}]}",github.com/OpCode1300/sopel-karma/commit/e4d49f7b3d88f8874c7862392f3f4c2065a25695,sopel_modules/karma/karma.py,cwe-089,127 cwe-476,imcb_file_send_start,"file_transfer_t *imcb_file_send_start(struct im_connection *ic, char *handle, char *file_name, size_t file_size) { bee_t *bee = ic->bee; bee_user_t *bu = bee_user_by_handle(bee, ic, handle); if (bee->ui->ft_in_start) { return bee->ui->ft_in_start(bee, bu, file_name, file_size); } else { return NULL; } }","file_transfer_t *imcb_file_send_start(struct im_connection *ic, char *handle, char *file_name, size_t file_size) { bee_t *bee = ic->bee; bee_user_t *bu = bee_user_by_handle(bee, ic, handle); if (bee->ui->ft_in_start && bu) { return bee->ui->ft_in_start(bee, bu, file_name, file_size); } else { return NULL; } }","{'deleted': [{'line_no': 6, 'char_start': 194, 'char_end': 223, 'line': '\tif (bee->ui->ft_in_start) {\n'}], 'added': [{'line_no': 6, 'char_start': 194, 'char_end': 229, 'line': '\tif (bee->ui->ft_in_start && bu) {\n'}]}","{'deleted': [], 'added': [{'char_start': 219, 'char_end': 225, 'chars': ' && bu'}]}",github.com/bitlbee/bitlbee/commit/701ab8129ba9ea64f569daedca9a8603abad740f,protocols/bee_ft.c,cwe-476,100 cwe-787,TiledInputFile::rawTileData,"TiledInputFile::rawTileData (int &dx, int &dy, int &lx, int &ly, const char *&pixelData, int &pixelDataSize) { try { Lock lock (*_data->_streamData); if (!isValidTile (dx, dy, lx, ly)) throw IEX_NAMESPACE::ArgExc (""Tried to read a tile outside "" ""the image file's data window.""); TileBuffer *tileBuffer = _data->getTileBuffer (0); // // if file is a multipart file, we have to seek to the required tile // since we don't know where the file pointer is // int old_dx=dx; int old_dy=dy; int old_lx=lx; int old_ly=ly; if(isMultiPart(version())) { _data->_streamData->is->seekg(_data->tileOffsets(dx,dy,lx,ly)); } readNextTileData (_data->_streamData, _data, dx, dy, lx, ly, tileBuffer->buffer, pixelDataSize); if(isMultiPart(version())) { if (old_dx!=dx || old_dy !=dy || old_lx!=lx || old_ly!=ly) { throw IEX_NAMESPACE::ArgExc (""rawTileData read the wrong tile""); } } pixelData = tileBuffer->buffer; } catch (IEX_NAMESPACE::BaseExc &e) { REPLACE_EXC (e, ""Error reading pixel data from image "" ""file \"""" << fileName() << ""\"". "" << e.what()); throw; } }","TiledInputFile::rawTileData (int &dx, int &dy, int &lx, int &ly, const char *&pixelData, int &pixelDataSize) { try { Lock lock (*_data->_streamData); if (!isValidTile (dx, dy, lx, ly)) throw IEX_NAMESPACE::ArgExc (""Tried to read a tile outside "" ""the image file's data window.""); TileBuffer *tileBuffer = _data->getTileBuffer (0); // // if file is a multipart file, we have to seek to the required tile // since we don't know where the file pointer is // int old_dx=dx; int old_dy=dy; int old_lx=lx; int old_ly=ly; if(isMultiPart(version())) { _data->_streamData->is->seekg(_data->tileOffsets(dx,dy,lx,ly)); } readNextTileData (_data->_streamData, _data, dx, dy, lx, ly, tileBuffer->buffer, pixelDataSize); if(isMultiPart(version())) { if (old_dx!=dx || old_dy !=dy || old_lx!=lx || old_ly!=ly) { throw IEX_NAMESPACE::ArgExc (""rawTileData read the wrong tile""); } } else { if(!isValidTile (dx, dy, lx, ly) ) { throw IEX_NAMESPACE::IoExc (""rawTileData read an invalid tile""); } } pixelData = tileBuffer->buffer; } catch (IEX_NAMESPACE::BaseExc &e) { REPLACE_EXC (e, ""Error reading pixel data from image "" ""file \"""" << fileName() << ""\"". "" << e.what()); throw; } }","{'deleted': [], 'added': [{'line_no': 38, 'char_start': 1183, 'char_end': 1196, 'line': ' else\n'}, {'line_no': 39, 'char_start': 1196, 'char_end': 1206, 'line': ' {\n'}, {'line_no': 40, 'char_start': 1206, 'char_end': 1254, 'line': ' if(!isValidTile (dx, dy, lx, ly) )\n'}, {'line_no': 41, 'char_start': 1254, 'char_end': 1269, 'line': ' {\n'}, {'line_no': 42, 'char_start': 1269, 'char_end': 1351, 'line': ' throw IEX_NAMESPACE::IoExc (""rawTileData read an invalid tile"");\n'}, {'line_no': 43, 'char_start': 1351, 'char_end': 1366, 'line': ' }\n'}, {'line_no': 44, 'char_start': 1366, 'char_end': 1376, 'line': ' }\n'}]}","{'deleted': [], 'added': [{'char_start': 1191, 'char_end': 1384, 'chars': 'else\n {\n if(!isValidTile (dx, dy, lx, ly) )\n {\n throw IEX_NAMESPACE::IoExc (""rawTileData read an invalid tile"");\n }\n }\n '}]}",github.com/AcademySoftwareFoundation/openexr/commit/6bb36714528a9563dd3b92720c5063a1284b86f8,OpenEXR/IlmImf/ImfTiledInputFile.cpp,cwe-787,361 cwe-089,getQueue," def getQueue(self, numberOfLinks=10): self.cursor.execute(""SELECT url FROM queue WHERE visited = '0' LIMIT {};"".format(numberOfLinks)) result = self.cursor.fetchall() self.remove(result) return result"," def getQueue(self, numberOfLinks=10): self.cursor.execute(""SELECT url FROM queue WHERE visited = '0' LIMIT ?;"", numberOfLinks) result = self.cursor.fetchall() self.remove(result) return result","{'deleted': [{'line_no': 2, 'char_start': 42, 'char_end': 147, 'line': ' self.cursor.execute(""SELECT url FROM queue WHERE visited = \'0\' LIMIT {};"".format(numberOfLinks))\n'}], 'added': [{'line_no': 2, 'char_start': 42, 'char_end': 139, 'line': ' self.cursor.execute(""SELECT url FROM queue WHERE visited = \'0\' LIMIT ?;"", numberOfLinks)\n'}]}","{'deleted': [{'char_start': 119, 'char_end': 121, 'chars': '{}'}, {'char_start': 123, 'char_end': 131, 'chars': '.format('}, {'char_start': 144, 'char_end': 145, 'chars': ')'}], 'added': [{'char_start': 119, 'char_end': 120, 'chars': '?'}, {'char_start': 122, 'char_end': 124, 'chars': ', '}]}",github.com/jappe999/WebScraper/commit/46a4e0843aa44d903293637afad53dfcbc37b480,beta/database.py,cwe-089,50 cwe-476,r_pkcs7_parse_cms,"RCMS *r_pkcs7_parse_cms (const ut8 *buffer, ut32 length) { RASN1Object *object; RCMS *container; if (!buffer || !length) { return NULL; } container = R_NEW0 (RCMS); if (!container) { return NULL; } object = r_asn1_create_object (buffer, length); if (!object || object->list.length != 2 || !object->list.objects[0] || object->list.objects[1]->list.length != 1) { r_asn1_free_object (object); free (container); return NULL; } container->contentType = r_asn1_stringify_oid (object->list.objects[0]->sector, object->list.objects[0]->length); r_pkcs7_parse_signeddata (&container->signedData, object->list.objects[1]->list.objects[0]); r_asn1_free_object (object); return container; }","RCMS *r_pkcs7_parse_cms (const ut8 *buffer, ut32 length) { RASN1Object *object; RCMS *container; if (!buffer || !length) { return NULL; } container = R_NEW0 (RCMS); if (!container) { return NULL; } object = r_asn1_create_object (buffer, length); if (!object || object->list.length != 2 || !object->list.objects || !object->list.objects[0] || !object->list.objects[1] || object->list.objects[1]->list.length != 1) { r_asn1_free_object (object); free (container); return NULL; } container->contentType = r_asn1_stringify_oid (object->list.objects[0]->sector, object->list.objects[0]->length); r_pkcs7_parse_signeddata (&container->signedData, object->list.objects[1]->list.objects[0]); r_asn1_free_object (object); return container; }","{'deleted': [{'line_no': 12, 'char_start': 258, 'char_end': 375, 'line': '\tif (!object || object->list.length != 2 || !object->list.objects[0] || object->list.objects[1]->list.length != 1) {\n'}], 'added': [{'line_no': 12, 'char_start': 258, 'char_end': 327, 'line': '\tif (!object || object->list.length != 2 || !object->list.objects ||\n'}, {'line_no': 13, 'char_start': 327, 'char_end': 385, 'line': '\t\t!object->list.objects[0] || !object->list.objects[1] ||\n'}, {'line_no': 14, 'char_start': 385, 'char_end': 432, 'line': '\t\tobject->list.objects[1]->list.length != 1) {\n'}]}","{'deleted': [], 'added': [{'char_start': 323, 'char_end': 350, 'chars': ' ||\n\t\t!object->list.objects'}, {'char_start': 357, 'char_end': 387, 'chars': '!object->list.objects[1] ||\n\t\t'}]}",github.com/radare/radare2/commit/7ab66cca5bbdf6cb2d69339ef4f513d95e532dbf,libr/util/r_pkcs7.c,cwe-476,207 cwe-089,add_post,"def add_post(content): """"""Add a post to the 'database' with the current timestamp."""""" conn = psycopg2.connect(""dbname=forum"") cursor = conn.cursor() cursor.execute(""insert into posts values ('%s')"" % content) conn.commit() conn.close()","def add_post(content): """"""Add a post to the 'database' with the current timestamp."""""" conn = psycopg2.connect(""dbname=forum"") cursor = conn.cursor() one_post = content cursor.execute(""insert into posts values (%s)"", (one_post,)) conn.commit() conn.close()","{'deleted': [{'line_no': 5, 'char_start': 155, 'char_end': 217, 'line': ' cursor.execute(""insert into posts values (\'%s\')"" % content)\n'}], 'added': [{'line_no': 5, 'char_start': 155, 'char_end': 176, 'line': ' one_post = content\n'}, {'line_no': 6, 'char_start': 176, 'char_end': 239, 'line': ' cursor.execute(""insert into posts values (%s)"", (one_post,))\n'}]}","{'deleted': [{'char_start': 199, 'char_end': 200, 'chars': ""'""}, {'char_start': 202, 'char_end': 203, 'chars': ""'""}, {'char_start': 205, 'char_end': 207, 'chars': ' %'}, {'char_start': 208, 'char_end': 209, 'chars': 'c'}, {'char_start': 211, 'char_end': 212, 'chars': 't'}, {'char_start': 213, 'char_end': 214, 'chars': 'n'}], 'added': [{'char_start': 157, 'char_end': 178, 'chars': 'one_post = content\n '}, {'char_start': 224, 'char_end': 225, 'chars': ','}, {'char_start': 226, 'char_end': 227, 'chars': '('}, {'char_start': 230, 'char_end': 234, 'chars': '_pos'}, {'char_start': 235, 'char_end': 237, 'chars': ',)'}]}",github.com/paulc1600/DB-API-Forum/commit/069700fb4beec79182fff3c556e9cccce3230d6f,forumdb.py,cwe-089,60 cwe-125,voutf,"static void voutf(struct GlobalConfig *config, const char *prefix, const char *fmt, va_list ap) { size_t width = (79 - strlen(prefix)); if(!config->mute) { size_t len; char *ptr; char *print_buffer; print_buffer = curlx_mvaprintf(fmt, ap); if(!print_buffer) return; len = strlen(print_buffer); ptr = print_buffer; while(len > 0) { fputs(prefix, config->errors); if(len > width) { size_t cut = width-1; while(!ISSPACE(ptr[cut]) && cut) { cut--; } if(0 == cut) /* not a single cutting position was found, just cut it at the max text width then! */ cut = width-1; (void)fwrite(ptr, cut + 1, 1, config->errors); fputs(""\n"", config->errors); ptr += cut + 1; /* skip the space too */ len -= cut; } else { fputs(ptr, config->errors); len = 0; } } curl_free(print_buffer); } }","static void voutf(struct GlobalConfig *config, const char *prefix, const char *fmt, va_list ap) { size_t width = (79 - strlen(prefix)); if(!config->mute) { size_t len; char *ptr; char *print_buffer; print_buffer = curlx_mvaprintf(fmt, ap); if(!print_buffer) return; len = strlen(print_buffer); ptr = print_buffer; while(len > 0) { fputs(prefix, config->errors); if(len > width) { size_t cut = width-1; while(!ISSPACE(ptr[cut]) && cut) { cut--; } if(0 == cut) /* not a single cutting position was found, just cut it at the max text width then! */ cut = width-1; (void)fwrite(ptr, cut + 1, 1, config->errors); fputs(""\n"", config->errors); ptr += cut + 1; /* skip the space too */ len -= cut + 1; } else { fputs(ptr, config->errors); len = 0; } } curl_free(print_buffer); } }","{'deleted': [{'line_no': 35, 'char_start': 890, 'char_end': 910, 'line': ' len -= cut;\n'}], 'added': [{'line_no': 35, 'char_start': 890, 'char_end': 914, 'line': ' len -= cut + 1;\n'}]}","{'deleted': [], 'added': [{'char_start': 908, 'char_end': 912, 'chars': ' + 1'}]}",github.com/curl/curl/commit/d530e92f59ae9bb2d47066c3c460b25d2ffeb211,src/tool_msgs.c,cwe-125,267 cwe-078,_remove_volume_from_volume_set," def _remove_volume_from_volume_set(self, volume_name, vvs_name): self._cli_run('removevvset -f %s %s' % (vvs_name, volume_name), None)"," def _remove_volume_from_volume_set(self, volume_name, vvs_name): self._cli_run(['removevvset', '-f', vvs_name, volume_name])","{'deleted': [{'line_no': 2, 'char_start': 69, 'char_end': 146, 'line': "" self._cli_run('removevvset -f %s %s' % (vvs_name, volume_name), None)\n""}], 'added': [{'line_no': 2, 'char_start': 69, 'char_end': 136, 'line': "" self._cli_run(['removevvset', '-f', vvs_name, volume_name])\n""}]}","{'deleted': [{'char_start': 106, 'char_end': 112, 'chars': ' %s %s'}, {'char_start': 113, 'char_end': 115, 'chars': ' %'}, {'char_start': 116, 'char_end': 117, 'chars': '('}, {'char_start': 138, 'char_end': 145, 'chars': '), None'}], 'added': [{'char_start': 91, 'char_end': 92, 'chars': '['}, {'char_start': 104, 'char_end': 106, 'chars': ""',""}, {'char_start': 107, 'char_end': 108, 'chars': ""'""}, {'char_start': 111, 'char_end': 112, 'chars': ','}, {'char_start': 134, 'char_end': 135, 'chars': ']'}]}",github.com/thatsdone/cinder/commit/c55589b131828f3a595903f6796cb2d0babb772f,cinder/volume/drivers/san/hp/hp_3par_common.py,cwe-078,44 cwe-416,shadow_server_start,"int shadow_server_start(rdpShadowServer* server) { BOOL ipc; BOOL status; WSADATA wsaData; if (!server) return -1; if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) return -1; #ifndef _WIN32 signal(SIGPIPE, SIG_IGN); #endif server->screen = shadow_screen_new(server); if (!server->screen) { WLog_ERR(TAG, ""screen_new failed""); return -1; } server->capture = shadow_capture_new(server); if (!server->capture) { WLog_ERR(TAG, ""capture_new failed""); return -1; } /* Bind magic: * * emtpy ... bind TCP all * ... bind local (IPC) * bind-socket,
... bind TCP to specified interface */ ipc = server->ipcSocket && (strncmp(bind_address, server->ipcSocket, strnlen(bind_address, sizeof(bind_address))) != 0); if (!ipc) { size_t x, count; char** list = CommandLineParseCommaSeparatedValuesEx(NULL, server->ipcSocket, &count); if (!list || (count <= 1)) { free(list); if (server->ipcSocket == NULL) { if (!open_port(server, NULL)) return -1; } else return -1; } for (x = 1; x < count; x++) { BOOL success = open_port(server, list[x]); if (!success) { free(list); return -1; } } free(list); } else { status = server->listener->OpenLocal(server->listener, server->ipcSocket); if (!status) { WLog_ERR(TAG, ""Problem creating local socket listener. (Port already used or "" ""insufficient permissions?)""); return -1; } } if (!(server->thread = CreateThread(NULL, 0, shadow_server_thread, (void*)server, 0, NULL))) { return -1; } return 0; }","int shadow_server_start(rdpShadowServer* server) { BOOL ipc; BOOL status; WSADATA wsaData; if (!server) return -1; if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) return -1; #ifndef _WIN32 signal(SIGPIPE, SIG_IGN); #endif server->screen = shadow_screen_new(server); if (!server->screen) { WLog_ERR(TAG, ""screen_new failed""); return -1; } server->capture = shadow_capture_new(server); if (!server->capture) { WLog_ERR(TAG, ""capture_new failed""); return -1; } /* Bind magic: * * emtpy ... bind TCP all * ... bind local (IPC) * bind-socket,
... bind TCP to specified interface */ ipc = server->ipcSocket && (strncmp(bind_address, server->ipcSocket, strnlen(bind_address, sizeof(bind_address))) != 0); if (!ipc) { size_t x, count; char** list = CommandLineParseCommaSeparatedValuesEx(NULL, server->ipcSocket, &count); if (!list || (count <= 1)) { if (server->ipcSocket == NULL) { if (!open_port(server, NULL)) { free(list); return -1; } } else { free(list); return -1; } } for (x = 1; x < count; x++) { BOOL success = open_port(server, list[x]); if (!success) { free(list); return -1; } } free(list); } else { status = server->listener->OpenLocal(server->listener, server->ipcSocket); if (!status) { WLog_ERR(TAG, ""Problem creating local socket listener. (Port already used or "" ""insufficient permissions?)""); return -1; } } if (!(server->thread = CreateThread(NULL, 0, shadow_server_thread, (void*)server, 0, NULL))) { return -1; } return 0; }","{'deleted': [{'line_no': 46, 'char_start': 981, 'char_end': 996, 'line': '\t\t\tfree(list);\n'}], 'added': [{'line_no': 49, 'char_start': 1054, 'char_end': 1060, 'line': '\t\t\t\t{\n'}, {'line_no': 50, 'char_start': 1060, 'char_end': 1077, 'line': '\t\t\t\t\tfree(list);\n'}, {'line_no': 52, 'char_start': 1093, 'char_end': 1099, 'line': '\t\t\t\t}\n'}, {'line_no': 55, 'char_start': 1112, 'char_end': 1117, 'line': '\t\t\t{\n'}, {'line_no': 56, 'char_start': 1117, 'char_end': 1133, 'line': '\t\t\t\tfree(list);\n'}, {'line_no': 58, 'char_start': 1148, 'char_end': 1153, 'line': '\t\t\t}\n'}]}","{'deleted': [{'char_start': 984, 'char_end': 999, 'chars': 'free(list);\n\t\t\t'}], 'added': [{'char_start': 1015, 'char_end': 1015, 'chars': ''}, {'char_start': 1054, 'char_end': 1077, 'chars': '\t\t\t\t{\n\t\t\t\t\tfree(list);\n'}, {'char_start': 1093, 'char_end': 1099, 'chars': '\t\t\t\t}\n'}, {'char_start': 1112, 'char_end': 1133, 'chars': '\t\t\t{\n\t\t\t\tfree(list);\n'}, {'char_start': 1147, 'char_end': 1152, 'chars': '\n\t\t\t}'}]}",github.com/FreeRDP/FreeRDP/commit/6d86e20e1e7caaab4f0c7f89e36d32914dbccc52,server/shadow/shadow_server.c,cwe-416,488 cwe-089,save_page_edit,"@app.route('//save', methods=['POST']) def save_page_edit(page_name): # grab the new content from the user content = request.form.get('content') # check if 'page_name' exists in the database query = db.query(""select page_content.content, page.id as page_id, page_content.id as content_id from page, page_content where page.id = page_content.page_id and page.page_name = '%s' order by page_content.id desc limit 1"" % page_name) result = query.namedresult() # if it doesn't exist, create a new page in the database if len(result) < 1: db.insert( 'page', { 'page_name': page_name } ) else: pass # now that we're certain that the page exists in the database, we again grab the query # and insert new content in the database query = db.query(""select id from page where page_name = '%s'"" % page_name) page_id = query.namedresult()[0].id db.insert( 'page_content', { 'page_id': page_id, 'content': content, 'timestamp': time.strftime(""%Y-%m-%d %H:%M:%S"", localtime()) } ) return redirect(""/%s"" % page_name)","@app.route('//save', methods=['POST']) def save_page_edit(page_name): # grab the new content from the user content = request.form.get('content') # check if 'page_name' exists in the database query = db.query(""select page_content.content, page.id as page_id, page_content.id as content_id from page, page_content where page.id = page_content.page_id and page.page_name = $1 order by page_content.id desc limit 1"", page_name) result = query.namedresult() # if it doesn't exist, create a new page in the database if len(result) < 1: db.insert( 'page', { 'page_name': page_name } ) else: pass # now that we're certain that the page exists in the database, we again grab the query # and insert new content in the database query = db.query(""select id from page where page_name = '%s'"" % page_name) page_id = query.namedresult()[0].id db.insert( 'page_content', { 'page_id': page_id, 'content': content, 'timestamp': time.strftime(""%Y-%m-%d %H:%M:%S"", localtime()) } ) return redirect(""/%s"" % page_name)","{'deleted': [{'line_no': 6, 'char_start': 214, 'char_end': 454, 'line': ' query = db.query(""select page_content.content, page.id as page_id, page_content.id as content_id from page, page_content where page.id = page_content.page_id and page.page_name = \'%s\' order by page_content.id desc limit 1"" % page_name)\n'}], 'added': [{'line_no': 6, 'char_start': 214, 'char_end': 451, 'line': ' query = db.query(""select page_content.content, page.id as page_id, page_content.id as content_id from page, page_content where page.id = page_content.page_id and page.page_name = $1 order by page_content.id desc limit 1"", page_name)\n'}]}","{'deleted': [{'char_start': 397, 'char_end': 401, 'chars': ""'%s'""}, {'char_start': 440, 'char_end': 442, 'chars': ' %'}], 'added': [{'char_start': 397, 'char_end': 399, 'chars': '$1'}, {'char_start': 438, 'char_end': 439, 'chars': ','}]}",github.com/Pumala/python_wiki_app_redo/commit/65d60747cd8efb05970304234d3bd949d2088e8b,server.py,cwe-089,293 cwe-125,ImagingPcxDecode,"ImagingPcxDecode(Imaging im, ImagingCodecState state, UINT8* buf, Py_ssize_t bytes) { UINT8 n; UINT8* ptr; if ((state->xsize * state->bits + 7) / 8 > state->bytes) { state->errcode = IMAGING_CODEC_OVERRUN; return -1; } ptr = buf; for (;;) { if (bytes < 1) return ptr - buf; if ((*ptr & 0xC0) == 0xC0) { /* Run */ if (bytes < 2) return ptr - buf; n = ptr[0] & 0x3F; while (n > 0) { if (state->x >= state->bytes) { state->errcode = IMAGING_CODEC_OVERRUN; break; } state->buffer[state->x++] = ptr[1]; n--; } ptr += 2; bytes -= 2; } else { /* Literal */ state->buffer[state->x++] = ptr[0]; ptr++; bytes--; } if (state->x >= state->bytes) { if (state->bytes % state->xsize && state->bytes > state->xsize) { int bands = state->bytes / state->xsize; int stride = state->bytes / bands; int i; for (i=1; i< bands; i++) { // note -- skipping first band memmove(&state->buffer[i*state->xsize], &state->buffer[i*stride], state->xsize); } } /* Got a full line, unpack it */ state->shuffle((UINT8*) im->image[state->y + state->yoff] + state->xoff * im->pixelsize, state->buffer, state->xsize); state->x = 0; if (++state->y >= state->ysize) { /* End of file (errcode = 0) */ return -1; } } } }","ImagingPcxDecode(Imaging im, ImagingCodecState state, UINT8* buf, Py_ssize_t bytes) { UINT8 n; UINT8* ptr; if ((state->xsize * state->bits + 7) / 8 > state->bytes) { state->errcode = IMAGING_CODEC_OVERRUN; return -1; } ptr = buf; for (;;) { if (bytes < 1) return ptr - buf; if ((*ptr & 0xC0) == 0xC0) { /* Run */ if (bytes < 2) return ptr - buf; n = ptr[0] & 0x3F; while (n > 0) { if (state->x >= state->bytes) { state->errcode = IMAGING_CODEC_OVERRUN; break; } state->buffer[state->x++] = ptr[1]; n--; } ptr += 2; bytes -= 2; } else { /* Literal */ state->buffer[state->x++] = ptr[0]; ptr++; bytes--; } if (state->x >= state->bytes) { if (state->bytes % state->xsize && state->bytes > state->xsize) { int bands = state->bytes / state->xsize; int stride = state->bytes / bands; int i; for (i=1; i< bands; i++) { // note -- skipping first band memmove(&state->buffer[i*state->xsize], &state->buffer[i*stride], state->xsize); } } /* Got a full line, unpack it */ state->shuffle((UINT8*) im->image[state->y + state->yoff] + state->xoff * im->pixelsize, state->buffer, state->xsize); state->x = 0; if (++state->y >= state->ysize) { /* End of file (errcode = 0) */ return -1; } } } }","{'deleted': [{'line_no': 6, 'char_start': 116, 'char_end': 179, 'line': ' if (strcmp(im->mode, ""1"") == 0 && state->xsize > state->bytes * 8) {\n'}, {'line_no': 7, 'char_start': 179, 'char_end': 227, 'line': ' state->errcode = IMAGING_CODEC_OVERRUN;\n'}, {'line_no': 8, 'char_start': 227, 'char_end': 246, 'line': ' return -1;\n'}, {'line_no': 9, 'char_start': 246, 'char_end': 252, 'line': ' } else if (strcmp(im->mode, ""P"") == 0 && state->xsize > state->bytes) {\n'}], 'added': [{'line_no': 6, 'char_start': 116, 'char_end': 179, 'line': ' if ((state->xsize * state->bits + 7) / 8 > state->bytes) {\n'}]}","{'deleted': [], 'added': []}",github.com/python-pillow/Pillow/commit/6a83e4324738bb0452fbe8074a995b1c73f08de7#diff-9478f2787e3ae9668a15123b165c23ac,src/libImaging/PcxDecode.c,cwe-125,462 cwe-079,oidc_handle_session_management_iframe_rp,"static int oidc_handle_session_management_iframe_rp(request_rec *r, oidc_cfg *c, oidc_session_t *session, const char *client_id, const char *check_session_iframe) { oidc_debug(r, ""enter""); const char *java_script = "" \n""; /* determine the origin for the check_session_iframe endpoint */ char *origin = apr_pstrdup(r->pool, check_session_iframe); apr_uri_t uri; apr_uri_parse(r->pool, check_session_iframe, &uri); char *p = strstr(origin, uri.path); *p = '\0'; /* the element identifier for the OP iframe */ const char *op_iframe_id = ""openidc-op""; /* restore the OP session_state from the session */ const char *session_state = oidc_session_get_session_state(r, session); if (session_state == NULL) { oidc_warn(r, ""no session_state found in the session; the OP does probably not support session management!?""); return DONE; } char *s_poll_interval = NULL; oidc_util_get_request_parameter(r, ""poll"", &s_poll_interval); if (s_poll_interval == NULL) s_poll_interval = ""3000""; const char *redirect_uri = oidc_get_redirect_uri(r, c); java_script = apr_psprintf(r->pool, java_script, origin, client_id, session_state, op_iframe_id, s_poll_interval, redirect_uri, redirect_uri); return oidc_util_html_send(r, NULL, java_script, ""setTimer"", NULL, DONE); }","static int oidc_handle_session_management_iframe_rp(request_rec *r, oidc_cfg *c, oidc_session_t *session, const char *client_id, const char *check_session_iframe) { oidc_debug(r, ""enter""); const char *java_script = "" \n""; /* determine the origin for the check_session_iframe endpoint */ char *origin = apr_pstrdup(r->pool, check_session_iframe); apr_uri_t uri; apr_uri_parse(r->pool, check_session_iframe, &uri); char *p = strstr(origin, uri.path); *p = '\0'; /* the element identifier for the OP iframe */ const char *op_iframe_id = ""openidc-op""; /* restore the OP session_state from the session */ const char *session_state = oidc_session_get_session_state(r, session); if (session_state == NULL) { oidc_warn(r, ""no session_state found in the session; the OP does probably not support session management!?""); return DONE; } char *s_poll_interval = NULL; oidc_util_get_request_parameter(r, ""poll"", &s_poll_interval); int poll_interval = s_poll_interval ? strtol(s_poll_interval, NULL, 10) : 0; if ((poll_interval <= 0) || (poll_interval > 3600 * 24)) poll_interval = 3000; const char *redirect_uri = oidc_get_redirect_uri(r, c); java_script = apr_psprintf(r->pool, java_script, origin, client_id, session_state, op_iframe_id, poll_interval, redirect_uri, redirect_uri); return oidc_util_html_send(r, NULL, java_script, ""setTimer"", NULL, DONE); }","{'deleted': [{'line_no': 21, 'char_start': 743, 'char_end': 803, 'line': '\t\t\t"" timerID = setInterval(\'checkSession()\', %s);\\n""\n'}, {'line_no': 64, 'char_start': 2273, 'char_end': 2303, 'line': '\tif (s_poll_interval == NULL)\n'}, {'line_no': 65, 'char_start': 2303, 'char_end': 2331, 'line': '\t\ts_poll_interval = ""3000"";\n'}, {'line_no': 69, 'char_start': 2458, 'char_end': 2521, 'line': '\t\t\tsession_state, op_iframe_id, s_poll_interval, redirect_uri,\n'}], 'added': [{'line_no': 21, 'char_start': 743, 'char_end': 803, 'line': '\t\t\t"" timerID = setInterval(\'checkSession()\', %d);\\n""\n'}, {'line_no': 64, 'char_start': 2273, 'char_end': 2351, 'line': '\tint poll_interval = s_poll_interval ? strtol(s_poll_interval, NULL, 10) : 0;\n'}, {'line_no': 65, 'char_start': 2351, 'char_end': 2409, 'line': '\tif ((poll_interval <= 0) || (poll_interval > 3600 * 24))\n'}, {'line_no': 66, 'char_start': 2409, 'char_end': 2433, 'line': '\t\tpoll_interval = 3000;\n'}, {'line_no': 70, 'char_start': 2560, 'char_end': 2621, 'line': '\t\t\tsession_state, op_iframe_id, poll_interval, redirect_uri,\n'}]}","{'deleted': [{'char_start': 796, 'char_end': 797, 'chars': 's'}, {'char_start': 2275, 'char_end': 2276, 'chars': 'f'}, {'char_start': 2293, 'char_end': 2296, 'chars': ' =='}, {'char_start': 2304, 'char_end': 2306, 'chars': '\ts'}, {'char_start': 2323, 'char_end': 2324, 'chars': '""'}, {'char_start': 2328, 'char_end': 2329, 'chars': '""'}, {'char_start': 2490, 'char_end': 2492, 'chars': 's_'}], 'added': [{'char_start': 796, 'char_end': 797, 'chars': 'd'}, {'char_start': 2275, 'char_end': 2291, 'chars': 'nt poll_interval'}, {'char_start': 2292, 'char_end': 2294, 'chars': '= '}, {'char_start': 2310, 'char_end': 2335, 'chars': '? strtol(s_poll_interval,'}, {'char_start': 2340, 'char_end': 2344, 'chars': ', 10'}, {'char_start': 2345, 'char_end': 2350, 'chars': ' : 0;'}, {'char_start': 2352, 'char_end': 2361, 'chars': 'if ((poll'}, {'char_start': 2362, 'char_end': 2411, 'chars': 'interval <= 0) || (poll_interval > 3600 * 24))\n\t\t'}]}",github.com/zmartzone/mod_auth_openidc/commit/132a4111bf3791e76437619a66336dce2ce4c79b,src/mod_auth_openidc.c,cwe-079,760 cwe-416,PlayerGeneric::~PlayerGeneric,"PlayerGeneric::~PlayerGeneric() { if (mixer) delete mixer; if (player) { if (mixer->isActive() && !mixer->isDeviceRemoved(player)) mixer->removeDevice(player); delete player; } delete[] audioDriverName; delete listener; }","PlayerGeneric::~PlayerGeneric() { if (player) { if (mixer && mixer->isActive() && !mixer->isDeviceRemoved(player)) mixer->removeDevice(player); delete player; } if (mixer) delete mixer; delete[] audioDriverName; delete listener; }","{'deleted': [{'line_no': 3, 'char_start': 34, 'char_end': 46, 'line': '\tif (mixer)\n'}, {'line_no': 4, 'char_start': 46, 'char_end': 62, 'line': '\t\tdelete mixer;\n'}, {'line_no': 8, 'char_start': 79, 'char_end': 139, 'line': '\t\tif (mixer->isActive() && !mixer->isDeviceRemoved(player))\n'}], 'added': [{'line_no': 6, 'char_start': 51, 'char_end': 120, 'line': '\t\tif (mixer && mixer->isActive() && !mixer->isDeviceRemoved(player))\n'}, {'line_no': 10, 'char_start': 172, 'char_end': 174, 'line': '\t\n'}, {'line_no': 11, 'char_start': 174, 'char_end': 186, 'line': '\tif (mixer)\n'}, {'line_no': 12, 'char_start': 186, 'char_end': 202, 'line': '\t\tdelete mixer;\n'}]}","{'deleted': [{'char_start': 34, 'char_end': 62, 'chars': '\tif (mixer)\n\t\tdelete mixer;\n'}], 'added': [{'char_start': 57, 'char_end': 66, 'chars': 'mixer && '}, {'char_start': 171, 'char_end': 201, 'chars': '\n\t\n\tif (mixer)\n\t\tdelete mixer;'}]}",github.com/milkytracker/MilkyTracker/commit/7afd55c42ad80d01a339197a2d8b5461d214edaf,src/milkyplay/PlayerGeneric.cpp,cwe-416,65 cwe-089,getOptions,"def getOptions(poll_name): conn, c = connectDB() options_str = queryOne(c, ""SELECT options FROM {} WHERE name='{}'"".format(CFG(""poll_table_name""), poll_name)) if options_str == None: return None options = options_str.split("","") closeDB(conn) return options","def getOptions(poll_name): conn, c = connectDB() req = ""SELECT options FROM {} WHERE name=?"".format(CFG(""poll_table_name"")) options_str = queryOne(c, req, (poll_name,)) if options_str == None: return None options = options_str.split("","") closeDB(conn) return options","{'deleted': [{'line_no': 3, 'char_start': 53, 'char_end': 167, 'line': ' options_str = queryOne(c, ""SELECT options FROM {} WHERE name=\'{}\'"".format(CFG(""poll_table_name""), poll_name))\n'}], 'added': [{'line_no': 3, 'char_start': 53, 'char_end': 132, 'line': ' req = ""SELECT options FROM {} WHERE name=?"".format(CFG(""poll_table_name""))\n'}, {'line_no': 4, 'char_start': 132, 'char_end': 181, 'line': ' options_str = queryOne(c, req, (poll_name,))\n'}]}","{'deleted': [{'char_start': 57, 'char_end': 67, 'chars': 'options_st'}, {'char_start': 71, 'char_end': 83, 'chars': 'queryOne(c, '}, {'char_start': 118, 'char_end': 122, 'chars': ""'{}'""}], 'added': [{'char_start': 58, 'char_end': 60, 'chars': 'eq'}, {'char_start': 98, 'char_end': 99, 'chars': '?'}, {'char_start': 130, 'char_end': 160, 'chars': ')\n options_str = queryOne(c'}, {'char_start': 162, 'char_end': 168, 'chars': 'req, ('}, {'char_start': 177, 'char_end': 178, 'chars': ','}]}",github.com/FAUSheppy/simple-python-poll/commit/186c5ff5cdf58272e253a1bb432419ee50d93109,database.py,cwe-089,71 cwe-079,json_dumps,"@register.filter def json_dumps(value, indent=None): if isinstance(value, QuerySet): result = serialize('json', value, indent=indent) else: result = json.dumps(value, indent=indent, cls=DjbletsJSONEncoder) return mark_safe(result)","@register.filter def json_dumps(value, indent=None): if isinstance(value, QuerySet): result = serialize('json', value, indent=indent) else: result = json.dumps(value, indent=indent, cls=DjbletsJSONEncoder) return mark_safe(force_text(result).translate(_safe_js_escapes))","{'deleted': [{'line_no': 8, 'char_start': 231, 'char_end': 259, 'line': ' return mark_safe(result)\n'}], 'added': [{'line_no': 8, 'char_start': 231, 'char_end': 299, 'line': ' return mark_safe(force_text(result).translate(_safe_js_escapes))\n'}]}","{'deleted': [], 'added': [{'char_start': 252, 'char_end': 263, 'chars': 'force_text('}, {'char_start': 270, 'char_end': 299, 'chars': '.translate(_safe_js_escapes))'}]}",github.com/djblets/djblets/commit/77a68c03cd619a0996f3f37337b8c39ca6643d6e,djblets/util/templatetags/djblets_js.py,cwe-079,61 cwe-078,get_logs,"@app.route('/api/uploads//logs') def get_logs(sid): if '/' not in sid: path = os.path.join(app.config['UPLOAD_FOLDER'], sid) if os.path.isfile(os.path.join(path, app.config['LOG_FILE'])): return send_from_directory(directory=path, filename=app.config['LOG_FILE']) else: abort(404) else: abort(403)","@app.route('/api/uploads//logs') def get_logs(sid): if utils.sid_is_valid(sid): path = join(app.config['UPLOAD_FOLDER'], sid) if os.path.isfile(join(path, app.config['LOG_FILE'])): return send_from_directory(directory=path, filename=app.config['LOG_FILE']) else: abort(404) else: abort(404)","{'deleted': [{'line_no': 3, 'char_start': 57, 'char_end': 80, 'line': "" if '/' not in sid:\n""}, {'line_no': 4, 'char_start': 80, 'char_end': 142, 'line': "" path = os.path.join(app.config['UPLOAD_FOLDER'], sid)\n""}, {'line_no': 5, 'char_start': 142, 'char_end': 213, 'line': "" if os.path.isfile(os.path.join(path, app.config['LOG_FILE'])):\n""}, {'line_no': 11, 'char_start': 388, 'char_end': 406, 'line': ' abort(403)\n'}], 'added': [{'line_no': 3, 'char_start': 57, 'char_end': 89, 'line': ' if utils.sid_is_valid(sid):\n'}, {'line_no': 4, 'char_start': 89, 'char_end': 143, 'line': "" path = join(app.config['UPLOAD_FOLDER'], sid)\n""}, {'line_no': 5, 'char_start': 143, 'char_end': 144, 'line': '\n'}, {'line_no': 6, 'char_start': 144, 'char_end': 207, 'line': "" if os.path.isfile(join(path, app.config['LOG_FILE'])):\n""}, {'line_no': 12, 'char_start': 382, 'char_end': 400, 'line': ' abort(404)\n'}]}","{'deleted': [{'char_start': 64, 'char_end': 70, 'chars': ""'/' no""}, {'char_start': 71, 'char_end': 72, 'chars': ' '}, {'char_start': 73, 'char_end': 75, 'chars': 'n '}, {'char_start': 95, 'char_end': 103, 'chars': 'os.path.'}, {'char_start': 168, 'char_end': 176, 'chars': 'os.path.'}, {'char_start': 404, 'char_end': 405, 'chars': '3'}], 'added': [{'char_start': 64, 'char_end': 65, 'chars': 'u'}, {'char_start': 66, 'char_end': 80, 'chars': 'ils.sid_is_val'}, {'char_start': 81, 'char_end': 83, 'chars': 'd('}, {'char_start': 86, 'char_end': 87, 'chars': ')'}, {'char_start': 143, 'char_end': 144, 'chars': '\n'}, {'char_start': 398, 'char_end': 399, 'chars': '4'}]}",github.com/cheukyin699/genset-demo-site/commit/abb55b1a6786b0a995c2cdf77a7977a1d51cfc0d,app/views.py,cwe-078,90 cwe-089,search_pages,"@app.route(""/search"", methods = [""POST""]) def search_pages(): search = request.form.get(""search"") page = db.query(""select title from page where title = '%s'"" % search).namedresult() if len(page) == 0: return redirect(""/%s"" % search) else: return place_holder(search)","@app.route(""/search"", methods = [""POST""]) def search_pages(): search = request.form.get(""search"") page = db.query(""select title from page where title = $1"", search).namedresult() if len(page) == 0: return redirect(""/%s"" % search) else: return place_holder(search)","{'deleted': [{'line_no': 4, 'char_start': 102, 'char_end': 190, 'line': ' page = db.query(""select title from page where title = \'%s\'"" % search).namedresult()\n'}], 'added': [{'line_no': 4, 'char_start': 102, 'char_end': 187, 'line': ' page = db.query(""select title from page where title = $1"", search).namedresult()\n'}]}","{'deleted': [{'char_start': 160, 'char_end': 164, 'chars': ""'%s'""}, {'char_start': 165, 'char_end': 167, 'chars': ' %'}], 'added': [{'char_start': 160, 'char_end': 162, 'chars': '$1'}, {'char_start': 163, 'char_end': 164, 'chars': ','}]}",github.com/jcortes0309/wiki_flask/commit/a6bf5316abe2eb528adf36c8241a013fd02c5ffa,server.py,cwe-089,73 cwe-089,update_date_modified," def update_date_modified(self): sql = ""UPDATE jdk_entries "" + \ ""SET date_last_modified = "" + CURRENT_DATESTAMP + "" "" + \ ""WHERE jdk_entries.id = '"" + self.entry_id + ""';"" db_execute(sql) return None"," def update_date_modified(self): quote_tuple = CURRENT_DATESTAMP, self.entry_id sql = ""UPDATE jdk_entries "" + \ ""SET date_last_modified = ? "" + \ ""WHERE jdk_entries.id = ?;"" db_execute(sql, quote_tuple) return None","{'deleted': [{'line_no': 3, 'char_start': 70, 'char_end': 134, 'line': ' ""SET date_last_modified = "" + CURRENT_DATESTAMP + "" "" + \\\n'}, {'line_no': 4, 'char_start': 134, 'char_end': 190, 'line': ' ""WHERE jdk_entries.id = \'"" + self.entry_id + ""\';""\n'}, {'line_no': 6, 'char_start': 195, 'char_end': 215, 'line': ' db_execute(sql)\n'}], 'added': [{'line_no': 2, 'char_start': 34, 'char_end': 85, 'line': ' quote_tuple = CURRENT_DATESTAMP, self.entry_id\n'}, {'line_no': 3, 'char_start': 85, 'char_end': 86, 'line': '\n'}, {'line_no': 5, 'char_start': 122, 'char_end': 162, 'line': ' ""SET date_last_modified = ? "" + \\\n'}, {'line_no': 6, 'char_start': 162, 'char_end': 196, 'line': ' ""WHERE jdk_entries.id = ?;""\n'}, {'line_no': 8, 'char_start': 201, 'char_end': 234, 'line': ' db_execute(sql, quote_tuple)\n'}]}","{'deleted': [{'char_start': 102, 'char_end': 127, 'chars': '"" + CURRENT_DATESTAMP + ""'}, {'char_start': 164, 'char_end': 187, 'chars': '\'"" + self.entry_id + ""\''}], 'added': [{'char_start': 38, 'char_end': 90, 'chars': 'quote_tuple = CURRENT_DATESTAMP, self.entry_id\n\n '}, {'char_start': 154, 'char_end': 155, 'chars': '?'}, {'char_start': 192, 'char_end': 193, 'chars': '?'}, {'char_start': 219, 'char_end': 232, 'chars': ', quote_tuple'}]}",github.com/peterlebrun/jdk/commit/000238566fbe55ba09676c3d57af04ae207235ae,entry.py,cwe-089,62 cwe-078,_get_hostvdisk_mappings," def _get_hostvdisk_mappings(self, host_name): """"""Return the defined storage mappings for a host."""""" return_data = {} ssh_cmd = 'svcinfo lshostvdiskmap -delim ! %s' % host_name out, err = self._run_ssh(ssh_cmd) mappings = out.strip().split('\n') if len(mappings): header = mappings.pop(0) for mapping_line in mappings: mapping_data = self._get_hdr_dic(header, mapping_line, '!') return_data[mapping_data['vdisk_name']] = mapping_data return return_data"," def _get_hostvdisk_mappings(self, host_name): """"""Return the defined storage mappings for a host."""""" return_data = {} ssh_cmd = ['svcinfo', 'lshostvdiskmap', '-delim', '!', host_name] out, err = self._run_ssh(ssh_cmd) mappings = out.strip().split('\n') if len(mappings): header = mappings.pop(0) for mapping_line in mappings: mapping_data = self._get_hdr_dic(header, mapping_line, '!') return_data[mapping_data['vdisk_name']] = mapping_data return return_data","{'deleted': [{'line_no': 5, 'char_start': 138, 'char_end': 205, 'line': "" ssh_cmd = 'svcinfo lshostvdiskmap -delim ! %s' % host_name\n""}], 'added': [{'line_no': 5, 'char_start': 138, 'char_end': 212, 'line': "" ssh_cmd = ['svcinfo', 'lshostvdiskmap', '-delim', '!', host_name]\n""}]}","{'deleted': [{'char_start': 188, 'char_end': 191, 'chars': ' %s'}, {'char_start': 192, 'char_end': 194, 'chars': ' %'}], 'added': [{'char_start': 156, 'char_end': 157, 'chars': '['}, {'char_start': 165, 'char_end': 167, 'chars': ""',""}, {'char_start': 168, 'char_end': 169, 'chars': ""'""}, {'char_start': 183, 'char_end': 185, 'chars': ""',""}, {'char_start': 186, 'char_end': 187, 'chars': ""'""}, {'char_start': 193, 'char_end': 195, 'chars': ""',""}, {'char_start': 196, 'char_end': 197, 'chars': ""'""}, {'char_start': 199, 'char_end': 200, 'chars': ','}, {'char_start': 210, 'char_end': 211, 'chars': ']'}]}",github.com/thatsdone/cinder/commit/f752302d181583a95cf44354aea607ce9d9283f4,cinder/volume/drivers/storwize_svc.py,cwe-078,132 cwe-125,HPHP::JSON_parser,"bool JSON_parser(Variant &z, const char *p, int length, bool const assoc, int depth, int64_t options) { // No GC safepoints during JSON parsing, please. Code is not re-entrant. NoHandleSurpriseScope no_surprise(SafepointFlags); json_parser *json = s_json_parser.get(); /* the parser state */ // Clear and reuse the thread-local string buffers. They are only freed if // they exceed kMaxPersistentStringBufferCapacity at exit or if the thread // is explicitly flushed (e.g., due to being idle). json->initSb(length); SCOPE_EXIT { constexpr int kMaxPersistentStringBufferCapacity = 256 * 1024; if (json->sb_cap > kMaxPersistentStringBufferCapacity) json->flushSb(); }; // SimpleParser only handles the most common set of options. Also, only use it // if its array nesting depth check is *more* restrictive than what the user // asks for, to ensure that the precise semantics of the general case is // applied for all nesting overflows. if (assoc && options == (options & (k_JSON_FB_LOOSE | k_JSON_FB_DARRAYS | k_JSON_FB_DARRAYS_AND_VARRAYS | k_JSON_FB_HACK_ARRAYS | k_JSON_FB_THRIFT_SIMPLE_JSON | k_JSON_FB_LEGACY_HACK_ARRAYS)) && depth >= SimpleParser::kMaxArrayDepth && length <= RuntimeOption::EvalSimpleJsonMaxLength && SimpleParser::TryParse(p, length, json->tl_buffer.tv, z, get_container_type_from_options(options), options & k_JSON_FB_THRIFT_SIMPLE_JSON)) { return true; } int b; /* the next character */ int c; /* the next character class */ int s; /* the next state */ int state = 0; /**/ bool const loose = options & k_JSON_FB_LOOSE; JSONContainerType const container_type = get_container_type_from_options(options); int qchr = 0; int8_t const *byte_class; int8_t const (*next_state_table)[32]; if (loose) { byte_class = loose_ascii_class; next_state_table = loose_state_transition_table; } else { byte_class = ascii_class; next_state_table = state_transition_table; } /**/ UncheckedBuffer *buf = &json->sb_buf; UncheckedBuffer *key = &json->sb_key; DataType type = kInvalidDataType; unsigned short escaped_bytes = 0; auto reset_type = [&] { type = kInvalidDataType; }; json->depth = depth; // Since the stack is maintainined on a per request basis, for performance // reasons, it only makes sense to expand if necessary and cycles are wasted // contracting. Calls with a depth other than default should be rare. if (depth > json->stack.size()) { json->stack.resize(depth); } SCOPE_EXIT { if (json->stack.empty()) return; for (int i = 0; i <= json->mark; i++) { json->stack[i].key.reset(); json->stack[i].val.unset(); } json->mark = -1; }; json->mark = json->top = -1; push(json, Mode::DONE); UTF8To16Decoder decoder(p, length, loose); for (;;) { b = decoder.decode(); // Fast-case most common transition: append a simple string character. if (state == 3 && type == KindOfString) { while (b != '\""' && b != '\\' && b != '\'' && b <= 127 && b >= ' ') { buf->append((char)b); b = decoder.decode(); } } if (b == UTF8_END) break; // UTF-8 decoding finishes successfully. if (b == UTF8_ERROR) { s_json_parser->error_code = JSON_ERROR_UTF8; return false; } assertx(b >= 0); if ((b & 127) == b) { /**/ c = byte_class[b]; /**/ if (c <= S_ERR) { s_json_parser->error_code = JSON_ERROR_CTRL_CHAR; return false; } } else { c = S_ETC; } /* Get the next state from the transition table. */ /**/ s = next_state_table[state][c]; if (s == -4) { if (b != qchr) { s = 3; } else { qchr = 0; } } /**/ if (s < 0) { /* Perform one of the predefined actions. */ switch (s) { /* empty } */ case -9: /**/ if (json->top == 1) z = json->stack[json->top].val; else { /**/ attach_zval(json, json->stack[json->top].key, assoc, container_type); /**/ } /**/ if (!pop(json, Mode::KEY)) { return false; } state = 9; break; /* { */ case -8: if (!push(json, Mode::KEY)) { s_json_parser->error_code = JSON_ERROR_DEPTH; return false; } state = 1; if (json->top > 0) { Variant &top = json->stack[json->top].val; /**/ if (container_type == JSONContainerType::COLLECTIONS) { // stable_maps is meaningless top = req::make(); } else { /**/ if (!assoc) { top = SystemLib::AllocStdClassObject(); /* */ } else if (container_type == JSONContainerType::HACK_ARRAYS) { top = Array::CreateDict(); } else if (container_type == JSONContainerType::DARRAYS || container_type == JSONContainerType::DARRAYS_AND_VARRAYS) { top = Array::CreateDArray(); /* */ } else if ( container_type == JSONContainerType::LEGACY_HACK_ARRAYS) { auto arr = staticEmptyDictArray()->copy(); arr->setLegacyArray(true); top = arr; } else { top = Array::CreateDArray(); } /**/ } /**/ json->stack[json->top].key = copy_and_clear(*key); reset_type(); } break; /* } */ case -7: /*** BEGIN Facebook: json_utf8_loose ***/ /* If this is a trailing comma in an object definition, we're in Mode::KEY. In that case, throw that off the stack and restore Mode::OBJECT so that we pretend the trailing comma just didn't happen. */ if (loose) { if (pop(json, Mode::KEY)) { push(json, Mode::OBJECT); } } /*** END Facebook: json_utf8_loose ***/ if (type != kInvalidDataType && json->stack[json->top].mode == Mode::OBJECT) { Variant mval; json_create_zval(mval, *buf, type, options); Variant &top = json->stack[json->top].val; object_set(json, top, copy_and_clear(*key), mval, assoc, container_type); buf->clear(); reset_type(); } /**/ if (json->top == 1) z = json->stack[json->top].val; else { /**/ attach_zval(json, json->stack[json->top].key, assoc, container_type); /**/ } /**/ if (!pop(json, Mode::OBJECT)) { s_json_parser->error_code = JSON_ERROR_STATE_MISMATCH; return false; } state = 9; break; /* [ */ case -6: if (!push(json, Mode::ARRAY)) { s_json_parser->error_code = JSON_ERROR_DEPTH; return false; } state = 2; if (json->top > 0) { Variant &top = json->stack[json->top].val; /**/ if (container_type == JSONContainerType::COLLECTIONS) { top = req::make(); } else if (container_type == JSONContainerType::HACK_ARRAYS) { top = Array::CreateVec(); } else if (container_type == JSONContainerType::DARRAYS_AND_VARRAYS) { top = Array::CreateVArray(); } else if (container_type == JSONContainerType::DARRAYS) { top = Array::CreateDArray(); } else if (container_type == JSONContainerType::LEGACY_HACK_ARRAYS) { auto arr = staticEmptyVecArray()->copy(); arr->setLegacyArray(true); top = arr; } else { top = Array::CreateDArray(); } /**/ json->stack[json->top].key = copy_and_clear(*key); reset_type(); } break; /* ] */ case -5: { if (type != kInvalidDataType && json->stack[json->top].mode == Mode::ARRAY) { Variant mval; json_create_zval(mval, *buf, type, options); auto& top = json->stack[json->top].val; if (container_type == JSONContainerType::COLLECTIONS) { collections::append(top.getObjectData(), mval.asTypedValue()); } else { top.asArrRef().append(mval); } buf->clear(); reset_type(); } /**/ if (json->top == 1) z = json->stack[json->top].val; else { /**/ attach_zval(json, json->stack[json->top].key, assoc, container_type); /**/ } /**/ if (!pop(json, Mode::ARRAY)) { s_json_parser->error_code = JSON_ERROR_STATE_MISMATCH; return false; } state = 9; } break; /* "" */ case -4: switch (json->stack[json->top].mode) { case Mode::KEY: state = 27; std::swap(buf, key); reset_type(); break; case Mode::ARRAY: case Mode::OBJECT: state = 9; break; case Mode::DONE: if (type == KindOfString) { z = copy_and_clear(*buf); state = 9; break; } /* fall through if not KindOfString */ default: s_json_parser->error_code = JSON_ERROR_SYNTAX; return false; } break; /* , */ case -3: { Variant mval; if (type != kInvalidDataType && (json->stack[json->top].mode == Mode::OBJECT || json->stack[json->top].mode == Mode::ARRAY)) { json_create_zval(mval, *buf, type, options); } switch (json->stack[json->top].mode) { case Mode::OBJECT: if (pop(json, Mode::OBJECT) && push(json, Mode::KEY)) { if (type != kInvalidDataType) { Variant &top = json->stack[json->top].val; object_set( json, top, copy_and_clear(*key), mval, assoc, container_type ); } state = 29; } break; case Mode::ARRAY: if (type != kInvalidDataType) { auto& top = json->stack[json->top].val; if (container_type == JSONContainerType::COLLECTIONS) { collections::append(top.getObjectData(), mval.asTypedValue()); } else { top.asArrRef().append(mval); } } state = 28; break; default: s_json_parser->error_code = JSON_ERROR_SYNTAX; return false; } buf->clear(); reset_type(); check_non_safepoint_surprise(); } break; /**/ /* : (after unquoted string) */ case -10: if (json->stack[json->top].mode == Mode::KEY) { state = 27; std::swap(buf, key); reset_type(); s = -2; } else { s = 3; break; } /**/ /* : */ case -2: if (pop(json, Mode::KEY) && push(json, Mode::OBJECT)) { state = 28; break; } /* syntax error */ case -1: s_json_parser->error_code = JSON_ERROR_SYNTAX; return false; } } else { /* Change the state and iterate. */ bool is_tsimplejson = options & k_JSON_FB_THRIFT_SIMPLE_JSON; if (type == KindOfString) { if (/**/(/**/s == 3/**/ || s == 30)/**/ && state != 8) { if (state != 4) { utf16_to_utf8(*buf, b); } else { switch (b) { case 'b': buf->append('\b'); break; case 't': buf->append('\t'); break; case 'n': buf->append('\n'); break; case 'f': buf->append('\f'); break; case 'r': buf->append('\r'); break; default: utf16_to_utf8(*buf, b); break; } } } else if (s == 6) { if (UNLIKELY(is_tsimplejson)) { if (UNLIKELY(b != '0')) { s_json_parser->error_code = JSON_ERROR_SYNTAX; return false; } escaped_bytes = 0; } else { escaped_bytes = dehexchar(b) << 12; } } else if (s == 7) { if (UNLIKELY(is_tsimplejson)) { if (UNLIKELY(b != '0')) { s_json_parser->error_code = JSON_ERROR_SYNTAX; return false; } } else { escaped_bytes += dehexchar(b) << 8; } } else if (s == 8) { escaped_bytes += dehexchar(b) << 4; } else if (s == 3 && state == 8) { escaped_bytes += dehexchar(b); if (UNLIKELY(is_tsimplejson)) { buf->append((char)escaped_bytes); } else { utf16_to_utf8(*buf, escaped_bytes); } } } else if ((type == kInvalidDataType || type == KindOfNull) && (c == S_DIG || c == S_ZER)) { type = KindOfInt64; buf->append((char)b); } else if (type == KindOfInt64 && s == 24) { type = KindOfDouble; buf->append((char)b); } else if ((type == kInvalidDataType || type == KindOfNull || type == KindOfInt64) && c == S_DOT) { type = KindOfDouble; buf->append((char)b); } else if (type != KindOfString && c == S_QUO) { type = KindOfString; /**/qchr = b;/**/ } else if ((type == kInvalidDataType || type == KindOfNull || type == KindOfInt64 || type == KindOfDouble) && ((state == 12 && s == 9) || (state == 16 && s == 9))) { type = KindOfBoolean; } else if (type == kInvalidDataType && state == 19 && s == 9) { type = KindOfNull; } else if (type != KindOfString && c > S_WSP) { utf16_to_utf8(*buf, b); } state = s; } } if (state == 9 && pop(json, Mode::DONE)) { s_json_parser->error_code = JSON_ERROR_NONE; return true; } s_json_parser->error_code = JSON_ERROR_SYNTAX; return false; }","bool JSON_parser(Variant &z, const char *p, int length, bool const assoc, int depth, int64_t options) { // No GC safepoints during JSON parsing, please. Code is not re-entrant. NoHandleSurpriseScope no_surprise(SafepointFlags); json_parser *json = s_json_parser.get(); /* the parser state */ // Clear and reuse the thread-local string buffers. They are only freed if // they exceed kMaxPersistentStringBufferCapacity at exit or if the thread // is explicitly flushed (e.g., due to being idle). json->initSb(length); if (depth <= 0) { json->error_code = json_error_codes::JSON_ERROR_DEPTH; return false; } SCOPE_EXIT { constexpr int kMaxPersistentStringBufferCapacity = 256 * 1024; if (json->sb_cap > kMaxPersistentStringBufferCapacity) json->flushSb(); }; // SimpleParser only handles the most common set of options. Also, only use it // if its array nesting depth check is *more* restrictive than what the user // asks for, to ensure that the precise semantics of the general case is // applied for all nesting overflows. if (assoc && options == (options & (k_JSON_FB_LOOSE | k_JSON_FB_DARRAYS | k_JSON_FB_DARRAYS_AND_VARRAYS | k_JSON_FB_HACK_ARRAYS | k_JSON_FB_THRIFT_SIMPLE_JSON | k_JSON_FB_LEGACY_HACK_ARRAYS)) && depth >= SimpleParser::kMaxArrayDepth && length <= RuntimeOption::EvalSimpleJsonMaxLength && SimpleParser::TryParse(p, length, json->tl_buffer.tv, z, get_container_type_from_options(options), options & k_JSON_FB_THRIFT_SIMPLE_JSON)) { return true; } int b; /* the next character */ int c; /* the next character class */ int s; /* the next state */ int state = 0; /**/ bool const loose = options & k_JSON_FB_LOOSE; JSONContainerType const container_type = get_container_type_from_options(options); int qchr = 0; int8_t const *byte_class; int8_t const (*next_state_table)[32]; if (loose) { byte_class = loose_ascii_class; next_state_table = loose_state_transition_table; } else { byte_class = ascii_class; next_state_table = state_transition_table; } /**/ UncheckedBuffer *buf = &json->sb_buf; UncheckedBuffer *key = &json->sb_key; DataType type = kInvalidDataType; unsigned short escaped_bytes = 0; auto reset_type = [&] { type = kInvalidDataType; }; json->depth = depth; // Since the stack is maintainined on a per request basis, for performance // reasons, it only makes sense to expand if necessary and cycles are wasted // contracting. Calls with a depth other than default should be rare. if (depth > json->stack.size()) { json->stack.resize(depth); } SCOPE_EXIT { if (json->stack.empty()) return; for (int i = 0; i <= json->mark; i++) { json->stack[i].key.reset(); json->stack[i].val.unset(); } json->mark = -1; }; json->mark = json->top = -1; push(json, Mode::DONE); UTF8To16Decoder decoder(p, length, loose); for (;;) { b = decoder.decode(); // Fast-case most common transition: append a simple string character. if (state == 3 && type == KindOfString) { while (b != '\""' && b != '\\' && b != '\'' && b <= 127 && b >= ' ') { buf->append((char)b); b = decoder.decode(); } } if (b == UTF8_END) break; // UTF-8 decoding finishes successfully. if (b == UTF8_ERROR) { s_json_parser->error_code = JSON_ERROR_UTF8; return false; } assertx(b >= 0); if ((b & 127) == b) { /**/ c = byte_class[b]; /**/ if (c <= S_ERR) { s_json_parser->error_code = JSON_ERROR_CTRL_CHAR; return false; } } else { c = S_ETC; } /* Get the next state from the transition table. */ /**/ s = next_state_table[state][c]; if (s == -4) { if (b != qchr) { s = 3; } else { qchr = 0; } } /**/ if (s < 0) { /* Perform one of the predefined actions. */ switch (s) { /* empty } */ case -9: /**/ if (json->top == 1) z = json->stack[json->top].val; else { /**/ attach_zval(json, json->stack[json->top].key, assoc, container_type); /**/ } /**/ if (!pop(json, Mode::KEY)) { return false; } state = 9; break; /* { */ case -8: if (!push(json, Mode::KEY)) { s_json_parser->error_code = JSON_ERROR_DEPTH; return false; } state = 1; if (json->top > 0) { Variant &top = json->stack[json->top].val; /**/ if (container_type == JSONContainerType::COLLECTIONS) { // stable_maps is meaningless top = req::make(); } else { /**/ if (!assoc) { top = SystemLib::AllocStdClassObject(); /* */ } else if (container_type == JSONContainerType::HACK_ARRAYS) { top = Array::CreateDict(); } else if (container_type == JSONContainerType::DARRAYS || container_type == JSONContainerType::DARRAYS_AND_VARRAYS) { top = Array::CreateDArray(); /* */ } else if ( container_type == JSONContainerType::LEGACY_HACK_ARRAYS) { auto arr = staticEmptyDictArray()->copy(); arr->setLegacyArray(true); top = arr; } else { top = Array::CreateDArray(); } /**/ } /**/ json->stack[json->top].key = copy_and_clear(*key); reset_type(); } break; /* } */ case -7: /*** BEGIN Facebook: json_utf8_loose ***/ /* If this is a trailing comma in an object definition, we're in Mode::KEY. In that case, throw that off the stack and restore Mode::OBJECT so that we pretend the trailing comma just didn't happen. */ if (loose) { if (pop(json, Mode::KEY)) { push(json, Mode::OBJECT); } } /*** END Facebook: json_utf8_loose ***/ if (type != kInvalidDataType && json->stack[json->top].mode == Mode::OBJECT) { Variant mval; json_create_zval(mval, *buf, type, options); Variant &top = json->stack[json->top].val; object_set(json, top, copy_and_clear(*key), mval, assoc, container_type); buf->clear(); reset_type(); } /**/ if (json->top == 1) z = json->stack[json->top].val; else { /**/ attach_zval(json, json->stack[json->top].key, assoc, container_type); /**/ } /**/ if (!pop(json, Mode::OBJECT)) { s_json_parser->error_code = JSON_ERROR_STATE_MISMATCH; return false; } state = 9; break; /* [ */ case -6: if (!push(json, Mode::ARRAY)) { s_json_parser->error_code = JSON_ERROR_DEPTH; return false; } state = 2; if (json->top > 0) { Variant &top = json->stack[json->top].val; /**/ if (container_type == JSONContainerType::COLLECTIONS) { top = req::make(); } else if (container_type == JSONContainerType::HACK_ARRAYS) { top = Array::CreateVec(); } else if (container_type == JSONContainerType::DARRAYS_AND_VARRAYS) { top = Array::CreateVArray(); } else if (container_type == JSONContainerType::DARRAYS) { top = Array::CreateDArray(); } else if (container_type == JSONContainerType::LEGACY_HACK_ARRAYS) { auto arr = staticEmptyVecArray()->copy(); arr->setLegacyArray(true); top = arr; } else { top = Array::CreateDArray(); } /**/ json->stack[json->top].key = copy_and_clear(*key); reset_type(); } break; /* ] */ case -5: { if (type != kInvalidDataType && json->stack[json->top].mode == Mode::ARRAY) { Variant mval; json_create_zval(mval, *buf, type, options); auto& top = json->stack[json->top].val; if (container_type == JSONContainerType::COLLECTIONS) { collections::append(top.getObjectData(), mval.asTypedValue()); } else { top.asArrRef().append(mval); } buf->clear(); reset_type(); } /**/ if (json->top == 1) z = json->stack[json->top].val; else { /**/ attach_zval(json, json->stack[json->top].key, assoc, container_type); /**/ } /**/ if (!pop(json, Mode::ARRAY)) { s_json_parser->error_code = JSON_ERROR_STATE_MISMATCH; return false; } state = 9; } break; /* "" */ case -4: switch (json->stack[json->top].mode) { case Mode::KEY: state = 27; std::swap(buf, key); reset_type(); break; case Mode::ARRAY: case Mode::OBJECT: state = 9; break; case Mode::DONE: if (type == KindOfString) { z = copy_and_clear(*buf); state = 9; break; } /* fall through if not KindOfString */ default: s_json_parser->error_code = JSON_ERROR_SYNTAX; return false; } break; /* , */ case -3: { Variant mval; if (type != kInvalidDataType && (json->stack[json->top].mode == Mode::OBJECT || json->stack[json->top].mode == Mode::ARRAY)) { json_create_zval(mval, *buf, type, options); } switch (json->stack[json->top].mode) { case Mode::OBJECT: if (pop(json, Mode::OBJECT) && push(json, Mode::KEY)) { if (type != kInvalidDataType) { Variant &top = json->stack[json->top].val; object_set( json, top, copy_and_clear(*key), mval, assoc, container_type ); } state = 29; } break; case Mode::ARRAY: if (type != kInvalidDataType) { auto& top = json->stack[json->top].val; if (container_type == JSONContainerType::COLLECTIONS) { collections::append(top.getObjectData(), mval.asTypedValue()); } else { top.asArrRef().append(mval); } } state = 28; break; default: s_json_parser->error_code = JSON_ERROR_SYNTAX; return false; } buf->clear(); reset_type(); check_non_safepoint_surprise(); } break; /**/ /* : (after unquoted string) */ case -10: if (json->stack[json->top].mode == Mode::KEY) { state = 27; std::swap(buf, key); reset_type(); s = -2; } else { s = 3; break; } /**/ /* : */ case -2: if (pop(json, Mode::KEY) && push(json, Mode::OBJECT)) { state = 28; break; } /* syntax error */ case -1: s_json_parser->error_code = JSON_ERROR_SYNTAX; return false; } } else { /* Change the state and iterate. */ bool is_tsimplejson = options & k_JSON_FB_THRIFT_SIMPLE_JSON; if (type == KindOfString) { if (/**/(/**/s == 3/**/ || s == 30)/**/ && state != 8) { if (state != 4) { utf16_to_utf8(*buf, b); } else { switch (b) { case 'b': buf->append('\b'); break; case 't': buf->append('\t'); break; case 'n': buf->append('\n'); break; case 'f': buf->append('\f'); break; case 'r': buf->append('\r'); break; default: utf16_to_utf8(*buf, b); break; } } } else if (s == 6) { if (UNLIKELY(is_tsimplejson)) { if (UNLIKELY(b != '0')) { s_json_parser->error_code = JSON_ERROR_SYNTAX; return false; } escaped_bytes = 0; } else { escaped_bytes = dehexchar(b) << 12; } } else if (s == 7) { if (UNLIKELY(is_tsimplejson)) { if (UNLIKELY(b != '0')) { s_json_parser->error_code = JSON_ERROR_SYNTAX; return false; } } else { escaped_bytes += dehexchar(b) << 8; } } else if (s == 8) { escaped_bytes += dehexchar(b) << 4; } else if (s == 3 && state == 8) { escaped_bytes += dehexchar(b); if (UNLIKELY(is_tsimplejson)) { buf->append((char)escaped_bytes); } else { utf16_to_utf8(*buf, escaped_bytes); } } } else if ((type == kInvalidDataType || type == KindOfNull) && (c == S_DIG || c == S_ZER)) { type = KindOfInt64; buf->append((char)b); } else if (type == KindOfInt64 && s == 24) { type = KindOfDouble; buf->append((char)b); } else if ((type == kInvalidDataType || type == KindOfNull || type == KindOfInt64) && c == S_DOT) { type = KindOfDouble; buf->append((char)b); } else if (type != KindOfString && c == S_QUO) { type = KindOfString; /**/qchr = b;/**/ } else if ((type == kInvalidDataType || type == KindOfNull || type == KindOfInt64 || type == KindOfDouble) && ((state == 12 && s == 9) || (state == 16 && s == 9))) { type = KindOfBoolean; } else if (type == kInvalidDataType && state == 19 && s == 9) { type = KindOfNull; } else if (type != KindOfString && c > S_WSP) { utf16_to_utf8(*buf, b); } state = s; } } if (state == 9 && pop(json, Mode::DONE)) { s_json_parser->error_code = JSON_ERROR_NONE; return true; } s_json_parser->error_code = JSON_ERROR_SYNTAX; return false; }","{'deleted': [], 'added': [{'line_no': 11, 'char_start': 548, 'char_end': 568, 'line': ' if (depth <= 0) {\n'}, {'line_no': 12, 'char_start': 568, 'char_end': 627, 'line': ' json->error_code = json_error_codes::JSON_ERROR_DEPTH;\n'}, {'line_no': 13, 'char_start': 627, 'char_end': 645, 'line': ' return false;\n'}, {'line_no': 14, 'char_start': 645, 'char_end': 649, 'line': ' }\n'}]}","{'deleted': [], 'added': [{'char_start': 550, 'char_end': 651, 'chars': 'if (depth <= 0) {\n json->error_code = json_error_codes::JSON_ERROR_DEPTH;\n return false;\n }\n '}]}",github.com/facebook/hhvm/commit/dabd48caf74995e605f1700344f1ff4a5d83441d,hphp/runtime/ext/json/JSON_parser.cpp,cwe-125,3769 cwe-079,html_content," @property async def html_content(self): content = await self.content if not content: return '' return markdown(content)"," @property async def html_content(self): content = markupsafe.escape(await self.content) if not content: return '' return markdown(content)","{'deleted': [{'line_no': 3, 'char_start': 48, 'char_end': 85, 'line': ' content = await self.content\n'}], 'added': [{'line_no': 3, 'char_start': 48, 'char_end': 104, 'line': ' content = markupsafe.escape(await self.content)\n'}]}","{'deleted': [], 'added': [{'char_start': 66, 'char_end': 84, 'chars': 'markupsafe.escape('}, {'char_start': 102, 'char_end': 103, 'chars': ')'}]}",github.com/dongweiming/lyanna/commit/fcefac79e4b7601e81a3b3fe0ad26ab18ee95d7d,models/comment.py,cwe-079,31 cwe-089,h2h,"@endpoints.route(""/h2h"") def h2h(): if db == None: init() player1 = request.args.get('tag1', default=""christmasmike"") player2 = request.args.get('tag2', default=""christmasmike"") sql = ""SELECT * FROM matches WHERE (player1 = '""+str(player1)+""' OR ""\ +""player2 = '""+str(player1)+""') AND (player1 = '""+str(player2)+""' OR ""\ +""player2 = '""+str(player2)+""') ORDER BY date DESC;"" result = db.exec(sql) return json.dumps(result)","@endpoints.route(""/h2h"") def h2h(): if db == None: init() player1 = request.args.get('tag1', default=""christmasmike"") player2 = request.args.get('tag2', default=""christmasmike"") sql = ""SELECT * FROM matches WHERE (player1 = '{player1}' OR ""\ +""player2 = '{player1}') AND (player1 = '{player2}' OR ""\ +""player2 = '{player2}') ORDER BY date DESC;"" args = {'player1': player1, 'player2': player2} result = db.exec(sql, args) return json.dumps(result)","{'deleted': [{'line_no': 8, 'char_start': 199, 'char_end': 274, 'line': ' sql = ""SELECT * FROM matches WHERE (player1 = \'""+str(player1)+""\' OR ""\\\n'}, {'line_no': 9, 'char_start': 274, 'char_end': 358, 'line': ' +""player2 = \'""+str(player1)+""\') AND (player1 = \'""+str(player2)+""\' OR ""\\\n'}, {'line_no': 10, 'char_start': 358, 'char_end': 423, 'line': ' +""player2 = \'""+str(player2)+""\') ORDER BY date DESC;""\n'}, {'line_no': 11, 'char_start': 423, 'char_end': 449, 'line': ' result = db.exec(sql)\n'}], 'added': [{'line_no': 8, 'char_start': 199, 'char_end': 267, 'line': ' sql = ""SELECT * FROM matches WHERE (player1 = \'{player1}\' OR ""\\\n'}, {'line_no': 9, 'char_start': 267, 'char_end': 337, 'line': ' +""player2 = \'{player1}\') AND (player1 = \'{player2}\' OR ""\\\n'}, {'line_no': 10, 'char_start': 337, 'char_end': 395, 'line': ' +""player2 = \'{player2}\') ORDER BY date DESC;""\n'}, {'line_no': 11, 'char_start': 395, 'char_end': 447, 'line': "" args = {'player1': player1, 'player2': player2}\n""}, {'line_no': 12, 'char_start': 447, 'char_end': 479, 'line': ' result = db.exec(sql, args)\n'}]}","{'deleted': [{'char_start': 250, 'char_end': 256, 'chars': '""+str('}, {'char_start': 263, 'char_end': 266, 'chars': ')+""'}, {'char_start': 299, 'char_end': 305, 'chars': '""+str('}, {'char_start': 312, 'char_end': 315, 'chars': ')+""'}, {'char_start': 334, 'char_end': 340, 'chars': '""+str('}, {'char_start': 347, 'char_end': 350, 'chars': ')+""'}, {'char_start': 383, 'char_end': 389, 'chars': '""+str('}, {'char_start': 396, 'char_end': 399, 'chars': ')+""'}], 'added': [{'char_start': 250, 'char_end': 251, 'chars': '{'}, {'char_start': 258, 'char_end': 259, 'chars': '}'}, {'char_start': 292, 'char_end': 293, 'chars': '{'}, {'char_start': 300, 'char_end': 301, 'chars': '}'}, {'char_start': 320, 'char_end': 321, 'chars': '{'}, {'char_start': 328, 'char_end': 329, 'chars': '}'}, {'char_start': 362, 'char_end': 363, 'chars': '{'}, {'char_start': 370, 'char_end': 371, 'chars': '}'}, {'char_start': 399, 'char_end': 451, 'chars': ""args = {'player1': player1, 'player2': player2}\n ""}, {'char_start': 471, 'char_end': 477, 'chars': ', args'}]}",github.com/DKelle/Smash_stats/commit/4bb83f3f6ce7d6bebbeb512cd015f9e72cf36d63,endpoints.py,cwe-089,132 cwe-089,add,"@mod.route('/add', methods=['GET', 'POST']) def add(): if request.method == 'POST': msg_id = int(request.form['msg_id']) user_id = session['logged_id'] content = request.form['content'] c_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S') sql = ""INSERT INTO comment(msg_id,user_id,content,c_time) "" + \ ""VALUES(%d,%d,'%s','%s');"" % (msg_id, user_id, content, c_time) cursor.execute(sql) conn.commit() return redirect(url_for('comment.show', msg_id=msg_id))","@mod.route('/add', methods=['GET', 'POST']) def add(): if request.method == 'POST': msg_id = int(request.form['msg_id']) user_id = session['logged_id'] content = request.form['content'] c_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S') cursor.execute(""INSERT INTO comment(msg_id,user_id,content,c_time) VALUES(%s,%s,%s,%s);"", (msg_id, user_id, content, c_time)) conn.commit() return redirect(url_for('comment.show', msg_id=msg_id))","{'deleted': [{'line_no': 8, 'char_start': 276, 'char_end': 348, 'line': ' sql = ""INSERT INTO comment(msg_id,user_id,content,c_time) "" + \\\n'}, {'line_no': 9, 'char_start': 348, 'char_end': 428, 'line': ' ""VALUES(%d,%d,\'%s\',\'%s\');"" % (msg_id, user_id, content, c_time)\n'}, {'line_no': 10, 'char_start': 428, 'char_end': 456, 'line': ' cursor.execute(sql)\n'}], 'added': [{'line_no': 8, 'char_start': 276, 'char_end': 410, 'line': ' cursor.execute(""INSERT INTO comment(msg_id,user_id,content,c_time) VALUES(%s,%s,%s,%s);"", (msg_id, user_id, content, c_time))\n'}]}","{'deleted': [{'char_start': 285, 'char_end': 290, 'chars': 'ql = '}, {'char_start': 342, 'char_end': 365, 'chars': '"" + \\\n ""'}, {'char_start': 373, 'char_end': 374, 'chars': 'd'}, {'char_start': 376, 'char_end': 377, 'chars': 'd'}, {'char_start': 378, 'char_end': 379, 'chars': ""'""}, {'char_start': 381, 'char_end': 382, 'chars': ""'""}, {'char_start': 383, 'char_end': 384, 'chars': ""'""}, {'char_start': 386, 'char_end': 387, 'chars': ""'""}, {'char_start': 390, 'char_end': 392, 'chars': ' %'}, {'char_start': 427, 'char_end': 454, 'chars': '\n cursor.execute(sql'}], 'added': [{'char_start': 284, 'char_end': 287, 'chars': 'cur'}, {'char_start': 288, 'char_end': 299, 'chars': 'or.execute('}, {'char_start': 359, 'char_end': 360, 'chars': 's'}, {'char_start': 362, 'char_end': 363, 'chars': 's'}, {'char_start': 372, 'char_end': 373, 'chars': ','}]}",github.com/ulyssetsd/bjtu-sql/commit/17d7b21864b72ba5666f15236474a93268b32ec9,flaskr/flaskr/views/comment.py,cwe-089,139 cwe-078,initialize_connection," def initialize_connection(self, volume, connector): """"""Restrict access to a volume."""""" try: cmd = ['volume', 'select', volume['name'], 'access', 'create', 'initiator', connector['initiator']] if self.configuration.eqlx_use_chap: cmd.extend(['authmethod chap', 'username', self.configuration.eqlx_chap_login]) self._eql_execute(*cmd) iscsi_properties = self._get_iscsi_properties(volume) return { 'driver_volume_type': 'iscsi', 'data': iscsi_properties } except Exception: with excutils.save_and_reraise_exception(): LOG.error(_('Failed to initialize connection to volume %s'), volume['name'])"," def initialize_connection(self, volume, connector): """"""Restrict access to a volume."""""" try: cmd = ['volume', 'select', volume['name'], 'access', 'create', 'initiator', connector['initiator']] if self.configuration.eqlx_use_chap: cmd.extend(['authmethod', 'chap', 'username', self.configuration.eqlx_chap_login]) self._eql_execute(*cmd) iscsi_properties = self._get_iscsi_properties(volume) return { 'driver_volume_type': 'iscsi', 'data': iscsi_properties } except Exception: with excutils.save_and_reraise_exception(): LOG.error(_('Failed to initialize connection to volume %s'), volume['name'])","{'deleted': [{'line_no': 7, 'char_start': 292, 'char_end': 351, 'line': "" cmd.extend(['authmethod chap', 'username',\n""}], 'added': [{'line_no': 7, 'char_start': 292, 'char_end': 354, 'line': "" cmd.extend(['authmethod', 'chap', 'username',\n""}]}","{'deleted': [], 'added': [{'char_start': 331, 'char_end': 333, 'chars': ""',""}, {'char_start': 334, 'char_end': 335, 'chars': ""'""}]}",github.com/thatsdone/cinder/commit/9e858bebb89de05b1c9ecc27f5bd9fbff95a728e,cinder/volume/drivers/eqlx.py,cwe-078,160 cwe-476,LookupModMask,"LookupModMask(struct xkb_context *ctx, const void *priv, xkb_atom_t field, enum expr_value_type type, xkb_mod_mask_t *val_rtrn) { const char *str; xkb_mod_index_t ndx; const LookupModMaskPriv *arg = priv; const struct xkb_mod_set *mods = arg->mods; enum mod_type mod_type = arg->mod_type; if (type != EXPR_TYPE_INT) return false; str = xkb_atom_text(ctx, field); if (istreq(str, ""all"")) { *val_rtrn = MOD_REAL_MASK_ALL; return true; } if (istreq(str, ""none"")) { *val_rtrn = 0; return true; } ndx = XkbModNameToIndex(mods, field, mod_type); if (ndx == XKB_MOD_INVALID) return false; *val_rtrn = (1u << ndx); return true; }","LookupModMask(struct xkb_context *ctx, const void *priv, xkb_atom_t field, enum expr_value_type type, xkb_mod_mask_t *val_rtrn) { const char *str; xkb_mod_index_t ndx; const LookupModMaskPriv *arg = priv; const struct xkb_mod_set *mods = arg->mods; enum mod_type mod_type = arg->mod_type; if (type != EXPR_TYPE_INT) return false; str = xkb_atom_text(ctx, field); if (!str) return false; if (istreq(str, ""all"")) { *val_rtrn = MOD_REAL_MASK_ALL; return true; } if (istreq(str, ""none"")) { *val_rtrn = 0; return true; } ndx = XkbModNameToIndex(mods, field, mod_type); if (ndx == XKB_MOD_INVALID) return false; *val_rtrn = (1u << ndx); return true; }","{'deleted': [], 'added': [{'line_no': 14, 'char_start': 415, 'char_end': 429, 'line': ' if (!str)\n'}, {'line_no': 15, 'char_start': 429, 'char_end': 451, 'line': ' return false;\n'}]}","{'deleted': [], 'added': [{'char_start': 415, 'char_end': 451, 'chars': ' if (!str)\n return false;\n'}]}",github.com/xkbcommon/libxkbcommon/commit/4e2ee9c3f6050d773f8bbe05bc0edb17f1ff8371,src/xkbcomp/expr.c,cwe-476,225 cwe-078,test_create_invalid_host," def test_create_invalid_host(self): self.flags(lock_path=self.tempdir) #record self.clear_mox() self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, ""get_cpg"", self.fake_get_cpg) self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, ""get_domain"", self.fake_get_domain) _run_ssh = self.mox.CreateMock(hpdriver.hpcommon.HP3PARCommon._run_ssh) self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, ""_run_ssh"", _run_ssh) show_host_cmd = 'showhost -verbose fakehost' _run_ssh(show_host_cmd, False).AndReturn([pack('no hosts listed'), '']) create_host_cmd = ('createhost -iscsi -persona 1 -domain ' '(\'OpenStack\',) ' 'fakehost iqn.1993-08.org.debian:01:222') in_use_ret = pack('\r\nalready used by host fakehost.foo ') _run_ssh(create_host_cmd, False).AndReturn([in_use_ret, '']) show_3par_cmd = 'showhost -verbose fakehost.foo' _run_ssh(show_3par_cmd, False).AndReturn([pack(ISCSI_3PAR_RET), '']) self.mox.ReplayAll() host = self.driver._create_host(self.volume, self.connector) self.assertEquals(host['name'], 'fakehost.foo')"," def test_create_invalid_host(self): self.flags(lock_path=self.tempdir) #record self.clear_mox() self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, ""get_cpg"", self.fake_get_cpg) self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, ""get_domain"", self.fake_get_domain) _run_ssh = self.mox.CreateMock(hpdriver.hpcommon.HP3PARCommon._run_ssh) self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, ""_run_ssh"", _run_ssh) show_host_cmd = ['showhost', '-verbose', 'fakehost'] _run_ssh(show_host_cmd, False).AndReturn([pack('no hosts listed'), '']) create_host_cmd = (['createhost', '-iscsi', '-persona', '1', '-domain', ('OpenStack',), 'fakehost', 'iqn.1993-08.org.debian:01:222']) in_use_ret = pack('\r\nalready used by host fakehost.foo ') _run_ssh(create_host_cmd, False).AndReturn([in_use_ret, '']) show_3par_cmd = ['showhost', '-verbose', 'fakehost.foo'] _run_ssh(show_3par_cmd, False).AndReturn([pack(ISCSI_3PAR_RET), '']) self.mox.ReplayAll() host = self.driver._create_host(self.volume, self.connector) self.assertEquals(host['name'], 'fakehost.foo')","{'deleted': [{'line_no': 13, 'char_start': 505, 'char_end': 558, 'line': "" show_host_cmd = 'showhost -verbose fakehost'\n""}, {'line_no': 16, 'char_start': 639, 'char_end': 706, 'line': "" create_host_cmd = ('createhost -iscsi -persona 1 -domain '\n""}, {'line_no': 17, 'char_start': 706, 'char_end': 753, 'line': "" '(\\'OpenStack\\',) '\n""}, {'line_no': 18, 'char_start': 753, 'char_end': 822, 'line': "" 'fakehost iqn.1993-08.org.debian:01:222')\n""}, {'line_no': 22, 'char_start': 960, 'char_end': 1017, 'line': "" show_3par_cmd = 'showhost -verbose fakehost.foo'\n""}], 'added': [{'line_no': 13, 'char_start': 505, 'char_end': 566, 'line': "" show_host_cmd = ['showhost', '-verbose', 'fakehost']\n""}, {'line_no': 16, 'char_start': 647, 'char_end': 727, 'line': "" create_host_cmd = (['createhost', '-iscsi', '-persona', '1', '-domain',\n""}, {'line_no': 17, 'char_start': 727, 'char_end': 782, 'line': "" ('OpenStack',), 'fakehost',\n""}, {'line_no': 18, 'char_start': 782, 'char_end': 844, 'line': "" 'iqn.1993-08.org.debian:01:222'])\n""}, {'line_no': 22, 'char_start': 982, 'char_end': 1047, 'line': "" show_3par_cmd = ['showhost', '-verbose', 'fakehost.foo']\n""}]}","{'deleted': [{'char_start': 703, 'char_end': 704, 'chars': ' '}, {'char_start': 733, 'char_end': 734, 'chars': ""'""}, {'char_start': 735, 'char_end': 736, 'chars': '\\'}, {'char_start': 746, 'char_end': 747, 'chars': '\\'}, {'char_start': 780, 'char_end': 789, 'chars': ""'fakehost""}], 'added': [{'char_start': 529, 'char_end': 530, 'chars': '['}, {'char_start': 539, 'char_end': 541, 'chars': ""',""}, {'char_start': 542, 'char_end': 543, 'chars': ""'""}, {'char_start': 551, 'char_end': 553, 'chars': ""',""}, {'char_start': 554, 'char_end': 555, 'chars': ""'""}, {'char_start': 564, 'char_end': 565, 'chars': ']'}, {'char_start': 674, 'char_end': 675, 'chars': '['}, {'char_start': 686, 'char_end': 688, 'chars': ""',""}, {'char_start': 689, 'char_end': 690, 'chars': ""'""}, {'char_start': 696, 'char_end': 698, 'chars': ""',""}, {'char_start': 699, 'char_end': 700, 'chars': ""'""}, {'char_start': 708, 'char_end': 710, 'chars': ""',""}, {'char_start': 711, 'char_end': 712, 'chars': ""'""}, {'char_start': 713, 'char_end': 715, 'chars': ""',""}, {'char_start': 716, 'char_end': 717, 'chars': ""'""}, {'char_start': 725, 'char_end': 726, 'chars': ','}, {'char_start': 768, 'char_end': 769, 'chars': ','}, {'char_start': 771, 'char_end': 781, 'chars': ""fakehost',""}, {'char_start': 782, 'char_end': 783, 'chars': ' '}, {'char_start': 841, 'char_end': 842, 'chars': ']'}, {'char_start': 1006, 'char_end': 1007, 'chars': '['}, {'char_start': 1016, 'char_end': 1018, 'chars': ""',""}, {'char_start': 1019, 'char_end': 1020, 'chars': ""'""}, {'char_start': 1028, 'char_end': 1030, 'chars': ""',""}, {'char_start': 1031, 'char_end': 1032, 'chars': ""'""}, {'char_start': 1045, 'char_end': 1046, 'chars': ']'}]}",github.com/thatsdone/cinder/commit/c55589b131828f3a595903f6796cb2d0babb772f,cinder/tests/test_hp3par.py,cwe-078,324 cwe-078,_get_3par_hostname_from_wwn_iqn," def _get_3par_hostname_from_wwn_iqn(self, wwns_iqn): out = self._cli_run('showhost -d', None) # wwns_iqn may be a list of strings or a single # string. So, if necessary, create a list to loop. if not isinstance(wwns_iqn, list): wwn_iqn_list = [wwns_iqn] else: wwn_iqn_list = wwns_iqn for wwn_iqn in wwn_iqn_list: for showhost in out: if (wwn_iqn.upper() in showhost.upper()): return showhost.split(',')[1]"," def _get_3par_hostname_from_wwn_iqn(self, wwns_iqn): out = self._cli_run(['showhost', '-d']) # wwns_iqn may be a list of strings or a single # string. So, if necessary, create a list to loop. if not isinstance(wwns_iqn, list): wwn_iqn_list = [wwns_iqn] else: wwn_iqn_list = wwns_iqn for wwn_iqn in wwn_iqn_list: for showhost in out: if (wwn_iqn.upper() in showhost.upper()): return showhost.split(',')[1]","{'deleted': [{'line_no': 2, 'char_start': 57, 'char_end': 106, 'line': "" out = self._cli_run('showhost -d', None)\n""}], 'added': [{'line_no': 2, 'char_start': 57, 'char_end': 105, 'line': "" out = self._cli_run(['showhost', '-d'])\n""}]}","{'deleted': [{'char_start': 98, 'char_end': 104, 'chars': ', None'}], 'added': [{'char_start': 85, 'char_end': 86, 'chars': '['}, {'char_start': 95, 'char_end': 97, 'chars': ""',""}, {'char_start': 98, 'char_end': 99, 'chars': ""'""}, {'char_start': 102, 'char_end': 103, 'chars': ']'}]}",github.com/thatsdone/cinder/commit/c55589b131828f3a595903f6796cb2d0babb772f,cinder/volume/drivers/san/hp/hp_3par_common.py,cwe-078,152 cwe-416,parse_playlist,"static int parse_playlist(HLSContext *c, const char *url, struct playlist *pls, AVIOContext *in) { int ret = 0, is_segment = 0, is_variant = 0; int64_t duration = 0; enum KeyType key_type = KEY_NONE; uint8_t iv[16] = """"; int has_iv = 0; char key[MAX_URL_SIZE] = """"; char line[MAX_URL_SIZE]; const char *ptr; int close_in = 0; int64_t seg_offset = 0; int64_t seg_size = -1; uint8_t *new_url = NULL; struct variant_info variant_info; char tmp_str[MAX_URL_SIZE]; struct segment *cur_init_section = NULL; if (!in) { #if 1 AVDictionary *opts = NULL; close_in = 1; /* Some HLS servers don't like being sent the range header */ av_dict_set(&opts, ""seekable"", ""0"", 0); // broker prior HTTP options that should be consistent across requests av_dict_set(&opts, ""user-agent"", c->user_agent, 0); av_dict_set(&opts, ""cookies"", c->cookies, 0); av_dict_set(&opts, ""headers"", c->headers, 0); ret = avio_open2(&in, url, AVIO_FLAG_READ, c->interrupt_callback, &opts); av_dict_free(&opts); if (ret < 0) return ret; #else ret = open_in(c, &in, url); if (ret < 0) return ret; close_in = 1; #endif } if (av_opt_get(in, ""location"", AV_OPT_SEARCH_CHILDREN, &new_url) >= 0) url = new_url; read_chomp_line(in, line, sizeof(line)); if (strcmp(line, ""#EXTM3U"")) { ret = AVERROR_INVALIDDATA; goto fail; } if (pls) { free_segment_list(pls); pls->finished = 0; pls->type = PLS_TYPE_UNSPECIFIED; } while (!avio_feof(in)) { read_chomp_line(in, line, sizeof(line)); if (av_strstart(line, ""#EXT-X-STREAM-INF:"", &ptr)) { is_variant = 1; memset(&variant_info, 0, sizeof(variant_info)); ff_parse_key_value(ptr, (ff_parse_key_val_cb) handle_variant_args, &variant_info); } else if (av_strstart(line, ""#EXT-X-KEY:"", &ptr)) { struct key_info info = {{0}}; ff_parse_key_value(ptr, (ff_parse_key_val_cb) handle_key_args, &info); key_type = KEY_NONE; has_iv = 0; if (!strcmp(info.method, ""AES-128"")) key_type = KEY_AES_128; if (!strcmp(info.method, ""SAMPLE-AES"")) key_type = KEY_SAMPLE_AES; if (!strncmp(info.iv, ""0x"", 2) || !strncmp(info.iv, ""0X"", 2)) { ff_hex_to_data(iv, info.iv + 2); has_iv = 1; } av_strlcpy(key, info.uri, sizeof(key)); } else if (av_strstart(line, ""#EXT-X-MEDIA:"", &ptr)) { struct rendition_info info = {{0}}; ff_parse_key_value(ptr, (ff_parse_key_val_cb) handle_rendition_args, &info); new_rendition(c, &info, url); } else if (av_strstart(line, ""#EXT-X-TARGETDURATION:"", &ptr)) { ret = ensure_playlist(c, &pls, url); if (ret < 0) goto fail; pls->target_duration = atoi(ptr) * AV_TIME_BASE; } else if (av_strstart(line, ""#EXT-X-MEDIA-SEQUENCE:"", &ptr)) { ret = ensure_playlist(c, &pls, url); if (ret < 0) goto fail; pls->start_seq_no = atoi(ptr); } else if (av_strstart(line, ""#EXT-X-PLAYLIST-TYPE:"", &ptr)) { ret = ensure_playlist(c, &pls, url); if (ret < 0) goto fail; if (!strcmp(ptr, ""EVENT"")) pls->type = PLS_TYPE_EVENT; else if (!strcmp(ptr, ""VOD"")) pls->type = PLS_TYPE_VOD; } else if (av_strstart(line, ""#EXT-X-MAP:"", &ptr)) { struct init_section_info info = {{0}}; ret = ensure_playlist(c, &pls, url); if (ret < 0) goto fail; ff_parse_key_value(ptr, (ff_parse_key_val_cb) handle_init_section_args, &info); cur_init_section = new_init_section(pls, &info, url); } else if (av_strstart(line, ""#EXT-X-ENDLIST"", &ptr)) { if (pls) pls->finished = 1; } else if (av_strstart(line, ""#EXTINF:"", &ptr)) { is_segment = 1; duration = atof(ptr) * AV_TIME_BASE; } else if (av_strstart(line, ""#EXT-X-BYTERANGE:"", &ptr)) { seg_size = atoi(ptr); ptr = strchr(ptr, '@'); if (ptr) seg_offset = atoi(ptr+1); } else if (av_strstart(line, ""#"", NULL)) { continue; } else if (line[0]) { if (is_variant) { if (!new_variant(c, &variant_info, line, url)) { ret = AVERROR(ENOMEM); goto fail; } is_variant = 0; } if (is_segment) { struct segment *seg; if (!pls) { if (!new_variant(c, 0, url, NULL)) { ret = AVERROR(ENOMEM); goto fail; } pls = c->playlists[c->n_playlists - 1]; } seg = av_malloc(sizeof(struct segment)); if (!seg) { ret = AVERROR(ENOMEM); goto fail; } seg->duration = duration; seg->key_type = key_type; if (has_iv) { memcpy(seg->iv, iv, sizeof(iv)); } else { int seq = pls->start_seq_no + pls->n_segments; memset(seg->iv, 0, sizeof(seg->iv)); AV_WB32(seg->iv + 12, seq); } if (key_type != KEY_NONE) { ff_make_absolute_url(tmp_str, sizeof(tmp_str), url, key); seg->key = av_strdup(tmp_str); if (!seg->key) { av_free(seg); ret = AVERROR(ENOMEM); goto fail; } } else { seg->key = NULL; } ff_make_absolute_url(tmp_str, sizeof(tmp_str), url, line); seg->url = av_strdup(tmp_str); if (!seg->url) { av_free(seg->key); av_free(seg); ret = AVERROR(ENOMEM); goto fail; } dynarray_add(&pls->segments, &pls->n_segments, seg); is_segment = 0; seg->size = seg_size; if (seg_size >= 0) { seg->url_offset = seg_offset; seg_offset += seg_size; seg_size = -1; } else { seg->url_offset = 0; seg_offset = 0; } seg->init_section = cur_init_section; } } } if (pls) pls->last_load_time = av_gettime_relative(); fail: av_free(new_url); if (close_in) avio_close(in); return ret; }","static int parse_playlist(HLSContext *c, const char *url, struct playlist *pls, AVIOContext *in) { int ret = 0, is_segment = 0, is_variant = 0; int64_t duration = 0; enum KeyType key_type = KEY_NONE; uint8_t iv[16] = """"; int has_iv = 0; char key[MAX_URL_SIZE] = """"; char line[MAX_URL_SIZE]; const char *ptr; int close_in = 0; int64_t seg_offset = 0; int64_t seg_size = -1; uint8_t *new_url = NULL; struct variant_info variant_info; char tmp_str[MAX_URL_SIZE]; struct segment *cur_init_section = NULL; if (!in) { #if 1 AVDictionary *opts = NULL; close_in = 1; /* Some HLS servers don't like being sent the range header */ av_dict_set(&opts, ""seekable"", ""0"", 0); // broker prior HTTP options that should be consistent across requests av_dict_set(&opts, ""user-agent"", c->user_agent, 0); av_dict_set(&opts, ""cookies"", c->cookies, 0); av_dict_set(&opts, ""headers"", c->headers, 0); ret = avio_open2(&in, url, AVIO_FLAG_READ, c->interrupt_callback, &opts); av_dict_free(&opts); if (ret < 0) return ret; #else ret = open_in(c, &in, url); if (ret < 0) return ret; close_in = 1; #endif } if (av_opt_get(in, ""location"", AV_OPT_SEARCH_CHILDREN, &new_url) >= 0) url = new_url; read_chomp_line(in, line, sizeof(line)); if (strcmp(line, ""#EXTM3U"")) { ret = AVERROR_INVALIDDATA; goto fail; } if (pls) { free_segment_list(pls); pls->finished = 0; pls->type = PLS_TYPE_UNSPECIFIED; } while (!avio_feof(in)) { read_chomp_line(in, line, sizeof(line)); if (av_strstart(line, ""#EXT-X-STREAM-INF:"", &ptr)) { is_variant = 1; memset(&variant_info, 0, sizeof(variant_info)); ff_parse_key_value(ptr, (ff_parse_key_val_cb) handle_variant_args, &variant_info); } else if (av_strstart(line, ""#EXT-X-KEY:"", &ptr)) { struct key_info info = {{0}}; ff_parse_key_value(ptr, (ff_parse_key_val_cb) handle_key_args, &info); key_type = KEY_NONE; has_iv = 0; if (!strcmp(info.method, ""AES-128"")) key_type = KEY_AES_128; if (!strcmp(info.method, ""SAMPLE-AES"")) key_type = KEY_SAMPLE_AES; if (!strncmp(info.iv, ""0x"", 2) || !strncmp(info.iv, ""0X"", 2)) { ff_hex_to_data(iv, info.iv + 2); has_iv = 1; } av_strlcpy(key, info.uri, sizeof(key)); } else if (av_strstart(line, ""#EXT-X-MEDIA:"", &ptr)) { struct rendition_info info = {{0}}; ff_parse_key_value(ptr, (ff_parse_key_val_cb) handle_rendition_args, &info); new_rendition(c, &info, url); } else if (av_strstart(line, ""#EXT-X-TARGETDURATION:"", &ptr)) { ret = ensure_playlist(c, &pls, url); if (ret < 0) goto fail; pls->target_duration = atoi(ptr) * AV_TIME_BASE; } else if (av_strstart(line, ""#EXT-X-MEDIA-SEQUENCE:"", &ptr)) { ret = ensure_playlist(c, &pls, url); if (ret < 0) goto fail; pls->start_seq_no = atoi(ptr); } else if (av_strstart(line, ""#EXT-X-PLAYLIST-TYPE:"", &ptr)) { ret = ensure_playlist(c, &pls, url); if (ret < 0) goto fail; if (!strcmp(ptr, ""EVENT"")) pls->type = PLS_TYPE_EVENT; else if (!strcmp(ptr, ""VOD"")) pls->type = PLS_TYPE_VOD; } else if (av_strstart(line, ""#EXT-X-MAP:"", &ptr)) { struct init_section_info info = {{0}}; ret = ensure_playlist(c, &pls, url); if (ret < 0) goto fail; ff_parse_key_value(ptr, (ff_parse_key_val_cb) handle_init_section_args, &info); cur_init_section = new_init_section(pls, &info, url); } else if (av_strstart(line, ""#EXT-X-ENDLIST"", &ptr)) { if (pls) pls->finished = 1; } else if (av_strstart(line, ""#EXTINF:"", &ptr)) { is_segment = 1; duration = atof(ptr) * AV_TIME_BASE; } else if (av_strstart(line, ""#EXT-X-BYTERANGE:"", &ptr)) { seg_size = atoi(ptr); ptr = strchr(ptr, '@'); if (ptr) seg_offset = atoi(ptr+1); } else if (av_strstart(line, ""#"", NULL)) { continue; } else if (line[0]) { if (is_variant) { if (!new_variant(c, &variant_info, line, url)) { ret = AVERROR(ENOMEM); goto fail; } is_variant = 0; } if (is_segment) { struct segment *seg; if (!pls) { if (!new_variant(c, 0, url, NULL)) { ret = AVERROR(ENOMEM); goto fail; } pls = c->playlists[c->n_playlists - 1]; } seg = av_malloc(sizeof(struct segment)); if (!seg) { ret = AVERROR(ENOMEM); goto fail; } if (has_iv) { memcpy(seg->iv, iv, sizeof(iv)); } else { int seq = pls->start_seq_no + pls->n_segments; memset(seg->iv, 0, sizeof(seg->iv)); AV_WB32(seg->iv + 12, seq); } if (key_type != KEY_NONE) { ff_make_absolute_url(tmp_str, sizeof(tmp_str), url, key); seg->key = av_strdup(tmp_str); if (!seg->key) { av_free(seg); ret = AVERROR(ENOMEM); goto fail; } } else { seg->key = NULL; } ff_make_absolute_url(tmp_str, sizeof(tmp_str), url, line); seg->url = av_strdup(tmp_str); if (!seg->url) { av_free(seg->key); av_free(seg); ret = AVERROR(ENOMEM); goto fail; } if (duration < 0.001 * AV_TIME_BASE) { duration = 0.001 * AV_TIME_BASE; } seg->duration = duration; seg->key_type = key_type; dynarray_add(&pls->segments, &pls->n_segments, seg); is_segment = 0; seg->size = seg_size; if (seg_size >= 0) { seg->url_offset = seg_offset; seg_offset += seg_size; seg_size = -1; } else { seg->url_offset = 0; seg_offset = 0; } seg->init_section = cur_init_section; } } } if (pls) pls->last_load_time = av_gettime_relative(); fail: av_free(new_url); if (close_in) avio_close(in); return ret; }","{'deleted': [{'line_no': 147, 'char_start': 5497, 'char_end': 5539, 'line': ' seg->duration = duration;\n'}, {'line_no': 148, 'char_start': 5539, 'char_end': 5581, 'line': ' seg->key_type = key_type;\n'}], 'added': [{'line_no': 176, 'char_start': 6550, 'char_end': 6605, 'line': ' if (duration < 0.001 * AV_TIME_BASE) {\n'}, {'line_no': 177, 'char_start': 6605, 'char_end': 6658, 'line': ' duration = 0.001 * AV_TIME_BASE;\n'}, {'line_no': 178, 'char_start': 6658, 'char_end': 6676, 'line': ' }\n'}, {'line_no': 179, 'char_start': 6676, 'char_end': 6718, 'line': ' seg->duration = duration;\n'}, {'line_no': 180, 'char_start': 6718, 'char_end': 6760, 'line': ' seg->key_type = key_type;\n'}]}","{'deleted': [{'char_start': 5513, 'char_end': 5597, 'chars': 'seg->duration = duration;\n seg->key_type = key_type;\n '}], 'added': [{'char_start': 6549, 'char_end': 6759, 'chars': '\n if (duration < 0.001 * AV_TIME_BASE) {\n duration = 0.001 * AV_TIME_BASE;\n }\n seg->duration = duration;\n seg->key_type = key_type;'}]}",github.com/FFmpeg/FFmpeg/commit/6959358683c7533f586c07a766acc5fe9544d8b2,libavformat/hls.c,cwe-416,1758 cwe-089,add_input," def add_input(self, data): connection = self.connect() try: # The following introduces a deliberate security flaw. # See section on SQL injection below query = ""INSERT INTO crimes (description) VALUES('{}');"".format(data) with connection.cursor() as cursor: cursor.execute(query) connection.commit() finally: connection.close()"," def add_input(self, data): connection = self.connect() try: # The following introduces a deliberate security flaw. # See section on SQL injection below query = ""INSERT INTO crimes (description) VALUES(%s);"" with connection.cursor() as cursor: cursor.execute(query, data) connection.commit() finally: connection.close()","{'deleted': [{'line_no': 6, 'char_start': 197, 'char_end': 279, 'line': ' query = ""INSERT INTO crimes (description) VALUES(\'{}\');"".format(data)\n'}, {'line_no': 8, 'char_start': 327, 'char_end': 365, 'line': ' cursor.execute(query)\n'}], 'added': [{'line_no': 6, 'char_start': 197, 'char_end': 264, 'line': ' query = ""INSERT INTO crimes (description) VALUES(%s);""\n'}, {'line_no': 8, 'char_start': 312, 'char_end': 356, 'line': ' cursor.execute(query, data)\n'}]}","{'deleted': [{'char_start': 258, 'char_end': 262, 'chars': ""'{}'""}, {'char_start': 265, 'char_end': 278, 'chars': '.format(data)'}], 'added': [{'char_start': 258, 'char_end': 260, 'chars': '%s'}, {'char_start': 348, 'char_end': 354, 'chars': ', data'}]}",github.com/mudspringhiker/crimemap/commit/35e78962e7288c643cdde0f886ff7aa5ac77cb8c,dbhelper.py,cwe-089,78 cwe-089,wins,"@endpoints.route(""/wins"") def wins(): if db == None: init() player = request.args.get('tag', default=""christmasmike"") sql = ""SELECT * FROM matches WHERE winner = '""+str(player)+""' ORDER BY date DESC;"" result = db.exec(sql) result = [str(x) for x in result] result = '\n'.join(result) return json.dumps(result)","@endpoints.route(""/wins"") def wins(): if db == None: init() player = request.args.get('tag', default=""christmasmike"") sql = ""SELECT * FROM matches WHERE winner = '{player}' ORDER BY date DESC;"" args = {'player': player} result = db.exec(sql, args) result = [str(x) for x in result] result = '\n'.join(result) return json.dumps(result)","{'deleted': [{'line_no': 7, 'char_start': 135, 'char_end': 222, 'line': ' sql = ""SELECT * FROM matches WHERE winner = \'""+str(player)+""\' ORDER BY date DESC;""\n'}, {'line_no': 8, 'char_start': 222, 'char_end': 248, 'line': ' result = db.exec(sql)\n'}], 'added': [{'line_no': 7, 'char_start': 135, 'char_end': 215, 'line': ' sql = ""SELECT * FROM matches WHERE winner = \'{player}\' ORDER BY date DESC;""\n'}, {'line_no': 8, 'char_start': 215, 'char_end': 245, 'line': "" args = {'player': player}\n""}, {'line_no': 9, 'char_start': 245, 'char_end': 277, 'line': ' result = db.exec(sql, args)\n'}]}","{'deleted': [{'char_start': 184, 'char_end': 190, 'chars': '""+str('}, {'char_start': 196, 'char_end': 199, 'chars': ')+""'}], 'added': [{'char_start': 184, 'char_end': 185, 'chars': '{'}, {'char_start': 191, 'char_end': 192, 'chars': '}'}, {'char_start': 219, 'char_end': 249, 'chars': ""args = {'player': player}\n ""}, {'char_start': 269, 'char_end': 275, 'chars': ', args'}]}",github.com/DKelle/Smash_stats/commit/4bb83f3f6ce7d6bebbeb512cd015f9e72cf36d63,endpoints.py,cwe-089,89 cwe-022,dd_get_item_size,"long dd_get_item_size(struct dump_dir *dd, const char *name) { long size = -1; char *iname = concat_path_file(dd->dd_dirname, name); struct stat statbuf; if (lstat(iname, &statbuf) == 0 && S_ISREG(statbuf.st_mode)) size = statbuf.st_size; else { if (errno == ENOENT) size = 0; else perror_msg(""Can't get size of file '%s'"", iname); } free(iname); return size; }","long dd_get_item_size(struct dump_dir *dd, const char *name) { if (!str_is_correct_filename(name)) error_msg_and_die(""Cannot get item size. '%s' is not a valid file name"", name); long size = -1; char *iname = concat_path_file(dd->dd_dirname, name); struct stat statbuf; if (lstat(iname, &statbuf) == 0 && S_ISREG(statbuf.st_mode)) size = statbuf.st_size; else { if (errno == ENOENT) size = 0; else perror_msg(""Can't get size of file '%s'"", iname); } free(iname); return size; }","{'deleted': [], 'added': [{'line_no': 3, 'char_start': 63, 'char_end': 103, 'line': ' if (!str_is_correct_filename(name))\n'}, {'line_no': 4, 'char_start': 103, 'char_end': 191, 'line': ' error_msg_and_die(""Cannot get item size. \'%s\' is not a valid file name"", name);\n'}, {'line_no': 5, 'char_start': 191, 'char_end': 192, 'line': '\n'}]}","{'deleted': [], 'added': [{'char_start': 67, 'char_end': 196, 'chars': 'if (!str_is_correct_filename(name))\n error_msg_and_die(""Cannot get item size. \'%s\' is not a valid file name"", name);\n\n '}]}",github.com/abrt/libreport/commit/239c4f7d1f47265526b39ad70106767d00805277,src/lib/dump_dir.c,cwe-022,129 cwe-787,unicode_unfold_key,"unicode_unfold_key(OnigCodePoint code) { static const struct ByUnfoldKey wordlist[] = { {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0x1040a, 3267, 1}, {0x1e0a, 1727, 1}, {0x040a, 1016, 1}, {0x010a, 186, 1}, {0x1f0a, 2088, 1}, {0x2c0a, 2451, 1}, {0x0189, 619, 1}, {0x1f89, 134, 2}, {0x1f85, 154, 2}, {0x0389, 733, 1}, {0x03ff, 724, 1}, {0xab89, 1523, 1}, {0xab85, 1511, 1}, {0x10c89, 3384, 1}, {0x10c85, 3372, 1}, {0x1e84, 1911, 1}, {0x03f5, 752, 1}, {0x0184, 360, 1}, {0x1f84, 149, 2}, {0x2c84, 2592, 1}, {0x017d, 351, 1}, {0x1ff3, 96, 2}, {0xab84, 1508, 1}, {0xa784, 3105, 1}, {0x10c84, 3369, 1}, {0xab7d, 1487, 1}, {0xa77d, 1706, 1}, {0x1e98, 38, 2}, {0x0498, 1106, 1}, {0x0198, 375, 1}, {0x1f98, 169, 2}, {0x2c98, 2622, 1}, {0x0398, 762, 1}, {0xa684, 2940, 1}, {0xab98, 1568, 1}, {0xa798, 3123, 1}, {0x10c98, 3429, 1}, {0x050a, 1277, 1}, {0x1ffb, 2265, 1}, {0x1e96, 16, 2}, {0x0496, 1103, 1}, {0x0196, 652, 1}, {0x1f96, 199, 2}, {0x2c96, 2619, 1}, {0x0396, 756, 1}, {0xa698, 2970, 1}, {0xab96, 1562, 1}, {0xa796, 3120, 1}, {0x10c96, 3423, 1}, {0x1feb, 2259, 1}, {0x2ceb, 2736, 1}, {0x1e90, 1929, 1}, {0x0490, 1094, 1}, {0x0190, 628, 1}, {0x1f90, 169, 2}, {0x2c90, 2610, 1}, {0x0390, 25, 3}, {0xa696, 2967, 1}, {0xab90, 1544, 1}, {0xa790, 3114, 1}, {0x10c90, 3405, 1}, {0x01d7, 444, 1}, {0x1fd7, 31, 3}, {0x1ea6, 1947, 1}, {0x04a6, 1127, 1}, {0x01a6, 676, 1}, {0x1fa6, 239, 2}, {0x2ca6, 2643, 1}, {0x03a6, 810, 1}, {0xa690, 2958, 1}, {0xaba6, 1610, 1}, {0xa7a6, 3144, 1}, {0x10ca6, 3471, 1}, {0x1ea4, 1944, 1}, {0x04a4, 1124, 1}, {0x01a4, 390, 1}, {0x1fa4, 229, 2}, {0x2ca4, 2640, 1}, {0x03a4, 804, 1}, {0x10a6, 2763, 1}, {0xaba4, 1604, 1}, {0xa7a4, 3141, 1}, {0x10ca4, 3465, 1}, {0x1ea0, 1938, 1}, {0x04a0, 1118, 1}, {0x01a0, 384, 1}, {0x1fa0, 209, 2}, {0x2ca0, 2634, 1}, {0x03a0, 792, 1}, {0x10a4, 2757, 1}, {0xaba0, 1592, 1}, {0xa7a0, 3135, 1}, {0x10ca0, 3453, 1}, {0x1eb2, 1965, 1}, {0x04b2, 1145, 1}, {0x01b2, 694, 1}, {0x1fb2, 249, 2}, {0x2cb2, 2661, 1}, {0x03fd, 718, 1}, {0x10a0, 2745, 1}, {0xabb2, 1646, 1}, {0xa7b2, 703, 1}, {0x10cb2, 3507, 1}, {0x1eac, 1956, 1}, {0x04ac, 1136, 1}, {0x01ac, 396, 1}, {0x1fac, 229, 2}, {0x2cac, 2652, 1}, {0x0537, 1352, 1}, {0x10b2, 2799, 1}, {0xabac, 1628, 1}, {0xa7ac, 637, 1}, {0x10cac, 3489, 1}, {0x1eaa, 1953, 1}, {0x04aa, 1133, 1}, {0x00dd, 162, 1}, {0x1faa, 219, 2}, {0x2caa, 2649, 1}, {0x03aa, 824, 1}, {0x10ac, 2781, 1}, {0xabaa, 1622, 1}, {0xa7aa, 646, 1}, {0x10caa, 3483, 1}, {0x1ea8, 1950, 1}, {0x04a8, 1130, 1}, {0x020a, 517, 1}, {0x1fa8, 209, 2}, {0x2ca8, 2646, 1}, {0x03a8, 817, 1}, {0x10aa, 2775, 1}, {0xaba8, 1616, 1}, {0xa7a8, 3147, 1}, {0x10ca8, 3477, 1}, {0x1ea2, 1941, 1}, {0x04a2, 1121, 1}, {0x01a2, 387, 1}, {0x1fa2, 219, 2}, {0x2ca2, 2637, 1}, {0x118a6, 3528, 1}, {0x10a8, 2769, 1}, {0xaba2, 1598, 1}, {0xa7a2, 3138, 1}, {0x10ca2, 3459, 1}, {0x2ced, 2739, 1}, {0x1fe9, 2283, 1}, {0x1fe7, 47, 3}, {0x1eb0, 1962, 1}, {0x04b0, 1142, 1}, {0x118a4, 3522, 1}, {0x10a2, 2751, 1}, {0x2cb0, 2658, 1}, {0x03b0, 41, 3}, {0x1fe3, 41, 3}, {0xabb0, 1640, 1}, {0xa7b0, 706, 1}, {0x10cb0, 3501, 1}, {0x01d9, 447, 1}, {0x1fd9, 2277, 1}, {0x118a0, 3510, 1}, {0x00df, 24, 2}, {0x00d9, 150, 1}, {0xab77, 1469, 1}, {0x10b0, 2793, 1}, {0x1eae, 1959, 1}, {0x04ae, 1139, 1}, {0x01ae, 685, 1}, {0x1fae, 239, 2}, {0x2cae, 2655, 1}, {0x118b2, 3564, 1}, {0xab73, 1457, 1}, {0xabae, 1634, 1}, {0xab71, 1451, 1}, {0x10cae, 3495, 1}, {0x1e2a, 1775, 1}, {0x042a, 968, 1}, {0x012a, 234, 1}, {0x1f2a, 2130, 1}, {0x2c2a, 2547, 1}, {0x118ac, 3546, 1}, {0x10ae, 2787, 1}, {0x0535, 1346, 1}, {0xa72a, 2988, 1}, {0x1e9a, 0, 2}, {0x049a, 1109, 1}, {0xff37, 3225, 1}, {0x1f9a, 179, 2}, {0x2c9a, 2625, 1}, {0x039a, 772, 1}, {0x118aa, 3540, 1}, {0xab9a, 1574, 1}, {0xa79a, 3126, 1}, {0x10c9a, 3435, 1}, {0x1e94, 1935, 1}, {0x0494, 1100, 1}, {0x0194, 640, 1}, {0x1f94, 189, 2}, {0x2c94, 2616, 1}, {0x0394, 749, 1}, {0x118a8, 3534, 1}, {0xab94, 1556, 1}, {0xa69a, 2973, 1}, {0x10c94, 3417, 1}, {0x10402, 3243, 1}, {0x1e02, 1715, 1}, {0x0402, 992, 1}, {0x0102, 174, 1}, {0x0533, 1340, 1}, {0x2c02, 2427, 1}, {0x118a2, 3516, 1}, {0x052a, 1325, 1}, {0xa694, 2964, 1}, {0x1e92, 1932, 1}, {0x0492, 1097, 1}, {0x2165, 2307, 1}, {0x1f92, 179, 2}, {0x2c92, 2613, 1}, {0x0392, 742, 1}, {0x2161, 2295, 1}, {0xab92, 1550, 1}, {0xa792, 3117, 1}, {0x10c92, 3411, 1}, {0x118b0, 3558, 1}, {0x1f5f, 2199, 1}, {0x1e8e, 1926, 1}, {0x048e, 1091, 1}, {0x018e, 453, 1}, {0x1f8e, 159, 2}, {0x2c8e, 2607, 1}, {0x038e, 833, 1}, {0xa692, 2961, 1}, {0xab8e, 1538, 1}, {0x0055, 59, 1}, {0x10c8e, 3399, 1}, {0x1f5d, 2196, 1}, {0x212a, 27, 1}, {0x04cb, 1181, 1}, {0x01cb, 425, 1}, {0x1fcb, 2241, 1}, {0x118ae, 3552, 1}, {0x0502, 1265, 1}, {0x00cb, 111, 1}, {0xa68e, 2955, 1}, {0x1e8a, 1920, 1}, {0x048a, 1085, 1}, {0x018a, 622, 1}, {0x1f8a, 139, 2}, {0x2c8a, 2601, 1}, {0x038a, 736, 1}, {0x2c67, 2571, 1}, {0xab8a, 1526, 1}, {0x1e86, 1914, 1}, {0x10c8a, 3387, 1}, {0x0186, 616, 1}, {0x1f86, 159, 2}, {0x2c86, 2595, 1}, {0x0386, 727, 1}, {0xff35, 3219, 1}, {0xab86, 1514, 1}, {0xa786, 3108, 1}, {0x10c86, 3375, 1}, {0xa68a, 2949, 1}, {0x0555, 1442, 1}, {0x1ebc, 1980, 1}, {0x04bc, 1160, 1}, {0x01bc, 411, 1}, {0x1fbc, 62, 2}, {0x2cbc, 2676, 1}, {0x1f5b, 2193, 1}, {0xa686, 2943, 1}, {0xabbc, 1676, 1}, {0x1eb8, 1974, 1}, {0x04b8, 1154, 1}, {0x01b8, 408, 1}, {0x1fb8, 2268, 1}, {0x2cb8, 2670, 1}, {0x01db, 450, 1}, {0x1fdb, 2247, 1}, {0xabb8, 1664, 1}, {0x10bc, 2829, 1}, {0x00db, 156, 1}, {0x1eb6, 1971, 1}, {0x04b6, 1151, 1}, {0xff33, 3213, 1}, {0x1fb6, 58, 2}, {0x2cb6, 2667, 1}, {0xff2a, 3186, 1}, {0x10b8, 2817, 1}, {0xabb6, 1658, 1}, {0xa7b6, 3153, 1}, {0x10426, 3351, 1}, {0x1e26, 1769, 1}, {0x0426, 956, 1}, {0x0126, 228, 1}, {0x0053, 52, 1}, {0x2c26, 2535, 1}, {0x0057, 65, 1}, {0x10b6, 2811, 1}, {0x022a, 562, 1}, {0xa726, 2982, 1}, {0x1e2e, 1781, 1}, {0x042e, 980, 1}, {0x012e, 240, 1}, {0x1f2e, 2142, 1}, {0x2c2e, 2559, 1}, {0xffffffff, -1, 0}, {0x2167, 2313, 1}, {0xffffffff, -1, 0}, {0xa72e, 2994, 1}, {0x1e2c, 1778, 1}, {0x042c, 974, 1}, {0x012c, 237, 1}, {0x1f2c, 2136, 1}, {0x2c2c, 2553, 1}, {0x1f6f, 2223, 1}, {0x2c6f, 604, 1}, {0xabbf, 1685, 1}, {0xa72c, 2991, 1}, {0x1e28, 1772, 1}, {0x0428, 962, 1}, {0x0128, 231, 1}, {0x1f28, 2124, 1}, {0x2c28, 2541, 1}, {0xffffffff, -1, 0}, {0x0553, 1436, 1}, {0x10bf, 2838, 1}, {0xa728, 2985, 1}, {0x0526, 1319, 1}, {0x0202, 505, 1}, {0x1e40, 1808, 1}, {0x10424, 3345, 1}, {0x1e24, 1766, 1}, {0x0424, 950, 1}, {0x0124, 225, 1}, {0xffffffff, -1, 0}, {0x2c24, 2529, 1}, {0x052e, 1331, 1}, {0xa740, 3018, 1}, {0x118bc, 3594, 1}, {0xa724, 2979, 1}, {0x1ef2, 2061, 1}, {0x04f2, 1241, 1}, {0x01f2, 483, 1}, {0x1ff2, 257, 2}, {0x2cf2, 2742, 1}, {0x052c, 1328, 1}, {0x118b8, 3582, 1}, {0xa640, 2865, 1}, {0x10422, 3339, 1}, {0x1e22, 1763, 1}, {0x0422, 944, 1}, {0x0122, 222, 1}, {0x2126, 820, 1}, {0x2c22, 2523, 1}, {0x0528, 1322, 1}, {0x01f1, 483, 1}, {0x118b6, 3576, 1}, {0xa722, 2976, 1}, {0x03f1, 796, 1}, {0x1ebe, 1983, 1}, {0x04be, 1163, 1}, {0xfb02, 12, 2}, {0x1fbe, 767, 1}, {0x2cbe, 2679, 1}, {0x01b5, 405, 1}, {0x0540, 1379, 1}, {0xabbe, 1682, 1}, {0x0524, 1316, 1}, {0x00b5, 779, 1}, {0xabb5, 1655, 1}, {0x1eba, 1977, 1}, {0x04ba, 1157, 1}, {0x216f, 2337, 1}, {0x1fba, 2226, 1}, {0x2cba, 2673, 1}, {0x10be, 2835, 1}, {0x0051, 46, 1}, {0xabba, 1670, 1}, {0x10b5, 2808, 1}, {0x1e6e, 1878, 1}, {0x046e, 1055, 1}, {0x016e, 330, 1}, {0x1f6e, 2220, 1}, {0x2c6e, 664, 1}, {0x118bf, 3603, 1}, {0x0522, 1313, 1}, {0x10ba, 2823, 1}, {0xa76e, 3087, 1}, {0x1eb4, 1968, 1}, {0x04b4, 1148, 1}, {0x2c75, 2583, 1}, {0x1fb4, 50, 2}, {0x2cb4, 2664, 1}, {0xab75, 1463, 1}, {0x1ec2, 1989, 1}, {0xabb4, 1652, 1}, {0xa7b4, 3150, 1}, {0x1fc2, 253, 2}, {0x2cc2, 2685, 1}, {0x03c2, 800, 1}, {0x00c2, 83, 1}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xff26, 3174, 1}, {0x10b4, 2805, 1}, {0x1eca, 2001, 1}, {0x0551, 1430, 1}, {0x01ca, 425, 1}, {0x1fca, 2238, 1}, {0x2cca, 2697, 1}, {0x10c2, 2847, 1}, {0x00ca, 108, 1}, {0xff2e, 3198, 1}, {0x1e8c, 1923, 1}, {0x048c, 1088, 1}, {0x0226, 556, 1}, {0x1f8c, 149, 2}, {0x2c8c, 2604, 1}, {0x038c, 830, 1}, {0xffffffff, -1, 0}, {0xab8c, 1532, 1}, {0xff2c, 3192, 1}, {0x10c8c, 3393, 1}, {0x1ec4, 1992, 1}, {0x022e, 568, 1}, {0x01c4, 417, 1}, {0x1fc4, 54, 2}, {0x2cc4, 2688, 1}, {0xffffffff, -1, 0}, {0x00c4, 89, 1}, {0xff28, 3180, 1}, {0xa68c, 2952, 1}, {0x01cf, 432, 1}, {0x022c, 565, 1}, {0x118be, 3600, 1}, {0x03cf, 839, 1}, {0x00cf, 123, 1}, {0x118b5, 3573, 1}, {0xffffffff, -1, 0}, {0x10c4, 2853, 1}, {0x216e, 2334, 1}, {0x24cb, 2406, 1}, {0x0228, 559, 1}, {0xff24, 3168, 1}, {0xffffffff, -1, 0}, {0x118ba, 3588, 1}, {0x1efe, 2079, 1}, {0x04fe, 1259, 1}, {0x01fe, 499, 1}, {0x1e9e, 24, 2}, {0x049e, 1115, 1}, {0x03fe, 721, 1}, {0x1f9e, 199, 2}, {0x2c9e, 2631, 1}, {0x039e, 786, 1}, {0x0224, 553, 1}, {0xab9e, 1586, 1}, {0xa79e, 3132, 1}, {0x10c9e, 3447, 1}, {0x01f7, 414, 1}, {0x1ff7, 67, 3}, {0xff22, 3162, 1}, {0x03f7, 884, 1}, {0x118b4, 3570, 1}, {0x049c, 1112, 1}, {0x019c, 661, 1}, {0x1f9c, 189, 2}, {0x2c9c, 2628, 1}, {0x039c, 779, 1}, {0x24bc, 2361, 1}, {0xab9c, 1580, 1}, {0xa79c, 3129, 1}, {0x10c9c, 3441, 1}, {0x0222, 550, 1}, {0x1e7c, 1899, 1}, {0x047c, 1076, 1}, {0x1e82, 1908, 1}, {0x24b8, 2349, 1}, {0x0182, 357, 1}, {0x1f82, 139, 2}, {0x2c82, 2589, 1}, {0xab7c, 1484, 1}, {0xffffffff, -1, 0}, {0xab82, 1502, 1}, {0xa782, 3102, 1}, {0x10c82, 3363, 1}, {0x2c63, 1709, 1}, {0x24b6, 2343, 1}, {0x1e80, 1905, 1}, {0x0480, 1082, 1}, {0x1f59, 2190, 1}, {0x1f80, 129, 2}, {0x2c80, 2586, 1}, {0x0059, 71, 1}, {0xa682, 2937, 1}, {0xab80, 1496, 1}, {0xa780, 3099, 1}, {0x10c80, 3357, 1}, {0xffffffff, -1, 0}, {0x1e4c, 1826, 1}, {0x0145, 270, 1}, {0x014c, 279, 1}, {0x1f4c, 2184, 1}, {0x0345, 767, 1}, {0x0045, 12, 1}, {0x004c, 31, 1}, {0xa680, 2934, 1}, {0xa74c, 3036, 1}, {0x1e4a, 1823, 1}, {0x01d5, 441, 1}, {0x014a, 276, 1}, {0x1f4a, 2178, 1}, {0x03d5, 810, 1}, {0x00d5, 141, 1}, {0x004a, 24, 1}, {0x24bf, 2370, 1}, {0xa74a, 3033, 1}, {0xa64c, 2883, 1}, {0x1041c, 3321, 1}, {0x1e1c, 1754, 1}, {0x041c, 926, 1}, {0x011c, 213, 1}, {0x1f1c, 2118, 1}, {0x2c1c, 2505, 1}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xa64a, 2880, 1}, {0x1041a, 3315, 1}, {0x1e1a, 1751, 1}, {0x041a, 920, 1}, {0x011a, 210, 1}, {0x1f1a, 2112, 1}, {0x2c1a, 2499, 1}, {0xabbd, 1679, 1}, {0x0545, 1394, 1}, {0x054c, 1415, 1}, {0x10418, 3309, 1}, {0x1e18, 1748, 1}, {0x0418, 914, 1}, {0x0118, 207, 1}, {0x1f18, 2106, 1}, {0x2c18, 2493, 1}, {0x10bd, 2832, 1}, {0x2163, 2301, 1}, {0x054a, 1409, 1}, {0x1040e, 3279, 1}, {0x1e0e, 1733, 1}, {0x040e, 1028, 1}, {0x010e, 192, 1}, {0x1f0e, 2100, 1}, {0x2c0e, 2463, 1}, {0x1efc, 2076, 1}, {0x04fc, 1256, 1}, {0x01fc, 496, 1}, {0x1ffc, 96, 2}, {0x051c, 1304, 1}, {0x1040c, 3273, 1}, {0x1e0c, 1730, 1}, {0x040c, 1022, 1}, {0x010c, 189, 1}, {0x1f0c, 2094, 1}, {0x2c0c, 2457, 1}, {0x1f6d, 2217, 1}, {0x2c6d, 607, 1}, {0x051a, 1301, 1}, {0x24be, 2367, 1}, {0x10408, 3261, 1}, {0x1e08, 1724, 1}, {0x0408, 1010, 1}, {0x0108, 183, 1}, {0x1f08, 2082, 1}, {0x2c08, 2445, 1}, {0x04c9, 1178, 1}, {0x0518, 1298, 1}, {0x1fc9, 2235, 1}, {0xffffffff, -1, 0}, {0x24ba, 2355, 1}, {0x00c9, 105, 1}, {0x10416, 3303, 1}, {0x1e16, 1745, 1}, {0x0416, 908, 1}, {0x0116, 204, 1}, {0x050e, 1283, 1}, {0x2c16, 2487, 1}, {0x10414, 3297, 1}, {0x1e14, 1742, 1}, {0x0414, 902, 1}, {0x0114, 201, 1}, {0x042b, 971, 1}, {0x2c14, 2481, 1}, {0x1f2b, 2133, 1}, {0x2c2b, 2550, 1}, {0xffffffff, -1, 0}, {0x050c, 1280, 1}, {0x10406, 3255, 1}, {0x1e06, 1721, 1}, {0x0406, 1004, 1}, {0x0106, 180, 1}, {0x13fb, 1697, 1}, {0x2c06, 2439, 1}, {0x24c2, 2379, 1}, {0x118bd, 3597, 1}, {0xffffffff, -1, 0}, {0x0508, 1274, 1}, {0x10404, 3249, 1}, {0x1e04, 1718, 1}, {0x0404, 998, 1}, {0x0104, 177, 1}, {0x1f95, 194, 2}, {0x2c04, 2433, 1}, {0x0395, 752, 1}, {0x24ca, 2403, 1}, {0xab95, 1559, 1}, {0x0531, 1334, 1}, {0x10c95, 3420, 1}, {0x0516, 1295, 1}, {0x1e6c, 1875, 1}, {0x046c, 1052, 1}, {0x016c, 327, 1}, {0x1f6c, 2214, 1}, {0x216d, 2331, 1}, {0x0514, 1292, 1}, {0x0245, 697, 1}, {0x024c, 598, 1}, {0xa76c, 3084, 1}, {0x10400, 3237, 1}, {0x1e00, 1712, 1}, {0x0400, 986, 1}, {0x0100, 171, 1}, {0x24c4, 2385, 1}, {0x2c00, 2421, 1}, {0x0506, 1271, 1}, {0x024a, 595, 1}, {0x1fab, 224, 2}, {0xa66c, 2931, 1}, {0x03ab, 827, 1}, {0x24cf, 2418, 1}, {0xabab, 1625, 1}, {0xa7ab, 631, 1}, {0x10cab, 3486, 1}, {0xffffffff, -1, 0}, {0x0504, 1268, 1}, {0xffffffff, -1, 0}, {0x021c, 544, 1}, {0x01a9, 679, 1}, {0x1fa9, 214, 2}, {0x10ab, 2778, 1}, {0x03a9, 820, 1}, {0x212b, 92, 1}, {0xaba9, 1619, 1}, {0x1e88, 1917, 1}, {0x10ca9, 3480, 1}, {0x021a, 541, 1}, {0x1f88, 129, 2}, {0x2c88, 2598, 1}, {0x0388, 730, 1}, {0x13fd, 1703, 1}, {0xab88, 1520, 1}, {0x10a9, 2772, 1}, {0x10c88, 3381, 1}, {0xffffffff, -1, 0}, {0x0218, 538, 1}, {0x0500, 1262, 1}, {0x1f4d, 2187, 1}, {0x01a7, 393, 1}, {0x1fa7, 244, 2}, {0x004d, 34, 1}, {0x03a7, 814, 1}, {0xa688, 2946, 1}, {0xaba7, 1613, 1}, {0x020e, 523, 1}, {0x10ca7, 3474, 1}, {0x1e6a, 1872, 1}, {0x046a, 1049, 1}, {0x016a, 324, 1}, {0x1f6a, 2208, 1}, {0xffffffff, -1, 0}, {0x216c, 2328, 1}, {0x10a7, 2766, 1}, {0x01d1, 435, 1}, {0xa76a, 3081, 1}, {0x020c, 520, 1}, {0x03d1, 762, 1}, {0x00d1, 129, 1}, {0x1e68, 1869, 1}, {0x0468, 1046, 1}, {0x0168, 321, 1}, {0x1f68, 2202, 1}, {0xffffffff, -1, 0}, {0xff31, 3207, 1}, {0xa66a, 2928, 1}, {0x0208, 514, 1}, {0xa768, 3078, 1}, {0x1e64, 1863, 1}, {0x0464, 1040, 1}, {0x0164, 315, 1}, {0x054d, 1418, 1}, {0x2c64, 673, 1}, {0xffffffff, -1, 0}, {0xff2b, 3189, 1}, {0xffffffff, -1, 0}, {0xa764, 3072, 1}, {0xa668, 2925, 1}, {0x0216, 535, 1}, {0xffffffff, -1, 0}, {0x118ab, 3543, 1}, {0x1e62, 1860, 1}, {0x0462, 1037, 1}, {0x0162, 312, 1}, {0x0214, 532, 1}, {0x2c62, 655, 1}, {0xa664, 2919, 1}, {0x1ed2, 2013, 1}, {0x04d2, 1193, 1}, {0xa762, 3069, 1}, {0x1fd2, 20, 3}, {0x2cd2, 2709, 1}, {0x118a9, 3537, 1}, {0x00d2, 132, 1}, {0x0206, 511, 1}, {0x10420, 3333, 1}, {0x1e20, 1760, 1}, {0x0420, 938, 1}, {0x0120, 219, 1}, {0xa662, 2916, 1}, {0x2c20, 2517, 1}, {0x1e60, 1856, 1}, {0x0460, 1034, 1}, {0x0160, 309, 1}, {0x0204, 508, 1}, {0x2c60, 2562, 1}, {0xffffffff, -1, 0}, {0x24bd, 2364, 1}, {0x216a, 2322, 1}, {0xa760, 3066, 1}, {0xffffffff, -1, 0}, {0xfb16, 125, 2}, {0x118a7, 3531, 1}, {0x1efa, 2073, 1}, {0x04fa, 1253, 1}, {0x01fa, 493, 1}, {0x1ffa, 2262, 1}, {0xfb14, 109, 2}, {0x03fa, 887, 1}, {0xa660, 2913, 1}, {0x2168, 2316, 1}, {0x01b7, 700, 1}, {0x1fb7, 10, 3}, {0x1f6b, 2211, 1}, {0x2c6b, 2577, 1}, {0x0200, 502, 1}, {0xabb7, 1661, 1}, {0xfb06, 29, 2}, {0x1e56, 1841, 1}, {0x2164, 2304, 1}, {0x0156, 294, 1}, {0x1f56, 62, 3}, {0x0520, 1310, 1}, {0x004f, 40, 1}, {0x0056, 62, 1}, {0x10b7, 2814, 1}, {0xa756, 3051, 1}, {0xfb04, 5, 3}, {0x1e78, 1893, 1}, {0x0478, 1070, 1}, {0x0178, 168, 1}, {0x1e54, 1838, 1}, {0x2162, 2298, 1}, {0x0154, 291, 1}, {0x1f54, 57, 3}, {0xab78, 1472, 1}, {0xa656, 2898, 1}, {0x0054, 56, 1}, {0x1e52, 1835, 1}, {0xa754, 3048, 1}, {0x0152, 288, 1}, {0x1f52, 52, 3}, {0x24c9, 2400, 1}, {0x1e32, 1787, 1}, {0x0052, 49, 1}, {0x0132, 243, 1}, {0xa752, 3045, 1}, {0xffffffff, -1, 0}, {0xfb00, 4, 2}, {0xa654, 2895, 1}, {0xffffffff, -1, 0}, {0xa732, 2997, 1}, {0x2160, 2292, 1}, {0x054f, 1424, 1}, {0x0556, 1445, 1}, {0x1e50, 1832, 1}, {0xa652, 2892, 1}, {0x0150, 285, 1}, {0x1f50, 84, 2}, {0x017b, 348, 1}, {0x1e4e, 1829, 1}, {0x0050, 43, 1}, {0x014e, 282, 1}, {0xa750, 3042, 1}, {0xab7b, 1481, 1}, {0xa77b, 3093, 1}, {0x004e, 37, 1}, {0x0554, 1439, 1}, {0xa74e, 3039, 1}, {0x1e48, 1820, 1}, {0xffffffff, -1, 0}, {0x216b, 2325, 1}, {0x1f48, 2172, 1}, {0xa650, 2889, 1}, {0x0552, 1433, 1}, {0x0048, 21, 1}, {0xffffffff, -1, 0}, {0xa748, 3030, 1}, {0xa64e, 2886, 1}, {0x0532, 1337, 1}, {0x1041e, 3327, 1}, {0x1e1e, 1757, 1}, {0x041e, 932, 1}, {0x011e, 216, 1}, {0x118b7, 3579, 1}, {0x2c1e, 2511, 1}, {0xffffffff, -1, 0}, {0xa648, 2877, 1}, {0x1ff9, 2253, 1}, {0xffffffff, -1, 0}, {0x03f9, 878, 1}, {0x0550, 1427, 1}, {0x10412, 3291, 1}, {0x1e12, 1739, 1}, {0x0412, 896, 1}, {0x0112, 198, 1}, {0x054e, 1421, 1}, {0x2c12, 2475, 1}, {0x10410, 3285, 1}, {0x1e10, 1736, 1}, {0x0410, 890, 1}, {0x0110, 195, 1}, {0xffffffff, -1, 0}, {0x2c10, 2469, 1}, {0x2132, 2289, 1}, {0x0548, 1403, 1}, {0x1ef8, 2070, 1}, {0x04f8, 1250, 1}, {0x01f8, 490, 1}, {0x1ff8, 2250, 1}, {0x0220, 381, 1}, {0x1ee2, 2037, 1}, {0x04e2, 1217, 1}, {0x01e2, 462, 1}, {0x1fe2, 36, 3}, {0x2ce2, 2733, 1}, {0x03e2, 857, 1}, {0x051e, 1307, 1}, {0x1ede, 2031, 1}, {0x04de, 1211, 1}, {0x01de, 456, 1}, {0xffffffff, -1, 0}, {0x2cde, 2727, 1}, {0x03de, 851, 1}, {0x00de, 165, 1}, {0x1f69, 2205, 1}, {0x2c69, 2574, 1}, {0x1eda, 2025, 1}, {0x04da, 1205, 1}, {0x0512, 1289, 1}, {0x1fda, 2244, 1}, {0x2cda, 2721, 1}, {0x03da, 845, 1}, {0x00da, 153, 1}, {0xffffffff, -1, 0}, {0x0510, 1286, 1}, {0x1ed8, 2022, 1}, {0x04d8, 1202, 1}, {0xffffffff, -1, 0}, {0x1fd8, 2274, 1}, {0x2cd8, 2718, 1}, {0x03d8, 842, 1}, {0x00d8, 147, 1}, {0x1ed6, 2019, 1}, {0x04d6, 1199, 1}, {0xffffffff, -1, 0}, {0x1fd6, 76, 2}, {0x2cd6, 2715, 1}, {0x03d6, 792, 1}, {0x00d6, 144, 1}, {0x1ec8, 1998, 1}, {0xffffffff, -1, 0}, {0x01c8, 421, 1}, {0x1fc8, 2232, 1}, {0x2cc8, 2694, 1}, {0xff32, 3210, 1}, {0x00c8, 102, 1}, {0x04c7, 1175, 1}, {0x01c7, 421, 1}, {0x1fc7, 15, 3}, {0x1ec0, 1986, 1}, {0x04c0, 1187, 1}, {0x00c7, 99, 1}, {0xffffffff, -1, 0}, {0x2cc0, 2682, 1}, {0x0179, 345, 1}, {0x00c0, 77, 1}, {0x0232, 574, 1}, {0x01b3, 402, 1}, {0x1fb3, 62, 2}, {0xab79, 1475, 1}, {0xa779, 3090, 1}, {0x10c7, 2859, 1}, {0xabb3, 1649, 1}, {0xa7b3, 3156, 1}, {0x1fa5, 234, 2}, {0x10c0, 2841, 1}, {0x03a5, 807, 1}, {0xffffffff, -1, 0}, {0xaba5, 1607, 1}, {0x01b1, 691, 1}, {0x10ca5, 3468, 1}, {0x10b3, 2802, 1}, {0x2169, 2319, 1}, {0x024e, 601, 1}, {0xabb1, 1643, 1}, {0xa7b1, 682, 1}, {0x10cb1, 3504, 1}, {0x10a5, 2760, 1}, {0xffffffff, -1, 0}, {0x01af, 399, 1}, {0x1faf, 244, 2}, {0xffffffff, -1, 0}, {0x0248, 592, 1}, {0x10b1, 2796, 1}, {0xabaf, 1637, 1}, {0x1fad, 234, 2}, {0x10caf, 3498, 1}, {0x04cd, 1184, 1}, {0x01cd, 429, 1}, {0xabad, 1631, 1}, {0xa7ad, 658, 1}, {0x10cad, 3492, 1}, {0x00cd, 117, 1}, {0x10af, 2790, 1}, {0x021e, 547, 1}, {0x1fa3, 224, 2}, {0xffffffff, -1, 0}, {0x03a3, 800, 1}, {0x10ad, 2784, 1}, {0xaba3, 1601, 1}, {0xffffffff, -1, 0}, {0x10ca3, 3462, 1}, {0x10cd, 2862, 1}, {0x1fa1, 214, 2}, {0x24b7, 2346, 1}, {0x03a1, 796, 1}, {0x0212, 529, 1}, {0xaba1, 1595, 1}, {0x10a3, 2754, 1}, {0x10ca1, 3456, 1}, {0x01d3, 438, 1}, {0x1fd3, 25, 3}, {0x0210, 526, 1}, {0xffffffff, -1, 0}, {0x00d3, 135, 1}, {0x1e97, 34, 2}, {0x10a1, 2748, 1}, {0x0197, 649, 1}, {0x1f97, 204, 2}, {0xffffffff, -1, 0}, {0x0397, 759, 1}, {0x1041d, 3324, 1}, {0xab97, 1565, 1}, {0x041d, 929, 1}, {0x10c97, 3426, 1}, {0x1f1d, 2121, 1}, {0x2c1d, 2508, 1}, {0x1e72, 1884, 1}, {0x0472, 1061, 1}, {0x0172, 336, 1}, {0x118b3, 3567, 1}, {0x2c72, 2580, 1}, {0x0372, 712, 1}, {0x1041b, 3318, 1}, {0xab72, 1454, 1}, {0x041b, 923, 1}, {0x118a5, 3525, 1}, {0x1f1b, 2115, 1}, {0x2c1b, 2502, 1}, {0x1e70, 1881, 1}, {0x0470, 1058, 1}, {0x0170, 333, 1}, {0x118b1, 3561, 1}, {0x2c70, 610, 1}, {0x0370, 709, 1}, {0x1e46, 1817, 1}, {0xab70, 1448, 1}, {0x1e66, 1866, 1}, {0x0466, 1043, 1}, {0x0166, 318, 1}, {0x1e44, 1814, 1}, {0x0046, 15, 1}, {0x118af, 3555, 1}, {0xa746, 3027, 1}, {0xffffffff, -1, 0}, {0xa766, 3075, 1}, {0x0044, 9, 1}, {0x118ad, 3549, 1}, {0xa744, 3024, 1}, {0x1e7a, 1896, 1}, {0x047a, 1073, 1}, {0x1e3a, 1799, 1}, {0xffffffff, -1, 0}, {0xa646, 2874, 1}, {0x1f3a, 2154, 1}, {0xa666, 2922, 1}, {0xab7a, 1478, 1}, {0x118a3, 3519, 1}, {0xa644, 2871, 1}, {0xa73a, 3009, 1}, {0xffffffff, -1, 0}, {0x1ef4, 2064, 1}, {0x04f4, 1244, 1}, {0x01f4, 487, 1}, {0x1ff4, 101, 2}, {0x118a1, 3513, 1}, {0x03f4, 762, 1}, {0x1eec, 2052, 1}, {0x04ec, 1232, 1}, {0x01ec, 477, 1}, {0x1fec, 2286, 1}, {0x0546, 1397, 1}, {0x03ec, 872, 1}, {0xffffffff, -1, 0}, {0x013f, 261, 1}, {0x1f3f, 2169, 1}, {0x0544, 1391, 1}, {0x1eea, 2049, 1}, {0x04ea, 1229, 1}, {0x01ea, 474, 1}, {0x1fea, 2256, 1}, {0xffffffff, -1, 0}, {0x03ea, 869, 1}, {0x1ee8, 2046, 1}, {0x04e8, 1226, 1}, {0x01e8, 471, 1}, {0x1fe8, 2280, 1}, {0x053a, 1361, 1}, {0x03e8, 866, 1}, {0x1ee6, 2043, 1}, {0x04e6, 1223, 1}, {0x01e6, 468, 1}, {0x1fe6, 88, 2}, {0x1f4b, 2181, 1}, {0x03e6, 863, 1}, {0x1e5e, 1853, 1}, {0x004b, 27, 1}, {0x015e, 306, 1}, {0x2166, 2310, 1}, {0x1ee4, 2040, 1}, {0x04e4, 1220, 1}, {0x01e4, 465, 1}, {0x1fe4, 80, 2}, {0xa75e, 3063, 1}, {0x03e4, 860, 1}, {0x1ee0, 2034, 1}, {0x04e0, 1214, 1}, {0x01e0, 459, 1}, {0x053f, 1376, 1}, {0x2ce0, 2730, 1}, {0x03e0, 854, 1}, {0x1edc, 2028, 1}, {0x04dc, 1208, 1}, {0xa65e, 2910, 1}, {0xffffffff, -1, 0}, {0x2cdc, 2724, 1}, {0x03dc, 848, 1}, {0x00dc, 159, 1}, {0x1ed0, 2010, 1}, {0x04d0, 1190, 1}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0x2cd0, 2706, 1}, {0x03d0, 742, 1}, {0x00d0, 126, 1}, {0x1ecc, 2004, 1}, {0x054b, 1412, 1}, {0xffffffff, -1, 0}, {0x1fcc, 71, 2}, {0x2ccc, 2700, 1}, {0x1ec6, 1995, 1}, {0x00cc, 114, 1}, {0xffffffff, -1, 0}, {0x1fc6, 67, 2}, {0x2cc6, 2691, 1}, {0x24c8, 2397, 1}, {0x00c6, 96, 1}, {0x04c5, 1172, 1}, {0x01c5, 417, 1}, {0xffffffff, -1, 0}, {0x1fbb, 2229, 1}, {0x24c7, 2394, 1}, {0x00c5, 92, 1}, {0x1fb9, 2271, 1}, {0xabbb, 1673, 1}, {0x24c0, 2373, 1}, {0x04c3, 1169, 1}, {0xabb9, 1667, 1}, {0x1fc3, 71, 2}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0x00c3, 86, 1}, {0x10c5, 2856, 1}, {0x10bb, 2826, 1}, {0x1ed4, 2016, 1}, {0x04d4, 1196, 1}, {0x10b9, 2820, 1}, {0x13fc, 1700, 1}, {0x2cd4, 2712, 1}, {0x0246, 589, 1}, {0x00d4, 138, 1}, {0x10c3, 2850, 1}, {0xffffffff, -1, 0}, {0xff3a, 3234, 1}, {0x0244, 688, 1}, {0x019f, 670, 1}, {0x1f9f, 204, 2}, {0xffffffff, -1, 0}, {0x039f, 789, 1}, {0xffffffff, -1, 0}, {0xab9f, 1589, 1}, {0xffffffff, -1, 0}, {0x10c9f, 3450, 1}, {0x019d, 667, 1}, {0x1f9d, 194, 2}, {0x023a, 2565, 1}, {0x039d, 783, 1}, {0x1e5a, 1847, 1}, {0xab9d, 1583, 1}, {0x015a, 300, 1}, {0x10c9d, 3444, 1}, {0x1e9b, 1856, 1}, {0x24cd, 2412, 1}, {0x005a, 74, 1}, {0x1f9b, 184, 2}, {0xa75a, 3057, 1}, {0x039b, 776, 1}, {0x1ece, 2007, 1}, {0xab9b, 1577, 1}, {0x1e99, 42, 2}, {0x10c9b, 3438, 1}, {0x2cce, 2703, 1}, {0x1f99, 174, 2}, {0x00ce, 120, 1}, {0x0399, 767, 1}, {0xa65a, 2904, 1}, {0xab99, 1571, 1}, {0xffffffff, -1, 0}, {0x10c99, 3432, 1}, {0x0193, 634, 1}, {0x1f93, 184, 2}, {0x1e58, 1844, 1}, {0x0393, 746, 1}, {0x0158, 297, 1}, {0xab93, 1553, 1}, {0xffffffff, -1, 0}, {0x10c93, 3414, 1}, {0x0058, 68, 1}, {0x042d, 977, 1}, {0xa758, 3054, 1}, {0x1f2d, 2139, 1}, {0x2c2d, 2556, 1}, {0x118bb, 3591, 1}, {0x0191, 369, 1}, {0x1f91, 174, 2}, {0x118b9, 3585, 1}, {0x0391, 739, 1}, {0xffffffff, -1, 0}, {0xab91, 1547, 1}, {0xa658, 2901, 1}, {0x10c91, 3408, 1}, {0x018f, 625, 1}, {0x1f8f, 164, 2}, {0xffffffff, -1, 0}, {0x038f, 836, 1}, {0xffffffff, -1, 0}, {0xab8f, 1541, 1}, {0xffffffff, -1, 0}, {0x10c8f, 3402, 1}, {0x018b, 366, 1}, {0x1f8b, 144, 2}, {0xffffffff, -1, 0}, {0x0187, 363, 1}, {0x1f87, 164, 2}, {0xab8b, 1529, 1}, {0xa78b, 3111, 1}, {0x10c8b, 3390, 1}, {0xab87, 1517, 1}, {0x04c1, 1166, 1}, {0x10c87, 3378, 1}, {0x1e7e, 1902, 1}, {0x047e, 1079, 1}, {0xffffffff, -1, 0}, {0x00c1, 80, 1}, {0x2c7e, 580, 1}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xab7e, 1490, 1}, {0xa77e, 3096, 1}, {0x1e76, 1890, 1}, {0x0476, 1067, 1}, {0x0176, 342, 1}, {0x1e42, 1811, 1}, {0x10c1, 2844, 1}, {0x0376, 715, 1}, {0x1e36, 1793, 1}, {0xab76, 1466, 1}, {0x0136, 249, 1}, {0x0042, 3, 1}, {0x1e3e, 1805, 1}, {0xa742, 3021, 1}, {0x1e38, 1796, 1}, {0x1f3e, 2166, 1}, {0xa736, 3003, 1}, {0x1f38, 2148, 1}, {0xffffffff, -1, 0}, {0x0587, 105, 2}, {0xa73e, 3015, 1}, {0xffffffff, -1, 0}, {0xa738, 3006, 1}, {0xa642, 2868, 1}, {0x1e5c, 1850, 1}, {0x1e34, 1790, 1}, {0x015c, 303, 1}, {0x0134, 246, 1}, {0x1ef6, 2067, 1}, {0x04f6, 1247, 1}, {0x01f6, 372, 1}, {0x1ff6, 92, 2}, {0xa75c, 3060, 1}, {0xa734, 3000, 1}, {0x1ef0, 2058, 1}, {0x04f0, 1238, 1}, {0x01f0, 20, 2}, {0xffffffff, -1, 0}, {0x1e30, 1784, 1}, {0x03f0, 772, 1}, {0x0130, 261, 2}, {0x0542, 1385, 1}, {0xa65c, 2907, 1}, {0x1f83, 144, 2}, {0x0536, 1349, 1}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xab83, 1505, 1}, {0x053e, 1373, 1}, {0x10c83, 3366, 1}, {0x0538, 1355, 1}, {0x1eee, 2055, 1}, {0x04ee, 1235, 1}, {0x01ee, 480, 1}, {0x1f8d, 154, 2}, {0xffffffff, -1, 0}, {0x03ee, 875, 1}, {0xffffffff, -1, 0}, {0xab8d, 1535, 1}, {0xa78d, 643, 1}, {0x10c8d, 3396, 1}, {0x0534, 1343, 1}, {0x0181, 613, 1}, {0x1f81, 134, 2}, {0x013d, 258, 1}, {0x1f3d, 2163, 1}, {0xffffffff, -1, 0}, {0xab81, 1499, 1}, {0x017f, 52, 1}, {0x10c81, 3360, 1}, {0x2c7f, 583, 1}, {0x037f, 881, 1}, {0xff2d, 3195, 1}, {0xab7f, 1493, 1}, {0x1e74, 1887, 1}, {0x0474, 1064, 1}, {0x0174, 339, 1}, {0x1e3c, 1802, 1}, {0x0149, 46, 2}, {0x1f49, 2175, 1}, {0x1f3c, 2160, 1}, {0xab74, 1460, 1}, {0x0049, 3606, 1}, {0x0143, 267, 1}, {0x24cc, 2409, 1}, {0xa73c, 3012, 1}, {0xffffffff, -1, 0}, {0x0043, 6, 1}, {0x0141, 264, 1}, {0x24c6, 2391, 1}, {0x013b, 255, 1}, {0x1f3b, 2157, 1}, {0x0041, 0, 1}, {0x0139, 252, 1}, {0x1f39, 2151, 1}, {0x24c5, 2388, 1}, {0x24bb, 2358, 1}, {0x13fa, 1694, 1}, {0x053d, 1370, 1}, {0x24b9, 2352, 1}, {0x0429, 965, 1}, {0x2183, 2340, 1}, {0x1f29, 2127, 1}, {0x2c29, 2544, 1}, {0x24c3, 2382, 1}, {0x10427, 3354, 1}, {0x10425, 3348, 1}, {0x0427, 959, 1}, {0x0425, 953, 1}, {0xffffffff, -1, 0}, {0x2c27, 2538, 1}, {0x2c25, 2532, 1}, {0x0549, 1406, 1}, {0x053c, 1367, 1}, {0x10423, 3342, 1}, {0xffffffff, -1, 0}, {0x0423, 947, 1}, {0x0543, 1388, 1}, {0xffffffff, -1, 0}, {0x2c23, 2526, 1}, {0xff36, 3222, 1}, {0xffffffff, -1, 0}, {0x0541, 1382, 1}, {0x10421, 3336, 1}, {0x053b, 1364, 1}, {0x0421, 941, 1}, {0xff38, 3228, 1}, {0x0539, 1358, 1}, {0x2c21, 2520, 1}, {0x10419, 3312, 1}, {0x10417, 3306, 1}, {0x0419, 917, 1}, {0x0417, 911, 1}, {0x1f19, 2109, 1}, {0x2c19, 2496, 1}, {0x2c17, 2490, 1}, {0x023e, 2568, 1}, {0xff34, 3216, 1}, {0x10415, 3300, 1}, {0x10413, 3294, 1}, {0x0415, 905, 1}, {0x0413, 899, 1}, {0xffffffff, -1, 0}, {0x2c15, 2484, 1}, {0x2c13, 2478, 1}, {0xffffffff, -1, 0}, {0x24ce, 2415, 1}, {0x1040f, 3282, 1}, {0xffffffff, -1, 0}, {0x040f, 1031, 1}, {0xff30, 3204, 1}, {0x1f0f, 2103, 1}, {0x2c0f, 2466, 1}, {0x1040d, 3276, 1}, {0xffffffff, -1, 0}, {0x040d, 1025, 1}, {0x0147, 273, 1}, {0x1f0d, 2097, 1}, {0x2c0d, 2460, 1}, {0x1040b, 3270, 1}, {0x0047, 18, 1}, {0x040b, 1019, 1}, {0x0230, 571, 1}, {0x1f0b, 2091, 1}, {0x2c0b, 2454, 1}, {0x10409, 3264, 1}, {0x10405, 3252, 1}, {0x0409, 1013, 1}, {0x0405, 1001, 1}, {0x1f09, 2085, 1}, {0x2c09, 2448, 1}, {0x2c05, 2436, 1}, {0x10403, 3246, 1}, {0x10401, 3240, 1}, {0x0403, 995, 1}, {0x0401, 989, 1}, {0xffffffff, -1, 0}, {0x2c03, 2430, 1}, {0x2c01, 2424, 1}, {0x13f9, 1691, 1}, {0x042f, 983, 1}, {0xffffffff, -1, 0}, {0x1f2f, 2145, 1}, {0x1041f, 3330, 1}, {0xffffffff, -1, 0}, {0x041f, 935, 1}, {0x023d, 378, 1}, {0x10411, 3288, 1}, {0x2c1f, 2514, 1}, {0x0411, 893, 1}, {0x0547, 1400, 1}, {0xffffffff, -1, 0}, {0x2c11, 2472, 1}, {0x10407, 3258, 1}, {0xffffffff, -1, 0}, {0x0407, 1007, 1}, {0x24c1, 2376, 1}, {0xffffffff, -1, 0}, {0x2c07, 2442, 1}, {0xffffffff, -1, 0}, {0x13f8, 1688, 1}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xff39, 3231, 1}, {0xffffffff, -1, 0}, {0x0243, 354, 1}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0x0241, 586, 1}, {0xff29, 3183, 1}, {0x023b, 577, 1}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xff27, 3177, 1}, {0xff25, 3171, 1}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xff23, 3165, 1}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xff21, 3159, 1}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xfb17, 117, 2}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xff2f, 3201, 1}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xfb15, 113, 2}, {0xfb13, 121, 2}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xfb05, 29, 2}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xfb03, 0, 3}, {0xfb01, 8, 2} }; if (0 == 0) { int key = hash(&code); if (key <= MAX_HASH_VALUE && key >= 0) { OnigCodePoint gcode = wordlist[key].code; if (code == gcode) return &wordlist[key]; } } return 0; }","unicode_unfold_key(OnigCodePoint code) { static const struct ByUnfoldKey wordlist[] = { {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0x1040a, 3267, 1}, {0x1e0a, 1727, 1}, {0x040a, 1016, 1}, {0x010a, 186, 1}, {0x1f0a, 2088, 1}, {0x2c0a, 2451, 1}, {0x0189, 619, 1}, {0x1f89, 134, 2}, {0x1f85, 154, 2}, {0x0389, 733, 1}, {0x03ff, 724, 1}, {0xab89, 1523, 1}, {0xab85, 1511, 1}, {0x10c89, 3384, 1}, {0x10c85, 3372, 1}, {0x1e84, 1911, 1}, {0x03f5, 752, 1}, {0x0184, 360, 1}, {0x1f84, 149, 2}, {0x2c84, 2592, 1}, {0x017d, 351, 1}, {0x1ff3, 96, 2}, {0xab84, 1508, 1}, {0xa784, 3105, 1}, {0x10c84, 3369, 1}, {0xab7d, 1487, 1}, {0xa77d, 1706, 1}, {0x1e98, 38, 2}, {0x0498, 1106, 1}, {0x0198, 375, 1}, {0x1f98, 169, 2}, {0x2c98, 2622, 1}, {0x0398, 762, 1}, {0xa684, 2940, 1}, {0xab98, 1568, 1}, {0xa798, 3123, 1}, {0x10c98, 3429, 1}, {0x050a, 1277, 1}, {0x1ffb, 2265, 1}, {0x1e96, 16, 2}, {0x0496, 1103, 1}, {0x0196, 652, 1}, {0x1f96, 199, 2}, {0x2c96, 2619, 1}, {0x0396, 756, 1}, {0xa698, 2970, 1}, {0xab96, 1562, 1}, {0xa796, 3120, 1}, {0x10c96, 3423, 1}, {0x1feb, 2259, 1}, {0x2ceb, 2736, 1}, {0x1e90, 1929, 1}, {0x0490, 1094, 1}, {0x0190, 628, 1}, {0x1f90, 169, 2}, {0x2c90, 2610, 1}, {0x0390, 25, 3}, {0xa696, 2967, 1}, {0xab90, 1544, 1}, {0xa790, 3114, 1}, {0x10c90, 3405, 1}, {0x01d7, 444, 1}, {0x1fd7, 31, 3}, {0x1ea6, 1947, 1}, {0x04a6, 1127, 1}, {0x01a6, 676, 1}, {0x1fa6, 239, 2}, {0x2ca6, 2643, 1}, {0x03a6, 810, 1}, {0xa690, 2958, 1}, {0xaba6, 1610, 1}, {0xa7a6, 3144, 1}, {0x10ca6, 3471, 1}, {0x1ea4, 1944, 1}, {0x04a4, 1124, 1}, {0x01a4, 390, 1}, {0x1fa4, 229, 2}, {0x2ca4, 2640, 1}, {0x03a4, 804, 1}, {0x10a6, 2763, 1}, {0xaba4, 1604, 1}, {0xa7a4, 3141, 1}, {0x10ca4, 3465, 1}, {0x1ea0, 1938, 1}, {0x04a0, 1118, 1}, {0x01a0, 384, 1}, {0x1fa0, 209, 2}, {0x2ca0, 2634, 1}, {0x03a0, 792, 1}, {0x10a4, 2757, 1}, {0xaba0, 1592, 1}, {0xa7a0, 3135, 1}, {0x10ca0, 3453, 1}, {0x1eb2, 1965, 1}, {0x04b2, 1145, 1}, {0x01b2, 694, 1}, {0x1fb2, 249, 2}, {0x2cb2, 2661, 1}, {0x03fd, 718, 1}, {0x10a0, 2745, 1}, {0xabb2, 1646, 1}, {0xa7b2, 703, 1}, {0x10cb2, 3507, 1}, {0x1eac, 1956, 1}, {0x04ac, 1136, 1}, {0x01ac, 396, 1}, {0x1fac, 229, 2}, {0x2cac, 2652, 1}, {0x0537, 1352, 1}, {0x10b2, 2799, 1}, {0xabac, 1628, 1}, {0xa7ac, 637, 1}, {0x10cac, 3489, 1}, {0x1eaa, 1953, 1}, {0x04aa, 1133, 1}, {0x00dd, 162, 1}, {0x1faa, 219, 2}, {0x2caa, 2649, 1}, {0x03aa, 824, 1}, {0x10ac, 2781, 1}, {0xabaa, 1622, 1}, {0xa7aa, 646, 1}, {0x10caa, 3483, 1}, {0x1ea8, 1950, 1}, {0x04a8, 1130, 1}, {0x020a, 517, 1}, {0x1fa8, 209, 2}, {0x2ca8, 2646, 1}, {0x03a8, 817, 1}, {0x10aa, 2775, 1}, {0xaba8, 1616, 1}, {0xa7a8, 3147, 1}, {0x10ca8, 3477, 1}, {0x1ea2, 1941, 1}, {0x04a2, 1121, 1}, {0x01a2, 387, 1}, {0x1fa2, 219, 2}, {0x2ca2, 2637, 1}, {0x118a6, 3528, 1}, {0x10a8, 2769, 1}, {0xaba2, 1598, 1}, {0xa7a2, 3138, 1}, {0x10ca2, 3459, 1}, {0x2ced, 2739, 1}, {0x1fe9, 2283, 1}, {0x1fe7, 47, 3}, {0x1eb0, 1962, 1}, {0x04b0, 1142, 1}, {0x118a4, 3522, 1}, {0x10a2, 2751, 1}, {0x2cb0, 2658, 1}, {0x03b0, 41, 3}, {0x1fe3, 41, 3}, {0xabb0, 1640, 1}, {0xa7b0, 706, 1}, {0x10cb0, 3501, 1}, {0x01d9, 447, 1}, {0x1fd9, 2277, 1}, {0x118a0, 3510, 1}, {0x00df, 24, 2}, {0x00d9, 150, 1}, {0xab77, 1469, 1}, {0x10b0, 2793, 1}, {0x1eae, 1959, 1}, {0x04ae, 1139, 1}, {0x01ae, 685, 1}, {0x1fae, 239, 2}, {0x2cae, 2655, 1}, {0x118b2, 3564, 1}, {0xab73, 1457, 1}, {0xabae, 1634, 1}, {0xab71, 1451, 1}, {0x10cae, 3495, 1}, {0x1e2a, 1775, 1}, {0x042a, 968, 1}, {0x012a, 234, 1}, {0x1f2a, 2130, 1}, {0x2c2a, 2547, 1}, {0x118ac, 3546, 1}, {0x10ae, 2787, 1}, {0x0535, 1346, 1}, {0xa72a, 2988, 1}, {0x1e9a, 0, 2}, {0x049a, 1109, 1}, {0xff37, 3225, 1}, {0x1f9a, 179, 2}, {0x2c9a, 2625, 1}, {0x039a, 772, 1}, {0x118aa, 3540, 1}, {0xab9a, 1574, 1}, {0xa79a, 3126, 1}, {0x10c9a, 3435, 1}, {0x1e94, 1935, 1}, {0x0494, 1100, 1}, {0x0194, 640, 1}, {0x1f94, 189, 2}, {0x2c94, 2616, 1}, {0x0394, 749, 1}, {0x118a8, 3534, 1}, {0xab94, 1556, 1}, {0xa69a, 2973, 1}, {0x10c94, 3417, 1}, {0x10402, 3243, 1}, {0x1e02, 1715, 1}, {0x0402, 992, 1}, {0x0102, 174, 1}, {0x0533, 1340, 1}, {0x2c02, 2427, 1}, {0x118a2, 3516, 1}, {0x052a, 1325, 1}, {0xa694, 2964, 1}, {0x1e92, 1932, 1}, {0x0492, 1097, 1}, {0x2165, 2307, 1}, {0x1f92, 179, 2}, {0x2c92, 2613, 1}, {0x0392, 742, 1}, {0x2161, 2295, 1}, {0xab92, 1550, 1}, {0xa792, 3117, 1}, {0x10c92, 3411, 1}, {0x118b0, 3558, 1}, {0x1f5f, 2199, 1}, {0x1e8e, 1926, 1}, {0x048e, 1091, 1}, {0x018e, 453, 1}, {0x1f8e, 159, 2}, {0x2c8e, 2607, 1}, {0x038e, 833, 1}, {0xa692, 2961, 1}, {0xab8e, 1538, 1}, {0x0055, 59, 1}, {0x10c8e, 3399, 1}, {0x1f5d, 2196, 1}, {0x212a, 27, 1}, {0x04cb, 1181, 1}, {0x01cb, 425, 1}, {0x1fcb, 2241, 1}, {0x118ae, 3552, 1}, {0x0502, 1265, 1}, {0x00cb, 111, 1}, {0xa68e, 2955, 1}, {0x1e8a, 1920, 1}, {0x048a, 1085, 1}, {0x018a, 622, 1}, {0x1f8a, 139, 2}, {0x2c8a, 2601, 1}, {0x038a, 736, 1}, {0x2c67, 2571, 1}, {0xab8a, 1526, 1}, {0x1e86, 1914, 1}, {0x10c8a, 3387, 1}, {0x0186, 616, 1}, {0x1f86, 159, 2}, {0x2c86, 2595, 1}, {0x0386, 727, 1}, {0xff35, 3219, 1}, {0xab86, 1514, 1}, {0xa786, 3108, 1}, {0x10c86, 3375, 1}, {0xa68a, 2949, 1}, {0x0555, 1442, 1}, {0x1ebc, 1980, 1}, {0x04bc, 1160, 1}, {0x01bc, 411, 1}, {0x1fbc, 62, 2}, {0x2cbc, 2676, 1}, {0x1f5b, 2193, 1}, {0xa686, 2943, 1}, {0xabbc, 1676, 1}, {0x1eb8, 1974, 1}, {0x04b8, 1154, 1}, {0x01b8, 408, 1}, {0x1fb8, 2268, 1}, {0x2cb8, 2670, 1}, {0x01db, 450, 1}, {0x1fdb, 2247, 1}, {0xabb8, 1664, 1}, {0x10bc, 2829, 1}, {0x00db, 156, 1}, {0x1eb6, 1971, 1}, {0x04b6, 1151, 1}, {0xff33, 3213, 1}, {0x1fb6, 58, 2}, {0x2cb6, 2667, 1}, {0xff2a, 3186, 1}, {0x10b8, 2817, 1}, {0xabb6, 1658, 1}, {0xa7b6, 3153, 1}, {0x10426, 3351, 1}, {0x1e26, 1769, 1}, {0x0426, 956, 1}, {0x0126, 228, 1}, {0x0053, 52, 1}, {0x2c26, 2535, 1}, {0x0057, 65, 1}, {0x10b6, 2811, 1}, {0x022a, 562, 1}, {0xa726, 2982, 1}, {0x1e2e, 1781, 1}, {0x042e, 980, 1}, {0x012e, 240, 1}, {0x1f2e, 2142, 1}, {0x2c2e, 2559, 1}, {0xffffffff, -1, 0}, {0x2167, 2313, 1}, {0xffffffff, -1, 0}, {0xa72e, 2994, 1}, {0x1e2c, 1778, 1}, {0x042c, 974, 1}, {0x012c, 237, 1}, {0x1f2c, 2136, 1}, {0x2c2c, 2553, 1}, {0x1f6f, 2223, 1}, {0x2c6f, 604, 1}, {0xabbf, 1685, 1}, {0xa72c, 2991, 1}, {0x1e28, 1772, 1}, {0x0428, 962, 1}, {0x0128, 231, 1}, {0x1f28, 2124, 1}, {0x2c28, 2541, 1}, {0xffffffff, -1, 0}, {0x0553, 1436, 1}, {0x10bf, 2838, 1}, {0xa728, 2985, 1}, {0x0526, 1319, 1}, {0x0202, 505, 1}, {0x1e40, 1808, 1}, {0x10424, 3345, 1}, {0x1e24, 1766, 1}, {0x0424, 950, 1}, {0x0124, 225, 1}, {0xffffffff, -1, 0}, {0x2c24, 2529, 1}, {0x052e, 1331, 1}, {0xa740, 3018, 1}, {0x118bc, 3594, 1}, {0xa724, 2979, 1}, {0x1ef2, 2061, 1}, {0x04f2, 1241, 1}, {0x01f2, 483, 1}, {0x1ff2, 257, 2}, {0x2cf2, 2742, 1}, {0x052c, 1328, 1}, {0x118b8, 3582, 1}, {0xa640, 2865, 1}, {0x10422, 3339, 1}, {0x1e22, 1763, 1}, {0x0422, 944, 1}, {0x0122, 222, 1}, {0x2126, 820, 1}, {0x2c22, 2523, 1}, {0x0528, 1322, 1}, {0x01f1, 483, 1}, {0x118b6, 3576, 1}, {0xa722, 2976, 1}, {0x03f1, 796, 1}, {0x1ebe, 1983, 1}, {0x04be, 1163, 1}, {0xfb02, 12, 2}, {0x1fbe, 767, 1}, {0x2cbe, 2679, 1}, {0x01b5, 405, 1}, {0x0540, 1379, 1}, {0xabbe, 1682, 1}, {0x0524, 1316, 1}, {0x00b5, 779, 1}, {0xabb5, 1655, 1}, {0x1eba, 1977, 1}, {0x04ba, 1157, 1}, {0x216f, 2337, 1}, {0x1fba, 2226, 1}, {0x2cba, 2673, 1}, {0x10be, 2835, 1}, {0x0051, 46, 1}, {0xabba, 1670, 1}, {0x10b5, 2808, 1}, {0x1e6e, 1878, 1}, {0x046e, 1055, 1}, {0x016e, 330, 1}, {0x1f6e, 2220, 1}, {0x2c6e, 664, 1}, {0x118bf, 3603, 1}, {0x0522, 1313, 1}, {0x10ba, 2823, 1}, {0xa76e, 3087, 1}, {0x1eb4, 1968, 1}, {0x04b4, 1148, 1}, {0x2c75, 2583, 1}, {0x1fb4, 50, 2}, {0x2cb4, 2664, 1}, {0xab75, 1463, 1}, {0x1ec2, 1989, 1}, {0xabb4, 1652, 1}, {0xa7b4, 3150, 1}, {0x1fc2, 253, 2}, {0x2cc2, 2685, 1}, {0x03c2, 800, 1}, {0x00c2, 83, 1}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xff26, 3174, 1}, {0x10b4, 2805, 1}, {0x1eca, 2001, 1}, {0x0551, 1430, 1}, {0x01ca, 425, 1}, {0x1fca, 2238, 1}, {0x2cca, 2697, 1}, {0x10c2, 2847, 1}, {0x00ca, 108, 1}, {0xff2e, 3198, 1}, {0x1e8c, 1923, 1}, {0x048c, 1088, 1}, {0x0226, 556, 1}, {0x1f8c, 149, 2}, {0x2c8c, 2604, 1}, {0x038c, 830, 1}, {0xffffffff, -1, 0}, {0xab8c, 1532, 1}, {0xff2c, 3192, 1}, {0x10c8c, 3393, 1}, {0x1ec4, 1992, 1}, {0x022e, 568, 1}, {0x01c4, 417, 1}, {0x1fc4, 54, 2}, {0x2cc4, 2688, 1}, {0xffffffff, -1, 0}, {0x00c4, 89, 1}, {0xff28, 3180, 1}, {0xa68c, 2952, 1}, {0x01cf, 432, 1}, {0x022c, 565, 1}, {0x118be, 3600, 1}, {0x03cf, 839, 1}, {0x00cf, 123, 1}, {0x118b5, 3573, 1}, {0xffffffff, -1, 0}, {0x10c4, 2853, 1}, {0x216e, 2334, 1}, {0x24cb, 2406, 1}, {0x0228, 559, 1}, {0xff24, 3168, 1}, {0xffffffff, -1, 0}, {0x118ba, 3588, 1}, {0x1efe, 2079, 1}, {0x04fe, 1259, 1}, {0x01fe, 499, 1}, {0x1e9e, 24, 2}, {0x049e, 1115, 1}, {0x03fe, 721, 1}, {0x1f9e, 199, 2}, {0x2c9e, 2631, 1}, {0x039e, 786, 1}, {0x0224, 553, 1}, {0xab9e, 1586, 1}, {0xa79e, 3132, 1}, {0x10c9e, 3447, 1}, {0x01f7, 414, 1}, {0x1ff7, 67, 3}, {0xff22, 3162, 1}, {0x03f7, 884, 1}, {0x118b4, 3570, 1}, {0x049c, 1112, 1}, {0x019c, 661, 1}, {0x1f9c, 189, 2}, {0x2c9c, 2628, 1}, {0x039c, 779, 1}, {0x24bc, 2361, 1}, {0xab9c, 1580, 1}, {0xa79c, 3129, 1}, {0x10c9c, 3441, 1}, {0x0222, 550, 1}, {0x1e7c, 1899, 1}, {0x047c, 1076, 1}, {0x1e82, 1908, 1}, {0x24b8, 2349, 1}, {0x0182, 357, 1}, {0x1f82, 139, 2}, {0x2c82, 2589, 1}, {0xab7c, 1484, 1}, {0xffffffff, -1, 0}, {0xab82, 1502, 1}, {0xa782, 3102, 1}, {0x10c82, 3363, 1}, {0x2c63, 1709, 1}, {0x24b6, 2343, 1}, {0x1e80, 1905, 1}, {0x0480, 1082, 1}, {0x1f59, 2190, 1}, {0x1f80, 129, 2}, {0x2c80, 2586, 1}, {0x0059, 71, 1}, {0xa682, 2937, 1}, {0xab80, 1496, 1}, {0xa780, 3099, 1}, {0x10c80, 3357, 1}, {0xffffffff, -1, 0}, {0x1e4c, 1826, 1}, {0x0145, 270, 1}, {0x014c, 279, 1}, {0x1f4c, 2184, 1}, {0x0345, 767, 1}, {0x0045, 12, 1}, {0x004c, 31, 1}, {0xa680, 2934, 1}, {0xa74c, 3036, 1}, {0x1e4a, 1823, 1}, {0x01d5, 441, 1}, {0x014a, 276, 1}, {0x1f4a, 2178, 1}, {0x03d5, 810, 1}, {0x00d5, 141, 1}, {0x004a, 24, 1}, {0x24bf, 2370, 1}, {0xa74a, 3033, 1}, {0xa64c, 2883, 1}, {0x1041c, 3321, 1}, {0x1e1c, 1754, 1}, {0x041c, 926, 1}, {0x011c, 213, 1}, {0x1f1c, 2118, 1}, {0x2c1c, 2505, 1}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xa64a, 2880, 1}, {0x1041a, 3315, 1}, {0x1e1a, 1751, 1}, {0x041a, 920, 1}, {0x011a, 210, 1}, {0x1f1a, 2112, 1}, {0x2c1a, 2499, 1}, {0xabbd, 1679, 1}, {0x0545, 1394, 1}, {0x054c, 1415, 1}, {0x10418, 3309, 1}, {0x1e18, 1748, 1}, {0x0418, 914, 1}, {0x0118, 207, 1}, {0x1f18, 2106, 1}, {0x2c18, 2493, 1}, {0x10bd, 2832, 1}, {0x2163, 2301, 1}, {0x054a, 1409, 1}, {0x1040e, 3279, 1}, {0x1e0e, 1733, 1}, {0x040e, 1028, 1}, {0x010e, 192, 1}, {0x1f0e, 2100, 1}, {0x2c0e, 2463, 1}, {0x1efc, 2076, 1}, {0x04fc, 1256, 1}, {0x01fc, 496, 1}, {0x1ffc, 96, 2}, {0x051c, 1304, 1}, {0x1040c, 3273, 1}, {0x1e0c, 1730, 1}, {0x040c, 1022, 1}, {0x010c, 189, 1}, {0x1f0c, 2094, 1}, {0x2c0c, 2457, 1}, {0x1f6d, 2217, 1}, {0x2c6d, 607, 1}, {0x051a, 1301, 1}, {0x24be, 2367, 1}, {0x10408, 3261, 1}, {0x1e08, 1724, 1}, {0x0408, 1010, 1}, {0x0108, 183, 1}, {0x1f08, 2082, 1}, {0x2c08, 2445, 1}, {0x04c9, 1178, 1}, {0x0518, 1298, 1}, {0x1fc9, 2235, 1}, {0xffffffff, -1, 0}, {0x24ba, 2355, 1}, {0x00c9, 105, 1}, {0x10416, 3303, 1}, {0x1e16, 1745, 1}, {0x0416, 908, 1}, {0x0116, 204, 1}, {0x050e, 1283, 1}, {0x2c16, 2487, 1}, {0x10414, 3297, 1}, {0x1e14, 1742, 1}, {0x0414, 902, 1}, {0x0114, 201, 1}, {0x042b, 971, 1}, {0x2c14, 2481, 1}, {0x1f2b, 2133, 1}, {0x2c2b, 2550, 1}, {0xffffffff, -1, 0}, {0x050c, 1280, 1}, {0x10406, 3255, 1}, {0x1e06, 1721, 1}, {0x0406, 1004, 1}, {0x0106, 180, 1}, {0x13fb, 1697, 1}, {0x2c06, 2439, 1}, {0x24c2, 2379, 1}, {0x118bd, 3597, 1}, {0xffffffff, -1, 0}, {0x0508, 1274, 1}, {0x10404, 3249, 1}, {0x1e04, 1718, 1}, {0x0404, 998, 1}, {0x0104, 177, 1}, {0x1f95, 194, 2}, {0x2c04, 2433, 1}, {0x0395, 752, 1}, {0x24ca, 2403, 1}, {0xab95, 1559, 1}, {0x0531, 1334, 1}, {0x10c95, 3420, 1}, {0x0516, 1295, 1}, {0x1e6c, 1875, 1}, {0x046c, 1052, 1}, {0x016c, 327, 1}, {0x1f6c, 2214, 1}, {0x216d, 2331, 1}, {0x0514, 1292, 1}, {0x0245, 697, 1}, {0x024c, 598, 1}, {0xa76c, 3084, 1}, {0x10400, 3237, 1}, {0x1e00, 1712, 1}, {0x0400, 986, 1}, {0x0100, 171, 1}, {0x24c4, 2385, 1}, {0x2c00, 2421, 1}, {0x0506, 1271, 1}, {0x024a, 595, 1}, {0x1fab, 224, 2}, {0xa66c, 2931, 1}, {0x03ab, 827, 1}, {0x24cf, 2418, 1}, {0xabab, 1625, 1}, {0xa7ab, 631, 1}, {0x10cab, 3486, 1}, {0xffffffff, -1, 0}, {0x0504, 1268, 1}, {0xffffffff, -1, 0}, {0x021c, 544, 1}, {0x01a9, 679, 1}, {0x1fa9, 214, 2}, {0x10ab, 2778, 1}, {0x03a9, 820, 1}, {0x212b, 92, 1}, {0xaba9, 1619, 1}, {0x1e88, 1917, 1}, {0x10ca9, 3480, 1}, {0x021a, 541, 1}, {0x1f88, 129, 2}, {0x2c88, 2598, 1}, {0x0388, 730, 1}, {0x13fd, 1703, 1}, {0xab88, 1520, 1}, {0x10a9, 2772, 1}, {0x10c88, 3381, 1}, {0xffffffff, -1, 0}, {0x0218, 538, 1}, {0x0500, 1262, 1}, {0x1f4d, 2187, 1}, {0x01a7, 393, 1}, {0x1fa7, 244, 2}, {0x004d, 34, 1}, {0x03a7, 814, 1}, {0xa688, 2946, 1}, {0xaba7, 1613, 1}, {0x020e, 523, 1}, {0x10ca7, 3474, 1}, {0x1e6a, 1872, 1}, {0x046a, 1049, 1}, {0x016a, 324, 1}, {0x1f6a, 2208, 1}, {0xffffffff, -1, 0}, {0x216c, 2328, 1}, {0x10a7, 2766, 1}, {0x01d1, 435, 1}, {0xa76a, 3081, 1}, {0x020c, 520, 1}, {0x03d1, 762, 1}, {0x00d1, 129, 1}, {0x1e68, 1869, 1}, {0x0468, 1046, 1}, {0x0168, 321, 1}, {0x1f68, 2202, 1}, {0xffffffff, -1, 0}, {0xff31, 3207, 1}, {0xa66a, 2928, 1}, {0x0208, 514, 1}, {0xa768, 3078, 1}, {0x1e64, 1863, 1}, {0x0464, 1040, 1}, {0x0164, 315, 1}, {0x054d, 1418, 1}, {0x2c64, 673, 1}, {0xffffffff, -1, 0}, {0xff2b, 3189, 1}, {0xffffffff, -1, 0}, {0xa764, 3072, 1}, {0xa668, 2925, 1}, {0x0216, 535, 1}, {0xffffffff, -1, 0}, {0x118ab, 3543, 1}, {0x1e62, 1860, 1}, {0x0462, 1037, 1}, {0x0162, 312, 1}, {0x0214, 532, 1}, {0x2c62, 655, 1}, {0xa664, 2919, 1}, {0x1ed2, 2013, 1}, {0x04d2, 1193, 1}, {0xa762, 3069, 1}, {0x1fd2, 20, 3}, {0x2cd2, 2709, 1}, {0x118a9, 3537, 1}, {0x00d2, 132, 1}, {0x0206, 511, 1}, {0x10420, 3333, 1}, {0x1e20, 1760, 1}, {0x0420, 938, 1}, {0x0120, 219, 1}, {0xa662, 2916, 1}, {0x2c20, 2517, 1}, {0x1e60, 1856, 1}, {0x0460, 1034, 1}, {0x0160, 309, 1}, {0x0204, 508, 1}, {0x2c60, 2562, 1}, {0xffffffff, -1, 0}, {0x24bd, 2364, 1}, {0x216a, 2322, 1}, {0xa760, 3066, 1}, {0xffffffff, -1, 0}, {0xfb16, 125, 2}, {0x118a7, 3531, 1}, {0x1efa, 2073, 1}, {0x04fa, 1253, 1}, {0x01fa, 493, 1}, {0x1ffa, 2262, 1}, {0xfb14, 109, 2}, {0x03fa, 887, 1}, {0xa660, 2913, 1}, {0x2168, 2316, 1}, {0x01b7, 700, 1}, {0x1fb7, 10, 3}, {0x1f6b, 2211, 1}, {0x2c6b, 2577, 1}, {0x0200, 502, 1}, {0xabb7, 1661, 1}, {0xfb06, 29, 2}, {0x1e56, 1841, 1}, {0x2164, 2304, 1}, {0x0156, 294, 1}, {0x1f56, 62, 3}, {0x0520, 1310, 1}, {0x004f, 40, 1}, {0x0056, 62, 1}, {0x10b7, 2814, 1}, {0xa756, 3051, 1}, {0xfb04, 5, 3}, {0x1e78, 1893, 1}, {0x0478, 1070, 1}, {0x0178, 168, 1}, {0x1e54, 1838, 1}, {0x2162, 2298, 1}, {0x0154, 291, 1}, {0x1f54, 57, 3}, {0xab78, 1472, 1}, {0xa656, 2898, 1}, {0x0054, 56, 1}, {0x1e52, 1835, 1}, {0xa754, 3048, 1}, {0x0152, 288, 1}, {0x1f52, 52, 3}, {0x24c9, 2400, 1}, {0x1e32, 1787, 1}, {0x0052, 49, 1}, {0x0132, 243, 1}, {0xa752, 3045, 1}, {0xffffffff, -1, 0}, {0xfb00, 4, 2}, {0xa654, 2895, 1}, {0xffffffff, -1, 0}, {0xa732, 2997, 1}, {0x2160, 2292, 1}, {0x054f, 1424, 1}, {0x0556, 1445, 1}, {0x1e50, 1832, 1}, {0xa652, 2892, 1}, {0x0150, 285, 1}, {0x1f50, 84, 2}, {0x017b, 348, 1}, {0x1e4e, 1829, 1}, {0x0050, 43, 1}, {0x014e, 282, 1}, {0xa750, 3042, 1}, {0xab7b, 1481, 1}, {0xa77b, 3093, 1}, {0x004e, 37, 1}, {0x0554, 1439, 1}, {0xa74e, 3039, 1}, {0x1e48, 1820, 1}, {0xffffffff, -1, 0}, {0x216b, 2325, 1}, {0x1f48, 2172, 1}, {0xa650, 2889, 1}, {0x0552, 1433, 1}, {0x0048, 21, 1}, {0xffffffff, -1, 0}, {0xa748, 3030, 1}, {0xa64e, 2886, 1}, {0x0532, 1337, 1}, {0x1041e, 3327, 1}, {0x1e1e, 1757, 1}, {0x041e, 932, 1}, {0x011e, 216, 1}, {0x118b7, 3579, 1}, {0x2c1e, 2511, 1}, {0xffffffff, -1, 0}, {0xa648, 2877, 1}, {0x1ff9, 2253, 1}, {0xffffffff, -1, 0}, {0x03f9, 878, 1}, {0x0550, 1427, 1}, {0x10412, 3291, 1}, {0x1e12, 1739, 1}, {0x0412, 896, 1}, {0x0112, 198, 1}, {0x054e, 1421, 1}, {0x2c12, 2475, 1}, {0x10410, 3285, 1}, {0x1e10, 1736, 1}, {0x0410, 890, 1}, {0x0110, 195, 1}, {0xffffffff, -1, 0}, {0x2c10, 2469, 1}, {0x2132, 2289, 1}, {0x0548, 1403, 1}, {0x1ef8, 2070, 1}, {0x04f8, 1250, 1}, {0x01f8, 490, 1}, {0x1ff8, 2250, 1}, {0x0220, 381, 1}, {0x1ee2, 2037, 1}, {0x04e2, 1217, 1}, {0x01e2, 462, 1}, {0x1fe2, 36, 3}, {0x2ce2, 2733, 1}, {0x03e2, 857, 1}, {0x051e, 1307, 1}, {0x1ede, 2031, 1}, {0x04de, 1211, 1}, {0x01de, 456, 1}, {0xffffffff, -1, 0}, {0x2cde, 2727, 1}, {0x03de, 851, 1}, {0x00de, 165, 1}, {0x1f69, 2205, 1}, {0x2c69, 2574, 1}, {0x1eda, 2025, 1}, {0x04da, 1205, 1}, {0x0512, 1289, 1}, {0x1fda, 2244, 1}, {0x2cda, 2721, 1}, {0x03da, 845, 1}, {0x00da, 153, 1}, {0xffffffff, -1, 0}, {0x0510, 1286, 1}, {0x1ed8, 2022, 1}, {0x04d8, 1202, 1}, {0xffffffff, -1, 0}, {0x1fd8, 2274, 1}, {0x2cd8, 2718, 1}, {0x03d8, 842, 1}, {0x00d8, 147, 1}, {0x1ed6, 2019, 1}, {0x04d6, 1199, 1}, {0xffffffff, -1, 0}, {0x1fd6, 76, 2}, {0x2cd6, 2715, 1}, {0x03d6, 792, 1}, {0x00d6, 144, 1}, {0x1ec8, 1998, 1}, {0xffffffff, -1, 0}, {0x01c8, 421, 1}, {0x1fc8, 2232, 1}, {0x2cc8, 2694, 1}, {0xff32, 3210, 1}, {0x00c8, 102, 1}, {0x04c7, 1175, 1}, {0x01c7, 421, 1}, {0x1fc7, 15, 3}, {0x1ec0, 1986, 1}, {0x04c0, 1187, 1}, {0x00c7, 99, 1}, {0xffffffff, -1, 0}, {0x2cc0, 2682, 1}, {0x0179, 345, 1}, {0x00c0, 77, 1}, {0x0232, 574, 1}, {0x01b3, 402, 1}, {0x1fb3, 62, 2}, {0xab79, 1475, 1}, {0xa779, 3090, 1}, {0x10c7, 2859, 1}, {0xabb3, 1649, 1}, {0xa7b3, 3156, 1}, {0x1fa5, 234, 2}, {0x10c0, 2841, 1}, {0x03a5, 807, 1}, {0xffffffff, -1, 0}, {0xaba5, 1607, 1}, {0x01b1, 691, 1}, {0x10ca5, 3468, 1}, {0x10b3, 2802, 1}, {0x2169, 2319, 1}, {0x024e, 601, 1}, {0xabb1, 1643, 1}, {0xa7b1, 682, 1}, {0x10cb1, 3504, 1}, {0x10a5, 2760, 1}, {0xffffffff, -1, 0}, {0x01af, 399, 1}, {0x1faf, 244, 2}, {0xffffffff, -1, 0}, {0x0248, 592, 1}, {0x10b1, 2796, 1}, {0xabaf, 1637, 1}, {0x1fad, 234, 2}, {0x10caf, 3498, 1}, {0x04cd, 1184, 1}, {0x01cd, 429, 1}, {0xabad, 1631, 1}, {0xa7ad, 658, 1}, {0x10cad, 3492, 1}, {0x00cd, 117, 1}, {0x10af, 2790, 1}, {0x021e, 547, 1}, {0x1fa3, 224, 2}, {0xffffffff, -1, 0}, {0x03a3, 800, 1}, {0x10ad, 2784, 1}, {0xaba3, 1601, 1}, {0xffffffff, -1, 0}, {0x10ca3, 3462, 1}, {0x10cd, 2862, 1}, {0x1fa1, 214, 2}, {0x24b7, 2346, 1}, {0x03a1, 796, 1}, {0x0212, 529, 1}, {0xaba1, 1595, 1}, {0x10a3, 2754, 1}, {0x10ca1, 3456, 1}, {0x01d3, 438, 1}, {0x1fd3, 25, 3}, {0x0210, 526, 1}, {0xffffffff, -1, 0}, {0x00d3, 135, 1}, {0x1e97, 34, 2}, {0x10a1, 2748, 1}, {0x0197, 649, 1}, {0x1f97, 204, 2}, {0xffffffff, -1, 0}, {0x0397, 759, 1}, {0x1041d, 3324, 1}, {0xab97, 1565, 1}, {0x041d, 929, 1}, {0x10c97, 3426, 1}, {0x1f1d, 2121, 1}, {0x2c1d, 2508, 1}, {0x1e72, 1884, 1}, {0x0472, 1061, 1}, {0x0172, 336, 1}, {0x118b3, 3567, 1}, {0x2c72, 2580, 1}, {0x0372, 712, 1}, {0x1041b, 3318, 1}, {0xab72, 1454, 1}, {0x041b, 923, 1}, {0x118a5, 3525, 1}, {0x1f1b, 2115, 1}, {0x2c1b, 2502, 1}, {0x1e70, 1881, 1}, {0x0470, 1058, 1}, {0x0170, 333, 1}, {0x118b1, 3561, 1}, {0x2c70, 610, 1}, {0x0370, 709, 1}, {0x1e46, 1817, 1}, {0xab70, 1448, 1}, {0x1e66, 1866, 1}, {0x0466, 1043, 1}, {0x0166, 318, 1}, {0x1e44, 1814, 1}, {0x0046, 15, 1}, {0x118af, 3555, 1}, {0xa746, 3027, 1}, {0xffffffff, -1, 0}, {0xa766, 3075, 1}, {0x0044, 9, 1}, {0x118ad, 3549, 1}, {0xa744, 3024, 1}, {0x1e7a, 1896, 1}, {0x047a, 1073, 1}, {0x1e3a, 1799, 1}, {0xffffffff, -1, 0}, {0xa646, 2874, 1}, {0x1f3a, 2154, 1}, {0xa666, 2922, 1}, {0xab7a, 1478, 1}, {0x118a3, 3519, 1}, {0xa644, 2871, 1}, {0xa73a, 3009, 1}, {0xffffffff, -1, 0}, {0x1ef4, 2064, 1}, {0x04f4, 1244, 1}, {0x01f4, 487, 1}, {0x1ff4, 101, 2}, {0x118a1, 3513, 1}, {0x03f4, 762, 1}, {0x1eec, 2052, 1}, {0x04ec, 1232, 1}, {0x01ec, 477, 1}, {0x1fec, 2286, 1}, {0x0546, 1397, 1}, {0x03ec, 872, 1}, {0xffffffff, -1, 0}, {0x013f, 261, 1}, {0x1f3f, 2169, 1}, {0x0544, 1391, 1}, {0x1eea, 2049, 1}, {0x04ea, 1229, 1}, {0x01ea, 474, 1}, {0x1fea, 2256, 1}, {0xffffffff, -1, 0}, {0x03ea, 869, 1}, {0x1ee8, 2046, 1}, {0x04e8, 1226, 1}, {0x01e8, 471, 1}, {0x1fe8, 2280, 1}, {0x053a, 1361, 1}, {0x03e8, 866, 1}, {0x1ee6, 2043, 1}, {0x04e6, 1223, 1}, {0x01e6, 468, 1}, {0x1fe6, 88, 2}, {0x1f4b, 2181, 1}, {0x03e6, 863, 1}, {0x1e5e, 1853, 1}, {0x004b, 27, 1}, {0x015e, 306, 1}, {0x2166, 2310, 1}, {0x1ee4, 2040, 1}, {0x04e4, 1220, 1}, {0x01e4, 465, 1}, {0x1fe4, 80, 2}, {0xa75e, 3063, 1}, {0x03e4, 860, 1}, {0x1ee0, 2034, 1}, {0x04e0, 1214, 1}, {0x01e0, 459, 1}, {0x053f, 1376, 1}, {0x2ce0, 2730, 1}, {0x03e0, 854, 1}, {0x1edc, 2028, 1}, {0x04dc, 1208, 1}, {0xa65e, 2910, 1}, {0xffffffff, -1, 0}, {0x2cdc, 2724, 1}, {0x03dc, 848, 1}, {0x00dc, 159, 1}, {0x1ed0, 2010, 1}, {0x04d0, 1190, 1}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0x2cd0, 2706, 1}, {0x03d0, 742, 1}, {0x00d0, 126, 1}, {0x1ecc, 2004, 1}, {0x054b, 1412, 1}, {0xffffffff, -1, 0}, {0x1fcc, 71, 2}, {0x2ccc, 2700, 1}, {0x1ec6, 1995, 1}, {0x00cc, 114, 1}, {0xffffffff, -1, 0}, {0x1fc6, 67, 2}, {0x2cc6, 2691, 1}, {0x24c8, 2397, 1}, {0x00c6, 96, 1}, {0x04c5, 1172, 1}, {0x01c5, 417, 1}, {0xffffffff, -1, 0}, {0x1fbb, 2229, 1}, {0x24c7, 2394, 1}, {0x00c5, 92, 1}, {0x1fb9, 2271, 1}, {0xabbb, 1673, 1}, {0x24c0, 2373, 1}, {0x04c3, 1169, 1}, {0xabb9, 1667, 1}, {0x1fc3, 71, 2}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0x00c3, 86, 1}, {0x10c5, 2856, 1}, {0x10bb, 2826, 1}, {0x1ed4, 2016, 1}, {0x04d4, 1196, 1}, {0x10b9, 2820, 1}, {0x13fc, 1700, 1}, {0x2cd4, 2712, 1}, {0x0246, 589, 1}, {0x00d4, 138, 1}, {0x10c3, 2850, 1}, {0xffffffff, -1, 0}, {0xff3a, 3234, 1}, {0x0244, 688, 1}, {0x019f, 670, 1}, {0x1f9f, 204, 2}, {0xffffffff, -1, 0}, {0x039f, 789, 1}, {0xffffffff, -1, 0}, {0xab9f, 1589, 1}, {0xffffffff, -1, 0}, {0x10c9f, 3450, 1}, {0x019d, 667, 1}, {0x1f9d, 194, 2}, {0x023a, 2565, 1}, {0x039d, 783, 1}, {0x1e5a, 1847, 1}, {0xab9d, 1583, 1}, {0x015a, 300, 1}, {0x10c9d, 3444, 1}, {0x1e9b, 1856, 1}, {0x24cd, 2412, 1}, {0x005a, 74, 1}, {0x1f9b, 184, 2}, {0xa75a, 3057, 1}, {0x039b, 776, 1}, {0x1ece, 2007, 1}, {0xab9b, 1577, 1}, {0x1e99, 42, 2}, {0x10c9b, 3438, 1}, {0x2cce, 2703, 1}, {0x1f99, 174, 2}, {0x00ce, 120, 1}, {0x0399, 767, 1}, {0xa65a, 2904, 1}, {0xab99, 1571, 1}, {0xffffffff, -1, 0}, {0x10c99, 3432, 1}, {0x0193, 634, 1}, {0x1f93, 184, 2}, {0x1e58, 1844, 1}, {0x0393, 746, 1}, {0x0158, 297, 1}, {0xab93, 1553, 1}, {0xffffffff, -1, 0}, {0x10c93, 3414, 1}, {0x0058, 68, 1}, {0x042d, 977, 1}, {0xa758, 3054, 1}, {0x1f2d, 2139, 1}, {0x2c2d, 2556, 1}, {0x118bb, 3591, 1}, {0x0191, 369, 1}, {0x1f91, 174, 2}, {0x118b9, 3585, 1}, {0x0391, 739, 1}, {0xffffffff, -1, 0}, {0xab91, 1547, 1}, {0xa658, 2901, 1}, {0x10c91, 3408, 1}, {0x018f, 625, 1}, {0x1f8f, 164, 2}, {0xffffffff, -1, 0}, {0x038f, 836, 1}, {0xffffffff, -1, 0}, {0xab8f, 1541, 1}, {0xffffffff, -1, 0}, {0x10c8f, 3402, 1}, {0x018b, 366, 1}, {0x1f8b, 144, 2}, {0xffffffff, -1, 0}, {0x0187, 363, 1}, {0x1f87, 164, 2}, {0xab8b, 1529, 1}, {0xa78b, 3111, 1}, {0x10c8b, 3390, 1}, {0xab87, 1517, 1}, {0x04c1, 1166, 1}, {0x10c87, 3378, 1}, {0x1e7e, 1902, 1}, {0x047e, 1079, 1}, {0xffffffff, -1, 0}, {0x00c1, 80, 1}, {0x2c7e, 580, 1}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xab7e, 1490, 1}, {0xa77e, 3096, 1}, {0x1e76, 1890, 1}, {0x0476, 1067, 1}, {0x0176, 342, 1}, {0x1e42, 1811, 1}, {0x10c1, 2844, 1}, {0x0376, 715, 1}, {0x1e36, 1793, 1}, {0xab76, 1466, 1}, {0x0136, 249, 1}, {0x0042, 3, 1}, {0x1e3e, 1805, 1}, {0xa742, 3021, 1}, {0x1e38, 1796, 1}, {0x1f3e, 2166, 1}, {0xa736, 3003, 1}, {0x1f38, 2148, 1}, {0xffffffff, -1, 0}, {0x0587, 105, 2}, {0xa73e, 3015, 1}, {0xffffffff, -1, 0}, {0xa738, 3006, 1}, {0xa642, 2868, 1}, {0x1e5c, 1850, 1}, {0x1e34, 1790, 1}, {0x015c, 303, 1}, {0x0134, 246, 1}, {0x1ef6, 2067, 1}, {0x04f6, 1247, 1}, {0x01f6, 372, 1}, {0x1ff6, 92, 2}, {0xa75c, 3060, 1}, {0xa734, 3000, 1}, {0x1ef0, 2058, 1}, {0x04f0, 1238, 1}, {0x01f0, 20, 2}, {0xffffffff, -1, 0}, {0x1e30, 1784, 1}, {0x03f0, 772, 1}, {0x0130, 261, 2}, {0x0542, 1385, 1}, {0xa65c, 2907, 1}, {0x1f83, 144, 2}, {0x0536, 1349, 1}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xab83, 1505, 1}, {0x053e, 1373, 1}, {0x10c83, 3366, 1}, {0x0538, 1355, 1}, {0x1eee, 2055, 1}, {0x04ee, 1235, 1}, {0x01ee, 480, 1}, {0x1f8d, 154, 2}, {0xffffffff, -1, 0}, {0x03ee, 875, 1}, {0xffffffff, -1, 0}, {0xab8d, 1535, 1}, {0xa78d, 643, 1}, {0x10c8d, 3396, 1}, {0x0534, 1343, 1}, {0x0181, 613, 1}, {0x1f81, 134, 2}, {0x013d, 258, 1}, {0x1f3d, 2163, 1}, {0xffffffff, -1, 0}, {0xab81, 1499, 1}, {0x017f, 52, 1}, {0x10c81, 3360, 1}, {0x2c7f, 583, 1}, {0x037f, 881, 1}, {0xff2d, 3195, 1}, {0xab7f, 1493, 1}, {0x1e74, 1887, 1}, {0x0474, 1064, 1}, {0x0174, 339, 1}, {0x1e3c, 1802, 1}, {0x0149, 46, 2}, {0x1f49, 2175, 1}, {0x1f3c, 2160, 1}, {0xab74, 1460, 1}, {0x0049, 3606, 1}, {0x0143, 267, 1}, {0x24cc, 2409, 1}, {0xa73c, 3012, 1}, {0xffffffff, -1, 0}, {0x0043, 6, 1}, {0x0141, 264, 1}, {0x24c6, 2391, 1}, {0x013b, 255, 1}, {0x1f3b, 2157, 1}, {0x0041, 0, 1}, {0x0139, 252, 1}, {0x1f39, 2151, 1}, {0x24c5, 2388, 1}, {0x24bb, 2358, 1}, {0x13fa, 1694, 1}, {0x053d, 1370, 1}, {0x24b9, 2352, 1}, {0x0429, 965, 1}, {0x2183, 2340, 1}, {0x1f29, 2127, 1}, {0x2c29, 2544, 1}, {0x24c3, 2382, 1}, {0x10427, 3354, 1}, {0x10425, 3348, 1}, {0x0427, 959, 1}, {0x0425, 953, 1}, {0xffffffff, -1, 0}, {0x2c27, 2538, 1}, {0x2c25, 2532, 1}, {0x0549, 1406, 1}, {0x053c, 1367, 1}, {0x10423, 3342, 1}, {0xffffffff, -1, 0}, {0x0423, 947, 1}, {0x0543, 1388, 1}, {0xffffffff, -1, 0}, {0x2c23, 2526, 1}, {0xff36, 3222, 1}, {0xffffffff, -1, 0}, {0x0541, 1382, 1}, {0x10421, 3336, 1}, {0x053b, 1364, 1}, {0x0421, 941, 1}, {0xff38, 3228, 1}, {0x0539, 1358, 1}, {0x2c21, 2520, 1}, {0x10419, 3312, 1}, {0x10417, 3306, 1}, {0x0419, 917, 1}, {0x0417, 911, 1}, {0x1f19, 2109, 1}, {0x2c19, 2496, 1}, {0x2c17, 2490, 1}, {0x023e, 2568, 1}, {0xff34, 3216, 1}, {0x10415, 3300, 1}, {0x10413, 3294, 1}, {0x0415, 905, 1}, {0x0413, 899, 1}, {0xffffffff, -1, 0}, {0x2c15, 2484, 1}, {0x2c13, 2478, 1}, {0xffffffff, -1, 0}, {0x24ce, 2415, 1}, {0x1040f, 3282, 1}, {0xffffffff, -1, 0}, {0x040f, 1031, 1}, {0xff30, 3204, 1}, {0x1f0f, 2103, 1}, {0x2c0f, 2466, 1}, {0x1040d, 3276, 1}, {0xffffffff, -1, 0}, {0x040d, 1025, 1}, {0x0147, 273, 1}, {0x1f0d, 2097, 1}, {0x2c0d, 2460, 1}, {0x1040b, 3270, 1}, {0x0047, 18, 1}, {0x040b, 1019, 1}, {0x0230, 571, 1}, {0x1f0b, 2091, 1}, {0x2c0b, 2454, 1}, {0x10409, 3264, 1}, {0x10405, 3252, 1}, {0x0409, 1013, 1}, {0x0405, 1001, 1}, {0x1f09, 2085, 1}, {0x2c09, 2448, 1}, {0x2c05, 2436, 1}, {0x10403, 3246, 1}, {0x10401, 3240, 1}, {0x0403, 995, 1}, {0x0401, 989, 1}, {0xffffffff, -1, 0}, {0x2c03, 2430, 1}, {0x2c01, 2424, 1}, {0x13f9, 1691, 1}, {0x042f, 983, 1}, {0xffffffff, -1, 0}, {0x1f2f, 2145, 1}, {0x1041f, 3330, 1}, {0xffffffff, -1, 0}, {0x041f, 935, 1}, {0x023d, 378, 1}, {0x10411, 3288, 1}, {0x2c1f, 2514, 1}, {0x0411, 893, 1}, {0x0547, 1400, 1}, {0xffffffff, -1, 0}, {0x2c11, 2472, 1}, {0x10407, 3258, 1}, {0xffffffff, -1, 0}, {0x0407, 1007, 1}, {0x24c1, 2376, 1}, {0xffffffff, -1, 0}, {0x2c07, 2442, 1}, {0xffffffff, -1, 0}, {0x13f8, 1688, 1}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xff39, 3231, 1}, {0xffffffff, -1, 0}, {0x0243, 354, 1}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0x0241, 586, 1}, {0xff29, 3183, 1}, {0x023b, 577, 1}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xff27, 3177, 1}, {0xff25, 3171, 1}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xff23, 3165, 1}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xff21, 3159, 1}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xfb17, 117, 2}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xff2f, 3201, 1}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xfb15, 113, 2}, {0xfb13, 121, 2}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xfb05, 29, 2}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xffffffff, -1, 0}, {0xfb03, 0, 3}, {0xfb01, 8, 2} }; if (0 == 0) { int key = hash(&code); if (key <= MAX_HASH_VALUE && key >= 0) { OnigCodePoint gcode = wordlist[key].code; if (code == gcode && wordlist[key].index >= 0) return &wordlist[key]; } } return 0; }","{'deleted': [{'line_no': 2780, 'char_start': 39629, 'char_end': 39658, 'line': ' if (code == gcode)\n'}], 'added': [{'line_no': 2780, 'char_start': 39629, 'char_end': 39686, 'line': ' if (code == gcode && wordlist[key].index >= 0)\n'}]}","{'deleted': [], 'added': [{'char_start': 39656, 'char_end': 39684, 'chars': ' && wordlist[key].index >= 0'}]}",github.com/kkos/oniguruma/commit/166a6c3999bf06b4de0ab4ce6b088a468cc4029f,src/unicode_unfold_key.c,cwe-787,25157 cwe-089,create_event," def create_event(self, title, start_time, time_zone, server_id, description): sql = """"""INSERT INTO events (title, start_time, time_zone, server_id, description) VALUES ('{0}', '{1}', '{2}', '{3}', '{4}') """""".format(title, start_time, time_zone, server_id, description) self.cur.execute(sql) self.conn.commit()"," def create_event(self, title, start_time, time_zone, server_id, description): sql = """""" INSERT INTO events (title, start_time, time_zone, server_id, description) VALUES (%s, %s, %s, %s, %s) """""" self.cur.execute(sql, (title, start_time, time_zone, server_id, description)) self.conn.commit()","{'deleted': [{'line_no': 2, 'char_start': 82, 'char_end': 173, 'line': ' sql = """"""INSERT INTO events (title, start_time, time_zone, server_id, description)\n'}, {'line_no': 3, 'char_start': 173, 'char_end': 233, 'line': "" VALUES ('{0}', '{1}', '{2}', '{3}', '{4}')\n""}, {'line_no': 4, 'char_start': 233, 'char_end': 315, 'line': ' """""".format(title, start_time, time_zone, server_id, description)\n'}, {'line_no': 5, 'char_start': 315, 'char_end': 345, 'line': ' self.cur.execute(sql)\n'}], 'added': [{'line_no': 2, 'char_start': 82, 'char_end': 100, 'line': ' sql = """"""\n'}, {'line_no': 3, 'char_start': 100, 'char_end': 188, 'line': ' INSERT INTO events (title, start_time, time_zone, server_id, description)\n'}, {'line_no': 4, 'char_start': 188, 'char_end': 230, 'line': ' VALUES (%s, %s, %s, %s, %s)\n'}, {'line_no': 5, 'char_start': 230, 'char_end': 248, 'line': ' """"""\n'}, {'line_no': 6, 'char_start': 248, 'char_end': 334, 'line': ' self.cur.execute(sql, (title, start_time, time_zone, server_id, description))\n'}]}","{'deleted': [{'char_start': 187, 'char_end': 190, 'chars': ' '}, {'char_start': 198, 'char_end': 203, 'chars': ""'{0}'""}, {'char_start': 205, 'char_end': 210, 'chars': ""'{1}'""}, {'char_start': 212, 'char_end': 217, 'chars': ""'{2}'""}, {'char_start': 219, 'char_end': 224, 'chars': ""'{3}'""}, {'char_start': 226, 'char_end': 231, 'chars': ""'{4}'""}, {'char_start': 250, 'char_end': 253, 'chars': '""""""'}, {'char_start': 254, 'char_end': 256, 'chars': 'fo'}, {'char_start': 257, 'char_end': 259, 'chars': 'ma'}, {'char_start': 314, 'char_end': 343, 'chars': '\n self.cur.execute(sql'}], 'added': [{'char_start': 99, 'char_end': 114, 'chars': '\n '}, {'char_start': 210, 'char_end': 212, 'chars': '%s'}, {'char_start': 214, 'char_end': 216, 'chars': '%s'}, {'char_start': 218, 'char_end': 220, 'chars': '%s'}, {'char_start': 222, 'char_end': 224, 'chars': '%s'}, {'char_start': 226, 'char_end': 228, 'chars': '%s'}, {'char_start': 247, 'char_end': 259, 'chars': '\n sel'}, {'char_start': 260, 'char_end': 263, 'chars': '.cu'}, {'char_start': 264, 'char_end': 270, 'chars': '.execu'}, {'char_start': 271, 'char_end': 278, 'chars': 'e(sql, '}]}",github.com/jgayfer/spirit/commit/01c846c534c8d3cf6763f8b7444a0efe2caa3799,db/dbase.py,cwe-089,85 cwe-190,vc4_get_bcl,"vc4_get_bcl(struct drm_device *dev, struct vc4_exec_info *exec) { struct drm_vc4_submit_cl *args = exec->args; void *temp = NULL; void *bin; int ret = 0; uint32_t bin_offset = 0; uint32_t shader_rec_offset = roundup(bin_offset + args->bin_cl_size, 16); uint32_t uniforms_offset = shader_rec_offset + args->shader_rec_size; uint32_t exec_size = uniforms_offset + args->uniforms_size; uint32_t temp_size = exec_size + (sizeof(struct vc4_shader_state) * args->shader_rec_count); struct vc4_bo *bo; if (uniforms_offset < shader_rec_offset || exec_size < uniforms_offset || args->shader_rec_count >= (UINT_MAX / sizeof(struct vc4_shader_state)) || temp_size < exec_size) { DRM_ERROR(""overflow in exec arguments\n""); goto fail; } /* Allocate space where we'll store the copied in user command lists * and shader records. * * We don't just copy directly into the BOs because we need to * read the contents back for validation, and I think the * bo->vaddr is uncached access. */ temp = drm_malloc_ab(temp_size, 1); if (!temp) { DRM_ERROR(""Failed to allocate storage for copying "" ""in bin/render CLs.\n""); ret = -ENOMEM; goto fail; } bin = temp + bin_offset; exec->shader_rec_u = temp + shader_rec_offset; exec->uniforms_u = temp + uniforms_offset; exec->shader_state = temp + exec_size; exec->shader_state_size = args->shader_rec_count; if (copy_from_user(bin, (void __user *)(uintptr_t)args->bin_cl, args->bin_cl_size)) { ret = -EFAULT; goto fail; } if (copy_from_user(exec->shader_rec_u, (void __user *)(uintptr_t)args->shader_rec, args->shader_rec_size)) { ret = -EFAULT; goto fail; } if (copy_from_user(exec->uniforms_u, (void __user *)(uintptr_t)args->uniforms, args->uniforms_size)) { ret = -EFAULT; goto fail; } bo = vc4_bo_create(dev, exec_size, true); if (IS_ERR(bo)) { DRM_ERROR(""Couldn't allocate BO for binning\n""); ret = PTR_ERR(bo); goto fail; } exec->exec_bo = &bo->base; list_add_tail(&to_vc4_bo(&exec->exec_bo->base)->unref_head, &exec->unref_list); exec->ct0ca = exec->exec_bo->paddr + bin_offset; exec->bin_u = bin; exec->shader_rec_v = exec->exec_bo->vaddr + shader_rec_offset; exec->shader_rec_p = exec->exec_bo->paddr + shader_rec_offset; exec->shader_rec_size = args->shader_rec_size; exec->uniforms_v = exec->exec_bo->vaddr + uniforms_offset; exec->uniforms_p = exec->exec_bo->paddr + uniforms_offset; exec->uniforms_size = args->uniforms_size; ret = vc4_validate_bin_cl(dev, exec->exec_bo->vaddr + bin_offset, bin, exec); if (ret) goto fail; ret = vc4_validate_shader_recs(dev, exec); if (ret) goto fail; /* Block waiting on any previous rendering into the CS's VBO, * IB, or textures, so that pixels are actually written by the * time we try to read them. */ ret = vc4_wait_for_seqno(dev, exec->bin_dep_seqno, ~0ull, true); fail: drm_free_large(temp); return ret; }","vc4_get_bcl(struct drm_device *dev, struct vc4_exec_info *exec) { struct drm_vc4_submit_cl *args = exec->args; void *temp = NULL; void *bin; int ret = 0; uint32_t bin_offset = 0; uint32_t shader_rec_offset = roundup(bin_offset + args->bin_cl_size, 16); uint32_t uniforms_offset = shader_rec_offset + args->shader_rec_size; uint32_t exec_size = uniforms_offset + args->uniforms_size; uint32_t temp_size = exec_size + (sizeof(struct vc4_shader_state) * args->shader_rec_count); struct vc4_bo *bo; if (shader_rec_offset < args->bin_cl_size || uniforms_offset < shader_rec_offset || exec_size < uniforms_offset || args->shader_rec_count >= (UINT_MAX / sizeof(struct vc4_shader_state)) || temp_size < exec_size) { DRM_ERROR(""overflow in exec arguments\n""); goto fail; } /* Allocate space where we'll store the copied in user command lists * and shader records. * * We don't just copy directly into the BOs because we need to * read the contents back for validation, and I think the * bo->vaddr is uncached access. */ temp = drm_malloc_ab(temp_size, 1); if (!temp) { DRM_ERROR(""Failed to allocate storage for copying "" ""in bin/render CLs.\n""); ret = -ENOMEM; goto fail; } bin = temp + bin_offset; exec->shader_rec_u = temp + shader_rec_offset; exec->uniforms_u = temp + uniforms_offset; exec->shader_state = temp + exec_size; exec->shader_state_size = args->shader_rec_count; if (copy_from_user(bin, (void __user *)(uintptr_t)args->bin_cl, args->bin_cl_size)) { ret = -EFAULT; goto fail; } if (copy_from_user(exec->shader_rec_u, (void __user *)(uintptr_t)args->shader_rec, args->shader_rec_size)) { ret = -EFAULT; goto fail; } if (copy_from_user(exec->uniforms_u, (void __user *)(uintptr_t)args->uniforms, args->uniforms_size)) { ret = -EFAULT; goto fail; } bo = vc4_bo_create(dev, exec_size, true); if (IS_ERR(bo)) { DRM_ERROR(""Couldn't allocate BO for binning\n""); ret = PTR_ERR(bo); goto fail; } exec->exec_bo = &bo->base; list_add_tail(&to_vc4_bo(&exec->exec_bo->base)->unref_head, &exec->unref_list); exec->ct0ca = exec->exec_bo->paddr + bin_offset; exec->bin_u = bin; exec->shader_rec_v = exec->exec_bo->vaddr + shader_rec_offset; exec->shader_rec_p = exec->exec_bo->paddr + shader_rec_offset; exec->shader_rec_size = args->shader_rec_size; exec->uniforms_v = exec->exec_bo->vaddr + uniforms_offset; exec->uniforms_p = exec->exec_bo->paddr + uniforms_offset; exec->uniforms_size = args->uniforms_size; ret = vc4_validate_bin_cl(dev, exec->exec_bo->vaddr + bin_offset, bin, exec); if (ret) goto fail; ret = vc4_validate_shader_recs(dev, exec); if (ret) goto fail; /* Block waiting on any previous rendering into the CS's VBO, * IB, or textures, so that pixels are actually written by the * time we try to read them. */ ret = vc4_wait_for_seqno(dev, exec->bin_dep_seqno, ~0ull, true); fail: drm_free_large(temp); return ret; }","{'deleted': [{'line_no': 16, 'char_start': 523, 'char_end': 567, 'line': '\tif (uniforms_offset < shader_rec_offset ||\n'}], 'added': [{'line_no': 16, 'char_start': 523, 'char_end': 569, 'line': '\tif (shader_rec_offset < args->bin_cl_size ||\n'}, {'line_no': 17, 'char_start': 569, 'char_end': 613, 'line': '\t uniforms_offset < shader_rec_offset ||\n'}]}","{'deleted': [], 'added': [{'char_start': 528, 'char_end': 574, 'chars': 'shader_rec_offset < args->bin_cl_size ||\n\t '}]}",github.com/torvalds/linux/commit/0f2ff82e11c86c05d051cae32b58226392d33bbf,drivers/gpu/drm/vc4/vc4_gem.c,cwe-190,852 cwe-089,update_institutions,"def update_institutions(conn, sqlite, k10plus, ai): """""" Update the institution table. """""" current_institutions = get_all_current_institutions(k10plus, ai) old_institutions = get_all_old_institutions(conn, sqlite) # Check if the institution table is allready filled and this is not the first checkup institution_table_is_filled = len(old_institutions) > 10 for old_institution in old_institutions: if institution_table_is_filled and old_institution not in current_institutions: message = ""Die ISIL %s ist im aktuellen Import nicht mehr vorhanden.\nWenn dies beabsichtigt ist, bitte die Institution aus der Datenbank loeschen."" % old_institution send_message(message) for current_institution in current_institutions: if current_institution == "" "" or '""' in current_institution: continue if current_institution not in old_institutions: message = ""The institution %s is new in Solr."" % current_institution if institution_table_is_filled: send_message(message) else: logging.info(message) sql = ""INSERT INTO institution (institution) VALUES ('%s')"" % current_institution sqlite.execute(sql) conn.commit()","def update_institutions(conn, sqlite, k10plus, ai): """""" Update the institution table. """""" current_institutions = get_all_current_institutions(k10plus, ai) old_institutions = get_all_old_institutions(conn, sqlite) # Check if the institution table is allready filled and this is not the first checkup institution_table_is_filled = len(old_institutions) > 10 for old_institution in old_institutions: if institution_table_is_filled and old_institution not in current_institutions: message = ""Die ISIL %s ist im aktuellen Import nicht mehr vorhanden.\nWenn dies beabsichtigt ist, bitte die Institution aus der Datenbank loeschen."" % old_institution send_message(message) for current_institution in current_institutions: if current_institution == "" "" or '""' in current_institution: continue if current_institution not in old_institutions: message = ""The institution %s is new in Solr."" % current_institution if institution_table_is_filled: send_message(message) else: logging.info(message) sql = ""INSERT INTO institution (institution) VALUES (?)"" sqlite.execute(sql, (current_institution,)) conn.commit()","{'deleted': [{'line_no': 25, 'char_start': 1155, 'char_end': 1249, 'line': ' sql = ""INSERT INTO institution (institution) VALUES (\'%s\')"" % current_institution\n'}, {'line_no': 26, 'char_start': 1249, 'char_end': 1281, 'line': ' sqlite.execute(sql)\n'}], 'added': [{'line_no': 25, 'char_start': 1155, 'char_end': 1224, 'line': ' sql = ""INSERT INTO institution (institution) VALUES (?)""\n'}, {'line_no': 26, 'char_start': 1224, 'char_end': 1280, 'line': ' sqlite.execute(sql, (current_institution,))\n'}]}","{'deleted': [{'char_start': 1220, 'char_end': 1224, 'chars': ""'%s'""}, {'char_start': 1226, 'char_end': 1248, 'chars': ' % current_institution'}], 'added': [{'char_start': 1220, 'char_end': 1221, 'chars': '?'}, {'char_start': 1254, 'char_end': 1278, 'chars': ', (current_institution,)'}]}",github.com/miku/siskin/commit/7fa398d2fea72bf2e8b4808f75df4b3d35ae959a,bin/solrcheckup.py,cwe-089,272 cwe-089,system_search," def system_search(self, search): search = search.lower() conn = sqlite3.connect('data/ed.db').cursor() table = conn.execute(f""select * from populated where lower(name) = '{search}'"") results = table.fetchone() if not results: table = conn.execute(f""select * from systems where lower(name) = '{search}'"") results = table.fetchone() if results: keys = tuple(i[0] for i in table.description) return '\n'.join(f'{key.replace(""_"", "" "").title()}: {field}' for key, field in zip(keys[1:], results[1:]) if field) else: return 'No systems found.'"," def system_search(self, search): search = search.lower() conn = sqlite3.connect('data/ed.db').cursor() table = conn.execute('select * from populated where lower(name) = ?', (search,)) results = table.fetchone() if not results: table = conn.execute('select * from systems where lower(name) = ?', (search,)) results = table.fetchone() if results: keys = tuple(i[0] for i in table.description) return '\n'.join(f'{key.replace(""_"", "" "").title()}: {field}' for key, field in zip(keys[1:], results[1:]) if field) else: return 'No systems found.'","{'deleted': [{'line_no': 4, 'char_start': 126, 'char_end': 215, 'line': ' table = conn.execute(f""select * from populated where lower(name) = \'{search}\'"")\r\n'}, {'line_no': 7, 'char_start': 276, 'char_end': 367, 'line': ' table = conn.execute(f""select * from systems where lower(name) = \'{search}\'"")\r\n'}], 'added': [{'line_no': 4, 'char_start': 126, 'char_end': 216, 'line': "" table = conn.execute('select * from populated where lower(name) = ?', (search,))\r\n""}, {'line_no': 7, 'char_start': 277, 'char_end': 369, 'line': "" table = conn.execute('select * from systems where lower(name) = ?', (search,))\r\n""}]}","{'deleted': [{'char_start': 155, 'char_end': 157, 'chars': 'f""'}, {'char_start': 202, 'char_end': 203, 'chars': '{'}, {'char_start': 209, 'char_end': 212, 'chars': '}\'""'}, {'char_start': 309, 'char_end': 311, 'chars': 'f""'}, {'char_start': 354, 'char_end': 355, 'chars': '{'}, {'char_start': 361, 'char_end': 364, 'chars': '}\'""'}], 'added': [{'char_start': 155, 'char_end': 156, 'chars': ""'""}, {'char_start': 200, 'char_end': 201, 'chars': '?'}, {'char_start': 202, 'char_end': 205, 'chars': ', ('}, {'char_start': 211, 'char_end': 213, 'chars': ',)'}, {'char_start': 310, 'char_end': 311, 'chars': ""'""}, {'char_start': 353, 'char_end': 354, 'chars': '?'}, {'char_start': 355, 'char_end': 358, 'chars': ', ('}, {'char_start': 364, 'char_end': 366, 'chars': ',)'}]}",github.com/BeatButton/beattie/commit/ab36b2053ee09faf4cc9a279cf7a4c010864cb29,eddb.py,cwe-089,153 cwe-078,take_bug_report," def take_bug_report(self, test_name, begin_time): """"""Takes a bug report on the device and stores it in a file. Args: test_name: Name of the test case that triggered this bug report. begin_time: Logline format timestamp taken when the test started. """""" new_br = True try: stdout = self.adb.shell('bugreportz -v').decode('utf-8') # This check is necessary for builds before N, where adb shell's ret # code and stderr are not propagated properly. if 'not found' in stdout: new_br = False except adb.AdbError: new_br = False br_path = os.path.join(self.log_path, 'BugReports') utils.create_dir(br_path) base_name = ',%s,%s.txt' % (begin_time, self.serial) if new_br: base_name = base_name.replace('.txt', '.zip') test_name_len = utils.MAX_FILENAME_LEN - len(base_name) out_name = test_name[:test_name_len] + base_name full_out_path = os.path.join(br_path, out_name.replace(' ', r'\ ')) # in case device restarted, wait for adb interface to return self.wait_for_boot_completion() self.log.info('Taking bugreport for %s.', test_name) if new_br: out = self.adb.shell('bugreportz').decode('utf-8') if not out.startswith('OK'): raise DeviceError(self, 'Failed to take bugreport: %s' % out) br_out_path = out.split(':')[1].strip() self.adb.pull('%s %s' % (br_out_path, full_out_path)) else: self.adb.bugreport(' > %s' % full_out_path) self.log.info('Bugreport for %s taken at %s.', test_name, full_out_path)"," def take_bug_report(self, test_name, begin_time): """"""Takes a bug report on the device and stores it in a file. Args: test_name: Name of the test case that triggered this bug report. begin_time: Logline format timestamp taken when the test started. """""" new_br = True try: stdout = self.adb.shell('bugreportz -v').decode('utf-8') # This check is necessary for builds before N, where adb shell's ret # code and stderr are not propagated properly. if 'not found' in stdout: new_br = False except adb.AdbError: new_br = False br_path = os.path.join(self.log_path, 'BugReports') utils.create_dir(br_path) base_name = ',%s,%s.txt' % (begin_time, self.serial) if new_br: base_name = base_name.replace('.txt', '.zip') test_name_len = utils.MAX_FILENAME_LEN - len(base_name) out_name = test_name[:test_name_len] + base_name full_out_path = os.path.join(br_path, out_name.replace(' ', r'\ ')) # in case device restarted, wait for adb interface to return self.wait_for_boot_completion() self.log.info('Taking bugreport for %s.', test_name) if new_br: out = self.adb.shell('bugreportz').decode('utf-8') if not out.startswith('OK'): raise DeviceError(self, 'Failed to take bugreport: %s' % out) br_out_path = out.split(':')[1].strip() self.adb.pull([br_out_path, full_out_path]) else: # shell=True as this command redirects the stdout to a local file # using shell redirection. self.adb.bugreport(' > %s' % full_out_path, shell=True) self.log.info('Bugreport for %s taken at %s.', test_name, full_out_path)","{'deleted': [{'line_no': 33, 'char_start': 1526, 'char_end': 1592, 'line': "" self.adb.pull('%s %s' % (br_out_path, full_out_path))\n""}, {'line_no': 35, 'char_start': 1606, 'char_end': 1662, 'line': "" self.adb.bugreport(' > %s' % full_out_path)\n""}], 'added': [{'line_no': 33, 'char_start': 1526, 'char_end': 1582, 'line': ' self.adb.pull([br_out_path, full_out_path])\n'}, {'line_no': 37, 'char_start': 1713, 'char_end': 1781, 'line': "" self.adb.bugreport(' > %s' % full_out_path, shell=True)\n""}]}","{'deleted': [{'char_start': 1552, 'char_end': 1563, 'chars': ""'%s %s' % (""}, {'char_start': 1589, 'char_end': 1590, 'chars': ')'}], 'added': [{'char_start': 1552, 'char_end': 1553, 'chars': '['}, {'char_start': 1579, 'char_end': 1580, 'chars': ']'}, {'char_start': 1608, 'char_end': 1725, 'chars': '# shell=True as this command redirects the stdout to a local file\n # using shell redirection.\n '}, {'char_start': 1767, 'char_end': 1779, 'chars': ', shell=True'}]}",github.com/google/mobly/commit/3862e8ba359040fbdd6e1a6d36e51d07cda8e1ee,mobly/controllers/android_device.py,cwe-078,416 cwe-089,add_language,"def add_language(lang): try: cur.execute(f""INSERT INTO language (name) VALUES ('{lang}')"") except Exception as e: pass cur.execute(f""SELECT language_id FROM language where name='{lang}'"") lang_id = cur.fetchone()[0] if conn.commit(): return lang_id return lang_id","def add_language(lang): try: cur.execute(""INSERT INTO language (name) VALUES (%s)"", (lang, )) except Exception as e: pass cur.execute(""SELECT language_id FROM language where name=%s"", (lang, )) lang_id = cur.fetchone()[0] if conn.commit(): return lang_id return lang_id","{'deleted': [{'line_no': 3, 'char_start': 33, 'char_end': 103, 'line': ' cur.execute(f""INSERT INTO language (name) VALUES (\'{lang}\')"")\n'}, {'line_no': 6, 'char_start': 143, 'char_end': 216, 'line': ' cur.execute(f""SELECT language_id FROM language where name=\'{lang}\'"")\n'}], 'added': [{'line_no': 3, 'char_start': 33, 'char_end': 106, 'line': ' cur.execute(""INSERT INTO language (name) VALUES (%s)"", (lang, ))\n'}, {'line_no': 6, 'char_start': 146, 'char_end': 222, 'line': ' cur.execute(""SELECT language_id FROM language where name=%s"", (lang, ))\n'}]}","{'deleted': [{'char_start': 53, 'char_end': 54, 'chars': 'f'}, {'char_start': 91, 'char_end': 93, 'chars': ""'{""}, {'char_start': 97, 'char_end': 99, 'chars': ""}'""}, {'char_start': 100, 'char_end': 101, 'chars': '""'}, {'char_start': 159, 'char_end': 160, 'chars': 'f'}, {'char_start': 205, 'char_end': 207, 'chars': ""'{""}, {'char_start': 211, 'char_end': 214, 'chars': '}\'""'}], 'added': [{'char_start': 90, 'char_end': 97, 'chars': '%s)"", ('}, {'char_start': 101, 'char_end': 103, 'chars': ', '}, {'char_start': 207, 'char_end': 213, 'chars': '%s"", ('}, {'char_start': 217, 'char_end': 220, 'chars': ', )'}]}",github.com/Elbertbiggs360/dvdrental/commit/ad144ae2a08a332498d0831bc255170d57ba754b,app.py,cwe-089,73 cwe-089,get_login2,"@bot.message_handler(func = lambda message: get_current_state(message.chat.id) == config.States.S_LOGIN.value) def get_login2(message): settings = sqlite3.connect(os.path.abspath(os.path.dirname(__file__)) + ""\\bases\\settings.db"") conn = settings.cursor() if bases.createuserbase.check_username(message.text): bot.send_message(message.chat.id, ""Invalid handle."") set_state(message.chat.id, config.States.S_START.value) return 0 conn.execute(""select * from users where chat_id = '"" + str(message.chat.id) + ""'"") name = conn.fetchone() settings.close() bases.update.cf_update() bases.createuserbase.clean_base(name[1]) bases.createuserbase.clean_base(message.text) bot.send_message(message.chat.id, ""Creating base..."") bases.createuserbase.init_user(message.text, message.chat.id) bot.send_message(message.chat.id, ""Done!"") set_state(message.chat.id, config.States.S_START.value)","@bot.message_handler(func = lambda message: get_current_state(message.chat.id) == config.States.S_LOGIN.value) def get_login2(message): settings = sqlite3.connect(os.path.abspath(os.path.dirname(__file__)) + ""\\bases\\settings.db"") conn = settings.cursor() if bases.createuserbase.check_username(message.text): bot.send_message(message.chat.id, ""Invalid handle."") set_state(message.chat.id, config.States.S_START.value) return 0 conn.execute(""select * from users where chat_id = ?"", (str(message.chat.id),)) name = conn.fetchone() settings.close() bases.update.cf_update() bases.createuserbase.clean_base(name[1]) bases.createuserbase.clean_base(message.text) bot.send_message(message.chat.id, ""Creating base..."") bases.createuserbase.init_user(message.text, message.chat.id) bot.send_message(message.chat.id, ""Done!"") set_state(message.chat.id, config.States.S_START.value)","{'deleted': [{'line_no': 9, 'char_start': 465, 'char_end': 466, 'line': '\n'}, {'line_no': 10, 'char_start': 466, 'char_end': 553, 'line': ' conn.execute(""select * from users where chat_id = \'"" + str(message.chat.id) + ""\'"")\n'}], 'added': [{'line_no': 9, 'char_start': 465, 'char_end': 548, 'line': ' conn.execute(""select * from users where chat_id = ?"", (str(message.chat.id),))\n'}]}","{'deleted': [{'char_start': 465, 'char_end': 466, 'chars': '\n'}, {'char_start': 520, 'char_end': 521, 'chars': ""'""}, {'char_start': 522, 'char_end': 524, 'chars': ' +'}, {'char_start': 545, 'char_end': 551, 'chars': ' + ""\'""'}], 'added': [{'char_start': 519, 'char_end': 520, 'chars': '?'}, {'char_start': 521, 'char_end': 522, 'chars': ','}, {'char_start': 523, 'char_end': 524, 'chars': '('}, {'char_start': 544, 'char_end': 546, 'chars': ',)'}]}",github.com/lissrbay/codeforces_bot/commit/cc7f5143445a0030b1149ac60a65b1b1b9c92a90,bot.py,cwe-089,210 cwe-089,getCommentsByPostid," def getCommentsByPostid(self,postid,userid): sqlText=""select (select Count(*) from comment_like where comments.commentid = comment_like.commentid) as like,(select Count(*) from comment_like where comments.commentid = comment_like.commentid and comment_like.userid=%d) as flag,commentid,name,comment from users,comments where users.userid=comments.userid and postid=%d order by date desc;""%(userid,postid) result=sql.queryDB(self.conn,sqlText) return result;"," def getCommentsByPostid(self,postid,userid): sqlText=""select (select Count(*) from comment_like where \ comments.commentid = comment_like.commentid) as like,(select Count(*) \ from comment_like where comments.commentid = \ comment_like.commentid and comment_like.userid=%s) as \ flag,commentid,name,comment from users,comments where \ users.userid=comments.userid and postid=%s order by date desc;"" params=[userid,postid] result=sql.queryDB(self.conn,sqlText,params) return result;","{'deleted': [{'line_no': 2, 'char_start': 49, 'char_end': 417, 'line': ' sqlText=""select (select Count(*) from comment_like where comments.commentid = comment_like.commentid) as like,(select Count(*) from comment_like where comments.commentid = comment_like.commentid and comment_like.userid=%d) as flag,commentid,name,comment from users,comments where users.userid=comments.userid and postid=%d order by date desc;""%(userid,postid)\n'}, {'line_no': 3, 'char_start': 417, 'char_end': 463, 'line': ' result=sql.queryDB(self.conn,sqlText)\n'}], 'added': [{'line_no': 2, 'char_start': 49, 'char_end': 116, 'line': ' sqlText=""select (select Count(*) from comment_like where \\\n'}, {'line_no': 3, 'char_start': 116, 'char_end': 196, 'line': ' comments.commentid = comment_like.commentid) as like,(select Count(*) \\\n'}, {'line_no': 4, 'char_start': 196, 'char_end': 259, 'line': ' from comment_like where comments.commentid = \\\n'}, {'line_no': 5, 'char_start': 259, 'char_end': 331, 'line': ' comment_like.commentid and comment_like.userid=%s) as \\\n'}, {'line_no': 6, 'char_start': 331, 'char_end': 403, 'line': ' flag,commentid,name,comment from users,comments where \\\n'}, {'line_no': 7, 'char_start': 403, 'char_end': 483, 'line': ' users.userid=comments.userid and postid=%s order by date desc;""\n'}, {'line_no': 8, 'char_start': 483, 'char_end': 514, 'line': ' params=[userid,postid]\n'}, {'line_no': 9, 'char_start': 514, 'char_end': 567, 'line': ' result=sql.queryDB(self.conn,sqlText,params)\n'}]}","{'deleted': [{'char_start': 277, 'char_end': 278, 'chars': 'd'}, {'char_start': 378, 'char_end': 379, 'chars': 'd'}, {'char_start': 400, 'char_end': 402, 'chars': '%('}, {'char_start': 415, 'char_end': 416, 'chars': ')'}], 'added': [{'char_start': 114, 'char_end': 124, 'chars': '\\\n '}, {'char_start': 194, 'char_end': 212, 'chars': '\\\n '}, {'char_start': 257, 'char_end': 275, 'chars': '\\\n '}, {'char_start': 323, 'char_end': 324, 'chars': 's'}, {'char_start': 329, 'char_end': 347, 'chars': '\\\n '}, {'char_start': 401, 'char_end': 419, 'chars': '\\\n '}, {'char_start': 460, 'char_end': 461, 'chars': 's'}, {'char_start': 482, 'char_end': 499, 'chars': '\n params=['}, {'char_start': 512, 'char_end': 513, 'chars': ']'}, {'char_start': 558, 'char_end': 565, 'chars': ',params'}]}",github.com/ShaominLi/Twitter_project/commit/5329d91f9e569c95184053c8e7ef596949c33ce9,modules/comment.py,cwe-089,111 cwe-089,delete_resultSet," def delete_resultSet(self, session, id): self._openContainer(session) sid = str(id) if (self.idNormalizer is not None): sid = self.idNormalizer.process_string(session, sid) query = ""DELETE FROM %s WHERE identifier = '%s';"" % (self.table, sid) self._query(query)"," def delete_resultSet(self, session, id): self._openContainer(session) sid = str(id) if (self.idNormalizer is not None): sid = self.idNormalizer.process_string(session, sid) query = ""DELETE FROM %s WHERE identifier = $1;"" % (self.table) self._query(query, sid)","{'deleted': [{'line_no': 6, 'char_start': 213, 'char_end': 291, 'line': ' query = ""DELETE FROM %s WHERE identifier = \'%s\';"" % (self.table, sid)\n'}, {'line_no': 7, 'char_start': 291, 'char_end': 317, 'line': ' self._query(query)\n'}], 'added': [{'line_no': 6, 'char_start': 213, 'char_end': 284, 'line': ' query = ""DELETE FROM %s WHERE identifier = $1;"" % (self.table)\n'}, {'line_no': 7, 'char_start': 284, 'char_end': 315, 'line': ' self._query(query, sid)'}]}","{'deleted': [{'char_start': 264, 'char_end': 268, 'chars': ""'%s'""}, {'char_start': 284, 'char_end': 289, 'chars': ', sid'}], 'added': [{'char_start': 264, 'char_end': 266, 'chars': '$1'}, {'char_start': 309, 'char_end': 314, 'chars': ', sid'}]}",github.com/cheshire3/cheshire3/commit/d350363b4ea10f102c24c8f26d7b76b006323e8e,cheshire3/sql/resultSetStore.py,cwe-089,76 cwe-787,mapi_attr_read,"mapi_attr_read (size_t len, unsigned char *buf) { size_t idx = 0; uint32 i,j; assert(len > 4); uint32 num_properties = GETINT32(buf+idx); MAPI_Attr** attrs = CHECKED_XMALLOC (MAPI_Attr*, (num_properties + 1)); idx += 4; if (!attrs) return NULL; for (i = 0; i < num_properties; i++) { MAPI_Attr* a = attrs[i] = CHECKED_XCALLOC(MAPI_Attr, 1); MAPI_Value* v = NULL; CHECKINT16(idx, len); a->type = GETINT16(buf+idx); idx += 2; CHECKINT16(idx, len); a->name = GETINT16(buf+idx); idx += 2; /* handle special case of GUID prefixed properties */ if (a->name & GUID_EXISTS_FLAG) { /* copy GUID */ a->guid = CHECKED_XMALLOC(GUID, 1); copy_guid_from_buf(a->guid, buf+idx, len); idx += sizeof (GUID); CHECKINT32(idx, len); a->num_names = GETINT32(buf+idx); idx += 4; if (a->num_names > 0) { /* FIXME: do something useful here! */ size_t i; a->names = CHECKED_XCALLOC(VarLenData, a->num_names); for (i = 0; i < a->num_names; i++) { size_t j; CHECKINT32(idx, len); a->names[i].len = GETINT32(buf+idx); idx += 4; /* read the data into a buffer */ a->names[i].data = CHECKED_XMALLOC(unsigned char, a->names[i].len); for (j = 0; j < (a->names[i].len >> 1); j++) a->names[i].data[j] = (buf+idx)[j*2]; /* But what are we going to do with it? */ idx += pad_to_4byte(a->names[i].len); } } else { /* get the 'real' name */ CHECKINT32(idx, len); a->name = GETINT32(buf+idx); idx+= 4; } } /* * Multi-value types and string/object/binary types have * multiple values */ if (a->type & MULTI_VALUE_FLAG || a->type == szMAPI_STRING || a->type == szMAPI_UNICODE_STRING || a->type == szMAPI_OBJECT || a->type == szMAPI_BINARY) { CHECKINT32(idx, len); a->num_values = GETINT32(buf+idx); idx += 4; } else { a->num_values = 1; } /* Amend the type in case of multi-value type */ if (a->type & MULTI_VALUE_FLAG) { a->type -= MULTI_VALUE_FLAG; } v = alloc_mapi_values (a); for (j = 0; j < a->num_values; j++) { switch (a->type) { case szMAPI_SHORT: /* 2 bytes */ v->len = 2; CHECKINT16(idx, len); v->data.bytes2 = GETINT16(buf+idx); idx += 4; /* assume padding of 2, advance by 4! */ break; case szMAPI_INT: /* 4 bytes */ v->len = 4; CHECKINT32(idx, len); v->data.bytes4 = GETINT32(buf+idx); idx += 4; v++; break; case szMAPI_FLOAT: /* 4 bytes */ case szMAPI_BOOLEAN: /* this should be 2 bytes + 2 padding */ v->len = 4; CHECKINT32(idx, len); v->data.bytes4 = GETINT32(buf+idx); idx += v->len; break; case szMAPI_SYSTIME: /* 8 bytes */ v->len = 8; CHECKINT32(idx, len); v->data.bytes8[0] = GETINT32(buf+idx); CHECKINT32(idx+4, len); v->data.bytes8[1] = GETINT32(buf+idx+4); idx += 8; v++; break; case szMAPI_DOUBLE: /* 8 bytes */ case szMAPI_APPTIME: case szMAPI_CURRENCY: case szMAPI_INT8BYTE: v->len = 8; CHECKINT32(idx, len); v->data.bytes8[0] = GETINT32(buf+idx); CHECKINT32(idx+4, len); v->data.bytes8[1] = GETINT32(buf+idx+4); idx += v->len; break; case szMAPI_CLSID: v->len = sizeof (GUID); copy_guid_from_buf(&v->data.guid, buf+idx, len); idx += v->len; break; case szMAPI_STRING: case szMAPI_UNICODE_STRING: case szMAPI_OBJECT: case szMAPI_BINARY: CHECKINT32(idx, len); v->len = GETINT32(buf+idx); idx += 4; if (a->type == szMAPI_UNICODE_STRING) { v->data.buf = (unsigned char*)unicode_to_utf8(v->len, buf+idx); } else { v->data.buf = CHECKED_XMALLOC(unsigned char, v->len); memmove (v->data.buf, buf+idx, v->len); } idx += pad_to_4byte(v->len); v++; break; case szMAPI_NULL: /* illegal in input tnef streams */ case szMAPI_ERROR: case szMAPI_UNSPECIFIED: fprintf (stderr, ""Invalid attribute, input file may be corrupted\n""); if (!ENCODE_SKIP) exit (1); return NULL; default: /* should never get here */ fprintf (stderr, ""Undefined attribute, input file may be corrupted\n""); if (!ENCODE_SKIP) exit (1); return NULL; } if (DEBUG_ON) mapi_attr_dump (attrs[i]); } } attrs[i] = NULL; return attrs; }","mapi_attr_read (size_t len, unsigned char *buf) { size_t idx = 0; uint32 i,j; assert(len > 4); uint32 num_properties = GETINT32(buf+idx); assert((num_properties+1) != 0); MAPI_Attr** attrs = CHECKED_XMALLOC (MAPI_Attr*, (num_properties + 1)); idx += 4; if (!attrs) return NULL; for (i = 0; i < num_properties; i++) { MAPI_Attr* a = attrs[i] = CHECKED_XCALLOC(MAPI_Attr, 1); MAPI_Value* v = NULL; CHECKINT16(idx, len); a->type = GETINT16(buf+idx); idx += 2; CHECKINT16(idx, len); a->name = GETINT16(buf+idx); idx += 2; /* handle special case of GUID prefixed properties */ if (a->name & GUID_EXISTS_FLAG) { /* copy GUID */ a->guid = CHECKED_XMALLOC(GUID, 1); copy_guid_from_buf(a->guid, buf+idx, len); idx += sizeof (GUID); CHECKINT32(idx, len); a->num_names = GETINT32(buf+idx); idx += 4; if (a->num_names > 0) { /* FIXME: do something useful here! */ size_t i; a->names = CHECKED_XCALLOC(VarLenData, a->num_names); for (i = 0; i < a->num_names; i++) { size_t j; CHECKINT32(idx, len); a->names[i].len = GETINT32(buf+idx); idx += 4; /* read the data into a buffer */ a->names[i].data = CHECKED_XMALLOC(unsigned char, a->names[i].len); assert((idx+(a->names[i].len*2)) <= len); for (j = 0; j < (a->names[i].len >> 1); j++) a->names[i].data[j] = (buf+idx)[j*2]; /* But what are we going to do with it? */ idx += pad_to_4byte(a->names[i].len); } } else { /* get the 'real' name */ CHECKINT32(idx, len); a->name = GETINT32(buf+idx); idx+= 4; } } /* * Multi-value types and string/object/binary types have * multiple values */ if (a->type & MULTI_VALUE_FLAG || a->type == szMAPI_STRING || a->type == szMAPI_UNICODE_STRING || a->type == szMAPI_OBJECT || a->type == szMAPI_BINARY) { CHECKINT32(idx, len); a->num_values = GETINT32(buf+idx); idx += 4; } else { a->num_values = 1; } /* Amend the type in case of multi-value type */ if (a->type & MULTI_VALUE_FLAG) { a->type -= MULTI_VALUE_FLAG; } v = alloc_mapi_values (a); for (j = 0; j < a->num_values; j++) { switch (a->type) { case szMAPI_SHORT: /* 2 bytes */ v->len = 2; CHECKINT16(idx, len); v->data.bytes2 = GETINT16(buf+idx); idx += 4; /* assume padding of 2, advance by 4! */ break; case szMAPI_INT: /* 4 bytes */ v->len = 4; CHECKINT32(idx, len); v->data.bytes4 = GETINT32(buf+idx); idx += 4; v++; break; case szMAPI_FLOAT: /* 4 bytes */ case szMAPI_BOOLEAN: /* this should be 2 bytes + 2 padding */ v->len = 4; CHECKINT32(idx, len); v->data.bytes4 = GETINT32(buf+idx); idx += v->len; break; case szMAPI_SYSTIME: /* 8 bytes */ v->len = 8; CHECKINT32(idx, len); v->data.bytes8[0] = GETINT32(buf+idx); CHECKINT32(idx+4, len); v->data.bytes8[1] = GETINT32(buf+idx+4); idx += 8; v++; break; case szMAPI_DOUBLE: /* 8 bytes */ case szMAPI_APPTIME: case szMAPI_CURRENCY: case szMAPI_INT8BYTE: v->len = 8; CHECKINT32(idx, len); v->data.bytes8[0] = GETINT32(buf+idx); CHECKINT32(idx+4, len); v->data.bytes8[1] = GETINT32(buf+idx+4); idx += v->len; break; case szMAPI_CLSID: v->len = sizeof (GUID); copy_guid_from_buf(&v->data.guid, buf+idx, len); idx += v->len; break; case szMAPI_STRING: case szMAPI_UNICODE_STRING: case szMAPI_OBJECT: case szMAPI_BINARY: CHECKINT32(idx, len); v->len = GETINT32(buf+idx); idx += 4; assert(v->len + idx <= len); if (a->type == szMAPI_UNICODE_STRING) { assert(v->len != 0); v->data.buf = (unsigned char*)unicode_to_utf8(v->len, buf+idx); } else { v->data.buf = CHECKED_XMALLOC(unsigned char, v->len); memmove (v->data.buf, buf+idx, v->len); } idx += pad_to_4byte(v->len); v++; break; case szMAPI_NULL: /* illegal in input tnef streams */ case szMAPI_ERROR: case szMAPI_UNSPECIFIED: fprintf (stderr, ""Invalid attribute, input file may be corrupted\n""); if (!ENCODE_SKIP) exit (1); return NULL; default: /* should never get here */ fprintf (stderr, ""Undefined attribute, input file may be corrupted\n""); if (!ENCODE_SKIP) exit (1); return NULL; } if (DEBUG_ON) mapi_attr_dump (attrs[i]); } } attrs[i] = NULL; return attrs; }","{'deleted': [], 'added': [{'line_no': 7, 'char_start': 154, 'char_end': 191, 'line': ' assert((num_properties+1) != 0);\n'}, {'line_no': 46, 'char_start': 1263, 'char_end': 1311, 'line': '\t\t assert((idx+(a->names[i].len*2)) <= len);\n'}, {'line_no': 143, 'char_start': 3582, 'char_end': 3613, 'line': '\t\tassert(v->len + idx <= len);\n'}, {'line_no': 144, 'char_start': 3613, 'char_end': 3614, 'line': '\n'}, {'line_no': 147, 'char_start': 3658, 'char_end': 3685, 'line': '\t\t assert(v->len != 0);\n'}]}","{'deleted': [], 'added': [{'char_start': 158, 'char_end': 195, 'chars': 'assert((num_properties+1) != 0);\n '}, {'char_start': 1257, 'char_end': 1305, 'chars': 'len);\n\t\t assert((idx+(a->names[i].len*2)) <= '}, {'char_start': 3584, 'char_end': 3616, 'chars': 'assert(v->len + idx <= len);\n\n\t\t'}, {'char_start': 3657, 'char_end': 3684, 'chars': '\n\t\t assert(v->len != 0);'}]}",github.com/verdammelt/tnef/commit/1a17af1ed0c791aec44dbdc9eab91218cc1e335a,src/mapi_attr.c,cwe-787,1479 cwe-078,terminate_connection," def terminate_connection(self, volume, connector, **kwargs): """"""Cleanup after an iSCSI connection has been terminated. When we clean up a terminated connection between a given connector and volume, we: 1. Translate the given connector to a host name 2. Remove the volume-to-host mapping if it exists 3. Delete the host if it has no more mappings (hosts are created automatically by this driver when mappings are created) """""" LOG.debug(_('enter: terminate_connection: volume %(vol)s with ' 'connector %(conn)s') % {'vol': str(volume), 'conn': str(connector)}) vol_name = volume['name'] host_name = self._get_host_from_connector(connector) # Verify that _get_host_from_connector returned the host. # This should always succeed as we terminate an existing connection. self._driver_assert( host_name is not None, _('_get_host_from_connector failed to return the host name ' 'for connector')) # Check if vdisk-host mapping exists, remove if it does mapping_data = self._get_hostvdisk_mappings(host_name) if vol_name in mapping_data: ssh_cmd = 'svctask rmvdiskhostmap -host %s %s' % \ (host_name, vol_name) out, err = self._run_ssh(ssh_cmd) # Verify CLI behaviour - no output is returned from # rmvdiskhostmap self._assert_ssh_return(len(out.strip()) == 0, 'terminate_connection', ssh_cmd, out, err) del mapping_data[vol_name] else: LOG.error(_('terminate_connection: No mapping of volume ' '%(vol_name)s to host %(host_name)s found') % {'vol_name': vol_name, 'host_name': host_name}) # If this host has no more mappings, delete it if not mapping_data: self._delete_host(host_name) LOG.debug(_('leave: terminate_connection: volume %(vol)s with ' 'connector %(conn)s') % {'vol': str(volume), 'conn': str(connector)})"," def terminate_connection(self, volume, connector, **kwargs): """"""Cleanup after an iSCSI connection has been terminated. When we clean up a terminated connection between a given connector and volume, we: 1. Translate the given connector to a host name 2. Remove the volume-to-host mapping if it exists 3. Delete the host if it has no more mappings (hosts are created automatically by this driver when mappings are created) """""" LOG.debug(_('enter: terminate_connection: volume %(vol)s with ' 'connector %(conn)s') % {'vol': str(volume), 'conn': str(connector)}) vol_name = volume['name'] host_name = self._get_host_from_connector(connector) # Verify that _get_host_from_connector returned the host. # This should always succeed as we terminate an existing connection. self._driver_assert( host_name is not None, _('_get_host_from_connector failed to return the host name ' 'for connector')) # Check if vdisk-host mapping exists, remove if it does mapping_data = self._get_hostvdisk_mappings(host_name) if vol_name in mapping_data: ssh_cmd = ['svctask', 'rmvdiskhostmap', '-host', host_name, vol_name] out, err = self._run_ssh(ssh_cmd) # Verify CLI behaviour - no output is returned from # rmvdiskhostmap self._assert_ssh_return(len(out.strip()) == 0, 'terminate_connection', ssh_cmd, out, err) del mapping_data[vol_name] else: LOG.error(_('terminate_connection: No mapping of volume ' '%(vol_name)s to host %(host_name)s found') % {'vol_name': vol_name, 'host_name': host_name}) # If this host has no more mappings, delete it if not mapping_data: self._delete_host(host_name) LOG.debug(_('leave: terminate_connection: volume %(vol)s with ' 'connector %(conn)s') % {'vol': str(volume), 'conn': str(connector)})","{'deleted': [{'line_no': 27, 'char_start': 1277, 'char_end': 1340, 'line': "" ssh_cmd = 'svctask rmvdiskhostmap -host %s %s' % \\\n""}, {'line_no': 28, 'char_start': 1340, 'char_end': 1378, 'line': ' (host_name, vol_name)\n'}], 'added': [{'line_no': 27, 'char_start': 1277, 'char_end': 1349, 'line': "" ssh_cmd = ['svctask', 'rmvdiskhostmap', '-host', host_name,\n""}, {'line_no': 28, 'char_start': 1349, 'char_end': 1382, 'line': ' vol_name]\n'}]}","{'deleted': [{'char_start': 1329, 'char_end': 1330, 'chars': '%'}, {'char_start': 1332, 'char_end': 1340, 'chars': ""%s' % \\\n""}, {'char_start': 1356, 'char_end': 1367, 'chars': '(host_name,'}, {'char_start': 1376, 'char_end': 1377, 'chars': ')'}], 'added': [{'char_start': 1299, 'char_end': 1300, 'chars': '['}, {'char_start': 1308, 'char_end': 1310, 'chars': ""',""}, {'char_start': 1311, 'char_end': 1312, 'chars': ""'""}, {'char_start': 1326, 'char_end': 1328, 'chars': ""',""}, {'char_start': 1329, 'char_end': 1330, 'chars': ""'""}, {'char_start': 1335, 'char_end': 1337, 'chars': ""',""}, {'char_start': 1338, 'char_end': 1340, 'chars': 'ho'}, {'char_start': 1341, 'char_end': 1350, 'chars': 't_name,\n '}, {'char_start': 1367, 'char_end': 1371, 'chars': ' '}, {'char_start': 1380, 'char_end': 1381, 'chars': ']'}]}",github.com/thatsdone/cinder/commit/f752302d181583a95cf44354aea607ce9d9283f4,cinder/volume/drivers/storwize_svc.py,cwe-078,462 cwe-125,ReadPSDImage,"static Image *ReadPSDImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *image; MagickBooleanType has_merged_image, skip_layers; MagickOffsetType offset; MagickSizeType length; MagickBooleanType status; PSDInfo psd_info; register ssize_t i; ssize_t count; unsigned char *data; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),""%s"", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read image header. */ image->endian=MSBEndian; count=ReadBlob(image,4,(unsigned char *) psd_info.signature); psd_info.version=ReadBlobMSBShort(image); if ((count == 0) || (LocaleNCompare(psd_info.signature,""8BPS"",4) != 0) || ((psd_info.version != 1) && (psd_info.version != 2))) ThrowReaderException(CorruptImageError,""ImproperImageHeader""); (void) ReadBlob(image,6,psd_info.reserved); psd_info.channels=ReadBlobMSBShort(image); if (psd_info.channels > MaxPSDChannels) ThrowReaderException(CorruptImageError,""MaximumChannelsExceeded""); psd_info.rows=ReadBlobMSBLong(image); psd_info.columns=ReadBlobMSBLong(image); if ((psd_info.version == 1) && ((psd_info.rows > 30000) || (psd_info.columns > 30000))) ThrowReaderException(CorruptImageError,""ImproperImageHeader""); psd_info.depth=ReadBlobMSBShort(image); if ((psd_info.depth != 1) && (psd_info.depth != 8) && (psd_info.depth != 16)) ThrowReaderException(CorruptImageError,""ImproperImageHeader""); psd_info.mode=ReadBlobMSBShort(image); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" Image is %.20g x %.20g with channels=%.20g, depth=%.20g, mode=%s"", (double) psd_info.columns,(double) psd_info.rows,(double) psd_info.channels,(double) psd_info.depth,ModeToString((PSDImageType) psd_info.mode)); /* Initialize image. */ image->depth=psd_info.depth; image->columns=psd_info.columns; image->rows=psd_info.rows; status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); if (SetImageBackgroundColor(image,exception) == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } if (psd_info.mode == LabMode) SetImageColorspace(image,LabColorspace,exception); if (psd_info.mode == CMYKMode) { SetImageColorspace(image,CMYKColorspace,exception); image->alpha_trait=psd_info.channels > 4 ? BlendPixelTrait : UndefinedPixelTrait; } else if ((psd_info.mode == BitmapMode) || (psd_info.mode == GrayscaleMode) || (psd_info.mode == DuotoneMode)) { status=AcquireImageColormap(image,psd_info.depth != 16 ? 256 : 65536, exception); if (status == MagickFalse) ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" Image colormap allocated""); SetImageColorspace(image,GRAYColorspace,exception); image->alpha_trait=psd_info.channels > 1 ? BlendPixelTrait : UndefinedPixelTrait; } else image->alpha_trait=psd_info.channels > 3 ? BlendPixelTrait : UndefinedPixelTrait; /* Read PSD raster colormap only present for indexed and duotone images. */ length=ReadBlobMSBLong(image); if (length != 0) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" reading colormap""); if (psd_info.mode == DuotoneMode) { /* Duotone image data; the format of this data is undocumented. */ data=(unsigned char *) AcquireQuantumMemory((size_t) length, sizeof(*data)); if (data == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); (void) ReadBlob(image,(size_t) length,data); data=(unsigned char *) RelinquishMagickMemory(data); } else { size_t number_colors; /* Read PSD raster colormap. */ number_colors=length/3; if (number_colors > 65536) ThrowReaderException(CorruptImageError,""ImproperImageHeader""); if (AcquireImageColormap(image,number_colors,exception) == MagickFalse) ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].red=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].green=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].blue=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); image->alpha_trait=UndefinedPixelTrait; } } has_merged_image=MagickTrue; length=ReadBlobMSBLong(image); if (length != 0) { unsigned char *blocks; /* Image resources block. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" reading image resource blocks - %.20g bytes"",(double) ((MagickOffsetType) length)); blocks=(unsigned char *) AcquireQuantumMemory((size_t) length, sizeof(*blocks)); if (blocks == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); count=ReadBlob(image,(size_t) length,blocks); if ((count != (ssize_t) length) || (LocaleNCompare((char *) blocks,""8BIM"",4) != 0)) { blocks=(unsigned char *) RelinquishMagickMemory(blocks); ThrowReaderException(CorruptImageError,""ImproperImageHeader""); } ParseImageResourceBlocks(image,blocks,(size_t) length,&has_merged_image, exception); blocks=(unsigned char *) RelinquishMagickMemory(blocks); } /* Layer and mask block. */ length=GetPSDSize(&psd_info,image); if (length == 8) { length=ReadBlobMSBLong(image); length=ReadBlobMSBLong(image); } offset=TellBlob(image); skip_layers=MagickFalse; if ((image_info->number_scenes == 1) && (image_info->scene == 0) && (has_merged_image != MagickFalse)) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" read composite only""); skip_layers=MagickTrue; } if (length == 0) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" image has no layers""); } else { if (ReadPSDLayers(image,image_info,&psd_info,skip_layers,exception) != MagickTrue) { (void) CloseBlob(image); image=DestroyImageList(image); return((Image *) NULL); } /* Skip the rest of the layer and mask information. */ SeekBlob(image,offset+length,SEEK_SET); } /* If we are only ""pinging"" the image, then we're done - so return. */ if (image_info->ping != MagickFalse) { (void) CloseBlob(image); return(GetFirstImageInList(image)); } /* Read the precombined layer, present for PSD < 4 compatibility. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" reading the precombined layer""); if ((has_merged_image != MagickFalse) || (GetImageListLength(image) == 1)) has_merged_image=(MagickBooleanType) ReadPSDMergedImage(image_info,image, &psd_info,exception); if ((has_merged_image == MagickFalse) && (GetImageListLength(image) == 1) && (length != 0)) { SeekBlob(image,offset,SEEK_SET); status=ReadPSDLayers(image,image_info,&psd_info,MagickFalse,exception); if (status != MagickTrue) { (void) CloseBlob(image); image=DestroyImageList(image); return((Image *) NULL); } } if ((has_merged_image == MagickFalse) && (GetImageListLength(image) > 1)) { Image *merged; SetImageAlphaChannel(image,TransparentAlphaChannel,exception); image->background_color.alpha=TransparentAlpha; image->background_color.alpha_trait=BlendPixelTrait; merged=MergeImageLayers(image,FlattenLayer,exception); ReplaceImageInList(&image,merged); } (void) CloseBlob(image); return(GetFirstImageInList(image)); }","static Image *ReadPSDImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *image; MagickBooleanType has_merged_image, skip_layers; MagickOffsetType offset; MagickSizeType length; MagickBooleanType status; PSDInfo psd_info; register ssize_t i; ssize_t count; unsigned char *data; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),""%s"", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read image header. */ image->endian=MSBEndian; count=ReadBlob(image,4,(unsigned char *) psd_info.signature); psd_info.version=ReadBlobMSBShort(image); if ((count == 0) || (LocaleNCompare(psd_info.signature,""8BPS"",4) != 0) || ((psd_info.version != 1) && (psd_info.version != 2))) ThrowReaderException(CorruptImageError,""ImproperImageHeader""); (void) ReadBlob(image,6,psd_info.reserved); psd_info.channels=ReadBlobMSBShort(image); if (psd_info.channels > MaxPSDChannels) ThrowReaderException(CorruptImageError,""MaximumChannelsExceeded""); psd_info.rows=ReadBlobMSBLong(image); psd_info.columns=ReadBlobMSBLong(image); if ((psd_info.version == 1) && ((psd_info.rows > 30000) || (psd_info.columns > 30000))) ThrowReaderException(CorruptImageError,""ImproperImageHeader""); psd_info.depth=ReadBlobMSBShort(image); if ((psd_info.depth != 1) && (psd_info.depth != 8) && (psd_info.depth != 16)) ThrowReaderException(CorruptImageError,""ImproperImageHeader""); psd_info.mode=ReadBlobMSBShort(image); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" Image is %.20g x %.20g with channels=%.20g, depth=%.20g, mode=%s"", (double) psd_info.columns,(double) psd_info.rows,(double) psd_info.channels,(double) psd_info.depth,ModeToString((PSDImageType) psd_info.mode)); /* Initialize image. */ image->depth=psd_info.depth; image->columns=psd_info.columns; image->rows=psd_info.rows; status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); if (SetImageBackgroundColor(image,exception) == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } if (psd_info.mode == LabMode) SetImageColorspace(image,LabColorspace,exception); if (psd_info.mode == CMYKMode) { SetImageColorspace(image,CMYKColorspace,exception); image->alpha_trait=psd_info.channels > 4 ? BlendPixelTrait : UndefinedPixelTrait; } else if ((psd_info.mode == BitmapMode) || (psd_info.mode == GrayscaleMode) || (psd_info.mode == DuotoneMode)) { status=AcquireImageColormap(image,psd_info.depth != 16 ? 256 : 65536, exception); if (status == MagickFalse) ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" Image colormap allocated""); SetImageColorspace(image,GRAYColorspace,exception); image->alpha_trait=psd_info.channels > 1 ? BlendPixelTrait : UndefinedPixelTrait; } else image->alpha_trait=psd_info.channels > 3 ? BlendPixelTrait : UndefinedPixelTrait; /* Read PSD raster colormap only present for indexed and duotone images. */ length=ReadBlobMSBLong(image); if (length != 0) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" reading colormap""); if (psd_info.mode == DuotoneMode) { /* Duotone image data; the format of this data is undocumented. */ data=(unsigned char *) AcquireQuantumMemory((size_t) length, sizeof(*data)); if (data == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); (void) ReadBlob(image,(size_t) length,data); data=(unsigned char *) RelinquishMagickMemory(data); } else { size_t number_colors; /* Read PSD raster colormap. */ number_colors=length/3; if (number_colors > 65536) ThrowReaderException(CorruptImageError,""ImproperImageHeader""); if (AcquireImageColormap(image,number_colors,exception) == MagickFalse) ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].red=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].green=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].blue=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); image->alpha_trait=UndefinedPixelTrait; } } if ((image->depth == 1) && (image->storage_class != PseudoClass)) ThrowReaderException(CorruptImageError, ""ImproperImageHeader""); has_merged_image=MagickTrue; length=ReadBlobMSBLong(image); if (length != 0) { unsigned char *blocks; /* Image resources block. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" reading image resource blocks - %.20g bytes"",(double) ((MagickOffsetType) length)); blocks=(unsigned char *) AcquireQuantumMemory((size_t) length, sizeof(*blocks)); if (blocks == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); count=ReadBlob(image,(size_t) length,blocks); if ((count != (ssize_t) length) || (LocaleNCompare((char *) blocks,""8BIM"",4) != 0)) { blocks=(unsigned char *) RelinquishMagickMemory(blocks); ThrowReaderException(CorruptImageError,""ImproperImageHeader""); } ParseImageResourceBlocks(image,blocks,(size_t) length,&has_merged_image, exception); blocks=(unsigned char *) RelinquishMagickMemory(blocks); } /* Layer and mask block. */ length=GetPSDSize(&psd_info,image); if (length == 8) { length=ReadBlobMSBLong(image); length=ReadBlobMSBLong(image); } offset=TellBlob(image); skip_layers=MagickFalse; if ((image_info->number_scenes == 1) && (image_info->scene == 0) && (has_merged_image != MagickFalse)) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" read composite only""); skip_layers=MagickTrue; } if (length == 0) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" image has no layers""); } else { if (ReadPSDLayers(image,image_info,&psd_info,skip_layers,exception) != MagickTrue) { (void) CloseBlob(image); image=DestroyImageList(image); return((Image *) NULL); } /* Skip the rest of the layer and mask information. */ SeekBlob(image,offset+length,SEEK_SET); } /* If we are only ""pinging"" the image, then we're done - so return. */ if (image_info->ping != MagickFalse) { (void) CloseBlob(image); return(GetFirstImageInList(image)); } /* Read the precombined layer, present for PSD < 4 compatibility. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" reading the precombined layer""); if ((has_merged_image != MagickFalse) || (GetImageListLength(image) == 1)) has_merged_image=(MagickBooleanType) ReadPSDMergedImage(image_info,image, &psd_info,exception); if ((has_merged_image == MagickFalse) && (GetImageListLength(image) == 1) && (length != 0)) { SeekBlob(image,offset,SEEK_SET); status=ReadPSDLayers(image,image_info,&psd_info,MagickFalse,exception); if (status != MagickTrue) { (void) CloseBlob(image); image=DestroyImageList(image); return((Image *) NULL); } } if ((has_merged_image == MagickFalse) && (GetImageListLength(image) > 1)) { Image *merged; SetImageAlphaChannel(image,TransparentAlphaChannel,exception); image->background_color.alpha=TransparentAlpha; image->background_color.alpha_trait=BlendPixelTrait; merged=MergeImageLayers(image,FlattenLayer,exception); ReplaceImageInList(&image,merged); } (void) CloseBlob(image); return(GetFirstImageInList(image)); }","{'deleted': [], 'added': [{'line_no': 162, 'char_start': 5509, 'char_end': 5577, 'line': ' if ((image->depth == 1) && (image->storage_class != PseudoClass))\n'}, {'line_no': 163, 'char_start': 5577, 'char_end': 5645, 'line': ' ThrowReaderException(CorruptImageError, ""ImproperImageHeader"");\n'}]}","{'deleted': [], 'added': [{'char_start': 5511, 'char_end': 5647, 'chars': 'if ((image->depth == 1) && (image->storage_class != PseudoClass))\n ThrowReaderException(CorruptImageError, ""ImproperImageHeader"");\n '}]}",github.com/ImageMagick/ImageMagick/commit/198fffab4daf8aea88badd9c629350e5b26ec32f,coders/psd.c,cwe-125,2365 cwe-125,bitmap_cache_new,"rdpBitmapCache* bitmap_cache_new(rdpSettings* settings) { int i; rdpBitmapCache* bitmapCache; bitmapCache = (rdpBitmapCache*)calloc(1, sizeof(rdpBitmapCache)); if (!bitmapCache) return NULL; bitmapCache->settings = settings; bitmapCache->update = ((freerdp*)settings->instance)->update; bitmapCache->context = bitmapCache->update->context; bitmapCache->maxCells = settings->BitmapCacheV2NumCells; bitmapCache->cells = (BITMAP_V2_CELL*)calloc(bitmapCache->maxCells, sizeof(BITMAP_V2_CELL)); if (!bitmapCache->cells) goto fail; for (i = 0; i < (int)bitmapCache->maxCells; i++) { bitmapCache->cells[i].number = settings->BitmapCacheV2CellInfo[i].numEntries; /* allocate an extra entry for BITMAP_CACHE_WAITING_LIST_INDEX */ bitmapCache->cells[i].entries = (rdpBitmap**)calloc((bitmapCache->cells[i].number + 1), sizeof(rdpBitmap*)); if (!bitmapCache->cells[i].entries) goto fail; } return bitmapCache; fail: if (bitmapCache->cells) { for (i = 0; i < (int)bitmapCache->maxCells; i++) free(bitmapCache->cells[i].entries); } free(bitmapCache); return NULL; }","rdpBitmapCache* bitmap_cache_new(rdpSettings* settings) { int i; rdpBitmapCache* bitmapCache; bitmapCache = (rdpBitmapCache*)calloc(1, sizeof(rdpBitmapCache)); if (!bitmapCache) return NULL; bitmapCache->settings = settings; bitmapCache->update = ((freerdp*)settings->instance)->update; bitmapCache->context = bitmapCache->update->context; bitmapCache->cells = (BITMAP_V2_CELL*)calloc(settings->BitmapCacheV2NumCells, sizeof(BITMAP_V2_CELL)); if (!bitmapCache->cells) goto fail; bitmapCache->maxCells = settings->BitmapCacheV2NumCells; for (i = 0; i < (int)bitmapCache->maxCells; i++) { bitmapCache->cells[i].number = settings->BitmapCacheV2CellInfo[i].numEntries; /* allocate an extra entry for BITMAP_CACHE_WAITING_LIST_INDEX */ bitmapCache->cells[i].entries = (rdpBitmap**)calloc((bitmapCache->cells[i].number + 1), sizeof(rdpBitmap*)); if (!bitmapCache->cells[i].entries) goto fail; } return bitmapCache; fail: if (bitmapCache->cells) { for (i = 0; i < (int)bitmapCache->maxCells; i++) free(bitmapCache->cells[i].entries); } free(bitmapCache); return NULL; }","{'deleted': [{'line_no': 13, 'char_start': 351, 'char_end': 409, 'line': '\tbitmapCache->maxCells = settings->BitmapCacheV2NumCells;\n'}, {'line_no': 14, 'char_start': 409, 'char_end': 503, 'line': '\tbitmapCache->cells = (BITMAP_V2_CELL*)calloc(bitmapCache->maxCells, sizeof(BITMAP_V2_CELL));\n'}], 'added': [{'line_no': 13, 'char_start': 351, 'char_end': 373, 'line': '\tbitmapCache->cells =\n'}, {'line_no': 14, 'char_start': 373, 'char_end': 460, 'line': '\t (BITMAP_V2_CELL*)calloc(settings->BitmapCacheV2NumCells, sizeof(BITMAP_V2_CELL));\n'}, {'line_no': 18, 'char_start': 500, 'char_end': 558, 'line': '\tbitmapCache->maxCells = settings->BitmapCacheV2NumCells;\n'}]}","{'deleted': [{'char_start': 365, 'char_end': 369, 'chars': 'maxC'}, {'char_start': 375, 'char_end': 408, 'chars': ' settings->BitmapCacheV2NumCells;'}, {'char_start': 410, 'char_end': 428, 'chars': 'bitmapCache->cells'}, {'char_start': 429, 'char_end': 430, 'chars': '='}, {'char_start': 455, 'char_end': 456, 'chars': 'b'}, {'char_start': 466, 'char_end': 468, 'chars': '->'}, {'char_start': 469, 'char_end': 471, 'chars': 'ax'}], 'added': [{'char_start': 365, 'char_end': 366, 'chars': 'c'}, {'char_start': 374, 'char_end': 376, 'chars': ' '}, {'char_start': 402, 'char_end': 413, 'chars': 'settings->B'}, {'char_start': 423, 'char_end': 427, 'chars': 'V2Nu'}, {'char_start': 498, 'char_end': 556, 'chars': ';\n\tbitmapCache->maxCells = settings->BitmapCacheV2NumCells'}]}",github.com/FreeRDP/FreeRDP/commit/58dc36b3c883fd460199cedb6d30e58eba58298c,libfreerdp/cache/bitmap.c,cwe-125,317 cwe-476,tar_directory_for_file,"tar_directory_for_file (GsfInfileTar *dir, const char *name, gboolean last) { const char *s = name; while (1) { const char *s0 = s; char *dirname; /* Find a directory component, if any. */ while (1) { if (*s == 0) { if (last && s != s0) break; else return dir; } /* This is deliberately slash-only. */ if (*s == '/') break; s++; } dirname = g_strndup (s0, s - s0); while (*s == '/') s++; if (strcmp (dirname, ""."") != 0) { GsfInput *subdir = gsf_infile_child_by_name (GSF_INFILE (dir), dirname); if (subdir) { /* Undo the ref. */ g_object_unref (subdir); dir = GSF_INFILE_TAR (subdir); } else dir = tar_create_dir (dir, dirname); } g_free (dirname); } }","tar_directory_for_file (GsfInfileTar *dir, const char *name, gboolean last) { const char *s = name; while (1) { const char *s0 = s; char *dirname; /* Find a directory component, if any. */ while (1) { if (*s == 0) { if (last && s != s0) break; else return dir; } /* This is deliberately slash-only. */ if (*s == '/') break; s++; } dirname = g_strndup (s0, s - s0); while (*s == '/') s++; if (strcmp (dirname, ""."") != 0) { GsfInput *subdir = gsf_infile_child_by_name (GSF_INFILE (dir), dirname); if (subdir) { dir = GSF_IS_INFILE_TAR (subdir) ? GSF_INFILE_TAR (subdir) : dir; /* Undo the ref. */ g_object_unref (subdir); } else dir = tar_create_dir (dir, dirname); } g_free (dirname); } }","{'deleted': [{'line_no': 34, 'char_start': 645, 'char_end': 680, 'line': '\t\t\t\tdir = GSF_INFILE_TAR (subdir);\n'}], 'added': [{'line_no': 32, 'char_start': 592, 'char_end': 629, 'line': '\t\t\t\tdir = GSF_IS_INFILE_TAR (subdir)\n'}, {'line_no': 33, 'char_start': 629, 'char_end': 660, 'line': '\t\t\t\t\t? GSF_INFILE_TAR (subdir)\n'}, {'line_no': 34, 'char_start': 660, 'char_end': 672, 'line': '\t\t\t\t\t: dir;\n'}]}","{'deleted': [{'char_start': 634, 'char_end': 669, 'chars': ' (subdir);\n\t\t\t\tdir = GSF_INFILE_TAR'}], 'added': [{'char_start': 596, 'char_end': 676, 'chars': 'dir = GSF_IS_INFILE_TAR (subdir)\n\t\t\t\t\t? GSF_INFILE_TAR (subdir)\n\t\t\t\t\t: dir;\n\t\t\t\t'}]}",github.com/GNOME/libgsf/commit/95a8351a75758cf10b3bf6abae0b6b461f90d9e5,gsf/gsf-infile-tar.c,cwe-476,256 cwe-190,_zend_hash_init,"ZEND_API void ZEND_FASTCALL _zend_hash_init(HashTable *ht, uint32_t nSize, dtor_func_t pDestructor, zend_bool persistent ZEND_FILE_LINE_DC) { GC_REFCOUNT(ht) = 1; GC_TYPE_INFO(ht) = IS_ARRAY; ht->u.flags = (persistent ? HASH_FLAG_PERSISTENT : 0) | HASH_FLAG_APPLY_PROTECTION | HASH_FLAG_STATIC_KEYS; ht->nTableSize = zend_hash_check_size(nSize); ht->nTableMask = HT_MIN_MASK; HT_SET_DATA_ADDR(ht, &uninitialized_bucket); ht->nNumUsed = 0; ht->nNumOfElements = 0; ht->nInternalPointer = HT_INVALID_IDX; ht->nNextFreeElement = 0; ht->pDestructor = pDestructor; }","ZEND_API void ZEND_FASTCALL _zend_hash_init(HashTable *ht, uint32_t nSize, dtor_func_t pDestructor, zend_bool persistent ZEND_FILE_LINE_DC) { GC_REFCOUNT(ht) = 1; GC_TYPE_INFO(ht) = IS_ARRAY; ht->u.flags = (persistent ? HASH_FLAG_PERSISTENT : 0) | HASH_FLAG_APPLY_PROTECTION | HASH_FLAG_STATIC_KEYS; ht->nTableMask = HT_MIN_MASK; HT_SET_DATA_ADDR(ht, &uninitialized_bucket); ht->nNumUsed = 0; ht->nNumOfElements = 0; ht->nInternalPointer = HT_INVALID_IDX; ht->nNextFreeElement = 0; ht->pDestructor = pDestructor; ht->nTableSize = zend_hash_check_size(nSize); }","{'deleted': [{'line_no': 6, 'char_start': 303, 'char_end': 350, 'line': '\tht->nTableSize = zend_hash_check_size(nSize);\n'}], 'added': [{'line_no': 13, 'char_start': 523, 'char_end': 570, 'line': '\tht->nTableSize = zend_hash_check_size(nSize);\n'}]}","{'deleted': [{'char_start': 314, 'char_end': 361, 'chars': 'Size = zend_hash_check_size(nSize);\n\tht->nTable'}], 'added': [{'char_start': 521, 'char_end': 568, 'chars': ';\n\tht->nTableSize = zend_hash_check_size(nSize)'}]}",github.com/php/php-src/commit/4cc0286f2f3780abc6084bcdae5dce595daa3c12,Zend/zend_hash.c,cwe-190,181 cwe-089,GameNewPlayed,"def GameNewPlayed(Played, ID): db.execute(""UPDATE games set GamesPlayed = %i WHERE ID = %i"" % (Played, ID)) database.commit()","def GameNewPlayed(Played, ID): db.execute(""UPDATE games set GamesPlayed = ? WHERE ID = ?"", Played, ID) database.commit()","{'deleted': [{'line_no': 2, 'char_start': 31, 'char_end': 109, 'line': '\tdb.execute(""UPDATE games set GamesPlayed = %i WHERE ID = %i"" % (Played, ID))\n'}], 'added': [{'line_no': 2, 'char_start': 31, 'char_end': 104, 'line': '\tdb.execute(""UPDATE games set GamesPlayed = ? WHERE ID = ?"", Played, ID)\n'}]}","{'deleted': [{'char_start': 75, 'char_end': 77, 'chars': '%i'}, {'char_start': 89, 'char_end': 91, 'chars': '%i'}, {'char_start': 92, 'char_end': 94, 'chars': ' %'}, {'char_start': 95, 'char_end': 96, 'chars': '('}, {'char_start': 106, 'char_end': 107, 'chars': ')'}], 'added': [{'char_start': 75, 'char_end': 76, 'chars': '?'}, {'char_start': 88, 'char_end': 89, 'chars': '?'}, {'char_start': 90, 'char_end': 91, 'chars': ','}]}",github.com/iScrE4m/XLeague/commit/59cab6e5fd8bd5e47f2418a7c71cb1d4e3cad0d2,plugins/database.py,cwe-089,36 cwe-125,sh_op,"static int sh_op(RAnal *anal, RAnalOp *op, ut64 addr, const ut8 *data, int len) { ut8 op_MSB,op_LSB; int ret; if (!data) return 0; memset (op, '\0', sizeof (RAnalOp)); op->addr = addr; op->type = R_ANAL_OP_TYPE_UNK; op->jump = op->fail = -1; op->ptr = op->val = -1; op->size = 2; op_MSB = anal->big_endian? data[0]: data[1]; op_LSB = anal->big_endian? data[1]: data[0]; ret = first_nibble_decode[(op_MSB>>4) & 0x0F](anal, op, (ut16)(op_MSB<<8 | op_LSB)); return ret; }","static int sh_op(RAnal *anal, RAnalOp *op, ut64 addr, const ut8 *data, int len) { ut8 op_MSB,op_LSB; int ret; if (!data || len < 2) { return 0; } memset (op, '\0', sizeof (RAnalOp)); op->addr = addr; op->type = R_ANAL_OP_TYPE_UNK; op->jump = op->fail = -1; op->ptr = op->val = -1; op->size = 2; op_MSB = anal->big_endian? data[0]: data[1]; op_LSB = anal->big_endian? data[1]: data[0]; ret = first_nibble_decode[(op_MSB>>4) & 0x0F](anal, op, (ut16)(op_MSB<<8 | op_LSB)); return ret; }","{'deleted': [{'line_no': 4, 'char_start': 112, 'char_end': 124, 'line': '\tif (!data)\n'}], 'added': [{'line_no': 4, 'char_start': 112, 'char_end': 137, 'line': '\tif (!data || len < 2) {\n'}, {'line_no': 6, 'char_start': 149, 'char_end': 152, 'line': '\t}\n'}]}","{'deleted': [], 'added': [{'char_start': 122, 'char_end': 133, 'chars': ' || len < 2'}, {'char_start': 134, 'char_end': 136, 'chars': ' {'}, {'char_start': 148, 'char_end': 151, 'chars': '\n\t}'}]}",github.com/radare/radare2/commit/77c47cf873dd55b396da60baa2ca83bbd39e4add,libr/anal/p/anal_sh.c,cwe-125,183 cwe-089,store_metadata," def store_metadata(self, session, key, mType, value): if (self.idNormalizer is not None): id = self.idNormalizer.process_string(session, id) elif type(id) == unicode: id = id.encode('utf-8') else: id = str(id) self._openContainer(session) query = (""UPDATE %s SET %s = %r WHERE identifier = '%s';"" % (self.table, mType, value, id) ) try: self._query(query) except: return None return value"," def store_metadata(self, session, key, mType, value): if (self.idNormalizer is not None): id = self.idNormalizer.process_string(session, id) elif type(id) == unicode: id = id.encode('utf-8') else: id = str(id) self._openContainer(session) query = (""UPDATE %s SET %s = $1 WHERE identifier = $2;"" % (self.table, mType) ) args = (value, id) try: self._query(query, *args) except: return None return value","{'deleted': [{'line_no': 9, 'char_start': 311, 'char_end': 379, 'line': ' query = (""UPDATE %s SET %s = %r WHERE identifier = \'%s\';"" %\n'}, {'line_no': 10, 'char_start': 379, 'char_end': 427, 'line': ' (self.table, mType, value, id)\n'}, {'line_no': 13, 'char_start': 459, 'char_end': 490, 'line': ' self._query(query)\n'}], 'added': [{'line_no': 9, 'char_start': 311, 'char_end': 377, 'line': ' query = (""UPDATE %s SET %s = $1 WHERE identifier = $2;"" %\n'}, {'line_no': 10, 'char_start': 377, 'char_end': 414, 'line': ' (self.table, mType)\n'}, {'line_no': 12, 'char_start': 433, 'char_end': 460, 'line': ' args = (value, id)\n'}, {'line_no': 14, 'char_start': 473, 'char_end': 511, 'line': ' self._query(query, *args)\n'}]}","{'deleted': [{'char_start': 348, 'char_end': 350, 'chars': '%r'}, {'char_start': 370, 'char_end': 374, 'chars': ""'%s'""}, {'char_start': 414, 'char_end': 415, 'chars': ','}, {'char_start': 416, 'char_end': 422, 'chars': 'value,'}, {'char_start': 423, 'char_end': 425, 'chars': 'id'}, {'char_start': 435, 'char_end': 441, 'chars': ' '}], 'added': [{'char_start': 348, 'char_end': 350, 'chars': '$1'}, {'char_start': 370, 'char_end': 372, 'chars': '$2'}, {'char_start': 441, 'char_end': 468, 'chars': 'args = (value, id)\n '}, {'char_start': 502, 'char_end': 509, 'chars': ', *args'}]}",github.com/cheshire3/cheshire3/commit/d350363b4ea10f102c24c8f26d7b76b006323e8e,cheshire3/sql/postgresStore.py,cwe-089,127 cwe-089,delete_crawl,"@app.route('/delete_crawl', methods=['POST']) @is_logged_in def delete_crawl(): # Get Form Fields cid = request.form['cid'] # Create cursor cur = mysql.connection.cursor() # Get user by username result = cur.execute(""DELETE FROM Crawls WHERE cid = %s"" % cid) # Commit to DB mysql.connection.commit() # Close connection cur.close() # FIXME check if successfull first, return message flash('Crawl successfully removed', 'success') return redirect(url_for('dashboard'))","@app.route('/delete_crawl', methods=['POST']) @is_logged_in def delete_crawl(): # Get Form Fields cid = request.form['cid'] # Create cursor cur = mysql.connection.cursor() # Get user by username result = cur.execute(""""""DELETE FROM Crawls WHERE cid = %s"""""" (cid,)) # Commit to DB mysql.connection.commit() # Close connection cur.close() # FIXME check if successfull first, return message flash('Crawl successfully removed', 'success') return redirect(url_for('dashboard'))","{'deleted': [{'line_no': 12, 'char_start': 238, 'char_end': 310, 'line': ' result = cur.execute(""DELETE FROM Crawls WHERE cid = %s"" % cid)\n'}], 'added': [{'line_no': 12, 'char_start': 238, 'char_end': 315, 'line': ' result = cur.execute(""""""DELETE FROM Crawls WHERE cid = %s"""""" (cid,))\n'}]}","{'deleted': [{'char_start': 303, 'char_end': 305, 'chars': '% '}], 'added': [{'char_start': 268, 'char_end': 270, 'chars': '""""'}, {'char_start': 304, 'char_end': 306, 'chars': '""""'}, {'char_start': 307, 'char_end': 308, 'chars': '('}, {'char_start': 311, 'char_end': 313, 'chars': ',)'}]}",github.com/yannvon/table-detection/commit/4bad3673debf0b9491b520f0e22e9186af78c375,bar.py,cwe-089,124 cwe-022,dd_exist,"int dd_exist(const struct dump_dir *dd, const char *path) { char *full_path = concat_path_file(dd->dd_dirname, path); int ret = exist_file_dir(full_path); free(full_path); return ret; }","int dd_exist(const struct dump_dir *dd, const char *path) { if (!str_is_correct_filename(path)) error_msg_and_die(""Cannot test existence. '%s' is not a valid file name"", path); char *full_path = concat_path_file(dd->dd_dirname, path); int ret = exist_file_dir(full_path); free(full_path); return ret; }","{'deleted': [], 'added': [{'line_no': 3, 'char_start': 60, 'char_end': 100, 'line': ' if (!str_is_correct_filename(path))\n'}, {'line_no': 4, 'char_start': 100, 'char_end': 189, 'line': ' error_msg_and_die(""Cannot test existence. \'%s\' is not a valid file name"", path);\n'}, {'line_no': 5, 'char_start': 189, 'char_end': 190, 'line': '\n'}]}","{'deleted': [], 'added': [{'char_start': 64, 'char_end': 194, 'chars': 'if (!str_is_correct_filename(path))\n error_msg_and_die(""Cannot test existence. \'%s\' is not a valid file name"", path);\n\n '}]}",github.com/abrt/libreport/commit/239c4f7d1f47265526b39ad70106767d00805277,src/lib/dump_dir.c,cwe-022,53 cwe-089,_get_degree_2,"def _get_degree_2(user_id, cnx): """"""Get all users of degree 2 follow that are not currently followed. Example: this user (follows) user B (follows) user B AND user (does NOT follow) user B means that user B will be in the list Args: user_id (int): id of user cnx: DB connection Returns: list: list of user_ids """""" sql = 'WITH tmp_suggest (followed_id) AS ' \ '(' \ 'SELECT b.followed_id AS followed_id ' \ 'FROM ' \ 'tbl_follow a INNER JOIN tbl_follow b ' \ 'ON a.followed_id = b.follower_id ' \ 'WHERE a.follower_id = %s ' \ 'AND b.followed_id NOT IN ' \ '(SELECT followed_id FROM tbl_follow WHERE follower_id = %s) ' \ 'AND b.followed_id != %s ' \ ') ' \ 'SELECT followed_id, COUNT(*) AS num_mutual FROM tmp_suggest ' \ 'GROUP BY followed_id ' \ 'ORDER BY num_mutual DESC' % (user_id, user_id, user_id) with cnx.cursor() as cursor: cursor.execute(sql) res = cursor.fetchall() return list(map(lambda x: x[0], res))","def _get_degree_2(user_id, cnx): """"""Get all users of degree 2 follow that are not currently followed. Example: this user (follows) user B (follows) user B AND user (does NOT follow) user B means that user B will be in the list Args: user_id (int): id of user cnx: DB connection Returns: list: list of user_ids """""" sql = 'WITH tmp_suggest (followed_id) AS ' \ '(' \ 'SELECT b.followed_id AS followed_id ' \ 'FROM ' \ 'tbl_follow a INNER JOIN tbl_follow b ' \ 'ON a.followed_id = b.follower_id ' \ 'WHERE a.follower_id = %s ' \ 'AND b.followed_id NOT IN ' \ '(SELECT followed_id FROM tbl_follow WHERE follower_id = %s) ' \ 'AND b.followed_id != %s ' \ ') ' \ 'SELECT followed_id, COUNT(*) AS num_mutual FROM tmp_suggest ' \ 'GROUP BY followed_id ' \ 'ORDER BY num_mutual DESC' with cnx.cursor() as cursor: cursor.execute(sql, (user_id, user_id, user_id)) res = cursor.fetchall() return list(map(lambda x: x[0], res))","{'deleted': [{'line_no': 26, 'char_start': 912, 'char_end': 973, 'line': "" 'ORDER BY num_mutual DESC' % (user_id, user_id, user_id)\n""}, {'line_no': 28, 'char_start': 1006, 'char_end': 1034, 'line': ' cursor.execute(sql)\n'}], 'added': [{'line_no': 26, 'char_start': 912, 'char_end': 943, 'line': "" 'ORDER BY num_mutual DESC'\n""}, {'line_no': 28, 'char_start': 976, 'char_end': 1033, 'line': ' cursor.execute(sql, (user_id, user_id, user_id))\n'}]}","{'deleted': [{'char_start': 942, 'char_end': 972, 'chars': ' % (user_id, user_id, user_id)'}], 'added': [{'char_start': 1002, 'char_end': 1031, 'chars': ', (user_id, user_id, user_id)'}]}",github.com/young-goons/rifflo-server/commit/fb311df76713b638c9486250f9badb288ffb2189,server/ygoons/modules/user/follow_suggest.py,cwe-089,299 cwe-089,getPostsByPostid," def getPostsByPostid(self,postid): sqlText=""select users.name,post.comment from users,post where \ users.userid=post.userid and post.postid=%d""%(postid) result=sql.queryDB(self.conn,sqlText) return result;"," def getPostsByPostid(self,postid): sqlText=""select users.name,post.comment from users,post where \ users.userid=post.userid and post.postid=%s"" params=[postid] result=sql.queryDB(self.conn,sqlText,params) return result;","{'deleted': [{'line_no': 3, 'char_start': 111, 'char_end': 181, 'line': ' users.userid=post.userid and post.postid=%d""%(postid)\n'}, {'line_no': 4, 'char_start': 181, 'char_end': 227, 'line': ' result=sql.queryDB(self.conn,sqlText)\n'}], 'added': [{'line_no': 3, 'char_start': 111, 'char_end': 172, 'line': ' users.userid=post.userid and post.postid=%s""\n'}, {'line_no': 4, 'char_start': 172, 'char_end': 196, 'line': ' params=[postid]\n'}, {'line_no': 5, 'char_start': 196, 'char_end': 249, 'line': ' result=sql.queryDB(self.conn,sqlText,params)\n'}]}","{'deleted': [{'char_start': 169, 'char_end': 170, 'chars': 'd'}, {'char_start': 171, 'char_end': 173, 'chars': '%('}, {'char_start': 179, 'char_end': 180, 'chars': ')'}], 'added': [{'char_start': 169, 'char_end': 170, 'chars': 's'}, {'char_start': 171, 'char_end': 188, 'chars': '\n params=['}, {'char_start': 194, 'char_end': 195, 'chars': ']'}, {'char_start': 240, 'char_end': 247, 'chars': ',params'}]}",github.com/ShaominLi/Twitter_project/commit/5329d91f9e569c95184053c8e7ef596949c33ce9,modules/post.py,cwe-089,59 cwe-787,concat_opt_exact_str,"concat_opt_exact_str(OptStr* to, UChar* s, UChar* end, OnigEncoding enc) { int i, j, len; UChar *p; for (i = to->len, p = s; p < end && i < OPT_EXACT_MAXLEN; ) { len = enclen(enc, p); if (i + len > OPT_EXACT_MAXLEN) break; for (j = 0; j < len && p < end; j++) to->s[i++] = *p++; } to->len = i; if (p >= end) to->reach_end = 1; }","concat_opt_exact_str(OptStr* to, UChar* s, UChar* end, OnigEncoding enc) { int i, j, len; UChar *p; for (i = to->len, p = s; p < end && i < OPT_EXACT_MAXLEN; ) { len = enclen(enc, p); if (i + len >= OPT_EXACT_MAXLEN) break; for (j = 0; j < len && p < end; j++) to->s[i++] = *p++; } to->len = i; if (p >= end) to->reach_end = 1; }","{'deleted': [{'line_no': 8, 'char_start': 195, 'char_end': 238, 'line': ' if (i + len > OPT_EXACT_MAXLEN) break;\n'}], 'added': [{'line_no': 8, 'char_start': 195, 'char_end': 239, 'line': ' if (i + len >= OPT_EXACT_MAXLEN) break;\n'}]}","{'deleted': [], 'added': [{'char_start': 212, 'char_end': 213, 'chars': '='}]}",github.com/kkos/oniguruma/commit/cbe9f8bd9cfc6c3c87a60fbae58fa1a85db59df0,src/regcomp.c,cwe-787,146 cwe-476,ReadDCMImage,"static Image *ReadDCMImage(const ImageInfo *image_info,ExceptionInfo *exception) { char explicit_vr[MagickPathExtent], implicit_vr[MagickPathExtent], magick[MagickPathExtent], photometric[MagickPathExtent]; DCMStreamInfo *stream_info; Image *image; int *bluemap, datum, *greenmap, *graymap, index, *redmap; MagickBooleanType explicit_file, explicit_retry, polarity, sequence, use_explicit; MagickOffsetType offset; Quantum *scale; register ssize_t i, x; register Quantum *q; register unsigned char *p; size_t bits_allocated, bytes_per_pixel, colors, depth, height, length, mask, max_value, number_scenes, quantum, samples_per_pixel, signed_data, significant_bits, status, width, window_width; ssize_t count, rescale_intercept, rescale_slope, scene, window_center, y; unsigned char *data; unsigned short group, element; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),""%s"", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } image->depth=8UL; image->endian=LSBEndian; /* Read DCM preamble. */ stream_info=(DCMStreamInfo *) AcquireMagickMemory(sizeof(*stream_info)); if (stream_info == (DCMStreamInfo *) NULL) ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); (void) ResetMagickMemory(stream_info,0,sizeof(*stream_info)); count=ReadBlob(image,128,(unsigned char *) magick); if (count != 128) ThrowReaderException(CorruptImageError,""ImproperImageHeader""); count=ReadBlob(image,4,(unsigned char *) magick); if ((count != 4) || (LocaleNCompare(magick,""DICM"",4) != 0)) { offset=SeekBlob(image,0L,SEEK_SET); if (offset < 0) ThrowReaderException(CorruptImageError,""ImproperImageHeader""); } /* Read DCM Medical image. */ (void) CopyMagickString(photometric,""MONOCHROME1 "",MagickPathExtent); bits_allocated=8; bytes_per_pixel=1; polarity=MagickFalse; data=(unsigned char *) NULL; depth=8; element=0; explicit_vr[2]='\0'; explicit_file=MagickFalse; colors=0; redmap=(int *) NULL; greenmap=(int *) NULL; bluemap=(int *) NULL; graymap=(int *) NULL; height=0; max_value=255UL; mask=0xffff; number_scenes=1; rescale_intercept=0; rescale_slope=1; samples_per_pixel=1; scale=(Quantum *) NULL; sequence=MagickFalse; signed_data=(~0UL); significant_bits=0; use_explicit=MagickFalse; explicit_retry = MagickFalse; width=0; window_center=0; window_width=0; for (group=0; (group != 0x7FE0) || (element != 0x0010) || (sequence != MagickFalse); ) { /* Read a group. */ image->offset=(ssize_t) TellBlob(image); group=ReadBlobLSBShort(image); element=ReadBlobLSBShort(image); if ((group != 0x0002) && (image->endian == MSBEndian)) { group=(unsigned short) ((group << 8) | ((group >> 8) & 0xFF)); element=(unsigned short) ((element << 8) | ((element >> 8) & 0xFF)); } quantum=0; /* Find corresponding VR for this group and element. */ for (i=0; dicom_info[i].group < 0xffff; i++) if ((group == dicom_info[i].group) && (element == dicom_info[i].element)) break; (void) CopyMagickString(implicit_vr,dicom_info[i].vr,MagickPathExtent); count=ReadBlob(image,2,(unsigned char *) explicit_vr); if (count != 2) ThrowReaderException(CorruptImageError,""ImproperImageHeader""); /* Check for ""explicitness"", but meta-file headers always explicit. */ if ((explicit_file == MagickFalse) && (group != 0x0002)) explicit_file=(isupper((unsigned char) *explicit_vr) != MagickFalse) && (isupper((unsigned char) *(explicit_vr+1)) != MagickFalse) ? MagickTrue : MagickFalse; use_explicit=((group == 0x0002) && (explicit_retry == MagickFalse)) || (explicit_file != MagickFalse) ? MagickTrue : MagickFalse; if ((use_explicit != MagickFalse) && (strncmp(implicit_vr,""xs"",2) == 0)) (void) CopyMagickString(implicit_vr,explicit_vr,MagickPathExtent); if ((use_explicit == MagickFalse) || (strncmp(implicit_vr,""!!"",2) == 0)) { offset=SeekBlob(image,(MagickOffsetType) -2,SEEK_CUR); if (offset < 0) ThrowReaderException(CorruptImageError,""ImproperImageHeader""); quantum=4; } else { /* Assume explicit type. */ quantum=2; if ((strncmp(explicit_vr,""OB"",2) == 0) || (strncmp(explicit_vr,""UN"",2) == 0) || (strncmp(explicit_vr,""OW"",2) == 0) || (strncmp(explicit_vr,""SQ"",2) == 0)) { (void) ReadBlobLSBShort(image); quantum=4; } } datum=0; if (quantum == 4) { if (group == 0x0002) datum=ReadBlobLSBSignedLong(image); else datum=ReadBlobSignedLong(image); } else if (quantum == 2) { if (group == 0x0002) datum=ReadBlobLSBSignedShort(image); else datum=ReadBlobSignedShort(image); } quantum=0; length=1; if (datum != 0) { if ((strncmp(implicit_vr,""SS"",2) == 0) || (strncmp(implicit_vr,""US"",2) == 0)) quantum=2; else if ((strncmp(implicit_vr,""UL"",2) == 0) || (strncmp(implicit_vr,""SL"",2) == 0) || (strncmp(implicit_vr,""FL"",2) == 0)) quantum=4; else if (strncmp(implicit_vr,""FD"",2) != 0) quantum=1; else quantum=8; if (datum != ~0) length=(size_t) datum/quantum; else { /* Sequence and item of undefined length. */ quantum=0; length=0; } } if (image_info->verbose != MagickFalse) { /* Display Dicom info. */ if (use_explicit == MagickFalse) explicit_vr[0]='\0'; for (i=0; dicom_info[i].description != (char *) NULL; i++) if ((group == dicom_info[i].group) && (element == dicom_info[i].element)) break; (void) FormatLocaleFile(stdout,""0x%04lX %4ld %s-%s (0x%04lx,0x%04lx)"", (unsigned long) image->offset,(long) length,implicit_vr,explicit_vr, (unsigned long) group,(unsigned long) element); if (dicom_info[i].description != (char *) NULL) (void) FormatLocaleFile(stdout,"" %s"",dicom_info[i].description); (void) FormatLocaleFile(stdout,"": ""); } if ((sequence == MagickFalse) && (group == 0x7FE0) && (element == 0x0010)) { if (image_info->verbose != MagickFalse) (void) FormatLocaleFile(stdout,""\n""); break; } /* Allocate space and read an array. */ data=(unsigned char *) NULL; if ((length == 1) && (quantum == 1)) datum=ReadBlobByte(image); else if ((length == 1) && (quantum == 2)) { if (group == 0x0002) datum=ReadBlobLSBSignedShort(image); else datum=ReadBlobSignedShort(image); } else if ((length == 1) && (quantum == 4)) { if (group == 0x0002) datum=ReadBlobLSBSignedLong(image); else datum=ReadBlobSignedLong(image); } else if ((quantum != 0) && (length != 0)) { if (~length >= 1) data=(unsigned char *) AcquireQuantumMemory(length+1,quantum* sizeof(*data)); if (data == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError, ""MemoryAllocationFailed""); count=ReadBlob(image,(size_t) quantum*length,data); if (count != (ssize_t) (quantum*length)) { if (image_info->verbose != MagickFalse) (void) FormatLocaleFile(stdout,""count=%d quantum=%d "" ""length=%d group=%d\n"",(int) count,(int) quantum,(int) length,(int) group); ThrowReaderException(CorruptImageError, ""InsufficientImageDataInFile""); } data[length*quantum]='\0'; } else if ((unsigned int) datum == 0xFFFFFFFFU) { sequence=MagickTrue; continue; } if ((unsigned int) ((group << 16) | element) == 0xFFFEE0DD) { if (data != (unsigned char *) NULL) data=(unsigned char *) RelinquishMagickMemory(data); sequence=MagickFalse; continue; } if (sequence != MagickFalse) { if (data != (unsigned char *) NULL) data=(unsigned char *) RelinquishMagickMemory(data); continue; } switch (group) { case 0x0002: { switch (element) { case 0x0010: { char transfer_syntax[MagickPathExtent]; /* Transfer Syntax. */ if ((datum == 0) && (explicit_retry == MagickFalse)) { explicit_retry=MagickTrue; (void) SeekBlob(image,(MagickOffsetType) 0,SEEK_SET); group=0; element=0; if (image_info->verbose != MagickFalse) (void) FormatLocaleFile(stdout, ""Corrupted image - trying explicit format\n""); break; } *transfer_syntax='\0'; if (data != (unsigned char *) NULL) (void) CopyMagickString(transfer_syntax,(char *) data, MagickPathExtent); if (image_info->verbose != MagickFalse) (void) FormatLocaleFile(stdout,""transfer_syntax=%s\n"", (const char *) transfer_syntax); if (strncmp(transfer_syntax,""1.2.840.10008.1.2"",17) == 0) { int count, subtype, type; type=1; subtype=0; if (strlen(transfer_syntax) > 17) { count=sscanf(transfer_syntax+17,"".%d.%d"",&type,&subtype); if (count < 1) ThrowReaderException(CorruptImageError, ""ImproperImageHeader""); } switch (type) { case 1: { image->endian=LSBEndian; break; } case 2: { image->endian=MSBEndian; break; } case 4: { if ((subtype >= 80) && (subtype <= 81)) image->compression=JPEGCompression; else if ((subtype >= 90) && (subtype <= 93)) image->compression=JPEG2000Compression; else image->compression=JPEGCompression; break; } case 5: { image->compression=RLECompression; break; } } } break; } default: break; } break; } case 0x0028: { switch (element) { case 0x0002: { /* Samples per pixel. */ samples_per_pixel=(size_t) datum; break; } case 0x0004: { /* Photometric interpretation. */ for (i=0; i < (ssize_t) MagickMin(length,MagickPathExtent-1); i++) photometric[i]=(char) data[i]; photometric[i]='\0'; polarity=LocaleCompare(photometric,""MONOCHROME1 "") == 0 ? MagickTrue : MagickFalse; break; } case 0x0006: { /* Planar configuration. */ if (datum == 1) image->interlace=PlaneInterlace; break; } case 0x0008: { /* Number of frames. */ number_scenes=StringToUnsignedLong((char *) data); break; } case 0x0010: { /* Image rows. */ height=(size_t) datum; break; } case 0x0011: { /* Image columns. */ width=(size_t) datum; break; } case 0x0100: { /* Bits allocated. */ bits_allocated=(size_t) datum; bytes_per_pixel=1; if (datum > 8) bytes_per_pixel=2; depth=bits_allocated; if (depth > 32) ThrowReaderException(CorruptImageError,""ImproperImageHeader""); max_value=(1UL << bits_allocated)-1; break; } case 0x0101: { /* Bits stored. */ significant_bits=(size_t) datum; bytes_per_pixel=1; if (significant_bits > 8) bytes_per_pixel=2; depth=significant_bits; if (depth > 32) ThrowReaderException(CorruptImageError,""ImproperImageHeader""); max_value=(1UL << significant_bits)-1; mask=(size_t) GetQuantumRange(significant_bits); break; } case 0x0102: { /* High bit. */ break; } case 0x0103: { /* Pixel representation. */ signed_data=(size_t) datum; break; } case 0x1050: { /* Visible pixel range: center. */ if (data != (unsigned char *) NULL) window_center=(ssize_t) StringToLong((char *) data); break; } case 0x1051: { /* Visible pixel range: width. */ if (data != (unsigned char *) NULL) window_width=StringToUnsignedLong((char *) data); break; } case 0x1052: { /* Rescale intercept */ if (data != (unsigned char *) NULL) rescale_intercept=(ssize_t) StringToLong((char *) data); break; } case 0x1053: { /* Rescale slope */ if (data != (unsigned char *) NULL) rescale_slope=(ssize_t) StringToLong((char *) data); break; } case 0x1200: case 0x3006: { /* Populate graymap. */ if (data == (unsigned char *) NULL) break; colors=(size_t) (length/bytes_per_pixel); datum=(int) colors; graymap=(int *) AcquireQuantumMemory((size_t) colors, sizeof(*graymap)); if (graymap == (int *) NULL) ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); for (i=0; i < (ssize_t) colors; i++) if (bytes_per_pixel == 1) graymap[i]=(int) data[i]; else graymap[i]=(int) ((short *) data)[i]; break; } case 0x1201: { unsigned short index; /* Populate redmap. */ if (data == (unsigned char *) NULL) break; colors=(size_t) (length/2); datum=(int) colors; redmap=(int *) AcquireQuantumMemory((size_t) colors, sizeof(*redmap)); if (redmap == (int *) NULL) ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); p=data; for (i=0; i < (ssize_t) colors; i++) { if (image->endian == MSBEndian) index=(unsigned short) ((*p << 8) | *(p+1)); else index=(unsigned short) (*p | (*(p+1) << 8)); redmap[i]=(int) index; p+=2; } break; } case 0x1202: { unsigned short index; /* Populate greenmap. */ if (data == (unsigned char *) NULL) break; colors=(size_t) (length/2); datum=(int) colors; greenmap=(int *) AcquireQuantumMemory((size_t) colors, sizeof(*greenmap)); if (greenmap == (int *) NULL) ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); p=data; for (i=0; i < (ssize_t) colors; i++) { if (image->endian == MSBEndian) index=(unsigned short) ((*p << 8) | *(p+1)); else index=(unsigned short) (*p | (*(p+1) << 8)); greenmap[i]=(int) index; p+=2; } break; } case 0x1203: { unsigned short index; /* Populate bluemap. */ if (data == (unsigned char *) NULL) break; colors=(size_t) (length/2); datum=(int) colors; bluemap=(int *) AcquireQuantumMemory((size_t) colors, sizeof(*bluemap)); if (bluemap == (int *) NULL) ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); p=data; for (i=0; i < (ssize_t) colors; i++) { if (image->endian == MSBEndian) index=(unsigned short) ((*p << 8) | *(p+1)); else index=(unsigned short) (*p | (*(p+1) << 8)); bluemap[i]=(int) index; p+=2; } break; } default: break; } break; } case 0x2050: { switch (element) { case 0x0020: { if ((data != (unsigned char *) NULL) && (strncmp((char *) data,""INVERSE"",7) == 0)) polarity=MagickTrue; break; } default: break; } break; } default: break; } if (data != (unsigned char *) NULL) { char *attribute; for (i=0; dicom_info[i].description != (char *) NULL; i++) if ((group == dicom_info[i].group) && (element == dicom_info[i].element)) break; if (dicom_info[i].description != (char *) NULL) { attribute=AcquireString(""dcm:""); (void) ConcatenateString(&attribute,dicom_info[i].description); for (i=0; i < (ssize_t) MagickMax(length,4); i++) if (isprint((int) data[i]) == MagickFalse) break; if ((i == (ssize_t) length) || (length > 4)) { (void) SubstituteString(&attribute,"" "",""""); (void) SetImageProperty(image,attribute,(char *) data,exception); } attribute=DestroyString(attribute); } } if (image_info->verbose != MagickFalse) { if (data == (unsigned char *) NULL) (void) FormatLocaleFile(stdout,""%d\n"",datum); else { /* Display group data. */ for (i=0; i < (ssize_t) MagickMax(length,4); i++) if (isprint((int) data[i]) == MagickFalse) break; if ((i != (ssize_t) length) && (length <= 4)) { ssize_t j; datum=0; for (j=(ssize_t) length-1; j >= 0; j--) datum=(256*datum+data[j]); (void) FormatLocaleFile(stdout,""%d"",datum); } else for (i=0; i < (ssize_t) length; i++) if (isprint((int) data[i]) != MagickFalse) (void) FormatLocaleFile(stdout,""%c"",data[i]); else (void) FormatLocaleFile(stdout,""%c"",'.'); (void) FormatLocaleFile(stdout,""\n""); } } if (data != (unsigned char *) NULL) data=(unsigned char *) RelinquishMagickMemory(data); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,""UnexpectedEndOfFile"", image->filename); break; } } if ((width == 0) || (height == 0)) ThrowReaderException(CorruptImageError,""ImproperImageHeader""); image->columns=(size_t) width; image->rows=(size_t) height; if (signed_data == 0xffff) signed_data=(size_t) (significant_bits == 16 ? 1 : 0); if ((image->compression == JPEGCompression) || (image->compression == JPEG2000Compression)) { Image *images; ImageInfo *read_info; int c; size_t length; unsigned int tag; /* Read offset table. */ for (i=0; i < (ssize_t) stream_info->remaining; i++) (void) ReadBlobByte(image); tag=(ReadBlobLSBShort(image) << 16) | ReadBlobLSBShort(image); (void) tag; length=(size_t) ReadBlobLSBLong(image); stream_info->offset_count=length >> 2; if (stream_info->offset_count != 0) { MagickOffsetType offset; stream_info->offsets=(ssize_t *) AcquireQuantumMemory( stream_info->offset_count,sizeof(*stream_info->offsets)); if (stream_info->offsets == (ssize_t *) NULL) ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); for (i=0; i < (ssize_t) stream_info->offset_count; i++) stream_info->offsets[i]=(ssize_t) ReadBlobLSBSignedLong(image); offset=TellBlob(image); for (i=0; i < (ssize_t) stream_info->offset_count; i++) stream_info->offsets[i]+=offset; } /* Handle non-native image formats. */ read_info=CloneImageInfo(image_info); SetImageInfoBlob(read_info,(void *) NULL,0); images=NewImageList(); for (scene=0; scene < (ssize_t) number_scenes; scene++) { char filename[MagickPathExtent]; const char *property; FILE *file; Image *jpeg_image; int unique_file; unsigned int tag; tag=(ReadBlobLSBShort(image) << 16) | ReadBlobLSBShort(image); length=(size_t) ReadBlobLSBLong(image); if (tag == 0xFFFEE0DD) break; /* sequence delimiter tag */ if (tag != 0xFFFEE000) ThrowReaderException(CorruptImageError,""ImproperImageHeader""); file=(FILE *) NULL; unique_file=AcquireUniqueFileResource(filename); if (unique_file != -1) file=fdopen(unique_file,""wb""); if (file == (FILE *) NULL) { (void) RelinquishUniqueFileResource(filename); ThrowFileException(exception,FileOpenError, ""UnableToCreateTemporaryFile"",filename); break; } for ( ; length != 0; length--) { c=ReadBlobByte(image); if (c == EOF) { ThrowFileException(exception,CorruptImageError, ""UnexpectedEndOfFile"",image->filename); break; } (void) fputc(c,file); } (void) fclose(file); (void) FormatLocaleString(read_info->filename,MagickPathExtent, ""jpeg:%s"",filename); if (image->compression == JPEG2000Compression) (void) FormatLocaleString(read_info->filename,MagickPathExtent, ""j2k:%s"",filename); jpeg_image=ReadImage(read_info,exception); if (jpeg_image != (Image *) NULL) { ResetImagePropertyIterator(image); property=GetNextImageProperty(image); while (property != (const char *) NULL) { (void) SetImageProperty(jpeg_image,property, GetImageProperty(image,property,exception),exception); property=GetNextImageProperty(image); } AppendImageToList(&images,jpeg_image); } (void) RelinquishUniqueFileResource(filename); } read_info=DestroyImageInfo(read_info); image=DestroyImage(image); return(GetFirstImageInList(images)); } if (depth != (1UL*MAGICKCORE_QUANTUM_DEPTH)) { QuantumAny range; size_t length; /* Compute pixel scaling table. */ length=(size_t) (GetQuantumRange(depth)+1); scale=(Quantum *) AcquireQuantumMemory(length,sizeof(*scale)); if (scale == (Quantum *) NULL) ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); range=GetQuantumRange(depth); for (i=0; i < (ssize_t) (GetQuantumRange(depth)+1); i++) scale[i]=ScaleAnyToQuantum((size_t) i,range); } if (image->compression == RLECompression) { size_t length; unsigned int tag; /* Read RLE offset table. */ for (i=0; i < (ssize_t) stream_info->remaining; i++) (void) ReadBlobByte(image); tag=(ReadBlobLSBShort(image) << 16) | ReadBlobLSBShort(image); (void) tag; length=(size_t) ReadBlobLSBLong(image); stream_info->offset_count=length >> 2; if (stream_info->offset_count != 0) { MagickOffsetType offset; stream_info->offsets=(ssize_t *) AcquireQuantumMemory( stream_info->offset_count,sizeof(*stream_info->offsets)); if (stream_info->offsets == (ssize_t *) NULL) ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); for (i=0; i < (ssize_t) stream_info->offset_count; i++) stream_info->offsets[i]=(ssize_t) ReadBlobLSBSignedLong(image); offset=TellBlob(image); for (i=0; i < (ssize_t) stream_info->offset_count; i++) stream_info->offsets[i]+=offset; } } for (scene=0; scene < (ssize_t) number_scenes; scene++) { if (image_info->ping != MagickFalse) break; image->columns=(size_t) width; image->rows=(size_t) height; image->depth=depth; status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) break; image->colorspace=RGBColorspace; if ((image->colormap == (PixelInfo *) NULL) && (samples_per_pixel == 1)) { size_t one; one=1; if (colors == 0) colors=one << depth; if (AcquireImageColormap(image,one << depth,exception) == MagickFalse) ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); if (redmap != (int *) NULL) for (i=0; i < (ssize_t) colors; i++) { index=redmap[i]; if ((scale != (Quantum *) NULL) && (index <= (int) max_value)) index=(int) scale[index]; image->colormap[i].red=(MagickRealType) index; } if (greenmap != (int *) NULL) for (i=0; i < (ssize_t) colors; i++) { index=greenmap[i]; if ((scale != (Quantum *) NULL) && (index <= (int) max_value)) index=(int) scale[index]; image->colormap[i].green=(MagickRealType) index; } if (bluemap != (int *) NULL) for (i=0; i < (ssize_t) colors; i++) { index=bluemap[i]; if ((scale != (Quantum *) NULL) && (index <= (int) max_value)) index=(int) scale[index]; image->colormap[i].blue=(MagickRealType) index; } if (graymap != (int *) NULL) for (i=0; i < (ssize_t) colors; i++) { index=graymap[i]; if ((scale != (Quantum *) NULL) && (index <= (int) max_value)) index=(int) scale[index]; image->colormap[i].red=(MagickRealType) index; image->colormap[i].green=(MagickRealType) index; image->colormap[i].blue=(MagickRealType) index; } } if (image->compression == RLECompression) { unsigned int tag; /* Read RLE segment table. */ for (i=0; i < (ssize_t) stream_info->remaining; i++) (void) ReadBlobByte(image); tag=(ReadBlobLSBShort(image) << 16) | ReadBlobLSBShort(image); stream_info->remaining=(size_t) ReadBlobLSBLong(image); if ((tag != 0xFFFEE000) || (stream_info->remaining <= 64) || (EOFBlob(image) != MagickFalse)) ThrowReaderException(CorruptImageError,""ImproperImageHeader""); stream_info->count=0; stream_info->segment_count=ReadBlobLSBLong(image); if (stream_info->segment_count > 1) { bytes_per_pixel=1; depth=8; } for (i=0; i < 15; i++) stream_info->segments[i]=(ssize_t) ReadBlobLSBSignedLong(image); stream_info->remaining-=64; } if ((samples_per_pixel > 1) && (image->interlace == PlaneInterlace)) { /* Convert Planar RGB DCM Medical image to pixel packets. */ for (i=0; i < (ssize_t) samples_per_pixel; i++) { for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { switch ((int) i) { case 0: { SetPixelRed(image,ScaleCharToQuantum((unsigned char) ReadDCMByte(stream_info,image)),q); break; } case 1: { SetPixelGreen(image,ScaleCharToQuantum((unsigned char) ReadDCMByte(stream_info,image)),q); break; } case 2: { SetPixelBlue(image,ScaleCharToQuantum((unsigned char) ReadDCMByte(stream_info,image)),q); break; } case 3: { SetPixelAlpha(image,ScaleCharToQuantum((unsigned char) ReadDCMByte(stream_info,image)),q); break; } default: break; } q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } } } else { const char *option; int byte; PixelPacket pixel; /* Convert DCM Medical image to pixel packets. */ byte=0; i=0; if ((window_center != 0) && (window_width == 0)) window_width=(size_t) window_center; option=GetImageOption(image_info,""dcm:display-range""); if (option != (const char *) NULL) { if (LocaleCompare(option,""reset"") == 0) window_width=0; } (void) ResetMagickMemory(&pixel,0,sizeof(pixel)); for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (samples_per_pixel == 1) { int pixel_value; if (bytes_per_pixel == 1) pixel_value=polarity != MagickFalse ? ((int) max_value-ReadDCMByte(stream_info,image)) : ReadDCMByte(stream_info,image); else if ((bits_allocated != 12) || (significant_bits != 12)) { if (signed_data) pixel_value=ReadDCMSignedShort(stream_info,image); else pixel_value=ReadDCMShort(stream_info,image); if (polarity != MagickFalse) pixel_value=(int)max_value-pixel_value; } else { if ((i & 0x01) != 0) pixel_value=(ReadDCMByte(stream_info,image) << 8) | byte; else { pixel_value=ReadDCMSignedShort(stream_info,image); byte=(int) (pixel_value & 0x0f); pixel_value>>=4; } i++; } index=(pixel_value*rescale_slope)+rescale_intercept; if (window_width == 0) { if (signed_data == 1) index-=32767; } else { ssize_t window_max, window_min; window_min=(ssize_t) ceil((double) window_center- (window_width-1.0)/2.0-0.5); window_max=(ssize_t) floor((double) window_center+ (window_width-1.0)/2.0+0.5); if ((ssize_t)index <= window_min) index=0; else if ((ssize_t)index > window_max) index=(int) max_value; else index=(int) (max_value*(((index-window_center- 0.5)/(window_width-1))+0.5)); } index&=mask; index=(int) ConstrainColormapIndex(image,(size_t) index, exception); SetPixelIndex(image,(Quantum) index,q); pixel.red=(unsigned int) image->colormap[index].red; pixel.green=(unsigned int) image->colormap[index].green; pixel.blue=(unsigned int) image->colormap[index].blue; } else { if (bytes_per_pixel == 1) { pixel.red=(unsigned int) ReadDCMByte(stream_info,image); pixel.green=(unsigned int) ReadDCMByte(stream_info,image); pixel.blue=(unsigned int) ReadDCMByte(stream_info,image); } else { pixel.red=ReadDCMShort(stream_info,image); pixel.green=ReadDCMShort(stream_info,image); pixel.blue=ReadDCMShort(stream_info,image); } pixel.red&=mask; pixel.green&=mask; pixel.blue&=mask; if (scale != (Quantum *) NULL) { pixel.red=scale[pixel.red]; pixel.green=scale[pixel.green]; pixel.blue=scale[pixel.blue]; } } SetPixelRed(image,(Quantum) pixel.red,q); SetPixelGreen(image,(Quantum) pixel.green,q); SetPixelBlue(image,(Quantum) pixel.blue,q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } if (stream_info->segment_count > 1) for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (samples_per_pixel == 1) { int pixel_value; if (bytes_per_pixel == 1) pixel_value=polarity != MagickFalse ? ((int) max_value-ReadDCMByte(stream_info,image)) : ReadDCMByte(stream_info,image); else if ((bits_allocated != 12) || (significant_bits != 12)) { pixel_value=(int) (polarity != MagickFalse ? (max_value-ReadDCMShort(stream_info,image)) : ReadDCMShort(stream_info,image)); if (signed_data == 1) pixel_value=((signed short) pixel_value); } else { if ((i & 0x01) != 0) pixel_value=(ReadDCMByte(stream_info,image) << 8) | byte; else { pixel_value=ReadDCMShort(stream_info,image); byte=(int) (pixel_value & 0x0f); pixel_value>>=4; } i++; } index=(pixel_value*rescale_slope)+rescale_intercept; if (window_width == 0) { if (signed_data == 1) index-=32767; } else { ssize_t window_max, window_min; window_min=(ssize_t) ceil((double) window_center- (window_width-1.0)/2.0-0.5); window_max=(ssize_t) floor((double) window_center+ (window_width-1.0)/2.0+0.5); if ((ssize_t)index <= window_min) index=0; else if ((ssize_t)index > window_max) index=(int) max_value; else index=(int) (max_value*(((index-window_center- 0.5)/(window_width-1))+0.5)); } index&=mask; index=(int) ConstrainColormapIndex(image,(size_t) index, exception); SetPixelIndex(image,(Quantum) (((size_t) GetPixelIndex(image,q)) | (((size_t) index) << 8)),q); pixel.red=(unsigned int) image->colormap[index].red; pixel.green=(unsigned int) image->colormap[index].green; pixel.blue=(unsigned int) image->colormap[index].blue; } else { if (bytes_per_pixel == 1) { pixel.red=(unsigned int) ReadDCMByte(stream_info,image); pixel.green=(unsigned int) ReadDCMByte(stream_info,image); pixel.blue=(unsigned int) ReadDCMByte(stream_info,image); } else { pixel.red=ReadDCMShort(stream_info,image); pixel.green=ReadDCMShort(stream_info,image); pixel.blue=ReadDCMShort(stream_info,image); } pixel.red&=mask; pixel.green&=mask; pixel.blue&=mask; if (scale != (Quantum *) NULL) { pixel.red=scale[pixel.red]; pixel.green=scale[pixel.green]; pixel.blue=scale[pixel.blue]; } } SetPixelRed(image,(Quantum) (((size_t) GetPixelRed(image,q)) | (((size_t) pixel.red) << 8)),q); SetPixelGreen(image,(Quantum) (((size_t) GetPixelGreen(image,q)) | (((size_t) pixel.green) << 8)),q); SetPixelBlue(image,(Quantum) (((size_t) GetPixelBlue(image,q)) | (((size_t) pixel.blue) << 8)),q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } } if (SetImageGray(image,exception) != MagickFalse) (void) SetImageColorspace(image,GRAYColorspace,exception); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,""UnexpectedEndOfFile"", image->filename); break; } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; if (scene < (ssize_t) (number_scenes-1)) { /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } /* Free resources. */ if (stream_info->offsets != (ssize_t *) NULL) stream_info->offsets=(ssize_t *) RelinquishMagickMemory(stream_info->offsets); stream_info=(DCMStreamInfo *) RelinquishMagickMemory(stream_info); if (scale != (Quantum *) NULL) scale=(Quantum *) RelinquishMagickMemory(scale); if (graymap != (int *) NULL) graymap=(int *) RelinquishMagickMemory(graymap); if (bluemap != (int *) NULL) bluemap=(int *) RelinquishMagickMemory(bluemap); if (greenmap != (int *) NULL) greenmap=(int *) RelinquishMagickMemory(greenmap); if (redmap != (int *) NULL) redmap=(int *) RelinquishMagickMemory(redmap); (void) CloseBlob(image); return(GetFirstImageInList(image)); }","static Image *ReadDCMImage(const ImageInfo *image_info,ExceptionInfo *exception) { char explicit_vr[MagickPathExtent], implicit_vr[MagickPathExtent], magick[MagickPathExtent], photometric[MagickPathExtent]; DCMStreamInfo *stream_info; Image *image; int *bluemap, datum, *greenmap, *graymap, index, *redmap; MagickBooleanType explicit_file, explicit_retry, polarity, sequence, use_explicit; MagickOffsetType offset; Quantum *scale; register ssize_t i, x; register Quantum *q; register unsigned char *p; size_t bits_allocated, bytes_per_pixel, colors, depth, height, length, mask, max_value, number_scenes, quantum, samples_per_pixel, signed_data, significant_bits, status, width, window_width; ssize_t count, rescale_intercept, rescale_slope, scene, window_center, y; unsigned char *data; unsigned short group, element; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),""%s"", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } image->depth=8UL; image->endian=LSBEndian; /* Read DCM preamble. */ stream_info=(DCMStreamInfo *) AcquireMagickMemory(sizeof(*stream_info)); if (stream_info == (DCMStreamInfo *) NULL) ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); (void) ResetMagickMemory(stream_info,0,sizeof(*stream_info)); count=ReadBlob(image,128,(unsigned char *) magick); if (count != 128) ThrowReaderException(CorruptImageError,""ImproperImageHeader""); count=ReadBlob(image,4,(unsigned char *) magick); if ((count != 4) || (LocaleNCompare(magick,""DICM"",4) != 0)) { offset=SeekBlob(image,0L,SEEK_SET); if (offset < 0) ThrowReaderException(CorruptImageError,""ImproperImageHeader""); } /* Read DCM Medical image. */ (void) CopyMagickString(photometric,""MONOCHROME1 "",MagickPathExtent); bits_allocated=8; bytes_per_pixel=1; polarity=MagickFalse; data=(unsigned char *) NULL; depth=8; element=0; explicit_vr[2]='\0'; explicit_file=MagickFalse; colors=0; redmap=(int *) NULL; greenmap=(int *) NULL; bluemap=(int *) NULL; graymap=(int *) NULL; height=0; max_value=255UL; mask=0xffff; number_scenes=1; rescale_intercept=0; rescale_slope=1; samples_per_pixel=1; scale=(Quantum *) NULL; sequence=MagickFalse; signed_data=(~0UL); significant_bits=0; use_explicit=MagickFalse; explicit_retry = MagickFalse; width=0; window_center=0; window_width=0; for (group=0; (group != 0x7FE0) || (element != 0x0010) || (sequence != MagickFalse); ) { /* Read a group. */ image->offset=(ssize_t) TellBlob(image); group=ReadBlobLSBShort(image); element=ReadBlobLSBShort(image); if ((group != 0x0002) && (image->endian == MSBEndian)) { group=(unsigned short) ((group << 8) | ((group >> 8) & 0xFF)); element=(unsigned short) ((element << 8) | ((element >> 8) & 0xFF)); } quantum=0; /* Find corresponding VR for this group and element. */ for (i=0; dicom_info[i].group < 0xffff; i++) if ((group == dicom_info[i].group) && (element == dicom_info[i].element)) break; (void) CopyMagickString(implicit_vr,dicom_info[i].vr,MagickPathExtent); count=ReadBlob(image,2,(unsigned char *) explicit_vr); if (count != 2) ThrowReaderException(CorruptImageError,""ImproperImageHeader""); /* Check for ""explicitness"", but meta-file headers always explicit. */ if ((explicit_file == MagickFalse) && (group != 0x0002)) explicit_file=(isupper((unsigned char) *explicit_vr) != MagickFalse) && (isupper((unsigned char) *(explicit_vr+1)) != MagickFalse) ? MagickTrue : MagickFalse; use_explicit=((group == 0x0002) && (explicit_retry == MagickFalse)) || (explicit_file != MagickFalse) ? MagickTrue : MagickFalse; if ((use_explicit != MagickFalse) && (strncmp(implicit_vr,""xs"",2) == 0)) (void) CopyMagickString(implicit_vr,explicit_vr,MagickPathExtent); if ((use_explicit == MagickFalse) || (strncmp(implicit_vr,""!!"",2) == 0)) { offset=SeekBlob(image,(MagickOffsetType) -2,SEEK_CUR); if (offset < 0) ThrowReaderException(CorruptImageError,""ImproperImageHeader""); quantum=4; } else { /* Assume explicit type. */ quantum=2; if ((strncmp(explicit_vr,""OB"",2) == 0) || (strncmp(explicit_vr,""UN"",2) == 0) || (strncmp(explicit_vr,""OW"",2) == 0) || (strncmp(explicit_vr,""SQ"",2) == 0)) { (void) ReadBlobLSBShort(image); quantum=4; } } datum=0; if (quantum == 4) { if (group == 0x0002) datum=ReadBlobLSBSignedLong(image); else datum=ReadBlobSignedLong(image); } else if (quantum == 2) { if (group == 0x0002) datum=ReadBlobLSBSignedShort(image); else datum=ReadBlobSignedShort(image); } quantum=0; length=1; if (datum != 0) { if ((strncmp(implicit_vr,""SS"",2) == 0) || (strncmp(implicit_vr,""US"",2) == 0)) quantum=2; else if ((strncmp(implicit_vr,""UL"",2) == 0) || (strncmp(implicit_vr,""SL"",2) == 0) || (strncmp(implicit_vr,""FL"",2) == 0)) quantum=4; else if (strncmp(implicit_vr,""FD"",2) != 0) quantum=1; else quantum=8; if (datum != ~0) length=(size_t) datum/quantum; else { /* Sequence and item of undefined length. */ quantum=0; length=0; } } if (image_info->verbose != MagickFalse) { /* Display Dicom info. */ if (use_explicit == MagickFalse) explicit_vr[0]='\0'; for (i=0; dicom_info[i].description != (char *) NULL; i++) if ((group == dicom_info[i].group) && (element == dicom_info[i].element)) break; (void) FormatLocaleFile(stdout,""0x%04lX %4ld %s-%s (0x%04lx,0x%04lx)"", (unsigned long) image->offset,(long) length,implicit_vr,explicit_vr, (unsigned long) group,(unsigned long) element); if (dicom_info[i].description != (char *) NULL) (void) FormatLocaleFile(stdout,"" %s"",dicom_info[i].description); (void) FormatLocaleFile(stdout,"": ""); } if ((sequence == MagickFalse) && (group == 0x7FE0) && (element == 0x0010)) { if (image_info->verbose != MagickFalse) (void) FormatLocaleFile(stdout,""\n""); break; } /* Allocate space and read an array. */ data=(unsigned char *) NULL; if ((length == 1) && (quantum == 1)) datum=ReadBlobByte(image); else if ((length == 1) && (quantum == 2)) { if (group == 0x0002) datum=ReadBlobLSBSignedShort(image); else datum=ReadBlobSignedShort(image); } else if ((length == 1) && (quantum == 4)) { if (group == 0x0002) datum=ReadBlobLSBSignedLong(image); else datum=ReadBlobSignedLong(image); } else if ((quantum != 0) && (length != 0)) { if (~length >= 1) data=(unsigned char *) AcquireQuantumMemory(length+1,quantum* sizeof(*data)); if (data == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError, ""MemoryAllocationFailed""); count=ReadBlob(image,(size_t) quantum*length,data); if (count != (ssize_t) (quantum*length)) { if (image_info->verbose != MagickFalse) (void) FormatLocaleFile(stdout,""count=%d quantum=%d "" ""length=%d group=%d\n"",(int) count,(int) quantum,(int) length,(int) group); ThrowReaderException(CorruptImageError, ""InsufficientImageDataInFile""); } data[length*quantum]='\0'; } else if ((unsigned int) datum == 0xFFFFFFFFU) { sequence=MagickTrue; continue; } if ((unsigned int) ((group << 16) | element) == 0xFFFEE0DD) { if (data != (unsigned char *) NULL) data=(unsigned char *) RelinquishMagickMemory(data); sequence=MagickFalse; continue; } if (sequence != MagickFalse) { if (data != (unsigned char *) NULL) data=(unsigned char *) RelinquishMagickMemory(data); continue; } switch (group) { case 0x0002: { switch (element) { case 0x0010: { char transfer_syntax[MagickPathExtent]; /* Transfer Syntax. */ if ((datum == 0) && (explicit_retry == MagickFalse)) { explicit_retry=MagickTrue; (void) SeekBlob(image,(MagickOffsetType) 0,SEEK_SET); group=0; element=0; if (image_info->verbose != MagickFalse) (void) FormatLocaleFile(stdout, ""Corrupted image - trying explicit format\n""); break; } *transfer_syntax='\0'; if (data != (unsigned char *) NULL) (void) CopyMagickString(transfer_syntax,(char *) data, MagickPathExtent); if (image_info->verbose != MagickFalse) (void) FormatLocaleFile(stdout,""transfer_syntax=%s\n"", (const char *) transfer_syntax); if (strncmp(transfer_syntax,""1.2.840.10008.1.2"",17) == 0) { int count, subtype, type; type=1; subtype=0; if (strlen(transfer_syntax) > 17) { count=sscanf(transfer_syntax+17,"".%d.%d"",&type,&subtype); if (count < 1) ThrowReaderException(CorruptImageError, ""ImproperImageHeader""); } switch (type) { case 1: { image->endian=LSBEndian; break; } case 2: { image->endian=MSBEndian; break; } case 4: { if ((subtype >= 80) && (subtype <= 81)) image->compression=JPEGCompression; else if ((subtype >= 90) && (subtype <= 93)) image->compression=JPEG2000Compression; else image->compression=JPEGCompression; break; } case 5: { image->compression=RLECompression; break; } } } break; } default: break; } break; } case 0x0028: { switch (element) { case 0x0002: { /* Samples per pixel. */ samples_per_pixel=(size_t) datum; break; } case 0x0004: { /* Photometric interpretation. */ if (data == (unsigned char *) NULL) break; for (i=0; i < (ssize_t) MagickMin(length,MagickPathExtent-1); i++) photometric[i]=(char) data[i]; photometric[i]='\0'; polarity=LocaleCompare(photometric,""MONOCHROME1 "") == 0 ? MagickTrue : MagickFalse; break; } case 0x0006: { /* Planar configuration. */ if (datum == 1) image->interlace=PlaneInterlace; break; } case 0x0008: { /* Number of frames. */ if (data == (unsigned char *) NULL) break; number_scenes=StringToUnsignedLong((char *) data); break; } case 0x0010: { /* Image rows. */ height=(size_t) datum; break; } case 0x0011: { /* Image columns. */ width=(size_t) datum; break; } case 0x0100: { /* Bits allocated. */ bits_allocated=(size_t) datum; bytes_per_pixel=1; if (datum > 8) bytes_per_pixel=2; depth=bits_allocated; if (depth > 32) ThrowReaderException(CorruptImageError,""ImproperImageHeader""); max_value=(1UL << bits_allocated)-1; break; } case 0x0101: { /* Bits stored. */ significant_bits=(size_t) datum; bytes_per_pixel=1; if (significant_bits > 8) bytes_per_pixel=2; depth=significant_bits; if (depth > 32) ThrowReaderException(CorruptImageError,""ImproperImageHeader""); max_value=(1UL << significant_bits)-1; mask=(size_t) GetQuantumRange(significant_bits); break; } case 0x0102: { /* High bit. */ break; } case 0x0103: { /* Pixel representation. */ signed_data=(size_t) datum; break; } case 0x1050: { /* Visible pixel range: center. */ if (data != (unsigned char *) NULL) window_center=(ssize_t) StringToLong((char *) data); break; } case 0x1051: { /* Visible pixel range: width. */ if (data != (unsigned char *) NULL) window_width=StringToUnsignedLong((char *) data); break; } case 0x1052: { /* Rescale intercept */ if (data != (unsigned char *) NULL) rescale_intercept=(ssize_t) StringToLong((char *) data); break; } case 0x1053: { /* Rescale slope */ if (data != (unsigned char *) NULL) rescale_slope=(ssize_t) StringToLong((char *) data); break; } case 0x1200: case 0x3006: { /* Populate graymap. */ if (data == (unsigned char *) NULL) break; colors=(size_t) (length/bytes_per_pixel); datum=(int) colors; graymap=(int *) AcquireQuantumMemory((size_t) colors, sizeof(*graymap)); if (graymap == (int *) NULL) ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); for (i=0; i < (ssize_t) colors; i++) if (bytes_per_pixel == 1) graymap[i]=(int) data[i]; else graymap[i]=(int) ((short *) data)[i]; break; } case 0x1201: { unsigned short index; /* Populate redmap. */ if (data == (unsigned char *) NULL) break; colors=(size_t) (length/2); datum=(int) colors; redmap=(int *) AcquireQuantumMemory((size_t) colors, sizeof(*redmap)); if (redmap == (int *) NULL) ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); p=data; for (i=0; i < (ssize_t) colors; i++) { if (image->endian == MSBEndian) index=(unsigned short) ((*p << 8) | *(p+1)); else index=(unsigned short) (*p | (*(p+1) << 8)); redmap[i]=(int) index; p+=2; } break; } case 0x1202: { unsigned short index; /* Populate greenmap. */ if (data == (unsigned char *) NULL) break; colors=(size_t) (length/2); datum=(int) colors; greenmap=(int *) AcquireQuantumMemory((size_t) colors, sizeof(*greenmap)); if (greenmap == (int *) NULL) ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); p=data; for (i=0; i < (ssize_t) colors; i++) { if (image->endian == MSBEndian) index=(unsigned short) ((*p << 8) | *(p+1)); else index=(unsigned short) (*p | (*(p+1) << 8)); greenmap[i]=(int) index; p+=2; } break; } case 0x1203: { unsigned short index; /* Populate bluemap. */ if (data == (unsigned char *) NULL) break; colors=(size_t) (length/2); datum=(int) colors; bluemap=(int *) AcquireQuantumMemory((size_t) colors, sizeof(*bluemap)); if (bluemap == (int *) NULL) ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); p=data; for (i=0; i < (ssize_t) colors; i++) { if (image->endian == MSBEndian) index=(unsigned short) ((*p << 8) | *(p+1)); else index=(unsigned short) (*p | (*(p+1) << 8)); bluemap[i]=(int) index; p+=2; } break; } default: break; } break; } case 0x2050: { switch (element) { case 0x0020: { if ((data != (unsigned char *) NULL) && (strncmp((char *) data,""INVERSE"",7) == 0)) polarity=MagickTrue; break; } default: break; } break; } default: break; } if (data != (unsigned char *) NULL) { char *attribute; for (i=0; dicom_info[i].description != (char *) NULL; i++) if ((group == dicom_info[i].group) && (element == dicom_info[i].element)) break; if (dicom_info[i].description != (char *) NULL) { attribute=AcquireString(""dcm:""); (void) ConcatenateString(&attribute,dicom_info[i].description); for (i=0; i < (ssize_t) MagickMax(length,4); i++) if (isprint((int) data[i]) == MagickFalse) break; if ((i == (ssize_t) length) || (length > 4)) { (void) SubstituteString(&attribute,"" "",""""); (void) SetImageProperty(image,attribute,(char *) data,exception); } attribute=DestroyString(attribute); } } if (image_info->verbose != MagickFalse) { if (data == (unsigned char *) NULL) (void) FormatLocaleFile(stdout,""%d\n"",datum); else { /* Display group data. */ for (i=0; i < (ssize_t) MagickMax(length,4); i++) if (isprint((int) data[i]) == MagickFalse) break; if ((i != (ssize_t) length) && (length <= 4)) { ssize_t j; datum=0; for (j=(ssize_t) length-1; j >= 0; j--) datum=(256*datum+data[j]); (void) FormatLocaleFile(stdout,""%d"",datum); } else for (i=0; i < (ssize_t) length; i++) if (isprint((int) data[i]) != MagickFalse) (void) FormatLocaleFile(stdout,""%c"",data[i]); else (void) FormatLocaleFile(stdout,""%c"",'.'); (void) FormatLocaleFile(stdout,""\n""); } } if (data != (unsigned char *) NULL) data=(unsigned char *) RelinquishMagickMemory(data); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,""UnexpectedEndOfFile"", image->filename); break; } } if ((width == 0) || (height == 0)) ThrowReaderException(CorruptImageError,""ImproperImageHeader""); image->columns=(size_t) width; image->rows=(size_t) height; if (signed_data == 0xffff) signed_data=(size_t) (significant_bits == 16 ? 1 : 0); if ((image->compression == JPEGCompression) || (image->compression == JPEG2000Compression)) { Image *images; ImageInfo *read_info; int c; size_t length; unsigned int tag; /* Read offset table. */ for (i=0; i < (ssize_t) stream_info->remaining; i++) (void) ReadBlobByte(image); tag=(ReadBlobLSBShort(image) << 16) | ReadBlobLSBShort(image); (void) tag; length=(size_t) ReadBlobLSBLong(image); stream_info->offset_count=length >> 2; if (stream_info->offset_count != 0) { MagickOffsetType offset; stream_info->offsets=(ssize_t *) AcquireQuantumMemory( stream_info->offset_count,sizeof(*stream_info->offsets)); if (stream_info->offsets == (ssize_t *) NULL) ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); for (i=0; i < (ssize_t) stream_info->offset_count; i++) stream_info->offsets[i]=(ssize_t) ReadBlobLSBSignedLong(image); offset=TellBlob(image); for (i=0; i < (ssize_t) stream_info->offset_count; i++) stream_info->offsets[i]+=offset; } /* Handle non-native image formats. */ read_info=CloneImageInfo(image_info); SetImageInfoBlob(read_info,(void *) NULL,0); images=NewImageList(); for (scene=0; scene < (ssize_t) number_scenes; scene++) { char filename[MagickPathExtent]; const char *property; FILE *file; Image *jpeg_image; int unique_file; unsigned int tag; tag=(ReadBlobLSBShort(image) << 16) | ReadBlobLSBShort(image); length=(size_t) ReadBlobLSBLong(image); if (tag == 0xFFFEE0DD) break; /* sequence delimiter tag */ if (tag != 0xFFFEE000) ThrowReaderException(CorruptImageError,""ImproperImageHeader""); file=(FILE *) NULL; unique_file=AcquireUniqueFileResource(filename); if (unique_file != -1) file=fdopen(unique_file,""wb""); if (file == (FILE *) NULL) { (void) RelinquishUniqueFileResource(filename); ThrowFileException(exception,FileOpenError, ""UnableToCreateTemporaryFile"",filename); break; } for ( ; length != 0; length--) { c=ReadBlobByte(image); if (c == EOF) { ThrowFileException(exception,CorruptImageError, ""UnexpectedEndOfFile"",image->filename); break; } (void) fputc(c,file); } (void) fclose(file); (void) FormatLocaleString(read_info->filename,MagickPathExtent, ""jpeg:%s"",filename); if (image->compression == JPEG2000Compression) (void) FormatLocaleString(read_info->filename,MagickPathExtent, ""j2k:%s"",filename); jpeg_image=ReadImage(read_info,exception); if (jpeg_image != (Image *) NULL) { ResetImagePropertyIterator(image); property=GetNextImageProperty(image); while (property != (const char *) NULL) { (void) SetImageProperty(jpeg_image,property, GetImageProperty(image,property,exception),exception); property=GetNextImageProperty(image); } AppendImageToList(&images,jpeg_image); } (void) RelinquishUniqueFileResource(filename); } read_info=DestroyImageInfo(read_info); image=DestroyImage(image); return(GetFirstImageInList(images)); } if (depth != (1UL*MAGICKCORE_QUANTUM_DEPTH)) { QuantumAny range; size_t length; /* Compute pixel scaling table. */ length=(size_t) (GetQuantumRange(depth)+1); scale=(Quantum *) AcquireQuantumMemory(length,sizeof(*scale)); if (scale == (Quantum *) NULL) ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); range=GetQuantumRange(depth); for (i=0; i <= (ssize_t) GetQuantumRange(depth); i++) scale[i]=ScaleAnyToQuantum((size_t) i,range); } if (image->compression == RLECompression) { size_t length; unsigned int tag; /* Read RLE offset table. */ for (i=0; i < (ssize_t) stream_info->remaining; i++) (void) ReadBlobByte(image); tag=(ReadBlobLSBShort(image) << 16) | ReadBlobLSBShort(image); (void) tag; length=(size_t) ReadBlobLSBLong(image); stream_info->offset_count=length >> 2; if (stream_info->offset_count != 0) { MagickOffsetType offset; stream_info->offsets=(ssize_t *) AcquireQuantumMemory( stream_info->offset_count,sizeof(*stream_info->offsets)); if (stream_info->offsets == (ssize_t *) NULL) ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); for (i=0; i < (ssize_t) stream_info->offset_count; i++) stream_info->offsets[i]=(ssize_t) ReadBlobLSBSignedLong(image); offset=TellBlob(image); for (i=0; i < (ssize_t) stream_info->offset_count; i++) stream_info->offsets[i]+=offset; } } for (scene=0; scene < (ssize_t) number_scenes; scene++) { if (image_info->ping != MagickFalse) break; image->columns=(size_t) width; image->rows=(size_t) height; image->depth=depth; status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) break; image->colorspace=RGBColorspace; if ((image->colormap == (PixelInfo *) NULL) && (samples_per_pixel == 1)) { size_t one; one=1; if (colors == 0) colors=one << depth; if (AcquireImageColormap(image,one << depth,exception) == MagickFalse) ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); if (redmap != (int *) NULL) for (i=0; i < (ssize_t) colors; i++) { index=redmap[i]; if ((scale != (Quantum *) NULL) && (index <= (int) max_value)) index=(int) scale[index]; image->colormap[i].red=(MagickRealType) index; } if (greenmap != (int *) NULL) for (i=0; i < (ssize_t) colors; i++) { index=greenmap[i]; if ((scale != (Quantum *) NULL) && (index <= (int) max_value)) index=(int) scale[index]; image->colormap[i].green=(MagickRealType) index; } if (bluemap != (int *) NULL) for (i=0; i < (ssize_t) colors; i++) { index=bluemap[i]; if ((scale != (Quantum *) NULL) && (index <= (int) max_value)) index=(int) scale[index]; image->colormap[i].blue=(MagickRealType) index; } if (graymap != (int *) NULL) for (i=0; i < (ssize_t) colors; i++) { index=graymap[i]; if ((scale != (Quantum *) NULL) && (index <= (int) max_value)) index=(int) scale[index]; image->colormap[i].red=(MagickRealType) index; image->colormap[i].green=(MagickRealType) index; image->colormap[i].blue=(MagickRealType) index; } } if (image->compression == RLECompression) { unsigned int tag; /* Read RLE segment table. */ for (i=0; i < (ssize_t) stream_info->remaining; i++) (void) ReadBlobByte(image); tag=(ReadBlobLSBShort(image) << 16) | ReadBlobLSBShort(image); stream_info->remaining=(size_t) ReadBlobLSBLong(image); if ((tag != 0xFFFEE000) || (stream_info->remaining <= 64) || (EOFBlob(image) != MagickFalse)) ThrowReaderException(CorruptImageError,""ImproperImageHeader""); stream_info->count=0; stream_info->segment_count=ReadBlobLSBLong(image); if (stream_info->segment_count > 1) { bytes_per_pixel=1; depth=8; } for (i=0; i < 15; i++) stream_info->segments[i]=(ssize_t) ReadBlobLSBSignedLong(image); stream_info->remaining-=64; } if ((samples_per_pixel > 1) && (image->interlace == PlaneInterlace)) { /* Convert Planar RGB DCM Medical image to pixel packets. */ for (i=0; i < (ssize_t) samples_per_pixel; i++) { for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { switch ((int) i) { case 0: { SetPixelRed(image,ScaleCharToQuantum((unsigned char) ReadDCMByte(stream_info,image)),q); break; } case 1: { SetPixelGreen(image,ScaleCharToQuantum((unsigned char) ReadDCMByte(stream_info,image)),q); break; } case 2: { SetPixelBlue(image,ScaleCharToQuantum((unsigned char) ReadDCMByte(stream_info,image)),q); break; } case 3: { SetPixelAlpha(image,ScaleCharToQuantum((unsigned char) ReadDCMByte(stream_info,image)),q); break; } default: break; } q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } } } else { const char *option; int byte; PixelPacket pixel; /* Convert DCM Medical image to pixel packets. */ byte=0; i=0; if ((window_center != 0) && (window_width == 0)) window_width=(size_t) window_center; option=GetImageOption(image_info,""dcm:display-range""); if (option != (const char *) NULL) { if (LocaleCompare(option,""reset"") == 0) window_width=0; } (void) ResetMagickMemory(&pixel,0,sizeof(pixel)); for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (samples_per_pixel == 1) { int pixel_value; if (bytes_per_pixel == 1) pixel_value=polarity != MagickFalse ? ((int) max_value-ReadDCMByte(stream_info,image)) : ReadDCMByte(stream_info,image); else if ((bits_allocated != 12) || (significant_bits != 12)) { if (signed_data) pixel_value=ReadDCMSignedShort(stream_info,image); else pixel_value=ReadDCMShort(stream_info,image); if (polarity != MagickFalse) pixel_value=(int)max_value-pixel_value; } else { if ((i & 0x01) != 0) pixel_value=(ReadDCMByte(stream_info,image) << 8) | byte; else { pixel_value=ReadDCMSignedShort(stream_info,image); byte=(int) (pixel_value & 0x0f); pixel_value>>=4; } i++; } index=(pixel_value*rescale_slope)+rescale_intercept; if (window_width == 0) { if (signed_data == 1) index-=32767; } else { ssize_t window_max, window_min; window_min=(ssize_t) ceil((double) window_center- (window_width-1.0)/2.0-0.5); window_max=(ssize_t) floor((double) window_center+ (window_width-1.0)/2.0+0.5); if ((ssize_t)index <= window_min) index=0; else if ((ssize_t)index > window_max) index=(int) max_value; else index=(int) (max_value*(((index-window_center- 0.5)/(window_width-1))+0.5)); } index&=mask; index=(int) ConstrainColormapIndex(image,(size_t) index, exception); SetPixelIndex(image,(Quantum) index,q); pixel.red=(unsigned int) image->colormap[index].red; pixel.green=(unsigned int) image->colormap[index].green; pixel.blue=(unsigned int) image->colormap[index].blue; } else { if (bytes_per_pixel == 1) { pixel.red=(unsigned int) ReadDCMByte(stream_info,image); pixel.green=(unsigned int) ReadDCMByte(stream_info,image); pixel.blue=(unsigned int) ReadDCMByte(stream_info,image); } else { pixel.red=ReadDCMShort(stream_info,image); pixel.green=ReadDCMShort(stream_info,image); pixel.blue=ReadDCMShort(stream_info,image); } pixel.red&=mask; pixel.green&=mask; pixel.blue&=mask; if (scale != (Quantum *) NULL) { if (pixel.red <= GetQuantumRange(depth)) pixel.red=scale[pixel.red]; if (pixel.green <= GetQuantumRange(depth)) pixel.green=scale[pixel.green]; if (pixel.blue <= GetQuantumRange(depth)) pixel.blue=scale[pixel.blue]; } } SetPixelRed(image,(Quantum) pixel.red,q); SetPixelGreen(image,(Quantum) pixel.green,q); SetPixelBlue(image,(Quantum) pixel.blue,q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } if (stream_info->segment_count > 1) for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (samples_per_pixel == 1) { int pixel_value; if (bytes_per_pixel == 1) pixel_value=polarity != MagickFalse ? ((int) max_value-ReadDCMByte(stream_info,image)) : ReadDCMByte(stream_info,image); else if ((bits_allocated != 12) || (significant_bits != 12)) { pixel_value=(int) (polarity != MagickFalse ? (max_value-ReadDCMShort(stream_info,image)) : ReadDCMShort(stream_info,image)); if (signed_data == 1) pixel_value=((signed short) pixel_value); } else { if ((i & 0x01) != 0) pixel_value=(ReadDCMByte(stream_info,image) << 8) | byte; else { pixel_value=ReadDCMShort(stream_info,image); byte=(int) (pixel_value & 0x0f); pixel_value>>=4; } i++; } index=(pixel_value*rescale_slope)+rescale_intercept; if (window_width == 0) { if (signed_data == 1) index-=32767; } else { ssize_t window_max, window_min; window_min=(ssize_t) ceil((double) window_center- (window_width-1.0)/2.0-0.5); window_max=(ssize_t) floor((double) window_center+ (window_width-1.0)/2.0+0.5); if ((ssize_t)index <= window_min) index=0; else if ((ssize_t)index > window_max) index=(int) max_value; else index=(int) (max_value*(((index-window_center- 0.5)/(window_width-1))+0.5)); } index&=mask; index=(int) ConstrainColormapIndex(image,(size_t) index, exception); SetPixelIndex(image,(Quantum) (((size_t) GetPixelIndex(image,q)) | (((size_t) index) << 8)),q); pixel.red=(unsigned int) image->colormap[index].red; pixel.green=(unsigned int) image->colormap[index].green; pixel.blue=(unsigned int) image->colormap[index].blue; } else { if (bytes_per_pixel == 1) { pixel.red=(unsigned int) ReadDCMByte(stream_info,image); pixel.green=(unsigned int) ReadDCMByte(stream_info,image); pixel.blue=(unsigned int) ReadDCMByte(stream_info,image); } else { pixel.red=ReadDCMShort(stream_info,image); pixel.green=ReadDCMShort(stream_info,image); pixel.blue=ReadDCMShort(stream_info,image); } pixel.red&=mask; pixel.green&=mask; pixel.blue&=mask; if (scale != (Quantum *) NULL) { pixel.red=scale[pixel.red]; pixel.green=scale[pixel.green]; pixel.blue=scale[pixel.blue]; } } SetPixelRed(image,(Quantum) (((size_t) GetPixelRed(image,q)) | (((size_t) pixel.red) << 8)),q); SetPixelGreen(image,(Quantum) (((size_t) GetPixelGreen(image,q)) | (((size_t) pixel.green) << 8)),q); SetPixelBlue(image,(Quantum) (((size_t) GetPixelBlue(image,q)) | (((size_t) pixel.blue) << 8)),q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } } if (SetImageGray(image,exception) != MagickFalse) (void) SetImageColorspace(image,GRAYColorspace,exception); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,""UnexpectedEndOfFile"", image->filename); break; } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; if (scene < (ssize_t) (number_scenes-1)) { /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } /* Free resources. */ if (stream_info->offsets != (ssize_t *) NULL) stream_info->offsets=(ssize_t *) RelinquishMagickMemory(stream_info->offsets); stream_info=(DCMStreamInfo *) RelinquishMagickMemory(stream_info); if (scale != (Quantum *) NULL) scale=(Quantum *) RelinquishMagickMemory(scale); if (graymap != (int *) NULL) graymap=(int *) RelinquishMagickMemory(graymap); if (bluemap != (int *) NULL) bluemap=(int *) RelinquishMagickMemory(bluemap); if (greenmap != (int *) NULL) greenmap=(int *) RelinquishMagickMemory(greenmap); if (redmap != (int *) NULL) redmap=(int *) RelinquishMagickMemory(redmap); (void) CloseBlob(image); return(GetFirstImageInList(image)); }","{'deleted': [{'line_no': 899, 'char_start': 26296, 'char_end': 26359, 'line': ' for (i=0; i < (ssize_t) (GetQuantumRange(depth)+1); i++)\n'}, {'line_no': 1190, 'char_start': 36778, 'char_end': 36826, 'line': ' pixel.red=scale[pixel.red];\n'}, {'line_no': 1191, 'char_start': 36826, 'char_end': 36878, 'line': ' pixel.green=scale[pixel.green];\n'}, {'line_no': 1192, 'char_start': 36878, 'char_end': 36928, 'line': ' pixel.blue=scale[pixel.blue];\n'}], 'added': [{'line_no': 441, 'char_start': 12526, 'char_end': 12574, 'line': ' if (data == (unsigned char *) NULL)\n'}, {'line_no': 442, 'char_start': 12574, 'char_end': 12595, 'line': ' break;\n'}, {'line_no': 464, 'char_start': 13197, 'char_end': 13245, 'line': ' if (data == (unsigned char *) NULL)\n'}, {'line_no': 465, 'char_start': 13245, 'char_end': 13266, 'line': ' break;\n'}, {'line_no': 903, 'char_start': 26434, 'char_end': 26494, 'line': ' for (i=0; i <= (ssize_t) GetQuantumRange(depth); i++)\n'}, {'line_no': 1194, 'char_start': 36913, 'char_end': 36974, 'line': ' if (pixel.red <= GetQuantumRange(depth))\n'}, {'line_no': 1195, 'char_start': 36974, 'char_end': 37024, 'line': ' pixel.red=scale[pixel.red];\n'}, {'line_no': 1196, 'char_start': 37024, 'char_end': 37087, 'line': ' if (pixel.green <= GetQuantumRange(depth))\n'}, {'line_no': 1197, 'char_start': 37087, 'char_end': 37141, 'line': ' pixel.green=scale[pixel.green];\n'}, {'line_no': 1198, 'char_start': 37141, 'char_end': 37203, 'line': ' if (pixel.blue <= GetQuantumRange(depth))\n'}, {'line_no': 1199, 'char_start': 37203, 'char_end': 37255, 'line': ' pixel.blue=scale[pixel.blue];\n'}]}","{'deleted': [{'char_start': 26326, 'char_end': 26327, 'chars': '('}, {'char_start': 26348, 'char_end': 26351, 'chars': ')+1'}], 'added': [{'char_start': 12538, 'char_end': 12607, 'chars': 'if (data == (unsigned char *) NULL)\n break;\n '}, {'char_start': 13196, 'char_end': 13265, 'chars': '\n if (data == (unsigned char *) NULL)\n break;'}, {'char_start': 26453, 'char_end': 26454, 'chars': '='}, {'char_start': 36933, 'char_end': 36996, 'chars': 'if (pixel.red <= GetQuantumRange(depth))\n '}, {'char_start': 37044, 'char_end': 37109, 'chars': 'if (pixel.green <= GetQuantumRange(depth))\n '}, {'char_start': 37141, 'char_end': 37205, 'chars': ' if (pixel.blue <= GetQuantumRange(depth))\n '}]}",github.com/ImageMagick/ImageMagick/commit/5511ef530576ed18fd636baa3bb4eda3d667665d,coders/dcm.c,cwe-476,10320 cwe-078,_update_volume_stats," def _update_volume_stats(self): """"""Retrieve stats info from volume group."""""" LOG.debug(_(""Updating volume stats"")) data = {} data['vendor_name'] = 'IBM' data['driver_version'] = '1.1' data['storage_protocol'] = list(self._enabled_protocols) data['total_capacity_gb'] = 0 # To be overwritten data['free_capacity_gb'] = 0 # To be overwritten data['reserved_percentage'] = 0 data['QoS_support'] = False pool = self.configuration.storwize_svc_volpool_name #Get storage system name ssh_cmd = 'svcinfo lssystem -delim !' attributes = self._execute_command_and_parse_attributes(ssh_cmd) if not attributes or not attributes['name']: exception_message = (_('_update_volume_stats: ' 'Could not get system name')) raise exception.VolumeBackendAPIException(data=exception_message) backend_name = self.configuration.safe_get('volume_backend_name') if not backend_name: backend_name = '%s_%s' % (attributes['name'], pool) data['volume_backend_name'] = backend_name ssh_cmd = 'svcinfo lsmdiskgrp -bytes -delim ! %s' % pool attributes = self._execute_command_and_parse_attributes(ssh_cmd) if not attributes: LOG.error(_('Could not get pool data from the storage')) exception_message = (_('_update_volume_stats: ' 'Could not get storage pool data')) raise exception.VolumeBackendAPIException(data=exception_message) data['total_capacity_gb'] = (float(attributes['capacity']) / (1024 ** 3)) data['free_capacity_gb'] = (float(attributes['free_capacity']) / (1024 ** 3)) data['easytier_support'] = attributes['easy_tier'] in ['on', 'auto'] data['compression_support'] = self._compression_enabled self._stats = data"," def _update_volume_stats(self): """"""Retrieve stats info from volume group."""""" LOG.debug(_(""Updating volume stats"")) data = {} data['vendor_name'] = 'IBM' data['driver_version'] = '1.1' data['storage_protocol'] = list(self._enabled_protocols) data['total_capacity_gb'] = 0 # To be overwritten data['free_capacity_gb'] = 0 # To be overwritten data['reserved_percentage'] = 0 data['QoS_support'] = False pool = self.configuration.storwize_svc_volpool_name #Get storage system name ssh_cmd = ['svcinfo', 'lssystem', '-delim', '!'] attributes = self._execute_command_and_parse_attributes(ssh_cmd) if not attributes or not attributes['name']: exception_message = (_('_update_volume_stats: ' 'Could not get system name')) raise exception.VolumeBackendAPIException(data=exception_message) backend_name = self.configuration.safe_get('volume_backend_name') if not backend_name: backend_name = '%s_%s' % (attributes['name'], pool) data['volume_backend_name'] = backend_name ssh_cmd = ['svcinfo', 'lsmdiskgrp', '-bytes', '-delim', '!', pool] attributes = self._execute_command_and_parse_attributes(ssh_cmd) if not attributes: LOG.error(_('Could not get pool data from the storage')) exception_message = (_('_update_volume_stats: ' 'Could not get storage pool data')) raise exception.VolumeBackendAPIException(data=exception_message) data['total_capacity_gb'] = (float(attributes['capacity']) / (1024 ** 3)) data['free_capacity_gb'] = (float(attributes['free_capacity']) / (1024 ** 3)) data['easytier_support'] = attributes['easy_tier'] in ['on', 'auto'] data['compression_support'] = self._compression_enabled self._stats = data","{'deleted': [{'line_no': 18, 'char_start': 584, 'char_end': 630, 'line': "" ssh_cmd = 'svcinfo lssystem -delim !'\n""}, {'line_no': 30, 'char_start': 1179, 'char_end': 1244, 'line': "" ssh_cmd = 'svcinfo lsmdiskgrp -bytes -delim ! %s' % pool\n""}], 'added': [{'line_no': 18, 'char_start': 584, 'char_end': 641, 'line': "" ssh_cmd = ['svcinfo', 'lssystem', '-delim', '!']\n""}, {'line_no': 30, 'char_start': 1190, 'char_end': 1265, 'line': "" ssh_cmd = ['svcinfo', 'lsmdiskgrp', '-bytes', '-delim', '!', pool]\n""}]}","{'deleted': [{'char_start': 1232, 'char_end': 1235, 'chars': ' %s'}, {'char_start': 1236, 'char_end': 1238, 'chars': ' %'}], 'added': [{'char_start': 602, 'char_end': 603, 'chars': '['}, {'char_start': 611, 'char_end': 613, 'chars': ""',""}, {'char_start': 614, 'char_end': 615, 'chars': ""'""}, {'char_start': 623, 'char_end': 625, 'chars': ""',""}, {'char_start': 626, 'char_end': 627, 'chars': ""'""}, {'char_start': 633, 'char_end': 635, 'chars': ""',""}, {'char_start': 636, 'char_end': 637, 'chars': ""'""}, {'char_start': 639, 'char_end': 640, 'chars': ']'}, {'char_start': 1208, 'char_end': 1209, 'chars': '['}, {'char_start': 1217, 'char_end': 1219, 'chars': ""',""}, {'char_start': 1220, 'char_end': 1221, 'chars': ""'""}, {'char_start': 1231, 'char_end': 1233, 'chars': ""',""}, {'char_start': 1234, 'char_end': 1235, 'chars': ""'""}, {'char_start': 1241, 'char_end': 1243, 'chars': ""',""}, {'char_start': 1244, 'char_end': 1245, 'chars': ""'""}, {'char_start': 1251, 'char_end': 1253, 'chars': ""',""}, {'char_start': 1254, 'char_end': 1255, 'chars': ""'""}, {'char_start': 1257, 'char_end': 1258, 'chars': ','}, {'char_start': 1263, 'char_end': 1264, 'chars': ']'}]}",github.com/thatsdone/cinder/commit/f752302d181583a95cf44354aea607ce9d9283f4,cinder/volume/drivers/storwize_svc.py,cwe-078,432 cwe-125,HPHP::SimpleParser::handleBackslash," bool handleBackslash(signed char& out) { char ch = *p++; switch (ch) { case 0: return false; case '""': out = ch; return true; case '\\': out = ch; return true; case '/': out = ch; return true; case 'b': out = '\b'; return true; case 'f': out = '\f'; return true; case 'n': out = '\n'; return true; case 'r': out = '\r'; return true; case 't': out = '\t'; return true; case 'u': { if (UNLIKELY(is_tsimplejson)) { auto const ch1 = *p++; auto const ch2 = *p++; auto const dch3 = dehexchar(*p++); auto const dch4 = dehexchar(*p++); if (UNLIKELY(ch1 != '0' || ch2 != '0' || dch3 < 0 || dch4 < 0)) { return false; } out = (dch3 << 4) | dch4; return true; } else { uint16_t u16cp = 0; for (int i = 0; i < 4; i++) { auto const hexv = dehexchar(*p++); if (hexv < 0) return false; // includes check for end of string u16cp <<= 4; u16cp |= hexv; } if (u16cp > 0x7f) { return false; } else { out = u16cp; return true; } } } default: return false; } }"," bool handleBackslash(signed char& out) { char ch = *p++; switch (ch) { case 0: return false; case '""': out = ch; return true; case '\\': out = ch; return true; case '/': out = ch; return true; case 'b': out = '\b'; return true; case 'f': out = '\f'; return true; case 'n': out = '\n'; return true; case 'r': out = '\r'; return true; case 't': out = '\t'; return true; case 'u': { if (UNLIKELY(is_tsimplejson)) { auto const ch1 = *p++; if (UNLIKELY(ch1 != '0')) return false; auto const ch2 = *p++; if (UNLIKELY(ch2 != '0')) return false; auto const dch3 = dehexchar(*p++); if (UNLIKELY(dch3 < 0)) return false; auto const dch4 = dehexchar(*p++); if (UNLIKELY(dch4 < 0)) return false; out = (dch3 << 4) | dch4; return true; } else { uint16_t u16cp = 0; for (int i = 0; i < 4; i++) { auto const hexv = dehexchar(*p++); if (hexv < 0) return false; // includes check for end of string u16cp <<= 4; u16cp |= hexv; } if (u16cp > 0x7f) { return false; } else { out = u16cp; return true; } } } default: return false; } }","{'deleted': [{'line_no': 19, 'char_start': 646, 'char_end': 722, 'line': "" if (UNLIKELY(ch1 != '0' || ch2 != '0' || dch3 < 0 || dch4 < 0)) {\n""}, {'line_no': 20, 'char_start': 722, 'char_end': 748, 'line': ' return false;\n'}, {'line_no': 21, 'char_start': 748, 'char_end': 760, 'line': ' }\n'}], 'added': [{'line_no': 16, 'char_start': 523, 'char_end': 573, 'line': "" if (UNLIKELY(ch1 != '0')) return false;\n""}, {'line_no': 18, 'char_start': 606, 'char_end': 656, 'line': "" if (UNLIKELY(ch2 != '0')) return false;\n""}, {'line_no': 20, 'char_start': 701, 'char_end': 749, 'line': ' if (UNLIKELY(dch3 < 0)) return false;\n'}, {'line_no': 22, 'char_start': 794, 'char_end': 842, 'line': ' if (UNLIKELY(dch4 < 0)) return false;\n'}]}","{'deleted': [{'char_start': 669, 'char_end': 709, 'chars': ""ch1 != '0' || ch2 != '0' || dch3 < 0 || ""}, {'char_start': 720, 'char_end': 734, 'chars': '{\n '}, {'char_start': 747, 'char_end': 759, 'chars': '\n }'}], 'added': [{'char_start': 533, 'char_end': 583, 'chars': ""if (UNLIKELY(ch1 != '0')) return false;\n ""}, {'char_start': 616, 'char_end': 666, 'chars': ""if (UNLIKELY(ch2 != '0')) return false;\n ""}, {'char_start': 711, 'char_end': 759, 'chars': 'if (UNLIKELY(dch3 < 0)) return false;\n '}]}",github.com/facebook/hhvm/commit/b3679121bb3c7017ff04b4c08402ffff5cf59b13,hphp/runtime/ext/json/JSON_parser.cpp,cwe-125,389 cwe-190,gdi_Bitmap_Decompress,"static BOOL gdi_Bitmap_Decompress(rdpContext* context, rdpBitmap* bitmap, const BYTE* pSrcData, UINT32 DstWidth, UINT32 DstHeight, UINT32 bpp, UINT32 length, BOOL compressed, UINT32 codecId) { UINT32 SrcSize = length; rdpGdi* gdi = context->gdi; bitmap->compressed = FALSE; bitmap->format = gdi->dstFormat; bitmap->length = DstWidth * DstHeight * GetBytesPerPixel(bitmap->format); bitmap->data = (BYTE*) _aligned_malloc(bitmap->length, 16); if (!bitmap->data) return FALSE; if (compressed) { if (bpp < 32) { if (!interleaved_decompress(context->codecs->interleaved, pSrcData, SrcSize, DstWidth, DstHeight, bpp, bitmap->data, bitmap->format, 0, 0, 0, DstWidth, DstHeight, &gdi->palette)) return FALSE; } else { if (!planar_decompress(context->codecs->planar, pSrcData, SrcSize, DstWidth, DstHeight, bitmap->data, bitmap->format, 0, 0, 0, DstWidth, DstHeight, TRUE)) return FALSE; } } else { const UINT32 SrcFormat = gdi_get_pixel_format(bpp); const size_t sbpp = GetBytesPerPixel(SrcFormat); const size_t dbpp = GetBytesPerPixel(bitmap->format); if ((sbpp == 0) || (dbpp == 0)) return FALSE; else { const size_t dstSize = SrcSize * dbpp / sbpp; if (dstSize < bitmap->length) return FALSE; } if (!freerdp_image_copy(bitmap->data, bitmap->format, 0, 0, 0, DstWidth, DstHeight, pSrcData, SrcFormat, 0, 0, 0, &gdi->palette, FREERDP_FLIP_VERTICAL)) return FALSE; } return TRUE; }","static BOOL gdi_Bitmap_Decompress(rdpContext* context, rdpBitmap* bitmap, const BYTE* pSrcData, UINT32 DstWidth, UINT32 DstHeight, UINT32 bpp, UINT32 length, BOOL compressed, UINT32 codecId) { UINT32 SrcSize = length; rdpGdi* gdi = context->gdi; UINT32 size = DstWidth * DstHeight; bitmap->compressed = FALSE; bitmap->format = gdi->dstFormat; if ((GetBytesPerPixel(bitmap->format) == 0) || (DstWidth == 0) || (DstHeight == 0) || (DstWidth > UINT32_MAX / DstHeight) || (size > (UINT32_MAX / GetBytesPerPixel(bitmap->format)))) return FALSE; size *= GetBytesPerPixel(bitmap->format); bitmap->length = size; bitmap->data = (BYTE*) _aligned_malloc(bitmap->length, 16); if (!bitmap->data) return FALSE; if (compressed) { if (bpp < 32) { if (!interleaved_decompress(context->codecs->interleaved, pSrcData, SrcSize, DstWidth, DstHeight, bpp, bitmap->data, bitmap->format, 0, 0, 0, DstWidth, DstHeight, &gdi->palette)) return FALSE; } else { if (!planar_decompress(context->codecs->planar, pSrcData, SrcSize, DstWidth, DstHeight, bitmap->data, bitmap->format, 0, 0, 0, DstWidth, DstHeight, TRUE)) return FALSE; } } else { const UINT32 SrcFormat = gdi_get_pixel_format(bpp); const size_t sbpp = GetBytesPerPixel(SrcFormat); const size_t dbpp = GetBytesPerPixel(bitmap->format); if ((sbpp == 0) || (dbpp == 0)) return FALSE; else { const size_t dstSize = SrcSize * dbpp / sbpp; if (dstSize < bitmap->length) return FALSE; } if (!freerdp_image_copy(bitmap->data, bitmap->format, 0, 0, 0, DstWidth, DstHeight, pSrcData, SrcFormat, 0, 0, 0, &gdi->palette, FREERDP_FLIP_VERTICAL)) return FALSE; } return TRUE; }","{'deleted': [{'line_no': 10, 'char_start': 413, 'char_end': 488, 'line': '\tbitmap->length = DstWidth * DstHeight * GetBytesPerPixel(bitmap->format);\n'}], 'added': [{'line_no': 8, 'char_start': 350, 'char_end': 387, 'line': '\tUINT32 size = DstWidth * DstHeight;\n'}, {'line_no': 11, 'char_start': 450, 'char_end': 451, 'line': '\n'}, {'line_no': 12, 'char_start': 451, 'char_end': 499, 'line': '\tif ((GetBytesPerPixel(bitmap->format) == 0) ||\n'}, {'line_no': 13, 'char_start': 499, 'char_end': 582, 'line': '\t (DstWidth == 0) || (DstHeight == 0) || (DstWidth > UINT32_MAX / DstHeight) ||\n'}, {'line_no': 14, 'char_start': 582, 'char_end': 645, 'line': '\t (size > (UINT32_MAX / GetBytesPerPixel(bitmap->format))))\n'}, {'line_no': 15, 'char_start': 645, 'char_end': 661, 'line': '\t\treturn FALSE;\n'}, {'line_no': 16, 'char_start': 661, 'char_end': 662, 'line': '\n'}, {'line_no': 17, 'char_start': 662, 'char_end': 705, 'line': '\tsize *= GetBytesPerPixel(bitmap->format);\n'}, {'line_no': 18, 'char_start': 705, 'char_end': 729, 'line': '\tbitmap->length = size;\n'}]}","{'deleted': [{'char_start': 422, 'char_end': 423, 'chars': 'l'}, {'char_start': 424, 'char_end': 425, 'chars': 'n'}, {'char_start': 427, 'char_end': 428, 'chars': 'h'}, {'char_start': 440, 'char_end': 441, 'chars': '*'}], 'added': [{'char_start': 351, 'char_end': 388, 'chars': 'UINT32 size = DstWidth * DstHeight;\n\t'}, {'char_start': 450, 'char_end': 451, 'chars': '\n'}, {'char_start': 452, 'char_end': 474, 'chars': 'if ((GetBytesPerPixel('}, {'char_start': 482, 'char_end': 528, 'chars': 'format) == 0) ||\n\t (DstWidth == 0) || (DstH'}, {'char_start': 529, 'char_end': 530, 'chars': 'i'}, {'char_start': 532, 'char_end': 533, 'chars': 't'}, {'char_start': 535, 'char_end': 542, 'chars': '= 0) ||'}, {'char_start': 543, 'char_end': 544, 'chars': '('}, {'char_start': 553, 'char_end': 567, 'chars': '> UINT32_MAX /'}, {'char_start': 577, 'char_end': 667, 'chars': ') ||\n\t (size > (UINT32_MAX / GetBytesPerPixel(bitmap->format))))\n\t\treturn FALSE;\n\n\tsize'}, {'char_start': 669, 'char_end': 670, 'chars': '='}, {'char_start': 703, 'char_end': 727, 'chars': ';\n\tbitmap->length = size'}]}",github.com/FreeRDP/FreeRDP/commit/09b9d4f1994a674c4ec85b4947aa656eda1aed8a,libfreerdp/gdi/graphics.c,cwe-190,516 cwe-089,edit,"@mod.route('/edit', methods=['GET', 'POST']) def edit(): sql = ""SELECT * FROM users where email = '%s';"" % (session['logged_email']) cursor.execute(sql) u = cursor.fetchone() if request.method == 'POST': sql = ""UPDATE users SET nickname = '%s' where email = '%s'"" \ % (request.form['nickname'], session['logged_email']) cursor.execute(sql) sql = ""SELECT * FROM users where email = '%s';"" \ % (session['logged_email']) cursor.execute(sql) u = cursor.fetchone() conn.commit() flash('Edit Nickname Success!') return render_template('users/edit.html', u=u)","@mod.route('/edit', methods=['GET', 'POST']) def edit(): cursor.execute(""SELECT * FROM users where email = %s;"", (session['logged_email'],)) u = cursor.fetchone() if request.method == 'POST': cursor.execute(""UPDATE users SET nickname = %s where email = %s"", (request.form['nickname'], session['logged_email'])) cursor.execute(""SELECT * FROM users where email = %s;"", (session['logged_email'],)) u = cursor.fetchone() conn.commit() flash('Edit Nickname Success!') return render_template('users/edit.html', u=u)","{'deleted': [{'line_no': 3, 'char_start': 57, 'char_end': 137, 'line': ' sql = ""SELECT * FROM users where email = \'%s\';"" % (session[\'logged_email\'])\n'}, {'line_no': 4, 'char_start': 137, 'char_end': 161, 'line': ' cursor.execute(sql)\n'}, {'line_no': 7, 'char_start': 220, 'char_end': 290, 'line': ' sql = ""UPDATE users SET nickname = \'%s\' where email = \'%s\'"" \\\n'}, {'line_no': 8, 'char_start': 290, 'char_end': 352, 'line': "" % (request.form['nickname'], session['logged_email'])\n""}, {'line_no': 9, 'char_start': 352, 'char_end': 380, 'line': ' cursor.execute(sql)\n'}, {'line_no': 10, 'char_start': 380, 'char_end': 438, 'line': ' sql = ""SELECT * FROM users where email = \'%s\';"" \\\n'}, {'line_no': 11, 'char_start': 438, 'char_end': 478, 'line': "" % (session['logged_email'])\n""}, {'line_no': 12, 'char_start': 478, 'char_end': 506, 'line': ' cursor.execute(sql)\n'}], 'added': [{'line_no': 3, 'char_start': 57, 'char_end': 145, 'line': ' cursor.execute(""SELECT * FROM users where email = %s;"", (session[\'logged_email\'],))\n'}, {'line_no': 6, 'char_start': 204, 'char_end': 331, 'line': ' cursor.execute(""UPDATE users SET nickname = %s where email = %s"", (request.form[\'nickname\'], session[\'logged_email\']))\n'}, {'line_no': 7, 'char_start': 331, 'char_end': 423, 'line': ' cursor.execute(""SELECT * FROM users where email = %s;"", (session[\'logged_email\'],))\n'}]}","{'deleted': [{'char_start': 62, 'char_end': 67, 'chars': 'ql = '}, {'char_start': 102, 'char_end': 103, 'chars': ""'""}, {'char_start': 105, 'char_end': 106, 'chars': ""'""}, {'char_start': 108, 'char_end': 110, 'chars': ' %'}, {'char_start': 136, 'char_end': 159, 'chars': '\n cursor.execute(sql'}, {'char_start': 229, 'char_end': 234, 'chars': 'ql = '}, {'char_start': 263, 'char_end': 264, 'chars': ""'""}, {'char_start': 266, 'char_end': 267, 'chars': ""'""}, {'char_start': 282, 'char_end': 283, 'chars': ""'""}, {'char_start': 285, 'char_end': 286, 'chars': ""'""}, {'char_start': 287, 'char_end': 299, 'chars': ' \\\n %'}, {'char_start': 375, 'char_end': 394, 'chars': 'sql)\n sql = '}, {'char_start': 429, 'char_end': 430, 'chars': ""'""}, {'char_start': 432, 'char_end': 433, 'chars': ""'""}, {'char_start': 435, 'char_end': 451, 'chars': ' \\\n %'}, {'char_start': 477, 'char_end': 504, 'chars': '\n cursor.execute(sql'}], 'added': [{'char_start': 61, 'char_end': 64, 'chars': 'cur'}, {'char_start': 65, 'char_end': 76, 'chars': 'or.execute('}, {'char_start': 115, 'char_end': 116, 'chars': ','}, {'char_start': 141, 'char_end': 142, 'chars': ','}, {'char_start': 212, 'char_end': 215, 'chars': 'cur'}, {'char_start': 216, 'char_end': 227, 'chars': 'or.execute('}, {'char_start': 276, 'char_end': 277, 'chars': ','}, {'char_start': 329, 'char_end': 330, 'chars': ')'}, {'char_start': 393, 'char_end': 394, 'chars': ','}, {'char_start': 419, 'char_end': 420, 'chars': ','}]}",github.com/ulyssetsd/bjtu-sql/commit/17d7b21864b72ba5666f15236474a93268b32ec9,flaskr/flaskr/views/users.py,cwe-089,153 cwe-078,_find_host_exhaustive," def _find_host_exhaustive(self, connector, hosts): for host in hosts: ssh_cmd = 'svcinfo lshost -delim ! %s' % host out, err = self._run_ssh(ssh_cmd) self._assert_ssh_return(len(out.strip()), '_find_host_exhaustive', ssh_cmd, out, err) for attr_line in out.split('\n'): # If '!' not found, return the string and two empty strings attr_name, foo, attr_val = attr_line.partition('!') if (attr_name == 'iscsi_name' and 'initiator' in connector and attr_val == connector['initiator']): return host elif (attr_name == 'WWPN' and 'wwpns' in connector and attr_val.lower() in map(str.lower, map(str, connector['wwpns']))): return host return None"," def _find_host_exhaustive(self, connector, hosts): for host in hosts: ssh_cmd = ['svcinfo', 'lshost', '-delim', '!', host] out, err = self._run_ssh(ssh_cmd) self._assert_ssh_return(len(out.strip()), '_find_host_exhaustive', ssh_cmd, out, err) for attr_line in out.split('\n'): # If '!' not found, return the string and two empty strings attr_name, foo, attr_val = attr_line.partition('!') if (attr_name == 'iscsi_name' and 'initiator' in connector and attr_val == connector['initiator']): return host elif (attr_name == 'WWPN' and 'wwpns' in connector and attr_val.lower() in map(str.lower, map(str, connector['wwpns']))): return host return None","{'deleted': [{'line_no': 3, 'char_start': 82, 'char_end': 140, 'line': "" ssh_cmd = 'svcinfo lshost -delim ! %s' % host\n""}], 'added': [{'line_no': 3, 'char_start': 82, 'char_end': 147, 'line': "" ssh_cmd = ['svcinfo', 'lshost', '-delim', '!', host]\n""}]}","{'deleted': [{'char_start': 128, 'char_end': 131, 'chars': ' %s'}, {'char_start': 132, 'char_end': 134, 'chars': ' %'}], 'added': [{'char_start': 104, 'char_end': 105, 'chars': '['}, {'char_start': 113, 'char_end': 115, 'chars': ""',""}, {'char_start': 116, 'char_end': 117, 'chars': ""'""}, {'char_start': 123, 'char_end': 125, 'chars': ""',""}, {'char_start': 126, 'char_end': 127, 'chars': ""'""}, {'char_start': 133, 'char_end': 135, 'chars': ""',""}, {'char_start': 136, 'char_end': 137, 'chars': ""'""}, {'char_start': 139, 'char_end': 140, 'chars': ','}, {'char_start': 145, 'char_end': 146, 'chars': ']'}]}",github.com/thatsdone/cinder/commit/f752302d181583a95cf44354aea607ce9d9283f4,cinder/volume/drivers/storwize_svc.py,cwe-078,205 cwe-125,name_parse,"name_parse(u8 *packet, int length, int *idx, char *name_out, int name_out_len) { int name_end = -1; int j = *idx; int ptr_count = 0; #define GET32(x) do { if (j + 4 > length) goto err; memcpy(&t32_, packet + j, 4); j += 4; x = ntohl(t32_); } while (0) #define GET16(x) do { if (j + 2 > length) goto err; memcpy(&t_, packet + j, 2); j += 2; x = ntohs(t_); } while (0) #define GET8(x) do { if (j >= length) goto err; x = packet[j++]; } while (0) char *cp = name_out; const char *const end = name_out + name_out_len; /* Normally, names are a series of length prefixed strings terminated */ /* with a length of 0 (the lengths are u8's < 63). */ /* However, the length can start with a pair of 1 bits and that */ /* means that the next 14 bits are a pointer within the current */ /* packet. */ for (;;) { u8 label_len; if (j >= length) return -1; GET8(label_len); if (!label_len) break; if (label_len & 0xc0) { u8 ptr_low; GET8(ptr_low); if (name_end < 0) name_end = j; j = (((int)label_len & 0x3f) << 8) + ptr_low; /* Make sure that the target offset is in-bounds. */ if (j < 0 || j >= length) return -1; /* If we've jumped more times than there are characters in the * message, we must have a loop. */ if (++ptr_count > length) return -1; continue; } if (label_len > 63) return -1; if (cp != name_out) { if (cp + 1 >= end) return -1; *cp++ = '.'; } if (cp + label_len >= end) return -1; memcpy(cp, packet + j, label_len); cp += label_len; j += label_len; } if (cp >= end) return -1; *cp = '\0'; if (name_end < 0) *idx = j; else *idx = name_end; return 0; err: return -1; }","name_parse(u8 *packet, int length, int *idx, char *name_out, int name_out_len) { int name_end = -1; int j = *idx; int ptr_count = 0; #define GET32(x) do { if (j + 4 > length) goto err; memcpy(&t32_, packet + j, 4); j += 4; x = ntohl(t32_); } while (0) #define GET16(x) do { if (j + 2 > length) goto err; memcpy(&t_, packet + j, 2); j += 2; x = ntohs(t_); } while (0) #define GET8(x) do { if (j >= length) goto err; x = packet[j++]; } while (0) char *cp = name_out; const char *const end = name_out + name_out_len; /* Normally, names are a series of length prefixed strings terminated */ /* with a length of 0 (the lengths are u8's < 63). */ /* However, the length can start with a pair of 1 bits and that */ /* means that the next 14 bits are a pointer within the current */ /* packet. */ for (;;) { u8 label_len; GET8(label_len); if (!label_len) break; if (label_len & 0xc0) { u8 ptr_low; GET8(ptr_low); if (name_end < 0) name_end = j; j = (((int)label_len & 0x3f) << 8) + ptr_low; /* Make sure that the target offset is in-bounds. */ if (j < 0 || j >= length) return -1; /* If we've jumped more times than there are characters in the * message, we must have a loop. */ if (++ptr_count > length) return -1; continue; } if (label_len > 63) return -1; if (cp != name_out) { if (cp + 1 >= end) return -1; *cp++ = '.'; } if (cp + label_len >= end) return -1; if (j + label_len > length) return -1; memcpy(cp, packet + j, label_len); cp += label_len; j += label_len; } if (cp >= end) return -1; *cp = '\0'; if (name_end < 0) *idx = j; else *idx = name_end; return 0; err: return -1; }","{'deleted': [{'line_no': 20, 'char_start': 830, 'char_end': 860, 'line': '\t\tif (j >= length) return -1;\n'}], 'added': [{'line_no': 40, 'char_start': 1425, 'char_end': 1466, 'line': '\t\tif (j + label_len > length) return -1;\n'}]}","{'deleted': [{'char_start': 832, 'char_end': 862, 'chars': 'if (j >= length) return -1;\n\t\t'}], 'added': [{'char_start': 1412, 'char_end': 1453, 'chars': ') return -1;\n\t\tif (j + label_len > length'}]}",github.com/libevent/libevent/commit/96f64a022014a208105ead6c8a7066018449d86d,evdns.c,cwe-125,578 cwe-476,tflite::Subgraph::Invoke,"TfLiteStatus Subgraph::Invoke() { if (!consistent_) { ReportError(""Invoke called on model that is not consistent.""); return kTfLiteError; } TfLiteStatus status = kTfLiteOk; if (state_ == kStateUninvokable) { ReportError(""Invoke called on model that is not ready.""); return kTfLiteError; } else if (memory_planner_ && !memory_planner_->HasNonPersistentMemory()) { ReportError(""Non-persistent memory is not available.""); return kTfLiteError; } // This is only needed for UseNNAPI(true); if (should_apply_nnapi_delegate_ && !applied_nnapi_delegate_) { TF_LITE_ENSURE_OK(&context_, ModifyGraphWithDelegate(NnApiDelegate())); // only need to modify the graph once upon the first invocation. applied_nnapi_delegate_ = true; } // Invocations are always done in node order. // Note that calling Invoke repeatedly will cause the original memory plan to // be reused, unless either ResizeInputTensor() or AllocateTensors() has been // called. for (int execution_plan_index = 0; execution_plan_index < execution_plan_.size(); execution_plan_index++) { if (execution_plan_index == next_execution_plan_index_to_prepare_) { TF_LITE_ENSURE_STATUS(PrepareOpsAndTensors()); TF_LITE_ENSURE(&context_, next_execution_plan_index_to_prepare_ >= execution_plan_index); } int node_index = execution_plan_[execution_plan_index]; TfLiteNode& node = nodes_and_registration_[node_index].first; const TfLiteRegistration& registration = nodes_and_registration_[node_index].second; const char* op_name = nullptr; if (profiler_) op_name = GetTFLiteOpName(registration); TFLITE_SCOPED_TAGGED_OPERATOR_PROFILE(profiler_.get(), op_name, node_index); // TODO(ycling): This is an extra loop through inputs to check if the data // need to be copied from Delegate buffer to raw memory, which is often not // needed. We may want to cache this in prepare to know if this needs to be // done for a node or not. for (int i = 0; i < node.inputs->size; ++i) { int tensor_index = node.inputs->data[i]; if (tensor_index == kTfLiteOptionalTensor) { continue; } TfLiteTensor* tensor = &tensors_[tensor_index]; if (tensor->delegate && tensor->delegate != node.delegate && tensor->data_is_stale) { TF_LITE_ENSURE_STATUS(EnsureTensorDataIsReadable(tensor_index)); } } if (check_cancelled_func_ != nullptr && check_cancelled_func_(cancellation_data_)) { ReportError(""Client requested cancel during Invoke()""); return kTfLiteError; } EnsureTensorsVectorCapacity(); tensor_resized_since_op_invoke_ = false; if (OpInvoke(registration, &node) != kTfLiteOk) { return ReportOpError(&context_, node, registration, node_index, ""failed to invoke""); } // Force execution prep for downstream ops if the latest op triggered the // resize of a dynamic tensor. if (tensor_resized_since_op_invoke_ && HasDynamicTensor(context_, node.outputs)) { next_execution_plan_index_to_prepare_ = execution_plan_index + 1; // This happens when an intermediate dynamic tensor is resized. // We don't have to prepare all the ops, but we need to recompute // the allocation plan. if (next_execution_plan_index_to_plan_allocation_ > next_execution_plan_index_to_prepare_) { next_execution_plan_index_to_plan_allocation_ = next_execution_plan_index_to_prepare_; if (memory_planner_) { TF_LITE_ENSURE_STATUS(memory_planner_->ResetAllocationsAfter( next_execution_plan_index_to_plan_allocation_ - 1)); } } } } return status; }","TfLiteStatus Subgraph::Invoke() { if (!consistent_) { ReportError(""Invoke called on model that is not consistent.""); return kTfLiteError; } TfLiteStatus status = kTfLiteOk; if (state_ == kStateUninvokable) { ReportError(""Invoke called on model that is not ready.""); return kTfLiteError; } else if (memory_planner_ && !memory_planner_->HasNonPersistentMemory()) { ReportError(""Non-persistent memory is not available.""); return kTfLiteError; } // This is only needed for UseNNAPI(true); if (should_apply_nnapi_delegate_ && !applied_nnapi_delegate_) { TF_LITE_ENSURE_OK(&context_, ModifyGraphWithDelegate(NnApiDelegate())); // only need to modify the graph once upon the first invocation. applied_nnapi_delegate_ = true; } // Invocations are always done in node order. // Note that calling Invoke repeatedly will cause the original memory plan to // be reused, unless either ResizeInputTensor() or AllocateTensors() has been // called. for (int execution_plan_index = 0; execution_plan_index < execution_plan_.size(); execution_plan_index++) { if (execution_plan_index == next_execution_plan_index_to_prepare_) { TF_LITE_ENSURE_STATUS(PrepareOpsAndTensors()); TF_LITE_ENSURE(&context_, next_execution_plan_index_to_prepare_ >= execution_plan_index); } int node_index = execution_plan_[execution_plan_index]; TfLiteNode& node = nodes_and_registration_[node_index].first; const TfLiteRegistration& registration = nodes_and_registration_[node_index].second; const char* op_name = nullptr; if (profiler_) op_name = GetTFLiteOpName(registration); TFLITE_SCOPED_TAGGED_OPERATOR_PROFILE(profiler_.get(), op_name, node_index); // TODO(ycling): This is an extra loop through inputs to check if the data // need to be copied from Delegate buffer to raw memory, which is often not // needed. We may want to cache this in prepare to know if this needs to be // done for a node or not. for (int i = 0; i < node.inputs->size; ++i) { int tensor_index = node.inputs->data[i]; if (tensor_index == kTfLiteOptionalTensor) { continue; } TfLiteTensor* tensor = &tensors_[tensor_index]; if (tensor->delegate && tensor->delegate != node.delegate && tensor->data_is_stale) { TF_LITE_ENSURE_STATUS(EnsureTensorDataIsReadable(tensor_index)); } if (tensor->data.raw == nullptr && tensor->bytes > 0) { if (registration.builtin_code == kTfLiteBuiltinReshape && i == 1) { // In general, having a tensor here with no buffer will be an error. // However, for the reshape operator, the second input tensor is only // used for the shape, not for the data. Thus, null buffer is ok. continue; } else { // In all other cases, we need to return an error as otherwise we will // trigger a null pointer dereference (likely). ReportError(""Input tensor %d lacks data"", tensor_index); return kTfLiteError; } } } if (check_cancelled_func_ != nullptr && check_cancelled_func_(cancellation_data_)) { ReportError(""Client requested cancel during Invoke()""); return kTfLiteError; } EnsureTensorsVectorCapacity(); tensor_resized_since_op_invoke_ = false; if (OpInvoke(registration, &node) != kTfLiteOk) { return ReportOpError(&context_, node, registration, node_index, ""failed to invoke""); } // Force execution prep for downstream ops if the latest op triggered the // resize of a dynamic tensor. if (tensor_resized_since_op_invoke_ && HasDynamicTensor(context_, node.outputs)) { next_execution_plan_index_to_prepare_ = execution_plan_index + 1; // This happens when an intermediate dynamic tensor is resized. // We don't have to prepare all the ops, but we need to recompute // the allocation plan. if (next_execution_plan_index_to_plan_allocation_ > next_execution_plan_index_to_prepare_) { next_execution_plan_index_to_plan_allocation_ = next_execution_plan_index_to_prepare_; if (memory_planner_) { TF_LITE_ENSURE_STATUS(memory_planner_->ResetAllocationsAfter( next_execution_plan_index_to_plan_allocation_ - 1)); } } } } return status; }","{'deleted': [], 'added': [{'line_no': 57, 'char_start': 2461, 'char_end': 2523, 'line': ' if (tensor->data.raw == nullptr && tensor->bytes > 0) {\n'}, {'line_no': 58, 'char_start': 2523, 'char_end': 2599, 'line': ' if (registration.builtin_code == kTfLiteBuiltinReshape && i == 1) {\n'}, {'line_no': 62, 'char_start': 2834, 'char_end': 2854, 'line': ' continue;\n'}, {'line_no': 63, 'char_start': 2854, 'char_end': 2871, 'line': ' } else {\n'}, {'line_no': 66, 'char_start': 3010, 'char_end': 3077, 'line': ' ReportError(""Input tensor %d lacks data"", tensor_index);\n'}, {'line_no': 67, 'char_start': 3077, 'char_end': 3108, 'line': ' return kTfLiteError;\n'}, {'line_no': 68, 'char_start': 3108, 'char_end': 3118, 'line': ' }\n'}, {'line_no': 69, 'char_start': 3118, 'char_end': 3126, 'line': ' }\n'}]}","{'deleted': [], 'added': [{'char_start': 2465, 'char_end': 3130, 'chars': ' if (tensor->data.raw == nullptr && tensor->bytes > 0) {\n if (registration.builtin_code == kTfLiteBuiltinReshape && i == 1) {\n // In general, having a tensor here with no buffer will be an error.\n // However, for the reshape operator, the second input tensor is only\n // used for the shape, not for the data. Thus, null buffer is ok.\n continue;\n } else {\n // In all other cases, we need to return an error as otherwise we will\n // trigger a null pointer dereference (likely).\n ReportError(""Input tensor %d lacks data"", tensor_index);\n return kTfLiteError;\n }\n }\n '}]}",github.com/tensorflow/tensorflow/commit/0b5662bc2be13a8c8f044d925d87fb6e56247cd8,tensorflow/lite/core/subgraph.cc,cwe-476,883 cwe-190,b_unpack,"static int b_unpack (lua_State *L) { Header h; const char *fmt = luaL_checkstring(L, 1); size_t ld; const char *data = luaL_checklstring(L, 2, &ld); size_t pos = luaL_optinteger(L, 3, 1) - 1; int n = 0; /* number of results */ defaultoptions(&h); while (*fmt) { int opt = *fmt++; size_t size = optsize(L, opt, &fmt); pos += gettoalign(pos, &h, opt, size); luaL_argcheck(L, pos+size <= ld, 2, ""data string too short""); /* stack space for item + next position */ luaL_checkstack(L, 2, ""too many results""); switch (opt) { case 'b': case 'B': case 'h': case 'H': case 'l': case 'L': case 'T': case 'i': case 'I': { /* integer types */ int issigned = islower(opt); lua_Number res = getinteger(data+pos, h.endian, issigned, size); lua_pushnumber(L, res); n++; break; } case 'x': { break; } case 'f': { float f; memcpy(&f, data+pos, size); correctbytes((char *)&f, sizeof(f), h.endian); lua_pushnumber(L, f); n++; break; } case 'd': { double d; memcpy(&d, data+pos, size); correctbytes((char *)&d, sizeof(d), h.endian); lua_pushnumber(L, d); n++; break; } case 'c': { if (size == 0) { if (n == 0 || !lua_isnumber(L, -1)) luaL_error(L, ""format 'c0' needs a previous size""); size = lua_tonumber(L, -1); lua_pop(L, 1); n--; luaL_argcheck(L, size <= ld && pos <= ld - size, 2, ""data string too short""); } lua_pushlstring(L, data+pos, size); n++; break; } case 's': { const char *e = (const char *)memchr(data+pos, '\0', ld - pos); if (e == NULL) luaL_error(L, ""unfinished string in data""); size = (e - (data+pos)) + 1; lua_pushlstring(L, data+pos, size - 1); n++; break; } default: controloptions(L, opt, &fmt, &h); } pos += size; } lua_pushinteger(L, pos + 1); /* next position */ return n + 1; }","static int b_unpack (lua_State *L) { Header h; const char *fmt = luaL_checkstring(L, 1); size_t ld; const char *data = luaL_checklstring(L, 2, &ld); size_t pos = luaL_optinteger(L, 3, 1); luaL_argcheck(L, pos > 0, 3, ""offset must be 1 or greater""); pos--; /* Lua indexes are 1-based, but here we want 0-based for C * pointer math. */ int n = 0; /* number of results */ defaultoptions(&h); while (*fmt) { int opt = *fmt++; size_t size = optsize(L, opt, &fmt); pos += gettoalign(pos, &h, opt, size); luaL_argcheck(L, size <= ld && pos <= ld - size, 2, ""data string too short""); /* stack space for item + next position */ luaL_checkstack(L, 2, ""too many results""); switch (opt) { case 'b': case 'B': case 'h': case 'H': case 'l': case 'L': case 'T': case 'i': case 'I': { /* integer types */ int issigned = islower(opt); lua_Number res = getinteger(data+pos, h.endian, issigned, size); lua_pushnumber(L, res); n++; break; } case 'x': { break; } case 'f': { float f; memcpy(&f, data+pos, size); correctbytes((char *)&f, sizeof(f), h.endian); lua_pushnumber(L, f); n++; break; } case 'd': { double d; memcpy(&d, data+pos, size); correctbytes((char *)&d, sizeof(d), h.endian); lua_pushnumber(L, d); n++; break; } case 'c': { if (size == 0) { if (n == 0 || !lua_isnumber(L, -1)) luaL_error(L, ""format 'c0' needs a previous size""); size = lua_tonumber(L, -1); lua_pop(L, 1); n--; luaL_argcheck(L, size <= ld && pos <= ld - size, 2, ""data string too short""); } lua_pushlstring(L, data+pos, size); n++; break; } case 's': { const char *e = (const char *)memchr(data+pos, '\0', ld - pos); if (e == NULL) luaL_error(L, ""unfinished string in data""); size = (e - (data+pos)) + 1; lua_pushlstring(L, data+pos, size - 1); n++; break; } default: controloptions(L, opt, &fmt, &h); } pos += size; } lua_pushinteger(L, pos + 1); /* next position */ return n + 1; }","{'deleted': [{'line_no': 6, 'char_start': 157, 'char_end': 202, 'line': ' size_t pos = luaL_optinteger(L, 3, 1) - 1;\n'}, {'line_no': 13, 'char_start': 385, 'char_end': 451, 'line': ' luaL_argcheck(L, pos+size <= ld, 2, ""data string too short"");\n'}], 'added': [{'line_no': 6, 'char_start': 157, 'char_end': 198, 'line': ' size_t pos = luaL_optinteger(L, 3, 1);\n'}, {'line_no': 7, 'char_start': 198, 'char_end': 261, 'line': ' luaL_argcheck(L, pos > 0, 3, ""offset must be 1 or greater"");\n'}, {'line_no': 8, 'char_start': 261, 'char_end': 329, 'line': ' pos--; /* Lua indexes are 1-based, but here we want 0-based for C\n'}, {'line_no': 9, 'char_start': 329, 'char_end': 358, 'line': ' * pointer math. */\n'}, {'line_no': 16, 'char_start': 541, 'char_end': 594, 'line': ' luaL_argcheck(L, size <= ld && pos <= ld - size,\n'}, {'line_no': 17, 'char_start': 594, 'char_end': 642, 'line': ' 2, ""data string too short"");\n'}]}","{'deleted': [{'char_start': 197, 'char_end': 198, 'chars': '-'}, {'char_start': 406, 'char_end': 410, 'chars': 'pos+'}], 'added': [{'char_start': 196, 'char_end': 236, 'chars': ';\n luaL_argcheck(L, pos > 0, 3, ""offset'}, {'char_start': 237, 'char_end': 267, 'chars': 'must be 1 or greater"");\n pos-'}, {'char_start': 268, 'char_end': 288, 'chars': '; /* Lua indexes are'}, {'char_start': 290, 'char_end': 357, 'chars': '-based, but here we want 0-based for C\n * pointer math. */'}, {'char_start': 572, 'char_end': 592, 'chars': ' && pos <= ld - size'}, {'char_start': 593, 'char_end': 612, 'chars': '\n '}]}",github.com/antirez/redis/commit/e89086e09a38cc6713bcd4b9c29abf92cf393936,deps/lua/src/lua_struct.c,cwe-190,638 cwe-089,get_articles_by_subject,"def get_articles_by_subject(subject): with conn.cursor(cursor_factory=DictCursor) as cur: query = ""SELECT * FROM articles WHERE subject='"" + subject + ""' ORDER BY last_submitted DESC"" cur.execute(query) articles = cur.fetchall() return articles","def get_articles_by_subject(subject): with conn.cursor(cursor_factory=DictCursor) as cur: query = ""SELECT * FROM articles WHERE subject=%s ORDER BY last_submitted DESC"" cur.execute(query, (subject,)) articles = cur.fetchall() return articles","{'deleted': [{'line_no': 3, 'char_start': 94, 'char_end': 196, 'line': ' query = ""SELECT * FROM articles WHERE subject=\'"" + subject + ""\' ORDER BY last_submitted DESC""\n'}, {'line_no': 4, 'char_start': 196, 'char_end': 223, 'line': ' cur.execute(query)\n'}], 'added': [{'line_no': 3, 'char_start': 94, 'char_end': 181, 'line': ' query = ""SELECT * FROM articles WHERE subject=%s ORDER BY last_submitted DESC""\n'}, {'line_no': 4, 'char_start': 181, 'char_end': 220, 'line': ' cur.execute(query, (subject,))\n'}]}","{'deleted': [{'char_start': 148, 'char_end': 153, 'chars': '\'"" + '}, {'char_start': 154, 'char_end': 165, 'chars': 'ubject + ""\''}], 'added': [{'char_start': 148, 'char_end': 149, 'chars': '%'}, {'char_start': 206, 'char_end': 218, 'chars': ', (subject,)'}]}",github.com/sepehr125/arxiv-doc2vec-recommender/commit/f23a4c32e6192b145017f64734b0a9a384c9123a,app.py,cwe-089,56 cwe-079,mode_input," def mode_input(self, request): """""" This is called by render_POST when the client is sending data to the server. Args: request (Request): Incoming request. """""" csessid = request.args.get('csessid')[0] self.last_alive[csessid] = (time.time(), False) sess = self.sessionhandler.sessions_from_csessid(csessid) if sess: sess = sess[0] cmdarray = json.loads(request.args.get('data')[0]) sess.sessionhandler.data_in(sess, **{cmdarray[0]: [cmdarray[1], cmdarray[2]]}) return '""""'"," def mode_input(self, request): """""" This is called by render_POST when the client is sending data to the server. Args: request (Request): Incoming request. """""" csessid = cgi.escape(request.args['csessid'][0]) self.last_alive[csessid] = (time.time(), False) sess = self.sessionhandler.sessions_from_csessid(csessid) if sess: sess = sess[0] cmdarray = json.loads(cgi.escape(request.args.get('data')[0])) sess.sessionhandler.data_in(sess, **{cmdarray[0]: [cmdarray[1], cmdarray[2]]}) return '""""'","{'deleted': [{'line_no': 10, 'char_start': 217, 'char_end': 266, 'line': "" csessid = request.args.get('csessid')[0]\n""}, {'line_no': 11, 'char_start': 266, 'char_end': 267, 'line': '\n'}, {'line_no': 16, 'char_start': 433, 'char_end': 496, 'line': "" cmdarray = json.loads(request.args.get('data')[0])\n""}], 'added': [{'line_no': 10, 'char_start': 217, 'char_end': 274, 'line': "" csessid = cgi.escape(request.args['csessid'][0])\n""}, {'line_no': 15, 'char_start': 440, 'char_end': 515, 'line': "" cmdarray = json.loads(cgi.escape(request.args.get('data')[0]))\n""}]}","{'deleted': [{'char_start': 247, 'char_end': 252, 'chars': '.get('}, {'char_start': 261, 'char_end': 262, 'chars': ')'}, {'char_start': 265, 'char_end': 266, 'chars': '\n'}], 'added': [{'char_start': 235, 'char_end': 246, 'chars': 'cgi.escape('}, {'char_start': 258, 'char_end': 259, 'chars': '['}, {'char_start': 268, 'char_end': 269, 'chars': ']'}, {'char_start': 272, 'char_end': 273, 'chars': ')'}, {'char_start': 474, 'char_end': 485, 'chars': 'cgi.escape('}, {'char_start': 512, 'char_end': 513, 'chars': ')'}]}",github.com/evennia/evennia/commit/300261529b82f95414c9d1d7150d6eda4695bb93,evennia/server/portal/webclient_ajax.py,cwe-079,145 cwe-089,karma_ask,"def karma_ask(name): db = db_connect() cursor = db.cursor() try: cursor.execute( ''' SELECT karma FROM people WHERE name='{}' '''.format(name)) karma = cursor.fetchone() if karma is None: logger.debug('No karma found for name {}'.format(name)) db.close() return karma else: karma = karma[0] logger.debug('karma of {} found for name {}'.format(karma, name)) db.close() return karma except Exception as e: logger.error('Execution failed with error: {}'.format(e)) raise","def karma_ask(name): db = db_connect() cursor = db.cursor() try: cursor.execute(''' SELECT karma FROM people WHERE name=%(name)s ''', (name, )) karma = cursor.fetchone() if karma is None: logger.debug('No karma found for name {}'.format(name)) db.close() return karma else: karma = karma[0] logger.debug('karma of {} found for name {}'.format(karma, name)) db.close() return karma except Exception as e: logger.error('Execution failed with error: {}'.format(e)) raise","{'deleted': [{'line_no': 5, 'char_start': 77, 'char_end': 101, 'line': ' cursor.execute(\n'}, {'line_no': 6, 'char_start': 101, 'char_end': 176, 'line': "" ''' SELECT karma FROM people WHERE name='{}' '''.format(name))\n""}], 'added': [{'line_no': 5, 'char_start': 77, 'char_end': 154, 'line': "" cursor.execute(''' SELECT karma FROM people WHERE name=%(name)s ''',\n""}, {'line_no': 6, 'char_start': 154, 'char_end': 187, 'line': ' (name, ))\n'}]}","{'deleted': [{'char_start': 100, 'char_end': 113, 'chars': '\n '}, {'char_start': 153, 'char_end': 157, 'chars': ""'{}'""}, {'char_start': 161, 'char_end': 168, 'chars': '.format'}], 'added': [{'char_start': 140, 'char_end': 148, 'chars': '%(name)s'}, {'char_start': 152, 'char_end': 177, 'chars': ',\n '}, {'char_start': 182, 'char_end': 184, 'chars': ', '}]}",github.com/tylarb/KarmaBoi-PCF/commit/c1d00a27d7f6b7eb6f15a3dacd4269654a32c10a,KarmaBoi/dbopts.py,cwe-089,130 cwe-476,nsv_read_chunk,"static int nsv_read_chunk(AVFormatContext *s, int fill_header) { NSVContext *nsv = s->priv_data; AVIOContext *pb = s->pb; AVStream *st[2] = {NULL, NULL}; NSVStream *nst; AVPacket *pkt; int i, err = 0; uint8_t auxcount; /* number of aux metadata, also 4 bits of vsize */ uint32_t vsize; uint16_t asize; uint16_t auxsize; if (nsv->ahead[0].data || nsv->ahead[1].data) return 0; //-1; /* hey! eat what you've in your plate first! */ null_chunk_retry: if (pb->eof_reached) return -1; for (i = 0; i < NSV_MAX_RESYNC_TRIES && nsv->state < NSV_FOUND_NSVS && !err; i++) err = nsv_resync(s); if (err < 0) return err; if (nsv->state == NSV_FOUND_NSVS) err = nsv_parse_NSVs_header(s); if (err < 0) return err; if (nsv->state != NSV_HAS_READ_NSVS && nsv->state != NSV_FOUND_BEEF) return -1; auxcount = avio_r8(pb); vsize = avio_rl16(pb); asize = avio_rl16(pb); vsize = (vsize << 4) | (auxcount >> 4); auxcount &= 0x0f; av_log(s, AV_LOG_TRACE, ""NSV CHUNK %""PRIu8"" aux, %""PRIu32"" bytes video, %""PRIu16"" bytes audio\n"", auxcount, vsize, asize); /* skip aux stuff */ for (i = 0; i < auxcount; i++) { uint32_t av_unused auxtag; auxsize = avio_rl16(pb); auxtag = avio_rl32(pb); avio_skip(pb, auxsize); vsize -= auxsize + sizeof(uint16_t) + sizeof(uint32_t); /* that's becoming brain-dead */ } if (pb->eof_reached) return -1; if (!vsize && !asize) { nsv->state = NSV_UNSYNC; goto null_chunk_retry; } /* map back streams to v,a */ if (s->nb_streams > 0) st[s->streams[0]->id] = s->streams[0]; if (s->nb_streams > 1) st[s->streams[1]->id] = s->streams[1]; if (vsize && st[NSV_ST_VIDEO]) { nst = st[NSV_ST_VIDEO]->priv_data; pkt = &nsv->ahead[NSV_ST_VIDEO]; av_get_packet(pb, pkt, vsize); pkt->stream_index = st[NSV_ST_VIDEO]->index;//NSV_ST_VIDEO; pkt->dts = nst->frame_offset; pkt->flags |= nsv->state == NSV_HAS_READ_NSVS ? AV_PKT_FLAG_KEY : 0; /* keyframe only likely on a sync frame */ for (i = 0; i < FFMIN(8, vsize); i++) av_log(s, AV_LOG_TRACE, ""NSV video: [%d] = %02""PRIx8""\n"", i, pkt->data[i]); } if(st[NSV_ST_VIDEO]) ((NSVStream*)st[NSV_ST_VIDEO]->priv_data)->frame_offset++; if (asize && st[NSV_ST_AUDIO]) { nst = st[NSV_ST_AUDIO]->priv_data; pkt = &nsv->ahead[NSV_ST_AUDIO]; /* read raw audio specific header on the first audio chunk... */ /* on ALL audio chunks ?? seems so! */ if (asize && st[NSV_ST_AUDIO]->codecpar->codec_tag == MKTAG('P', 'C', 'M', ' ')/* && fill_header*/) { uint8_t bps; uint8_t channels; uint16_t samplerate; bps = avio_r8(pb); channels = avio_r8(pb); samplerate = avio_rl16(pb); if (!channels || !samplerate) return AVERROR_INVALIDDATA; asize-=4; av_log(s, AV_LOG_TRACE, ""NSV RAWAUDIO: bps %""PRIu8"", nchan %""PRIu8"", srate %""PRIu16""\n"", bps, channels, samplerate); if (fill_header) { st[NSV_ST_AUDIO]->need_parsing = AVSTREAM_PARSE_NONE; /* we know everything */ if (bps != 16) { av_log(s, AV_LOG_TRACE, ""NSV AUDIO bit/sample != 16 (%""PRIu8"")!!!\n"", bps); } bps /= channels; // ??? if (bps == 8) st[NSV_ST_AUDIO]->codecpar->codec_id = AV_CODEC_ID_PCM_U8; samplerate /= 4;/* UGH ??? XXX */ channels = 1; st[NSV_ST_AUDIO]->codecpar->channels = channels; st[NSV_ST_AUDIO]->codecpar->sample_rate = samplerate; av_log(s, AV_LOG_TRACE, ""NSV RAWAUDIO: bps %""PRIu8"", nchan %""PRIu8"", srate %""PRIu16""\n"", bps, channels, samplerate); } } av_get_packet(pb, pkt, asize); pkt->stream_index = st[NSV_ST_AUDIO]->index;//NSV_ST_AUDIO; pkt->flags |= nsv->state == NSV_HAS_READ_NSVS ? AV_PKT_FLAG_KEY : 0; /* keyframe only likely on a sync frame */ if( nsv->state == NSV_HAS_READ_NSVS && st[NSV_ST_VIDEO] ) { /* on a nsvs frame we have new information on a/v sync */ pkt->dts = (((NSVStream*)st[NSV_ST_VIDEO]->priv_data)->frame_offset-1); pkt->dts *= (int64_t)1000 * nsv->framerate.den; pkt->dts += (int64_t)nsv->avsync * nsv->framerate.num; av_log(s, AV_LOG_TRACE, ""NSV AUDIO: sync:%""PRId16"", dts:%""PRId64, nsv->avsync, pkt->dts); } nst->frame_offset++; } nsv->state = NSV_UNSYNC; return 0; }","static int nsv_read_chunk(AVFormatContext *s, int fill_header) { NSVContext *nsv = s->priv_data; AVIOContext *pb = s->pb; AVStream *st[2] = {NULL, NULL}; NSVStream *nst; AVPacket *pkt; int i, err = 0; uint8_t auxcount; /* number of aux metadata, also 4 bits of vsize */ uint32_t vsize; uint16_t asize; uint16_t auxsize; int ret; if (nsv->ahead[0].data || nsv->ahead[1].data) return 0; //-1; /* hey! eat what you've in your plate first! */ null_chunk_retry: if (pb->eof_reached) return -1; for (i = 0; i < NSV_MAX_RESYNC_TRIES && nsv->state < NSV_FOUND_NSVS && !err; i++) err = nsv_resync(s); if (err < 0) return err; if (nsv->state == NSV_FOUND_NSVS) err = nsv_parse_NSVs_header(s); if (err < 0) return err; if (nsv->state != NSV_HAS_READ_NSVS && nsv->state != NSV_FOUND_BEEF) return -1; auxcount = avio_r8(pb); vsize = avio_rl16(pb); asize = avio_rl16(pb); vsize = (vsize << 4) | (auxcount >> 4); auxcount &= 0x0f; av_log(s, AV_LOG_TRACE, ""NSV CHUNK %""PRIu8"" aux, %""PRIu32"" bytes video, %""PRIu16"" bytes audio\n"", auxcount, vsize, asize); /* skip aux stuff */ for (i = 0; i < auxcount; i++) { uint32_t av_unused auxtag; auxsize = avio_rl16(pb); auxtag = avio_rl32(pb); avio_skip(pb, auxsize); vsize -= auxsize + sizeof(uint16_t) + sizeof(uint32_t); /* that's becoming brain-dead */ } if (pb->eof_reached) return -1; if (!vsize && !asize) { nsv->state = NSV_UNSYNC; goto null_chunk_retry; } /* map back streams to v,a */ if (s->nb_streams > 0) st[s->streams[0]->id] = s->streams[0]; if (s->nb_streams > 1) st[s->streams[1]->id] = s->streams[1]; if (vsize && st[NSV_ST_VIDEO]) { nst = st[NSV_ST_VIDEO]->priv_data; pkt = &nsv->ahead[NSV_ST_VIDEO]; if ((ret = av_get_packet(pb, pkt, vsize)) < 0) return ret; pkt->stream_index = st[NSV_ST_VIDEO]->index;//NSV_ST_VIDEO; pkt->dts = nst->frame_offset; pkt->flags |= nsv->state == NSV_HAS_READ_NSVS ? AV_PKT_FLAG_KEY : 0; /* keyframe only likely on a sync frame */ for (i = 0; i < FFMIN(8, vsize); i++) av_log(s, AV_LOG_TRACE, ""NSV video: [%d] = %02""PRIx8""\n"", i, pkt->data[i]); } if(st[NSV_ST_VIDEO]) ((NSVStream*)st[NSV_ST_VIDEO]->priv_data)->frame_offset++; if (asize && st[NSV_ST_AUDIO]) { nst = st[NSV_ST_AUDIO]->priv_data; pkt = &nsv->ahead[NSV_ST_AUDIO]; /* read raw audio specific header on the first audio chunk... */ /* on ALL audio chunks ?? seems so! */ if (asize && st[NSV_ST_AUDIO]->codecpar->codec_tag == MKTAG('P', 'C', 'M', ' ')/* && fill_header*/) { uint8_t bps; uint8_t channels; uint16_t samplerate; bps = avio_r8(pb); channels = avio_r8(pb); samplerate = avio_rl16(pb); if (!channels || !samplerate) return AVERROR_INVALIDDATA; asize-=4; av_log(s, AV_LOG_TRACE, ""NSV RAWAUDIO: bps %""PRIu8"", nchan %""PRIu8"", srate %""PRIu16""\n"", bps, channels, samplerate); if (fill_header) { st[NSV_ST_AUDIO]->need_parsing = AVSTREAM_PARSE_NONE; /* we know everything */ if (bps != 16) { av_log(s, AV_LOG_TRACE, ""NSV AUDIO bit/sample != 16 (%""PRIu8"")!!!\n"", bps); } bps /= channels; // ??? if (bps == 8) st[NSV_ST_AUDIO]->codecpar->codec_id = AV_CODEC_ID_PCM_U8; samplerate /= 4;/* UGH ??? XXX */ channels = 1; st[NSV_ST_AUDIO]->codecpar->channels = channels; st[NSV_ST_AUDIO]->codecpar->sample_rate = samplerate; av_log(s, AV_LOG_TRACE, ""NSV RAWAUDIO: bps %""PRIu8"", nchan %""PRIu8"", srate %""PRIu16""\n"", bps, channels, samplerate); } } if ((ret = av_get_packet(pb, pkt, asize)) < 0) return ret; pkt->stream_index = st[NSV_ST_AUDIO]->index;//NSV_ST_AUDIO; pkt->flags |= nsv->state == NSV_HAS_READ_NSVS ? AV_PKT_FLAG_KEY : 0; /* keyframe only likely on a sync frame */ if( nsv->state == NSV_HAS_READ_NSVS && st[NSV_ST_VIDEO] ) { /* on a nsvs frame we have new information on a/v sync */ pkt->dts = (((NSVStream*)st[NSV_ST_VIDEO]->priv_data)->frame_offset-1); pkt->dts *= (int64_t)1000 * nsv->framerate.den; pkt->dts += (int64_t)nsv->avsync * nsv->framerate.num; av_log(s, AV_LOG_TRACE, ""NSV AUDIO: sync:%""PRId16"", dts:%""PRId64, nsv->avsync, pkt->dts); } nst->frame_offset++; } nsv->state = NSV_UNSYNC; return 0; }","{'deleted': [{'line_no': 64, 'char_start': 1938, 'char_end': 1977, 'line': ' av_get_packet(pb, pkt, vsize);\n'}, {'line_no': 108, 'char_start': 4074, 'char_end': 4113, 'line': ' av_get_packet(pb, pkt, asize);\n'}], 'added': [{'line_no': 13, 'char_start': 360, 'char_end': 373, 'line': ' int ret;\n'}, {'line_no': 65, 'char_start': 1951, 'char_end': 2006, 'line': ' if ((ret = av_get_packet(pb, pkt, vsize)) < 0)\n'}, {'line_no': 66, 'char_start': 2006, 'char_end': 2030, 'line': ' return ret;\n'}, {'line_no': 110, 'char_start': 4127, 'char_end': 4182, 'line': ' if ((ret = av_get_packet(pb, pkt, asize)) < 0)\n'}, {'line_no': 111, 'char_start': 4182, 'char_end': 4206, 'line': ' return ret;\n'}]}","{'deleted': [], 'added': [{'char_start': 360, 'char_end': 373, 'chars': ' int ret;\n'}, {'char_start': 1959, 'char_end': 1970, 'chars': 'if ((ret = '}, {'char_start': 1999, 'char_end': 2028, 'chars': ') < 0)\n return ret'}, {'char_start': 4135, 'char_end': 4146, 'chars': 'if ((ret = '}, {'char_start': 4175, 'char_end': 4204, 'chars': ') < 0)\n return ret'}]}",github.com/libav/libav/commit/fe6eea99efac66839052af547426518efd970b24,libavformat/nsvdec.c,cwe-476,1525 cwe-787,tflite::ops::builtin::segment_sum::ResizeOutputTensor,"TfLiteStatus ResizeOutputTensor(TfLiteContext* context, const TfLiteTensor* data, const TfLiteTensor* segment_ids, TfLiteTensor* output) { int max_index = -1; const int segment_id_size = segment_ids->dims->data[0]; if (segment_id_size > 0) { max_index = segment_ids->data.i32[segment_id_size - 1]; } const int data_rank = NumDimensions(data); TfLiteIntArray* output_shape = TfLiteIntArrayCreate(NumDimensions(data)); output_shape->data[0] = max_index + 1; for (int i = 1; i < data_rank; ++i) { output_shape->data[i] = data->dims->data[i]; } return context->ResizeTensor(context, output, output_shape); }","TfLiteStatus ResizeOutputTensor(TfLiteContext* context, const TfLiteTensor* data, const TfLiteTensor* segment_ids, TfLiteTensor* output) { // Segment ids should be of same cardinality as first input dimension and they // should be increasing by at most 1, from 0 (e.g., [0, 0, 1, 2, 3] is valid) const int segment_id_size = segment_ids->dims->data[0]; TF_LITE_ENSURE_EQ(context, segment_id_size, data->dims->data[0]); int previous_segment_id = -1; for (int i = 0; i < segment_id_size; i++) { const int current_segment_id = GetTensorData(segment_ids)[i]; if (i == 0) { TF_LITE_ENSURE_EQ(context, current_segment_id, 0); } else { int delta = current_segment_id - previous_segment_id; TF_LITE_ENSURE(context, delta == 0 || delta == 1); } previous_segment_id = current_segment_id; } const int max_index = previous_segment_id; const int data_rank = NumDimensions(data); TfLiteIntArray* output_shape = TfLiteIntArrayCreate(NumDimensions(data)); output_shape->data[0] = max_index + 1; for (int i = 1; i < data_rank; ++i) { output_shape->data[i] = data->dims->data[i]; } return context->ResizeTensor(context, output, output_shape); }","{'deleted': [{'line_no': 5, 'char_start': 235, 'char_end': 257, 'line': ' int max_index = -1;\n'}, {'line_no': 7, 'char_start': 315, 'char_end': 344, 'line': ' if (segment_id_size > 0) {\n'}, {'line_no': 8, 'char_start': 344, 'char_end': 404, 'line': ' max_index = segment_ids->data.i32[segment_id_size - 1];\n'}], 'added': [{'line_no': 8, 'char_start': 454, 'char_end': 522, 'line': ' TF_LITE_ENSURE_EQ(context, segment_id_size, data->dims->data[0]);\n'}, {'line_no': 9, 'char_start': 522, 'char_end': 554, 'line': ' int previous_segment_id = -1;\n'}, {'line_no': 10, 'char_start': 554, 'char_end': 600, 'line': ' for (int i = 0; i < segment_id_size; i++) {\n'}, {'line_no': 11, 'char_start': 600, 'char_end': 675, 'line': ' const int current_segment_id = GetTensorData(segment_ids)[i];\n'}, {'line_no': 12, 'char_start': 675, 'char_end': 693, 'line': ' if (i == 0) {\n'}, {'line_no': 13, 'char_start': 693, 'char_end': 750, 'line': ' TF_LITE_ENSURE_EQ(context, current_segment_id, 0);\n'}, {'line_no': 14, 'char_start': 750, 'char_end': 763, 'line': ' } else {\n'}, {'line_no': 15, 'char_start': 763, 'char_end': 823, 'line': ' int delta = current_segment_id - previous_segment_id;\n'}, {'line_no': 16, 'char_start': 823, 'char_end': 880, 'line': ' TF_LITE_ENSURE(context, delta == 0 || delta == 1);\n'}, {'line_no': 17, 'char_start': 880, 'char_end': 886, 'line': ' }\n'}, {'line_no': 18, 'char_start': 886, 'char_end': 932, 'line': ' previous_segment_id = current_segment_id;\n'}, {'line_no': 20, 'char_start': 936, 'char_end': 937, 'line': '\n'}, {'line_no': 21, 'char_start': 937, 'char_end': 982, 'line': ' const int max_index = previous_segment_id;\n'}, {'line_no': 22, 'char_start': 982, 'char_end': 983, 'line': '\n'}]}","{'deleted': [{'char_start': 237, 'char_end': 238, 'chars': 'i'}, {'char_start': 243, 'char_end': 245, 'chars': 'x_'}, {'char_start': 249, 'char_end': 250, 'chars': 'x'}, {'char_start': 251, 'char_end': 252, 'chars': '='}, {'char_start': 253, 'char_end': 254, 'chars': '-'}, {'char_start': 255, 'char_end': 256, 'chars': ';'}, {'char_start': 349, 'char_end': 351, 'chars': 'ax'}, {'char_start': 356, 'char_end': 357, 'chars': 'x'}, {'char_start': 371, 'char_end': 373, 'chars': '->'}, {'char_start': 377, 'char_end': 378, 'chars': '.'}, {'char_start': 379, 'char_end': 382, 'chars': '32['}, {'char_start': 395, 'char_end': 396, 'chars': 'z'}, {'char_start': 398, 'char_end': 399, 'chars': '-'}, {'char_start': 400, 'char_end': 402, 'chars': '1]'}, {'char_start': 404, 'char_end': 407, 'chars': ' }'}], 'added': [{'char_start': 237, 'char_end': 274, 'chars': '// Segment ids should be of same card'}, {'char_start': 276, 'char_end': 279, 'chars': 'ali'}, {'char_start': 280, 'char_end': 284, 'chars': 'y as'}, {'char_start': 285, 'char_end': 299, 'chars': 'first input di'}, {'char_start': 300, 'char_end': 307, 'chars': 'ension '}, {'char_start': 308, 'char_end': 338, 'chars': 'nd they\n // should be increas'}, {'char_start': 340, 'char_end': 364, 'chars': 'g by at most 1, from 0 ('}, {'char_start': 365, 'char_end': 369, 'chars': '.g.,'}, {'char_start': 370, 'char_end': 373, 'chars': '[0,'}, {'char_start': 374, 'char_end': 377, 'chars': '0, '}, {'char_start': 378, 'char_end': 395, 'chars': ', 2, 3] is valid)'}, {'char_start': 456, 'char_end': 491, 'chars': 'TF_LITE_ENSURE_EQ(context, segment_'}, {'char_start': 492, 'char_end': 556, 'chars': 'd_size, data->dims->data[0]);\n int previous_segment_id = -1;\n '}, {'char_start': 557, 'char_end': 559, 'chars': 'or'}, {'char_start': 561, 'char_end': 576, 'chars': 'int i = 0; i < '}, {'char_start': 591, 'char_end': 592, 'chars': ';'}, {'char_start': 593, 'char_end': 656, 'chars': 'i++) {\n const int current_segment_id = GetTensorDatasipx_family != AF_IPX) break; f.ipx_network = sipx->sipx_network; memcpy(f.ipx_device, ifr.ifr_name, sizeof(f.ipx_device)); memcpy(f.ipx_node, sipx->sipx_node, IPX_NODE_LEN); f.ipx_dlink_type = sipx->sipx_type; f.ipx_special = sipx->sipx_special; if (sipx->sipx_action == IPX_DLTITF) rc = ipxitf_delete(&f); else rc = ipxitf_create(&f); break; } case SIOCGIFADDR: { struct sockaddr_ipx *sipx; struct ipx_interface *ipxif; struct net_device *dev; rc = -EFAULT; if (copy_from_user(&ifr, arg, sizeof(ifr))) break; sipx = (struct sockaddr_ipx *)&ifr.ifr_addr; dev = __dev_get_by_name(&init_net, ifr.ifr_name); rc = -ENODEV; if (!dev) break; ipxif = ipxitf_find_using_phys(dev, ipx_map_frame_type(sipx->sipx_type)); rc = -EADDRNOTAVAIL; if (!ipxif) break; sipx->sipx_family = AF_IPX; sipx->sipx_network = ipxif->if_netnum; memcpy(sipx->sipx_node, ipxif->if_node, sizeof(sipx->sipx_node)); rc = -EFAULT; if (copy_to_user(arg, &ifr, sizeof(ifr))) break; ipxitf_put(ipxif); rc = 0; break; } case SIOCAIPXITFCRT: rc = -EFAULT; if (get_user(val, (unsigned char __user *) arg)) break; rc = 0; ipxcfg_auto_create_interfaces = val; break; case SIOCAIPXPRISLT: rc = -EFAULT; if (get_user(val, (unsigned char __user *) arg)) break; rc = 0; ipxcfg_set_auto_select(val); break; } return rc; }","static int ipxitf_ioctl(unsigned int cmd, void __user *arg) { int rc = -EINVAL; struct ifreq ifr; int val; switch (cmd) { case SIOCSIFADDR: { struct sockaddr_ipx *sipx; struct ipx_interface_definition f; rc = -EFAULT; if (copy_from_user(&ifr, arg, sizeof(ifr))) break; sipx = (struct sockaddr_ipx *)&ifr.ifr_addr; rc = -EINVAL; if (sipx->sipx_family != AF_IPX) break; f.ipx_network = sipx->sipx_network; memcpy(f.ipx_device, ifr.ifr_name, sizeof(f.ipx_device)); memcpy(f.ipx_node, sipx->sipx_node, IPX_NODE_LEN); f.ipx_dlink_type = sipx->sipx_type; f.ipx_special = sipx->sipx_special; if (sipx->sipx_action == IPX_DLTITF) rc = ipxitf_delete(&f); else rc = ipxitf_create(&f); break; } case SIOCGIFADDR: { struct sockaddr_ipx *sipx; struct ipx_interface *ipxif; struct net_device *dev; rc = -EFAULT; if (copy_from_user(&ifr, arg, sizeof(ifr))) break; sipx = (struct sockaddr_ipx *)&ifr.ifr_addr; dev = __dev_get_by_name(&init_net, ifr.ifr_name); rc = -ENODEV; if (!dev) break; ipxif = ipxitf_find_using_phys(dev, ipx_map_frame_type(sipx->sipx_type)); rc = -EADDRNOTAVAIL; if (!ipxif) break; sipx->sipx_family = AF_IPX; sipx->sipx_network = ipxif->if_netnum; memcpy(sipx->sipx_node, ipxif->if_node, sizeof(sipx->sipx_node)); rc = 0; if (copy_to_user(arg, &ifr, sizeof(ifr))) rc = -EFAULT; ipxitf_put(ipxif); break; } case SIOCAIPXITFCRT: rc = -EFAULT; if (get_user(val, (unsigned char __user *) arg)) break; rc = 0; ipxcfg_auto_create_interfaces = val; break; case SIOCAIPXPRISLT: rc = -EFAULT; if (get_user(val, (unsigned char __user *) arg)) break; rc = 0; ipxcfg_set_auto_select(val); break; } return rc; }","{'deleted': [{'line_no': 55, 'char_start': 1332, 'char_end': 1348, 'line': '\t\trc = -EFAULT;\n'}, {'line_no': 57, 'char_start': 1392, 'char_end': 1402, 'line': '\t\t\tbreak;\n'}, {'line_no': 59, 'char_start': 1423, 'char_end': 1433, 'line': '\t\trc = 0;\n'}], 'added': [{'line_no': 55, 'char_start': 1332, 'char_end': 1342, 'line': '\t\trc = 0;\n'}, {'line_no': 57, 'char_start': 1386, 'char_end': 1403, 'line': '\t\t\trc = -EFAULT;\n'}]}","{'deleted': [{'char_start': 1339, 'char_end': 1346, 'chars': '-EFAULT'}, {'char_start': 1395, 'char_end': 1396, 'chars': 'b'}, {'char_start': 1397, 'char_end': 1400, 'chars': 'eak'}, {'char_start': 1421, 'char_end': 1431, 'chars': ';\n\t\trc = 0'}], 'added': [{'char_start': 1339, 'char_end': 1340, 'chars': '0'}, {'char_start': 1390, 'char_end': 1401, 'chars': 'c = -EFAULT'}]}",github.com/torvalds/linux/commit/ee0d8d8482345ff97a75a7d747efc309f13b0d80,net/ipx/af_ipx.c,cwe-416,620 cwe-476,ipv4_pktinfo_prepare,"void ipv4_pktinfo_prepare(const struct sock *sk, struct sk_buff *skb) { struct in_pktinfo *pktinfo = PKTINFO_SKB_CB(skb); bool prepare = (inet_sk(sk)->cmsg_flags & IP_CMSG_PKTINFO) || ipv6_sk_rxinfo(sk); if (prepare && skb_rtable(skb)) { /* skb->cb is overloaded: prior to this point it is IP{6}CB * which has interface index (iif) as the first member of the * underlying inet{6}_skb_parm struct. This code then overlays * PKTINFO_SKB_CB and in_pktinfo also has iif as the first * element so the iif is picked up from the prior IPCB. If iif * is the loopback interface, then return the sending interface * (e.g., process binds socket to eth0 for Tx which is * redirected to loopback in the rtable/dst). */ if (pktinfo->ipi_ifindex == LOOPBACK_IFINDEX) pktinfo->ipi_ifindex = inet_iif(skb); pktinfo->ipi_spec_dst.s_addr = fib_compute_spec_dst(skb); } else { pktinfo->ipi_ifindex = 0; pktinfo->ipi_spec_dst.s_addr = 0; } skb_dst_drop(skb); }","void ipv4_pktinfo_prepare(const struct sock *sk, struct sk_buff *skb) { struct in_pktinfo *pktinfo = PKTINFO_SKB_CB(skb); bool prepare = (inet_sk(sk)->cmsg_flags & IP_CMSG_PKTINFO) || ipv6_sk_rxinfo(sk); if (prepare && skb_rtable(skb)) { /* skb->cb is overloaded: prior to this point it is IP{6}CB * which has interface index (iif) as the first member of the * underlying inet{6}_skb_parm struct. This code then overlays * PKTINFO_SKB_CB and in_pktinfo also has iif as the first * element so the iif is picked up from the prior IPCB. If iif * is the loopback interface, then return the sending interface * (e.g., process binds socket to eth0 for Tx which is * redirected to loopback in the rtable/dst). */ if (pktinfo->ipi_ifindex == LOOPBACK_IFINDEX) pktinfo->ipi_ifindex = inet_iif(skb); pktinfo->ipi_spec_dst.s_addr = fib_compute_spec_dst(skb); } else { pktinfo->ipi_ifindex = 0; pktinfo->ipi_spec_dst.s_addr = 0; } /* We need to keep the dst for __ip_options_echo() * We could restrict the test to opt.ts_needtime || opt.srr, * but the following is good enough as IP options are not often used. */ if (unlikely(IPCB(skb)->opt.optlen)) skb_dst_force(skb); else skb_dst_drop(skb); }","{'deleted': [{'line_no': 25, 'char_start': 972, 'char_end': 992, 'line': '\tskb_dst_drop(skb);\n'}], 'added': [{'line_no': 25, 'char_start': 972, 'char_end': 1024, 'line': '\t/* We need to keep the dst for __ip_options_echo()\n'}, {'line_no': 26, 'char_start': 1024, 'char_end': 1086, 'line': '\t * We could restrict the test to opt.ts_needtime || opt.srr,\n'}, {'line_no': 27, 'char_start': 1086, 'char_end': 1157, 'line': '\t * but the following is good enough as IP options are not often used.\n'}, {'line_no': 28, 'char_start': 1157, 'char_end': 1162, 'line': '\t */\n'}, {'line_no': 29, 'char_start': 1162, 'char_end': 1200, 'line': '\tif (unlikely(IPCB(skb)->opt.optlen))\n'}, {'line_no': 30, 'char_start': 1200, 'char_end': 1222, 'line': '\t\tskb_dst_force(skb);\n'}, {'line_no': 31, 'char_start': 1222, 'char_end': 1228, 'line': '\telse\n'}, {'line_no': 32, 'char_start': 1228, 'char_end': 1249, 'line': '\t\tskb_dst_drop(skb);\n'}]}","{'deleted': [], 'added': [{'char_start': 973, 'char_end': 1230, 'chars': '/* We need to keep the dst for __ip_options_echo()\n\t * We could restrict the test to opt.ts_needtime || opt.srr,\n\t * but the following is good enough as IP options are not often used.\n\t */\n\tif (unlikely(IPCB(skb)->opt.optlen))\n\t\tskb_dst_force(skb);\n\telse\n\t\t'}]}",github.com/torvalds/linux/commit/34b2cef20f19c87999fff3da4071e66937db9644,net/ipv4/ip_sockglue.c,cwe-476,297 cwe-079,Logger::addMessage,"void Logger::addMessage(const QString &message, const Log::MsgType &type) { QWriteLocker locker(&lock); Log::Msg temp = { msgCounter++, QDateTime::currentMSecsSinceEpoch(), type, message }; m_messages.push_back(temp); if (m_messages.size() >= MAX_LOG_MESSAGES) m_messages.pop_front(); emit newLogMessage(temp); }","void Logger::addMessage(const QString &message, const Log::MsgType &type) { QWriteLocker locker(&lock); Log::Msg temp = { msgCounter++, QDateTime::currentMSecsSinceEpoch(), type, Utils::String::toHtmlEscaped(message) }; m_messages.push_back(temp); if (m_messages.size() >= MAX_LOG_MESSAGES) m_messages.pop_front(); emit newLogMessage(temp); }","{'deleted': [{'line_no': 5, 'char_start': 109, 'char_end': 199, 'line': ' Log::Msg temp = { msgCounter++, QDateTime::currentMSecsSinceEpoch(), type, message };\n'}], 'added': [{'line_no': 5, 'char_start': 109, 'char_end': 229, 'line': ' Log::Msg temp = { msgCounter++, QDateTime::currentMSecsSinceEpoch(), type, Utils::String::toHtmlEscaped(message) };\n'}]}","{'deleted': [], 'added': [{'char_start': 188, 'char_end': 217, 'chars': 'Utils::String::toHtmlEscaped('}, {'char_start': 224, 'char_end': 225, 'chars': ')'}]}",github.com/qbittorrent/qBittorrent/commit/6ca3e4f094da0a0017cb2d483ec1db6176bb0b16,src/base/logger.cpp,cwe-079,82 cwe-787,mwifiex_ret_wmm_get_status,"int mwifiex_ret_wmm_get_status(struct mwifiex_private *priv, const struct host_cmd_ds_command *resp) { u8 *curr = (u8 *) &resp->params.get_wmm_status; uint16_t resp_len = le16_to_cpu(resp->size), tlv_len; int mask = IEEE80211_WMM_IE_AP_QOSINFO_PARAM_SET_CNT_MASK; bool valid = true; struct mwifiex_ie_types_data *tlv_hdr; struct mwifiex_ie_types_wmm_queue_status *tlv_wmm_qstatus; struct ieee_types_wmm_parameter *wmm_param_ie = NULL; struct mwifiex_wmm_ac_status *ac_status; mwifiex_dbg(priv->adapter, INFO, ""info: WMM: WMM_GET_STATUS cmdresp received: %d\n"", resp_len); while ((resp_len >= sizeof(tlv_hdr->header)) && valid) { tlv_hdr = (struct mwifiex_ie_types_data *) curr; tlv_len = le16_to_cpu(tlv_hdr->header.len); if (resp_len < tlv_len + sizeof(tlv_hdr->header)) break; switch (le16_to_cpu(tlv_hdr->header.type)) { case TLV_TYPE_WMMQSTATUS: tlv_wmm_qstatus = (struct mwifiex_ie_types_wmm_queue_status *) tlv_hdr; mwifiex_dbg(priv->adapter, CMD, ""info: CMD_RESP: WMM_GET_STATUS:\t"" ""QSTATUS TLV: %d, %d, %d\n"", tlv_wmm_qstatus->queue_index, tlv_wmm_qstatus->flow_required, tlv_wmm_qstatus->disabled); ac_status = &priv->wmm.ac_status[tlv_wmm_qstatus-> queue_index]; ac_status->disabled = tlv_wmm_qstatus->disabled; ac_status->flow_required = tlv_wmm_qstatus->flow_required; ac_status->flow_created = tlv_wmm_qstatus->flow_created; break; case WLAN_EID_VENDOR_SPECIFIC: /* * Point the regular IEEE IE 2 bytes into the Marvell IE * and setup the IEEE IE type and length byte fields */ wmm_param_ie = (struct ieee_types_wmm_parameter *) (curr + 2); wmm_param_ie->vend_hdr.len = (u8) tlv_len; wmm_param_ie->vend_hdr.element_id = WLAN_EID_VENDOR_SPECIFIC; mwifiex_dbg(priv->adapter, CMD, ""info: CMD_RESP: WMM_GET_STATUS:\t"" ""WMM Parameter Set Count: %d\n"", wmm_param_ie->qos_info_bitmap & mask); memcpy((u8 *) &priv->curr_bss_params.bss_descriptor. wmm_ie, wmm_param_ie, wmm_param_ie->vend_hdr.len + 2); break; default: valid = false; break; } curr += (tlv_len + sizeof(tlv_hdr->header)); resp_len -= (tlv_len + sizeof(tlv_hdr->header)); } mwifiex_wmm_setup_queue_priorities(priv, wmm_param_ie); mwifiex_wmm_setup_ac_downgrade(priv); return 0; }","int mwifiex_ret_wmm_get_status(struct mwifiex_private *priv, const struct host_cmd_ds_command *resp) { u8 *curr = (u8 *) &resp->params.get_wmm_status; uint16_t resp_len = le16_to_cpu(resp->size), tlv_len; int mask = IEEE80211_WMM_IE_AP_QOSINFO_PARAM_SET_CNT_MASK; bool valid = true; struct mwifiex_ie_types_data *tlv_hdr; struct mwifiex_ie_types_wmm_queue_status *tlv_wmm_qstatus; struct ieee_types_wmm_parameter *wmm_param_ie = NULL; struct mwifiex_wmm_ac_status *ac_status; mwifiex_dbg(priv->adapter, INFO, ""info: WMM: WMM_GET_STATUS cmdresp received: %d\n"", resp_len); while ((resp_len >= sizeof(tlv_hdr->header)) && valid) { tlv_hdr = (struct mwifiex_ie_types_data *) curr; tlv_len = le16_to_cpu(tlv_hdr->header.len); if (resp_len < tlv_len + sizeof(tlv_hdr->header)) break; switch (le16_to_cpu(tlv_hdr->header.type)) { case TLV_TYPE_WMMQSTATUS: tlv_wmm_qstatus = (struct mwifiex_ie_types_wmm_queue_status *) tlv_hdr; mwifiex_dbg(priv->adapter, CMD, ""info: CMD_RESP: WMM_GET_STATUS:\t"" ""QSTATUS TLV: %d, %d, %d\n"", tlv_wmm_qstatus->queue_index, tlv_wmm_qstatus->flow_required, tlv_wmm_qstatus->disabled); ac_status = &priv->wmm.ac_status[tlv_wmm_qstatus-> queue_index]; ac_status->disabled = tlv_wmm_qstatus->disabled; ac_status->flow_required = tlv_wmm_qstatus->flow_required; ac_status->flow_created = tlv_wmm_qstatus->flow_created; break; case WLAN_EID_VENDOR_SPECIFIC: /* * Point the regular IEEE IE 2 bytes into the Marvell IE * and setup the IEEE IE type and length byte fields */ wmm_param_ie = (struct ieee_types_wmm_parameter *) (curr + 2); wmm_param_ie->vend_hdr.len = (u8) tlv_len; wmm_param_ie->vend_hdr.element_id = WLAN_EID_VENDOR_SPECIFIC; mwifiex_dbg(priv->adapter, CMD, ""info: CMD_RESP: WMM_GET_STATUS:\t"" ""WMM Parameter Set Count: %d\n"", wmm_param_ie->qos_info_bitmap & mask); if (wmm_param_ie->vend_hdr.len + 2 > sizeof(struct ieee_types_wmm_parameter)) break; memcpy((u8 *) &priv->curr_bss_params.bss_descriptor. wmm_ie, wmm_param_ie, wmm_param_ie->vend_hdr.len + 2); break; default: valid = false; break; } curr += (tlv_len + sizeof(tlv_hdr->header)); resp_len -= (tlv_len + sizeof(tlv_hdr->header)); } mwifiex_wmm_setup_queue_priorities(priv, wmm_param_ie); mwifiex_wmm_setup_ac_downgrade(priv); return 0; }","{'deleted': [], 'added': [{'line_no': 63, 'char_start': 2014, 'char_end': 2054, 'line': '\t\t\tif (wmm_param_ie->vend_hdr.len + 2 >\n'}, {'line_no': 64, 'char_start': 2054, 'char_end': 2099, 'line': '\t\t\t\tsizeof(struct ieee_types_wmm_parameter))\n'}, {'line_no': 65, 'char_start': 2099, 'char_end': 2110, 'line': '\t\t\t\tbreak;\n'}, {'line_no': 66, 'char_start': 2110, 'char_end': 2111, 'line': '\n'}]}","{'deleted': [], 'added': [{'char_start': 2017, 'char_end': 2114, 'chars': 'if (wmm_param_ie->vend_hdr.len + 2 >\n\t\t\t\tsizeof(struct ieee_types_wmm_parameter))\n\t\t\t\tbreak;\n\n\t\t\t'}]}",github.com/torvalds/linux/commit/3a9b153c5591548612c3955c9600a98150c81875,drivers/net/wireless/marvell/mwifiex/wmm.c,cwe-787,732 cwe-125,tensorflow::GraphConstructor::MakeEdge,"Status GraphConstructor::MakeEdge(Node* src, int output_index, Node* dst, int input_index) { DataType src_out = src->output_type(output_index); DataType dst_in = dst->input_type(input_index); if (!TypesCompatible(dst_in, src_out)) { return errors::InvalidArgument( ""Input "", input_index, "" of node "", dst->name(), "" was passed "", DataTypeString(src_out), "" from "", src->name(), "":"", output_index, "" incompatible with expected "", DataTypeString(dst_in), "".""); } g_->AddEdge(src, output_index, dst, input_index); return Status::OK(); }","Status GraphConstructor::MakeEdge(Node* src, int output_index, Node* dst, int input_index) { if (output_index >= src->num_outputs()) { return errors::InvalidArgument( ""Output "", output_index, "" of node "", src->name(), "" does not exist. Node only has "", src->num_outputs(), "" outputs.""); } if (input_index >= dst->num_inputs()) { return errors::InvalidArgument( ""Input "", input_index, "" of node "", dst->name(), "" does not exist. Node only has "", dst->num_inputs(), "" inputs.""); } DataType src_out = src->output_type(output_index); DataType dst_in = dst->input_type(input_index); if (!TypesCompatible(dst_in, src_out)) { return errors::InvalidArgument( ""Input "", input_index, "" of node "", dst->name(), "" was passed "", DataTypeString(src_out), "" from "", src->name(), "":"", output_index, "" incompatible with expected "", DataTypeString(dst_in), "".""); } g_->AddEdge(src, output_index, dst, input_index); return Status::OK(); }","{'deleted': [], 'added': [{'line_no': 3, 'char_start': 127, 'char_end': 171, 'line': ' if (output_index >= src->num_outputs()) {\n'}, {'line_no': 4, 'char_start': 171, 'char_end': 207, 'line': ' return errors::InvalidArgument(\n'}, {'line_no': 5, 'char_start': 207, 'char_end': 266, 'line': ' ""Output "", output_index, "" of node "", src->name(),\n'}, {'line_no': 6, 'char_start': 266, 'char_end': 343, 'line': ' "" does not exist. Node only has "", src->num_outputs(), "" outputs."");\n'}, {'line_no': 7, 'char_start': 343, 'char_end': 347, 'line': ' }\n'}, {'line_no': 8, 'char_start': 347, 'char_end': 389, 'line': ' if (input_index >= dst->num_inputs()) {\n'}, {'line_no': 9, 'char_start': 389, 'char_end': 425, 'line': ' return errors::InvalidArgument(\n'}, {'line_no': 10, 'char_start': 425, 'char_end': 482, 'line': ' ""Input "", input_index, "" of node "", dst->name(),\n'}, {'line_no': 11, 'char_start': 482, 'char_end': 557, 'line': ' "" does not exist. Node only has "", dst->num_inputs(), "" inputs."");\n'}, {'line_no': 12, 'char_start': 557, 'char_end': 561, 'line': ' }\n'}, {'line_no': 13, 'char_start': 561, 'char_end': 562, 'line': '\n'}]}","{'deleted': [], 'added': [{'char_start': 129, 'char_end': 564, 'chars': 'if (output_index >= src->num_outputs()) {\n return errors::InvalidArgument(\n ""Output "", output_index, "" of node "", src->name(),\n "" does not exist. Node only has "", src->num_outputs(), "" outputs."");\n }\n if (input_index >= dst->num_inputs()) {\n return errors::InvalidArgument(\n ""Input "", input_index, "" of node "", dst->name(),\n "" does not exist. Node only has "", dst->num_inputs(), "" inputs."");\n }\n\n '}]}",github.com/tensorflow/tensorflow/commit/0cc38aaa4064fd9e79101994ce9872c6d91f816b,tensorflow/core/common_runtime/graph_constructor.cc,cwe-125,140 cwe-089,deletePost," def deletePost(self,postid): sqlText=""delete from post where post.postid=%d""%(postid) result=sql.deleteDB(self.conn,sqlText) return result;"," def deletePost(self,postid): sqlText=""delete from post where post.postid=%s"" params=[postid] result=sql.deleteDB(self.conn,sqlText,params) return result;","{'deleted': [{'line_no': 2, 'char_start': 33, 'char_end': 98, 'line': ' sqlText=""delete from post where post.postid=%d""%(postid)\n'}, {'line_no': 3, 'char_start': 98, 'char_end': 145, 'line': ' result=sql.deleteDB(self.conn,sqlText)\n'}], 'added': [{'line_no': 2, 'char_start': 33, 'char_end': 89, 'line': ' sqlText=""delete from post where post.postid=%s""\n'}, {'line_no': 3, 'char_start': 89, 'char_end': 113, 'line': ' params=[postid]\n'}, {'line_no': 4, 'char_start': 113, 'char_end': 167, 'line': ' result=sql.deleteDB(self.conn,sqlText,params)\n'}]}","{'deleted': [{'char_start': 86, 'char_end': 87, 'chars': 'd'}, {'char_start': 88, 'char_end': 90, 'chars': '%('}, {'char_start': 96, 'char_end': 97, 'chars': ')'}], 'added': [{'char_start': 86, 'char_end': 87, 'chars': 's'}, {'char_start': 88, 'char_end': 105, 'chars': '\n params=['}, {'char_start': 111, 'char_end': 112, 'chars': ']'}, {'char_start': 158, 'char_end': 165, 'chars': ',params'}]}",github.com/ShaominLi/Twitter_project/commit/5329d91f9e569c95184053c8e7ef596949c33ce9,modules/post.py,cwe-089,42 cwe-787,decode_frame,"static int decode_frame(AVCodecContext *avctx, void *data, int *got_frame, AVPacket *avpkt) { EXRContext *s = avctx->priv_data; ThreadFrame frame = { .f = data }; AVFrame *picture = data; uint8_t *ptr; int i, y, ret, ymax; int planes; int out_line_size; int nb_blocks; /* nb scanline or nb tile */ uint64_t start_offset_table; uint64_t start_next_scanline; PutByteContext offset_table_writer; bytestream2_init(&s->gb, avpkt->data, avpkt->size); if ((ret = decode_header(s, picture)) < 0) return ret; switch (s->pixel_type) { case EXR_FLOAT: case EXR_HALF: if (s->channel_offsets[3] >= 0) { if (!s->is_luma) { avctx->pix_fmt = AV_PIX_FMT_GBRAPF32; } else { /* todo: change this when a floating point pixel format with luma with alpha is implemented */ avctx->pix_fmt = AV_PIX_FMT_GBRAPF32; } } else { if (!s->is_luma) { avctx->pix_fmt = AV_PIX_FMT_GBRPF32; } else { avctx->pix_fmt = AV_PIX_FMT_GRAYF32; } } break; case EXR_UINT: if (s->channel_offsets[3] >= 0) { if (!s->is_luma) { avctx->pix_fmt = AV_PIX_FMT_RGBA64; } else { avctx->pix_fmt = AV_PIX_FMT_YA16; } } else { if (!s->is_luma) { avctx->pix_fmt = AV_PIX_FMT_RGB48; } else { avctx->pix_fmt = AV_PIX_FMT_GRAY16; } } break; default: av_log(avctx, AV_LOG_ERROR, ""Missing channel list.\n""); return AVERROR_INVALIDDATA; } if (s->apply_trc_type != AVCOL_TRC_UNSPECIFIED) avctx->color_trc = s->apply_trc_type; switch (s->compression) { case EXR_RAW: case EXR_RLE: case EXR_ZIP1: s->scan_lines_per_block = 1; break; case EXR_PXR24: case EXR_ZIP16: s->scan_lines_per_block = 16; break; case EXR_PIZ: case EXR_B44: case EXR_B44A: s->scan_lines_per_block = 32; break; default: avpriv_report_missing_feature(avctx, ""Compression %d"", s->compression); return AVERROR_PATCHWELCOME; } /* Verify the xmin, xmax, ymin and ymax before setting the actual image size. * It's possible for the data window can larger or outside the display window */ if (s->xmin > s->xmax || s->ymin > s->ymax || s->ydelta == 0xFFFFFFFF || s->xdelta == 0xFFFFFFFF) { av_log(avctx, AV_LOG_ERROR, ""Wrong or missing size information.\n""); return AVERROR_INVALIDDATA; } if ((ret = ff_set_dimensions(avctx, s->w, s->h)) < 0) return ret; s->desc = av_pix_fmt_desc_get(avctx->pix_fmt); if (!s->desc) return AVERROR_INVALIDDATA; if (s->desc->flags & AV_PIX_FMT_FLAG_FLOAT) { planes = s->desc->nb_components; out_line_size = avctx->width * 4; } else { planes = 1; out_line_size = avctx->width * 2 * s->desc->nb_components; } if (s->is_tile) { nb_blocks = ((s->xdelta + s->tile_attr.xSize - 1) / s->tile_attr.xSize) * ((s->ydelta + s->tile_attr.ySize - 1) / s->tile_attr.ySize); } else { /* scanline */ nb_blocks = (s->ydelta + s->scan_lines_per_block - 1) / s->scan_lines_per_block; } if ((ret = ff_thread_get_buffer(avctx, &frame, 0)) < 0) return ret; if (bytestream2_get_bytes_left(&s->gb)/8 < nb_blocks) return AVERROR_INVALIDDATA; // check offset table and recreate it if need if (!s->is_tile && bytestream2_peek_le64(&s->gb) == 0) { av_log(s->avctx, AV_LOG_DEBUG, ""recreating invalid scanline offset table\n""); start_offset_table = bytestream2_tell(&s->gb); start_next_scanline = start_offset_table + nb_blocks * 8; bytestream2_init_writer(&offset_table_writer, &avpkt->data[start_offset_table], nb_blocks * 8); for (y = 0; y < nb_blocks; y++) { /* write offset of prev scanline in offset table */ bytestream2_put_le64(&offset_table_writer, start_next_scanline); /* get len of next scanline */ bytestream2_seek(&s->gb, start_next_scanline + 4, SEEK_SET);/* skip line number */ start_next_scanline += (bytestream2_get_le32(&s->gb) + 8); } bytestream2_seek(&s->gb, start_offset_table, SEEK_SET); } // save pointer we are going to use in decode_block s->buf = avpkt->data; s->buf_size = avpkt->size; // Zero out the start if ymin is not 0 for (i = 0; i < planes; i++) { ptr = picture->data[i]; for (y = 0; y < s->ymin; y++) { memset(ptr, 0, out_line_size); ptr += picture->linesize[i]; } } s->picture = picture; avctx->execute2(avctx, decode_block, s->thread_data, NULL, nb_blocks); ymax = FFMAX(0, s->ymax + 1); // Zero out the end if ymax+1 is not h for (i = 0; i < planes; i++) { ptr = picture->data[i] + (ymax * picture->linesize[i]); for (y = ymax; y < avctx->height; y++) { memset(ptr, 0, out_line_size); ptr += picture->linesize[i]; } } picture->pict_type = AV_PICTURE_TYPE_I; *got_frame = 1; return avpkt->size; }","static int decode_frame(AVCodecContext *avctx, void *data, int *got_frame, AVPacket *avpkt) { EXRContext *s = avctx->priv_data; ThreadFrame frame = { .f = data }; AVFrame *picture = data; uint8_t *ptr; int i, y, ret, ymax; int planes; int out_line_size; int nb_blocks; /* nb scanline or nb tile */ uint64_t start_offset_table; uint64_t start_next_scanline; PutByteContext offset_table_writer; bytestream2_init(&s->gb, avpkt->data, avpkt->size); if ((ret = decode_header(s, picture)) < 0) return ret; switch (s->pixel_type) { case EXR_FLOAT: case EXR_HALF: if (s->channel_offsets[3] >= 0) { if (!s->is_luma) { avctx->pix_fmt = AV_PIX_FMT_GBRAPF32; } else { /* todo: change this when a floating point pixel format with luma with alpha is implemented */ avctx->pix_fmt = AV_PIX_FMT_GBRAPF32; } } else { if (!s->is_luma) { avctx->pix_fmt = AV_PIX_FMT_GBRPF32; } else { avctx->pix_fmt = AV_PIX_FMT_GRAYF32; } } break; case EXR_UINT: if (s->channel_offsets[3] >= 0) { if (!s->is_luma) { avctx->pix_fmt = AV_PIX_FMT_RGBA64; } else { avctx->pix_fmt = AV_PIX_FMT_YA16; } } else { if (!s->is_luma) { avctx->pix_fmt = AV_PIX_FMT_RGB48; } else { avctx->pix_fmt = AV_PIX_FMT_GRAY16; } } break; default: av_log(avctx, AV_LOG_ERROR, ""Missing channel list.\n""); return AVERROR_INVALIDDATA; } if (s->apply_trc_type != AVCOL_TRC_UNSPECIFIED) avctx->color_trc = s->apply_trc_type; switch (s->compression) { case EXR_RAW: case EXR_RLE: case EXR_ZIP1: s->scan_lines_per_block = 1; break; case EXR_PXR24: case EXR_ZIP16: s->scan_lines_per_block = 16; break; case EXR_PIZ: case EXR_B44: case EXR_B44A: s->scan_lines_per_block = 32; break; default: avpriv_report_missing_feature(avctx, ""Compression %d"", s->compression); return AVERROR_PATCHWELCOME; } /* Verify the xmin, xmax, ymin and ymax before setting the actual image size. * It's possible for the data window can larger or outside the display window */ if (s->xmin > s->xmax || s->ymin > s->ymax || s->ydelta == 0xFFFFFFFF || s->xdelta == 0xFFFFFFFF) { av_log(avctx, AV_LOG_ERROR, ""Wrong or missing size information.\n""); return AVERROR_INVALIDDATA; } if ((ret = ff_set_dimensions(avctx, s->w, s->h)) < 0) return ret; s->desc = av_pix_fmt_desc_get(avctx->pix_fmt); if (!s->desc) return AVERROR_INVALIDDATA; if (s->desc->flags & AV_PIX_FMT_FLAG_FLOAT) { planes = s->desc->nb_components; out_line_size = avctx->width * 4; } else { planes = 1; out_line_size = avctx->width * 2 * s->desc->nb_components; } if (s->is_tile) { nb_blocks = ((s->xdelta + s->tile_attr.xSize - 1) / s->tile_attr.xSize) * ((s->ydelta + s->tile_attr.ySize - 1) / s->tile_attr.ySize); } else { /* scanline */ nb_blocks = (s->ydelta + s->scan_lines_per_block - 1) / s->scan_lines_per_block; } if ((ret = ff_thread_get_buffer(avctx, &frame, 0)) < 0) return ret; if (bytestream2_get_bytes_left(&s->gb)/8 < nb_blocks) return AVERROR_INVALIDDATA; // check offset table and recreate it if need if (!s->is_tile && bytestream2_peek_le64(&s->gb) == 0) { av_log(s->avctx, AV_LOG_DEBUG, ""recreating invalid scanline offset table\n""); start_offset_table = bytestream2_tell(&s->gb); start_next_scanline = start_offset_table + nb_blocks * 8; bytestream2_init_writer(&offset_table_writer, &avpkt->data[start_offset_table], nb_blocks * 8); for (y = 0; y < nb_blocks; y++) { /* write offset of prev scanline in offset table */ bytestream2_put_le64(&offset_table_writer, start_next_scanline); /* get len of next scanline */ bytestream2_seek(&s->gb, start_next_scanline + 4, SEEK_SET);/* skip line number */ start_next_scanline += (bytestream2_get_le32(&s->gb) + 8); } bytestream2_seek(&s->gb, start_offset_table, SEEK_SET); } // save pointer we are going to use in decode_block s->buf = avpkt->data; s->buf_size = avpkt->size; // Zero out the start if ymin is not 0 for (i = 0; i < planes; i++) { ptr = picture->data[i]; for (y = 0; y < FFMIN(s->ymin, s->h); y++) { memset(ptr, 0, out_line_size); ptr += picture->linesize[i]; } } s->picture = picture; avctx->execute2(avctx, decode_block, s->thread_data, NULL, nb_blocks); ymax = FFMAX(0, s->ymax + 1); // Zero out the end if ymax+1 is not h for (i = 0; i < planes; i++) { ptr = picture->data[i] + (ymax * picture->linesize[i]); for (y = ymax; y < avctx->height; y++) { memset(ptr, 0, out_line_size); ptr += picture->linesize[i]; } } picture->pict_type = AV_PICTURE_TYPE_I; *got_frame = 1; return avpkt->size; }","{'deleted': [{'line_no': 146, 'char_start': 4801, 'char_end': 4841, 'line': ' for (y = 0; y < s->ymin; y++) {\n'}], 'added': [{'line_no': 146, 'char_start': 4801, 'char_end': 4854, 'line': ' for (y = 0; y < FFMIN(s->ymin, s->h); y++) {\n'}]}","{'deleted': [], 'added': [{'char_start': 4825, 'char_end': 4831, 'chars': 'FFMIN('}, {'char_start': 4838, 'char_end': 4845, 'chars': ', s->h)'}]}",github.com/FFmpeg/FFmpeg/commit/3e5959b3457f7f1856d997261e6ac672bba49e8b,libavcodec/exr.c,cwe-787,1571 cwe-190,perf_cpu_time_max_percent_handler,"int perf_cpu_time_max_percent_handler(struct ctl_table *table, int write, void __user *buffer, size_t *lenp, loff_t *ppos) { int ret = proc_dointvec(table, write, buffer, lenp, ppos); if (ret || !write) return ret; if (sysctl_perf_cpu_time_max_percent == 100 || sysctl_perf_cpu_time_max_percent == 0) { printk(KERN_WARNING ""perf: Dynamic interrupt throttling disabled, can hang your system!\n""); WRITE_ONCE(perf_sample_allowed_ns, 0); } else { update_perf_cpu_limits(); } return 0; }","int perf_cpu_time_max_percent_handler(struct ctl_table *table, int write, void __user *buffer, size_t *lenp, loff_t *ppos) { int ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos); if (ret || !write) return ret; if (sysctl_perf_cpu_time_max_percent == 100 || sysctl_perf_cpu_time_max_percent == 0) { printk(KERN_WARNING ""perf: Dynamic interrupt throttling disabled, can hang your system!\n""); WRITE_ONCE(perf_sample_allowed_ns, 0); } else { update_perf_cpu_limits(); } return 0; }","{'deleted': [{'line_no': 5, 'char_start': 133, 'char_end': 193, 'line': '\tint ret = proc_dointvec(table, write, buffer, lenp, ppos);\n'}], 'added': [{'line_no': 5, 'char_start': 133, 'char_end': 200, 'line': '\tint ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);\n'}]}","{'deleted': [], 'added': [{'char_start': 157, 'char_end': 164, 'chars': '_minmax'}]}",github.com/torvalds/linux/commit/1572e45a924f254d9570093abde46430c3172e3d,kernel/events/core.c,cwe-190,148 cwe-089,get_max_task_id_for_project," @staticmethod def get_max_task_id_for_project(project_id: int): """"""Gets the nights task id currently in use on a project"""""" sql = """"""select max(id) from tasks where project_id = {0} GROUP BY project_id"""""".format(project_id) result = db.engine.execute(sql) if result.rowcount == 0: raise NotFound() for row in result: return row[0]"," @staticmethod def get_max_task_id_for_project(project_id: int): """"""Gets the nights task id currently in use on a project"""""" sql = """"""select max(id) from tasks where project_id = :project_id GROUP BY project_id"""""" result = db.engine.execute(text(sql), project_id=project_id) if result.rowcount == 0: raise NotFound() for row in result: return row[0]","{'deleted': [{'line_no': 4, 'char_start': 140, 'char_end': 248, 'line': ' sql = """"""select max(id) from tasks where project_id = {0} GROUP BY project_id"""""".format(project_id)\n'}, {'line_no': 5, 'char_start': 248, 'char_end': 288, 'line': ' result = db.engine.execute(sql)\n'}], 'added': [{'line_no': 4, 'char_start': 140, 'char_end': 237, 'line': ' sql = """"""select max(id) from tasks where project_id = :project_id GROUP BY project_id""""""\n'}, {'line_no': 5, 'char_start': 237, 'char_end': 306, 'line': ' result = db.engine.execute(text(sql), project_id=project_id)\n'}]}","{'deleted': [{'char_start': 202, 'char_end': 205, 'chars': '{0}'}, {'char_start': 228, 'char_end': 247, 'chars': '.format(project_id)'}], 'added': [{'char_start': 202, 'char_end': 213, 'chars': ':project_id'}, {'char_start': 272, 'char_end': 277, 'chars': 'text('}, {'char_start': 280, 'char_end': 304, 'chars': '), project_id=project_id'}]}",github.com/hotosm/tasking-manager/commit/dee040a2d22b3c4d5e38e2dbf8c6b651ad4c241a,server/models/postgis/task.py,cwe-089,90 cwe-787,NeXTDecode,"NeXTDecode(TIFF* tif, uint8* buf, tmsize_t occ, uint16 s) { static const char module[] = ""NeXTDecode""; unsigned char *bp, *op; tmsize_t cc; uint8* row; tmsize_t scanline, n; (void) s; /* * Each scanline is assumed to start off as all * white (we assume a PhotometricInterpretation * of ``min-is-black''). */ for (op = (unsigned char*) buf, cc = occ; cc-- > 0;) *op++ = 0xff; bp = (unsigned char *)tif->tif_rawcp; cc = tif->tif_rawcc; scanline = tif->tif_scanlinesize; if (occ % scanline) { TIFFErrorExt(tif->tif_clientdata, module, ""Fractional scanlines cannot be read""); return (0); } for (row = buf; cc > 0 && occ > 0; occ -= scanline, row += scanline) { n = *bp++, cc--; switch (n) { case LITERALROW: /* * The entire scanline is given as literal values. */ if (cc < scanline) goto bad; _TIFFmemcpy(row, bp, scanline); bp += scanline; cc -= scanline; break; case LITERALSPAN: { tmsize_t off; /* * The scanline has a literal span that begins at some * offset. */ if( cc < 4 ) goto bad; off = (bp[0] * 256) + bp[1]; n = (bp[2] * 256) + bp[3]; if (cc < 4+n || off+n > scanline) goto bad; _TIFFmemcpy(row+off, bp+4, n); bp += 4+n; cc -= 4+n; break; } default: { uint32 npixels = 0, grey; uint32 imagewidth = tif->tif_dir.td_imagewidth; if( isTiled(tif) ) imagewidth = tif->tif_dir.td_tilewidth; /* * The scanline is composed of a sequence of constant * color ``runs''. We shift into ``run mode'' and * interpret bytes as codes of the form * until we've filled the scanline. */ op = row; for (;;) { grey = (uint32)((n>>6) & 0x3); n &= 0x3f; /* * Ensure the run does not exceed the scanline * bounds, potentially resulting in a security * issue. */ while (n-- > 0 && npixels < imagewidth) SETPIXEL(op, grey); if (npixels >= imagewidth) break; if (cc == 0) goto bad; n = *bp++, cc--; } break; } } } tif->tif_rawcp = (uint8*) bp; tif->tif_rawcc = cc; return (1); bad: TIFFErrorExt(tif->tif_clientdata, module, ""Not enough data for scanline %ld"", (long) tif->tif_row); return (0); }","NeXTDecode(TIFF* tif, uint8* buf, tmsize_t occ, uint16 s) { static const char module[] = ""NeXTDecode""; unsigned char *bp, *op; tmsize_t cc; uint8* row; tmsize_t scanline, n; (void) s; /* * Each scanline is assumed to start off as all * white (we assume a PhotometricInterpretation * of ``min-is-black''). */ for (op = (unsigned char*) buf, cc = occ; cc-- > 0;) *op++ = 0xff; bp = (unsigned char *)tif->tif_rawcp; cc = tif->tif_rawcc; scanline = tif->tif_scanlinesize; if (occ % scanline) { TIFFErrorExt(tif->tif_clientdata, module, ""Fractional scanlines cannot be read""); return (0); } for (row = buf; cc > 0 && occ > 0; occ -= scanline, row += scanline) { n = *bp++, cc--; switch (n) { case LITERALROW: /* * The entire scanline is given as literal values. */ if (cc < scanline) goto bad; _TIFFmemcpy(row, bp, scanline); bp += scanline; cc -= scanline; break; case LITERALSPAN: { tmsize_t off; /* * The scanline has a literal span that begins at some * offset. */ if( cc < 4 ) goto bad; off = (bp[0] * 256) + bp[1]; n = (bp[2] * 256) + bp[3]; if (cc < 4+n || off+n > scanline) goto bad; _TIFFmemcpy(row+off, bp+4, n); bp += 4+n; cc -= 4+n; break; } default: { uint32 npixels = 0, grey; uint32 imagewidth = tif->tif_dir.td_imagewidth; if( isTiled(tif) ) imagewidth = tif->tif_dir.td_tilewidth; tmsize_t op_offset = 0; /* * The scanline is composed of a sequence of constant * color ``runs''. We shift into ``run mode'' and * interpret bytes as codes of the form * until we've filled the scanline. */ op = row; for (;;) { grey = (uint32)((n>>6) & 0x3); n &= 0x3f; /* * Ensure the run does not exceed the scanline * bounds, potentially resulting in a security * issue. */ while (n-- > 0 && npixels < imagewidth && op_offset < scanline) SETPIXEL(op, grey); if (npixels >= imagewidth) break; if (op_offset >= scanline ) { TIFFErrorExt(tif->tif_clientdata, module, ""Invalid data for scanline %ld"", (long) tif->tif_row); return (0); } if (cc == 0) goto bad; n = *bp++, cc--; } break; } } } tif->tif_rawcp = (uint8*) bp; tif->tif_rawcc = cc; return (1); bad: TIFFErrorExt(tif->tif_clientdata, module, ""Not enough data for scanline %ld"", (long) tif->tif_row); return (0); }","{'deleted': [{'line_no': 77, 'char_start': 1882, 'char_end': 1926, 'line': '\t\t\t\twhile (n-- > 0 && npixels < imagewidth)\n'}], 'added': [{'line_no': 61, 'char_start': 1450, 'char_end': 1486, 'line': ' tmsize_t op_offset = 0;\n'}, {'line_no': 78, 'char_start': 1918, 'char_end': 1986, 'line': '\t\t\t\twhile (n-- > 0 && npixels < imagewidth && op_offset < scanline)\n'}, {'line_no': 82, 'char_start': 2054, 'char_end': 2100, 'line': ' if (op_offset >= scanline ) {\n'}, {'line_no': 83, 'char_start': 2100, 'char_end': 2195, 'line': ' TIFFErrorExt(tif->tif_clientdata, module, ""Invalid data for scanline %ld"",\n'}, {'line_no': 84, 'char_start': 2195, 'char_end': 2241, 'line': ' (long) tif->tif_row);\n'}, {'line_no': 85, 'char_start': 2241, 'char_end': 2273, 'line': ' return (0);\n'}, {'line_no': 86, 'char_start': 2273, 'char_end': 2291, 'line': ' }\n'}]}","{'deleted': [], 'added': [{'char_start': 1450, 'char_end': 1486, 'chars': ' tmsize_t op_offset = 0;\n'}, {'char_start': 1960, 'char_end': 1984, 'chars': ' && op_offset < scanline'}, {'char_start': 2053, 'char_end': 2290, 'chars': '\n if (op_offset >= scanline ) {\n TIFFErrorExt(tif->tif_clientdata, module, ""Invalid data for scanline %ld"",\n (long) tif->tif_row);\n return (0);\n }'}]}",github.com/vadz/libtiff/commit/b18012dae552f85dcc5c57d3bf4e997a15b1cc1c,libtiff/tif_next.c,cwe-787,780 cwe-078,initHeader," def initHeader(self): """"""Initialize the IP header according to the IP format definition. """""" # Ethernet header # Retrieve remote MAC address dstMacAddr = arpreq.arpreq(self.remoteIP) if dstMacAddr is not None: dstMacAddr = dstMacAddr.replace(':', '') dstMacAddr = binascii.unhexlify(dstMacAddr) else: # Force ARP resolution p = subprocess.Popen(""ping -c1 {}"".format(self.remoteIP), shell=True) p.wait() time.sleep(0.1) dstMacAddr = arpreq.arpreq(self.remoteIP) if dstMacAddr is not None: dstMacAddr = dstMacAddr.replace(':', '') dstMacAddr = binascii.unhexlify(dstMacAddr) else: raise Exception(""Cannot resolve IP address to a MAC address for IP: '{}'"".format(self.remoteIP)) # Retrieve local MAC address srcMacAddr = self.get_interface_addr(bytes(self.interface, 'utf-8'))[1] eth_dst = Field(name='eth.dst', domain=Raw(dstMacAddr)) eth_src = Field(name='eth.src', domain=Raw(srcMacAddr)) eth_type = Field(name='eth.type', domain=Raw(b""\x08\x00"")) # IP header ip_ver = Field( name='ip.version', domain=BitArray( value=bitarray('0100'))) # IP Version 4 ip_ihl = Field(name='ip.hdr_len', domain=BitArray(bitarray('0000'))) ip_tos = Field( name='ip.tos', domain=Data( dataType=BitArray(nbBits=8), originalValue=bitarray('00000000'), svas=SVAS.PERSISTENT)) ip_tot_len = Field( name='ip.len', domain=BitArray(bitarray('0000000000000000'))) ip_id = Field(name='ip.id', domain=BitArray(nbBits=16)) ip_flags = Field(name='ip.flags', domain=Data(dataType=BitArray(nbBits=3), originalValue=bitarray('000'), svas=SVAS.PERSISTENT)) ip_frag_off = Field(name='ip.fragment', domain=Data(dataType=BitArray(nbBits=13), originalValue=bitarray('0000000000000'), svas=SVAS.PERSISTENT)) ip_ttl = Field(name='ip.ttl', domain=Data(dataType=BitArray(nbBits=8), originalValue=bitarray('01000000'), svas=SVAS.PERSISTENT)) ip_proto = Field(name='ip.proto', domain=Integer(value=self.upperProtocol, unitSize=AbstractType.UNITSIZE_8, endianness=AbstractType.ENDIAN_BIG, sign=AbstractType.SIGN_UNSIGNED)) ip_checksum = Field(name='ip.checksum', domain=BitArray(bitarray('0000000000000000'))) ip_saddr = Field(name='ip.src', domain=IPv4(self.localIP)) ip_daddr = Field( name='ip.dst', domain=IPv4(self.remoteIP)) ip_payload = Field(name='ip.payload', domain=Raw()) ip_ihl.domain = Size([ip_ver, ip_ihl, ip_tos, ip_tot_len, ip_id, ip_flags, ip_frag_off, ip_ttl, ip_proto, ip_checksum, ip_saddr, ip_daddr], dataType=BitArray(nbBits=4), factor=1/float(32)) ip_tot_len.domain = Size([ip_ver, ip_ihl, ip_tos, ip_tot_len, ip_id, ip_flags, ip_frag_off, ip_ttl, ip_proto, ip_checksum, ip_saddr, ip_daddr, ip_payload], dataType=Integer(unitSize=AbstractType.UNITSIZE_16, sign=AbstractType.SIGN_UNSIGNED), factor=1/float(8)) ip_checksum.domain = InternetChecksum(fields=[ip_ver, ip_ihl, ip_tos, ip_tot_len, ip_id, ip_flags, ip_frag_off, ip_ttl, ip_proto, ip_checksum, ip_saddr, ip_daddr], dataType=Raw(nbBytes=2, unitSize=AbstractType.UNITSIZE_16)) self.header = Symbol(name='Ethernet layer', fields=[eth_dst, eth_src, eth_type, ip_ver, ip_ihl, ip_tos, ip_tot_len, ip_id, ip_flags, ip_frag_off, ip_ttl, ip_proto, ip_checksum, ip_saddr, ip_daddr, ip_payload])"," def initHeader(self): """"""Initialize the IP header according to the IP format definition. """""" # Ethernet header # Retrieve remote MAC address dstMacAddr = arpreq.arpreq(self.remoteIP) if dstMacAddr is not None: dstMacAddr = dstMacAddr.replace(':', '') dstMacAddr = binascii.unhexlify(dstMacAddr) else: # Force ARP resolution p = subprocess.Popen([""/bin/ping"", ""-c1"", self.remoteIP]) p.wait() time.sleep(0.1) dstMacAddr = arpreq.arpreq(self.remoteIP) if dstMacAddr is not None: dstMacAddr = dstMacAddr.replace(':', '') dstMacAddr = binascii.unhexlify(dstMacAddr) else: raise Exception(""Cannot resolve IP address to a MAC address for IP: '{}'"".format(self.remoteIP)) # Retrieve local MAC address srcMacAddr = self.get_interface_addr(bytes(self.interface, 'utf-8'))[1] eth_dst = Field(name='eth.dst', domain=Raw(dstMacAddr)) eth_src = Field(name='eth.src', domain=Raw(srcMacAddr)) eth_type = Field(name='eth.type', domain=Raw(b""\x08\x00"")) # IP header ip_ver = Field( name='ip.version', domain=BitArray( value=bitarray('0100'))) # IP Version 4 ip_ihl = Field(name='ip.hdr_len', domain=BitArray(bitarray('0000'))) ip_tos = Field( name='ip.tos', domain=Data( dataType=BitArray(nbBits=8), originalValue=bitarray('00000000'), svas=SVAS.PERSISTENT)) ip_tot_len = Field( name='ip.len', domain=BitArray(bitarray('0000000000000000'))) ip_id = Field(name='ip.id', domain=BitArray(nbBits=16)) ip_flags = Field(name='ip.flags', domain=Data(dataType=BitArray(nbBits=3), originalValue=bitarray('000'), svas=SVAS.PERSISTENT)) ip_frag_off = Field(name='ip.fragment', domain=Data(dataType=BitArray(nbBits=13), originalValue=bitarray('0000000000000'), svas=SVAS.PERSISTENT)) ip_ttl = Field(name='ip.ttl', domain=Data(dataType=BitArray(nbBits=8), originalValue=bitarray('01000000'), svas=SVAS.PERSISTENT)) ip_proto = Field(name='ip.proto', domain=Integer(value=self.upperProtocol, unitSize=AbstractType.UNITSIZE_8, endianness=AbstractType.ENDIAN_BIG, sign=AbstractType.SIGN_UNSIGNED)) ip_checksum = Field(name='ip.checksum', domain=BitArray(bitarray('0000000000000000'))) ip_saddr = Field(name='ip.src', domain=IPv4(self.localIP)) ip_daddr = Field( name='ip.dst', domain=IPv4(self.remoteIP)) ip_payload = Field(name='ip.payload', domain=Raw()) ip_ihl.domain = Size([ip_ver, ip_ihl, ip_tos, ip_tot_len, ip_id, ip_flags, ip_frag_off, ip_ttl, ip_proto, ip_checksum, ip_saddr, ip_daddr], dataType=BitArray(nbBits=4), factor=1/float(32)) ip_tot_len.domain = Size([ip_ver, ip_ihl, ip_tos, ip_tot_len, ip_id, ip_flags, ip_frag_off, ip_ttl, ip_proto, ip_checksum, ip_saddr, ip_daddr, ip_payload], dataType=Integer(unitSize=AbstractType.UNITSIZE_16, sign=AbstractType.SIGN_UNSIGNED), factor=1/float(8)) ip_checksum.domain = InternetChecksum(fields=[ip_ver, ip_ihl, ip_tos, ip_tot_len, ip_id, ip_flags, ip_frag_off, ip_ttl, ip_proto, ip_checksum, ip_saddr, ip_daddr], dataType=Raw(nbBytes=2, unitSize=AbstractType.UNITSIZE_16)) self.header = Symbol(name='Ethernet layer', fields=[eth_dst, eth_src, eth_type, ip_ver, ip_ihl, ip_tos, ip_tot_len, ip_id, ip_flags, ip_frag_off, ip_ttl, ip_proto, ip_checksum, ip_saddr, ip_daddr, ip_payload])","{'deleted': [{'line_no': 15, 'char_start': 423, 'char_end': 505, 'line': ' p = subprocess.Popen(""ping -c1 {}"".format(self.remoteIP), shell=True)\n'}], 'added': [{'line_no': 15, 'char_start': 423, 'char_end': 493, 'line': ' p = subprocess.Popen([""/bin/ping"", ""-c1"", self.remoteIP])\n'}]}","{'deleted': [{'char_start': 465, 'char_end': 468, 'chars': ' {}'}, {'char_start': 469, 'char_end': 477, 'chars': '.format('}, {'char_start': 490, 'char_end': 503, 'chars': '), shell=True'}], 'added': [{'char_start': 456, 'char_end': 457, 'chars': '['}, {'char_start': 458, 'char_end': 463, 'chars': '/bin/'}, {'char_start': 467, 'char_end': 469, 'chars': '"",'}, {'char_start': 470, 'char_end': 471, 'chars': '""'}, {'char_start': 475, 'char_end': 477, 'chars': ', '}, {'char_start': 490, 'char_end': 491, 'chars': ']'}]}",github.com/netzob/netzob/commit/557abf64867d715497979b029efedbd2777b912e,src/netzob/Simulator/Channels/RawEthernetClient.py,cwe-078,1073 cwe-078,_formatCredentials," def _formatCredentials(self, data, name): """""" Credentials are of the form RCLONE_CONFIG_CURRENT_TYPE=s3 ^ ^ ^ ^ [mandatory ][name ][key][value] """""" prefix = ""RCLONE_CONFIG_{}"".format(name.upper()) credentials = '' credentials += ""{}_TYPE='{}' "".format(prefix, data.type) def _addCredential(credentials, env_key, data_key): value = getattr(data, data_key, None) if value is not None: credentials += ""{}='{}' "".format(env_key, value) return credentials if data.type == 's3': credentials = _addCredential(credentials, '{}_REGION'.format(prefix), 's3_region' ) credentials = _addCredential(credentials, '{}_ACCESS_KEY_ID'.format(prefix), 's3_access_key_id' ) credentials = _addCredential(credentials, '{}_SECRET_ACCESS_KEY'.format(prefix), 's3_secret_access_key' ) credentials = _addCredential(credentials, '{}_ENDPOINT'.format(prefix), 's3_endpoint' ) credentials = _addCredential(credentials, '{}_V2_AUTH'.format(prefix), 's3_v2_auth' ) elif data.type == 'azureblob': credentials = _addCredential(credentials, '{}_ACCOUNT'.format(prefix), 'azure_account' ) credentials = _addCredential(credentials, '{}_KEY'.format(prefix), 'azure_key' ) elif data.type == 'swift': credentials = _addCredential(credentials, '{}_USER'.format(prefix), 'swift_user' ) credentials = _addCredential(credentials, '{}_KEY'.format(prefix), 'swift_key' ) credentials = _addCredential(credentials, '{}_AUTH'.format(prefix), 'swift_auth' ) credentials = _addCredential(credentials, '{}_TENANT'.format(prefix), 'swift_tenant' ) elif data.type == 'google cloud storage': credentials = _addCredential(credentials, '{}_CLIENT_ID'.format(prefix), 'gcp_client_id' ) credentials = _addCredential(credentials, '{}_SERVICE_ACCOUNT_CREDENTIALS'.format(prefix), 'gcp_service_account_credentials' ) credentials = _addCredential(credentials, '{}_PROJECT_NUMBER'.format(prefix), 'gcp_project_number' ) credentials = _addCredential(credentials, '{}_OBJECT_ACL'.format(prefix), 'gcp_object_acl' ) credentials = _addCredential(credentials, '{}_BUCKET_ACL'.format(prefix), 'gcp_bucket_acl' ) else: logging.error(""Connection type unknown: {}"".format(data.type)) return credentials"," def _formatCredentials(self, data, name): """""" Credentials are of the form RCLONE_CONFIG_CURRENT_TYPE=s3 ^ ^ ^ ^ [mandatory ][name ][key][value] """""" prefix = ""RCLONE_CONFIG_{}"".format(name.upper()) credentials = {} credentials['{}_TYPE'.format(prefix)] = data.type def _addCredential(credentials, env_key, data_key): value = getattr(data, data_key, None) if value is not None: credentials[env_key] = value return credentials if data.type == 's3': credentials = _addCredential(credentials, '{}_REGION'.format(prefix), 's3_region' ) credentials = _addCredential(credentials, '{}_ACCESS_KEY_ID'.format(prefix), 's3_access_key_id' ) credentials = _addCredential(credentials, '{}_SECRET_ACCESS_KEY'.format(prefix), 's3_secret_access_key' ) credentials = _addCredential(credentials, '{}_ENDPOINT'.format(prefix), 's3_endpoint' ) credentials = _addCredential(credentials, '{}_V2_AUTH'.format(prefix), 's3_v2_auth' ) elif data.type == 'azureblob': credentials = _addCredential(credentials, '{}_ACCOUNT'.format(prefix), 'azure_account' ) credentials = _addCredential(credentials, '{}_KEY'.format(prefix), 'azure_key' ) elif data.type == 'swift': credentials = _addCredential(credentials, '{}_USER'.format(prefix), 'swift_user' ) credentials = _addCredential(credentials, '{}_KEY'.format(prefix), 'swift_key' ) credentials = _addCredential(credentials, '{}_AUTH'.format(prefix), 'swift_auth' ) credentials = _addCredential(credentials, '{}_TENANT'.format(prefix), 'swift_tenant' ) elif data.type == 'google cloud storage': credentials = _addCredential(credentials, '{}_CLIENT_ID'.format(prefix), 'gcp_client_id' ) credentials = _addCredential(credentials, '{}_SERVICE_ACCOUNT_CREDENTIALS'.format(prefix), 'gcp_service_account_credentials' ) credentials = _addCredential(credentials, '{}_PROJECT_NUMBER'.format(prefix), 'gcp_project_number' ) credentials = _addCredential(credentials, '{}_OBJECT_ACL'.format(prefix), 'gcp_object_acl' ) credentials = _addCredential(credentials, '{}_BUCKET_ACL'.format(prefix), 'gcp_bucket_acl' ) else: logging.error(""Connection type unknown: {}"".format(data.type)) return credentials","{'deleted': [{'line_no': 11, 'char_start': 283, 'char_end': 308, 'line': "" credentials = ''\n""}, {'line_no': 12, 'char_start': 308, 'char_end': 373, 'line': ' credentials += ""{}_TYPE=\'{}\' "".format(prefix, data.type)\n'}, {'line_no': 17, 'char_start': 518, 'char_end': 583, 'line': ' credentials += ""{}=\'{}\' "".format(env_key, value)\n'}], 'added': [{'line_no': 11, 'char_start': 283, 'char_end': 308, 'line': ' credentials = {}\n'}, {'line_no': 12, 'char_start': 308, 'char_end': 366, 'line': "" credentials['{}_TYPE'.format(prefix)] = data.type\n""}, {'line_no': 17, 'char_start': 511, 'char_end': 556, 'line': ' credentials[env_key] = value\n'}]}","{'deleted': [{'char_start': 305, 'char_end': 307, 'chars': ""''""}, {'char_start': 327, 'char_end': 332, 'chars': ' += ""'}, {'char_start': 339, 'char_end': 340, 'chars': '='}, {'char_start': 341, 'char_end': 346, 'chars': '{}\' ""'}, {'char_start': 360, 'char_end': 361, 'chars': ','}, {'char_start': 371, 'char_end': 372, 'chars': ')'}, {'char_start': 545, 'char_end': 567, 'chars': ' += ""{}=\'{}\' "".format('}, {'char_start': 574, 'char_end': 575, 'chars': ','}, {'char_start': 581, 'char_end': 582, 'chars': ')'}], 'added': [{'char_start': 305, 'char_end': 307, 'chars': '{}'}, {'char_start': 327, 'char_end': 329, 'chars': ""['""}, {'char_start': 351, 'char_end': 355, 'chars': ')] ='}, {'char_start': 538, 'char_end': 539, 'chars': '['}, {'char_start': 546, 'char_end': 549, 'chars': '] ='}]}",github.com/FredHutch/motuz/commit/045468cb9bff47bb3bb72268b6d5a3fe44e383db,src/backend/api/utils/rclone_connection.py,cwe-078,599 cwe-125,enc_untrusted_inet_pton,"int enc_untrusted_inet_pton(int af, const char *src, void *dst) { if (!src || !dst) { return 0; } MessageWriter input; input.Push(TokLinuxAfFamily(af)); input.PushByReference(Extent{ src, std::min(strlen(src) + 1, static_cast(INET6_ADDRSTRLEN))}); MessageReader output; const auto status = NonSystemCallDispatcher( ::asylo::host_call::kInetPtonHandler, &input, &output); CheckStatusAndParamCount(status, output, ""enc_untrusted_inet_pton"", 3); int result = output.next(); int klinux_errno = output.next(); if (result == -1) { errno = FromkLinuxErrorNumber(klinux_errno); return -1; } auto klinux_addr_buffer = output.next(); size_t max_size = 0; if (af == AF_INET) { max_size = sizeof(struct in_addr); } else if (af == AF_INET6) { max_size = sizeof(struct in6_addr); } memcpy(dst, klinux_addr_buffer.data(), std::min(klinux_addr_buffer.size(), max_size)); return result; }","int enc_untrusted_inet_pton(int af, const char *src, void *dst) { if (!src || !dst) { return 0; } MessageWriter input; input.Push(TokLinuxAfFamily(af)); input.PushByReference(Extent{ src, std::min(strlen(src) + 1, static_cast(INET6_ADDRSTRLEN))}); MessageReader output; const auto status = NonSystemCallDispatcher( ::asylo::host_call::kInetPtonHandler, &input, &output); CheckStatusAndParamCount(status, output, ""enc_untrusted_inet_pton"", 3); int result = output.next(); int klinux_errno = output.next(); if (result == -1) { errno = FromkLinuxErrorNumber(klinux_errno); return -1; } auto klinux_addr_buffer = output.next(); size_t max_size = 0; if (af == AF_INET) { if (klinux_addr_buffer.size() != sizeof(klinux_in_addr)) { ::asylo::primitives::TrustedPrimitives::BestEffortAbort( ""enc_untrusted_inet_pton: unexpected output size""); } max_size = sizeof(struct in_addr); } else if (af == AF_INET6) { if (klinux_addr_buffer.size() != sizeof(klinux_in6_addr)) { ::asylo::primitives::TrustedPrimitives::BestEffortAbort( ""enc_untrusted_inet_pton: unexpected output size""); } max_size = sizeof(struct in6_addr); } memcpy(dst, klinux_addr_buffer.data(), std::min(klinux_addr_buffer.size(), max_size)); return result; }","{'deleted': [], 'added': [{'line_no': 26, 'char_start': 747, 'char_end': 810, 'line': ' if (klinux_addr_buffer.size() != sizeof(klinux_in_addr)) {\n'}, {'line_no': 27, 'char_start': 810, 'char_end': 873, 'line': ' ::asylo::primitives::TrustedPrimitives::BestEffortAbort(\n'}, {'line_no': 28, 'char_start': 873, 'char_end': 935, 'line': ' ""enc_untrusted_inet_pton: unexpected output size"");\n'}, {'line_no': 29, 'char_start': 935, 'char_end': 941, 'line': ' }\n'}, {'line_no': 32, 'char_start': 1011, 'char_end': 1075, 'line': ' if (klinux_addr_buffer.size() != sizeof(klinux_in6_addr)) {\n'}, {'line_no': 33, 'char_start': 1075, 'char_end': 1138, 'line': ' ::asylo::primitives::TrustedPrimitives::BestEffortAbort(\n'}, {'line_no': 34, 'char_start': 1138, 'char_end': 1200, 'line': ' ""enc_untrusted_inet_pton: unexpected output size"");\n'}, {'line_no': 35, 'char_start': 1200, 'char_end': 1206, 'line': ' }\n'}]}","{'deleted': [], 'added': [{'char_start': 751, 'char_end': 945, 'chars': 'if (klinux_addr_buffer.size() != sizeof(klinux_in_addr)) {\n ::asylo::primitives::TrustedPrimitives::BestEffortAbort(\n ""enc_untrusted_inet_pton: unexpected output size"");\n }\n '}, {'char_start': 1010, 'char_end': 1205, 'chars': '\n if (klinux_addr_buffer.size() != sizeof(klinux_in6_addr)) {\n ::asylo::primitives::TrustedPrimitives::BestEffortAbort(\n ""enc_untrusted_inet_pton: unexpected output size"");\n }'}]}",github.com/google/asylo/commit/8fed5e334131abaf9c5e17307642fbf6ce4a57ec,asylo/platform/host_call/trusted/host_calls.cc,cwe-125,280 cwe-089,add_translationname," def add_translationname(self, trname): """"""Add new translation by item name for an item."""""" if self.connection: for item in self.find_item_name([trname[0], '0']): self.cursor.execute('insert into itemtranslation (itemid, itemlanguageid, translation) values (""%s"", ""%s"", ""%s"")' % (item[0], trname[1], trname[2])) self.connection.commit()"," def add_translationname(self, trname): """"""Add new translation by item name for an item."""""" if self.connection: for item in self.find_item_name([trname[0], '0']): t = (item[0], trname[1], trname[2], ) self.cursor.execute('insert into itemtranslation (itemid, itemlanguageid, translation) values (?, ?, ?)', t) self.connection.commit()","{'deleted': [{'line_no': 5, 'char_start': 194, 'char_end': 359, 'line': ' self.cursor.execute(\'insert into itemtranslation (itemid, itemlanguageid, translation) values (""%s"", ""%s"", ""%s"")\' % (item[0], trname[1], trname[2]))\n'}], 'added': [{'line_no': 5, 'char_start': 194, 'char_end': 248, 'line': ' t = (item[0], trname[1], trname[2], )\n'}, {'line_no': 6, 'char_start': 248, 'char_end': 373, 'line': "" self.cursor.execute('insert into itemtranslation (itemid, itemlanguageid, translation) values (?, ?, ?)', t)\n""}, {'line_no': 7, 'char_start': 373, 'char_end': 409, 'line': ' self.connection.commit()\n'}]}","{'deleted': [{'char_start': 305, 'char_end': 309, 'chars': '""%s""'}, {'char_start': 311, 'char_end': 315, 'chars': '""%s""'}, {'char_start': 317, 'char_end': 321, 'chars': '""%s""'}, {'char_start': 323, 'char_end': 334, 'chars': ' % (item[0]'}, {'char_start': 337, 'char_end': 357, 'chars': 'rname[1], trname[2])'}], 'added': [{'char_start': 210, 'char_end': 264, 'chars': 't = (item[0], trname[1], trname[2], )\n '}, {'char_start': 359, 'char_end': 360, 'chars': '?'}, {'char_start': 362, 'char_end': 363, 'chars': '?'}, {'char_start': 365, 'char_end': 366, 'chars': '?'}]}",github.com/ecosl-developers/ecosl/commit/8af050a513338bf68ff2a243e4a2482d24e9aa3a,ecosldb/ecosldb.py,cwe-089,94 cwe-022,_inject_net_into_fs,"def _inject_net_into_fs(net, fs, execute=None): """"""Inject /etc/network/interfaces into the filesystem rooted at fs. net is the contents of /etc/network/interfaces. """""" netdir = os.path.join(os.path.join(fs, 'etc'), 'network') utils.execute('mkdir', '-p', netdir, run_as_root=True) utils.execute('chown', 'root:root', netdir, run_as_root=True) utils.execute('chmod', 755, netdir, run_as_root=True) netfile = os.path.join(netdir, 'interfaces') utils.execute('tee', netfile, process_input=net, run_as_root=True)","def _inject_net_into_fs(net, fs, execute=None): """"""Inject /etc/network/interfaces into the filesystem rooted at fs. net is the contents of /etc/network/interfaces. """""" netdir = _join_and_check_path_within_fs(fs, 'etc', 'network') utils.execute('mkdir', '-p', netdir, run_as_root=True) utils.execute('chown', 'root:root', netdir, run_as_root=True) utils.execute('chmod', 755, netdir, run_as_root=True) netfile = os.path.join('etc', 'network', 'interfaces') _inject_file_into_fs(fs, netfile, net)","{'deleted': [{'line_no': 6, 'char_start': 181, 'char_end': 243, 'line': "" netdir = os.path.join(os.path.join(fs, 'etc'), 'network')\n""}, {'line_no': 10, 'char_start': 426, 'char_end': 475, 'line': "" netfile = os.path.join(netdir, 'interfaces')\n""}, {'line_no': 11, 'char_start': 475, 'char_end': 545, 'line': "" utils.execute('tee', netfile, process_input=net, run_as_root=True)\n""}], 'added': [{'line_no': 6, 'char_start': 181, 'char_end': 247, 'line': "" netdir = _join_and_check_path_within_fs(fs, 'etc', 'network')\n""}, {'line_no': 10, 'char_start': 430, 'char_end': 431, 'line': '\n'}, {'line_no': 11, 'char_start': 431, 'char_end': 490, 'line': "" netfile = os.path.join('etc', 'network', 'interfaces')\n""}, {'line_no': 12, 'char_start': 490, 'char_end': 532, 'line': ' _inject_file_into_fs(fs, netfile, net)\n'}]}","{'deleted': [{'char_start': 194, 'char_end': 202, 'chars': 'os.path.'}, {'char_start': 206, 'char_end': 210, 'chars': '(os.'}, {'char_start': 214, 'char_end': 217, 'chars': '.jo'}, {'char_start': 229, 'char_end': 230, 'chars': ')'}, {'char_start': 456, 'char_end': 458, 'chars': 'di'}, {'char_start': 479, 'char_end': 480, 'chars': 'u'}, {'char_start': 483, 'char_end': 485, 'chars': 's.'}, {'char_start': 486, 'char_end': 490, 'chars': 'xecu'}, {'char_start': 491, 'char_end': 492, 'chars': 'e'}, {'char_start': 493, 'char_end': 498, 'chars': ""'tee'""}, {'char_start': 509, 'char_end': 523, 'chars': 'process_input='}, {'char_start': 526, 'char_end': 544, 'chars': ', run_as_root=True'}], 'added': [{'char_start': 194, 'char_end': 196, 'chars': '_j'}, {'char_start': 197, 'char_end': 210, 'chars': 'in_and_check_'}, {'char_start': 214, 'char_end': 216, 'chars': '_w'}, {'char_start': 221, 'char_end': 224, 'chars': '_fs'}, {'char_start': 430, 'char_end': 431, 'chars': '\n'}, {'char_start': 458, 'char_end': 466, 'chars': ""'etc', '""}, {'char_start': 469, 'char_end': 471, 'chars': 'wo'}, {'char_start': 472, 'char_end': 474, 'chars': ""k'""}, {'char_start': 494, 'char_end': 495, 'chars': '_'}, {'char_start': 496, 'char_end': 498, 'chars': 'nj'}, {'char_start': 501, 'char_end': 505, 'chars': '_fil'}, {'char_start': 506, 'char_end': 509, 'chars': '_in'}, {'char_start': 510, 'char_end': 517, 'chars': 'o_fs(fs'}]}",github.com/openstack/nova/commit/2427d4a99bed35baefd8f17ba422cb7aae8dcca7,nova/virt/disk/api.py,cwe-022,146 cwe-079,link_dialog,"def link_dialog(request): # list of wiki pages name = request.values.get(""pagename"", """") if name: from MoinMoin import search # XXX error handling! searchresult = search.searchPages(request, 't:""%s""' % name) pages = [p.page_name for p in searchresult.hits] pages.sort() pages[0:0] = [name] page_list = ''' ''' % ""\n"".join(['' % (wikiutil.escape(page), wikiutil.escape(page)) for page in pages]) else: page_list = """" # list of interwiki names interwiki_list = wikiutil.load_wikimap(request) interwiki = interwiki_list.keys() interwiki.sort() iwpreferred = request.cfg.interwiki_preferred[:] if not iwpreferred or iwpreferred and iwpreferred[-1] is not None: resultlist = iwpreferred for iw in interwiki: if not iw in iwpreferred: resultlist.append(iw) else: resultlist = iwpreferred[:-1] interwiki = ""\n"".join( ['' % (wikiutil.escape(key), wikiutil.escape(key)) for key in resultlist]) # wiki url url_prefix_static = request.cfg.url_prefix_static scriptname = request.script_root + '/' action = scriptname basepage = wikiutil.escape(request.page.page_name) request.write(u''' Link Properties
Link Type


%(page_list)s
Page Name
Wiki:PageName
:
Protocol
  URL

''' % locals())","def link_dialog(request): # list of wiki pages name = request.values.get(""pagename"", """") name_escaped = wikiutil.escape(name) if name: from MoinMoin import search # XXX error handling! searchresult = search.searchPages(request, 't:""%s""' % name) pages = [p.page_name for p in searchresult.hits] pages.sort() pages[0:0] = [name] page_list = ''' ''' % ""\n"".join(['' % (wikiutil.escape(page), wikiutil.escape(page)) for page in pages]) else: page_list = """" # list of interwiki names interwiki_list = wikiutil.load_wikimap(request) interwiki = interwiki_list.keys() interwiki.sort() iwpreferred = request.cfg.interwiki_preferred[:] if not iwpreferred or iwpreferred and iwpreferred[-1] is not None: resultlist = iwpreferred for iw in interwiki: if not iw in iwpreferred: resultlist.append(iw) else: resultlist = iwpreferred[:-1] interwiki = ""\n"".join( ['' % (wikiutil.escape(key), wikiutil.escape(key)) for key in resultlist]) # wiki url url_prefix_static = request.cfg.url_prefix_static scriptname = request.script_root + '/' action = scriptname basepage = wikiutil.escape(request.page.page_name) request.write(u''' Link Properties
Link Type


%(page_list)s
Page Name
Wiki:PageName
:
Protocol
  URL

''' % locals())","{'deleted': [{'line_no': 100, 'char_start': 3711, 'char_end': 3789, 'line': ' \n'}], 'added': [{'line_no': 4, 'char_start': 97, 'char_end': 138, 'line': ' name_escaped = wikiutil.escape(name)\n'}, {'line_no': 101, 'char_start': 3752, 'char_end': 3838, 'line': ' \n'}]}","{'deleted': [], 'added': [{'char_start': 101, 'char_end': 142, 'chars': 'name_escaped = wikiutil.escape(name)\n '}, {'char_start': 3825, 'char_end': 3833, 'chars': '_escaped'}]}",github.com/moinwiki/moin-1.9/commit/70955a8eae091cc88fd9a6e510177e70289ec024,MoinMoin/action/fckdialog.py,cwe-079,1565 cwe-416,tcpmss_mangle_packet,"tcpmss_mangle_packet(struct sk_buff *skb, const struct xt_action_param *par, unsigned int family, unsigned int tcphoff, unsigned int minlen) { const struct xt_tcpmss_info *info = par->targinfo; struct tcphdr *tcph; int len, tcp_hdrlen; unsigned int i; __be16 oldval; u16 newmss; u8 *opt; /* This is a fragment, no TCP header is available */ if (par->fragoff != 0) return 0; if (!skb_make_writable(skb, skb->len)) return -1; len = skb->len - tcphoff; if (len < (int)sizeof(struct tcphdr)) return -1; tcph = (struct tcphdr *)(skb_network_header(skb) + tcphoff); tcp_hdrlen = tcph->doff * 4; if (len < tcp_hdrlen) return -1; if (info->mss == XT_TCPMSS_CLAMP_PMTU) { struct net *net = xt_net(par); unsigned int in_mtu = tcpmss_reverse_mtu(net, skb, family); unsigned int min_mtu = min(dst_mtu(skb_dst(skb)), in_mtu); if (min_mtu <= minlen) { net_err_ratelimited(""unknown or invalid path-MTU (%u)\n"", min_mtu); return -1; } newmss = min_mtu - minlen; } else newmss = info->mss; opt = (u_int8_t *)tcph; for (i = sizeof(struct tcphdr); i <= tcp_hdrlen - TCPOLEN_MSS; i += optlen(opt, i)) { if (opt[i] == TCPOPT_MSS && opt[i+1] == TCPOLEN_MSS) { u_int16_t oldmss; oldmss = (opt[i+2] << 8) | opt[i+3]; /* Never increase MSS, even when setting it, as * doing so results in problems for hosts that rely * on MSS being set correctly. */ if (oldmss <= newmss) return 0; opt[i+2] = (newmss & 0xff00) >> 8; opt[i+3] = newmss & 0x00ff; inet_proto_csum_replace2(&tcph->check, skb, htons(oldmss), htons(newmss), false); return 0; } } /* There is data after the header so the option can't be added * without moving it, and doing so may make the SYN packet * itself too large. Accept the packet unmodified instead. */ if (len > tcp_hdrlen) return 0; /* * MSS Option not found ?! add it.. */ if (skb_tailroom(skb) < TCPOLEN_MSS) { if (pskb_expand_head(skb, 0, TCPOLEN_MSS - skb_tailroom(skb), GFP_ATOMIC)) return -1; tcph = (struct tcphdr *)(skb_network_header(skb) + tcphoff); } skb_put(skb, TCPOLEN_MSS); /* * IPv4: RFC 1122 states ""If an MSS option is not received at * connection setup, TCP MUST assume a default send MSS of 536"". * IPv6: RFC 2460 states IPv6 has a minimum MTU of 1280 and a minimum * length IPv6 header of 60, ergo the default MSS value is 1220 * Since no MSS was provided, we must use the default values */ if (xt_family(par) == NFPROTO_IPV4) newmss = min(newmss, (u16)536); else newmss = min(newmss, (u16)1220); opt = (u_int8_t *)tcph + sizeof(struct tcphdr); memmove(opt + TCPOLEN_MSS, opt, len - sizeof(struct tcphdr)); inet_proto_csum_replace2(&tcph->check, skb, htons(len), htons(len + TCPOLEN_MSS), true); opt[0] = TCPOPT_MSS; opt[1] = TCPOLEN_MSS; opt[2] = (newmss & 0xff00) >> 8; opt[3] = newmss & 0x00ff; inet_proto_csum_replace4(&tcph->check, skb, 0, *((__be32 *)opt), false); oldval = ((__be16 *)tcph)[6]; tcph->doff += TCPOLEN_MSS/4; inet_proto_csum_replace2(&tcph->check, skb, oldval, ((__be16 *)tcph)[6], false); return TCPOLEN_MSS; }","tcpmss_mangle_packet(struct sk_buff *skb, const struct xt_action_param *par, unsigned int family, unsigned int tcphoff, unsigned int minlen) { const struct xt_tcpmss_info *info = par->targinfo; struct tcphdr *tcph; int len, tcp_hdrlen; unsigned int i; __be16 oldval; u16 newmss; u8 *opt; /* This is a fragment, no TCP header is available */ if (par->fragoff != 0) return 0; if (!skb_make_writable(skb, skb->len)) return -1; len = skb->len - tcphoff; if (len < (int)sizeof(struct tcphdr)) return -1; tcph = (struct tcphdr *)(skb_network_header(skb) + tcphoff); tcp_hdrlen = tcph->doff * 4; if (len < tcp_hdrlen || tcp_hdrlen < sizeof(struct tcphdr)) return -1; if (info->mss == XT_TCPMSS_CLAMP_PMTU) { struct net *net = xt_net(par); unsigned int in_mtu = tcpmss_reverse_mtu(net, skb, family); unsigned int min_mtu = min(dst_mtu(skb_dst(skb)), in_mtu); if (min_mtu <= minlen) { net_err_ratelimited(""unknown or invalid path-MTU (%u)\n"", min_mtu); return -1; } newmss = min_mtu - minlen; } else newmss = info->mss; opt = (u_int8_t *)tcph; for (i = sizeof(struct tcphdr); i <= tcp_hdrlen - TCPOLEN_MSS; i += optlen(opt, i)) { if (opt[i] == TCPOPT_MSS && opt[i+1] == TCPOLEN_MSS) { u_int16_t oldmss; oldmss = (opt[i+2] << 8) | opt[i+3]; /* Never increase MSS, even when setting it, as * doing so results in problems for hosts that rely * on MSS being set correctly. */ if (oldmss <= newmss) return 0; opt[i+2] = (newmss & 0xff00) >> 8; opt[i+3] = newmss & 0x00ff; inet_proto_csum_replace2(&tcph->check, skb, htons(oldmss), htons(newmss), false); return 0; } } /* There is data after the header so the option can't be added * without moving it, and doing so may make the SYN packet * itself too large. Accept the packet unmodified instead. */ if (len > tcp_hdrlen) return 0; /* tcph->doff has 4 bits, do not wrap it to 0 */ if (tcp_hdrlen >= 15 * 4) return 0; /* * MSS Option not found ?! add it.. */ if (skb_tailroom(skb) < TCPOLEN_MSS) { if (pskb_expand_head(skb, 0, TCPOLEN_MSS - skb_tailroom(skb), GFP_ATOMIC)) return -1; tcph = (struct tcphdr *)(skb_network_header(skb) + tcphoff); } skb_put(skb, TCPOLEN_MSS); /* * IPv4: RFC 1122 states ""If an MSS option is not received at * connection setup, TCP MUST assume a default send MSS of 536"". * IPv6: RFC 2460 states IPv6 has a minimum MTU of 1280 and a minimum * length IPv6 header of 60, ergo the default MSS value is 1220 * Since no MSS was provided, we must use the default values */ if (xt_family(par) == NFPROTO_IPV4) newmss = min(newmss, (u16)536); else newmss = min(newmss, (u16)1220); opt = (u_int8_t *)tcph + sizeof(struct tcphdr); memmove(opt + TCPOLEN_MSS, opt, len - sizeof(struct tcphdr)); inet_proto_csum_replace2(&tcph->check, skb, htons(len), htons(len + TCPOLEN_MSS), true); opt[0] = TCPOPT_MSS; opt[1] = TCPOLEN_MSS; opt[2] = (newmss & 0xff00) >> 8; opt[3] = newmss & 0x00ff; inet_proto_csum_replace4(&tcph->check, skb, 0, *((__be32 *)opt), false); oldval = ((__be16 *)tcph)[6]; tcph->doff += TCPOLEN_MSS/4; inet_proto_csum_replace2(&tcph->check, skb, oldval, ((__be16 *)tcph)[6], false); return TCPOLEN_MSS; }","{'deleted': [{'line_no': 29, 'char_start': 642, 'char_end': 665, 'line': '\tif (len < tcp_hdrlen)\n'}], 'added': [{'line_no': 29, 'char_start': 642, 'char_end': 703, 'line': '\tif (len < tcp_hdrlen || tcp_hdrlen < sizeof(struct tcphdr))\n'}, {'line_no': 77, 'char_start': 1935, 'char_end': 1985, 'line': '\t/* tcph->doff has 4 bits, do not wrap it to 0 */\n'}, {'line_no': 78, 'char_start': 1985, 'char_end': 2012, 'line': '\tif (tcp_hdrlen >= 15 * 4)\n'}, {'line_no': 79, 'char_start': 2012, 'char_end': 2024, 'line': '\t\treturn 0;\n'}, {'line_no': 80, 'char_start': 2024, 'char_end': 2025, 'line': '\n'}]}","{'deleted': [], 'added': [{'char_start': 663, 'char_end': 701, 'chars': ' || tcp_hdrlen < sizeof(struct tcphdr)'}, {'char_start': 1920, 'char_end': 2010, 'chars': ')\n\t\treturn 0;\n\n\t/* tcph->doff has 4 bits, do not wrap it to 0 */\n\tif (tcp_hdrlen >= 15 * 4'}]}",github.com/torvalds/linux/commit/2638fd0f92d4397884fd991d8f4925cb3f081901,net/netfilter/xt_TCPMSS.c,cwe-416,1117 cwe-089,new_category,"def new_category(category_name): try: conn = check_heroku_db() cur = conn.cursor() cur.execute('''INSERT INTO categories (cat_name) VALUES (%s)''', (category_name,)) conn.commit() conn.close() except psycopg2.DatabaseError as e: print('Error %s' % e) sys.exit(1)","def new_category(category_name): try: conn = check_heroku_db() cur = conn.cursor() query = ""INSERT INTO categories (cat_name) VALUES (%s);"" data = (category_name,) cur.execute(query, data) conn.commit() conn.close() except psycopg2.DatabaseError as e: print('Error %s' % e) sys.exit(1)","{'deleted': [{'line_no': 5, 'char_start': 103, 'char_end': 194, 'line': "" cur.execute('''INSERT INTO categories (cat_name) VALUES (%s)''', (category_name,))\n""}], 'added': [{'line_no': 5, 'char_start': 103, 'char_end': 104, 'line': '\n'}, {'line_no': 6, 'char_start': 104, 'char_end': 169, 'line': ' query = ""INSERT INTO categories (cat_name) VALUES (%s);""\n'}, {'line_no': 7, 'char_start': 169, 'char_end': 201, 'line': ' data = (category_name,)\n'}, {'line_no': 8, 'char_start': 201, 'char_end': 234, 'line': ' cur.execute(query, data)\n'}, {'line_no': 9, 'char_start': 234, 'char_end': 235, 'line': '\n'}]}","{'deleted': [{'char_start': 111, 'char_end': 112, 'chars': 'c'}, {'char_start': 114, 'char_end': 126, 'chars': "".execute('''""}, {'char_start': 171, 'char_end': 175, 'chars': ""''',""}], 'added': [{'char_start': 103, 'char_end': 104, 'chars': '\n'}, {'char_start': 112, 'char_end': 113, 'chars': 'q'}, {'char_start': 115, 'char_end': 121, 'chars': 'ry = ""'}, {'char_start': 166, 'char_end': 183, 'chars': ';""\n data ='}, {'char_start': 200, 'char_end': 232, 'chars': '\n cur.execute(query, data'}, {'char_start': 233, 'char_end': 234, 'chars': '\n'}]}",github.com/leeorb321/expenses/commit/f93c0fa4d30787ef16420bfefc52565b98bc7fcf,db.py,cwe-089,78 cwe-476,expand_downwards,"int expand_downwards(struct vm_area_struct *vma, unsigned long address) { struct mm_struct *mm = vma->vm_mm; struct vm_area_struct *prev; int error; address &= PAGE_MASK; error = security_mmap_addr(address); if (error) return error; /* Enforce stack_guard_gap */ prev = vma->vm_prev; /* Check that both stack segments have the same anon_vma? */ if (prev && !(prev->vm_flags & VM_GROWSDOWN) && (prev->vm_flags & (VM_WRITE|VM_READ|VM_EXEC))) { if (address - prev->vm_end < stack_guard_gap) return -ENOMEM; } /* We must make sure the anon_vma is allocated. */ if (unlikely(anon_vma_prepare(vma))) return -ENOMEM; /* * vma->vm_start/vm_end cannot change under us because the caller * is required to hold the mmap_sem in read mode. We need the * anon_vma lock to serialize against concurrent expand_stacks. */ anon_vma_lock_write(vma->anon_vma); /* Somebody else might have raced and expanded it already */ if (address < vma->vm_start) { unsigned long size, grow; size = vma->vm_end - address; grow = (vma->vm_start - address) >> PAGE_SHIFT; error = -ENOMEM; if (grow <= vma->vm_pgoff) { error = acct_stack_growth(vma, size, grow); if (!error) { /* * vma_gap_update() doesn't support concurrent * updates, but we only hold a shared mmap_sem * lock here, so we need to protect against * concurrent vma expansions. * anon_vma_lock_write() doesn't help here, as * we don't guarantee that all growable vmas * in a mm share the same root anon vma. * So, we reuse mm->page_table_lock to guard * against concurrent vma expansions. */ spin_lock(&mm->page_table_lock); if (vma->vm_flags & VM_LOCKED) mm->locked_vm += grow; vm_stat_account(mm, vma->vm_flags, grow); anon_vma_interval_tree_pre_update_vma(vma); vma->vm_start = address; vma->vm_pgoff -= grow; anon_vma_interval_tree_post_update_vma(vma); vma_gap_update(vma); spin_unlock(&mm->page_table_lock); perf_event_mmap(vma); } } } anon_vma_unlock_write(vma->anon_vma); khugepaged_enter_vma_merge(vma, vma->vm_flags); validate_mm(mm); return error; }","int expand_downwards(struct vm_area_struct *vma, unsigned long address) { struct mm_struct *mm = vma->vm_mm; struct vm_area_struct *prev; int error = 0; address &= PAGE_MASK; if (address < mmap_min_addr) return -EPERM; /* Enforce stack_guard_gap */ prev = vma->vm_prev; /* Check that both stack segments have the same anon_vma? */ if (prev && !(prev->vm_flags & VM_GROWSDOWN) && (prev->vm_flags & (VM_WRITE|VM_READ|VM_EXEC))) { if (address - prev->vm_end < stack_guard_gap) return -ENOMEM; } /* We must make sure the anon_vma is allocated. */ if (unlikely(anon_vma_prepare(vma))) return -ENOMEM; /* * vma->vm_start/vm_end cannot change under us because the caller * is required to hold the mmap_sem in read mode. We need the * anon_vma lock to serialize against concurrent expand_stacks. */ anon_vma_lock_write(vma->anon_vma); /* Somebody else might have raced and expanded it already */ if (address < vma->vm_start) { unsigned long size, grow; size = vma->vm_end - address; grow = (vma->vm_start - address) >> PAGE_SHIFT; error = -ENOMEM; if (grow <= vma->vm_pgoff) { error = acct_stack_growth(vma, size, grow); if (!error) { /* * vma_gap_update() doesn't support concurrent * updates, but we only hold a shared mmap_sem * lock here, so we need to protect against * concurrent vma expansions. * anon_vma_lock_write() doesn't help here, as * we don't guarantee that all growable vmas * in a mm share the same root anon vma. * So, we reuse mm->page_table_lock to guard * against concurrent vma expansions. */ spin_lock(&mm->page_table_lock); if (vma->vm_flags & VM_LOCKED) mm->locked_vm += grow; vm_stat_account(mm, vma->vm_flags, grow); anon_vma_interval_tree_pre_update_vma(vma); vma->vm_start = address; vma->vm_pgoff -= grow; anon_vma_interval_tree_post_update_vma(vma); vma_gap_update(vma); spin_unlock(&mm->page_table_lock); perf_event_mmap(vma); } } } anon_vma_unlock_write(vma->anon_vma); khugepaged_enter_vma_merge(vma, vma->vm_flags); validate_mm(mm); return error; }","{'deleted': [{'line_no': 6, 'char_start': 147, 'char_end': 159, 'line': '\tint error;\n'}, {'line_no': 9, 'char_start': 183, 'char_end': 221, 'line': '\terror = security_mmap_addr(address);\n'}, {'line_no': 10, 'char_start': 221, 'char_end': 233, 'line': '\tif (error)\n'}, {'line_no': 11, 'char_start': 233, 'char_end': 249, 'line': '\t\treturn error;\n'}], 'added': [{'line_no': 6, 'char_start': 147, 'char_end': 163, 'line': '\tint error = 0;\n'}, {'line_no': 9, 'char_start': 187, 'char_end': 217, 'line': '\tif (address < mmap_min_addr)\n'}, {'line_no': 10, 'char_start': 217, 'char_end': 234, 'line': '\t\treturn -EPERM;\n'}]}","{'deleted': [{'char_start': 185, 'char_end': 189, 'chars': 'rror'}, {'char_start': 190, 'char_end': 191, 'chars': '='}, {'char_start': 192, 'char_end': 201, 'chars': 'security_'}, {'char_start': 210, 'char_end': 231, 'chars': '(address);\n\tif (error'}, {'char_start': 242, 'char_end': 247, 'chars': 'error'}], 'added': [{'char_start': 157, 'char_end': 161, 'chars': ' = 0'}, {'char_start': 188, 'char_end': 195, 'chars': 'if (add'}, {'char_start': 196, 'char_end': 199, 'chars': 'ess'}, {'char_start': 200, 'char_end': 201, 'chars': '<'}, {'char_start': 207, 'char_end': 211, 'chars': 'min_'}, {'char_start': 226, 'char_end': 232, 'chars': '-EPERM'}]}",github.com/torvalds/linux/commit/0a1d52994d440e21def1c2174932410b4f2a98a1,mm/mmap.c,cwe-476,619 cwe-022,get," def get(self, key): try: result = self.etcd.get(os.path.join(self.namespace, key)) except etcd.EtcdException as err: log_error(""Error fetching key %s: [%r]"" % (key, repr(err))) raise CSStoreError('Error occurred while trying to get key') return result.value"," def get(self, key): try: result = self.etcd.get(self._absolute_key(key)) except etcd.EtcdException as err: log_error(""Error fetching key %s: [%r]"" % (key, repr(err))) raise CSStoreError('Error occurred while trying to get key') return result.value","{'deleted': [{'line_no': 3, 'char_start': 37, 'char_end': 107, 'line': ' result = self.etcd.get(os.path.join(self.namespace, key))\n'}], 'added': [{'line_no': 3, 'char_start': 37, 'char_end': 97, 'line': ' result = self.etcd.get(self._absolute_key(key))\n'}]}","{'deleted': [{'char_start': 72, 'char_end': 85, 'chars': 'os.path.join('}, {'char_start': 90, 'char_end': 91, 'chars': 'n'}, {'char_start': 92, 'char_end': 94, 'chars': 'me'}, {'char_start': 95, 'char_end': 98, 'chars': 'pac'}, {'char_start': 99, 'char_end': 101, 'chars': ', '}], 'added': [{'char_start': 77, 'char_end': 78, 'chars': '_'}, {'char_start': 79, 'char_end': 85, 'chars': 'bsolut'}, {'char_start': 86, 'char_end': 88, 'chars': '_k'}, {'char_start': 89, 'char_end': 91, 'chars': 'y('}]}",github.com/latchset/custodia/commit/785fc87f38b4811bc4ce43a0a9b2267ee7d500b4,custodia/store/etcdstore.py,cwe-022,74 cwe-089,post," def post(self): """""" Returns JWT upon login verification """""" json_data = request.get_json() if not json_data['email']: return jsonify({""msg"": ""Missing email""}), 400 data = database_utilities.execute_query( f""""""select * from admins where email = '{json_data['email']}'"""""") if data: email = data[0]['email'] access_token = create_access_token(identity=email) refresh_token = create_refresh_token(identity=email) resp = jsonify({""login"": True}) set_access_cookies(resp, access_token) set_refresh_cookies(resp, refresh_token) return resp else: return jsonify({""msg"": ""User is not an admin""})"," def post(self): """""" Returns JWT upon login verification """""" json_data = request.get_json() if not json_data['email']: return jsonify({""msg"": ""Missing email""}), 400 data = database_utilities.execute_query( f""""""select * from admins where email = %s"""""", (json_data['email'], )) if data: email = data[0]['email'] access_token = create_access_token(identity=email) refresh_token = create_refresh_token(identity=email) resp = jsonify({""login"": True}) set_access_cookies(resp, access_token) set_refresh_cookies(resp, refresh_token) return resp else: return jsonify({""msg"": ""User is not an admin""})","{'deleted': [{'line_no': 8, 'char_start': 254, 'char_end': 332, 'line': ' f""""""select * from admins where email = \'{json_data[\'email\']}\'"""""")\n'}], 'added': [{'line_no': 8, 'char_start': 254, 'char_end': 336, 'line': ' f""""""select * from admins where email = %s"""""", (json_data[\'email\'], ))\n'}]}","{'deleted': [{'char_start': 305, 'char_end': 307, 'chars': ""'{""}, {'char_start': 325, 'char_end': 330, 'chars': '}\'""""""'}], 'added': [{'char_start': 305, 'char_end': 313, 'chars': '%s"""""", ('}, {'char_start': 331, 'char_end': 334, 'chars': ', )'}]}",github.com/sgosal2/tiger-boards-backend/commit/4670109dd613df2f2fe7e8403ebd149df2b55485,apis/login.py,cwe-089,150 cwe-089,get_roster," def get_roster(self, server_id): sql = """"""SELECT username, role FROM roles WHERE roles.server_id = {0}; """""".format(server_id) self.cur.execute(sql) return self.cur.fetchall()"," def get_roster(self, server_id): sql = """""" SELECT username, role FROM roles WHERE roles.server_id = %s; """""" self.cur.execute(sql, (server_id,)) return self.cur.fetchall()","{'deleted': [{'line_no': 2, 'char_start': 37, 'char_end': 76, 'line': ' sql = """"""SELECT username, role\n'}, {'line_no': 3, 'char_start': 76, 'char_end': 104, 'line': ' FROM roles\n'}, {'line_no': 4, 'char_start': 104, 'char_end': 150, 'line': ' WHERE roles.server_id = {0};\n'}, {'line_no': 5, 'char_start': 150, 'char_end': 189, 'line': ' """""".format(server_id)\n'}, {'line_no': 6, 'char_start': 189, 'char_end': 219, 'line': ' self.cur.execute(sql)\n'}], 'added': [{'line_no': 2, 'char_start': 37, 'char_end': 55, 'line': ' sql = """"""\n'}, {'line_no': 3, 'char_start': 55, 'char_end': 91, 'line': ' SELECT username, role\n'}, {'line_no': 4, 'char_start': 91, 'char_end': 116, 'line': ' FROM roles\n'}, {'line_no': 5, 'char_start': 116, 'char_end': 158, 'line': ' WHERE roles.server_id = %s;\n'}, {'line_no': 6, 'char_start': 158, 'char_end': 176, 'line': ' """"""\n'}, {'line_no': 7, 'char_start': 176, 'char_end': 220, 'line': ' self.cur.execute(sql, (server_id,))\n'}]}","{'deleted': [{'char_start': 76, 'char_end': 77, 'chars': ' '}, {'char_start': 91, 'char_end': 93, 'chars': ' '}, {'char_start': 104, 'char_end': 107, 'chars': ' '}, {'char_start': 145, 'char_end': 148, 'chars': '{0}'}, {'char_start': 150, 'char_end': 153, 'chars': ' '}, {'char_start': 170, 'char_end': 188, 'chars': '.format(server_id)'}], 'added': [{'char_start': 54, 'char_end': 69, 'chars': '\n '}, {'char_start': 154, 'char_end': 156, 'chars': '%s'}, {'char_start': 204, 'char_end': 218, 'chars': ', (server_id,)'}]}",github.com/jgayfer/spirit/commit/01c846c534c8d3cf6763f8b7444a0efe2caa3799,db/dbase.py,cwe-089,50 cwe-022,dd_save_binary,"void dd_save_binary(struct dump_dir* dd, const char* name, const char* data, unsigned size) { if (!dd->locked) error_msg_and_die(""dump_dir is not opened""); /* bug */ char *full_path = concat_path_file(dd->dd_dirname, name); save_binary_file(full_path, data, size, dd->dd_uid, dd->dd_gid, dd->mode); free(full_path); }","void dd_save_binary(struct dump_dir* dd, const char* name, const char* data, unsigned size) { if (!dd->locked) error_msg_and_die(""dump_dir is not opened""); /* bug */ if (!str_is_correct_filename(name)) error_msg_and_die(""Cannot save binary. '%s' is not a valid file name"", name); char *full_path = concat_path_file(dd->dd_dirname, name); save_binary_file(full_path, data, size, dd->dd_uid, dd->dd_gid, dd->mode); free(full_path); }","{'deleted': [], 'added': [{'line_no': 6, 'char_start': 179, 'char_end': 219, 'line': ' if (!str_is_correct_filename(name))\n'}, {'line_no': 7, 'char_start': 219, 'char_end': 305, 'line': ' error_msg_and_die(""Cannot save binary. \'%s\' is not a valid file name"", name);\n'}, {'line_no': 8, 'char_start': 305, 'char_end': 306, 'line': '\n'}]}","{'deleted': [], 'added': [{'char_start': 183, 'char_end': 310, 'chars': 'if (!str_is_correct_filename(name))\n error_msg_and_die(""Cannot save binary. \'%s\' is not a valid file name"", name);\n\n '}]}",github.com/abrt/libreport/commit/239c4f7d1f47265526b39ad70106767d00805277,src/lib/dump_dir.c,cwe-022,94 cwe-190,read_entry,"static int read_entry( git_index_entry **out, size_t *out_size, git_index *index, const void *buffer, size_t buffer_size, const char *last) { size_t path_length, entry_size; const char *path_ptr; struct entry_short source; git_index_entry entry = {{0}}; bool compressed = index->version >= INDEX_VERSION_NUMBER_COMP; char *tmp_path = NULL; if (INDEX_FOOTER_SIZE + minimal_entry_size > buffer_size) return -1; /* buffer is not guaranteed to be aligned */ memcpy(&source, buffer, sizeof(struct entry_short)); entry.ctime.seconds = (git_time_t)ntohl(source.ctime.seconds); entry.ctime.nanoseconds = ntohl(source.ctime.nanoseconds); entry.mtime.seconds = (git_time_t)ntohl(source.mtime.seconds); entry.mtime.nanoseconds = ntohl(source.mtime.nanoseconds); entry.dev = ntohl(source.dev); entry.ino = ntohl(source.ino); entry.mode = ntohl(source.mode); entry.uid = ntohl(source.uid); entry.gid = ntohl(source.gid); entry.file_size = ntohl(source.file_size); git_oid_cpy(&entry.id, &source.oid); entry.flags = ntohs(source.flags); if (entry.flags & GIT_IDXENTRY_EXTENDED) { uint16_t flags_raw; size_t flags_offset; flags_offset = offsetof(struct entry_long, flags_extended); memcpy(&flags_raw, (const char *) buffer + flags_offset, sizeof(flags_raw)); flags_raw = ntohs(flags_raw); memcpy(&entry.flags_extended, &flags_raw, sizeof(flags_raw)); path_ptr = (const char *) buffer + offsetof(struct entry_long, path); } else path_ptr = (const char *) buffer + offsetof(struct entry_short, path); if (!compressed) { path_length = entry.flags & GIT_IDXENTRY_NAMEMASK; /* if this is a very long string, we must find its * real length without overflowing */ if (path_length == 0xFFF) { const char *path_end; path_end = memchr(path_ptr, '\0', buffer_size); if (path_end == NULL) return -1; path_length = path_end - path_ptr; } entry_size = index_entry_size(path_length, 0, entry.flags); entry.path = (char *)path_ptr; } else { size_t varint_len; size_t strip_len = git_decode_varint((const unsigned char *)path_ptr, &varint_len); size_t last_len = strlen(last); size_t prefix_len = last_len - strip_len; size_t suffix_len = strlen(path_ptr + varint_len); size_t path_len; if (varint_len == 0) return index_error_invalid(""incorrect prefix length""); GITERR_CHECK_ALLOC_ADD(&path_len, prefix_len, suffix_len); GITERR_CHECK_ALLOC_ADD(&path_len, path_len, 1); tmp_path = git__malloc(path_len); GITERR_CHECK_ALLOC(tmp_path); memcpy(tmp_path, last, prefix_len); memcpy(tmp_path + prefix_len, path_ptr + varint_len, suffix_len + 1); entry_size = index_entry_size(suffix_len, varint_len, entry.flags); entry.path = tmp_path; } if (entry_size == 0) return -1; if (INDEX_FOOTER_SIZE + entry_size > buffer_size) return -1; if (index_entry_dup(out, index, &entry) < 0) { git__free(tmp_path); return -1; } git__free(tmp_path); *out_size = entry_size; return 0; }","static int read_entry( git_index_entry **out, size_t *out_size, git_index *index, const void *buffer, size_t buffer_size, const char *last) { size_t path_length, entry_size; const char *path_ptr; struct entry_short source; git_index_entry entry = {{0}}; bool compressed = index->version >= INDEX_VERSION_NUMBER_COMP; char *tmp_path = NULL; if (INDEX_FOOTER_SIZE + minimal_entry_size > buffer_size) return -1; /* buffer is not guaranteed to be aligned */ memcpy(&source, buffer, sizeof(struct entry_short)); entry.ctime.seconds = (git_time_t)ntohl(source.ctime.seconds); entry.ctime.nanoseconds = ntohl(source.ctime.nanoseconds); entry.mtime.seconds = (git_time_t)ntohl(source.mtime.seconds); entry.mtime.nanoseconds = ntohl(source.mtime.nanoseconds); entry.dev = ntohl(source.dev); entry.ino = ntohl(source.ino); entry.mode = ntohl(source.mode); entry.uid = ntohl(source.uid); entry.gid = ntohl(source.gid); entry.file_size = ntohl(source.file_size); git_oid_cpy(&entry.id, &source.oid); entry.flags = ntohs(source.flags); if (entry.flags & GIT_IDXENTRY_EXTENDED) { uint16_t flags_raw; size_t flags_offset; flags_offset = offsetof(struct entry_long, flags_extended); memcpy(&flags_raw, (const char *) buffer + flags_offset, sizeof(flags_raw)); flags_raw = ntohs(flags_raw); memcpy(&entry.flags_extended, &flags_raw, sizeof(flags_raw)); path_ptr = (const char *) buffer + offsetof(struct entry_long, path); } else path_ptr = (const char *) buffer + offsetof(struct entry_short, path); if (!compressed) { path_length = entry.flags & GIT_IDXENTRY_NAMEMASK; /* if this is a very long string, we must find its * real length without overflowing */ if (path_length == 0xFFF) { const char *path_end; path_end = memchr(path_ptr, '\0', buffer_size); if (path_end == NULL) return -1; path_length = path_end - path_ptr; } entry_size = index_entry_size(path_length, 0, entry.flags); entry.path = (char *)path_ptr; } else { size_t varint_len, last_len, prefix_len, suffix_len, path_len; uintmax_t strip_len; strip_len = git_decode_varint((const unsigned char *)path_ptr, &varint_len); last_len = strlen(last); if (varint_len == 0 || last_len < strip_len) return index_error_invalid(""incorrect prefix length""); prefix_len = last_len - strip_len; suffix_len = strlen(path_ptr + varint_len); GITERR_CHECK_ALLOC_ADD(&path_len, prefix_len, suffix_len); GITERR_CHECK_ALLOC_ADD(&path_len, path_len, 1); tmp_path = git__malloc(path_len); GITERR_CHECK_ALLOC(tmp_path); memcpy(tmp_path, last, prefix_len); memcpy(tmp_path + prefix_len, path_ptr + varint_len, suffix_len + 1); entry_size = index_entry_size(suffix_len, varint_len, entry.flags); entry.path = tmp_path; } if (entry_size == 0) return -1; if (INDEX_FOOTER_SIZE + entry_size > buffer_size) return -1; if (index_entry_dup(out, index, &entry) < 0) { git__free(tmp_path); return -1; } git__free(tmp_path); *out_size = entry_size; return 0; }","{'deleted': [{'line_no': 67, 'char_start': 2004, 'char_end': 2025, 'line': '\t\tsize_t varint_len;\n'}, {'line_no': 68, 'char_start': 2025, 'char_end': 2097, 'line': '\t\tsize_t strip_len = git_decode_varint((const unsigned char *)path_ptr,\n'}, {'line_no': 69, 'char_start': 2097, 'char_end': 2122, 'line': '\t\t\t\t\t\t &varint_len);\n'}, {'line_no': 70, 'char_start': 2122, 'char_end': 2156, 'line': '\t\tsize_t last_len = strlen(last);\n'}, {'line_no': 71, 'char_start': 2156, 'char_end': 2200, 'line': '\t\tsize_t prefix_len = last_len - strip_len;\n'}, {'line_no': 72, 'char_start': 2200, 'char_end': 2253, 'line': '\t\tsize_t suffix_len = strlen(path_ptr + varint_len);\n'}, {'line_no': 73, 'char_start': 2253, 'char_end': 2272, 'line': '\t\tsize_t path_len;\n'}, {'line_no': 74, 'char_start': 2272, 'char_end': 2273, 'line': '\n'}, {'line_no': 75, 'char_start': 2273, 'char_end': 2296, 'line': '\t\tif (varint_len == 0)\n'}], 'added': [{'line_no': 67, 'char_start': 2004, 'char_end': 2069, 'line': '\t\tsize_t varint_len, last_len, prefix_len, suffix_len, path_len;\n'}, {'line_no': 68, 'char_start': 2069, 'char_end': 2092, 'line': '\t\tuintmax_t strip_len;\n'}, {'line_no': 69, 'char_start': 2092, 'char_end': 2093, 'line': '\n'}, {'line_no': 70, 'char_start': 2093, 'char_end': 2172, 'line': '\t\tstrip_len = git_decode_varint((const unsigned char *)path_ptr, &varint_len);\n'}, {'line_no': 71, 'char_start': 2172, 'char_end': 2199, 'line': '\t\tlast_len = strlen(last);\n'}, {'line_no': 72, 'char_start': 2199, 'char_end': 2200, 'line': '\n'}, {'line_no': 73, 'char_start': 2200, 'char_end': 2247, 'line': '\t\tif (varint_len == 0 || last_len < strip_len)\n'}, {'line_no': 76, 'char_start': 2306, 'char_end': 2343, 'line': '\t\tprefix_len = last_len - strip_len;\n'}, {'line_no': 77, 'char_start': 2343, 'char_end': 2389, 'line': '\t\tsuffix_len = strlen(path_ptr + varint_len);\n'}, {'line_no': 78, 'char_start': 2389, 'char_end': 2390, 'line': '\n'}]}","{'deleted': [{'char_start': 2027, 'char_end': 2028, 'chars': 's'}, {'char_start': 2029, 'char_end': 2031, 'chars': 'ze'}, {'char_start': 2096, 'char_end': 2107, 'chars': '\n\t\t\t\t\t\t '}, {'char_start': 2124, 'char_end': 2131, 'chars': 'size_t '}, {'char_start': 2158, 'char_end': 2159, 'chars': 's'}, {'char_start': 2160, 'char_end': 2164, 'chars': 'ze_t'}, {'char_start': 2165, 'char_end': 2166, 'chars': 'p'}, {'char_start': 2167, 'char_end': 2169, 'chars': 'ef'}, {'char_start': 2170, 'char_end': 2171, 'chars': 'x'}, {'char_start': 2187, 'char_end': 2188, 'chars': '-'}, {'char_start': 2198, 'char_end': 2199, 'chars': ';'}, {'char_start': 2202, 'char_end': 2205, 'chars': 'siz'}, {'char_start': 2206, 'char_end': 2207, 'chars': '_'}, {'char_start': 2209, 'char_end': 2213, 'chars': 'suff'}, {'char_start': 2218, 'char_end': 2219, 'chars': 'n'}, {'char_start': 2220, 'char_end': 2221, 'chars': '='}, {'char_start': 2222, 'char_end': 2225, 'chars': 'str'}, {'char_start': 2228, 'char_end': 2231, 'chars': '(pa'}, {'char_start': 2233, 'char_end': 2234, 'chars': '_'}, {'char_start': 2235, 'char_end': 2236, 'chars': 't'}, {'char_start': 2238, 'char_end': 2239, 'chars': '+'}, {'char_start': 2240, 'char_end': 2241, 'chars': 'v'}, {'char_start': 2242, 'char_end': 2245, 'chars': 'rin'}, {'char_start': 2250, 'char_end': 2255, 'chars': ');\n\t\t'}, {'char_start': 2257, 'char_end': 2262, 'chars': 'ze_t '}, {'char_start': 2263, 'char_end': 2266, 'chars': 'ath'}, {'char_start': 2272, 'char_end': 2273, 'chars': '\n'}, {'char_start': 2275, 'char_end': 2276, 'chars': 'i'}, {'char_start': 2277, 'char_end': 2282, 'chars': ' (var'}, {'char_start': 2283, 'char_end': 2285, 'chars': 'nt'}, {'char_start': 2291, 'char_end': 2292, 'chars': '='}, {'char_start': 2293, 'char_end': 2299, 'chars': '0)\n\t\t\t'}, {'char_start': 2302, 'char_end': 2311, 'chars': 'urn index'}, {'char_start': 2312, 'char_end': 2314, 'chars': 'er'}, {'char_start': 2315, 'char_end': 2320, 'chars': 'or_in'}, {'char_start': 2322, 'char_end': 2327, 'chars': 'lid(""'}, {'char_start': 2329, 'char_end': 2335, 'chars': 'correc'}, {'char_start': 2336, 'char_end': 2344, 'chars': ' prefix '}, {'char_start': 2347, 'char_end': 2351, 'chars': 'gth""'}], 'added': [{'char_start': 2023, 'char_end': 2067, 'chars': ', last_len, prefix_len, suffix_len, path_len'}, {'char_start': 2071, 'char_end': 2072, 'chars': 'u'}, {'char_start': 2073, 'char_end': 2078, 'chars': 'ntmax'}, {'char_start': 2081, 'char_end': 2095, 'chars': 'strip_len;\n\n\t\t'}, {'char_start': 2199, 'char_end': 2200, 'chars': '\n'}, {'char_start': 2203, 'char_end': 2204, 'chars': 'f'}, {'char_start': 2205, 'char_end': 2208, 'chars': '(va'}, {'char_start': 2210, 'char_end': 2212, 'chars': 'nt'}, {'char_start': 2217, 'char_end': 2218, 'chars': '='}, {'char_start': 2220, 'char_end': 2225, 'chars': '0 || '}, {'char_start': 2234, 'char_end': 2235, 'chars': '<'}, {'char_start': 2245, 'char_end': 2246, 'chars': ')'}, {'char_start': 2249, 'char_end': 2251, 'chars': '\tr'}, {'char_start': 2254, 'char_end': 2257, 'chars': 'rn '}, {'char_start': 2258, 'char_end': 2261, 'chars': 'nde'}, {'char_start': 2264, 'char_end': 2270, 'chars': 'rror_i'}, {'char_start': 2271, 'char_end': 2286, 'chars': 'valid(""incorrec'}, {'char_start': 2287, 'char_end': 2289, 'chars': ' p'}, {'char_start': 2290, 'char_end': 2295, 'chars': 'efix '}, {'char_start': 2298, 'char_end': 2299, 'chars': 'g'}, {'char_start': 2301, 'char_end': 2308, 'chars': '"");\n\n\t\t'}, {'char_start': 2310, 'char_end': 2318, 'chars': 'efix_len'}, {'char_start': 2319, 'char_end': 2320, 'chars': '='}, {'char_start': 2321, 'char_end': 2322, 'chars': 'l'}, {'char_start': 2323, 'char_end': 2324, 'chars': 's'}, {'char_start': 2329, 'char_end': 2332, 'chars': ' - '}, {'char_start': 2334, 'char_end': 2336, 'chars': 'ri'}, {'char_start': 2345, 'char_end': 2348, 'chars': 'suf'}, {'char_start': 2350, 'char_end': 2351, 'chars': 'x'}, {'char_start': 2358, 'char_end': 2360, 'chars': 'st'}, {'char_start': 2361, 'char_end': 2362, 'chars': 'l'}, {'char_start': 2363, 'char_end': 2367, 'chars': 'n(pa'}, {'char_start': 2368, 'char_end': 2372, 'chars': 'h_pt'}, {'char_start': 2373, 'char_end': 2375, 'chars': ' +'}, {'char_start': 2378, 'char_end': 2379, 'chars': 'r'}, {'char_start': 2382, 'char_end': 2383, 'chars': '_'}]}",github.com/libgit2/libgit2/commit/3207ddb0103543da8ad2139ec6539f590f9900c1,src/index.c,cwe-190,794 cwe-079,subscribe_for_tags,"@csrf.csrf_protect def subscribe_for_tags(request): """"""process subscription of users by tags"""""" #todo - use special separator to split tags tag_names = request.REQUEST.get('tags','').strip().split() pure_tag_names, wildcards = forms.clean_marked_tagnames(tag_names) if request.user.is_authenticated(): if request.method == 'POST': if 'ok' in request.POST: request.user.mark_tags( pure_tag_names, wildcards, reason = 'good', action = 'add' ) request.user.message_set.create( message = _('Your tag subscription was saved, thanks!') ) else: message = _( 'Tag subscription was canceled (undo).' ) % {'url': request.path + '?tags=' + request.REQUEST['tags']} request.user.message_set.create(message = message) return HttpResponseRedirect(reverse('index')) else: data = {'tags': tag_names} return render(request, 'subscribe_for_tags.html', data) else: all_tag_names = pure_tag_names + wildcards message = _('Please sign in to subscribe for: %(tags)s') \ % {'tags': ', '.join(all_tag_names)} request.user.message_set.create(message = message) request.session['subscribe_for_tags'] = (pure_tag_names, wildcards) return HttpResponseRedirect(url_utils.get_login_url())","@csrf.csrf_protect def subscribe_for_tags(request): """"""process subscription of users by tags"""""" #todo - use special separator to split tags tag_names = request.REQUEST.get('tags','').strip().split() pure_tag_names, wildcards = forms.clean_marked_tagnames(tag_names) if request.user.is_authenticated(): if request.method == 'POST': if 'ok' in request.POST: request.user.mark_tags( pure_tag_names, wildcards, reason = 'good', action = 'add' ) request.user.message_set.create( message = _('Your tag subscription was saved, thanks!') ) else: message = _( 'Tag subscription was canceled (undo).' ) % {'url': escape(request.path) + '?tags=' + request.REQUEST['tags']} request.user.message_set.create(message = message) return HttpResponseRedirect(reverse('index')) else: data = {'tags': tag_names} return render(request, 'subscribe_for_tags.html', data) else: all_tag_names = pure_tag_names + wildcards message = _('Please sign in to subscribe for: %(tags)s') \ % {'tags': ', '.join(all_tag_names)} request.user.message_set.create(message = message) request.session['subscribe_for_tags'] = (pure_tag_names, wildcards) return HttpResponseRedirect(url_utils.get_login_url())","{'deleted': [{'line_no': 22, 'char_start': 905, 'char_end': 984, 'line': "" ) % {'url': request.path + '?tags=' + request.REQUEST['tags']}\n""}], 'added': [{'line_no': 22, 'char_start': 905, 'char_end': 992, 'line': "" ) % {'url': escape(request.path) + '?tags=' + request.REQUEST['tags']}\n""}]}","{'deleted': [], 'added': [{'char_start': 933, 'char_end': 940, 'chars': 'escape('}, {'char_start': 952, 'char_end': 953, 'chars': ')'}]}",github.com/ASKBOT/askbot-devel/commit/a676a86b6b7a5737d4da4f59f71e037406f88d29,askbot/views/commands.py,cwe-079,305 cwe-022,handle_method_call,"static void handle_method_call(GDBusConnection *connection, const gchar *caller, const gchar *object_path, const gchar *interface_name, const gchar *method_name, GVariant *parameters, GDBusMethodInvocation *invocation, gpointer user_data) { reset_timeout(); uid_t caller_uid; GVariant *response; caller_uid = get_caller_uid(connection, invocation, caller); log_notice(""caller_uid:%ld method:'%s'"", (long)caller_uid, method_name); if (caller_uid == (uid_t) -1) return; if (g_strcmp0(method_name, ""NewProblem"") == 0) { char *error = NULL; char *problem_id = handle_new_problem(g_variant_get_child_value(parameters, 0), caller_uid, &error); if (!problem_id) { g_dbus_method_invocation_return_dbus_error(invocation, ""org.freedesktop.problems.Failure"", error); free(error); return; } /* else */ response = g_variant_new(""(s)"", problem_id); g_dbus_method_invocation_return_value(invocation, response); free(problem_id); return; } if (g_strcmp0(method_name, ""GetProblems"") == 0) { GList *dirs = get_problem_dirs_for_uid(caller_uid, g_settings_dump_location); response = variant_from_string_list(dirs); list_free_with_free(dirs); g_dbus_method_invocation_return_value(invocation, response); //I was told that g_dbus_method frees the response //g_variant_unref(response); return; } if (g_strcmp0(method_name, ""GetAllProblems"") == 0) { /* - so, we have UID, - if it's 0, then we don't have to check anything and just return all directories - if uid != 0 then we want to ask for authorization */ if (caller_uid != 0) { if (polkit_check_authorization_dname(caller, ""org.freedesktop.problems.getall"") == PolkitYes) caller_uid = 0; } GList * dirs = get_problem_dirs_for_uid(caller_uid, g_settings_dump_location); response = variant_from_string_list(dirs); list_free_with_free(dirs); g_dbus_method_invocation_return_value(invocation, response); return; } if (g_strcmp0(method_name, ""GetForeignProblems"") == 0) { GList * dirs = get_problem_dirs_not_accessible_by_uid(caller_uid, g_settings_dump_location); response = variant_from_string_list(dirs); list_free_with_free(dirs); g_dbus_method_invocation_return_value(invocation, response); return; } if (g_strcmp0(method_name, ""ChownProblemDir"") == 0) { const gchar *problem_dir; g_variant_get(parameters, ""(&s)"", &problem_dir); log_notice(""problem_dir:'%s'"", problem_dir); if (!allowed_problem_dir(problem_dir)) { return_InvalidProblemDir_error(invocation, problem_dir); return; } int dir_fd = dd_openfd(problem_dir); if (dir_fd < 0) { perror_msg(""can't open problem directory '%s'"", problem_dir); return_InvalidProblemDir_error(invocation, problem_dir); return; } int ddstat = fdump_dir_stat_for_uid(dir_fd, caller_uid); if (ddstat < 0) { if (errno == ENOTDIR) { log_notice(""requested directory does not exist '%s'"", problem_dir); } else { perror_msg(""can't get stat of '%s'"", problem_dir); } return_InvalidProblemDir_error(invocation, problem_dir); close(dir_fd); return; } if (ddstat & DD_STAT_OWNED_BY_UID) { //caller seems to be in group with access to this dir, so no action needed log_notice(""caller has access to the requested directory %s"", problem_dir); g_dbus_method_invocation_return_value(invocation, NULL); close(dir_fd); return; } if ((ddstat & DD_STAT_ACCESSIBLE_BY_UID) == 0 && polkit_check_authorization_dname(caller, ""org.freedesktop.problems.getall"") != PolkitYes) { log_notice(""not authorized""); g_dbus_method_invocation_return_dbus_error(invocation, ""org.freedesktop.problems.AuthFailure"", _(""Not Authorized"")); close(dir_fd); return; } struct dump_dir *dd = dd_fdopendir(dir_fd, problem_dir, DD_OPEN_READONLY | DD_FAIL_QUIETLY_EACCES); if (!dd) { return_InvalidProblemDir_error(invocation, problem_dir); return; } int chown_res = dd_chown(dd, caller_uid); if (chown_res != 0) g_dbus_method_invocation_return_dbus_error(invocation, ""org.freedesktop.problems.ChownError"", _(""Chowning directory failed. Check system logs for more details."")); else g_dbus_method_invocation_return_value(invocation, NULL); dd_close(dd); return; } if (g_strcmp0(method_name, ""GetInfo"") == 0) { /* Parameter tuple is (sas) */ /* Get 1st param - problem dir name */ const gchar *problem_dir; g_variant_get_child(parameters, 0, ""&s"", &problem_dir); log_notice(""problem_dir:'%s'"", problem_dir); if (!allowed_problem_dir(problem_dir)) { return_InvalidProblemDir_error(invocation, problem_dir); return; } int dir_fd = dd_openfd(problem_dir); if (dir_fd < 0) { perror_msg(""can't open problem directory '%s'"", problem_dir); return_InvalidProblemDir_error(invocation, problem_dir); return; } if (!fdump_dir_accessible_by_uid(dir_fd, caller_uid)) { if (errno == ENOTDIR) { log_notice(""Requested directory does not exist '%s'"", problem_dir); return_InvalidProblemDir_error(invocation, problem_dir); close(dir_fd); return; } if (polkit_check_authorization_dname(caller, ""org.freedesktop.problems.getall"") != PolkitYes) { log_notice(""not authorized""); g_dbus_method_invocation_return_dbus_error(invocation, ""org.freedesktop.problems.AuthFailure"", _(""Not Authorized"")); close(dir_fd); return; } } struct dump_dir *dd = dd_fdopendir(dir_fd, problem_dir, DD_OPEN_READONLY | DD_FAIL_QUIETLY_EACCES); if (!dd) { return_InvalidProblemDir_error(invocation, problem_dir); return; } /* Get 2nd param - vector of element names */ GVariant *array = g_variant_get_child_value(parameters, 1); GList *elements = string_list_from_variant(array); g_variant_unref(array); GVariantBuilder *builder = NULL; for (GList *l = elements; l; l = l->next) { const char *element_name = (const char*)l->data; char *value = dd_load_text_ext(dd, element_name, 0 | DD_LOAD_TEXT_RETURN_NULL_ON_FAILURE | DD_FAIL_QUIETLY_ENOENT | DD_FAIL_QUIETLY_EACCES); log_notice(""element '%s' %s"", element_name, value ? ""fetched"" : ""not found""); if (value) { if (!builder) builder = g_variant_builder_new(G_VARIANT_TYPE_ARRAY); /* g_variant_builder_add makes a copy. No need to xstrdup here */ g_variant_builder_add(builder, ""{ss}"", element_name, value); free(value); } } list_free_with_free(elements); dd_close(dd); /* It is OK to call g_variant_new(""(a{ss})"", NULL) because */ /* G_VARIANT_TYPE_TUPLE allows NULL value */ GVariant *response = g_variant_new(""(a{ss})"", builder); if (builder) g_variant_builder_unref(builder); log_info(""GetInfo: returning value for '%s'"", problem_dir); g_dbus_method_invocation_return_value(invocation, response); return; } if (g_strcmp0(method_name, ""SetElement"") == 0) { const char *problem_id; const char *element; const char *value; g_variant_get(parameters, ""(&s&s&s)"", &problem_id, &element, &value); if (element == NULL || element[0] == '\0' || strlen(element) > 64) { log_notice(""'%s' is not a valid element name of '%s'"", element, problem_id); char *error = xasprintf(_(""'%s' is not a valid element name""), element); g_dbus_method_invocation_return_dbus_error(invocation, ""org.freedesktop.problems.InvalidElement"", error); free(error); return; } struct dump_dir *dd = open_directory_for_modification_of_element( invocation, caller_uid, problem_id, element); if (!dd) /* Already logged from open_directory_for_modification_of_element() */ return; /* Is it good idea to make it static? Is it possible to change the max size while a single run? */ const double max_dir_size = g_settings_nMaxCrashReportsSize * (1024 * 1024); const long item_size = dd_get_item_size(dd, element); if (item_size < 0) { log_notice(""Can't get size of '%s/%s'"", problem_id, element); char *error = xasprintf(_(""Can't get size of '%s'""), element); g_dbus_method_invocation_return_dbus_error(invocation, ""org.freedesktop.problems.Failure"", error); return; } const double requested_size = (double)strlen(value) - item_size; /* Don't want to check the size limit in case of reducing of size */ if (requested_size > 0 && requested_size > (max_dir_size - get_dirsize(g_settings_dump_location))) { log_notice(""No problem space left in '%s' (requested Bytes %f)"", problem_id, requested_size); g_dbus_method_invocation_return_dbus_error(invocation, ""org.freedesktop.problems.Failure"", _(""No problem space left"")); } else { dd_save_text(dd, element, value); g_dbus_method_invocation_return_value(invocation, NULL); } dd_close(dd); return; } if (g_strcmp0(method_name, ""DeleteElement"") == 0) { const char *problem_id; const char *element; g_variant_get(parameters, ""(&s&s)"", &problem_id, &element); struct dump_dir *dd = open_directory_for_modification_of_element( invocation, caller_uid, problem_id, element); if (!dd) /* Already logged from open_directory_for_modification_of_element() */ return; const int res = dd_delete_item(dd, element); dd_close(dd); if (res != 0) { log_notice(""Can't delete the element '%s' from the problem directory '%s'"", element, problem_id); char *error = xasprintf(_(""Can't delete the element '%s' from the problem directory '%s'""), element, problem_id); g_dbus_method_invocation_return_dbus_error(invocation, ""org.freedesktop.problems.Failure"", error); free(error); return; } g_dbus_method_invocation_return_value(invocation, NULL); return; } if (g_strcmp0(method_name, ""DeleteProblem"") == 0) { /* Dbus parameters are always tuples. * In this case, it's (as) - a tuple of one element (array of strings). * Need to fetch the array: */ GVariant *array = g_variant_get_child_value(parameters, 0); GList *problem_dirs = string_list_from_variant(array); g_variant_unref(array); for (GList *l = problem_dirs; l; l = l->next) { const char *dir_name = (const char*)l->data; log_notice(""dir_name:'%s'"", dir_name); if (!allowed_problem_dir(dir_name)) { return_InvalidProblemDir_error(invocation, dir_name); goto ret; } } for (GList *l = problem_dirs; l; l = l->next) { const char *dir_name = (const char*)l->data; int dir_fd = dd_openfd(dir_name); if (dir_fd < 0) { perror_msg(""can't open problem directory '%s'"", dir_name); return_InvalidProblemDir_error(invocation, dir_name); return; } if (!fdump_dir_accessible_by_uid(dir_fd, caller_uid)) { if (errno == ENOTDIR) { log_notice(""Requested directory does not exist '%s'"", dir_name); close(dir_fd); continue; } if (polkit_check_authorization_dname(caller, ""org.freedesktop.problems.getall"") != PolkitYes) { // if user didn't provide correct credentials, just move to the next dir close(dir_fd); continue; } } struct dump_dir *dd = dd_fdopendir(dir_fd, dir_name, /*flags:*/ 0); if (dd) { if (dd_delete(dd) != 0) { error_msg(""Failed to delete problem directory '%s'"", dir_name); dd_close(dd); } } } g_dbus_method_invocation_return_value(invocation, NULL); ret: list_free_with_free(problem_dirs); return; } if (g_strcmp0(method_name, ""FindProblemByElementInTimeRange"") == 0) { const gchar *element; const gchar *value; glong timestamp_from; glong timestamp_to; gboolean all; g_variant_get_child(parameters, 0, ""&s"", &element); g_variant_get_child(parameters, 1, ""&s"", &value); g_variant_get_child(parameters, 2, ""x"", ×tamp_from); g_variant_get_child(parameters, 3, ""x"", ×tamp_to); g_variant_get_child(parameters, 4, ""b"", &all); if (all && polkit_check_authorization_dname(caller, ""org.freedesktop.problems.getall"") == PolkitYes) caller_uid = 0; GList *dirs = get_problem_dirs_for_element_in_time(caller_uid, element, value, timestamp_from, timestamp_to); response = variant_from_string_list(dirs); list_free_with_free(dirs); g_dbus_method_invocation_return_value(invocation, response); return; } if (g_strcmp0(method_name, ""Quit"") == 0) { g_dbus_method_invocation_return_value(invocation, NULL); g_main_loop_quit(loop); return; } }","static void handle_method_call(GDBusConnection *connection, const gchar *caller, const gchar *object_path, const gchar *interface_name, const gchar *method_name, GVariant *parameters, GDBusMethodInvocation *invocation, gpointer user_data) { reset_timeout(); uid_t caller_uid; GVariant *response; caller_uid = get_caller_uid(connection, invocation, caller); log_notice(""caller_uid:%ld method:'%s'"", (long)caller_uid, method_name); if (caller_uid == (uid_t) -1) return; if (g_strcmp0(method_name, ""NewProblem"") == 0) { char *error = NULL; char *problem_id = handle_new_problem(g_variant_get_child_value(parameters, 0), caller_uid, &error); if (!problem_id) { g_dbus_method_invocation_return_dbus_error(invocation, ""org.freedesktop.problems.Failure"", error); free(error); return; } /* else */ response = g_variant_new(""(s)"", problem_id); g_dbus_method_invocation_return_value(invocation, response); free(problem_id); return; } if (g_strcmp0(method_name, ""GetProblems"") == 0) { GList *dirs = get_problem_dirs_for_uid(caller_uid, g_settings_dump_location); response = variant_from_string_list(dirs); list_free_with_free(dirs); g_dbus_method_invocation_return_value(invocation, response); //I was told that g_dbus_method frees the response //g_variant_unref(response); return; } if (g_strcmp0(method_name, ""GetAllProblems"") == 0) { /* - so, we have UID, - if it's 0, then we don't have to check anything and just return all directories - if uid != 0 then we want to ask for authorization */ if (caller_uid != 0) { if (polkit_check_authorization_dname(caller, ""org.freedesktop.problems.getall"") == PolkitYes) caller_uid = 0; } GList * dirs = get_problem_dirs_for_uid(caller_uid, g_settings_dump_location); response = variant_from_string_list(dirs); list_free_with_free(dirs); g_dbus_method_invocation_return_value(invocation, response); return; } if (g_strcmp0(method_name, ""GetForeignProblems"") == 0) { GList * dirs = get_problem_dirs_not_accessible_by_uid(caller_uid, g_settings_dump_location); response = variant_from_string_list(dirs); list_free_with_free(dirs); g_dbus_method_invocation_return_value(invocation, response); return; } if (g_strcmp0(method_name, ""ChownProblemDir"") == 0) { const gchar *problem_dir; g_variant_get(parameters, ""(&s)"", &problem_dir); log_notice(""problem_dir:'%s'"", problem_dir); if (!allowed_problem_dir(problem_dir)) { return_InvalidProblemDir_error(invocation, problem_dir); return; } int dir_fd = dd_openfd(problem_dir); if (dir_fd < 0) { perror_msg(""can't open problem directory '%s'"", problem_dir); return_InvalidProblemDir_error(invocation, problem_dir); return; } int ddstat = fdump_dir_stat_for_uid(dir_fd, caller_uid); if (ddstat < 0) { if (errno == ENOTDIR) { log_notice(""requested directory does not exist '%s'"", problem_dir); } else { perror_msg(""can't get stat of '%s'"", problem_dir); } return_InvalidProblemDir_error(invocation, problem_dir); close(dir_fd); return; } if (ddstat & DD_STAT_OWNED_BY_UID) { //caller seems to be in group with access to this dir, so no action needed log_notice(""caller has access to the requested directory %s"", problem_dir); g_dbus_method_invocation_return_value(invocation, NULL); close(dir_fd); return; } if ((ddstat & DD_STAT_ACCESSIBLE_BY_UID) == 0 && polkit_check_authorization_dname(caller, ""org.freedesktop.problems.getall"") != PolkitYes) { log_notice(""not authorized""); g_dbus_method_invocation_return_dbus_error(invocation, ""org.freedesktop.problems.AuthFailure"", _(""Not Authorized"")); close(dir_fd); return; } struct dump_dir *dd = dd_fdopendir(dir_fd, problem_dir, DD_OPEN_READONLY | DD_FAIL_QUIETLY_EACCES); if (!dd) { return_InvalidProblemDir_error(invocation, problem_dir); return; } int chown_res = dd_chown(dd, caller_uid); if (chown_res != 0) g_dbus_method_invocation_return_dbus_error(invocation, ""org.freedesktop.problems.ChownError"", _(""Chowning directory failed. Check system logs for more details."")); else g_dbus_method_invocation_return_value(invocation, NULL); dd_close(dd); return; } if (g_strcmp0(method_name, ""GetInfo"") == 0) { /* Parameter tuple is (sas) */ /* Get 1st param - problem dir name */ const gchar *problem_dir; g_variant_get_child(parameters, 0, ""&s"", &problem_dir); log_notice(""problem_dir:'%s'"", problem_dir); if (!allowed_problem_dir(problem_dir)) { return_InvalidProblemDir_error(invocation, problem_dir); return; } int dir_fd = dd_openfd(problem_dir); if (dir_fd < 0) { perror_msg(""can't open problem directory '%s'"", problem_dir); return_InvalidProblemDir_error(invocation, problem_dir); return; } if (!fdump_dir_accessible_by_uid(dir_fd, caller_uid)) { if (errno == ENOTDIR) { log_notice(""Requested directory does not exist '%s'"", problem_dir); return_InvalidProblemDir_error(invocation, problem_dir); close(dir_fd); return; } if (polkit_check_authorization_dname(caller, ""org.freedesktop.problems.getall"") != PolkitYes) { log_notice(""not authorized""); g_dbus_method_invocation_return_dbus_error(invocation, ""org.freedesktop.problems.AuthFailure"", _(""Not Authorized"")); close(dir_fd); return; } } struct dump_dir *dd = dd_fdopendir(dir_fd, problem_dir, DD_OPEN_READONLY | DD_FAIL_QUIETLY_EACCES); if (!dd) { return_InvalidProblemDir_error(invocation, problem_dir); return; } /* Get 2nd param - vector of element names */ GVariant *array = g_variant_get_child_value(parameters, 1); GList *elements = string_list_from_variant(array); g_variant_unref(array); GVariantBuilder *builder = NULL; for (GList *l = elements; l; l = l->next) { const char *element_name = (const char*)l->data; char *value = dd_load_text_ext(dd, element_name, 0 | DD_LOAD_TEXT_RETURN_NULL_ON_FAILURE | DD_FAIL_QUIETLY_ENOENT | DD_FAIL_QUIETLY_EACCES); log_notice(""element '%s' %s"", element_name, value ? ""fetched"" : ""not found""); if (value) { if (!builder) builder = g_variant_builder_new(G_VARIANT_TYPE_ARRAY); /* g_variant_builder_add makes a copy. No need to xstrdup here */ g_variant_builder_add(builder, ""{ss}"", element_name, value); free(value); } } list_free_with_free(elements); dd_close(dd); /* It is OK to call g_variant_new(""(a{ss})"", NULL) because */ /* G_VARIANT_TYPE_TUPLE allows NULL value */ GVariant *response = g_variant_new(""(a{ss})"", builder); if (builder) g_variant_builder_unref(builder); log_info(""GetInfo: returning value for '%s'"", problem_dir); g_dbus_method_invocation_return_value(invocation, response); return; } if (g_strcmp0(method_name, ""SetElement"") == 0) { const char *problem_id; const char *element; const char *value; g_variant_get(parameters, ""(&s&s&s)"", &problem_id, &element, &value); if (!str_is_correct_filename(element)) { log_notice(""'%s' is not a valid element name of '%s'"", element, problem_id); char *error = xasprintf(_(""'%s' is not a valid element name""), element); g_dbus_method_invocation_return_dbus_error(invocation, ""org.freedesktop.problems.InvalidElement"", error); free(error); return; } struct dump_dir *dd = open_directory_for_modification_of_element( invocation, caller_uid, problem_id, element); if (!dd) /* Already logged from open_directory_for_modification_of_element() */ return; /* Is it good idea to make it static? Is it possible to change the max size while a single run? */ const double max_dir_size = g_settings_nMaxCrashReportsSize * (1024 * 1024); const long item_size = dd_get_item_size(dd, element); if (item_size < 0) { log_notice(""Can't get size of '%s/%s'"", problem_id, element); char *error = xasprintf(_(""Can't get size of '%s'""), element); g_dbus_method_invocation_return_dbus_error(invocation, ""org.freedesktop.problems.Failure"", error); return; } const double requested_size = (double)strlen(value) - item_size; /* Don't want to check the size limit in case of reducing of size */ if (requested_size > 0 && requested_size > (max_dir_size - get_dirsize(g_settings_dump_location))) { log_notice(""No problem space left in '%s' (requested Bytes %f)"", problem_id, requested_size); g_dbus_method_invocation_return_dbus_error(invocation, ""org.freedesktop.problems.Failure"", _(""No problem space left"")); } else { dd_save_text(dd, element, value); g_dbus_method_invocation_return_value(invocation, NULL); } dd_close(dd); return; } if (g_strcmp0(method_name, ""DeleteElement"") == 0) { const char *problem_id; const char *element; g_variant_get(parameters, ""(&s&s)"", &problem_id, &element); if (!str_is_correct_filename(element)) { log_notice(""'%s' is not a valid element name of '%s'"", element, problem_id); char *error = xasprintf(_(""'%s' is not a valid element name""), element); g_dbus_method_invocation_return_dbus_error(invocation, ""org.freedesktop.problems.InvalidElement"", error); free(error); return; } struct dump_dir *dd = open_directory_for_modification_of_element( invocation, caller_uid, problem_id, element); if (!dd) /* Already logged from open_directory_for_modification_of_element() */ return; const int res = dd_delete_item(dd, element); dd_close(dd); if (res != 0) { log_notice(""Can't delete the element '%s' from the problem directory '%s'"", element, problem_id); char *error = xasprintf(_(""Can't delete the element '%s' from the problem directory '%s'""), element, problem_id); g_dbus_method_invocation_return_dbus_error(invocation, ""org.freedesktop.problems.Failure"", error); free(error); return; } g_dbus_method_invocation_return_value(invocation, NULL); return; } if (g_strcmp0(method_name, ""DeleteProblem"") == 0) { /* Dbus parameters are always tuples. * In this case, it's (as) - a tuple of one element (array of strings). * Need to fetch the array: */ GVariant *array = g_variant_get_child_value(parameters, 0); GList *problem_dirs = string_list_from_variant(array); g_variant_unref(array); for (GList *l = problem_dirs; l; l = l->next) { const char *dir_name = (const char*)l->data; log_notice(""dir_name:'%s'"", dir_name); if (!allowed_problem_dir(dir_name)) { return_InvalidProblemDir_error(invocation, dir_name); goto ret; } } for (GList *l = problem_dirs; l; l = l->next) { const char *dir_name = (const char*)l->data; int dir_fd = dd_openfd(dir_name); if (dir_fd < 0) { perror_msg(""can't open problem directory '%s'"", dir_name); return_InvalidProblemDir_error(invocation, dir_name); return; } if (!fdump_dir_accessible_by_uid(dir_fd, caller_uid)) { if (errno == ENOTDIR) { log_notice(""Requested directory does not exist '%s'"", dir_name); close(dir_fd); continue; } if (polkit_check_authorization_dname(caller, ""org.freedesktop.problems.getall"") != PolkitYes) { // if user didn't provide correct credentials, just move to the next dir close(dir_fd); continue; } } struct dump_dir *dd = dd_fdopendir(dir_fd, dir_name, /*flags:*/ 0); if (dd) { if (dd_delete(dd) != 0) { error_msg(""Failed to delete problem directory '%s'"", dir_name); dd_close(dd); } } } g_dbus_method_invocation_return_value(invocation, NULL); ret: list_free_with_free(problem_dirs); return; } if (g_strcmp0(method_name, ""FindProblemByElementInTimeRange"") == 0) { const gchar *element; const gchar *value; glong timestamp_from; glong timestamp_to; gboolean all; g_variant_get_child(parameters, 0, ""&s"", &element); g_variant_get_child(parameters, 1, ""&s"", &value); g_variant_get_child(parameters, 2, ""x"", ×tamp_from); g_variant_get_child(parameters, 3, ""x"", ×tamp_to); g_variant_get_child(parameters, 4, ""b"", &all); if (all && polkit_check_authorization_dname(caller, ""org.freedesktop.problems.getall"") == PolkitYes) caller_uid = 0; GList *dirs = get_problem_dirs_for_element_in_time(caller_uid, element, value, timestamp_from, timestamp_to); response = variant_from_string_list(dirs); list_free_with_free(dirs); g_dbus_method_invocation_return_value(invocation, response); return; } if (g_strcmp0(method_name, ""Quit"") == 0) { g_dbus_method_invocation_return_value(invocation, NULL); g_main_loop_quit(loop); return; } }","{'deleted': [{'line_no': 259, 'char_start': 9073, 'char_end': 9148, 'line': "" if (element == NULL || element[0] == '\\0' || strlen(element) > 64)\n""}], 'added': [{'line_no': 259, 'char_start': 9073, 'char_end': 9120, 'line': ' if (!str_is_correct_filename(element))\n'}, {'line_no': 318, 'char_start': 11559, 'char_end': 11606, 'line': ' if (!str_is_correct_filename(element))\n'}, {'line_no': 319, 'char_start': 11606, 'char_end': 11616, 'line': ' {\n'}, {'line_no': 320, 'char_start': 11616, 'char_end': 11705, 'line': ' log_notice(""\'%s\' is not a valid element name of \'%s\'"", element, problem_id);\n'}, {'line_no': 321, 'char_start': 11705, 'char_end': 11790, 'line': ' char *error = xasprintf(_(""\'%s\' is not a valid element name""), element);\n'}, {'line_no': 322, 'char_start': 11790, 'char_end': 11857, 'line': ' g_dbus_method_invocation_return_dbus_error(invocation,\n'}, {'line_no': 323, 'char_start': 11857, 'char_end': 11946, 'line': ' ""org.freedesktop.problems.InvalidElement"",\n'}, {'line_no': 324, 'char_start': 11946, 'char_end': 12000, 'line': ' error);\n'}, {'line_no': 325, 'char_start': 12000, 'char_end': 12001, 'line': '\n'}, {'line_no': 326, 'char_start': 12001, 'char_end': 12026, 'line': ' free(error);\n'}, {'line_no': 327, 'char_start': 12026, 'char_end': 12046, 'line': ' return;\n'}, {'line_no': 328, 'char_start': 12046, 'char_end': 12056, 'line': ' }\n'}, {'line_no': 329, 'char_start': 12056, 'char_end': 12057, 'line': '\n'}]}","{'deleted': [{'char_start': 9085, 'char_end': 9126, 'chars': ""element == NULL || element[0] == '\\0' || ""}, {'char_start': 9141, 'char_end': 9146, 'chars': ' > 64'}], 'added': [{'char_start': 9085, 'char_end': 9097, 'chars': '!str_is_corr'}, {'char_start': 9098, 'char_end': 9103, 'chars': 'ct_fi'}, {'char_start': 9106, 'char_end': 9107, 'chars': 'a'}, {'char_start': 11557, 'char_end': 12055, 'chars': '\n\n if (!str_is_correct_filename(element))\n {\n log_notice(""\'%s\' is not a valid element name of \'%s\'"", element, problem_id);\n char *error = xasprintf(_(""\'%s\' is not a valid element name""), element);\n g_dbus_method_invocation_return_dbus_error(invocation,\n ""org.freedesktop.problems.InvalidElement"",\n error);\n\n free(error);\n return;\n }'}]}",github.com/abrt/abrt/commit/f3c2a6af3455b2882e28570e8a04f1c2d4500d5b,src/dbus/abrt-dbus.c,cwe-022,3390 cwe-416,updateDevice,"updateDevice(const struct header * headers, time_t t) { struct device ** pp = &devlist; struct device * p = *pp; /* = devlist; */ while(p) { if( p->headers[HEADER_NT].l == headers[HEADER_NT].l && (0==memcmp(p->headers[HEADER_NT].p, headers[HEADER_NT].p, headers[HEADER_NT].l)) && p->headers[HEADER_USN].l == headers[HEADER_USN].l && (0==memcmp(p->headers[HEADER_USN].p, headers[HEADER_USN].p, headers[HEADER_USN].l)) ) { /*printf(""found! %d\n"", (int)(t - p->t));*/ syslog(LOG_DEBUG, ""device updated : %.*s"", headers[HEADER_USN].l, headers[HEADER_USN].p); p->t = t; /* update Location ! */ if(headers[HEADER_LOCATION].l > p->headers[HEADER_LOCATION].l) { struct device * tmp; tmp = realloc(p, sizeof(struct device) + headers[0].l+headers[1].l+headers[2].l); if(!tmp) /* allocation error */ { syslog(LOG_ERR, ""updateDevice() : memory allocation error""); free(p); return 0; } p = tmp; *pp = p; } memcpy(p->data + p->headers[0].l + p->headers[1].l, headers[2].p, headers[2].l); /* TODO : check p->headers[HEADER_LOCATION].l */ return 0; } pp = &p->next; p = *pp; /* p = p->next; */ } syslog(LOG_INFO, ""new device discovered : %.*s"", headers[HEADER_USN].l, headers[HEADER_USN].p); /* add */ { char * pc; int i; p = malloc( sizeof(struct device) + headers[0].l+headers[1].l+headers[2].l ); if(!p) { syslog(LOG_ERR, ""updateDevice(): cannot allocate memory""); return -1; } p->next = devlist; p->t = t; pc = p->data; for(i = 0; i < 3; i++) { p->headers[i].p = pc; p->headers[i].l = headers[i].l; memcpy(pc, headers[i].p, headers[i].l); pc += headers[i].l; } devlist = p; sendNotifications(NOTIF_NEW, p, NULL); } return 1; }","updateDevice(const struct header * headers, time_t t) { struct device ** pp = &devlist; struct device * p = *pp; /* = devlist; */ while(p) { if( p->headers[HEADER_NT].l == headers[HEADER_NT].l && (0==memcmp(p->headers[HEADER_NT].p, headers[HEADER_NT].p, headers[HEADER_NT].l)) && p->headers[HEADER_USN].l == headers[HEADER_USN].l && (0==memcmp(p->headers[HEADER_USN].p, headers[HEADER_USN].p, headers[HEADER_USN].l)) ) { /*printf(""found! %d\n"", (int)(t - p->t));*/ syslog(LOG_DEBUG, ""device updated : %.*s"", headers[HEADER_USN].l, headers[HEADER_USN].p); p->t = t; /* update Location ! */ if(headers[HEADER_LOCATION].l > p->headers[HEADER_LOCATION].l) { struct device * tmp; tmp = realloc(p, sizeof(struct device) + headers[0].l+headers[1].l+headers[2].l); if(!tmp) /* allocation error */ { syslog(LOG_ERR, ""updateDevice() : memory allocation error""); *pp = p->next; /* remove ""p"" from the list */ free(p); return 0; } p = tmp; *pp = p; } memcpy(p->data + p->headers[0].l + p->headers[1].l, headers[2].p, headers[2].l); /* TODO : check p->headers[HEADER_LOCATION].l */ return 0; } pp = &p->next; p = *pp; /* p = p->next; */ } syslog(LOG_INFO, ""new device discovered : %.*s"", headers[HEADER_USN].l, headers[HEADER_USN].p); /* add */ { char * pc; int i; p = malloc( sizeof(struct device) + headers[0].l+headers[1].l+headers[2].l ); if(!p) { syslog(LOG_ERR, ""updateDevice(): cannot allocate memory""); return -1; } p->next = devlist; p->t = t; pc = p->data; for(i = 0; i < 3; i++) { p->headers[i].p = pc; p->headers[i].l = headers[i].l; memcpy(pc, headers[i].p, headers[i].l); pc += headers[i].l; } devlist = p; sendNotifications(NOTIF_NEW, p, NULL); } return 1; }","{'deleted': [], 'added': [{'line_no': 24, 'char_start': 920, 'char_end': 971, 'line': '\t\t\t\t\t*pp = p->next;\t/* remove ""p"" from the list */\n'}]}","{'deleted': [], 'added': [{'char_start': 925, 'char_end': 976, 'chars': '*pp = p->next;\t/* remove ""p"" from the list */\n\t\t\t\t\t'}]}",github.com/miniupnp/miniupnp/commit/cd506a67e174a45c6a202eff182a712955ed6d6f,minissdpd/minissdpd.c,cwe-416,624 cwe-089,get_asset_and_volume,"@app.route('/get_asset_and_volume') def get_asset_and_volume(): asset_id = request.args.get('asset_id') if not isObject(asset_id): ws.send('{""id"":1, ""method"":""call"", ""params"":[0,""lookup_asset_symbols"",[[""' + asset_id + '""], 0]]}') result_l = ws.recv() j_l = json.loads(result_l) asset_id = j_l[""result""][0][""id""] #print asset_id ws.send('{""id"":1, ""method"":""call"", ""params"":[0,""get_assets"",[[""' + asset_id + '""], 0]]}') result = ws.recv() j = json.loads(result) dynamic_asset_data_id = j[""result""][0][""dynamic_asset_data_id""] ws.send('{""id"": 1, ""method"": ""call"", ""params"": [0, ""get_objects"", [[""'+dynamic_asset_data_id+'""]]]}') result2 = ws.recv() j2 = json.loads(result2) #print j2[""result""][0][""current_supply""] j[""result""][0][""current_supply""] = j2[""result""][0][""current_supply""] j[""result""][0][""confidential_supply""] = j2[""result""][0][""confidential_supply""] #print j[""result""] j[""result""][0][""accumulated_fees""] = j2[""result""][0][""accumulated_fees""] j[""result""][0][""fee_pool""] = j2[""result""][0][""fee_pool""] issuer = j[""result""][0][""issuer""] ws.send('{""id"": 1, ""method"": ""call"", ""params"": [0, ""get_objects"", [[""'+issuer+'""]]]}') result3 = ws.recv() j3 = json.loads(result3) j[""result""][0][""issuer_name""] = j3[""result""][0][""name""] con = psycopg2.connect(**config.POSTGRES) cur = con.cursor() query = ""SELECT volume, mcap FROM assets WHERE aid='""+asset_id+""'"" cur.execute(query) results = cur.fetchall() con.close() try: j[""result""][0][""volume""] = results[0][0] j[""result""][0][""mcap""] = results[0][1] except: j[""result""][0][""volume""] = 0 j[""result""][0][""mcap""] = 0 return jsonify(j[""result""])","@app.route('/get_asset_and_volume') def get_asset_and_volume(): asset_id = request.args.get('asset_id') if not isObject(asset_id): ws.send('{""id"":1, ""method"":""call"", ""params"":[0,""lookup_asset_symbols"",[[""' + asset_id + '""], 0]]}') result_l = ws.recv() j_l = json.loads(result_l) asset_id = j_l[""result""][0][""id""] #print asset_id ws.send('{""id"":1, ""method"":""call"", ""params"":[0,""get_assets"",[[""' + asset_id + '""], 0]]}') result = ws.recv() j = json.loads(result) dynamic_asset_data_id = j[""result""][0][""dynamic_asset_data_id""] ws.send('{""id"": 1, ""method"": ""call"", ""params"": [0, ""get_objects"", [[""'+dynamic_asset_data_id+'""]]]}') result2 = ws.recv() j2 = json.loads(result2) #print j2[""result""][0][""current_supply""] j[""result""][0][""current_supply""] = j2[""result""][0][""current_supply""] j[""result""][0][""confidential_supply""] = j2[""result""][0][""confidential_supply""] #print j[""result""] j[""result""][0][""accumulated_fees""] = j2[""result""][0][""accumulated_fees""] j[""result""][0][""fee_pool""] = j2[""result""][0][""fee_pool""] issuer = j[""result""][0][""issuer""] ws.send('{""id"": 1, ""method"": ""call"", ""params"": [0, ""get_objects"", [[""'+issuer+'""]]]}') result3 = ws.recv() j3 = json.loads(result3) j[""result""][0][""issuer_name""] = j3[""result""][0][""name""] con = psycopg2.connect(**config.POSTGRES) cur = con.cursor() query = ""SELECT volume, mcap FROM assets WHERE aid=%s"" cur.execute(query, (asset_id,)) results = cur.fetchall() con.close() try: j[""result""][0][""volume""] = results[0][0] j[""result""][0][""mcap""] = results[0][1] except: j[""result""][0][""volume""] = 0 j[""result""][0][""mcap""] = 0 return jsonify(j[""result""])","{'deleted': [{'line_no': 40, 'char_start': 1428, 'char_end': 1499, 'line': ' query = ""SELECT volume, mcap FROM assets WHERE aid=\'""+asset_id+""\'""\n'}, {'line_no': 41, 'char_start': 1499, 'char_end': 1522, 'line': ' cur.execute(query)\n'}], 'added': [{'line_no': 40, 'char_start': 1428, 'char_end': 1487, 'line': ' query = ""SELECT volume, mcap FROM assets WHERE aid=%s""\n'}, {'line_no': 41, 'char_start': 1487, 'char_end': 1523, 'line': ' cur.execute(query, (asset_id,))\n'}]}","{'deleted': [{'char_start': 1483, 'char_end': 1487, 'chars': '\'""+a'}, {'char_start': 1488, 'char_end': 1497, 'chars': 'set_id+""\''}], 'added': [{'char_start': 1483, 'char_end': 1484, 'chars': '%'}, {'char_start': 1508, 'char_end': 1521, 'chars': ', (asset_id,)'}]}",github.com/VinChain/vinchain-python-api-backend/commit/b78088a551fbb712121269c6eb7f43ede120ff60,api.py,cwe-089,534 cwe-089,process_form,"def process_form(): # see https://docs.python.org/3.4/library/cgi.html for the basic usage # here. form = cgi.FieldStorage() if ""player1"" not in form or ""player2"" not in form or ""size"" not in form: raise FormError(""Invalid parameters."") player1 = form[""player1""].value player2 = form[""player2""].value for c in player1+player2: if c not in ""_-"" and not c.isdigit() and not c.isalpha(): raise FormError(""Invalid parameters: The player names can only contains upper and lowercase characters, digits, underscores, and hypens"") return try: size = int(form[""size""].value) except: raise FormError(""Invalid parameters: 'size' is not an integer."") return if size < 2 or size > 9: raise FormError(""The 'size' must be in the range 2-9, inclusive."") # connect to the database conn = MySQLdb.connect(host = pnsdp.SQL_HOST, user = pnsdp.SQL_USER, passwd = pnsdp.SQL_PASSWD, db = pnsdp.SQL_DB) cursor = conn.cursor() # insert the new row cursor.execute(""""""INSERT INTO games(player1,player2,size) VALUES(""%s"",""%s"",%d);"""""" % (player1,player2,size)) gameID = cursor.lastrowid # MySQLdb has been building a transaction as we run. Commit them now, and # also clean up the other resources we've allocated. conn.commit() cursor.close() conn.close() return gameID","def process_form(): # see https://docs.python.org/3.4/library/cgi.html for the basic usage # here. form = cgi.FieldStorage() if ""player1"" not in form or ""player2"" not in form or ""size"" not in form: raise FormError(""Invalid parameters."") player1 = form[""player1""].value player2 = form[""player2""].value for c in player1+player2: if c not in ""_-"" and not c.isdigit() and not c.isalpha(): raise FormError(""Invalid parameters: The player names can only contains upper and lowercase characters, digits, underscores, and hypens"") return try: size = int(form[""size""].value) except: raise FormError(""Invalid parameters: 'size' is not an integer."") return if size < 2 or size > 9: raise FormError(""The 'size' must be in the range 2-9, inclusive."") # connect to the database conn = MySQLdb.connect(host = pnsdp.SQL_HOST, user = pnsdp.SQL_USER, passwd = pnsdp.SQL_PASSWD, db = pnsdp.SQL_DB) cursor = conn.cursor() # insert the new row cursor.execute(""""""INSERT INTO games(player1,player2,size) VALUES(""%s"",""%s"",%d);"""""", (player1,player2,size)) gameID = cursor.lastrowid # MySQLdb has been building a transaction as we run. Commit them now, and # also clean up the other resources we've allocated. conn.commit() cursor.close() conn.close() return gameID","{'deleted': [{'line_no': 35, 'char_start': 1148, 'char_end': 1261, 'line': ' cursor.execute(""""""INSERT INTO games(player1,player2,size) VALUES(""%s"",""%s"",%d);"""""" % (player1,player2,size))\n'}], 'added': [{'line_no': 35, 'char_start': 1148, 'char_end': 1260, 'line': ' cursor.execute(""""""INSERT INTO games(player1,player2,size) VALUES(""%s"",""%s"",%d);"""""", (player1,player2,size))\n'}]}","{'deleted': [{'char_start': 1234, 'char_end': 1236, 'chars': ' %'}], 'added': [{'char_start': 1234, 'char_end': 1235, 'chars': ','}]}",github.com/russ-lewis/ttt_-_python_cgi/commit/6096f43fd4b2d91211eec4614b7960c0816900da,cgi/create_game.py,cwe-089,373 cwe-125,gmc_mmx,"static void gmc_mmx(uint8_t *dst, uint8_t *src, int stride, int h, int ox, int oy, int dxx, int dxy, int dyx, int dyy, int shift, int r, int width, int height) { const int w = 8; const int ix = ox >> (16 + shift); const int iy = oy >> (16 + shift); const int oxs = ox >> 4; const int oys = oy >> 4; const int dxxs = dxx >> 4; const int dxys = dxy >> 4; const int dyxs = dyx >> 4; const int dyys = dyy >> 4; const uint16_t r4[4] = { r, r, r, r }; const uint16_t dxy4[4] = { dxys, dxys, dxys, dxys }; const uint16_t dyy4[4] = { dyys, dyys, dyys, dyys }; const uint64_t shift2 = 2 * shift; #define MAX_STRIDE 4096U #define MAX_H 8U uint8_t edge_buf[(MAX_H + 1) * MAX_STRIDE]; int x, y; const int dxw = (dxx - (1 << (16 + shift))) * (w - 1); const int dyh = (dyy - (1 << (16 + shift))) * (h - 1); const int dxh = dxy * (h - 1); const int dyw = dyx * (w - 1); int need_emu = (unsigned) ix >= width - w || (unsigned) iy >= height - h; if ( // non-constant fullpel offset (3% of blocks) ((ox ^ (ox + dxw)) | (ox ^ (ox + dxh)) | (ox ^ (ox + dxw + dxh)) | (oy ^ (oy + dyw)) | (oy ^ (oy + dyh)) | (oy ^ (oy + dyw + dyh))) >> (16 + shift) || // uses more than 16 bits of subpel mv (only at huge resolution) (dxx | dxy | dyx | dyy) & 15 || (need_emu && (h > MAX_H || stride > MAX_STRIDE))) { // FIXME could still use mmx for some of the rows ff_gmc_c(dst, src, stride, h, ox, oy, dxx, dxy, dyx, dyy, shift, r, width, height); return; } src += ix + iy * stride; if (need_emu) { ff_emulated_edge_mc_8(edge_buf, src, stride, stride, w + 1, h + 1, ix, iy, width, height); src = edge_buf; } __asm__ volatile ( ""movd %0, %%mm6 \n\t"" ""pxor %%mm7, %%mm7 \n\t"" ""punpcklwd %%mm6, %%mm6 \n\t"" ""punpcklwd %%mm6, %%mm6 \n\t"" :: ""r"" (1 << shift)); for (x = 0; x < w; x += 4) { uint16_t dx4[4] = { oxs - dxys + dxxs * (x + 0), oxs - dxys + dxxs * (x + 1), oxs - dxys + dxxs * (x + 2), oxs - dxys + dxxs * (x + 3) }; uint16_t dy4[4] = { oys - dyys + dyxs * (x + 0), oys - dyys + dyxs * (x + 1), oys - dyys + dyxs * (x + 2), oys - dyys + dyxs * (x + 3) }; for (y = 0; y < h; y++) { __asm__ volatile ( ""movq %0, %%mm4 \n\t"" ""movq %1, %%mm5 \n\t"" ""paddw %2, %%mm4 \n\t"" ""paddw %3, %%mm5 \n\t"" ""movq %%mm4, %0 \n\t"" ""movq %%mm5, %1 \n\t"" ""psrlw $12, %%mm4 \n\t"" ""psrlw $12, %%mm5 \n\t"" : ""+m"" (*dx4), ""+m"" (*dy4) : ""m"" (*dxy4), ""m"" (*dyy4)); __asm__ volatile ( ""movq %%mm6, %%mm2 \n\t"" ""movq %%mm6, %%mm1 \n\t"" ""psubw %%mm4, %%mm2 \n\t"" ""psubw %%mm5, %%mm1 \n\t"" ""movq %%mm2, %%mm0 \n\t"" ""movq %%mm4, %%mm3 \n\t"" ""pmullw %%mm1, %%mm0 \n\t"" // (s - dx) * (s - dy) ""pmullw %%mm5, %%mm3 \n\t"" // dx * dy ""pmullw %%mm5, %%mm2 \n\t"" // (s - dx) * dy ""pmullw %%mm4, %%mm1 \n\t"" // dx * (s - dy) ""movd %4, %%mm5 \n\t"" ""movd %3, %%mm4 \n\t"" ""punpcklbw %%mm7, %%mm5 \n\t"" ""punpcklbw %%mm7, %%mm4 \n\t"" ""pmullw %%mm5, %%mm3 \n\t"" // src[1, 1] * dx * dy ""pmullw %%mm4, %%mm2 \n\t"" // src[0, 1] * (s - dx) * dy ""movd %2, %%mm5 \n\t"" ""movd %1, %%mm4 \n\t"" ""punpcklbw %%mm7, %%mm5 \n\t"" ""punpcklbw %%mm7, %%mm4 \n\t"" ""pmullw %%mm5, %%mm1 \n\t"" // src[1, 0] * dx * (s - dy) ""pmullw %%mm4, %%mm0 \n\t"" // src[0, 0] * (s - dx) * (s - dy) ""paddw %5, %%mm1 \n\t"" ""paddw %%mm3, %%mm2 \n\t"" ""paddw %%mm1, %%mm0 \n\t"" ""paddw %%mm2, %%mm0 \n\t"" ""psrlw %6, %%mm0 \n\t"" ""packuswb %%mm0, %%mm0 \n\t"" ""movd %%mm0, %0 \n\t"" : ""=m"" (dst[x + y * stride]) : ""m"" (src[0]), ""m"" (src[1]), ""m"" (src[stride]), ""m"" (src[stride + 1]), ""m"" (*r4), ""m"" (shift2)); src += stride; } src += 4 - h * stride; } }","static void gmc_mmx(uint8_t *dst, uint8_t *src, int stride, int h, int ox, int oy, int dxx, int dxy, int dyx, int dyy, int shift, int r, int width, int height) { const int w = 8; const int ix = ox >> (16 + shift); const int iy = oy >> (16 + shift); const int oxs = ox >> 4; const int oys = oy >> 4; const int dxxs = dxx >> 4; const int dxys = dxy >> 4; const int dyxs = dyx >> 4; const int dyys = dyy >> 4; const uint16_t r4[4] = { r, r, r, r }; const uint16_t dxy4[4] = { dxys, dxys, dxys, dxys }; const uint16_t dyy4[4] = { dyys, dyys, dyys, dyys }; const uint64_t shift2 = 2 * shift; #define MAX_STRIDE 4096U #define MAX_H 8U uint8_t edge_buf[(MAX_H + 1) * MAX_STRIDE]; int x, y; const int dxw = (dxx - (1 << (16 + shift))) * (w - 1); const int dyh = (dyy - (1 << (16 + shift))) * (h - 1); const int dxh = dxy * (h - 1); const int dyw = dyx * (w - 1); int need_emu = (unsigned) ix >= width - w || width < w || (unsigned) iy >= height - h || height< h ; if ( // non-constant fullpel offset (3% of blocks) ((ox ^ (ox + dxw)) | (ox ^ (ox + dxh)) | (ox ^ (ox + dxw + dxh)) | (oy ^ (oy + dyw)) | (oy ^ (oy + dyh)) | (oy ^ (oy + dyw + dyh))) >> (16 + shift) || // uses more than 16 bits of subpel mv (only at huge resolution) (dxx | dxy | dyx | dyy) & 15 || (need_emu && (h > MAX_H || stride > MAX_STRIDE))) { // FIXME could still use mmx for some of the rows ff_gmc_c(dst, src, stride, h, ox, oy, dxx, dxy, dyx, dyy, shift, r, width, height); return; } src += ix + iy * stride; if (need_emu) { ff_emulated_edge_mc_8(edge_buf, src, stride, stride, w + 1, h + 1, ix, iy, width, height); src = edge_buf; } __asm__ volatile ( ""movd %0, %%mm6 \n\t"" ""pxor %%mm7, %%mm7 \n\t"" ""punpcklwd %%mm6, %%mm6 \n\t"" ""punpcklwd %%mm6, %%mm6 \n\t"" :: ""r"" (1 << shift)); for (x = 0; x < w; x += 4) { uint16_t dx4[4] = { oxs - dxys + dxxs * (x + 0), oxs - dxys + dxxs * (x + 1), oxs - dxys + dxxs * (x + 2), oxs - dxys + dxxs * (x + 3) }; uint16_t dy4[4] = { oys - dyys + dyxs * (x + 0), oys - dyys + dyxs * (x + 1), oys - dyys + dyxs * (x + 2), oys - dyys + dyxs * (x + 3) }; for (y = 0; y < h; y++) { __asm__ volatile ( ""movq %0, %%mm4 \n\t"" ""movq %1, %%mm5 \n\t"" ""paddw %2, %%mm4 \n\t"" ""paddw %3, %%mm5 \n\t"" ""movq %%mm4, %0 \n\t"" ""movq %%mm5, %1 \n\t"" ""psrlw $12, %%mm4 \n\t"" ""psrlw $12, %%mm5 \n\t"" : ""+m"" (*dx4), ""+m"" (*dy4) : ""m"" (*dxy4), ""m"" (*dyy4)); __asm__ volatile ( ""movq %%mm6, %%mm2 \n\t"" ""movq %%mm6, %%mm1 \n\t"" ""psubw %%mm4, %%mm2 \n\t"" ""psubw %%mm5, %%mm1 \n\t"" ""movq %%mm2, %%mm0 \n\t"" ""movq %%mm4, %%mm3 \n\t"" ""pmullw %%mm1, %%mm0 \n\t"" // (s - dx) * (s - dy) ""pmullw %%mm5, %%mm3 \n\t"" // dx * dy ""pmullw %%mm5, %%mm2 \n\t"" // (s - dx) * dy ""pmullw %%mm4, %%mm1 \n\t"" // dx * (s - dy) ""movd %4, %%mm5 \n\t"" ""movd %3, %%mm4 \n\t"" ""punpcklbw %%mm7, %%mm5 \n\t"" ""punpcklbw %%mm7, %%mm4 \n\t"" ""pmullw %%mm5, %%mm3 \n\t"" // src[1, 1] * dx * dy ""pmullw %%mm4, %%mm2 \n\t"" // src[0, 1] * (s - dx) * dy ""movd %2, %%mm5 \n\t"" ""movd %1, %%mm4 \n\t"" ""punpcklbw %%mm7, %%mm5 \n\t"" ""punpcklbw %%mm7, %%mm4 \n\t"" ""pmullw %%mm5, %%mm1 \n\t"" // src[1, 0] * dx * (s - dy) ""pmullw %%mm4, %%mm0 \n\t"" // src[0, 0] * (s - dx) * (s - dy) ""paddw %5, %%mm1 \n\t"" ""paddw %%mm3, %%mm2 \n\t"" ""paddw %%mm1, %%mm0 \n\t"" ""paddw %%mm2, %%mm0 \n\t"" ""psrlw %6, %%mm0 \n\t"" ""packuswb %%mm0, %%mm0 \n\t"" ""movd %%mm0, %0 \n\t"" : ""=m"" (dst[x + y * stride]) : ""m"" (src[0]), ""m"" (src[1]), ""m"" (src[stride]), ""m"" (src[stride + 1]), ""m"" (*r4), ""m"" (shift2)); src += stride; } src += 4 - h * stride; } }","{'deleted': [{'line_no': 28, 'char_start': 1008, 'char_end': 1060, 'line': ' int need_emu = (unsigned) ix >= width - w ||\n'}, {'line_no': 29, 'char_start': 1060, 'char_end': 1110, 'line': ' (unsigned) iy >= height - h;\n'}], 'added': [{'line_no': 28, 'char_start': 1008, 'char_end': 1073, 'line': ' int need_emu = (unsigned) ix >= width - w || width < w ||\n'}, {'line_no': 29, 'char_start': 1073, 'char_end': 1135, 'line': ' (unsigned) iy >= height - h || height< h\n'}, {'line_no': 30, 'char_start': 1135, 'char_end': 1158, 'line': ' ;\n'}]}","{'deleted': [], 'added': [{'char_start': 1059, 'char_end': 1072, 'chars': ' width < w ||'}, {'char_start': 1121, 'char_end': 1156, 'chars': ' || height< h\n '}]}",github.com/FFmpeg/FFmpeg/commit/58cf31cee7a456057f337b3102a03206d833d5e8,libavcodec/x86/mpegvideodsp.c,cwe-125,1806 cwe-089,insertData," def insertData(self,userid,post): sqlText=""insert into post(userid,date,comment) \ values(%d,current_timestamp(0),'%s');""%(userid,post); result=sql.insertDB(self.conn,sqlText) return result;"," def insertData(self,userid,post): sqlText=""insert into post(userid,date,comment) \ values(%s,current_timestamp(0),%s);"" params=[userid,post]; result=sql.insertDB(self.conn,sqlText,params) return result;","{'deleted': [{'line_no': 3, 'char_start': 95, 'char_end': 165, 'line': ' values(%d,current_timestamp(0),\'%s\');""%(userid,post);\n'}, {'line_no': 4, 'char_start': 165, 'char_end': 212, 'line': ' result=sql.insertDB(self.conn,sqlText)\n'}], 'added': [{'line_no': 3, 'char_start': 95, 'char_end': 148, 'line': ' values(%s,current_timestamp(0),%s);""\n'}, {'line_no': 4, 'char_start': 148, 'char_end': 178, 'line': ' params=[userid,post];\n'}, {'line_no': 5, 'char_start': 178, 'char_end': 232, 'line': ' result=sql.insertDB(self.conn,sqlText,params)\n'}]}","{'deleted': [{'char_start': 119, 'char_end': 120, 'chars': 'd'}, {'char_start': 142, 'char_end': 143, 'chars': ""'""}, {'char_start': 145, 'char_end': 146, 'chars': ""'""}, {'char_start': 149, 'char_end': 151, 'chars': '%('}, {'char_start': 162, 'char_end': 163, 'chars': ')'}], 'added': [{'char_start': 119, 'char_end': 120, 'chars': 's'}, {'char_start': 147, 'char_end': 164, 'chars': '\n params=['}, {'char_start': 175, 'char_end': 176, 'chars': ']'}, {'char_start': 223, 'char_end': 230, 'chars': ',params'}]}",github.com/ShaominLi/Twitter_project/commit/5329d91f9e569c95184053c8e7ef596949c33ce9,modules/post.py,cwe-089,56 cwe-079,htmlvalue," def htmlvalue(self, val): return self.block.render_basic(val)"," def htmlvalue(self, val): """""" Return an HTML representation of this block that is safe to be included in comparison views """""" return escape(text_from_html(self.block.render_basic(val)))","{'deleted': [{'line_no': 2, 'char_start': 30, 'char_end': 73, 'line': ' return self.block.render_basic(val)\n'}], 'added': [{'line_no': 2, 'char_start': 30, 'char_end': 42, 'line': ' """"""\n'}, {'line_no': 3, 'char_start': 42, 'char_end': 122, 'line': ' Return an HTML representation of this block that is safe to be included\n'}, {'line_no': 4, 'char_start': 122, 'char_end': 150, 'line': ' in comparison views\n'}, {'line_no': 5, 'char_start': 150, 'char_end': 162, 'line': ' """"""\n'}, {'line_no': 6, 'char_start': 162, 'char_end': 229, 'line': ' return escape(text_from_html(self.block.render_basic(val)))\n'}]}","{'deleted': [], 'added': [{'char_start': 38, 'char_end': 68, 'chars': '""""""\n Return an HTML rep'}, {'char_start': 70, 'char_end': 73, 'chars': 'sen'}, {'char_start': 74, 'char_end': 117, 'chars': 'ation of this block that is safe to be incl'}, {'char_start': 118, 'char_end': 138, 'chars': 'ded\n in compa'}, {'char_start': 139, 'char_end': 142, 'chars': 'iso'}, {'char_start': 144, 'char_end': 199, 'chars': 'views\n """"""\n return escape(text_from_html('}, {'char_start': 227, 'char_end': 229, 'chars': '))'}]}",github.com/wagtail/wagtail/commit/61045ceefea114c40ac4b680af58990dbe732389,wagtail/admin/compare.py,cwe-079,16 cwe-078,get_ports," def get_ports(self): # First get the active FC ports out = self._cli_run('showport', None) # strip out header # N:S:P,Mode,State,----Node_WWN----,-Port_WWN/HW_Addr-,Type, # Protocol,Label,Partner,FailoverState out = out[1:len(out) - 2] ports = {'FC': [], 'iSCSI': {}} for line in out: tmp = line.split(',') if tmp: if tmp[1] == 'target' and tmp[2] == 'ready': if tmp[6] == 'FC': ports['FC'].append(tmp[4]) # now get the active iSCSI ports out = self._cli_run('showport -iscsi', None) # strip out header # N:S:P,State,IPAddr,Netmask,Gateway, # TPGT,MTU,Rate,DHCP,iSNS_Addr,iSNS_Port out = out[1:len(out) - 2] for line in out: tmp = line.split(',') if tmp and len(tmp) > 2: if tmp[1] == 'ready': ports['iSCSI'][tmp[2]] = {} # now get the nsp and iqn result = self._cli_run('showport -iscsiname', None) if result: # first line is header # nsp, ip,iqn result = result[1:] for line in result: info = line.split("","") if info and len(info) > 2: if info[1] in ports['iSCSI']: nsp = info[0] ip_addr = info[1] iqn = info[2] ports['iSCSI'][ip_addr] = {'nsp': nsp, 'iqn': iqn } LOG.debug(""PORTS = %s"" % pprint.pformat(ports)) return ports"," def get_ports(self): # First get the active FC ports out = self._cli_run(['showport']) # strip out header # N:S:P,Mode,State,----Node_WWN----,-Port_WWN/HW_Addr-,Type, # Protocol,Label,Partner,FailoverState out = out[1:len(out) - 2] ports = {'FC': [], 'iSCSI': {}} for line in out: tmp = line.split(',') if tmp: if tmp[1] == 'target' and tmp[2] == 'ready': if tmp[6] == 'FC': ports['FC'].append(tmp[4]) # now get the active iSCSI ports out = self._cli_run(['showport', '-iscsi']) # strip out header # N:S:P,State,IPAddr,Netmask,Gateway, # TPGT,MTU,Rate,DHCP,iSNS_Addr,iSNS_Port out = out[1:len(out) - 2] for line in out: tmp = line.split(',') if tmp and len(tmp) > 2: if tmp[1] == 'ready': ports['iSCSI'][tmp[2]] = {} # now get the nsp and iqn result = self._cli_run(['showport', '-iscsiname']) if result: # first line is header # nsp, ip,iqn result = result[1:] for line in result: info = line.split("","") if info and len(info) > 2: if info[1] in ports['iSCSI']: nsp = info[0] ip_addr = info[1] iqn = info[2] ports['iSCSI'][ip_addr] = {'nsp': nsp, 'iqn': iqn } LOG.debug(""PORTS = %s"" % pprint.pformat(ports)) return ports","{'deleted': [{'line_no': 3, 'char_start': 65, 'char_end': 111, 'line': "" out = self._cli_run('showport', None)\n""}, {'line_no': 20, 'char_start': 603, 'char_end': 656, 'line': "" out = self._cli_run('showport -iscsi', None)\n""}, {'line_no': 34, 'char_start': 1031, 'char_end': 1091, 'line': "" result = self._cli_run('showport -iscsiname', None)\n""}], 'added': [{'line_no': 3, 'char_start': 65, 'char_end': 107, 'line': "" out = self._cli_run(['showport'])\n""}, {'line_no': 20, 'char_start': 599, 'char_end': 651, 'line': "" out = self._cli_run(['showport', '-iscsi'])\n""}, {'line_no': 34, 'char_start': 1026, 'char_end': 1085, 'line': "" result = self._cli_run(['showport', '-iscsiname'])\n""}]}","{'deleted': [{'char_start': 103, 'char_end': 109, 'chars': ', None'}, {'char_start': 648, 'char_end': 654, 'chars': ', None'}, {'char_start': 1083, 'char_end': 1089, 'chars': ', None'}], 'added': [{'char_start': 93, 'char_end': 94, 'chars': '['}, {'char_start': 104, 'char_end': 105, 'chars': ']'}, {'char_start': 627, 'char_end': 628, 'chars': '['}, {'char_start': 637, 'char_end': 639, 'chars': ""',""}, {'char_start': 640, 'char_end': 641, 'chars': ""'""}, {'char_start': 648, 'char_end': 649, 'chars': ']'}, {'char_start': 1057, 'char_end': 1058, 'chars': '['}, {'char_start': 1067, 'char_end': 1069, 'chars': ""',""}, {'char_start': 1070, 'char_end': 1071, 'chars': ""'""}, {'char_start': 1082, 'char_end': 1083, 'chars': ']'}]}",github.com/thatsdone/cinder/commit/c55589b131828f3a595903f6796cb2d0babb772f,cinder/volume/drivers/san/hp/hp_3par_common.py,cwe-078,450 cwe-787,ContentLine_Analyzer::DoDeliverOnce,"int ContentLine_Analyzer::DoDeliverOnce(int len, const u_char* data) { const u_char* data_start = data; if ( len <= 0 ) return 0; for ( ; len > 0; --len, ++data ) { if ( offset >= buf_len ) InitBuffer(buf_len * 2); int c = data[0]; #define EMIT_LINE \ { \ buf[offset] = '\0'; \ int seq_len = data + 1 - data_start; \ seq_delivered_in_lines = seq + seq_len; \ last_char = c; \ ForwardStream(offset, buf, IsOrig()); \ offset = 0; \ return seq_len; \ } switch ( c ) { case '\r': // Look ahead for '\n'. if ( len > 1 && data[1] == '\n' ) { --len; ++data; last_char = c; c = data[0]; EMIT_LINE } else if ( CR_LF_as_EOL & CR_as_EOL ) EMIT_LINE else buf[offset++] = c; break; case '\n': if ( last_char == '\r' ) { --offset; // remove '\r' EMIT_LINE } else if ( CR_LF_as_EOL & LF_as_EOL ) EMIT_LINE else { if ( ! suppress_weirds && Conn()->FlagEvent(SINGULAR_LF) ) Conn()->Weird(""line_terminated_with_single_LF""); buf[offset++] = c; } break; case '\0': if ( flag_NULs ) CheckNUL(); else buf[offset++] = c; break; default: buf[offset++] = c; break; } if ( last_char == '\r' ) if ( ! suppress_weirds && Conn()->FlagEvent(SINGULAR_CR) ) Conn()->Weird(""line_terminated_with_single_CR""); last_char = c; } return data - data_start; }","int ContentLine_Analyzer::DoDeliverOnce(int len, const u_char* data) { const u_char* data_start = data; if ( len <= 0 ) return 0; for ( ; len > 0; --len, ++data ) { if ( offset >= buf_len ) InitBuffer(buf_len * 2); int c = data[0]; #define EMIT_LINE \ { \ buf[offset] = '\0'; \ int seq_len = data + 1 - data_start; \ seq_delivered_in_lines = seq + seq_len; \ last_char = c; \ ForwardStream(offset, buf, IsOrig()); \ offset = 0; \ return seq_len; \ } switch ( c ) { case '\r': // Look ahead for '\n'. if ( len > 1 && data[1] == '\n' ) { --len; ++data; last_char = c; c = data[0]; EMIT_LINE } else if ( CR_LF_as_EOL & CR_as_EOL ) EMIT_LINE else buf[offset++] = c; break; case '\n': if ( last_char == '\r' ) { // Weird corner-case: // this can happen if we see a \r at the end of a packet where crlf is // set to CR_as_EOL | LF_as_EOL, with the packet causing crlf to be set to // 0 and the next packet beginning with a \n. In this case we just swallow // the character and re-set last_char. if ( offset == 0 ) { last_char = c; break; } --offset; // remove '\r' EMIT_LINE } else if ( CR_LF_as_EOL & LF_as_EOL ) EMIT_LINE else { if ( ! suppress_weirds && Conn()->FlagEvent(SINGULAR_LF) ) Conn()->Weird(""line_terminated_with_single_LF""); buf[offset++] = c; } break; case '\0': if ( flag_NULs ) CheckNUL(); else buf[offset++] = c; break; default: buf[offset++] = c; break; } if ( last_char == '\r' ) if ( ! suppress_weirds && Conn()->FlagEvent(SINGULAR_CR) ) Conn()->Weird(""line_terminated_with_single_CR""); last_char = c; } return data - data_start; }","{'deleted': [], 'added': [{'line_no': 52, 'char_start': 1101, 'char_end': 1124, 'line': '\t\t\t\tif ( offset == 0 )\n'}, {'line_no': 53, 'char_start': 1124, 'char_end': 1131, 'line': '\t\t\t\t\t{\n'}, {'line_no': 54, 'char_start': 1131, 'char_end': 1151, 'line': '\t\t\t\t\tlast_char = c;\n'}, {'line_no': 55, 'char_start': 1151, 'char_end': 1163, 'line': '\t\t\t\t\tbreak;\n'}, {'line_no': 56, 'char_start': 1163, 'char_end': 1170, 'line': '\t\t\t\t\t}\n'}]}","{'deleted': [], 'added': [{'char_start': 803, 'char_end': 1174, 'chars': '// Weird corner-case:\n\t\t\t\t// this can happen if we see a \\r at the end of a packet where crlf is\n\t\t\t\t// set to CR_as_EOL | LF_as_EOL, with the packet causing crlf to be set to\n\t\t\t\t// 0 and the next packet beginning with a \\n. In this case we just swallow\n\t\t\t\t// the character and re-set last_char.\n\t\t\t\tif ( offset == 0 )\n\t\t\t\t\t{\n\t\t\t\t\tlast_char = c;\n\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t'}]}",github.com/bro/bro/commit/6c0f101a62489b1c5927b4ed63b0e1d37db40282,src/analyzer/protocol/tcp/ContentLine.cc,cwe-787,476 cwe-089,get_article,"def get_article(index): with conn.cursor(cursor_factory=DictCursor) as cur: query = ""SELECT * FROM articles WHERE index=""+str(index) cur.execute(query) article = cur.fetchone() return article","def get_article(index): with conn.cursor(cursor_factory=DictCursor) as cur: query = ""SELECT * FROM articles WHERE index=%s"" cur.execute(query, (index, )) article = cur.fetchone() return article","{'deleted': [{'line_no': 3, 'char_start': 80, 'char_end': 145, 'line': ' query = ""SELECT * FROM articles WHERE index=""+str(index)\n'}, {'line_no': 4, 'char_start': 145, 'char_end': 172, 'line': ' cur.execute(query)\n'}], 'added': [{'line_no': 3, 'char_start': 80, 'char_end': 136, 'line': ' query = ""SELECT * FROM articles WHERE index=%s""\n'}, {'line_no': 4, 'char_start': 136, 'char_end': 174, 'line': ' cur.execute(query, (index, ))\n'}]}","{'deleted': [{'char_start': 132, 'char_end': 134, 'chars': '""+'}, {'char_start': 135, 'char_end': 144, 'chars': 'tr(index)'}], 'added': [{'char_start': 132, 'char_end': 133, 'chars': '%'}, {'char_start': 134, 'char_end': 135, 'chars': '""'}, {'char_start': 161, 'char_end': 172, 'chars': ', (index, )'}]}",github.com/sepehr125/arxiv-doc2vec-recommender/commit/f23a4c32e6192b145017f64734b0a9a384c9123a,app.py,cwe-089,46 cwe-089,get_monthly_ranks_for_scene,"def get_monthly_ranks_for_scene(db, scene, tag): sql = ""SELECT date, rank FROM ranks WHERE scene='{}' AND player='{}'"".format(scene, tag) res = db.exec(sql) res = [r for r in res if played_during_month(db, scene, tag, get_previous_month(r[0]))] # Build up a dict of {date: rank} ranks = {} for r in res: ranks[r[0]] = r[1] return ranks","def get_monthly_ranks_for_scene(db, scene, tag): sql = ""SELECT date, rank FROM ranks WHERE scene='{scene}' AND player='{tag}'"" args = {'scene': scene, 'tag': tag} res = db.exec(sql, args) res = [r for r in res if played_during_month(db, scene, tag, get_previous_month(r[0]))] # Build up a dict of {date: rank} ranks = {} for r in res: ranks[r[0]] = r[1] return ranks","{'deleted': [{'line_no': 3, 'char_start': 50, 'char_end': 143, 'line': ' sql = ""SELECT date, rank FROM ranks WHERE scene=\'{}\' AND player=\'{}\'"".format(scene, tag)\n'}, {'line_no': 4, 'char_start': 143, 'char_end': 166, 'line': ' res = db.exec(sql)\n'}], 'added': [{'line_no': 3, 'char_start': 50, 'char_end': 132, 'line': ' sql = ""SELECT date, rank FROM ranks WHERE scene=\'{scene}\' AND player=\'{tag}\'""\n'}, {'line_no': 4, 'char_start': 132, 'char_end': 172, 'line': "" args = {'scene': scene, 'tag': tag}\n""}, {'line_no': 5, 'char_start': 172, 'char_end': 201, 'line': ' res = db.exec(sql, args)\n'}]}","{'deleted': [{'char_start': 123, 'char_end': 126, 'chars': '.fo'}, {'char_start': 127, 'char_end': 131, 'chars': 'mat('}, {'char_start': 141, 'char_end': 142, 'chars': ')'}], 'added': [{'char_start': 104, 'char_end': 109, 'chars': 'scene'}, {'char_start': 125, 'char_end': 128, 'chars': 'tag'}, {'char_start': 131, 'char_end': 136, 'chars': '\n '}, {'char_start': 137, 'char_end': 153, 'chars': ""rgs = {'scene': ""}, {'char_start': 160, 'char_end': 161, 'chars': ""'""}, {'char_start': 164, 'char_end': 171, 'chars': ""': tag}""}, {'char_start': 193, 'char_end': 199, 'chars': ', args'}]}",github.com/DKelle/Smash_stats/commit/4bb83f3f6ce7d6bebbeb512cd015f9e72cf36d63,bracket_utils.py,cwe-089,111 cwe-078,_modify_3par_fibrechan_host," def _modify_3par_fibrechan_host(self, hostname, wwn): # when using -add, you can not send the persona or domain options out = self.common._cli_run('createhost -add %s %s' % (hostname, "" "".join(wwn)), None)"," def _modify_3par_fibrechan_host(self, hostname, wwns): # when using -add, you can not send the persona or domain options command = ['createhost', '-add', hostname] for wwn in wwns: command.append(wwn) out = self.common._cli_run(command)","{'deleted': [{'line_no': 1, 'char_start': 0, 'char_end': 58, 'line': ' def _modify_3par_fibrechan_host(self, hostname, wwn):\n'}, {'line_no': 3, 'char_start': 132, 'char_end': 191, 'line': "" out = self.common._cli_run('createhost -add %s %s'\n""}, {'line_no': 4, 'char_start': 191, 'char_end': 260, 'line': ' % (hostname, "" "".join(wwn)), None)\n'}], 'added': [{'line_no': 1, 'char_start': 0, 'char_end': 59, 'line': ' def _modify_3par_fibrechan_host(self, hostname, wwns):\n'}, {'line_no': 3, 'char_start': 133, 'char_end': 184, 'line': "" command = ['createhost', '-add', hostname]\n""}, {'line_no': 4, 'char_start': 184, 'char_end': 209, 'line': ' for wwn in wwns:\n'}, {'line_no': 5, 'char_start': 209, 'char_end': 241, 'line': ' command.append(wwn)\n'}, {'line_no': 6, 'char_start': 241, 'char_end': 242, 'line': '\n'}, {'line_no': 7, 'char_start': 242, 'char_end': 285, 'line': ' out = self.common._cli_run(command)\n'}]}","{'deleted': [{'char_start': 58, 'char_end': 58, 'chars': ''}, {'char_start': 140, 'char_end': 151, 'chars': 'out = self.'}, {'char_start': 155, 'char_end': 156, 'chars': 'o'}, {'char_start': 157, 'char_end': 167, 'chars': '._cli_run('}, {'char_start': 184, 'char_end': 188, 'chars': '%s %'}, {'char_start': 189, 'char_end': 190, 'chars': ""'""}, {'char_start': 191, 'char_end': 194, 'chars': ' '}, {'char_start': 202, 'char_end': 204, 'chars': ' '}, {'char_start': 226, 'char_end': 230, 'chars': '% (h'}, {'char_start': 231, 'char_end': 232, 'chars': 's'}, {'char_start': 233, 'char_end': 238, 'chars': 'name,'}, {'char_start': 239, 'char_end': 240, 'chars': '""'}, {'char_start': 241, 'char_end': 242, 'chars': '""'}, {'char_start': 243, 'char_end': 244, 'chars': 'j'}, {'char_start': 248, 'char_end': 256, 'chars': 'wwn)), N'}, {'char_start': 258, 'char_end': 259, 'chars': 'e'}], 'added': [{'char_start': 55, 'char_end': 56, 'chars': 's'}, {'char_start': 145, 'char_end': 146, 'chars': 'a'}, {'char_start': 147, 'char_end': 152, 'chars': 'd = ['}, {'char_start': 163, 'char_end': 165, 'chars': ""',""}, {'char_start': 166, 'char_end': 167, 'chars': ""'""}, {'char_start': 171, 'char_end': 173, 'chars': ""',""}, {'char_start': 174, 'char_end': 176, 'chars': 'ho'}, {'char_start': 177, 'char_end': 183, 'chars': 'tname]'}, {'char_start': 192, 'char_end': 195, 'chars': 'for'}, {'char_start': 196, 'char_end': 199, 'chars': 'wwn'}, {'char_start': 200, 'char_end': 202, 'chars': 'in'}, {'char_start': 203, 'char_end': 209, 'chars': 'wwns:\n'}, {'char_start': 221, 'char_end': 242, 'chars': 'command.append(wwn)\n\n'}, {'char_start': 251, 'char_end': 252, 'chars': 'u'}, {'char_start': 254, 'char_end': 255, 'chars': '='}, {'char_start': 256, 'char_end': 260, 'chars': 'self'}, {'char_start': 261, 'char_end': 265, 'chars': 'comm'}, {'char_start': 266, 'char_end': 271, 'chars': 'n._cl'}, {'char_start': 272, 'char_end': 275, 'chars': '_ru'}, {'char_start': 277, 'char_end': 278, 'chars': 'c'}, {'char_start': 279, 'char_end': 282, 'chars': 'mma'}, {'char_start': 283, 'char_end': 284, 'chars': 'd'}]}",github.com/thatsdone/cinder/commit/c55589b131828f3a595903f6796cb2d0babb772f,cinder/volume/drivers/san/hp/hp_3par_fc.py,cwe-078,67 cwe-125,SMB2_negotiate,"SMB2_negotiate(const unsigned int xid, struct cifs_ses *ses) { struct smb_rqst rqst; struct smb2_negotiate_req *req; struct smb2_negotiate_rsp *rsp; struct kvec iov[1]; struct kvec rsp_iov; int rc = 0; int resp_buftype; struct TCP_Server_Info *server = ses->server; int blob_offset, blob_length; char *security_blob; int flags = CIFS_NEG_OP; unsigned int total_len; cifs_dbg(FYI, ""Negotiate protocol\n""); if (!server) { WARN(1, ""%s: server is NULL!\n"", __func__); return -EIO; } rc = smb2_plain_req_init(SMB2_NEGOTIATE, NULL, (void **) &req, &total_len); if (rc) return rc; req->sync_hdr.SessionId = 0; memset(server->preauth_sha_hash, 0, SMB2_PREAUTH_HASH_SIZE); memset(ses->preauth_sha_hash, 0, SMB2_PREAUTH_HASH_SIZE); if (strcmp(ses->server->vals->version_string, SMB3ANY_VERSION_STRING) == 0) { req->Dialects[0] = cpu_to_le16(SMB30_PROT_ID); req->Dialects[1] = cpu_to_le16(SMB302_PROT_ID); req->DialectCount = cpu_to_le16(2); total_len += 4; } else if (strcmp(ses->server->vals->version_string, SMBDEFAULT_VERSION_STRING) == 0) { req->Dialects[0] = cpu_to_le16(SMB21_PROT_ID); req->Dialects[1] = cpu_to_le16(SMB30_PROT_ID); req->Dialects[2] = cpu_to_le16(SMB302_PROT_ID); req->Dialects[3] = cpu_to_le16(SMB311_PROT_ID); req->DialectCount = cpu_to_le16(4); total_len += 8; } else { /* otherwise send specific dialect */ req->Dialects[0] = cpu_to_le16(ses->server->vals->protocol_id); req->DialectCount = cpu_to_le16(1); total_len += 2; } /* only one of SMB2 signing flags may be set in SMB2 request */ if (ses->sign) req->SecurityMode = cpu_to_le16(SMB2_NEGOTIATE_SIGNING_REQUIRED); else if (global_secflags & CIFSSEC_MAY_SIGN) req->SecurityMode = cpu_to_le16(SMB2_NEGOTIATE_SIGNING_ENABLED); else req->SecurityMode = 0; req->Capabilities = cpu_to_le32(ses->server->vals->req_capabilities); /* ClientGUID must be zero for SMB2.02 dialect */ if (ses->server->vals->protocol_id == SMB20_PROT_ID) memset(req->ClientGUID, 0, SMB2_CLIENT_GUID_SIZE); else { memcpy(req->ClientGUID, server->client_guid, SMB2_CLIENT_GUID_SIZE); if ((ses->server->vals->protocol_id == SMB311_PROT_ID) || (strcmp(ses->server->vals->version_string, SMBDEFAULT_VERSION_STRING) == 0)) assemble_neg_contexts(req, &total_len); } iov[0].iov_base = (char *)req; iov[0].iov_len = total_len; memset(&rqst, 0, sizeof(struct smb_rqst)); rqst.rq_iov = iov; rqst.rq_nvec = 1; rc = cifs_send_recv(xid, ses, &rqst, &resp_buftype, flags, &rsp_iov); cifs_small_buf_release(req); rsp = (struct smb2_negotiate_rsp *)rsp_iov.iov_base; /* * No tcon so can't do * cifs_stats_inc(&tcon->stats.smb2_stats.smb2_com_fail[SMB2...]); */ if (rc == -EOPNOTSUPP) { cifs_dbg(VFS, ""Dialect not supported by server. Consider "" ""specifying vers=1.0 or vers=2.0 on mount for accessing"" "" older servers\n""); goto neg_exit; } else if (rc != 0) goto neg_exit; if (strcmp(ses->server->vals->version_string, SMB3ANY_VERSION_STRING) == 0) { if (rsp->DialectRevision == cpu_to_le16(SMB20_PROT_ID)) { cifs_dbg(VFS, ""SMB2 dialect returned but not requested\n""); return -EIO; } else if (rsp->DialectRevision == cpu_to_le16(SMB21_PROT_ID)) { cifs_dbg(VFS, ""SMB2.1 dialect returned but not requested\n""); return -EIO; } } else if (strcmp(ses->server->vals->version_string, SMBDEFAULT_VERSION_STRING) == 0) { if (rsp->DialectRevision == cpu_to_le16(SMB20_PROT_ID)) { cifs_dbg(VFS, ""SMB2 dialect returned but not requested\n""); return -EIO; } else if (rsp->DialectRevision == cpu_to_le16(SMB21_PROT_ID)) { /* ops set to 3.0 by default for default so update */ ses->server->ops = &smb21_operations; } else if (rsp->DialectRevision == cpu_to_le16(SMB311_PROT_ID)) ses->server->ops = &smb311_operations; } else if (le16_to_cpu(rsp->DialectRevision) != ses->server->vals->protocol_id) { /* if requested single dialect ensure returned dialect matched */ cifs_dbg(VFS, ""Illegal 0x%x dialect returned: not requested\n"", le16_to_cpu(rsp->DialectRevision)); return -EIO; } cifs_dbg(FYI, ""mode 0x%x\n"", rsp->SecurityMode); if (rsp->DialectRevision == cpu_to_le16(SMB20_PROT_ID)) cifs_dbg(FYI, ""negotiated smb2.0 dialect\n""); else if (rsp->DialectRevision == cpu_to_le16(SMB21_PROT_ID)) cifs_dbg(FYI, ""negotiated smb2.1 dialect\n""); else if (rsp->DialectRevision == cpu_to_le16(SMB30_PROT_ID)) cifs_dbg(FYI, ""negotiated smb3.0 dialect\n""); else if (rsp->DialectRevision == cpu_to_le16(SMB302_PROT_ID)) cifs_dbg(FYI, ""negotiated smb3.02 dialect\n""); else if (rsp->DialectRevision == cpu_to_le16(SMB311_PROT_ID)) cifs_dbg(FYI, ""negotiated smb3.1.1 dialect\n""); else { cifs_dbg(VFS, ""Illegal dialect returned by server 0x%x\n"", le16_to_cpu(rsp->DialectRevision)); rc = -EIO; goto neg_exit; } server->dialect = le16_to_cpu(rsp->DialectRevision); /* * Keep a copy of the hash after negprot. This hash will be * the starting hash value for all sessions made from this * server. */ memcpy(server->preauth_sha_hash, ses->preauth_sha_hash, SMB2_PREAUTH_HASH_SIZE); /* SMB2 only has an extended negflavor */ server->negflavor = CIFS_NEGFLAVOR_EXTENDED; /* set it to the maximum buffer size value we can send with 1 credit */ server->maxBuf = min_t(unsigned int, le32_to_cpu(rsp->MaxTransactSize), SMB2_MAX_BUFFER_SIZE); server->max_read = le32_to_cpu(rsp->MaxReadSize); server->max_write = le32_to_cpu(rsp->MaxWriteSize); server->sec_mode = le16_to_cpu(rsp->SecurityMode); if ((server->sec_mode & SMB2_SEC_MODE_FLAGS_ALL) != server->sec_mode) cifs_dbg(FYI, ""Server returned unexpected security mode 0x%x\n"", server->sec_mode); server->capabilities = le32_to_cpu(rsp->Capabilities); /* Internal types */ server->capabilities |= SMB2_NT_FIND | SMB2_LARGE_FILES; security_blob = smb2_get_data_area_len(&blob_offset, &blob_length, (struct smb2_sync_hdr *)rsp); /* * See MS-SMB2 section 2.2.4: if no blob, client picks default which * for us will be * ses->sectype = RawNTLMSSP; * but for time being this is our only auth choice so doesn't matter. * We just found a server which sets blob length to zero expecting raw. */ if (blob_length == 0) { cifs_dbg(FYI, ""missing security blob on negprot\n""); server->sec_ntlmssp = true; } rc = cifs_enable_signing(server, ses->sign); if (rc) goto neg_exit; if (blob_length) { rc = decode_negTokenInit(security_blob, blob_length, server); if (rc == 1) rc = 0; else if (rc == 0) rc = -EIO; } if (rsp->DialectRevision == cpu_to_le16(SMB311_PROT_ID)) { if (rsp->NegotiateContextCount) rc = smb311_decode_neg_context(rsp, server, rsp_iov.iov_len); else cifs_dbg(VFS, ""Missing expected negotiate contexts\n""); } neg_exit: free_rsp_buf(resp_buftype, rsp); return rc; }","SMB2_negotiate(const unsigned int xid, struct cifs_ses *ses) { struct smb_rqst rqst; struct smb2_negotiate_req *req; struct smb2_negotiate_rsp *rsp; struct kvec iov[1]; struct kvec rsp_iov; int rc = 0; int resp_buftype; struct TCP_Server_Info *server = ses->server; int blob_offset, blob_length; char *security_blob; int flags = CIFS_NEG_OP; unsigned int total_len; cifs_dbg(FYI, ""Negotiate protocol\n""); if (!server) { WARN(1, ""%s: server is NULL!\n"", __func__); return -EIO; } rc = smb2_plain_req_init(SMB2_NEGOTIATE, NULL, (void **) &req, &total_len); if (rc) return rc; req->sync_hdr.SessionId = 0; memset(server->preauth_sha_hash, 0, SMB2_PREAUTH_HASH_SIZE); memset(ses->preauth_sha_hash, 0, SMB2_PREAUTH_HASH_SIZE); if (strcmp(ses->server->vals->version_string, SMB3ANY_VERSION_STRING) == 0) { req->Dialects[0] = cpu_to_le16(SMB30_PROT_ID); req->Dialects[1] = cpu_to_le16(SMB302_PROT_ID); req->DialectCount = cpu_to_le16(2); total_len += 4; } else if (strcmp(ses->server->vals->version_string, SMBDEFAULT_VERSION_STRING) == 0) { req->Dialects[0] = cpu_to_le16(SMB21_PROT_ID); req->Dialects[1] = cpu_to_le16(SMB30_PROT_ID); req->Dialects[2] = cpu_to_le16(SMB302_PROT_ID); req->Dialects[3] = cpu_to_le16(SMB311_PROT_ID); req->DialectCount = cpu_to_le16(4); total_len += 8; } else { /* otherwise send specific dialect */ req->Dialects[0] = cpu_to_le16(ses->server->vals->protocol_id); req->DialectCount = cpu_to_le16(1); total_len += 2; } /* only one of SMB2 signing flags may be set in SMB2 request */ if (ses->sign) req->SecurityMode = cpu_to_le16(SMB2_NEGOTIATE_SIGNING_REQUIRED); else if (global_secflags & CIFSSEC_MAY_SIGN) req->SecurityMode = cpu_to_le16(SMB2_NEGOTIATE_SIGNING_ENABLED); else req->SecurityMode = 0; req->Capabilities = cpu_to_le32(ses->server->vals->req_capabilities); /* ClientGUID must be zero for SMB2.02 dialect */ if (ses->server->vals->protocol_id == SMB20_PROT_ID) memset(req->ClientGUID, 0, SMB2_CLIENT_GUID_SIZE); else { memcpy(req->ClientGUID, server->client_guid, SMB2_CLIENT_GUID_SIZE); if ((ses->server->vals->protocol_id == SMB311_PROT_ID) || (strcmp(ses->server->vals->version_string, SMBDEFAULT_VERSION_STRING) == 0)) assemble_neg_contexts(req, &total_len); } iov[0].iov_base = (char *)req; iov[0].iov_len = total_len; memset(&rqst, 0, sizeof(struct smb_rqst)); rqst.rq_iov = iov; rqst.rq_nvec = 1; rc = cifs_send_recv(xid, ses, &rqst, &resp_buftype, flags, &rsp_iov); cifs_small_buf_release(req); rsp = (struct smb2_negotiate_rsp *)rsp_iov.iov_base; /* * No tcon so can't do * cifs_stats_inc(&tcon->stats.smb2_stats.smb2_com_fail[SMB2...]); */ if (rc == -EOPNOTSUPP) { cifs_dbg(VFS, ""Dialect not supported by server. Consider "" ""specifying vers=1.0 or vers=2.0 on mount for accessing"" "" older servers\n""); goto neg_exit; } else if (rc != 0) goto neg_exit; if (strcmp(ses->server->vals->version_string, SMB3ANY_VERSION_STRING) == 0) { if (rsp->DialectRevision == cpu_to_le16(SMB20_PROT_ID)) { cifs_dbg(VFS, ""SMB2 dialect returned but not requested\n""); return -EIO; } else if (rsp->DialectRevision == cpu_to_le16(SMB21_PROT_ID)) { cifs_dbg(VFS, ""SMB2.1 dialect returned but not requested\n""); return -EIO; } } else if (strcmp(ses->server->vals->version_string, SMBDEFAULT_VERSION_STRING) == 0) { if (rsp->DialectRevision == cpu_to_le16(SMB20_PROT_ID)) { cifs_dbg(VFS, ""SMB2 dialect returned but not requested\n""); return -EIO; } else if (rsp->DialectRevision == cpu_to_le16(SMB21_PROT_ID)) { /* ops set to 3.0 by default for default so update */ ses->server->ops = &smb21_operations; ses->server->vals = &smb21_values; } else if (rsp->DialectRevision == cpu_to_le16(SMB311_PROT_ID)) { ses->server->ops = &smb311_operations; ses->server->vals = &smb311_values; } } else if (le16_to_cpu(rsp->DialectRevision) != ses->server->vals->protocol_id) { /* if requested single dialect ensure returned dialect matched */ cifs_dbg(VFS, ""Illegal 0x%x dialect returned: not requested\n"", le16_to_cpu(rsp->DialectRevision)); return -EIO; } cifs_dbg(FYI, ""mode 0x%x\n"", rsp->SecurityMode); if (rsp->DialectRevision == cpu_to_le16(SMB20_PROT_ID)) cifs_dbg(FYI, ""negotiated smb2.0 dialect\n""); else if (rsp->DialectRevision == cpu_to_le16(SMB21_PROT_ID)) cifs_dbg(FYI, ""negotiated smb2.1 dialect\n""); else if (rsp->DialectRevision == cpu_to_le16(SMB30_PROT_ID)) cifs_dbg(FYI, ""negotiated smb3.0 dialect\n""); else if (rsp->DialectRevision == cpu_to_le16(SMB302_PROT_ID)) cifs_dbg(FYI, ""negotiated smb3.02 dialect\n""); else if (rsp->DialectRevision == cpu_to_le16(SMB311_PROT_ID)) cifs_dbg(FYI, ""negotiated smb3.1.1 dialect\n""); else { cifs_dbg(VFS, ""Illegal dialect returned by server 0x%x\n"", le16_to_cpu(rsp->DialectRevision)); rc = -EIO; goto neg_exit; } server->dialect = le16_to_cpu(rsp->DialectRevision); /* * Keep a copy of the hash after negprot. This hash will be * the starting hash value for all sessions made from this * server. */ memcpy(server->preauth_sha_hash, ses->preauth_sha_hash, SMB2_PREAUTH_HASH_SIZE); /* SMB2 only has an extended negflavor */ server->negflavor = CIFS_NEGFLAVOR_EXTENDED; /* set it to the maximum buffer size value we can send with 1 credit */ server->maxBuf = min_t(unsigned int, le32_to_cpu(rsp->MaxTransactSize), SMB2_MAX_BUFFER_SIZE); server->max_read = le32_to_cpu(rsp->MaxReadSize); server->max_write = le32_to_cpu(rsp->MaxWriteSize); server->sec_mode = le16_to_cpu(rsp->SecurityMode); if ((server->sec_mode & SMB2_SEC_MODE_FLAGS_ALL) != server->sec_mode) cifs_dbg(FYI, ""Server returned unexpected security mode 0x%x\n"", server->sec_mode); server->capabilities = le32_to_cpu(rsp->Capabilities); /* Internal types */ server->capabilities |= SMB2_NT_FIND | SMB2_LARGE_FILES; security_blob = smb2_get_data_area_len(&blob_offset, &blob_length, (struct smb2_sync_hdr *)rsp); /* * See MS-SMB2 section 2.2.4: if no blob, client picks default which * for us will be * ses->sectype = RawNTLMSSP; * but for time being this is our only auth choice so doesn't matter. * We just found a server which sets blob length to zero expecting raw. */ if (blob_length == 0) { cifs_dbg(FYI, ""missing security blob on negprot\n""); server->sec_ntlmssp = true; } rc = cifs_enable_signing(server, ses->sign); if (rc) goto neg_exit; if (blob_length) { rc = decode_negTokenInit(security_blob, blob_length, server); if (rc == 1) rc = 0; else if (rc == 0) rc = -EIO; } if (rsp->DialectRevision == cpu_to_le16(SMB311_PROT_ID)) { if (rsp->NegotiateContextCount) rc = smb311_decode_neg_context(rsp, server, rsp_iov.iov_len); else cifs_dbg(VFS, ""Missing expected negotiate contexts\n""); } neg_exit: free_rsp_buf(resp_buftype, rsp); return rc; }","{'deleted': [{'line_no': 116, 'char_start': 3733, 'char_end': 3799, 'line': '\t\t} else if (rsp->DialectRevision == cpu_to_le16(SMB311_PROT_ID))\n'}], 'added': [{'line_no': 116, 'char_start': 3733, 'char_end': 3771, 'line': '\t\t\tses->server->vals = &smb21_values;\n'}, {'line_no': 117, 'char_start': 3771, 'char_end': 3839, 'line': '\t\t} else if (rsp->DialectRevision == cpu_to_le16(SMB311_PROT_ID)) {\n'}, {'line_no': 119, 'char_start': 3881, 'char_end': 3920, 'line': '\t\t\tses->server->vals = &smb311_values;\n'}, {'line_no': 120, 'char_start': 3920, 'char_end': 3924, 'line': '\t\t}\n'}]}","{'deleted': [], 'added': [{'char_start': 3735, 'char_end': 3773, 'chars': '\tses->server->vals = &smb21_values;\n\t\t'}, {'char_start': 3836, 'char_end': 3838, 'chars': ' {'}, {'char_start': 3880, 'char_end': 3923, 'chars': '\n\t\t\tses->server->vals = &smb311_values;\n\t\t}'}]}",github.com/torvalds/linux/commit/b57a55e2200ede754e4dc9cce4ba9402544b9365,fs/cifs/smb2pdu.c,cwe-125,2266 cwe-079,action_save_user,"def action_save_user(request: HttpRequest, default_forward_url: str = ""/admin/users""): """""" This functions saves the changes to the user or adds a new one. It completely creates the HttpResponse :param request: the HttpRequest :param default_forward_url: The URL to forward to if nothing was specified :return: The crafted HttpResponse """""" forward_url = default_forward_url if request.GET.get(""redirect""): forward_url = request.GET[""redirect""] if not request.user.is_authenticated: return HttpResponseForbidden() profile = Profile.objects.get(authuser=request.user) if profile.rights < 2: return HttpResponseForbidden() try: if request.GET.get(""user_id""): pid = int(request.GET[""user_id""]) displayname = str(request.POST[""display_name""]) dect = int(request.POST[""dect""]) notes = str(request.POST[""notes""]) pw1 = str(request.POST[""password""]) pw2 = str(request.POST[""confirm_password""]) mail = str(request.POST[""email""]) rights = int(request.POST[""rights""]) user: Profile = Profile.objects.get(pk=pid) user.displayName = displayname user.dect = dect user.notes = notes user.rights = rights user.number_of_allowed_reservations = int(request.POST[""allowed_reservations""]) if request.POST.get(""active""): user.active = magic.parse_bool(request.POST[""active""]) au: User = user.authuser if check_password_conformity(pw1, pw2): logging.log(logging.INFO, ""Set password for user: "" + user.displayName) au.set_password(pw1) else: logging.log(logging.INFO, ""Failed to set password for: "" + user.displayName) au.email = mail au.save() user.save() else: # assume new user username = str(request.POST[""username""]) displayname = str(request.POST[""display_name""]) dect = int(request.POST[""dect""]) notes = str(request.POST[""notes""]) pw1 = str(request.POST[""password""]) pw2 = str(request.POST[""confirm_password""]) mail = str(request.POST[""email""]) rights = int(request.POST[""rights""]) if not check_password_conformity(pw1, pw2): recreate_form('password mismatch') auth_user: User = User.objects.create_user(username=username, email=mail, password=pw1) auth_user.save() user: Profile = Profile() user.rights = rights user.number_of_allowed_reservations = int(request.POST[""allowed_reservations""]) user.displayName = displayname user.authuser = auth_user user.dect = dect user.notes = notes user.active = True user.save() pass pass except Exception as e: return HttpResponseBadRequest(str(e)) return redirect(forward_url)","def action_save_user(request: HttpRequest, default_forward_url: str = ""/admin/users""): """""" This functions saves the changes to the user or adds a new one. It completely creates the HttpResponse :param request: the HttpRequest :param default_forward_url: The URL to forward to if nothing was specified :return: The crafted HttpResponse """""" forward_url = default_forward_url if request.GET.get(""redirect""): forward_url = request.GET[""redirect""] if not request.user.is_authenticated: return HttpResponseForbidden() profile = Profile.objects.get(authuser=request.user) if profile.rights < 2: return HttpResponseForbidden() try: if request.GET.get(""user_id""): pid = int(request.GET[""user_id""]) displayname = str(request.POST[""display_name""]) dect = int(request.POST[""dect""]) notes = str(request.POST[""notes""]) pw1 = str(request.POST[""password""]) pw2 = str(request.POST[""confirm_password""]) mail = str(request.POST[""email""]) rights = int(request.POST[""rights""]) user: Profile = Profile.objects.get(pk=pid) user.displayName = escape(displayname) user.dect = dect user.notes = escape(notes) user.rights = rights user.number_of_allowed_reservations = int(request.POST[""allowed_reservations""]) if request.POST.get(""active""): user.active = magic.parse_bool(request.POST[""active""]) au: User = user.authuser if check_password_conformity(pw1, pw2): logging.log(logging.INFO, ""Set password for user: "" + user.displayName) au.set_password(pw1) else: logging.log(logging.INFO, ""Failed to set password for: "" + user.displayName) au.email = escape(mail) au.save() user.save() else: # assume new user username = str(request.POST[""username""]) displayname = str(request.POST[""display_name""]) dect = int(request.POST[""dect""]) notes = str(request.POST[""notes""]) pw1 = str(request.POST[""password""]) pw2 = str(request.POST[""confirm_password""]) mail = str(request.POST[""email""]) rights = int(request.POST[""rights""]) if not check_password_conformity(pw1, pw2): recreate_form('password mismatch') auth_user: User = User.objects.create_user(username=escape(username), email=escape(mail), password=pw1) auth_user.save() user: Profile = Profile() user.rights = rights user.number_of_allowed_reservations = int(request.POST[""allowed_reservations""]) user.displayName = escape(displayname) user.authuser = auth_user user.dect = dect user.notes = escape(notes) user.active = True user.save() pass pass except Exception as e: return HttpResponseBadRequest(str(e)) return redirect(forward_url)","{'deleted': [{'line_no': 27, 'char_start': 1188, 'char_end': 1231, 'line': ' user.displayName = displayname\n'}, {'line_no': 29, 'char_start': 1260, 'char_end': 1291, 'line': ' user.notes = notes\n'}, {'line_no': 40, 'char_start': 1855, 'char_end': 1883, 'line': ' au.email = mail\n'}, {'line_no': 55, 'char_start': 2484, 'char_end': 2584, 'line': ' auth_user: User = User.objects.create_user(username=username, email=mail, password=pw1)\n'}, {'line_no': 60, 'char_start': 2776, 'char_end': 2819, 'line': ' user.displayName = displayname\n'}, {'line_no': 63, 'char_start': 2886, 'char_end': 2917, 'line': ' user.notes = notes\n'}], 'added': [{'line_no': 27, 'char_start': 1188, 'char_end': 1239, 'line': ' user.displayName = escape(displayname)\n'}, {'line_no': 29, 'char_start': 1268, 'char_end': 1307, 'line': ' user.notes = escape(notes)\n'}, {'line_no': 40, 'char_start': 1871, 'char_end': 1907, 'line': ' au.email = escape(mail)\n'}, {'line_no': 55, 'char_start': 2508, 'char_end': 2624, 'line': ' auth_user: User = User.objects.create_user(username=escape(username), email=escape(mail), password=pw1)\n'}, {'line_no': 60, 'char_start': 2816, 'char_end': 2867, 'line': ' user.displayName = escape(displayname)\n'}, {'line_no': 63, 'char_start': 2934, 'char_end': 2973, 'line': ' user.notes = escape(notes)\n'}]}","{'deleted': [], 'added': [{'char_start': 1219, 'char_end': 1226, 'chars': 'escape('}, {'char_start': 1237, 'char_end': 1238, 'chars': ')'}, {'char_start': 1293, 'char_end': 1300, 'chars': 'escape('}, {'char_start': 1305, 'char_end': 1306, 'chars': ')'}, {'char_start': 1894, 'char_end': 1901, 'chars': 'escape('}, {'char_start': 1905, 'char_end': 1906, 'chars': ')'}, {'char_start': 2572, 'char_end': 2579, 'chars': 'escape('}, {'char_start': 2587, 'char_end': 2588, 'chars': ')'}, {'char_start': 2596, 'char_end': 2603, 'chars': 'escape('}, {'char_start': 2607, 'char_end': 2608, 'chars': ')'}, {'char_start': 2847, 'char_end': 2854, 'chars': 'escape('}, {'char_start': 2865, 'char_end': 2866, 'chars': ')'}, {'char_start': 2959, 'char_end': 2966, 'chars': 'escape('}, {'char_start': 2971, 'char_end': 2972, 'chars': ')'}]}",github.com/Technikradio/C3FOCSite/commit/6e330d4d44bbfdfce9993dffea97008276771600,c3shop/frontpage/management/edit_user.py,cwe-079,622 cwe-190,ring_buffer_resize,"int ring_buffer_resize(struct ring_buffer *buffer, unsigned long size, int cpu_id) { struct ring_buffer_per_cpu *cpu_buffer; unsigned long nr_pages; int cpu, err = 0; /* * Always succeed at resizing a non-existent buffer: */ if (!buffer) return size; /* Make sure the requested buffer exists */ if (cpu_id != RING_BUFFER_ALL_CPUS && !cpumask_test_cpu(cpu_id, buffer->cpumask)) return size; size = DIV_ROUND_UP(size, BUF_PAGE_SIZE); size *= BUF_PAGE_SIZE; /* we need a minimum of two pages */ if (size < BUF_PAGE_SIZE * 2) size = BUF_PAGE_SIZE * 2; nr_pages = DIV_ROUND_UP(size, BUF_PAGE_SIZE); /* * Don't succeed if resizing is disabled, as a reader might be * manipulating the ring buffer and is expecting a sane state while * this is true. */ if (atomic_read(&buffer->resize_disabled)) return -EBUSY; /* prevent another thread from changing buffer sizes */ mutex_lock(&buffer->mutex); if (cpu_id == RING_BUFFER_ALL_CPUS) { /* calculate the pages to update */ for_each_buffer_cpu(buffer, cpu) { cpu_buffer = buffer->buffers[cpu]; cpu_buffer->nr_pages_to_update = nr_pages - cpu_buffer->nr_pages; /* * nothing more to do for removing pages or no update */ if (cpu_buffer->nr_pages_to_update <= 0) continue; /* * to add pages, make sure all new pages can be * allocated without receiving ENOMEM */ INIT_LIST_HEAD(&cpu_buffer->new_pages); if (__rb_allocate_pages(cpu_buffer->nr_pages_to_update, &cpu_buffer->new_pages, cpu)) { /* not enough memory for new pages */ err = -ENOMEM; goto out_err; } } get_online_cpus(); /* * Fire off all the required work handlers * We can't schedule on offline CPUs, but it's not necessary * since we can change their buffer sizes without any race. */ for_each_buffer_cpu(buffer, cpu) { cpu_buffer = buffer->buffers[cpu]; if (!cpu_buffer->nr_pages_to_update) continue; /* Can't run something on an offline CPU. */ if (!cpu_online(cpu)) { rb_update_pages(cpu_buffer); cpu_buffer->nr_pages_to_update = 0; } else { schedule_work_on(cpu, &cpu_buffer->update_pages_work); } } /* wait for all the updates to complete */ for_each_buffer_cpu(buffer, cpu) { cpu_buffer = buffer->buffers[cpu]; if (!cpu_buffer->nr_pages_to_update) continue; if (cpu_online(cpu)) wait_for_completion(&cpu_buffer->update_done); cpu_buffer->nr_pages_to_update = 0; } put_online_cpus(); } else { /* Make sure this CPU has been intitialized */ if (!cpumask_test_cpu(cpu_id, buffer->cpumask)) goto out; cpu_buffer = buffer->buffers[cpu_id]; if (nr_pages == cpu_buffer->nr_pages) goto out; cpu_buffer->nr_pages_to_update = nr_pages - cpu_buffer->nr_pages; INIT_LIST_HEAD(&cpu_buffer->new_pages); if (cpu_buffer->nr_pages_to_update > 0 && __rb_allocate_pages(cpu_buffer->nr_pages_to_update, &cpu_buffer->new_pages, cpu_id)) { err = -ENOMEM; goto out_err; } get_online_cpus(); /* Can't run something on an offline CPU. */ if (!cpu_online(cpu_id)) rb_update_pages(cpu_buffer); else { schedule_work_on(cpu_id, &cpu_buffer->update_pages_work); wait_for_completion(&cpu_buffer->update_done); } cpu_buffer->nr_pages_to_update = 0; put_online_cpus(); } out: /* * The ring buffer resize can happen with the ring buffer * enabled, so that the update disturbs the tracing as little * as possible. But if the buffer is disabled, we do not need * to worry about that, and we can take the time to verify * that the buffer is not corrupt. */ if (atomic_read(&buffer->record_disabled)) { atomic_inc(&buffer->record_disabled); /* * Even though the buffer was disabled, we must make sure * that it is truly disabled before calling rb_check_pages. * There could have been a race between checking * record_disable and incrementing it. */ synchronize_sched(); for_each_buffer_cpu(buffer, cpu) { cpu_buffer = buffer->buffers[cpu]; rb_check_pages(cpu_buffer); } atomic_dec(&buffer->record_disabled); } mutex_unlock(&buffer->mutex); return size; out_err: for_each_buffer_cpu(buffer, cpu) { struct buffer_page *bpage, *tmp; cpu_buffer = buffer->buffers[cpu]; cpu_buffer->nr_pages_to_update = 0; if (list_empty(&cpu_buffer->new_pages)) continue; list_for_each_entry_safe(bpage, tmp, &cpu_buffer->new_pages, list) { list_del_init(&bpage->list); free_buffer_page(bpage); } } mutex_unlock(&buffer->mutex); return err; }","int ring_buffer_resize(struct ring_buffer *buffer, unsigned long size, int cpu_id) { struct ring_buffer_per_cpu *cpu_buffer; unsigned long nr_pages; int cpu, err = 0; /* * Always succeed at resizing a non-existent buffer: */ if (!buffer) return size; /* Make sure the requested buffer exists */ if (cpu_id != RING_BUFFER_ALL_CPUS && !cpumask_test_cpu(cpu_id, buffer->cpumask)) return size; nr_pages = DIV_ROUND_UP(size, BUF_PAGE_SIZE); /* we need a minimum of two pages */ if (nr_pages < 2) nr_pages = 2; size = nr_pages * BUF_PAGE_SIZE; /* * Don't succeed if resizing is disabled, as a reader might be * manipulating the ring buffer and is expecting a sane state while * this is true. */ if (atomic_read(&buffer->resize_disabled)) return -EBUSY; /* prevent another thread from changing buffer sizes */ mutex_lock(&buffer->mutex); if (cpu_id == RING_BUFFER_ALL_CPUS) { /* calculate the pages to update */ for_each_buffer_cpu(buffer, cpu) { cpu_buffer = buffer->buffers[cpu]; cpu_buffer->nr_pages_to_update = nr_pages - cpu_buffer->nr_pages; /* * nothing more to do for removing pages or no update */ if (cpu_buffer->nr_pages_to_update <= 0) continue; /* * to add pages, make sure all new pages can be * allocated without receiving ENOMEM */ INIT_LIST_HEAD(&cpu_buffer->new_pages); if (__rb_allocate_pages(cpu_buffer->nr_pages_to_update, &cpu_buffer->new_pages, cpu)) { /* not enough memory for new pages */ err = -ENOMEM; goto out_err; } } get_online_cpus(); /* * Fire off all the required work handlers * We can't schedule on offline CPUs, but it's not necessary * since we can change their buffer sizes without any race. */ for_each_buffer_cpu(buffer, cpu) { cpu_buffer = buffer->buffers[cpu]; if (!cpu_buffer->nr_pages_to_update) continue; /* Can't run something on an offline CPU. */ if (!cpu_online(cpu)) { rb_update_pages(cpu_buffer); cpu_buffer->nr_pages_to_update = 0; } else { schedule_work_on(cpu, &cpu_buffer->update_pages_work); } } /* wait for all the updates to complete */ for_each_buffer_cpu(buffer, cpu) { cpu_buffer = buffer->buffers[cpu]; if (!cpu_buffer->nr_pages_to_update) continue; if (cpu_online(cpu)) wait_for_completion(&cpu_buffer->update_done); cpu_buffer->nr_pages_to_update = 0; } put_online_cpus(); } else { /* Make sure this CPU has been intitialized */ if (!cpumask_test_cpu(cpu_id, buffer->cpumask)) goto out; cpu_buffer = buffer->buffers[cpu_id]; if (nr_pages == cpu_buffer->nr_pages) goto out; cpu_buffer->nr_pages_to_update = nr_pages - cpu_buffer->nr_pages; INIT_LIST_HEAD(&cpu_buffer->new_pages); if (cpu_buffer->nr_pages_to_update > 0 && __rb_allocate_pages(cpu_buffer->nr_pages_to_update, &cpu_buffer->new_pages, cpu_id)) { err = -ENOMEM; goto out_err; } get_online_cpus(); /* Can't run something on an offline CPU. */ if (!cpu_online(cpu_id)) rb_update_pages(cpu_buffer); else { schedule_work_on(cpu_id, &cpu_buffer->update_pages_work); wait_for_completion(&cpu_buffer->update_done); } cpu_buffer->nr_pages_to_update = 0; put_online_cpus(); } out: /* * The ring buffer resize can happen with the ring buffer * enabled, so that the update disturbs the tracing as little * as possible. But if the buffer is disabled, we do not need * to worry about that, and we can take the time to verify * that the buffer is not corrupt. */ if (atomic_read(&buffer->record_disabled)) { atomic_inc(&buffer->record_disabled); /* * Even though the buffer was disabled, we must make sure * that it is truly disabled before calling rb_check_pages. * There could have been a race between checking * record_disable and incrementing it. */ synchronize_sched(); for_each_buffer_cpu(buffer, cpu) { cpu_buffer = buffer->buffers[cpu]; rb_check_pages(cpu_buffer); } atomic_dec(&buffer->record_disabled); } mutex_unlock(&buffer->mutex); return size; out_err: for_each_buffer_cpu(buffer, cpu) { struct buffer_page *bpage, *tmp; cpu_buffer = buffer->buffers[cpu]; cpu_buffer->nr_pages_to_update = 0; if (list_empty(&cpu_buffer->new_pages)) continue; list_for_each_entry_safe(bpage, tmp, &cpu_buffer->new_pages, list) { list_del_init(&bpage->list); free_buffer_page(bpage); } } mutex_unlock(&buffer->mutex); return err; }","{'deleted': [{'line_no': 19, 'char_start': 416, 'char_end': 459, 'line': '\tsize = DIV_ROUND_UP(size, BUF_PAGE_SIZE);\n'}, {'line_no': 20, 'char_start': 459, 'char_end': 483, 'line': '\tsize *= BUF_PAGE_SIZE;\n'}, {'line_no': 23, 'char_start': 522, 'char_end': 553, 'line': '\tif (size < BUF_PAGE_SIZE * 2)\n'}, {'line_no': 24, 'char_start': 553, 'char_end': 581, 'line': '\t\tsize = BUF_PAGE_SIZE * 2;\n'}, {'line_no': 26, 'char_start': 582, 'char_end': 629, 'line': '\tnr_pages = DIV_ROUND_UP(size, BUF_PAGE_SIZE);\n'}], 'added': [{'line_no': 19, 'char_start': 416, 'char_end': 463, 'line': '\tnr_pages = DIV_ROUND_UP(size, BUF_PAGE_SIZE);\n'}, {'line_no': 22, 'char_start': 502, 'char_end': 521, 'line': '\tif (nr_pages < 2)\n'}, {'line_no': 23, 'char_start': 521, 'char_end': 537, 'line': '\t\tnr_pages = 2;\n'}, {'line_no': 25, 'char_start': 538, 'char_end': 572, 'line': '\tsize = nr_pages * BUF_PAGE_SIZE;\n'}]}","{'deleted': [{'char_start': 417, 'char_end': 420, 'chars': 'siz'}, {'char_start': 459, 'char_end': 483, 'chars': '\tsize *= BUF_PAGE_SIZE;\n'}, {'char_start': 527, 'char_end': 530, 'chars': 'siz'}, {'char_start': 534, 'char_end': 550, 'chars': 'BUF_PAGE_SIZE * '}, {'char_start': 555, 'char_end': 558, 'chars': 'siz'}, {'char_start': 562, 'char_end': 578, 'chars': 'BUF_PAGE_SIZE * '}, {'char_start': 592, 'char_end': 612, 'chars': '= DIV_ROUND_UP(size,'}, {'char_start': 626, 'char_end': 627, 'chars': ')'}], 'added': [{'char_start': 417, 'char_end': 423, 'chars': 'nr_pag'}, {'char_start': 424, 'char_end': 425, 'chars': 's'}, {'char_start': 507, 'char_end': 514, 'chars': 'nr_page'}, {'char_start': 523, 'char_end': 529, 'chars': 'nr_pag'}, {'char_start': 530, 'char_end': 531, 'chars': 's'}, {'char_start': 539, 'char_end': 546, 'chars': 'size = '}, {'char_start': 555, 'char_end': 556, 'chars': '*'}]}",github.com/torvalds/linux/commit/59643d1535eb220668692a5359de22545af579f6,kernel/trace/ring_buffer.c,cwe-190,1218 cwe-787,opj_j2k_set_cinema_parameters,"static void opj_j2k_set_cinema_parameters(opj_cparameters_t *parameters, opj_image_t *image, opj_event_mgr_t *p_manager) { /* Configure cinema parameters */ int i; /* No tiling */ parameters->tile_size_on = OPJ_FALSE; parameters->cp_tdx = 1; parameters->cp_tdy = 1; /* One tile part for each component */ parameters->tp_flag = 'C'; parameters->tp_on = 1; /* Tile and Image shall be at (0,0) */ parameters->cp_tx0 = 0; parameters->cp_ty0 = 0; parameters->image_offset_x0 = 0; parameters->image_offset_y0 = 0; /* Codeblock size= 32*32 */ parameters->cblockw_init = 32; parameters->cblockh_init = 32; /* Codeblock style: no mode switch enabled */ parameters->mode = 0; /* No ROI */ parameters->roi_compno = -1; /* No subsampling */ parameters->subsampling_dx = 1; parameters->subsampling_dy = 1; /* 9-7 transform */ parameters->irreversible = 1; /* Number of layers */ if (parameters->tcp_numlayers > 1) { opj_event_msg(p_manager, EVT_WARNING, ""JPEG 2000 Profile-3 and 4 (2k/4k dc profile) requires:\n"" ""1 single quality layer"" ""-> Number of layers forced to 1 (rather than %d)\n"" ""-> Rate of the last layer (%3.1f) will be used"", parameters->tcp_numlayers, parameters->tcp_rates[parameters->tcp_numlayers - 1]); parameters->tcp_rates[0] = parameters->tcp_rates[parameters->tcp_numlayers - 1]; parameters->tcp_numlayers = 1; } /* Resolution levels */ switch (parameters->rsiz) { case OPJ_PROFILE_CINEMA_2K: if (parameters->numresolution > 6) { opj_event_msg(p_manager, EVT_WARNING, ""JPEG 2000 Profile-3 (2k dc profile) requires:\n"" ""Number of decomposition levels <= 5\n"" ""-> Number of decomposition levels forced to 5 (rather than %d)\n"", parameters->numresolution + 1); parameters->numresolution = 6; } break; case OPJ_PROFILE_CINEMA_4K: if (parameters->numresolution < 2) { opj_event_msg(p_manager, EVT_WARNING, ""JPEG 2000 Profile-4 (4k dc profile) requires:\n"" ""Number of decomposition levels >= 1 && <= 6\n"" ""-> Number of decomposition levels forced to 1 (rather than %d)\n"", parameters->numresolution + 1); parameters->numresolution = 1; } else if (parameters->numresolution > 7) { opj_event_msg(p_manager, EVT_WARNING, ""JPEG 2000 Profile-4 (4k dc profile) requires:\n"" ""Number of decomposition levels >= 1 && <= 6\n"" ""-> Number of decomposition levels forced to 6 (rather than %d)\n"", parameters->numresolution + 1); parameters->numresolution = 7; } break; default : break; } /* Precincts */ parameters->csty |= 0x01; parameters->res_spec = parameters->numresolution - 1; for (i = 0; i < parameters->res_spec; i++) { parameters->prcw_init[i] = 256; parameters->prch_init[i] = 256; } /* The progression order shall be CPRL */ parameters->prog_order = OPJ_CPRL; /* Progression order changes for 4K, disallowed for 2K */ if (parameters->rsiz == OPJ_PROFILE_CINEMA_4K) { parameters->numpocs = (OPJ_UINT32)opj_j2k_initialise_4K_poc(parameters->POC, parameters->numresolution); } else { parameters->numpocs = 0; } /* Limited bit-rate */ parameters->cp_disto_alloc = 1; if (parameters->max_cs_size <= 0) { /* No rate has been introduced, 24 fps is assumed */ parameters->max_cs_size = OPJ_CINEMA_24_CS; opj_event_msg(p_manager, EVT_WARNING, ""JPEG 2000 Profile-3 and 4 (2k/4k dc profile) requires:\n"" ""Maximum 1302083 compressed bytes @ 24fps\n"" ""As no rate has been given, this limit will be used.\n""); } else if (parameters->max_cs_size > OPJ_CINEMA_24_CS) { opj_event_msg(p_manager, EVT_WARNING, ""JPEG 2000 Profile-3 and 4 (2k/4k dc profile) requires:\n"" ""Maximum 1302083 compressed bytes @ 24fps\n"" ""-> Specified rate exceeds this limit. Rate will be forced to 1302083 bytes.\n""); parameters->max_cs_size = OPJ_CINEMA_24_CS; } if (parameters->max_comp_size <= 0) { /* No rate has been introduced, 24 fps is assumed */ parameters->max_comp_size = OPJ_CINEMA_24_COMP; opj_event_msg(p_manager, EVT_WARNING, ""JPEG 2000 Profile-3 and 4 (2k/4k dc profile) requires:\n"" ""Maximum 1041666 compressed bytes @ 24fps\n"" ""As no rate has been given, this limit will be used.\n""); } else if (parameters->max_comp_size > OPJ_CINEMA_24_COMP) { opj_event_msg(p_manager, EVT_WARNING, ""JPEG 2000 Profile-3 and 4 (2k/4k dc profile) requires:\n"" ""Maximum 1041666 compressed bytes @ 24fps\n"" ""-> Specified rate exceeds this limit. Rate will be forced to 1041666 bytes.\n""); parameters->max_comp_size = OPJ_CINEMA_24_COMP; } parameters->tcp_rates[0] = (OPJ_FLOAT32)(image->numcomps * image->comps[0].w * image->comps[0].h * image->comps[0].prec) / (OPJ_FLOAT32)(((OPJ_UINT32)parameters->max_cs_size) * 8 * image->comps[0].dx * image->comps[0].dy); }","static void opj_j2k_set_cinema_parameters(opj_cparameters_t *parameters, opj_image_t *image, opj_event_mgr_t *p_manager) { /* Configure cinema parameters */ int i; /* No tiling */ parameters->tile_size_on = OPJ_FALSE; parameters->cp_tdx = 1; parameters->cp_tdy = 1; /* One tile part for each component */ parameters->tp_flag = 'C'; parameters->tp_on = 1; /* Tile and Image shall be at (0,0) */ parameters->cp_tx0 = 0; parameters->cp_ty0 = 0; parameters->image_offset_x0 = 0; parameters->image_offset_y0 = 0; /* Codeblock size= 32*32 */ parameters->cblockw_init = 32; parameters->cblockh_init = 32; /* Codeblock style: no mode switch enabled */ parameters->mode = 0; /* No ROI */ parameters->roi_compno = -1; /* No subsampling */ parameters->subsampling_dx = 1; parameters->subsampling_dy = 1; /* 9-7 transform */ parameters->irreversible = 1; /* Number of layers */ if (parameters->tcp_numlayers > 1) { opj_event_msg(p_manager, EVT_WARNING, ""JPEG 2000 Profile-3 and 4 (2k/4k dc profile) requires:\n"" ""1 single quality layer"" ""-> Number of layers forced to 1 (rather than %d)\n"" ""-> Rate of the last layer (%3.1f) will be used"", parameters->tcp_numlayers, parameters->tcp_rates[parameters->tcp_numlayers - 1]); parameters->tcp_rates[0] = parameters->tcp_rates[parameters->tcp_numlayers - 1]; parameters->tcp_numlayers = 1; } /* Resolution levels */ switch (parameters->rsiz) { case OPJ_PROFILE_CINEMA_2K: if (parameters->numresolution > 6) { opj_event_msg(p_manager, EVT_WARNING, ""JPEG 2000 Profile-3 (2k dc profile) requires:\n"" ""Number of decomposition levels <= 5\n"" ""-> Number of decomposition levels forced to 5 (rather than %d)\n"", parameters->numresolution + 1); parameters->numresolution = 6; } break; case OPJ_PROFILE_CINEMA_4K: if (parameters->numresolution < 2) { opj_event_msg(p_manager, EVT_WARNING, ""JPEG 2000 Profile-4 (4k dc profile) requires:\n"" ""Number of decomposition levels >= 1 && <= 6\n"" ""-> Number of decomposition levels forced to 1 (rather than %d)\n"", parameters->numresolution + 1); parameters->numresolution = 1; } else if (parameters->numresolution > 7) { opj_event_msg(p_manager, EVT_WARNING, ""JPEG 2000 Profile-4 (4k dc profile) requires:\n"" ""Number of decomposition levels >= 1 && <= 6\n"" ""-> Number of decomposition levels forced to 6 (rather than %d)\n"", parameters->numresolution + 1); parameters->numresolution = 7; } break; default : break; } /* Precincts */ parameters->csty |= 0x01; if (parameters->numresolution == 1) { parameters->res_spec = 1; parameters->prcw_init[0] = 128; parameters->prch_init[0] = 128; } else { parameters->res_spec = parameters->numresolution - 1; for (i = 0; i < parameters->res_spec; i++) { parameters->prcw_init[i] = 256; parameters->prch_init[i] = 256; } } /* The progression order shall be CPRL */ parameters->prog_order = OPJ_CPRL; /* Progression order changes for 4K, disallowed for 2K */ if (parameters->rsiz == OPJ_PROFILE_CINEMA_4K) { parameters->numpocs = (OPJ_UINT32)opj_j2k_initialise_4K_poc(parameters->POC, parameters->numresolution); } else { parameters->numpocs = 0; } /* Limited bit-rate */ parameters->cp_disto_alloc = 1; if (parameters->max_cs_size <= 0) { /* No rate has been introduced, 24 fps is assumed */ parameters->max_cs_size = OPJ_CINEMA_24_CS; opj_event_msg(p_manager, EVT_WARNING, ""JPEG 2000 Profile-3 and 4 (2k/4k dc profile) requires:\n"" ""Maximum 1302083 compressed bytes @ 24fps\n"" ""As no rate has been given, this limit will be used.\n""); } else if (parameters->max_cs_size > OPJ_CINEMA_24_CS) { opj_event_msg(p_manager, EVT_WARNING, ""JPEG 2000 Profile-3 and 4 (2k/4k dc profile) requires:\n"" ""Maximum 1302083 compressed bytes @ 24fps\n"" ""-> Specified rate exceeds this limit. Rate will be forced to 1302083 bytes.\n""); parameters->max_cs_size = OPJ_CINEMA_24_CS; } if (parameters->max_comp_size <= 0) { /* No rate has been introduced, 24 fps is assumed */ parameters->max_comp_size = OPJ_CINEMA_24_COMP; opj_event_msg(p_manager, EVT_WARNING, ""JPEG 2000 Profile-3 and 4 (2k/4k dc profile) requires:\n"" ""Maximum 1041666 compressed bytes @ 24fps\n"" ""As no rate has been given, this limit will be used.\n""); } else if (parameters->max_comp_size > OPJ_CINEMA_24_COMP) { opj_event_msg(p_manager, EVT_WARNING, ""JPEG 2000 Profile-3 and 4 (2k/4k dc profile) requires:\n"" ""Maximum 1041666 compressed bytes @ 24fps\n"" ""-> Specified rate exceeds this limit. Rate will be forced to 1041666 bytes.\n""); parameters->max_comp_size = OPJ_CINEMA_24_COMP; } parameters->tcp_rates[0] = (OPJ_FLOAT32)(image->numcomps * image->comps[0].w * image->comps[0].h * image->comps[0].prec) / (OPJ_FLOAT32)(((OPJ_UINT32)parameters->max_cs_size) * 8 * image->comps[0].dx * image->comps[0].dy); }","{'deleted': [{'line_no': 87, 'char_start': 3193, 'char_end': 3251, 'line': ' parameters->res_spec = parameters->numresolution - 1;\n'}, {'line_no': 88, 'char_start': 3251, 'char_end': 3300, 'line': ' for (i = 0; i < parameters->res_spec; i++) {\n'}, {'line_no': 89, 'char_start': 3300, 'char_end': 3340, 'line': ' parameters->prcw_init[i] = 256;\n'}, {'line_no': 90, 'char_start': 3340, 'char_end': 3380, 'line': ' parameters->prch_init[i] = 256;\n'}], 'added': [{'line_no': 87, 'char_start': 3193, 'char_end': 3235, 'line': ' if (parameters->numresolution == 1) {\n'}, {'line_no': 88, 'char_start': 3235, 'char_end': 3269, 'line': ' parameters->res_spec = 1;\n'}, {'line_no': 89, 'char_start': 3269, 'char_end': 3309, 'line': ' parameters->prcw_init[0] = 128;\n'}, {'line_no': 90, 'char_start': 3309, 'char_end': 3349, 'line': ' parameters->prch_init[0] = 128;\n'}, {'line_no': 91, 'char_start': 3349, 'char_end': 3362, 'line': ' } else {\n'}, {'line_no': 92, 'char_start': 3362, 'char_end': 3424, 'line': ' parameters->res_spec = parameters->numresolution - 1;\n'}, {'line_no': 93, 'char_start': 3424, 'char_end': 3477, 'line': ' for (i = 0; i < parameters->res_spec; i++) {\n'}, {'line_no': 94, 'char_start': 3477, 'char_end': 3521, 'line': ' parameters->prcw_init[i] = 256;\n'}, {'line_no': 95, 'char_start': 3521, 'char_end': 3565, 'line': ' parameters->prch_init[i] = 256;\n'}, {'line_no': 96, 'char_start': 3565, 'char_end': 3575, 'line': ' }\n'}]}","{'deleted': [], 'added': [{'char_start': 3197, 'char_end': 3370, 'chars': 'if (parameters->numresolution == 1) {\n parameters->res_spec = 1;\n parameters->prcw_init[0] = 128;\n parameters->prch_init[0] = 128;\n } else {\n '}, {'char_start': 3424, 'char_end': 3428, 'chars': ' '}, {'char_start': 3485, 'char_end': 3489, 'chars': ' '}, {'char_start': 3521, 'char_end': 3523, 'chars': ' '}, {'char_start': 3531, 'char_end': 3533, 'chars': ' '}, {'char_start': 3564, 'char_end': 3574, 'chars': '\n }'}]}",github.com/uclouvain/openjpeg/commit/4241ae6fbbf1de9658764a80944dc8108f2b4154,src/lib/openjp2/j2k.c,cwe-787,1569 cwe-078,_modify_3par_iscsi_host," def _modify_3par_iscsi_host(self, hostname, iscsi_iqn): # when using -add, you can not send the persona or domain options self.common._cli_run('createhost -iscsi -add %s %s' % (hostname, iscsi_iqn), None)"," def _modify_3par_iscsi_host(self, hostname, iscsi_iqn): # when using -add, you can not send the persona or domain options command = ['createhost', '-iscsi', '-add', hostname, iscsi_iqn] self.common._cli_run(command)","{'deleted': [{'line_no': 3, 'char_start': 134, 'char_end': 194, 'line': "" self.common._cli_run('createhost -iscsi -add %s %s'\n""}, {'line_no': 4, 'char_start': 194, 'char_end': 253, 'line': ' % (hostname, iscsi_iqn), None)\n'}], 'added': [{'line_no': 3, 'char_start': 134, 'char_end': 206, 'line': "" command = ['createhost', '-iscsi', '-add', hostname, iscsi_iqn]\n""}, {'line_no': 4, 'char_start': 206, 'char_end': 243, 'line': ' self.common._cli_run(command)\n'}]}","{'deleted': [{'char_start': 142, 'char_end': 147, 'chars': 'self.'}, {'char_start': 151, 'char_end': 152, 'chars': 'o'}, {'char_start': 153, 'char_end': 163, 'chars': '._cli_run('}, {'char_start': 186, 'char_end': 192, 'chars': ' %s %s'}, {'char_start': 193, 'char_end': 222, 'chars': '\n '}, {'char_start': 223, 'char_end': 226, 'chars': '% ('}, {'char_start': 245, 'char_end': 247, 'chars': '),'}, {'char_start': 248, 'char_end': 249, 'chars': 'N'}, {'char_start': 251, 'char_end': 252, 'chars': 'e'}], 'added': [{'char_start': 146, 'char_end': 147, 'chars': 'a'}, {'char_start': 148, 'char_end': 153, 'chars': 'd = ['}, {'char_start': 164, 'char_end': 166, 'chars': ""',""}, {'char_start': 167, 'char_end': 168, 'chars': ""'""}, {'char_start': 174, 'char_end': 176, 'chars': ""',""}, {'char_start': 177, 'char_end': 178, 'chars': ""'""}, {'char_start': 183, 'char_end': 184, 'chars': ','}, {'char_start': 204, 'char_end': 206, 'chars': ']\n'}, {'char_start': 207, 'char_end': 223, 'chars': ' self.comm'}, {'char_start': 225, 'char_end': 242, 'chars': '._cli_run(command'}]}",github.com/thatsdone/cinder/commit/c55589b131828f3a595903f6796cb2d0babb772f,cinder/volume/drivers/san/hp/hp_3par_iscsi.py,cwe-078,68 cwe-476,avpriv_ac3_parse_header,"int avpriv_ac3_parse_header(AC3HeaderInfo **phdr, const uint8_t *buf, size_t size) { GetBitContext gb; AC3HeaderInfo *hdr; int err; if (!*phdr) *phdr = av_mallocz(sizeof(AC3HeaderInfo)); if (!*phdr) return AVERROR(ENOMEM); hdr = *phdr; init_get_bits8(&gb, buf, size); err = ff_ac3_parse_header(&gb, hdr); if (err < 0) return AVERROR_INVALIDDATA; return get_bits_count(&gb); }","int avpriv_ac3_parse_header(AC3HeaderInfo **phdr, const uint8_t *buf, size_t size) { GetBitContext gb; AC3HeaderInfo *hdr; int err; if (!*phdr) *phdr = av_mallocz(sizeof(AC3HeaderInfo)); if (!*phdr) return AVERROR(ENOMEM); hdr = *phdr; err = init_get_bits8(&gb, buf, size); if (err < 0) return AVERROR_INVALIDDATA; err = ff_ac3_parse_header(&gb, hdr); if (err < 0) return AVERROR_INVALIDDATA; return get_bits_count(&gb); }","{'deleted': [{'line_no': 14, 'char_start': 306, 'char_end': 342, 'line': ' init_get_bits8(&gb, buf, size);\n'}], 'added': [{'line_no': 14, 'char_start': 306, 'char_end': 348, 'line': ' err = init_get_bits8(&gb, buf, size);\n'}, {'line_no': 15, 'char_start': 348, 'char_end': 365, 'line': ' if (err < 0)\n'}, {'line_no': 16, 'char_start': 365, 'char_end': 401, 'line': ' return AVERROR_INVALIDDATA;\n'}]}","{'deleted': [], 'added': [{'char_start': 310, 'char_end': 316, 'chars': 'err = '}, {'char_start': 346, 'char_end': 399, 'chars': ';\n if (err < 0)\n return AVERROR_INVALIDDATA'}]}",github.com/FFmpeg/FFmpeg/commit/00e8181bd97c834fe60751b0c511d4bb97875f78,libavcodec/ac3_parser.c,cwe-476,139 cwe-089,retrieve_playlist_by_id,"def retrieve_playlist_by_id(id, db): db.execute( ""SELECT id, name, video_position from playlist WHERE id={id};"".format(id=id)) row = db.fetchone() return row","def retrieve_playlist_by_id(id, db): db.execute( ""SELECT id, name, video_position from playlist WHERE id=%s;"", (id,)) row = db.fetchone() return row","{'deleted': [{'line_no': 3, 'char_start': 53, 'char_end': 139, 'line': ' ""SELECT id, name, video_position from playlist WHERE id={id};"".format(id=id))\n'}], 'added': [{'line_no': 3, 'char_start': 53, 'char_end': 130, 'line': ' ""SELECT id, name, video_position from playlist WHERE id=%s;"", (id,))\n'}]}","{'deleted': [{'char_start': 117, 'char_end': 121, 'chars': '{id}'}, {'char_start': 123, 'char_end': 130, 'chars': '.format'}, {'char_start': 133, 'char_end': 136, 'chars': '=id'}], 'added': [{'char_start': 117, 'char_end': 119, 'chars': '%s'}, {'char_start': 121, 'char_end': 123, 'chars': ', '}, {'char_start': 126, 'char_end': 127, 'chars': ','}]}",github.com/Madmous/playlist/commit/666e52c5f0b8c1f4296e84471637033d9542a7a6,playlist/playlist_repository.py,cwe-089,43 cwe-089,get_login,"@bot.message_handler(commands =['login']) def get_login(message): settings = sqlite3.connect(os.path.abspath(os.path.dirname(__file__)) + ""\\bases\\settings.db"") conn = settings.cursor() conn.execute(""select * from users where chat_id = '"" + str(message.chat.id) + ""'"") name = conn.fetchone() if name != None: bot.send_message(message.chat.id, ""Previous handle: "" + str(name[1])) else: bot.send_message(message.chat.id, ""Previous handle: None"") settings.close() bot.send_message(message.chat.id, ""Type new handle: "") set_state(message.chat.id, config.States.S_LOGIN.value)","@bot.message_handler(commands =['login']) def get_login(message): settings = sqlite3.connect(os.path.abspath(os.path.dirname(__file__)) + ""\\bases\\settings.db"") conn = settings.cursor() conn.execute(""select * from users where chat_id = ?"", (str(message.chat.id),)) name = conn.fetchone() if name != None: bot.send_message(message.chat.id, ""Previous handle: "" + str(name[1])) else: bot.send_message(message.chat.id, ""Previous handle: None"") settings.close() bot.send_message(message.chat.id, ""Type new handle: "") set_state(message.chat.id, config.States.S_LOGIN.value)","{'deleted': [{'line_no': 5, 'char_start': 195, 'char_end': 282, 'line': ' conn.execute(""select * from users where chat_id = \'"" + str(message.chat.id) + ""\'"")\n'}], 'added': [{'line_no': 5, 'char_start': 195, 'char_end': 278, 'line': ' conn.execute(""select * from users where chat_id = ?"", (str(message.chat.id),))\n'}]}","{'deleted': [{'char_start': 249, 'char_end': 250, 'chars': ""'""}, {'char_start': 251, 'char_end': 253, 'chars': ' +'}, {'char_start': 274, 'char_end': 280, 'chars': ' + ""\'""'}], 'added': [{'char_start': 249, 'char_end': 250, 'chars': '?'}, {'char_start': 251, 'char_end': 252, 'chars': ','}, {'char_start': 253, 'char_end': 254, 'chars': '('}, {'char_start': 274, 'char_end': 276, 'chars': ',)'}]}",github.com/lissrbay/codeforces_bot/commit/cc7f5143445a0030b1149ac60a65b1b1b9c92a90,bot.py,cwe-089,144 cwe-022,dd_delete_item,"int dd_delete_item(struct dump_dir *dd, const char *name) { if (!dd->locked) error_msg_and_die(""dump_dir is not opened""); /* bug */ char *path = concat_path_file(dd->dd_dirname, name); int res = unlink(path); if (res < 0) { if (errno == ENOENT) errno = res = 0; else perror_msg(""Can't delete file '%s'"", path); } free(path); return res; }","int dd_delete_item(struct dump_dir *dd, const char *name) { if (!dd->locked) error_msg_and_die(""dump_dir is not opened""); /* bug */ if (!str_is_correct_filename(name)) error_msg_and_die(""Cannot delete item. '%s' is not a valid file name"", name); char *path = concat_path_file(dd->dd_dirname, name); int res = unlink(path); if (res < 0) { if (errno == ENOENT) errno = res = 0; else perror_msg(""Can't delete file '%s'"", path); } free(path); return res; }","{'deleted': [], 'added': [{'line_no': 6, 'char_start': 145, 'char_end': 185, 'line': ' if (!str_is_correct_filename(name))\n'}, {'line_no': 7, 'char_start': 185, 'char_end': 271, 'line': ' error_msg_and_die(""Cannot delete item. \'%s\' is not a valid file name"", name);\n'}, {'line_no': 8, 'char_start': 271, 'char_end': 272, 'line': '\n'}]}","{'deleted': [], 'added': [{'char_start': 149, 'char_end': 276, 'chars': 'if (!str_is_correct_filename(name))\n error_msg_and_die(""Cannot delete item. \'%s\' is not a valid file name"", name);\n\n '}]}",github.com/abrt/libreport/commit/239c4f7d1f47265526b39ad70106767d00805277,src/lib/dump_dir.c,cwe-022,115 cwe-787,decode_frame,"static int decode_frame(AVCodecContext *avctx, void *data, int *got_frame, AVPacket *avpkt) { PicContext *s = avctx->priv_data; AVFrame *frame = data; uint32_t *palette; int bits_per_plane, bpp, etype, esize, npal, pos_after_pal; int i, x, y, plane, tmp, ret, val; bytestream2_init(&s->g, avpkt->data, avpkt->size); if (bytestream2_get_bytes_left(&s->g) < 11) return AVERROR_INVALIDDATA; if (bytestream2_get_le16u(&s->g) != 0x1234) return AVERROR_INVALIDDATA; s->width = bytestream2_get_le16u(&s->g); s->height = bytestream2_get_le16u(&s->g); bytestream2_skip(&s->g, 4); tmp = bytestream2_get_byteu(&s->g); bits_per_plane = tmp & 0xF; s->nb_planes = (tmp >> 4) + 1; bpp = bits_per_plane * s->nb_planes; if (bits_per_plane > 8 || bpp < 1 || bpp > 32) { avpriv_request_sample(avctx, ""Unsupported bit depth""); return AVERROR_PATCHWELCOME; } if (bytestream2_peek_byte(&s->g) == 0xFF || bpp == 1 || bpp == 4 || bpp == 8) { bytestream2_skip(&s->g, 2); etype = bytestream2_get_le16(&s->g); esize = bytestream2_get_le16(&s->g); if (bytestream2_get_bytes_left(&s->g) < esize) return AVERROR_INVALIDDATA; } else { etype = -1; esize = 0; } avctx->pix_fmt = AV_PIX_FMT_PAL8; if (av_image_check_size(s->width, s->height, 0, avctx) < 0) return -1; if (s->width != avctx->width && s->height != avctx->height) { ret = ff_set_dimensions(avctx, s->width, s->height); if (ret < 0) return ret; } if ((ret = ff_get_buffer(avctx, frame, 0)) < 0) return ret; memset(frame->data[0], 0, s->height * frame->linesize[0]); frame->pict_type = AV_PICTURE_TYPE_I; frame->palette_has_changed = 1; pos_after_pal = bytestream2_tell(&s->g) + esize; palette = (uint32_t*)frame->data[1]; if (etype == 1 && esize > 1 && bytestream2_peek_byte(&s->g) < 6) { int idx = bytestream2_get_byte(&s->g); npal = 4; for (i = 0; i < npal; i++) palette[i] = ff_cga_palette[ cga_mode45_index[idx][i] ]; } else if (etype == 2) { npal = FFMIN(esize, 16); for (i = 0; i < npal; i++) { int pal_idx = bytestream2_get_byte(&s->g); palette[i] = ff_cga_palette[FFMIN(pal_idx, 15)]; } } else if (etype == 3) { npal = FFMIN(esize, 16); for (i = 0; i < npal; i++) { int pal_idx = bytestream2_get_byte(&s->g); palette[i] = ff_ega_palette[FFMIN(pal_idx, 63)]; } } else if (etype == 4 || etype == 5) { npal = FFMIN(esize / 3, 256); for (i = 0; i < npal; i++) { palette[i] = bytestream2_get_be24(&s->g) << 2; palette[i] |= 0xFFU << 24 | palette[i] >> 6 & 0x30303; } } else { if (bpp == 1) { npal = 2; palette[0] = 0xFF000000; palette[1] = 0xFFFFFFFF; } else if (bpp == 2) { npal = 4; for (i = 0; i < npal; i++) palette[i] = ff_cga_palette[ cga_mode45_index[0][i] ]; } else { npal = 16; memcpy(palette, ff_cga_palette, npal * 4); } } // fill remaining palette entries memset(palette + npal, 0, AVPALETTE_SIZE - npal * 4); // skip remaining palette bytes bytestream2_seek(&s->g, pos_after_pal, SEEK_SET); val = 0; y = s->height - 1; if (bytestream2_get_le16(&s->g)) { x = 0; plane = 0; while (bytestream2_get_bytes_left(&s->g) >= 6) { int stop_size, marker, t1, t2; t1 = bytestream2_get_bytes_left(&s->g); t2 = bytestream2_get_le16(&s->g); stop_size = t1 - FFMIN(t1, t2); // ignore uncompressed block size bytestream2_skip(&s->g, 2); marker = bytestream2_get_byte(&s->g); while (plane < s->nb_planes && bytestream2_get_bytes_left(&s->g) > stop_size) { int run = 1; val = bytestream2_get_byte(&s->g); if (val == marker) { run = bytestream2_get_byte(&s->g); if (run == 0) run = bytestream2_get_le16(&s->g); val = bytestream2_get_byte(&s->g); } if (!bytestream2_get_bytes_left(&s->g)) break; if (bits_per_plane == 8) { picmemset_8bpp(s, frame, val, run, &x, &y); if (y < 0) goto finish; } else { picmemset(s, frame, val, run, &x, &y, &plane, bits_per_plane); } } } if (x < avctx->width) { int run = (y + 1) * avctx->width - x; if (bits_per_plane == 8) picmemset_8bpp(s, frame, val, run, &x, &y); else picmemset(s, frame, val, run / (8 / bits_per_plane), &x, &y, &plane, bits_per_plane); } } else { while (y >= 0 && bytestream2_get_bytes_left(&s->g) > 0) { memcpy(frame->data[0] + y * frame->linesize[0], s->g.buffer, FFMIN(avctx->width, bytestream2_get_bytes_left(&s->g))); bytestream2_skip(&s->g, avctx->width); y--; } } finish: *got_frame = 1; return avpkt->size; }","static int decode_frame(AVCodecContext *avctx, void *data, int *got_frame, AVPacket *avpkt) { PicContext *s = avctx->priv_data; AVFrame *frame = data; uint32_t *palette; int bits_per_plane, bpp, etype, esize, npal, pos_after_pal; int i, x, y, plane, tmp, ret, val; bytestream2_init(&s->g, avpkt->data, avpkt->size); if (bytestream2_get_bytes_left(&s->g) < 11) return AVERROR_INVALIDDATA; if (bytestream2_get_le16u(&s->g) != 0x1234) return AVERROR_INVALIDDATA; s->width = bytestream2_get_le16u(&s->g); s->height = bytestream2_get_le16u(&s->g); bytestream2_skip(&s->g, 4); tmp = bytestream2_get_byteu(&s->g); bits_per_plane = tmp & 0xF; s->nb_planes = (tmp >> 4) + 1; bpp = bits_per_plane * s->nb_planes; if (bits_per_plane > 8 || bpp < 1 || bpp > 32) { avpriv_request_sample(avctx, ""Unsupported bit depth""); return AVERROR_PATCHWELCOME; } if (bytestream2_peek_byte(&s->g) == 0xFF || bpp == 1 || bpp == 4 || bpp == 8) { bytestream2_skip(&s->g, 2); etype = bytestream2_get_le16(&s->g); esize = bytestream2_get_le16(&s->g); if (bytestream2_get_bytes_left(&s->g) < esize) return AVERROR_INVALIDDATA; } else { etype = -1; esize = 0; } avctx->pix_fmt = AV_PIX_FMT_PAL8; if (av_image_check_size(s->width, s->height, 0, avctx) < 0) return -1; if (s->width != avctx->width || s->height != avctx->height) { ret = ff_set_dimensions(avctx, s->width, s->height); if (ret < 0) return ret; } if ((ret = ff_get_buffer(avctx, frame, 0)) < 0) return ret; memset(frame->data[0], 0, s->height * frame->linesize[0]); frame->pict_type = AV_PICTURE_TYPE_I; frame->palette_has_changed = 1; pos_after_pal = bytestream2_tell(&s->g) + esize; palette = (uint32_t*)frame->data[1]; if (etype == 1 && esize > 1 && bytestream2_peek_byte(&s->g) < 6) { int idx = bytestream2_get_byte(&s->g); npal = 4; for (i = 0; i < npal; i++) palette[i] = ff_cga_palette[ cga_mode45_index[idx][i] ]; } else if (etype == 2) { npal = FFMIN(esize, 16); for (i = 0; i < npal; i++) { int pal_idx = bytestream2_get_byte(&s->g); palette[i] = ff_cga_palette[FFMIN(pal_idx, 15)]; } } else if (etype == 3) { npal = FFMIN(esize, 16); for (i = 0; i < npal; i++) { int pal_idx = bytestream2_get_byte(&s->g); palette[i] = ff_ega_palette[FFMIN(pal_idx, 63)]; } } else if (etype == 4 || etype == 5) { npal = FFMIN(esize / 3, 256); for (i = 0; i < npal; i++) { palette[i] = bytestream2_get_be24(&s->g) << 2; palette[i] |= 0xFFU << 24 | palette[i] >> 6 & 0x30303; } } else { if (bpp == 1) { npal = 2; palette[0] = 0xFF000000; palette[1] = 0xFFFFFFFF; } else if (bpp == 2) { npal = 4; for (i = 0; i < npal; i++) palette[i] = ff_cga_palette[ cga_mode45_index[0][i] ]; } else { npal = 16; memcpy(palette, ff_cga_palette, npal * 4); } } // fill remaining palette entries memset(palette + npal, 0, AVPALETTE_SIZE - npal * 4); // skip remaining palette bytes bytestream2_seek(&s->g, pos_after_pal, SEEK_SET); val = 0; y = s->height - 1; if (bytestream2_get_le16(&s->g)) { x = 0; plane = 0; while (bytestream2_get_bytes_left(&s->g) >= 6) { int stop_size, marker, t1, t2; t1 = bytestream2_get_bytes_left(&s->g); t2 = bytestream2_get_le16(&s->g); stop_size = t1 - FFMIN(t1, t2); // ignore uncompressed block size bytestream2_skip(&s->g, 2); marker = bytestream2_get_byte(&s->g); while (plane < s->nb_planes && bytestream2_get_bytes_left(&s->g) > stop_size) { int run = 1; val = bytestream2_get_byte(&s->g); if (val == marker) { run = bytestream2_get_byte(&s->g); if (run == 0) run = bytestream2_get_le16(&s->g); val = bytestream2_get_byte(&s->g); } if (!bytestream2_get_bytes_left(&s->g)) break; if (bits_per_plane == 8) { picmemset_8bpp(s, frame, val, run, &x, &y); if (y < 0) goto finish; } else { picmemset(s, frame, val, run, &x, &y, &plane, bits_per_plane); } } } if (x < avctx->width) { int run = (y + 1) * avctx->width - x; if (bits_per_plane == 8) picmemset_8bpp(s, frame, val, run, &x, &y); else picmemset(s, frame, val, run / (8 / bits_per_plane), &x, &y, &plane, bits_per_plane); } } else { while (y >= 0 && bytestream2_get_bytes_left(&s->g) > 0) { memcpy(frame->data[0] + y * frame->linesize[0], s->g.buffer, FFMIN(avctx->width, bytestream2_get_bytes_left(&s->g))); bytestream2_skip(&s->g, avctx->width); y--; } } finish: *got_frame = 1; return avpkt->size; }","{'deleted': [{'line_no': 46, 'char_start': 1512, 'char_end': 1578, 'line': ' if (s->width != avctx->width && s->height != avctx->height) {\n'}], 'added': [{'line_no': 46, 'char_start': 1512, 'char_end': 1578, 'line': ' if (s->width != avctx->width || s->height != avctx->height) {\n'}]}","{'deleted': [{'char_start': 1545, 'char_end': 1547, 'chars': '&&'}], 'added': [{'char_start': 1545, 'char_end': 1547, 'chars': '||'}]}",github.com/FFmpeg/FFmpeg/commit/8c2ea3030af7b40a3c4275696fb5c76cdb80950a,libavcodec/pictordec.c,cwe-787,1779 cwe-089,findNPC,"def findNPC(race, classe, sex,level): c, conn = getConnection() date = now() #select image, SUM(legit) as l FROM npc WHERE race='Elf' AND class='Bard' AND sex='Male' GROUP BY image HAVING l>5 ORDER BY SUM(legit) DESC; c.execute(""select image, avg(legit) as l FROM npc WHERE race='""+race+""' AND class='""+classe+""' AND sex='""+sex+""' GROUP BY image HAVING l > 5 ORDER BY SUM(legit) DESC;"") conn.commit() out = c.fetchmany(5) conn.close() return out","def findNPC(race, classe, sex,level): c, conn = getConnection() date = now() #select image, SUM(legit) as l FROM npc WHERE race='Elf' AND class='Bard' AND sex='Male' GROUP BY image HAVING l>5 ORDER BY SUM(legit) DESC; c.execute(""select image, avg(legit) as l FROM npc WHERE race=(?) AND class=(?) AND sex=(?) GROUP BY image HAVING l > 5 ORDER BY SUM(legit) DESC"",(race,classe,sex)) conn.commit() out = c.fetchmany(5) conn.close() return out","{'deleted': [{'line_no': 5, 'char_start': 221, 'char_end': 391, 'line': '\tc.execute(""select image, avg(legit) as l FROM npc WHERE race=\'""+race+""\' AND class=\'""+classe+""\' AND sex=\'""+sex+""\' GROUP BY image HAVING l > 5 ORDER BY SUM(legit) DESC;"")\n'}], 'added': [{'line_no': 5, 'char_start': 221, 'char_end': 386, 'line': '\tc.execute(""select image, avg(legit) as l FROM npc WHERE race=(?) AND class=(?) AND sex=(?) GROUP BY image HAVING l > 5 ORDER BY SUM(legit) DESC"",(race,classe,sex))\n'}]}","{'deleted': [{'char_start': 283, 'char_end': 293, 'chars': '\'""+race+""\''}, {'char_start': 304, 'char_end': 316, 'chars': '\'""+classe+""\''}, {'char_start': 325, 'char_end': 334, 'chars': '\'""+sex+""\''}, {'char_start': 387, 'char_end': 388, 'chars': ';'}], 'added': [{'char_start': 283, 'char_end': 286, 'chars': '(?)'}, {'char_start': 297, 'char_end': 300, 'chars': '(?)'}, {'char_start': 309, 'char_end': 312, 'chars': '(?)'}, {'char_start': 366, 'char_end': 384, 'chars': ',(race,classe,sex)'}]}",github.com/DangerBlack/DungeonsAndDragonsMasterBot/commit/63f980c6dff746f5fcf3005d0646b6c24f81cdc0,database.py,cwe-089,134 cwe-089,delete,"@mod.route('/delete/', methods=['GET', 'POST']) def delete(cmt_id): if request.method == 'GET': sql = ""SELECT msg_id FROM comment where cmt_id = %d;"" % (cmt_id) cursor.execute(sql) m = cursor.fetchone() sql = ""DELETE FROM comment where cmt_id = '%d';"" % (cmt_id) cursor.execute(sql) conn.commit() flash('Delete Success!') return redirect(url_for('comment.show', msg_id=m[0]))","@mod.route('/delete/', methods=['GET', 'POST']) def delete(cmt_id): if request.method == 'GET': cursor.execute(""SELECT msg_id FROM comment where cmt_id = %s;"", (cmt_id,)) m = cursor.fetchone() cursor.execute(""DELETE FROM comment where cmt_id = %s;"", (cmt_id,)) conn.commit() flash('Delete Success!') return redirect(url_for('comment.show', msg_id=m[0]))","{'deleted': [{'line_no': 4, 'char_start': 112, 'char_end': 185, 'line': ' sql = ""SELECT msg_id FROM comment where cmt_id = %d;"" % (cmt_id)\n'}, {'line_no': 5, 'char_start': 185, 'char_end': 213, 'line': ' cursor.execute(sql)\n'}, {'line_no': 7, 'char_start': 243, 'char_end': 311, 'line': ' sql = ""DELETE FROM comment where cmt_id = \'%d\';"" % (cmt_id)\n'}, {'line_no': 8, 'char_start': 311, 'char_end': 339, 'line': ' cursor.execute(sql)\n'}], 'added': [{'line_no': 4, 'char_start': 112, 'char_end': 195, 'line': ' cursor.execute(""SELECT msg_id FROM comment where cmt_id = %s;"", (cmt_id,))\n'}, {'line_no': 6, 'char_start': 225, 'char_end': 301, 'line': ' cursor.execute(""DELETE FROM comment where cmt_id = %s;"", (cmt_id,))\n'}]}","{'deleted': [{'char_start': 121, 'char_end': 126, 'chars': 'ql = '}, {'char_start': 170, 'char_end': 171, 'chars': 'd'}, {'char_start': 173, 'char_end': 175, 'chars': ' %'}, {'char_start': 184, 'char_end': 211, 'chars': '\n cursor.execute(sql'}, {'char_start': 252, 'char_end': 257, 'chars': 'ql = '}, {'char_start': 293, 'char_end': 294, 'chars': ""'""}, {'char_start': 295, 'char_end': 297, 'chars': ""d'""}, {'char_start': 299, 'char_end': 301, 'chars': ' %'}, {'char_start': 310, 'char_end': 337, 'chars': '\n cursor.execute(sql'}], 'added': [{'char_start': 120, 'char_end': 123, 'chars': 'cur'}, {'char_start': 124, 'char_end': 135, 'chars': 'or.execute('}, {'char_start': 179, 'char_end': 180, 'chars': 's'}, {'char_start': 182, 'char_end': 183, 'chars': ','}, {'char_start': 191, 'char_end': 193, 'chars': ',)'}, {'char_start': 203, 'char_end': 207, 'chars': 'm = '}, {'char_start': 214, 'char_end': 215, 'chars': 'f'}, {'char_start': 217, 'char_end': 221, 'chars': 'chon'}, {'char_start': 241, 'char_end': 245, 'chars': 'xecu'}, {'char_start': 285, 'char_end': 286, 'chars': 's'}, {'char_start': 288, 'char_end': 289, 'chars': ','}, {'char_start': 297, 'char_end': 298, 'chars': ','}]}",github.com/ulyssetsd/bjtu-sql/commit/17d7b21864b72ba5666f15236474a93268b32ec9,flaskr/flaskr/views/comment.py,cwe-089,118 cwe-125,HPHP::exif_scan_JPEG_header,"static int exif_scan_JPEG_header(image_info_type *ImageInfo) { int section, sn; int marker = 0, last_marker = M_PSEUDO, comment_correction=1; int ll, lh; unsigned char *Data; size_t fpos, size, got, itemlen; jpeg_sof_info sof_info; for(section=0;;section++) { // get marker byte, swallowing possible padding // some software does not count the length bytes of COM section // one company doing so is very much envolved in JPEG... // so we accept too if (last_marker==M_COM && comment_correction) { comment_correction = 2; } do { if ((marker = ImageInfo->infile->getc()) == EOF) { raise_warning(""File structure corrupted""); return 0; } if (last_marker==M_COM && comment_correction>0) { if (marker!=0xFF) { marker = 0xff; comment_correction--; } else { last_marker = M_PSEUDO; /* stop skipping 0 for M_COM */ } } } while (marker == 0xff); if (last_marker==M_COM && !comment_correction) { raise_notice(""Image has corrupt COM section: some software set "" ""wrong length information""); } if (last_marker==M_COM && comment_correction) return M_EOI; /* ah illegal: char after COM section not 0xFF */ fpos = ImageInfo->infile->tell(); if (marker == 0xff) { // 0xff is legal padding, but if we get that many, something's wrong. raise_warning(""To many padding bytes""); return 0; } /* Read the length of the section. */ if ((lh = ImageInfo->infile->getc()) == EOF) { raise_warning(""File structure corrupted""); return 0; } if ((ll = ImageInfo->infile->getc()) == EOF) { raise_warning(""File structure corrupted""); return 0; } itemlen = (lh << 8) | ll; if (itemlen < 2) { raise_warning(""File structure corrupted""); return 0; } sn = exif_file_sections_add(ImageInfo, marker, itemlen+1, nullptr); if (sn == -1) return 0; Data = ImageInfo->file.list[sn].data; /* Store first two pre-read bytes. */ Data[0] = (unsigned char)lh; Data[1] = (unsigned char)ll; String str = ImageInfo->infile->read(itemlen-2); got = str.length(); if (got != itemlen-2) { raise_warning(""Error reading from file: "" ""got=x%04lX(=%lu) != itemlen-2=x%04lX(=%lu)"", got, got, itemlen-2, itemlen-2); return 0; } memcpy(Data+2, str.c_str(), got); switch(marker) { case M_SOS: /* stop before hitting compressed data */ // If reading entire image is requested, read the rest of the data. if (ImageInfo->read_all) { /* Determine how much file is left. */ fpos = ImageInfo->infile->tell(); size = ImageInfo->FileSize - fpos; sn = exif_file_sections_add(ImageInfo, M_PSEUDO, size, nullptr); if (sn == -1) return 0; Data = ImageInfo->file.list[sn].data; str = ImageInfo->infile->read(size); got = str.length(); if (got != size) { raise_warning(""Unexpected end of file reached""); return 0; } memcpy(Data, str.c_str(), got); } return 1; case M_EOI: /* in case it's a tables-only JPEG stream */ raise_warning(""No image in jpeg!""); return (ImageInfo->sections_found&(~FOUND_COMPUTED)) ? 1 : 0; case M_COM: /* Comment section */ exif_process_COM(ImageInfo, (char *)Data, itemlen); break; case M_EXIF: if (!(ImageInfo->sections_found&FOUND_IFD0)) { /*ImageInfo->sections_found |= FOUND_EXIF;*/ /* Seen files from some 'U-lead' software with Vivitar scanner that uses marker 31 later in the file (no clue what for!) */ exif_process_APP1(ImageInfo, (char *)Data, itemlen, fpos); } break; case M_APP12: exif_process_APP12(ImageInfo, (char *)Data, itemlen); break; case M_SOF0: case M_SOF1: case M_SOF2: case M_SOF3: case M_SOF5: case M_SOF6: case M_SOF7: case M_SOF9: case M_SOF10: case M_SOF11: case M_SOF13: case M_SOF14: case M_SOF15: exif_process_SOFn(Data, marker, &sof_info); ImageInfo->Width = sof_info.width; ImageInfo->Height = sof_info.height; if (sof_info.num_components == 3) { ImageInfo->IsColor = 1; } else { ImageInfo->IsColor = 0; } break; default: /* skip any other marker silently. */ break; } /* keep track of last marker */ last_marker = marker; } return 1; }","static int exif_scan_JPEG_header(image_info_type *ImageInfo) { int section, sn; int marker = 0, last_marker = M_PSEUDO, comment_correction=1; int ll, lh; unsigned char *Data; size_t fpos, size, got, itemlen; jpeg_sof_info sof_info; for(section=0;;section++) { // get marker byte, swallowing possible padding // some software does not count the length bytes of COM section // one company doing so is very much envolved in JPEG... // so we accept too if (last_marker==M_COM && comment_correction) { comment_correction = 2; } do { if ((marker = ImageInfo->infile->getc()) == EOF) { raise_warning(""File structure corrupted""); return 0; } if (last_marker==M_COM && comment_correction>0) { if (marker!=0xFF) { marker = 0xff; comment_correction--; } else { last_marker = M_PSEUDO; /* stop skipping 0 for M_COM */ } } } while (marker == 0xff); if (last_marker==M_COM && !comment_correction) { raise_notice(""Image has corrupt COM section: some software set "" ""wrong length information""); } if (last_marker==M_COM && comment_correction) return M_EOI; /* ah illegal: char after COM section not 0xFF */ fpos = ImageInfo->infile->tell(); if (marker == 0xff) { // 0xff is legal padding, but if we get that many, something's wrong. raise_warning(""To many padding bytes""); return 0; } /* Read the length of the section. */ if ((lh = ImageInfo->infile->getc()) == EOF) { raise_warning(""File structure corrupted""); return 0; } if ((ll = ImageInfo->infile->getc()) == EOF) { raise_warning(""File structure corrupted""); return 0; } itemlen = (lh << 8) | ll; if (itemlen < 2) { raise_warning(""File structure corrupted""); return 0; } sn = exif_file_sections_add(ImageInfo, marker, itemlen+1, nullptr); if (sn == -1) return 0; Data = ImageInfo->file.list[sn].data; /* Store first two pre-read bytes. */ Data[0] = (unsigned char)lh; Data[1] = (unsigned char)ll; String str = ImageInfo->infile->read(itemlen-2); got = str.length(); if (got != itemlen-2) { raise_warning(""Error reading from file: "" ""got=x%04lX(=%lu) != itemlen-2=x%04lX(=%lu)"", got, got, itemlen-2, itemlen-2); return 0; } memcpy(Data+2, str.c_str(), got); switch(marker) { case M_SOS: /* stop before hitting compressed data */ // If reading entire image is requested, read the rest of the data. if (ImageInfo->read_all) { /* Determine how much file is left. */ fpos = ImageInfo->infile->tell(); size = ImageInfo->FileSize - fpos; sn = exif_file_sections_add(ImageInfo, M_PSEUDO, size, nullptr); if (sn == -1) return 0; Data = ImageInfo->file.list[sn].data; str = ImageInfo->infile->read(size); got = str.length(); if (got != size) { raise_warning(""Unexpected end of file reached""); return 0; } memcpy(Data, str.c_str(), got); } return 1; case M_EOI: /* in case it's a tables-only JPEG stream */ raise_warning(""No image in jpeg!""); return (ImageInfo->sections_found&(~FOUND_COMPUTED)) ? 1 : 0; case M_COM: /* Comment section */ exif_process_COM(ImageInfo, (char *)Data, itemlen); break; case M_EXIF: if (!(ImageInfo->sections_found&FOUND_IFD0)) { /*ImageInfo->sections_found |= FOUND_EXIF;*/ /* Seen files from some 'U-lead' software with Vivitar scanner that uses marker 31 later in the file (no clue what for!) */ exif_process_APP1(ImageInfo, (char *)Data, itemlen, fpos); } break; case M_APP12: exif_process_APP12(ImageInfo, (char *)Data, itemlen); break; case M_SOF0: case M_SOF1: case M_SOF2: case M_SOF3: case M_SOF5: case M_SOF6: case M_SOF7: case M_SOF9: case M_SOF10: case M_SOF11: case M_SOF13: case M_SOF14: case M_SOF15: if ((itemlen - 2) < 6) { return 0; } exif_process_SOFn(Data, marker, &sof_info); ImageInfo->Width = sof_info.width; ImageInfo->Height = sof_info.height; if (sof_info.num_components == 3) { ImageInfo->IsColor = 1; } else { ImageInfo->IsColor = 0; } break; default: /* skip any other marker silently. */ break; } /* keep track of last marker */ last_marker = marker; } return 1; }","{'deleted': [], 'added': [{'line_no': 137, 'char_start': 4277, 'char_end': 4310, 'line': ' if ((itemlen - 2) < 6) {\n'}, {'line_no': 138, 'char_start': 4310, 'char_end': 4330, 'line': ' return 0;\n'}, {'line_no': 139, 'char_start': 4330, 'char_end': 4340, 'line': ' }\n'}, {'line_no': 140, 'char_start': 4340, 'char_end': 4341, 'line': '\n'}]}","{'deleted': [], 'added': [{'char_start': 4285, 'char_end': 4349, 'chars': 'if ((itemlen - 2) < 6) {\n return 0;\n }\n\n '}]}",github.com/facebook/hhvm/commit/f9680d21beaa9eb39d166e8810e29fbafa51ad15,hphp/runtime/ext/gd/ext_gd.cpp,cwe-125,1269 cwe-787,flb_gzip_compress,"int flb_gzip_compress(void *in_data, size_t in_len, void **out_data, size_t *out_len) { int flush; int status; int footer_start; uint8_t *pb; size_t out_size; void *out_buf; z_stream strm; mz_ulong crc; out_size = in_len + 32; out_buf = flb_malloc(out_size); if (!out_buf) { flb_errno(); flb_error(""[gzip] could not allocate outgoing buffer""); return -1; } /* Initialize streaming buffer context */ memset(&strm, '\0', sizeof(strm)); strm.zalloc = Z_NULL; strm.zfree = Z_NULL; strm.opaque = Z_NULL; strm.next_in = in_data; strm.avail_in = in_len; strm.total_out = 0; /* Deflate mode */ deflateInit2(&strm, Z_DEFAULT_COMPRESSION, Z_DEFLATED, -Z_DEFAULT_WINDOW_BITS, 9, Z_DEFAULT_STRATEGY); /* * Miniz don't support GZip format directly, instead we will: * * - append manual GZip magic bytes * - deflate raw content * - append manual CRC32 data */ gzip_header(out_buf); /* Header offset */ pb = (uint8_t *) out_buf + FLB_GZIP_HEADER_OFFSET; flush = Z_NO_FLUSH; while (1) { strm.next_out = pb + strm.total_out; strm.avail_out = out_size - (pb - (uint8_t *) out_buf); if (strm.avail_in == 0) { flush = Z_FINISH; } status = deflate(&strm, flush); if (status == Z_STREAM_END) { break; } else if (status != Z_OK) { deflateEnd(&strm); return -1; } } if (deflateEnd(&strm) != Z_OK) { flb_free(out_buf); return -1; } *out_len = strm.total_out; /* Construct the gzip checksum (CRC32 footer) */ footer_start = FLB_GZIP_HEADER_OFFSET + *out_len; pb = (uint8_t *) out_buf + footer_start; crc = mz_crc32(MZ_CRC32_INIT, in_data, in_len); *pb++ = crc & 0xFF; *pb++ = (crc >> 8) & 0xFF; *pb++ = (crc >> 16) & 0xFF; *pb++ = (crc >> 24) & 0xFF; *pb++ = in_len & 0xFF; *pb++ = (in_len >> 8) & 0xFF; *pb++ = (in_len >> 16) & 0xFF; *pb++ = (in_len >> 24) & 0xFF; /* Set the real buffer size for the caller */ *out_len += FLB_GZIP_HEADER_OFFSET + 8; *out_data = out_buf; return 0; }","int flb_gzip_compress(void *in_data, size_t in_len, void **out_data, size_t *out_len) { int flush; int status; int footer_start; uint8_t *pb; size_t out_size; void *out_buf; z_stream strm; mz_ulong crc; /* * GZIP relies on an algorithm with worst-case expansion * of 5 bytes per 32KB data. This means we need to create a variable * length output, that depends on the input length. * See RFC 1951 for details. */ int max_input_expansion = ((int)(in_len / 32000) + 1) * 5; /* * Max compressed size is equal to sum of: * 10 byte header * 8 byte foot * max input expansion * size of input */ out_size = 10 + 8 + max_input_expansion + in_len; out_buf = flb_malloc(out_size); if (!out_buf) { flb_errno(); flb_error(""[gzip] could not allocate outgoing buffer""); return -1; } /* Initialize streaming buffer context */ memset(&strm, '\0', sizeof(strm)); strm.zalloc = Z_NULL; strm.zfree = Z_NULL; strm.opaque = Z_NULL; strm.next_in = in_data; strm.avail_in = in_len; strm.total_out = 0; /* Deflate mode */ deflateInit2(&strm, Z_DEFAULT_COMPRESSION, Z_DEFLATED, -Z_DEFAULT_WINDOW_BITS, 9, Z_DEFAULT_STRATEGY); /* * Miniz don't support GZip format directly, instead we will: * * - append manual GZip magic bytes * - deflate raw content * - append manual CRC32 data */ gzip_header(out_buf); /* Header offset */ pb = (uint8_t *) out_buf + FLB_GZIP_HEADER_OFFSET; flush = Z_NO_FLUSH; while (1) { strm.next_out = pb + strm.total_out; strm.avail_out = out_size - (pb - (uint8_t *) out_buf); if (strm.avail_in == 0) { flush = Z_FINISH; } status = deflate(&strm, flush); if (status == Z_STREAM_END) { break; } else if (status != Z_OK) { deflateEnd(&strm); return -1; } } if (deflateEnd(&strm) != Z_OK) { flb_free(out_buf); return -1; } *out_len = strm.total_out; /* Construct the gzip checksum (CRC32 footer) */ footer_start = FLB_GZIP_HEADER_OFFSET + *out_len; pb = (uint8_t *) out_buf + footer_start; crc = mz_crc32(MZ_CRC32_INIT, in_data, in_len); *pb++ = crc & 0xFF; *pb++ = (crc >> 8) & 0xFF; *pb++ = (crc >> 16) & 0xFF; *pb++ = (crc >> 24) & 0xFF; *pb++ = in_len & 0xFF; *pb++ = (in_len >> 8) & 0xFF; *pb++ = (in_len >> 16) & 0xFF; *pb++ = (in_len >> 24) & 0xFF; /* Set the real buffer size for the caller */ *out_len += FLB_GZIP_HEADER_OFFSET + 8; *out_data = out_buf; return 0; }","{'deleted': [{'line_no': 13, 'char_start': 258, 'char_end': 286, 'line': ' out_size = in_len + 32;\n'}], 'added': [{'line_no': 13, 'char_start': 258, 'char_end': 259, 'line': '\n'}, {'line_no': 14, 'char_start': 259, 'char_end': 266, 'line': ' /*\n'}, {'line_no': 15, 'char_start': 266, 'char_end': 327, 'line': ' * GZIP relies on an algorithm with worst-case expansion\n'}, {'line_no': 16, 'char_start': 327, 'char_end': 400, 'line': ' * of 5 bytes per 32KB data. This means we need to create a variable\n'}, {'line_no': 17, 'char_start': 400, 'char_end': 456, 'line': ' * length output, that depends on the input length.\n'}, {'line_no': 18, 'char_start': 456, 'char_end': 489, 'line': ' * See RFC 1951 for details.\n'}, {'line_no': 19, 'char_start': 489, 'char_end': 497, 'line': ' */\n'}, {'line_no': 20, 'char_start': 497, 'char_end': 560, 'line': ' int max_input_expansion = ((int)(in_len / 32000) + 1) * 5;\n'}, {'line_no': 21, 'char_start': 560, 'char_end': 561, 'line': '\n'}, {'line_no': 22, 'char_start': 561, 'char_end': 568, 'line': ' /*\n'}, {'line_no': 23, 'char_start': 568, 'char_end': 615, 'line': ' * Max compressed size is equal to sum of:\n'}, {'line_no': 24, 'char_start': 615, 'char_end': 639, 'line': ' * 10 byte header\n'}, {'line_no': 25, 'char_start': 639, 'char_end': 660, 'line': ' * 8 byte foot\n'}, {'line_no': 26, 'char_start': 660, 'char_end': 689, 'line': ' * max input expansion\n'}, {'line_no': 27, 'char_start': 689, 'char_end': 712, 'line': ' * size of input\n'}, {'line_no': 28, 'char_start': 712, 'char_end': 720, 'line': ' */\n'}, {'line_no': 29, 'char_start': 720, 'char_end': 774, 'line': ' out_size = 10 + 8 + max_input_expansion + in_len;\n'}, {'line_no': 31, 'char_start': 810, 'char_end': 811, 'line': '\n'}]}","{'deleted': [{'char_start': 276, 'char_end': 277, 'chars': 'l'}, {'char_start': 282, 'char_end': 284, 'chars': '32'}], 'added': [{'char_start': 258, 'char_end': 259, 'chars': '\n'}, {'char_start': 263, 'char_end': 324, 'chars': '/*\n * GZIP relies on an algorithm with worst-case expansi'}, {'char_start': 325, 'char_end': 418, 'chars': 'n\n * of 5 bytes per 32KB data. This means we need to create a variable\n * length outp'}, {'char_start': 420, 'char_end': 433, 'chars': ', that depend'}, {'char_start': 434, 'char_end': 442, 'chars': ' on the '}, {'char_start': 443, 'char_end': 465, 'chars': 'nput length.\n * Se'}, {'char_start': 467, 'char_end': 525, 'chars': 'RFC 1951 for details.\n */\n int max_input_expansion '}, {'char_start': 527, 'char_end': 534, 'chars': '((int)('}, {'char_start': 541, 'char_end': 542, 'chars': '/'}, {'char_start': 545, 'char_end': 772, 'chars': '000) + 1) * 5;\n\n /*\n * Max compressed size is equal to sum of:\n * 10 byte header\n * 8 byte foot\n * max input expansion\n * size of input\n */\n out_size = 10 + 8 + max_input_expansion + in_len'}, {'char_start': 809, 'char_end': 810, 'chars': '\n'}]}",github.com/fluent/fluent-bit/commit/cadff53c093210404aed01c4cf586adb8caa07af,src/flb_gzip.c,cwe-787,698 cwe-079,add_article_action,"def add_article_action(request: HttpRequest, default_foreward_url: str): forward_url: str = default_foreward_url if request.GET.get(""redirect""): forward_url = request.GET[""redirect""] else: forward_url = ""/admin"" if ""rid"" not in request.GET: return HttpResponseRedirect(""/admin?error=Missing%20reservation%20id%20in%20request"") u: Profile = get_current_user(request) current_reservation = GroupReservation.objects.get(id=str(request.GET[""rid""])) if current_reservation.createdByUser != u and u.rights < 2: return HttpResponseRedirect(""/admin?error=noyb"") if current_reservation.submitted == True: return HttpResponseRedirect(""/admin?error=Already%20submitted"") # Test for multiple or single article if ""article_id"" in request.POST: # Actual adding of article aid: int = int(request.GET.get(""article_id"")) quantity: int = int(request.POST[""quantity""]) notes: str = request.POST[""notes""] ar = ArticleRequested() ar.AID = Article.objects.get(id=aid) ar.RID = current_reservation if ""srid"" in request.GET: ar.SRID = SubReservation.objects.get(id=int(request.GET[""srid""])) ar.amount = quantity ar.notes = notes ar.save() # Actual adding of multiple articles else: if ""group_id"" not in request.GET: return HttpResponseRedirect(""/admin?error=missing%20group%20id"") g: ArticleGroup = ArticleGroup.objects.get(id=int(request.GET[""group_id""])) for art in Article.objects.all().filter(group=g): if str(""quantity_"" + str(art.id)) not in request.POST or str(""notes_"" + str(art.id)) not in request.POST: return HttpResponseRedirect(""/admin?error=Missing%20article%20data%20in%20request"") amount = int(request.POST[""quantity_"" + str(art.id)]) if amount > 0: ar = ArticleRequested() ar.AID = art ar.RID = current_reservation ar.amount = amount if ""srid"" in request.GET: ar.SRID = SubReservation.objects.get(id=int(request.GET[""srid""])) ar.notes = str(request.POST[str(""notes_"" + str(art.id))]) ar.save() if ""srid"" in request.GET: response = HttpResponseRedirect(forward_url + ""?rid="" + str(current_reservation.id) + ""&srid="" + request.GET[""srid""]) else: response = HttpResponseRedirect(forward_url + ""?rid="" + str(current_reservation.id)) return response","def add_article_action(request: HttpRequest, default_foreward_url: str): forward_url: str = default_foreward_url if request.GET.get(""redirect""): forward_url = request.GET[""redirect""] else: forward_url = ""/admin"" if ""rid"" not in request.GET: return HttpResponseRedirect(""/admin?error=Missing%20reservation%20id%20in%20request"") u: Profile = get_current_user(request) current_reservation = GroupReservation.objects.get(id=str(request.GET[""rid""])) if current_reservation.createdByUser != u and u.rights < 2: return HttpResponseRedirect(""/admin?error=noyb"") if current_reservation.submitted == True: return HttpResponseRedirect(""/admin?error=Already%20submitted"") # Test for multiple or single article if ""article_id"" in request.POST: # Actual adding of article aid: int = int(request.GET.get(""article_id"")) quantity: int = int(request.POST[""quantity""]) notes: str = escape(request.POST[""notes""]) ar = ArticleRequested() ar.AID = Article.objects.get(id=aid) ar.RID = current_reservation if ""srid"" in request.GET: ar.SRID = SubReservation.objects.get(id=int(request.GET[""srid""])) ar.amount = quantity ar.notes = notes ar.save() # Actual adding of multiple articles else: if ""group_id"" not in request.GET: return HttpResponseRedirect(""/admin?error=missing%20group%20id"") g: ArticleGroup = ArticleGroup.objects.get(id=int(request.GET[""group_id""])) for art in Article.objects.all().filter(group=g): if str(""quantity_"" + str(art.id)) not in request.POST or str(""notes_"" + str(art.id)) not in request.POST: return HttpResponseRedirect(""/admin?error=Missing%20article%20data%20in%20request"") amount = int(request.POST[""quantity_"" + str(art.id)]) if amount > 0: ar = ArticleRequested() ar.AID = art ar.RID = current_reservation ar.amount = amount if ""srid"" in request.GET: ar.SRID = SubReservation.objects.get(id=int(request.GET[""srid""])) ar.notes = escape(str(request.POST[str(""notes_"" + str(art.id))])) ar.save() if ""srid"" in request.GET: response = HttpResponseRedirect(forward_url + ""?rid="" + str(current_reservation.id) + ""&srid="" + request.GET[""srid""]) else: response = HttpResponseRedirect(forward_url + ""?rid="" + str(current_reservation.id)) return response","{'deleted': [{'line_no': 20, 'char_start': 954, 'char_end': 997, 'line': ' notes: str = request.POST[""notes""]\n'}, {'line_no': 45, 'char_start': 2195, 'char_end': 2269, 'line': ' ar.notes = str(request.POST[str(""notes_"" + str(art.id))])\n'}], 'added': [{'line_no': 20, 'char_start': 954, 'char_end': 1005, 'line': ' notes: str = escape(request.POST[""notes""])\n'}, {'line_no': 45, 'char_start': 2203, 'char_end': 2285, 'line': ' ar.notes = escape(str(request.POST[str(""notes_"" + str(art.id))]))\n'}]}","{'deleted': [], 'added': [{'char_start': 975, 'char_end': 982, 'chars': 'escape('}, {'char_start': 1003, 'char_end': 1004, 'chars': ')'}, {'char_start': 2230, 'char_end': 2237, 'chars': 'escape('}, {'char_start': 2282, 'char_end': 2283, 'chars': ')'}]}",github.com/Technikradio/C3FOCSite/commit/6e330d4d44bbfdfce9993dffea97008276771600,c3shop/frontpage/management/reservation_actions.py,cwe-079,581 cwe-416,archive_read_format_rar_read_data,"archive_read_format_rar_read_data(struct archive_read *a, const void **buff, size_t *size, int64_t *offset) { struct rar *rar = (struct rar *)(a->format->data); int ret; if (rar->has_encrypted_entries == ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW) { rar->has_encrypted_entries = 0; } if (rar->bytes_unconsumed > 0) { /* Consume as much as the decompressor actually used. */ __archive_read_consume(a, rar->bytes_unconsumed); rar->bytes_unconsumed = 0; } *buff = NULL; if (rar->entry_eof || rar->offset_seek >= rar->unp_size) { *size = 0; *offset = rar->offset; if (*offset < rar->unp_size) *offset = rar->unp_size; return (ARCHIVE_EOF); } switch (rar->compression_method) { case COMPRESS_METHOD_STORE: ret = read_data_stored(a, buff, size, offset); break; case COMPRESS_METHOD_FASTEST: case COMPRESS_METHOD_FAST: case COMPRESS_METHOD_NORMAL: case COMPRESS_METHOD_GOOD: case COMPRESS_METHOD_BEST: ret = read_data_compressed(a, buff, size, offset); if (ret != ARCHIVE_OK && ret != ARCHIVE_WARN) __archive_ppmd7_functions.Ppmd7_Free(&rar->ppmd7_context); break; default: archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, ""Unsupported compression method for RAR file.""); ret = ARCHIVE_FATAL; break; } return (ret); }","archive_read_format_rar_read_data(struct archive_read *a, const void **buff, size_t *size, int64_t *offset) { struct rar *rar = (struct rar *)(a->format->data); int ret; if (rar->has_encrypted_entries == ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW) { rar->has_encrypted_entries = 0; } if (rar->bytes_unconsumed > 0) { /* Consume as much as the decompressor actually used. */ __archive_read_consume(a, rar->bytes_unconsumed); rar->bytes_unconsumed = 0; } *buff = NULL; if (rar->entry_eof || rar->offset_seek >= rar->unp_size) { *size = 0; *offset = rar->offset; if (*offset < rar->unp_size) *offset = rar->unp_size; return (ARCHIVE_EOF); } switch (rar->compression_method) { case COMPRESS_METHOD_STORE: ret = read_data_stored(a, buff, size, offset); break; case COMPRESS_METHOD_FASTEST: case COMPRESS_METHOD_FAST: case COMPRESS_METHOD_NORMAL: case COMPRESS_METHOD_GOOD: case COMPRESS_METHOD_BEST: ret = read_data_compressed(a, buff, size, offset); if (ret != ARCHIVE_OK && ret != ARCHIVE_WARN) { __archive_ppmd7_functions.Ppmd7_Free(&rar->ppmd7_context); rar->start_new_table = 1; } break; default: archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, ""Unsupported compression method for RAR file.""); ret = ARCHIVE_FATAL; break; } return (ret); }","{'deleted': [{'line_no': 38, 'char_start': 1072, 'char_end': 1122, 'line': ' if (ret != ARCHIVE_OK && ret != ARCHIVE_WARN)\n'}], 'added': [{'line_no': 38, 'char_start': 1072, 'char_end': 1124, 'line': ' if (ret != ARCHIVE_OK && ret != ARCHIVE_WARN) {\n'}, {'line_no': 40, 'char_start': 1189, 'char_end': 1221, 'line': ' rar->start_new_table = 1;\n'}, {'line_no': 41, 'char_start': 1221, 'char_end': 1227, 'line': ' }\n'}]}","{'deleted': [], 'added': [{'char_start': 1121, 'char_end': 1123, 'chars': ' {'}, {'char_start': 1188, 'char_end': 1226, 'chars': '\n rar->start_new_table = 1;\n }'}]}",github.com/libarchive/libarchive/commit/b8592ecba2f9e451e1f5cb7ab6dcee8b8e7b3f60,libarchive/archive_read_support_format_rar.c,cwe-416,387 cwe-476,dnxhd_find_frame_end,"static int dnxhd_find_frame_end(DNXHDParserContext *dctx, const uint8_t *buf, int buf_size) { ParseContext *pc = &dctx->pc; uint64_t state = pc->state64; int pic_found = pc->frame_start_found; int i = 0; if (!pic_found) { for (i = 0; i < buf_size; i++) { state = (state << 8) | buf[i]; if (ff_dnxhd_check_header_prefix(state & 0xffffffffff00LL) != 0) { i++; pic_found = 1; dctx->cur_byte = 0; dctx->remaining = 0; break; } } } if (pic_found && !dctx->remaining) { if (!buf_size) /* EOF considered as end of frame */ return 0; for (; i < buf_size; i++) { dctx->cur_byte++; state = (state << 8) | buf[i]; if (dctx->cur_byte == 24) { dctx->h = (state >> 32) & 0xFFFF; } else if (dctx->cur_byte == 26) { dctx->w = (state >> 32) & 0xFFFF; } else if (dctx->cur_byte == 42) { int cid = (state >> 32) & 0xFFFFFFFF; if (cid <= 0) continue; dctx->remaining = avpriv_dnxhd_get_frame_size(cid); if (dctx->remaining <= 0) { dctx->remaining = dnxhd_get_hr_frame_size(cid, dctx->w, dctx->h); if (dctx->remaining <= 0) return dctx->remaining; } if (buf_size - i + 47 >= dctx->remaining) { int remaining = dctx->remaining; pc->frame_start_found = 0; pc->state64 = -1; dctx->cur_byte = 0; dctx->remaining = 0; return remaining; } else { dctx->remaining -= buf_size; } } } } else if (pic_found) { if (dctx->remaining > buf_size) { dctx->remaining -= buf_size; } else { int remaining = dctx->remaining; pc->frame_start_found = 0; pc->state64 = -1; dctx->cur_byte = 0; dctx->remaining = 0; return remaining; } } pc->frame_start_found = pic_found; pc->state64 = state; return END_NOT_FOUND; }","static int dnxhd_find_frame_end(DNXHDParserContext *dctx, const uint8_t *buf, int buf_size) { ParseContext *pc = &dctx->pc; uint64_t state = pc->state64; int pic_found = pc->frame_start_found; int i = 0; if (!pic_found) { for (i = 0; i < buf_size; i++) { state = (state << 8) | buf[i]; if (ff_dnxhd_check_header_prefix(state & 0xffffffffff00LL) != 0) { i++; pic_found = 1; dctx->cur_byte = 0; dctx->remaining = 0; break; } } } if (pic_found && !dctx->remaining) { if (!buf_size) /* EOF considered as end of frame */ return 0; for (; i < buf_size; i++) { dctx->cur_byte++; state = (state << 8) | buf[i]; if (dctx->cur_byte == 24) { dctx->h = (state >> 32) & 0xFFFF; } else if (dctx->cur_byte == 26) { dctx->w = (state >> 32) & 0xFFFF; } else if (dctx->cur_byte == 42) { int cid = (state >> 32) & 0xFFFFFFFF; int remaining; if (cid <= 0) continue; remaining = avpriv_dnxhd_get_frame_size(cid); if (remaining <= 0) { remaining = dnxhd_get_hr_frame_size(cid, dctx->w, dctx->h); if (remaining <= 0) continue; } dctx->remaining = remaining; if (buf_size - i + 47 >= dctx->remaining) { int remaining = dctx->remaining; pc->frame_start_found = 0; pc->state64 = -1; dctx->cur_byte = 0; dctx->remaining = 0; return remaining; } else { dctx->remaining -= buf_size; } } } } else if (pic_found) { if (dctx->remaining > buf_size) { dctx->remaining -= buf_size; } else { int remaining = dctx->remaining; pc->frame_start_found = 0; pc->state64 = -1; dctx->cur_byte = 0; dctx->remaining = 0; return remaining; } } pc->frame_start_found = pic_found; pc->state64 = state; return END_NOT_FOUND; }","{'deleted': [{'line_no': 39, 'char_start': 1200, 'char_end': 1268, 'line': ' dctx->remaining = avpriv_dnxhd_get_frame_size(cid);\n'}, {'line_no': 40, 'char_start': 1268, 'char_end': 1312, 'line': ' if (dctx->remaining <= 0) {\n'}, {'line_no': 41, 'char_start': 1312, 'char_end': 1398, 'line': ' dctx->remaining = dnxhd_get_hr_frame_size(cid, dctx->w, dctx->h);\n'}, {'line_no': 42, 'char_start': 1398, 'char_end': 1444, 'line': ' if (dctx->remaining <= 0)\n'}, {'line_no': 43, 'char_start': 1444, 'char_end': 1492, 'line': ' return dctx->remaining;\n'}], 'added': [{'line_no': 35, 'char_start': 1138, 'char_end': 1169, 'line': ' int remaining;\n'}, {'line_no': 40, 'char_start': 1231, 'char_end': 1293, 'line': ' remaining = avpriv_dnxhd_get_frame_size(cid);\n'}, {'line_no': 41, 'char_start': 1293, 'char_end': 1331, 'line': ' if (remaining <= 0) {\n'}, {'line_no': 42, 'char_start': 1331, 'char_end': 1411, 'line': ' remaining = dnxhd_get_hr_frame_size(cid, dctx->w, dctx->h);\n'}, {'line_no': 43, 'char_start': 1411, 'char_end': 1451, 'line': ' if (remaining <= 0)\n'}, {'line_no': 44, 'char_start': 1451, 'char_end': 1485, 'line': ' continue;\n'}, {'line_no': 46, 'char_start': 1503, 'char_end': 1548, 'line': ' dctx->remaining = remaining;\n'}]}","{'deleted': [{'char_start': 1216, 'char_end': 1222, 'chars': 'dctx->'}, {'char_start': 1288, 'char_end': 1294, 'chars': 'dctx->'}, {'char_start': 1332, 'char_end': 1338, 'chars': 'dctx->'}, {'char_start': 1422, 'char_end': 1428, 'chars': 'dctx->'}, {'char_start': 1468, 'char_end': 1476, 'chars': 'return d'}, {'char_start': 1477, 'char_end': 1486, 'chars': 'tx->remai'}, {'char_start': 1489, 'char_end': 1490, 'chars': 'g'}], 'added': [{'char_start': 1138, 'char_end': 1169, 'chars': ' int remaining;\n'}, {'char_start': 1476, 'char_end': 1478, 'chars': 'on'}, {'char_start': 1481, 'char_end': 1483, 'chars': 'ue'}, {'char_start': 1502, 'char_end': 1547, 'chars': '\n dctx->remaining = remaining;'}]}",github.com/FFmpeg/FFmpeg/commit/0a709e2a10b8288a0cc383547924ecfe285cef89,libavcodec/dnxhd_parser.c,cwe-476,622 cwe-125,ndpi_search_oracle,"void ndpi_search_oracle(struct ndpi_detection_module_struct *ndpi_struct, struct ndpi_flow_struct *flow) { struct ndpi_packet_struct *packet = &flow->packet; u_int16_t dport = 0, sport = 0; NDPI_LOG_DBG(ndpi_struct, ""search ORACLE\n""); if(packet->tcp != NULL) { sport = ntohs(packet->tcp->source), dport = ntohs(packet->tcp->dest); NDPI_LOG_DBG2(ndpi_struct, ""calculating ORACLE over tcp\n""); /* Oracle Database 9g,10g,11g */ if ((dport == 1521 || sport == 1521) && (((packet->payload[0] == 0x07) && (packet->payload[1] == 0xff) && (packet->payload[2] == 0x00)) || ((packet->payload_packet_len >= 232) && ((packet->payload[0] == 0x00) || (packet->payload[0] == 0x01)) && (packet->payload[1] != 0x00) && (packet->payload[2] == 0x00) && (packet->payload[3] == 0x00)))) { NDPI_LOG_INFO(ndpi_struct, ""found oracle\n""); ndpi_int_oracle_add_connection(ndpi_struct, flow); } else if (packet->payload_packet_len == 213 && packet->payload[0] == 0x00 && packet->payload[1] == 0xd5 && packet->payload[2] == 0x00 && packet->payload[3] == 0x00 ) { NDPI_LOG_INFO(ndpi_struct, ""found oracle\n""); ndpi_int_oracle_add_connection(ndpi_struct, flow); } } else { NDPI_EXCLUDE_PROTO(ndpi_struct, flow); } }","void ndpi_search_oracle(struct ndpi_detection_module_struct *ndpi_struct, struct ndpi_flow_struct *flow) { struct ndpi_packet_struct *packet = &flow->packet; u_int16_t dport = 0, sport = 0; NDPI_LOG_DBG(ndpi_struct, ""search ORACLE\n""); if(packet->tcp != NULL) { sport = ntohs(packet->tcp->source), dport = ntohs(packet->tcp->dest); NDPI_LOG_DBG2(ndpi_struct, ""calculating ORACLE over tcp\n""); /* Oracle Database 9g,10g,11g */ if ((dport == 1521 || sport == 1521) && (((packet->payload_packet_len >= 3 && packet->payload[0] == 0x07) && (packet->payload[1] == 0xff) && (packet->payload[2] == 0x00)) || ((packet->payload_packet_len >= 232) && ((packet->payload[0] == 0x00) || (packet->payload[0] == 0x01)) && (packet->payload[1] != 0x00) && (packet->payload[2] == 0x00) && (packet->payload[3] == 0x00)))) { NDPI_LOG_INFO(ndpi_struct, ""found oracle\n""); ndpi_int_oracle_add_connection(ndpi_struct, flow); } else if (packet->payload_packet_len == 213 && packet->payload[0] == 0x00 && packet->payload[1] == 0xd5 && packet->payload[2] == 0x00 && packet->payload[3] == 0x00 ) { NDPI_LOG_INFO(ndpi_struct, ""found oracle\n""); ndpi_int_oracle_add_connection(ndpi_struct, flow); } } else { NDPI_EXCLUDE_PROTO(ndpi_struct, flow); } }","{'deleted': [{'line_no': 13, 'char_start': 489, 'char_end': 590, 'line': '\t&& (((packet->payload[0] == 0x07) && (packet->payload[1] == 0xff) && (packet->payload[2] == 0x00))\n'}], 'added': [{'line_no': 13, 'char_start': 489, 'char_end': 625, 'line': '\t&& (((packet->payload_packet_len >= 3 && packet->payload[0] == 0x07) && (packet->payload[1] == 0xff) && (packet->payload[2] == 0x00))\n'}]}","{'deleted': [], 'added': [{'char_start': 512, 'char_end': 547, 'chars': '_packet_len >= 3 && packet->payload'}]}",github.com/ntop/nDPI/commit/b69177be2fbe01c2442239a61832c44e40136c05,src/lib/protocols/oracle.c,cwe-125,442 cwe-078,handle_message," def handle_message(self, ch, method, properties, body): """""" this is a pika.basic_consumer callback handles client inputs, runs appropriate workflows and views Args: ch: amqp channel method: amqp method properties: body: message body """""" input = {} try: self.sessid = method.routing_key input = json_decode(body) data = input['data'] # since this comes as ""path"" we dont know if it's view or workflow yet #TODO: just a workaround till we modify ui to if 'path' in data: if data['path'] in settings.VIEW_URLS: data['view'] = data['path'] else: data['wf'] = data['path'] session = Session(self.sessid) headers = {'remote_ip': input['_zops_remote_ip']} if 'wf' in data: output = self._handle_workflow(session, data, headers) elif 'job' in data: self._handle_job(session, data, headers) return else: output = self._handle_view(session, data, headers) except HTTPError as e: import sys if hasattr(sys, '_called_from_test'): raise output = {'cmd': 'error', 'error': self._prepare_error_msg(e.message), ""code"": e.code} log.exception(""Http error occurred"") except: self.current = Current(session=session, input=data) self.current.headers = headers import sys if hasattr(sys, '_called_from_test'): raise err = traceback.format_exc() output = {'error': self._prepare_error_msg(err), ""code"": 500} log.exception(""Worker error occurred with messsage body:\n%s"" % body) if 'callbackID' in input: output['callbackID'] = input['callbackID'] log.info(""OUTPUT for %s: %s"" % (self.sessid, output)) output['reply_timestamp'] = time() self.send_output(output)"," def handle_message(self, ch, method, properties, body): """""" this is a pika.basic_consumer callback handles client inputs, runs appropriate workflows and views Args: ch: amqp channel method: amqp method properties: body: message body """""" input = {} headers = {} try: self.sessid = method.routing_key input = json_decode(body) data = input['data'] # since this comes as ""path"" we dont know if it's view or workflow yet # TODO: just a workaround till we modify ui to if 'path' in data: if data['path'] in settings.VIEW_URLS: data['view'] = data['path'] else: data['wf'] = data['path'] session = Session(self.sessid) headers = {'remote_ip': input['_zops_remote_ip'], 'source': input['_zops_source']} if 'wf' in data: output = self._handle_workflow(session, data, headers) elif 'job' in data: self._handle_job(session, data, headers) return else: output = self._handle_view(session, data, headers) except HTTPError as e: import sys if hasattr(sys, '_called_from_test'): raise output = {'cmd': 'error', 'error': self._prepare_error_msg(e.message), ""code"": e.code} log.exception(""Http error occurred"") except: self.current = Current(session=session, input=data) self.current.headers = headers import sys if hasattr(sys, '_called_from_test'): raise err = traceback.format_exc() output = {'error': self._prepare_error_msg(err), ""code"": 500} log.exception(""Worker error occurred with messsage body:\n%s"" % body) if 'callbackID' in input: output['callbackID'] = input['callbackID'] log.info(""OUTPUT for %s: %s"" % (self.sessid, output)) output['reply_timestamp'] = time() self.send_output(output)","{'deleted': [{'line_no': 28, 'char_start': 867, 'char_end': 929, 'line': "" headers = {'remote_ip': input['_zops_remote_ip']}\n""}], 'added': [{'line_no': 13, 'char_start': 349, 'char_end': 370, 'line': ' headers = {}\n'}, {'line_no': 29, 'char_start': 889, 'char_end': 951, 'line': "" headers = {'remote_ip': input['_zops_remote_ip'],\n""}, {'line_no': 30, 'char_start': 951, 'char_end': 1007, 'line': "" 'source': input['_zops_source']}\n""}]}","{'deleted': [], 'added': [{'char_start': 357, 'char_end': 378, 'chars': 'headers = {}\n '}, {'char_start': 597, 'char_end': 598, 'chars': ' '}, {'char_start': 947, 'char_end': 1003, 'chars': ""'],\n 'source': input['_zops_source""}]}",github.com/zetaops/zengine/commit/52eafbee90f8ddf78be0c7452828d49423246851,zengine/wf_daemon.py,cwe-078,453 cwe-079,get_list_context,"def get_list_context(context=None): list_context = frappe._dict( template = ""templates/includes/blog/blog.html"", get_list = get_blog_list, hide_filters = True, children = get_children(), # show_search = True, title = _('Blog') ) category = frappe.local.form_dict.blog_category or frappe.local.form_dict.category if category: category_title = get_blog_category(category) list_context.sub_title = _(""Posts filed under {0}"").format(category_title) list_context.title = category_title elif frappe.local.form_dict.blogger: blogger = frappe.db.get_value(""Blogger"", {""name"": frappe.local.form_dict.blogger}, ""full_name"") list_context.sub_title = _(""Posts by {0}"").format(blogger) list_context.title = blogger elif frappe.local.form_dict.txt: list_context.sub_title = _('Filtered by ""{0}""').format(frappe.local.form_dict.txt) if list_context.sub_title: list_context.parents = [{""name"": _(""Home""), ""route"": ""/""}, {""name"": ""Blog"", ""route"": ""/blog""}] else: list_context.parents = [{""name"": _(""Home""), ""route"": ""/""}] list_context.update(frappe.get_doc(""Blog Settings"", ""Blog Settings"").as_dict(no_default_fields=True)) return list_context","def get_list_context(context=None): list_context = frappe._dict( template = ""templates/includes/blog/blog.html"", get_list = get_blog_list, hide_filters = True, children = get_children(), # show_search = True, title = _('Blog') ) category = sanitize_html(frappe.local.form_dict.blog_category or frappe.local.form_dict.category) if category: category_title = get_blog_category(category) list_context.sub_title = _(""Posts filed under {0}"").format(category_title) list_context.title = category_title elif frappe.local.form_dict.blogger: blogger = frappe.db.get_value(""Blogger"", {""name"": frappe.local.form_dict.blogger}, ""full_name"") list_context.sub_title = _(""Posts by {0}"").format(blogger) list_context.title = blogger elif frappe.local.form_dict.txt: list_context.sub_title = _('Filtered by ""{0}""').format(sanitize_html(frappe.local.form_dict.txt)) if list_context.sub_title: list_context.parents = [{""name"": _(""Home""), ""route"": ""/""}, {""name"": ""Blog"", ""route"": ""/blog""}] else: list_context.parents = [{""name"": _(""Home""), ""route"": ""/""}] list_context.update(frappe.get_doc(""Blog Settings"", ""Blog Settings"").as_dict(no_default_fields=True)) return list_context","{'deleted': [{'line_no': 11, 'char_start': 244, 'char_end': 328, 'line': '\tcategory = frappe.local.form_dict.blog_category or frappe.local.form_dict.category\n'}, {'line_no': 23, 'char_start': 768, 'char_end': 853, 'line': '\t\tlist_context.sub_title = _(\'Filtered by ""{0}""\').format(frappe.local.form_dict.txt)\n'}], 'added': [{'line_no': 11, 'char_start': 244, 'char_end': 343, 'line': '\tcategory = sanitize_html(frappe.local.form_dict.blog_category or frappe.local.form_dict.category)\n'}, {'line_no': 23, 'char_start': 783, 'char_end': 883, 'line': '\t\tlist_context.sub_title = _(\'Filtered by ""{0}""\').format(sanitize_html(frappe.local.form_dict.txt))\n'}]}","{'deleted': [], 'added': [{'char_start': 256, 'char_end': 270, 'chars': 'sanitize_html('}, {'char_start': 341, 'char_end': 342, 'chars': ')'}, {'char_start': 840, 'char_end': 854, 'chars': 'sanitize_html('}, {'char_start': 880, 'char_end': 881, 'chars': ')'}]}",github.com/omirajkar/bench_frappe/commit/2fa19c25066ed17478d683666895e3266936aee6,frappe/website/doctype/blog_post/blog_post.py,cwe-079,290 cwe-089,reportMatch._checkPairing," def _checkPairing(): if winner == loser: raise ValueError('Attempt to match player against self') q = ''' SELECT COUNT(*) FROM matches WHERE (matches.winner_id = %s AND matches.loser_id = %s) OR (matches.winner_id = %s AND matches.loser_id = %s); ''' % (winner, loser, loser, winner) cur.execute(q) if cur.fetchone()[0] > 0: raise ValueError('Pairing %s, %s already played' % (winner, loser))"," def _checkPairing(): if winner == loser: raise ValueError('Attempt to match player against self') q = ''' SELECT COUNT(*) FROM matches WHERE (matches.winner_id = %s AND matches.loser_id = %s) OR (matches.winner_id = %s AND matches.loser_id = %s); ''' cur.execute(q, (winner, loser, loser, winner)) if cur.fetchone()[0] > 0: raise ValueError('Pairing %s, %s already played' % (winner, loser))","{'deleted': [{'line_no': 9, 'char_start': 310, 'char_end': 355, 'line': "" ''' % (winner, loser, loser, winner)\n""}, {'line_no': 10, 'char_start': 355, 'char_end': 378, 'line': ' cur.execute(q)\n'}], 'added': [{'line_no': 9, 'char_start': 310, 'char_end': 322, 'line': "" '''\n""}, {'line_no': 10, 'char_start': 322, 'char_end': 377, 'line': ' cur.execute(q, (winner, loser, loser, winner))\n'}]}","{'deleted': [{'char_start': 322, 'char_end': 323, 'chars': '%'}, {'char_start': 354, 'char_end': 376, 'chars': '\n cur.execute(q'}], 'added': [{'char_start': 321, 'char_end': 327, 'chars': '\n '}, {'char_start': 328, 'char_end': 344, 'chars': ' cur.execute(q,'}]}",github.com/juanchopanza/Tournament/commit/5799aee52d2cabb685800b88977257bd0964d0da,vagrant/tournament/tournament.py,cwe-089,121 cwe-787,MultiPartInputFile::Data::chunkOffsetReconstruction,"MultiPartInputFile::Data::chunkOffsetReconstruction(OPENEXR_IMF_INTERNAL_NAMESPACE::IStream& is, const vector& parts) { // // Reconstruct broken chunk offset tables. Stop once we received any exception. // Int64 position = is.tellg(); // // check we understand all the parts available: if not, we cannot continue // exceptions thrown here should trickle back up to the constructor // for (size_t i = 0; i < parts.size(); i++) { Header& header=parts[i]->header; // // do we have a valid type entry? // we only need them for true multipart files or single part non-image (deep) files // if(!header.hasType() && (isMultiPart(version) || isNonImage(version))) { throw IEX_NAMESPACE::ArgExc(""cannot reconstruct incomplete file: part with missing type""); } if(!isSupportedType(header.type())) { throw IEX_NAMESPACE::ArgExc(""cannot reconstruct incomplete file: part with unknown type ""+header.type()); } } // how many chunks should we read? We should stop when we reach the end size_t total_chunks = 0; // for tiled-based parts, array of (pointers to) tileOffsets objects // to create mapping between tile coordinates and chunk table indices vector tileOffsets(parts.size()); // for scanline-based parts, number of scanlines in each chunk vector rowsizes(parts.size()); for(size_t i = 0 ; i < parts.size() ; i++) { total_chunks += parts[i]->chunkOffsets.size(); if (isTiled(parts[i]->header.type())) { tileOffsets[i] = createTileOffsets(parts[i]->header); }else{ tileOffsets[i] = NULL; // (TODO) fix this so that it doesn't need to be revised for future compression types. switch(parts[i]->header.compression()) { case DWAB_COMPRESSION : rowsizes[i] = 256; break; case PIZ_COMPRESSION : case B44_COMPRESSION : case B44A_COMPRESSION : case DWAA_COMPRESSION : rowsizes[i]=32; break; case ZIP_COMPRESSION : case PXR24_COMPRESSION : rowsizes[i]=16; break; case ZIPS_COMPRESSION : case RLE_COMPRESSION : case NO_COMPRESSION : rowsizes[i]=1; break; default : throw(IEX_NAMESPACE::ArgExc(""Unknown compression method in chunk offset reconstruction"")); } } } try { // // // Int64 chunk_start = position; for (size_t i = 0; i < total_chunks ; i++) { // // do we have a part number? // int partNumber = 0; if(isMultiPart(version)) { OPENEXR_IMF_INTERNAL_NAMESPACE::Xdr::read (is, partNumber); } if(partNumber<0 || partNumber> static_cast(parts.size())) { throw IEX_NAMESPACE::IoExc(""part number out of range""); } Header& header = parts[partNumber]->header; // size of chunk NOT including multipart field Int64 size_of_chunk=0; if (isTiled(header.type())) { // // // int tilex,tiley,levelx,levely; OPENEXR_IMF_INTERNAL_NAMESPACE::Xdr::read (is, tilex); OPENEXR_IMF_INTERNAL_NAMESPACE::Xdr::read (is, tiley); OPENEXR_IMF_INTERNAL_NAMESPACE::Xdr::read (is, levelx); OPENEXR_IMF_INTERNAL_NAMESPACE::Xdr::read (is, levely); //std::cout << ""chunk_start for "" << tilex <<',' << tiley << ',' << levelx << ' ' << levely << ':' << chunk_start << std::endl; if(!tileOffsets[partNumber]) { // this shouldn't actually happen - we should have allocated a valid // tileOffsets for any part which isTiled throw IEX_NAMESPACE::IoExc(""part not tiled""); } if(!tileOffsets[partNumber]->isValidTile(tilex,tiley,levelx,levely)) { throw IEX_NAMESPACE::IoExc(""invalid tile coordinates""); } (*tileOffsets[partNumber])(tilex,tiley,levelx,levely)=chunk_start; // compute chunk sizes - different procedure for deep tiles and regular // ones if(header.type()==DEEPTILE) { Int64 packed_offset; Int64 packed_sample; OPENEXR_IMF_INTERNAL_NAMESPACE::Xdr::read (is, packed_offset); OPENEXR_IMF_INTERNAL_NAMESPACE::Xdr::read (is, packed_sample); //add 40 byte header to packed sizes (tile coordinates, packed sizes, unpacked size) size_of_chunk=packed_offset+packed_sample+40; } else { // regular image has 20 bytes of header, 4 byte chunksize; int chunksize; OPENEXR_IMF_INTERNAL_NAMESPACE::Xdr::read (is, chunksize); size_of_chunk=chunksize+20; } } else { int y_coordinate; OPENEXR_IMF_INTERNAL_NAMESPACE::Xdr::read (is, y_coordinate); if(y_coordinate < header.dataWindow().min.y || y_coordinate > header.dataWindow().max.y) { throw IEX_NAMESPACE::IoExc(""y out of range""); } y_coordinate -= header.dataWindow().min.y; y_coordinate /= rowsizes[partNumber]; if(y_coordinate < 0 || y_coordinate >= int(parts[partNumber]->chunkOffsets.size())) { throw IEX_NAMESPACE::IoExc(""chunk index out of range""); } parts[partNumber]->chunkOffsets[y_coordinate]=chunk_start; if(header.type()==DEEPSCANLINE) { Int64 packed_offset; Int64 packed_sample; OPENEXR_IMF_INTERNAL_NAMESPACE::Xdr::read (is, packed_offset); OPENEXR_IMF_INTERNAL_NAMESPACE::Xdr::read (is, packed_sample); size_of_chunk=packed_offset+packed_sample+28; } else { int chunksize; OPENEXR_IMF_INTERNAL_NAMESPACE::Xdr::read (is, chunksize); size_of_chunk=chunksize+8; } } if(isMultiPart(version)) { chunk_start+=4; } chunk_start+=size_of_chunk; is.seekg(chunk_start); } } catch (...) { // // Suppress all exceptions. This functions is // called only to reconstruct the line offset // table for incomplete files, and exceptions // are likely. // } // copy tiled part data back to chunk offsets for(size_t partNumber=0;partNumber > > offsets = tileOffsets[partNumber]->getOffsets(); for (size_t l = 0; l < offsets.size(); l++) for (size_t y = 0; y < offsets[l].size(); y++) for (size_t x = 0; x < offsets[l][y].size(); x++) { parts[ partNumber ]->chunkOffsets[pos] = offsets[l][y][x]; pos++; } delete tileOffsets[partNumber]; } } is.clear(); is.seekg (position); }","MultiPartInputFile::Data::chunkOffsetReconstruction(OPENEXR_IMF_INTERNAL_NAMESPACE::IStream& is, const vector& parts) { // // Reconstruct broken chunk offset tables. Stop once we received any exception. // Int64 position = is.tellg(); // // check we understand all the parts available: if not, we cannot continue // exceptions thrown here should trickle back up to the constructor // for (size_t i = 0; i < parts.size(); i++) { Header& header=parts[i]->header; // // do we have a valid type entry? // we only need them for true multipart files or single part non-image (deep) files // if(!header.hasType() && (isMultiPart(version) || isNonImage(version))) { throw IEX_NAMESPACE::ArgExc(""cannot reconstruct incomplete file: part with missing type""); } if(!isSupportedType(header.type())) { throw IEX_NAMESPACE::ArgExc(""cannot reconstruct incomplete file: part with unknown type ""+header.type()); } } // how many chunks should we read? We should stop when we reach the end size_t total_chunks = 0; // for tiled-based parts, array of (pointers to) tileOffsets objects // to create mapping between tile coordinates and chunk table indices vector tileOffsets(parts.size()); // for scanline-based parts, number of scanlines in each chunk vector rowsizes(parts.size()); for(size_t i = 0 ; i < parts.size() ; i++) { total_chunks += parts[i]->chunkOffsets.size(); if (isTiled(parts[i]->header.type())) { tileOffsets[i] = createTileOffsets(parts[i]->header); }else{ tileOffsets[i] = NULL; // (TODO) fix this so that it doesn't need to be revised for future compression types. switch(parts[i]->header.compression()) { case DWAB_COMPRESSION : rowsizes[i] = 256; break; case PIZ_COMPRESSION : case B44_COMPRESSION : case B44A_COMPRESSION : case DWAA_COMPRESSION : rowsizes[i]=32; break; case ZIP_COMPRESSION : case PXR24_COMPRESSION : rowsizes[i]=16; break; case ZIPS_COMPRESSION : case RLE_COMPRESSION : case NO_COMPRESSION : rowsizes[i]=1; break; default : throw(IEX_NAMESPACE::ArgExc(""Unknown compression method in chunk offset reconstruction"")); } } } try { // // // Int64 chunk_start = position; for (size_t i = 0; i < total_chunks ; i++) { // // do we have a part number? // int partNumber = 0; if(isMultiPart(version)) { OPENEXR_IMF_INTERNAL_NAMESPACE::Xdr::read (is, partNumber); } if(partNumber<0 || partNumber>= static_cast(parts.size())) { throw IEX_NAMESPACE::IoExc(""part number out of range""); } Header& header = parts[partNumber]->header; // size of chunk NOT including multipart field Int64 size_of_chunk=0; if (isTiled(header.type())) { // // // int tilex,tiley,levelx,levely; OPENEXR_IMF_INTERNAL_NAMESPACE::Xdr::read (is, tilex); OPENEXR_IMF_INTERNAL_NAMESPACE::Xdr::read (is, tiley); OPENEXR_IMF_INTERNAL_NAMESPACE::Xdr::read (is, levelx); OPENEXR_IMF_INTERNAL_NAMESPACE::Xdr::read (is, levely); //std::cout << ""chunk_start for "" << tilex <<',' << tiley << ',' << levelx << ' ' << levely << ':' << chunk_start << std::endl; if(!tileOffsets[partNumber]) { // this shouldn't actually happen - we should have allocated a valid // tileOffsets for any part which isTiled throw IEX_NAMESPACE::IoExc(""part not tiled""); } if(!tileOffsets[partNumber]->isValidTile(tilex,tiley,levelx,levely)) { throw IEX_NAMESPACE::IoExc(""invalid tile coordinates""); } (*tileOffsets[partNumber])(tilex,tiley,levelx,levely)=chunk_start; // compute chunk sizes - different procedure for deep tiles and regular // ones if(header.type()==DEEPTILE) { Int64 packed_offset; Int64 packed_sample; OPENEXR_IMF_INTERNAL_NAMESPACE::Xdr::read (is, packed_offset); OPENEXR_IMF_INTERNAL_NAMESPACE::Xdr::read (is, packed_sample); //add 40 byte header to packed sizes (tile coordinates, packed sizes, unpacked size) size_of_chunk=packed_offset+packed_sample+40; } else { // regular image has 20 bytes of header, 4 byte chunksize; int chunksize; OPENEXR_IMF_INTERNAL_NAMESPACE::Xdr::read (is, chunksize); size_of_chunk=chunksize+20; } } else { int y_coordinate; OPENEXR_IMF_INTERNAL_NAMESPACE::Xdr::read (is, y_coordinate); if(y_coordinate < header.dataWindow().min.y || y_coordinate > header.dataWindow().max.y) { throw IEX_NAMESPACE::IoExc(""y out of range""); } y_coordinate -= header.dataWindow().min.y; y_coordinate /= rowsizes[partNumber]; if(y_coordinate < 0 || y_coordinate >= int(parts[partNumber]->chunkOffsets.size())) { throw IEX_NAMESPACE::IoExc(""chunk index out of range""); } parts[partNumber]->chunkOffsets[y_coordinate]=chunk_start; if(header.type()==DEEPSCANLINE) { Int64 packed_offset; Int64 packed_sample; OPENEXR_IMF_INTERNAL_NAMESPACE::Xdr::read (is, packed_offset); OPENEXR_IMF_INTERNAL_NAMESPACE::Xdr::read (is, packed_sample); size_of_chunk=packed_offset+packed_sample+28; } else { int chunksize; OPENEXR_IMF_INTERNAL_NAMESPACE::Xdr::read (is, chunksize); size_of_chunk=chunksize+8; } } if(isMultiPart(version)) { chunk_start+=4; } chunk_start+=size_of_chunk; is.seekg(chunk_start); } } catch (...) { // // Suppress all exceptions. This functions is // called only to reconstruct the line offset // table for incomplete files, and exceptions // are likely. // } // copy tiled part data back to chunk offsets for(size_t partNumber=0;partNumber > > offsets = tileOffsets[partNumber]->getOffsets(); for (size_t l = 0; l < offsets.size(); l++) for (size_t y = 0; y < offsets[l].size(); y++) for (size_t x = 0; x < offsets[l][y].size(); x++) { parts[ partNumber ]->chunkOffsets[pos] = offsets[l][y][x]; pos++; } delete tileOffsets[partNumber]; } } is.clear(); is.seekg (position); }","{'deleted': [{'line_no': 103, 'char_start': 3326, 'char_end': 3401, 'line': ' if(partNumber<0 || partNumber> static_cast(parts.size()))\n'}], 'added': [{'line_no': 103, 'char_start': 3326, 'char_end': 3402, 'line': ' if(partNumber<0 || partNumber>= static_cast(parts.size()))\n'}]}","{'deleted': [], 'added': [{'char_start': 3368, 'char_end': 3369, 'chars': '='}]}",github.com/AcademySoftwareFoundation/openexr/commit/8b5370c688a7362673c3a5256d93695617a4cd9a,OpenEXR/IlmImf/ImfMultiPartInputFile.cpp,cwe-787,1892 cwe-190,HPHP::StringUtil::Implode,"String StringUtil::Implode(const Variant& items, const String& delim, const bool checkIsContainer /* = true */) { if (checkIsContainer && !isContainer(items)) { throw_param_is_not_container(); } int size = getContainerSize(items); if (size == 0) return empty_string(); req::vector sitems; sitems.reserve(size); int len = 0; int lenDelim = delim.size(); for (ArrayIter iter(items); iter; ++iter) { sitems.emplace_back(iter.second().toString()); len += sitems.back().size() + lenDelim; } len -= lenDelim; // always one delimiter less than count of items assert(sitems.size() == size); String s = String(len, ReserveString); char *buffer = s.mutableData(); const char *sdelim = delim.data(); char *p = buffer; String &init_str = sitems[0]; int init_len = init_str.size(); memcpy(p, init_str.data(), init_len); p += init_len; for (int i = 1; i < size; i++) { String &item = sitems[i]; memcpy(p, sdelim, lenDelim); p += lenDelim; int lenItem = item.size(); memcpy(p, item.data(), lenItem); p += lenItem; } assert(p - buffer == len); s.setSize(len); return s; }","String StringUtil::Implode(const Variant& items, const String& delim, const bool checkIsContainer /* = true */) { if (checkIsContainer && !isContainer(items)) { throw_param_is_not_container(); } int size = getContainerSize(items); if (size == 0) return empty_string(); req::vector sitems; sitems.reserve(size); size_t len = 0; size_t lenDelim = delim.size(); for (ArrayIter iter(items); iter; ++iter) { sitems.emplace_back(iter.second().toString()); len += sitems.back().size() + lenDelim; } len -= lenDelim; // always one delimiter less than count of items assert(sitems.size() == size); String s = String(len, ReserveString); char *buffer = s.mutableData(); const char *sdelim = delim.data(); char *p = buffer; String &init_str = sitems[0]; int init_len = init_str.size(); memcpy(p, init_str.data(), init_len); p += init_len; for (int i = 1; i < size; i++) { String &item = sitems[i]; memcpy(p, sdelim, lenDelim); p += lenDelim; int lenItem = item.size(); memcpy(p, item.data(), lenItem); p += lenItem; } assert(p - buffer == len); s.setSize(len); return s; }","{'deleted': [{'line_no': 11, 'char_start': 363, 'char_end': 378, 'line': ' int len = 0;\n'}, {'line_no': 12, 'char_start': 378, 'char_end': 409, 'line': ' int lenDelim = delim.size();\n'}], 'added': [{'line_no': 11, 'char_start': 363, 'char_end': 381, 'line': ' size_t len = 0;\n'}, {'line_no': 12, 'char_start': 381, 'char_end': 415, 'line': ' size_t lenDelim = delim.size();\n'}]}","{'deleted': [{'char_start': 366, 'char_end': 367, 'chars': 'n'}, {'char_start': 381, 'char_end': 382, 'chars': 'n'}], 'added': [{'char_start': 365, 'char_end': 366, 'chars': 's'}, {'char_start': 367, 'char_end': 370, 'chars': 'ze_'}, {'char_start': 383, 'char_end': 384, 'chars': 's'}, {'char_start': 385, 'char_end': 388, 'chars': 'ze_'}]}",github.com/facebook/hhvm/commit/2c9a8fcc73a151608634d3e712973d192027c271,hphp/runtime/base/string-util.cpp,cwe-190,328 cwe-125,store_versioninfo_gnu_verneed,"static Sdb *store_versioninfo_gnu_verneed(ELFOBJ *bin, Elf_(Shdr) *shdr, int sz) { ut8 *end, *need = NULL; const char *section_name = """"; Elf_(Shdr) *link_shdr = NULL; const char *link_section_name = """"; Sdb *sdb_vernaux = NULL; Sdb *sdb_version = NULL; Sdb *sdb = NULL; int i, cnt; if (!bin || !bin->dynstr) { return NULL; } if (shdr->sh_link > bin->ehdr.e_shnum) { return NULL; } if (shdr->sh_size < 1) { return NULL; } sdb = sdb_new0 (); if (!sdb) { return NULL; } link_shdr = &bin->shdr[shdr->sh_link]; if (bin->shstrtab && shdr->sh_name < bin->shstrtab_size) { section_name = &bin->shstrtab[shdr->sh_name]; } if (bin->shstrtab && link_shdr->sh_name < bin->shstrtab_size) { link_section_name = &bin->shstrtab[link_shdr->sh_name]; } if (!(need = (ut8*) calloc (R_MAX (1, shdr->sh_size), sizeof (ut8)))) { bprintf (""Warning: Cannot allocate memory for Elf_(Verneed)\n""); goto beach; } end = need + shdr->sh_size; sdb_set (sdb, ""section_name"", section_name, 0); sdb_num_set (sdb, ""num_entries"", shdr->sh_info, 0); sdb_num_set (sdb, ""addr"", shdr->sh_addr, 0); sdb_num_set (sdb, ""offset"", shdr->sh_offset, 0); sdb_num_set (sdb, ""link"", shdr->sh_link, 0); sdb_set (sdb, ""link_section_name"", link_section_name, 0); if (shdr->sh_offset > bin->size || shdr->sh_offset + shdr->sh_size > bin->size) { goto beach; } if (shdr->sh_offset + shdr->sh_size < shdr->sh_size) { goto beach; } i = r_buf_read_at (bin->b, shdr->sh_offset, need, shdr->sh_size); if (i < 0) goto beach; //XXX we should use DT_VERNEEDNUM instead of sh_info //TODO https://sourceware.org/ml/binutils/2014-11/msg00353.html for (i = 0, cnt = 0; cnt < shdr->sh_info; ++cnt) { int j, isum; ut8 *vstart = need + i; Elf_(Verneed) vvn = {0}; if (vstart + sizeof (Elf_(Verneed)) > end) { goto beach; } Elf_(Verneed) *entry = &vvn; char key[32] = {0}; sdb_version = sdb_new0 (); if (!sdb_version) { goto beach; } j = 0; vvn.vn_version = READ16 (vstart, j) vvn.vn_cnt = READ16 (vstart, j) vvn.vn_file = READ32 (vstart, j) vvn.vn_aux = READ32 (vstart, j) vvn.vn_next = READ32 (vstart, j) sdb_num_set (sdb_version, ""vn_version"", entry->vn_version, 0); sdb_num_set (sdb_version, ""idx"", i, 0); if (entry->vn_file > bin->dynstr_size) { goto beach; } { char *s = r_str_ndup (&bin->dynstr[entry->vn_file], 16); sdb_set (sdb_version, ""file_name"", s, 0); free (s); } sdb_num_set (sdb_version, ""cnt"", entry->vn_cnt, 0); vstart += entry->vn_aux; for (j = 0, isum = i + entry->vn_aux; j < entry->vn_cnt && vstart + sizeof (Elf_(Vernaux)) <= end; ++j) { int k; Elf_(Vernaux) * aux = NULL; Elf_(Vernaux) vaux = {0}; sdb_vernaux = sdb_new0 (); if (!sdb_vernaux) { goto beach; } aux = (Elf_(Vernaux)*)&vaux; k = 0; vaux.vna_hash = READ32 (vstart, k) vaux.vna_flags = READ16 (vstart, k) vaux.vna_other = READ16 (vstart, k) vaux.vna_name = READ32 (vstart, k) vaux.vna_next = READ32 (vstart, k) if (aux->vna_name > bin->dynstr_size) { goto beach; } sdb_num_set (sdb_vernaux, ""idx"", isum, 0); if (aux->vna_name > 0 && aux->vna_name + 8 < bin->dynstr_size) { char name [16]; strncpy (name, &bin->dynstr[aux->vna_name], sizeof (name)-1); name[sizeof(name)-1] = 0; sdb_set (sdb_vernaux, ""name"", name, 0); } sdb_set (sdb_vernaux, ""flags"", get_ver_flags (aux->vna_flags), 0); sdb_num_set (sdb_vernaux, ""version"", aux->vna_other, 0); isum += aux->vna_next; vstart += aux->vna_next; snprintf (key, sizeof (key), ""vernaux%d"", j); sdb_ns_set (sdb_version, key, sdb_vernaux); } if ((int)entry->vn_next < 0) { bprintf (""Invalid vn_next\n""); break; } i += entry->vn_next; snprintf (key, sizeof (key), ""version%d"", cnt ); sdb_ns_set (sdb, key, sdb_version); //if entry->vn_next is 0 it iterate infinitely if (!entry->vn_next) { break; } } free (need); return sdb; beach: free (need); sdb_free (sdb_vernaux); sdb_free (sdb_version); sdb_free (sdb); return NULL; }","static Sdb *store_versioninfo_gnu_verneed(ELFOBJ *bin, Elf_(Shdr) *shdr, int sz) { ut8 *end, *need = NULL; const char *section_name = """"; Elf_(Shdr) *link_shdr = NULL; const char *link_section_name = """"; Sdb *sdb_vernaux = NULL; Sdb *sdb_version = NULL; Sdb *sdb = NULL; int i, cnt; if (!bin || !bin->dynstr) { return NULL; } if (shdr->sh_link > bin->ehdr.e_shnum) { return NULL; } if (shdr->sh_size < 1) { return NULL; } sdb = sdb_new0 (); if (!sdb) { return NULL; } link_shdr = &bin->shdr[shdr->sh_link]; if (bin->shstrtab && shdr->sh_name < bin->shstrtab_size) { section_name = &bin->shstrtab[shdr->sh_name]; } if (bin->shstrtab && link_shdr->sh_name < bin->shstrtab_size) { link_section_name = &bin->shstrtab[link_shdr->sh_name]; } if (!(need = (ut8*) calloc (R_MAX (1, shdr->sh_size), sizeof (ut8)))) { bprintf (""Warning: Cannot allocate memory for Elf_(Verneed)\n""); goto beach; } end = need + shdr->sh_size; sdb_set (sdb, ""section_name"", section_name, 0); sdb_num_set (sdb, ""num_entries"", shdr->sh_info, 0); sdb_num_set (sdb, ""addr"", shdr->sh_addr, 0); sdb_num_set (sdb, ""offset"", shdr->sh_offset, 0); sdb_num_set (sdb, ""link"", shdr->sh_link, 0); sdb_set (sdb, ""link_section_name"", link_section_name, 0); if (shdr->sh_offset > bin->size || shdr->sh_offset + shdr->sh_size > bin->size) { goto beach; } if (shdr->sh_offset + shdr->sh_size < shdr->sh_size) { goto beach; } i = r_buf_read_at (bin->b, shdr->sh_offset, need, shdr->sh_size); if (i < 0) goto beach; //XXX we should use DT_VERNEEDNUM instead of sh_info //TODO https://sourceware.org/ml/binutils/2014-11/msg00353.html for (i = 0, cnt = 0; cnt < shdr->sh_info; ++cnt) { int j, isum; ut8 *vstart = need + i; Elf_(Verneed) vvn = {0}; if (vstart + sizeof (Elf_(Verneed)) > end) { goto beach; } Elf_(Verneed) *entry = &vvn; char key[32] = {0}; sdb_version = sdb_new0 (); if (!sdb_version) { goto beach; } j = 0; vvn.vn_version = READ16 (vstart, j) vvn.vn_cnt = READ16 (vstart, j) vvn.vn_file = READ32 (vstart, j) vvn.vn_aux = READ32 (vstart, j) vvn.vn_next = READ32 (vstart, j) sdb_num_set (sdb_version, ""vn_version"", entry->vn_version, 0); sdb_num_set (sdb_version, ""idx"", i, 0); if (entry->vn_file > bin->dynstr_size) { goto beach; } { char *s = r_str_ndup (&bin->dynstr[entry->vn_file], 16); sdb_set (sdb_version, ""file_name"", s, 0); free (s); } sdb_num_set (sdb_version, ""cnt"", entry->vn_cnt, 0); st32 vnaux = entry->vn_aux; if (vnaux < 1) { goto beach; } vstart += vnaux; for (j = 0, isum = i + entry->vn_aux; j < entry->vn_cnt && vstart + sizeof (Elf_(Vernaux)) <= end; ++j) { int k; Elf_(Vernaux) * aux = NULL; Elf_(Vernaux) vaux = {0}; sdb_vernaux = sdb_new0 (); if (!sdb_vernaux) { goto beach; } aux = (Elf_(Vernaux)*)&vaux; k = 0; vaux.vna_hash = READ32 (vstart, k) vaux.vna_flags = READ16 (vstart, k) vaux.vna_other = READ16 (vstart, k) vaux.vna_name = READ32 (vstart, k) vaux.vna_next = READ32 (vstart, k) if (aux->vna_name > bin->dynstr_size) { goto beach; } sdb_num_set (sdb_vernaux, ""idx"", isum, 0); if (aux->vna_name > 0 && aux->vna_name + 8 < bin->dynstr_size) { char name [16]; strncpy (name, &bin->dynstr[aux->vna_name], sizeof (name)-1); name[sizeof(name)-1] = 0; sdb_set (sdb_vernaux, ""name"", name, 0); } sdb_set (sdb_vernaux, ""flags"", get_ver_flags (aux->vna_flags), 0); sdb_num_set (sdb_vernaux, ""version"", aux->vna_other, 0); isum += aux->vna_next; vstart += aux->vna_next; snprintf (key, sizeof (key), ""vernaux%d"", j); sdb_ns_set (sdb_version, key, sdb_vernaux); } if ((int)entry->vn_next < 0) { bprintf (""Invalid vn_next\n""); break; } i += entry->vn_next; snprintf (key, sizeof (key), ""version%d"", cnt ); sdb_ns_set (sdb, key, sdb_version); //if entry->vn_next is 0 it iterate infinitely if (!entry->vn_next) { break; } } free (need); return sdb; beach: free (need); sdb_free (sdb_vernaux); sdb_free (sdb_version); sdb_free (sdb); return NULL; }","{'deleted': [{'line_no': 85, 'char_start': 2490, 'char_end': 2517, 'line': '\t\tvstart += entry->vn_aux;\n'}], 'added': [{'line_no': 85, 'char_start': 2490, 'char_end': 2520, 'line': '\t\tst32 vnaux = entry->vn_aux;\n'}, {'line_no': 86, 'char_start': 2520, 'char_end': 2539, 'line': '\t\tif (vnaux < 1) {\n'}, {'line_no': 87, 'char_start': 2539, 'char_end': 2554, 'line': '\t\t\tgoto beach;\n'}, {'line_no': 88, 'char_start': 2554, 'char_end': 2558, 'line': '\t\t}\n'}, {'line_no': 89, 'char_start': 2558, 'char_end': 2577, 'line': '\t\tvstart += vnaux;\n'}]}","{'deleted': [{'char_start': 2492, 'char_end': 2493, 'chars': 'v'}, {'char_start': 2496, 'char_end': 2498, 'chars': 'rt'}, {'char_start': 2499, 'char_end': 2500, 'chars': '+'}], 'added': [{'char_start': 2494, 'char_end': 2499, 'chars': '32 vn'}, {'char_start': 2500, 'char_end': 2502, 'chars': 'ux'}, {'char_start': 2515, 'char_end': 2572, 'chars': 'aux;\n\t\tif (vnaux < 1) {\n\t\t\tgoto beach;\n\t\t}\n\t\tvstart += vn'}]}",github.com/radare/radare2/commit/c6d0076c924891ad9948a62d89d0bcdaf965f0cd,libr/bin/format/elf/elf.c,cwe-125,1547 cwe-125,usbhid_parse,"static int usbhid_parse(struct hid_device *hid) { struct usb_interface *intf = to_usb_interface(hid->dev.parent); struct usb_host_interface *interface = intf->cur_altsetting; struct usb_device *dev = interface_to_usbdev (intf); struct hid_descriptor *hdesc; u32 quirks = 0; unsigned int rsize = 0; char *rdesc; int ret, n; quirks = usbhid_lookup_quirk(le16_to_cpu(dev->descriptor.idVendor), le16_to_cpu(dev->descriptor.idProduct)); if (quirks & HID_QUIRK_IGNORE) return -ENODEV; /* Many keyboards and mice don't like to be polled for reports, * so we will always set the HID_QUIRK_NOGET flag for them. */ if (interface->desc.bInterfaceSubClass == USB_INTERFACE_SUBCLASS_BOOT) { if (interface->desc.bInterfaceProtocol == USB_INTERFACE_PROTOCOL_KEYBOARD || interface->desc.bInterfaceProtocol == USB_INTERFACE_PROTOCOL_MOUSE) quirks |= HID_QUIRK_NOGET; } if (usb_get_extra_descriptor(interface, HID_DT_HID, &hdesc) && (!interface->desc.bNumEndpoints || usb_get_extra_descriptor(&interface->endpoint[0], HID_DT_HID, &hdesc))) { dbg_hid(""class descriptor not present\n""); return -ENODEV; } hid->version = le16_to_cpu(hdesc->bcdHID); hid->country = hdesc->bCountryCode; for (n = 0; n < hdesc->bNumDescriptors; n++) if (hdesc->desc[n].bDescriptorType == HID_DT_REPORT) rsize = le16_to_cpu(hdesc->desc[n].wDescriptorLength); if (!rsize || rsize > HID_MAX_DESCRIPTOR_SIZE) { dbg_hid(""weird size of report descriptor (%u)\n"", rsize); return -EINVAL; } rdesc = kmalloc(rsize, GFP_KERNEL); if (!rdesc) return -ENOMEM; hid_set_idle(dev, interface->desc.bInterfaceNumber, 0, 0); ret = hid_get_class_descriptor(dev, interface->desc.bInterfaceNumber, HID_DT_REPORT, rdesc, rsize); if (ret < 0) { dbg_hid(""reading report descriptor failed\n""); kfree(rdesc); goto err; } ret = hid_parse_report(hid, rdesc, rsize); kfree(rdesc); if (ret) { dbg_hid(""parsing report descriptor failed\n""); goto err; } hid->quirks |= quirks; return 0; err: return ret; }","static int usbhid_parse(struct hid_device *hid) { struct usb_interface *intf = to_usb_interface(hid->dev.parent); struct usb_host_interface *interface = intf->cur_altsetting; struct usb_device *dev = interface_to_usbdev (intf); struct hid_descriptor *hdesc; u32 quirks = 0; unsigned int rsize = 0; char *rdesc; int ret, n; int num_descriptors; size_t offset = offsetof(struct hid_descriptor, desc); quirks = usbhid_lookup_quirk(le16_to_cpu(dev->descriptor.idVendor), le16_to_cpu(dev->descriptor.idProduct)); if (quirks & HID_QUIRK_IGNORE) return -ENODEV; /* Many keyboards and mice don't like to be polled for reports, * so we will always set the HID_QUIRK_NOGET flag for them. */ if (interface->desc.bInterfaceSubClass == USB_INTERFACE_SUBCLASS_BOOT) { if (interface->desc.bInterfaceProtocol == USB_INTERFACE_PROTOCOL_KEYBOARD || interface->desc.bInterfaceProtocol == USB_INTERFACE_PROTOCOL_MOUSE) quirks |= HID_QUIRK_NOGET; } if (usb_get_extra_descriptor(interface, HID_DT_HID, &hdesc) && (!interface->desc.bNumEndpoints || usb_get_extra_descriptor(&interface->endpoint[0], HID_DT_HID, &hdesc))) { dbg_hid(""class descriptor not present\n""); return -ENODEV; } if (hdesc->bLength < sizeof(struct hid_descriptor)) { dbg_hid(""hid descriptor is too short\n""); return -EINVAL; } hid->version = le16_to_cpu(hdesc->bcdHID); hid->country = hdesc->bCountryCode; num_descriptors = min_t(int, hdesc->bNumDescriptors, (hdesc->bLength - offset) / sizeof(struct hid_class_descriptor)); for (n = 0; n < num_descriptors; n++) if (hdesc->desc[n].bDescriptorType == HID_DT_REPORT) rsize = le16_to_cpu(hdesc->desc[n].wDescriptorLength); if (!rsize || rsize > HID_MAX_DESCRIPTOR_SIZE) { dbg_hid(""weird size of report descriptor (%u)\n"", rsize); return -EINVAL; } rdesc = kmalloc(rsize, GFP_KERNEL); if (!rdesc) return -ENOMEM; hid_set_idle(dev, interface->desc.bInterfaceNumber, 0, 0); ret = hid_get_class_descriptor(dev, interface->desc.bInterfaceNumber, HID_DT_REPORT, rdesc, rsize); if (ret < 0) { dbg_hid(""reading report descriptor failed\n""); kfree(rdesc); goto err; } ret = hid_parse_report(hid, rdesc, rsize); kfree(rdesc); if (ret) { dbg_hid(""parsing report descriptor failed\n""); goto err; } hid->quirks |= quirks; return 0; err: return ret; }","{'deleted': [{'line_no': 36, 'char_start': 1218, 'char_end': 1264, 'line': '\tfor (n = 0; n < hdesc->bNumDescriptors; n++)\n'}], 'added': [{'line_no': 11, 'char_start': 331, 'char_end': 353, 'line': '\tint num_descriptors;\n'}, {'line_no': 12, 'char_start': 353, 'char_end': 409, 'line': '\tsize_t offset = offsetof(struct hid_descriptor, desc);\n'}, {'line_no': 35, 'char_start': 1214, 'char_end': 1269, 'line': '\tif (hdesc->bLength < sizeof(struct hid_descriptor)) {\n'}, {'line_no': 36, 'char_start': 1269, 'char_end': 1313, 'line': '\t\tdbg_hid(""hid descriptor is too short\\n"");\n'}, {'line_no': 37, 'char_start': 1313, 'char_end': 1331, 'line': '\t\treturn -EINVAL;\n'}, {'line_no': 38, 'char_start': 1331, 'char_end': 1334, 'line': '\t}\n'}, {'line_no': 39, 'char_start': 1334, 'char_end': 1335, 'line': '\n'}, {'line_no': 43, 'char_start': 1417, 'char_end': 1471, 'line': '\tnum_descriptors = min_t(int, hdesc->bNumDescriptors,\n'}, {'line_no': 44, 'char_start': 1471, 'char_end': 1545, 'line': '\t (hdesc->bLength - offset) / sizeof(struct hid_class_descriptor));\n'}, {'line_no': 45, 'char_start': 1545, 'char_end': 1546, 'line': '\n'}, {'line_no': 46, 'char_start': 1546, 'char_end': 1585, 'line': '\tfor (n = 0; n < num_descriptors; n++)\n'}]}","{'deleted': [{'char_start': 1219, 'char_end': 1220, 'chars': 'f'}, {'char_start': 1226, 'char_end': 1227, 'chars': '='}, {'char_start': 1228, 'char_end': 1230, 'chars': '0;'}, {'char_start': 1231, 'char_end': 1232, 'chars': 'n'}, {'char_start': 1233, 'char_end': 1234, 'chars': '<'}, {'char_start': 1243, 'char_end': 1244, 'chars': 'N'}, {'char_start': 1246, 'char_end': 1247, 'chars': 'D'}], 'added': [{'char_start': 331, 'char_end': 409, 'chars': '\tint num_descriptors;\n\tsize_t offset = offsetof(struct hid_descriptor, desc);\n'}, {'char_start': 1215, 'char_end': 1336, 'chars': 'if (hdesc->bLength < sizeof(struct hid_descriptor)) {\n\t\tdbg_hid(""hid descriptor is too short\\n"");\n\t\treturn -EINVAL;\n\t}\n\n\t'}, {'char_start': 1418, 'char_end': 1430, 'chars': 'num_descript'}, {'char_start': 1432, 'char_end': 1433, 'chars': 's'}, {'char_start': 1434, 'char_end': 1441, 'chars': '= min_t'}, {'char_start': 1442, 'char_end': 1443, 'chars': 'i'}, {'char_start': 1444, 'char_end': 1446, 'chars': 't,'}, {'char_start': 1447, 'char_end': 1472, 'chars': 'hdesc->bNumDescriptors,\n\t'}, {'char_start': 1473, 'char_end': 1476, 'chars': ' '}, {'char_start': 1479, 'char_end': 1480, 'chars': '('}, {'char_start': 1488, 'char_end': 1564, 'chars': 'Length - offset) / sizeof(struct hid_class_descriptor));\n\n\tfor (n = 0; n < n'}, {'char_start': 1566, 'char_end': 1568, 'chars': '_d'}]}",github.com/torvalds/linux/commit/f043bfc98c193c284e2cd768fefabe18ac2fed9b,drivers/hid/usbhid/hid-core.c,cwe-125,581 cwe-476,nfc_genl_deactivate_target,"static int nfc_genl_deactivate_target(struct sk_buff *skb, struct genl_info *info) { struct nfc_dev *dev; u32 device_idx, target_idx; int rc; if (!info->attrs[NFC_ATTR_DEVICE_INDEX]) return -EINVAL; device_idx = nla_get_u32(info->attrs[NFC_ATTR_DEVICE_INDEX]); dev = nfc_get_device(device_idx); if (!dev) return -ENODEV; target_idx = nla_get_u32(info->attrs[NFC_ATTR_TARGET_INDEX]); rc = nfc_deactivate_target(dev, target_idx, NFC_TARGET_MODE_SLEEP); nfc_put_device(dev); return rc; }","static int nfc_genl_deactivate_target(struct sk_buff *skb, struct genl_info *info) { struct nfc_dev *dev; u32 device_idx, target_idx; int rc; if (!info->attrs[NFC_ATTR_DEVICE_INDEX] || !info->attrs[NFC_ATTR_TARGET_INDEX]) return -EINVAL; device_idx = nla_get_u32(info->attrs[NFC_ATTR_DEVICE_INDEX]); dev = nfc_get_device(device_idx); if (!dev) return -ENODEV; target_idx = nla_get_u32(info->attrs[NFC_ATTR_TARGET_INDEX]); rc = nfc_deactivate_target(dev, target_idx, NFC_TARGET_MODE_SLEEP); nfc_put_device(dev); return rc; }","{'deleted': [{'line_no': 8, 'char_start': 156, 'char_end': 198, 'line': '\tif (!info->attrs[NFC_ATTR_DEVICE_INDEX])\n'}], 'added': [{'line_no': 8, 'char_start': 156, 'char_end': 200, 'line': '\tif (!info->attrs[NFC_ATTR_DEVICE_INDEX] ||\n'}, {'line_no': 9, 'char_start': 200, 'char_end': 242, 'line': '\t !info->attrs[NFC_ATTR_TARGET_INDEX])\n'}]}","{'deleted': [], 'added': [{'char_start': 196, 'char_end': 240, 'chars': ' ||\n\t !info->attrs[NFC_ATTR_TARGET_INDEX]'}]}",github.com/torvalds/linux/commit/385097a3675749cbc9e97c085c0e5dfe4269ca51,net/nfc/netlink.c,cwe-476,141 cwe-416,ffs_user_copy_worker,"static void ffs_user_copy_worker(struct work_struct *work) { struct ffs_io_data *io_data = container_of(work, struct ffs_io_data, work); int ret = io_data->req->status ? io_data->req->status : io_data->req->actual; if (io_data->read && ret > 0) { use_mm(io_data->mm); ret = copy_to_iter(io_data->buf, ret, &io_data->data); if (iov_iter_count(&io_data->data)) ret = -EFAULT; unuse_mm(io_data->mm); } io_data->kiocb->ki_complete(io_data->kiocb, ret, ret); if (io_data->ffs->ffs_eventfd && !(io_data->kiocb->ki_flags & IOCB_EVENTFD)) eventfd_signal(io_data->ffs->ffs_eventfd, 1); usb_ep_free_request(io_data->ep, io_data->req); io_data->kiocb->private = NULL; if (io_data->read) kfree(io_data->to_free); kfree(io_data->buf); kfree(io_data); }","static void ffs_user_copy_worker(struct work_struct *work) { struct ffs_io_data *io_data = container_of(work, struct ffs_io_data, work); int ret = io_data->req->status ? io_data->req->status : io_data->req->actual; bool kiocb_has_eventfd = io_data->kiocb->ki_flags & IOCB_EVENTFD; if (io_data->read && ret > 0) { use_mm(io_data->mm); ret = copy_to_iter(io_data->buf, ret, &io_data->data); if (iov_iter_count(&io_data->data)) ret = -EFAULT; unuse_mm(io_data->mm); } io_data->kiocb->ki_complete(io_data->kiocb, ret, ret); if (io_data->ffs->ffs_eventfd && !kiocb_has_eventfd) eventfd_signal(io_data->ffs->ffs_eventfd, 1); usb_ep_free_request(io_data->ep, io_data->req); if (io_data->read) kfree(io_data->to_free); kfree(io_data->buf); kfree(io_data); }","{'deleted': [{'line_no': 18, 'char_start': 488, 'char_end': 522, 'line': '\tif (io_data->ffs->ffs_eventfd &&\n'}, {'line_no': 19, 'char_start': 522, 'char_end': 571, 'line': '\t !(io_data->kiocb->ki_flags & IOCB_EVENTFD))\n'}, {'line_no': 24, 'char_start': 670, 'char_end': 703, 'line': '\tio_data->kiocb->private = NULL;\n'}], 'added': [{'line_no': 7, 'char_start': 232, 'char_end': 299, 'line': '\tbool kiocb_has_eventfd = io_data->kiocb->ki_flags & IOCB_EVENTFD;\n'}, {'line_no': 19, 'char_start': 555, 'char_end': 609, 'line': '\tif (io_data->ffs->ffs_eventfd && !kiocb_has_eventfd)\n'}]}","{'deleted': [{'char_start': 521, 'char_end': 526, 'chars': '\n\t '}, {'char_start': 528, 'char_end': 538, 'chars': '(io_data->'}, {'char_start': 543, 'char_end': 547, 'chars': '->ki'}, {'char_start': 548, 'char_end': 550, 'chars': 'fl'}, {'char_start': 551, 'char_end': 552, 'chars': 'g'}, {'char_start': 553, 'char_end': 560, 'chars': ' & IOCB'}, {'char_start': 561, 'char_end': 569, 'chars': 'EVENTFD)'}, {'char_start': 669, 'char_end': 702, 'chars': '\n\tio_data->kiocb->private = NULL;'}], 'added': [{'char_start': 232, 'char_end': 299, 'chars': '\tbool kiocb_has_eventfd = io_data->kiocb->ki_flags & IOCB_EVENTFD;\n'}, {'char_start': 596, 'char_end': 597, 'chars': 'h'}, {'char_start': 600, 'char_end': 607, 'chars': 'eventfd'}]}",github.com/torvalds/linux/commit/38740a5b87d53ceb89eb2c970150f6e94e00373a,drivers/usb/gadget/function/f_fs.c,cwe-416,250 cwe-022,_inject_file_into_fs,"def _inject_file_into_fs(fs, path, contents): absolute_path = os.path.join(fs, path.lstrip('/')) parent_dir = os.path.dirname(absolute_path) utils.execute('mkdir', '-p', parent_dir, run_as_root=True) utils.execute('tee', absolute_path, process_input=contents, run_as_root=True)","def _inject_file_into_fs(fs, path, contents, append=False): absolute_path = _join_and_check_path_within_fs(fs, path.lstrip('/')) parent_dir = os.path.dirname(absolute_path) utils.execute('mkdir', '-p', parent_dir, run_as_root=True) args = [] if append: args.append('-a') args.append(absolute_path) kwargs = dict(process_input=contents, run_as_root=True) utils.execute('tee', *args, **kwargs)","{'deleted': [{'line_no': 5, 'char_start': 212, 'char_end': 276, 'line': "" utils.execute('tee', absolute_path, process_input=contents,\n""}, {'line_no': 6, 'char_start': 276, 'char_end': 303, 'line': ' run_as_root=True)\n'}], 'added': [{'line_no': 1, 'char_start': 0, 'char_end': 60, 'line': 'def _inject_file_into_fs(fs, path, contents, append=False):\n'}, {'line_no': 2, 'char_start': 60, 'char_end': 133, 'line': "" absolute_path = _join_and_check_path_within_fs(fs, path.lstrip('/'))\n""}, {'line_no': 3, 'char_start': 133, 'char_end': 134, 'line': '\n'}, {'line_no': 6, 'char_start': 245, 'char_end': 246, 'line': '\n'}, {'line_no': 7, 'char_start': 246, 'char_end': 260, 'line': ' args = []\n'}, {'line_no': 8, 'char_start': 260, 'char_end': 275, 'line': ' if append:\n'}, {'line_no': 9, 'char_start': 275, 'char_end': 301, 'line': "" args.append('-a')\n""}, {'line_no': 10, 'char_start': 301, 'char_end': 332, 'line': ' args.append(absolute_path)\n'}, {'line_no': 11, 'char_start': 332, 'char_end': 333, 'line': '\n'}, {'line_no': 12, 'char_start': 333, 'char_end': 393, 'line': ' kwargs = dict(process_input=contents, run_as_root=True)\n'}, {'line_no': 13, 'char_start': 393, 'char_end': 394, 'line': '\n'}, {'line_no': 14, 'char_start': 394, 'char_end': 435, 'line': "" utils.execute('tee', *args, **kwargs)\n""}]}","{'deleted': [{'char_start': 67, 'char_end': 69, 'chars': 's.'}, {'char_start': 73, 'char_end': 76, 'chars': '.jo'}, {'char_start': 216, 'char_end': 218, 'chars': 'ut'}, {'char_start': 219, 'char_end': 220, 'chars': 'l'}, {'char_start': 222, 'char_end': 224, 'chars': 'ex'}, {'char_start': 225, 'char_end': 229, 'chars': 'cute'}, {'char_start': 231, 'char_end': 234, 'chars': 'tee'}, {'char_start': 235, 'char_end': 236, 'chars': ','}, {'char_start': 250, 'char_end': 251, 'chars': ','}, {'char_start': 275, 'char_end': 285, 'chars': '\n '}], 'added': [{'char_start': 43, 'char_end': 57, 'chars': ', append=False'}, {'char_start': 80, 'char_end': 82, 'chars': '_j'}, {'char_start': 83, 'char_end': 96, 'chars': 'in_and_check_'}, {'char_start': 100, 'char_end': 105, 'chars': '_with'}, {'char_start': 107, 'char_end': 110, 'chars': '_fs'}, {'char_start': 133, 'char_end': 134, 'chars': '\n'}, {'char_start': 245, 'char_end': 246, 'chars': '\n'}, {'char_start': 250, 'char_end': 264, 'chars': 'args = []\n '}, {'char_start': 265, 'char_end': 286, 'chars': 'f append:\n arg'}, {'char_start': 288, 'char_end': 291, 'chars': 'app'}, {'char_start': 292, 'char_end': 294, 'chars': 'nd'}, {'char_start': 296, 'char_end': 298, 'chars': '-a'}, {'char_start': 299, 'char_end': 304, 'chars': ')\n '}, {'char_start': 306, 'char_end': 318, 'chars': 'rgs.append(a'}, {'char_start': 330, 'char_end': 333, 'chars': ')\n\n'}, {'char_start': 334, 'char_end': 351, 'chars': ' kwargs = dict('}, {'char_start': 392, 'char_end': 435, 'chars': ""\n\n utils.execute('tee', *args, **kwargs)""}]}",github.com/openstack/nova/commit/2427d4a99bed35baefd8f17ba422cb7aae8dcca7,nova/virt/disk/api.py,cwe-022,74 cwe-787,tcos_decipher,"static int tcos_decipher(sc_card_t *card, const u8 * crgram, size_t crgram_len, u8 * out, size_t outlen) { sc_context_t *ctx; sc_apdu_t apdu; u8 rbuf[SC_MAX_APDU_BUFFER_SIZE]; u8 sbuf[SC_MAX_APDU_BUFFER_SIZE]; tcos_data *data; int tcos3, r; assert(card != NULL && crgram != NULL && out != NULL); ctx = card->ctx; tcos3=(card->type==SC_CARD_TYPE_TCOS_V3); data=(tcos_data *)card->drv_data; LOG_FUNC_CALLED(ctx); sc_log(ctx, ""TCOS3:%d PKCS1:%d\n"",tcos3, !!(data->pad_flags & SC_ALGORITHM_RSA_PAD_PKCS1)); sc_format_apdu(card, &apdu, crgram_len>255 ? SC_APDU_CASE_4_EXT : SC_APDU_CASE_4_SHORT, 0x2A, 0x80, 0x86); apdu.resp = rbuf; apdu.resplen = sizeof(rbuf); apdu.le = crgram_len; apdu.data = sbuf; apdu.lc = apdu.datalen = crgram_len+1; sbuf[0] = tcos3 ? 0x00 : ((data->pad_flags & SC_ALGORITHM_RSA_PAD_PKCS1) ? 0x81 : 0x02); memcpy(sbuf+1, crgram, crgram_len); r = sc_transmit_apdu(card, &apdu); LOG_TEST_RET(card->ctx, r, ""APDU transmit failed""); if (apdu.sw1==0x90 && apdu.sw2==0x00) { size_t len= (apdu.resplen>outlen) ? outlen : apdu.resplen; unsigned int offset=0; if(tcos3 && (data->pad_flags & SC_ALGORITHM_RSA_PAD_PKCS1) && apdu.resp[0]==0 && apdu.resp[1]==2) { offset=2; while(offsetctx, SC_LOG_DEBUG_VERBOSE, len-offset); } SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, sc_check_sw(card, apdu.sw1, apdu.sw2)); }","static int tcos_decipher(sc_card_t *card, const u8 * crgram, size_t crgram_len, u8 * out, size_t outlen) { sc_context_t *ctx; sc_apdu_t apdu; u8 rbuf[SC_MAX_APDU_BUFFER_SIZE]; u8 sbuf[SC_MAX_APDU_BUFFER_SIZE]; tcos_data *data; int tcos3, r; assert(card != NULL && crgram != NULL && out != NULL); ctx = card->ctx; tcos3=(card->type==SC_CARD_TYPE_TCOS_V3); data=(tcos_data *)card->drv_data; LOG_FUNC_CALLED(ctx); sc_log(ctx, ""TCOS3:%d PKCS1:%d\n"",tcos3, !!(data->pad_flags & SC_ALGORITHM_RSA_PAD_PKCS1)); sc_format_apdu(card, &apdu, crgram_len>255 ? SC_APDU_CASE_4_EXT : SC_APDU_CASE_4_SHORT, 0x2A, 0x80, 0x86); apdu.resp = rbuf; apdu.resplen = sizeof(rbuf); apdu.le = crgram_len; apdu.data = sbuf; apdu.lc = apdu.datalen = crgram_len+1; sbuf[0] = tcos3 ? 0x00 : ((data->pad_flags & SC_ALGORITHM_RSA_PAD_PKCS1) ? 0x81 : 0x02); if (sizeof sbuf - 1 < crgram_len) return SC_ERROR_INVALID_ARGUMENTS; memcpy(sbuf+1, crgram, crgram_len); r = sc_transmit_apdu(card, &apdu); LOG_TEST_RET(card->ctx, r, ""APDU transmit failed""); if (apdu.sw1==0x90 && apdu.sw2==0x00) { size_t len= (apdu.resplen>outlen) ? outlen : apdu.resplen; unsigned int offset=0; if(tcos3 && (data->pad_flags & SC_ALGORITHM_RSA_PAD_PKCS1) && apdu.resp[0]==0 && apdu.resp[1]==2) { offset=2; while(offsetctx, SC_LOG_DEBUG_VERBOSE, len-offset); } SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, sc_check_sw(card, apdu.sw1, apdu.sw2)); }","{'deleted': [], 'added': [{'line_no': 28, 'char_start': 852, 'char_end': 887, 'line': '\tif (sizeof sbuf - 1 < crgram_len)\n'}, {'line_no': 29, 'char_start': 887, 'char_end': 924, 'line': '\t\treturn SC_ERROR_INVALID_ARGUMENTS;\n'}]}","{'deleted': [], 'added': [{'char_start': 853, 'char_end': 925, 'chars': 'if (sizeof sbuf - 1 < crgram_len)\n\t\treturn SC_ERROR_INVALID_ARGUMENTS;\n\t'}]}",github.com/OpenSC/OpenSC/commit/9d294de90d1cc66956389856e60b6944b27b4817,src/libopensc/card-tcos.c,cwe-787,553 cwe-022,get," def get(self, path): return static_file(path, self.get_base_path())"," def get(self, path): path = self.sanitize_path(path) base_paths = self.get_base_paths() if hasattr(base_paths, 'split'): # String, so go simple base_path = base_paths else: base_path = self.get_first_base(base_paths, path) return static_file(path, base_path)","{'deleted': [{'line_no': 2, 'char_start': 25, 'char_end': 79, 'line': ' return static_file(path, self.get_base_path())\n'}], 'added': [{'line_no': 2, 'char_start': 25, 'char_end': 65, 'line': ' path = self.sanitize_path(path)\n'}, {'line_no': 3, 'char_start': 65, 'char_end': 108, 'line': ' base_paths = self.get_base_paths()\n'}, {'line_no': 4, 'char_start': 108, 'char_end': 149, 'line': "" if hasattr(base_paths, 'split'):\n""}, {'line_no': 6, 'char_start': 184, 'char_end': 219, 'line': ' base_path = base_paths\n'}, {'line_no': 7, 'char_start': 219, 'char_end': 233, 'line': ' else:\n'}, {'line_no': 8, 'char_start': 233, 'char_end': 295, 'line': ' base_path = self.get_first_base(base_paths, path)\n'}, {'line_no': 9, 'char_start': 295, 'char_end': 338, 'line': ' return static_file(path, base_path)\n'}]}","{'deleted': [{'char_start': 36, 'char_end': 37, 'chars': 'u'}, {'char_start': 44, 'char_end': 49, 'chars': 'ic_fi'}, {'char_start': 51, 'char_end': 52, 'chars': '('}, {'char_start': 56, 'char_end': 57, 'chars': ','}, {'char_start': 77, 'char_end': 78, 'chars': ')'}], 'added': [{'char_start': 33, 'char_end': 76, 'chars': 'path = self.sanitize_path(path)\n bas'}, {'char_start': 77, 'char_end': 80, 'chars': '_pa'}, {'char_start': 81, 'char_end': 85, 'chars': 'hs ='}, {'char_start': 87, 'char_end': 93, 'chars': 'elf.ge'}, {'char_start': 94, 'char_end': 101, 'chars': '_base_p'}, {'char_start': 103, 'char_end': 116, 'chars': 'hs()\n '}, {'char_start': 118, 'char_end': 143, 'chars': "" hasattr(base_paths, 'spl""}, {'char_start': 144, 'char_end': 181, 'chars': ""t'):\n # String, so go simp""}, {'char_start': 183, 'char_end': 250, 'chars': '\n base_path = base_paths\n else:\n base_'}, {'char_start': 254, 'char_end': 256, 'chars': ' ='}, {'char_start': 266, 'char_end': 277, 'chars': 'first_base('}, {'char_start': 286, 'char_end': 293, 'chars': 's, path'}, {'char_start': 294, 'char_end': 337, 'chars': '\n return static_file(path, base_path'}]}",github.com/foxbunny/seagull/commit/1fb790712fe0c1d1957b31e34a8e0e6593af87a7,seagull/routes/app.py,cwe-022,18 cwe-125,WriteHDRImage,"static MagickBooleanType WriteHDRImage(const ImageInfo *image_info,Image *image, ExceptionInfo *exception) { char header[MagickPathExtent]; const char *property; MagickBooleanType status; register const Quantum *p; register ssize_t i, x; size_t length; ssize_t count, y; unsigned char pixel[4], *pixels; /* Open output image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),""%s"",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); if (status == MagickFalse) return(status); if (IsRGBColorspace(image->colorspace) == MagickFalse) (void) TransformImageColorspace(image,RGBColorspace,exception); /* Write header. */ (void) ResetMagickMemory(header,' ',MagickPathExtent); length=CopyMagickString(header,""#?RGBE\n"",MagickPathExtent); (void) WriteBlob(image,length,(unsigned char *) header); property=GetImageProperty(image,""comment"",exception); if ((property != (const char *) NULL) && (strchr(property,'\n') == (char *) NULL)) { count=FormatLocaleString(header,MagickPathExtent,""#%s\n"",property); (void) WriteBlob(image,(size_t) count,(unsigned char *) header); } property=GetImageProperty(image,""hdr:exposure"",exception); if (property != (const char *) NULL) { count=FormatLocaleString(header,MagickPathExtent,""EXPOSURE=%g\n"", strtod(property,(char **) NULL)); (void) WriteBlob(image,(size_t) count,(unsigned char *) header); } if (image->gamma != 0.0) { count=FormatLocaleString(header,MagickPathExtent,""GAMMA=%g\n"",image->gamma); (void) WriteBlob(image,(size_t) count,(unsigned char *) header); } count=FormatLocaleString(header,MagickPathExtent, ""PRIMARIES=%g %g %g %g %g %g %g %g\n"", image->chromaticity.red_primary.x,image->chromaticity.red_primary.y, image->chromaticity.green_primary.x,image->chromaticity.green_primary.y, image->chromaticity.blue_primary.x,image->chromaticity.blue_primary.y, image->chromaticity.white_point.x,image->chromaticity.white_point.y); (void) WriteBlob(image,(size_t) count,(unsigned char *) header); length=CopyMagickString(header,""FORMAT=32-bit_rle_rgbe\n\n"",MagickPathExtent); (void) WriteBlob(image,length,(unsigned char *) header); count=FormatLocaleString(header,MagickPathExtent,""-Y %.20g +X %.20g\n"", (double) image->rows,(double) image->columns); (void) WriteBlob(image,(size_t) count,(unsigned char *) header); /* Write HDR pixels. */ pixels=(unsigned char *) AcquireQuantumMemory(image->columns,4* sizeof(*pixels)); if (pixels == (unsigned char *) NULL) ThrowWriterException(ResourceLimitError,""MemoryAllocationFailed""); for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; if ((image->columns >= 8) && (image->columns <= 0x7ffff)) { pixel[0]=2; pixel[1]=2; pixel[2]=(unsigned char) (image->columns >> 8); pixel[3]=(unsigned char) (image->columns & 0xff); count=WriteBlob(image,4*sizeof(*pixel),pixel); if (count != (ssize_t) (4*sizeof(*pixel))) break; } i=0; for (x=0; x < (ssize_t) image->columns; x++) { double gamma; pixel[0]=0; pixel[1]=0; pixel[2]=0; pixel[3]=0; gamma=QuantumScale*GetPixelRed(image,p); if ((QuantumScale*GetPixelGreen(image,p)) > gamma) gamma=QuantumScale*GetPixelGreen(image,p); if ((QuantumScale*GetPixelBlue(image,p)) > gamma) gamma=QuantumScale*GetPixelBlue(image,p); if (gamma > MagickEpsilon) { int exponent; gamma=frexp(gamma,&exponent)*256.0/gamma; pixel[0]=(unsigned char) (gamma*QuantumScale*GetPixelRed(image,p)); pixel[1]=(unsigned char) (gamma*QuantumScale*GetPixelGreen(image,p)); pixel[2]=(unsigned char) (gamma*QuantumScale*GetPixelBlue(image,p)); pixel[3]=(unsigned char) (exponent+128); } if ((image->columns >= 8) && (image->columns <= 0x7ffff)) { pixels[x]=pixel[0]; pixels[x+image->columns]=pixel[1]; pixels[x+2*image->columns]=pixel[2]; pixels[x+3*image->columns]=pixel[3]; } else { pixels[i++]=pixel[0]; pixels[i++]=pixel[1]; pixels[i++]=pixel[2]; pixels[i++]=pixel[3]; } p+=GetPixelChannels(image); } if ((image->columns >= 8) && (image->columns <= 0x7ffff)) { for (i=0; i < 4; i++) length=HDRWriteRunlengthPixels(image,&pixels[i*image->columns]); } else { count=WriteBlob(image,4*image->columns*sizeof(*pixels),pixels); if (count != (ssize_t) (4*image->columns*sizeof(*pixels))) break; } status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } pixels=(unsigned char *) RelinquishMagickMemory(pixels); (void) CloseBlob(image); return(MagickTrue); }","static MagickBooleanType WriteHDRImage(const ImageInfo *image_info,Image *image, ExceptionInfo *exception) { char header[MagickPathExtent]; const char *property; MagickBooleanType status; register const Quantum *p; register ssize_t i, x; size_t length; ssize_t count, y; unsigned char pixel[4], *pixels; /* Open output image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),""%s"",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); if (status == MagickFalse) return(status); if (IsRGBColorspace(image->colorspace) == MagickFalse) (void) TransformImageColorspace(image,RGBColorspace,exception); /* Write header. */ (void) ResetMagickMemory(header,' ',MagickPathExtent); length=CopyMagickString(header,""#?RGBE\n"",MagickPathExtent); (void) WriteBlob(image,length,(unsigned char *) header); property=GetImageProperty(image,""comment"",exception); if ((property != (const char *) NULL) && (strchr(property,'\n') == (char *) NULL)) { count=FormatLocaleString(header,MagickPathExtent,""#%s\n"",property); (void) WriteBlob(image,(size_t) count,(unsigned char *) header); } property=GetImageProperty(image,""hdr:exposure"",exception); if (property != (const char *) NULL) { count=FormatLocaleString(header,MagickPathExtent,""EXPOSURE=%g\n"", strtod(property,(char **) NULL)); (void) WriteBlob(image,(size_t) count,(unsigned char *) header); } if (image->gamma != 0.0) { count=FormatLocaleString(header,MagickPathExtent,""GAMMA=%g\n"", image->gamma); (void) WriteBlob(image,(size_t) count,(unsigned char *) header); } count=FormatLocaleString(header,MagickPathExtent, ""PRIMARIES=%g %g %g %g %g %g %g %g\n"", image->chromaticity.red_primary.x,image->chromaticity.red_primary.y, image->chromaticity.green_primary.x,image->chromaticity.green_primary.y, image->chromaticity.blue_primary.x,image->chromaticity.blue_primary.y, image->chromaticity.white_point.x,image->chromaticity.white_point.y); (void) WriteBlob(image,(size_t) count,(unsigned char *) header); length=CopyMagickString(header,""FORMAT=32-bit_rle_rgbe\n\n"",MagickPathExtent); (void) WriteBlob(image,length,(unsigned char *) header); count=FormatLocaleString(header,MagickPathExtent,""-Y %.20g +X %.20g\n"", (double) image->rows,(double) image->columns); (void) WriteBlob(image,(size_t) count,(unsigned char *) header); /* Write HDR pixels. */ pixels=(unsigned char *) AcquireQuantumMemory(image->columns+128,4* sizeof(*pixels)); if (pixels == (unsigned char *) NULL) ThrowWriterException(ResourceLimitError,""MemoryAllocationFailed""); (void) ResetMagickMemory(pixels,0,4*(image->columns+128)*sizeof(*pixels)); for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; if ((image->columns >= 8) && (image->columns <= 0x7ffff)) { pixel[0]=2; pixel[1]=2; pixel[2]=(unsigned char) (image->columns >> 8); pixel[3]=(unsigned char) (image->columns & 0xff); count=WriteBlob(image,4*sizeof(*pixel),pixel); if (count != (ssize_t) (4*sizeof(*pixel))) break; } i=0; for (x=0; x < (ssize_t) image->columns; x++) { double gamma; pixel[0]=0; pixel[1]=0; pixel[2]=0; pixel[3]=0; gamma=QuantumScale*GetPixelRed(image,p); if ((QuantumScale*GetPixelGreen(image,p)) > gamma) gamma=QuantumScale*GetPixelGreen(image,p); if ((QuantumScale*GetPixelBlue(image,p)) > gamma) gamma=QuantumScale*GetPixelBlue(image,p); if (gamma > MagickEpsilon) { int exponent; gamma=frexp(gamma,&exponent)*256.0/gamma; pixel[0]=(unsigned char) (gamma*QuantumScale*GetPixelRed(image,p)); pixel[1]=(unsigned char) (gamma*QuantumScale*GetPixelGreen(image,p)); pixel[2]=(unsigned char) (gamma*QuantumScale*GetPixelBlue(image,p)); pixel[3]=(unsigned char) (exponent+128); } if ((image->columns >= 8) && (image->columns <= 0x7ffff)) { pixels[x]=pixel[0]; pixels[x+image->columns]=pixel[1]; pixels[x+2*image->columns]=pixel[2]; pixels[x+3*image->columns]=pixel[3]; } else { pixels[i++]=pixel[0]; pixels[i++]=pixel[1]; pixels[i++]=pixel[2]; pixels[i++]=pixel[3]; } p+=GetPixelChannels(image); } if ((image->columns >= 8) && (image->columns <= 0x7ffff)) { for (i=0; i < 4; i++) length=HDRWriteRunlengthPixels(image,&pixels[i*image->columns]); } else { count=WriteBlob(image,4*image->columns*sizeof(*pixels),pixels); if (count != (ssize_t) (4*image->columns*sizeof(*pixels))) break; } status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } pixels=(unsigned char *) RelinquishMagickMemory(pixels); (void) CloseBlob(image); return(MagickTrue); }","{'deleted': [{'line_no': 69, 'char_start': 1901, 'char_end': 1984, 'line': ' count=FormatLocaleString(header,MagickPathExtent,""GAMMA=%g\\n"",image->gamma);\n'}, {'line_no': 87, 'char_start': 2886, 'char_end': 2952, 'line': ' pixels=(unsigned char *) AcquireQuantumMemory(image->columns,4*\n'}], 'added': [{'line_no': 69, 'char_start': 1901, 'char_end': 1970, 'line': ' count=FormatLocaleString(header,MagickPathExtent,""GAMMA=%g\\n"",\n'}, {'line_no': 70, 'char_start': 1970, 'char_end': 1993, 'line': ' image->gamma);\n'}, {'line_no': 88, 'char_start': 2895, 'char_end': 2965, 'line': ' pixels=(unsigned char *) AcquireQuantumMemory(image->columns+128,4*\n'}, {'line_no': 92, 'char_start': 3098, 'char_end': 3175, 'line': ' (void) ResetMagickMemory(pixels,0,4*(image->columns+128)*sizeof(*pixels));\n'}]}","{'deleted': [], 'added': [{'char_start': 1969, 'char_end': 1978, 'chars': '\n '}, {'char_start': 2957, 'char_end': 2961, 'chars': '+128'}, {'char_start': 3095, 'char_end': 3172, 'chars': ');\n (void) ResetMagickMemory(pixels,0,4*(image->columns+128)*sizeof(*pixels)'}]}",github.com/ImageMagick/ImageMagick/commit/14e606db148d6ebcaae20f1e1d6d71903ca4a556,coders/hdr.c,cwe-125,1522 cwe-190,jpc_dec_process_siz,"static int jpc_dec_process_siz(jpc_dec_t *dec, jpc_ms_t *ms) { jpc_siz_t *siz = &ms->parms.siz; int compno; int tileno; jpc_dec_tile_t *tile; jpc_dec_tcomp_t *tcomp; int htileno; int vtileno; jpc_dec_cmpt_t *cmpt; dec->xstart = siz->xoff; dec->ystart = siz->yoff; dec->xend = siz->width; dec->yend = siz->height; dec->tilewidth = siz->tilewidth; dec->tileheight = siz->tileheight; dec->tilexoff = siz->tilexoff; dec->tileyoff = siz->tileyoff; dec->numcomps = siz->numcomps; if (!(dec->cp = jpc_dec_cp_create(dec->numcomps))) { return -1; } if (!(dec->cmpts = jas_alloc2(dec->numcomps, sizeof(jpc_dec_cmpt_t)))) { return -1; } for (compno = 0, cmpt = dec->cmpts; compno < dec->numcomps; ++compno, ++cmpt) { cmpt->prec = siz->comps[compno].prec; cmpt->sgnd = siz->comps[compno].sgnd; cmpt->hstep = siz->comps[compno].hsamp; cmpt->vstep = siz->comps[compno].vsamp; cmpt->width = JPC_CEILDIV(dec->xend, cmpt->hstep) - JPC_CEILDIV(dec->xstart, cmpt->hstep); cmpt->height = JPC_CEILDIV(dec->yend, cmpt->vstep) - JPC_CEILDIV(dec->ystart, cmpt->vstep); cmpt->hsubstep = 0; cmpt->vsubstep = 0; } dec->image = 0; dec->numhtiles = JPC_CEILDIV(dec->xend - dec->tilexoff, dec->tilewidth); dec->numvtiles = JPC_CEILDIV(dec->yend - dec->tileyoff, dec->tileheight); dec->numtiles = dec->numhtiles * dec->numvtiles; JAS_DBGLOG(10, (""numtiles = %d; numhtiles = %d; numvtiles = %d;\n"", dec->numtiles, dec->numhtiles, dec->numvtiles)); if (!(dec->tiles = jas_alloc2(dec->numtiles, sizeof(jpc_dec_tile_t)))) { return -1; } for (tileno = 0, tile = dec->tiles; tileno < dec->numtiles; ++tileno, ++tile) { htileno = tileno % dec->numhtiles; vtileno = tileno / dec->numhtiles; tile->realmode = 0; tile->state = JPC_TILE_INIT; tile->xstart = JAS_MAX(dec->tilexoff + htileno * dec->tilewidth, dec->xstart); tile->ystart = JAS_MAX(dec->tileyoff + vtileno * dec->tileheight, dec->ystart); tile->xend = JAS_MIN(dec->tilexoff + (htileno + 1) * dec->tilewidth, dec->xend); tile->yend = JAS_MIN(dec->tileyoff + (vtileno + 1) * dec->tileheight, dec->yend); tile->numparts = 0; tile->partno = 0; tile->pkthdrstream = 0; tile->pkthdrstreampos = 0; tile->pptstab = 0; tile->cp = 0; tile->pi = 0; if (!(tile->tcomps = jas_alloc2(dec->numcomps, sizeof(jpc_dec_tcomp_t)))) { return -1; } for (compno = 0, cmpt = dec->cmpts, tcomp = tile->tcomps; compno < dec->numcomps; ++compno, ++cmpt, ++tcomp) { tcomp->rlvls = 0; tcomp->numrlvls = 0; tcomp->data = 0; tcomp->xstart = JPC_CEILDIV(tile->xstart, cmpt->hstep); tcomp->ystart = JPC_CEILDIV(tile->ystart, cmpt->vstep); tcomp->xend = JPC_CEILDIV(tile->xend, cmpt->hstep); tcomp->yend = JPC_CEILDIV(tile->yend, cmpt->vstep); tcomp->tsfb = 0; } } dec->pkthdrstreams = 0; /* We should expect to encounter other main header marker segments or an SOT marker segment next. */ dec->state = JPC_MH; return 0; }","static int jpc_dec_process_siz(jpc_dec_t *dec, jpc_ms_t *ms) { jpc_siz_t *siz = &ms->parms.siz; int compno; int tileno; jpc_dec_tile_t *tile; jpc_dec_tcomp_t *tcomp; int htileno; int vtileno; jpc_dec_cmpt_t *cmpt; size_t size; dec->xstart = siz->xoff; dec->ystart = siz->yoff; dec->xend = siz->width; dec->yend = siz->height; dec->tilewidth = siz->tilewidth; dec->tileheight = siz->tileheight; dec->tilexoff = siz->tilexoff; dec->tileyoff = siz->tileyoff; dec->numcomps = siz->numcomps; if (!(dec->cp = jpc_dec_cp_create(dec->numcomps))) { return -1; } if (!(dec->cmpts = jas_alloc2(dec->numcomps, sizeof(jpc_dec_cmpt_t)))) { return -1; } for (compno = 0, cmpt = dec->cmpts; compno < dec->numcomps; ++compno, ++cmpt) { cmpt->prec = siz->comps[compno].prec; cmpt->sgnd = siz->comps[compno].sgnd; cmpt->hstep = siz->comps[compno].hsamp; cmpt->vstep = siz->comps[compno].vsamp; cmpt->width = JPC_CEILDIV(dec->xend, cmpt->hstep) - JPC_CEILDIV(dec->xstart, cmpt->hstep); cmpt->height = JPC_CEILDIV(dec->yend, cmpt->vstep) - JPC_CEILDIV(dec->ystart, cmpt->vstep); cmpt->hsubstep = 0; cmpt->vsubstep = 0; } dec->image = 0; dec->numhtiles = JPC_CEILDIV(dec->xend - dec->tilexoff, dec->tilewidth); dec->numvtiles = JPC_CEILDIV(dec->yend - dec->tileyoff, dec->tileheight); if (!jas_safe_size_mul(dec->numhtiles, dec->numvtiles, &size)) { return -1; } dec->numtiles = size; JAS_DBGLOG(10, (""numtiles = %d; numhtiles = %d; numvtiles = %d;\n"", dec->numtiles, dec->numhtiles, dec->numvtiles)); if (!(dec->tiles = jas_alloc2(dec->numtiles, sizeof(jpc_dec_tile_t)))) { return -1; } for (tileno = 0, tile = dec->tiles; tileno < dec->numtiles; ++tileno, ++tile) { htileno = tileno % dec->numhtiles; vtileno = tileno / dec->numhtiles; tile->realmode = 0; tile->state = JPC_TILE_INIT; tile->xstart = JAS_MAX(dec->tilexoff + htileno * dec->tilewidth, dec->xstart); tile->ystart = JAS_MAX(dec->tileyoff + vtileno * dec->tileheight, dec->ystart); tile->xend = JAS_MIN(dec->tilexoff + (htileno + 1) * dec->tilewidth, dec->xend); tile->yend = JAS_MIN(dec->tileyoff + (vtileno + 1) * dec->tileheight, dec->yend); tile->numparts = 0; tile->partno = 0; tile->pkthdrstream = 0; tile->pkthdrstreampos = 0; tile->pptstab = 0; tile->cp = 0; tile->pi = 0; if (!(tile->tcomps = jas_alloc2(dec->numcomps, sizeof(jpc_dec_tcomp_t)))) { return -1; } for (compno = 0, cmpt = dec->cmpts, tcomp = tile->tcomps; compno < dec->numcomps; ++compno, ++cmpt, ++tcomp) { tcomp->rlvls = 0; tcomp->numrlvls = 0; tcomp->data = 0; tcomp->xstart = JPC_CEILDIV(tile->xstart, cmpt->hstep); tcomp->ystart = JPC_CEILDIV(tile->ystart, cmpt->vstep); tcomp->xend = JPC_CEILDIV(tile->xend, cmpt->hstep); tcomp->yend = JPC_CEILDIV(tile->yend, cmpt->vstep); tcomp->tsfb = 0; } } dec->pkthdrstreams = 0; /* We should expect to encounter other main header marker segments or an SOT marker segment next. */ dec->state = JPC_MH; return 0; }","{'deleted': [{'line_no': 47, 'char_start': 1312, 'char_end': 1362, 'line': '\tdec->numtiles = dec->numhtiles * dec->numvtiles;\n'}], 'added': [{'line_no': 11, 'char_start': 222, 'char_end': 236, 'line': '\tsize_t size;\n'}, {'line_no': 48, 'char_start': 1326, 'char_end': 1392, 'line': '\tif (!jas_safe_size_mul(dec->numhtiles, dec->numvtiles, &size)) {\n'}, {'line_no': 49, 'char_start': 1392, 'char_end': 1405, 'line': '\t\treturn -1;\n'}, {'line_no': 50, 'char_start': 1405, 'char_end': 1408, 'line': '\t}\n'}, {'line_no': 51, 'char_start': 1408, 'char_end': 1431, 'line': '\tdec->numtiles = size;\n'}]}","{'deleted': [{'char_start': 1326, 'char_end': 1328, 'chars': ' ='}, {'char_start': 1337, 'char_end': 1338, 'chars': 'h'}, {'char_start': 1344, 'char_end': 1345, 'chars': '*'}, {'char_start': 1354, 'char_end': 1355, 'chars': 'v'}], 'added': [{'char_start': 222, 'char_end': 236, 'chars': '\tsize_t size;\n'}, {'char_start': 1327, 'char_end': 1350, 'chars': 'if (!jas_safe_size_mul('}, {'char_start': 1358, 'char_end': 1359, 'chars': 'h'}, {'char_start': 1364, 'char_end': 1365, 'chars': ','}, {'char_start': 1374, 'char_end': 1375, 'chars': 'v'}, {'char_start': 1380, 'char_end': 1381, 'chars': ','}, {'char_start': 1382, 'char_end': 1400, 'chars': '&size)) {\n\t\treturn'}, {'char_start': 1401, 'char_end': 1409, 'chars': '-1;\n\t}\n\t'}, {'char_start': 1422, 'char_end': 1429, 'chars': ' = size'}]}",github.com/mdadams/jasper/commit/d91198abd00fc435a397fe6bad906a4c1748e9cf,src/libjasper/jpc/jpc_dec.c,cwe-190,1166 cwe-079,__init__," def __init__(self, *args, **kwargs): """""" Takes two additional keyword arguments: :param cartpos: The cart position the form should be for :param event: The event this belongs to """""" cartpos = self.cartpos = kwargs.pop('cartpos', None) orderpos = self.orderpos = kwargs.pop('orderpos', None) pos = cartpos or orderpos item = pos.item questions = pos.item.questions_to_ask event = kwargs.pop('event') super().__init__(*args, **kwargs) if item.admission and event.settings.attendee_names_asked: self.fields['attendee_name_parts'] = NamePartsFormField( max_length=255, required=event.settings.attendee_names_required, scheme=event.settings.name_scheme, label=_('Attendee name'), initial=(cartpos.attendee_name_parts if cartpos else orderpos.attendee_name_parts), ) if item.admission and event.settings.attendee_emails_asked: self.fields['attendee_email'] = forms.EmailField( required=event.settings.attendee_emails_required, label=_('Attendee email'), initial=(cartpos.attendee_email if cartpos else orderpos.attendee_email) ) for q in questions: # Do we already have an answer? Provide it as the initial value answers = [a for a in pos.answerlist if a.question_id == q.id] if answers: initial = answers[0] else: initial = None tz = pytz.timezone(event.settings.timezone) help_text = rich_text(q.help_text) if q.type == Question.TYPE_BOOLEAN: if q.required: # For some reason, django-bootstrap3 does not set the required attribute # itself. widget = forms.CheckboxInput(attrs={'required': 'required'}) else: widget = forms.CheckboxInput() if initial: initialbool = (initial.answer == ""True"") else: initialbool = False field = forms.BooleanField( label=q.question, required=q.required, help_text=help_text, initial=initialbool, widget=widget, ) elif q.type == Question.TYPE_NUMBER: field = forms.DecimalField( label=q.question, required=q.required, help_text=q.help_text, initial=initial.answer if initial else None, min_value=Decimal('0.00'), ) elif q.type == Question.TYPE_STRING: field = forms.CharField( label=q.question, required=q.required, help_text=help_text, initial=initial.answer if initial else None, ) elif q.type == Question.TYPE_TEXT: field = forms.CharField( label=q.question, required=q.required, help_text=help_text, widget=forms.Textarea, initial=initial.answer if initial else None, ) elif q.type == Question.TYPE_CHOICE: field = forms.ModelChoiceField( queryset=q.options, label=q.question, required=q.required, help_text=help_text, widget=forms.Select, empty_label='', initial=initial.options.first() if initial else None, ) elif q.type == Question.TYPE_CHOICE_MULTIPLE: field = forms.ModelMultipleChoiceField( queryset=q.options, label=q.question, required=q.required, help_text=help_text, widget=forms.CheckboxSelectMultiple, initial=initial.options.all() if initial else None, ) elif q.type == Question.TYPE_FILE: field = forms.FileField( label=q.question, required=q.required, help_text=help_text, initial=initial.file if initial else None, widget=UploadedFileWidget(position=pos, event=event, answer=initial), ) elif q.type == Question.TYPE_DATE: field = forms.DateField( label=q.question, required=q.required, help_text=help_text, initial=dateutil.parser.parse(initial.answer).date() if initial and initial.answer else None, widget=DatePickerWidget(), ) elif q.type == Question.TYPE_TIME: field = forms.TimeField( label=q.question, required=q.required, help_text=help_text, initial=dateutil.parser.parse(initial.answer).time() if initial and initial.answer else None, widget=TimePickerWidget(time_format=get_format_without_seconds('TIME_INPUT_FORMATS')), ) elif q.type == Question.TYPE_DATETIME: field = SplitDateTimeField( label=q.question, required=q.required, help_text=help_text, initial=dateutil.parser.parse(initial.answer).astimezone(tz) if initial and initial.answer else None, widget=SplitDateTimePickerWidget(time_format=get_format_without_seconds('TIME_INPUT_FORMATS')), ) field.question = q if answers: # Cache the answer object for later use field.answer = answers[0] self.fields['question_%s' % q.id] = field responses = question_form_fields.send(sender=event, position=pos) data = pos.meta_info_data for r, response in sorted(responses, key=lambda r: str(r[0])): for key, value in response.items(): # We need to be this explicit, since OrderedDict.update does not retain ordering self.fields[key] = value value.initial = data.get('question_form_data', {}).get(key)"," def __init__(self, *args, **kwargs): """""" Takes two additional keyword arguments: :param cartpos: The cart position the form should be for :param event: The event this belongs to """""" cartpos = self.cartpos = kwargs.pop('cartpos', None) orderpos = self.orderpos = kwargs.pop('orderpos', None) pos = cartpos or orderpos item = pos.item questions = pos.item.questions_to_ask event = kwargs.pop('event') super().__init__(*args, **kwargs) if item.admission and event.settings.attendee_names_asked: self.fields['attendee_name_parts'] = NamePartsFormField( max_length=255, required=event.settings.attendee_names_required, scheme=event.settings.name_scheme, label=_('Attendee name'), initial=(cartpos.attendee_name_parts if cartpos else orderpos.attendee_name_parts), ) if item.admission and event.settings.attendee_emails_asked: self.fields['attendee_email'] = forms.EmailField( required=event.settings.attendee_emails_required, label=_('Attendee email'), initial=(cartpos.attendee_email if cartpos else orderpos.attendee_email) ) for q in questions: # Do we already have an answer? Provide it as the initial value answers = [a for a in pos.answerlist if a.question_id == q.id] if answers: initial = answers[0] else: initial = None tz = pytz.timezone(event.settings.timezone) help_text = rich_text(q.help_text) label = escape(q.question) # django-bootstrap3 calls mark_safe if q.type == Question.TYPE_BOOLEAN: if q.required: # For some reason, django-bootstrap3 does not set the required attribute # itself. widget = forms.CheckboxInput(attrs={'required': 'required'}) else: widget = forms.CheckboxInput() if initial: initialbool = (initial.answer == ""True"") else: initialbool = False field = forms.BooleanField( label=label, required=q.required, help_text=help_text, initial=initialbool, widget=widget, ) elif q.type == Question.TYPE_NUMBER: field = forms.DecimalField( label=label, required=q.required, help_text=q.help_text, initial=initial.answer if initial else None, min_value=Decimal('0.00'), ) elif q.type == Question.TYPE_STRING: field = forms.CharField( label=label, required=q.required, help_text=help_text, initial=initial.answer if initial else None, ) elif q.type == Question.TYPE_TEXT: field = forms.CharField( label=label, required=q.required, help_text=help_text, widget=forms.Textarea, initial=initial.answer if initial else None, ) elif q.type == Question.TYPE_CHOICE: field = forms.ModelChoiceField( queryset=q.options, label=label, required=q.required, help_text=help_text, widget=forms.Select, empty_label='', initial=initial.options.first() if initial else None, ) elif q.type == Question.TYPE_CHOICE_MULTIPLE: field = forms.ModelMultipleChoiceField( queryset=q.options, label=label, required=q.required, help_text=help_text, widget=forms.CheckboxSelectMultiple, initial=initial.options.all() if initial else None, ) elif q.type == Question.TYPE_FILE: field = forms.FileField( label=label, required=q.required, help_text=help_text, initial=initial.file if initial else None, widget=UploadedFileWidget(position=pos, event=event, answer=initial), ) elif q.type == Question.TYPE_DATE: field = forms.DateField( label=label, required=q.required, help_text=help_text, initial=dateutil.parser.parse(initial.answer).date() if initial and initial.answer else None, widget=DatePickerWidget(), ) elif q.type == Question.TYPE_TIME: field = forms.TimeField( label=label, required=q.required, help_text=help_text, initial=dateutil.parser.parse(initial.answer).time() if initial and initial.answer else None, widget=TimePickerWidget(time_format=get_format_without_seconds('TIME_INPUT_FORMATS')), ) elif q.type == Question.TYPE_DATETIME: field = SplitDateTimeField( label=label, required=q.required, help_text=help_text, initial=dateutil.parser.parse(initial.answer).astimezone(tz) if initial and initial.answer else None, widget=SplitDateTimePickerWidget(time_format=get_format_without_seconds('TIME_INPUT_FORMATS')), ) field.question = q if answers: # Cache the answer object for later use field.answer = answers[0] self.fields['question_%s' % q.id] = field responses = question_form_fields.send(sender=event, position=pos) data = pos.meta_info_data for r, response in sorted(responses, key=lambda r: str(r[0])): for key, value in response.items(): # We need to be this explicit, since OrderedDict.update does not retain ordering self.fields[key] = value value.initial = data.get('question_form_data', {}).get(key)","{'deleted': [{'line_no': 55, 'char_start': 2264, 'char_end': 2323, 'line': ' label=q.question, required=q.required,\n'}, {'line_no': 61, 'char_start': 2531, 'char_end': 2590, 'line': ' label=q.question, required=q.required,\n'}, {'line_no': 68, 'char_start': 2853, 'char_end': 2912, 'line': ' label=q.question, required=q.required,\n'}, {'line_no': 74, 'char_start': 3124, 'char_end': 3183, 'line': ' label=q.question, required=q.required,\n'}, {'line_no': 82, 'char_start': 3487, 'char_end': 3546, 'line': ' label=q.question, required=q.required,\n'}, {'line_no': 91, 'char_start': 3910, 'char_end': 3969, 'line': ' label=q.question, required=q.required,\n'}, {'line_no': 98, 'char_start': 4245, 'char_end': 4304, 'line': ' label=q.question, required=q.required,\n'}, {'line_no': 105, 'char_start': 4604, 'char_end': 4663, 'line': ' label=q.question, required=q.required,\n'}, {'line_no': 112, 'char_start': 4971, 'char_end': 5030, 'line': ' label=q.question, required=q.required,\n'}, {'line_no': 119, 'char_start': 5405, 'char_end': 5464, 'line': ' label=q.question, required=q.required,\n'}], 'added': [{'line_no': 41, 'char_start': 1711, 'char_end': 1787, 'line': ' label = escape(q.question) # django-bootstrap3 calls mark_safe\n'}, {'line_no': 56, 'char_start': 2340, 'char_end': 2394, 'line': ' label=label, required=q.required,\n'}, {'line_no': 62, 'char_start': 2602, 'char_end': 2656, 'line': ' label=label, required=q.required,\n'}, {'line_no': 69, 'char_start': 2919, 'char_end': 2973, 'line': ' label=label, required=q.required,\n'}, {'line_no': 75, 'char_start': 3185, 'char_end': 3239, 'line': ' label=label, required=q.required,\n'}, {'line_no': 83, 'char_start': 3543, 'char_end': 3597, 'line': ' label=label, required=q.required,\n'}, {'line_no': 92, 'char_start': 3961, 'char_end': 4015, 'line': ' label=label, required=q.required,\n'}, {'line_no': 99, 'char_start': 4291, 'char_end': 4345, 'line': ' label=label, required=q.required,\n'}, {'line_no': 106, 'char_start': 4645, 'char_end': 4699, 'line': ' label=label, required=q.required,\n'}, {'line_no': 113, 'char_start': 5007, 'char_end': 5061, 'line': ' label=label, required=q.required,\n'}, {'line_no': 120, 'char_start': 5436, 'char_end': 5490, 'line': ' label=label, required=q.required,\n'}]}","{'deleted': [{'char_start': 1759, 'char_end': 1759, 'chars': ''}, {'char_start': 2290, 'char_end': 2294, 'chars': 'q.qu'}, {'char_start': 2295, 'char_end': 2300, 'chars': 'stion'}, {'char_start': 2557, 'char_end': 2561, 'chars': 'q.qu'}, {'char_start': 2562, 'char_end': 2567, 'chars': 'stion'}, {'char_start': 2879, 'char_end': 2883, 'chars': 'q.qu'}, {'char_start': 2884, 'char_end': 2889, 'chars': 'stion'}, {'char_start': 3150, 'char_end': 3154, 'chars': 'q.qu'}, {'char_start': 3155, 'char_end': 3160, 'chars': 'stion'}, {'char_start': 3513, 'char_end': 3517, 'chars': 'q.qu'}, {'char_start': 3518, 'char_end': 3523, 'chars': 'stion'}, {'char_start': 3936, 'char_end': 3940, 'chars': 'q.qu'}, {'char_start': 3941, 'char_end': 3946, 'chars': 'stion'}, {'char_start': 4271, 'char_end': 4275, 'chars': 'q.qu'}, {'char_start': 4276, 'char_end': 4281, 'chars': 'stion'}, {'char_start': 4630, 'char_end': 4634, 'chars': 'q.qu'}, {'char_start': 4635, 'char_end': 4640, 'chars': 'stion'}, {'char_start': 4997, 'char_end': 5001, 'chars': 'q.qu'}, {'char_start': 5002, 'char_end': 5007, 'chars': 'stion'}, {'char_start': 5431, 'char_end': 5435, 'chars': 'q.qu'}, {'char_start': 5436, 'char_end': 5441, 'chars': 'stion'}], 'added': [{'char_start': 1723, 'char_end': 1799, 'chars': 'label = escape(q.question) # django-bootstrap3 calls mark_safe\n '}, {'char_start': 2366, 'char_end': 2369, 'chars': 'lab'}, {'char_start': 2370, 'char_end': 2371, 'chars': 'l'}, {'char_start': 2628, 'char_end': 2631, 'chars': 'lab'}, {'char_start': 2632, 'char_end': 2633, 'chars': 'l'}, {'char_start': 2945, 'char_end': 2948, 'chars': 'lab'}, {'char_start': 2949, 'char_end': 2950, 'chars': 'l'}, {'char_start': 3211, 'char_end': 3214, 'chars': 'lab'}, {'char_start': 3215, 'char_end': 3216, 'chars': 'l'}, {'char_start': 3569, 'char_end': 3572, 'chars': 'lab'}, {'char_start': 3573, 'char_end': 3574, 'chars': 'l'}, {'char_start': 3987, 'char_end': 3990, 'chars': 'lab'}, {'char_start': 3991, 'char_end': 3992, 'chars': 'l'}, {'char_start': 4317, 'char_end': 4320, 'chars': 'lab'}, {'char_start': 4321, 'char_end': 4322, 'chars': 'l'}, {'char_start': 4671, 'char_end': 4674, 'chars': 'lab'}, {'char_start': 4675, 'char_end': 4676, 'chars': 'l'}, {'char_start': 5033, 'char_end': 5036, 'chars': 'lab'}, {'char_start': 5037, 'char_end': 5038, 'chars': 'l'}, {'char_start': 5462, 'char_end': 5465, 'chars': 'lab'}, {'char_start': 5466, 'char_end': 5467, 'chars': 'l'}]}",github.com/pretix/pretix/commit/affc6254a8316643d4afe9e8b7f8cd288c86ca1f,src/pretix/base/forms/questions.py,cwe-079,1143 cwe-022,handle," def handle(self, keepalive=True, initial_timeout=None): # we are requested to skip processing and keep the previous values if self.skip: return self.response.handle() # default to no keepalive in case something happens while even trying ensure we have a request self.keepalive = False self.headers = HTTPHeaders() # if initial_timeout is set, only wait that long for the initial request line if initial_timeout: self.connection.settimeout(initial_timeout) else: self.connection.settimeout(self.timeout) # get request line try: # ignore empty lines waiting on request request = '\r\n' while request == '\r\n': request = self.rfile.readline(max_line_size + 1).decode(http_encoding) # if read hits timeout or has some other error, ignore the request except Exception: return True # ignore empty requests if not request: return True # we have a request, go back to normal timeout if initial_timeout: self.connection.settimeout(self.timeout) # remove \r\n from the end self.request_line = request[:-2] # set some reasonable defaults in case the worst happens and we need to tell the client self.method = '' self.resource = '/' try: # HTTP Status 414 if len(request) > max_line_size: raise HTTPError(414) # HTTP Status 400 if request[-2:] != '\r\n': raise HTTPError(400) # try the request line and error out if can't parse it try: self.method, self.resource, self.request_http = self.request_line.split() # HTTP Status 400 except ValueError: raise HTTPError(400) # HTTP Status 505 if self.request_http != http_version: raise HTTPError(505) # read and parse request headers while True: line = self.rfile.readline(max_line_size + 1).decode(http_encoding) # hit end of headers if line == '\r\n': break self.headers.add(line) # if we are requested to close the connection after we finish, do so if self.headers.get('Connection') == 'close': self.keepalive = False # else since we are sure we have a request and have read all of the request data, keepalive for more later (if allowed) else: self.keepalive = keepalive # find a matching regex to handle the request with for regex, handler in self.server.routes.items(): match = regex.match(self.resource) if match: # create a dictionary of groups groups = match.groupdict() values = groups.values() for idx, group in enumerate(match.groups()): if group not in values: groups[idx] = group # create handler self.handler = handler(self, self.response, groups) break # HTTP Status 404 # if loop is not broken (handler is not found), raise a 404 else: raise HTTPError(404) # use DummyHandler so the error is raised again when ready for response except Exception as error: self.handler = DummyHandler(self, self.response, (), error) finally: # we finished listening and handling early errors and so let a response class now finish up the job of talking return self.response.handle()"," def handle(self, keepalive=True, initial_timeout=None): # we are requested to skip processing and keep the previous values if self.skip: return self.response.handle() # default to no keepalive in case something happens while even trying ensure we have a request self.keepalive = False self.headers = HTTPHeaders() # if initial_timeout is set, only wait that long for the initial request line if initial_timeout: self.connection.settimeout(initial_timeout) else: self.connection.settimeout(self.timeout) # get request line try: # ignore empty lines waiting on request request = '\r\n' while request == '\r\n': request = self.rfile.readline(max_line_size + 1).decode(http_encoding) # if read hits timeout or has some other error, ignore the request except Exception: return True # ignore empty requests if not request: return True # we have a request, go back to normal timeout if initial_timeout: self.connection.settimeout(self.timeout) # remove \r\n from the end self.request_line = request[:-2] # set some reasonable defaults in case the worst happens and we need to tell the client self.method = '' self.resource = '/' try: # HTTP Status 414 if len(request) > max_line_size: raise HTTPError(414) # HTTP Status 400 if request[-2:] != '\r\n': raise HTTPError(400) # try the request line and error out if can't parse it try: self.method, resource, self.request_http = self.request_line.split() self.resource = urllib.parse.unquote(resource) # HTTP Status 400 except ValueError: raise HTTPError(400) # HTTP Status 505 if self.request_http != http_version: raise HTTPError(505) # read and parse request headers while True: line = self.rfile.readline(max_line_size + 1).decode(http_encoding) # hit end of headers if line == '\r\n': break self.headers.add(line) # if we are requested to close the connection after we finish, do so if self.headers.get('Connection') == 'close': self.keepalive = False # else since we are sure we have a request and have read all of the request data, keepalive for more later (if allowed) else: self.keepalive = keepalive # find a matching regex to handle the request with for regex, handler in self.server.routes.items(): match = regex.match(self.resource) if match: # create a dictionary of groups groups = match.groupdict() values = groups.values() for idx, group in enumerate(match.groups()): if group not in values: groups[idx] = group # create handler self.handler = handler(self, self.response, groups) break # HTTP Status 404 # if loop is not broken (handler is not found), raise a 404 else: raise HTTPError(404) # use DummyHandler so the error is raised again when ready for response except Exception as error: self.handler = DummyHandler(self, self.response, (), error) finally: # we finished listening and handling early errors and so let a response class now finish up the job of talking return self.response.handle()","{'deleted': [{'line_no': 53, 'char_start': 1744, 'char_end': 1834, 'line': ' self.method, self.resource, self.request_http = self.request_line.split()\n'}], 'added': [{'line_no': 53, 'char_start': 1744, 'char_end': 1829, 'line': ' self.method, resource, self.request_http = self.request_line.split()\n'}, {'line_no': 54, 'char_start': 1829, 'char_end': 1892, 'line': ' self.resource = urllib.parse.unquote(resource)\n'}]}","{'deleted': [{'char_start': 1773, 'char_end': 1778, 'chars': 'self.'}], 'added': [{'char_start': 1827, 'char_end': 1890, 'chars': ')\n self.resource = urllib.parse.unquote(resource'}]}",github.com/fkmclane/python-fooster-web/commit/80202a6d3788ad1212a162d19785c600025e6aa4,fooster/web/web.py,cwe-022,761 cwe-022,deleteKey,"def deleteKey(client): """"""Deletes the specified key. Returns an error if the key doesn't exist """""" global BAD_REQUEST global NOT_FOUND validateClient(client) client_pub_key = loadClientRSAKey(client) token_data = decodeRequestToken(request.data, client_pub_key) if re.search('[^a-zA-Z0-9]', token_data['key']): raise FoxlockError(BAD_REQUEST, 'Invalid key requested') try: os.remove('keys/%s/%s.key' % (client, token_data['key'])) except FileNotFoundError: raise FoxlockError(NOT_FOUND, ""Key '%s' not found"" % token_data['key']) return ""Key '%s' successfully deleted"" % token_data['key']","def deleteKey(client): """"""Deletes the specified key. Returns an error if the key doesn't exist """""" global NOT_FOUND validateClient(client) client_pub_key = loadClientRSAKey(client) token_data = decodeRequestToken(request.data, client_pub_key) validateKeyName(token_data['key']) try: os.remove('keys/%s/%s.key' % (client, token_data['key'])) except FileNotFoundError: raise FoxlockError(NOT_FOUND, ""Key '%s' not found"" % token_data['key']) return ""Key '%s' successfully deleted"" % token_data['key']","{'deleted': [{'line_no': 5, 'char_start': 102, 'char_end': 122, 'line': '\tglobal BAD_REQUEST\n'}, {'line_no': 9, 'char_start': 165, 'char_end': 166, 'line': '\n'}, {'line_no': 12, 'char_start': 272, 'char_end': 273, 'line': '\n'}, {'line_no': 13, 'char_start': 273, 'char_end': 323, 'line': ""\tif re.search('[^a-zA-Z0-9]', token_data['key']):\n""}, {'line_no': 14, 'char_start': 323, 'char_end': 382, 'line': ""\t\traise FoxlockError(BAD_REQUEST, 'Invalid key requested')\n""}], 'added': [{'line_no': 10, 'char_start': 251, 'char_end': 287, 'line': ""\tvalidateKeyName(token_data['key'])\n""}]}","{'deleted': [{'char_start': 110, 'char_end': 130, 'chars': 'BAD_REQUEST\n\tglobal '}, {'char_start': 165, 'char_end': 166, 'chars': '\n'}, {'char_start': 272, 'char_end': 273, 'chars': '\n'}, {'char_start': 275, 'char_end': 278, 'chars': 'f r'}, {'char_start': 279, 'char_end': 281, 'chars': '.s'}, {'char_start': 283, 'char_end': 286, 'chars': 'rch'}, {'char_start': 287, 'char_end': 303, 'chars': ""'[^a-zA-Z0-9]', ""}, {'char_start': 320, 'char_end': 380, 'chars': ""):\n\t\traise FoxlockError(BAD_REQUEST, 'Invalid key requested'""}], 'added': [{'char_start': 120, 'char_end': 120, 'chars': ''}, {'char_start': 252, 'char_end': 255, 'chars': 'val'}, {'char_start': 256, 'char_end': 259, 'chars': 'dat'}, {'char_start': 260, 'char_end': 261, 'chars': 'K'}, {'char_start': 262, 'char_end': 264, 'chars': 'yN'}, {'char_start': 265, 'char_end': 267, 'chars': 'me'}]}",github.com/Mimickal/FoxLock/commit/7c665e556987f4e2c1a75e143a1e80ae066ad833,impl.py,cwe-022,154 cwe-787,enc_untrusted_create_wait_queue,"int32_t *enc_untrusted_create_wait_queue() { MessageWriter input; MessageReader output; input.Push(sizeof(int32_t)); const auto status = NonSystemCallDispatcher( ::asylo::host_call::kLocalLifetimeAllocHandler, &input, &output); CheckStatusAndParamCount(status, output, ""enc_untrusted_create_wait_queue"", 2); int32_t *queue = reinterpret_cast(output.next()); int klinux_errno = output.next(); if (queue == nullptr) { errno = FromkLinuxErrorNumber(klinux_errno); } enc_untrusted_disable_waiting(queue); return queue; }","int32_t *enc_untrusted_create_wait_queue() { MessageWriter input; MessageReader output; input.Push(sizeof(int32_t)); const auto status = NonSystemCallDispatcher( ::asylo::host_call::kLocalLifetimeAllocHandler, &input, &output); CheckStatusAndParamCount(status, output, ""enc_untrusted_create_wait_queue"", 2); int32_t *queue = reinterpret_cast(output.next()); if (!TrustedPrimitives::IsOutsideEnclave(queue, sizeof(int32_t))) { TrustedPrimitives::BestEffortAbort( ""enc_untrusted_create_wait_queue: queue should be in untrusted memory""); } int klinux_errno = output.next(); if (queue == nullptr) { errno = FromkLinuxErrorNumber(klinux_errno); } enc_untrusted_disable_waiting(queue); return queue; }","{'deleted': [], 'added': [{'line_no': 10, 'char_start': 435, 'char_end': 505, 'line': ' if (!TrustedPrimitives::IsOutsideEnclave(queue, sizeof(int32_t))) {\n'}, {'line_no': 11, 'char_start': 505, 'char_end': 545, 'line': ' TrustedPrimitives::BestEffortAbort(\n'}, {'line_no': 12, 'char_start': 545, 'char_end': 626, 'line': ' ""enc_untrusted_create_wait_queue: queue should be in untrusted memory"");\n'}, {'line_no': 13, 'char_start': 626, 'char_end': 630, 'line': ' }\n'}]}","{'deleted': [], 'added': [{'char_start': 438, 'char_end': 633, 'chars': 'f (!TrustedPrimitives::IsOutsideEnclave(queue, sizeof(int32_t))) {\n TrustedPrimitives::BestEffortAbort(\n ""enc_untrusted_create_wait_queue: queue should be in untrusted memory"");\n }\n i'}]}",github.com/google/asylo/commit/a37fb6a0e7daf30134dbbf357c9a518a1026aa02,asylo/platform/host_call/trusted/concurrency.cc,cwe-787,155 cwe-476,CompileKeymap,"CompileKeymap(XkbFile *file, struct xkb_keymap *keymap, enum merge_mode merge) { bool ok; XkbFile *files[LAST_KEYMAP_FILE_TYPE + 1] = { NULL }; enum xkb_file_type type; struct xkb_context *ctx = keymap->ctx; /* Collect section files and check for duplicates. */ for (file = (XkbFile *) file->defs; file; file = (XkbFile *) file->common.next) { if (file->file_type < FIRST_KEYMAP_FILE_TYPE || file->file_type > LAST_KEYMAP_FILE_TYPE) { log_err(ctx, ""Cannot define %s in a keymap file\n"", xkb_file_type_to_string(file->file_type)); continue; } if (files[file->file_type]) { log_err(ctx, ""More than one %s section in keymap file; "" ""All sections after the first ignored\n"", xkb_file_type_to_string(file->file_type)); continue; } files[file->file_type] = file; } /* * Check that all required section were provided. * Report everything before failing. */ ok = true; for (type = FIRST_KEYMAP_FILE_TYPE; type <= LAST_KEYMAP_FILE_TYPE; type++) { if (files[type] == NULL) { log_err(ctx, ""Required section %s missing from keymap\n"", xkb_file_type_to_string(type)); ok = false; } } if (!ok) return false; /* Compile sections. */ for (type = FIRST_KEYMAP_FILE_TYPE; type <= LAST_KEYMAP_FILE_TYPE; type++) { log_dbg(ctx, ""Compiling %s \""%s\""\n"", xkb_file_type_to_string(type), files[type]->name); ok = compile_file_fns[type](files[type], keymap, merge); if (!ok) { log_err(ctx, ""Failed to compile %s\n"", xkb_file_type_to_string(type)); return false; } } return UpdateDerivedKeymapFields(keymap); }","CompileKeymap(XkbFile *file, struct xkb_keymap *keymap, enum merge_mode merge) { bool ok; XkbFile *files[LAST_KEYMAP_FILE_TYPE + 1] = { NULL }; enum xkb_file_type type; struct xkb_context *ctx = keymap->ctx; /* Collect section files and check for duplicates. */ for (file = (XkbFile *) file->defs; file; file = (XkbFile *) file->common.next) { if (file->file_type < FIRST_KEYMAP_FILE_TYPE || file->file_type > LAST_KEYMAP_FILE_TYPE) { if (file->file_type == FILE_TYPE_GEOMETRY) { log_vrb(ctx, 1, ""Geometry sections are not supported; ignoring\n""); } else { log_err(ctx, ""Cannot define %s in a keymap file\n"", xkb_file_type_to_string(file->file_type)); } continue; } if (files[file->file_type]) { log_err(ctx, ""More than one %s section in keymap file; "" ""All sections after the first ignored\n"", xkb_file_type_to_string(file->file_type)); continue; } files[file->file_type] = file; } /* * Check that all required section were provided. * Report everything before failing. */ ok = true; for (type = FIRST_KEYMAP_FILE_TYPE; type <= LAST_KEYMAP_FILE_TYPE; type++) { if (files[type] == NULL) { log_err(ctx, ""Required section %s missing from keymap\n"", xkb_file_type_to_string(type)); ok = false; } } if (!ok) return false; /* Compile sections. */ for (type = FIRST_KEYMAP_FILE_TYPE; type <= LAST_KEYMAP_FILE_TYPE; type++) { log_dbg(ctx, ""Compiling %s \""%s\""\n"", xkb_file_type_to_string(type), files[type]->name); ok = compile_file_fns[type](files[type], keymap, merge); if (!ok) { log_err(ctx, ""Failed to compile %s\n"", xkb_file_type_to_string(type)); return false; } } return UpdateDerivedKeymapFields(keymap); }","{'deleted': [{'line_no': 13, 'char_start': 489, 'char_end': 553, 'line': ' log_err(ctx, ""Cannot define %s in a keymap file\\n"",\n'}, {'line_no': 14, 'char_start': 553, 'char_end': 616, 'line': ' xkb_file_type_to_string(file->file_type));\n'}], 'added': [{'line_no': 13, 'char_start': 489, 'char_end': 546, 'line': ' if (file->file_type == FILE_TYPE_GEOMETRY) {\n'}, {'line_no': 14, 'char_start': 546, 'char_end': 578, 'line': ' log_vrb(ctx, 1,\n'}, {'line_no': 15, 'char_start': 578, 'char_end': 654, 'line': ' ""Geometry sections are not supported; ignoring\\n"");\n'}, {'line_no': 16, 'char_start': 654, 'char_end': 675, 'line': ' } else {\n'}, {'line_no': 17, 'char_start': 675, 'char_end': 743, 'line': ' log_err(ctx, ""Cannot define %s in a keymap file\\n"",\n'}, {'line_no': 18, 'char_start': 743, 'char_end': 810, 'line': ' xkb_file_type_to_string(file->file_type));\n'}, {'line_no': 19, 'char_start': 810, 'char_end': 824, 'line': ' }\n'}]}","{'deleted': [], 'added': [{'char_start': 501, 'char_end': 691, 'chars': 'if (file->file_type == FILE_TYPE_GEOMETRY) {\n log_vrb(ctx, 1,\n ""Geometry sections are not supported; ignoring\\n"");\n } else {\n '}, {'char_start': 763, 'char_end': 767, 'chars': ' '}, {'char_start': 809, 'char_end': 823, 'chars': '\n }'}]}",github.com/xkbcommon/libxkbcommon/commit/917636b1d0d70205a13f89062b95e3a0fc31d4ff,src/xkbcomp/keymap.c,cwe-476,465 cwe-022,TarFileReader::extract,"std::string TarFileReader::extract(const string &_path) { if (_path.empty()) THROW(""path cannot be empty""); if (!hasMore()) THROW(""No more tar files""); string path = _path; if (SystemUtilities::isDirectory(path)) path += ""/"" + getFilename(); LOG_DEBUG(5, ""Extracting: "" << path); return extract(*SystemUtilities::oopen(path)); }","std::string TarFileReader::extract(const string &_path) { if (_path.empty()) THROW(""path cannot be empty""); if (!hasMore()) THROW(""No more tar files""); string path = _path; if (SystemUtilities::isDirectory(path)) { path += ""/"" + getFilename(); // Check that path is under the target directory string a = SystemUtilities::getCanonicalPath(_path); string b = SystemUtilities::getCanonicalPath(path); if (!String::startsWith(b, a)) THROW(""Tar path points outside of the extraction directory: "" << path); } LOG_DEBUG(5, ""Extracting: "" << path); switch (getType()) { case NORMAL_FILE: case CONTIGUOUS_FILE: return extract(*SystemUtilities::oopen(path)); case DIRECTORY: SystemUtilities::ensureDirectory(path); break; default: THROW(""Unsupported tar file type "" << getType()); } return getFilename(); }","{'deleted': [{'line_no': 6, 'char_start': 180, 'char_end': 251, 'line': ' if (SystemUtilities::isDirectory(path)) path += ""/"" + getFilename();\n'}, {'line_no': 10, 'char_start': 293, 'char_end': 342, 'line': ' return extract(*SystemUtilities::oopen(path));\n'}], 'added': [{'line_no': 6, 'char_start': 180, 'char_end': 224, 'line': ' if (SystemUtilities::isDirectory(path)) {\n'}, {'line_no': 7, 'char_start': 224, 'char_end': 257, 'line': ' path += ""/"" + getFilename();\n'}, {'line_no': 8, 'char_start': 257, 'char_end': 258, 'line': '\n'}, {'line_no': 10, 'char_start': 311, 'char_end': 368, 'line': ' string a = SystemUtilities::getCanonicalPath(_path);\n'}, {'line_no': 11, 'char_start': 368, 'char_end': 424, 'line': ' string b = SystemUtilities::getCanonicalPath(path);\n'}, {'line_no': 12, 'char_start': 424, 'char_end': 459, 'line': ' if (!String::startsWith(b, a))\n'}, {'line_no': 13, 'char_start': 459, 'char_end': 537, 'line': ' THROW(""Tar path points outside of the extraction directory: "" << path);\n'}, {'line_no': 14, 'char_start': 537, 'char_end': 541, 'line': ' }\n'}, {'line_no': 18, 'char_start': 583, 'char_end': 606, 'line': ' switch (getType()) {\n'}, {'line_no': 19, 'char_start': 606, 'char_end': 648, 'line': ' case NORMAL_FILE: case CONTIGUOUS_FILE:\n'}, {'line_no': 20, 'char_start': 648, 'char_end': 699, 'line': ' return extract(*SystemUtilities::oopen(path));\n'}, {'line_no': 21, 'char_start': 699, 'char_end': 764, 'line': ' case DIRECTORY: SystemUtilities::ensureDirectory(path); break;\n'}, {'line_no': 22, 'char_start': 764, 'char_end': 825, 'line': ' default: THROW(""Unsupported tar file type "" << getType());\n'}, {'line_no': 23, 'char_start': 825, 'char_end': 829, 'line': ' }\n'}, {'line_no': 24, 'char_start': 829, 'char_end': 830, 'line': '\n'}, {'line_no': 25, 'char_start': 830, 'char_end': 854, 'line': ' return getFilename();\n'}]}","{'deleted': [], 'added': [{'char_start': 222, 'char_end': 228, 'chars': '{\n '}, {'char_start': 260, 'char_end': 544, 'chars': ' // Check that path is under the target directory\n string a = SystemUtilities::getCanonicalPath(_path);\n string b = SystemUtilities::getCanonicalPath(path);\n if (!String::startsWith(b, a))\n THROW(""Tar path points outside of the extraction directory: "" << path);\n }\n\n '}, {'char_start': 585, 'char_end': 652, 'chars': 'switch (getType()) {\n case NORMAL_FILE: case CONTIGUOUS_FILE:\n '}, {'char_start': 696, 'char_end': 851, 'chars': ');\n case DIRECTORY: SystemUtilities::ensureDirectory(path); break;\n default: THROW(""Unsupported tar file type "" << getType());\n }\n\n return getFilename('}]}",github.com/CauldronDevelopmentLLC/cbang/commit/1c1dba62bd3e6fa9d0d0c0aa21926043b75382c7,src/cbang/tar/TarFileReader.cpp,cwe-022,90 cwe-125,security_fips_decrypt,"BOOL security_fips_decrypt(BYTE* data, size_t length, rdpRdp* rdp) { size_t olen; if (!winpr_Cipher_Update(rdp->fips_decrypt, data, length, data, &olen)) return FALSE; return TRUE; }","BOOL security_fips_decrypt(BYTE* data, size_t length, rdpRdp* rdp) { size_t olen; if (!rdp || !rdp->fips_decrypt) return FALSE; if (!winpr_Cipher_Update(rdp->fips_decrypt, data, length, data, &olen)) return FALSE; return TRUE; }","{'deleted': [], 'added': [{'line_no': 5, 'char_start': 84, 'char_end': 117, 'line': '\tif (!rdp || !rdp->fips_decrypt)\n'}, {'line_no': 6, 'char_start': 117, 'char_end': 133, 'line': '\t\treturn FALSE;\n'}, {'line_no': 7, 'char_start': 133, 'char_end': 134, 'line': '\n'}]}","{'deleted': [], 'added': [{'char_start': 90, 'char_end': 140, 'chars': 'rdp || !rdp->fips_decrypt)\n\t\treturn FALSE;\n\n\tif (!'}]}",github.com/FreeRDP/FreeRDP/commit/d6cd14059b257318f176c0ba3ee0a348826a9ef8,libfreerdp/core/security.c,cwe-125,59 cwe-125,cx24116_send_diseqc_msg,"static int cx24116_send_diseqc_msg(struct dvb_frontend *fe, struct dvb_diseqc_master_cmd *d) { struct cx24116_state *state = fe->demodulator_priv; int i, ret; /* Dump DiSEqC message */ if (debug) { printk(KERN_INFO ""cx24116: %s("", __func__); for (i = 0 ; i < d->msg_len ;) { printk(KERN_INFO ""0x%02x"", d->msg[i]); if (++i < d->msg_len) printk(KERN_INFO "", ""); } printk("") toneburst=%d\n"", toneburst); } /* Validate length */ if (d->msg_len > (CX24116_ARGLEN - CX24116_DISEQC_MSGOFS)) return -EINVAL; /* DiSEqC message */ for (i = 0; i < d->msg_len; i++) state->dsec_cmd.args[CX24116_DISEQC_MSGOFS + i] = d->msg[i]; /* DiSEqC message length */ state->dsec_cmd.args[CX24116_DISEQC_MSGLEN] = d->msg_len; /* Command length */ state->dsec_cmd.len = CX24116_DISEQC_MSGOFS + state->dsec_cmd.args[CX24116_DISEQC_MSGLEN]; /* DiSEqC toneburst */ if (toneburst == CX24116_DISEQC_MESGCACHE) /* Message is cached */ return 0; else if (toneburst == CX24116_DISEQC_TONEOFF) /* Message is sent without burst */ state->dsec_cmd.args[CX24116_DISEQC_BURST] = 0; else if (toneburst == CX24116_DISEQC_TONECACHE) { /* * Message is sent with derived else cached burst * * WRITE PORT GROUP COMMAND 38 * * 0/A/A: E0 10 38 F0..F3 * 1/B/B: E0 10 38 F4..F7 * 2/C/A: E0 10 38 F8..FB * 3/D/B: E0 10 38 FC..FF * * databyte[3]= 8421:8421 * ABCD:WXYZ * CLR :SET * * WX= PORT SELECT 0..3 (X=TONEBURST) * Y = VOLTAGE (0=13V, 1=18V) * Z = BAND (0=LOW, 1=HIGH(22K)) */ if (d->msg_len >= 4 && d->msg[2] == 0x38) state->dsec_cmd.args[CX24116_DISEQC_BURST] = ((d->msg[3] & 4) >> 2); if (debug) dprintk(""%s burst=%d\n"", __func__, state->dsec_cmd.args[CX24116_DISEQC_BURST]); } /* Wait for LNB ready */ ret = cx24116_wait_for_lnb(fe); if (ret != 0) return ret; /* Wait for voltage/min repeat delay */ msleep(100); /* Command */ ret = cx24116_cmd_execute(fe, &state->dsec_cmd); if (ret != 0) return ret; /* * Wait for send * * Eutelsat spec: * >15ms delay + (XXX determine if FW does this, see set_tone) * 13.5ms per byte + * >15ms delay + * 12.5ms burst + * >15ms delay (XXX determine if FW does this, see set_tone) */ msleep((state->dsec_cmd.args[CX24116_DISEQC_MSGLEN] << 4) + ((toneburst == CX24116_DISEQC_TONEOFF) ? 30 : 60)); return 0; }","static int cx24116_send_diseqc_msg(struct dvb_frontend *fe, struct dvb_diseqc_master_cmd *d) { struct cx24116_state *state = fe->demodulator_priv; int i, ret; /* Validate length */ if (d->msg_len > sizeof(d->msg)) return -EINVAL; /* Dump DiSEqC message */ if (debug) { printk(KERN_INFO ""cx24116: %s("", __func__); for (i = 0 ; i < d->msg_len ;) { printk(KERN_INFO ""0x%02x"", d->msg[i]); if (++i < d->msg_len) printk(KERN_INFO "", ""); } printk("") toneburst=%d\n"", toneburst); } /* DiSEqC message */ for (i = 0; i < d->msg_len; i++) state->dsec_cmd.args[CX24116_DISEQC_MSGOFS + i] = d->msg[i]; /* DiSEqC message length */ state->dsec_cmd.args[CX24116_DISEQC_MSGLEN] = d->msg_len; /* Command length */ state->dsec_cmd.len = CX24116_DISEQC_MSGOFS + state->dsec_cmd.args[CX24116_DISEQC_MSGLEN]; /* DiSEqC toneburst */ if (toneburst == CX24116_DISEQC_MESGCACHE) /* Message is cached */ return 0; else if (toneburst == CX24116_DISEQC_TONEOFF) /* Message is sent without burst */ state->dsec_cmd.args[CX24116_DISEQC_BURST] = 0; else if (toneburst == CX24116_DISEQC_TONECACHE) { /* * Message is sent with derived else cached burst * * WRITE PORT GROUP COMMAND 38 * * 0/A/A: E0 10 38 F0..F3 * 1/B/B: E0 10 38 F4..F7 * 2/C/A: E0 10 38 F8..FB * 3/D/B: E0 10 38 FC..FF * * databyte[3]= 8421:8421 * ABCD:WXYZ * CLR :SET * * WX= PORT SELECT 0..3 (X=TONEBURST) * Y = VOLTAGE (0=13V, 1=18V) * Z = BAND (0=LOW, 1=HIGH(22K)) */ if (d->msg_len >= 4 && d->msg[2] == 0x38) state->dsec_cmd.args[CX24116_DISEQC_BURST] = ((d->msg[3] & 4) >> 2); if (debug) dprintk(""%s burst=%d\n"", __func__, state->dsec_cmd.args[CX24116_DISEQC_BURST]); } /* Wait for LNB ready */ ret = cx24116_wait_for_lnb(fe); if (ret != 0) return ret; /* Wait for voltage/min repeat delay */ msleep(100); /* Command */ ret = cx24116_cmd_execute(fe, &state->dsec_cmd); if (ret != 0) return ret; /* * Wait for send * * Eutelsat spec: * >15ms delay + (XXX determine if FW does this, see set_tone) * 13.5ms per byte + * >15ms delay + * 12.5ms burst + * >15ms delay (XXX determine if FW does this, see set_tone) */ msleep((state->dsec_cmd.args[CX24116_DISEQC_MSGLEN] << 4) + ((toneburst == CX24116_DISEQC_TONEOFF) ? 30 : 60)); return 0; }","{'deleted': [{'line_no': 18, 'char_start': 429, 'char_end': 452, 'line': '\t/* Validate length */\n'}, {'line_no': 19, 'char_start': 452, 'char_end': 512, 'line': '\tif (d->msg_len > (CX24116_ARGLEN - CX24116_DISEQC_MSGOFS))\n'}, {'line_no': 20, 'char_start': 512, 'char_end': 530, 'line': '\t\treturn -EINVAL;\n'}, {'line_no': 21, 'char_start': 530, 'char_end': 531, 'line': '\n'}], 'added': [{'line_no': 7, 'char_start': 163, 'char_end': 186, 'line': '\t/* Validate length */\n'}, {'line_no': 8, 'char_start': 186, 'char_end': 220, 'line': '\tif (d->msg_len > sizeof(d->msg))\n'}, {'line_no': 9, 'char_start': 220, 'char_end': 252, 'line': ' return -EINVAL;\n'}, {'line_no': 10, 'char_start': 252, 'char_end': 253, 'line': '\n'}]}","{'deleted': [{'char_start': 427, 'char_end': 529, 'chars': '\n\n\t/* Validate length */\n\tif (d->msg_len > (CX24116_ARGLEN - CX24116_DISEQC_MSGOFS))\n\t\treturn -EINVAL;'}], 'added': [{'char_start': 167, 'char_end': 257, 'chars': 'Validate length */\n\tif (d->msg_len > sizeof(d->msg))\n return -EINVAL;\n\n\t/* '}]}",github.com/torvalds/linux/commit/1fa2337a315a2448c5434f41e00d56b01a22283c,drivers/media/dvb-frontends/cx24116.c,cwe-125,996 cwe-089,view_page_history,"@app.route('//history') def view_page_history(page_name): query = db.query(""select page_content.timestamp, page_content.id from page, page_content where page.id = page_content.page_id and page.page_name = '%s'"" % page_name) page_histories = query.namedresult() return render_template( 'page_history.html', page_name = page_name, page_histories = page_histories )","@app.route('//history') def view_page_history(page_name): query = db.query(""select page_content.timestamp, page_content.id from page, page_content where page.id = page_content.page_id and page.page_name = $1"", page_name) page_histories = query.namedresult() return render_template( 'page_history.html', page_name = page_name, page_histories = page_histories )","{'deleted': [{'line_no': 3, 'char_start': 69, 'char_end': 239, 'line': ' query = db.query(""select page_content.timestamp, page_content.id from page, page_content where page.id = page_content.page_id and page.page_name = \'%s\'"" % page_name)\n'}], 'added': [{'line_no': 3, 'char_start': 69, 'char_end': 236, 'line': ' query = db.query(""select page_content.timestamp, page_content.id from page, page_content where page.id = page_content.page_id and page.page_name = $1"", page_name)\n'}]}","{'deleted': [{'char_start': 220, 'char_end': 224, 'chars': ""'%s'""}, {'char_start': 225, 'char_end': 227, 'chars': ' %'}], 'added': [{'char_start': 220, 'char_end': 222, 'chars': '$1'}, {'char_start': 223, 'char_end': 224, 'chars': ','}]}",github.com/Pumala/python_wiki_app_redo/commit/65d60747cd8efb05970304234d3bd949d2088e8b,server.py,cwe-089,93 cwe-476,ResolveStateAndPredicate,"ResolveStateAndPredicate(ExprDef *expr, enum xkb_match_operation *pred_rtrn, xkb_mod_mask_t *mods_rtrn, CompatInfo *info) { if (expr == NULL) { *pred_rtrn = MATCH_ANY_OR_NONE; *mods_rtrn = MOD_REAL_MASK_ALL; return true; } *pred_rtrn = MATCH_EXACTLY; if (expr->expr.op == EXPR_ACTION_DECL) { const char *pred_txt = xkb_atom_text(info->ctx, expr->action.name); if (!LookupString(symInterpretMatchMaskNames, pred_txt, pred_rtrn)) { log_err(info->ctx, ""Illegal modifier predicate \""%s\""; Ignored\n"", pred_txt); return false; } expr = expr->action.args; } else if (expr->expr.op == EXPR_IDENT) { const char *pred_txt = xkb_atom_text(info->ctx, expr->ident.ident); if (pred_txt && istreq(pred_txt, ""any"")) { *pred_rtrn = MATCH_ANY; *mods_rtrn = MOD_REAL_MASK_ALL; return true; } } return ExprResolveModMask(info->ctx, expr, MOD_REAL, &info->mods, mods_rtrn); }","ResolveStateAndPredicate(ExprDef *expr, enum xkb_match_operation *pred_rtrn, xkb_mod_mask_t *mods_rtrn, CompatInfo *info) { if (expr == NULL) { *pred_rtrn = MATCH_ANY_OR_NONE; *mods_rtrn = MOD_REAL_MASK_ALL; return true; } *pred_rtrn = MATCH_EXACTLY; if (expr->expr.op == EXPR_ACTION_DECL) { const char *pred_txt = xkb_atom_text(info->ctx, expr->action.name); if (!LookupString(symInterpretMatchMaskNames, pred_txt, pred_rtrn) || !expr->action.args) { log_err(info->ctx, ""Illegal modifier predicate \""%s\""; Ignored\n"", pred_txt); return false; } expr = expr->action.args; } else if (expr->expr.op == EXPR_IDENT) { const char *pred_txt = xkb_atom_text(info->ctx, expr->ident.ident); if (pred_txt && istreq(pred_txt, ""any"")) { *pred_rtrn = MATCH_ANY; *mods_rtrn = MOD_REAL_MASK_ALL; return true; } } return ExprResolveModMask(info->ctx, expr, MOD_REAL, &info->mods, mods_rtrn); }","{'deleted': [{'line_no': 13, 'char_start': 434, 'char_end': 512, 'line': ' if (!LookupString(symInterpretMatchMaskNames, pred_txt, pred_rtrn)) {\n'}], 'added': [{'line_no': 13, 'char_start': 434, 'char_end': 512, 'line': ' if (!LookupString(symInterpretMatchMaskNames, pred_txt, pred_rtrn) ||\n'}, {'line_no': 14, 'char_start': 512, 'char_end': 546, 'line': ' !expr->action.args) {\n'}]}","{'deleted': [], 'added': [{'char_start': 508, 'char_end': 542, 'chars': ' ||\n !expr->action.args'}]}",github.com/xkbcommon/libxkbcommon/commit/96df3106d49438e442510c59acad306e94f3db4d,src/xkbcomp/compat.c,cwe-476,290 cwe-089,fetch_page_name," def fetch_page_name(self, page_id): ''' Returns the page name corresponding to the provided page ID. Args: page_id: The page ID whose ID to fetch. Returns: str: The page name corresponding to the provided page ID. Raises: ValueError: If the provided page ID is invalid or does not exist. ''' helpers.validate_page_id(page_id) query = 'SELECT name FROM pages WHERE id=""{0}""'.format(page_id) self.cursor.execute(query) page_name = self.cursor.fetchone() if not page_name: raise ValueError('Invalid page ID ""{0}"" provided. Page ID does not exist.'.format(page_id)) return page_name[0].encode('utf-8').replace('_', ' ')"," def fetch_page_name(self, page_id): ''' Returns the page name corresponding to the provided page ID. Args: page_id: The page ID whose ID to fetch. Returns: str: The page name corresponding to the provided page ID. Raises: ValueError: If the provided page ID is invalid or does not exist. ''' helpers.validate_page_id(page_id) query = 'SELECT name FROM pages WHERE id = ?;' query_bindings = (page_id,) self.cursor.execute(query, query_bindings) page_name = self.cursor.fetchone() if not page_name: raise ValueError('Invalid page ID ""{0}"" provided. Page ID does not exist.'.format(page_id)) return page_name[0].encode('utf-8').replace('_', ' ')","{'deleted': [{'line_no': 16, 'char_start': 378, 'char_end': 446, 'line': ' query = \'SELECT name FROM pages WHERE id=""{0}""\'.format(page_id)\n'}, {'line_no': 17, 'char_start': 446, 'char_end': 477, 'line': ' self.cursor.execute(query)\n'}], 'added': [{'line_no': 16, 'char_start': 378, 'char_end': 429, 'line': "" query = 'SELECT name FROM pages WHERE id = ?;'\n""}, {'line_no': 17, 'char_start': 429, 'char_end': 461, 'line': ' query_bindings = (page_id,)\n'}, {'line_no': 18, 'char_start': 461, 'char_end': 508, 'line': ' self.cursor.execute(query, query_bindings)\n'}]}","{'deleted': [{'char_start': 423, 'char_end': 428, 'chars': '""{0}""'}, {'char_start': 429, 'char_end': 432, 'chars': '.fo'}, {'char_start': 433, 'char_end': 436, 'chars': 'mat'}], 'added': [{'char_start': 422, 'char_end': 423, 'chars': ' '}, {'char_start': 424, 'char_end': 427, 'chars': ' ?;'}, {'char_start': 428, 'char_end': 436, 'chars': '\n que'}, {'char_start': 437, 'char_end': 450, 'chars': 'y_bindings = '}, {'char_start': 458, 'char_end': 459, 'chars': ','}, {'char_start': 490, 'char_end': 506, 'chars': ', query_bindings'}]}",github.com/jwngr/sdow/commit/4db98f3521592f17550d2b723336f33fec5e112a,sdow/database.py,cwe-089,160 cwe-078,_call_prepare_fc_map," def _call_prepare_fc_map(self, fc_map_id, source, target): try: out, err = self._run_ssh('svctask prestartfcmap %s' % fc_map_id) except exception.ProcessExecutionError as e: with excutils.save_and_reraise_exception(): LOG.error(_('_prepare_fc_map: Failed to prepare FlashCopy ' 'from %(source)s to %(target)s.\n' 'stdout: %(out)s\n stderr: %(err)s') % {'source': source, 'target': target, 'out': e.stdout, 'err': e.stderr})"," def _call_prepare_fc_map(self, fc_map_id, source, target): try: out, err = self._run_ssh(['svctask', 'prestartfcmap', fc_map_id]) except exception.ProcessExecutionError as e: with excutils.save_and_reraise_exception(): LOG.error(_('_prepare_fc_map: Failed to prepare FlashCopy ' 'from %(source)s to %(target)s.\n' 'stdout: %(out)s\n stderr: %(err)s') % {'source': source, 'target': target, 'out': e.stdout, 'err': e.stderr})","{'deleted': [{'line_no': 3, 'char_start': 76, 'char_end': 153, 'line': "" out, err = self._run_ssh('svctask prestartfcmap %s' % fc_map_id)\n""}], 'added': [{'line_no': 3, 'char_start': 76, 'char_end': 154, 'line': "" out, err = self._run_ssh(['svctask', 'prestartfcmap', fc_map_id])\n""}]}","{'deleted': [{'char_start': 135, 'char_end': 138, 'chars': ' %s'}, {'char_start': 139, 'char_end': 141, 'chars': ' %'}], 'added': [{'char_start': 113, 'char_end': 114, 'chars': '['}, {'char_start': 122, 'char_end': 124, 'chars': ""',""}, {'char_start': 125, 'char_end': 126, 'chars': ""'""}, {'char_start': 140, 'char_end': 141, 'chars': ','}, {'char_start': 151, 'char_end': 152, 'chars': ']'}]}",github.com/thatsdone/cinder/commit/f752302d181583a95cf44354aea607ce9d9283f4,cinder/volume/drivers/storwize_svc.py,cwe-078,134 cwe-089,get_top_popular,"def get_top_popular(top_num): """""" query the top(top_num) popular articles top_num => list of [title, count] """""" cmd = """"""SELECT title, views FROM articles INNER JOIN ( SELECT path, count(path) AS views FROM log GROUP BY log.path ) AS log ON log.path = '/article/' || articles.slug ORDER BY views DESC LIMIT {}"""""".format(top_num) return execute_query(cmd)","def get_top_popular(top_num): """""" query the top(top_num) popular articles top_num => list of [title, count] """""" cmd = """"""SELECT title, views FROM articles INNER JOIN ( SELECT path, count(path) AS views FROM log GROUP BY log.path ) AS log ON log.path = '/article/' || articles.slug ORDER BY views DESC LIMIT %s"""""" data = [top_num, ] return execute_query(cmd, data)","{'deleted': [{'line_no': 12, 'char_start': 410, 'char_end': 452, 'line': ' LIMIT {}"""""".format(top_num)\r\n'}, {'line_no': 13, 'char_start': 452, 'char_end': 481, 'line': ' return execute_query(cmd)\r\n'}], 'added': [{'line_no': 12, 'char_start': 410, 'char_end': 436, 'line': ' LIMIT %s""""""\r\n'}, {'line_no': 13, 'char_start': 436, 'char_end': 460, 'line': ' data = [top_num, ]\r\n'}, {'line_no': 14, 'char_start': 460, 'char_end': 495, 'line': ' return execute_query(cmd, data)\r\n'}]}","{'deleted': [{'char_start': 429, 'char_end': 431, 'chars': '{}'}, {'char_start': 434, 'char_end': 439, 'chars': '.form'}, {'char_start': 441, 'char_end': 442, 'chars': '('}, {'char_start': 449, 'char_end': 450, 'chars': ')'}], 'added': [{'char_start': 429, 'char_end': 431, 'chars': '%s'}, {'char_start': 434, 'char_end': 441, 'chars': '\r\n d'}, {'char_start': 443, 'char_end': 448, 'chars': 'a = ['}, {'char_start': 455, 'char_end': 458, 'chars': ', ]'}, {'char_start': 488, 'char_end': 494, 'chars': ', data'}]}",github.com/thugasin/udacity-homework-logAnalyzer/commit/506f25f9a1caee7f17034adf7c75e0efbc88082b,logAnalyzerDb.py,cwe-089,102 cwe-125,MAPIPrint,"void MAPIPrint(MAPIProps *p) { int j, i, index, h, x; DDWORD *ddword_ptr; DDWORD ddword_tmp; dtr thedate; MAPIProperty *mapi; variableLength *mapidata; variableLength vlTemp; int found; for (j = 0; j < p->count; j++) { mapi = &(p->properties[j]); printf("" #%i: Type: ["", j); switch (PROP_TYPE(mapi->id)) { case PT_UNSPECIFIED: printf("" NONE ""); break; case PT_NULL: printf("" NULL ""); break; case PT_I2: printf("" I2 ""); break; case PT_LONG: printf("" LONG ""); break; case PT_R4: printf("" R4 ""); break; case PT_DOUBLE: printf("" DOUBLE ""); break; case PT_CURRENCY: printf(""CURRENCY ""); break; case PT_APPTIME: printf(""APP TIME ""); break; case PT_ERROR: printf("" ERROR ""); break; case PT_BOOLEAN: printf("" BOOLEAN ""); break; case PT_OBJECT: printf("" OBJECT ""); break; case PT_I8: printf("" I8 ""); break; case PT_STRING8: printf("" STRING8 ""); break; case PT_UNICODE: printf("" UNICODE ""); break; case PT_SYSTIME: printf(""SYS TIME ""); break; case PT_CLSID: printf(""OLE GUID ""); break; case PT_BINARY: printf("" BINARY ""); break; default: printf(""<%x>"", PROP_TYPE(mapi->id)); break; } printf(""] Code: [""); if (mapi->custom == 1) { printf(""UD:x%04x"", PROP_ID(mapi->id)); } else { found = 0; for (index = 0; index < sizeof(MPList) / sizeof(MAPIPropertyTagList); index++) { if ((MPList[index].id == PROP_ID(mapi->id)) && (found == 0)) { printf(""%s"", MPList[index].name); found = 1; } } if (found == 0) { printf(""0x%04x"", PROP_ID(mapi->id)); } } printf(""]\n""); if (mapi->namedproperty > 0) { for (i = 0; i < mapi->namedproperty; i++) { printf("" Name: %s\n"", mapi->propnames[i].data); } } for (i = 0; i < mapi->count; i++) { mapidata = &(mapi->data[i]); if (mapi->count > 1) { printf("" [%i/%u] "", i, mapi->count); } else { printf("" ""); } printf(""Size: %i"", mapidata->size); switch (PROP_TYPE(mapi->id)) { case PT_SYSTIME: MAPISysTimetoDTR(mapidata->data, &thedate); printf("" Value: ""); ddword_tmp = *((DDWORD *)mapidata->data); TNEFPrintDate(thedate); printf("" [HEX: ""); for (x = 0; x < sizeof(ddword_tmp); x++) { printf("" %02x"", (BYTE)mapidata->data[x]); } printf(""] (%llu)\n"", ddword_tmp); break; case PT_LONG: printf("" Value: %li\n"", *((long*)mapidata->data)); break; case PT_I2: printf("" Value: %hi\n"", *((short int*)mapidata->data)); break; case PT_BOOLEAN: if (mapi->data->data[0] != 0) { printf("" Value: True\n""); } else { printf("" Value: False\n""); } break; case PT_OBJECT: printf(""\n""); break; case PT_BINARY: if (IsCompressedRTF(mapidata) == 1) { printf("" Detected Compressed RTF. ""); printf(""Decompressed text follows\n""); printf(""-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\n""); if ((vlTemp.data = (BYTE*)DecompressRTF(mapidata, &(vlTemp.size))) != NULL) { printf(""%s\n"", vlTemp.data); free(vlTemp.data); } printf(""-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\n""); } else { printf("" Value: [""); for (h = 0; h < mapidata->size; h++) { if (isprint(mapidata->data[h])) { printf(""%c"", mapidata->data[h]); } else { printf("".""); } } printf(""]\n""); } break; case PT_STRING8: printf("" Value: [%s]\n"", mapidata->data); if (strlen((char*)mapidata->data) != mapidata->size - 1) { printf(""Detected Hidden data: [""); for (h = 0; h < mapidata->size; h++) { if (isprint(mapidata->data[h])) { printf(""%c"", mapidata->data[h]); } else { printf("".""); } } printf(""]\n""); } break; case PT_CLSID: printf("" Value: ""); printf(""[HEX: ""); for(x=0; x< 16; x++) { printf("" %02x"", (BYTE)mapidata->data[x]); } printf(""]\n""); break; default: printf("" Value: [%s]\n"", mapidata->data); } } } }","void MAPIPrint(MAPIProps *p) { int j, i, index, h, x; DDWORD *ddword_ptr; DDWORD ddword_tmp; dtr thedate; MAPIProperty *mapi; variableLength *mapidata; variableLength vlTemp; int found; for (j = 0; j < p->count; j++) { mapi = &(p->properties[j]); printf("" #%i: Type: ["", j); switch (PROP_TYPE(mapi->id)) { case PT_UNSPECIFIED: printf("" NONE ""); break; case PT_NULL: printf("" NULL ""); break; case PT_I2: printf("" I2 ""); break; case PT_LONG: printf("" LONG ""); break; case PT_R4: printf("" R4 ""); break; case PT_DOUBLE: printf("" DOUBLE ""); break; case PT_CURRENCY: printf(""CURRENCY ""); break; case PT_APPTIME: printf(""APP TIME ""); break; case PT_ERROR: printf("" ERROR ""); break; case PT_BOOLEAN: printf("" BOOLEAN ""); break; case PT_OBJECT: printf("" OBJECT ""); break; case PT_I8: printf("" I8 ""); break; case PT_STRING8: printf("" STRING8 ""); break; case PT_UNICODE: printf("" UNICODE ""); break; case PT_SYSTIME: printf(""SYS TIME ""); break; case PT_CLSID: printf(""OLE GUID ""); break; case PT_BINARY: printf("" BINARY ""); break; default: printf(""<%x>"", PROP_TYPE(mapi->id)); break; } printf(""] Code: [""); if (mapi->custom == 1) { printf(""UD:x%04x"", PROP_ID(mapi->id)); } else { found = 0; for (index = 0; index < sizeof(MPList) / sizeof(MAPIPropertyTagList); index++) { if ((MPList[index].id == PROP_ID(mapi->id)) && (found == 0)) { printf(""%s"", MPList[index].name); found = 1; } } if (found == 0) { printf(""0x%04x"", PROP_ID(mapi->id)); } } printf(""]\n""); if (mapi->namedproperty > 0) { for (i = 0; i < mapi->namedproperty; i++) { printf("" Name: %s\n"", mapi->propnames[i].data); } } for (i = 0; i < mapi->count; i++) { mapidata = &(mapi->data[i]); if (mapi->count > 1) { printf("" [%i/%u] "", i, mapi->count); } else { printf("" ""); } printf(""Size: %i"", mapidata->size); switch (PROP_TYPE(mapi->id)) { case PT_SYSTIME: MAPISysTimetoDTR(mapidata->data, &thedate); printf("" Value: ""); ddword_tmp = *((DDWORD *)mapidata->data); TNEFPrintDate(thedate); printf("" [HEX: ""); for (x = 0; x < sizeof(ddword_tmp); x++) { printf("" %02x"", (BYTE)mapidata->data[x]); } printf(""] (%llu)\n"", ddword_tmp); break; case PT_LONG: printf("" Value: %i\n"", *((int*)mapidata->data)); break; case PT_I2: printf("" Value: %hi\n"", *((short int*)mapidata->data)); break; case PT_BOOLEAN: if (mapi->data->data[0] != 0) { printf("" Value: True\n""); } else { printf("" Value: False\n""); } break; case PT_OBJECT: printf(""\n""); break; case PT_BINARY: if (IsCompressedRTF(mapidata) == 1) { printf("" Detected Compressed RTF. ""); printf(""Decompressed text follows\n""); printf(""-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\n""); if ((vlTemp.data = (BYTE*)DecompressRTF(mapidata, &(vlTemp.size))) != NULL) { printf(""%s\n"", vlTemp.data); free(vlTemp.data); } printf(""-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\n""); } else { printf("" Value: [""); for (h = 0; h < mapidata->size; h++) { if (isprint(mapidata->data[h])) { printf(""%c"", mapidata->data[h]); } else { printf("".""); } } printf(""]\n""); } break; case PT_STRING8: printf("" Value: [%s]\n"", mapidata->data); if (strlen((char*)mapidata->data) != mapidata->size - 1) { printf(""Detected Hidden data: [""); for (h = 0; h < mapidata->size; h++) { if (isprint(mapidata->data[h])) { printf(""%c"", mapidata->data[h]); } else { printf("".""); } } printf(""]\n""); } break; case PT_CLSID: printf("" Value: ""); printf(""[HEX: ""); for(x=0; x< 16; x++) { printf("" %02x"", (BYTE)mapidata->data[x]); } printf(""]\n""); break; default: printf("" Value: [%s]\n"", mapidata->data); } } } }","{'deleted': [{'line_no': 95, 'char_start': 2731, 'char_end': 2795, 'line': ' printf("" Value: %li\\n"", *((long*)mapidata->data));\n'}], 'added': [{'line_no': 95, 'char_start': 2731, 'char_end': 2793, 'line': ' printf("" Value: %i\\n"", *((int*)mapidata->data));\n'}]}","{'deleted': [{'char_start': 2761, 'char_end': 2762, 'chars': 'l'}, {'char_start': 2771, 'char_end': 2773, 'chars': 'lo'}, {'char_start': 2774, 'char_end': 2775, 'chars': 'g'}], 'added': [{'char_start': 2770, 'char_end': 2771, 'chars': 'i'}, {'char_start': 2772, 'char_end': 2773, 'chars': 't'}]}",github.com/Yeraze/ytnef/commit/f98f5d4adc1c4bd4033638f6167c1bb95d642f89,lib/ytnef.c,cwe-125,1306 cwe-089,delete," @jwt_required def delete(self, user_id): """""" Deletes user with the corresponding user_id """""" return database_utilities.execute_query(f""""""delete from users where user_id = '{user_id}'"""""")"," @jwt_required def delete(self, user_id): """""" Deletes user with the corresponding user_id """""" return database_utilities.execute_query(f""""""delete from users where user_id = %s"""""", (user_id, ))","{'deleted': [{'line_no': 4, 'char_start': 109, 'char_end': 210, 'line': ' return database_utilities.execute_query(f""""""delete from users where user_id = \'{user_id}\'"""""")\n'}], 'added': [{'line_no': 4, 'char_start': 109, 'char_end': 214, 'line': ' return database_utilities.execute_query(f""""""delete from users where user_id = %s"""""", (user_id, ))\n'}]}","{'deleted': [{'char_start': 195, 'char_end': 197, 'chars': ""'{""}, {'char_start': 204, 'char_end': 209, 'chars': '}\'""""""'}], 'added': [{'char_start': 195, 'char_end': 203, 'chars': '%s"""""", ('}, {'char_start': 210, 'char_end': 213, 'chars': ', )'}]}",github.com/sgosal2/tiger-boards-backend/commit/4670109dd613df2f2fe7e8403ebd149df2b55485,apis/users.py,cwe-089,44 cwe-022,pascal_case,"def pascal_case(value: str) -> str: return stringcase.pascalcase(value)","def pascal_case(value: str) -> str: return stringcase.pascalcase(_sanitize(value))","{'deleted': [{'line_no': 2, 'char_start': 36, 'char_end': 75, 'line': ' return stringcase.pascalcase(value)\n'}], 'added': [{'line_no': 2, 'char_start': 36, 'char_end': 86, 'line': ' return stringcase.pascalcase(_sanitize(value))\n'}]}","{'deleted': [], 'added': [{'char_start': 69, 'char_end': 79, 'chars': '_sanitize('}, {'char_start': 85, 'char_end': 86, 'chars': ')'}]}",github.com/openapi-generators/openapi-python-client/commit/3e7dfae5d0b3685abf1ede1bc6c086a116ac4746,openapi_python_client/utils.py,cwe-022,20 cwe-476,acc_ctx_cont,"acc_ctx_cont(OM_uint32 *minstat, gss_buffer_t buf, gss_ctx_id_t *ctx, gss_buffer_t *responseToken, gss_buffer_t *mechListMIC, OM_uint32 *negState, send_token_flag *return_token) { OM_uint32 ret, tmpmin; gss_OID supportedMech; spnego_gss_ctx_id_t sc; unsigned int len; unsigned char *ptr, *bufstart; sc = (spnego_gss_ctx_id_t)*ctx; ret = GSS_S_DEFECTIVE_TOKEN; *negState = REJECT; *minstat = 0; supportedMech = GSS_C_NO_OID; *return_token = ERROR_TOKEN_SEND; *responseToken = *mechListMIC = GSS_C_NO_BUFFER; ptr = bufstart = buf->value; #define REMAIN (buf->length - (ptr - bufstart)) if (REMAIN > INT_MAX) return GSS_S_DEFECTIVE_TOKEN; /* * Attempt to work with old Sun SPNEGO. */ if (*ptr == HEADER_ID) { ret = g_verify_token_header(gss_mech_spnego, &len, &ptr, 0, REMAIN); if (ret) { *minstat = ret; return GSS_S_DEFECTIVE_TOKEN; } } if (*ptr != (CONTEXT | 0x01)) { return GSS_S_DEFECTIVE_TOKEN; } ret = get_negTokenResp(minstat, ptr, REMAIN, negState, &supportedMech, responseToken, mechListMIC); if (ret != GSS_S_COMPLETE) goto cleanup; if (*responseToken == GSS_C_NO_BUFFER && *mechListMIC == GSS_C_NO_BUFFER) { ret = GSS_S_DEFECTIVE_TOKEN; goto cleanup; } if (supportedMech != GSS_C_NO_OID) { ret = GSS_S_DEFECTIVE_TOKEN; goto cleanup; } sc->firstpass = 0; *negState = ACCEPT_INCOMPLETE; *return_token = CONT_TOKEN_SEND; cleanup: if (supportedMech != GSS_C_NO_OID) { generic_gss_release_oid(&tmpmin, &supportedMech); } return ret; #undef REMAIN }","acc_ctx_cont(OM_uint32 *minstat, gss_buffer_t buf, gss_ctx_id_t *ctx, gss_buffer_t *responseToken, gss_buffer_t *mechListMIC, OM_uint32 *negState, send_token_flag *return_token) { OM_uint32 ret, tmpmin; gss_OID supportedMech; spnego_gss_ctx_id_t sc; unsigned int len; unsigned char *ptr, *bufstart; sc = (spnego_gss_ctx_id_t)*ctx; ret = GSS_S_DEFECTIVE_TOKEN; *negState = REJECT; *minstat = 0; supportedMech = GSS_C_NO_OID; *return_token = ERROR_TOKEN_SEND; *responseToken = *mechListMIC = GSS_C_NO_BUFFER; ptr = bufstart = buf->value; #define REMAIN (buf->length - (ptr - bufstart)) if (REMAIN == 0 || REMAIN > INT_MAX) return GSS_S_DEFECTIVE_TOKEN; /* * Attempt to work with old Sun SPNEGO. */ if (*ptr == HEADER_ID) { ret = g_verify_token_header(gss_mech_spnego, &len, &ptr, 0, REMAIN); if (ret) { *minstat = ret; return GSS_S_DEFECTIVE_TOKEN; } } if (*ptr != (CONTEXT | 0x01)) { return GSS_S_DEFECTIVE_TOKEN; } ret = get_negTokenResp(minstat, ptr, REMAIN, negState, &supportedMech, responseToken, mechListMIC); if (ret != GSS_S_COMPLETE) goto cleanup; if (*responseToken == GSS_C_NO_BUFFER && *mechListMIC == GSS_C_NO_BUFFER) { ret = GSS_S_DEFECTIVE_TOKEN; goto cleanup; } if (supportedMech != GSS_C_NO_OID) { ret = GSS_S_DEFECTIVE_TOKEN; goto cleanup; } sc->firstpass = 0; *negState = ACCEPT_INCOMPLETE; *return_token = CONT_TOKEN_SEND; cleanup: if (supportedMech != GSS_C_NO_OID) { generic_gss_release_oid(&tmpmin, &supportedMech); } return ret; #undef REMAIN }","{'deleted': [{'line_no': 25, 'char_start': 635, 'char_end': 658, 'line': '\tif (REMAIN > INT_MAX)\n'}], 'added': [{'line_no': 25, 'char_start': 635, 'char_end': 673, 'line': '\tif (REMAIN == 0 || REMAIN > INT_MAX)\n'}]}","{'deleted': [], 'added': [{'char_start': 647, 'char_end': 662, 'chars': '== 0 || REMAIN '}]}",github.com/krb5/krb5/commit/524688ce87a15fc75f87efc8c039ba4c7d5c197b,src/lib/gssapi/spnego/spnego_mech.c,cwe-476,506 cwe-089,add_input," def add_input(self,data): connection = self.connect() try: # The following is a flaw query = ""INSERT INTO crimes(description) VALUES ('{}');"".format(data) with connection.cursor() as cursor: cursor.execute(query) connection.commit() finally: connection.close()"," def add_input(self,data): connection = self.connect() try: # The following is a flaw query = ""INSERT INTO crimes(description) VALUES (%s);"" with connection.cursor() as cursor: cursor.execute(query, data) connection.commit() finally: connection.close()","{'deleted': [{'line_no': 5, 'char_start': 117, 'char_end': 199, 'line': ' query = ""INSERT INTO crimes(description) VALUES (\'{}\');"".format(data)\n'}, {'line_no': 7, 'char_start': 247, 'char_end': 285, 'line': ' cursor.execute(query)\n'}], 'added': [{'line_no': 5, 'char_start': 117, 'char_end': 184, 'line': ' query = ""INSERT INTO crimes(description) VALUES (%s);""\n'}, {'line_no': 7, 'char_start': 232, 'char_end': 276, 'line': ' cursor.execute(query, data)\n'}]}","{'deleted': [{'char_start': 178, 'char_end': 182, 'chars': ""'{}'""}, {'char_start': 185, 'char_end': 198, 'chars': '.format(data)'}], 'added': [{'char_start': 178, 'char_end': 180, 'chars': '%s'}, {'char_start': 268, 'char_end': 274, 'chars': ', data'}]}",github.com/amrishc/crimemap/commit/51b3d51aa031d7c285295de36f5464d43debf6de,dbhelper.py,cwe-089,65 cwe-022,_inject_key_into_fs,"def _inject_key_into_fs(key, fs, execute=None): """"""Add the given public ssh key to root's authorized_keys. key is an ssh key string. fs is the path to the base of the filesystem into which to inject the key. """""" sshdir = os.path.join(fs, 'root', '.ssh') utils.execute('mkdir', '-p', sshdir, run_as_root=True) utils.execute('chown', 'root', sshdir, run_as_root=True) utils.execute('chmod', '700', sshdir, run_as_root=True) keyfile = os.path.join(sshdir, 'authorized_keys') key_data = [ '\n', '# The following ssh key was injected by Nova', '\n', key.strip(), '\n', ] utils.execute('tee', '-a', keyfile, process_input=''.join(key_data), run_as_root=True)","def _inject_key_into_fs(key, fs, execute=None): """"""Add the given public ssh key to root's authorized_keys. key is an ssh key string. fs is the path to the base of the filesystem into which to inject the key. """""" sshdir = _join_and_check_path_within_fs(fs, 'root', '.ssh') utils.execute('mkdir', '-p', sshdir, run_as_root=True) utils.execute('chown', 'root', sshdir, run_as_root=True) utils.execute('chmod', '700', sshdir, run_as_root=True) keyfile = os.path.join('root', '.ssh', 'authorized_keys') key_data = ''.join([ '\n', '# The following ssh key was injected by Nova', '\n', key.strip(), '\n', ]) _inject_file_into_fs(fs, keyfile, key_data, append=True)","{'deleted': [{'line_no': 7, 'char_start': 229, 'char_end': 275, 'line': "" sshdir = os.path.join(fs, 'root', '.ssh')\n""}, {'line_no': 11, 'char_start': 455, 'char_end': 509, 'line': "" keyfile = os.path.join(sshdir, 'authorized_keys')\n""}, {'line_no': 12, 'char_start': 509, 'char_end': 526, 'line': ' key_data = [\n'}, {'line_no': 18, 'char_start': 645, 'char_end': 651, 'line': ' ]\n'}, {'line_no': 19, 'char_start': 651, 'char_end': 691, 'line': "" utils.execute('tee', '-a', keyfile,\n""}, {'line_no': 20, 'char_start': 691, 'char_end': 759, 'line': "" process_input=''.join(key_data), run_as_root=True)\n""}], 'added': [{'line_no': 7, 'char_start': 229, 'char_end': 293, 'line': "" sshdir = _join_and_check_path_within_fs(fs, 'root', '.ssh')\n""}, {'line_no': 11, 'char_start': 473, 'char_end': 474, 'line': '\n'}, {'line_no': 12, 'char_start': 474, 'char_end': 536, 'line': "" keyfile = os.path.join('root', '.ssh', 'authorized_keys')\n""}, {'line_no': 13, 'char_start': 536, 'char_end': 537, 'line': '\n'}, {'line_no': 14, 'char_start': 537, 'char_end': 562, 'line': "" key_data = ''.join([\n""}, {'line_no': 20, 'char_start': 681, 'char_end': 688, 'line': ' ])\n'}, {'line_no': 21, 'char_start': 688, 'char_end': 689, 'line': '\n'}, {'line_no': 22, 'char_start': 689, 'char_end': 749, 'line': ' _inject_file_into_fs(fs, keyfile, key_data, append=True)\n'}]}","{'deleted': [{'char_start': 243, 'char_end': 245, 'chars': 's.'}, {'char_start': 249, 'char_end': 252, 'chars': '.jo'}, {'char_start': 485, 'char_end': 488, 'chars': 'dir'}, {'char_start': 655, 'char_end': 656, 'chars': 'u'}, {'char_start': 659, 'char_end': 663, 'chars': 's.ex'}, {'char_start': 664, 'char_end': 666, 'chars': 'cu'}, {'char_start': 667, 'char_end': 668, 'chars': 'e'}, {'char_start': 669, 'char_end': 680, 'chars': ""'tee', '-a'""}, {'char_start': 690, 'char_end': 699, 'chars': '\n '}, {'char_start': 700, 'char_end': 731, 'chars': "" process_input=''.join(""}, {'char_start': 739, 'char_end': 740, 'chars': ')'}, {'char_start': 742, 'char_end': 744, 'chars': 'ru'}, {'char_start': 745, 'char_end': 753, 'chars': '_as_root'}], 'added': [{'char_start': 242, 'char_end': 244, 'chars': '_j'}, {'char_start': 245, 'char_end': 258, 'chars': 'in_and_check_'}, {'char_start': 262, 'char_end': 267, 'chars': '_with'}, {'char_start': 269, 'char_end': 272, 'chars': '_fs'}, {'char_start': 473, 'char_end': 474, 'chars': '\n'}, {'char_start': 501, 'char_end': 511, 'chars': ""'root', '.""}, {'char_start': 514, 'char_end': 515, 'chars': ""'""}, {'char_start': 536, 'char_end': 537, 'chars': '\n'}, {'char_start': 552, 'char_end': 560, 'chars': ""''.join(""}, {'char_start': 686, 'char_end': 688, 'chars': ')\n'}, {'char_start': 693, 'char_end': 694, 'chars': '_'}, {'char_start': 695, 'char_end': 697, 'chars': 'nj'}, {'char_start': 700, 'char_end': 704, 'chars': '_fil'}, {'char_start': 705, 'char_end': 708, 'chars': '_in'}, {'char_start': 709, 'char_end': 716, 'chars': 'o_fs(fs'}, {'char_start': 738, 'char_end': 743, 'chars': 'ppend'}]}",github.com/openstack/nova/commit/2427d4a99bed35baefd8f17ba422cb7aae8dcca7,nova/virt/disk/api.py,cwe-022,199 cwe-089,process_ranks," def process_ranks(self, scene, urls, recent_date): PLAYER1 = 0 PLAYER2 = 1 WINNER = 2 DATE = 3 SCENE = 4 # make sure if we already have calculated ranks for these players at this time, we do not do it again sql = ""SELECT * FROM ranks WHERE scene = '{}' AND date='{}';"".format(str(scene), recent_date) res = self.db.exec(sql) if len(res) > 0: LOG.info('We have already calculated ranks for {} on date {}. SKipping'.format(scene, recent_date)) return matches = bracket_utils.get_matches_from_urls(self.db, urls) LOG.info('About to start processing ranks for scene {} on {}'.format(scene, recent_date)) # Iterate through each match, and build up our dict win_loss_dict = {} for match in matches: p1 = match[PLAYER1] p2 = match[PLAYER2] winner = match[WINNER] date = match[DATE] #Add p1 to the dict if p1 not in win_loss_dict: win_loss_dict[p1] = {} if p2 not in win_loss_dict[p1]: win_loss_dict[p1][p2] = [] # Add an entry to represent this match to p1 win_loss_dict[p1][p2].append((date, winner == p1)) # add p2 to the dict if p2 not in win_loss_dict: win_loss_dict[p2] = {} if p1 not in win_loss_dict[p2]: win_loss_dict[p2][p1] = [] win_loss_dict[p2][p1].append((date, winner == p2)) ranks = get_ranks(win_loss_dict) tag_rank_map = {} for i, x in enumerate(ranks): points, player = x rank = len(ranks) - i sql = ""INSERT INTO ranks (scene, player, rank, points, date) VALUES ('{}', '{}', '{}', '{}', '{}');""\ .format(str(scene), str(player), int(rank), str(points), str(recent_date)) self.db.exec(sql) # Only count this player if this is the scene he/she belongs to sql = ""SELECT scene FROM players WHERE tag='{}';"".format(player) res = self.db.exec(sql) if len(res) == 0 or res[0][0] == scene: # Also create a list to update the player web map = {'rank':rank, 'total_ranked':len(ranks)} tag_rank_map[player] = map player_web.update_ranks(tag_rank_map)"," def process_ranks(self, scene, urls, recent_date): PLAYER1 = 0 PLAYER2 = 1 WINNER = 2 DATE = 3 SCENE = 4 # make sure if we already have calculated ranks for these players at this time, we do not do it again sql = ""SELECT * FROM ranks WHERE scene = '{scene}' AND date='{date}';"" args = {'scene': scene, 'date': recent_date} res = self.db.exec(sql, args) if len(res) > 0: LOG.info('We have already calculated ranks for {} on date {}. SKipping'.format(scene, recent_date)) return matches = bracket_utils.get_matches_from_urls(self.db, urls) LOG.info('About to start processing ranks for scene {} on {}'.format(scene, recent_date)) # Iterate through each match, and build up our dict win_loss_dict = {} for match in matches: p1 = match[PLAYER1] p2 = match[PLAYER2] winner = match[WINNER] date = match[DATE] #Add p1 to the dict if p1 not in win_loss_dict: win_loss_dict[p1] = {} if p2 not in win_loss_dict[p1]: win_loss_dict[p1][p2] = [] # Add an entry to represent this match to p1 win_loss_dict[p1][p2].append((date, winner == p1)) # add p2 to the dict if p2 not in win_loss_dict: win_loss_dict[p2] = {} if p1 not in win_loss_dict[p2]: win_loss_dict[p2][p1] = [] win_loss_dict[p2][p1].append((date, winner == p2)) ranks = get_ranks(win_loss_dict) tag_rank_map = {} for i, x in enumerate(ranks): points, player = x rank = len(ranks) - i sql = ""INSERT INTO ranks (scene, player, rank, points, date) VALUES ('{scene}', '{player}', '{rank}', '{points}', '{recent_date}');"" args = {'scene': scene, 'player': player, 'rank': rank, 'points': points, 'recent_date': recent_date} self.db.exec(sql, args) # Only count this player if this is the scene he/she belongs to sql = ""SELECT scene FROM players WHERE tag='{player}';"" args = {'player': player} res = self.db.exec(sql, args) if len(res) == 0 or res[0][0] == scene: # Also create a list to update the player web map = {'rank':rank, 'total_ranked':len(ranks)} tag_rank_map[player] = map player_web.update_ranks(tag_rank_map)","{'deleted': [{'line_no': 9, 'char_start': 260, 'char_end': 362, 'line': ' sql = ""SELECT * FROM ranks WHERE scene = \'{}\' AND date=\'{}\';"".format(str(scene), recent_date)\n'}, {'line_no': 10, 'char_start': 362, 'char_end': 394, 'line': ' res = self.db.exec(sql)\n'}, {'line_no': 52, 'char_start': 1725, 'char_end': 1839, 'line': ' sql = ""INSERT INTO ranks (scene, player, rank, points, date) VALUES (\'{}\', \'{}\', \'{}\', \'{}\', \'{}\');""\\\n'}, {'line_no': 53, 'char_start': 1839, 'char_end': 1934, 'line': ' .format(str(scene), str(player), int(rank), str(points), str(recent_date))\n'}, {'line_no': 54, 'char_start': 1934, 'char_end': 1964, 'line': ' self.db.exec(sql)\n'}, {'line_no': 57, 'char_start': 2041, 'char_end': 2118, 'line': ' sql = ""SELECT scene FROM players WHERE tag=\'{}\';"".format(player)\n'}, {'line_no': 58, 'char_start': 2118, 'char_end': 2154, 'line': ' res = self.db.exec(sql)\n'}], 'added': [{'line_no': 9, 'char_start': 260, 'char_end': 339, 'line': ' sql = ""SELECT * FROM ranks WHERE scene = \'{scene}\' AND date=\'{date}\';""\n'}, {'line_no': 10, 'char_start': 339, 'char_end': 392, 'line': "" args = {'scene': scene, 'date': recent_date}\n""}, {'line_no': 11, 'char_start': 392, 'char_end': 430, 'line': ' res = self.db.exec(sql, args)\n'}, {'line_no': 53, 'char_start': 1761, 'char_end': 1906, 'line': ' sql = ""INSERT INTO ranks (scene, player, rank, points, date) VALUES (\'{scene}\', \'{player}\', \'{rank}\', \'{points}\', \'{recent_date}\');""\n'}, {'line_no': 54, 'char_start': 1906, 'char_end': 2020, 'line': "" args = {'scene': scene, 'player': player, 'rank': rank, 'points': points, 'recent_date': recent_date}\n""}, {'line_no': 55, 'char_start': 2020, 'char_end': 2056, 'line': ' self.db.exec(sql, args)\n'}, {'line_no': 58, 'char_start': 2133, 'char_end': 2201, 'line': ' sql = ""SELECT scene FROM players WHERE tag=\'{player}\';""\n'}, {'line_no': 59, 'char_start': 2201, 'char_end': 2239, 'line': "" args = {'player': player}\n""}, {'line_no': 60, 'char_start': 2239, 'char_end': 2281, 'line': ' res = self.db.exec(sql, args)\n'}]}","{'deleted': [{'char_start': 329, 'char_end': 334, 'chars': '.form'}, {'char_start': 335, 'char_end': 339, 'chars': 't(st'}, {'char_start': 340, 'char_end': 341, 'chars': '('}, {'char_start': 346, 'char_end': 347, 'chars': ')'}, {'char_start': 360, 'char_end': 361, 'chars': ')'}, {'char_start': 1837, 'char_end': 1838, 'chars': '\\'}, {'char_start': 1853, 'char_end': 1857, 'chars': ' '}, {'char_start': 1858, 'char_end': 1871, 'chars': ' .format(str('}, {'char_start': 1876, 'char_end': 1877, 'chars': ')'}, {'char_start': 1879, 'char_end': 1881, 'chars': 'st'}, {'char_start': 1882, 'char_end': 1883, 'chars': '('}, {'char_start': 1889, 'char_end': 1890, 'chars': ')'}, {'char_start': 1892, 'char_end': 1893, 'chars': 'i'}, {'char_start': 1894, 'char_end': 1896, 'chars': 't('}, {'char_start': 1900, 'char_end': 1901, 'chars': ')'}, {'char_start': 1903, 'char_end': 1904, 'chars': 's'}, {'char_start': 1905, 'char_end': 1907, 'chars': 'r('}, {'char_start': 1913, 'char_end': 1914, 'chars': ')'}, {'char_start': 1916, 'char_end': 1917, 'chars': 's'}, {'char_start': 1918, 'char_end': 1920, 'chars': 'r('}, {'char_start': 1931, 'char_end': 1933, 'chars': '))'}, {'char_start': 2102, 'char_end': 2105, 'chars': '.fo'}, {'char_start': 2106, 'char_end': 2107, 'chars': 'm'}, {'char_start': 2108, 'char_end': 2110, 'chars': 't('}, {'char_start': 2116, 'char_end': 2117, 'chars': ')'}], 'added': [{'char_start': 311, 'char_end': 316, 'chars': 'scene'}, {'char_start': 330, 'char_end': 334, 'chars': 'date'}, {'char_start': 338, 'char_end': 348, 'chars': '\n a'}, {'char_start': 349, 'char_end': 356, 'chars': ""gs = {'""}, {'char_start': 357, 'char_end': 364, 'chars': ""cene': ""}, {'char_start': 371, 'char_end': 379, 'chars': ""'date': ""}, {'char_start': 390, 'char_end': 391, 'chars': '}'}, {'char_start': 422, 'char_end': 428, 'chars': ', args'}, {'char_start': 1844, 'char_end': 1849, 'chars': 'scene'}, {'char_start': 1855, 'char_end': 1861, 'chars': 'player'}, {'char_start': 1867, 'char_end': 1871, 'chars': 'rank'}, {'char_start': 1877, 'char_end': 1883, 'chars': 'points'}, {'char_start': 1889, 'char_end': 1900, 'chars': 'recent_date'}, {'char_start': 1918, 'char_end': 1922, 'chars': 'args'}, {'char_start': 1923, 'char_end': 1924, 'chars': '='}, {'char_start': 1925, 'char_end': 1927, 'chars': ""{'""}, {'char_start': 1928, 'char_end': 1935, 'chars': ""cene': ""}, {'char_start': 1942, 'char_end': 1948, 'chars': ""'playe""}, {'char_start': 1949, 'char_end': 1952, 'chars': ""': ""}, {'char_start': 1960, 'char_end': 1963, 'chars': ""'ra""}, {'char_start': 1964, 'char_end': 1968, 'chars': ""k': ""}, {'char_start': 1974, 'char_end': 1980, 'chars': ""'point""}, {'char_start': 1981, 'char_end': 1984, 'chars': ""': ""}, {'char_start': 1992, 'char_end': 1993, 'chars': ""'""}, {'char_start': 1994, 'char_end': 2007, 'chars': ""ecent_date': ""}, {'char_start': 2018, 'char_end': 2019, 'chars': '}'}, {'char_start': 2048, 'char_end': 2054, 'chars': ', args'}, {'char_start': 2190, 'char_end': 2196, 'chars': 'player'}, {'char_start': 2200, 'char_end': 2214, 'chars': '\n a'}, {'char_start': 2215, 'char_end': 2224, 'chars': ""gs = {'pl""}, {'char_start': 2225, 'char_end': 2231, 'chars': ""yer': ""}, {'char_start': 2237, 'char_end': 2238, 'chars': '}'}, {'char_start': 2273, 'char_end': 2279, 'chars': ', args'}]}",github.com/DKelle/Smash_stats/commit/4bb83f3f6ce7d6bebbeb512cd015f9e72cf36d63,process_data.py,cwe-089,594 cwe-089,makeJudge,"def makeJudge(judge): db.execute(""UPDATE players SET Judge = 1 WHERE Name = '%s' COLLATE NOCASE"" % (judge)) database.commit()","def makeJudge(judge): db.execute(""UPDATE players SET Judge = 1 WHERE Name = ? COLLATE NOCASE"", judge) database.commit()","{'deleted': [{'line_no': 2, 'char_start': 22, 'char_end': 110, 'line': '\tdb.execute(""UPDATE players SET Judge = 1 WHERE Name = \'%s\' COLLATE NOCASE"" % (judge)) \n'}], 'added': [{'line_no': 2, 'char_start': 22, 'char_end': 104, 'line': '\tdb.execute(""UPDATE players SET Judge = 1 WHERE Name = ? COLLATE NOCASE"", judge) \n'}]}","{'deleted': [{'char_start': 77, 'char_end': 81, 'chars': ""'%s'""}, {'char_start': 97, 'char_end': 99, 'chars': ' %'}, {'char_start': 100, 'char_end': 101, 'chars': '('}, {'char_start': 106, 'char_end': 107, 'chars': ')'}], 'added': [{'char_start': 77, 'char_end': 78, 'chars': '?'}, {'char_start': 94, 'char_end': 95, 'chars': ','}]}",github.com/iScrE4m/XLeague/commit/59cab6e5fd8bd5e47f2418a7c71cb1d4e3cad0d2,plugins/database.py,cwe-089,36 cwe-022,wiki_handle_rest_call,"wiki_handle_rest_call(HttpRequest *req, HttpResponse *res, char *func) { if (func != NULL && *func != '\0') { if (!strcmp(func, ""page/get"")) { char *page = http_request_param_get(req, ""page""); if (page == NULL) page = http_request_get_query_string(req); if (page && (access(page, R_OK) == 0)) { http_response_printf(res, ""%s"", file_read(page)); http_response_send(res); return; } } else if (!strcmp(func, ""page/set"")) { char *wikitext = NULL, *page = NULL; if( ( (wikitext = http_request_param_get(req, ""text"")) != NULL) && ( (page = http_request_param_get(req, ""page"")) != NULL)) { file_write(page, wikitext); http_response_printf(res, ""success""); http_response_send(res); return; } } else if (!strcmp(func, ""page/delete"")) { char *page = http_request_param_get(req, ""page""); if (page == NULL) page = http_request_get_query_string(req); if (page && (unlink(page) > 0)) { http_response_printf(res, ""success""); http_response_send(res); return; } } else if (!strcmp(func, ""page/exists"")) { char *page = http_request_param_get(req, ""page""); if (page == NULL) page = http_request_get_query_string(req); if (page && (access(page, R_OK) == 0)) { http_response_printf(res, ""success""); http_response_send(res); return; } } else if (!strcmp(func, ""pages"") || !strcmp(func, ""search"")) { WikiPageList **pages = NULL; int n_pages, i; char *expr = http_request_param_get(req, ""expr""); if (expr == NULL) expr = http_request_get_query_string(req); pages = wiki_get_pages(&n_pages, expr); if (pages) { for (i=0; imtime); strftime(datebuf, sizeof(datebuf), ""%Y-%m-%d %H:%M"", pTm); http_response_printf(res, ""%s\t%s\n"", pages[i]->name, datebuf); } http_response_send(res); return; } } } http_response_set_status(res, 500, ""Error""); http_response_printf(res, ""Failed\n""); http_response_send(res); return; }","wiki_handle_rest_call(HttpRequest *req, HttpResponse *res, char *func) { if (func != NULL && *func != '\0') { if (!strcmp(func, ""page/get"")) { char *page = http_request_param_get(req, ""page""); if (page == NULL) page = http_request_get_query_string(req); if (page && page_name_is_good(page) && (access(page, R_OK) == 0)) { http_response_printf(res, ""%s"", file_read(page)); http_response_send(res); return; } } else if (!strcmp(func, ""page/set"")) { char *wikitext = NULL, *page = NULL; if( ( (wikitext = http_request_param_get(req, ""text"")) != NULL) && ( (page = http_request_param_get(req, ""page"")) != NULL)) { if (page_name_is_good(page)) { file_write(page, wikitext); http_response_printf(res, ""success""); http_response_send(res); return; } } } else if (!strcmp(func, ""page/delete"")) { char *page = http_request_param_get(req, ""page""); if (page == NULL) page = http_request_get_query_string(req); if (page && page_name_is_good(page) && (unlink(page) > 0)) { http_response_printf(res, ""success""); http_response_send(res); return; } } else if (!strcmp(func, ""page/exists"")) { char *page = http_request_param_get(req, ""page""); if (page == NULL) page = http_request_get_query_string(req); if (page && page_name_is_good(page) && (access(page, R_OK) == 0)) { http_response_printf(res, ""success""); http_response_send(res); return; } } else if (!strcmp(func, ""pages"") || !strcmp(func, ""search"")) { WikiPageList **pages = NULL; int n_pages, i; char *expr = http_request_param_get(req, ""expr""); if (expr == NULL) expr = http_request_get_query_string(req); pages = wiki_get_pages(&n_pages, expr); if (pages) { for (i=0; imtime); strftime(datebuf, sizeof(datebuf), ""%Y-%m-%d %H:%M"", pTm); http_response_printf(res, ""%s\t%s\n"", pages[i]->name, datebuf); } http_response_send(res); return; } } } http_response_set_status(res, 500, ""Error""); http_response_printf(res, ""Failed\n""); http_response_send(res); return; }","{'deleted': [{'line_no': 15, 'char_start': 307, 'char_end': 350, 'line': '\t if (page && (access(page, R_OK) == 0)) \n'}, {'line_no': 28, 'char_start': 699, 'char_end': 741, 'line': '\t file_write(page, wikitext);\t \n'}, {'line_no': 41, 'char_start': 1015, 'char_end': 1050, 'line': '\t if (page && (unlink(page) > 0))\n'}, {'line_no': 55, 'char_start': 1333, 'char_end': 1376, 'line': '\t if (page && (access(page, R_OK) == 0)) \n'}], 'added': [{'line_no': 15, 'char_start': 307, 'char_end': 376, 'line': '\t if (page && page_name_is_good(page) && (access(page, R_OK) == 0))\n'}, {'line_no': 28, 'char_start': 725, 'char_end': 757, 'line': '\t if (page_name_is_good(page))\n'}, {'line_no': 29, 'char_start': 757, 'char_end': 764, 'line': '\t {\n'}, {'line_no': 30, 'char_start': 764, 'char_end': 799, 'line': '\t file_write(page, wikitext);\n'}, {'line_no': 35, 'char_start': 898, 'char_end': 905, 'line': '\t }\n'}, {'line_no': 44, 'char_start': 1080, 'char_end': 1142, 'line': '\t if (page && page_name_is_good(page) && (unlink(page) > 0))\n'}, {'line_no': 58, 'char_start': 1425, 'char_end': 1494, 'line': '\t if (page && page_name_is_good(page) && (access(page, R_OK) == 0))\n'}]}","{'deleted': [{'char_start': 348, 'char_end': 349, 'chars': ' '}, {'char_start': 733, 'char_end': 740, 'chars': '\t '}, {'char_start': 1374, 'char_end': 1375, 'chars': ' '}], 'added': [{'char_start': 322, 'char_end': 349, 'chars': 'page_name_is_good(page) && '}, {'char_start': 725, 'char_end': 764, 'chars': '\t if (page_name_is_good(page))\n\t {\n'}, {'char_start': 898, 'char_end': 905, 'chars': '\t }\n'}, {'char_start': 1095, 'char_end': 1122, 'chars': 'page_name_is_good(page) && '}, {'char_start': 1440, 'char_end': 1467, 'chars': 'page_name_is_good(page) && '}]}",github.com/yarolig/didiwiki/commit/5e5c796617e1712905dc5462b94bd5e6c08d15ea,src/wiki.c,cwe-022,641 cwe-079,is_safe_url,"def is_safe_url(url, host=None): """""" Return ``True`` if the url is a safe redirection (i.e. it doesn't point to a different host and uses a safe scheme). Always returns ``False`` on an empty url. """""" if url is not None: url = url.strip() if not url: return False # Chrome treats \ completely as / url = url.replace('\\', '/') # Chrome considers any URL with more than two slashes to be absolute, but # urlparse is not so flexible. Treat any url with three slashes as unsafe. if url.startswith('///'): return False url_info = urlparse(url) # Forbid URLs like http:///example.com - with a scheme, but without a hostname. # In that URL, example.com is not the hostname but, a path component. However, # Chrome will still consider example.com to be the hostname, so we must not # allow this syntax. if not url_info.netloc and url_info.scheme: return False # Forbid URLs that start with control characters. Some browsers (like # Chrome) ignore quite a few control characters at the start of a # URL and might consider the URL as scheme relative. if unicodedata.category(url[0])[0] == 'C': return False return ((not url_info.netloc or url_info.netloc == host) and (not url_info.scheme or url_info.scheme in ['http', 'https']))","def is_safe_url(url, host=None): """""" Return ``True`` if the url is a safe redirection (i.e. it doesn't point to a different host and uses a safe scheme). Always returns ``False`` on an empty url. """""" if url is not None: url = url.strip() if not url: return False # Chrome treats \ completely as / in paths but it could be part of some # basic auth credentials so we need to check both URLs. return _is_safe_url(url, host) and _is_safe_url(url.replace('\\', '/'), host)","{'deleted': [{'line_no': 13, 'char_start': 346, 'char_end': 379, 'line': "" url = url.replace('\\\\', '/')\n""}], 'added': [{'line_no': 14, 'char_start': 444, 'char_end': 525, 'line': "" return _is_safe_url(url, host) and _is_safe_url(url.replace('\\\\', '/'), host)\n""}]}","{'deleted': [{'char_start': 345, 'char_end': 346, 'chars': '\n'}, {'char_start': 347, 'char_end': 396, 'chars': "" url = url.replace('\\\\', '/')\n # Chrome cons""}, {'char_start': 397, 'char_end': 403, 'chars': 'ders a'}, {'char_start': 404, 'char_end': 405, 'chars': 'y'}, {'char_start': 406, 'char_end': 422, 'chars': 'URL with more th'}, {'char_start': 423, 'char_end': 425, 'chars': 'n '}, {'char_start': 426, 'char_end': 433, 'chars': 'wo slas'}, {'char_start': 434, 'char_end': 435, 'chars': 'e'}, {'char_start': 436, 'char_end': 439, 'chars': ' to'}, {'char_start': 441, 'char_end': 448, 'chars': 'e absol'}, {'char_start': 450, 'char_end': 471, 'chars': 'e, but\n # urlparse'}, {'char_start': 473, 'char_end': 477, 'chars': 's no'}, {'char_start': 479, 'char_end': 480, 'chars': 's'}, {'char_start': 481, 'char_end': 502, 'chars': ' flexible. Treat any '}, {'char_start': 503, 'char_end': 504, 'chars': 'r'}, {'char_start': 505, 'char_end': 510, 'chars': ' with'}, {'char_start': 511, 'char_end': 514, 'chars': 'thr'}, {'char_start': 515, 'char_end': 536, 'chars': 'e slashes as unsafe.\n'}, {'char_start': 537, 'char_end': 549, 'chars': ' if url.st'}, {'char_start': 552, 'char_end': 568, 'chars': ""swith('///'):\n ""}, {'char_start': 569, 'char_end': 598, 'chars': ' return False\n url_inf'}, {'char_start': 599, 'char_end': 601, 'chars': ' ='}, {'char_start': 602, 'char_end': 608, 'chars': 'urlpar'}, {'char_start': 610, 'char_end': 615, 'chars': '(url)'}, {'char_start': 622, 'char_end': 625, 'chars': 'For'}, {'char_start': 626, 'char_end': 649, 'chars': 'id URLs like http:///ex'}, {'char_start': 650, 'char_end': 668, 'chars': 'mple.com - with a '}, {'char_start': 669, 'char_end': 681, 'chars': 'cheme, but w'}, {'char_start': 682, 'char_end': 727, 'chars': 'thout a hostname.\n # In that URL, example.'}, {'char_start': 728, 'char_end': 730, 'chars': 'om'}, {'char_start': 731, 'char_end': 747, 'chars': 'is not the hostn'}, {'char_start': 748, 'char_end': 752, 'chars': 'me b'}, {'char_start': 754, 'char_end': 761, 'chars': ', a pat'}, {'char_start': 764, 'char_end': 780, 'chars': 'omponent. Howeve'}, {'char_start': 781, 'char_end': 794, 'chars': ',\n # Chrom'}, {'char_start': 795, 'char_end': 812, 'chars': ' will still consi'}, {'char_start': 814, 'char_end': 842, 'chars': 'r example.com to be the host'}, {'char_start': 843, 'char_end': 857, 'chars': 'ame, so we mus'}, {'char_start': 858, 'char_end': 877, 'chars': ' not\n # allow th'}, {'char_start': 878, 'char_end': 884, 'chars': 's synt'}, {'char_start': 885, 'char_end': 901, 'chars': 'x.\n if not ur'}, {'char_start': 902, 'char_end': 928, 'chars': '_info.netloc and url_info.'}, {'char_start': 929, 'char_end': 936, 'chars': 'cheme:\n'}, {'char_start': 937, 'char_end': 954, 'chars': ' return Fal'}, {'char_start': 955, 'char_end': 964, 'chars': 'e\n # F'}, {'char_start': 965, 'char_end': 985, 'chars': 'rbid URLs that start'}, {'char_start': 987, 'char_end': 1006, 'chars': 'ith control charact'}, {'char_start': 1007, 'char_end': 1010, 'chars': 'rs.'}, {'char_start': 1011, 'char_end': 1047, 'chars': 'Some browsers (like\n # Chrome) ig'}, {'char_start': 1048, 'char_end': 1050, 'chars': 'or'}, {'char_start': 1051, 'char_end': 1056, 'chars': ' quit'}, {'char_start': 1058, 'char_end': 1067, 'chars': 'a few con'}, {'char_start': 1068, 'char_end': 1069, 'chars': 'r'}, {'char_start': 1070, 'char_end': 1071, 'chars': 'l'}, {'char_start': 1074, 'char_end': 1079, 'chars': 'aract'}, {'char_start': 1080, 'char_end': 1110, 'chars': 'rs at the start of a\n # URL'}, {'char_start': 1111, 'char_end': 1122, 'chars': 'and might c'}, {'char_start': 1123, 'char_end': 1130, 'chars': 'nsider '}, {'char_start': 1132, 'char_end': 1133, 'chars': 'e'}, {'char_start': 1137, 'char_end': 1139, 'chars': ' a'}, {'char_start': 1140, 'char_end': 1156, 'chars': ' scheme relative'}, {'char_start': 1162, 'char_end': 1213, 'chars': ""if unicodedata.category(url[0])[0] == 'C':\n ""}, {'char_start': 1220, 'char_end': 1246, 'chars': 'False\n return ((not url'}, {'char_start': 1248, 'char_end': 1249, 'chars': 'n'}, {'char_start': 1250, 'char_end': 1253, 'chars': 'o.n'}, {'char_start': 1254, 'char_end': 1262, 'chars': 'tloc or '}, {'char_start': 1265, 'char_end': 1274, 'chars': '_info.net'}, {'char_start': 1275, 'char_end': 1280, 'chars': 'oc =='}, {'char_start': 1290, 'char_end': 1296, 'chars': '\n '}, {'char_start': 1297, 'char_end': 1311, 'chars': ' (not url'}, {'char_start': 1313, 'char_end': 1317, 'chars': 'nfo.'}, {'char_start': 1318, 'char_end': 1320, 'chars': 'ch'}, {'char_start': 1321, 'char_end': 1325, 'chars': 'me o'}, {'char_start': 1326, 'char_end': 1327, 'chars': ' '}, {'char_start': 1330, 'char_end': 1335, 'chars': '_info'}, {'char_start': 1336, 'char_end': 1339, 'chars': 'sch'}, {'char_start': 1340, 'char_end': 1341, 'chars': 'm'}, {'char_start': 1343, 'char_end': 1347, 'chars': 'in ['}, {'char_start': 1348, 'char_end': 1352, 'chars': 'http'}, {'char_start': 1355, 'char_end': 1356, 'chars': ""'""}, {'char_start': 1357, 'char_end': 1360, 'chars': 'ttp'}, {'char_start': 1361, 'char_end': 1364, 'chars': ""'])""}], 'added': [{'char_start': 349, 'char_end': 350, 'chars': 'p'}, {'char_start': 359, 'char_end': 360, 'chars': 'i'}, {'char_start': 362, 'char_end': 364, 'chars': 'co'}, {'char_start': 366, 'char_end': 367, 'chars': 'd'}, {'char_start': 371, 'char_end': 372, 'chars': 'p'}, {'char_start': 376, 'char_end': 377, 'chars': 'o'}, {'char_start': 381, 'char_end': 382, 'chars': 'm'}, {'char_start': 408, 'char_end': 409, 'chars': 'i'}, {'char_start': 416, 'char_end': 417, 'chars': 'w'}, {'char_start': 430, 'char_end': 432, 'chars': 'ck'}, {'char_start': 455, 'char_end': 457, 'chars': '_i'}, {'char_start': 458, 'char_end': 462, 'chars': '_saf'}, {'char_start': 463, 'char_end': 464, 'chars': '_'}, {'char_start': 466, 'char_end': 467, 'chars': 'l'}, {'char_start': 471, 'char_end': 472, 'chars': ','}, {'char_start': 486, 'char_end': 490, 'chars': '_saf'}, {'char_start': 491, 'char_end': 493, 'chars': '_u'}, {'char_start': 494, 'char_end': 496, 'chars': 'l('}, {'char_start': 500, 'char_end': 505, 'chars': 'repla'}, {'char_start': 507, 'char_end': 508, 'chars': '('}, {'char_start': 509, 'char_end': 511, 'chars': '\\\\'}, {'char_start': 515, 'char_end': 520, 'chars': ""/'), ""}, {'char_start': 521, 'char_end': 522, 'chars': 'o'}, {'char_start': 523, 'char_end': 524, 'chars': 't'}]}",github.com/django/django/commit/c5544d289233f501917e25970c03ed444abbd4f0,django/utils/http.py,cwe-079,325 cwe-089,get_mod_taken_together_with,"def get_mod_taken_together_with(code): ''' Retrieves the list of modules taken together with the specified module code in the same semester. Returns a table of lists (up to 10 top results). Each list contains (specified code, module code of mod taken together, aySem, number of students) e.g. [(CS1010, CS1231, AY 16/17 Sem 1, 5)] means there are 5 students taking CS1010 and CS1231 together in AY 16/17 Sem 1. ''' NUM_TOP_RESULTS_TO_RETURN = 10 sql_command = ""SELECT sp1.moduleCode, sp2.moduleCode, sp1.acadYearAndSem, COUNT(*) "" + \ ""FROM studentPlans sp1, studentPlans sp2 "" + \ ""WHERE sp1.moduleCode = '"" + code + ""' AND "" + \ ""sp2.moduleCode <> sp1.moduleCode AND "" + \ ""sp1.studentId = sp2.studentId AND "" + \ ""sp1.acadYearAndSem = sp2.acadYearAndSem "" + \ ""GROUP BY sp1.moduleCode, sp2.moduleCode, sp1.acadYearAndSem "" + \ ""ORDER BY COUNT(*) DESC"" DB_CURSOR.execute(sql_command) return DB_CURSOR.fetchmany(NUM_TOP_RESULTS_TO_RETURN)","def get_mod_taken_together_with(code): ''' Retrieves the list of modules taken together with the specified module code in the same semester. Returns a table of lists (up to 10 top results). Each list contains (specified code, module code of mod taken together, aySem, number of students) e.g. [(CS1010, CS1231, AY 16/17 Sem 1, 5)] means there are 5 students taking CS1010 and CS1231 together in AY 16/17 Sem 1. ''' NUM_TOP_RESULTS_TO_RETURN = 10 sql_command = ""SELECT sp1.moduleCode, sp2.moduleCode, sp1.acadYearAndSem, COUNT(*) "" + \ ""FROM studentPlans sp1, studentPlans sp2 "" + \ ""WHERE sp1.moduleCode = %s AND "" + \ ""sp2.moduleCode <> sp1.moduleCode AND "" + \ ""sp1.studentId = sp2.studentId AND "" + \ ""sp1.acadYearAndSem = sp2.acadYearAndSem "" + \ ""GROUP BY sp1.moduleCode, sp2.moduleCode, sp1.acadYearAndSem "" + \ ""ORDER BY COUNT(*) DESC"" DB_CURSOR.execute(sql_command, (code,)) return DB_CURSOR.fetchmany(NUM_TOP_RESULTS_TO_RETURN)","{'deleted': [{'line_no': 16, 'char_start': 665, 'char_end': 730, 'line': ' ""WHERE sp1.moduleCode = \'"" + code + ""\' AND "" + \\\n'}, {'line_no': 23, 'char_start': 1035, 'char_end': 1070, 'line': ' DB_CURSOR.execute(sql_command)\n'}], 'added': [{'line_no': 16, 'char_start': 665, 'char_end': 718, 'line': ' ""WHERE sp1.moduleCode = %s AND "" + \\\n'}, {'line_no': 23, 'char_start': 1023, 'char_end': 1067, 'line': ' DB_CURSOR.execute(sql_command, (code,))\n'}]}","{'deleted': [{'char_start': 705, 'char_end': 719, 'chars': '\'"" + code + ""\''}], 'added': [{'char_start': 705, 'char_end': 707, 'chars': '%s'}, {'char_start': 1056, 'char_end': 1065, 'chars': ', (code,)'}]}",github.com/nus-mtp/cs-modify/commit/79b4b1dd7eba5445751808e4c50b49d2dd08366b,components/model.py,cwe-089,310 cwe-787,sc_oberthur_read_file,"sc_oberthur_read_file(struct sc_pkcs15_card *p15card, const char *in_path, unsigned char **out, size_t *out_len, int verify_pin) { struct sc_context *ctx = p15card->card->ctx; struct sc_card *card = p15card->card; struct sc_file *file = NULL; struct sc_path path; size_t sz; int rv; LOG_FUNC_CALLED(ctx); if (!in_path || !out || !out_len) LOG_TEST_RET(ctx, SC_ERROR_INVALID_ARGUMENTS, ""Cannot read oberthur file""); sc_log(ctx, ""read file '%s'; verify_pin:%i"", in_path, verify_pin); *out = NULL; *out_len = 0; sc_format_path(in_path, &path); rv = sc_select_file(card, &path, &file); if (rv != SC_SUCCESS) { sc_file_free(file); LOG_TEST_RET(ctx, rv, ""Cannot select oberthur file to read""); } if (file->ef_structure == SC_FILE_EF_TRANSPARENT) sz = file->size; else sz = (file->record_length + 2) * file->record_count; *out = calloc(sz, 1); if (*out == NULL) { sc_file_free(file); LOG_TEST_RET(ctx, SC_ERROR_OUT_OF_MEMORY, ""Cannot read oberthur file""); } if (file->ef_structure == SC_FILE_EF_TRANSPARENT) { rv = sc_read_binary(card, 0, *out, sz, 0); } else { int rec; int offs = 0; int rec_len = file->record_length; for (rec = 1; ; rec++) { rv = sc_read_record(card, rec, *out + offs + 2, rec_len, SC_RECORD_BY_REC_NR); if (rv == SC_ERROR_RECORD_NOT_FOUND) { rv = 0; break; } else if (rv < 0) { break; } rec_len = rv; *(*out + offs) = 'R'; *(*out + offs + 1) = rv; offs += rv + 2; } sz = offs; } sc_log(ctx, ""read oberthur file result %i"", rv); if (verify_pin && rv == SC_ERROR_SECURITY_STATUS_NOT_SATISFIED) { struct sc_pkcs15_object *objs[0x10], *pin_obj = NULL; const struct sc_acl_entry *acl = sc_file_get_acl_entry(file, SC_AC_OP_READ); int ii; rv = sc_pkcs15_get_objects(p15card, SC_PKCS15_TYPE_AUTH_PIN, objs, 0x10); if (rv != SC_SUCCESS) { sc_file_free(file); LOG_TEST_RET(ctx, rv, ""Cannot read oberthur file: get AUTH objects error""); } for (ii=0; iidata; sc_log(ctx, ""compare PIN/ACL refs:%i/%i, method:%i/%i"", auth_info->attrs.pin.reference, acl->key_ref, auth_info->auth_method, acl->method); if (auth_info->attrs.pin.reference == (int)acl->key_ref && auth_info->auth_method == (unsigned)acl->method) { pin_obj = objs[ii]; break; } } if (!pin_obj || !pin_obj->content.value) { rv = SC_ERROR_SECURITY_STATUS_NOT_SATISFIED; } else { rv = sc_pkcs15_verify_pin(p15card, pin_obj, pin_obj->content.value, pin_obj->content.len); if (!rv) rv = sc_oberthur_read_file(p15card, in_path, out, out_len, 0); } }; sc_file_free(file); if (rv < 0) { free(*out); *out = NULL; *out_len = 0; } *out_len = sz; LOG_FUNC_RETURN(ctx, rv); }","sc_oberthur_read_file(struct sc_pkcs15_card *p15card, const char *in_path, unsigned char **out, size_t *out_len, int verify_pin) { struct sc_context *ctx = p15card->card->ctx; struct sc_card *card = p15card->card; struct sc_file *file = NULL; struct sc_path path; size_t sz; int rv; LOG_FUNC_CALLED(ctx); if (!in_path || !out || !out_len) LOG_TEST_RET(ctx, SC_ERROR_INVALID_ARGUMENTS, ""Cannot read oberthur file""); sc_log(ctx, ""read file '%s'; verify_pin:%i"", in_path, verify_pin); *out = NULL; *out_len = 0; sc_format_path(in_path, &path); rv = sc_select_file(card, &path, &file); if (rv != SC_SUCCESS) { sc_file_free(file); LOG_TEST_RET(ctx, rv, ""Cannot select oberthur file to read""); } if (file->ef_structure == SC_FILE_EF_TRANSPARENT) sz = file->size; else sz = (file->record_length + 2) * file->record_count; *out = calloc(sz, 1); if (*out == NULL) { sc_file_free(file); LOG_TEST_RET(ctx, SC_ERROR_OUT_OF_MEMORY, ""Cannot read oberthur file""); } if (file->ef_structure == SC_FILE_EF_TRANSPARENT) { rv = sc_read_binary(card, 0, *out, sz, 0); } else { size_t rec; size_t offs = 0; size_t rec_len = file->record_length; for (rec = 1; ; rec++) { if (rec > file->record_count) { rv = 0; break; } rv = sc_read_record(card, rec, *out + offs + 2, rec_len, SC_RECORD_BY_REC_NR); if (rv == SC_ERROR_RECORD_NOT_FOUND) { rv = 0; break; } else if (rv < 0) { break; } rec_len = rv; *(*out + offs) = 'R'; *(*out + offs + 1) = rv; offs += rv + 2; } sz = offs; } sc_log(ctx, ""read oberthur file result %i"", rv); if (verify_pin && rv == SC_ERROR_SECURITY_STATUS_NOT_SATISFIED) { struct sc_pkcs15_object *objs[0x10], *pin_obj = NULL; const struct sc_acl_entry *acl = sc_file_get_acl_entry(file, SC_AC_OP_READ); int ii; rv = sc_pkcs15_get_objects(p15card, SC_PKCS15_TYPE_AUTH_PIN, objs, 0x10); if (rv != SC_SUCCESS) { sc_file_free(file); LOG_TEST_RET(ctx, rv, ""Cannot read oberthur file: get AUTH objects error""); } for (ii=0; iidata; sc_log(ctx, ""compare PIN/ACL refs:%i/%i, method:%i/%i"", auth_info->attrs.pin.reference, acl->key_ref, auth_info->auth_method, acl->method); if (auth_info->attrs.pin.reference == (int)acl->key_ref && auth_info->auth_method == (unsigned)acl->method) { pin_obj = objs[ii]; break; } } if (!pin_obj || !pin_obj->content.value) { rv = SC_ERROR_SECURITY_STATUS_NOT_SATISFIED; } else { rv = sc_pkcs15_verify_pin(p15card, pin_obj, pin_obj->content.value, pin_obj->content.len); if (!rv) rv = sc_oberthur_read_file(p15card, in_path, out, out_len, 0); } }; sc_file_free(file); if (rv < 0) { free(*out); *out = NULL; *out_len = 0; } *out_len = sz; LOG_FUNC_RETURN(ctx, rv); }","{'deleted': [{'line_no': 43, 'char_start': 1107, 'char_end': 1118, 'line': '\t\tint rec;\n'}, {'line_no': 44, 'char_start': 1118, 'char_end': 1134, 'line': '\t\tint offs = 0;\n'}, {'line_no': 45, 'char_start': 1134, 'char_end': 1171, 'line': '\t\tint rec_len = file->record_length;\n'}], 'added': [{'line_no': 43, 'char_start': 1107, 'char_end': 1121, 'line': '\t\tsize_t rec;\n'}, {'line_no': 44, 'char_start': 1121, 'char_end': 1140, 'line': '\t\tsize_t offs = 0;\n'}, {'line_no': 45, 'char_start': 1140, 'char_end': 1180, 'line': '\t\tsize_t rec_len = file->record_length;\n'}, {'line_no': 48, 'char_start': 1210, 'char_end': 1245, 'line': '\t\t\tif (rec > file->record_count) {\n'}, {'line_no': 49, 'char_start': 1245, 'char_end': 1257, 'line': '\t\t\t\trv = 0;\n'}, {'line_no': 50, 'char_start': 1257, 'char_end': 1268, 'line': '\t\t\t\tbreak;\n'}, {'line_no': 51, 'char_start': 1268, 'char_end': 1273, 'line': '\t\t\t}\n'}]}","{'deleted': [{'char_start': 1110, 'char_end': 1111, 'chars': 'n'}, {'char_start': 1121, 'char_end': 1122, 'chars': 'n'}, {'char_start': 1137, 'char_end': 1138, 'chars': 'n'}], 'added': [{'char_start': 1109, 'char_end': 1110, 'chars': 's'}, {'char_start': 1111, 'char_end': 1114, 'chars': 'ze_'}, {'char_start': 1123, 'char_end': 1124, 'chars': 's'}, {'char_start': 1125, 'char_end': 1128, 'chars': 'ze_'}, {'char_start': 1142, 'char_end': 1143, 'chars': 's'}, {'char_start': 1144, 'char_end': 1147, 'chars': 'ze_'}, {'char_start': 1209, 'char_end': 1272, 'chars': '\n\t\t\tif (rec > file->record_count) {\n\t\t\t\trv = 0;\n\t\t\t\tbreak;\n\t\t\t}'}]}",github.com/OpenSC/OpenSC/commit/6903aebfddc466d966c7b865fae34572bf3ed23e,src/libopensc/pkcs15-oberthur.c,cwe-787,937 cwe-089,add_language," def add_language(self, language): """"""""Add new language for item translations."""""" if self.connection: self.cursor.execute('insert into itemlanguage (language) values (""%s"")' % language[0]) self.connection.commit()"," def add_language(self, language): """"""""Add new language for item translations."""""" if self.connection: t = (language[0], ) self.cursor.execute('insert into itemlanguage (language) values (?)', t) self.connection.commit()","{'deleted': [{'line_no': 4, 'char_start': 121, 'char_end': 220, 'line': ' self.cursor.execute(\'insert into itemlanguage (language) values (""%s"")\' % language[0])\n'}], 'added': [{'line_no': 4, 'char_start': 121, 'char_end': 153, 'line': ' t = (language[0], )\n'}, {'line_no': 5, 'char_start': 153, 'char_end': 238, 'line': "" self.cursor.execute('insert into itemlanguage (language) values (?)', t)\n""}]}","{'deleted': [{'char_start': 198, 'char_end': 202, 'chars': '""%s""'}, {'char_start': 204, 'char_end': 206, 'chars': ' %'}, {'char_start': 207, 'char_end': 218, 'chars': 'language[0]'}], 'added': [{'char_start': 133, 'char_end': 165, 'chars': 't = (language[0], )\n '}, {'char_start': 230, 'char_end': 231, 'chars': '?'}, {'char_start': 233, 'char_end': 234, 'chars': ','}, {'char_start': 235, 'char_end': 236, 'chars': 't'}]}",github.com/ecosl-developers/ecosl/commit/8af050a513338bf68ff2a243e4a2482d24e9aa3a,ecosldb/ecosldb.py,cwe-089,50 cwe-089,_add_to_db," @staticmethod def _add_to_db(user): """""" Adds User object to the database :param user: User object with info about user :return: None """""" query = (""INSERT INTO users (chat_id, first_name, nickname, "" ""last_name, language) "" f""VALUES ({user.chat_id}, '{user.first_name}', "" f""'{user.nickname}', '{user.last_name}', '{user.language}')"") try: db.add(query) except DatabaseError: log.error(""Cannot add user to the database"") else: log.info(f""User {user} was successfully added to the users db"")"," @staticmethod def _add_to_db(user): """""" Adds User object to the database :param user: User object with info about user :return: None """""" query = (""INSERT INTO users (chat_id, first_name, nickname, "" ""last_name, language) "" f""VALUES (%s, %s, %s, %s, %s)"") parameters = (user.chat_id, user.first_name, user.nickname, user.last_name, user.language) try: db.add(query, parameters) except DatabaseError: log.error(""Cannot add user to the database"") else: log.info(f""User {user} was successfully added to the users db"")","{'deleted': [{'line_no': 10, 'char_start': 296, 'char_end': 362, 'line': ' f""VALUES ({user.chat_id}, \'{user.first_name}\', ""\n'}, {'line_no': 11, 'char_start': 362, 'char_end': 441, 'line': ' f""\'{user.nickname}\', \'{user.last_name}\', \'{user.language}\')"")\n'}, {'line_no': 13, 'char_start': 454, 'char_end': 480, 'line': ' db.add(query)\n'}], 'added': [{'line_no': 10, 'char_start': 296, 'char_end': 345, 'line': ' f""VALUES (%s, %s, %s, %s, %s)"")\n'}, {'line_no': 11, 'char_start': 345, 'char_end': 346, 'line': '\n'}, {'line_no': 12, 'char_start': 346, 'char_end': 414, 'line': ' parameters = (user.chat_id, user.first_name, user.nickname,\n'}, {'line_no': 13, 'char_start': 414, 'char_end': 467, 'line': ' user.last_name, user.language)\n'}, {'line_no': 14, 'char_start': 467, 'char_end': 468, 'line': '\n'}, {'line_no': 16, 'char_start': 481, 'char_end': 519, 'line': ' db.add(query, parameters)\n'}]}","{'deleted': [{'char_start': 323, 'char_end': 324, 'chars': '{'}, {'char_start': 336, 'char_end': 337, 'chars': '}'}, {'char_start': 339, 'char_end': 341, 'chars': ""'{""}, {'char_start': 356, 'char_end': 358, 'chars': ""}'""}, {'char_start': 360, 'char_end': 361, 'chars': '""'}, {'char_start': 379, 'char_end': 399, 'chars': 'f""\'{user.nickname}\','}, {'char_start': 400, 'char_end': 402, 'chars': ""'{""}, {'char_start': 416, 'char_end': 418, 'chars': ""}'""}, {'char_start': 420, 'char_end': 422, 'chars': ""'{""}, {'char_start': 435, 'char_end': 437, 'chars': ""}'""}, {'char_start': 438, 'char_end': 440, 'chars': '"")'}], 'added': [{'char_start': 323, 'char_end': 368, 'chars': '%s, %s, %s, %s, %s)"")\n\n parameters = ('}, {'char_start': 399, 'char_end': 413, 'chars': 'user.nickname,'}, {'char_start': 431, 'char_end': 435, 'chars': ' '}, {'char_start': 466, 'char_end': 467, 'chars': '\n'}, {'char_start': 505, 'char_end': 517, 'chars': ', parameters'}]}",github.com/RandyRomero/photoGPSbot/commit/0e9f57f13e61863b3672f5730e27f149da00786a,photogpsbot/users.py,cwe-089,143 cwe-079,PropertiesWidget::loadTorrentInfos,"void PropertiesWidget::loadTorrentInfos(BitTorrent::TorrentHandle *const torrent) { clear(); m_torrent = torrent; downloaded_pieces->setTorrent(m_torrent); pieces_availability->setTorrent(m_torrent); if (!m_torrent) return; // Save path updateSavePath(m_torrent); // Hash hash_lbl->setText(m_torrent->hash()); PropListModel->model()->clear(); if (m_torrent->hasMetadata()) { // Creation date lbl_creationDate->setText(m_torrent->creationDate().toString(Qt::DefaultLocaleShortDate)); label_total_size_val->setText(Utils::Misc::friendlyUnit(m_torrent->totalSize())); // Comment comment_text->setText(Utils::Misc::parseHtmlLinks(m_torrent->comment())); // URL seeds loadUrlSeeds(); label_created_by_val->setText(m_torrent->creator()); // List files in torrent PropListModel->model()->setupModelData(m_torrent->info()); filesList->setExpanded(PropListModel->index(0, 0), true); // Load file priorities PropListModel->model()->updateFilesPriorities(m_torrent->filePriorities()); } // Load dynamic data loadDynamicData(); }","void PropertiesWidget::loadTorrentInfos(BitTorrent::TorrentHandle *const torrent) { clear(); m_torrent = torrent; downloaded_pieces->setTorrent(m_torrent); pieces_availability->setTorrent(m_torrent); if (!m_torrent) return; // Save path updateSavePath(m_torrent); // Hash hash_lbl->setText(m_torrent->hash()); PropListModel->model()->clear(); if (m_torrent->hasMetadata()) { // Creation date lbl_creationDate->setText(m_torrent->creationDate().toString(Qt::DefaultLocaleShortDate)); label_total_size_val->setText(Utils::Misc::friendlyUnit(m_torrent->totalSize())); // Comment comment_text->setText(Utils::Misc::parseHtmlLinks(Utils::String::toHtmlEscaped(m_torrent->comment()))); // URL seeds loadUrlSeeds(); label_created_by_val->setText(Utils::String::toHtmlEscaped(m_torrent->creator())); // List files in torrent PropListModel->model()->setupModelData(m_torrent->info()); filesList->setExpanded(PropListModel->index(0, 0), true); // Load file priorities PropListModel->model()->updateFilesPriorities(m_torrent->filePriorities()); } // Load dynamic data loadDynamicData(); }","{'deleted': [{'line_no': 21, 'char_start': 655, 'char_end': 737, 'line': ' comment_text->setText(Utils::Misc::parseHtmlLinks(m_torrent->comment()));\n'}, {'line_no': 26, 'char_start': 784, 'char_end': 845, 'line': ' label_created_by_val->setText(m_torrent->creator());\n'}], 'added': [{'line_no': 21, 'char_start': 655, 'char_end': 767, 'line': ' comment_text->setText(Utils::Misc::parseHtmlLinks(Utils::String::toHtmlEscaped(m_torrent->comment())));\n'}, {'line_no': 26, 'char_start': 814, 'char_end': 905, 'line': ' label_created_by_val->setText(Utils::String::toHtmlEscaped(m_torrent->creator()));\n'}]}","{'deleted': [], 'added': [{'char_start': 713, 'char_end': 742, 'chars': 'Utils::String::toHtmlEscaped('}, {'char_start': 761, 'char_end': 762, 'chars': ')'}, {'char_start': 852, 'char_end': 881, 'chars': 'Utils::String::toHtmlEscaped('}, {'char_start': 900, 'char_end': 901, 'chars': ')'}]}",github.com/qbittorrent/qBittorrent/commit/6ca3e4f094da0a0017cb2d483ec1db6176bb0b16,src/gui/properties/propertieswidget.cpp,cwe-079,275 cwe-476,validate_as_request,"validate_as_request(kdc_realm_t *kdc_active_realm, register krb5_kdc_req *request, krb5_db_entry client, krb5_db_entry server, krb5_timestamp kdc_time, const char **status, krb5_pa_data ***e_data) { int errcode; krb5_error_code ret; /* * If an option is set that is only allowed in TGS requests, complain. */ if (request->kdc_options & AS_INVALID_OPTIONS) { *status = ""INVALID AS OPTIONS""; return KDC_ERR_BADOPTION; } /* The client must not be expired */ if (client.expiration && client.expiration < kdc_time) { *status = ""CLIENT EXPIRED""; if (vague_errors) return(KRB_ERR_GENERIC); else return(KDC_ERR_NAME_EXP); } /* The client's password must not be expired, unless the server is a KRB5_KDC_PWCHANGE_SERVICE. */ if (client.pw_expiration && client.pw_expiration < kdc_time && !isflagset(server.attributes, KRB5_KDB_PWCHANGE_SERVICE)) { *status = ""CLIENT KEY EXPIRED""; if (vague_errors) return(KRB_ERR_GENERIC); else return(KDC_ERR_KEY_EXP); } /* The server must not be expired */ if (server.expiration && server.expiration < kdc_time) { *status = ""SERVICE EXPIRED""; return(KDC_ERR_SERVICE_EXP); } /* * If the client requires password changing, then only allow the * pwchange service. */ if (isflagset(client.attributes, KRB5_KDB_REQUIRES_PWCHANGE) && !isflagset(server.attributes, KRB5_KDB_PWCHANGE_SERVICE)) { *status = ""REQUIRED PWCHANGE""; return(KDC_ERR_KEY_EXP); } /* Client and server must allow postdating tickets */ if ((isflagset(request->kdc_options, KDC_OPT_ALLOW_POSTDATE) || isflagset(request->kdc_options, KDC_OPT_POSTDATED)) && (isflagset(client.attributes, KRB5_KDB_DISALLOW_POSTDATED) || isflagset(server.attributes, KRB5_KDB_DISALLOW_POSTDATED))) { *status = ""POSTDATE NOT ALLOWED""; return(KDC_ERR_CANNOT_POSTDATE); } /* * A Windows KDC will return KDC_ERR_PREAUTH_REQUIRED instead of * KDC_ERR_POLICY in the following case: * * - KDC_OPT_FORWARDABLE is set in KDCOptions but local * policy has KRB5_KDB_DISALLOW_FORWARDABLE set for the * client, and; * - KRB5_KDB_REQUIRES_PRE_AUTH is set for the client but * preauthentication data is absent in the request. * * Hence, this check most be done after the check for preauth * data, and is now performed by validate_forwardable() (the * contents of which were previously below). */ /* Client and server must allow proxiable tickets */ if (isflagset(request->kdc_options, KDC_OPT_PROXIABLE) && (isflagset(client.attributes, KRB5_KDB_DISALLOW_PROXIABLE) || isflagset(server.attributes, KRB5_KDB_DISALLOW_PROXIABLE))) { *status = ""PROXIABLE NOT ALLOWED""; return(KDC_ERR_POLICY); } /* Check to see if client is locked out */ if (isflagset(client.attributes, KRB5_KDB_DISALLOW_ALL_TIX)) { *status = ""CLIENT LOCKED OUT""; return(KDC_ERR_CLIENT_REVOKED); } /* Check to see if server is locked out */ if (isflagset(server.attributes, KRB5_KDB_DISALLOW_ALL_TIX)) { *status = ""SERVICE LOCKED OUT""; return(KDC_ERR_S_PRINCIPAL_UNKNOWN); } /* Check to see if server is allowed to be a service */ if (isflagset(server.attributes, KRB5_KDB_DISALLOW_SVR)) { *status = ""SERVICE NOT ALLOWED""; return(KDC_ERR_MUST_USE_USER2USER); } if (check_anon(kdc_active_realm, request->client, request->server) != 0) { *status = ""ANONYMOUS NOT ALLOWED""; return(KDC_ERR_POLICY); } /* Perform KDB module policy checks. */ ret = krb5_db_check_policy_as(kdc_context, request, &client, &server, kdc_time, status, e_data); if (ret && ret != KRB5_PLUGIN_OP_NOTSUPP) return errcode_to_protocol(ret); /* Check against local policy. */ errcode = against_local_policy_as(request, client, server, kdc_time, status, e_data); if (errcode) return errcode; return 0; }","validate_as_request(kdc_realm_t *kdc_active_realm, register krb5_kdc_req *request, krb5_db_entry client, krb5_db_entry server, krb5_timestamp kdc_time, const char **status, krb5_pa_data ***e_data) { int errcode; krb5_error_code ret; /* * If an option is set that is only allowed in TGS requests, complain. */ if (request->kdc_options & AS_INVALID_OPTIONS) { *status = ""INVALID AS OPTIONS""; return KDC_ERR_BADOPTION; } /* The client must not be expired */ if (client.expiration && client.expiration < kdc_time) { *status = ""CLIENT EXPIRED""; if (vague_errors) return(KRB_ERR_GENERIC); else return(KDC_ERR_NAME_EXP); } /* The client's password must not be expired, unless the server is a KRB5_KDC_PWCHANGE_SERVICE. */ if (client.pw_expiration && client.pw_expiration < kdc_time && !isflagset(server.attributes, KRB5_KDB_PWCHANGE_SERVICE)) { *status = ""CLIENT KEY EXPIRED""; if (vague_errors) return(KRB_ERR_GENERIC); else return(KDC_ERR_KEY_EXP); } /* The server must not be expired */ if (server.expiration && server.expiration < kdc_time) { *status = ""SERVICE EXPIRED""; return(KDC_ERR_SERVICE_EXP); } /* * If the client requires password changing, then only allow the * pwchange service. */ if (isflagset(client.attributes, KRB5_KDB_REQUIRES_PWCHANGE) && !isflagset(server.attributes, KRB5_KDB_PWCHANGE_SERVICE)) { *status = ""REQUIRED PWCHANGE""; return(KDC_ERR_KEY_EXP); } /* Client and server must allow postdating tickets */ if ((isflagset(request->kdc_options, KDC_OPT_ALLOW_POSTDATE) || isflagset(request->kdc_options, KDC_OPT_POSTDATED)) && (isflagset(client.attributes, KRB5_KDB_DISALLOW_POSTDATED) || isflagset(server.attributes, KRB5_KDB_DISALLOW_POSTDATED))) { *status = ""POSTDATE NOT ALLOWED""; return(KDC_ERR_CANNOT_POSTDATE); } /* * A Windows KDC will return KDC_ERR_PREAUTH_REQUIRED instead of * KDC_ERR_POLICY in the following case: * * - KDC_OPT_FORWARDABLE is set in KDCOptions but local * policy has KRB5_KDB_DISALLOW_FORWARDABLE set for the * client, and; * - KRB5_KDB_REQUIRES_PRE_AUTH is set for the client but * preauthentication data is absent in the request. * * Hence, this check most be done after the check for preauth * data, and is now performed by validate_forwardable() (the * contents of which were previously below). */ /* Client and server must allow proxiable tickets */ if (isflagset(request->kdc_options, KDC_OPT_PROXIABLE) && (isflagset(client.attributes, KRB5_KDB_DISALLOW_PROXIABLE) || isflagset(server.attributes, KRB5_KDB_DISALLOW_PROXIABLE))) { *status = ""PROXIABLE NOT ALLOWED""; return(KDC_ERR_POLICY); } /* Check to see if client is locked out */ if (isflagset(client.attributes, KRB5_KDB_DISALLOW_ALL_TIX)) { *status = ""CLIENT LOCKED OUT""; return(KDC_ERR_CLIENT_REVOKED); } /* Check to see if server is locked out */ if (isflagset(server.attributes, KRB5_KDB_DISALLOW_ALL_TIX)) { *status = ""SERVICE LOCKED OUT""; return(KDC_ERR_S_PRINCIPAL_UNKNOWN); } /* Check to see if server is allowed to be a service */ if (isflagset(server.attributes, KRB5_KDB_DISALLOW_SVR)) { *status = ""SERVICE NOT ALLOWED""; return(KDC_ERR_MUST_USE_USER2USER); } if (check_anon(kdc_active_realm, client.princ, request->server) != 0) { *status = ""ANONYMOUS NOT ALLOWED""; return(KDC_ERR_POLICY); } /* Perform KDB module policy checks. */ ret = krb5_db_check_policy_as(kdc_context, request, &client, &server, kdc_time, status, e_data); if (ret && ret != KRB5_PLUGIN_OP_NOTSUPP) return errcode_to_protocol(ret); /* Check against local policy. */ errcode = against_local_policy_as(request, client, server, kdc_time, status, e_data); if (errcode) return errcode; return 0; }","{'deleted': [{'line_no': 103, 'char_start': 3679, 'char_end': 3758, 'line': ' if (check_anon(kdc_active_realm, request->client, request->server) != 0) {\n'}], 'added': [{'line_no': 103, 'char_start': 3679, 'char_end': 3755, 'line': ' if (check_anon(kdc_active_realm, client.princ, request->server) != 0) {\n'}]}","{'deleted': [{'char_start': 3716, 'char_end': 3725, 'chars': 'request->'}], 'added': [{'char_start': 3722, 'char_end': 3728, 'chars': '.princ'}]}",github.com/krb5/krb5/commit/93b4a6306a0026cf1cc31ac4bd8a49ba5d034ba7,src/kdc/kdc_util.c,cwe-476,1098 cwe-078,test_get_least_used_nsp," def test_get_least_used_nsp(self): self.flags(lock_path=self.tempdir) #record self.clear_mox() _run_ssh = self.mox.CreateMock(hpdriver.hpcommon.HP3PARCommon._run_ssh) self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, ""_run_ssh"", _run_ssh) show_vlun_cmd = 'showvlun -a -showcols Port' _run_ssh(show_vlun_cmd, False).AndReturn([pack(SHOW_VLUN_NONE), '']) _run_ssh(show_vlun_cmd, False).AndReturn([pack(SHOW_VLUN_NONE), '']) _run_ssh(show_vlun_cmd, False).AndReturn([pack(SHOW_VLUN_NONE), '']) self.mox.ReplayAll() # in use count 11 12 nsp = self.driver._get_least_used_nsp(['0:2:1', '1:8:1']) self.assertEqual(nsp, '0:2:1') # in use count 11 10 nsp = self.driver._get_least_used_nsp(['0:2:1', '1:2:1']) self.assertEqual(nsp, '1:2:1') # in use count 0 10 nsp = self.driver._get_least_used_nsp(['1:1:1', '1:2:1']) self.assertEqual(nsp, '1:1:1')"," def test_get_least_used_nsp(self): self.flags(lock_path=self.tempdir) #record self.clear_mox() _run_ssh = self.mox.CreateMock(hpdriver.hpcommon.HP3PARCommon._run_ssh) self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, ""_run_ssh"", _run_ssh) show_vlun_cmd = ['showvlun', '-a', '-showcols', 'Port'] _run_ssh(show_vlun_cmd, False).AndReturn([pack(SHOW_VLUN_NONE), '']) _run_ssh(show_vlun_cmd, False).AndReturn([pack(SHOW_VLUN_NONE), '']) _run_ssh(show_vlun_cmd, False).AndReturn([pack(SHOW_VLUN_NONE), '']) self.mox.ReplayAll() # in use count 11 12 nsp = self.driver._get_least_used_nsp(['0:2:1', '1:8:1']) self.assertEqual(nsp, '0:2:1') # in use count 11 10 nsp = self.driver._get_least_used_nsp(['0:2:1', '1:2:1']) self.assertEqual(nsp, '1:2:1') # in use count 0 10 nsp = self.driver._get_least_used_nsp(['1:1:1', '1:2:1']) self.assertEqual(nsp, '1:1:1')","{'deleted': [{'line_no': 9, 'char_start': 282, 'char_end': 335, 'line': "" show_vlun_cmd = 'showvlun -a -showcols Port'\n""}], 'added': [{'line_no': 9, 'char_start': 282, 'char_end': 346, 'line': "" show_vlun_cmd = ['showvlun', '-a', '-showcols', 'Port']\n""}]}","{'deleted': [], 'added': [{'char_start': 306, 'char_end': 307, 'chars': '['}, {'char_start': 316, 'char_end': 318, 'chars': ""',""}, {'char_start': 319, 'char_end': 320, 'chars': ""'""}, {'char_start': 322, 'char_end': 324, 'chars': ""',""}, {'char_start': 325, 'char_end': 326, 'chars': ""'""}, {'char_start': 335, 'char_end': 337, 'chars': ""',""}, {'char_start': 338, 'char_end': 339, 'chars': ""'""}, {'char_start': 344, 'char_end': 345, 'chars': ']'}]}",github.com/thatsdone/cinder/commit/c55589b131828f3a595903f6796cb2d0babb772f,cinder/tests/test_hp3par.py,cwe-078,336 cwe-190,amqp_handle_input,"int amqp_handle_input(amqp_connection_state_t state, amqp_bytes_t received_data, amqp_frame_t *decoded_frame) { size_t bytes_consumed; void *raw_frame; /* Returning frame_type of zero indicates either insufficient input, or a complete, ignored frame was read. */ decoded_frame->frame_type = 0; if (received_data.len == 0) { return AMQP_STATUS_OK; } if (state->state == CONNECTION_STATE_IDLE) { state->state = CONNECTION_STATE_HEADER; } bytes_consumed = consume_data(state, &received_data); /* do we have target_size data yet? if not, return with the expectation that more will arrive */ if (state->inbound_offset < state->target_size) { return (int)bytes_consumed; } raw_frame = state->inbound_buffer.bytes; switch (state->state) { case CONNECTION_STATE_INITIAL: /* check for a protocol header from the server */ if (memcmp(raw_frame, ""AMQP"", 4) == 0) { decoded_frame->frame_type = AMQP_PSEUDOFRAME_PROTOCOL_HEADER; decoded_frame->channel = 0; decoded_frame->payload.protocol_header.transport_high = amqp_d8(amqp_offset(raw_frame, 4)); decoded_frame->payload.protocol_header.transport_low = amqp_d8(amqp_offset(raw_frame, 5)); decoded_frame->payload.protocol_header.protocol_version_major = amqp_d8(amqp_offset(raw_frame, 6)); decoded_frame->payload.protocol_header.protocol_version_minor = amqp_d8(amqp_offset(raw_frame, 7)); return_to_idle(state); return (int)bytes_consumed; } /* it's not a protocol header; fall through to process it as a regular frame header */ case CONNECTION_STATE_HEADER: { amqp_channel_t channel; amqp_pool_t *channel_pool; /* frame length is 3 bytes in */ channel = amqp_d16(amqp_offset(raw_frame, 1)); state->target_size = amqp_d32(amqp_offset(raw_frame, 3)) + HEADER_SIZE + FOOTER_SIZE; if ((size_t)state->frame_max < state->target_size) { return AMQP_STATUS_BAD_AMQP_DATA; } channel_pool = amqp_get_or_create_channel_pool(state, channel); if (NULL == channel_pool) { return AMQP_STATUS_NO_MEMORY; } amqp_pool_alloc_bytes(channel_pool, state->target_size, &state->inbound_buffer); if (NULL == state->inbound_buffer.bytes) { return AMQP_STATUS_NO_MEMORY; } memcpy(state->inbound_buffer.bytes, state->header_buffer, HEADER_SIZE); raw_frame = state->inbound_buffer.bytes; state->state = CONNECTION_STATE_BODY; bytes_consumed += consume_data(state, &received_data); /* do we have target_size data yet? if not, return with the expectation that more will arrive */ if (state->inbound_offset < state->target_size) { return (int)bytes_consumed; } } /* fall through to process body */ case CONNECTION_STATE_BODY: { amqp_bytes_t encoded; int res; amqp_pool_t *channel_pool; /* Check frame end marker (footer) */ if (amqp_d8(amqp_offset(raw_frame, state->target_size - 1)) != AMQP_FRAME_END) { return AMQP_STATUS_BAD_AMQP_DATA; } decoded_frame->frame_type = amqp_d8(amqp_offset(raw_frame, 0)); decoded_frame->channel = amqp_d16(amqp_offset(raw_frame, 1)); channel_pool = amqp_get_or_create_channel_pool(state, decoded_frame->channel); if (NULL == channel_pool) { return AMQP_STATUS_NO_MEMORY; } switch (decoded_frame->frame_type) { case AMQP_FRAME_METHOD: decoded_frame->payload.method.id = amqp_d32(amqp_offset(raw_frame, HEADER_SIZE)); encoded.bytes = amqp_offset(raw_frame, HEADER_SIZE + 4); encoded.len = state->target_size - HEADER_SIZE - 4 - FOOTER_SIZE; res = amqp_decode_method(decoded_frame->payload.method.id, channel_pool, encoded, &decoded_frame->payload.method.decoded); if (res < 0) { return res; } break; case AMQP_FRAME_HEADER: decoded_frame->payload.properties.class_id = amqp_d16(amqp_offset(raw_frame, HEADER_SIZE)); /* unused 2-byte weight field goes here */ decoded_frame->payload.properties.body_size = amqp_d64(amqp_offset(raw_frame, HEADER_SIZE + 4)); encoded.bytes = amqp_offset(raw_frame, HEADER_SIZE + 12); encoded.len = state->target_size - HEADER_SIZE - 12 - FOOTER_SIZE; decoded_frame->payload.properties.raw = encoded; res = amqp_decode_properties( decoded_frame->payload.properties.class_id, channel_pool, encoded, &decoded_frame->payload.properties.decoded); if (res < 0) { return res; } break; case AMQP_FRAME_BODY: decoded_frame->payload.body_fragment.len = state->target_size - HEADER_SIZE - FOOTER_SIZE; decoded_frame->payload.body_fragment.bytes = amqp_offset(raw_frame, HEADER_SIZE); break; case AMQP_FRAME_HEARTBEAT: break; default: /* Ignore the frame */ decoded_frame->frame_type = 0; break; } return_to_idle(state); return (int)bytes_consumed; } default: amqp_abort(""Internal error: invalid amqp_connection_state_t->state %d"", state->state); } }","int amqp_handle_input(amqp_connection_state_t state, amqp_bytes_t received_data, amqp_frame_t *decoded_frame) { size_t bytes_consumed; void *raw_frame; /* Returning frame_type of zero indicates either insufficient input, or a complete, ignored frame was read. */ decoded_frame->frame_type = 0; if (received_data.len == 0) { return AMQP_STATUS_OK; } if (state->state == CONNECTION_STATE_IDLE) { state->state = CONNECTION_STATE_HEADER; } bytes_consumed = consume_data(state, &received_data); /* do we have target_size data yet? if not, return with the expectation that more will arrive */ if (state->inbound_offset < state->target_size) { return (int)bytes_consumed; } raw_frame = state->inbound_buffer.bytes; switch (state->state) { case CONNECTION_STATE_INITIAL: /* check for a protocol header from the server */ if (memcmp(raw_frame, ""AMQP"", 4) == 0) { decoded_frame->frame_type = AMQP_PSEUDOFRAME_PROTOCOL_HEADER; decoded_frame->channel = 0; decoded_frame->payload.protocol_header.transport_high = amqp_d8(amqp_offset(raw_frame, 4)); decoded_frame->payload.protocol_header.transport_low = amqp_d8(amqp_offset(raw_frame, 5)); decoded_frame->payload.protocol_header.protocol_version_major = amqp_d8(amqp_offset(raw_frame, 6)); decoded_frame->payload.protocol_header.protocol_version_minor = amqp_d8(amqp_offset(raw_frame, 7)); return_to_idle(state); return (int)bytes_consumed; } /* it's not a protocol header; fall through to process it as a regular frame header */ case CONNECTION_STATE_HEADER: { amqp_channel_t channel; amqp_pool_t *channel_pool; uint32_t frame_size; channel = amqp_d16(amqp_offset(raw_frame, 1)); /* frame length is 3 bytes in */ frame_size = amqp_d32(amqp_offset(raw_frame, 3)); /* To prevent the target_size calculation below from overflowing, check * that the stated frame_size is smaller than a signed 32-bit. Given * the library only allows configuring frame_max as an int32_t, and * frame_size is uint32_t, the math below is safe from overflow. */ if (frame_size >= INT32_MAX) { return AMQP_STATUS_BAD_AMQP_DATA; } state->target_size = frame_size + HEADER_SIZE + FOOTER_SIZE; if ((size_t)state->frame_max < state->target_size) { return AMQP_STATUS_BAD_AMQP_DATA; } channel_pool = amqp_get_or_create_channel_pool(state, channel); if (NULL == channel_pool) { return AMQP_STATUS_NO_MEMORY; } amqp_pool_alloc_bytes(channel_pool, state->target_size, &state->inbound_buffer); if (NULL == state->inbound_buffer.bytes) { return AMQP_STATUS_NO_MEMORY; } memcpy(state->inbound_buffer.bytes, state->header_buffer, HEADER_SIZE); raw_frame = state->inbound_buffer.bytes; state->state = CONNECTION_STATE_BODY; bytes_consumed += consume_data(state, &received_data); /* do we have target_size data yet? if not, return with the expectation that more will arrive */ if (state->inbound_offset < state->target_size) { return (int)bytes_consumed; } } /* fall through to process body */ case CONNECTION_STATE_BODY: { amqp_bytes_t encoded; int res; amqp_pool_t *channel_pool; /* Check frame end marker (footer) */ if (amqp_d8(amqp_offset(raw_frame, state->target_size - 1)) != AMQP_FRAME_END) { return AMQP_STATUS_BAD_AMQP_DATA; } decoded_frame->frame_type = amqp_d8(amqp_offset(raw_frame, 0)); decoded_frame->channel = amqp_d16(amqp_offset(raw_frame, 1)); channel_pool = amqp_get_or_create_channel_pool(state, decoded_frame->channel); if (NULL == channel_pool) { return AMQP_STATUS_NO_MEMORY; } switch (decoded_frame->frame_type) { case AMQP_FRAME_METHOD: decoded_frame->payload.method.id = amqp_d32(amqp_offset(raw_frame, HEADER_SIZE)); encoded.bytes = amqp_offset(raw_frame, HEADER_SIZE + 4); encoded.len = state->target_size - HEADER_SIZE - 4 - FOOTER_SIZE; res = amqp_decode_method(decoded_frame->payload.method.id, channel_pool, encoded, &decoded_frame->payload.method.decoded); if (res < 0) { return res; } break; case AMQP_FRAME_HEADER: decoded_frame->payload.properties.class_id = amqp_d16(amqp_offset(raw_frame, HEADER_SIZE)); /* unused 2-byte weight field goes here */ decoded_frame->payload.properties.body_size = amqp_d64(amqp_offset(raw_frame, HEADER_SIZE + 4)); encoded.bytes = amqp_offset(raw_frame, HEADER_SIZE + 12); encoded.len = state->target_size - HEADER_SIZE - 12 - FOOTER_SIZE; decoded_frame->payload.properties.raw = encoded; res = amqp_decode_properties( decoded_frame->payload.properties.class_id, channel_pool, encoded, &decoded_frame->payload.properties.decoded); if (res < 0) { return res; } break; case AMQP_FRAME_BODY: decoded_frame->payload.body_fragment.len = state->target_size - HEADER_SIZE - FOOTER_SIZE; decoded_frame->payload.body_fragment.bytes = amqp_offset(raw_frame, HEADER_SIZE); break; case AMQP_FRAME_HEARTBEAT: break; default: /* Ignore the frame */ decoded_frame->frame_type = 0; break; } return_to_idle(state); return (int)bytes_consumed; } default: amqp_abort(""Internal error: invalid amqp_connection_state_t->state %d"", state->state); } }","{'deleted': [{'line_no': 54, 'char_start': 1794, 'char_end': 1833, 'line': ' /* frame length is 3 bytes in */\n'}, {'line_no': 57, 'char_start': 1887, 'char_end': 1914, 'line': ' state->target_size =\n'}, {'line_no': 58, 'char_start': 1914, 'char_end': 1989, 'line': ' amqp_d32(amqp_offset(raw_frame, 3)) + HEADER_SIZE + FOOTER_SIZE;\n'}], 'added': [{'line_no': 54, 'char_start': 1794, 'char_end': 1821, 'line': ' uint32_t frame_size;\n'}, {'line_no': 55, 'char_start': 1821, 'char_end': 1822, 'line': '\n'}, {'line_no': 58, 'char_start': 1876, 'char_end': 1915, 'line': ' /* frame length is 3 bytes in */\n'}, {'line_no': 59, 'char_start': 1915, 'char_end': 1971, 'line': ' frame_size = amqp_d32(amqp_offset(raw_frame, 3));\n'}, {'line_no': 60, 'char_start': 1971, 'char_end': 2049, 'line': ' /* To prevent the target_size calculation below from overflowing, check\n'}, {'line_no': 61, 'char_start': 2049, 'char_end': 2124, 'line': ' * that the stated frame_size is smaller than a signed 32-bit. Given\n'}, {'line_no': 62, 'char_start': 2124, 'char_end': 2198, 'line': ' * the library only allows configuring frame_max as an int32_t, and\n'}, {'line_no': 63, 'char_start': 2198, 'char_end': 2272, 'line': ' * frame_size is uint32_t, the math below is safe from overflow. */\n'}, {'line_no': 64, 'char_start': 2272, 'char_end': 2309, 'line': ' if (frame_size >= INT32_MAX) {\n'}, {'line_no': 65, 'char_start': 2309, 'char_end': 2351, 'line': ' return AMQP_STATUS_BAD_AMQP_DATA;\n'}, {'line_no': 66, 'char_start': 2351, 'char_end': 2359, 'line': ' }\n'}, {'line_no': 68, 'char_start': 2360, 'char_end': 2427, 'line': ' state->target_size = frame_size + HEADER_SIZE + FOOTER_SIZE;\n'}]}","{'deleted': [{'char_start': 1800, 'char_end': 1802, 'chars': '/*'}, {'char_start': 1808, 'char_end': 1816, 'chars': ' length '}, {'char_start': 1817, 'char_end': 1824, 'chars': 's 3 byt'}, {'char_start': 1825, 'char_end': 1832, 'chars': 's in */'}, {'char_start': 1893, 'char_end': 1895, 'chars': 'st'}, {'char_start': 1896, 'char_end': 1897, 'chars': 't'}, {'char_start': 1898, 'char_end': 1904, 'chars': '->targ'}, {'char_start': 1906, 'char_end': 1907, 'chars': '_'}, {'char_start': 1908, 'char_end': 1911, 'chars': 'ize'}, {'char_start': 1912, 'char_end': 1914, 'chars': '=\n'}, {'char_start': 1988, 'char_end': 1989, 'chars': '\n'}], 'added': [{'char_start': 1800, 'char_end': 1808, 'chars': 'uint32_t'}, {'char_start': 1814, 'char_end': 1815, 'chars': '_'}, {'char_start': 1816, 'char_end': 1818, 'chars': 'iz'}, {'char_start': 1819, 'char_end': 1821, 'chars': ';\n'}, {'char_start': 1882, 'char_end': 1899, 'chars': '/* frame length i'}, {'char_start': 1900, 'char_end': 1905, 'chars': ' 3 by'}, {'char_start': 1906, 'char_end': 1923, 'chars': 'es in */\n fr'}, {'char_start': 1924, 'char_end': 1953, 'chars': 'me_size = amqp_d32(amqp_offse'}, {'char_start': 1954, 'char_end': 1963, 'chars': '(raw_fram'}, {'char_start': 1964, 'char_end': 1995, 'chars': ', 3));\n /* To prevent the '}, {'char_start': 2007, 'char_end': 2048, 'chars': 'calculation below from overflowing, check'}, {'char_start': 2056, 'char_end': 2057, 'chars': '*'}, {'char_start': 2058, 'char_end': 2062, 'chars': 'that'}, {'char_start': 2063, 'char_end': 2066, 'chars': 'the'}, {'char_start': 2067, 'char_end': 2076, 'chars': 'stated fr'}, {'char_start': 2078, 'char_end': 2079, 'chars': 'e'}, {'char_start': 2080, 'char_end': 2108, 'chars': 'size is smaller than a signe'}, {'char_start': 2109, 'char_end': 2110, 'chars': ' '}, {'char_start': 2112, 'char_end': 2209, 'chars': '-bit. Given\n * the library only allows configuring frame_max as an int32_t, and\n * fr'}, {'char_start': 2211, 'char_end': 2227, 'chars': 'e_size is uint32'}, {'char_start': 2228, 'char_end': 2243, 'chars': 't, the math bel'}, {'char_start': 2244, 'char_end': 2251, 'chars': 'w is sa'}, {'char_start': 2252, 'char_end': 2254, 'chars': 'e '}, {'char_start': 2255, 'char_end': 2288, 'chars': 'rom overflow. */\n if (frame_'}, {'char_start': 2289, 'char_end': 2318, 'chars': 'ize >= INT32_MAX) {\n r'}, {'char_start': 2320, 'char_end': 2321, 'chars': 'u'}, {'char_start': 2322, 'char_end': 2368, 'chars': 'n AMQP_STATUS_BAD_AMQP_DATA;\n }\n\n st'}, {'char_start': 2369, 'char_end': 2379, 'chars': 'te->target'}, {'char_start': 2380, 'char_end': 2387, 'chars': 'size = '}, {'char_start': 2392, 'char_end': 2397, 'chars': '_size'}]}",github.com/alanxz/rabbitmq-c/commit/fc85be7123050b91b054e45b91c78d3241a5047a,librabbitmq/amqp_connection.c,cwe-190,1275 cwe-089,get_item,"@api.route('/items/', methods=['GET']) def get_item(item_id): sql = '''SELECT id, name_enus FROM tblDBCItem WHERE id = {} AND auctionable = true;'''.format(item_id) cursor = mysql.connection.cursor() cursor.execute(sql) data = cursor.fetchone() if data: item = {} for tup in zip([column[0] for column in cursor.description], data): item[tup[0]] = tup[1] else: return jsonify({""error"": ""item not found""}), 404 return jsonify(item)","@api.route('/items/', methods=['GET']) def get_item(item_id): sql = '''SELECT id, name_enus FROM tblDBCItem WHERE id = %s AND auctionable = true;''' cursor = mysql.connection.cursor() cursor.execute(sql, [item_id]) data = cursor.fetchone() if data: item = {} for tup in zip([column[0] for column in cursor.description], data): item[tup[0]] = tup[1] else: return jsonify({""error"": ""item not found""}), 404 return jsonify(item)","{'deleted': [{'line_no': 3, 'char_start': 75, 'char_end': 182, 'line': "" sql = '''SELECT id, name_enus FROM tblDBCItem WHERE id = {} AND auctionable = true;'''.format(item_id)\n""}, {'line_no': 5, 'char_start': 221, 'char_end': 245, 'line': ' cursor.execute(sql)\n'}], 'added': [{'line_no': 3, 'char_start': 75, 'char_end': 166, 'line': "" sql = '''SELECT id, name_enus FROM tblDBCItem WHERE id = %s AND auctionable = true;'''\n""}, {'line_no': 5, 'char_start': 205, 'char_end': 240, 'line': ' cursor.execute(sql, [item_id])\n'}]}","{'deleted': [{'char_start': 136, 'char_end': 138, 'chars': '{}'}, {'char_start': 165, 'char_end': 181, 'chars': '.format(item_id)'}], 'added': [{'char_start': 136, 'char_end': 138, 'chars': '%s'}, {'char_start': 227, 'char_end': 238, 'chars': ', [item_id]'}]}",github.com/cosileone/TimeIsMoneyFriend-API/commit/3d3b5defd26ef7d205915bf643b6b1df90a15e44,timf/api/views.py,cwe-089,130 cwe-476,AP4_HdlrAtom::AP4_HdlrAtom,"AP4_HdlrAtom::AP4_HdlrAtom(AP4_UI32 size, AP4_UI08 version, AP4_UI32 flags, AP4_ByteStream& stream) : AP4_Atom(AP4_ATOM_TYPE_HDLR, size, version, flags) { AP4_UI32 predefined; stream.ReadUI32(predefined); stream.ReadUI32(m_HandlerType); stream.ReadUI32(m_Reserved[0]); stream.ReadUI32(m_Reserved[1]); stream.ReadUI32(m_Reserved[2]); // read the name unless it is empty int name_size = size-(AP4_FULL_ATOM_HEADER_SIZE+20); if (name_size == 0) return; char* name = new char[name_size+1]; stream.Read(name, name_size); name[name_size] = '\0'; // force a null termination // handle a special case: the Quicktime files have a pascal // string here, but ISO MP4 files have a C string. // we try to detect a pascal encoding and correct it. if (name[0] == name_size-1) { m_HandlerName = name+1; } else { m_HandlerName = name; } delete[] name; }","AP4_HdlrAtom::AP4_HdlrAtom(AP4_UI32 size, AP4_UI08 version, AP4_UI32 flags, AP4_ByteStream& stream) : AP4_Atom(AP4_ATOM_TYPE_HDLR, size, version, flags) { AP4_UI32 predefined; stream.ReadUI32(predefined); stream.ReadUI32(m_HandlerType); stream.ReadUI32(m_Reserved[0]); stream.ReadUI32(m_Reserved[1]); stream.ReadUI32(m_Reserved[2]); // read the name unless it is empty if (size < AP4_FULL_ATOM_HEADER_SIZE+20) return; AP4_UI32 name_size = size-(AP4_FULL_ATOM_HEADER_SIZE+20); char* name = new char[name_size+1]; if (name == NULL) return; stream.Read(name, name_size); name[name_size] = '\0'; // force a null termination // handle a special case: the Quicktime files have a pascal // string here, but ISO MP4 files have a C string. // we try to detect a pascal encoding and correct it. if (name[0] == name_size-1) { m_HandlerName = name+1; } else { m_HandlerName = name; } delete[] name; }","{'deleted': [{'line_no': 15, 'char_start': 509, 'char_end': 566, 'line': ' int name_size = size-(AP4_FULL_ATOM_HEADER_SIZE+20);\n'}, {'line_no': 16, 'char_start': 566, 'char_end': 598, 'line': ' if (name_size == 0) return;\n'}], 'added': [{'line_no': 15, 'char_start': 509, 'char_end': 562, 'line': ' if (size < AP4_FULL_ATOM_HEADER_SIZE+20) return;\n'}, {'line_no': 16, 'char_start': 562, 'char_end': 624, 'line': ' AP4_UI32 name_size = size-(AP4_FULL_ATOM_HEADER_SIZE+20);\n'}, {'line_no': 18, 'char_start': 664, 'char_end': 694, 'line': ' if (name == NULL) return;\n'}]}","{'deleted': [{'char_start': 514, 'char_end': 516, 'chars': 'nt'}, {'char_start': 517, 'char_end': 522, 'chars': 'name_'}, {'char_start': 527, 'char_end': 528, 'chars': '='}, {'char_start': 529, 'char_end': 535, 'chars': 'size-('}, {'char_start': 570, 'char_end': 572, 'chars': 'if'}, {'char_start': 573, 'char_end': 574, 'chars': '('}, {'char_start': 585, 'char_end': 586, 'chars': '='}, {'char_start': 589, 'char_end': 596, 'chars': ' return'}], 'added': [{'char_start': 514, 'char_end': 515, 'chars': 'f'}, {'char_start': 516, 'char_end': 517, 'chars': '('}, {'char_start': 522, 'char_end': 523, 'chars': '<'}, {'char_start': 553, 'char_end': 560, 'chars': ' return'}, {'char_start': 566, 'char_end': 574, 'chars': 'AP4_UI32'}, {'char_start': 587, 'char_end': 620, 'chars': 'size-(AP4_FULL_ATOM_HEADER_SIZE+2'}, {'char_start': 662, 'char_end': 692, 'chars': ';\n if (name == NULL) return'}]}",github.com/axiomatic-systems/Bento4/commit/22192de5367fa0cee985917f092be4060b7c00b0,Source/C++/Core/Ap4HdlrAtom.cpp,cwe-476,294 cwe-476,lexer_process_char_literal,"lexer_process_char_literal (parser_context_t *context_p, /**< context */ const uint8_t *char_p, /**< characters */ size_t length, /**< length of string */ uint8_t literal_type, /**< final literal type */ bool has_escape) /**< has escape sequences */ { parser_list_iterator_t literal_iterator; lexer_literal_t *literal_p; uint32_t literal_index = 0; JERRY_ASSERT (literal_type == LEXER_IDENT_LITERAL || literal_type == LEXER_STRING_LITERAL); JERRY_ASSERT (literal_type != LEXER_IDENT_LITERAL || length <= PARSER_MAXIMUM_IDENT_LENGTH); JERRY_ASSERT (literal_type != LEXER_STRING_LITERAL || length <= PARSER_MAXIMUM_STRING_LENGTH); parser_list_iterator_init (&context_p->literal_pool, &literal_iterator); while ((literal_p = (lexer_literal_t *) parser_list_iterator_next (&literal_iterator)) != NULL) { if (literal_p->type == literal_type && literal_p->prop.length == length && memcmp (literal_p->u.char_p, char_p, length) == 0) { context_p->lit_object.literal_p = literal_p; context_p->lit_object.index = (uint16_t) literal_index; literal_p->status_flags = (uint8_t) (literal_p->status_flags & ~LEXER_FLAG_UNUSED_IDENT); return; } literal_index++; } JERRY_ASSERT (literal_index == context_p->literal_count); if (literal_index >= PARSER_MAXIMUM_NUMBER_OF_LITERALS) { parser_raise_error (context_p, PARSER_ERR_LITERAL_LIMIT_REACHED); } literal_p = (lexer_literal_t *) parser_list_append (context_p, &context_p->literal_pool); literal_p->prop.length = (uint16_t) length; literal_p->type = literal_type; literal_p->status_flags = has_escape ? 0 : LEXER_FLAG_SOURCE_PTR; if (has_escape) { literal_p->u.char_p = (uint8_t *) jmem_heap_alloc_block (length); memcpy ((uint8_t *) literal_p->u.char_p, char_p, length); } else { literal_p->u.char_p = char_p; } context_p->lit_object.literal_p = literal_p; context_p->lit_object.index = (uint16_t) literal_index; context_p->literal_count++; } /* lexer_process_char_literal */","lexer_process_char_literal (parser_context_t *context_p, /**< context */ const uint8_t *char_p, /**< characters */ size_t length, /**< length of string */ uint8_t literal_type, /**< final literal type */ bool has_escape) /**< has escape sequences */ { parser_list_iterator_t literal_iterator; lexer_literal_t *literal_p; uint32_t literal_index = 0; JERRY_ASSERT (literal_type == LEXER_IDENT_LITERAL || literal_type == LEXER_STRING_LITERAL); JERRY_ASSERT (literal_type != LEXER_IDENT_LITERAL || length <= PARSER_MAXIMUM_IDENT_LENGTH); JERRY_ASSERT (literal_type != LEXER_STRING_LITERAL || length <= PARSER_MAXIMUM_STRING_LENGTH); parser_list_iterator_init (&context_p->literal_pool, &literal_iterator); while ((literal_p = (lexer_literal_t *) parser_list_iterator_next (&literal_iterator)) != NULL) { if (literal_p->type == literal_type && literal_p->prop.length == length && memcmp (literal_p->u.char_p, char_p, length) == 0) { context_p->lit_object.literal_p = literal_p; context_p->lit_object.index = (uint16_t) literal_index; literal_p->status_flags = (uint8_t) (literal_p->status_flags & ~LEXER_FLAG_UNUSED_IDENT); return; } literal_index++; } JERRY_ASSERT (literal_index == context_p->literal_count); if (literal_index >= PARSER_MAXIMUM_NUMBER_OF_LITERALS) { parser_raise_error (context_p, PARSER_ERR_LITERAL_LIMIT_REACHED); } if (length == 0) { has_escape = false; } literal_p = (lexer_literal_t *) parser_list_append (context_p, &context_p->literal_pool); literal_p->prop.length = (uint16_t) length; literal_p->type = literal_type; literal_p->status_flags = has_escape ? 0 : LEXER_FLAG_SOURCE_PTR; if (has_escape) { literal_p->u.char_p = (uint8_t *) jmem_heap_alloc_block (length); memcpy ((uint8_t *) literal_p->u.char_p, char_p, length); } else { literal_p->u.char_p = char_p; } context_p->lit_object.literal_p = literal_p; context_p->lit_object.index = (uint16_t) literal_index; context_p->literal_count++; } /* lexer_process_char_literal */","{'deleted': [], 'added': [{'line_no': 41, 'char_start': 1556, 'char_end': 1575, 'line': ' if (length == 0)\n'}, {'line_no': 42, 'char_start': 1575, 'char_end': 1579, 'line': ' {\n'}, {'line_no': 43, 'char_start': 1579, 'char_end': 1603, 'line': ' has_escape = false;\n'}, {'line_no': 44, 'char_start': 1603, 'char_end': 1607, 'line': ' }\n'}, {'line_no': 45, 'char_start': 1607, 'char_end': 1608, 'line': '\n'}]}","{'deleted': [], 'added': [{'char_start': 1558, 'char_end': 1610, 'chars': 'if (length == 0)\n {\n has_escape = false;\n }\n\n '}]}",github.com/zherczeg/jerryscript/commit/03a8c630f015f63268639d3ed3bf82cff6fa77d8,jerry-core/parser/js/js-lexer.c,cwe-476,532 cwe-125,autodetect_recv_bandwidth_measure_results,"static BOOL autodetect_recv_bandwidth_measure_results(rdpRdp* rdp, wStream* s, AUTODETECT_RSP_PDU* autodetectRspPdu) { BOOL success = TRUE; if (autodetectRspPdu->headerLength != 0x0E) return FALSE; WLog_VRB(AUTODETECT_TAG, ""received Bandwidth Measure Results PDU""); Stream_Read_UINT32(s, rdp->autodetect->bandwidthMeasureTimeDelta); /* timeDelta (4 bytes) */ Stream_Read_UINT32(s, rdp->autodetect->bandwidthMeasureByteCount); /* byteCount (4 bytes) */ if (rdp->autodetect->bandwidthMeasureTimeDelta > 0) rdp->autodetect->netCharBandwidth = rdp->autodetect->bandwidthMeasureByteCount * 8 / rdp->autodetect->bandwidthMeasureTimeDelta; else rdp->autodetect->netCharBandwidth = 0; IFCALLRET(rdp->autodetect->BandwidthMeasureResults, success, rdp->context, autodetectRspPdu->sequenceNumber); return success; }","static BOOL autodetect_recv_bandwidth_measure_results(rdpRdp* rdp, wStream* s, AUTODETECT_RSP_PDU* autodetectRspPdu) { BOOL success = TRUE; if (autodetectRspPdu->headerLength != 0x0E) return FALSE; WLog_VRB(AUTODETECT_TAG, ""received Bandwidth Measure Results PDU""); if (Stream_GetRemainingLength(s) < 8) return -1; Stream_Read_UINT32(s, rdp->autodetect->bandwidthMeasureTimeDelta); /* timeDelta (4 bytes) */ Stream_Read_UINT32(s, rdp->autodetect->bandwidthMeasureByteCount); /* byteCount (4 bytes) */ if (rdp->autodetect->bandwidthMeasureTimeDelta > 0) rdp->autodetect->netCharBandwidth = rdp->autodetect->bandwidthMeasureByteCount * 8 / rdp->autodetect->bandwidthMeasureTimeDelta; else rdp->autodetect->netCharBandwidth = 0; IFCALLRET(rdp->autodetect->BandwidthMeasureResults, success, rdp->context, autodetectRspPdu->sequenceNumber); return success; }","{'deleted': [], 'added': [{'line_no': 10, 'char_start': 327, 'char_end': 366, 'line': '\tif (Stream_GetRemainingLength(s) < 8)\n'}, {'line_no': 11, 'char_start': 366, 'char_end': 379, 'line': '\t\treturn -1;\n'}]}","{'deleted': [], 'added': [{'char_start': 328, 'char_end': 380, 'chars': 'if (Stream_GetRemainingLength(s) < 8)\n\t\treturn -1;\n\t'}]}",github.com/FreeRDP/FreeRDP/commit/f5e73cc7c9cd973b516a618da877c87b80950b65,libfreerdp/core/autodetect.c,cwe-125,264 cwe-787,rfbHandleAuthResult,"rfbHandleAuthResult(rfbClient* client) { uint32_t authResult=0, reasonLen=0; char *reason=NULL; if (!ReadFromRFBServer(client, (char *)&authResult, 4)) return FALSE; authResult = rfbClientSwap32IfLE(authResult); switch (authResult) { case rfbVncAuthOK: rfbClientLog(""VNC authentication succeeded\n""); return TRUE; break; case rfbVncAuthFailed: if (client->major==3 && client->minor>7) { /* we have an error following */ if (!ReadFromRFBServer(client, (char *)&reasonLen, 4)) return FALSE; reasonLen = rfbClientSwap32IfLE(reasonLen); reason = malloc((uint64_t)reasonLen+1); if (!ReadFromRFBServer(client, reason, reasonLen)) { free(reason); return FALSE; } reason[reasonLen]=0; rfbClientLog(""VNC connection failed: %s\n"",reason); free(reason); return FALSE; } rfbClientLog(""VNC authentication failed\n""); return FALSE; case rfbVncAuthTooMany: rfbClientLog(""VNC authentication failed - too many tries\n""); return FALSE; } rfbClientLog(""Unknown VNC authentication result: %d\n"", (int)authResult); return FALSE; }","rfbHandleAuthResult(rfbClient* client) { uint32_t authResult=0; if (!ReadFromRFBServer(client, (char *)&authResult, 4)) return FALSE; authResult = rfbClientSwap32IfLE(authResult); switch (authResult) { case rfbVncAuthOK: rfbClientLog(""VNC authentication succeeded\n""); return TRUE; break; case rfbVncAuthFailed: if (client->major==3 && client->minor>7) { /* we have an error following */ ReadReason(client); return FALSE; } rfbClientLog(""VNC authentication failed\n""); return FALSE; case rfbVncAuthTooMany: rfbClientLog(""VNC authentication failed - too many tries\n""); return FALSE; } rfbClientLog(""Unknown VNC authentication result: %d\n"", (int)authResult); return FALSE; }","{'deleted': [{'line_no': 3, 'char_start': 41, 'char_end': 81, 'line': ' uint32_t authResult=0, reasonLen=0;\n'}, {'line_no': 4, 'char_start': 81, 'char_end': 104, 'line': ' char *reason=NULL;\n'}, {'line_no': 19, 'char_start': 489, 'char_end': 566, 'line': ' if (!ReadFromRFBServer(client, (char *)&reasonLen, 4)) return FALSE;\n'}, {'line_no': 20, 'char_start': 566, 'char_end': 618, 'line': ' reasonLen = rfbClientSwap32IfLE(reasonLen);\n'}, {'line_no': 21, 'char_start': 618, 'char_end': 666, 'line': ' reason = malloc((uint64_t)reasonLen+1);\n'}, {'line_no': 22, 'char_start': 666, 'char_end': 757, 'line': ' if (!ReadFromRFBServer(client, reason, reasonLen)) { free(reason); return FALSE; }\n'}, {'line_no': 23, 'char_start': 757, 'char_end': 786, 'line': ' reason[reasonLen]=0;\n'}, {'line_no': 24, 'char_start': 786, 'char_end': 846, 'line': ' rfbClientLog(""VNC connection failed: %s\\n"",reason);\n'}, {'line_no': 25, 'char_start': 846, 'char_end': 868, 'line': ' free(reason);\n'}], 'added': [{'line_no': 3, 'char_start': 41, 'char_end': 68, 'line': ' uint32_t authResult=0;\n'}, {'line_no': 18, 'char_start': 453, 'char_end': 481, 'line': ' ReadReason(client);\n'}]}","{'deleted': [{'char_start': 66, 'char_end': 102, 'chars': ', reasonLen=0;\n char *reason=NULL'}, {'char_start': 497, 'char_end': 502, 'chars': 'if (!'}, {'char_start': 506, 'char_end': 510, 'chars': 'From'}, {'char_start': 511, 'char_end': 538, 'chars': 'FBServer(client, (char *)&r'}, {'char_start': 543, 'char_end': 696, 'chars': 'Len, 4)) return FALSE;\n reasonLen = rfbClientSwap32IfLE(reasonLen);\n reason = malloc((uint64_t)reasonLen+1);\n if (!ReadFromRFBServer'}, {'char_start': 703, 'char_end': 865, 'chars': ', reason, reasonLen)) { free(reason); return FALSE; }\n reason[reasonLen]=0;\n rfbClientLog(""VNC connection failed: %s\\n"",reason);\n free(reason'}], 'added': [{'char_start': 68, 'char_end': 68, 'chars': ''}]}",github.com/LibVNC/libvncserver/commit/e34bcbb759ca5bef85809967a268fdf214c1ad2c,libvncclient/rfbproto.c,cwe-787,325 cwe-125,get_uncompressed_data,"get_uncompressed_data(struct archive_read *a, const void **buff, size_t size, size_t minimum) { struct _7zip *zip = (struct _7zip *)a->format->data; ssize_t bytes_avail; if (zip->codec == _7Z_COPY && zip->codec2 == (unsigned long)-1) { /* Copy mode. */ /* * Note: '1' here is a performance optimization. * Recall that the decompression layer returns a count of * available bytes; asking for more than that forces the * decompressor to combine reads by copying data. */ *buff = __archive_read_ahead(a, 1, &bytes_avail); if (bytes_avail <= 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, ""Truncated 7-Zip file data""); return (ARCHIVE_FATAL); } if ((size_t)bytes_avail > zip->uncompressed_buffer_bytes_remaining) bytes_avail = (ssize_t) zip->uncompressed_buffer_bytes_remaining; if ((size_t)bytes_avail > size) bytes_avail = (ssize_t)size; zip->pack_stream_bytes_unconsumed = bytes_avail; } else if (zip->uncompressed_buffer_pointer == NULL) { /* Decompression has failed. */ archive_set_error(&(a->archive), ARCHIVE_ERRNO_MISC, ""Damaged 7-Zip archive""); return (ARCHIVE_FATAL); } else { /* Packed mode. */ if (minimum > zip->uncompressed_buffer_bytes_remaining) { /* * If remaining uncompressed data size is less than * the minimum size, fill the buffer up to the * minimum size. */ if (extract_pack_stream(a, minimum) < 0) return (ARCHIVE_FATAL); } if (size > zip->uncompressed_buffer_bytes_remaining) bytes_avail = (ssize_t) zip->uncompressed_buffer_bytes_remaining; else bytes_avail = (ssize_t)size; *buff = zip->uncompressed_buffer_pointer; zip->uncompressed_buffer_pointer += bytes_avail; } zip->uncompressed_buffer_bytes_remaining -= bytes_avail; return (bytes_avail); }","get_uncompressed_data(struct archive_read *a, const void **buff, size_t size, size_t minimum) { struct _7zip *zip = (struct _7zip *)a->format->data; ssize_t bytes_avail; if (zip->codec == _7Z_COPY && zip->codec2 == (unsigned long)-1) { /* Copy mode. */ *buff = __archive_read_ahead(a, minimum, &bytes_avail); if (bytes_avail <= 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, ""Truncated 7-Zip file data""); return (ARCHIVE_FATAL); } if ((size_t)bytes_avail > zip->uncompressed_buffer_bytes_remaining) bytes_avail = (ssize_t) zip->uncompressed_buffer_bytes_remaining; if ((size_t)bytes_avail > size) bytes_avail = (ssize_t)size; zip->pack_stream_bytes_unconsumed = bytes_avail; } else if (zip->uncompressed_buffer_pointer == NULL) { /* Decompression has failed. */ archive_set_error(&(a->archive), ARCHIVE_ERRNO_MISC, ""Damaged 7-Zip archive""); return (ARCHIVE_FATAL); } else { /* Packed mode. */ if (minimum > zip->uncompressed_buffer_bytes_remaining) { /* * If remaining uncompressed data size is less than * the minimum size, fill the buffer up to the * minimum size. */ if (extract_pack_stream(a, minimum) < 0) return (ARCHIVE_FATAL); } if (size > zip->uncompressed_buffer_bytes_remaining) bytes_avail = (ssize_t) zip->uncompressed_buffer_bytes_remaining; else bytes_avail = (ssize_t)size; *buff = zip->uncompressed_buffer_pointer; zip->uncompressed_buffer_pointer += bytes_avail; } zip->uncompressed_buffer_bytes_remaining -= bytes_avail; return (bytes_avail); }","{'deleted': [{'line_no': 10, 'char_start': 264, 'char_end': 269, 'line': '\t\t/*\n'}, {'line_no': 11, 'char_start': 269, 'char_end': 320, 'line': ""\t\t * Note: '1' here is a performance optimization.\n""}, {'line_no': 12, 'char_start': 320, 'char_end': 380, 'line': '\t\t * Recall that the decompression layer returns a count of\n'}, {'line_no': 13, 'char_start': 380, 'char_end': 439, 'line': '\t\t * available bytes; asking for more than that forces the\n'}, {'line_no': 14, 'char_start': 439, 'char_end': 491, 'line': '\t\t * decompressor to combine reads by copying data.\n'}, {'line_no': 15, 'char_start': 491, 'char_end': 497, 'line': '\t\t */\n'}, {'line_no': 16, 'char_start': 497, 'char_end': 549, 'line': '\t\t*buff = __archive_read_ahead(a, 1, &bytes_avail);\n'}], 'added': [{'line_no': 10, 'char_start': 264, 'char_end': 322, 'line': '\t\t*buff = __archive_read_ahead(a, minimum, &bytes_avail);\n'}]}","{'deleted': [{'char_start': 266, 'char_end': 499, 'chars': ""/*\n\t\t * Note: '1' here is a performance optimization.\n\t\t * Recall that the decompression layer returns a count of\n\t\t * available bytes; asking for more than that forces the\n\t\t * decompressor to combine reads by copying data.\n\t\t */\n\t\t""}, {'char_start': 531, 'char_end': 532, 'chars': '1'}], 'added': [{'char_start': 298, 'char_end': 305, 'chars': 'minimum'}]}",github.com/libarchive/libarchive/commit/65a23f5dbee4497064e9bb467f81138a62b0dae1,libarchive/archive_read_support_format_7zip.c,cwe-125,499 cwe-787,HandleRFBServerMessage,"HandleRFBServerMessage(rfbClient* client) { rfbServerToClientMsg msg; if (client->serverPort==-1) client->vncRec->readTimestamp = TRUE; if (!ReadFromRFBServer(client, (char *)&msg, 1)) return FALSE; switch (msg.type) { case rfbSetColourMapEntries: { /* TODO: int i; uint16_t rgb[3]; XColor xc; if (!ReadFromRFBServer(client, ((char *)&msg) + 1, sz_rfbSetColourMapEntriesMsg - 1)) return FALSE; msg.scme.firstColour = rfbClientSwap16IfLE(msg.scme.firstColour); msg.scme.nColours = rfbClientSwap16IfLE(msg.scme.nColours); for (i = 0; i < msg.scme.nColours; i++) { if (!ReadFromRFBServer(client, (char *)rgb, 6)) return FALSE; xc.pixel = msg.scme.firstColour + i; xc.red = rfbClientSwap16IfLE(rgb[0]); xc.green = rfbClientSwap16IfLE(rgb[1]); xc.blue = rfbClientSwap16IfLE(rgb[2]); xc.flags = DoRed|DoGreen|DoBlue; XStoreColor(dpy, cmap, &xc); } */ break; } case rfbFramebufferUpdate: { rfbFramebufferUpdateRectHeader rect; int linesToRead; int bytesPerLine; int i; if (!ReadFromRFBServer(client, ((char *)&msg.fu) + 1, sz_rfbFramebufferUpdateMsg - 1)) return FALSE; msg.fu.nRects = rfbClientSwap16IfLE(msg.fu.nRects); for (i = 0; i < msg.fu.nRects; i++) { if (!ReadFromRFBServer(client, (char *)&rect, sz_rfbFramebufferUpdateRectHeader)) return FALSE; rect.encoding = rfbClientSwap32IfLE(rect.encoding); if (rect.encoding == rfbEncodingLastRect) break; rect.r.x = rfbClientSwap16IfLE(rect.r.x); rect.r.y = rfbClientSwap16IfLE(rect.r.y); rect.r.w = rfbClientSwap16IfLE(rect.r.w); rect.r.h = rfbClientSwap16IfLE(rect.r.h); if (rect.encoding == rfbEncodingXCursor || rect.encoding == rfbEncodingRichCursor) { if (!HandleCursorShape(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h, rect.encoding)) { return FALSE; } continue; } if (rect.encoding == rfbEncodingPointerPos) { if (!client->HandleCursorPos(client,rect.r.x, rect.r.y)) { return FALSE; } continue; } if (rect.encoding == rfbEncodingKeyboardLedState) { /* OK! We have received a keyboard state message!!! */ client->KeyboardLedStateEnabled = 1; if (client->HandleKeyboardLedState!=NULL) client->HandleKeyboardLedState(client, rect.r.x, 0); /* stash it for the future */ client->CurrentKeyboardLedState = rect.r.x; continue; } if (rect.encoding == rfbEncodingNewFBSize) { client->width = rect.r.w; client->height = rect.r.h; client->updateRect.x = client->updateRect.y = 0; client->updateRect.w = client->width; client->updateRect.h = client->height; if (!client->MallocFrameBuffer(client)) return FALSE; SendFramebufferUpdateRequest(client, 0, 0, rect.r.w, rect.r.h, FALSE); rfbClientLog(""Got new framebuffer size: %dx%d\n"", rect.r.w, rect.r.h); continue; } /* rect.r.w=byte count */ if (rect.encoding == rfbEncodingSupportedMessages) { int loop; if (!ReadFromRFBServer(client, (char *)&client->supportedMessages, sz_rfbSupportedMessages)) return FALSE; /* msgs is two sets of bit flags of supported messages client2server[] and server2client[] */ /* currently ignored by this library */ rfbClientLog(""client2server supported messages (bit flags)\n""); for (loop=0;loop<32;loop+=8) rfbClientLog(""%02X: %04x %04x %04x %04x - %04x %04x %04x %04x\n"", loop, client->supportedMessages.client2server[loop], client->supportedMessages.client2server[loop+1], client->supportedMessages.client2server[loop+2], client->supportedMessages.client2server[loop+3], client->supportedMessages.client2server[loop+4], client->supportedMessages.client2server[loop+5], client->supportedMessages.client2server[loop+6], client->supportedMessages.client2server[loop+7]); rfbClientLog(""server2client supported messages (bit flags)\n""); for (loop=0;loop<32;loop+=8) rfbClientLog(""%02X: %04x %04x %04x %04x - %04x %04x %04x %04x\n"", loop, client->supportedMessages.server2client[loop], client->supportedMessages.server2client[loop+1], client->supportedMessages.server2client[loop+2], client->supportedMessages.server2client[loop+3], client->supportedMessages.server2client[loop+4], client->supportedMessages.server2client[loop+5], client->supportedMessages.server2client[loop+6], client->supportedMessages.server2client[loop+7]); continue; } /* rect.r.w=byte count, rect.r.h=# of encodings */ if (rect.encoding == rfbEncodingSupportedEncodings) { char *buffer; buffer = malloc(rect.r.w); if (!ReadFromRFBServer(client, buffer, rect.r.w)) { free(buffer); return FALSE; } /* buffer now contains rect.r.h # of uint32_t encodings that the server supports */ /* currently ignored by this library */ free(buffer); continue; } /* rect.r.w=byte count */ if (rect.encoding == rfbEncodingServerIdentity) { char *buffer; buffer = malloc(rect.r.w+1); if (!ReadFromRFBServer(client, buffer, rect.r.w)) { free(buffer); return FALSE; } buffer[rect.r.w]=0; /* null terminate, just in case */ rfbClientLog(""Connected to Server \""%s\""\n"", buffer); free(buffer); continue; } /* rfbEncodingUltraZip is a collection of subrects. x = # of subrects, and h is always 0 */ if (rect.encoding != rfbEncodingUltraZip) { if ((rect.r.x + rect.r.w > client->width) || (rect.r.y + rect.r.h > client->height)) { rfbClientLog(""Rect too large: %dx%d at (%d, %d)\n"", rect.r.w, rect.r.h, rect.r.x, rect.r.y); return FALSE; } /* UltraVNC with scaling, will send rectangles with a zero W or H * if ((rect.encoding != rfbEncodingTight) && (rect.r.h * rect.r.w == 0)) { rfbClientLog(""Zero size rect - ignoring (encoding=%d (0x%08x) %dx, %dy, %dw, %dh)\n"", rect.encoding, rect.encoding, rect.r.x, rect.r.y, rect.r.w, rect.r.h); continue; } */ /* If RichCursor encoding is used, we should prevent collisions between framebuffer updates and cursor drawing operations. */ client->SoftCursorLockArea(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h); } switch (rect.encoding) { case rfbEncodingRaw: { int y=rect.r.y, h=rect.r.h; bytesPerLine = rect.r.w * client->format.bitsPerPixel / 8; /* RealVNC 4.x-5.x on OSX can induce bytesPerLine==0, usually during GPU accel. */ /* Regardless of cause, do not divide by zero. */ linesToRead = bytesPerLine ? (RFB_BUFFER_SIZE / bytesPerLine) : 0; while (linesToRead && h > 0) { if (linesToRead > h) linesToRead = h; if (!ReadFromRFBServer(client, client->buffer,bytesPerLine * linesToRead)) return FALSE; client->GotBitmap(client, (uint8_t *)client->buffer, rect.r.x, y, rect.r.w,linesToRead); h -= linesToRead; y += linesToRead; } break; } case rfbEncodingCopyRect: { rfbCopyRect cr; if (!ReadFromRFBServer(client, (char *)&cr, sz_rfbCopyRect)) return FALSE; cr.srcX = rfbClientSwap16IfLE(cr.srcX); cr.srcY = rfbClientSwap16IfLE(cr.srcY); /* If RichCursor encoding is used, we should extend our ""cursor lock area"" (previously set to destination rectangle) to the source rectangle as well. */ client->SoftCursorLockArea(client, cr.srcX, cr.srcY, rect.r.w, rect.r.h); client->GotCopyRect(client, cr.srcX, cr.srcY, rect.r.w, rect.r.h, rect.r.x, rect.r.y); break; } case rfbEncodingRRE: { switch (client->format.bitsPerPixel) { case 8: if (!HandleRRE8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 16: if (!HandleRRE16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 32: if (!HandleRRE32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; } break; } case rfbEncodingCoRRE: { switch (client->format.bitsPerPixel) { case 8: if (!HandleCoRRE8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 16: if (!HandleCoRRE16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 32: if (!HandleCoRRE32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; } break; } case rfbEncodingHextile: { switch (client->format.bitsPerPixel) { case 8: if (!HandleHextile8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 16: if (!HandleHextile16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 32: if (!HandleHextile32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; } break; } case rfbEncodingUltra: { switch (client->format.bitsPerPixel) { case 8: if (!HandleUltra8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 16: if (!HandleUltra16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 32: if (!HandleUltra32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; } break; } case rfbEncodingUltraZip: { switch (client->format.bitsPerPixel) { case 8: if (!HandleUltraZip8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 16: if (!HandleUltraZip16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 32: if (!HandleUltraZip32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; } break; } case rfbEncodingTRLE: { switch (client->format.bitsPerPixel) { case 8: if (!HandleTRLE8(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h)) return FALSE; break; case 16: if (client->si.format.greenMax > 0x1F) { if (!HandleTRLE16(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h)) return FALSE; } else { if (!HandleTRLE15(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h)) return FALSE; } break; case 32: { uint32_t maxColor = (client->format.redMax << client->format.redShift) | (client->format.greenMax << client->format.greenShift) | (client->format.blueMax << client->format.blueShift); if ((client->format.bigEndian && (maxColor & 0xff) == 0) || (!client->format.bigEndian && (maxColor & 0xff000000) == 0)) { if (!HandleTRLE24(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h)) return FALSE; } else if (!client->format.bigEndian && (maxColor & 0xff) == 0) { if (!HandleTRLE24Up(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h)) return FALSE; } else if (client->format.bigEndian && (maxColor & 0xff000000) == 0) { if (!HandleTRLE24Down(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h)) return FALSE; } else if (!HandleTRLE32(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h)) return FALSE; break; } } break; } #ifdef LIBVNCSERVER_HAVE_LIBZ case rfbEncodingZlib: { switch (client->format.bitsPerPixel) { case 8: if (!HandleZlib8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 16: if (!HandleZlib16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 32: if (!HandleZlib32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; } break; } #ifdef LIBVNCSERVER_HAVE_LIBJPEG case rfbEncodingTight: { switch (client->format.bitsPerPixel) { case 8: if (!HandleTight8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 16: if (!HandleTight16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 32: if (!HandleTight32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; } break; } #endif case rfbEncodingZRLE: /* Fail safe for ZYWRLE unsupport VNC server. */ client->appData.qualityLevel = 9; /* fall through */ case rfbEncodingZYWRLE: { switch (client->format.bitsPerPixel) { case 8: if (!HandleZRLE8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 16: if (client->si.format.greenMax > 0x1F) { if (!HandleZRLE16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; } else { if (!HandleZRLE15(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; } break; case 32: { uint32_t maxColor=(client->format.redMax<format.redShift)| (client->format.greenMax<format.greenShift)| (client->format.blueMax<format.blueShift); if ((client->format.bigEndian && (maxColor&0xff)==0) || (!client->format.bigEndian && (maxColor&0xff000000)==0)) { if (!HandleZRLE24(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; } else if (!client->format.bigEndian && (maxColor&0xff)==0) { if (!HandleZRLE24Up(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; } else if (client->format.bigEndian && (maxColor&0xff000000)==0) { if (!HandleZRLE24Down(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; } else if (!HandleZRLE32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; } } break; } #endif default: { rfbBool handled = FALSE; rfbClientProtocolExtension* e; for(e = rfbClientExtensions; !handled && e; e = e->next) if(e->handleEncoding && e->handleEncoding(client, &rect)) handled = TRUE; if(!handled) { rfbClientLog(""Unknown rect encoding %d\n"", (int)rect.encoding); return FALSE; } } } /* Now we may discard ""soft cursor locks"". */ client->SoftCursorUnlockScreen(client); client->GotFrameBufferUpdate(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h); } if (!SendIncrementalFramebufferUpdateRequest(client)) return FALSE; if (client->FinishedFrameBufferUpdate) client->FinishedFrameBufferUpdate(client); break; } case rfbBell: { client->Bell(client); break; } case rfbServerCutText: { char *buffer; if (!ReadFromRFBServer(client, ((char *)&msg) + 1, sz_rfbServerCutTextMsg - 1)) return FALSE; msg.sct.length = rfbClientSwap32IfLE(msg.sct.length); if (msg.sct.length > 1<<20) { rfbClientErr(""Ignoring too big cut text length sent by server: %u B > 1 MB\n"", (unsigned int)msg.sct.length); return FALSE; } buffer = malloc((uint64_t)msg.sct.length+1); if (!ReadFromRFBServer(client, buffer, msg.sct.length)) { free(buffer); return FALSE; } buffer[msg.sct.length] = 0; if (client->GotXCutText) client->GotXCutText(client, buffer, msg.sct.length); free(buffer); break; } case rfbTextChat: { char *buffer=NULL; if (!ReadFromRFBServer(client, ((char *)&msg) + 1, sz_rfbTextChatMsg- 1)) return FALSE; msg.tc.length = rfbClientSwap32IfLE(msg.sct.length); switch(msg.tc.length) { case rfbTextChatOpen: rfbClientLog(""Received TextChat Open\n""); if (client->HandleTextChat!=NULL) client->HandleTextChat(client, (int)rfbTextChatOpen, NULL); break; case rfbTextChatClose: rfbClientLog(""Received TextChat Close\n""); if (client->HandleTextChat!=NULL) client->HandleTextChat(client, (int)rfbTextChatClose, NULL); break; case rfbTextChatFinished: rfbClientLog(""Received TextChat Finished\n""); if (client->HandleTextChat!=NULL) client->HandleTextChat(client, (int)rfbTextChatFinished, NULL); break; default: buffer=malloc(msg.tc.length+1); if (!ReadFromRFBServer(client, buffer, msg.tc.length)) { free(buffer); return FALSE; } /* Null Terminate */ buffer[msg.tc.length]=0; rfbClientLog(""Received TextChat \""%s\""\n"", buffer); if (client->HandleTextChat!=NULL) client->HandleTextChat(client, (int)msg.tc.length, buffer); free(buffer); break; } break; } case rfbXvp: { if (!ReadFromRFBServer(client, ((char *)&msg) + 1, sz_rfbXvpMsg -1)) return FALSE; SetClient2Server(client, rfbXvp); /* technically, we only care what we can *send* to the server * but, we set Server2Client Just in case it ever becomes useful */ SetServer2Client(client, rfbXvp); if(client->HandleXvpMsg) client->HandleXvpMsg(client, msg.xvp.version, msg.xvp.code); break; } case rfbResizeFrameBuffer: { if (!ReadFromRFBServer(client, ((char *)&msg) + 1, sz_rfbResizeFrameBufferMsg -1)) return FALSE; client->width = rfbClientSwap16IfLE(msg.rsfb.framebufferWidth); client->height = rfbClientSwap16IfLE(msg.rsfb.framebufferHeigth); client->updateRect.x = client->updateRect.y = 0; client->updateRect.w = client->width; client->updateRect.h = client->height; if (!client->MallocFrameBuffer(client)) return FALSE; SendFramebufferUpdateRequest(client, 0, 0, client->width, client->height, FALSE); rfbClientLog(""Got new framebuffer size: %dx%d\n"", client->width, client->height); break; } case rfbPalmVNCReSizeFrameBuffer: { if (!ReadFromRFBServer(client, ((char *)&msg) + 1, sz_rfbPalmVNCReSizeFrameBufferMsg -1)) return FALSE; client->width = rfbClientSwap16IfLE(msg.prsfb.buffer_w); client->height = rfbClientSwap16IfLE(msg.prsfb.buffer_h); client->updateRect.x = client->updateRect.y = 0; client->updateRect.w = client->width; client->updateRect.h = client->height; if (!client->MallocFrameBuffer(client)) return FALSE; SendFramebufferUpdateRequest(client, 0, 0, client->width, client->height, FALSE); rfbClientLog(""Got new framebuffer size: %dx%d\n"", client->width, client->height); break; } default: { rfbBool handled = FALSE; rfbClientProtocolExtension* e; for(e = rfbClientExtensions; !handled && e; e = e->next) if(e->handleMessage && e->handleMessage(client, &msg)) handled = TRUE; if(!handled) { char buffer[256]; rfbClientLog(""Unknown message type %d from VNC server\n"",msg.type); ReadFromRFBServer(client, buffer, 256); return FALSE; } } } return TRUE; }","HandleRFBServerMessage(rfbClient* client) { rfbServerToClientMsg msg; if (client->serverPort==-1) client->vncRec->readTimestamp = TRUE; if (!ReadFromRFBServer(client, (char *)&msg, 1)) return FALSE; switch (msg.type) { case rfbSetColourMapEntries: { /* TODO: int i; uint16_t rgb[3]; XColor xc; if (!ReadFromRFBServer(client, ((char *)&msg) + 1, sz_rfbSetColourMapEntriesMsg - 1)) return FALSE; msg.scme.firstColour = rfbClientSwap16IfLE(msg.scme.firstColour); msg.scme.nColours = rfbClientSwap16IfLE(msg.scme.nColours); for (i = 0; i < msg.scme.nColours; i++) { if (!ReadFromRFBServer(client, (char *)rgb, 6)) return FALSE; xc.pixel = msg.scme.firstColour + i; xc.red = rfbClientSwap16IfLE(rgb[0]); xc.green = rfbClientSwap16IfLE(rgb[1]); xc.blue = rfbClientSwap16IfLE(rgb[2]); xc.flags = DoRed|DoGreen|DoBlue; XStoreColor(dpy, cmap, &xc); } */ break; } case rfbFramebufferUpdate: { rfbFramebufferUpdateRectHeader rect; int linesToRead; int bytesPerLine; int i; if (!ReadFromRFBServer(client, ((char *)&msg.fu) + 1, sz_rfbFramebufferUpdateMsg - 1)) return FALSE; msg.fu.nRects = rfbClientSwap16IfLE(msg.fu.nRects); for (i = 0; i < msg.fu.nRects; i++) { if (!ReadFromRFBServer(client, (char *)&rect, sz_rfbFramebufferUpdateRectHeader)) return FALSE; rect.encoding = rfbClientSwap32IfLE(rect.encoding); if (rect.encoding == rfbEncodingLastRect) break; rect.r.x = rfbClientSwap16IfLE(rect.r.x); rect.r.y = rfbClientSwap16IfLE(rect.r.y); rect.r.w = rfbClientSwap16IfLE(rect.r.w); rect.r.h = rfbClientSwap16IfLE(rect.r.h); if (rect.encoding == rfbEncodingXCursor || rect.encoding == rfbEncodingRichCursor) { if (!HandleCursorShape(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h, rect.encoding)) { return FALSE; } continue; } if (rect.encoding == rfbEncodingPointerPos) { if (!client->HandleCursorPos(client,rect.r.x, rect.r.y)) { return FALSE; } continue; } if (rect.encoding == rfbEncodingKeyboardLedState) { /* OK! We have received a keyboard state message!!! */ client->KeyboardLedStateEnabled = 1; if (client->HandleKeyboardLedState!=NULL) client->HandleKeyboardLedState(client, rect.r.x, 0); /* stash it for the future */ client->CurrentKeyboardLedState = rect.r.x; continue; } if (rect.encoding == rfbEncodingNewFBSize) { client->width = rect.r.w; client->height = rect.r.h; client->updateRect.x = client->updateRect.y = 0; client->updateRect.w = client->width; client->updateRect.h = client->height; if (!client->MallocFrameBuffer(client)) return FALSE; SendFramebufferUpdateRequest(client, 0, 0, rect.r.w, rect.r.h, FALSE); rfbClientLog(""Got new framebuffer size: %dx%d\n"", rect.r.w, rect.r.h); continue; } /* rect.r.w=byte count */ if (rect.encoding == rfbEncodingSupportedMessages) { int loop; if (!ReadFromRFBServer(client, (char *)&client->supportedMessages, sz_rfbSupportedMessages)) return FALSE; /* msgs is two sets of bit flags of supported messages client2server[] and server2client[] */ /* currently ignored by this library */ rfbClientLog(""client2server supported messages (bit flags)\n""); for (loop=0;loop<32;loop+=8) rfbClientLog(""%02X: %04x %04x %04x %04x - %04x %04x %04x %04x\n"", loop, client->supportedMessages.client2server[loop], client->supportedMessages.client2server[loop+1], client->supportedMessages.client2server[loop+2], client->supportedMessages.client2server[loop+3], client->supportedMessages.client2server[loop+4], client->supportedMessages.client2server[loop+5], client->supportedMessages.client2server[loop+6], client->supportedMessages.client2server[loop+7]); rfbClientLog(""server2client supported messages (bit flags)\n""); for (loop=0;loop<32;loop+=8) rfbClientLog(""%02X: %04x %04x %04x %04x - %04x %04x %04x %04x\n"", loop, client->supportedMessages.server2client[loop], client->supportedMessages.server2client[loop+1], client->supportedMessages.server2client[loop+2], client->supportedMessages.server2client[loop+3], client->supportedMessages.server2client[loop+4], client->supportedMessages.server2client[loop+5], client->supportedMessages.server2client[loop+6], client->supportedMessages.server2client[loop+7]); continue; } /* rect.r.w=byte count, rect.r.h=# of encodings */ if (rect.encoding == rfbEncodingSupportedEncodings) { char *buffer; buffer = malloc(rect.r.w); if (!ReadFromRFBServer(client, buffer, rect.r.w)) { free(buffer); return FALSE; } /* buffer now contains rect.r.h # of uint32_t encodings that the server supports */ /* currently ignored by this library */ free(buffer); continue; } /* rect.r.w=byte count */ if (rect.encoding == rfbEncodingServerIdentity) { char *buffer; buffer = malloc(rect.r.w+1); if (!ReadFromRFBServer(client, buffer, rect.r.w)) { free(buffer); return FALSE; } buffer[rect.r.w]=0; /* null terminate, just in case */ rfbClientLog(""Connected to Server \""%s\""\n"", buffer); free(buffer); continue; } /* rfbEncodingUltraZip is a collection of subrects. x = # of subrects, and h is always 0 */ if (rect.encoding != rfbEncodingUltraZip) { if ((rect.r.x + rect.r.w > client->width) || (rect.r.y + rect.r.h > client->height)) { rfbClientLog(""Rect too large: %dx%d at (%d, %d)\n"", rect.r.w, rect.r.h, rect.r.x, rect.r.y); return FALSE; } /* UltraVNC with scaling, will send rectangles with a zero W or H * if ((rect.encoding != rfbEncodingTight) && (rect.r.h * rect.r.w == 0)) { rfbClientLog(""Zero size rect - ignoring (encoding=%d (0x%08x) %dx, %dy, %dw, %dh)\n"", rect.encoding, rect.encoding, rect.r.x, rect.r.y, rect.r.w, rect.r.h); continue; } */ /* If RichCursor encoding is used, we should prevent collisions between framebuffer updates and cursor drawing operations. */ client->SoftCursorLockArea(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h); } switch (rect.encoding) { case rfbEncodingRaw: { int y=rect.r.y, h=rect.r.h; bytesPerLine = rect.r.w * client->format.bitsPerPixel / 8; /* RealVNC 4.x-5.x on OSX can induce bytesPerLine==0, usually during GPU accel. */ /* Regardless of cause, do not divide by zero. */ linesToRead = bytesPerLine ? (RFB_BUFFER_SIZE / bytesPerLine) : 0; while (linesToRead && h > 0) { if (linesToRead > h) linesToRead = h; if (!ReadFromRFBServer(client, client->buffer,bytesPerLine * linesToRead)) return FALSE; client->GotBitmap(client, (uint8_t *)client->buffer, rect.r.x, y, rect.r.w,linesToRead); h -= linesToRead; y += linesToRead; } break; } case rfbEncodingCopyRect: { rfbCopyRect cr; if (!ReadFromRFBServer(client, (char *)&cr, sz_rfbCopyRect)) return FALSE; cr.srcX = rfbClientSwap16IfLE(cr.srcX); cr.srcY = rfbClientSwap16IfLE(cr.srcY); /* If RichCursor encoding is used, we should extend our ""cursor lock area"" (previously set to destination rectangle) to the source rectangle as well. */ client->SoftCursorLockArea(client, cr.srcX, cr.srcY, rect.r.w, rect.r.h); client->GotCopyRect(client, cr.srcX, cr.srcY, rect.r.w, rect.r.h, rect.r.x, rect.r.y); break; } case rfbEncodingRRE: { switch (client->format.bitsPerPixel) { case 8: if (!HandleRRE8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 16: if (!HandleRRE16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 32: if (!HandleRRE32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; } break; } case rfbEncodingCoRRE: { switch (client->format.bitsPerPixel) { case 8: if (!HandleCoRRE8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 16: if (!HandleCoRRE16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 32: if (!HandleCoRRE32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; } break; } case rfbEncodingHextile: { switch (client->format.bitsPerPixel) { case 8: if (!HandleHextile8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 16: if (!HandleHextile16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 32: if (!HandleHextile32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; } break; } case rfbEncodingUltra: { switch (client->format.bitsPerPixel) { case 8: if (!HandleUltra8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 16: if (!HandleUltra16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 32: if (!HandleUltra32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; } break; } case rfbEncodingUltraZip: { switch (client->format.bitsPerPixel) { case 8: if (!HandleUltraZip8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 16: if (!HandleUltraZip16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 32: if (!HandleUltraZip32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; } break; } case rfbEncodingTRLE: { switch (client->format.bitsPerPixel) { case 8: if (!HandleTRLE8(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h)) return FALSE; break; case 16: if (client->si.format.greenMax > 0x1F) { if (!HandleTRLE16(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h)) return FALSE; } else { if (!HandleTRLE15(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h)) return FALSE; } break; case 32: { uint32_t maxColor = (client->format.redMax << client->format.redShift) | (client->format.greenMax << client->format.greenShift) | (client->format.blueMax << client->format.blueShift); if ((client->format.bigEndian && (maxColor & 0xff) == 0) || (!client->format.bigEndian && (maxColor & 0xff000000) == 0)) { if (!HandleTRLE24(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h)) return FALSE; } else if (!client->format.bigEndian && (maxColor & 0xff) == 0) { if (!HandleTRLE24Up(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h)) return FALSE; } else if (client->format.bigEndian && (maxColor & 0xff000000) == 0) { if (!HandleTRLE24Down(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h)) return FALSE; } else if (!HandleTRLE32(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h)) return FALSE; break; } } break; } #ifdef LIBVNCSERVER_HAVE_LIBZ case rfbEncodingZlib: { switch (client->format.bitsPerPixel) { case 8: if (!HandleZlib8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 16: if (!HandleZlib16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 32: if (!HandleZlib32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; } break; } #ifdef LIBVNCSERVER_HAVE_LIBJPEG case rfbEncodingTight: { switch (client->format.bitsPerPixel) { case 8: if (!HandleTight8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 16: if (!HandleTight16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 32: if (!HandleTight32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; } break; } #endif case rfbEncodingZRLE: /* Fail safe for ZYWRLE unsupport VNC server. */ client->appData.qualityLevel = 9; /* fall through */ case rfbEncodingZYWRLE: { switch (client->format.bitsPerPixel) { case 8: if (!HandleZRLE8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 16: if (client->si.format.greenMax > 0x1F) { if (!HandleZRLE16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; } else { if (!HandleZRLE15(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; } break; case 32: { uint32_t maxColor=(client->format.redMax<format.redShift)| (client->format.greenMax<format.greenShift)| (client->format.blueMax<format.blueShift); if ((client->format.bigEndian && (maxColor&0xff)==0) || (!client->format.bigEndian && (maxColor&0xff000000)==0)) { if (!HandleZRLE24(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; } else if (!client->format.bigEndian && (maxColor&0xff)==0) { if (!HandleZRLE24Up(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; } else if (client->format.bigEndian && (maxColor&0xff000000)==0) { if (!HandleZRLE24Down(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; } else if (!HandleZRLE32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; } } break; } #endif default: { rfbBool handled = FALSE; rfbClientProtocolExtension* e; for(e = rfbClientExtensions; !handled && e; e = e->next) if(e->handleEncoding && e->handleEncoding(client, &rect)) handled = TRUE; if(!handled) { rfbClientLog(""Unknown rect encoding %d\n"", (int)rect.encoding); return FALSE; } } } /* Now we may discard ""soft cursor locks"". */ client->SoftCursorUnlockScreen(client); client->GotFrameBufferUpdate(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h); } if (!SendIncrementalFramebufferUpdateRequest(client)) return FALSE; if (client->FinishedFrameBufferUpdate) client->FinishedFrameBufferUpdate(client); break; } case rfbBell: { client->Bell(client); break; } case rfbServerCutText: { char *buffer; if (!ReadFromRFBServer(client, ((char *)&msg) + 1, sz_rfbServerCutTextMsg - 1)) return FALSE; msg.sct.length = rfbClientSwap32IfLE(msg.sct.length); if (msg.sct.length > 1<<20) { rfbClientErr(""Ignoring too big cut text length sent by server: %u B > 1 MB\n"", (unsigned int)msg.sct.length); return FALSE; } buffer = malloc(msg.sct.length+1); if (!ReadFromRFBServer(client, buffer, msg.sct.length)) { free(buffer); return FALSE; } buffer[msg.sct.length] = 0; if (client->GotXCutText) client->GotXCutText(client, buffer, msg.sct.length); free(buffer); break; } case rfbTextChat: { char *buffer=NULL; if (!ReadFromRFBServer(client, ((char *)&msg) + 1, sz_rfbTextChatMsg- 1)) return FALSE; msg.tc.length = rfbClientSwap32IfLE(msg.sct.length); switch(msg.tc.length) { case rfbTextChatOpen: rfbClientLog(""Received TextChat Open\n""); if (client->HandleTextChat!=NULL) client->HandleTextChat(client, (int)rfbTextChatOpen, NULL); break; case rfbTextChatClose: rfbClientLog(""Received TextChat Close\n""); if (client->HandleTextChat!=NULL) client->HandleTextChat(client, (int)rfbTextChatClose, NULL); break; case rfbTextChatFinished: rfbClientLog(""Received TextChat Finished\n""); if (client->HandleTextChat!=NULL) client->HandleTextChat(client, (int)rfbTextChatFinished, NULL); break; default: buffer=malloc(msg.tc.length+1); if (!ReadFromRFBServer(client, buffer, msg.tc.length)) { free(buffer); return FALSE; } /* Null Terminate */ buffer[msg.tc.length]=0; rfbClientLog(""Received TextChat \""%s\""\n"", buffer); if (client->HandleTextChat!=NULL) client->HandleTextChat(client, (int)msg.tc.length, buffer); free(buffer); break; } break; } case rfbXvp: { if (!ReadFromRFBServer(client, ((char *)&msg) + 1, sz_rfbXvpMsg -1)) return FALSE; SetClient2Server(client, rfbXvp); /* technically, we only care what we can *send* to the server * but, we set Server2Client Just in case it ever becomes useful */ SetServer2Client(client, rfbXvp); if(client->HandleXvpMsg) client->HandleXvpMsg(client, msg.xvp.version, msg.xvp.code); break; } case rfbResizeFrameBuffer: { if (!ReadFromRFBServer(client, ((char *)&msg) + 1, sz_rfbResizeFrameBufferMsg -1)) return FALSE; client->width = rfbClientSwap16IfLE(msg.rsfb.framebufferWidth); client->height = rfbClientSwap16IfLE(msg.rsfb.framebufferHeigth); client->updateRect.x = client->updateRect.y = 0; client->updateRect.w = client->width; client->updateRect.h = client->height; if (!client->MallocFrameBuffer(client)) return FALSE; SendFramebufferUpdateRequest(client, 0, 0, client->width, client->height, FALSE); rfbClientLog(""Got new framebuffer size: %dx%d\n"", client->width, client->height); break; } case rfbPalmVNCReSizeFrameBuffer: { if (!ReadFromRFBServer(client, ((char *)&msg) + 1, sz_rfbPalmVNCReSizeFrameBufferMsg -1)) return FALSE; client->width = rfbClientSwap16IfLE(msg.prsfb.buffer_w); client->height = rfbClientSwap16IfLE(msg.prsfb.buffer_h); client->updateRect.x = client->updateRect.y = 0; client->updateRect.w = client->width; client->updateRect.h = client->height; if (!client->MallocFrameBuffer(client)) return FALSE; SendFramebufferUpdateRequest(client, 0, 0, client->width, client->height, FALSE); rfbClientLog(""Got new framebuffer size: %dx%d\n"", client->width, client->height); break; } default: { rfbBool handled = FALSE; rfbClientProtocolExtension* e; for(e = rfbClientExtensions; !handled && e; e = e->next) if(e->handleMessage && e->handleMessage(client, &msg)) handled = TRUE; if(!handled) { char buffer[256]; rfbClientLog(""Unknown message type %d from VNC server\n"",msg.type); ReadFromRFBServer(client, buffer, 256); return FALSE; } } } return TRUE; }","{'deleted': [{'line_no': 517, 'char_start': 15578, 'char_end': 15627, 'line': ' buffer = malloc((uint64_t)msg.sct.length+1);\n'}], 'added': [{'line_no': 517, 'char_start': 15578, 'char_end': 15617, 'line': ' buffer = malloc(msg.sct.length+1);\n'}]}","{'deleted': [{'char_start': 15598, 'char_end': 15608, 'chars': '(uint64_t)'}], 'added': []}",github.com/LibVNC/libvncserver/commit/a64c3b37af9a6c8f8009d7516874b8d266b42bae,libvncclient/rfbproto.c,cwe-787,5548 cwe-416,SMB2_write,"SMB2_write(const unsigned int xid, struct cifs_io_parms *io_parms, unsigned int *nbytes, struct kvec *iov, int n_vec) { struct smb_rqst rqst; int rc = 0; struct smb2_write_req *req = NULL; struct smb2_write_rsp *rsp = NULL; int resp_buftype; struct kvec rsp_iov; int flags = 0; unsigned int total_len; *nbytes = 0; if (n_vec < 1) return rc; rc = smb2_plain_req_init(SMB2_WRITE, io_parms->tcon, (void **) &req, &total_len); if (rc) return rc; if (io_parms->tcon->ses->server == NULL) return -ECONNABORTED; if (smb3_encryption_required(io_parms->tcon)) flags |= CIFS_TRANSFORM_REQ; req->sync_hdr.ProcessId = cpu_to_le32(io_parms->pid); req->PersistentFileId = io_parms->persistent_fid; req->VolatileFileId = io_parms->volatile_fid; req->WriteChannelInfoOffset = 0; req->WriteChannelInfoLength = 0; req->Channel = 0; req->Length = cpu_to_le32(io_parms->length); req->Offset = cpu_to_le64(io_parms->offset); req->DataOffset = cpu_to_le16( offsetof(struct smb2_write_req, Buffer)); req->RemainingBytes = 0; trace_smb3_write_enter(xid, io_parms->persistent_fid, io_parms->tcon->tid, io_parms->tcon->ses->Suid, io_parms->offset, io_parms->length); iov[0].iov_base = (char *)req; /* 1 for Buffer */ iov[0].iov_len = total_len - 1; memset(&rqst, 0, sizeof(struct smb_rqst)); rqst.rq_iov = iov; rqst.rq_nvec = n_vec + 1; rc = cifs_send_recv(xid, io_parms->tcon->ses, &rqst, &resp_buftype, flags, &rsp_iov); cifs_small_buf_release(req); rsp = (struct smb2_write_rsp *)rsp_iov.iov_base; if (rc) { trace_smb3_write_err(xid, req->PersistentFileId, io_parms->tcon->tid, io_parms->tcon->ses->Suid, io_parms->offset, io_parms->length, rc); cifs_stats_fail_inc(io_parms->tcon, SMB2_WRITE_HE); cifs_dbg(VFS, ""Send error in write = %d\n"", rc); } else { *nbytes = le32_to_cpu(rsp->DataLength); trace_smb3_write_done(xid, req->PersistentFileId, io_parms->tcon->tid, io_parms->tcon->ses->Suid, io_parms->offset, *nbytes); } free_rsp_buf(resp_buftype, rsp); return rc; }","SMB2_write(const unsigned int xid, struct cifs_io_parms *io_parms, unsigned int *nbytes, struct kvec *iov, int n_vec) { struct smb_rqst rqst; int rc = 0; struct smb2_write_req *req = NULL; struct smb2_write_rsp *rsp = NULL; int resp_buftype; struct kvec rsp_iov; int flags = 0; unsigned int total_len; *nbytes = 0; if (n_vec < 1) return rc; rc = smb2_plain_req_init(SMB2_WRITE, io_parms->tcon, (void **) &req, &total_len); if (rc) return rc; if (io_parms->tcon->ses->server == NULL) return -ECONNABORTED; if (smb3_encryption_required(io_parms->tcon)) flags |= CIFS_TRANSFORM_REQ; req->sync_hdr.ProcessId = cpu_to_le32(io_parms->pid); req->PersistentFileId = io_parms->persistent_fid; req->VolatileFileId = io_parms->volatile_fid; req->WriteChannelInfoOffset = 0; req->WriteChannelInfoLength = 0; req->Channel = 0; req->Length = cpu_to_le32(io_parms->length); req->Offset = cpu_to_le64(io_parms->offset); req->DataOffset = cpu_to_le16( offsetof(struct smb2_write_req, Buffer)); req->RemainingBytes = 0; trace_smb3_write_enter(xid, io_parms->persistent_fid, io_parms->tcon->tid, io_parms->tcon->ses->Suid, io_parms->offset, io_parms->length); iov[0].iov_base = (char *)req; /* 1 for Buffer */ iov[0].iov_len = total_len - 1; memset(&rqst, 0, sizeof(struct smb_rqst)); rqst.rq_iov = iov; rqst.rq_nvec = n_vec + 1; rc = cifs_send_recv(xid, io_parms->tcon->ses, &rqst, &resp_buftype, flags, &rsp_iov); rsp = (struct smb2_write_rsp *)rsp_iov.iov_base; if (rc) { trace_smb3_write_err(xid, req->PersistentFileId, io_parms->tcon->tid, io_parms->tcon->ses->Suid, io_parms->offset, io_parms->length, rc); cifs_stats_fail_inc(io_parms->tcon, SMB2_WRITE_HE); cifs_dbg(VFS, ""Send error in write = %d\n"", rc); } else { *nbytes = le32_to_cpu(rsp->DataLength); trace_smb3_write_done(xid, req->PersistentFileId, io_parms->tcon->tid, io_parms->tcon->ses->Suid, io_parms->offset, *nbytes); } cifs_small_buf_release(req); free_rsp_buf(resp_buftype, rsp); return rc; }","{'deleted': [{'line_no': 56, 'char_start': 1475, 'char_end': 1505, 'line': '\tcifs_small_buf_release(req);\n'}], 'added': [{'line_no': 73, 'char_start': 2020, 'char_end': 2050, 'line': '\tcifs_small_buf_release(req);\n'}]}","{'deleted': [{'char_start': 1476, 'char_end': 1506, 'chars': 'cifs_small_buf_release(req);\n\t'}], 'added': [{'char_start': 2019, 'char_end': 2049, 'chars': '\n\tcifs_small_buf_release(req);'}]}",github.com/torvalds/linux/commit/6a3eb3360667170988f8a6477f6686242061488a,fs/cifs/smb2pdu.c,cwe-416,673 cwe-476,_kdc_as_rep,"_kdc_as_rep(kdc_request_t r, krb5_data *reply, const char *from, struct sockaddr *from_addr, int datagram_reply) { krb5_context context = r->context; krb5_kdc_configuration *config = r->config; KDC_REQ *req = &r->req; KDC_REQ_BODY *b = NULL; AS_REP rep; KDCOptions f; krb5_enctype setype; krb5_error_code ret = 0; Key *skey; int found_pa = 0; int i, flags = HDB_F_FOR_AS_REQ; METHOD_DATA error_method; const PA_DATA *pa; memset(&rep, 0, sizeof(rep)); error_method.len = 0; error_method.val = NULL; /* * Look for FAST armor and unwrap */ ret = _kdc_fast_unwrap_request(r); if (ret) { _kdc_r_log(r, 0, ""FAST unwrap request from %s failed: %d"", from, ret); goto out; } b = &req->req_body; f = b->kdc_options; if (f.canonicalize) flags |= HDB_F_CANON; if(b->sname == NULL){ ret = KRB5KRB_ERR_GENERIC; _kdc_set_e_text(r, ""No server in request""); } else{ ret = _krb5_principalname2krb5_principal (context, &r->server_princ, *(b->sname), b->realm); if (ret == 0) ret = krb5_unparse_name(context, r->server_princ, &r->server_name); } if (ret) { kdc_log(context, config, 0, ""AS-REQ malformed server name from %s"", from); goto out; } if(b->cname == NULL){ ret = KRB5KRB_ERR_GENERIC; _kdc_set_e_text(r, ""No client in request""); } else { ret = _krb5_principalname2krb5_principal (context, &r->client_princ, *(b->cname), b->realm); if (ret) goto out; ret = krb5_unparse_name(context, r->client_princ, &r->client_name); } if (ret) { kdc_log(context, config, 0, ""AS-REQ malformed client name from %s"", from); goto out; } kdc_log(context, config, 0, ""AS-REQ %s from %s for %s"", r->client_name, from, r->server_name); /* * */ if (_kdc_is_anonymous(context, r->client_princ)) { if (!_kdc_is_anon_request(b)) { kdc_log(context, config, 0, ""Anonymous ticket w/o anonymous flag""); ret = KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN; goto out; } } else if (_kdc_is_anon_request(b)) { kdc_log(context, config, 0, ""Request for a anonymous ticket with non "" ""anonymous client name: %s"", r->client_name); ret = KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN; goto out; } /* * */ ret = _kdc_db_fetch(context, config, r->client_princ, HDB_F_GET_CLIENT | flags, NULL, &r->clientdb, &r->client); if(ret == HDB_ERR_NOT_FOUND_HERE) { kdc_log(context, config, 5, ""client %s does not have secrets at this KDC, need to proxy"", r->client_name); goto out; } else if (ret == HDB_ERR_WRONG_REALM) { char *fixed_client_name = NULL; ret = krb5_unparse_name(context, r->client->entry.principal, &fixed_client_name); if (ret) { goto out; } kdc_log(context, config, 0, ""WRONG_REALM - %s -> %s"", r->client_name, fixed_client_name); free(fixed_client_name); ret = _kdc_fast_mk_error(context, r, &error_method, r->armor_crypto, &req->req_body, KRB5_KDC_ERR_WRONG_REALM, NULL, r->server_princ, NULL, &r->client->entry.principal->realm, NULL, NULL, reply); goto out; } else if(ret){ const char *msg = krb5_get_error_message(context, ret); kdc_log(context, config, 0, ""UNKNOWN -- %s: %s"", r->client_name, msg); krb5_free_error_message(context, msg); ret = KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN; goto out; } ret = _kdc_db_fetch(context, config, r->server_princ, HDB_F_GET_SERVER|HDB_F_GET_KRBTGT | flags, NULL, NULL, &r->server); if(ret == HDB_ERR_NOT_FOUND_HERE) { kdc_log(context, config, 5, ""target %s does not have secrets at this KDC, need to proxy"", r->server_name); goto out; } else if(ret){ const char *msg = krb5_get_error_message(context, ret); kdc_log(context, config, 0, ""UNKNOWN -- %s: %s"", r->server_name, msg); krb5_free_error_message(context, msg); ret = KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN; goto out; } /* * Select a session enctype from the list of the crypto system * supported enctypes that is supported by the client and is one of * the enctype of the enctype of the service (likely krbtgt). * * The latter is used as a hint of what enctypes all KDC support, * to make sure a newer version of KDC won't generate a session * enctype that an older version of a KDC in the same realm can't * decrypt. */ ret = _kdc_find_etype(context, krb5_principal_is_krbtgt(context, r->server_princ) ? config->tgt_use_strongest_session_key : config->svc_use_strongest_session_key, FALSE, r->client, b->etype.val, b->etype.len, &r->sessionetype, NULL); if (ret) { kdc_log(context, config, 0, ""Client (%s) from %s has no common enctypes with KDC "" ""to use for the session key"", r->client_name, from); goto out; } /* * Pre-auth processing */ if(req->padata){ unsigned int n; log_patypes(context, config, req->padata); /* Check if preauth matching */ for (n = 0; !found_pa && n < sizeof(pat) / sizeof(pat[0]); n++) { if (pat[n].validate == NULL) continue; if (r->armor_crypto == NULL && (pat[n].flags & PA_REQ_FAST)) continue; kdc_log(context, config, 5, ""Looking for %s pa-data -- %s"", pat[n].name, r->client_name); i = 0; pa = _kdc_find_padata(req, &i, pat[n].type); if (pa) { ret = pat[n].validate(r, pa); if (ret != 0) { goto out; } kdc_log(context, config, 0, ""%s pre-authentication succeeded -- %s"", pat[n].name, r->client_name); found_pa = 1; r->et.flags.pre_authent = 1; } } } if (found_pa == 0) { Key *ckey = NULL; size_t n; for (n = 0; n < sizeof(pat) / sizeof(pat[0]); n++) { if ((pat[n].flags & PA_ANNOUNCE) == 0) continue; ret = krb5_padata_add(context, &error_method, pat[n].type, NULL, 0); if (ret) goto out; } /* * If there is a client key, send ETYPE_INFO{,2} */ ret = _kdc_find_etype(context, config->preauth_use_strongest_session_key, TRUE, r->client, b->etype.val, b->etype.len, NULL, &ckey); if (ret == 0) { /* * RFC4120 requires: * - If the client only knows about old enctypes, then send * both info replies (we send 'info' first in the list). * - If the client is 'modern', because it knows about 'new' * enctype types, then only send the 'info2' reply. * * Before we send the full list of etype-info data, we pick * the client key we would have used anyway below, just pick * that instead. */ if (older_enctype(ckey->key.keytype)) { ret = get_pa_etype_info(context, config, &error_method, ckey); if (ret) goto out; } ret = get_pa_etype_info2(context, config, &error_method, ckey); if (ret) goto out; } /* * send requre preauth is its required or anon is requested, * anon is today only allowed via preauth mechanisms. */ if (require_preauth_p(r) || _kdc_is_anon_request(b)) { ret = KRB5KDC_ERR_PREAUTH_REQUIRED; _kdc_set_e_text(r, ""Need to use PA-ENC-TIMESTAMP/PA-PK-AS-REQ""); goto out; } if (ckey == NULL) { ret = KRB5KDC_ERR_CLIENT_NOTYET; _kdc_set_e_text(r, ""Doesn't have a client key available""); goto out; } krb5_free_keyblock_contents(r->context, &r->reply_key); ret = krb5_copy_keyblock_contents(r->context, &ckey->key, &r->reply_key); if (ret) goto out; } if (r->clientdb->hdb_auth_status) { r->clientdb->hdb_auth_status(context, r->clientdb, r->client, HDB_AUTH_SUCCESS); } /* * Verify flags after the user been required to prove its identity * with in a preauth mech. */ ret = _kdc_check_access(context, config, r->client, r->client_name, r->server, r->server_name, req, &error_method); if(ret) goto out; /* * Select the best encryption type for the KDC with out regard to * the client since the client never needs to read that data. */ ret = _kdc_get_preferred_key(context, config, r->server, r->server_name, &setype, &skey); if(ret) goto out; if(f.renew || f.validate || f.proxy || f.forwarded || f.enc_tkt_in_skey || (_kdc_is_anon_request(b) && !config->allow_anonymous)) { ret = KRB5KDC_ERR_BADOPTION; _kdc_set_e_text(r, ""Bad KDC options""); goto out; } /* * Build reply */ rep.pvno = 5; rep.msg_type = krb_as_rep; if (_kdc_is_anonymous(context, r->client_princ)) { Realm anon_realm=KRB5_ANON_REALM; ret = copy_Realm(&anon_realm, &rep.crealm); } else ret = copy_Realm(&r->client->entry.principal->realm, &rep.crealm); if (ret) goto out; ret = _krb5_principal2principalname(&rep.cname, r->client->entry.principal); if (ret) goto out; rep.ticket.tkt_vno = 5; ret = copy_Realm(&r->server->entry.principal->realm, &rep.ticket.realm); if (ret) goto out; _krb5_principal2principalname(&rep.ticket.sname, r->server->entry.principal); /* java 1.6 expects the name to be the same type, lets allow that * uncomplicated name-types. */ #define CNT(sp,t) (((sp)->sname->name_type) == KRB5_NT_##t) if (CNT(b, UNKNOWN) || CNT(b, PRINCIPAL) || CNT(b, SRV_INST) || CNT(b, SRV_HST) || CNT(b, SRV_XHST)) rep.ticket.sname.name_type = b->sname->name_type; #undef CNT r->et.flags.initial = 1; if(r->client->entry.flags.forwardable && r->server->entry.flags.forwardable) r->et.flags.forwardable = f.forwardable; else if (f.forwardable) { _kdc_set_e_text(r, ""Ticket may not be forwardable""); ret = KRB5KDC_ERR_POLICY; goto out; } if(r->client->entry.flags.proxiable && r->server->entry.flags.proxiable) r->et.flags.proxiable = f.proxiable; else if (f.proxiable) { _kdc_set_e_text(r, ""Ticket may not be proxiable""); ret = KRB5KDC_ERR_POLICY; goto out; } if(r->client->entry.flags.postdate && r->server->entry.flags.postdate) r->et.flags.may_postdate = f.allow_postdate; else if (f.allow_postdate){ _kdc_set_e_text(r, ""Ticket may not be postdate""); ret = KRB5KDC_ERR_POLICY; goto out; } /* check for valid set of addresses */ if(!_kdc_check_addresses(context, config, b->addresses, from_addr)) { _kdc_set_e_text(r, ""Bad address list in requested""); ret = KRB5KRB_AP_ERR_BADADDR; goto out; } ret = copy_PrincipalName(&rep.cname, &r->et.cname); if (ret) goto out; ret = copy_Realm(&rep.crealm, &r->et.crealm); if (ret) goto out; { time_t start; time_t t; start = r->et.authtime = kdc_time; if(f.postdated && req->req_body.from){ ALLOC(r->et.starttime); start = *r->et.starttime = *req->req_body.from; r->et.flags.invalid = 1; r->et.flags.postdated = 1; /* XXX ??? */ } _kdc_fix_time(&b->till); t = *b->till; /* be careful not overflowing */ if(r->client->entry.max_life) t = start + min(t - start, *r->client->entry.max_life); if(r->server->entry.max_life) t = start + min(t - start, *r->server->entry.max_life); #if 0 t = min(t, start + realm->max_life); #endif r->et.endtime = t; if(f.renewable_ok && r->et.endtime < *b->till){ f.renewable = 1; if(b->rtime == NULL){ ALLOC(b->rtime); *b->rtime = 0; } if(*b->rtime < *b->till) *b->rtime = *b->till; } if(f.renewable && b->rtime){ t = *b->rtime; if(t == 0) t = MAX_TIME; if(r->client->entry.max_renew) t = start + min(t - start, *r->client->entry.max_renew); if(r->server->entry.max_renew) t = start + min(t - start, *r->server->entry.max_renew); #if 0 t = min(t, start + realm->max_renew); #endif ALLOC(r->et.renew_till); *r->et.renew_till = t; r->et.flags.renewable = 1; } } if (_kdc_is_anon_request(b)) r->et.flags.anonymous = 1; if(b->addresses){ ALLOC(r->et.caddr); copy_HostAddresses(b->addresses, r->et.caddr); } r->et.transited.tr_type = DOMAIN_X500_COMPRESS; krb5_data_zero(&r->et.transited.contents); /* The MIT ASN.1 library (obviously) doesn't tell lengths encoded * as 0 and as 0x80 (meaning indefinite length) apart, and is thus * incapable of correctly decoding SEQUENCE OF's of zero length. * * To fix this, always send at least one no-op last_req * * If there's a pw_end or valid_end we will use that, * otherwise just a dummy lr. */ r->ek.last_req.val = malloc(2 * sizeof(*r->ek.last_req.val)); if (r->ek.last_req.val == NULL) { ret = ENOMEM; goto out; } r->ek.last_req.len = 0; if (r->client->entry.pw_end && (config->kdc_warn_pwexpire == 0 || kdc_time + config->kdc_warn_pwexpire >= *r->client->entry.pw_end)) { r->ek.last_req.val[r->ek.last_req.len].lr_type = LR_PW_EXPTIME; r->ek.last_req.val[r->ek.last_req.len].lr_value = *r->client->entry.pw_end; ++r->ek.last_req.len; } if (r->client->entry.valid_end) { r->ek.last_req.val[r->ek.last_req.len].lr_type = LR_ACCT_EXPTIME; r->ek.last_req.val[r->ek.last_req.len].lr_value = *r->client->entry.valid_end; ++r->ek.last_req.len; } if (r->ek.last_req.len == 0) { r->ek.last_req.val[r->ek.last_req.len].lr_type = LR_NONE; r->ek.last_req.val[r->ek.last_req.len].lr_value = 0; ++r->ek.last_req.len; } r->ek.nonce = b->nonce; if (r->client->entry.valid_end || r->client->entry.pw_end) { ALLOC(r->ek.key_expiration); if (r->client->entry.valid_end) { if (r->client->entry.pw_end) *r->ek.key_expiration = min(*r->client->entry.valid_end, *r->client->entry.pw_end); else *r->ek.key_expiration = *r->client->entry.valid_end; } else *r->ek.key_expiration = *r->client->entry.pw_end; } else r->ek.key_expiration = NULL; r->ek.flags = r->et.flags; r->ek.authtime = r->et.authtime; if (r->et.starttime) { ALLOC(r->ek.starttime); *r->ek.starttime = *r->et.starttime; } r->ek.endtime = r->et.endtime; if (r->et.renew_till) { ALLOC(r->ek.renew_till); *r->ek.renew_till = *r->et.renew_till; } ret = copy_Realm(&rep.ticket.realm, &r->ek.srealm); if (ret) goto out; ret = copy_PrincipalName(&rep.ticket.sname, &r->ek.sname); if (ret) goto out; if(r->et.caddr){ ALLOC(r->ek.caddr); copy_HostAddresses(r->et.caddr, r->ek.caddr); } /* * Check and session and reply keys */ if (r->session_key.keytype == ETYPE_NULL) { ret = krb5_generate_random_keyblock(context, r->sessionetype, &r->session_key); if (ret) goto out; } if (r->reply_key.keytype == ETYPE_NULL) { _kdc_set_e_text(r, ""Client have no reply key""); ret = KRB5KDC_ERR_CLIENT_NOTYET; goto out; } ret = copy_EncryptionKey(&r->session_key, &r->et.key); if (ret) goto out; ret = copy_EncryptionKey(&r->session_key, &r->ek.key); if (ret) goto out; if (r->outpadata.len) { ALLOC(rep.padata); if (rep.padata == NULL) { ret = ENOMEM; goto out; } ret = copy_METHOD_DATA(&r->outpadata, rep.padata); if (ret) goto out; } /* Add the PAC */ if (send_pac_p(context, req)) { generate_pac(r, skey); } _kdc_log_timestamp(context, config, ""AS-REQ"", r->et.authtime, r->et.starttime, r->et.endtime, r->et.renew_till); /* do this as the last thing since this signs the EncTicketPart */ ret = _kdc_add_KRB5SignedPath(context, config, r->server, setype, r->client->entry.principal, NULL, NULL, &r->et); if (ret) goto out; log_as_req(context, config, r->reply_key.keytype, setype, b); /* * We always say we support FAST/enc-pa-rep */ r->et.flags.enc_pa_rep = r->ek.flags.enc_pa_rep = 1; /* * Add REQ_ENC_PA_REP if client supports it */ i = 0; pa = _kdc_find_padata(req, &i, KRB5_PADATA_REQ_ENC_PA_REP); if (pa) { ret = add_enc_pa_rep(r); if (ret) { const char *msg = krb5_get_error_message(r->context, ret); _kdc_r_log(r, 0, ""add_enc_pa_rep failed: %s: %d"", msg, ret); krb5_free_error_message(r->context, msg); goto out; } } /* * */ ret = _kdc_encode_reply(context, config, r->armor_crypto, req->req_body.nonce, &rep, &r->et, &r->ek, setype, r->server->entry.kvno, &skey->key, r->client->entry.kvno, &r->reply_key, 0, &r->e_text, reply); if (ret) goto out; /* * Check if message too large */ if (datagram_reply && reply->length > config->max_datagram_reply_length) { krb5_data_free(reply); ret = KRB5KRB_ERR_RESPONSE_TOO_BIG; _kdc_set_e_text(r, ""Reply packet too large""); } out: free_AS_REP(&rep); /* * In case of a non proxy error, build an error message. */ if(ret != 0 && ret != HDB_ERR_NOT_FOUND_HERE && reply->length == 0) { ret = _kdc_fast_mk_error(context, r, &error_method, r->armor_crypto, &req->req_body, ret, r->e_text, r->server_princ, &r->client_princ->name, &r->client_princ->realm, NULL, NULL, reply); if (ret) goto out2; } out2: free_EncTicketPart(&r->et); free_EncKDCRepPart(&r->ek); free_KDCFastState(&r->fast); if (error_method.len) free_METHOD_DATA(&error_method); if (r->outpadata.len) free_METHOD_DATA(&r->outpadata); if (r->client_princ) { krb5_free_principal(context, r->client_princ); r->client_princ = NULL; } if (r->client_name) { free(r->client_name); r->client_name = NULL; } if (r->server_princ){ krb5_free_principal(context, r->server_princ); r->server_princ = NULL; } if (r->server_name) { free(r->server_name); r->server_name = NULL; } if (r->client) _kdc_free_ent(context, r->client); if (r->server) _kdc_free_ent(context, r->server); if (r->armor_crypto) { krb5_crypto_destroy(r->context, r->armor_crypto); r->armor_crypto = NULL; } krb5_free_keyblock_contents(r->context, &r->reply_key); krb5_free_keyblock_contents(r->context, &r->session_key); return ret; }","_kdc_as_rep(kdc_request_t r, krb5_data *reply, const char *from, struct sockaddr *from_addr, int datagram_reply) { krb5_context context = r->context; krb5_kdc_configuration *config = r->config; KDC_REQ *req = &r->req; KDC_REQ_BODY *b = NULL; AS_REP rep; KDCOptions f; krb5_enctype setype; krb5_error_code ret = 0; Key *skey; int found_pa = 0; int i, flags = HDB_F_FOR_AS_REQ; METHOD_DATA error_method; const PA_DATA *pa; memset(&rep, 0, sizeof(rep)); error_method.len = 0; error_method.val = NULL; /* * Look for FAST armor and unwrap */ ret = _kdc_fast_unwrap_request(r); if (ret) { _kdc_r_log(r, 0, ""FAST unwrap request from %s failed: %d"", from, ret); goto out; } b = &req->req_body; f = b->kdc_options; if (f.canonicalize) flags |= HDB_F_CANON; if(b->sname == NULL){ ret = KRB5KRB_ERR_GENERIC; _kdc_set_e_text(r, ""No server in request""); } else{ ret = _krb5_principalname2krb5_principal (context, &r->server_princ, *(b->sname), b->realm); if (ret == 0) ret = krb5_unparse_name(context, r->server_princ, &r->server_name); } if (ret) { kdc_log(context, config, 0, ""AS-REQ malformed server name from %s"", from); goto out; } if(b->cname == NULL){ ret = KRB5KRB_ERR_GENERIC; _kdc_set_e_text(r, ""No client in request""); } else { ret = _krb5_principalname2krb5_principal (context, &r->client_princ, *(b->cname), b->realm); if (ret) goto out; ret = krb5_unparse_name(context, r->client_princ, &r->client_name); } if (ret) { kdc_log(context, config, 0, ""AS-REQ malformed client name from %s"", from); goto out; } kdc_log(context, config, 0, ""AS-REQ %s from %s for %s"", r->client_name, from, r->server_name); /* * */ if (_kdc_is_anonymous(context, r->client_princ)) { if (!_kdc_is_anon_request(b)) { kdc_log(context, config, 0, ""Anonymous ticket w/o anonymous flag""); ret = KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN; goto out; } } else if (_kdc_is_anon_request(b)) { kdc_log(context, config, 0, ""Request for a anonymous ticket with non "" ""anonymous client name: %s"", r->client_name); ret = KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN; goto out; } /* * */ ret = _kdc_db_fetch(context, config, r->client_princ, HDB_F_GET_CLIENT | flags, NULL, &r->clientdb, &r->client); if(ret == HDB_ERR_NOT_FOUND_HERE) { kdc_log(context, config, 5, ""client %s does not have secrets at this KDC, need to proxy"", r->client_name); goto out; } else if (ret == HDB_ERR_WRONG_REALM) { char *fixed_client_name = NULL; ret = krb5_unparse_name(context, r->client->entry.principal, &fixed_client_name); if (ret) { goto out; } kdc_log(context, config, 0, ""WRONG_REALM - %s -> %s"", r->client_name, fixed_client_name); free(fixed_client_name); ret = _kdc_fast_mk_error(context, r, &error_method, r->armor_crypto, &req->req_body, KRB5_KDC_ERR_WRONG_REALM, NULL, r->server_princ, NULL, &r->client->entry.principal->realm, NULL, NULL, reply); goto out; } else if(ret){ const char *msg = krb5_get_error_message(context, ret); kdc_log(context, config, 0, ""UNKNOWN -- %s: %s"", r->client_name, msg); krb5_free_error_message(context, msg); ret = KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN; goto out; } ret = _kdc_db_fetch(context, config, r->server_princ, HDB_F_GET_SERVER|HDB_F_GET_KRBTGT | flags, NULL, NULL, &r->server); if(ret == HDB_ERR_NOT_FOUND_HERE) { kdc_log(context, config, 5, ""target %s does not have secrets at this KDC, need to proxy"", r->server_name); goto out; } else if(ret){ const char *msg = krb5_get_error_message(context, ret); kdc_log(context, config, 0, ""UNKNOWN -- %s: %s"", r->server_name, msg); krb5_free_error_message(context, msg); ret = KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN; goto out; } /* * Select a session enctype from the list of the crypto system * supported enctypes that is supported by the client and is one of * the enctype of the enctype of the service (likely krbtgt). * * The latter is used as a hint of what enctypes all KDC support, * to make sure a newer version of KDC won't generate a session * enctype that an older version of a KDC in the same realm can't * decrypt. */ ret = _kdc_find_etype(context, krb5_principal_is_krbtgt(context, r->server_princ) ? config->tgt_use_strongest_session_key : config->svc_use_strongest_session_key, FALSE, r->client, b->etype.val, b->etype.len, &r->sessionetype, NULL); if (ret) { kdc_log(context, config, 0, ""Client (%s) from %s has no common enctypes with KDC "" ""to use for the session key"", r->client_name, from); goto out; } /* * Pre-auth processing */ if(req->padata){ unsigned int n; log_patypes(context, config, req->padata); /* Check if preauth matching */ for (n = 0; !found_pa && n < sizeof(pat) / sizeof(pat[0]); n++) { if (pat[n].validate == NULL) continue; if (r->armor_crypto == NULL && (pat[n].flags & PA_REQ_FAST)) continue; kdc_log(context, config, 5, ""Looking for %s pa-data -- %s"", pat[n].name, r->client_name); i = 0; pa = _kdc_find_padata(req, &i, pat[n].type); if (pa) { ret = pat[n].validate(r, pa); if (ret != 0) { goto out; } kdc_log(context, config, 0, ""%s pre-authentication succeeded -- %s"", pat[n].name, r->client_name); found_pa = 1; r->et.flags.pre_authent = 1; } } } if (found_pa == 0) { Key *ckey = NULL; size_t n; for (n = 0; n < sizeof(pat) / sizeof(pat[0]); n++) { if ((pat[n].flags & PA_ANNOUNCE) == 0) continue; ret = krb5_padata_add(context, &error_method, pat[n].type, NULL, 0); if (ret) goto out; } /* * If there is a client key, send ETYPE_INFO{,2} */ ret = _kdc_find_etype(context, config->preauth_use_strongest_session_key, TRUE, r->client, b->etype.val, b->etype.len, NULL, &ckey); if (ret == 0) { /* * RFC4120 requires: * - If the client only knows about old enctypes, then send * both info replies (we send 'info' first in the list). * - If the client is 'modern', because it knows about 'new' * enctype types, then only send the 'info2' reply. * * Before we send the full list of etype-info data, we pick * the client key we would have used anyway below, just pick * that instead. */ if (older_enctype(ckey->key.keytype)) { ret = get_pa_etype_info(context, config, &error_method, ckey); if (ret) goto out; } ret = get_pa_etype_info2(context, config, &error_method, ckey); if (ret) goto out; } /* * send requre preauth is its required or anon is requested, * anon is today only allowed via preauth mechanisms. */ if (require_preauth_p(r) || _kdc_is_anon_request(b)) { ret = KRB5KDC_ERR_PREAUTH_REQUIRED; _kdc_set_e_text(r, ""Need to use PA-ENC-TIMESTAMP/PA-PK-AS-REQ""); goto out; } if (ckey == NULL) { ret = KRB5KDC_ERR_CLIENT_NOTYET; _kdc_set_e_text(r, ""Doesn't have a client key available""); goto out; } krb5_free_keyblock_contents(r->context, &r->reply_key); ret = krb5_copy_keyblock_contents(r->context, &ckey->key, &r->reply_key); if (ret) goto out; } if (r->clientdb->hdb_auth_status) { r->clientdb->hdb_auth_status(context, r->clientdb, r->client, HDB_AUTH_SUCCESS); } /* * Verify flags after the user been required to prove its identity * with in a preauth mech. */ ret = _kdc_check_access(context, config, r->client, r->client_name, r->server, r->server_name, req, &error_method); if(ret) goto out; /* * Select the best encryption type for the KDC with out regard to * the client since the client never needs to read that data. */ ret = _kdc_get_preferred_key(context, config, r->server, r->server_name, &setype, &skey); if(ret) goto out; if(f.renew || f.validate || f.proxy || f.forwarded || f.enc_tkt_in_skey || (_kdc_is_anon_request(b) && !config->allow_anonymous)) { ret = KRB5KDC_ERR_BADOPTION; _kdc_set_e_text(r, ""Bad KDC options""); goto out; } /* * Build reply */ rep.pvno = 5; rep.msg_type = krb_as_rep; if (_kdc_is_anonymous(context, r->client_princ)) { Realm anon_realm=KRB5_ANON_REALM; ret = copy_Realm(&anon_realm, &rep.crealm); } else ret = copy_Realm(&r->client->entry.principal->realm, &rep.crealm); if (ret) goto out; ret = _krb5_principal2principalname(&rep.cname, r->client->entry.principal); if (ret) goto out; rep.ticket.tkt_vno = 5; ret = copy_Realm(&r->server->entry.principal->realm, &rep.ticket.realm); if (ret) goto out; _krb5_principal2principalname(&rep.ticket.sname, r->server->entry.principal); /* java 1.6 expects the name to be the same type, lets allow that * uncomplicated name-types. */ #define CNT(sp,t) (((sp)->sname->name_type) == KRB5_NT_##t) if (CNT(b, UNKNOWN) || CNT(b, PRINCIPAL) || CNT(b, SRV_INST) || CNT(b, SRV_HST) || CNT(b, SRV_XHST)) rep.ticket.sname.name_type = b->sname->name_type; #undef CNT r->et.flags.initial = 1; if(r->client->entry.flags.forwardable && r->server->entry.flags.forwardable) r->et.flags.forwardable = f.forwardable; else if (f.forwardable) { _kdc_set_e_text(r, ""Ticket may not be forwardable""); ret = KRB5KDC_ERR_POLICY; goto out; } if(r->client->entry.flags.proxiable && r->server->entry.flags.proxiable) r->et.flags.proxiable = f.proxiable; else if (f.proxiable) { _kdc_set_e_text(r, ""Ticket may not be proxiable""); ret = KRB5KDC_ERR_POLICY; goto out; } if(r->client->entry.flags.postdate && r->server->entry.flags.postdate) r->et.flags.may_postdate = f.allow_postdate; else if (f.allow_postdate){ _kdc_set_e_text(r, ""Ticket may not be postdate""); ret = KRB5KDC_ERR_POLICY; goto out; } /* check for valid set of addresses */ if(!_kdc_check_addresses(context, config, b->addresses, from_addr)) { _kdc_set_e_text(r, ""Bad address list in requested""); ret = KRB5KRB_AP_ERR_BADADDR; goto out; } ret = copy_PrincipalName(&rep.cname, &r->et.cname); if (ret) goto out; ret = copy_Realm(&rep.crealm, &r->et.crealm); if (ret) goto out; { time_t start; time_t t; start = r->et.authtime = kdc_time; if(f.postdated && req->req_body.from){ ALLOC(r->et.starttime); start = *r->et.starttime = *req->req_body.from; r->et.flags.invalid = 1; r->et.flags.postdated = 1; /* XXX ??? */ } _kdc_fix_time(&b->till); t = *b->till; /* be careful not overflowing */ if(r->client->entry.max_life) t = start + min(t - start, *r->client->entry.max_life); if(r->server->entry.max_life) t = start + min(t - start, *r->server->entry.max_life); #if 0 t = min(t, start + realm->max_life); #endif r->et.endtime = t; if(f.renewable_ok && r->et.endtime < *b->till){ f.renewable = 1; if(b->rtime == NULL){ ALLOC(b->rtime); *b->rtime = 0; } if(*b->rtime < *b->till) *b->rtime = *b->till; } if(f.renewable && b->rtime){ t = *b->rtime; if(t == 0) t = MAX_TIME; if(r->client->entry.max_renew) t = start + min(t - start, *r->client->entry.max_renew); if(r->server->entry.max_renew) t = start + min(t - start, *r->server->entry.max_renew); #if 0 t = min(t, start + realm->max_renew); #endif ALLOC(r->et.renew_till); *r->et.renew_till = t; r->et.flags.renewable = 1; } } if (_kdc_is_anon_request(b)) r->et.flags.anonymous = 1; if(b->addresses){ ALLOC(r->et.caddr); copy_HostAddresses(b->addresses, r->et.caddr); } r->et.transited.tr_type = DOMAIN_X500_COMPRESS; krb5_data_zero(&r->et.transited.contents); /* The MIT ASN.1 library (obviously) doesn't tell lengths encoded * as 0 and as 0x80 (meaning indefinite length) apart, and is thus * incapable of correctly decoding SEQUENCE OF's of zero length. * * To fix this, always send at least one no-op last_req * * If there's a pw_end or valid_end we will use that, * otherwise just a dummy lr. */ r->ek.last_req.val = malloc(2 * sizeof(*r->ek.last_req.val)); if (r->ek.last_req.val == NULL) { ret = ENOMEM; goto out; } r->ek.last_req.len = 0; if (r->client->entry.pw_end && (config->kdc_warn_pwexpire == 0 || kdc_time + config->kdc_warn_pwexpire >= *r->client->entry.pw_end)) { r->ek.last_req.val[r->ek.last_req.len].lr_type = LR_PW_EXPTIME; r->ek.last_req.val[r->ek.last_req.len].lr_value = *r->client->entry.pw_end; ++r->ek.last_req.len; } if (r->client->entry.valid_end) { r->ek.last_req.val[r->ek.last_req.len].lr_type = LR_ACCT_EXPTIME; r->ek.last_req.val[r->ek.last_req.len].lr_value = *r->client->entry.valid_end; ++r->ek.last_req.len; } if (r->ek.last_req.len == 0) { r->ek.last_req.val[r->ek.last_req.len].lr_type = LR_NONE; r->ek.last_req.val[r->ek.last_req.len].lr_value = 0; ++r->ek.last_req.len; } r->ek.nonce = b->nonce; if (r->client->entry.valid_end || r->client->entry.pw_end) { ALLOC(r->ek.key_expiration); if (r->client->entry.valid_end) { if (r->client->entry.pw_end) *r->ek.key_expiration = min(*r->client->entry.valid_end, *r->client->entry.pw_end); else *r->ek.key_expiration = *r->client->entry.valid_end; } else *r->ek.key_expiration = *r->client->entry.pw_end; } else r->ek.key_expiration = NULL; r->ek.flags = r->et.flags; r->ek.authtime = r->et.authtime; if (r->et.starttime) { ALLOC(r->ek.starttime); *r->ek.starttime = *r->et.starttime; } r->ek.endtime = r->et.endtime; if (r->et.renew_till) { ALLOC(r->ek.renew_till); *r->ek.renew_till = *r->et.renew_till; } ret = copy_Realm(&rep.ticket.realm, &r->ek.srealm); if (ret) goto out; ret = copy_PrincipalName(&rep.ticket.sname, &r->ek.sname); if (ret) goto out; if(r->et.caddr){ ALLOC(r->ek.caddr); copy_HostAddresses(r->et.caddr, r->ek.caddr); } /* * Check and session and reply keys */ if (r->session_key.keytype == ETYPE_NULL) { ret = krb5_generate_random_keyblock(context, r->sessionetype, &r->session_key); if (ret) goto out; } if (r->reply_key.keytype == ETYPE_NULL) { _kdc_set_e_text(r, ""Client have no reply key""); ret = KRB5KDC_ERR_CLIENT_NOTYET; goto out; } ret = copy_EncryptionKey(&r->session_key, &r->et.key); if (ret) goto out; ret = copy_EncryptionKey(&r->session_key, &r->ek.key); if (ret) goto out; if (r->outpadata.len) { ALLOC(rep.padata); if (rep.padata == NULL) { ret = ENOMEM; goto out; } ret = copy_METHOD_DATA(&r->outpadata, rep.padata); if (ret) goto out; } /* Add the PAC */ if (send_pac_p(context, req)) { generate_pac(r, skey); } _kdc_log_timestamp(context, config, ""AS-REQ"", r->et.authtime, r->et.starttime, r->et.endtime, r->et.renew_till); /* do this as the last thing since this signs the EncTicketPart */ ret = _kdc_add_KRB5SignedPath(context, config, r->server, setype, r->client->entry.principal, NULL, NULL, &r->et); if (ret) goto out; log_as_req(context, config, r->reply_key.keytype, setype, b); /* * We always say we support FAST/enc-pa-rep */ r->et.flags.enc_pa_rep = r->ek.flags.enc_pa_rep = 1; /* * Add REQ_ENC_PA_REP if client supports it */ i = 0; pa = _kdc_find_padata(req, &i, KRB5_PADATA_REQ_ENC_PA_REP); if (pa) { ret = add_enc_pa_rep(r); if (ret) { const char *msg = krb5_get_error_message(r->context, ret); _kdc_r_log(r, 0, ""add_enc_pa_rep failed: %s: %d"", msg, ret); krb5_free_error_message(r->context, msg); goto out; } } /* * */ ret = _kdc_encode_reply(context, config, r->armor_crypto, req->req_body.nonce, &rep, &r->et, &r->ek, setype, r->server->entry.kvno, &skey->key, r->client->entry.kvno, &r->reply_key, 0, &r->e_text, reply); if (ret) goto out; /* * Check if message too large */ if (datagram_reply && reply->length > config->max_datagram_reply_length) { krb5_data_free(reply); ret = KRB5KRB_ERR_RESPONSE_TOO_BIG; _kdc_set_e_text(r, ""Reply packet too large""); } out: free_AS_REP(&rep); /* * In case of a non proxy error, build an error message. */ if (ret != 0 && ret != HDB_ERR_NOT_FOUND_HERE && reply->length == 0) { ret = _kdc_fast_mk_error(context, r, &error_method, r->armor_crypto, &req->req_body, ret, r->e_text, r->server_princ, r->client_princ ? &r->client_princ->name : NULL, r->client_princ ? &r->client_princ->realm : NULL, NULL, NULL, reply); if (ret) goto out2; } out2: free_EncTicketPart(&r->et); free_EncKDCRepPart(&r->ek); free_KDCFastState(&r->fast); if (error_method.len) free_METHOD_DATA(&error_method); if (r->outpadata.len) free_METHOD_DATA(&r->outpadata); if (r->client_princ) { krb5_free_principal(context, r->client_princ); r->client_princ = NULL; } if (r->client_name) { free(r->client_name); r->client_name = NULL; } if (r->server_princ){ krb5_free_principal(context, r->server_princ); r->server_princ = NULL; } if (r->server_name) { free(r->server_name); r->server_name = NULL; } if (r->client) _kdc_free_ent(context, r->client); if (r->server) _kdc_free_ent(context, r->server); if (r->armor_crypto) { krb5_crypto_destroy(r->context, r->armor_crypto); r->armor_crypto = NULL; } krb5_free_keyblock_contents(r->context, &r->reply_key); krb5_free_keyblock_contents(r->context, &r->session_key); return ret; }","{'deleted': [{'line_no': 619, 'char_start': 16727, 'char_end': 16801, 'line': ' if(ret != 0 && ret != HDB_ERR_NOT_FOUND_HERE && reply->length == 0) {\n'}, {'line_no': 626, 'char_start': 16945, 'char_end': 16974, 'line': '\t\t\t\t &r->client_princ->name,\n'}, {'line_no': 627, 'char_start': 16974, 'char_end': 17004, 'line': '\t\t\t\t &r->client_princ->realm,\n'}], 'added': [{'line_no': 619, 'char_start': 16727, 'char_end': 16802, 'line': ' if (ret != 0 && ret != HDB_ERR_NOT_FOUND_HERE && reply->length == 0) {\n'}, {'line_no': 626, 'char_start': 16946, 'char_end': 16969, 'line': '\t\t\t\t r->client_princ ?\n'}, {'line_no': 627, 'char_start': 16969, 'char_end': 17037, 'line': ' &r->client_princ->name : NULL,\n'}, {'line_no': 628, 'char_start': 17037, 'char_end': 17060, 'line': '\t\t\t\t r->client_princ ?\n'}, {'line_no': 629, 'char_start': 17060, 'char_end': 17129, 'line': ' &r->client_princ->realm : NULL,\n'}]}","{'deleted': [], 'added': [{'char_start': 16733, 'char_end': 16734, 'chars': ' '}, {'char_start': 16951, 'char_end': 17006, 'chars': 'r->client_princ ?\n '}, {'char_start': 17028, 'char_end': 17035, 'chars': ' : NULL'}, {'char_start': 17042, 'char_end': 17097, 'chars': 'r->client_princ ?\n '}, {'char_start': 17120, 'char_end': 17127, 'chars': ' : NULL'}]}",github.com/heimdal/heimdal/commit/1a6a6e462dc2ac6111f9e02c6852ddec4849b887,kdc/kerberos5.c,cwe-476,5675 cwe-078,_get_host_from_connector," def _get_host_from_connector(self, connector): """"""List the hosts defined in the storage. Return the host name with the given connection info, or None if there is no host fitting that information. """""" prefix = self._connector_to_hostname_prefix(connector) LOG.debug(_('enter: _get_host_from_connector: prefix %s') % prefix) # Get list of host in the storage ssh_cmd = 'svcinfo lshost -delim !' out, err = self._run_ssh(ssh_cmd) if not len(out.strip()): return None # If we have FC information, we have a faster lookup option hostname = None if 'wwpns' in connector: hostname = self._find_host_from_wwpn(connector) # If we don't have a hostname yet, try the long way if not hostname: host_lines = out.strip().split('\n') self._assert_ssh_return(len(host_lines), '_get_host_from_connector', ssh_cmd, out, err) header = host_lines.pop(0).split('!') self._assert_ssh_return('name' in header, '_get_host_from_connector', ssh_cmd, out, err) name_index = header.index('name') hosts = map(lambda x: x.split('!')[name_index], host_lines) hostname = self._find_host_exhaustive(connector, hosts) LOG.debug(_('leave: _get_host_from_connector: host %s') % hostname) return hostname"," def _get_host_from_connector(self, connector): """"""List the hosts defined in the storage. Return the host name with the given connection info, or None if there is no host fitting that information. """""" prefix = self._connector_to_hostname_prefix(connector) LOG.debug(_('enter: _get_host_from_connector: prefix %s') % prefix) # Get list of host in the storage ssh_cmd = ['svcinfo', 'lshost', '-delim', '!'] out, err = self._run_ssh(ssh_cmd) if not len(out.strip()): return None # If we have FC information, we have a faster lookup option hostname = None if 'wwpns' in connector: hostname = self._find_host_from_wwpn(connector) # If we don't have a hostname yet, try the long way if not hostname: host_lines = out.strip().split('\n') self._assert_ssh_return(len(host_lines), '_get_host_from_connector', ssh_cmd, out, err) header = host_lines.pop(0).split('!') self._assert_ssh_return('name' in header, '_get_host_from_connector', ssh_cmd, out, err) name_index = header.index('name') hosts = map(lambda x: x.split('!')[name_index], host_lines) hostname = self._find_host_exhaustive(connector, hosts) LOG.debug(_('leave: _get_host_from_connector: host %s') % hostname) return hostname","{'deleted': [{'line_no': 13, 'char_start': 421, 'char_end': 465, 'line': "" ssh_cmd = 'svcinfo lshost -delim !'\n""}], 'added': [{'line_no': 13, 'char_start': 421, 'char_end': 476, 'line': "" ssh_cmd = ['svcinfo', 'lshost', '-delim', '!']\n""}]}","{'deleted': [], 'added': [{'char_start': 439, 'char_end': 440, 'chars': '['}, {'char_start': 448, 'char_end': 450, 'chars': ""',""}, {'char_start': 451, 'char_end': 452, 'chars': ""'""}, {'char_start': 458, 'char_end': 460, 'chars': ""',""}, {'char_start': 461, 'char_end': 462, 'chars': ""'""}, {'char_start': 468, 'char_end': 470, 'chars': ""',""}, {'char_start': 471, 'char_end': 472, 'chars': ""'""}, {'char_start': 474, 'char_end': 475, 'chars': ']'}]}",github.com/thatsdone/cinder/commit/f752302d181583a95cf44354aea607ce9d9283f4,cinder/volume/drivers/storwize_svc.py,cwe-078,331 cwe-125,adjust_scalar_min_max_vals,"static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env, struct bpf_insn *insn, struct bpf_reg_state *dst_reg, struct bpf_reg_state src_reg) { struct bpf_reg_state *regs = cur_regs(env); u8 opcode = BPF_OP(insn->code); bool src_known, dst_known; s64 smin_val, smax_val; u64 umin_val, umax_val; u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32; smin_val = src_reg.smin_value; smax_val = src_reg.smax_value; umin_val = src_reg.umin_value; umax_val = src_reg.umax_value; src_known = tnum_is_const(src_reg.var_off); dst_known = tnum_is_const(dst_reg->var_off); if ((src_known && (smin_val != smax_val || umin_val != umax_val)) || smin_val > smax_val || umin_val > umax_val) { /* Taint dst register if offset had invalid bounds derived from * e.g. dead branches. */ __mark_reg_unknown(dst_reg); return 0; } if (!src_known && opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) { __mark_reg_unknown(dst_reg); return 0; } switch (opcode) { case BPF_ADD: if (signed_add_overflows(dst_reg->smin_value, smin_val) || signed_add_overflows(dst_reg->smax_value, smax_val)) { dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; } else { dst_reg->smin_value += smin_val; dst_reg->smax_value += smax_val; } if (dst_reg->umin_value + umin_val < umin_val || dst_reg->umax_value + umax_val < umax_val) { dst_reg->umin_value = 0; dst_reg->umax_value = U64_MAX; } else { dst_reg->umin_value += umin_val; dst_reg->umax_value += umax_val; } dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off); break; case BPF_SUB: if (signed_sub_overflows(dst_reg->smin_value, smax_val) || signed_sub_overflows(dst_reg->smax_value, smin_val)) { /* Overflow possible, we know nothing */ dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; } else { dst_reg->smin_value -= smax_val; dst_reg->smax_value -= smin_val; } if (dst_reg->umin_value < umax_val) { /* Overflow possible, we know nothing */ dst_reg->umin_value = 0; dst_reg->umax_value = U64_MAX; } else { /* Cannot overflow (as long as bounds are consistent) */ dst_reg->umin_value -= umax_val; dst_reg->umax_value -= umin_val; } dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off); break; case BPF_MUL: dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off); if (smin_val < 0 || dst_reg->smin_value < 0) { /* Ain't nobody got time to multiply that sign */ __mark_reg_unbounded(dst_reg); __update_reg_bounds(dst_reg); break; } /* Both values are positive, so we can work with unsigned and * copy the result to signed (unless it exceeds S64_MAX). */ if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) { /* Potential overflow, we know nothing */ __mark_reg_unbounded(dst_reg); /* (except what we can learn from the var_off) */ __update_reg_bounds(dst_reg); break; } dst_reg->umin_value *= umin_val; dst_reg->umax_value *= umax_val; if (dst_reg->umax_value > S64_MAX) { /* Overflow possible, we know nothing */ dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; } else { dst_reg->smin_value = dst_reg->umin_value; dst_reg->smax_value = dst_reg->umax_value; } break; case BPF_AND: if (src_known && dst_known) { __mark_reg_known(dst_reg, dst_reg->var_off.value & src_reg.var_off.value); break; } /* We get our minimum from the var_off, since that's inherently * bitwise. Our maximum is the minimum of the operands' maxima. */ dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off); dst_reg->umin_value = dst_reg->var_off.value; dst_reg->umax_value = min(dst_reg->umax_value, umax_val); if (dst_reg->smin_value < 0 || smin_val < 0) { /* Lose signed bounds when ANDing negative numbers, * ain't nobody got time for that. */ dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; } else { /* ANDing two positives gives a positive, so safe to * cast result into s64. */ dst_reg->smin_value = dst_reg->umin_value; dst_reg->smax_value = dst_reg->umax_value; } /* We may learn something more from the var_off */ __update_reg_bounds(dst_reg); break; case BPF_OR: if (src_known && dst_known) { __mark_reg_known(dst_reg, dst_reg->var_off.value | src_reg.var_off.value); break; } /* We get our maximum from the var_off, and our minimum is the * maximum of the operands' minima */ dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off); dst_reg->umin_value = max(dst_reg->umin_value, umin_val); dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask; if (dst_reg->smin_value < 0 || smin_val < 0) { /* Lose signed bounds when ORing negative numbers, * ain't nobody got time for that. */ dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; } else { /* ORing two positives gives a positive, so safe to * cast result into s64. */ dst_reg->smin_value = dst_reg->umin_value; dst_reg->smax_value = dst_reg->umax_value; } /* We may learn something more from the var_off */ __update_reg_bounds(dst_reg); break; case BPF_LSH: if (umax_val >= insn_bitness) { /* Shifts greater than 31 or 63 are undefined. * This includes shifts by a negative number. */ mark_reg_unknown(env, regs, insn->dst_reg); break; } /* We lose all sign bit information (except what we can pick * up from var_off) */ dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; /* If we might shift our top bit out, then we know nothing */ if (dst_reg->umax_value > 1ULL << (63 - umax_val)) { dst_reg->umin_value = 0; dst_reg->umax_value = U64_MAX; } else { dst_reg->umin_value <<= umin_val; dst_reg->umax_value <<= umax_val; } dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val); /* We may learn something more from the var_off */ __update_reg_bounds(dst_reg); break; case BPF_RSH: if (umax_val >= insn_bitness) { /* Shifts greater than 31 or 63 are undefined. * This includes shifts by a negative number. */ mark_reg_unknown(env, regs, insn->dst_reg); break; } /* BPF_RSH is an unsigned shift. If the value in dst_reg might * be negative, then either: * 1) src_reg might be zero, so the sign bit of the result is * unknown, so we lose our signed bounds * 2) it's known negative, thus the unsigned bounds capture the * signed bounds * 3) the signed bounds cross zero, so they tell us nothing * about the result * If the value in dst_reg is known nonnegative, then again the * unsigned bounts capture the signed bounds. * Thus, in all cases it suffices to blow away our signed bounds * and rely on inferring new ones from the unsigned bounds and * var_off of the result. */ dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val); dst_reg->umin_value >>= umax_val; dst_reg->umax_value >>= umin_val; /* We may learn something more from the var_off */ __update_reg_bounds(dst_reg); break; case BPF_ARSH: if (umax_val >= insn_bitness) { /* Shifts greater than 31 or 63 are undefined. * This includes shifts by a negative number. */ mark_reg_unknown(env, regs, insn->dst_reg); break; } /* Upon reaching here, src_known is true and * umax_val is equal to umin_val. */ dst_reg->smin_value >>= umin_val; dst_reg->smax_value >>= umin_val; dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val); /* blow away the dst_reg umin_value/umax_value and rely on * dst_reg var_off to refine the result. */ dst_reg->umin_value = 0; dst_reg->umax_value = U64_MAX; __update_reg_bounds(dst_reg); break; default: mark_reg_unknown(env, regs, insn->dst_reg); break; } if (BPF_CLASS(insn->code) != BPF_ALU64) { /* 32-bit ALU ops are (32,32)->32 */ coerce_reg_to_size(dst_reg, 4); coerce_reg_to_size(&src_reg, 4); } __reg_deduce_bounds(dst_reg); __reg_bound_offset(dst_reg); return 0; }","static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env, struct bpf_insn *insn, struct bpf_reg_state *dst_reg, struct bpf_reg_state src_reg) { struct bpf_reg_state *regs = cur_regs(env); u8 opcode = BPF_OP(insn->code); bool src_known, dst_known; s64 smin_val, smax_val; u64 umin_val, umax_val; u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32; if (insn_bitness == 32) { /* Relevant for 32-bit RSH: Information can propagate towards * LSB, so it isn't sufficient to only truncate the output to * 32 bits. */ coerce_reg_to_size(dst_reg, 4); coerce_reg_to_size(&src_reg, 4); } smin_val = src_reg.smin_value; smax_val = src_reg.smax_value; umin_val = src_reg.umin_value; umax_val = src_reg.umax_value; src_known = tnum_is_const(src_reg.var_off); dst_known = tnum_is_const(dst_reg->var_off); if ((src_known && (smin_val != smax_val || umin_val != umax_val)) || smin_val > smax_val || umin_val > umax_val) { /* Taint dst register if offset had invalid bounds derived from * e.g. dead branches. */ __mark_reg_unknown(dst_reg); return 0; } if (!src_known && opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) { __mark_reg_unknown(dst_reg); return 0; } switch (opcode) { case BPF_ADD: if (signed_add_overflows(dst_reg->smin_value, smin_val) || signed_add_overflows(dst_reg->smax_value, smax_val)) { dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; } else { dst_reg->smin_value += smin_val; dst_reg->smax_value += smax_val; } if (dst_reg->umin_value + umin_val < umin_val || dst_reg->umax_value + umax_val < umax_val) { dst_reg->umin_value = 0; dst_reg->umax_value = U64_MAX; } else { dst_reg->umin_value += umin_val; dst_reg->umax_value += umax_val; } dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off); break; case BPF_SUB: if (signed_sub_overflows(dst_reg->smin_value, smax_val) || signed_sub_overflows(dst_reg->smax_value, smin_val)) { /* Overflow possible, we know nothing */ dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; } else { dst_reg->smin_value -= smax_val; dst_reg->smax_value -= smin_val; } if (dst_reg->umin_value < umax_val) { /* Overflow possible, we know nothing */ dst_reg->umin_value = 0; dst_reg->umax_value = U64_MAX; } else { /* Cannot overflow (as long as bounds are consistent) */ dst_reg->umin_value -= umax_val; dst_reg->umax_value -= umin_val; } dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off); break; case BPF_MUL: dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off); if (smin_val < 0 || dst_reg->smin_value < 0) { /* Ain't nobody got time to multiply that sign */ __mark_reg_unbounded(dst_reg); __update_reg_bounds(dst_reg); break; } /* Both values are positive, so we can work with unsigned and * copy the result to signed (unless it exceeds S64_MAX). */ if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) { /* Potential overflow, we know nothing */ __mark_reg_unbounded(dst_reg); /* (except what we can learn from the var_off) */ __update_reg_bounds(dst_reg); break; } dst_reg->umin_value *= umin_val; dst_reg->umax_value *= umax_val; if (dst_reg->umax_value > S64_MAX) { /* Overflow possible, we know nothing */ dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; } else { dst_reg->smin_value = dst_reg->umin_value; dst_reg->smax_value = dst_reg->umax_value; } break; case BPF_AND: if (src_known && dst_known) { __mark_reg_known(dst_reg, dst_reg->var_off.value & src_reg.var_off.value); break; } /* We get our minimum from the var_off, since that's inherently * bitwise. Our maximum is the minimum of the operands' maxima. */ dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off); dst_reg->umin_value = dst_reg->var_off.value; dst_reg->umax_value = min(dst_reg->umax_value, umax_val); if (dst_reg->smin_value < 0 || smin_val < 0) { /* Lose signed bounds when ANDing negative numbers, * ain't nobody got time for that. */ dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; } else { /* ANDing two positives gives a positive, so safe to * cast result into s64. */ dst_reg->smin_value = dst_reg->umin_value; dst_reg->smax_value = dst_reg->umax_value; } /* We may learn something more from the var_off */ __update_reg_bounds(dst_reg); break; case BPF_OR: if (src_known && dst_known) { __mark_reg_known(dst_reg, dst_reg->var_off.value | src_reg.var_off.value); break; } /* We get our maximum from the var_off, and our minimum is the * maximum of the operands' minima */ dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off); dst_reg->umin_value = max(dst_reg->umin_value, umin_val); dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask; if (dst_reg->smin_value < 0 || smin_val < 0) { /* Lose signed bounds when ORing negative numbers, * ain't nobody got time for that. */ dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; } else { /* ORing two positives gives a positive, so safe to * cast result into s64. */ dst_reg->smin_value = dst_reg->umin_value; dst_reg->smax_value = dst_reg->umax_value; } /* We may learn something more from the var_off */ __update_reg_bounds(dst_reg); break; case BPF_LSH: if (umax_val >= insn_bitness) { /* Shifts greater than 31 or 63 are undefined. * This includes shifts by a negative number. */ mark_reg_unknown(env, regs, insn->dst_reg); break; } /* We lose all sign bit information (except what we can pick * up from var_off) */ dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; /* If we might shift our top bit out, then we know nothing */ if (dst_reg->umax_value > 1ULL << (63 - umax_val)) { dst_reg->umin_value = 0; dst_reg->umax_value = U64_MAX; } else { dst_reg->umin_value <<= umin_val; dst_reg->umax_value <<= umax_val; } dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val); /* We may learn something more from the var_off */ __update_reg_bounds(dst_reg); break; case BPF_RSH: if (umax_val >= insn_bitness) { /* Shifts greater than 31 or 63 are undefined. * This includes shifts by a negative number. */ mark_reg_unknown(env, regs, insn->dst_reg); break; } /* BPF_RSH is an unsigned shift. If the value in dst_reg might * be negative, then either: * 1) src_reg might be zero, so the sign bit of the result is * unknown, so we lose our signed bounds * 2) it's known negative, thus the unsigned bounds capture the * signed bounds * 3) the signed bounds cross zero, so they tell us nothing * about the result * If the value in dst_reg is known nonnegative, then again the * unsigned bounts capture the signed bounds. * Thus, in all cases it suffices to blow away our signed bounds * and rely on inferring new ones from the unsigned bounds and * var_off of the result. */ dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val); dst_reg->umin_value >>= umax_val; dst_reg->umax_value >>= umin_val; /* We may learn something more from the var_off */ __update_reg_bounds(dst_reg); break; case BPF_ARSH: if (umax_val >= insn_bitness) { /* Shifts greater than 31 or 63 are undefined. * This includes shifts by a negative number. */ mark_reg_unknown(env, regs, insn->dst_reg); break; } /* Upon reaching here, src_known is true and * umax_val is equal to umin_val. */ dst_reg->smin_value >>= umin_val; dst_reg->smax_value >>= umin_val; dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val); /* blow away the dst_reg umin_value/umax_value and rely on * dst_reg var_off to refine the result. */ dst_reg->umin_value = 0; dst_reg->umax_value = U64_MAX; __update_reg_bounds(dst_reg); break; default: mark_reg_unknown(env, regs, insn->dst_reg); break; } if (BPF_CLASS(insn->code) != BPF_ALU64) { /* 32-bit ALU ops are (32,32)->32 */ coerce_reg_to_size(dst_reg, 4); } __reg_deduce_bounds(dst_reg); __reg_bound_offset(dst_reg); return 0; }","{'deleted': [{'line_no': 248, 'char_start': 8087, 'char_end': 8122, 'line': '\t\tcoerce_reg_to_size(&src_reg, 4);\n'}], 'added': [{'line_no': 13, 'char_start': 409, 'char_end': 436, 'line': '\tif (insn_bitness == 32) {\n'}, {'line_no': 14, 'char_start': 436, 'char_end': 500, 'line': '\t\t/* Relevant for 32-bit RSH: Information can propagate towards\n'}, {'line_no': 15, 'char_start': 500, 'char_end': 564, 'line': ""\t\t * LSB, so it isn't sufficient to only truncate the output to\n""}, {'line_no': 16, 'char_start': 564, 'char_end': 578, 'line': '\t\t * 32 bits.\n'}, {'line_no': 17, 'char_start': 578, 'char_end': 584, 'line': '\t\t */\n'}, {'line_no': 18, 'char_start': 584, 'char_end': 618, 'line': '\t\tcoerce_reg_to_size(dst_reg, 4);\n'}, {'line_no': 19, 'char_start': 618, 'char_end': 653, 'line': '\t\tcoerce_reg_to_size(&src_reg, 4);\n'}, {'line_no': 20, 'char_start': 653, 'char_end': 656, 'line': '\t}\n'}, {'line_no': 21, 'char_start': 656, 'char_end': 657, 'line': '\n'}]}","{'deleted': [{'char_start': 8077, 'char_end': 8112, 'chars': '_reg, 4);\n\t\tcoerce_reg_to_size(&src'}], 'added': [{'char_start': 410, 'char_end': 658, 'chars': ""if (insn_bitness == 32) {\n\t\t/* Relevant for 32-bit RSH: Information can propagate towards\n\t\t * LSB, so it isn't sufficient to only truncate the output to\n\t\t * 32 bits.\n\t\t */\n\t\tcoerce_reg_to_size(dst_reg, 4);\n\t\tcoerce_reg_to_size(&src_reg, 4);\n\t}\n\n\t""}]}",github.com/torvalds/linux/commit/b799207e1e1816b09e7a5920fbb2d5fcf6edd681,kernel/bpf/verifier.c,cwe-125,2575 cwe-079,Logger::addPeer,"void Logger::addPeer(const QString &ip, bool blocked, const QString &reason) { QWriteLocker locker(&lock); Log::Peer temp = { peerCounter++, QDateTime::currentMSecsSinceEpoch(), ip, blocked, reason }; m_peers.push_back(temp); if (m_peers.size() >= MAX_LOG_MESSAGES) m_peers.pop_front(); emit newLogPeer(temp); }","void Logger::addPeer(const QString &ip, bool blocked, const QString &reason) { QWriteLocker locker(&lock); Log::Peer temp = { peerCounter++, QDateTime::currentMSecsSinceEpoch(), Utils::String::toHtmlEscaped(ip), blocked, Utils::String::toHtmlEscaped(reason) }; m_peers.push_back(temp); if (m_peers.size() >= MAX_LOG_MESSAGES) m_peers.pop_front(); emit newLogPeer(temp); }","{'deleted': [{'line_no': 5, 'char_start': 112, 'char_end': 210, 'line': ' Log::Peer temp = { peerCounter++, QDateTime::currentMSecsSinceEpoch(), ip, blocked, reason };\n'}], 'added': [{'line_no': 5, 'char_start': 112, 'char_end': 270, 'line': ' Log::Peer temp = { peerCounter++, QDateTime::currentMSecsSinceEpoch(), Utils::String::toHtmlEscaped(ip), blocked, Utils::String::toHtmlEscaped(reason) };\n'}]}","{'deleted': [], 'added': [{'char_start': 187, 'char_end': 216, 'chars': 'Utils::String::toHtmlEscaped('}, {'char_start': 218, 'char_end': 219, 'chars': ')'}, {'char_start': 230, 'char_end': 259, 'chars': 'Utils::String::toHtmlEscaped('}, {'char_start': 265, 'char_end': 266, 'chars': ')'}]}",github.com/qbittorrent/qBittorrent/commit/6ca3e4f094da0a0017cb2d483ec1db6176bb0b16,src/base/logger.cpp,cwe-079,87 cwe-125,readContigTilesIntoBuffer,"static int readContigTilesIntoBuffer (TIFF* in, uint8* buf, uint32 imagelength, uint32 imagewidth, uint32 tw, uint32 tl, tsample_t spp, uint16 bps) { int status = 1; tsample_t sample = 0; tsample_t count = spp; uint32 row, col, trow; uint32 nrow, ncol; uint32 dst_rowsize, shift_width; uint32 bytes_per_sample, bytes_per_pixel; uint32 trailing_bits, prev_trailing_bits; uint32 tile_rowsize = TIFFTileRowSize(in); uint32 src_offset, dst_offset; uint32 row_offset, col_offset; uint8 *bufp = (uint8*) buf; unsigned char *src = NULL; unsigned char *dst = NULL; tsize_t tbytes = 0, tile_buffsize = 0; tsize_t tilesize = TIFFTileSize(in); unsigned char *tilebuf = NULL; bytes_per_sample = (bps + 7) / 8; bytes_per_pixel = ((bps * spp) + 7) / 8; if ((bps % 8) == 0) shift_width = 0; else { if (bytes_per_pixel < (bytes_per_sample + 1)) shift_width = bytes_per_pixel; else shift_width = bytes_per_sample + 1; } tile_buffsize = tilesize; if (tilesize == 0 || tile_rowsize == 0) { TIFFError(""readContigTilesIntoBuffer"", ""Tile size or tile rowsize is zero""); exit(-1); } if (tilesize < (tsize_t)(tl * tile_rowsize)) { #ifdef DEBUG2 TIFFError(""readContigTilesIntoBuffer"", ""Tilesize %lu is too small, using alternate calculation %u"", tilesize, tl * tile_rowsize); #endif tile_buffsize = tl * tile_rowsize; if (tl != (tile_buffsize / tile_rowsize)) { TIFFError(""readContigTilesIntoBuffer"", ""Integer overflow when calculating buffer size.""); exit(-1); } } tilebuf = _TIFFmalloc(tile_buffsize); if (tilebuf == 0) return 0; dst_rowsize = ((imagewidth * bps * spp) + 7) / 8; for (row = 0; row < imagelength; row += tl) { nrow = (row + tl > imagelength) ? imagelength - row : tl; for (col = 0; col < imagewidth; col += tw) { tbytes = TIFFReadTile(in, tilebuf, col, row, 0, 0); if (tbytes < tilesize && !ignore) { TIFFError(TIFFFileName(in), ""Error, can't read tile at row %lu col %lu, Read %lu bytes of %lu"", (unsigned long) col, (unsigned long) row, (unsigned long)tbytes, (unsigned long)tilesize); status = 0; _TIFFfree(tilebuf); return status; } row_offset = row * dst_rowsize; col_offset = ((col * bps * spp) + 7)/ 8; bufp = buf + row_offset + col_offset; if (col + tw > imagewidth) ncol = imagewidth - col; else ncol = tw; /* Each tile scanline will start on a byte boundary but it * has to be merged into the scanline for the entire * image buffer and the previous segment may not have * ended on a byte boundary */ /* Optimization for common bit depths, all samples */ if (((bps % 8) == 0) && (count == spp)) { for (trow = 0; trow < nrow; trow++) { src_offset = trow * tile_rowsize; _TIFFmemcpy (bufp, tilebuf + src_offset, (ncol * spp * bps) / 8); bufp += (imagewidth * bps * spp) / 8; } } else { /* Bit depths not a multiple of 8 and/or extract fewer than spp samples */ prev_trailing_bits = trailing_bits = 0; trailing_bits = (ncol * bps * spp) % 8; /* for (trow = 0; tl < nrow; trow++) */ for (trow = 0; trow < nrow; trow++) { src_offset = trow * tile_rowsize; src = tilebuf + src_offset; dst_offset = (row + trow) * dst_rowsize; dst = buf + dst_offset + col_offset; switch (shift_width) { case 0: if (extractContigSamplesBytes (src, dst, ncol, sample, spp, bps, count, 0, ncol)) { TIFFError(""readContigTilesIntoBuffer"", ""Unable to extract row %d from tile %lu"", row, (unsigned long)TIFFCurrentTile(in)); return 1; } break; case 1: if (bps == 1) { if (extractContigSamplesShifted8bits (src, dst, ncol, sample, spp, bps, count, 0, ncol, prev_trailing_bits)) { TIFFError(""readContigTilesIntoBuffer"", ""Unable to extract row %d from tile %lu"", row, (unsigned long)TIFFCurrentTile(in)); return 1; } break; } else if (extractContigSamplesShifted16bits (src, dst, ncol, sample, spp, bps, count, 0, ncol, prev_trailing_bits)) { TIFFError(""readContigTilesIntoBuffer"", ""Unable to extract row %d from tile %lu"", row, (unsigned long)TIFFCurrentTile(in)); return 1; } break; case 2: if (extractContigSamplesShifted24bits (src, dst, ncol, sample, spp, bps, count, 0, ncol, prev_trailing_bits)) { TIFFError(""readContigTilesIntoBuffer"", ""Unable to extract row %d from tile %lu"", row, (unsigned long)TIFFCurrentTile(in)); return 1; } break; case 3: case 4: case 5: if (extractContigSamplesShifted32bits (src, dst, ncol, sample, spp, bps, count, 0, ncol, prev_trailing_bits)) { TIFFError(""readContigTilesIntoBuffer"", ""Unable to extract row %d from tile %lu"", row, (unsigned long)TIFFCurrentTile(in)); return 1; } break; default: TIFFError(""readContigTilesIntoBuffer"", ""Unsupported bit depth %d"", bps); return 1; } } prev_trailing_bits += trailing_bits; /* if (prev_trailing_bits > 7) */ /* prev_trailing_bits-= 8; */ } } } _TIFFfree(tilebuf); return status; }","static int readContigTilesIntoBuffer (TIFF* in, uint8* buf, uint32 imagelength, uint32 imagewidth, uint32 tw, uint32 tl, tsample_t spp, uint16 bps) { int status = 1; tsample_t sample = 0; tsample_t count = spp; uint32 row, col, trow; uint32 nrow, ncol; uint32 dst_rowsize, shift_width; uint32 bytes_per_sample, bytes_per_pixel; uint32 trailing_bits, prev_trailing_bits; uint32 tile_rowsize = TIFFTileRowSize(in); uint32 src_offset, dst_offset; uint32 row_offset, col_offset; uint8 *bufp = (uint8*) buf; unsigned char *src = NULL; unsigned char *dst = NULL; tsize_t tbytes = 0, tile_buffsize = 0; tsize_t tilesize = TIFFTileSize(in); unsigned char *tilebuf = NULL; bytes_per_sample = (bps + 7) / 8; bytes_per_pixel = ((bps * spp) + 7) / 8; if ((bps % 8) == 0) shift_width = 0; else { if (bytes_per_pixel < (bytes_per_sample + 1)) shift_width = bytes_per_pixel; else shift_width = bytes_per_sample + 1; } tile_buffsize = tilesize; if (tilesize == 0 || tile_rowsize == 0) { TIFFError(""readContigTilesIntoBuffer"", ""Tile size or tile rowsize is zero""); exit(-1); } if (tilesize < (tsize_t)(tl * tile_rowsize)) { #ifdef DEBUG2 TIFFError(""readContigTilesIntoBuffer"", ""Tilesize %lu is too small, using alternate calculation %u"", tilesize, tl * tile_rowsize); #endif tile_buffsize = tl * tile_rowsize; if (tl != (tile_buffsize / tile_rowsize)) { TIFFError(""readContigTilesIntoBuffer"", ""Integer overflow when calculating buffer size.""); exit(-1); } } /* Add 3 padding bytes for extractContigSamplesShifted32bits */ if( tile_buffsize > 0xFFFFFFFFU - 3 ) { TIFFError(""readContigTilesIntoBuffer"", ""Integer overflow when calculating buffer size.""); exit(-1); } tilebuf = _TIFFmalloc(tile_buffsize + 3); if (tilebuf == 0) return 0; tilebuf[tile_buffsize] = 0; tilebuf[tile_buffsize+1] = 0; tilebuf[tile_buffsize+2] = 0; dst_rowsize = ((imagewidth * bps * spp) + 7) / 8; for (row = 0; row < imagelength; row += tl) { nrow = (row + tl > imagelength) ? imagelength - row : tl; for (col = 0; col < imagewidth; col += tw) { tbytes = TIFFReadTile(in, tilebuf, col, row, 0, 0); if (tbytes < tilesize && !ignore) { TIFFError(TIFFFileName(in), ""Error, can't read tile at row %lu col %lu, Read %lu bytes of %lu"", (unsigned long) col, (unsigned long) row, (unsigned long)tbytes, (unsigned long)tilesize); status = 0; _TIFFfree(tilebuf); return status; } row_offset = row * dst_rowsize; col_offset = ((col * bps * spp) + 7)/ 8; bufp = buf + row_offset + col_offset; if (col + tw > imagewidth) ncol = imagewidth - col; else ncol = tw; /* Each tile scanline will start on a byte boundary but it * has to be merged into the scanline for the entire * image buffer and the previous segment may not have * ended on a byte boundary */ /* Optimization for common bit depths, all samples */ if (((bps % 8) == 0) && (count == spp)) { for (trow = 0; trow < nrow; trow++) { src_offset = trow * tile_rowsize; _TIFFmemcpy (bufp, tilebuf + src_offset, (ncol * spp * bps) / 8); bufp += (imagewidth * bps * spp) / 8; } } else { /* Bit depths not a multiple of 8 and/or extract fewer than spp samples */ prev_trailing_bits = trailing_bits = 0; trailing_bits = (ncol * bps * spp) % 8; /* for (trow = 0; tl < nrow; trow++) */ for (trow = 0; trow < nrow; trow++) { src_offset = trow * tile_rowsize; src = tilebuf + src_offset; dst_offset = (row + trow) * dst_rowsize; dst = buf + dst_offset + col_offset; switch (shift_width) { case 0: if (extractContigSamplesBytes (src, dst, ncol, sample, spp, bps, count, 0, ncol)) { TIFFError(""readContigTilesIntoBuffer"", ""Unable to extract row %d from tile %lu"", row, (unsigned long)TIFFCurrentTile(in)); return 1; } break; case 1: if (bps == 1) { if (extractContigSamplesShifted8bits (src, dst, ncol, sample, spp, bps, count, 0, ncol, prev_trailing_bits)) { TIFFError(""readContigTilesIntoBuffer"", ""Unable to extract row %d from tile %lu"", row, (unsigned long)TIFFCurrentTile(in)); return 1; } break; } else if (extractContigSamplesShifted16bits (src, dst, ncol, sample, spp, bps, count, 0, ncol, prev_trailing_bits)) { TIFFError(""readContigTilesIntoBuffer"", ""Unable to extract row %d from tile %lu"", row, (unsigned long)TIFFCurrentTile(in)); return 1; } break; case 2: if (extractContigSamplesShifted24bits (src, dst, ncol, sample, spp, bps, count, 0, ncol, prev_trailing_bits)) { TIFFError(""readContigTilesIntoBuffer"", ""Unable to extract row %d from tile %lu"", row, (unsigned long)TIFFCurrentTile(in)); return 1; } break; case 3: case 4: case 5: if (extractContigSamplesShifted32bits (src, dst, ncol, sample, spp, bps, count, 0, ncol, prev_trailing_bits)) { TIFFError(""readContigTilesIntoBuffer"", ""Unable to extract row %d from tile %lu"", row, (unsigned long)TIFFCurrentTile(in)); return 1; } break; default: TIFFError(""readContigTilesIntoBuffer"", ""Unsupported bit depth %d"", bps); return 1; } } prev_trailing_bits += trailing_bits; /* if (prev_trailing_bits > 7) */ /* prev_trailing_bits-= 8; */ } } } _TIFFfree(tilebuf); return status; }","{'deleted': [{'line_no': 60, 'char_start': 1763, 'char_end': 1803, 'line': ' tilebuf = _TIFFmalloc(tile_buffsize);\n'}], 'added': [{'line_no': 60, 'char_start': 1763, 'char_end': 1829, 'line': ' /* Add 3 padding bytes for extractContigSamplesShifted32bits */\n'}, {'line_no': 61, 'char_start': 1829, 'char_end': 1869, 'line': ' if( tile_buffsize > 0xFFFFFFFFU - 3 )\n'}, {'line_no': 62, 'char_start': 1869, 'char_end': 1873, 'line': ' {\n'}, {'line_no': 63, 'char_start': 1873, 'char_end': 1969, 'line': ' TIFFError(""readContigTilesIntoBuffer"", ""Integer overflow when calculating buffer size."");\n'}, {'line_no': 64, 'char_start': 1969, 'char_end': 1985, 'line': ' exit(-1);\n'}, {'line_no': 65, 'char_start': 1985, 'char_end': 1989, 'line': ' }\n'}, {'line_no': 66, 'char_start': 1989, 'char_end': 2033, 'line': ' tilebuf = _TIFFmalloc(tile_buffsize + 3);\n'}, {'line_no': 69, 'char_start': 2067, 'char_end': 2097, 'line': ' tilebuf[tile_buffsize] = 0;\n'}, {'line_no': 70, 'char_start': 2097, 'char_end': 2129, 'line': ' tilebuf[tile_buffsize+1] = 0;\n'}, {'line_no': 71, 'char_start': 2129, 'char_end': 2161, 'line': ' tilebuf[tile_buffsize+2] = 0;\n'}]}","{'deleted': [], 'added': [{'char_start': 1765, 'char_end': 1991, 'chars': '/* Add 3 padding bytes for extractContigSamplesShifted32bits */\n if( tile_buffsize > 0xFFFFFFFFU - 3 )\n {\n TIFFError(""readContigTilesIntoBuffer"", ""Integer overflow when calculating buffer size."");\n exit(-1);\n }\n '}, {'char_start': 2026, 'char_end': 2030, 'chars': ' + 3'}, {'char_start': 2063, 'char_end': 2157, 'chars': ' 0;\n tilebuf[tile_buffsize] = 0;\n tilebuf[tile_buffsize+1] = 0;\n tilebuf[tile_buffsize+2] ='}]}",github.com/vadz/libtiff/commit/ae9365db1b271b62b35ce018eac8799b1d5e8a53,tools/tiffcrop.c,cwe-125,1703 cwe-125,dbd_st_prepare,"dbd_st_prepare( SV *sth, imp_sth_t *imp_sth, char *statement, SV *attribs) { int i; SV **svp; dTHX; #if MYSQL_VERSION_ID >= SERVER_PREPARE_VERSION #if MYSQL_VERSION_ID < CALL_PLACEHOLDER_VERSION char *str_ptr, *str_last_ptr; #if MYSQL_VERSION_ID < LIMIT_PLACEHOLDER_VERSION int limit_flag=0; #endif #endif int col_type, prepare_retval; MYSQL_BIND *bind, *bind_end; imp_sth_phb_t *fbind; #endif D_imp_xxh(sth); D_imp_dbh_from_sth; if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), ""\t-> dbd_st_prepare MYSQL_VERSION_ID %d, SQL statement: %s\n"", MYSQL_VERSION_ID, statement); #if MYSQL_VERSION_ID >= SERVER_PREPARE_VERSION /* Set default value of 'mysql_server_prepare' attribute for sth from dbh */ imp_sth->use_server_side_prepare= imp_dbh->use_server_side_prepare; if (attribs) { svp= DBD_ATTRIB_GET_SVP(attribs, ""mysql_server_prepare"", 20); imp_sth->use_server_side_prepare = (svp) ? SvTRUE(*svp) : imp_dbh->use_server_side_prepare; svp = DBD_ATTRIB_GET_SVP(attribs, ""async"", 5); if(svp && SvTRUE(*svp)) { #if MYSQL_ASYNC imp_sth->is_async = TRUE; imp_sth->use_server_side_prepare = FALSE; #else do_error(sth, 2000, ""Async support was not built into this version of DBD::mysql"", ""HY000""); return 0; #endif } } imp_sth->fetch_done= 0; #endif imp_sth->done_desc= 0; imp_sth->result= NULL; imp_sth->currow= 0; /* Set default value of 'mysql_use_result' attribute for sth from dbh */ svp= DBD_ATTRIB_GET_SVP(attribs, ""mysql_use_result"", 16); imp_sth->use_mysql_use_result= svp ? SvTRUE(*svp) : imp_dbh->use_mysql_use_result; for (i= 0; i < AV_ATTRIB_LAST; i++) imp_sth->av_attr[i]= Nullav; /* Clean-up previous result set(s) for sth to prevent 'Commands out of sync' error */ mysql_st_free_result_sets(sth, imp_sth); #if MYSQL_VERSION_ID >= SERVER_PREPARE_VERSION && MYSQL_VERSION_ID < CALL_PLACEHOLDER_VERSION if (imp_sth->use_server_side_prepare) { if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), ""\t\tuse_server_side_prepare set, check restrictions\n""); /* This code is here because placeholder support is not implemented for statements with :- 1. LIMIT < 5.0.7 2. CALL < 5.5.3 (Added support for out & inout parameters) In these cases we have to disable server side prepared statements NOTE: These checks could cause a false positive on statements which include columns / table names that match ""call "" or "" limit "" */ if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), #if MYSQL_VERSION_ID < LIMIT_PLACEHOLDER_VERSION ""\t\tneed to test for LIMIT & CALL\n""); #else ""\t\tneed to test for restrictions\n""); #endif str_last_ptr = statement + strlen(statement); for (str_ptr= statement; str_ptr < str_last_ptr; str_ptr++) { #if MYSQL_VERSION_ID < LIMIT_PLACEHOLDER_VERSION /* Place holders not supported in LIMIT's */ if (limit_flag) { if (*str_ptr == '?') { if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), ""\t\tLIMIT and ? found, set to use_server_side_prepare=0\n""); /* ... then we do not want to try server side prepare (use emulation) */ imp_sth->use_server_side_prepare= 0; break; } } else if (str_ptr < str_last_ptr - 6 && isspace(*(str_ptr + 0)) && tolower(*(str_ptr + 1)) == 'l' && tolower(*(str_ptr + 2)) == 'i' && tolower(*(str_ptr + 3)) == 'm' && tolower(*(str_ptr + 4)) == 'i' && tolower(*(str_ptr + 5)) == 't' && isspace(*(str_ptr + 6))) { if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), ""LIMIT set limit flag to 1\n""); limit_flag= 1; } #endif /* Place holders not supported in CALL's */ if (str_ptr < str_last_ptr - 4 && tolower(*(str_ptr + 0)) == 'c' && tolower(*(str_ptr + 1)) == 'a' && tolower(*(str_ptr + 2)) == 'l' && tolower(*(str_ptr + 3)) == 'l' && isspace(*(str_ptr + 4))) { if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), ""Disable PS mode for CALL()\n""); imp_sth->use_server_side_prepare= 0; break; } } } #endif #if MYSQL_VERSION_ID >= SERVER_PREPARE_VERSION if (imp_sth->use_server_side_prepare) { if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), ""\t\tuse_server_side_prepare set\n""); /* do we really need this? If we do, we should return, not just continue */ if (imp_sth->stmt) fprintf(stderr, ""ERROR: Trying to prepare new stmt while we have \ already not closed one \n""); imp_sth->stmt= mysql_stmt_init(imp_dbh->pmysql); if (! imp_sth->stmt) { if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), ""\t\tERROR: Unable to return MYSQL_STMT structure \ from mysql_stmt_init(): ERROR NO: %d ERROR MSG:%s\n"", mysql_errno(imp_dbh->pmysql), mysql_error(imp_dbh->pmysql)); } prepare_retval= mysql_stmt_prepare(imp_sth->stmt, statement, strlen(statement)); if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), ""\t\tmysql_stmt_prepare returned %d\n"", prepare_retval); if (prepare_retval) { if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), ""\t\tmysql_stmt_prepare %d %s\n"", mysql_stmt_errno(imp_sth->stmt), mysql_stmt_error(imp_sth->stmt)); /* For commands that are not supported by server side prepared statement mechanism lets try to pass them through regular API */ if (mysql_stmt_errno(imp_sth->stmt) == ER_UNSUPPORTED_PS) { if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), ""\t\tSETTING imp_sth->use_server_side_prepare to 0\n""); imp_sth->use_server_side_prepare= 0; } else { do_error(sth, mysql_stmt_errno(imp_sth->stmt), mysql_stmt_error(imp_sth->stmt), mysql_sqlstate(imp_dbh->pmysql)); mysql_stmt_close(imp_sth->stmt); imp_sth->stmt= NULL; return FALSE; } } else { DBIc_NUM_PARAMS(imp_sth)= mysql_stmt_param_count(imp_sth->stmt); /* mysql_stmt_param_count */ if (DBIc_NUM_PARAMS(imp_sth) > 0) { int has_statement_fields= imp_sth->stmt->fields != 0; /* Allocate memory for bind variables */ imp_sth->bind= alloc_bind(DBIc_NUM_PARAMS(imp_sth)); imp_sth->fbind= alloc_fbind(DBIc_NUM_PARAMS(imp_sth)); imp_sth->has_been_bound= 0; /* Initialize ph variables with NULL values */ for (i= 0, bind= imp_sth->bind, fbind= imp_sth->fbind, bind_end= bind+DBIc_NUM_PARAMS(imp_sth); bind < bind_end ; bind++, fbind++, i++ ) { /* if this statement has a result set, field types will be correctly identified. If there is no result set, such as with an INSERT, fields will not be defined, and all buffer_type will default to MYSQL_TYPE_VAR_STRING */ col_type= (has_statement_fields ? imp_sth->stmt->fields[i].type : MYSQL_TYPE_STRING); bind->buffer_type= mysql_to_perl_type(col_type); if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), ""\t\tmysql_to_perl_type returned %d\n"", col_type); bind->buffer= NULL; bind->length= &(fbind->length); bind->is_null= (char*) &(fbind->is_null); fbind->is_null= 1; fbind->length= 0; } } } } #endif #if MYSQL_VERSION_ID >= SERVER_PREPARE_VERSION /* Count the number of parameters (driver, vs server-side) */ if (imp_sth->use_server_side_prepare == 0) DBIc_NUM_PARAMS(imp_sth) = count_params((imp_xxh_t *)imp_dbh, aTHX_ statement, imp_dbh->bind_comment_placeholders); #else DBIc_NUM_PARAMS(imp_sth) = count_params((imp_xxh_t *)imp_dbh, aTHX_ statement, imp_dbh->bind_comment_placeholders); #endif /* Allocate memory for parameters */ imp_sth->params= alloc_param(DBIc_NUM_PARAMS(imp_sth)); DBIc_IMPSET_on(imp_sth); if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), ""\t<- dbd_st_prepare\n""); return 1; }","dbd_st_prepare( SV *sth, imp_sth_t *imp_sth, char *statement, SV *attribs) { int i; SV **svp; dTHX; #if MYSQL_VERSION_ID >= SERVER_PREPARE_VERSION #if MYSQL_VERSION_ID < CALL_PLACEHOLDER_VERSION char *str_ptr, *str_last_ptr; #if MYSQL_VERSION_ID < LIMIT_PLACEHOLDER_VERSION int limit_flag=0; #endif #endif int prepare_retval; MYSQL_BIND *bind, *bind_end; imp_sth_phb_t *fbind; #endif D_imp_xxh(sth); D_imp_dbh_from_sth; if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), ""\t-> dbd_st_prepare MYSQL_VERSION_ID %d, SQL statement: %s\n"", MYSQL_VERSION_ID, statement); #if MYSQL_VERSION_ID >= SERVER_PREPARE_VERSION /* Set default value of 'mysql_server_prepare' attribute for sth from dbh */ imp_sth->use_server_side_prepare= imp_dbh->use_server_side_prepare; if (attribs) { svp= DBD_ATTRIB_GET_SVP(attribs, ""mysql_server_prepare"", 20); imp_sth->use_server_side_prepare = (svp) ? SvTRUE(*svp) : imp_dbh->use_server_side_prepare; svp = DBD_ATTRIB_GET_SVP(attribs, ""async"", 5); if(svp && SvTRUE(*svp)) { #if MYSQL_ASYNC imp_sth->is_async = TRUE; imp_sth->use_server_side_prepare = FALSE; #else do_error(sth, 2000, ""Async support was not built into this version of DBD::mysql"", ""HY000""); return 0; #endif } } imp_sth->fetch_done= 0; #endif imp_sth->done_desc= 0; imp_sth->result= NULL; imp_sth->currow= 0; /* Set default value of 'mysql_use_result' attribute for sth from dbh */ svp= DBD_ATTRIB_GET_SVP(attribs, ""mysql_use_result"", 16); imp_sth->use_mysql_use_result= svp ? SvTRUE(*svp) : imp_dbh->use_mysql_use_result; for (i= 0; i < AV_ATTRIB_LAST; i++) imp_sth->av_attr[i]= Nullav; /* Clean-up previous result set(s) for sth to prevent 'Commands out of sync' error */ mysql_st_free_result_sets(sth, imp_sth); #if MYSQL_VERSION_ID >= SERVER_PREPARE_VERSION && MYSQL_VERSION_ID < CALL_PLACEHOLDER_VERSION if (imp_sth->use_server_side_prepare) { if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), ""\t\tuse_server_side_prepare set, check restrictions\n""); /* This code is here because placeholder support is not implemented for statements with :- 1. LIMIT < 5.0.7 2. CALL < 5.5.3 (Added support for out & inout parameters) In these cases we have to disable server side prepared statements NOTE: These checks could cause a false positive on statements which include columns / table names that match ""call "" or "" limit "" */ if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), #if MYSQL_VERSION_ID < LIMIT_PLACEHOLDER_VERSION ""\t\tneed to test for LIMIT & CALL\n""); #else ""\t\tneed to test for restrictions\n""); #endif str_last_ptr = statement + strlen(statement); for (str_ptr= statement; str_ptr < str_last_ptr; str_ptr++) { #if MYSQL_VERSION_ID < LIMIT_PLACEHOLDER_VERSION /* Place holders not supported in LIMIT's */ if (limit_flag) { if (*str_ptr == '?') { if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), ""\t\tLIMIT and ? found, set to use_server_side_prepare=0\n""); /* ... then we do not want to try server side prepare (use emulation) */ imp_sth->use_server_side_prepare= 0; break; } } else if (str_ptr < str_last_ptr - 6 && isspace(*(str_ptr + 0)) && tolower(*(str_ptr + 1)) == 'l' && tolower(*(str_ptr + 2)) == 'i' && tolower(*(str_ptr + 3)) == 'm' && tolower(*(str_ptr + 4)) == 'i' && tolower(*(str_ptr + 5)) == 't' && isspace(*(str_ptr + 6))) { if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), ""LIMIT set limit flag to 1\n""); limit_flag= 1; } #endif /* Place holders not supported in CALL's */ if (str_ptr < str_last_ptr - 4 && tolower(*(str_ptr + 0)) == 'c' && tolower(*(str_ptr + 1)) == 'a' && tolower(*(str_ptr + 2)) == 'l' && tolower(*(str_ptr + 3)) == 'l' && isspace(*(str_ptr + 4))) { if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), ""Disable PS mode for CALL()\n""); imp_sth->use_server_side_prepare= 0; break; } } } #endif #if MYSQL_VERSION_ID >= SERVER_PREPARE_VERSION if (imp_sth->use_server_side_prepare) { if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), ""\t\tuse_server_side_prepare set\n""); /* do we really need this? If we do, we should return, not just continue */ if (imp_sth->stmt) fprintf(stderr, ""ERROR: Trying to prepare new stmt while we have \ already not closed one \n""); imp_sth->stmt= mysql_stmt_init(imp_dbh->pmysql); if (! imp_sth->stmt) { if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), ""\t\tERROR: Unable to return MYSQL_STMT structure \ from mysql_stmt_init(): ERROR NO: %d ERROR MSG:%s\n"", mysql_errno(imp_dbh->pmysql), mysql_error(imp_dbh->pmysql)); } prepare_retval= mysql_stmt_prepare(imp_sth->stmt, statement, strlen(statement)); if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), ""\t\tmysql_stmt_prepare returned %d\n"", prepare_retval); if (prepare_retval) { if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), ""\t\tmysql_stmt_prepare %d %s\n"", mysql_stmt_errno(imp_sth->stmt), mysql_stmt_error(imp_sth->stmt)); /* For commands that are not supported by server side prepared statement mechanism lets try to pass them through regular API */ if (mysql_stmt_errno(imp_sth->stmt) == ER_UNSUPPORTED_PS) { if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), ""\t\tSETTING imp_sth->use_server_side_prepare to 0\n""); imp_sth->use_server_side_prepare= 0; } else { do_error(sth, mysql_stmt_errno(imp_sth->stmt), mysql_stmt_error(imp_sth->stmt), mysql_sqlstate(imp_dbh->pmysql)); mysql_stmt_close(imp_sth->stmt); imp_sth->stmt= NULL; return FALSE; } } else { DBIc_NUM_PARAMS(imp_sth)= mysql_stmt_param_count(imp_sth->stmt); /* mysql_stmt_param_count */ if (DBIc_NUM_PARAMS(imp_sth) > 0) { /* Allocate memory for bind variables */ imp_sth->bind= alloc_bind(DBIc_NUM_PARAMS(imp_sth)); imp_sth->fbind= alloc_fbind(DBIc_NUM_PARAMS(imp_sth)); imp_sth->has_been_bound= 0; /* Initialize ph variables with NULL values */ for (i= 0, bind= imp_sth->bind, fbind= imp_sth->fbind, bind_end= bind+DBIc_NUM_PARAMS(imp_sth); bind < bind_end ; bind++, fbind++, i++ ) { bind->buffer_type= MYSQL_TYPE_STRING; bind->buffer= NULL; bind->length= &(fbind->length); bind->is_null= (char*) &(fbind->is_null); fbind->is_null= 1; fbind->length= 0; } } } } #endif #if MYSQL_VERSION_ID >= SERVER_PREPARE_VERSION /* Count the number of parameters (driver, vs server-side) */ if (imp_sth->use_server_side_prepare == 0) DBIc_NUM_PARAMS(imp_sth) = count_params((imp_xxh_t *)imp_dbh, aTHX_ statement, imp_dbh->bind_comment_placeholders); #else DBIc_NUM_PARAMS(imp_sth) = count_params((imp_xxh_t *)imp_dbh, aTHX_ statement, imp_dbh->bind_comment_placeholders); #endif /* Allocate memory for parameters */ imp_sth->params= alloc_param(DBIc_NUM_PARAMS(imp_sth)); DBIc_IMPSET_on(imp_sth); if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), ""\t<- dbd_st_prepare\n""); return 1; }","{'deleted': [{'line_no': 17, 'char_start': 324, 'char_end': 356, 'line': ' int col_type, prepare_retval;\n'}, {'line_no': 213, 'char_start': 7021, 'char_end': 7083, 'line': ' int has_statement_fields= imp_sth->stmt->fields != 0;\n'}, {'line_no': 227, 'char_start': 7601, 'char_end': 7614, 'line': ' /*\n'}, {'line_no': 228, 'char_start': 7614, 'char_end': 7682, 'line': ' if this statement has a result set, field types will be\n'}, {'line_no': 229, 'char_start': 7682, 'char_end': 7751, 'line': ' correctly identified. If there is no result set, such as\n'}, {'line_no': 230, 'char_start': 7751, 'char_end': 7827, 'line': ' with an INSERT, fields will not be defined, and all buffer_type\n'}, {'line_no': 231, 'char_start': 7827, 'char_end': 7877, 'line': ' will default to MYSQL_TYPE_VAR_STRING\n'}, {'line_no': 232, 'char_start': 7877, 'char_end': 7890, 'line': ' */\n'}, {'line_no': 233, 'char_start': 7890, 'char_end': 7934, 'line': ' col_type= (has_statement_fields ?\n'}, {'line_no': 234, 'char_start': 7934, 'char_end': 8007, 'line': ' imp_sth->stmt->fields[i].type : MYSQL_TYPE_STRING);\n'}, {'line_no': 235, 'char_start': 8007, 'char_end': 8008, 'line': '\n'}, {'line_no': 236, 'char_start': 8008, 'char_end': 8068, 'line': ' bind->buffer_type= mysql_to_perl_type(col_type);\n'}, {'line_no': 237, 'char_start': 8068, 'char_end': 8069, 'line': '\n'}, {'line_no': 238, 'char_start': 8069, 'char_end': 8115, 'line': ' if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)\n'}, {'line_no': 239, 'char_start': 8115, 'char_end': 8214, 'line': ' PerlIO_printf(DBIc_LOGPIO(imp_xxh), ""\\t\\tmysql_to_perl_type returned %d\\n"", col_type);\n'}, {'line_no': 240, 'char_start': 8214, 'char_end': 8215, 'line': '\n'}], 'added': [{'line_no': 17, 'char_start': 324, 'char_end': 346, 'line': ' int prepare_retval;\n'}, {'line_no': 226, 'char_start': 7529, 'char_end': 7578, 'line': ' bind->buffer_type= MYSQL_TYPE_STRING;\n'}]}","{'deleted': [{'char_start': 330, 'char_end': 340, 'chars': 'col_type, '}, {'char_start': 7029, 'char_end': 7091, 'chars': 'int has_statement_fields= imp_sth->stmt->fields != 0;\n '}, {'char_start': 7611, 'char_end': 7679, 'chars': '/*\n if this statement has a result set, field types will '}, {'char_start': 7680, 'char_end': 7704, 'chars': 'e\n correctly '}, {'char_start': 7705, 'char_end': 7707, 'chars': 'de'}, {'char_start': 7708, 'char_end': 7713, 'chars': 'tifie'}, {'char_start': 7714, 'char_end': 7815, 'chars': '. If there is no result set, such as\n with an INSERT, fields will not be defined, and all '}, {'char_start': 7826, 'char_end': 7908, 'chars': '\n will default to MYSQL_TYPE_VAR_STRING\n */\n col_type'}, {'char_start': 7910, 'char_end': 7986, 'chars': '(has_statement_fields ?\n imp_sth->stmt->fields[i].type :'}, {'char_start': 8004, 'char_end': 8005, 'chars': ')'}, {'char_start': 8006, 'char_end': 8214, 'chars': '\n\n bind->buffer_type= mysql_to_perl_type(col_type);\n\n if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)\n PerlIO_printf(DBIc_LOGPIO(imp_xxh), ""\\t\\tmysql_to_perl_type returned %d\\n"", col_type);\n'}], 'added': [{'char_start': 7060, 'char_end': 7060, 'chars': ''}, {'char_start': 7543, 'char_end': 7545, 'chars': '->'}]}",github.com/perl5-dbi/DBD-mysql/commit/793b72b1a0baa5070adacaac0e12fd995a6fbabe,dbdimp.c,cwe-125,2524 cwe-079,mode_receive," def mode_receive(self, request): """""" This is called by render_POST when the client is telling us that it is ready to receive data as soon as it is available. This is the basis of a long-polling (comet) mechanism: the server will wait to reply until data is available. Args: request (Request): Incoming request. """""" csessid = request.args.get('csessid')[0] self.last_alive[csessid] = (time.time(), False) dataentries = self.databuffer.get(csessid, []) if dataentries: return dataentries.pop(0) request.notifyFinish().addErrback(self._responseFailed, csessid, request) if csessid in self.requests: self.requests[csessid].finish() # Clear any stale request. self.requests[csessid] = request return server.NOT_DONE_YET"," def mode_receive(self, request): """""" This is called by render_POST when the client is telling us that it is ready to receive data as soon as it is available. This is the basis of a long-polling (comet) mechanism: the server will wait to reply until data is available. Args: request (Request): Incoming request. """""" csessid = cgi.escape(request.args['csessid'][0]) self.last_alive[csessid] = (time.time(), False) dataentries = self.databuffer.get(csessid, []) if dataentries: return dataentries.pop(0) request.notifyFinish().addErrback(self._responseFailed, csessid, request) if csessid in self.requests: self.requests[csessid].finish() # Clear any stale request. self.requests[csessid] = request return server.NOT_DONE_YET","{'deleted': [{'line_no': 12, 'char_start': 389, 'char_end': 438, 'line': "" csessid = request.args.get('csessid')[0]\n""}], 'added': [{'line_no': 12, 'char_start': 389, 'char_end': 446, 'line': "" csessid = cgi.escape(request.args['csessid'][0])\n""}]}","{'deleted': [{'char_start': 419, 'char_end': 424, 'chars': '.get('}, {'char_start': 433, 'char_end': 434, 'chars': ')'}], 'added': [{'char_start': 407, 'char_end': 418, 'chars': 'cgi.escape('}, {'char_start': 430, 'char_end': 431, 'chars': '['}, {'char_start': 440, 'char_end': 441, 'chars': ']'}, {'char_start': 444, 'char_end': 445, 'chars': ')'}]}",github.com/evennia/evennia/commit/300261529b82f95414c9d1d7150d6eda4695bb93,evennia/server/portal/webclient_ajax.py,cwe-079,202 cwe-089,check,"def check(current_num): try: cursor.execute('SELECT * FROM comics WHERE num=""%s""' % current_num) except sqlite3.OperationalError: cursor.execute('CREATE TABLE comics (num text)') return False else: return False if cursor.fetchone() is None else True","def check(current_num): try: cursor.execute('SELECT * FROM comics WHERE num=?', (current_num,)) except sqlite3.OperationalError: cursor.execute('CREATE TABLE comics (num text)') return False else: return False if cursor.fetchone() is None else True","{'deleted': [{'line_no': 3, 'char_start': 33, 'char_end': 109, 'line': ' cursor.execute(\'SELECT * FROM comics WHERE num=""%s""\' % current_num)\n'}], 'added': [{'line_no': 3, 'char_start': 33, 'char_end': 108, 'line': "" cursor.execute('SELECT * FROM comics WHERE num=?', (current_num,))\n""}]}","{'deleted': [{'char_start': 88, 'char_end': 92, 'chars': '""%s""'}, {'char_start': 93, 'char_end': 95, 'chars': ' %'}], 'added': [{'char_start': 88, 'char_end': 89, 'chars': '?'}, {'char_start': 90, 'char_end': 91, 'chars': ','}, {'char_start': 92, 'char_end': 93, 'chars': '('}, {'char_start': 104, 'char_end': 106, 'chars': ',)'}]}",github.com/lord63/a_bunch_of_code/commit/c0d67a1312306fd1257c354bfb5d6cac7643aa29,comics/check_comics.py,cwe-089,63 cwe-089,tag_num_to_tag," def tag_num_to_tag(self, tag_num): ''' Returns tag given tag_num. ''' q = ""SELECT tag FROM tags WHERE rowid = '"" + str(tag_num) + ""'"" self.query(q) return self.c.fetchone()[0]"," def tag_num_to_tag(self, tag_num): ''' Returns tag given tag_num. ''' q = ""SELECT tag FROM tags WHERE rowid = ?"" self.query(q, tag_num) return self.c.fetchone()[0]","{'deleted': [{'line_no': 4, 'char_start': 83, 'char_end': 155, 'line': ' q = ""SELECT tag FROM tags WHERE rowid = \'"" + str(tag_num) + ""\'""\n'}, {'line_no': 5, 'char_start': 155, 'char_end': 177, 'line': ' self.query(q)\n'}], 'added': [{'line_no': 4, 'char_start': 83, 'char_end': 134, 'line': ' q = ""SELECT tag FROM tags WHERE rowid = ?""\n'}, {'line_no': 5, 'char_start': 134, 'char_end': 165, 'line': ' self.query(q, tag_num)\n'}]}","{'deleted': [{'char_start': 131, 'char_end': 153, 'chars': '\'"" + str(tag_num) + ""\''}], 'added': [{'char_start': 131, 'char_end': 132, 'chars': '?'}, {'char_start': 154, 'char_end': 163, 'chars': ', tag_num'}]}",github.com/pukkapies/urop2019/commit/3ca2e2c291d2d5fe262d20a8e0520bdfb622432b,modules/query_lastfm.py,cwe-089,54 cwe-190,rwpng_read_image24_libpng,"static pngquant_error rwpng_read_image24_libpng(FILE *infile, png24_image *mainprog_ptr, int verbose) { png_structp png_ptr = NULL; png_infop info_ptr = NULL; png_size_t rowbytes; int color_type, bit_depth; png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, mainprog_ptr, rwpng_error_handler, verbose ? rwpng_warning_stderr_handler : rwpng_warning_silent_handler); if (!png_ptr) { return PNG_OUT_OF_MEMORY_ERROR; /* out of memory */ } info_ptr = png_create_info_struct(png_ptr); if (!info_ptr) { png_destroy_read_struct(&png_ptr, NULL, NULL); return PNG_OUT_OF_MEMORY_ERROR; /* out of memory */ } /* setjmp() must be called in every function that calls a non-trivial * libpng function */ if (setjmp(mainprog_ptr->jmpbuf)) { png_destroy_read_struct(&png_ptr, &info_ptr, NULL); return LIBPNG_FATAL_ERROR; /* fatal libpng error (via longjmp()) */ } #if defined(PNG_SKIP_sRGB_CHECK_PROFILE) && defined(PNG_SET_OPTION_SUPPORTED) png_set_option(png_ptr, PNG_SKIP_sRGB_CHECK_PROFILE, PNG_OPTION_ON); #endif #if PNG_LIBPNG_VER >= 10500 && defined(PNG_UNKNOWN_CHUNKS_SUPPORTED) /* copy standard chunks too */ png_set_keep_unknown_chunks(png_ptr, PNG_HANDLE_CHUNK_IF_SAFE, (png_const_bytep)""pHYs\0iTXt\0tEXt\0zTXt"", 4); #endif png_set_read_user_chunk_fn(png_ptr, &mainprog_ptr->chunks, read_chunk_callback); struct rwpng_read_data read_data = {infile, 0}; png_set_read_fn(png_ptr, &read_data, user_read_data); png_read_info(png_ptr, info_ptr); /* read all PNG info up to image data */ /* alternatively, could make separate calls to png_get_image_width(), * etc., but want bit_depth and color_type for later [don't care about * compression_type and filter_type => NULLs] */ png_get_IHDR(png_ptr, info_ptr, &mainprog_ptr->width, &mainprog_ptr->height, &bit_depth, &color_type, NULL, NULL, NULL); // For overflow safety reject images that won't fit in 32-bit if (mainprog_ptr->width > INT_MAX/mainprog_ptr->height) { png_destroy_read_struct(&png_ptr, &info_ptr, NULL); return PNG_OUT_OF_MEMORY_ERROR; /* not quite true, but whatever */ } /* expand palette images to RGB, low-bit-depth grayscale images to 8 bits, * transparency chunks to full alpha channel; strip 16-bit-per-sample * images to 8 bits per sample; and convert grayscale to RGB[A] */ /* GRR TO DO: preserve all safe-to-copy ancillary PNG chunks */ if (!(color_type & PNG_COLOR_MASK_ALPHA)) { #ifdef PNG_READ_FILLER_SUPPORTED png_set_expand(png_ptr); png_set_filler(png_ptr, 65535L, PNG_FILLER_AFTER); #else fprintf(stderr, ""pngquant readpng: image is neither RGBA nor GA\n""); png_destroy_read_struct(&png_ptr, &info_ptr, NULL); mainprog_ptr->retval = WRONG_INPUT_COLOR_TYPE; return mainprog_ptr->retval; #endif } if (bit_depth == 16) { png_set_strip_16(png_ptr); } if (!(color_type & PNG_COLOR_MASK_COLOR)) { png_set_gray_to_rgb(png_ptr); } /* get source gamma for gamma correction, or use sRGB default */ double gamma = 0.45455; if (png_get_valid(png_ptr, info_ptr, PNG_INFO_sRGB)) { mainprog_ptr->input_color = RWPNG_SRGB; mainprog_ptr->output_color = RWPNG_SRGB; } else { png_get_gAMA(png_ptr, info_ptr, &gamma); if (gamma > 0 && gamma <= 1.0) { mainprog_ptr->input_color = RWPNG_GAMA_ONLY; mainprog_ptr->output_color = RWPNG_GAMA_ONLY; } else { fprintf(stderr, ""pngquant readpng: ignored out-of-range gamma %f\n"", gamma); mainprog_ptr->input_color = RWPNG_NONE; mainprog_ptr->output_color = RWPNG_NONE; gamma = 0.45455; } } mainprog_ptr->gamma = gamma; png_set_interlace_handling(png_ptr); /* all transformations have been registered; now update info_ptr data, * get rowbytes and channels, and allocate image memory */ png_read_update_info(png_ptr, info_ptr); rowbytes = png_get_rowbytes(png_ptr, info_ptr); if ((mainprog_ptr->rgba_data = malloc(rowbytes * mainprog_ptr->height)) == NULL) { fprintf(stderr, ""pngquant readpng: unable to allocate image data\n""); png_destroy_read_struct(&png_ptr, &info_ptr, NULL); return PNG_OUT_OF_MEMORY_ERROR; } png_bytepp row_pointers = rwpng_create_row_pointers(info_ptr, png_ptr, mainprog_ptr->rgba_data, mainprog_ptr->height, 0); /* now we can go ahead and just read the whole image */ png_read_image(png_ptr, row_pointers); /* and we're done! (png_read_end() can be omitted if no processing of * post-IDAT text/time/etc. is desired) */ png_read_end(png_ptr, NULL); #if USE_LCMS #if PNG_LIBPNG_VER < 10500 png_charp ProfileData; #else png_bytep ProfileData; #endif png_uint_32 ProfileLen; cmsHPROFILE hInProfile = NULL; /* color_type is read from the image before conversion to RGBA */ int COLOR_PNG = color_type & PNG_COLOR_MASK_COLOR; /* embedded ICC profile */ if (png_get_iCCP(png_ptr, info_ptr, &(png_charp){0}, &(int){0}, &ProfileData, &ProfileLen)) { hInProfile = cmsOpenProfileFromMem(ProfileData, ProfileLen); cmsColorSpaceSignature colorspace = cmsGetColorSpace(hInProfile); /* only RGB (and GRAY) valid for PNGs */ if (colorspace == cmsSigRgbData && COLOR_PNG) { mainprog_ptr->input_color = RWPNG_ICCP; mainprog_ptr->output_color = RWPNG_SRGB; } else { if (colorspace == cmsSigGrayData && !COLOR_PNG) { mainprog_ptr->input_color = RWPNG_ICCP_WARN_GRAY; mainprog_ptr->output_color = RWPNG_SRGB; } cmsCloseProfile(hInProfile); hInProfile = NULL; } } /* build RGB profile from cHRM and gAMA */ if (hInProfile == NULL && COLOR_PNG && !png_get_valid(png_ptr, info_ptr, PNG_INFO_sRGB) && png_get_valid(png_ptr, info_ptr, PNG_INFO_gAMA) && png_get_valid(png_ptr, info_ptr, PNG_INFO_cHRM)) { cmsCIExyY WhitePoint; cmsCIExyYTRIPLE Primaries; png_get_cHRM(png_ptr, info_ptr, &WhitePoint.x, &WhitePoint.y, &Primaries.Red.x, &Primaries.Red.y, &Primaries.Green.x, &Primaries.Green.y, &Primaries.Blue.x, &Primaries.Blue.y); WhitePoint.Y = Primaries.Red.Y = Primaries.Green.Y = Primaries.Blue.Y = 1.0; cmsToneCurve *GammaTable[3]; GammaTable[0] = GammaTable[1] = GammaTable[2] = cmsBuildGamma(NULL, 1/gamma); hInProfile = cmsCreateRGBProfile(&WhitePoint, &Primaries, GammaTable); cmsFreeToneCurve(GammaTable[0]); mainprog_ptr->input_color = RWPNG_GAMA_CHRM; mainprog_ptr->output_color = RWPNG_SRGB; } /* transform image to sRGB colorspace */ if (hInProfile != NULL) { cmsHPROFILE hOutProfile = cmsCreate_sRGBProfile(); cmsHTRANSFORM hTransform = cmsCreateTransform(hInProfile, TYPE_RGBA_8, hOutProfile, TYPE_RGBA_8, INTENT_PERCEPTUAL, omp_get_max_threads() > 1 ? cmsFLAGS_NOCACHE : 0); #pragma omp parallel for \ if (mainprog_ptr->height*mainprog_ptr->width > 8000) \ schedule(static) for (unsigned int i = 0; i < mainprog_ptr->height; i++) { /* It is safe to use the same block for input and output, when both are of the same TYPE. */ cmsDoTransform(hTransform, row_pointers[i], row_pointers[i], mainprog_ptr->width); } cmsDeleteTransform(hTransform); cmsCloseProfile(hOutProfile); cmsCloseProfile(hInProfile); mainprog_ptr->gamma = 0.45455; } #endif png_destroy_read_struct(&png_ptr, &info_ptr, NULL); mainprog_ptr->file_size = read_data.bytes_read; mainprog_ptr->row_pointers = (unsigned char **)row_pointers; return SUCCESS; }","static pngquant_error rwpng_read_image24_libpng(FILE *infile, png24_image *mainprog_ptr, int verbose) { png_structp png_ptr = NULL; png_infop info_ptr = NULL; png_size_t rowbytes; int color_type, bit_depth; png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, mainprog_ptr, rwpng_error_handler, verbose ? rwpng_warning_stderr_handler : rwpng_warning_silent_handler); if (!png_ptr) { return PNG_OUT_OF_MEMORY_ERROR; /* out of memory */ } info_ptr = png_create_info_struct(png_ptr); if (!info_ptr) { png_destroy_read_struct(&png_ptr, NULL, NULL); return PNG_OUT_OF_MEMORY_ERROR; /* out of memory */ } /* setjmp() must be called in every function that calls a non-trivial * libpng function */ if (setjmp(mainprog_ptr->jmpbuf)) { png_destroy_read_struct(&png_ptr, &info_ptr, NULL); return LIBPNG_FATAL_ERROR; /* fatal libpng error (via longjmp()) */ } #if defined(PNG_SKIP_sRGB_CHECK_PROFILE) && defined(PNG_SET_OPTION_SUPPORTED) png_set_option(png_ptr, PNG_SKIP_sRGB_CHECK_PROFILE, PNG_OPTION_ON); #endif #if PNG_LIBPNG_VER >= 10500 && defined(PNG_UNKNOWN_CHUNKS_SUPPORTED) /* copy standard chunks too */ png_set_keep_unknown_chunks(png_ptr, PNG_HANDLE_CHUNK_IF_SAFE, (png_const_bytep)""pHYs\0iTXt\0tEXt\0zTXt"", 4); #endif png_set_read_user_chunk_fn(png_ptr, &mainprog_ptr->chunks, read_chunk_callback); struct rwpng_read_data read_data = {infile, 0}; png_set_read_fn(png_ptr, &read_data, user_read_data); png_read_info(png_ptr, info_ptr); /* read all PNG info up to image data */ /* alternatively, could make separate calls to png_get_image_width(), * etc., but want bit_depth and color_type for later [don't care about * compression_type and filter_type => NULLs] */ png_get_IHDR(png_ptr, info_ptr, &mainprog_ptr->width, &mainprog_ptr->height, &bit_depth, &color_type, NULL, NULL, NULL); /* expand palette images to RGB, low-bit-depth grayscale images to 8 bits, * transparency chunks to full alpha channel; strip 16-bit-per-sample * images to 8 bits per sample; and convert grayscale to RGB[A] */ /* GRR TO DO: preserve all safe-to-copy ancillary PNG chunks */ if (!(color_type & PNG_COLOR_MASK_ALPHA)) { #ifdef PNG_READ_FILLER_SUPPORTED png_set_expand(png_ptr); png_set_filler(png_ptr, 65535L, PNG_FILLER_AFTER); #else fprintf(stderr, ""pngquant readpng: image is neither RGBA nor GA\n""); png_destroy_read_struct(&png_ptr, &info_ptr, NULL); mainprog_ptr->retval = WRONG_INPUT_COLOR_TYPE; return mainprog_ptr->retval; #endif } if (bit_depth == 16) { png_set_strip_16(png_ptr); } if (!(color_type & PNG_COLOR_MASK_COLOR)) { png_set_gray_to_rgb(png_ptr); } /* get source gamma for gamma correction, or use sRGB default */ double gamma = 0.45455; if (png_get_valid(png_ptr, info_ptr, PNG_INFO_sRGB)) { mainprog_ptr->input_color = RWPNG_SRGB; mainprog_ptr->output_color = RWPNG_SRGB; } else { png_get_gAMA(png_ptr, info_ptr, &gamma); if (gamma > 0 && gamma <= 1.0) { mainprog_ptr->input_color = RWPNG_GAMA_ONLY; mainprog_ptr->output_color = RWPNG_GAMA_ONLY; } else { fprintf(stderr, ""pngquant readpng: ignored out-of-range gamma %f\n"", gamma); mainprog_ptr->input_color = RWPNG_NONE; mainprog_ptr->output_color = RWPNG_NONE; gamma = 0.45455; } } mainprog_ptr->gamma = gamma; png_set_interlace_handling(png_ptr); /* all transformations have been registered; now update info_ptr data, * get rowbytes and channels, and allocate image memory */ png_read_update_info(png_ptr, info_ptr); rowbytes = png_get_rowbytes(png_ptr, info_ptr); // For overflow safety reject images that won't fit in 32-bit if (rowbytes > INT_MAX/mainprog_ptr->height) { png_destroy_read_struct(&png_ptr, &info_ptr, NULL); return PNG_OUT_OF_MEMORY_ERROR; } if ((mainprog_ptr->rgba_data = malloc(rowbytes * mainprog_ptr->height)) == NULL) { fprintf(stderr, ""pngquant readpng: unable to allocate image data\n""); png_destroy_read_struct(&png_ptr, &info_ptr, NULL); return PNG_OUT_OF_MEMORY_ERROR; } png_bytepp row_pointers = rwpng_create_row_pointers(info_ptr, png_ptr, mainprog_ptr->rgba_data, mainprog_ptr->height, 0); /* now we can go ahead and just read the whole image */ png_read_image(png_ptr, row_pointers); /* and we're done! (png_read_end() can be omitted if no processing of * post-IDAT text/time/etc. is desired) */ png_read_end(png_ptr, NULL); #if USE_LCMS #if PNG_LIBPNG_VER < 10500 png_charp ProfileData; #else png_bytep ProfileData; #endif png_uint_32 ProfileLen; cmsHPROFILE hInProfile = NULL; /* color_type is read from the image before conversion to RGBA */ int COLOR_PNG = color_type & PNG_COLOR_MASK_COLOR; /* embedded ICC profile */ if (png_get_iCCP(png_ptr, info_ptr, &(png_charp){0}, &(int){0}, &ProfileData, &ProfileLen)) { hInProfile = cmsOpenProfileFromMem(ProfileData, ProfileLen); cmsColorSpaceSignature colorspace = cmsGetColorSpace(hInProfile); /* only RGB (and GRAY) valid for PNGs */ if (colorspace == cmsSigRgbData && COLOR_PNG) { mainprog_ptr->input_color = RWPNG_ICCP; mainprog_ptr->output_color = RWPNG_SRGB; } else { if (colorspace == cmsSigGrayData && !COLOR_PNG) { mainprog_ptr->input_color = RWPNG_ICCP_WARN_GRAY; mainprog_ptr->output_color = RWPNG_SRGB; } cmsCloseProfile(hInProfile); hInProfile = NULL; } } /* build RGB profile from cHRM and gAMA */ if (hInProfile == NULL && COLOR_PNG && !png_get_valid(png_ptr, info_ptr, PNG_INFO_sRGB) && png_get_valid(png_ptr, info_ptr, PNG_INFO_gAMA) && png_get_valid(png_ptr, info_ptr, PNG_INFO_cHRM)) { cmsCIExyY WhitePoint; cmsCIExyYTRIPLE Primaries; png_get_cHRM(png_ptr, info_ptr, &WhitePoint.x, &WhitePoint.y, &Primaries.Red.x, &Primaries.Red.y, &Primaries.Green.x, &Primaries.Green.y, &Primaries.Blue.x, &Primaries.Blue.y); WhitePoint.Y = Primaries.Red.Y = Primaries.Green.Y = Primaries.Blue.Y = 1.0; cmsToneCurve *GammaTable[3]; GammaTable[0] = GammaTable[1] = GammaTable[2] = cmsBuildGamma(NULL, 1/gamma); hInProfile = cmsCreateRGBProfile(&WhitePoint, &Primaries, GammaTable); cmsFreeToneCurve(GammaTable[0]); mainprog_ptr->input_color = RWPNG_GAMA_CHRM; mainprog_ptr->output_color = RWPNG_SRGB; } /* transform image to sRGB colorspace */ if (hInProfile != NULL) { cmsHPROFILE hOutProfile = cmsCreate_sRGBProfile(); cmsHTRANSFORM hTransform = cmsCreateTransform(hInProfile, TYPE_RGBA_8, hOutProfile, TYPE_RGBA_8, INTENT_PERCEPTUAL, omp_get_max_threads() > 1 ? cmsFLAGS_NOCACHE : 0); #pragma omp parallel for \ if (mainprog_ptr->height*mainprog_ptr->width > 8000) \ schedule(static) for (unsigned int i = 0; i < mainprog_ptr->height; i++) { /* It is safe to use the same block for input and output, when both are of the same TYPE. */ cmsDoTransform(hTransform, row_pointers[i], row_pointers[i], mainprog_ptr->width); } cmsDeleteTransform(hTransform); cmsCloseProfile(hOutProfile); cmsCloseProfile(hInProfile); mainprog_ptr->gamma = 0.45455; } #endif png_destroy_read_struct(&png_ptr, &info_ptr, NULL); mainprog_ptr->file_size = read_data.bytes_read; mainprog_ptr->row_pointers = (unsigned char **)row_pointers; return SUCCESS; }","{'deleted': [{'line_no': 51, 'char_start': 2054, 'char_end': 2116, 'line': ' if (mainprog_ptr->width > INT_MAX/mainprog_ptr->height) {\n'}, {'line_no': 52, 'char_start': 2116, 'char_end': 2176, 'line': ' png_destroy_read_struct(&png_ptr, &info_ptr, NULL);\n'}, {'line_no': 53, 'char_start': 2176, 'char_end': 2252, 'line': ' return PNG_OUT_OF_MEMORY_ERROR; /* not quite true, but whatever */\n'}, {'line_no': 54, 'char_start': 2252, 'char_end': 2258, 'line': ' }\n'}, {'line_no': 55, 'char_start': 2258, 'char_end': 2259, 'line': '\n'}], 'added': [{'line_no': 105, 'char_start': 3976, 'char_end': 4027, 'line': ' if (rowbytes > INT_MAX/mainprog_ptr->height) {\n'}, {'line_no': 106, 'char_start': 4027, 'char_end': 4087, 'line': ' png_destroy_read_struct(&png_ptr, &info_ptr, NULL);\n'}, {'line_no': 107, 'char_start': 4087, 'char_end': 4127, 'line': ' return PNG_OUT_OF_MEMORY_ERROR;\n'}, {'line_no': 108, 'char_start': 4127, 'char_end': 4133, 'line': ' }\n'}, {'line_no': 109, 'char_start': 4133, 'char_end': 4134, 'line': '\n'}]}","{'deleted': [{'char_start': 1993, 'char_end': 2264, 'chars': ""/ For overflow safety reject images that won't fit in 32-bit\n if (mainprog_ptr->width > INT_MAX/mainprog_ptr->height) {\n png_destroy_read_struct(&png_ptr, &info_ptr, NULL);\n return PNG_OUT_OF_MEMORY_ERROR; /* not quite true, but whatever */\n }\n\n /""}], 'added': [{'char_start': 3908, 'char_end': 4132, 'chars': ""\n\n // For overflow safety reject images that won't fit in 32-bit\n if (rowbytes > INT_MAX/mainprog_ptr->height) {\n png_destroy_read_struct(&png_ptr, &info_ptr, NULL);\n return PNG_OUT_OF_MEMORY_ERROR;\n }""}]}",github.com/pornel/pngquant/commit/b7c217680cda02dddced245d237ebe8c383be285,rwpng.c,cwe-190,2127 cwe-089,analyze_smashgg," def analyze_smashgg(self, urls, name): LOG.info('we are about to analyze scene {} with {} brackets'.format(name, len(urls))) for url in urls: # Before we process this URL, check to see if we already have sql = ""SELECT * FROM analyzed where base_url='{}'"".format(url) res = self.db.exec(sql) if len(res) == 0: display_name = bracket_utils.get_display_base(url) # We don't care about doubles tournaments if 'doubles' in display_name.lower() or 'dubs' in display_name.lower(): LOG.info('We are skipping the tournament {} because it is a doubles tournament'.format(display_name)) continue LOG.info('About to process pro bracket {}'.format(url)) self.data_processor.process(url, name, display_name) else: LOG.info(""Skpping pro bracket because it has already been analyzed: {}"".format(url))"," def analyze_smashgg(self, urls, name): LOG.info('we are about to analyze scene {} with {} brackets'.format(name, len(urls))) for url in urls: # Before we process this URL, check to see if we already have sql = ""SELECT * FROM analyzed where base_url='{url}'"" args = {'url':url} res = self.db.exec(sql, args) if len(res) == 0: display_name = bracket_utils.get_display_base(url) # We don't care about doubles tournaments if 'doubles' in display_name.lower() or 'dubs' in display_name.lower(): LOG.info('We are skipping the tournament {} because it is a doubles tournament'.format(display_name)) continue LOG.info('About to process pro bracket {}'.format(url)) self.data_processor.process(url, name, display_name) else: LOG.info(""Skpping pro bracket because it has already been analyzed: {}"".format(url))","{'deleted': [{'line_no': 5, 'char_start': 236, 'char_end': 311, 'line': ' sql = ""SELECT * FROM analyzed where base_url=\'{}\'"".format(url)\n'}, {'line_no': 6, 'char_start': 311, 'char_end': 347, 'line': ' res = self.db.exec(sql)\n'}], 'added': [{'line_no': 5, 'char_start': 236, 'char_end': 302, 'line': ' sql = ""SELECT * FROM analyzed where base_url=\'{url}\'""\n'}, {'line_no': 6, 'char_start': 302, 'char_end': 333, 'line': "" args = {'url':url}\n""}, {'line_no': 7, 'char_start': 333, 'char_end': 375, 'line': ' res = self.db.exec(sql, args)\n'}]}","{'deleted': [{'char_start': 298, 'char_end': 303, 'chars': '.form'}, {'char_start': 304, 'char_end': 306, 'chars': 't('}, {'char_start': 309, 'char_end': 310, 'chars': ')'}], 'added': [{'char_start': 295, 'char_end': 298, 'chars': 'url'}, {'char_start': 301, 'char_end': 324, 'chars': ""\n args = {'u""}, {'char_start': 325, 'char_end': 328, 'chars': ""l':""}, {'char_start': 331, 'char_end': 332, 'chars': '}'}, {'char_start': 367, 'char_end': 373, 'chars': ', args'}]}",github.com/DKelle/Smash_stats/commit/4bb83f3f6ce7d6bebbeb512cd015f9e72cf36d63,validURLs.py,cwe-089,203 cwe-125,ExtractPostscript,"static Image *ExtractPostscript(Image *image,const ImageInfo *image_info, MagickOffsetType PS_Offset,ssize_t PS_Size,ExceptionInfo *exception) { char postscript_file[MaxTextExtent]; const MagicInfo *magic_info; FILE *ps_file; ImageInfo *clone_info; Image *image2; unsigned char magick[2*MaxTextExtent]; if ((clone_info=CloneImageInfo(image_info)) == NULL) return(image); clone_info->blob=(void *) NULL; clone_info->length=0; /* Obtain temporary file */ (void) AcquireUniqueFilename(postscript_file); ps_file=fopen_utf8(postscript_file,""wb""); if (ps_file == (FILE *) NULL) goto FINISH; /* Copy postscript to temporary file */ (void) SeekBlob(image,PS_Offset,SEEK_SET); (void) ReadBlob(image, 2*MaxTextExtent, magick); (void) SeekBlob(image,PS_Offset,SEEK_SET); while(PS_Size-- > 0) { (void) fputc(ReadBlobByte(image),ps_file); } (void) fclose(ps_file); /* Detect file format - Check magic.mgk configuration file. */ magic_info=GetMagicInfo(magick,2*MaxTextExtent,exception); if(magic_info == (const MagicInfo *) NULL) goto FINISH_UNL; /* printf(""Detected:%s \n"",magic_info->name); */ if(exception->severity != UndefinedException) goto FINISH_UNL; if(magic_info->name == (char *) NULL) goto FINISH_UNL; (void) CopyMagickMemory(clone_info->magick,magic_info->name,MaxTextExtent); /* Read nested image */ /*FormatString(clone_info->filename,""%s:%s"",magic_info->name,postscript_file);*/ FormatLocaleString(clone_info->filename,MaxTextExtent,""%s"",postscript_file); image2=ReadImage(clone_info,exception); if (!image2) goto FINISH_UNL; /* Replace current image with new image while copying base image attributes. */ (void) CopyMagickMemory(image2->filename,image->filename,MaxTextExtent); (void) CopyMagickMemory(image2->magick_filename,image->magick_filename,MaxTextExtent); (void) CopyMagickMemory(image2->magick,image->magick,MaxTextExtent); image2->depth=image->depth; DestroyBlob(image2); image2->blob=ReferenceBlob(image->blob); if ((image->rows == 0) || (image->columns == 0)) DeleteImageFromList(&image); AppendImageToList(&image,image2); FINISH_UNL: (void) RelinquishUniqueFileResource(postscript_file); FINISH: DestroyImageInfo(clone_info); return(image); }","static Image *ExtractPostscript(Image *image,const ImageInfo *image_info, MagickOffsetType PS_Offset,ssize_t PS_Size,ExceptionInfo *exception) { char postscript_file[MaxTextExtent]; const MagicInfo *magic_info; FILE *ps_file; ImageInfo *clone_info; Image *image2; unsigned char magick[2*MaxTextExtent]; if ((clone_info=CloneImageInfo(image_info)) == NULL) return(image); clone_info->blob=(void *) NULL; clone_info->length=0; /* Obtain temporary file */ (void) AcquireUniqueFilename(postscript_file); ps_file=fopen_utf8(postscript_file,""wb""); if (ps_file == (FILE *) NULL) goto FINISH; /* Copy postscript to temporary file */ (void) SeekBlob(image,PS_Offset,SEEK_SET); (void) ReadBlob(image, 2*MaxTextExtent, magick); (void) SeekBlob(image,PS_Offset,SEEK_SET); while(PS_Size-- > 0) { (void) fputc(ReadBlobByte(image),ps_file); } (void) fclose(ps_file); /* Detect file format - Check magic.mgk configuration file. */ magic_info=GetMagicInfo(magick,2*MaxTextExtent,exception); if(magic_info == (const MagicInfo *) NULL) goto FINISH_UNL; /* printf(""Detected:%s \n"",magic_info->name); */ if(exception->severity != UndefinedException) goto FINISH_UNL; if(magic_info->name == (char *) NULL) goto FINISH_UNL; (void) strncpy(clone_info->magick,magic_info->name,MaxTextExtent); /* Read nested image */ /*FormatString(clone_info->filename,""%s:%s"",magic_info->name,postscript_file);*/ FormatLocaleString(clone_info->filename,MaxTextExtent,""%s"",postscript_file); image2=ReadImage(clone_info,exception); if (!image2) goto FINISH_UNL; /* Replace current image with new image while copying base image attributes. */ (void) CopyMagickMemory(image2->filename,image->filename,MaxTextExtent); (void) CopyMagickMemory(image2->magick_filename,image->magick_filename,MaxTextExtent); (void) CopyMagickMemory(image2->magick,image->magick,MaxTextExtent); image2->depth=image->depth; DestroyBlob(image2); image2->blob=ReferenceBlob(image->blob); if ((image->rows == 0) || (image->columns == 0)) DeleteImageFromList(&image); AppendImageToList(&image,image2); FINISH_UNL: (void) RelinquishUniqueFileResource(postscript_file); FINISH: DestroyImageInfo(clone_info); return(image); }","{'deleted': [{'line_no': 52, 'char_start': 1318, 'char_end': 1396, 'line': ' (void) CopyMagickMemory(clone_info->magick,magic_info->name,MaxTextExtent);\n'}], 'added': [{'line_no': 52, 'char_start': 1318, 'char_end': 1387, 'line': ' (void) strncpy(clone_info->magick,magic_info->name,MaxTextExtent);\n'}]}","{'deleted': [{'char_start': 1327, 'char_end': 1329, 'chars': 'Co'}, {'char_start': 1330, 'char_end': 1342, 'chars': 'yMagickMemor'}], 'added': [{'char_start': 1327, 'char_end': 1329, 'chars': 'st'}, {'char_start': 1330, 'char_end': 1333, 'chars': 'ncp'}]}",github.com/ImageMagick/ImageMagick/commit/a251039393f423c7858e63cab6aa98d17b8b7a41,coders/wpg.c,cwe-125,654 cwe-476,keyctl_read_key,"long keyctl_read_key(key_serial_t keyid, char __user *buffer, size_t buflen) { struct key *key; key_ref_t key_ref; long ret; /* find the key first */ key_ref = lookup_user_key(keyid, 0, 0); if (IS_ERR(key_ref)) { ret = -ENOKEY; goto error; } key = key_ref_to_ptr(key_ref); /* see if we can read it directly */ ret = key_permission(key_ref, KEY_NEED_READ); if (ret == 0) goto can_read_key; if (ret != -EACCES) goto error2; /* we can't; see if it's searchable from this process's keyrings * - we automatically take account of the fact that it may be * dangling off an instantiation key */ if (!is_key_possessed(key_ref)) { ret = -EACCES; goto error2; } /* the key is probably readable - now try to read it */ can_read_key: ret = -EOPNOTSUPP; if (key->type->read) { /* Read the data with the semaphore held (since we might sleep) * to protect against the key being updated or revoked. */ down_read(&key->sem); ret = key_validate(key); if (ret == 0) ret = key->type->read(key, buffer, buflen); up_read(&key->sem); } error2: key_put(key); error: return ret; }","long keyctl_read_key(key_serial_t keyid, char __user *buffer, size_t buflen) { struct key *key; key_ref_t key_ref; long ret; /* find the key first */ key_ref = lookup_user_key(keyid, 0, 0); if (IS_ERR(key_ref)) { ret = -ENOKEY; goto error; } key = key_ref_to_ptr(key_ref); if (test_bit(KEY_FLAG_NEGATIVE, &key->flags)) { ret = -ENOKEY; goto error2; } /* see if we can read it directly */ ret = key_permission(key_ref, KEY_NEED_READ); if (ret == 0) goto can_read_key; if (ret != -EACCES) goto error2; /* we can't; see if it's searchable from this process's keyrings * - we automatically take account of the fact that it may be * dangling off an instantiation key */ if (!is_key_possessed(key_ref)) { ret = -EACCES; goto error2; } /* the key is probably readable - now try to read it */ can_read_key: ret = -EOPNOTSUPP; if (key->type->read) { /* Read the data with the semaphore held (since we might sleep) * to protect against the key being updated or revoked. */ down_read(&key->sem); ret = key_validate(key); if (ret == 0) ret = key->type->read(key, buffer, buflen); up_read(&key->sem); } error2: key_put(key); error: return ret; }","{'deleted': [], 'added': [{'line_no': 16, 'char_start': 288, 'char_end': 337, 'line': '\tif (test_bit(KEY_FLAG_NEGATIVE, &key->flags)) {\n'}, {'line_no': 17, 'char_start': 337, 'char_end': 354, 'line': '\t\tret = -ENOKEY;\n'}, {'line_no': 18, 'char_start': 354, 'char_end': 369, 'line': '\t\tgoto error2;\n'}, {'line_no': 19, 'char_start': 369, 'char_end': 372, 'line': '\t}\n'}, {'line_no': 20, 'char_start': 372, 'char_end': 373, 'line': '\n'}]}","{'deleted': [], 'added': [{'char_start': 289, 'char_end': 374, 'chars': 'if (test_bit(KEY_FLAG_NEGATIVE, &key->flags)) {\n\t\tret = -ENOKEY;\n\t\tgoto error2;\n\t}\n\n\t'}]}",github.com/torvalds/linux/commit/37863c43b2c6464f252862bf2e9768264e961678,security/keys/keyctl.c,cwe-476,334 cwe-190,git_delta_apply,"int git_delta_apply( void **out, size_t *out_len, const unsigned char *base, size_t base_len, const unsigned char *delta, size_t delta_len) { const unsigned char *delta_end = delta + delta_len; size_t base_sz, res_sz, alloc_sz; unsigned char *res_dp; *out = NULL; *out_len = 0; /* * Check that the base size matches the data we were given; * if not we would underflow while accessing data from the * base object, resulting in data corruption or segfault. */ if ((hdr_sz(&base_sz, &delta, delta_end) < 0) || (base_sz != base_len)) { giterr_set(GITERR_INVALID, ""failed to apply delta: base size does not match given data""); return -1; } if (hdr_sz(&res_sz, &delta, delta_end) < 0) { giterr_set(GITERR_INVALID, ""failed to apply delta: base size does not match given data""); return -1; } GITERR_CHECK_ALLOC_ADD(&alloc_sz, res_sz, 1); res_dp = git__malloc(alloc_sz); GITERR_CHECK_ALLOC(res_dp); res_dp[res_sz] = '\0'; *out = res_dp; *out_len = res_sz; while (delta < delta_end) { unsigned char cmd = *delta++; if (cmd & 0x80) { /* cmd is a copy instruction; copy from the base. */ size_t off = 0, len = 0; #define ADD_DELTA(o, shift) { if (delta < delta_end) (o) |= ((unsigned) *delta++ << shift); else goto fail; } if (cmd & 0x01) ADD_DELTA(off, 0UL); if (cmd & 0x02) ADD_DELTA(off, 8UL); if (cmd & 0x04) ADD_DELTA(off, 16UL); if (cmd & 0x08) ADD_DELTA(off, 24UL); if (cmd & 0x10) ADD_DELTA(len, 0UL); if (cmd & 0x20) ADD_DELTA(len, 8UL); if (cmd & 0x40) ADD_DELTA(len, 16UL); if (!len) len = 0x10000; #undef ADD_DELTA if (base_len < off + len || res_sz < len) goto fail; memcpy(res_dp, base + off, len); res_dp += len; res_sz -= len; } else if (cmd) { /* * cmd is a literal insert instruction; copy from * the delta stream itself. */ if (delta_end - delta < cmd || res_sz < cmd) goto fail; memcpy(res_dp, delta, cmd); delta += cmd; res_dp += cmd; res_sz -= cmd; } else { /* cmd == 0 is reserved for future encodings. */ goto fail; } } if (delta != delta_end || res_sz) goto fail; return 0; fail: git__free(*out); *out = NULL; *out_len = 0; giterr_set(GITERR_INVALID, ""failed to apply delta""); return -1; }","int git_delta_apply( void **out, size_t *out_len, const unsigned char *base, size_t base_len, const unsigned char *delta, size_t delta_len) { const unsigned char *delta_end = delta + delta_len; size_t base_sz, res_sz, alloc_sz; unsigned char *res_dp; *out = NULL; *out_len = 0; /* * Check that the base size matches the data we were given; * if not we would underflow while accessing data from the * base object, resulting in data corruption or segfault. */ if ((hdr_sz(&base_sz, &delta, delta_end) < 0) || (base_sz != base_len)) { giterr_set(GITERR_INVALID, ""failed to apply delta: base size does not match given data""); return -1; } if (hdr_sz(&res_sz, &delta, delta_end) < 0) { giterr_set(GITERR_INVALID, ""failed to apply delta: base size does not match given data""); return -1; } GITERR_CHECK_ALLOC_ADD(&alloc_sz, res_sz, 1); res_dp = git__malloc(alloc_sz); GITERR_CHECK_ALLOC(res_dp); res_dp[res_sz] = '\0'; *out = res_dp; *out_len = res_sz; while (delta < delta_end) { unsigned char cmd = *delta++; if (cmd & 0x80) { /* cmd is a copy instruction; copy from the base. */ size_t off = 0, len = 0, end; #define ADD_DELTA(o, shift) { if (delta < delta_end) (o) |= ((unsigned) *delta++ << shift); else goto fail; } if (cmd & 0x01) ADD_DELTA(off, 0UL); if (cmd & 0x02) ADD_DELTA(off, 8UL); if (cmd & 0x04) ADD_DELTA(off, 16UL); if (cmd & 0x08) ADD_DELTA(off, 24UL); if (cmd & 0x10) ADD_DELTA(len, 0UL); if (cmd & 0x20) ADD_DELTA(len, 8UL); if (cmd & 0x40) ADD_DELTA(len, 16UL); if (!len) len = 0x10000; #undef ADD_DELTA if (GIT_ADD_SIZET_OVERFLOW(&end, off, len) || base_len < end || res_sz < len) goto fail; memcpy(res_dp, base + off, len); res_dp += len; res_sz -= len; } else if (cmd) { /* * cmd is a literal insert instruction; copy from * the delta stream itself. */ if (delta_end - delta < cmd || res_sz < cmd) goto fail; memcpy(res_dp, delta, cmd); delta += cmd; res_dp += cmd; res_sz -= cmd; } else { /* cmd == 0 is reserved for future encodings. */ goto fail; } } if (delta != delta_end || res_sz) goto fail; return 0; fail: git__free(*out); *out = NULL; *out_len = 0; giterr_set(GITERR_INVALID, ""failed to apply delta""); return -1; }","{'deleted': [{'line_no': 43, 'char_start': 1128, 'char_end': 1156, 'line': '\t\t\tsize_t off = 0, len = 0;\n'}, {'line_no': 57, 'char_start': 1603, 'char_end': 1648, 'line': '\t\t\tif (base_len < off + len || res_sz < len)\n'}], 'added': [{'line_no': 43, 'char_start': 1128, 'char_end': 1161, 'line': '\t\t\tsize_t off = 0, len = 0, end;\n'}, {'line_no': 57, 'char_start': 1608, 'char_end': 1657, 'line': '\t\t\tif (GIT_ADD_SIZET_OVERFLOW(&end, off, len) ||\n'}, {'line_no': 58, 'char_start': 1657, 'char_end': 1696, 'line': '\t\t\t base_len < end || res_sz < len)\n'}, {'line_no': 60, 'char_start': 1711, 'char_end': 1712, 'line': '\n'}]}","{'deleted': [{'char_start': 1621, 'char_end': 1628, 'chars': 'off + l'}], 'added': [{'char_start': 1154, 'char_end': 1159, 'chars': ', end'}, {'char_start': 1615, 'char_end': 1664, 'chars': 'GIT_ADD_SIZET_OVERFLOW(&end, off, len) ||\n\t\t\t '}, {'char_start': 1677, 'char_end': 1678, 'chars': 'd'}, {'char_start': 1710, 'char_end': 1711, 'chars': '\n'}]}",github.com/libgit2/libgit2/commit/c1577110467b701dcbcf9439ac225ea851b47d22,src/delta.c,cwe-190,738 cwe-079,history_data,"def history_data(start_time, offset=None): """"""Return history data. Arguments: start_time: select history starting from this timestamp. offset: number of items to skip """""" # history atimes are stored as ints, ensure start_time is not a float start_time = int(start_time) hist = objreg.get('web-history') if offset is not None: entries = hist.entries_before(start_time, limit=1000, offset=offset) else: # end is 24hrs earlier than start end_time = start_time - 24*60*60 entries = hist.entries_between(end_time, start_time) return [{""url"": e.url, ""title"": e.title or e.url, ""time"": e.atime} for e in entries]","def history_data(start_time, offset=None): """"""Return history data. Arguments: start_time: select history starting from this timestamp. offset: number of items to skip """""" # history atimes are stored as ints, ensure start_time is not a float start_time = int(start_time) hist = objreg.get('web-history') if offset is not None: entries = hist.entries_before(start_time, limit=1000, offset=offset) else: # end is 24hrs earlier than start end_time = start_time - 24*60*60 entries = hist.entries_between(end_time, start_time) return [{""url"": html.escape(e.url), ""title"": html.escape(e.title) or html.escape(e.url), ""time"": e.atime} for e in entries]","{'deleted': [{'line_no': 18, 'char_start': 603, 'char_end': 674, 'line': ' return [{""url"": e.url, ""title"": e.title or e.url, ""time"": e.atime}\n'}, {'line_no': 19, 'char_start': 674, 'char_end': 703, 'line': ' for e in entries]\n'}], 'added': [{'line_no': 18, 'char_start': 603, 'char_end': 643, 'line': ' return [{""url"": html.escape(e.url),\n'}, {'line_no': 19, 'char_start': 643, 'char_end': 709, 'line': ' ""title"": html.escape(e.title) or html.escape(e.url),\n'}, {'line_no': 20, 'char_start': 709, 'char_end': 756, 'line': ' ""time"": e.atime} for e in entries]\n'}]}","{'deleted': [{'char_start': 673, 'char_end': 685, 'chars': '\n '}], 'added': [{'char_start': 623, 'char_end': 635, 'chars': 'html.escape('}, {'char_start': 640, 'char_end': 641, 'chars': ')'}, {'char_start': 642, 'char_end': 655, 'chars': '\n '}, {'char_start': 665, 'char_end': 677, 'chars': 'html.escape('}, {'char_start': 684, 'char_end': 685, 'chars': ')'}, {'char_start': 689, 'char_end': 701, 'chars': 'html.escape('}, {'char_start': 706, 'char_end': 707, 'chars': ')'}, {'char_start': 708, 'char_end': 721, 'chars': '\n '}]}",github.com/qutebrowser/qutebrowser/commit/4c9360237f186681b1e3f2a0f30c45161cf405c7,qutebrowser/browser/qutescheme.py,cwe-079,177 cwe-125,update_read_icon_info,"static BOOL update_read_icon_info(wStream* s, ICON_INFO* iconInfo) { BYTE* newBitMask; if (Stream_GetRemainingLength(s) < 8) return FALSE; Stream_Read_UINT16(s, iconInfo->cacheEntry); /* cacheEntry (2 bytes) */ Stream_Read_UINT8(s, iconInfo->cacheId); /* cacheId (1 byte) */ Stream_Read_UINT8(s, iconInfo->bpp); /* bpp (1 byte) */ if ((iconInfo->bpp < 1) || (iconInfo->bpp > 32)) { WLog_ERR(TAG, ""invalid bpp value %"" PRIu32 """", iconInfo->bpp); return FALSE; } Stream_Read_UINT16(s, iconInfo->width); /* width (2 bytes) */ Stream_Read_UINT16(s, iconInfo->height); /* height (2 bytes) */ /* cbColorTable is only present when bpp is 1, 4 or 8 */ switch (iconInfo->bpp) { case 1: case 4: case 8: if (Stream_GetRemainingLength(s) < 2) return FALSE; Stream_Read_UINT16(s, iconInfo->cbColorTable); /* cbColorTable (2 bytes) */ break; default: iconInfo->cbColorTable = 0; break; } if (Stream_GetRemainingLength(s) < 4) return FALSE; Stream_Read_UINT16(s, iconInfo->cbBitsMask); /* cbBitsMask (2 bytes) */ Stream_Read_UINT16(s, iconInfo->cbBitsColor); /* cbBitsColor (2 bytes) */ if (Stream_GetRemainingLength(s) < iconInfo->cbBitsMask + iconInfo->cbBitsColor) return FALSE; /* bitsMask */ newBitMask = (BYTE*)realloc(iconInfo->bitsMask, iconInfo->cbBitsMask); if (!newBitMask) { free(iconInfo->bitsMask); iconInfo->bitsMask = NULL; return FALSE; } iconInfo->bitsMask = newBitMask; Stream_Read(s, iconInfo->bitsMask, iconInfo->cbBitsMask); /* colorTable */ if (iconInfo->colorTable == NULL) { if (iconInfo->cbColorTable) { iconInfo->colorTable = (BYTE*)malloc(iconInfo->cbColorTable); if (!iconInfo->colorTable) return FALSE; } } else if (iconInfo->cbColorTable) { BYTE* new_tab; new_tab = (BYTE*)realloc(iconInfo->colorTable, iconInfo->cbColorTable); if (!new_tab) { free(iconInfo->colorTable); iconInfo->colorTable = NULL; return FALSE; } iconInfo->colorTable = new_tab; } else { free(iconInfo->colorTable); iconInfo->colorTable = NULL; } if (iconInfo->colorTable) Stream_Read(s, iconInfo->colorTable, iconInfo->cbColorTable); /* bitsColor */ newBitMask = (BYTE*)realloc(iconInfo->bitsColor, iconInfo->cbBitsColor); if (!newBitMask) { free(iconInfo->bitsColor); iconInfo->bitsColor = NULL; return FALSE; } iconInfo->bitsColor = newBitMask; Stream_Read(s, iconInfo->bitsColor, iconInfo->cbBitsColor); return TRUE; }","static BOOL update_read_icon_info(wStream* s, ICON_INFO* iconInfo) { BYTE* newBitMask; if (Stream_GetRemainingLength(s) < 8) return FALSE; Stream_Read_UINT16(s, iconInfo->cacheEntry); /* cacheEntry (2 bytes) */ Stream_Read_UINT8(s, iconInfo->cacheId); /* cacheId (1 byte) */ Stream_Read_UINT8(s, iconInfo->bpp); /* bpp (1 byte) */ if ((iconInfo->bpp < 1) || (iconInfo->bpp > 32)) { WLog_ERR(TAG, ""invalid bpp value %"" PRIu32 """", iconInfo->bpp); return FALSE; } Stream_Read_UINT16(s, iconInfo->width); /* width (2 bytes) */ Stream_Read_UINT16(s, iconInfo->height); /* height (2 bytes) */ /* cbColorTable is only present when bpp is 1, 4 or 8 */ switch (iconInfo->bpp) { case 1: case 4: case 8: if (Stream_GetRemainingLength(s) < 2) return FALSE; Stream_Read_UINT16(s, iconInfo->cbColorTable); /* cbColorTable (2 bytes) */ break; default: iconInfo->cbColorTable = 0; break; } if (Stream_GetRemainingLength(s) < 4) return FALSE; Stream_Read_UINT16(s, iconInfo->cbBitsMask); /* cbBitsMask (2 bytes) */ Stream_Read_UINT16(s, iconInfo->cbBitsColor); /* cbBitsColor (2 bytes) */ /* bitsMask */ newBitMask = (BYTE*)realloc(iconInfo->bitsMask, iconInfo->cbBitsMask); if (!newBitMask) { free(iconInfo->bitsMask); iconInfo->bitsMask = NULL; return FALSE; } iconInfo->bitsMask = newBitMask; if (Stream_GetRemainingLength(s) < iconInfo->cbBitsMask) return FALSE; Stream_Read(s, iconInfo->bitsMask, iconInfo->cbBitsMask); /* colorTable */ if (iconInfo->colorTable == NULL) { if (iconInfo->cbColorTable) { iconInfo->colorTable = (BYTE*)malloc(iconInfo->cbColorTable); if (!iconInfo->colorTable) return FALSE; } } else if (iconInfo->cbColorTable) { BYTE* new_tab; new_tab = (BYTE*)realloc(iconInfo->colorTable, iconInfo->cbColorTable); if (!new_tab) { free(iconInfo->colorTable); iconInfo->colorTable = NULL; return FALSE; } iconInfo->colorTable = new_tab; } else { free(iconInfo->colorTable); iconInfo->colorTable = NULL; } if (iconInfo->colorTable) { if (Stream_GetRemainingLength(s) < iconInfo->cbColorTable) return FALSE; Stream_Read(s, iconInfo->colorTable, iconInfo->cbColorTable); } /* bitsColor */ newBitMask = (BYTE*)realloc(iconInfo->bitsColor, iconInfo->cbBitsColor); if (!newBitMask) { free(iconInfo->bitsColor); iconInfo->bitsColor = NULL; return FALSE; } iconInfo->bitsColor = newBitMask; if (Stream_GetRemainingLength(s) < iconInfo->cbBitsColor) return FALSE; Stream_Read(s, iconInfo->bitsColor, iconInfo->cbBitsColor); return TRUE; }","{'deleted': [{'line_no': 44, 'char_start': 1148, 'char_end': 1230, 'line': '\tif (Stream_GetRemainingLength(s) < iconInfo->cbBitsMask + iconInfo->cbBitsColor)\n'}, {'line_no': 45, 'char_start': 1230, 'char_end': 1246, 'line': '\t\treturn FALSE;\n'}, {'line_no': 46, 'char_start': 1246, 'char_end': 1247, 'line': '\n'}], 'added': [{'line_no': 55, 'char_start': 1369, 'char_end': 1427, 'line': '\tif (Stream_GetRemainingLength(s) < iconInfo->cbBitsMask)\n'}, {'line_no': 56, 'char_start': 1427, 'char_end': 1443, 'line': '\t\treturn FALSE;\n'}, {'line_no': 91, 'char_start': 2086, 'char_end': 2089, 'line': '\t{\n'}, {'line_no': 92, 'char_start': 2089, 'char_end': 2150, 'line': '\t\tif (Stream_GetRemainingLength(s) < iconInfo->cbColorTable)\n'}, {'line_no': 93, 'char_start': 2150, 'char_end': 2167, 'line': '\t\t\treturn FALSE;\n'}, {'line_no': 95, 'char_start': 2231, 'char_end': 2234, 'line': '\t}\n'}, {'line_no': 108, 'char_start': 2462, 'char_end': 2521, 'line': '\tif (Stream_GetRemainingLength(s) < iconInfo->cbBitsColor)\n'}, {'line_no': 109, 'char_start': 2521, 'char_end': 2537, 'line': '\t\treturn FALSE;\n'}]}","{'deleted': [{'char_start': 1149, 'char_end': 1248, 'chars': 'if (Stream_GetRemainingLength(s) < iconInfo->cbBitsMask + iconInfo->cbBitsColor)\n\t\treturn FALSE;\n\n\t'}, {'char_start': 2368, 'char_end': 2368, 'chars': ''}], 'added': [{'char_start': 1164, 'char_end': 1164, 'chars': ''}, {'char_start': 1369, 'char_end': 1443, 'chars': '\tif (Stream_GetRemainingLength(s) < iconInfo->cbBitsMask)\n\t\treturn FALSE;\n'}, {'char_start': 2086, 'char_end': 2167, 'chars': '\t{\n\t\tif (Stream_GetRemainingLength(s) < iconInfo->cbColorTable)\n\t\t\treturn FALSE;\n'}, {'char_start': 2230, 'char_end': 2233, 'chars': '\n\t}'}, {'char_start': 2460, 'char_end': 2535, 'chars': ';\n\tif (Stream_GetRemainingLength(s) < iconInfo->cbBitsColor)\n\t\treturn FALSE'}]}",github.com/FreeRDP/FreeRDP/commit/6b2bc41935e53b0034fe5948aeeab4f32e80f30f,libfreerdp/core/window.c,cwe-125,769 cwe-125,avr_op_analyze,"static OPCODE_DESC* avr_op_analyze(RAnal *anal, RAnalOp *op, ut64 addr, const ut8 *buf, int len, CPU_MODEL *cpu) { OPCODE_DESC *opcode_desc; ut16 ins = (buf[1] << 8) | buf[0]; int fail; char *t; // initialize op struct memset (op, 0, sizeof (RAnalOp)); op->ptr = UT64_MAX; op->val = UT64_MAX; op->jump = UT64_MAX; r_strbuf_init (&op->esil); // process opcode for (opcode_desc = opcodes; opcode_desc->handler; opcode_desc++) { if ((ins & opcode_desc->mask) == opcode_desc->selector) { fail = 0; // copy default cycles/size values op->cycles = opcode_desc->cycles; op->size = opcode_desc->size; op->type = opcode_desc->type; op->jump = UT64_MAX; op->fail = UT64_MAX; // op->fail = addr + op->size; op->addr = addr; // start void esil expression r_strbuf_setf (&op->esil, """"); // handle opcode opcode_desc->handler (anal, op, buf, len, &fail, cpu); if (fail) { goto INVALID_OP; } if (op->cycles <= 0) { // eprintf (""opcode %s @%""PFMT64x"" returned 0 cycles.\n"", opcode_desc->name, op->addr); opcode_desc->cycles = 2; } op->nopcode = (op->type == R_ANAL_OP_TYPE_UNK); // remove trailing coma (COMETE LA COMA) t = r_strbuf_get (&op->esil); if (t && strlen (t) > 1) { t += strlen (t) - 1; if (*t == ',') { *t = '\0'; } } return opcode_desc; } } // ignore reserved opcodes (if they have not been caught by the previous loop) if ((ins & 0xff00) == 0xff00 && (ins & 0xf) > 7) { goto INVALID_OP; } INVALID_OP: // An unknown or invalid option has appeared. // -- Throw pokeball! op->family = R_ANAL_OP_FAMILY_UNKNOWN; op->type = R_ANAL_OP_TYPE_UNK; op->addr = addr; op->fail = UT64_MAX; op->jump = UT64_MAX; op->ptr = UT64_MAX; op->val = UT64_MAX; op->nopcode = 1; op->cycles = 1; op->size = 2; // launch esil trap (for communicating upper layers about this weird // and stinky situation r_strbuf_set (&op->esil, ""1,$""); return NULL; }","static OPCODE_DESC* avr_op_analyze(RAnal *anal, RAnalOp *op, ut64 addr, const ut8 *buf, int len, CPU_MODEL *cpu) { OPCODE_DESC *opcode_desc; if (len < 2) { return NULL; } ut16 ins = (buf[1] << 8) | buf[0]; int fail; char *t; // initialize op struct memset (op, 0, sizeof (RAnalOp)); op->ptr = UT64_MAX; op->val = UT64_MAX; op->jump = UT64_MAX; r_strbuf_init (&op->esil); // process opcode for (opcode_desc = opcodes; opcode_desc->handler; opcode_desc++) { if ((ins & opcode_desc->mask) == opcode_desc->selector) { fail = 0; // copy default cycles/size values op->cycles = opcode_desc->cycles; op->size = opcode_desc->size; op->type = opcode_desc->type; op->jump = UT64_MAX; op->fail = UT64_MAX; // op->fail = addr + op->size; op->addr = addr; // start void esil expression r_strbuf_setf (&op->esil, """"); // handle opcode opcode_desc->handler (anal, op, buf, len, &fail, cpu); if (fail) { goto INVALID_OP; } if (op->cycles <= 0) { // eprintf (""opcode %s @%""PFMT64x"" returned 0 cycles.\n"", opcode_desc->name, op->addr); opcode_desc->cycles = 2; } op->nopcode = (op->type == R_ANAL_OP_TYPE_UNK); // remove trailing coma (COMETE LA COMA) t = r_strbuf_get (&op->esil); if (t && strlen (t) > 1) { t += strlen (t) - 1; if (*t == ',') { *t = '\0'; } } return opcode_desc; } } // ignore reserved opcodes (if they have not been caught by the previous loop) if ((ins & 0xff00) == 0xff00 && (ins & 0xf) > 7) { goto INVALID_OP; } INVALID_OP: // An unknown or invalid option has appeared. // -- Throw pokeball! op->family = R_ANAL_OP_FAMILY_UNKNOWN; op->type = R_ANAL_OP_TYPE_UNK; op->addr = addr; op->fail = UT64_MAX; op->jump = UT64_MAX; op->ptr = UT64_MAX; op->val = UT64_MAX; op->nopcode = 1; op->cycles = 1; op->size = 2; // launch esil trap (for communicating upper layers about this weird // and stinky situation r_strbuf_set (&op->esil, ""1,$""); return NULL; }","{'deleted': [], 'added': [{'line_no': 3, 'char_start': 142, 'char_end': 158, 'line': '\tif (len < 2) {\n'}, {'line_no': 4, 'char_start': 158, 'char_end': 173, 'line': '\t\treturn NULL;\n'}, {'line_no': 5, 'char_start': 173, 'char_end': 176, 'line': '\t}\n'}]}","{'deleted': [], 'added': [{'char_start': 143, 'char_end': 177, 'chars': 'if (len < 2) {\n\t\treturn NULL;\n\t}\n\t'}]}",github.com/radare/radare2/commit/b35530fa0681b27eba084de5527037ebfb397422,libr/anal/p/anal_avr.c,cwe-125,677 cwe-089,verify_rno," def verify_rno(self, rno): query = ""SELECT COUNT(rno) FROM rides WHERE rno = {rno}"".format(rno = rno) self.cursor.execute(query) result = self.cursor.fetchone() if (int(result[0]) > 0): return True else: return False"," def verify_rno(self, rno): self.cursor.execute(""SELECT COUNT(rno) FROM rides WHERE rno = :rno"", {'rno': rno}) result = self.cursor.fetchone() if (int(result[0]) > 0): return True else: return False","{'deleted': [{'line_no': 2, 'char_start': 31, 'char_end': 114, 'line': ' query = ""SELECT COUNT(rno) FROM rides WHERE rno = {rno}"".format(rno = rno)\n'}, {'line_no': 3, 'char_start': 114, 'char_end': 149, 'line': ' self.cursor.execute(query)\n'}], 'added': [{'line_no': 2, 'char_start': 31, 'char_end': 122, 'line': ' self.cursor.execute(""SELECT COUNT(rno) FROM rides WHERE rno = :rno"", {\'rno\': rno})\n'}]}","{'deleted': [{'char_start': 39, 'char_end': 41, 'chars': 'qu'}, {'char_start': 43, 'char_end': 47, 'chars': 'y = '}, {'char_start': 89, 'char_end': 90, 'chars': '{'}, {'char_start': 93, 'char_end': 94, 'chars': '}'}, {'char_start': 95, 'char_end': 103, 'chars': '.format('}, {'char_start': 106, 'char_end': 108, 'chars': ' ='}, {'char_start': 112, 'char_end': 147, 'chars': ')\n self.cursor.execute(query'}], 'added': [{'char_start': 39, 'char_end': 55, 'chars': 'self.cursor.exec'}, {'char_start': 56, 'char_end': 57, 'chars': 't'}, {'char_start': 58, 'char_end': 59, 'chars': '('}, {'char_start': 101, 'char_end': 102, 'chars': ':'}, {'char_start': 106, 'char_end': 107, 'chars': ','}, {'char_start': 108, 'char_end': 110, 'chars': ""{'""}, {'char_start': 113, 'char_end': 115, 'chars': ""':""}, {'char_start': 117, 'char_end': 118, 'chars': 'n'}, {'char_start': 119, 'char_end': 120, 'chars': '}'}]}",github.com/kenboo98/291-Mini-Project-I/commit/3080ccb687c79c83954ce703faee8fcceec8c9eb,book_rides/book_rides.py,cwe-089,71 cwe-476,mrb_class_real,"mrb_class_real(struct RClass* cl) { if (cl == 0) return NULL; while ((cl->tt == MRB_TT_SCLASS) || (cl->tt == MRB_TT_ICLASS)) { cl = cl->super; } return cl; }","mrb_class_real(struct RClass* cl) { if (cl == 0) return NULL; while ((cl->tt == MRB_TT_SCLASS) || (cl->tt == MRB_TT_ICLASS)) { cl = cl->super; if (cl == 0) return NULL; } return cl; }","{'deleted': [{'line_no': 3, 'char_start': 36, 'char_end': 51, 'line': ' if (cl == 0)\n'}, {'line_no': 4, 'char_start': 51, 'char_end': 68, 'line': ' return NULL;\n'}], 'added': [{'line_no': 3, 'char_start': 36, 'char_end': 64, 'line': ' if (cl == 0) return NULL;\n'}, {'line_no': 6, 'char_start': 151, 'char_end': 181, 'line': ' if (cl == 0) return NULL;\n'}]}","{'deleted': [{'char_start': 50, 'char_end': 54, 'chars': '\n '}], 'added': [{'char_start': 149, 'char_end': 179, 'chars': ';\n if (cl == 0) return NULL'}]}",github.com/mruby/mruby/commit/faa4eaf6803bd11669bc324b4c34e7162286bfa3,src/class.c,cwe-476,66 cwe-416,audio_sample_entry_Read,"GF_Err audio_sample_entry_Read(GF_Box *s, GF_BitStream *bs) { GF_MPEGAudioSampleEntryBox *ptr; char *data; u8 a, b, c, d; u32 i, size, v, nb_alnum; GF_Err e; u64 pos, start; ptr = (GF_MPEGAudioSampleEntryBox *)s; start = gf_bs_get_position(bs); gf_bs_seek(bs, start + 8); v = gf_bs_read_u16(bs); if (v) ptr->is_qtff = 1; //try to disambiguate QTFF v1 and MP4 v1 audio sample entries ... if (v==1) { //go to end of ISOM audio sample entry, skip 4 byte (box size field), read 4 bytes (box type) and check if this looks like a box gf_bs_seek(bs, start + 8 + 20 + 4); a = gf_bs_read_u8(bs); b = gf_bs_read_u8(bs); c = gf_bs_read_u8(bs); d = gf_bs_read_u8(bs); nb_alnum = 0; if (isalnum(a)) nb_alnum++; if (isalnum(b)) nb_alnum++; if (isalnum(c)) nb_alnum++; if (isalnum(d)) nb_alnum++; if (nb_alnum>2) ptr->is_qtff = 0; } gf_bs_seek(bs, start); e = gf_isom_audio_sample_entry_read((GF_AudioSampleEntryBox*)s, bs); if (e) return e; pos = gf_bs_get_position(bs); size = (u32) s->size; //when cookie is set on bs, always convert qtff-style mp4a to isobmff-style //since the conversion is done in addBox and we don't have the bitstream there (arg...), flag the box if (gf_bs_get_cookie(bs)) { ptr->is_qtff |= 1<<16; } e = gf_isom_box_array_read(s, bs, audio_sample_entry_AddBox); if (!e) return GF_OK; if (size<8) return GF_ISOM_INVALID_FILE; /*hack for some weird files (possibly recorded with live.com tools, needs further investigations)*/ gf_bs_seek(bs, pos); data = (char*)gf_malloc(sizeof(char) * size); gf_bs_read_data(bs, data, size); for (i=0; iesd) { gf_isom_box_del((GF_Box *)ptr->esd); ptr->esd=NULL; } e = gf_isom_box_parse((GF_Box **)&ptr->esd, mybs); if (e==GF_OK) { gf_isom_box_add_for_dump_mode((GF_Box*)ptr, (GF_Box*)ptr->esd); } else if (ptr->esd) { gf_isom_box_del((GF_Box *)ptr->esd); ptr->esd=NULL; } gf_bs_del(mybs); break; } } gf_free(data); return e; }","GF_Err audio_sample_entry_Read(GF_Box *s, GF_BitStream *bs) { GF_MPEGAudioSampleEntryBox *ptr; char *data; u8 a, b, c, d; u32 i, size, v, nb_alnum; GF_Err e; u64 pos, start; ptr = (GF_MPEGAudioSampleEntryBox *)s; start = gf_bs_get_position(bs); gf_bs_seek(bs, start + 8); v = gf_bs_read_u16(bs); if (v) ptr->is_qtff = 1; //try to disambiguate QTFF v1 and MP4 v1 audio sample entries ... if (v==1) { //go to end of ISOM audio sample entry, skip 4 byte (box size field), read 4 bytes (box type) and check if this looks like a box gf_bs_seek(bs, start + 8 + 20 + 4); a = gf_bs_read_u8(bs); b = gf_bs_read_u8(bs); c = gf_bs_read_u8(bs); d = gf_bs_read_u8(bs); nb_alnum = 0; if (isalnum(a)) nb_alnum++; if (isalnum(b)) nb_alnum++; if (isalnum(c)) nb_alnum++; if (isalnum(d)) nb_alnum++; if (nb_alnum>2) ptr->is_qtff = 0; } gf_bs_seek(bs, start); e = gf_isom_audio_sample_entry_read((GF_AudioSampleEntryBox*)s, bs); if (e) return e; pos = gf_bs_get_position(bs); size = (u32) s->size; //when cookie is set on bs, always convert qtff-style mp4a to isobmff-style //since the conversion is done in addBox and we don't have the bitstream there (arg...), flag the box if (gf_bs_get_cookie(bs)) { ptr->is_qtff |= 1<<16; } e = gf_isom_box_array_read(s, bs, audio_sample_entry_AddBox); if (!e) return GF_OK; if (size<8) return GF_ISOM_INVALID_FILE; /*hack for some weird files (possibly recorded with live.com tools, needs further investigations)*/ gf_bs_seek(bs, pos); data = (char*)gf_malloc(sizeof(char) * size); gf_bs_read_data(bs, data, size); for (i=0; iesd) { if (!use_dump_mode) gf_isom_box_del((GF_Box *)ptr->esd); ptr->esd=NULL; } e = gf_isom_box_parse((GF_Box **)&ptr->esd, mybs); if (e==GF_OK) { gf_isom_box_add_for_dump_mode((GF_Box*)ptr, (GF_Box*)ptr->esd); } else if (ptr->esd) { gf_isom_box_del((GF_Box *)ptr->esd); ptr->esd=NULL; } gf_bs_del(mybs); break; } } gf_free(data); return e; }","{'deleted': [{'line_no': 58, 'char_start': 1827, 'char_end': 1868, 'line': '\t\t\t\tgf_isom_box_del((GF_Box *)ptr->esd);\n'}], 'added': [{'line_no': 56, 'char_start': 1734, 'char_end': 1764, 'line': '\t\t\textern Bool use_dump_mode;\n'}, {'line_no': 59, 'char_start': 1857, 'char_end': 1918, 'line': '\t\t\t\tif (!use_dump_mode) gf_isom_box_del((GF_Box *)ptr->esd);\n'}]}","{'deleted': [], 'added': [{'char_start': 1737, 'char_end': 1767, 'chars': 'extern Bool use_dump_mode;\n\t\t\t'}, {'char_start': 1861, 'char_end': 1881, 'chars': 'if (!use_dump_mode) '}]}",github.com/gpac/gpac/commit/6063b1a011c3f80cee25daade18154e15e4c058c,src/isomedia/box_code_base.c,cwe-416,793 cwe-078,get_output,"def get_output(command: str) -> bytes: """""" Run a command and return raw output :param str command: the command to run :returns: the stdout output of the command """""" return subprocess.check_output(command.split())","def get_output(command: List[str]) -> str: """""" Run a command and return raw output :param str command: the command to run :returns: the stdout output of the command """""" result = subprocess.run(command, stdout=subprocess.PIPE, check=True) return result.stdout.decode()","{'deleted': [{'line_no': 1, 'char_start': 0, 'char_end': 39, 'line': 'def get_output(command: str) -> bytes:\n'}, {'line_no': 8, 'char_start': 186, 'char_end': 237, 'line': ' return subprocess.check_output(command.split())\n'}], 'added': [{'line_no': 1, 'char_start': 0, 'char_end': 43, 'line': 'def get_output(command: List[str]) -> str:\n'}, {'line_no': 8, 'char_start': 190, 'char_end': 263, 'line': ' result = subprocess.run(command, stdout=subprocess.PIPE, check=True)\n'}, {'line_no': 9, 'char_start': 263, 'char_end': 296, 'line': ' return result.stdout.decode()\n'}]}","{'deleted': [{'char_start': 32, 'char_end': 36, 'chars': 'byte'}, {'char_start': 213, 'char_end': 215, 'chars': '_o'}, {'char_start': 217, 'char_end': 218, 'chars': 'p'}, {'char_start': 220, 'char_end': 221, 'chars': '('}, {'char_start': 223, 'char_end': 227, 'chars': 'mman'}, {'char_start': 228, 'char_end': 234, 'chars': '.split'}, {'char_start': 236, 'char_end': 237, 'chars': ')'}], 'added': [{'char_start': 24, 'char_end': 29, 'chars': 'List['}, {'char_start': 32, 'char_end': 33, 'chars': ']'}, {'char_start': 38, 'char_end': 39, 'chars': 's'}, {'char_start': 40, 'char_end': 41, 'chars': 'r'}, {'char_start': 196, 'char_end': 199, 'chars': 'sul'}, {'char_start': 200, 'char_end': 204, 'chars': ' = s'}, {'char_start': 205, 'char_end': 207, 'chars': 'bp'}, {'char_start': 208, 'char_end': 216, 'chars': 'ocess.ru'}, {'char_start': 217, 'char_end': 226, 'chars': '(command,'}, {'char_start': 227, 'char_end': 234, 'chars': 'stdout='}, {'char_start': 245, 'char_end': 251, 'chars': 'PIPE, '}, {'char_start': 256, 'char_end': 259, 'chars': '=Tr'}, {'char_start': 260, 'char_end': 269, 'chars': 'e)\n re'}, {'char_start': 270, 'char_end': 285, 'chars': 'urn result.stdo'}, {'char_start': 287, 'char_end': 290, 'chars': '.de'}, {'char_start': 293, 'char_end': 294, 'chars': 'e'}]}",github.com/timothycrosley/isort/commit/1ab38f4f7840a3c19bf961a24630a992a8373a76,isort/hooks.py,cwe-078,53 cwe-125,tensorflow::QuantizeAndDequantizeV2Op::Compute," void Compute(OpKernelContext* ctx) override { const Tensor& input = ctx->input(0); const int depth = (axis_ == -1) ? 1 : input.dim_size(axis_); Tensor input_min_tensor; Tensor input_max_tensor; Tensor* output = nullptr; OP_REQUIRES_OK(ctx, ctx->allocate_output(0, input.shape(), &output)); if (range_given_) { input_min_tensor = ctx->input(1); input_max_tensor = ctx->input(2); if (axis_ == -1) { auto min_val = input_min_tensor.scalar()(); auto max_val = input_max_tensor.scalar()(); OP_REQUIRES(ctx, min_val <= max_val, errors::InvalidArgument(""Invalid range: input_min "", min_val, "" > input_max "", max_val)); } else { OP_REQUIRES(ctx, input_min_tensor.dim_size(0) == depth, errors::InvalidArgument( ""input_min_tensor has incorrect size, was "", input_min_tensor.dim_size(0), "" expected "", depth, "" to match dim "", axis_, "" of the input "", input_min_tensor.shape())); OP_REQUIRES(ctx, input_max_tensor.dim_size(0) == depth, errors::InvalidArgument( ""input_max_tensor has incorrect size, was "", input_max_tensor.dim_size(0), "" expected "", depth, "" to match dim "", axis_, "" of the input "", input_max_tensor.shape())); } } else { auto range_shape = (axis_ == -1) ? TensorShape({}) : TensorShape({depth}); OP_REQUIRES_OK(ctx, ctx->allocate_temp(DataTypeToEnum::value, range_shape, &input_min_tensor)); OP_REQUIRES_OK(ctx, ctx->allocate_temp(DataTypeToEnum::value, range_shape, &input_max_tensor)); } if (axis_ == -1) { functor::QuantizeAndDequantizeOneScaleFunctor f; f(ctx->eigen_device(), input.flat(), signed_input_, num_bits_, range_given_, &input_min_tensor, &input_max_tensor, round_mode_, narrow_range_, output->flat()); } else { functor::QuantizeAndDequantizePerChannelFunctor f; f(ctx->eigen_device(), input.template flat_inner_outer_dims(axis_ - 1), signed_input_, num_bits_, range_given_, &input_min_tensor, &input_max_tensor, round_mode_, narrow_range_, output->template flat_inner_outer_dims(axis_ - 1)); } }"," void Compute(OpKernelContext* ctx) override { const Tensor& input = ctx->input(0); OP_REQUIRES( ctx, (axis_ == -1 || axis_ < input.shape().dims()), errors::InvalidArgument(""Shape must be at least rank "", axis_ + 1, "" but is rank "", input.shape().dims())); const int depth = (axis_ == -1) ? 1 : input.dim_size(axis_); Tensor input_min_tensor; Tensor input_max_tensor; Tensor* output = nullptr; OP_REQUIRES_OK(ctx, ctx->allocate_output(0, input.shape(), &output)); if (range_given_) { input_min_tensor = ctx->input(1); input_max_tensor = ctx->input(2); if (axis_ == -1) { auto min_val = input_min_tensor.scalar()(); auto max_val = input_max_tensor.scalar()(); OP_REQUIRES(ctx, min_val <= max_val, errors::InvalidArgument(""Invalid range: input_min "", min_val, "" > input_max "", max_val)); } else { OP_REQUIRES(ctx, input_min_tensor.dim_size(0) == depth, errors::InvalidArgument( ""input_min_tensor has incorrect size, was "", input_min_tensor.dim_size(0), "" expected "", depth, "" to match dim "", axis_, "" of the input "", input_min_tensor.shape())); OP_REQUIRES(ctx, input_max_tensor.dim_size(0) == depth, errors::InvalidArgument( ""input_max_tensor has incorrect size, was "", input_max_tensor.dim_size(0), "" expected "", depth, "" to match dim "", axis_, "" of the input "", input_max_tensor.shape())); } } else { auto range_shape = (axis_ == -1) ? TensorShape({}) : TensorShape({depth}); OP_REQUIRES_OK(ctx, ctx->allocate_temp(DataTypeToEnum::value, range_shape, &input_min_tensor)); OP_REQUIRES_OK(ctx, ctx->allocate_temp(DataTypeToEnum::value, range_shape, &input_max_tensor)); } if (axis_ == -1) { functor::QuantizeAndDequantizeOneScaleFunctor f; f(ctx->eigen_device(), input.flat(), signed_input_, num_bits_, range_given_, &input_min_tensor, &input_max_tensor, round_mode_, narrow_range_, output->flat()); } else { functor::QuantizeAndDequantizePerChannelFunctor f; f(ctx->eigen_device(), input.template flat_inner_outer_dims(axis_ - 1), signed_input_, num_bits_, range_given_, &input_min_tensor, &input_max_tensor, round_mode_, narrow_range_, output->template flat_inner_outer_dims(axis_ - 1)); } }","{'deleted': [], 'added': [{'line_no': 3, 'char_start': 89, 'char_end': 106, 'line': ' OP_REQUIRES(\n'}, {'line_no': 4, 'char_start': 106, 'char_end': 166, 'line': ' ctx, (axis_ == -1 || axis_ < input.shape().dims()),\n'}, {'line_no': 5, 'char_start': 166, 'char_end': 241, 'line': ' errors::InvalidArgument(""Shape must be at least rank "", axis_ + 1,\n'}, {'line_no': 6, 'char_start': 241, 'char_end': 314, 'line': ' "" but is rank "", input.shape().dims()));\n'}]}","{'deleted': [], 'added': [{'char_start': 93, 'char_end': 318, 'chars': 'OP_REQUIRES(\n ctx, (axis_ == -1 || axis_ < input.shape().dims()),\n errors::InvalidArgument(""Shape must be at least rank "", axis_ + 1,\n "" but is rank "", input.shape().dims()));\n '}]}",github.com/tensorflow/tensorflow/commit/eccb7ec454e6617738554a255d77f08e60ee0808,tensorflow/core/kernels/quantize_and_dequantize_op.cc,cwe-125,583 cwe-125,matchCurrentInput,"matchCurrentInput( const InString *input, int pos, const widechar *passInstructions, int passIC) { int k; int kk = pos; for (k = passIC + 2; k < passIC + 2 + passInstructions[passIC + 1]; k++) if (input->chars[kk] == ENDSEGMENT || passInstructions[k] != input->chars[kk++]) return 0; return 1; }","matchCurrentInput( const InString *input, int pos, const widechar *passInstructions, int passIC) { int k; int kk = pos; for (k = passIC + 2; ((k < passIC + 2 + passInstructions[passIC + 1]) && (kk < input->length)); k++) if (input->chars[kk] == ENDSEGMENT || passInstructions[k] != input->chars[kk++]) return 0; return 1; }","{'deleted': [{'line_no': 5, 'char_start': 124, 'char_end': 198, 'line': '\tfor (k = passIC + 2; k < passIC + 2 + passInstructions[passIC + 1]; k++)\n'}], 'added': [{'line_no': 5, 'char_start': 124, 'char_end': 146, 'line': '\tfor (k = passIC + 2;\n'}, {'line_no': 6, 'char_start': 146, 'char_end': 224, 'line': '\t\t\t((k < passIC + 2 + passInstructions[passIC + 1]) && (kk < input->length));\n'}, {'line_no': 7, 'char_start': 224, 'char_end': 232, 'line': '\t\t\tk++)\n'}]}","{'deleted': [{'char_start': 145, 'char_end': 146, 'chars': ' '}, {'char_start': 192, 'char_end': 193, 'chars': ' '}], 'added': [{'char_start': 145, 'char_end': 151, 'chars': '\n\t\t\t(('}, {'char_start': 196, 'char_end': 206, 'chars': ') && (kk <'}, {'char_start': 207, 'char_end': 227, 'chars': 'input->length));\n\t\t\t'}]}",github.com/liblouis/liblouis/commit/5e4089659bb49b3095fa541fa6387b4c40d7396e,liblouis/lou_translateString.c,cwe-125,99 cwe-476,mrb_obj_clone,"mrb_obj_clone(mrb_state *mrb, mrb_value self) { struct RObject *p; mrb_value clone; if (mrb_immediate_p(self)) { mrb_raisef(mrb, E_TYPE_ERROR, ""can't clone %S"", self); } if (mrb_type(self) == MRB_TT_SCLASS) { mrb_raise(mrb, E_TYPE_ERROR, ""can't clone singleton class""); } p = (struct RObject*)mrb_obj_alloc(mrb, mrb_type(self), mrb_obj_class(mrb, self)); p->c = mrb_singleton_class_clone(mrb, self); mrb_field_write_barrier(mrb, (struct RBasic*)p, (struct RBasic*)p->c); clone = mrb_obj_value(p); init_copy(mrb, clone, self); p->flags = mrb_obj_ptr(self)->flags; return clone; }","mrb_obj_clone(mrb_state *mrb, mrb_value self) { struct RObject *p; mrb_value clone; if (mrb_immediate_p(self)) { mrb_raisef(mrb, E_TYPE_ERROR, ""can't clone %S"", self); } if (mrb_type(self) == MRB_TT_SCLASS) { mrb_raise(mrb, E_TYPE_ERROR, ""can't clone singleton class""); } p = (struct RObject*)mrb_obj_alloc(mrb, mrb_type(self), mrb_obj_class(mrb, self)); p->c = mrb_singleton_class_clone(mrb, self); mrb_field_write_barrier(mrb, (struct RBasic*)p, (struct RBasic*)p->c); clone = mrb_obj_value(p); init_copy(mrb, clone, self); p->flags |= mrb_obj_ptr(self)->flags & MRB_FLAG_IS_FROZEN; return clone; }","{'deleted': [{'line_no': 17, 'char_start': 557, 'char_end': 596, 'line': ' p->flags = mrb_obj_ptr(self)->flags;\n'}], 'added': [{'line_no': 17, 'char_start': 557, 'char_end': 618, 'line': ' p->flags |= mrb_obj_ptr(self)->flags & MRB_FLAG_IS_FROZEN;\n'}]}","{'deleted': [], 'added': [{'char_start': 568, 'char_end': 569, 'chars': '|'}, {'char_start': 595, 'char_end': 616, 'chars': ' & MRB_FLAG_IS_FROZEN'}]}",github.com/mruby/mruby/commit/55edae0226409de25e59922807cb09acb45731a2,src/kernel.c,cwe-476,198 cwe-416,dbd_st_fetch,"dbd_st_fetch(SV *sth, imp_sth_t* imp_sth) { dTHX; int num_fields, ChopBlanks, i, rc; unsigned long *lengths; AV *av; int av_length, av_readonly; MYSQL_ROW cols; D_imp_dbh_from_sth; MYSQL* svsock= imp_dbh->pmysql; imp_sth_fbh_t *fbh; D_imp_xxh(sth); #if MYSQL_VERSION_ID >=SERVER_PREPARE_VERSION MYSQL_BIND *buffer; #endif MYSQL_FIELD *fields; if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), ""\t-> dbd_st_fetch\n""); #if MYSQL_ASYNC if(imp_dbh->async_query_in_flight) { if(mysql_db_async_result(sth, &imp_sth->result) <= 0) { return Nullav; } } #endif #if MYSQL_VERSION_ID >=SERVER_PREPARE_VERSION if (imp_sth->use_server_side_prepare) { if (!DBIc_ACTIVE(imp_sth) ) { do_error(sth, JW_ERR_SEQUENCE, ""no statement executing\n"",NULL); return Nullav; } if (imp_sth->fetch_done) { do_error(sth, JW_ERR_SEQUENCE, ""fetch() but fetch already done"",NULL); return Nullav; } if (!imp_sth->done_desc) { if (!dbd_describe(sth, imp_sth)) { do_error(sth, JW_ERR_SEQUENCE, ""Error while describe result set."", NULL); return Nullav; } } } #endif ChopBlanks = DBIc_is(imp_sth, DBIcf_ChopBlanks); if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), ""\t\tdbd_st_fetch for %p, chopblanks %d\n"", sth, ChopBlanks); if (!imp_sth->result) { do_error(sth, JW_ERR_SEQUENCE, ""fetch() without execute()"" ,NULL); return Nullav; } /* fix from 2.9008 */ imp_dbh->pmysql->net.last_errno = 0; #if MYSQL_VERSION_ID >=SERVER_PREPARE_VERSION if (imp_sth->use_server_side_prepare) { if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), ""\t\tdbd_st_fetch calling mysql_fetch\n""); if ((rc= mysql_stmt_fetch(imp_sth->stmt))) { if (rc == 1) do_error(sth, mysql_stmt_errno(imp_sth->stmt), mysql_stmt_error(imp_sth->stmt), mysql_stmt_sqlstate(imp_sth->stmt)); #if MYSQL_VERSION_ID >= MYSQL_VERSION_5_0 if (rc == MYSQL_DATA_TRUNCATED) { if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), ""\t\tdbd_st_fetch data truncated\n""); goto process; } #endif if (rc == MYSQL_NO_DATA) { /* Update row_num to affected_rows value */ imp_sth->row_num= mysql_stmt_affected_rows(imp_sth->stmt); imp_sth->fetch_done=1; if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), ""\t\tdbd_st_fetch no data\n""); } dbd_st_finish(sth, imp_sth); return Nullav; } process: imp_sth->currow++; av= DBIc_DBISTATE(imp_sth)->get_fbav(imp_sth); num_fields=mysql_stmt_field_count(imp_sth->stmt); if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), ""\t\tdbd_st_fetch called mysql_fetch, rc %d num_fields %d\n"", rc, num_fields); for ( buffer= imp_sth->buffer, fbh= imp_sth->fbh, i= 0; i < num_fields; i++, fbh++, buffer++ ) { SV *sv= AvARRAY(av)[i]; /* Note: we (re)use the SV in the AV */ STRLEN len; /* This is wrong, null is not being set correctly * This is not the way to determine length (this would break blobs!) */ if (fbh->is_null) (void) SvOK_off(sv); /* Field is NULL, return undef */ else { /* In case of BLOB/TEXT fields we allocate only 8192 bytes in dbd_describe() for data. Here we know real size of field so we should increase buffer size and refetch column value */ if (fbh->length > buffer->buffer_length || fbh->error) { if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), ""\t\tRefetch BLOB/TEXT column: %d, length: %lu, error: %d\n"", i, fbh->length, fbh->error); Renew(fbh->data, fbh->length, char); buffer->buffer_length= fbh->length; buffer->buffer= (char *) fbh->data; if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) { int j; int m = MIN(*buffer->length, buffer->buffer_length); char *ptr = (char*)buffer->buffer; PerlIO_printf(DBIc_LOGPIO(imp_xxh),""\t\tbefore buffer->buffer: ""); for (j = 0; j < m; j++) { PerlIO_printf(DBIc_LOGPIO(imp_xxh), ""%c"", *ptr++); } PerlIO_printf(DBIc_LOGPIO(imp_xxh),""\n""); } /*TODO: Use offset instead of 0 to fetch only remain part of data*/ if (mysql_stmt_fetch_column(imp_sth->stmt, buffer , i, 0)) do_error(sth, mysql_stmt_errno(imp_sth->stmt), mysql_stmt_error(imp_sth->stmt), mysql_stmt_sqlstate(imp_sth->stmt)); if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) { int j; int m = MIN(*buffer->length, buffer->buffer_length); char *ptr = (char*)buffer->buffer; PerlIO_printf(DBIc_LOGPIO(imp_xxh),""\t\tafter buffer->buffer: ""); for (j = 0; j < m; j++) { PerlIO_printf(DBIc_LOGPIO(imp_xxh), ""%c"", *ptr++); } PerlIO_printf(DBIc_LOGPIO(imp_xxh),""\n""); } } /* This does look a lot like Georg's PHP driver doesn't it? --Brian */ /* Credit due to Georg - mysqli_api.c ;) --PMG */ switch (buffer->buffer_type) { case MYSQL_TYPE_DOUBLE: if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), ""\t\tst_fetch double data %f\n"", fbh->ddata); sv_setnv(sv, fbh->ddata); break; case MYSQL_TYPE_LONG: case MYSQL_TYPE_LONGLONG: if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), ""\t\tst_fetch int data %""IVdf"", unsigned? %d\n"", fbh->ldata, buffer->is_unsigned); if (buffer->is_unsigned) sv_setuv(sv, fbh->ldata); else sv_setiv(sv, fbh->ldata); break; case MYSQL_TYPE_BIT: sv_setpvn(sv, fbh->data, fbh->length); break; default: if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), ""\t\tERROR IN st_fetch_string""); len= fbh->length; /* ChopBlanks server-side prepared statement */ if (ChopBlanks) { /* see bottom of: http://www.mysql.org/doc/refman/5.0/en/c-api-datatypes.html */ if (fbh->charsetnr != 63) while (len && fbh->data[len-1] == ' ') { --len; } } /* END OF ChopBlanks */ sv_setpvn(sv, fbh->data, len); /* UTF8 */ /*HELMUT*/ #if defined(sv_utf8_decode) && MYSQL_VERSION_ID >=SERVER_PREPARE_VERSION #if MYSQL_VERSION_ID >= FIELD_CHARSETNR_VERSION /* SHOW COLLATION WHERE Id = 63; -- 63 == charset binary, collation binary */ if ((imp_dbh->enable_utf8 || imp_dbh->enable_utf8mb4) && fbh->charsetnr != 63) #else if ((imp_dbh->enable_utf8 || imp_dbh->enable_utf8mb4) && !(fbh->flags & BINARY_FLAG)) #endif sv_utf8_decode(sv); #endif /* END OF UTF8 */ break; } } } if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), ""\t<- dbd_st_fetch, %d cols\n"", num_fields); return av; } else { #endif imp_sth->currow++; if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) { PerlIO_printf(DBIc_LOGPIO(imp_xxh), ""\tdbd_st_fetch result set details\n""); PerlIO_printf(DBIc_LOGPIO(imp_xxh), ""\timp_sth->result=%p\n"", imp_sth->result); PerlIO_printf(DBIc_LOGPIO(imp_xxh), ""\tmysql_num_fields=%u\n"", mysql_num_fields(imp_sth->result)); PerlIO_printf(DBIc_LOGPIO(imp_xxh), ""\tmysql_num_rows=%llu\n"", mysql_num_rows(imp_sth->result)); PerlIO_printf(DBIc_LOGPIO(imp_xxh), ""\tmysql_affected_rows=%llu\n"", mysql_affected_rows(imp_dbh->pmysql)); PerlIO_printf(DBIc_LOGPIO(imp_xxh), ""\tdbd_st_fetch for %p, currow= %d\n"", sth,imp_sth->currow); } if (!(cols= mysql_fetch_row(imp_sth->result))) { if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) { PerlIO_printf(DBIc_LOGPIO(imp_xxh), ""\tdbd_st_fetch, no more rows to fetch""); } if (mysql_errno(imp_dbh->pmysql)) do_error(sth, mysql_errno(imp_dbh->pmysql), mysql_error(imp_dbh->pmysql), mysql_sqlstate(imp_dbh->pmysql)); #if MYSQL_VERSION_ID >= MULTIPLE_RESULT_SET_VERSION if (!mysql_more_results(svsock)) #endif dbd_st_finish(sth, imp_sth); return Nullav; } num_fields= mysql_num_fields(imp_sth->result); fields= mysql_fetch_fields(imp_sth->result); lengths= mysql_fetch_lengths(imp_sth->result); if ((av= DBIc_FIELDS_AV(imp_sth)) != Nullav) { av_length= av_len(av)+1; if (av_length != num_fields) /* Resize array if necessary */ { if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), ""\t<- dbd_st_fetch, size of results array(%d) != num_fields(%d)\n"", av_length, num_fields); if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), ""\t<- dbd_st_fetch, result fields(%d)\n"", DBIc_NUM_FIELDS(imp_sth)); av_readonly = SvREADONLY(av); if (av_readonly) SvREADONLY_off( av ); /* DBI sets this readonly */ while (av_length < num_fields) { av_store(av, av_length++, newSV(0)); } while (av_length > num_fields) { SvREFCNT_dec(av_pop(av)); av_length--; } if (av_readonly) SvREADONLY_on(av); } } av= DBIc_DBISTATE(imp_sth)->get_fbav(imp_sth); for (i= 0; i < num_fields; ++i) { char *col= cols[i]; SV *sv= AvARRAY(av)[i]; /* Note: we (re)use the SV in the AV */ if (col) { STRLEN len= lengths[i]; if (ChopBlanks) { while (len && col[len-1] == ' ') { --len; } } /* Set string value returned from mysql server */ sv_setpvn(sv, col, len); switch (mysql_to_perl_type(fields[i].type)) { case MYSQL_TYPE_DOUBLE: /* Coerce to dobule and set scalar as NV */ (void) SvNV(sv); SvNOK_only(sv); break; case MYSQL_TYPE_LONG: case MYSQL_TYPE_LONGLONG: /* Coerce to integer and set scalar as UV resp. IV */ if (fields[i].flags & UNSIGNED_FLAG) { (void) SvUV(sv); SvIOK_only_UV(sv); } else { (void) SvIV(sv); SvIOK_only(sv); } break; #if MYSQL_VERSION_ID > NEW_DATATYPE_VERSION case MYSQL_TYPE_BIT: /* Let it as binary string */ break; #endif default: /* UTF8 */ /*HELMUT*/ #if defined(sv_utf8_decode) && MYSQL_VERSION_ID >=SERVER_PREPARE_VERSION /* see bottom of: http://www.mysql.org/doc/refman/5.0/en/c-api-datatypes.html */ if ((imp_dbh->enable_utf8 || imp_dbh->enable_utf8mb4) && fields[i].charsetnr != 63) sv_utf8_decode(sv); #endif /* END OF UTF8 */ break; } } else (void) SvOK_off(sv); /* Field is NULL, return undef */ } if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), ""\t<- dbd_st_fetch, %d cols\n"", num_fields); return av; #if MYSQL_VERSION_ID >= SERVER_PREPARE_VERSION } #endif }","dbd_st_fetch(SV *sth, imp_sth_t* imp_sth) { dTHX; int num_fields, ChopBlanks, i, rc; unsigned long *lengths; AV *av; int av_length, av_readonly; MYSQL_ROW cols; D_imp_dbh_from_sth; MYSQL* svsock= imp_dbh->pmysql; imp_sth_fbh_t *fbh; D_imp_xxh(sth); #if MYSQL_VERSION_ID >=SERVER_PREPARE_VERSION MYSQL_BIND *buffer; #endif MYSQL_FIELD *fields; if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), ""\t-> dbd_st_fetch\n""); #if MYSQL_ASYNC if(imp_dbh->async_query_in_flight) { if(mysql_db_async_result(sth, &imp_sth->result) <= 0) { return Nullav; } } #endif #if MYSQL_VERSION_ID >=SERVER_PREPARE_VERSION if (imp_sth->use_server_side_prepare) { if (!DBIc_ACTIVE(imp_sth) ) { do_error(sth, JW_ERR_SEQUENCE, ""no statement executing\n"",NULL); return Nullav; } if (imp_sth->fetch_done) { do_error(sth, JW_ERR_SEQUENCE, ""fetch() but fetch already done"",NULL); return Nullav; } if (!imp_sth->done_desc) { if (!dbd_describe(sth, imp_sth)) { do_error(sth, JW_ERR_SEQUENCE, ""Error while describe result set."", NULL); return Nullav; } } } #endif ChopBlanks = DBIc_is(imp_sth, DBIcf_ChopBlanks); if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), ""\t\tdbd_st_fetch for %p, chopblanks %d\n"", sth, ChopBlanks); if (!imp_sth->result) { do_error(sth, JW_ERR_SEQUENCE, ""fetch() without execute()"" ,NULL); return Nullav; } /* fix from 2.9008 */ imp_dbh->pmysql->net.last_errno = 0; #if MYSQL_VERSION_ID >=SERVER_PREPARE_VERSION if (imp_sth->use_server_side_prepare) { if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), ""\t\tdbd_st_fetch calling mysql_fetch\n""); if ((rc= mysql_stmt_fetch(imp_sth->stmt))) { if (rc == 1) do_error(sth, mysql_stmt_errno(imp_sth->stmt), mysql_stmt_error(imp_sth->stmt), mysql_stmt_sqlstate(imp_sth->stmt)); #if MYSQL_VERSION_ID >= MYSQL_VERSION_5_0 if (rc == MYSQL_DATA_TRUNCATED) { if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), ""\t\tdbd_st_fetch data truncated\n""); goto process; } #endif if (rc == MYSQL_NO_DATA) { /* Update row_num to affected_rows value */ imp_sth->row_num= mysql_stmt_affected_rows(imp_sth->stmt); imp_sth->fetch_done=1; if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), ""\t\tdbd_st_fetch no data\n""); } dbd_st_finish(sth, imp_sth); return Nullav; } process: imp_sth->currow++; av= DBIc_DBISTATE(imp_sth)->get_fbav(imp_sth); num_fields=mysql_stmt_field_count(imp_sth->stmt); if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), ""\t\tdbd_st_fetch called mysql_fetch, rc %d num_fields %d\n"", rc, num_fields); for ( buffer= imp_sth->buffer, fbh= imp_sth->fbh, i= 0; i < num_fields; i++, fbh++, buffer++ ) { SV *sv= AvARRAY(av)[i]; /* Note: we (re)use the SV in the AV */ STRLEN len; /* This is wrong, null is not being set correctly * This is not the way to determine length (this would break blobs!) */ if (fbh->is_null) (void) SvOK_off(sv); /* Field is NULL, return undef */ else { /* In case of BLOB/TEXT fields we allocate only 8192 bytes in dbd_describe() for data. Here we know real size of field so we should increase buffer size and refetch column value */ if (fbh->length > buffer->buffer_length || fbh->error) { if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), ""\t\tRefetch BLOB/TEXT column: %d, length: %lu, error: %d\n"", i, fbh->length, fbh->error); Renew(fbh->data, fbh->length, char); buffer->buffer_length= fbh->length; buffer->buffer= (char *) fbh->data; imp_sth->stmt->bind[i].buffer_length = fbh->length; imp_sth->stmt->bind[i].buffer = (char *)fbh->data; if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) { int j; int m = MIN(*buffer->length, buffer->buffer_length); char *ptr = (char*)buffer->buffer; PerlIO_printf(DBIc_LOGPIO(imp_xxh),""\t\tbefore buffer->buffer: ""); for (j = 0; j < m; j++) { PerlIO_printf(DBIc_LOGPIO(imp_xxh), ""%c"", *ptr++); } PerlIO_printf(DBIc_LOGPIO(imp_xxh),""\n""); } /*TODO: Use offset instead of 0 to fetch only remain part of data*/ if (mysql_stmt_fetch_column(imp_sth->stmt, buffer , i, 0)) do_error(sth, mysql_stmt_errno(imp_sth->stmt), mysql_stmt_error(imp_sth->stmt), mysql_stmt_sqlstate(imp_sth->stmt)); if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) { int j; int m = MIN(*buffer->length, buffer->buffer_length); char *ptr = (char*)buffer->buffer; PerlIO_printf(DBIc_LOGPIO(imp_xxh),""\t\tafter buffer->buffer: ""); for (j = 0; j < m; j++) { PerlIO_printf(DBIc_LOGPIO(imp_xxh), ""%c"", *ptr++); } PerlIO_printf(DBIc_LOGPIO(imp_xxh),""\n""); } } /* This does look a lot like Georg's PHP driver doesn't it? --Brian */ /* Credit due to Georg - mysqli_api.c ;) --PMG */ switch (buffer->buffer_type) { case MYSQL_TYPE_DOUBLE: if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), ""\t\tst_fetch double data %f\n"", fbh->ddata); sv_setnv(sv, fbh->ddata); break; case MYSQL_TYPE_LONG: case MYSQL_TYPE_LONGLONG: if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), ""\t\tst_fetch int data %""IVdf"", unsigned? %d\n"", fbh->ldata, buffer->is_unsigned); if (buffer->is_unsigned) sv_setuv(sv, fbh->ldata); else sv_setiv(sv, fbh->ldata); break; case MYSQL_TYPE_BIT: sv_setpvn(sv, fbh->data, fbh->length); break; default: if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), ""\t\tERROR IN st_fetch_string""); len= fbh->length; /* ChopBlanks server-side prepared statement */ if (ChopBlanks) { /* see bottom of: http://www.mysql.org/doc/refman/5.0/en/c-api-datatypes.html */ if (fbh->charsetnr != 63) while (len && fbh->data[len-1] == ' ') { --len; } } /* END OF ChopBlanks */ sv_setpvn(sv, fbh->data, len); /* UTF8 */ /*HELMUT*/ #if defined(sv_utf8_decode) && MYSQL_VERSION_ID >=SERVER_PREPARE_VERSION #if MYSQL_VERSION_ID >= FIELD_CHARSETNR_VERSION /* SHOW COLLATION WHERE Id = 63; -- 63 == charset binary, collation binary */ if ((imp_dbh->enable_utf8 || imp_dbh->enable_utf8mb4) && fbh->charsetnr != 63) #else if ((imp_dbh->enable_utf8 || imp_dbh->enable_utf8mb4) && !(fbh->flags & BINARY_FLAG)) #endif sv_utf8_decode(sv); #endif /* END OF UTF8 */ break; } } } if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), ""\t<- dbd_st_fetch, %d cols\n"", num_fields); return av; } else { #endif imp_sth->currow++; if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) { PerlIO_printf(DBIc_LOGPIO(imp_xxh), ""\tdbd_st_fetch result set details\n""); PerlIO_printf(DBIc_LOGPIO(imp_xxh), ""\timp_sth->result=%p\n"", imp_sth->result); PerlIO_printf(DBIc_LOGPIO(imp_xxh), ""\tmysql_num_fields=%u\n"", mysql_num_fields(imp_sth->result)); PerlIO_printf(DBIc_LOGPIO(imp_xxh), ""\tmysql_num_rows=%llu\n"", mysql_num_rows(imp_sth->result)); PerlIO_printf(DBIc_LOGPIO(imp_xxh), ""\tmysql_affected_rows=%llu\n"", mysql_affected_rows(imp_dbh->pmysql)); PerlIO_printf(DBIc_LOGPIO(imp_xxh), ""\tdbd_st_fetch for %p, currow= %d\n"", sth,imp_sth->currow); } if (!(cols= mysql_fetch_row(imp_sth->result))) { if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) { PerlIO_printf(DBIc_LOGPIO(imp_xxh), ""\tdbd_st_fetch, no more rows to fetch""); } if (mysql_errno(imp_dbh->pmysql)) do_error(sth, mysql_errno(imp_dbh->pmysql), mysql_error(imp_dbh->pmysql), mysql_sqlstate(imp_dbh->pmysql)); #if MYSQL_VERSION_ID >= MULTIPLE_RESULT_SET_VERSION if (!mysql_more_results(svsock)) #endif dbd_st_finish(sth, imp_sth); return Nullav; } num_fields= mysql_num_fields(imp_sth->result); fields= mysql_fetch_fields(imp_sth->result); lengths= mysql_fetch_lengths(imp_sth->result); if ((av= DBIc_FIELDS_AV(imp_sth)) != Nullav) { av_length= av_len(av)+1; if (av_length != num_fields) /* Resize array if necessary */ { if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), ""\t<- dbd_st_fetch, size of results array(%d) != num_fields(%d)\n"", av_length, num_fields); if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), ""\t<- dbd_st_fetch, result fields(%d)\n"", DBIc_NUM_FIELDS(imp_sth)); av_readonly = SvREADONLY(av); if (av_readonly) SvREADONLY_off( av ); /* DBI sets this readonly */ while (av_length < num_fields) { av_store(av, av_length++, newSV(0)); } while (av_length > num_fields) { SvREFCNT_dec(av_pop(av)); av_length--; } if (av_readonly) SvREADONLY_on(av); } } av= DBIc_DBISTATE(imp_sth)->get_fbav(imp_sth); for (i= 0; i < num_fields; ++i) { char *col= cols[i]; SV *sv= AvARRAY(av)[i]; /* Note: we (re)use the SV in the AV */ if (col) { STRLEN len= lengths[i]; if (ChopBlanks) { while (len && col[len-1] == ' ') { --len; } } /* Set string value returned from mysql server */ sv_setpvn(sv, col, len); switch (mysql_to_perl_type(fields[i].type)) { case MYSQL_TYPE_DOUBLE: /* Coerce to dobule and set scalar as NV */ (void) SvNV(sv); SvNOK_only(sv); break; case MYSQL_TYPE_LONG: case MYSQL_TYPE_LONGLONG: /* Coerce to integer and set scalar as UV resp. IV */ if (fields[i].flags & UNSIGNED_FLAG) { (void) SvUV(sv); SvIOK_only_UV(sv); } else { (void) SvIV(sv); SvIOK_only(sv); } break; #if MYSQL_VERSION_ID > NEW_DATATYPE_VERSION case MYSQL_TYPE_BIT: /* Let it as binary string */ break; #endif default: /* UTF8 */ /*HELMUT*/ #if defined(sv_utf8_decode) && MYSQL_VERSION_ID >=SERVER_PREPARE_VERSION /* see bottom of: http://www.mysql.org/doc/refman/5.0/en/c-api-datatypes.html */ if ((imp_dbh->enable_utf8 || imp_dbh->enable_utf8mb4) && fields[i].charsetnr != 63) sv_utf8_decode(sv); #endif /* END OF UTF8 */ break; } } else (void) SvOK_off(sv); /* Field is NULL, return undef */ } if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) PerlIO_printf(DBIc_LOGPIO(imp_xxh), ""\t<- dbd_st_fetch, %d cols\n"", num_fields); return av; #if MYSQL_VERSION_ID >= SERVER_PREPARE_VERSION } #endif }","{'deleted': [], 'added': [{'line_no': 150, 'char_start': 4222, 'char_end': 4284, 'line': ' imp_sth->stmt->bind[i].buffer_length = fbh->length;\n'}, {'line_no': 151, 'char_start': 4284, 'char_end': 4345, 'line': ' imp_sth->stmt->bind[i].buffer = (char *)fbh->data;\n'}]}","{'deleted': [], 'added': [{'char_start': 4222, 'char_end': 4345, 'chars': ' imp_sth->stmt->bind[i].buffer_length = fbh->length;\n imp_sth->stmt->bind[i].buffer = (char *)fbh->data;\n'}]}",github.com/perl5-dbi/DBD-mysql/commit/3619c170461a3107a258d1fd2d00ed4832adb1b1,dbdimp.c,cwe-416,3447 cwe-078,test_create_invalid_host," def test_create_invalid_host(self): self.flags(lock_path=self.tempdir) #record self.clear_mox() self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, ""get_cpg"", self.fake_get_cpg) self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, ""get_domain"", self.fake_get_domain) _run_ssh = self.mox.CreateMock(hpdriver.hpcommon.HP3PARCommon._run_ssh) self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, ""_run_ssh"", _run_ssh) show_host_cmd = 'showhost -verbose fakehost' _run_ssh(show_host_cmd, False).AndReturn([pack('no hosts listed'), '']) create_host_cmd = ('createhost -persona 1 -domain (\'OpenStack\',) ' 'fakehost 123456789012345 123456789054321') create_host_ret = pack(CLI_CR + 'already used by host fakehost.foo (19)') _run_ssh(create_host_cmd, False).AndReturn([create_host_ret, '']) show_3par_cmd = 'showhost -verbose fakehost.foo' _run_ssh(show_3par_cmd, False).AndReturn([pack(FC_SHOWHOST_RET), '']) self.mox.ReplayAll() host = self.driver._create_host(self.volume, self.connector) self.assertEquals(host['name'], 'fakehost.foo')"," def test_create_invalid_host(self): self.flags(lock_path=self.tempdir) #record self.clear_mox() self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, ""get_cpg"", self.fake_get_cpg) self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, ""get_domain"", self.fake_get_domain) _run_ssh = self.mox.CreateMock(hpdriver.hpcommon.HP3PARCommon._run_ssh) self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, ""_run_ssh"", _run_ssh) show_host_cmd = ['showhost', '-verbose', 'fakehost'] _run_ssh(show_host_cmd, False).AndReturn([pack('no hosts listed'), '']) create_host_cmd = (['createhost', '-persona', '1', '-domain', ('OpenStack',), 'fakehost', '123456789012345', '123456789054321']) create_host_ret = pack(CLI_CR + 'already used by host fakehost.foo (19)') _run_ssh(create_host_cmd, False).AndReturn([create_host_ret, '']) show_3par_cmd = ['showhost', '-verbose', 'fakehost.foo'] _run_ssh(show_3par_cmd, False).AndReturn([pack(FC_SHOWHOST_RET), '']) self.mox.ReplayAll() host = self.driver._create_host(self.volume, self.connector) self.assertEquals(host['name'], 'fakehost.foo')","{'deleted': [{'line_no': 13, 'char_start': 505, 'char_end': 558, 'line': "" show_host_cmd = 'showhost -verbose fakehost'\n""}, {'line_no': 16, 'char_start': 639, 'char_end': 716, 'line': "" create_host_cmd = ('createhost -persona 1 -domain (\\'OpenStack\\',) '\n""}, {'line_no': 17, 'char_start': 716, 'char_end': 787, 'line': "" 'fakehost 123456789012345 123456789054321')\n""}, {'line_no': 22, 'char_start': 975, 'char_end': 1032, 'line': "" show_3par_cmd = 'showhost -verbose fakehost.foo'\n""}], 'added': [{'line_no': 13, 'char_start': 505, 'char_end': 566, 'line': "" show_host_cmd = ['showhost', '-verbose', 'fakehost']\n""}, {'line_no': 16, 'char_start': 647, 'char_end': 717, 'line': "" create_host_cmd = (['createhost', '-persona', '1', '-domain',\n""}, {'line_no': 17, 'char_start': 717, 'char_end': 792, 'line': "" ('OpenStack',), 'fakehost', '123456789012345',\n""}, {'line_no': 18, 'char_start': 792, 'char_end': 840, 'line': "" '123456789054321'])\n""}, {'line_no': 23, 'char_start': 1028, 'char_end': 1093, 'line': "" show_3par_cmd = ['showhost', '-verbose', 'fakehost.foo']\n""}]}","{'deleted': [{'char_start': 696, 'char_end': 710, 'chars': "" (\\'OpenStack\\""}, {'char_start': 712, 'char_end': 715, 'chars': "") '""}], 'added': [{'char_start': 529, 'char_end': 530, 'chars': '['}, {'char_start': 539, 'char_end': 541, 'chars': ""',""}, {'char_start': 542, 'char_end': 543, 'chars': ""'""}, {'char_start': 551, 'char_end': 553, 'chars': ""',""}, {'char_start': 554, 'char_end': 555, 'chars': ""'""}, {'char_start': 564, 'char_end': 565, 'chars': ']'}, {'char_start': 674, 'char_end': 675, 'chars': '['}, {'char_start': 686, 'char_end': 688, 'chars': ""',""}, {'char_start': 689, 'char_end': 690, 'chars': ""'""}, {'char_start': 698, 'char_end': 700, 'chars': ""',""}, {'char_start': 701, 'char_end': 702, 'chars': ""'""}, {'char_start': 703, 'char_end': 705, 'chars': ""',""}, {'char_start': 706, 'char_end': 707, 'chars': ""'""}, {'char_start': 744, 'char_end': 761, 'chars': "" ('OpenStack',), ""}, {'char_start': 770, 'char_end': 772, 'chars': ""',""}, {'char_start': 773, 'char_end': 774, 'chars': ""'""}, {'char_start': 789, 'char_end': 802, 'chars': ""',\n ""}, {'char_start': 803, 'char_end': 821, 'chars': "" '""}, {'char_start': 837, 'char_end': 838, 'chars': ']'}, {'char_start': 1052, 'char_end': 1053, 'chars': '['}, {'char_start': 1062, 'char_end': 1064, 'chars': ""',""}, {'char_start': 1065, 'char_end': 1066, 'chars': ""'""}, {'char_start': 1074, 'char_end': 1076, 'chars': ""',""}, {'char_start': 1077, 'char_end': 1078, 'chars': ""'""}, {'char_start': 1091, 'char_end': 1092, 'chars': ']'}]}",github.com/thatsdone/cinder/commit/c55589b131828f3a595903f6796cb2d0babb772f,cinder/tests/test_hp3par.py,cwe-078,337 cwe-078,_create_3par_fibrechan_host," def _create_3par_fibrechan_host(self, hostname, wwn, domain, persona_id): """"""Create a 3PAR host. Create a 3PAR host, if there is already a host on the 3par using the same wwn but with a different hostname, return the hostname used by 3PAR. """""" out = self.common._cli_run('createhost -persona %s -domain %s %s %s' % (persona_id, domain, hostname, "" "".join(wwn)), None) if out and len(out) > 1: return self.common.parse_create_host_error(hostname, out) return hostname"," def _create_3par_fibrechan_host(self, hostname, wwns, domain, persona_id): """"""Create a 3PAR host. Create a 3PAR host, if there is already a host on the 3par using the same wwn but with a different hostname, return the hostname used by 3PAR. """""" command = ['createhost', '-persona', persona_id, '-domain', domain, hostname] for wwn in wwns: command.append(wwn) out = self.common._cli_run(command) if out and len(out) > 1: return self.common.parse_create_host_error(hostname, out) return hostname","{'deleted': [{'line_no': 1, 'char_start': 0, 'char_end': 78, 'line': ' def _create_3par_fibrechan_host(self, hostname, wwn, domain, persona_id):\n'}, {'line_no': 8, 'char_start': 289, 'char_end': 366, 'line': "" out = self.common._cli_run('createhost -persona %s -domain %s %s %s'\n""}, {'line_no': 9, 'char_start': 366, 'char_end': 424, 'line': ' % (persona_id, domain,\n'}, {'line_no': 10, 'char_start': 424, 'char_end': 494, 'line': ' hostname, "" "".join(wwn)), None)\n'}], 'added': [{'line_no': 1, 'char_start': 0, 'char_end': 79, 'line': ' def _create_3par_fibrechan_host(self, hostname, wwns, domain, persona_id):\n'}, {'line_no': 8, 'char_start': 290, 'char_end': 366, 'line': "" command = ['createhost', '-persona', persona_id, '-domain', domain,\n""}, {'line_no': 9, 'char_start': 366, 'char_end': 395, 'line': ' hostname]\n'}, {'line_no': 10, 'char_start': 395, 'char_end': 420, 'line': ' for wwn in wwns:\n'}, {'line_no': 11, 'char_start': 420, 'char_end': 452, 'line': ' command.append(wwn)\n'}, {'line_no': 12, 'char_start': 452, 'char_end': 453, 'line': '\n'}, {'line_no': 13, 'char_start': 453, 'char_end': 497, 'line': ' out = self.common._cli_run(command)\n'}]}","{'deleted': [{'char_start': 297, 'char_end': 308, 'chars': 'out = self.'}, {'char_start': 312, 'char_end': 313, 'chars': 'o'}, {'char_start': 314, 'char_end': 324, 'chars': '._cli_run('}, {'char_start': 345, 'char_end': 346, 'chars': '%'}, {'char_start': 356, 'char_end': 365, 'chars': ""%s %s %s'""}, {'char_start': 366, 'char_end': 373, 'chars': ' '}, {'char_start': 392, 'char_end': 407, 'chars': ' % (per'}, {'char_start': 408, 'char_end': 409, 'chars': 'o'}, {'char_start': 411, 'char_end': 418, 'chars': '_id, do'}, {'char_start': 419, 'char_end': 423, 'chars': 'ain,'}, {'char_start': 456, 'char_end': 461, 'chars': ' '}, {'char_start': 462, 'char_end': 464, 'chars': 'ho'}, {'char_start': 465, 'char_end': 469, 'chars': 'tnam'}, {'char_start': 470, 'char_end': 475, 'chars': ', "" ""'}, {'char_start': 476, 'char_end': 477, 'chars': 'j'}, {'char_start': 481, 'char_end': 489, 'chars': 'wwn)), N'}, {'char_start': 491, 'char_end': 492, 'chars': 'e'}], 'added': [{'char_start': 55, 'char_end': 56, 'chars': 's'}, {'char_start': 302, 'char_end': 303, 'chars': 'a'}, {'char_start': 304, 'char_end': 309, 'chars': 'd = ['}, {'char_start': 320, 'char_end': 322, 'chars': ""',""}, {'char_start': 323, 'char_end': 324, 'chars': ""'""}, {'char_start': 332, 'char_end': 334, 'chars': ""',""}, {'char_start': 335, 'char_end': 338, 'chars': 'per'}, {'char_start': 339, 'char_end': 346, 'chars': 'ona_id,'}, {'char_start': 347, 'char_end': 348, 'chars': ""'""}, {'char_start': 355, 'char_end': 357, 'chars': ""',""}, {'char_start': 358, 'char_end': 365, 'chars': 'domain,'}, {'char_start': 385, 'char_end': 387, 'chars': 'ho'}, {'char_start': 388, 'char_end': 389, 'chars': 't'}, {'char_start': 392, 'char_end': 394, 'chars': 'e]'}, {'char_start': 403, 'char_end': 406, 'chars': 'for'}, {'char_start': 407, 'char_end': 410, 'chars': 'wwn'}, {'char_start': 411, 'char_end': 413, 'chars': 'in'}, {'char_start': 414, 'char_end': 420, 'chars': 'wwns:\n'}, {'char_start': 432, 'char_end': 453, 'chars': 'command.append(wwn)\n\n'}, {'char_start': 462, 'char_end': 463, 'chars': 'u'}, {'char_start': 465, 'char_end': 466, 'chars': '='}, {'char_start': 467, 'char_end': 471, 'chars': 'self'}, {'char_start': 472, 'char_end': 476, 'chars': 'comm'}, {'char_start': 477, 'char_end': 482, 'chars': 'n._cl'}, {'char_start': 483, 'char_end': 486, 'chars': '_ru'}, {'char_start': 488, 'char_end': 489, 'chars': 'c'}, {'char_start': 490, 'char_end': 493, 'chars': 'mma'}, {'char_start': 494, 'char_end': 495, 'chars': 'd'}]}",github.com/thatsdone/cinder/commit/c55589b131828f3a595903f6796cb2d0babb772f,cinder/volume/drivers/san/hp/hp_3par_fc.py,cwe-078,147 cwe-125,read_Header,"read_Header(struct archive_read *a, struct _7z_header_info *h, int check_header_id) { struct _7zip *zip = (struct _7zip *)a->format->data; const unsigned char *p; struct _7z_folder *folders; struct _7z_stream_info *si = &(zip->si); struct _7zip_entry *entries; uint32_t folderIndex, indexInFolder; unsigned i; int eindex, empty_streams, sindex; if (check_header_id) { /* * Read Header. */ if ((p = header_bytes(a, 1)) == NULL) return (-1); if (*p != kHeader) return (-1); } /* * Read ArchiveProperties. */ if ((p = header_bytes(a, 1)) == NULL) return (-1); if (*p == kArchiveProperties) { for (;;) { uint64_t size; if ((p = header_bytes(a, 1)) == NULL) return (-1); if (*p == 0) break; if (parse_7zip_uint64(a, &size) < 0) return (-1); } if ((p = header_bytes(a, 1)) == NULL) return (-1); } /* * Read MainStreamsInfo. */ if (*p == kMainStreamsInfo) { if (read_StreamsInfo(a, &(zip->si)) < 0) return (-1); if ((p = header_bytes(a, 1)) == NULL) return (-1); } if (*p == kEnd) return (0); /* * Read FilesInfo. */ if (*p != kFilesInfo) return (-1); if (parse_7zip_uint64(a, &(zip->numFiles)) < 0) return (-1); if (UMAX_ENTRY < zip->numFiles) return (-1); zip->entries = calloc((size_t)zip->numFiles, sizeof(*zip->entries)); if (zip->entries == NULL) return (-1); entries = zip->entries; empty_streams = 0; for (;;) { int type; uint64_t size; size_t ll; if ((p = header_bytes(a, 1)) == NULL) return (-1); type = *p; if (type == kEnd) break; if (parse_7zip_uint64(a, &size) < 0) return (-1); if (zip->header_bytes_remaining < size) return (-1); ll = (size_t)size; switch (type) { case kEmptyStream: h->emptyStreamBools = calloc((size_t)zip->numFiles, sizeof(*h->emptyStreamBools)); if (h->emptyStreamBools == NULL) return (-1); if (read_Bools( a, h->emptyStreamBools, (size_t)zip->numFiles) < 0) return (-1); empty_streams = 0; for (i = 0; i < zip->numFiles; i++) { if (h->emptyStreamBools[i]) empty_streams++; } break; case kEmptyFile: if (empty_streams <= 0) { /* Unexcepted sequence. Skip this. */ if (header_bytes(a, ll) == NULL) return (-1); break; } h->emptyFileBools = calloc(empty_streams, sizeof(*h->emptyFileBools)); if (h->emptyFileBools == NULL) return (-1); if (read_Bools(a, h->emptyFileBools, empty_streams) < 0) return (-1); break; case kAnti: if (empty_streams <= 0) { /* Unexcepted sequence. Skip this. */ if (header_bytes(a, ll) == NULL) return (-1); break; } h->antiBools = calloc(empty_streams, sizeof(*h->antiBools)); if (h->antiBools == NULL) return (-1); if (read_Bools(a, h->antiBools, empty_streams) < 0) return (-1); break; case kCTime: case kATime: case kMTime: if (read_Times(a, h, type) < 0) return (-1); break; case kName: { unsigned char *np; size_t nl, nb; /* Skip one byte. */ if ((p = header_bytes(a, 1)) == NULL) return (-1); ll--; if ((ll & 1) || ll < zip->numFiles * 4) return (-1); zip->entry_names = malloc(ll); if (zip->entry_names == NULL) return (-1); np = zip->entry_names; nb = ll; /* * Copy whole file names. * NOTE: This loop prevents from expanding * the uncompressed buffer in order not to * use extra memory resource. */ while (nb) { size_t b; if (nb > UBUFF_SIZE) b = UBUFF_SIZE; else b = nb; if ((p = header_bytes(a, b)) == NULL) return (-1); memcpy(np, p, b); np += b; nb -= b; } np = zip->entry_names; nl = ll; for (i = 0; i < zip->numFiles; i++) { entries[i].utf16name = np; #if defined(_WIN32) && !defined(__CYGWIN__) && defined(_DEBUG) entries[i].wname = (wchar_t *)np; #endif /* Find a terminator. */ while (nl >= 2 && (np[0] || np[1])) { np += 2; nl -= 2; } if (nl < 2) return (-1);/* Terminator not found */ entries[i].name_len = np - entries[i].utf16name; np += 2; nl -= 2; } break; } case kAttributes: { int allAreDefined; if ((p = header_bytes(a, 2)) == NULL) return (-1); allAreDefined = *p; h->attrBools = calloc((size_t)zip->numFiles, sizeof(*h->attrBools)); if (h->attrBools == NULL) return (-1); if (allAreDefined) memset(h->attrBools, 1, (size_t)zip->numFiles); else { if (read_Bools(a, h->attrBools, (size_t)zip->numFiles) < 0) return (-1); } for (i = 0; i < zip->numFiles; i++) { if (h->attrBools[i]) { if ((p = header_bytes(a, 4)) == NULL) return (-1); entries[i].attr = archive_le32dec(p); } } break; } case kDummy: if (ll == 0) break; default: if (header_bytes(a, ll) == NULL) return (-1); break; } } /* * Set up entry's attributes. */ folders = si->ci.folders; eindex = sindex = 0; folderIndex = indexInFolder = 0; for (i = 0; i < zip->numFiles; i++) { if (h->emptyStreamBools == NULL || h->emptyStreamBools[i] == 0) entries[i].flg |= HAS_STREAM; /* The high 16 bits of attributes is a posix file mode. */ entries[i].mode = entries[i].attr >> 16; if (entries[i].flg & HAS_STREAM) { if ((size_t)sindex >= si->ss.unpack_streams) return (-1); if (entries[i].mode == 0) entries[i].mode = AE_IFREG | 0666; if (si->ss.digestsDefined[sindex]) entries[i].flg |= CRC32_IS_SET; entries[i].ssIndex = sindex; sindex++; } else { int dir; if (h->emptyFileBools == NULL) dir = 1; else { if (h->emptyFileBools[eindex]) dir = 0; else dir = 1; eindex++; } if (entries[i].mode == 0) { if (dir) entries[i].mode = AE_IFDIR | 0777; else entries[i].mode = AE_IFREG | 0666; } else if (dir && (entries[i].mode & AE_IFMT) != AE_IFDIR) { entries[i].mode &= ~AE_IFMT; entries[i].mode |= AE_IFDIR; } if ((entries[i].mode & AE_IFMT) == AE_IFDIR && entries[i].name_len >= 2 && (entries[i].utf16name[entries[i].name_len-2] != '/' || entries[i].utf16name[entries[i].name_len-1] != 0)) { entries[i].utf16name[entries[i].name_len] = '/'; entries[i].utf16name[entries[i].name_len+1] = 0; entries[i].name_len += 2; } entries[i].ssIndex = -1; } if (entries[i].attr & 0x01) entries[i].mode &= ~0222;/* Read only. */ if ((entries[i].flg & HAS_STREAM) == 0 && indexInFolder == 0) { /* * The entry is an empty file or a directory file, * those both have no contents. */ entries[i].folderIndex = -1; continue; } if (indexInFolder == 0) { for (;;) { if (folderIndex >= si->ci.numFolders) return (-1); if (folders[folderIndex].numUnpackStreams) break; folderIndex++; } } entries[i].folderIndex = folderIndex; if ((entries[i].flg & HAS_STREAM) == 0) continue; indexInFolder++; if (indexInFolder >= folders[folderIndex].numUnpackStreams) { folderIndex++; indexInFolder = 0; } } return (0); }","read_Header(struct archive_read *a, struct _7z_header_info *h, int check_header_id) { struct _7zip *zip = (struct _7zip *)a->format->data; const unsigned char *p; struct _7z_folder *folders; struct _7z_stream_info *si = &(zip->si); struct _7zip_entry *entries; uint32_t folderIndex, indexInFolder; unsigned i; int eindex, empty_streams, sindex; if (check_header_id) { /* * Read Header. */ if ((p = header_bytes(a, 1)) == NULL) return (-1); if (*p != kHeader) return (-1); } /* * Read ArchiveProperties. */ if ((p = header_bytes(a, 1)) == NULL) return (-1); if (*p == kArchiveProperties) { for (;;) { uint64_t size; if ((p = header_bytes(a, 1)) == NULL) return (-1); if (*p == 0) break; if (parse_7zip_uint64(a, &size) < 0) return (-1); } if ((p = header_bytes(a, 1)) == NULL) return (-1); } /* * Read MainStreamsInfo. */ if (*p == kMainStreamsInfo) { if (read_StreamsInfo(a, &(zip->si)) < 0) return (-1); if ((p = header_bytes(a, 1)) == NULL) return (-1); } if (*p == kEnd) return (0); /* * Read FilesInfo. */ if (*p != kFilesInfo) return (-1); if (parse_7zip_uint64(a, &(zip->numFiles)) < 0) return (-1); if (UMAX_ENTRY < zip->numFiles) return (-1); zip->entries = calloc((size_t)zip->numFiles, sizeof(*zip->entries)); if (zip->entries == NULL) return (-1); entries = zip->entries; empty_streams = 0; for (;;) { int type; uint64_t size; size_t ll; if ((p = header_bytes(a, 1)) == NULL) return (-1); type = *p; if (type == kEnd) break; if (parse_7zip_uint64(a, &size) < 0) return (-1); if (zip->header_bytes_remaining < size) return (-1); ll = (size_t)size; switch (type) { case kEmptyStream: if (h->emptyStreamBools != NULL) return (-1); h->emptyStreamBools = calloc((size_t)zip->numFiles, sizeof(*h->emptyStreamBools)); if (h->emptyStreamBools == NULL) return (-1); if (read_Bools( a, h->emptyStreamBools, (size_t)zip->numFiles) < 0) return (-1); empty_streams = 0; for (i = 0; i < zip->numFiles; i++) { if (h->emptyStreamBools[i]) empty_streams++; } break; case kEmptyFile: if (empty_streams <= 0) { /* Unexcepted sequence. Skip this. */ if (header_bytes(a, ll) == NULL) return (-1); break; } if (h->emptyFileBools != NULL) return (-1); h->emptyFileBools = calloc(empty_streams, sizeof(*h->emptyFileBools)); if (h->emptyFileBools == NULL) return (-1); if (read_Bools(a, h->emptyFileBools, empty_streams) < 0) return (-1); break; case kAnti: if (empty_streams <= 0) { /* Unexcepted sequence. Skip this. */ if (header_bytes(a, ll) == NULL) return (-1); break; } if (h->antiBools != NULL) return (-1); h->antiBools = calloc(empty_streams, sizeof(*h->antiBools)); if (h->antiBools == NULL) return (-1); if (read_Bools(a, h->antiBools, empty_streams) < 0) return (-1); break; case kCTime: case kATime: case kMTime: if (read_Times(a, h, type) < 0) return (-1); break; case kName: { unsigned char *np; size_t nl, nb; /* Skip one byte. */ if ((p = header_bytes(a, 1)) == NULL) return (-1); ll--; if ((ll & 1) || ll < zip->numFiles * 4) return (-1); if (zip->entry_names != NULL) return (-1); zip->entry_names = malloc(ll); if (zip->entry_names == NULL) return (-1); np = zip->entry_names; nb = ll; /* * Copy whole file names. * NOTE: This loop prevents from expanding * the uncompressed buffer in order not to * use extra memory resource. */ while (nb) { size_t b; if (nb > UBUFF_SIZE) b = UBUFF_SIZE; else b = nb; if ((p = header_bytes(a, b)) == NULL) return (-1); memcpy(np, p, b); np += b; nb -= b; } np = zip->entry_names; nl = ll; for (i = 0; i < zip->numFiles; i++) { entries[i].utf16name = np; #if defined(_WIN32) && !defined(__CYGWIN__) && defined(_DEBUG) entries[i].wname = (wchar_t *)np; #endif /* Find a terminator. */ while (nl >= 2 && (np[0] || np[1])) { np += 2; nl -= 2; } if (nl < 2) return (-1);/* Terminator not found */ entries[i].name_len = np - entries[i].utf16name; np += 2; nl -= 2; } break; } case kAttributes: { int allAreDefined; if ((p = header_bytes(a, 2)) == NULL) return (-1); allAreDefined = *p; if (h->attrBools != NULL) return (-1); h->attrBools = calloc((size_t)zip->numFiles, sizeof(*h->attrBools)); if (h->attrBools == NULL) return (-1); if (allAreDefined) memset(h->attrBools, 1, (size_t)zip->numFiles); else { if (read_Bools(a, h->attrBools, (size_t)zip->numFiles) < 0) return (-1); } for (i = 0; i < zip->numFiles; i++) { if (h->attrBools[i]) { if ((p = header_bytes(a, 4)) == NULL) return (-1); entries[i].attr = archive_le32dec(p); } } break; } case kDummy: if (ll == 0) break; default: if (header_bytes(a, ll) == NULL) return (-1); break; } } /* * Set up entry's attributes. */ folders = si->ci.folders; eindex = sindex = 0; folderIndex = indexInFolder = 0; for (i = 0; i < zip->numFiles; i++) { if (h->emptyStreamBools == NULL || h->emptyStreamBools[i] == 0) entries[i].flg |= HAS_STREAM; /* The high 16 bits of attributes is a posix file mode. */ entries[i].mode = entries[i].attr >> 16; if (entries[i].flg & HAS_STREAM) { if ((size_t)sindex >= si->ss.unpack_streams) return (-1); if (entries[i].mode == 0) entries[i].mode = AE_IFREG | 0666; if (si->ss.digestsDefined[sindex]) entries[i].flg |= CRC32_IS_SET; entries[i].ssIndex = sindex; sindex++; } else { int dir; if (h->emptyFileBools == NULL) dir = 1; else { if (h->emptyFileBools[eindex]) dir = 0; else dir = 1; eindex++; } if (entries[i].mode == 0) { if (dir) entries[i].mode = AE_IFDIR | 0777; else entries[i].mode = AE_IFREG | 0666; } else if (dir && (entries[i].mode & AE_IFMT) != AE_IFDIR) { entries[i].mode &= ~AE_IFMT; entries[i].mode |= AE_IFDIR; } if ((entries[i].mode & AE_IFMT) == AE_IFDIR && entries[i].name_len >= 2 && (entries[i].utf16name[entries[i].name_len-2] != '/' || entries[i].utf16name[entries[i].name_len-1] != 0)) { entries[i].utf16name[entries[i].name_len] = '/'; entries[i].utf16name[entries[i].name_len+1] = 0; entries[i].name_len += 2; } entries[i].ssIndex = -1; } if (entries[i].attr & 0x01) entries[i].mode &= ~0222;/* Read only. */ if ((entries[i].flg & HAS_STREAM) == 0 && indexInFolder == 0) { /* * The entry is an empty file or a directory file, * those both have no contents. */ entries[i].folderIndex = -1; continue; } if (indexInFolder == 0) { for (;;) { if (folderIndex >= si->ci.numFolders) return (-1); if (folders[folderIndex].numUnpackStreams) break; folderIndex++; } } entries[i].folderIndex = folderIndex; if ((entries[i].flg & HAS_STREAM) == 0) continue; indexInFolder++; if (indexInFolder >= folders[folderIndex].numUnpackStreams) { folderIndex++; indexInFolder = 0; } } return (0); }","{'deleted': [], 'added': [{'line_no': 90, 'char_start': 1753, 'char_end': 1789, 'line': '\t\t\tif (h->emptyStreamBools != NULL)\n'}, {'line_no': 91, 'char_start': 1789, 'char_end': 1806, 'line': '\t\t\t\treturn (-1);\n'}, {'line_no': 112, 'char_start': 2340, 'char_end': 2374, 'line': '\t\t\tif (h->emptyFileBools != NULL)\n'}, {'line_no': 113, 'char_start': 2374, 'char_end': 2391, 'line': '\t\t\t\treturn (-1);\n'}, {'line_no': 128, 'char_start': 2766, 'char_end': 2795, 'line': '\t\t\tif (h->antiBools != NULL)\n'}, {'line_no': 129, 'char_start': 2795, 'char_end': 2812, 'line': '\t\t\t\treturn (-1);\n'}, {'line_no': 156, 'char_start': 3330, 'char_end': 3363, 'line': '\t\t\tif (zip->entry_names != NULL)\n'}, {'line_no': 157, 'char_start': 3363, 'char_end': 3380, 'line': '\t\t\t\treturn (-1);\n'}, {'line_no': 210, 'char_start': 4491, 'char_end': 4520, 'line': '\t\t\tif (h->attrBools != NULL)\n'}, {'line_no': 211, 'char_start': 4520, 'char_end': 4537, 'line': '\t\t\t\treturn (-1);\n'}]}","{'deleted': [{'char_start': 1808, 'char_end': 1808, 'chars': ''}, {'char_start': 4268, 'char_end': 4268, 'chars': ''}], 'added': [{'char_start': 1756, 'char_end': 1809, 'chars': 'if (h->emptyStreamBools != NULL)\n\t\t\t\treturn (-1);\n\t\t\t'}, {'char_start': 2340, 'char_end': 2391, 'chars': '\t\t\tif (h->emptyFileBools != NULL)\n\t\t\t\treturn (-1);\n'}, {'char_start': 2766, 'char_end': 2812, 'chars': '\t\t\tif (h->antiBools != NULL)\n\t\t\t\treturn (-1);\n'}, {'char_start': 3330, 'char_end': 3380, 'chars': '\t\t\tif (zip->entry_names != NULL)\n\t\t\t\treturn (-1);\n'}, {'char_start': 4489, 'char_end': 4535, 'chars': ';\n\t\t\tif (h->attrBools != NULL)\n\t\t\t\treturn (-1)'}]}",github.com/libarchive/libarchive/commit/7f17c791dcfd8c0416e2cd2485b19410e47ef126,libarchive/archive_read_support_format_7zip.c,cwe-125,2453 cwe-787,patch,"static PyObject* patch(PyObject* self, PyObject* args) { char *origData, *newData, *diffBlock, *extraBlock, *diffPtr, *extraPtr; Py_ssize_t origDataLength, newDataLength, diffBlockLength, extraBlockLength; PyObject *controlTuples, *tuple, *results; off_t oldpos, newpos, x, y, z; int i, j, numTuples; if (!PyArg_ParseTuple(args, ""s#nO!s#s#"", &origData, &origDataLength, &newDataLength, &PyList_Type, &controlTuples, &diffBlock, &diffBlockLength, &extraBlock, &extraBlockLength)) return NULL; /* allocate the memory for the new data */ newData = PyMem_Malloc(newDataLength + 1); if (!newData) return PyErr_NoMemory(); oldpos = 0; newpos = 0; diffPtr = diffBlock; extraPtr = extraBlock; numTuples = PyList_GET_SIZE(controlTuples); for (i = 0; i < numTuples; i++) { tuple = PyList_GET_ITEM(controlTuples, i); if (!PyTuple_Check(tuple)) { PyMem_Free(newData); PyErr_SetString(PyExc_TypeError, ""expecting tuple""); return NULL; } if (PyTuple_GET_SIZE(tuple) != 3) { PyMem_Free(newData); PyErr_SetString(PyExc_TypeError, ""expecting tuple of size 3""); return NULL; } x = PyLong_AsLong(PyTuple_GET_ITEM(tuple, 0)); y = PyLong_AsLong(PyTuple_GET_ITEM(tuple, 1)); z = PyLong_AsLong(PyTuple_GET_ITEM(tuple, 2)); if (newpos + x > newDataLength || diffPtr + x > diffBlock + diffBlockLength || extraPtr + y > extraBlock + extraBlockLength) { PyMem_Free(newData); PyErr_SetString(PyExc_ValueError, ""corrupt patch (overflow)""); return NULL; } memcpy(newData + newpos, diffPtr, x); diffPtr += x; for (j = 0; j < x; j++) if ((oldpos + j >= 0) && (oldpos + j < origDataLength)) newData[newpos + j] += origData[oldpos + j]; newpos += x; oldpos += x; memcpy(newData + newpos, extraPtr, y); extraPtr += y; newpos += y; oldpos += z; } /* confirm that a valid patch was applied */ if (newpos != newDataLength || diffPtr != diffBlock + diffBlockLength || extraPtr != extraBlock + extraBlockLength) { PyMem_Free(newData); PyErr_SetString(PyExc_ValueError, ""corrupt patch (underflow)""); return NULL; } results = PyBytes_FromStringAndSize(newData, newDataLength); PyMem_Free(newData); return results; }","static PyObject* patch(PyObject* self, PyObject* args) { char *origData, *newData, *diffBlock, *extraBlock, *diffPtr, *extraPtr; Py_ssize_t origDataLength, newDataLength, diffBlockLength, extraBlockLength; PyObject *controlTuples, *tuple, *results; off_t oldpos, newpos, x, y, z; int i, j, numTuples; if (!PyArg_ParseTuple(args, ""s#nO!s#s#"", &origData, &origDataLength, &newDataLength, &PyList_Type, &controlTuples, &diffBlock, &diffBlockLength, &extraBlock, &extraBlockLength)) return NULL; /* allocate the memory for the new data */ newData = PyMem_Malloc(newDataLength + 1); if (!newData) return PyErr_NoMemory(); oldpos = 0; newpos = 0; diffPtr = diffBlock; extraPtr = extraBlock; numTuples = PyList_GET_SIZE(controlTuples); for (i = 0; i < numTuples; i++) { tuple = PyList_GET_ITEM(controlTuples, i); if (!PyTuple_Check(tuple)) { PyMem_Free(newData); PyErr_SetString(PyExc_TypeError, ""expecting tuple""); return NULL; } if (PyTuple_GET_SIZE(tuple) != 3) { PyMem_Free(newData); PyErr_SetString(PyExc_TypeError, ""expecting tuple of size 3""); return NULL; } x = PyLong_AsLong(PyTuple_GET_ITEM(tuple, 0)); y = PyLong_AsLong(PyTuple_GET_ITEM(tuple, 1)); z = PyLong_AsLong(PyTuple_GET_ITEM(tuple, 2)); if (newpos + x > newDataLength || diffPtr + x > diffBlock + diffBlockLength) { PyMem_Free(newData); PyErr_SetString(PyExc_ValueError, ""corrupt patch (overflow)""); return NULL; } memcpy(newData + newpos, diffPtr, x); diffPtr += x; for (j = 0; j < x; j++) if ((oldpos + j >= 0) && (oldpos + j < origDataLength)) newData[newpos + j] += origData[oldpos + j]; newpos += x; oldpos += x; if (newpos + y > newDataLength || extraPtr + y > extraBlock + extraBlockLength) { PyMem_Free(newData); PyErr_SetString(PyExc_ValueError, ""corrupt patch (overflow)""); return NULL; } memcpy(newData + newpos, extraPtr, y); extraPtr += y; newpos += y; oldpos += z; } /* confirm that a valid patch was applied */ if (newpos != newDataLength || diffPtr != diffBlock + diffBlockLength || extraPtr != extraBlock + extraBlockLength) { PyMem_Free(newData); PyErr_SetString(PyExc_ValueError, ""corrupt patch (underflow)""); return NULL; } results = PyBytes_FromStringAndSize(newData, newDataLength); PyMem_Free(newData); return results; }","{'deleted': [{'line_no': 42, 'char_start': 1561, 'char_end': 1622, 'line': ' diffPtr + x > diffBlock + diffBlockLength ||\n'}, {'line_no': 43, 'char_start': 1622, 'char_end': 1686, 'line': ' extraPtr + y > extraBlock + extraBlockLength) {\n'}], 'added': [{'line_no': 42, 'char_start': 1561, 'char_end': 1622, 'line': ' diffPtr + x > diffBlock + diffBlockLength) {\n'}, {'line_no': 54, 'char_start': 2036, 'char_end': 2078, 'line': ' if (newpos + y > newDataLength ||\n'}, {'line_no': 55, 'char_start': 2078, 'char_end': 2142, 'line': ' extraPtr + y > extraBlock + extraBlockLength) {\n'}, {'line_no': 56, 'char_start': 2142, 'char_end': 2175, 'line': ' PyMem_Free(newData);\n'}, {'line_no': 57, 'char_start': 2175, 'char_end': 2250, 'line': ' PyErr_SetString(PyExc_ValueError, ""corrupt patch (overflow)"");\n'}, {'line_no': 58, 'char_start': 2250, 'char_end': 2275, 'line': ' return NULL;\n'}, {'line_no': 59, 'char_start': 2275, 'char_end': 2285, 'line': ' }\n'}]}","{'deleted': [{'char_start': 1618, 'char_end': 1682, 'chars': ' ||\n extraPtr + y > extraBlock + extraBlockLength'}], 'added': [{'char_start': 2035, 'char_end': 2284, 'chars': '\n if (newpos + y > newDataLength ||\n extraPtr + y > extraBlock + extraBlockLength) {\n PyMem_Free(newData);\n PyErr_SetString(PyExc_ValueError, ""corrupt patch (overflow)"");\n return NULL;\n }'}]}",github.com/ilanschnell/bsdiff4/commit/49a4cee2feef7deaf9d89e5e793a8824930284d7,bsdiff4/core.c,cwe-787,685 cwe-078,test_skip_paths_issue_938,"def test_skip_paths_issue_938(tmpdir): base_dir = tmpdir.mkdir('project') config_dir = base_dir.mkdir('conf') config_dir.join('.isort.cfg').write('[isort]\n' 'line_length = 88\n' 'multi_line_output = 4\n' 'lines_after_imports = 2\n' 'skip_glob =\n' ' migrations/**.py\n') base_dir.join('dont_skip.py').write('import os\n' '\n' 'print(""Hello World"")' '\n' 'import sys\n') migrations_dir = base_dir.mkdir('migrations') migrations_dir.join('file_glob_skip.py').write('import os\n' '\n' 'print(""Hello World"")\n' '\n' 'import sys\n') test_run_directory = os.getcwd() os.chdir(str(base_dir)) results = check_output(['isort', 'dont_skip.py', 'migrations/file_glob_skip.py']) os.chdir(str(test_run_directory)) assert b'skipped' not in results.lower() os.chdir(str(base_dir)) results = check_output(['isort', '--filter-files', '--settings-path=conf/.isort.cfg', 'dont_skip.py', 'migrations/file_glob_skip.py']) os.chdir(str(test_run_directory)) assert b'skipped 1' in results.lower()","def test_skip_paths_issue_938(tmpdir): base_dir = tmpdir.mkdir('project') config_dir = base_dir.mkdir('conf') config_dir.join('.isort.cfg').write('[isort]\n' 'line_length = 88\n' 'multi_line_output = 4\n' 'lines_after_imports = 2\n' 'skip_glob =\n' ' migrations/**.py\n') base_dir.join('dont_skip.py').write('import os\n' '\n' 'print(""Hello World"")' '\n' 'import sys\n') migrations_dir = base_dir.mkdir('migrations') migrations_dir.join('file_glob_skip.py').write('import os\n' '\n' 'print(""Hello World"")\n' '\n' 'import sys\n') test_run_directory = os.getcwd() os.chdir(str(base_dir)) result = subprocess.run( ['isort', 'dont_skip.py', 'migrations/file_glob_skip.py'], stdout=subprocess.PIPE, check=True, ) os.chdir(str(test_run_directory)) assert b'skipped' not in result.stdout.lower() os.chdir(str(base_dir)) result = subprocess.run( ['isort', '--filter-files', '--settings-path=conf/.isort.cfg', 'dont_skip.py', 'migrations/file_glob_skip.py'], stdout=subprocess.PIPE, check=True, ) os.chdir(str(test_run_directory)) assert b'skipped 1' in result.stdout.lower()","{'deleted': [{'line_no': 25, 'char_start': 1187, 'char_end': 1273, 'line': "" results = check_output(['isort', 'dont_skip.py', 'migrations/file_glob_skip.py'])\n""}, {'line_no': 28, 'char_start': 1312, 'char_end': 1357, 'line': "" assert b'skipped' not in results.lower()\n""}, {'line_no': 31, 'char_start': 1386, 'char_end': 1525, 'line': "" results = check_output(['isort', '--filter-files', '--settings-path=conf/.isort.cfg', 'dont_skip.py', 'migrations/file_glob_skip.py'])\n""}, {'line_no': 34, 'char_start': 1564, 'char_end': 1606, 'line': "" assert b'skipped 1' in results.lower()\n""}], 'added': [{'line_no': 25, 'char_start': 1187, 'char_end': 1216, 'line': ' result = subprocess.run(\n'}, {'line_no': 26, 'char_start': 1216, 'char_end': 1283, 'line': "" ['isort', 'dont_skip.py', 'migrations/file_glob_skip.py'],\n""}, {'line_no': 27, 'char_start': 1283, 'char_end': 1315, 'line': ' stdout=subprocess.PIPE,\n'}, {'line_no': 28, 'char_start': 1315, 'char_end': 1335, 'line': ' check=True,\n'}, {'line_no': 29, 'char_start': 1335, 'char_end': 1341, 'line': ' )\n'}, {'line_no': 32, 'char_start': 1380, 'char_end': 1431, 'line': "" assert b'skipped' not in result.stdout.lower()\n""}, {'line_no': 35, 'char_start': 1460, 'char_end': 1489, 'line': ' result = subprocess.run(\n'}, {'line_no': 36, 'char_start': 1489, 'char_end': 1609, 'line': "" ['isort', '--filter-files', '--settings-path=conf/.isort.cfg', 'dont_skip.py', 'migrations/file_glob_skip.py'],\n""}, {'line_no': 37, 'char_start': 1609, 'char_end': 1641, 'line': ' stdout=subprocess.PIPE,\n'}, {'line_no': 38, 'char_start': 1641, 'char_end': 1661, 'line': ' check=True,\n'}, {'line_no': 39, 'char_start': 1661, 'char_end': 1667, 'line': ' )\n'}, {'line_no': 42, 'char_start': 1706, 'char_end': 1754, 'line': "" assert b'skipped 1' in result.stdout.lower()\n""}]}","{'deleted': [{'char_start': 1197, 'char_end': 1198, 'chars': 's'}, {'char_start': 1202, 'char_end': 1203, 'chars': 'h'}, {'char_start': 1204, 'char_end': 1211, 'chars': 'ck_outp'}, {'char_start': 1212, 'char_end': 1213, 'chars': 't'}, {'char_start': 1396, 'char_end': 1397, 'chars': 's'}, {'char_start': 1401, 'char_end': 1402, 'chars': 'h'}, {'char_start': 1403, 'char_end': 1410, 'chars': 'ck_outp'}, {'char_start': 1411, 'char_end': 1412, 'chars': 't'}], 'added': [{'char_start': 1200, 'char_end': 1206, 'chars': 'subpro'}, {'char_start': 1208, 'char_end': 1212, 'chars': 'ss.r'}, {'char_start': 1213, 'char_end': 1214, 'chars': 'n'}, {'char_start': 1215, 'char_end': 1224, 'chars': '\n '}, {'char_start': 1281, 'char_end': 1339, 'chars': ',\n stdout=subprocess.PIPE,\n check=True,\n '}, {'char_start': 1415, 'char_end': 1416, 'chars': '.'}, {'char_start': 1417, 'char_end': 1422, 'chars': 'tdout'}, {'char_start': 1473, 'char_end': 1479, 'chars': 'subpro'}, {'char_start': 1481, 'char_end': 1485, 'chars': 'ss.r'}, {'char_start': 1486, 'char_end': 1487, 'chars': 'n'}, {'char_start': 1488, 'char_end': 1497, 'chars': '\n '}, {'char_start': 1607, 'char_end': 1665, 'chars': ',\n stdout=subprocess.PIPE,\n check=True,\n '}, {'char_start': 1739, 'char_end': 1740, 'chars': '.'}, {'char_start': 1741, 'char_end': 1746, 'chars': 'tdout'}]}",github.com/timothycrosley/isort/commit/1ab38f4f7840a3c19bf961a24630a992a8373a76,test_isort.py,cwe-078,305 cwe-078,_delete_vdisk," def _delete_vdisk(self, name, force): """"""Deletes existing vdisks. It is very important to properly take care of mappings before deleting the disk: 1. If no mappings, then it was a vdisk, and can be deleted 2. If it is the source of a flashcopy mapping and copy_rate is 0, then it is a vdisk that has a snapshot. If the force flag is set, delete the mapping and the vdisk, otherwise set the mapping to copy and wait (this will allow users to delete vdisks that have snapshots if/when the upper layers allow it). 3. If it is the target of a mapping and copy_rate is 0, it is a snapshot, and we should properly stop the mapping and delete. 4. If it is the source/target of a mapping and copy_rate is not 0, it is a clone or vdisk created from a snapshot. We wait for the copy to complete (the mapping will be autodeleted) and then delete the vdisk. """""" LOG.debug(_('enter: _delete_vdisk: vdisk %s') % name) # Try to delete volume only if found on the storage vdisk_defined = self._is_vdisk_defined(name) if not vdisk_defined: LOG.info(_('warning: Tried to delete vdisk %s but it does not ' 'exist.') % name) return self._ensure_vdisk_no_fc_mappings(name) forceflag = '-force' if force else '' cmd_params = {'frc': forceflag, 'name': name} ssh_cmd = 'svctask rmvdisk %(frc)s %(name)s' % cmd_params out, err = self._run_ssh(ssh_cmd) # No output should be returned from rmvdisk self._assert_ssh_return(len(out.strip()) == 0, ('_delete_vdisk %(name)s') % {'name': name}, ssh_cmd, out, err) LOG.debug(_('leave: _delete_vdisk: vdisk %s') % name)"," def _delete_vdisk(self, name, force): """"""Deletes existing vdisks. It is very important to properly take care of mappings before deleting the disk: 1. If no mappings, then it was a vdisk, and can be deleted 2. If it is the source of a flashcopy mapping and copy_rate is 0, then it is a vdisk that has a snapshot. If the force flag is set, delete the mapping and the vdisk, otherwise set the mapping to copy and wait (this will allow users to delete vdisks that have snapshots if/when the upper layers allow it). 3. If it is the target of a mapping and copy_rate is 0, it is a snapshot, and we should properly stop the mapping and delete. 4. If it is the source/target of a mapping and copy_rate is not 0, it is a clone or vdisk created from a snapshot. We wait for the copy to complete (the mapping will be autodeleted) and then delete the vdisk. """""" LOG.debug(_('enter: _delete_vdisk: vdisk %s') % name) # Try to delete volume only if found on the storage vdisk_defined = self._is_vdisk_defined(name) if not vdisk_defined: LOG.info(_('warning: Tried to delete vdisk %s but it does not ' 'exist.') % name) return self._ensure_vdisk_no_fc_mappings(name) ssh_cmd = ['svctask', 'rmvdisk', '-force', name] if not force: ssh_cmd.remove('-force') out, err = self._run_ssh(ssh_cmd) # No output should be returned from rmvdisk self._assert_ssh_return(len(out.strip()) == 0, ('_delete_vdisk %(name)s') % {'name': name}, ssh_cmd, out, err) LOG.debug(_('leave: _delete_vdisk: vdisk %s') % name)","{'deleted': [{'line_no': 32, 'char_start': 1403, 'char_end': 1449, 'line': "" forceflag = '-force' if force else ''\n""}, {'line_no': 33, 'char_start': 1449, 'char_end': 1503, 'line': "" cmd_params = {'frc': forceflag, 'name': name}\n""}, {'line_no': 34, 'char_start': 1503, 'char_end': 1569, 'line': "" ssh_cmd = 'svctask rmvdisk %(frc)s %(name)s' % cmd_params\n""}], 'added': [{'line_no': 32, 'char_start': 1403, 'char_end': 1460, 'line': "" ssh_cmd = ['svctask', 'rmvdisk', '-force', name]\n""}, {'line_no': 33, 'char_start': 1460, 'char_end': 1482, 'line': ' if not force:\n'}, {'line_no': 34, 'char_start': 1482, 'char_end': 1519, 'line': "" ssh_cmd.remove('-force')\n""}]}","{'deleted': [{'char_start': 1411, 'char_end': 1414, 'chars': 'for'}, {'char_start': 1415, 'char_end': 1420, 'chars': 'eflag'}, {'char_start': 1424, 'char_end': 1428, 'chars': '-for'}, {'char_start': 1429, 'char_end': 1430, 'chars': 'e'}, {'char_start': 1433, 'char_end': 1434, 'chars': 'f'}, {'char_start': 1441, 'char_end': 1444, 'chars': 'els'}, {'char_start': 1445, 'char_end': 1448, 'chars': "" ''""}, {'char_start': 1457, 'char_end': 1472, 'chars': ""cmd_params = {'""}, {'char_start': 1473, 'char_end': 1477, 'chars': ""rc':""}, {'char_start': 1483, 'char_end': 1488, 'chars': 'flag,'}, {'char_start': 1489, 'char_end': 1496, 'chars': ""'name':""}, {'char_start': 1497, 'char_end': 1503, 'chars': 'name}\n'}, {'char_start': 1518, 'char_end': 1530, 'chars': "" = 'svctask ""}, {'char_start': 1533, 'char_end': 1539, 'chars': 'disk %'}, {'char_start': 1543, 'char_end': 1551, 'chars': ')s %(nam'}, {'char_start': 1552, 'char_end': 1554, 'chars': ')s'}, {'char_start': 1555, 'char_end': 1568, 'chars': ' % cmd_params'}], 'added': [{'char_start': 1411, 'char_end': 1415, 'chars': 'ssh_'}, {'char_start': 1416, 'char_end': 1418, 'chars': 'md'}, {'char_start': 1421, 'char_end': 1422, 'chars': '['}, {'char_start': 1423, 'char_end': 1425, 'chars': 'sv'}, {'char_start': 1426, 'char_end': 1430, 'chars': 'task'}, {'char_start': 1431, 'char_end': 1432, 'chars': ','}, {'char_start': 1433, 'char_end': 1438, 'chars': ""'rmvd""}, {'char_start': 1439, 'char_end': 1443, 'chars': ""sk',""}, {'char_start': 1444, 'char_end': 1446, 'chars': ""'-""}, {'char_start': 1451, 'char_end': 1453, 'chars': ""',""}, {'char_start': 1454, 'char_end': 1457, 'chars': 'nam'}, {'char_start': 1458, 'char_end': 1459, 'chars': ']'}, {'char_start': 1468, 'char_end': 1470, 'chars': 'if'}, {'char_start': 1471, 'char_end': 1474, 'chars': 'not'}, {'char_start': 1476, 'char_end': 1477, 'chars': 'o'}, {'char_start': 1479, 'char_end': 1480, 'chars': 'e'}, {'char_start': 1481, 'char_end': 1482, 'chars': '\n'}, {'char_start': 1485, 'char_end': 1486, 'chars': ' '}, {'char_start': 1501, 'char_end': 1502, 'chars': '.'}, {'char_start': 1503, 'char_end': 1504, 'chars': 'e'}, {'char_start': 1505, 'char_end': 1506, 'chars': 'o'}, {'char_start': 1507, 'char_end': 1508, 'chars': 'e'}, {'char_start': 1509, 'char_end': 1511, 'chars': ""'-""}, {'char_start': 1512, 'char_end': 1513, 'chars': 'o'}, {'char_start': 1517, 'char_end': 1518, 'chars': ')'}]}",github.com/thatsdone/cinder/commit/f752302d181583a95cf44354aea607ce9d9283f4,cinder/volume/drivers/storwize_svc.py,cwe-078,468 cwe-079,edit_bundle,"@check_document_access_permission() def edit_bundle(request): bundle_id = request.GET.get('bundle') doc = None if bundle_id: doc = Document2.objects.get(id=bundle_id) bundle = Bundle(document=doc) else: bundle = Bundle() coordinators = [dict([('uuid', d.content_object.uuid), ('name', d.content_object.name)]) for d in Document.objects.get_docs(request.user, Document2, extra='coordinator2')] return render('editor/bundle_editor.mako', request, { 'bundle_json': bundle.json, 'coordinators_json': json.dumps(coordinators), 'doc1_id': doc.doc.get().id if doc else -1, 'can_edit_json': json.dumps(doc is None or doc.doc.get().is_editable(request.user)) })","@check_document_access_permission() def edit_bundle(request): bundle_id = request.GET.get('bundle') doc = None if bundle_id: doc = Document2.objects.get(id=bundle_id) bundle = Bundle(document=doc) else: bundle = Bundle() coordinators = [dict([('uuid', d.content_object.uuid), ('name', d.content_object.name)]) for d in Document.objects.get_docs(request.user, Document2, extra='coordinator2')] return render('editor/bundle_editor.mako', request, { 'bundle_json': bundle.json_for_html(), 'coordinators_json': json.dumps(coordinators, cls=JSONEncoderForHTML), 'doc1_id': doc.doc.get().id if doc else -1, 'can_edit_json': json.dumps(doc is None or doc.doc.get().is_editable(request.user)) })","{'deleted': [{'line_no': 16, 'char_start': 498, 'char_end': 532, 'line': "" 'bundle_json': bundle.json,\n""}, {'line_no': 17, 'char_start': 532, 'char_end': 585, 'line': "" 'coordinators_json': json.dumps(coordinators),\n""}], 'added': [{'line_no': 16, 'char_start': 498, 'char_end': 543, 'line': "" 'bundle_json': bundle.json_for_html(),\n""}, {'line_no': 17, 'char_start': 543, 'char_end': 620, 'line': "" 'coordinators_json': json.dumps(coordinators, cls=JSONEncoderForHTML),\n""}]}","{'deleted': [], 'added': [{'char_start': 530, 'char_end': 541, 'chars': '_for_html()'}, {'char_start': 593, 'char_end': 617, 'chars': ', cls=JSONEncoderForHTML'}]}",github.com/gethue/hue/commit/6641c62beaa1468082e47d82da5ed758d11c7735,apps/oozie/src/oozie/views/editor2.py,cwe-079,179 cwe-125,ReadMATImage,"static Image *ReadMATImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *image, *image2=NULL, *rotated_image; PixelPacket *q; unsigned int status; MATHeader MATLAB_HDR; size_t size; size_t CellType; QuantumInfo *quantum_info; ImageInfo *clone_info; int i; ssize_t ldblk; unsigned char *BImgBuff = NULL; double MinVal, MaxVal; size_t Unknown6; unsigned z, z2; unsigned Frames; int logging; int sample_size; MagickOffsetType filepos=0x80; BlobInfo *blob; size_t one; unsigned int (*ReadBlobXXXLong)(Image *image); unsigned short (*ReadBlobXXXShort)(Image *image); void (*ReadBlobDoublesXXX)(Image * image, size_t len, double *data); void (*ReadBlobFloatsXXX)(Image * image, size_t len, float *data); assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); logging = LogMagickEvent(CoderEvent,GetMagickModule(),""enter""); /* Open image file. */ image = AcquireImage(image_info); status = OpenBlob(image_info, image, ReadBinaryBlobMode, exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read MATLAB image. */ clone_info=CloneImageInfo(image_info); if(ReadBlob(image,124,(unsigned char *) &MATLAB_HDR.identific) != 124) ThrowReaderException(CorruptImageError,""ImproperImageHeader""); MATLAB_HDR.Version = ReadBlobLSBShort(image); if(ReadBlob(image,2,(unsigned char *) &MATLAB_HDR.EndianIndicator) != 2) ThrowReaderException(CorruptImageError,""ImproperImageHeader""); if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),"" Endian %c%c"", MATLAB_HDR.EndianIndicator[0],MATLAB_HDR.EndianIndicator[1]); if (!strncmp(MATLAB_HDR.EndianIndicator, ""IM"", 2)) { ReadBlobXXXLong = ReadBlobLSBLong; ReadBlobXXXShort = ReadBlobLSBShort; ReadBlobDoublesXXX = ReadBlobDoublesLSB; ReadBlobFloatsXXX = ReadBlobFloatsLSB; image->endian = LSBEndian; } else if (!strncmp(MATLAB_HDR.EndianIndicator, ""MI"", 2)) { ReadBlobXXXLong = ReadBlobMSBLong; ReadBlobXXXShort = ReadBlobMSBShort; ReadBlobDoublesXXX = ReadBlobDoublesMSB; ReadBlobFloatsXXX = ReadBlobFloatsMSB; image->endian = MSBEndian; } else goto MATLAB_KO; /* unsupported endian */ if (strncmp(MATLAB_HDR.identific, ""MATLAB"", 6)) MATLAB_KO: ThrowReaderException(CorruptImageError,""ImproperImageHeader""); filepos = TellBlob(image); while(!EOFBlob(image)) /* object parser loop */ { Frames = 1; (void) SeekBlob(image,filepos,SEEK_SET); /* printf(""pos=%X\n"",TellBlob(image)); */ MATLAB_HDR.DataType = ReadBlobXXXLong(image); if(EOFBlob(image)) break; MATLAB_HDR.ObjectSize = ReadBlobXXXLong(image); if(EOFBlob(image)) break; filepos += MATLAB_HDR.ObjectSize + 4 + 4; image2 = image; #if defined(MAGICKCORE_ZLIB_DELEGATE) if(MATLAB_HDR.DataType == miCOMPRESSED) { image2 = DecompressBlock(image,MATLAB_HDR.ObjectSize,clone_info,exception); if(image2==NULL) continue; MATLAB_HDR.DataType = ReadBlobXXXLong(image2); /* replace compressed object type. */ } #endif if(MATLAB_HDR.DataType!=miMATRIX) continue; /* skip another objects. */ MATLAB_HDR.unknown1 = ReadBlobXXXLong(image2); MATLAB_HDR.unknown2 = ReadBlobXXXLong(image2); MATLAB_HDR.unknown5 = ReadBlobXXXLong(image2); MATLAB_HDR.StructureClass = MATLAB_HDR.unknown5 & 0xFF; MATLAB_HDR.StructureFlag = (MATLAB_HDR.unknown5>>8) & 0xFF; MATLAB_HDR.unknown3 = ReadBlobXXXLong(image2); if(image!=image2) MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2); /* ??? don't understand why ?? */ MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2); MATLAB_HDR.DimFlag = ReadBlobXXXLong(image2); MATLAB_HDR.SizeX = ReadBlobXXXLong(image2); MATLAB_HDR.SizeY = ReadBlobXXXLong(image2); switch(MATLAB_HDR.DimFlag) { case 8: z2=z=1; break; /* 2D matrix*/ case 12: z2=z = ReadBlobXXXLong(image2); /* 3D matrix RGB*/ Unknown6 = ReadBlobXXXLong(image2); (void) Unknown6; if(z!=3) ThrowReaderException(CoderError, ""MultidimensionalMatricesAreNotSupported""); break; case 16: z2=z = ReadBlobXXXLong(image2); /* 4D matrix animation */ if(z!=3 && z!=1) ThrowReaderException(CoderError, ""MultidimensionalMatricesAreNotSupported""); Frames = ReadBlobXXXLong(image2); break; default: ThrowReaderException(CoderError, ""MultidimensionalMatricesAreNotSupported""); } MATLAB_HDR.Flag1 = ReadBlobXXXShort(image2); MATLAB_HDR.NameFlag = ReadBlobXXXShort(image2); if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), ""MATLAB_HDR.StructureClass %d"",MATLAB_HDR.StructureClass); if (MATLAB_HDR.StructureClass != mxCHAR_CLASS && MATLAB_HDR.StructureClass != mxSINGLE_CLASS && /* float + complex float */ MATLAB_HDR.StructureClass != mxDOUBLE_CLASS && /* double + complex double */ MATLAB_HDR.StructureClass != mxINT8_CLASS && MATLAB_HDR.StructureClass != mxUINT8_CLASS && /* uint8 + uint8 3D */ MATLAB_HDR.StructureClass != mxINT16_CLASS && MATLAB_HDR.StructureClass != mxUINT16_CLASS && /* uint16 + uint16 3D */ MATLAB_HDR.StructureClass != mxINT32_CLASS && MATLAB_HDR.StructureClass != mxUINT32_CLASS && /* uint32 + uint32 3D */ MATLAB_HDR.StructureClass != mxINT64_CLASS && MATLAB_HDR.StructureClass != mxUINT64_CLASS) /* uint64 + uint64 3D */ ThrowReaderException(CoderError,""UnsupportedCellTypeInTheMatrix""); switch (MATLAB_HDR.NameFlag) { case 0: size = ReadBlobXXXLong(image2); /* Object name string size */ size = 4 * (ssize_t) ((size + 3 + 1) / 4); (void) SeekBlob(image2, size, SEEK_CUR); break; case 1: case 2: case 3: case 4: (void) ReadBlob(image2, 4, (unsigned char *) &size); /* Object name string */ break; default: goto MATLAB_KO; } CellType = ReadBlobXXXLong(image2); /* Additional object type */ if (logging) (void) LogMagickEvent(CoderEvent,GetMagickModule(), ""MATLAB_HDR.CellType: %.20g"",(double) CellType); (void) ReadBlob(image2, 4, (unsigned char *) &size); /* data size */ NEXT_FRAME: switch (CellType) { case miINT8: case miUINT8: sample_size = 8; if(MATLAB_HDR.StructureFlag & FLAG_LOGICAL) image->depth = 1; else image->depth = 8; /* Byte type cell */ ldblk = (ssize_t) MATLAB_HDR.SizeX; break; case miINT16: case miUINT16: sample_size = 16; image->depth = 16; /* Word type cell */ ldblk = (ssize_t) (2 * MATLAB_HDR.SizeX); break; case miINT32: case miUINT32: sample_size = 32; image->depth = 32; /* Dword type cell */ ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX); break; case miINT64: case miUINT64: sample_size = 64; image->depth = 64; /* Qword type cell */ ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX); break; case miSINGLE: sample_size = 32; image->depth = 32; /* double type cell */ (void) SetImageOption(clone_info,""quantum:format"",""floating-point""); if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX) { /* complex float type cell */ } ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX); break; case miDOUBLE: sample_size = 64; image->depth = 64; /* double type cell */ (void) SetImageOption(clone_info,""quantum:format"",""floating-point""); DisableMSCWarning(4127) if (sizeof(double) != 8) RestoreMSCWarning ThrowReaderException(CoderError, ""IncompatibleSizeOfDouble""); if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX) { /* complex double type cell */ } ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX); break; default: ThrowReaderException(CoderError, ""UnsupportedCellTypeInTheMatrix""); } (void) sample_size; image->columns = MATLAB_HDR.SizeX; image->rows = MATLAB_HDR.SizeY; quantum_info=AcquireQuantumInfo(clone_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); one=1; image->colors = one << image->depth; if (image->columns == 0 || image->rows == 0) goto MATLAB_KO; /* Image is gray when no complex flag is set and 2D Matrix */ if ((MATLAB_HDR.DimFlag == 8) && ((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0)) { SetImageColorspace(image,GRAYColorspace); image->type=GrayscaleType; } /* If ping is true, then only set image size and colors without reading any image data. */ if (image_info->ping) { size_t temp = image->columns; image->columns = image->rows; image->rows = temp; goto done_reading; /* !!!!!! BAD !!!! */ } status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } /* ----- Load raster data ----- */ BImgBuff = (unsigned char *) AcquireQuantumMemory((size_t) (ldblk),sizeof(double)); /* Ldblk was set in the check phase */ if (BImgBuff == NULL) ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); MinVal = 0; MaxVal = 0; if (CellType==miDOUBLE || CellType==miSINGLE) /* Find Min and Max Values for floats */ { CalcMinMax(image2, image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &quantum_info->minimum, &quantum_info->maximum); } /* Main loop for reading all scanlines */ if(z==1) z=0; /* read grey scanlines */ /* else read color scanlines */ do { for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++) { q=GetAuthenticPixels(image,0,MATLAB_HDR.SizeY-i-1,image->columns,1,exception); if (q == (PixelPacket *) NULL) { if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), "" MAT set image pixels returns unexpected NULL on a row %u."", (unsigned)(MATLAB_HDR.SizeY-i-1)); goto done_reading; /* Skip image rotation, when cannot set image pixels */ } if(ReadBlob(image2,ldblk,(unsigned char *)BImgBuff) != (ssize_t) ldblk) { if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), "" MAT cannot read scanrow %u from a file."", (unsigned)(MATLAB_HDR.SizeY-i-1)); goto ExitLoop; } if((CellType==miINT8 || CellType==miUINT8) && (MATLAB_HDR.StructureFlag & FLAG_LOGICAL)) { FixLogical((unsigned char *)BImgBuff,ldblk); if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0) { ImportQuantumPixelsFailed: if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), "" MAT failed to ImportQuantumPixels for a row %u"", (unsigned)(MATLAB_HDR.SizeY-i-1)); break; } } else { if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0) goto ImportQuantumPixelsFailed; if (z<=1 && /* fix only during a last pass z==0 || z==1 */ (CellType==miINT8 || CellType==miINT16 || CellType==miINT32 || CellType==miINT64)) FixSignedValues(q,MATLAB_HDR.SizeX); } if (!SyncAuthenticPixels(image,exception)) { if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), "" MAT failed to sync image pixels for a row %u"", (unsigned)(MATLAB_HDR.SizeY-i-1)); goto ExitLoop; } } } while(z-- >= 2); ExitLoop: /* Read complex part of numbers here */ if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX) { /* Find Min and Max Values for complex parts of floats */ CellType = ReadBlobXXXLong(image2); /* Additional object type */ i = ReadBlobXXXLong(image2); /* size of a complex part - toss away*/ if (CellType==miDOUBLE || CellType==miSINGLE) { CalcMinMax(image2, image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &MinVal, &MaxVal); } if (CellType==miDOUBLE) for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++) { ReadBlobDoublesXXX(image2, ldblk, (double *)BImgBuff); InsertComplexDoubleRow((double *)BImgBuff, i, image, MinVal, MaxVal); } if (CellType==miSINGLE) for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++) { ReadBlobFloatsXXX(image2, ldblk, (float *)BImgBuff); InsertComplexFloatRow((float *)BImgBuff, i, image, MinVal, MaxVal); } } /* Image is gray when no complex flag is set and 2D Matrix AGAIN!!! */ if ((MATLAB_HDR.DimFlag == 8) && ((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0)) image->type=GrayscaleType; if (image->depth == 1) image->type=BilevelType; if(image2==image) image2 = NULL; /* Remove shadow copy to an image before rotation. */ /* Rotate image. */ rotated_image = RotateImage(image, 90.0, exception); if (rotated_image != (Image *) NULL) { /* Remove page offsets added by RotateImage */ rotated_image->page.x=0; rotated_image->page.y=0; blob = rotated_image->blob; rotated_image->blob = image->blob; rotated_image->colors = image->colors; image->blob = blob; AppendImageToList(&image,rotated_image); DeleteImageFromList(&image); } done_reading: if(image2!=NULL) if(image2!=image) { DeleteImageFromList(&image2); if(clone_info) { if(clone_info->file) { fclose(clone_info->file); clone_info->file = NULL; (void) remove_utf8(clone_info->filename); } } } /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (image->next == (Image *) NULL) break; image=SyncNextImageInList(image); image->columns=image->rows=0; image->colors=0; /* row scan buffer is no longer needed */ RelinquishMagickMemory(BImgBuff); BImgBuff = NULL; if(--Frames>0) { z = z2; if(image2==NULL) image2 = image; goto NEXT_FRAME; } if(image2!=NULL) if(image2!=image) /* Does shadow temporary decompressed image exist? */ { /* CloseBlob(image2); */ DeleteImageFromList(&image2); if(clone_info) { if(clone_info->file) { fclose(clone_info->file); clone_info->file = NULL; (void) unlink(clone_info->filename); } } } } clone_info=DestroyImageInfo(clone_info); RelinquishMagickMemory(BImgBuff); CloseBlob(image); { Image *p; ssize_t scene=0; /* Rewind list, removing any empty images while rewinding. */ p=image; image=NULL; while (p != (Image *) NULL) { Image *tmp=p; if ((p->rows == 0) || (p->columns == 0)) { p=p->previous; DeleteImageFromList(&tmp); } else { image=p; p=p->previous; } } /* Fix scene numbers */ for (p=image; p != (Image *) NULL; p=p->next) p->scene=scene++; } if(clone_info != NULL) /* cleanup garbage file from compression */ { if(clone_info->file) { fclose(clone_info->file); clone_info->file = NULL; (void) remove_utf8(clone_info->filename); } DestroyImageInfo(clone_info); clone_info = NULL; } if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),""return""); if(image==NULL) ThrowReaderException(CorruptImageError,""ImproperImageHeader""); return (image); }","static Image *ReadMATImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *image, *image2=NULL, *rotated_image; PixelPacket *q; unsigned int status; MATHeader MATLAB_HDR; size_t size; size_t CellType; QuantumInfo *quantum_info; ImageInfo *clone_info; int i; ssize_t ldblk; unsigned char *BImgBuff = NULL; double MinVal, MaxVal; size_t Unknown6; unsigned z, z2; unsigned Frames; int logging; int sample_size; MagickOffsetType filepos=0x80; BlobInfo *blob; size_t one; unsigned int (*ReadBlobXXXLong)(Image *image); unsigned short (*ReadBlobXXXShort)(Image *image); void (*ReadBlobDoublesXXX)(Image * image, size_t len, double *data); void (*ReadBlobFloatsXXX)(Image * image, size_t len, float *data); assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); logging = LogMagickEvent(CoderEvent,GetMagickModule(),""enter""); /* Open image file. */ image = AcquireImage(image_info); status = OpenBlob(image_info, image, ReadBinaryBlobMode, exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read MATLAB image. */ clone_info=CloneImageInfo(image_info); if(ReadBlob(image,124,(unsigned char *) &MATLAB_HDR.identific) != 124) ThrowReaderException(CorruptImageError,""ImproperImageHeader""); MATLAB_HDR.Version = ReadBlobLSBShort(image); if(ReadBlob(image,2,(unsigned char *) &MATLAB_HDR.EndianIndicator) != 2) ThrowReaderException(CorruptImageError,""ImproperImageHeader""); if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),"" Endian %c%c"", MATLAB_HDR.EndianIndicator[0],MATLAB_HDR.EndianIndicator[1]); if (!strncmp(MATLAB_HDR.EndianIndicator, ""IM"", 2)) { ReadBlobXXXLong = ReadBlobLSBLong; ReadBlobXXXShort = ReadBlobLSBShort; ReadBlobDoublesXXX = ReadBlobDoublesLSB; ReadBlobFloatsXXX = ReadBlobFloatsLSB; image->endian = LSBEndian; } else if (!strncmp(MATLAB_HDR.EndianIndicator, ""MI"", 2)) { ReadBlobXXXLong = ReadBlobMSBLong; ReadBlobXXXShort = ReadBlobMSBShort; ReadBlobDoublesXXX = ReadBlobDoublesMSB; ReadBlobFloatsXXX = ReadBlobFloatsMSB; image->endian = MSBEndian; } else goto MATLAB_KO; /* unsupported endian */ if (strncmp(MATLAB_HDR.identific, ""MATLAB"", 6)) MATLAB_KO: ThrowReaderException(CorruptImageError,""ImproperImageHeader""); filepos = TellBlob(image); while(!EOFBlob(image)) /* object parser loop */ { Frames = 1; (void) SeekBlob(image,filepos,SEEK_SET); /* printf(""pos=%X\n"",TellBlob(image)); */ MATLAB_HDR.DataType = ReadBlobXXXLong(image); if(EOFBlob(image)) break; MATLAB_HDR.ObjectSize = ReadBlobXXXLong(image); if(EOFBlob(image)) break; filepos += MATLAB_HDR.ObjectSize + 4 + 4; image2 = image; #if defined(MAGICKCORE_ZLIB_DELEGATE) if(MATLAB_HDR.DataType == miCOMPRESSED) { image2 = DecompressBlock(image,MATLAB_HDR.ObjectSize,clone_info,exception); if(image2==NULL) continue; MATLAB_HDR.DataType = ReadBlobXXXLong(image2); /* replace compressed object type. */ } #endif if(MATLAB_HDR.DataType!=miMATRIX) continue; /* skip another objects. */ MATLAB_HDR.unknown1 = ReadBlobXXXLong(image2); MATLAB_HDR.unknown2 = ReadBlobXXXLong(image2); MATLAB_HDR.unknown5 = ReadBlobXXXLong(image2); MATLAB_HDR.StructureClass = MATLAB_HDR.unknown5 & 0xFF; MATLAB_HDR.StructureFlag = (MATLAB_HDR.unknown5>>8) & 0xFF; MATLAB_HDR.unknown3 = ReadBlobXXXLong(image2); if(image!=image2) MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2); /* ??? don't understand why ?? */ MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2); MATLAB_HDR.DimFlag = ReadBlobXXXLong(image2); MATLAB_HDR.SizeX = ReadBlobXXXLong(image2); MATLAB_HDR.SizeY = ReadBlobXXXLong(image2); switch(MATLAB_HDR.DimFlag) { case 8: z2=z=1; break; /* 2D matrix*/ case 12: z2=z = ReadBlobXXXLong(image2); /* 3D matrix RGB*/ Unknown6 = ReadBlobXXXLong(image2); (void) Unknown6; if(z!=3) ThrowReaderException(CoderError, ""MultidimensionalMatricesAreNotSupported""); break; case 16: z2=z = ReadBlobXXXLong(image2); /* 4D matrix animation */ if(z!=3 && z!=1) ThrowReaderException(CoderError, ""MultidimensionalMatricesAreNotSupported""); Frames = ReadBlobXXXLong(image2); break; default: ThrowReaderException(CoderError, ""MultidimensionalMatricesAreNotSupported""); } MATLAB_HDR.Flag1 = ReadBlobXXXShort(image2); MATLAB_HDR.NameFlag = ReadBlobXXXShort(image2); if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), ""MATLAB_HDR.StructureClass %d"",MATLAB_HDR.StructureClass); if (MATLAB_HDR.StructureClass != mxCHAR_CLASS && MATLAB_HDR.StructureClass != mxSINGLE_CLASS && /* float + complex float */ MATLAB_HDR.StructureClass != mxDOUBLE_CLASS && /* double + complex double */ MATLAB_HDR.StructureClass != mxINT8_CLASS && MATLAB_HDR.StructureClass != mxUINT8_CLASS && /* uint8 + uint8 3D */ MATLAB_HDR.StructureClass != mxINT16_CLASS && MATLAB_HDR.StructureClass != mxUINT16_CLASS && /* uint16 + uint16 3D */ MATLAB_HDR.StructureClass != mxINT32_CLASS && MATLAB_HDR.StructureClass != mxUINT32_CLASS && /* uint32 + uint32 3D */ MATLAB_HDR.StructureClass != mxINT64_CLASS && MATLAB_HDR.StructureClass != mxUINT64_CLASS) /* uint64 + uint64 3D */ ThrowReaderException(CoderError,""UnsupportedCellTypeInTheMatrix""); switch (MATLAB_HDR.NameFlag) { case 0: size = ReadBlobXXXLong(image2); /* Object name string size */ size = 4 * (ssize_t) ((size + 3 + 1) / 4); (void) SeekBlob(image2, size, SEEK_CUR); break; case 1: case 2: case 3: case 4: (void) ReadBlob(image2, 4, (unsigned char *) &size); /* Object name string */ break; default: goto MATLAB_KO; } CellType = ReadBlobXXXLong(image2); /* Additional object type */ if (logging) (void) LogMagickEvent(CoderEvent,GetMagickModule(), ""MATLAB_HDR.CellType: %.20g"",(double) CellType); (void) ReadBlob(image2, 4, (unsigned char *) &size); /* data size */ NEXT_FRAME: switch (CellType) { case miINT8: case miUINT8: sample_size = 8; if(MATLAB_HDR.StructureFlag & FLAG_LOGICAL) image->depth = 1; else image->depth = 8; /* Byte type cell */ ldblk = (ssize_t) MATLAB_HDR.SizeX; break; case miINT16: case miUINT16: sample_size = 16; image->depth = 16; /* Word type cell */ ldblk = (ssize_t) (2 * MATLAB_HDR.SizeX); break; case miINT32: case miUINT32: sample_size = 32; image->depth = 32; /* Dword type cell */ ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX); break; case miINT64: case miUINT64: sample_size = 64; image->depth = 64; /* Qword type cell */ ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX); break; case miSINGLE: sample_size = 32; image->depth = 32; /* double type cell */ (void) SetImageOption(clone_info,""quantum:format"",""floating-point""); if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX) { /* complex float type cell */ } ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX); break; case miDOUBLE: sample_size = 64; image->depth = 64; /* double type cell */ (void) SetImageOption(clone_info,""quantum:format"",""floating-point""); DisableMSCWarning(4127) if (sizeof(double) != 8) RestoreMSCWarning ThrowReaderException(CoderError, ""IncompatibleSizeOfDouble""); if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX) { /* complex double type cell */ } ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX); break; default: ThrowReaderException(CoderError, ""UnsupportedCellTypeInTheMatrix""); } (void) sample_size; image->columns = MATLAB_HDR.SizeX; image->rows = MATLAB_HDR.SizeY; quantum_info=AcquireQuantumInfo(clone_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); one=1; image->colors = one << image->depth; if (image->columns == 0 || image->rows == 0) goto MATLAB_KO; /* Image is gray when no complex flag is set and 2D Matrix */ if ((MATLAB_HDR.DimFlag == 8) && ((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0)) { SetImageColorspace(image,GRAYColorspace); image->type=GrayscaleType; } /* If ping is true, then only set image size and colors without reading any image data. */ if (image_info->ping) { size_t temp = image->columns; image->columns = image->rows; image->rows = temp; goto done_reading; /* !!!!!! BAD !!!! */ } status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } /* ----- Load raster data ----- */ BImgBuff = (unsigned char *) AcquireQuantumMemory((size_t) (ldblk),sizeof(double)); /* Ldblk was set in the check phase */ if (BImgBuff == NULL) ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); MinVal = 0; MaxVal = 0; if (CellType==miDOUBLE || CellType==miSINGLE) /* Find Min and Max Values for floats */ { CalcMinMax(image2, image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &quantum_info->minimum, &quantum_info->maximum); } /* Main loop for reading all scanlines */ if(z==1) z=0; /* read grey scanlines */ /* else read color scanlines */ do { for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++) { q=GetAuthenticPixels(image,0,MATLAB_HDR.SizeY-i-1,image->columns,1,exception); if (q == (PixelPacket *) NULL) { if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), "" MAT set image pixels returns unexpected NULL on a row %u."", (unsigned)(MATLAB_HDR.SizeY-i-1)); goto done_reading; /* Skip image rotation, when cannot set image pixels */ } if(ReadBlob(image2,ldblk,(unsigned char *)BImgBuff) != (ssize_t) ldblk) { if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), "" MAT cannot read scanrow %u from a file."", (unsigned)(MATLAB_HDR.SizeY-i-1)); goto ExitLoop; } if((CellType==miINT8 || CellType==miUINT8) && (MATLAB_HDR.StructureFlag & FLAG_LOGICAL)) { FixLogical((unsigned char *)BImgBuff,ldblk); if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0) { ImportQuantumPixelsFailed: if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), "" MAT failed to ImportQuantumPixels for a row %u"", (unsigned)(MATLAB_HDR.SizeY-i-1)); break; } } else { if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0) goto ImportQuantumPixelsFailed; if (z<=1 && /* fix only during a last pass z==0 || z==1 */ (CellType==miINT8 || CellType==miINT16 || CellType==miINT32 || CellType==miINT64)) FixSignedValues(q,MATLAB_HDR.SizeX); } if (!SyncAuthenticPixels(image,exception)) { if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), "" MAT failed to sync image pixels for a row %u"", (unsigned)(MATLAB_HDR.SizeY-i-1)); goto ExitLoop; } } } while(z-- >= 2); quantum_info=DestroyQuantumInfo(quantum_info); ExitLoop: /* Read complex part of numbers here */ if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX) { /* Find Min and Max Values for complex parts of floats */ CellType = ReadBlobXXXLong(image2); /* Additional object type */ i = ReadBlobXXXLong(image2); /* size of a complex part - toss away*/ if (CellType==miDOUBLE || CellType==miSINGLE) { CalcMinMax(image2, image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &MinVal, &MaxVal); } if (CellType==miDOUBLE) for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++) { ReadBlobDoublesXXX(image2, ldblk, (double *)BImgBuff); InsertComplexDoubleRow((double *)BImgBuff, i, image, MinVal, MaxVal); } if (CellType==miSINGLE) for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++) { ReadBlobFloatsXXX(image2, ldblk, (float *)BImgBuff); InsertComplexFloatRow((float *)BImgBuff, i, image, MinVal, MaxVal); } } /* Image is gray when no complex flag is set and 2D Matrix AGAIN!!! */ if ((MATLAB_HDR.DimFlag == 8) && ((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0)) image->type=GrayscaleType; if (image->depth == 1) image->type=BilevelType; if(image2==image) image2 = NULL; /* Remove shadow copy to an image before rotation. */ /* Rotate image. */ rotated_image = RotateImage(image, 90.0, exception); if (rotated_image != (Image *) NULL) { /* Remove page offsets added by RotateImage */ rotated_image->page.x=0; rotated_image->page.y=0; blob = rotated_image->blob; rotated_image->blob = image->blob; rotated_image->colors = image->colors; image->blob = blob; AppendImageToList(&image,rotated_image); DeleteImageFromList(&image); } done_reading: if(image2!=NULL) if(image2!=image) { DeleteImageFromList(&image2); if(clone_info) { if(clone_info->file) { fclose(clone_info->file); clone_info->file = NULL; (void) remove_utf8(clone_info->filename); } } } /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (image->next == (Image *) NULL) break; image=SyncNextImageInList(image); image->columns=image->rows=0; image->colors=0; /* row scan buffer is no longer needed */ RelinquishMagickMemory(BImgBuff); BImgBuff = NULL; if(--Frames>0) { z = z2; if(image2==NULL) image2 = image; goto NEXT_FRAME; } if(image2!=NULL) if(image2!=image) /* Does shadow temporary decompressed image exist? */ { /* CloseBlob(image2); */ DeleteImageFromList(&image2); if(clone_info) { if(clone_info->file) { fclose(clone_info->file); clone_info->file = NULL; (void) unlink(clone_info->filename); } } } } clone_info=DestroyImageInfo(clone_info); RelinquishMagickMemory(BImgBuff); CloseBlob(image); { Image *p; ssize_t scene=0; /* Rewind list, removing any empty images while rewinding. */ p=image; image=NULL; while (p != (Image *) NULL) { Image *tmp=p; if ((p->rows == 0) || (p->columns == 0)) { p=p->previous; DeleteImageFromList(&tmp); } else { image=p; p=p->previous; } } /* Fix scene numbers */ for (p=image; p != (Image *) NULL; p=p->next) p->scene=scene++; } if(clone_info != NULL) /* cleanup garbage file from compression */ { if(clone_info->file) { fclose(clone_info->file); clone_info->file = NULL; (void) remove_utf8(clone_info->filename); } DestroyImageInfo(clone_info); clone_info = NULL; } if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),""return""); if(image==NULL) ThrowReaderException(CorruptImageError,""ImproperImageHeader""); return (image); }","{'deleted': [], 'added': [{'line_no': 336, 'char_start': 12091, 'char_end': 12142, 'line': ' quantum_info=DestroyQuantumInfo(quantum_info);\n'}]}","{'deleted': [], 'added': [{'char_start': 12091, 'char_end': 12142, 'chars': ' quantum_info=DestroyQuantumInfo(quantum_info);\n'}]}",github.com/ImageMagick/ImageMagick/commit/b173a352397877775c51c9a0e9d59eb6ce24c455,coders/mat.c,cwe-125,4426 cwe-787,avcodec_align_dimensions2,"void avcodec_align_dimensions2(AVCodecContext *s, int *width, int *height, int linesize_align[AV_NUM_DATA_POINTERS]) { int i; int w_align = 1; int h_align = 1; AVPixFmtDescriptor const *desc = av_pix_fmt_desc_get(s->pix_fmt); if (desc) { w_align = 1 << desc->log2_chroma_w; h_align = 1 << desc->log2_chroma_h; } switch (s->pix_fmt) { case AV_PIX_FMT_YUV420P: case AV_PIX_FMT_YUYV422: case AV_PIX_FMT_YVYU422: case AV_PIX_FMT_UYVY422: case AV_PIX_FMT_YUV422P: case AV_PIX_FMT_YUV440P: case AV_PIX_FMT_YUV444P: case AV_PIX_FMT_GBRP: case AV_PIX_FMT_GBRAP: case AV_PIX_FMT_GRAY8: case AV_PIX_FMT_GRAY16BE: case AV_PIX_FMT_GRAY16LE: case AV_PIX_FMT_YUVJ420P: case AV_PIX_FMT_YUVJ422P: case AV_PIX_FMT_YUVJ440P: case AV_PIX_FMT_YUVJ444P: case AV_PIX_FMT_YUVA420P: case AV_PIX_FMT_YUVA422P: case AV_PIX_FMT_YUVA444P: case AV_PIX_FMT_YUV420P9LE: case AV_PIX_FMT_YUV420P9BE: case AV_PIX_FMT_YUV420P10LE: case AV_PIX_FMT_YUV420P10BE: case AV_PIX_FMT_YUV420P12LE: case AV_PIX_FMT_YUV420P12BE: case AV_PIX_FMT_YUV420P14LE: case AV_PIX_FMT_YUV420P14BE: case AV_PIX_FMT_YUV420P16LE: case AV_PIX_FMT_YUV420P16BE: case AV_PIX_FMT_YUVA420P9LE: case AV_PIX_FMT_YUVA420P9BE: case AV_PIX_FMT_YUVA420P10LE: case AV_PIX_FMT_YUVA420P10BE: case AV_PIX_FMT_YUVA420P16LE: case AV_PIX_FMT_YUVA420P16BE: case AV_PIX_FMT_YUV422P9LE: case AV_PIX_FMT_YUV422P9BE: case AV_PIX_FMT_YUV422P10LE: case AV_PIX_FMT_YUV422P10BE: case AV_PIX_FMT_YUV422P12LE: case AV_PIX_FMT_YUV422P12BE: case AV_PIX_FMT_YUV422P14LE: case AV_PIX_FMT_YUV422P14BE: case AV_PIX_FMT_YUV422P16LE: case AV_PIX_FMT_YUV422P16BE: case AV_PIX_FMT_YUVA422P9LE: case AV_PIX_FMT_YUVA422P9BE: case AV_PIX_FMT_YUVA422P10LE: case AV_PIX_FMT_YUVA422P10BE: case AV_PIX_FMT_YUVA422P16LE: case AV_PIX_FMT_YUVA422P16BE: case AV_PIX_FMT_YUV440P10LE: case AV_PIX_FMT_YUV440P10BE: case AV_PIX_FMT_YUV440P12LE: case AV_PIX_FMT_YUV440P12BE: case AV_PIX_FMT_YUV444P9LE: case AV_PIX_FMT_YUV444P9BE: case AV_PIX_FMT_YUV444P10LE: case AV_PIX_FMT_YUV444P10BE: case AV_PIX_FMT_YUV444P12LE: case AV_PIX_FMT_YUV444P12BE: case AV_PIX_FMT_YUV444P14LE: case AV_PIX_FMT_YUV444P14BE: case AV_PIX_FMT_YUV444P16LE: case AV_PIX_FMT_YUV444P16BE: case AV_PIX_FMT_YUVA444P9LE: case AV_PIX_FMT_YUVA444P9BE: case AV_PIX_FMT_YUVA444P10LE: case AV_PIX_FMT_YUVA444P10BE: case AV_PIX_FMT_YUVA444P16LE: case AV_PIX_FMT_YUVA444P16BE: case AV_PIX_FMT_GBRP9LE: case AV_PIX_FMT_GBRP9BE: case AV_PIX_FMT_GBRP10LE: case AV_PIX_FMT_GBRP10BE: case AV_PIX_FMT_GBRP12LE: case AV_PIX_FMT_GBRP12BE: case AV_PIX_FMT_GBRP14LE: case AV_PIX_FMT_GBRP14BE: case AV_PIX_FMT_GBRP16LE: case AV_PIX_FMT_GBRP16BE: case AV_PIX_FMT_GBRAP12LE: case AV_PIX_FMT_GBRAP12BE: case AV_PIX_FMT_GBRAP16LE: case AV_PIX_FMT_GBRAP16BE: w_align = 16; //FIXME assume 16 pixel per macroblock h_align = 16 * 2; // interlaced needs 2 macroblocks height break; case AV_PIX_FMT_YUV411P: case AV_PIX_FMT_YUVJ411P: case AV_PIX_FMT_UYYVYY411: w_align = 32; h_align = 16 * 2; break; case AV_PIX_FMT_YUV410P: if (s->codec_id == AV_CODEC_ID_SVQ1) { w_align = 64; h_align = 64; } break; case AV_PIX_FMT_RGB555: if (s->codec_id == AV_CODEC_ID_RPZA) { w_align = 4; h_align = 4; } break; case AV_PIX_FMT_PAL8: case AV_PIX_FMT_BGR8: case AV_PIX_FMT_RGB8: if (s->codec_id == AV_CODEC_ID_SMC || s->codec_id == AV_CODEC_ID_CINEPAK) { w_align = 4; h_align = 4; } if (s->codec_id == AV_CODEC_ID_JV) { w_align = 8; h_align = 8; } break; case AV_PIX_FMT_BGR24: if ((s->codec_id == AV_CODEC_ID_MSZH) || (s->codec_id == AV_CODEC_ID_ZLIB)) { w_align = 4; h_align = 4; } break; case AV_PIX_FMT_RGB24: if (s->codec_id == AV_CODEC_ID_CINEPAK) { w_align = 4; h_align = 4; } break; default: break; } if (s->codec_id == AV_CODEC_ID_IFF_ILBM) { w_align = FFMAX(w_align, 8); } *width = FFALIGN(*width, w_align); *height = FFALIGN(*height, h_align); if (s->codec_id == AV_CODEC_ID_H264 || s->lowres) { // some of the optimized chroma MC reads one line too much // which is also done in mpeg decoders with lowres > 0 *height += 2; // H.264 uses edge emulation for out of frame motion vectors, for this // it requires a temporary area large enough to hold a 21x21 block, // increasing witdth ensure that the temporary area is large enough, // the next rounded up width is 32 *width = FFMAX(*width, 32); } for (i = 0; i < 4; i++) linesize_align[i] = STRIDE_ALIGN; }","void avcodec_align_dimensions2(AVCodecContext *s, int *width, int *height, int linesize_align[AV_NUM_DATA_POINTERS]) { int i; int w_align = 1; int h_align = 1; AVPixFmtDescriptor const *desc = av_pix_fmt_desc_get(s->pix_fmt); if (desc) { w_align = 1 << desc->log2_chroma_w; h_align = 1 << desc->log2_chroma_h; } switch (s->pix_fmt) { case AV_PIX_FMT_YUV420P: case AV_PIX_FMT_YUYV422: case AV_PIX_FMT_YVYU422: case AV_PIX_FMT_UYVY422: case AV_PIX_FMT_YUV422P: case AV_PIX_FMT_YUV440P: case AV_PIX_FMT_YUV444P: case AV_PIX_FMT_GBRP: case AV_PIX_FMT_GBRAP: case AV_PIX_FMT_GRAY8: case AV_PIX_FMT_GRAY16BE: case AV_PIX_FMT_GRAY16LE: case AV_PIX_FMT_YUVJ420P: case AV_PIX_FMT_YUVJ422P: case AV_PIX_FMT_YUVJ440P: case AV_PIX_FMT_YUVJ444P: case AV_PIX_FMT_YUVA420P: case AV_PIX_FMT_YUVA422P: case AV_PIX_FMT_YUVA444P: case AV_PIX_FMT_YUV420P9LE: case AV_PIX_FMT_YUV420P9BE: case AV_PIX_FMT_YUV420P10LE: case AV_PIX_FMT_YUV420P10BE: case AV_PIX_FMT_YUV420P12LE: case AV_PIX_FMT_YUV420P12BE: case AV_PIX_FMT_YUV420P14LE: case AV_PIX_FMT_YUV420P14BE: case AV_PIX_FMT_YUV420P16LE: case AV_PIX_FMT_YUV420P16BE: case AV_PIX_FMT_YUVA420P9LE: case AV_PIX_FMT_YUVA420P9BE: case AV_PIX_FMT_YUVA420P10LE: case AV_PIX_FMT_YUVA420P10BE: case AV_PIX_FMT_YUVA420P16LE: case AV_PIX_FMT_YUVA420P16BE: case AV_PIX_FMT_YUV422P9LE: case AV_PIX_FMT_YUV422P9BE: case AV_PIX_FMT_YUV422P10LE: case AV_PIX_FMT_YUV422P10BE: case AV_PIX_FMT_YUV422P12LE: case AV_PIX_FMT_YUV422P12BE: case AV_PIX_FMT_YUV422P14LE: case AV_PIX_FMT_YUV422P14BE: case AV_PIX_FMT_YUV422P16LE: case AV_PIX_FMT_YUV422P16BE: case AV_PIX_FMT_YUVA422P9LE: case AV_PIX_FMT_YUVA422P9BE: case AV_PIX_FMT_YUVA422P10LE: case AV_PIX_FMT_YUVA422P10BE: case AV_PIX_FMT_YUVA422P16LE: case AV_PIX_FMT_YUVA422P16BE: case AV_PIX_FMT_YUV440P10LE: case AV_PIX_FMT_YUV440P10BE: case AV_PIX_FMT_YUV440P12LE: case AV_PIX_FMT_YUV440P12BE: case AV_PIX_FMT_YUV444P9LE: case AV_PIX_FMT_YUV444P9BE: case AV_PIX_FMT_YUV444P10LE: case AV_PIX_FMT_YUV444P10BE: case AV_PIX_FMT_YUV444P12LE: case AV_PIX_FMT_YUV444P12BE: case AV_PIX_FMT_YUV444P14LE: case AV_PIX_FMT_YUV444P14BE: case AV_PIX_FMT_YUV444P16LE: case AV_PIX_FMT_YUV444P16BE: case AV_PIX_FMT_YUVA444P9LE: case AV_PIX_FMT_YUVA444P9BE: case AV_PIX_FMT_YUVA444P10LE: case AV_PIX_FMT_YUVA444P10BE: case AV_PIX_FMT_YUVA444P16LE: case AV_PIX_FMT_YUVA444P16BE: case AV_PIX_FMT_GBRP9LE: case AV_PIX_FMT_GBRP9BE: case AV_PIX_FMT_GBRP10LE: case AV_PIX_FMT_GBRP10BE: case AV_PIX_FMT_GBRP12LE: case AV_PIX_FMT_GBRP12BE: case AV_PIX_FMT_GBRP14LE: case AV_PIX_FMT_GBRP14BE: case AV_PIX_FMT_GBRP16LE: case AV_PIX_FMT_GBRP16BE: case AV_PIX_FMT_GBRAP12LE: case AV_PIX_FMT_GBRAP12BE: case AV_PIX_FMT_GBRAP16LE: case AV_PIX_FMT_GBRAP16BE: w_align = 16; //FIXME assume 16 pixel per macroblock h_align = 16 * 2; // interlaced needs 2 macroblocks height break; case AV_PIX_FMT_YUV411P: case AV_PIX_FMT_YUVJ411P: case AV_PIX_FMT_UYYVYY411: w_align = 32; h_align = 16 * 2; break; case AV_PIX_FMT_YUV410P: if (s->codec_id == AV_CODEC_ID_SVQ1) { w_align = 64; h_align = 64; } break; case AV_PIX_FMT_RGB555: if (s->codec_id == AV_CODEC_ID_RPZA) { w_align = 4; h_align = 4; } if (s->codec_id == AV_CODEC_ID_INTERPLAY_VIDEO) { w_align = 8; h_align = 8; } break; case AV_PIX_FMT_PAL8: case AV_PIX_FMT_BGR8: case AV_PIX_FMT_RGB8: if (s->codec_id == AV_CODEC_ID_SMC || s->codec_id == AV_CODEC_ID_CINEPAK) { w_align = 4; h_align = 4; } if (s->codec_id == AV_CODEC_ID_JV || s->codec_id == AV_CODEC_ID_INTERPLAY_VIDEO) { w_align = 8; h_align = 8; } break; case AV_PIX_FMT_BGR24: if ((s->codec_id == AV_CODEC_ID_MSZH) || (s->codec_id == AV_CODEC_ID_ZLIB)) { w_align = 4; h_align = 4; } break; case AV_PIX_FMT_RGB24: if (s->codec_id == AV_CODEC_ID_CINEPAK) { w_align = 4; h_align = 4; } break; default: break; } if (s->codec_id == AV_CODEC_ID_IFF_ILBM) { w_align = FFMAX(w_align, 8); } *width = FFALIGN(*width, w_align); *height = FFALIGN(*height, h_align); if (s->codec_id == AV_CODEC_ID_H264 || s->lowres) { // some of the optimized chroma MC reads one line too much // which is also done in mpeg decoders with lowres > 0 *height += 2; // H.264 uses edge emulation for out of frame motion vectors, for this // it requires a temporary area large enough to hold a 21x21 block, // increasing witdth ensure that the temporary area is large enough, // the next rounded up width is 32 *width = FFMAX(*width, 32); } for (i = 0; i < 4; i++) linesize_align[i] = STRIDE_ALIGN; }","{'deleted': [{'line_no': 129, 'char_start': 3941, 'char_end': 3986, 'line': ' if (s->codec_id == AV_CODEC_ID_JV) {\n'}], 'added': [{'line_no': 120, 'char_start': 3692, 'char_end': 3750, 'line': ' if (s->codec_id == AV_CODEC_ID_INTERPLAY_VIDEO) {\n'}, {'line_no': 121, 'char_start': 3750, 'char_end': 3775, 'line': ' w_align = 8;\n'}, {'line_no': 122, 'char_start': 3775, 'char_end': 3800, 'line': ' h_align = 8;\n'}, {'line_no': 123, 'char_start': 3800, 'char_end': 3810, 'line': ' }\n'}, {'line_no': 133, 'char_start': 4059, 'char_end': 4104, 'line': ' if (s->codec_id == AV_CODEC_ID_JV ||\n'}, {'line_no': 134, 'char_start': 4104, 'char_end': 4162, 'line': ' s->codec_id == AV_CODEC_ID_INTERPLAY_VIDEO) {\n'}]}","{'deleted': [], 'added': [{'char_start': 3700, 'char_end': 3818, 'chars': 'if (s->codec_id == AV_CODEC_ID_INTERPLAY_VIDEO) {\n w_align = 8;\n h_align = 8;\n }\n '}, {'char_start': 4100, 'char_end': 4158, 'chars': ' ||\n s->codec_id == AV_CODEC_ID_INTERPLAY_VIDEO'}]}",github.com/FFmpeg/FFmpeg/commit/2080bc33717955a0e4268e738acf8c1eeddbf8cb,libavcodec/utils.c,cwe-787,1890 cwe-089,delete," @jwt_required def delete(self, email): """""" Deletes admin with the corresponding email """""" return database_utilities.execute_query(f""""""delete from admins where email = '{email}'"""""")"," @jwt_required def delete(self, email): """""" Deletes admin with the corresponding email """""" return database_utilities.execute_query(f""""""delete from admins where email = %s"""""", (email, ))","{'deleted': [{'line_no': 4, 'char_start': 106, 'char_end': 204, 'line': ' return database_utilities.execute_query(f""""""delete from admins where email = \'{email}\'"""""")\n'}], 'added': [{'line_no': 4, 'char_start': 106, 'char_end': 208, 'line': ' return database_utilities.execute_query(f""""""delete from admins where email = %s"""""", (email, ))'}]}","{'deleted': [{'char_start': 191, 'char_end': 193, 'chars': ""'{""}, {'char_start': 198, 'char_end': 203, 'chars': '}\'""""""'}], 'added': [{'char_start': 191, 'char_end': 199, 'chars': '%s"""""", ('}, {'char_start': 204, 'char_end': 207, 'chars': ', )'}]}",github.com/sgosal2/tiger-boards-backend/commit/4670109dd613df2f2fe7e8403ebd149df2b55485,apis/admins.py,cwe-089,40 cwe-125,X86_insn_reg_intel,"x86_reg X86_insn_reg_intel(unsigned int id, enum cs_ac_type *access) { unsigned int first = 0; unsigned int last = ARR_SIZE(insn_regs_intel) - 1; unsigned int mid = ARR_SIZE(insn_regs_intel) / 2; if (!intel_regs_sorted) { memcpy(insn_regs_intel_sorted, insn_regs_intel, sizeof(insn_regs_intel_sorted)); qsort(insn_regs_intel_sorted, ARR_SIZE(insn_regs_intel_sorted), sizeof(struct insn_reg), regs_cmp); intel_regs_sorted = true; } while (first <= last) { if (insn_regs_intel_sorted[mid].insn < id) { first = mid + 1; } else if (insn_regs_intel_sorted[mid].insn == id) { if (access) { *access = insn_regs_intel_sorted[mid].access; } return insn_regs_intel_sorted[mid].reg; } else { if (mid == 0) break; last = mid - 1; } mid = (first + last) / 2; } // not found return 0; }","x86_reg X86_insn_reg_intel(unsigned int id, enum cs_ac_type *access) { static bool intel_regs_sorted = false; unsigned int first = 0; unsigned int last = ARR_SIZE(insn_regs_intel) - 1; unsigned int mid; if (!intel_regs_sorted) { memcpy(insn_regs_intel_sorted, insn_regs_intel, sizeof(insn_regs_intel_sorted)); qsort(insn_regs_intel_sorted, ARR_SIZE(insn_regs_intel_sorted), sizeof(struct insn_reg), regs_cmp); intel_regs_sorted = true; } if (insn_regs_intel_sorted[0].insn > id || insn_regs_intel_sorted[last].insn < id) { return 0; } while (first <= last) { mid = (first + last) / 2; if (insn_regs_intel_sorted[mid].insn < id) { first = mid + 1; } else if (insn_regs_intel_sorted[mid].insn == id) { if (access) { *access = insn_regs_intel_sorted[mid].access; } return insn_regs_intel_sorted[mid].reg; } else { if (mid == 0) break; last = mid - 1; } } // not found return 0; }","{'deleted': [{'line_no': 5, 'char_start': 148, 'char_end': 199, 'line': '\tunsigned int mid = ARR_SIZE(insn_regs_intel) / 2;\n'}, {'line_no': 29, 'char_start': 780, 'char_end': 808, 'line': '\t\tmid = (first + last) / 2;\n'}], 'added': [{'line_no': 3, 'char_start': 71, 'char_end': 111, 'line': '\tstatic bool intel_regs_sorted = false;\n'}, {'line_no': 6, 'char_start': 188, 'char_end': 207, 'line': '\tunsigned int mid;\n'}, {'line_no': 17, 'char_start': 464, 'char_end': 508, 'line': '\tif (insn_regs_intel_sorted[0].insn > id ||\n'}, {'line_no': 18, 'char_start': 508, 'char_end': 553, 'line': '\t\t\tinsn_regs_intel_sorted[last].insn < id) {\n'}, {'line_no': 19, 'char_start': 553, 'char_end': 565, 'line': '\t\treturn 0;\n'}, {'line_no': 20, 'char_start': 565, 'char_end': 568, 'line': '\t}\n'}, {'line_no': 21, 'char_start': 568, 'char_end': 569, 'line': '\n'}, {'line_no': 23, 'char_start': 594, 'char_end': 622, 'line': '\t\tmid = (first + last) / 2;\n'}]}","{'deleted': [{'char_start': 165, 'char_end': 197, 'chars': ' = ARR_SIZE(insn_regs_intel) / 2'}, {'char_start': 779, 'char_end': 807, 'chars': '\n\t\tmid = (first + last) / 2;'}], 'added': [{'char_start': 72, 'char_end': 112, 'chars': 'static bool intel_regs_sorted = false;\n\t'}, {'char_start': 465, 'char_end': 570, 'chars': 'if (insn_regs_intel_sorted[0].insn > id ||\n\t\t\tinsn_regs_intel_sorted[last].insn < id) {\n\t\treturn 0;\n\t}\n\n\t'}, {'char_start': 593, 'char_end': 621, 'chars': '\n\t\tmid = (first + last) / 2;'}]}",github.com/aquynh/capstone/commit/87a25bb543c8e4c09b48d4b4a6c7db31ce58df06,arch/X86/X86Mapping.c,cwe-125,266 cwe-190,AllocateDataSet,"void AllocateDataSet(cmsIT8* it8) { TABLE* t = GetTable(it8); if (t -> Data) return; // Already allocated t-> nSamples = atoi(cmsIT8GetProperty(it8, ""NUMBER_OF_FIELDS"")); t-> nPatches = atoi(cmsIT8GetProperty(it8, ""NUMBER_OF_SETS"")); t-> Data = (char**)AllocChunk (it8, ((cmsUInt32Number) t->nSamples + 1) * ((cmsUInt32Number) t->nPatches + 1) *sizeof (char*)); if (t->Data == NULL) { SynError(it8, ""AllocateDataSet: Unable to allocate data array""); } }","void AllocateDataSet(cmsIT8* it8) { TABLE* t = GetTable(it8); if (t -> Data) return; // Already allocated t-> nSamples = atoi(cmsIT8GetProperty(it8, ""NUMBER_OF_FIELDS"")); t-> nPatches = atoi(cmsIT8GetProperty(it8, ""NUMBER_OF_SETS"")); if (t -> nSamples < 0 || t->nSamples > 0x7ffe || t->nPatches < 0 || t->nPatches > 0x7ffe) { SynError(it8, ""AllocateDataSet: too much data""); } else { t->Data = (char**)AllocChunk(it8, ((cmsUInt32Number)t->nSamples + 1) * ((cmsUInt32Number)t->nPatches + 1) * sizeof(char*)); if (t->Data == NULL) { SynError(it8, ""AllocateDataSet: Unable to allocate data array""); } } }","{'deleted': [{'line_no': 10, 'char_start': 260, 'char_end': 392, 'line': ' t-> Data = (char**)AllocChunk (it8, ((cmsUInt32Number) t->nSamples + 1) * ((cmsUInt32Number) t->nPatches + 1) *sizeof (char*));\n'}, {'line_no': 11, 'char_start': 392, 'char_end': 419, 'line': ' if (t->Data == NULL) {\n'}, {'line_no': 13, 'char_start': 420, 'char_end': 493, 'line': ' SynError(it8, ""AllocateDataSet: Unable to allocate data array"");\n'}], 'added': [{'line_no': 10, 'char_start': 260, 'char_end': 354, 'line': ' if (t -> nSamples < 0 || t->nSamples > 0x7ffe || t->nPatches < 0 || t->nPatches > 0x7ffe)\n'}, {'line_no': 11, 'char_start': 354, 'char_end': 360, 'line': ' {\n'}, {'line_no': 12, 'char_start': 360, 'char_end': 417, 'line': ' SynError(it8, ""AllocateDataSet: too much data"");\n'}, {'line_no': 13, 'char_start': 417, 'char_end': 423, 'line': ' }\n'}, {'line_no': 14, 'char_start': 423, 'char_end': 434, 'line': ' else {\n'}, {'line_no': 15, 'char_start': 434, 'char_end': 566, 'line': ' t->Data = (char**)AllocChunk(it8, ((cmsUInt32Number)t->nSamples + 1) * ((cmsUInt32Number)t->nPatches + 1) * sizeof(char*));\n'}, {'line_no': 16, 'char_start': 566, 'char_end': 597, 'line': ' if (t->Data == NULL) {\n'}, {'line_no': 18, 'char_start': 598, 'char_end': 675, 'line': ' SynError(it8, ""AllocateDataSet: Unable to allocate data array"");\n'}, {'line_no': 19, 'char_start': 675, 'char_end': 685, 'line': ' }\n'}]}","{'deleted': [{'char_start': 293, 'char_end': 294, 'chars': ' '}, {'char_start': 318, 'char_end': 319, 'chars': ' '}, {'char_start': 356, 'char_end': 357, 'chars': ' '}, {'char_start': 381, 'char_end': 382, 'chars': ' '}], 'added': [{'char_start': 264, 'char_end': 289, 'chars': 'if (t -> nSamples < 0 || '}, {'char_start': 292, 'char_end': 367, 'chars': 'nSamples > 0x7ffe || t->nPatches < 0 || t->nPatches > 0x7ffe)\n {\n '}, {'char_start': 368, 'char_end': 445, 'chars': 'SynError(it8, ""AllocateDataSet: too much data"");\n }\n else {\n t->'}, {'char_start': 549, 'char_end': 550, 'chars': ' '}, {'char_start': 570, 'char_end': 574, 'chars': ' '}, {'char_start': 598, 'char_end': 600, 'chars': ' '}, {'char_start': 608, 'char_end': 610, 'chars': ' '}, {'char_start': 674, 'char_end': 684, 'chars': '\n }'}]}",github.com/mm2/Little-CMS/commit/768f70ca405cd3159d990e962d54456773bb8cf8,src/cmscgats.c,cwe-190,160 cwe-125,WriteImageChannels,"static MagickBooleanType WriteImageChannels(const PSDInfo *psd_info, const ImageInfo *image_info,Image *image,Image *next_image, const MagickBooleanType separate,ExceptionInfo *exception) { size_t channels, packet_size; unsigned char *compact_pixels; /* Write uncompressed pixels as separate planes. */ channels=1; packet_size=next_image->depth > 8UL ? 2UL : 1UL; compact_pixels=(unsigned char *) NULL; if (next_image->compression == RLECompression) { compact_pixels=(unsigned char *) AcquireQuantumMemory(2*channels* next_image->columns,packet_size*sizeof(*compact_pixels)); if (compact_pixels == (unsigned char *) NULL) ThrowWriterException(ResourceLimitError,""MemoryAllocationFailed""); } if (IsImageGray(next_image) != MagickFalse) { if (next_image->compression == RLECompression) { /* Packbits compression. */ (void) WriteBlobMSBShort(image,1); WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,GrayQuantum,exception); if (next_image->alpha_trait != UndefinedPixelTrait) WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,AlphaQuantum,exception); } WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, GrayQuantum,MagickTrue,exception); if (next_image->alpha_trait != UndefinedPixelTrait) WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, AlphaQuantum,separate,exception); (void) SetImageProgress(image,SaveImagesTag,0,1); } else if (next_image->storage_class == PseudoClass) { if (next_image->compression == RLECompression) { /* Packbits compression. */ (void) WriteBlobMSBShort(image,1); WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,IndexQuantum,exception); if (next_image->alpha_trait != UndefinedPixelTrait) WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,AlphaQuantum,exception); } WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, IndexQuantum,MagickTrue,exception); if (next_image->alpha_trait != UndefinedPixelTrait) WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, AlphaQuantum,separate,exception); (void) SetImageProgress(image,SaveImagesTag,0,1); } else { if (next_image->colorspace == CMYKColorspace) (void) NegateCMYK(next_image,exception); if (next_image->compression == RLECompression) { /* Packbits compression. */ (void) WriteBlobMSBShort(image,1); WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,RedQuantum,exception); WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,GreenQuantum,exception); WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,BlueQuantum,exception); if (next_image->colorspace == CMYKColorspace) WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,BlackQuantum,exception); if (next_image->alpha_trait != UndefinedPixelTrait) WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,AlphaQuantum,exception); } (void) SetImageProgress(image,SaveImagesTag,0,6); WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, RedQuantum,MagickTrue,exception); (void) SetImageProgress(image,SaveImagesTag,1,6); WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, GreenQuantum,separate,exception); (void) SetImageProgress(image,SaveImagesTag,2,6); WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, BlueQuantum,separate,exception); (void) SetImageProgress(image,SaveImagesTag,3,6); if (next_image->colorspace == CMYKColorspace) WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, BlackQuantum,separate,exception); (void) SetImageProgress(image,SaveImagesTag,4,6); if (next_image->alpha_trait != UndefinedPixelTrait) WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, AlphaQuantum,separate,exception); (void) SetImageProgress(image,SaveImagesTag,5,6); if (next_image->colorspace == CMYKColorspace) (void) NegateCMYK(next_image,exception); } if (next_image->compression == RLECompression) compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); return(MagickTrue); }","static MagickBooleanType WriteImageChannels(const PSDInfo *psd_info, const ImageInfo *image_info,Image *image,Image *next_image, const MagickBooleanType separate,ExceptionInfo *exception) { size_t channels, packet_size; unsigned char *compact_pixels; /* Write uncompressed pixels as separate planes. */ channels=1; packet_size=next_image->depth > 8UL ? 2UL : 1UL; compact_pixels=(unsigned char *) NULL; if (next_image->compression == RLECompression) { compact_pixels=(unsigned char *) AcquireQuantumMemory((2*channels* next_image->columns)+1,packet_size*sizeof(*compact_pixels)); if (compact_pixels == (unsigned char *) NULL) ThrowWriterException(ResourceLimitError,""MemoryAllocationFailed""); } if (IsImageGray(next_image) != MagickFalse) { if (next_image->compression == RLECompression) { /* Packbits compression. */ (void) WriteBlobMSBShort(image,1); WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,GrayQuantum,exception); if (next_image->alpha_trait != UndefinedPixelTrait) WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,AlphaQuantum,exception); } WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, GrayQuantum,MagickTrue,exception); if (next_image->alpha_trait != UndefinedPixelTrait) WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, AlphaQuantum,separate,exception); (void) SetImageProgress(image,SaveImagesTag,0,1); } else if (next_image->storage_class == PseudoClass) { if (next_image->compression == RLECompression) { /* Packbits compression. */ (void) WriteBlobMSBShort(image,1); WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,IndexQuantum,exception); if (next_image->alpha_trait != UndefinedPixelTrait) WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,AlphaQuantum,exception); } WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, IndexQuantum,MagickTrue,exception); if (next_image->alpha_trait != UndefinedPixelTrait) WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, AlphaQuantum,separate,exception); (void) SetImageProgress(image,SaveImagesTag,0,1); } else { if (next_image->colorspace == CMYKColorspace) (void) NegateCMYK(next_image,exception); if (next_image->compression == RLECompression) { /* Packbits compression. */ (void) WriteBlobMSBShort(image,1); WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,RedQuantum,exception); WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,GreenQuantum,exception); WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,BlueQuantum,exception); if (next_image->colorspace == CMYKColorspace) WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,BlackQuantum,exception); if (next_image->alpha_trait != UndefinedPixelTrait) WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,AlphaQuantum,exception); } (void) SetImageProgress(image,SaveImagesTag,0,6); WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, RedQuantum,MagickTrue,exception); (void) SetImageProgress(image,SaveImagesTag,1,6); WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, GreenQuantum,separate,exception); (void) SetImageProgress(image,SaveImagesTag,2,6); WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, BlueQuantum,separate,exception); (void) SetImageProgress(image,SaveImagesTag,3,6); if (next_image->colorspace == CMYKColorspace) WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, BlackQuantum,separate,exception); (void) SetImageProgress(image,SaveImagesTag,4,6); if (next_image->alpha_trait != UndefinedPixelTrait) WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, AlphaQuantum,separate,exception); (void) SetImageProgress(image,SaveImagesTag,5,6); if (next_image->colorspace == CMYKColorspace) (void) NegateCMYK(next_image,exception); } if (next_image->compression == RLECompression) compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); return(MagickTrue); }","{'deleted': [{'line_no': 20, 'char_start': 494, 'char_end': 566, 'line': ' compact_pixels=(unsigned char *) AcquireQuantumMemory(2*channels*\n'}, {'line_no': 21, 'char_start': 566, 'char_end': 632, 'line': ' next_image->columns,packet_size*sizeof(*compact_pixels));\n'}], 'added': [{'line_no': 20, 'char_start': 494, 'char_end': 567, 'line': ' compact_pixels=(unsigned char *) AcquireQuantumMemory((2*channels*\n'}, {'line_no': 21, 'char_start': 567, 'char_end': 636, 'line': ' next_image->columns)+1,packet_size*sizeof(*compact_pixels));\n'}]}","{'deleted': [], 'added': [{'char_start': 554, 'char_end': 555, 'chars': '('}, {'char_start': 594, 'char_end': 597, 'chars': ')+1'}]}",github.com/ImageMagick/ImageMagick/commit/6f1879d498bcc5cce12fe0c5decb8dbc0f608e5d,coders/psd.c,cwe-125,1131 cwe-416,mif_process_cmpt,"static int mif_process_cmpt(mif_hdr_t *hdr, char *buf) { jas_tvparser_t *tvp; mif_cmpt_t *cmpt; int id; cmpt = 0; tvp = 0; if (!(cmpt = mif_cmpt_create())) { goto error; } cmpt->tlx = 0; cmpt->tly = 0; cmpt->sampperx = 0; cmpt->samppery = 0; cmpt->width = 0; cmpt->height = 0; cmpt->prec = 0; cmpt->sgnd = -1; cmpt->data = 0; if (!(tvp = jas_tvparser_create(buf))) { goto error; } while (!(id = jas_tvparser_next(tvp))) { switch (jas_taginfo_nonull(jas_taginfos_lookup(mif_tags, jas_tvparser_gettag(tvp)))->id) { case MIF_TLX: cmpt->tlx = atoi(jas_tvparser_getval(tvp)); break; case MIF_TLY: cmpt->tly = atoi(jas_tvparser_getval(tvp)); break; case MIF_WIDTH: cmpt->width = atoi(jas_tvparser_getval(tvp)); break; case MIF_HEIGHT: cmpt->height = atoi(jas_tvparser_getval(tvp)); break; case MIF_HSAMP: cmpt->sampperx = atoi(jas_tvparser_getval(tvp)); break; case MIF_VSAMP: cmpt->samppery = atoi(jas_tvparser_getval(tvp)); break; case MIF_PREC: cmpt->prec = atoi(jas_tvparser_getval(tvp)); break; case MIF_SGND: cmpt->sgnd = atoi(jas_tvparser_getval(tvp)); break; case MIF_DATA: if (!(cmpt->data = jas_strdup(jas_tvparser_getval(tvp)))) { return -1; } break; } } jas_tvparser_destroy(tvp); if (!cmpt->sampperx || !cmpt->samppery) { goto error; } if (mif_hdr_addcmpt(hdr, hdr->numcmpts, cmpt)) { goto error; } return 0; error: if (cmpt) { mif_cmpt_destroy(cmpt); } if (tvp) { jas_tvparser_destroy(tvp); } return -1; }","static int mif_process_cmpt(mif_hdr_t *hdr, char *buf) { jas_tvparser_t *tvp; mif_cmpt_t *cmpt; int id; cmpt = 0; tvp = 0; if (!(cmpt = mif_cmpt_create())) { goto error; } cmpt->tlx = 0; cmpt->tly = 0; cmpt->sampperx = 0; cmpt->samppery = 0; cmpt->width = 0; cmpt->height = 0; cmpt->prec = 0; cmpt->sgnd = -1; cmpt->data = 0; if (!(tvp = jas_tvparser_create(buf))) { goto error; } while (!(id = jas_tvparser_next(tvp))) { switch (jas_taginfo_nonull(jas_taginfos_lookup(mif_tags, jas_tvparser_gettag(tvp)))->id) { case MIF_TLX: cmpt->tlx = atoi(jas_tvparser_getval(tvp)); break; case MIF_TLY: cmpt->tly = atoi(jas_tvparser_getval(tvp)); break; case MIF_WIDTH: cmpt->width = atoi(jas_tvparser_getval(tvp)); break; case MIF_HEIGHT: cmpt->height = atoi(jas_tvparser_getval(tvp)); break; case MIF_HSAMP: cmpt->sampperx = atoi(jas_tvparser_getval(tvp)); break; case MIF_VSAMP: cmpt->samppery = atoi(jas_tvparser_getval(tvp)); break; case MIF_PREC: cmpt->prec = atoi(jas_tvparser_getval(tvp)); break; case MIF_SGND: cmpt->sgnd = atoi(jas_tvparser_getval(tvp)); break; case MIF_DATA: if (!(cmpt->data = jas_strdup(jas_tvparser_getval(tvp)))) { return -1; } break; } } if (!cmpt->sampperx || !cmpt->samppery) { goto error; } if (mif_hdr_addcmpt(hdr, hdr->numcmpts, cmpt)) { goto error; } jas_tvparser_destroy(tvp); return 0; error: if (cmpt) { mif_cmpt_destroy(cmpt); } if (tvp) { jas_tvparser_destroy(tvp); } return -1; }","{'deleted': [{'line_no': 60, 'char_start': 1274, 'char_end': 1302, 'line': '\tjas_tvparser_destroy(tvp);\n'}], 'added': [{'line_no': 66, 'char_start': 1401, 'char_end': 1429, 'line': '\tjas_tvparser_destroy(tvp);\n'}]}","{'deleted': [{'char_start': 1275, 'char_end': 1303, 'chars': 'jas_tvparser_destroy(tvp);\n\t'}], 'added': [{'char_start': 1400, 'char_end': 1428, 'chars': '\n\tjas_tvparser_destroy(tvp);'}]}",github.com/mdadams/jasper/commit/df5d2867e8004e51e18b89865bc4aa69229227b3,src/libjasper/mif/mif_cod.c,cwe-416,574 cwe-022,wiki_handle_http_request,"wiki_handle_http_request(HttpRequest *req) { HttpResponse *res = http_response_new(req); char *page = http_request_get_path_info(req); char *command = http_request_get_query_string(req); char *wikitext = """"; util_dehttpize(page); /* remove any encoding on the requested page name. */ if (!strcmp(page, ""/"")) { if (access(""WikiHome"", R_OK) != 0) wiki_redirect(res, ""/WikiHome?create""); page = ""/WikiHome""; } if (!strcmp(page, ""/styles.css"")) { /* Return CSS page */ http_response_set_content_type(res, ""text/css""); http_response_printf(res, ""%s"", CssData); http_response_send(res); exit(0); } if (!strcmp(page, ""/favicon.ico"")) { /* Return favicon */ http_response_set_content_type(res, ""image/ico""); http_response_set_data(res, FaviconData, FaviconDataLen); http_response_send(res); exit(0); } page = page + 1; /* skip slash */ if (!strncmp(page, ""api/"", 4)) { char *p; page += 4; for (p=page; *p != '\0'; p++) if (*p=='?') { *p ='\0'; break; } wiki_handle_rest_call(req, res, page); exit(0); } /* A little safety. issue a malformed request for any paths, * There shouldn't need to be any.. */ if (strchr(page, '/')) { http_response_set_status(res, 404, ""Not Found""); http_response_printf(res, ""404 Not Found\n""); http_response_send(res); exit(0); } if (!strcmp(page, ""Changes"")) { wiki_show_changes_page(res); } else if (!strcmp(page, ""ChangesRss"")) { wiki_show_changes_page_rss(res); } else if (!strcmp(page, ""Search"")) { wiki_show_search_results_page(res, http_request_param_get(req, ""expr"")); } else if (!strcmp(page, ""Create"")) { if ( (wikitext = http_request_param_get(req, ""title"")) != NULL) { /* create page and redirect */ wiki_redirect(res, http_request_param_get(req, ""title"")); } else { /* show create page form */ wiki_show_create_page(res); } } else { /* TODO: dont blindly write wikitext data to disk */ if ( (wikitext = http_request_param_get(req, ""wikitext"")) != NULL) { file_write(page, wikitext); } if (access(page, R_OK) == 0) /* page exists */ { wikitext = file_read(page); if (!strcmp(command, ""edit"")) { /* print edit page */ wiki_show_edit_page(res, wikitext, page); } else { wiki_show_page(res, wikitext, page); } } else { if (!strcmp(command, ""create"")) { wiki_show_edit_page(res, NULL, page); } else { char buf[1024]; snprintf(buf, 1024, ""%s?create"", page); wiki_redirect(res, buf); } } } }","wiki_handle_http_request(HttpRequest *req) { HttpResponse *res = http_response_new(req); char *page = http_request_get_path_info(req); char *command = http_request_get_query_string(req); char *wikitext = """"; util_dehttpize(page); /* remove any encoding on the requested page name. */ if (!strcmp(page, ""/"")) { if (access(""WikiHome"", R_OK) != 0) wiki_redirect(res, ""/WikiHome?create""); page = ""/WikiHome""; } if (!strcmp(page, ""/styles.css"")) { /* Return CSS page */ http_response_set_content_type(res, ""text/css""); http_response_printf(res, ""%s"", CssData); http_response_send(res); exit(0); } if (!strcmp(page, ""/favicon.ico"")) { /* Return favicon */ http_response_set_content_type(res, ""image/ico""); http_response_set_data(res, FaviconData, FaviconDataLen); http_response_send(res); exit(0); } page = page + 1; /* skip slash */ if (!strncmp(page, ""api/"", 4)) { char *p; page += 4; for (p=page; *p != '\0'; p++) if (*p=='?') { *p ='\0'; break; } wiki_handle_rest_call(req, res, page); exit(0); } /* A little safety. issue a malformed request for any paths, * There shouldn't need to be any.. */ if (!page_name_is_good(page)) { http_response_set_status(res, 404, ""Not Found""); http_response_printf(res, ""404 Not Found\n""); http_response_send(res); exit(0); } if (!strcmp(page, ""Changes"")) { wiki_show_changes_page(res); } else if (!strcmp(page, ""ChangesRss"")) { wiki_show_changes_page_rss(res); } else if (!strcmp(page, ""Search"")) { wiki_show_search_results_page(res, http_request_param_get(req, ""expr"")); } else if (!strcmp(page, ""Create"")) { if ( (wikitext = http_request_param_get(req, ""title"")) != NULL) { /* create page and redirect */ wiki_redirect(res, http_request_param_get(req, ""title"")); } else { /* show create page form */ wiki_show_create_page(res); } } else { /* TODO: dont blindly write wikitext data to disk */ if ( (wikitext = http_request_param_get(req, ""wikitext"")) != NULL) { file_write(page, wikitext); } if (access(page, R_OK) == 0) /* page exists */ { wikitext = file_read(page); if (!strcmp(command, ""edit"")) { /* print edit page */ wiki_show_edit_page(res, wikitext, page); } else { wiki_show_page(res, wikitext, page); } } else { if (!strcmp(command, ""create"")) { wiki_show_edit_page(res, NULL, page); } else { char buf[1024]; snprintf(buf, 1024, ""%s?create"", page); wiki_redirect(res, buf); } } } }","{'deleted': [{'line_no': 54, 'char_start': 1350, 'char_end': 1375, 'line': "" if (strchr(page, '/'))\n""}], 'added': [{'line_no': 54, 'char_start': 1350, 'char_end': 1382, 'line': ' if (!page_name_is_good(page))\n'}]}","{'deleted': [{'char_start': 1357, 'char_end': 1362, 'chars': 'trchr'}, {'char_start': 1367, 'char_end': 1372, 'chars': "", '/'""}], 'added': [{'char_start': 1356, 'char_end': 1368, 'chars': '!page_name_i'}, {'char_start': 1369, 'char_end': 1374, 'chars': '_good'}]}",github.com/yarolig/didiwiki/commit/5e5c796617e1712905dc5462b94bd5e6c08d15ea,src/wiki.c,cwe-022,795 cwe-416,ReadMATImage,"static Image *ReadMATImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *image, *image2=NULL, *rotated_image; register Quantum *q; unsigned int status; MATHeader MATLAB_HDR; size_t size; size_t CellType; QuantumInfo *quantum_info; ImageInfo *clone_info; int i; ssize_t ldblk; unsigned char *BImgBuff = NULL; double MinVal, MaxVal; unsigned z, z2; unsigned Frames; int logging; int sample_size; MagickOffsetType filepos=0x80; BlobInfo *blob; size_t one; unsigned int (*ReadBlobXXXLong)(Image *image); unsigned short (*ReadBlobXXXShort)(Image *image); void (*ReadBlobDoublesXXX)(Image * image, size_t len, double *data); void (*ReadBlobFloatsXXX)(Image * image, size_t len, float *data); assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); logging = LogMagickEvent(CoderEvent,GetMagickModule(),""enter""); /* Open image file. */ image = AcquireImage(image_info,exception); status = OpenBlob(image_info, image, ReadBinaryBlobMode, exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read MATLAB image. */ quantum_info=(QuantumInfo *) NULL; clone_info=(ImageInfo *) NULL; if (ReadBlob(image,124,(unsigned char *) &MATLAB_HDR.identific) != 124) ThrowReaderException(CorruptImageError,""ImproperImageHeader""); if (strncmp(MATLAB_HDR.identific,""MATLAB"",6) != 0) { image2=ReadMATImageV4(image_info,image,exception); if (image2 == NULL) goto MATLAB_KO; image=image2; goto END_OF_READING; } MATLAB_HDR.Version = ReadBlobLSBShort(image); if(ReadBlob(image,2,(unsigned char *) &MATLAB_HDR.EndianIndicator) != 2) ThrowReaderException(CorruptImageError,""ImproperImageHeader""); if (logging) (void) LogMagickEvent(CoderEvent,GetMagickModule(),"" Endian %c%c"", MATLAB_HDR.EndianIndicator[0],MATLAB_HDR.EndianIndicator[1]); if (!strncmp(MATLAB_HDR.EndianIndicator, ""IM"", 2)) { ReadBlobXXXLong = ReadBlobLSBLong; ReadBlobXXXShort = ReadBlobLSBShort; ReadBlobDoublesXXX = ReadBlobDoublesLSB; ReadBlobFloatsXXX = ReadBlobFloatsLSB; image->endian = LSBEndian; } else if (!strncmp(MATLAB_HDR.EndianIndicator, ""MI"", 2)) { ReadBlobXXXLong = ReadBlobMSBLong; ReadBlobXXXShort = ReadBlobMSBShort; ReadBlobDoublesXXX = ReadBlobDoublesMSB; ReadBlobFloatsXXX = ReadBlobFloatsMSB; image->endian = MSBEndian; } else goto MATLAB_KO; /* unsupported endian */ if (strncmp(MATLAB_HDR.identific, ""MATLAB"", 6)) { MATLAB_KO: if ((image != image2) && (image2 != (Image *) NULL)) image2=DestroyImage(image2); if (clone_info != (ImageInfo *) NULL) clone_info=DestroyImageInfo(clone_info); ThrowReaderException(CorruptImageError,""ImproperImageHeader""); } filepos = TellBlob(image); while(!EOFBlob(image)) /* object parser loop */ { Frames = 1; (void) SeekBlob(image,filepos,SEEK_SET); /* printf(""pos=%X\n"",TellBlob(image)); */ MATLAB_HDR.DataType = ReadBlobXXXLong(image); if(EOFBlob(image)) break; MATLAB_HDR.ObjectSize = ReadBlobXXXLong(image); if(EOFBlob(image)) break; if((MagickSizeType) (MATLAB_HDR.ObjectSize+filepos) > GetBlobSize(image)) goto MATLAB_KO; filepos += MATLAB_HDR.ObjectSize + 4 + 4; clone_info=CloneImageInfo(image_info); image2 = image; #if defined(MAGICKCORE_ZLIB_DELEGATE) if(MATLAB_HDR.DataType == miCOMPRESSED) { image2 = decompress_block(image,&MATLAB_HDR.ObjectSize,clone_info,exception); if(image2==NULL) continue; MATLAB_HDR.DataType = ReadBlobXXXLong(image2); /* replace compressed object type. */ } #endif if (MATLAB_HDR.DataType!=miMATRIX) { clone_info=DestroyImageInfo(clone_info); continue; /* skip another objects. */ } MATLAB_HDR.unknown1 = ReadBlobXXXLong(image2); MATLAB_HDR.unknown2 = ReadBlobXXXLong(image2); MATLAB_HDR.unknown5 = ReadBlobXXXLong(image2); MATLAB_HDR.StructureClass = MATLAB_HDR.unknown5 & 0xFF; MATLAB_HDR.StructureFlag = (MATLAB_HDR.unknown5>>8) & 0xFF; MATLAB_HDR.unknown3 = ReadBlobXXXLong(image2); if(image!=image2) MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2); /* ??? don't understand why ?? */ MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2); MATLAB_HDR.DimFlag = ReadBlobXXXLong(image2); MATLAB_HDR.SizeX = ReadBlobXXXLong(image2); MATLAB_HDR.SizeY = ReadBlobXXXLong(image2); switch(MATLAB_HDR.DimFlag) { case 8: z2=z=1; break; /* 2D matrix*/ case 12: z2=z = ReadBlobXXXLong(image2); /* 3D matrix RGB*/ (void) ReadBlobXXXLong(image2); if(z!=3) ThrowReaderException(CoderError, ""MultidimensionalMatricesAreNotSupported""); break; case 16: z2=z = ReadBlobXXXLong(image2); /* 4D matrix animation */ if(z!=3 && z!=1) ThrowReaderException(CoderError, ""MultidimensionalMatricesAreNotSupported""); Frames = ReadBlobXXXLong(image2); if (Frames == 0) ThrowReaderException(CorruptImageError,""ImproperImageHeader""); break; default: if (clone_info != (ImageInfo *) NULL) clone_info=DestroyImageInfo(clone_info); if ((image != image2) && (image2 != (Image *) NULL)) image2=DestroyImage(image2); ThrowReaderException(CoderError, ""MultidimensionalMatricesAreNotSupported""); } MATLAB_HDR.Flag1 = ReadBlobXXXShort(image2); MATLAB_HDR.NameFlag = ReadBlobXXXShort(image2); if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), ""MATLAB_HDR.StructureClass %d"",MATLAB_HDR.StructureClass); if (MATLAB_HDR.StructureClass != mxCHAR_CLASS && MATLAB_HDR.StructureClass != mxSINGLE_CLASS && /* float + complex float */ MATLAB_HDR.StructureClass != mxDOUBLE_CLASS && /* double + complex double */ MATLAB_HDR.StructureClass != mxINT8_CLASS && MATLAB_HDR.StructureClass != mxUINT8_CLASS && /* uint8 + uint8 3D */ MATLAB_HDR.StructureClass != mxINT16_CLASS && MATLAB_HDR.StructureClass != mxUINT16_CLASS && /* uint16 + uint16 3D */ MATLAB_HDR.StructureClass != mxINT32_CLASS && MATLAB_HDR.StructureClass != mxUINT32_CLASS && /* uint32 + uint32 3D */ MATLAB_HDR.StructureClass != mxINT64_CLASS && MATLAB_HDR.StructureClass != mxUINT64_CLASS) /* uint64 + uint64 3D */ ThrowReaderException(CoderError,""UnsupportedCellTypeInTheMatrix""); switch (MATLAB_HDR.NameFlag) { case 0: size = ReadBlobXXXLong(image2); /* Object name string size */ size = 4 * (ssize_t) ((size + 3 + 1) / 4); (void) SeekBlob(image2, size, SEEK_CUR); break; case 1: case 2: case 3: case 4: (void) ReadBlob(image2, 4, (unsigned char *) &size); /* Object name string */ break; default: goto MATLAB_KO; } CellType = ReadBlobXXXLong(image2); /* Additional object type */ if (logging) (void) LogMagickEvent(CoderEvent,GetMagickModule(), ""MATLAB_HDR.CellType: %.20g"",(double) CellType); (void) ReadBlob(image2, 4, (unsigned char *) &size); /* data size */ NEXT_FRAME: switch (CellType) { case miINT8: case miUINT8: sample_size = 8; if(MATLAB_HDR.StructureFlag & FLAG_LOGICAL) image->depth = 1; else image->depth = 8; /* Byte type cell */ ldblk = (ssize_t) MATLAB_HDR.SizeX; break; case miINT16: case miUINT16: sample_size = 16; image->depth = 16; /* Word type cell */ ldblk = (ssize_t) (2 * MATLAB_HDR.SizeX); break; case miINT32: case miUINT32: sample_size = 32; image->depth = 32; /* Dword type cell */ ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX); break; case miINT64: case miUINT64: sample_size = 64; image->depth = 64; /* Qword type cell */ ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX); break; case miSINGLE: sample_size = 32; image->depth = 32; /* double type cell */ (void) SetImageOption(clone_info,""quantum:format"",""floating-point""); if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX) { /* complex float type cell */ } ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX); break; case miDOUBLE: sample_size = 64; image->depth = 64; /* double type cell */ (void) SetImageOption(clone_info,""quantum:format"",""floating-point""); DisableMSCWarning(4127) if (sizeof(double) != 8) RestoreMSCWarning ThrowReaderException(CoderError, ""IncompatibleSizeOfDouble""); if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX) { /* complex double type cell */ } ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX); break; default: if ((image != image2) && (image2 != (Image *) NULL)) image2=DestroyImage(image2); if (clone_info) clone_info=DestroyImageInfo(clone_info); ThrowReaderException(CoderError, ""UnsupportedCellTypeInTheMatrix""); } (void) sample_size; image->columns = MATLAB_HDR.SizeX; image->rows = MATLAB_HDR.SizeY; one=1; image->colors = one << image->depth; if (image->columns == 0 || image->rows == 0) goto MATLAB_KO; if((unsigned long)ldblk*MATLAB_HDR.SizeY > MATLAB_HDR.ObjectSize) goto MATLAB_KO; /* Image is gray when no complex flag is set and 2D Matrix */ if ((MATLAB_HDR.DimFlag == 8) && ((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0)) { image->type=GrayscaleType; SetImageColorspace(image,GRAYColorspace,exception); } /* If ping is true, then only set image size and colors without reading any image data. */ if (image_info->ping) { size_t temp = image->columns; image->columns = image->rows; image->rows = temp; goto done_reading; /* !!!!!! BAD !!!! */ } status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) { if ((image != image2) && (image2 != (Image *) NULL)) image2=DestroyImage(image2); return(DestroyImageList(image)); } quantum_info=AcquireQuantumInfo(clone_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); /* ----- Load raster data ----- */ BImgBuff = (unsigned char *) AcquireQuantumMemory((size_t) (ldblk),sizeof(double)); /* Ldblk was set in the check phase */ if (BImgBuff == NULL) ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); (void) ResetMagickMemory(BImgBuff,0,ldblk*sizeof(double)); MinVal = 0; MaxVal = 0; if (CellType==miDOUBLE || CellType==miSINGLE) /* Find Min and Max Values for floats */ { CalcMinMax(image2, image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &quantum_info->minimum, &quantum_info->maximum); } /* Main loop for reading all scanlines */ if(z==1) z=0; /* read grey scanlines */ /* else read color scanlines */ do { for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++) { q=GetAuthenticPixels(image,0,MATLAB_HDR.SizeY-i-1,image->columns,1,exception); if (q == (Quantum *) NULL) { if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), "" MAT set image pixels returns unexpected NULL on a row %u."", (unsigned)(MATLAB_HDR.SizeY-i-1)); goto done_reading; /* Skip image rotation, when cannot set image pixels */ } if(ReadBlob(image2,ldblk,(unsigned char *)BImgBuff) != (ssize_t) ldblk) { if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), "" MAT cannot read scanrow %u from a file."", (unsigned)(MATLAB_HDR.SizeY-i-1)); goto ExitLoop; } if((CellType==miINT8 || CellType==miUINT8) && (MATLAB_HDR.StructureFlag & FLAG_LOGICAL)) { FixLogical((unsigned char *)BImgBuff,ldblk); if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0) { ImportQuantumPixelsFailed: if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), "" MAT failed to ImportQuantumPixels for a row %u"", (unsigned)(MATLAB_HDR.SizeY-i-1)); break; } } else { if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0) goto ImportQuantumPixelsFailed; if (z<=1 && /* fix only during a last pass z==0 || z==1 */ (CellType==miINT8 || CellType==miINT16 || CellType==miINT32 || CellType==miINT64)) FixSignedValues(image,q,MATLAB_HDR.SizeX); } if (!SyncAuthenticPixels(image,exception)) { if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), "" MAT failed to sync image pixels for a row %u"", (unsigned)(MATLAB_HDR.SizeY-i-1)); goto ExitLoop; } } } while(z-- >= 2); ExitLoop: /* Read complex part of numbers here */ if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX) { /* Find Min and Max Values for complex parts of floats */ CellType = ReadBlobXXXLong(image2); /* Additional object type */ i = ReadBlobXXXLong(image2); /* size of a complex part - toss away*/ if (CellType==miDOUBLE || CellType==miSINGLE) { CalcMinMax(image2, image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &MinVal, &MaxVal); } if (CellType==miDOUBLE) for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++) { ReadBlobDoublesXXX(image2, ldblk, (double *)BImgBuff); InsertComplexDoubleRow(image, (double *)BImgBuff, i, MinVal, MaxVal, exception); } if (CellType==miSINGLE) for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++) { ReadBlobFloatsXXX(image2, ldblk, (float *)BImgBuff); InsertComplexFloatRow(image,(float *)BImgBuff,i,MinVal,MaxVal, exception); } } /* Image is gray when no complex flag is set and 2D Matrix AGAIN!!! */ if ((MATLAB_HDR.DimFlag == 8) && ((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0)) image->type=GrayscaleType; if (image->depth == 1) image->type=BilevelType; if(image2==image) image2 = NULL; /* Remove shadow copy to an image before rotation. */ /* Rotate image. */ rotated_image = RotateImage(image, 90.0, exception); if (rotated_image != (Image *) NULL) { /* Remove page offsets added by RotateImage */ rotated_image->page.x=0; rotated_image->page.y=0; blob = rotated_image->blob; rotated_image->blob = image->blob; rotated_image->colors = image->colors; image->blob = blob; AppendImageToList(&image,rotated_image); DeleteImageFromList(&image); } done_reading: if(image2!=NULL) if(image2!=image) { DeleteImageFromList(&image2); if(clone_info) { if(clone_info->file) { fclose(clone_info->file); clone_info->file = NULL; (void) remove_utf8(clone_info->filename); } } } /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (image->next == (Image *) NULL) break; image=SyncNextImageInList(image); image->columns=image->rows=0; image->colors=0; /* row scan buffer is no longer needed */ RelinquishMagickMemory(BImgBuff); BImgBuff = NULL; if(--Frames>0) { z = z2; if(image2==NULL) image2 = image; goto NEXT_FRAME; } if ((image2!=NULL) && (image2!=image)) /* Does shadow temporary decompressed image exist? */ { /* CloseBlob(image2); */ DeleteImageFromList(&image2); if(clone_info) { if(clone_info->file) { fclose(clone_info->file); clone_info->file = NULL; (void) remove_utf8(clone_info->filename); } } } if (quantum_info != (QuantumInfo *) NULL) quantum_info=DestroyQuantumInfo(quantum_info); if (clone_info) clone_info=DestroyImageInfo(clone_info); } RelinquishMagickMemory(BImgBuff); if (quantum_info != (QuantumInfo *) NULL) quantum_info=DestroyQuantumInfo(quantum_info); END_OF_READING: if (clone_info) clone_info=DestroyImageInfo(clone_info); CloseBlob(image); { Image *p; ssize_t scene=0; /* Rewind list, removing any empty images while rewinding. */ p=image; image=NULL; while (p != (Image *) NULL) { Image *tmp=p; if ((p->rows == 0) || (p->columns == 0)) { p=p->previous; DeleteImageFromList(&tmp); } else { image=p; p=p->previous; } } /* Fix scene numbers */ for (p=image; p != (Image *) NULL; p=p->next) p->scene=scene++; } if(clone_info != NULL) /* cleanup garbage file from compression */ { if(clone_info->file) { fclose(clone_info->file); clone_info->file = NULL; (void) remove_utf8(clone_info->filename); } DestroyImageInfo(clone_info); clone_info = NULL; } if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),""return""); if (image==NULL) ThrowReaderException(CorruptImageError,""ImproperImageHeader"") else if ((image != image2) && (image2 != (Image *) NULL)) image2=DestroyImage(image2); return (image); }","static Image *ReadMATImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *image, *image2=NULL, *rotated_image; register Quantum *q; unsigned int status; MATHeader MATLAB_HDR; size_t size; size_t CellType; QuantumInfo *quantum_info; ImageInfo *clone_info; int i; ssize_t ldblk; unsigned char *BImgBuff = NULL; double MinVal, MaxVal; unsigned z, z2; unsigned Frames; int logging; int sample_size; MagickOffsetType filepos=0x80; BlobInfo *blob; size_t one; unsigned int (*ReadBlobXXXLong)(Image *image); unsigned short (*ReadBlobXXXShort)(Image *image); void (*ReadBlobDoublesXXX)(Image * image, size_t len, double *data); void (*ReadBlobFloatsXXX)(Image * image, size_t len, float *data); assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); logging = LogMagickEvent(CoderEvent,GetMagickModule(),""enter""); /* Open image file. */ image = AcquireImage(image_info,exception); status = OpenBlob(image_info, image, ReadBinaryBlobMode, exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read MATLAB image. */ quantum_info=(QuantumInfo *) NULL; clone_info=(ImageInfo *) NULL; if (ReadBlob(image,124,(unsigned char *) &MATLAB_HDR.identific) != 124) ThrowReaderException(CorruptImageError,""ImproperImageHeader""); if (strncmp(MATLAB_HDR.identific,""MATLAB"",6) != 0) { image2=ReadMATImageV4(image_info,image,exception); if (image2 == NULL) goto MATLAB_KO; image=image2; goto END_OF_READING; } MATLAB_HDR.Version = ReadBlobLSBShort(image); if(ReadBlob(image,2,(unsigned char *) &MATLAB_HDR.EndianIndicator) != 2) ThrowReaderException(CorruptImageError,""ImproperImageHeader""); if (logging) (void) LogMagickEvent(CoderEvent,GetMagickModule(),"" Endian %c%c"", MATLAB_HDR.EndianIndicator[0],MATLAB_HDR.EndianIndicator[1]); if (!strncmp(MATLAB_HDR.EndianIndicator, ""IM"", 2)) { ReadBlobXXXLong = ReadBlobLSBLong; ReadBlobXXXShort = ReadBlobLSBShort; ReadBlobDoublesXXX = ReadBlobDoublesLSB; ReadBlobFloatsXXX = ReadBlobFloatsLSB; image->endian = LSBEndian; } else if (!strncmp(MATLAB_HDR.EndianIndicator, ""MI"", 2)) { ReadBlobXXXLong = ReadBlobMSBLong; ReadBlobXXXShort = ReadBlobMSBShort; ReadBlobDoublesXXX = ReadBlobDoublesMSB; ReadBlobFloatsXXX = ReadBlobFloatsMSB; image->endian = MSBEndian; } else goto MATLAB_KO; /* unsupported endian */ if (strncmp(MATLAB_HDR.identific, ""MATLAB"", 6)) { MATLAB_KO: if ((image != image2) && (image2 != (Image *) NULL)) image2=DestroyImage(image2); if (clone_info != (ImageInfo *) NULL) clone_info=DestroyImageInfo(clone_info); ThrowReaderException(CorruptImageError,""ImproperImageHeader""); } filepos = TellBlob(image); while(!EOFBlob(image)) /* object parser loop */ { Frames = 1; (void) SeekBlob(image,filepos,SEEK_SET); /* printf(""pos=%X\n"",TellBlob(image)); */ MATLAB_HDR.DataType = ReadBlobXXXLong(image); if(EOFBlob(image)) break; MATLAB_HDR.ObjectSize = ReadBlobXXXLong(image); if(EOFBlob(image)) break; if((MagickSizeType) (MATLAB_HDR.ObjectSize+filepos) > GetBlobSize(image)) goto MATLAB_KO; filepos += MATLAB_HDR.ObjectSize + 4 + 4; clone_info=CloneImageInfo(image_info); image2 = image; #if defined(MAGICKCORE_ZLIB_DELEGATE) if(MATLAB_HDR.DataType == miCOMPRESSED) { image2 = decompress_block(image,&MATLAB_HDR.ObjectSize,clone_info,exception); if(image2==NULL) continue; MATLAB_HDR.DataType = ReadBlobXXXLong(image2); /* replace compressed object type. */ } #endif if (MATLAB_HDR.DataType!=miMATRIX) { clone_info=DestroyImageInfo(clone_info); continue; /* skip another objects. */ } MATLAB_HDR.unknown1 = ReadBlobXXXLong(image2); MATLAB_HDR.unknown2 = ReadBlobXXXLong(image2); MATLAB_HDR.unknown5 = ReadBlobXXXLong(image2); MATLAB_HDR.StructureClass = MATLAB_HDR.unknown5 & 0xFF; MATLAB_HDR.StructureFlag = (MATLAB_HDR.unknown5>>8) & 0xFF; MATLAB_HDR.unknown3 = ReadBlobXXXLong(image2); if(image!=image2) MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2); /* ??? don't understand why ?? */ MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2); MATLAB_HDR.DimFlag = ReadBlobXXXLong(image2); MATLAB_HDR.SizeX = ReadBlobXXXLong(image2); MATLAB_HDR.SizeY = ReadBlobXXXLong(image2); switch(MATLAB_HDR.DimFlag) { case 8: z2=z=1; break; /* 2D matrix*/ case 12: z2=z = ReadBlobXXXLong(image2); /* 3D matrix RGB*/ (void) ReadBlobXXXLong(image2); if(z!=3) ThrowReaderException(CoderError, ""MultidimensionalMatricesAreNotSupported""); break; case 16: z2=z = ReadBlobXXXLong(image2); /* 4D matrix animation */ if(z!=3 && z!=1) ThrowReaderException(CoderError, ""MultidimensionalMatricesAreNotSupported""); Frames = ReadBlobXXXLong(image2); if (Frames == 0) ThrowReaderException(CorruptImageError,""ImproperImageHeader""); break; default: if (clone_info != (ImageInfo *) NULL) clone_info=DestroyImageInfo(clone_info); if ((image != image2) && (image2 != (Image *) NULL)) image2=DestroyImage(image2); ThrowReaderException(CoderError, ""MultidimensionalMatricesAreNotSupported""); } MATLAB_HDR.Flag1 = ReadBlobXXXShort(image2); MATLAB_HDR.NameFlag = ReadBlobXXXShort(image2); if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), ""MATLAB_HDR.StructureClass %d"",MATLAB_HDR.StructureClass); if (MATLAB_HDR.StructureClass != mxCHAR_CLASS && MATLAB_HDR.StructureClass != mxSINGLE_CLASS && /* float + complex float */ MATLAB_HDR.StructureClass != mxDOUBLE_CLASS && /* double + complex double */ MATLAB_HDR.StructureClass != mxINT8_CLASS && MATLAB_HDR.StructureClass != mxUINT8_CLASS && /* uint8 + uint8 3D */ MATLAB_HDR.StructureClass != mxINT16_CLASS && MATLAB_HDR.StructureClass != mxUINT16_CLASS && /* uint16 + uint16 3D */ MATLAB_HDR.StructureClass != mxINT32_CLASS && MATLAB_HDR.StructureClass != mxUINT32_CLASS && /* uint32 + uint32 3D */ MATLAB_HDR.StructureClass != mxINT64_CLASS && MATLAB_HDR.StructureClass != mxUINT64_CLASS) /* uint64 + uint64 3D */ ThrowReaderException(CoderError,""UnsupportedCellTypeInTheMatrix""); switch (MATLAB_HDR.NameFlag) { case 0: size = ReadBlobXXXLong(image2); /* Object name string size */ size = 4 * (ssize_t) ((size + 3 + 1) / 4); (void) SeekBlob(image2, size, SEEK_CUR); break; case 1: case 2: case 3: case 4: (void) ReadBlob(image2, 4, (unsigned char *) &size); /* Object name string */ break; default: goto MATLAB_KO; } CellType = ReadBlobXXXLong(image2); /* Additional object type */ if (logging) (void) LogMagickEvent(CoderEvent,GetMagickModule(), ""MATLAB_HDR.CellType: %.20g"",(double) CellType); (void) ReadBlob(image2, 4, (unsigned char *) &size); /* data size */ NEXT_FRAME: switch (CellType) { case miINT8: case miUINT8: sample_size = 8; if(MATLAB_HDR.StructureFlag & FLAG_LOGICAL) image->depth = 1; else image->depth = 8; /* Byte type cell */ ldblk = (ssize_t) MATLAB_HDR.SizeX; break; case miINT16: case miUINT16: sample_size = 16; image->depth = 16; /* Word type cell */ ldblk = (ssize_t) (2 * MATLAB_HDR.SizeX); break; case miINT32: case miUINT32: sample_size = 32; image->depth = 32; /* Dword type cell */ ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX); break; case miINT64: case miUINT64: sample_size = 64; image->depth = 64; /* Qword type cell */ ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX); break; case miSINGLE: sample_size = 32; image->depth = 32; /* double type cell */ (void) SetImageOption(clone_info,""quantum:format"",""floating-point""); if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX) { /* complex float type cell */ } ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX); break; case miDOUBLE: sample_size = 64; image->depth = 64; /* double type cell */ (void) SetImageOption(clone_info,""quantum:format"",""floating-point""); DisableMSCWarning(4127) if (sizeof(double) != 8) RestoreMSCWarning ThrowReaderException(CoderError, ""IncompatibleSizeOfDouble""); if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX) { /* complex double type cell */ } ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX); break; default: if ((image != image2) && (image2 != (Image *) NULL)) image2=DestroyImage(image2); if (clone_info) clone_info=DestroyImageInfo(clone_info); ThrowReaderException(CoderError, ""UnsupportedCellTypeInTheMatrix""); } (void) sample_size; image->columns = MATLAB_HDR.SizeX; image->rows = MATLAB_HDR.SizeY; one=1; image->colors = one << image->depth; if (image->columns == 0 || image->rows == 0) goto MATLAB_KO; if((unsigned long)ldblk*MATLAB_HDR.SizeY > MATLAB_HDR.ObjectSize) goto MATLAB_KO; /* Image is gray when no complex flag is set and 2D Matrix */ if ((MATLAB_HDR.DimFlag == 8) && ((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0)) { image->type=GrayscaleType; SetImageColorspace(image,GRAYColorspace,exception); } /* If ping is true, then only set image size and colors without reading any image data. */ if (image_info->ping) { size_t temp = image->columns; image->columns = image->rows; image->rows = temp; goto done_reading; /* !!!!!! BAD !!!! */ } status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) { if ((image != image2) && (image2 != (Image *) NULL)) image2=DestroyImage(image2); return(DestroyImageList(image)); } quantum_info=AcquireQuantumInfo(clone_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); /* ----- Load raster data ----- */ BImgBuff = (unsigned char *) AcquireQuantumMemory((size_t) (ldblk),sizeof(double)); /* Ldblk was set in the check phase */ if (BImgBuff == NULL) ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); (void) ResetMagickMemory(BImgBuff,0,ldblk*sizeof(double)); MinVal = 0; MaxVal = 0; if (CellType==miDOUBLE || CellType==miSINGLE) /* Find Min and Max Values for floats */ { CalcMinMax(image2, image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &quantum_info->minimum, &quantum_info->maximum); } /* Main loop for reading all scanlines */ if(z==1) z=0; /* read grey scanlines */ /* else read color scanlines */ do { for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++) { q=GetAuthenticPixels(image,0,MATLAB_HDR.SizeY-i-1,image->columns,1,exception); if (q == (Quantum *) NULL) { if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), "" MAT set image pixels returns unexpected NULL on a row %u."", (unsigned)(MATLAB_HDR.SizeY-i-1)); goto done_reading; /* Skip image rotation, when cannot set image pixels */ } if(ReadBlob(image2,ldblk,(unsigned char *)BImgBuff) != (ssize_t) ldblk) { if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), "" MAT cannot read scanrow %u from a file."", (unsigned)(MATLAB_HDR.SizeY-i-1)); goto ExitLoop; } if((CellType==miINT8 || CellType==miUINT8) && (MATLAB_HDR.StructureFlag & FLAG_LOGICAL)) { FixLogical((unsigned char *)BImgBuff,ldblk); if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0) { ImportQuantumPixelsFailed: if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), "" MAT failed to ImportQuantumPixels for a row %u"", (unsigned)(MATLAB_HDR.SizeY-i-1)); break; } } else { if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0) goto ImportQuantumPixelsFailed; if (z<=1 && /* fix only during a last pass z==0 || z==1 */ (CellType==miINT8 || CellType==miINT16 || CellType==miINT32 || CellType==miINT64)) FixSignedValues(image,q,MATLAB_HDR.SizeX); } if (!SyncAuthenticPixels(image,exception)) { if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), "" MAT failed to sync image pixels for a row %u"", (unsigned)(MATLAB_HDR.SizeY-i-1)); goto ExitLoop; } } } while(z-- >= 2); ExitLoop: /* Read complex part of numbers here */ if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX) { /* Find Min and Max Values for complex parts of floats */ CellType = ReadBlobXXXLong(image2); /* Additional object type */ i = ReadBlobXXXLong(image2); /* size of a complex part - toss away*/ if (CellType==miDOUBLE || CellType==miSINGLE) { CalcMinMax(image2, image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &MinVal, &MaxVal); } if (CellType==miDOUBLE) for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++) { ReadBlobDoublesXXX(image2, ldblk, (double *)BImgBuff); InsertComplexDoubleRow(image, (double *)BImgBuff, i, MinVal, MaxVal, exception); } if (CellType==miSINGLE) for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++) { ReadBlobFloatsXXX(image2, ldblk, (float *)BImgBuff); InsertComplexFloatRow(image,(float *)BImgBuff,i,MinVal,MaxVal, exception); } } /* Image is gray when no complex flag is set and 2D Matrix AGAIN!!! */ if ((MATLAB_HDR.DimFlag == 8) && ((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0)) image->type=GrayscaleType; if (image->depth == 1) image->type=BilevelType; if(image2==image) image2 = NULL; /* Remove shadow copy to an image before rotation. */ /* Rotate image. */ rotated_image = RotateImage(image, 90.0, exception); if (rotated_image != (Image *) NULL) { /* Remove page offsets added by RotateImage */ rotated_image->page.x=0; rotated_image->page.y=0; blob = rotated_image->blob; rotated_image->blob = image->blob; rotated_image->colors = image->colors; image->blob = blob; AppendImageToList(&image,rotated_image); DeleteImageFromList(&image); } done_reading: if(image2!=NULL) if(image2!=image) { DeleteImageFromList(&image2); if(clone_info) { if(clone_info->file) { fclose(clone_info->file); clone_info->file = NULL; (void) remove_utf8(clone_info->filename); } } } /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (image->next == (Image *) NULL) break; image=SyncNextImageInList(image); image->columns=image->rows=0; image->colors=0; /* row scan buffer is no longer needed */ RelinquishMagickMemory(BImgBuff); BImgBuff = NULL; if(--Frames>0) { z = z2; if(image2==NULL) image2 = image; goto NEXT_FRAME; } if ((image2!=NULL) && (image2!=image)) /* Does shadow temporary decompressed image exist? */ { /* CloseBlob(image2); */ DeleteImageFromList(&image2); if(clone_info) { if(clone_info->file) { fclose(clone_info->file); clone_info->file = NULL; (void) remove_utf8(clone_info->filename); } } } if (quantum_info != (QuantumInfo *) NULL) quantum_info=DestroyQuantumInfo(quantum_info); if (clone_info) clone_info=DestroyImageInfo(clone_info); } RelinquishMagickMemory(BImgBuff); if (quantum_info != (QuantumInfo *) NULL) quantum_info=DestroyQuantumInfo(quantum_info); END_OF_READING: CloseBlob(image); { Image *p; ssize_t scene=0; /* Rewind list, removing any empty images while rewinding. */ p=image; image=NULL; while (p != (Image *) NULL) { Image *tmp=p; if ((p->rows == 0) || (p->columns == 0)) { p=p->previous; if (tmp == image2) image2=(Image *) NULL; DeleteImageFromList(&tmp); } else { image=p; p=p->previous; } } /* Fix scene numbers */ for (p=image; p != (Image *) NULL; p=p->next) p->scene=scene++; } if(clone_info != NULL) /* cleanup garbage file from compression */ { if(clone_info->file) { fclose(clone_info->file); clone_info->file = NULL; (void) remove_utf8(clone_info->filename); } DestroyImageInfo(clone_info); clone_info = NULL; } if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),""return""); if (image==NULL) ThrowReaderException(CorruptImageError,""ImproperImageHeader"") else if ((image != image2) && (image2 != (Image *) NULL)) image2=DestroyImage(image2); return (image); }","{'deleted': [{'line_no': 489, 'char_start': 16851, 'char_end': 16869, 'line': ' if (clone_info)\n'}, {'line_no': 490, 'char_start': 16869, 'char_end': 16914, 'line': ' clone_info=DestroyImageInfo(clone_info);\n'}], 'added': [{'line_no': 506, 'char_start': 17156, 'char_end': 17185, 'line': ' if (tmp == image2)\n'}, {'line_no': 507, 'char_start': 17185, 'char_end': 17220, 'line': ' image2=(Image *) NULL;\n'}]}","{'deleted': [{'char_start': 16853, 'char_end': 16916, 'chars': 'if (clone_info)\n clone_info=DestroyImageInfo(clone_info);\n '}], 'added': [{'char_start': 17154, 'char_end': 17218, 'chars': ';\n if (tmp == image2)\n image2=(Image *) NULL'}]}",github.com/ImageMagick/ImageMagick/commit/04178de2247e353fc095846784b9a10fefdbf890,coders/mat.c,cwe-416,4907 cwe-022,save,"async def save(request): # TODO csrf data = await request.post() item = Item(data['src']) # Update name new_src = data.get('new_src') if new_src and new_src != data['src']: # don't need to worry about html unquote shutil.move(item.abspath, settings.STORAGE_DIR + new_src) old_backup_abspath = item.backup_abspath item = Item(new_src) if os.path.isfile(old_backup_abspath): shutil.move(old_backup_abspath, item.backup_abspath) # Update meta for field in item.FORM: # TODO handle .repeatable (keywords) item.meta[field] = [data.get(field, '')] if settings.SAVE_ORIGINALS and not os.path.isfile(item.backup_abspath): shutil.copyfile(item.abspath, item.backup_abspath) # WISHLIST don't write() if nothing changed item.meta.write() return web.Response( status=200, body=json.dumps(item.get_form_fields()).encode('utf8'), content_type='application/json', )","async def save(request): # TODO csrf data = await request.post() item = Item(data['src']) # Update name new_src = data.get('new_src') if new_src: new_abspath = os.path.abspath(settings.STORAGE_DIR + new_src) if not new_abspath.startswith(settings.STORAGE_DIR): return web.Response(status=400, body=b'Invalid Request') if new_abspath != item.abspath: shutil.move(item.abspath, new_abspath) old_backup_abspath = item.backup_abspath item = Item(new_src) if os.path.isfile(old_backup_abspath): shutil.move(old_backup_abspath, item.backup_abspath) # Update meta for field in item.FORM: # TODO handle .repeatable (keywords) item.meta[field] = [data.get(field, '')] if settings.SAVE_ORIGINALS and not os.path.isfile(item.backup_abspath): shutil.copyfile(item.abspath, item.backup_abspath) # WISHLIST don't write() if nothing changed item.meta.write() return web.Response( status=200, body=json.dumps(item.get_form_fields()).encode('utf8'), content_type='application/json', )","{'deleted': [{'line_no': 8, 'char_start': 155, 'char_end': 198, 'line': "" if new_src and new_src != data['src']:\n""}, {'line_no': 10, 'char_start': 247, 'char_end': 313, 'line': ' shutil.move(item.abspath, settings.STORAGE_DIR + new_src)\n'}, {'line_no': 11, 'char_start': 313, 'char_end': 362, 'line': ' old_backup_abspath = item.backup_abspath\n'}, {'line_no': 12, 'char_start': 362, 'char_end': 391, 'line': ' item = Item(new_src)\n'}, {'line_no': 13, 'char_start': 391, 'char_end': 438, 'line': ' if os.path.isfile(old_backup_abspath):\n'}, {'line_no': 14, 'char_start': 438, 'char_end': 503, 'line': ' shutil.move(old_backup_abspath, item.backup_abspath)\n'}], 'added': [{'line_no': 8, 'char_start': 155, 'char_end': 171, 'line': ' if new_src:\n'}, {'line_no': 9, 'char_start': 171, 'char_end': 241, 'line': ' new_abspath = os.path.abspath(settings.STORAGE_DIR + new_src)\n'}, {'line_no': 10, 'char_start': 241, 'char_end': 302, 'line': ' if not new_abspath.startswith(settings.STORAGE_DIR):\n'}, {'line_no': 11, 'char_start': 302, 'char_end': 371, 'line': "" return web.Response(status=400, body=b'Invalid Request')\n""}, {'line_no': 12, 'char_start': 371, 'char_end': 372, 'line': '\n'}, {'line_no': 13, 'char_start': 372, 'char_end': 412, 'line': ' if new_abspath != item.abspath:\n'}, {'line_no': 14, 'char_start': 412, 'char_end': 463, 'line': ' shutil.move(item.abspath, new_abspath)\n'}, {'line_no': 15, 'char_start': 463, 'char_end': 516, 'line': ' old_backup_abspath = item.backup_abspath\n'}, {'line_no': 16, 'char_start': 516, 'char_end': 549, 'line': ' item = Item(new_src)\n'}, {'line_no': 17, 'char_start': 549, 'char_end': 600, 'line': ' if os.path.isfile(old_backup_abspath):\n'}, {'line_no': 18, 'char_start': 600, 'char_end': 669, 'line': ' shutil.move(old_backup_abspath, item.backup_abspath)\n'}]}","{'deleted': [{'char_start': 170, 'char_end': 173, 'chars': 'and'}, {'char_start': 179, 'char_end': 181, 'chars': 'rc'}, {'char_start': 182, 'char_end': 183, 'chars': '!'}, {'char_start': 185, 'char_end': 186, 'chars': 'd'}, {'char_start': 189, 'char_end': 191, 'chars': ""['""}, {'char_start': 194, 'char_end': 197, 'chars': ""']:""}, {'char_start': 206, 'char_end': 207, 'chars': '#'}, {'char_start': 208, 'char_end': 209, 'chars': 'd'}, {'char_start': 210, 'char_end': 212, 'chars': ""n'""}, {'char_start': 217, 'char_end': 218, 'chars': 'd'}, {'char_start': 219, 'char_end': 221, 'chars': 'to'}, {'char_start': 222, 'char_end': 224, 'chars': 'wo'}, {'char_start': 226, 'char_end': 227, 'chars': 'y'}, {'char_start': 228, 'char_end': 229, 'chars': 'a'}, {'char_start': 232, 'char_end': 233, 'chars': 't'}, {'char_start': 234, 'char_end': 237, 'chars': 'htm'}, {'char_start': 239, 'char_end': 241, 'chars': 'un'}, {'char_start': 243, 'char_end': 244, 'chars': 'o'}, {'char_start': 281, 'char_end': 304, 'chars': 'settings.STORAGE_DIR + '}, {'char_start': 309, 'char_end': 311, 'chars': 'rc'}], 'added': [{'char_start': 169, 'char_end': 171, 'chars': ':\n'}, {'char_start': 172, 'char_end': 178, 'chars': ' '}, {'char_start': 183, 'char_end': 185, 'chars': 'ab'}, {'char_start': 186, 'char_end': 190, 'chars': 'path'}, {'char_start': 193, 'char_end': 197, 'chars': 'os.p'}, {'char_start': 199, 'char_end': 201, 'chars': 'h.'}, {'char_start': 202, 'char_end': 236, 'chars': 'bspath(settings.STORAGE_DIR + new_'}, {'char_start': 239, 'char_end': 240, 'chars': ')'}, {'char_start': 249, 'char_end': 251, 'chars': 'if'}, {'char_start': 253, 'char_end': 254, 'chars': 'o'}, {'char_start': 258, 'char_end': 280, 'chars': 'w_abspath.startswith(s'}, {'char_start': 281, 'char_end': 305, 'chars': 'ttings.STORAGE_DIR):\n '}, {'char_start': 306, 'char_end': 316, 'chars': ' re'}, {'char_start': 317, 'char_end': 320, 'chars': 'urn'}, {'char_start': 322, 'char_end': 329, 'chars': 'eb.Resp'}, {'char_start': 330, 'char_end': 336, 'chars': 'nse(st'}, {'char_start': 337, 'char_end': 346, 'chars': 'tus=400, '}, {'char_start': 348, 'char_end': 364, 'chars': ""dy=b'Invalid Req""}, {'char_start': 365, 'char_end': 367, 'chars': 'es'}, {'char_start': 368, 'char_end': 379, 'chars': ""')\n\n ""}, {'char_start': 380, 'char_end': 393, 'chars': 'if new_abspat'}, {'char_start': 394, 'char_end': 399, 'chars': ' != i'}, {'char_start': 400, 'char_end': 401, 'chars': 'e'}, {'char_start': 402, 'char_end': 408, 'chars': '.abspa'}, {'char_start': 409, 'char_end': 411, 'chars': 'h:'}, {'char_start': 412, 'char_end': 416, 'chars': ' '}, {'char_start': 454, 'char_end': 456, 'chars': 'ab'}, {'char_start': 457, 'char_end': 461, 'chars': 'path'}, {'char_start': 463, 'char_end': 467, 'chars': ' '}, {'char_start': 516, 'char_end': 520, 'chars': ' '}, {'char_start': 557, 'char_end': 561, 'chars': ' '}, {'char_start': 600, 'char_end': 604, 'chars': ' '}]}",github.com/crccheck/gallery-cms/commit/60dec5c580a779ae27824ed54cb113eca25afdc0,gallery/gallery.py,cwe-022,239 cwe-125,WavpackVerifySingleBlock,"int WavpackVerifySingleBlock (unsigned char *buffer, int verify_checksum) { WavpackHeader *wphdr = (WavpackHeader *) buffer; uint32_t checksum_passed = 0, bcount, meta_bc; unsigned char *dp, meta_id, c1, c2; if (strncmp (wphdr->ckID, ""wvpk"", 4) || wphdr->ckSize + 8 < sizeof (WavpackHeader)) return FALSE; bcount = wphdr->ckSize - sizeof (WavpackHeader) + 8; dp = (unsigned char *)(wphdr + 1); while (bcount >= 2) { meta_id = *dp++; c1 = *dp++; meta_bc = c1 << 1; bcount -= 2; if (meta_id & ID_LARGE) { if (bcount < 2) return FALSE; c1 = *dp++; c2 = *dp++; meta_bc += ((uint32_t) c1 << 9) + ((uint32_t) c2 << 17); bcount -= 2; } if (bcount < meta_bc) return FALSE; if (verify_checksum && (meta_id & ID_UNIQUE) == ID_BLOCK_CHECKSUM) { #ifdef BITSTREAM_SHORTS uint16_t *csptr = (uint16_t*) buffer; #else unsigned char *csptr = buffer; #endif int wcount = (int)(dp - 2 - buffer) >> 1; uint32_t csum = (uint32_t) -1; if ((meta_id & ID_ODD_SIZE) || meta_bc < 2 || meta_bc > 4) return FALSE; #ifdef BITSTREAM_SHORTS while (wcount--) csum = (csum * 3) + *csptr++; #else WavpackNativeToLittleEndian ((WavpackHeader *) buffer, WavpackHeaderFormat); while (wcount--) { csum = (csum * 3) + csptr [0] + (csptr [1] << 8); csptr += 2; } WavpackLittleEndianToNative ((WavpackHeader *) buffer, WavpackHeaderFormat); #endif if (meta_bc == 4) { if (*dp++ != (csum & 0xff) || *dp++ != ((csum >> 8) & 0xff) || *dp++ != ((csum >> 16) & 0xff) || *dp++ != ((csum >> 24) & 0xff)) return FALSE; } else { csum ^= csum >> 16; if (*dp++ != (csum & 0xff) || *dp++ != ((csum >> 8) & 0xff)) return FALSE; } checksum_passed++; } bcount -= meta_bc; dp += meta_bc; } return (bcount == 0) && (!verify_checksum || !(wphdr->flags & HAS_CHECKSUM) || checksum_passed); }","int WavpackVerifySingleBlock (unsigned char *buffer, int verify_checksum) { WavpackHeader *wphdr = (WavpackHeader *) buffer; uint32_t checksum_passed = 0, bcount, meta_bc; unsigned char *dp, meta_id, c1, c2; if (strncmp (wphdr->ckID, ""wvpk"", 4) || wphdr->ckSize + 8 < sizeof (WavpackHeader)) return FALSE; bcount = wphdr->ckSize - sizeof (WavpackHeader) + 8; dp = (unsigned char *)(wphdr + 1); while (bcount >= 2) { meta_id = *dp++; c1 = *dp++; meta_bc = c1 << 1; bcount -= 2; if (meta_id & ID_LARGE) { if (bcount < 2) return FALSE; c1 = *dp++; c2 = *dp++; meta_bc += ((uint32_t) c1 << 9) + ((uint32_t) c2 << 17); bcount -= 2; } if (bcount < meta_bc) return FALSE; if (verify_checksum && (meta_id & ID_UNIQUE) == ID_BLOCK_CHECKSUM) { #ifdef BITSTREAM_SHORTS uint16_t *csptr = (uint16_t*) buffer; #else unsigned char *csptr = buffer; #endif int wcount = (int)(dp - 2 - buffer) >> 1; uint32_t csum = (uint32_t) -1; if ((meta_id & ID_ODD_SIZE) || meta_bc < 2 || meta_bc > 4) return FALSE; #ifdef BITSTREAM_SHORTS while (wcount--) csum = (csum * 3) + *csptr++; #else WavpackNativeToLittleEndian ((WavpackHeader *) buffer, WavpackHeaderFormat); while (wcount--) { csum = (csum * 3) + csptr [0] + (csptr [1] << 8); csptr += 2; } WavpackLittleEndianToNative ((WavpackHeader *) buffer, WavpackHeaderFormat); #endif if (meta_bc == 4) { if (*dp != (csum & 0xff) || dp[1] != ((csum >> 8) & 0xff) || dp[2] != ((csum >> 16) & 0xff) || dp[3] != ((csum >> 24) & 0xff)) return FALSE; } else { csum ^= csum >> 16; if (*dp != (csum & 0xff) || dp[1] != ((csum >> 8) & 0xff)) return FALSE; } checksum_passed++; } bcount -= meta_bc; dp += meta_bc; } return (bcount == 0) && (!verify_checksum || !(wphdr->flags & HAS_CHECKSUM) || checksum_passed); }","{'deleted': [{'line_no': 60, 'char_start': 1724, 'char_end': 1869, 'line': ' if (*dp++ != (csum & 0xff) || *dp++ != ((csum >> 8) & 0xff) || *dp++ != ((csum >> 16) & 0xff) || *dp++ != ((csum >> 24) & 0xff))\n'}, {'line_no': 66, 'char_start': 1973, 'char_end': 2050, 'line': ' if (*dp++ != (csum & 0xff) || *dp++ != ((csum >> 8) & 0xff))\n'}], 'added': [{'line_no': 60, 'char_start': 1724, 'char_end': 1867, 'line': ' if (*dp != (csum & 0xff) || dp[1] != ((csum >> 8) & 0xff) || dp[2] != ((csum >> 16) & 0xff) || dp[3] != ((csum >> 24) & 0xff))\n'}, {'line_no': 66, 'char_start': 1971, 'char_end': 2046, 'line': ' if (*dp != (csum & 0xff) || dp[1] != ((csum >> 8) & 0xff))\n'}]}","{'deleted': [{'char_start': 1747, 'char_end': 1749, 'chars': '++'}, {'char_start': 1770, 'char_end': 1771, 'chars': '*'}, {'char_start': 1773, 'char_end': 1775, 'chars': '++'}, {'char_start': 1803, 'char_end': 1804, 'chars': '*'}, {'char_start': 1806, 'char_end': 1808, 'chars': '++'}, {'char_start': 1837, 'char_end': 1838, 'chars': '*'}, {'char_start': 1840, 'char_end': 1842, 'chars': '++'}, {'char_start': 1996, 'char_end': 1998, 'chars': '++'}, {'char_start': 2019, 'char_end': 2020, 'chars': '*'}, {'char_start': 2022, 'char_end': 2024, 'chars': '++'}], 'added': [{'char_start': 1770, 'char_end': 1773, 'chars': '[1]'}, {'char_start': 1803, 'char_end': 1806, 'chars': '[2]'}, {'char_start': 1837, 'char_end': 1840, 'chars': '[3]'}, {'char_start': 2017, 'char_end': 2020, 'chars': '[1]'}]}",github.com/dbry/WavPack/commit/bba5389dc598a92bdf2b297c3ea34620b6679b5b,src/open_utils.c,cwe-125,707 cwe-078,_delete_host," def _delete_host(self, host_name): """"""Delete a host on the storage system."""""" LOG.debug(_('enter: _delete_host: host %s ') % host_name) ssh_cmd = 'svctask rmhost %s ' % host_name out, err = self._run_ssh(ssh_cmd) # No output should be returned from rmhost self._assert_ssh_return(len(out.strip()) == 0, '_delete_host', ssh_cmd, out, err) LOG.debug(_('leave: _delete_host: host %s ') % host_name)"," def _delete_host(self, host_name): """"""Delete a host on the storage system."""""" LOG.debug(_('enter: _delete_host: host %s ') % host_name) ssh_cmd = ['svctask', 'rmhost', host_name] out, err = self._run_ssh(ssh_cmd) # No output should be returned from rmhost self._assert_ssh_return(len(out.strip()) == 0, '_delete_host', ssh_cmd, out, err) LOG.debug(_('leave: _delete_host: host %s ') % host_name)","{'deleted': [{'line_no': 6, 'char_start': 158, 'char_end': 209, 'line': "" ssh_cmd = 'svctask rmhost %s ' % host_name\n""}], 'added': [{'line_no': 6, 'char_start': 158, 'char_end': 209, 'line': "" ssh_cmd = ['svctask', 'rmhost', host_name]\n""}]}","{'deleted': [{'char_start': 191, 'char_end': 195, 'chars': ' %s '}, {'char_start': 196, 'char_end': 198, 'chars': ' %'}], 'added': [{'char_start': 176, 'char_end': 177, 'chars': '['}, {'char_start': 185, 'char_end': 187, 'chars': ""',""}, {'char_start': 188, 'char_end': 189, 'chars': ""'""}, {'char_start': 196, 'char_end': 197, 'chars': ','}, {'char_start': 207, 'char_end': 208, 'chars': ']'}]}",github.com/thatsdone/cinder/commit/f752302d181583a95cf44354aea607ce9d9283f4,cinder/volume/drivers/storwize_svc.py,cwe-078,123 cwe-089,process_form,"def process_form(): # see https://docs.python.org/3.4/library/cgi.html for the basic usage # here. form = cgi.FieldStorage() # connect to the database conn = MySQLdb.connect(host = pnsdp.SQL_HOST, user = pnsdp.SQL_USER, passwd = pnsdp.SQL_PASSWD, db = pnsdp.SQL_DB) if ""user"" not in form or ""game"" not in form: raise FormError(""Invalid parameters."") if ""pos"" not in form and ""resign"" not in form: raise FormError(""Invalid parameters."") game = int(form[""game""].value) (players,size,state) = get_game_info(conn, game) user = form[""user""].value if user not in players: raise FormError(""Invalid player ID - player is not part of this game"") if ""resign"" in form: resign = True else: resign = False pos = form[""pos""].value.split("","") assert len(pos) == 2 x = int(pos[0]) y = int(pos[1]) (board,nextPlayer,letter) = build_board(conn, game,size) if user != players[nextPlayer]: raise FormError(""Internal error, incorrect player is attempting to move."") if resign: # this user is choosing to resign. Update the game state to reflect that. other_player_name = players[1-nextPlayer] cursor = conn.cursor() cursor.execute(""""""UPDATE games SET state=""%s:resignation"" WHERE id=%d;"""""" % (other_player_name,game)) cursor.close() else: assert x >= 0 and x < size assert y >= 0 and y < size assert board[x][y] == """" board[x][y] = ""XO""[nextPlayer] # we've done all of our sanity checks. We now know enough to say that # it's safe to add a new move. cursor = conn.cursor() cursor.execute(""""""INSERT INTO moves(gameID,x,y,letter,time) VALUES(%d,%d,%d,""%s"",NOW());"""""" % (game,x,y,letter)) if cursor.rowcount != 1: raise FormError(""Could not make move, reason unknown."") cursor.close() result = analyze_board(board) if result != """": if result == ""win"": result = players[nextPlayer]+"":win"" cursor = conn.cursor() cursor.execute(""""""UPDATE games SET state=""%s"" WHERE id=%d;"""""" % (result,game)) cursor.close() # we've made changes, make sure to commit them! conn.commit() conn.close() # return the parms to the caller, so that they can build a good redirect return (user,game)","def process_form(): # see https://docs.python.org/3.4/library/cgi.html for the basic usage # here. form = cgi.FieldStorage() # connect to the database conn = MySQLdb.connect(host = pnsdp.SQL_HOST, user = pnsdp.SQL_USER, passwd = pnsdp.SQL_PASSWD, db = pnsdp.SQL_DB) if ""user"" not in form or ""game"" not in form: raise FormError(""Invalid parameters."") if ""pos"" not in form and ""resign"" not in form: raise FormError(""Invalid parameters."") game = int(form[""game""].value) (players,size,state) = get_game_info(conn, game) user = form[""user""].value if user not in players: raise FormError(""Invalid player ID - player is not part of this game"") if ""resign"" in form: resign = True else: resign = False pos = form[""pos""].value.split("","") assert len(pos) == 2 x = int(pos[0]) y = int(pos[1]) (board,nextPlayer,letter) = build_board(conn, game,size) if user != players[nextPlayer]: raise FormError(""Internal error, incorrect player is attempting to move."") if resign: # this user is choosing to resign. Update the game state to reflect that. other_player_name = players[1-nextPlayer] cursor = conn.cursor() cursor.execute(""""""UPDATE games SET state=""%s:resignation"" WHERE id=%d;"""""", (other_player_name,game)) cursor.close() else: assert x >= 0 and x < size assert y >= 0 and y < size assert board[x][y] == """" board[x][y] = ""XO""[nextPlayer] # we've done all of our sanity checks. We now know enough to say that # it's safe to add a new move. cursor = conn.cursor() cursor.execute(""""""INSERT INTO moves(gameID,x,y,letter,time) VALUES(%d,%d,%d,""%s"",NOW());"""""", (game,x,y,letter)) if cursor.rowcount != 1: raise FormError(""Could not make move, reason unknown."") cursor.close() result = analyze_board(board) if result != """": if result == ""win"": result = players[nextPlayer]+"":win"" cursor = conn.cursor() cursor.execute(""""""UPDATE games SET state=""%s"" WHERE id=%d;"""""", (result,game)) cursor.close() # we've made changes, make sure to commit them! conn.commit() conn.close() # return the parms to the caller, so that they can build a good redirect return (user,game)","{'deleted': [{'line_no': 50, 'char_start': 1369, 'char_end': 1479, 'line': ' cursor.execute(""""""UPDATE games SET state=""%s:resignation"" WHERE id=%d;"""""" % (other_player_name,game))\n'}, {'line_no': 63, 'char_start': 1806, 'char_end': 1927, 'line': ' cursor.execute(""""""INSERT INTO moves(gameID,x,y,letter,time) VALUES(%d,%d,%d,""%s"",NOW());"""""" % (game,x,y,letter))\n'}, {'line_no': 76, 'char_start': 2237, 'char_end': 2328, 'line': ' cursor.execute(""""""UPDATE games SET state=""%s"" WHERE id=%d;"""""" % (result,game))\n'}], 'added': [{'line_no': 50, 'char_start': 1369, 'char_end': 1478, 'line': ' cursor.execute(""""""UPDATE games SET state=""%s:resignation"" WHERE id=%d;"""""", (other_player_name,game))\n'}, {'line_no': 63, 'char_start': 1805, 'char_end': 1925, 'line': ' cursor.execute(""""""INSERT INTO moves(gameID,x,y,letter,time) VALUES(%d,%d,%d,""%s"",NOW());"""""", (game,x,y,letter))\n'}, {'line_no': 76, 'char_start': 2235, 'char_end': 2325, 'line': ' cursor.execute(""""""UPDATE games SET state=""%s"" WHERE id=%d;"""""", (result,game))\n'}]}","{'deleted': [{'char_start': 1450, 'char_end': 1452, 'chars': ' %'}, {'char_start': 1905, 'char_end': 1907, 'chars': ' %'}, {'char_start': 2310, 'char_end': 2312, 'chars': ' %'}], 'added': [{'char_start': 1450, 'char_end': 1451, 'chars': ','}, {'char_start': 1904, 'char_end': 1905, 'chars': ','}, {'char_start': 2308, 'char_end': 2309, 'chars': ','}]}",github.com/russ-lewis/ttt_-_python_cgi/commit/6096f43fd4b2d91211eec4614b7960c0816900da,cgi/move.py,cwe-089,617 cwe-089,create_playlist,"def create_playlist(name, db): db.execute( ""INSERT INTO playlist (name, video_position) VALUES('{name}', 0);"".format(name=name))","def create_playlist(name, db): db.execute( ""INSERT INTO playlist (name, video_position) VALUES(%s, 0);"", (name,))","{'deleted': [{'line_no': 3, 'char_start': 47, 'char_end': 140, 'line': ' ""INSERT INTO playlist (name, video_position) VALUES(\'{name}\', 0);"".format(name=name))\n'}], 'added': [{'line_no': 3, 'char_start': 47, 'char_end': 125, 'line': ' ""INSERT INTO playlist (name, video_position) VALUES(%s, 0);"", (name,))'}]}","{'deleted': [{'char_start': 107, 'char_end': 115, 'chars': ""'{name}'""}, {'char_start': 121, 'char_end': 128, 'chars': '.format'}, {'char_start': 133, 'char_end': 138, 'chars': '=name'}], 'added': [{'char_start': 107, 'char_end': 109, 'chars': '%s'}, {'char_start': 115, 'char_end': 117, 'chars': ', '}, {'char_start': 122, 'char_end': 123, 'chars': ','}]}",github.com/Madmous/playlist/commit/666e52c5f0b8c1f4296e84471637033d9542a7a6,playlist/playlist_repository.py,cwe-089,34 cwe-416,luaD_shrinkstack,"void luaD_shrinkstack (lua_State *L) { int inuse = stackinuse(L); int goodsize = inuse + (inuse / 8) + 2*EXTRA_STACK; if (goodsize > LUAI_MAXSTACK) goodsize = LUAI_MAXSTACK; /* respect stack limit */ /* if thread is currently not handling a stack overflow and its good size is smaller than current size, shrink its stack */ if (inuse <= (LUAI_MAXSTACK - EXTRA_STACK) && goodsize < L->stacksize) luaD_reallocstack(L, goodsize, 0); /* ok if that fails */ else /* don't change stack */ condmovestack(L,{},{}); /* (change only for debugging) */ luaE_shrinkCI(L); /* shrink CI list */ }","void luaD_shrinkstack (lua_State *L) { int inuse = stackinuse(L); int goodsize = inuse + BASIC_STACK_SIZE; if (goodsize > LUAI_MAXSTACK) goodsize = LUAI_MAXSTACK; /* respect stack limit */ /* if thread is currently not handling a stack overflow and its good size is smaller than current size, shrink its stack */ if (inuse <= (LUAI_MAXSTACK - EXTRA_STACK) && goodsize < L->stacksize) luaD_reallocstack(L, goodsize, 0); /* ok if that fails */ else /* don't change stack */ condmovestack(L,{},{}); /* (change only for debugging) */ luaE_shrinkCI(L); /* shrink CI list */ }","{'deleted': [{'line_no': 3, 'char_start': 68, 'char_end': 122, 'line': ' int goodsize = inuse + (inuse / 8) + 2*EXTRA_STACK;\n'}, {'line_no': 8, 'char_start': 342, 'char_end': 390, 'line': ' if (inuse <= (LUAI_MAXSTACK - EXTRA_STACK) &&\n'}, {'line_no': 9, 'char_start': 390, 'char_end': 421, 'line': ' goodsize < L->stacksize)\n'}], 'added': [{'line_no': 3, 'char_start': 68, 'char_end': 111, 'line': ' int goodsize = inuse + BASIC_STACK_SIZE;\n'}, {'line_no': 8, 'char_start': 331, 'char_end': 404, 'line': ' if (inuse <= (LUAI_MAXSTACK - EXTRA_STACK) && goodsize < L->stacksize)\n'}]}","{'deleted': [{'char_start': 93, 'char_end': 113, 'chars': '(inuse / 8) + 2*EXTR'}, {'char_start': 389, 'char_end': 395, 'chars': '\n '}], 'added': [{'char_start': 93, 'char_end': 94, 'chars': 'B'}, {'char_start': 95, 'char_end': 98, 'chars': 'SIC'}, {'char_start': 104, 'char_end': 109, 'chars': '_SIZE'}]}",github.com/lua/lua/commit/6298903e35217ab69c279056f925fb72900ce0b7,ldo.c,cwe-416,188 cwe-416,disk_seqf_stop,"static void disk_seqf_stop(struct seq_file *seqf, void *v) { struct class_dev_iter *iter = seqf->private; /* stop is called even after start failed :-( */ if (iter) { class_dev_iter_exit(iter); kfree(iter); } }","static void disk_seqf_stop(struct seq_file *seqf, void *v) { struct class_dev_iter *iter = seqf->private; /* stop is called even after start failed :-( */ if (iter) { class_dev_iter_exit(iter); kfree(iter); seqf->private = NULL; } }","{'deleted': [], 'added': [{'line_no': 9, 'char_start': 215, 'char_end': 239, 'line': '\t\tseqf->private = NULL;\n'}]}","{'deleted': [], 'added': [{'char_start': 216, 'char_end': 240, 'chars': '\tseqf->private = NULL;\n\t'}]}",github.com/torvalds/linux/commit/77da160530dd1dc94f6ae15a981f24e5f0021e84,block/genhd.c,cwe-416,61 cwe-089,on_save," def on_save(self): connection = get_connection() cursor = connection.cursor() cursor.execute( f""insert into visitors (ip_address, user_agent, referrer, full_path, visit_time) values ('{self.ip_address}', '{self.user_agent}', '{self.referrer}', '{self.full_path}', '{self.visit_time}');"") connection.commit() connection.close() return 0"," def on_save(self): connection = get_connection() cursor = connection.cursor() cursor.execute( ""insert into visitors (ip_address, user_agent, referrer, full_path, visit_time) values (%s, %s, %s, %s, %s);"", (str(self.ip_address), str(self.user_agent), str(self.referrer), str(self.full_path), self.visit_time)) connection.commit() connection.close() return 0","{'deleted': [{'line_no': 5, 'char_start': 122, 'char_end': 328, 'line': ' f""insert into visitors (ip_address, user_agent, referrer, full_path, visit_time) values (\'{self.ip_address}\', \'{self.user_agent}\', \'{self.referrer}\', \'{self.full_path}\', \'{self.visit_time}\');"")\n'}], 'added': [{'line_no': 5, 'char_start': 122, 'char_end': 245, 'line': ' ""insert into visitors (ip_address, user_agent, referrer, full_path, visit_time) values (%s, %s, %s, %s, %s);"",\n'}, {'line_no': 6, 'char_start': 245, 'char_end': 361, 'line': ' (str(self.ip_address), str(self.user_agent), str(self.referrer), str(self.full_path), self.visit_time))\n'}]}","{'deleted': [{'char_start': 134, 'char_end': 135, 'chars': 'f'}, {'char_start': 223, 'char_end': 225, 'chars': ""'{""}, {'char_start': 240, 'char_end': 242, 'chars': ""}'""}, {'char_start': 244, 'char_end': 246, 'chars': ""'{""}, {'char_start': 261, 'char_end': 263, 'chars': ""}'""}, {'char_start': 265, 'char_end': 267, 'chars': ""'{""}, {'char_start': 280, 'char_end': 282, 'chars': ""}'""}, {'char_start': 284, 'char_end': 286, 'chars': ""'{""}, {'char_start': 300, 'char_end': 302, 'chars': ""}'""}, {'char_start': 304, 'char_end': 306, 'chars': ""'{""}, {'char_start': 321, 'char_end': 323, 'chars': ""}'""}, {'char_start': 324, 'char_end': 326, 'chars': ';""'}], 'added': [{'char_start': 222, 'char_end': 262, 'chars': '%s, %s, %s, %s, %s);"",\n (str('}, {'char_start': 277, 'char_end': 278, 'chars': ')'}, {'char_start': 280, 'char_end': 284, 'chars': 'str('}, {'char_start': 299, 'char_end': 300, 'chars': ')'}, {'char_start': 302, 'char_end': 306, 'chars': 'str('}, {'char_start': 319, 'char_end': 320, 'chars': ')'}, {'char_start': 322, 'char_end': 326, 'chars': 'str('}, {'char_start': 340, 'char_end': 341, 'chars': ')'}]}",github.com/onewyoming/onewyoming/commit/54fc7b076fda2de74eeb55e6b75b28e09ef231c2,experimental/python/buford/model/visitor.py,cwe-089,85 cwe-078,delete_video,"@app.route('/delete_video/') def delete_video(filename): if 'username' in session: #os.remove(""static/videos/{}"".format(filename)) print(session['username'], file=sys.stdout) data=users.query.filter_by(Username=session['username']).first() video=Video.query.filter_by(UserID=data.UserID,Name=filename).first() if video != None: os.remove(""static/videos/{}"".format(filename)) db.session.delete(video) db.session.commit() else: return ""Don't delete other people's videos!"" return redirect(url_for('upload')) return ""test""","@app.route('/delete_video/') def delete_video(filename): if 'username' in session: #os.remove(""static/videos/{}"".format(filename)) print(session['username'], file=sys.stdout) data=users.query.filter_by(Username=session['username']).first() video=Video.query.filter_by(UserID=data.UserID,Name=filename).first() if video != None: #os.remove(""static/videos/{}"".format(filename)) os.system(""rm static/videos/{}"".format(filename)) db.session.delete(video) db.session.commit() else: return ""Don't delete other people's videos!"" return redirect(url_for('upload')) return ""test""","{'deleted': [{'line_no': 9, 'char_start': 349, 'char_end': 399, 'line': '\t\t\tos.remove(""static/videos/{}"".format(filename))\n'}], 'added': [{'line_no': 10, 'char_start': 400, 'char_end': 453, 'line': '\t\t\tos.system(""rm static/videos/{}"".format(filename))\n'}]}","{'deleted': [], 'added': [{'char_start': 352, 'char_end': 353, 'chars': '#'}, {'char_start': 364, 'char_end': 417, 'chars': 'static/videos/{}"".format(filename))\n\t\t\tos.system(""rm '}]}",github.com/jmarcello97/CSEC-380-Project/commit/05dcd628aa5879b6e4979c43e7c635075975de09,Trialwebsite/app/app.py,cwe-078,130 cwe-078,_start_fc_map," def _start_fc_map(self, fc_map_id, source, target): try: out, err = self._run_ssh('svctask startfcmap %s' % fc_map_id) except exception.ProcessExecutionError as e: with excutils.save_and_reraise_exception(): LOG.error(_('_start_fc_map: Failed to start FlashCopy ' 'from %(source)s to %(target)s.\n' 'stdout: %(out)s\n stderr: %(err)s') % {'source': source, 'target': target, 'out': e.stdout, 'err': e.stderr})"," def _start_fc_map(self, fc_map_id, source, target): try: out, err = self._run_ssh(['svctask', 'startfcmap', fc_map_id]) except exception.ProcessExecutionError as e: with excutils.save_and_reraise_exception(): LOG.error(_('_start_fc_map: Failed to start FlashCopy ' 'from %(source)s to %(target)s.\n' 'stdout: %(out)s\n stderr: %(err)s') % {'source': source, 'target': target, 'out': e.stdout, 'err': e.stderr})","{'deleted': [{'line_no': 3, 'char_start': 69, 'char_end': 143, 'line': "" out, err = self._run_ssh('svctask startfcmap %s' % fc_map_id)\n""}], 'added': [{'line_no': 3, 'char_start': 69, 'char_end': 144, 'line': "" out, err = self._run_ssh(['svctask', 'startfcmap', fc_map_id])\n""}]}","{'deleted': [{'char_start': 125, 'char_end': 128, 'chars': ' %s'}, {'char_start': 129, 'char_end': 131, 'chars': ' %'}], 'added': [{'char_start': 106, 'char_end': 107, 'chars': '['}, {'char_start': 115, 'char_end': 117, 'chars': ""',""}, {'char_start': 118, 'char_end': 119, 'chars': ""'""}, {'char_start': 130, 'char_end': 131, 'chars': ','}, {'char_start': 141, 'char_end': 142, 'chars': ']'}]}",github.com/thatsdone/cinder/commit/f752302d181583a95cf44354aea607ce9d9283f4,cinder/volume/drivers/storwize_svc.py,cwe-078,132 cwe-190,TIFFSeekCustomStream,"static MagickOffsetType TIFFSeekCustomStream(const MagickOffsetType offset, const int whence,void *user_data) { PhotoshopProfile *profile; profile=(PhotoshopProfile *) user_data; switch (whence) { case SEEK_SET: default: { if (offset < 0) return(-1); profile->offset=offset; break; } case SEEK_CUR: { if ((profile->offset+offset) < 0) return(-1); profile->offset+=offset; break; } case SEEK_END: { if (((MagickOffsetType) profile->length+offset) < 0) return(-1); profile->offset=profile->length+offset; break; } } return(profile->offset); }","static MagickOffsetType TIFFSeekCustomStream(const MagickOffsetType offset, const int whence,void *user_data) { PhotoshopProfile *profile; profile=(PhotoshopProfile *) user_data; switch (whence) { case SEEK_SET: default: { if (offset < 0) return(-1); profile->offset=offset; break; } case SEEK_CUR: { if (((offset > 0) && (profile->offset > (SSIZE_MAX-offset))) || ((offset < 0) && (profile->offset < (-SSIZE_MAX-offset)))) { errno=EOVERFLOW; return(-1); } if ((profile->offset+offset) < 0) return(-1); profile->offset+=offset; break; } case SEEK_END: { if (((MagickOffsetType) profile->length+offset) < 0) return(-1); profile->offset=profile->length+offset; break; } } return(profile->offset); }","{'deleted': [], 'added': [{'line_no': 20, 'char_start': 366, 'char_end': 436, 'line': ' if (((offset > 0) && (profile->offset > (SSIZE_MAX-offset))) ||\n'}, {'line_no': 21, 'char_start': 436, 'char_end': 505, 'line': ' ((offset < 0) && (profile->offset < (-SSIZE_MAX-offset))))\n'}, {'line_no': 22, 'char_start': 505, 'char_end': 515, 'line': ' {\n'}, {'line_no': 23, 'char_start': 515, 'char_end': 542, 'line': ' errno=EOVERFLOW;\n'}, {'line_no': 24, 'char_start': 542, 'char_end': 564, 'line': ' return(-1);\n'}, {'line_no': 25, 'char_start': 564, 'char_end': 574, 'line': ' }\n'}]}","{'deleted': [], 'added': [{'char_start': 377, 'char_end': 585, 'chars': '(offset > 0) && (profile->offset > (SSIZE_MAX-offset))) ||\n ((offset < 0) && (profile->offset < (-SSIZE_MAX-offset))))\n {\n errno=EOVERFLOW;\n return(-1);\n }\n if (('}]}",github.com/ImageMagick/ImageMagick/commit/fe5f4b85e6b1b54d3b4588a77133c06ade46d891,coders/tiff.c,cwe-190,174 cwe-190,mem_check_range,"int mem_check_range(struct rxe_mem *mem, u64 iova, size_t length) { switch (mem->type) { case RXE_MEM_TYPE_DMA: return 0; case RXE_MEM_TYPE_MR: case RXE_MEM_TYPE_FMR: return ((iova < mem->iova) || ((iova + length) > (mem->iova + mem->length))) ? -EFAULT : 0; default: return -EFAULT; } }","int mem_check_range(struct rxe_mem *mem, u64 iova, size_t length) { switch (mem->type) { case RXE_MEM_TYPE_DMA: return 0; case RXE_MEM_TYPE_MR: case RXE_MEM_TYPE_FMR: if (iova < mem->iova || length > mem->length || iova > mem->iova + mem->length - length) return -EFAULT; return 0; default: return -EFAULT; } }","{'deleted': [{'line_no': 9, 'char_start': 174, 'char_end': 206, 'line': '\t\treturn ((iova < mem->iova) ||\n'}, {'line_no': 10, 'char_start': 206, 'char_end': 258, 'line': '\t\t\t((iova + length) > (mem->iova + mem->length))) ?\n'}, {'line_no': 11, 'char_start': 258, 'char_end': 274, 'line': '\t\t\t-EFAULT : 0;\n'}], 'added': [{'line_no': 9, 'char_start': 174, 'char_end': 200, 'line': '\t\tif (iova < mem->iova ||\n'}, {'line_no': 10, 'char_start': 200, 'char_end': 230, 'line': '\t\t length > mem->length ||\n'}, {'line_no': 11, 'char_start': 230, 'char_end': 277, 'line': '\t\t iova > mem->iova + mem->length - length)\n'}, {'line_no': 12, 'char_start': 277, 'char_end': 296, 'line': '\t\t\treturn -EFAULT;\n'}, {'line_no': 13, 'char_start': 296, 'char_end': 308, 'line': '\t\treturn 0;\n'}]}","{'deleted': [{'char_start': 176, 'char_end': 182, 'chars': 'return'}, {'char_start': 183, 'char_end': 184, 'chars': '('}, {'char_start': 201, 'char_end': 202, 'chars': ')'}, {'char_start': 208, 'char_end': 215, 'chars': '\t((iova'}, {'char_start': 216, 'char_end': 217, 'chars': '+'}, {'char_start': 224, 'char_end': 225, 'chars': ')'}, {'char_start': 228, 'char_end': 229, 'chars': '('}, {'char_start': 252, 'char_end': 255, 'chars': ')))'}, {'char_start': 256, 'char_end': 257, 'chars': '?'}, {'char_start': 268, 'char_end': 270, 'chars': ' :'}], 'added': [{'char_start': 176, 'char_end': 178, 'chars': 'if'}, {'char_start': 202, 'char_end': 204, 'chars': ' '}, {'char_start': 212, 'char_end': 240, 'chars': ' > mem->length ||\n\t\t iova'}, {'char_start': 266, 'char_end': 268, 'chars': ' -'}, {'char_start': 269, 'char_end': 276, 'chars': 'length)'}, {'char_start': 280, 'char_end': 287, 'chars': 'return '}, {'char_start': 294, 'char_end': 304, 'chars': ';\n\t\treturn'}]}",github.com/torvalds/linux/commit/647bf3d8a8e5777319da92af672289b2a6c4dc66,drivers/infiniband/sw/rxe/rxe_mr.c,cwe-190,106 cwe-476,copyIPv6IfDifferent,"static void copyIPv6IfDifferent(void * dest, const void * src) { if(dest != src) { memcpy(dest, src, sizeof(struct in6_addr)); } }","static void copyIPv6IfDifferent(void * dest, const void * src) { if(dest != src && src != NULL) { memcpy(dest, src, sizeof(struct in6_addr)); } }","{'deleted': [{'line_no': 3, 'char_start': 65, 'char_end': 84, 'line': '\tif(dest != src) {\n'}], 'added': [{'line_no': 3, 'char_start': 65, 'char_end': 99, 'line': '\tif(dest != src && src != NULL) {\n'}]}","{'deleted': [], 'added': [{'char_start': 80, 'char_end': 95, 'chars': ' && src != NULL'}]}",github.com/miniupnp/miniupnp/commit/cb8a02af7a5677cf608e86d57ab04241cf34e24f,miniupnpd/pcpserver.c,cwe-476,38 cwe-089,get_tournaments_during_month,"def get_tournaments_during_month(db, scene, date): y, m, d = date.split('-') ym_date = '{}-{}'.format(y, m) sql = ""select url, date from matches where scene='{}' and date like '%{}%' group by url, date order by date"".format(scene, ym_date) res = db.exec(sql) urls = [r[0] for r in res] return urls","def get_tournaments_during_month(db, scene, date): y, m, d = date.split('-') ym_date = '{}-{}'.format(y, m) sql = ""select url, date from matches where scene='{scene}' and date like '%{date}%' group by url, date order by date"" args = {'scene': scene, 'date': ym_date} res = db.exec(sql, args) urls = [r[0] for r in res] return urls","{'deleted': [{'line_no': 4, 'char_start': 116, 'char_end': 252, 'line': ' sql = ""select url, date from matches where scene=\'{}\' and date like \'%{}%\' group by url, date order by date"".format(scene, ym_date)\n'}, {'line_no': 5, 'char_start': 252, 'char_end': 275, 'line': ' res = db.exec(sql)\n'}], 'added': [{'line_no': 4, 'char_start': 116, 'char_end': 238, 'line': ' sql = ""select url, date from matches where scene=\'{scene}\' and date like \'%{date}%\' group by url, date order by date""\n'}, {'line_no': 5, 'char_start': 238, 'char_end': 283, 'line': "" args = {'scene': scene, 'date': ym_date}\n""}, {'line_no': 6, 'char_start': 283, 'char_end': 312, 'line': ' res = db.exec(sql, args)\n'}]}","{'deleted': [{'char_start': 228, 'char_end': 231, 'chars': '.fo'}, {'char_start': 232, 'char_end': 236, 'chars': 'mat('}, {'char_start': 250, 'char_end': 251, 'chars': ')'}], 'added': [{'char_start': 171, 'char_end': 176, 'chars': 'scene'}, {'char_start': 196, 'char_end': 200, 'chars': 'date'}, {'char_start': 237, 'char_end': 242, 'chars': '\n '}, {'char_start': 243, 'char_end': 259, 'chars': ""rgs = {'scene': ""}, {'char_start': 266, 'char_end': 274, 'chars': ""'date': ""}, {'char_start': 281, 'char_end': 282, 'chars': '}'}, {'char_start': 304, 'char_end': 310, 'chars': ', args'}]}",github.com/DKelle/Smash_stats/commit/4bb83f3f6ce7d6bebbeb512cd015f9e72cf36d63,bracket_utils.py,cwe-089,97 cwe-476,prplcb_xfer_new_send_cb,"static gboolean prplcb_xfer_new_send_cb(gpointer data, gint fd, b_input_condition cond) { PurpleXfer *xfer = data; struct im_connection *ic = purple_ic_by_pa(xfer->account); struct prpl_xfer_data *px = xfer->ui_data; PurpleBuddy *buddy; const char *who; buddy = purple_find_buddy(xfer->account, xfer->who); who = buddy ? purple_buddy_get_name(buddy) : xfer->who; /* TODO(wilmer): After spreading some more const goodness in BitlBee, remove the evil cast below. */ px->ft = imcb_file_send_start(ic, (char *) who, xfer->filename, xfer->size); px->ft->data = px; px->ft->accept = prpl_xfer_accept; px->ft->canceled = prpl_xfer_canceled; px->ft->free = prpl_xfer_free; px->ft->write_request = prpl_xfer_write_request; return FALSE; }","static gboolean prplcb_xfer_new_send_cb(gpointer data, gint fd, b_input_condition cond) { PurpleXfer *xfer = data; struct im_connection *ic = purple_ic_by_pa(xfer->account); struct prpl_xfer_data *px = xfer->ui_data; PurpleBuddy *buddy; const char *who; buddy = purple_find_buddy(xfer->account, xfer->who); who = buddy ? purple_buddy_get_name(buddy) : xfer->who; /* TODO(wilmer): After spreading some more const goodness in BitlBee, remove the evil cast below. */ px->ft = imcb_file_send_start(ic, (char *) who, xfer->filename, xfer->size); if (!px->ft) { return FALSE; } px->ft->data = px; px->ft->accept = prpl_xfer_accept; px->ft->canceled = prpl_xfer_canceled; px->ft->free = prpl_xfer_free; px->ft->write_request = prpl_xfer_write_request; return FALSE; }","{'deleted': [], 'added': [{'line_no': 15, 'char_start': 556, 'char_end': 557, 'line': '\n'}, {'line_no': 16, 'char_start': 557, 'char_end': 573, 'line': '\tif (!px->ft) {\n'}, {'line_no': 17, 'char_start': 573, 'char_end': 589, 'line': '\t\treturn FALSE;\n'}, {'line_no': 18, 'char_start': 589, 'char_end': 592, 'line': '\t}\n'}]}","{'deleted': [], 'added': [{'char_start': 556, 'char_end': 592, 'chars': '\n\tif (!px->ft) {\n\t\treturn FALSE;\n\t}\n'}]}",github.com/bitlbee/bitlbee/commit/30d598ce7cd3f136ee9d7097f39fa9818a272441,protocols/purple/ft.c,cwe-476,235 cwe-089,edit,"@mod.route('/edit/', methods=['GET', 'POST']) def edit(cmt_id): m = None if request.method == 'GET': sql = ""SELECT * FROM comment where cmt_id = %d;"" % (cmt_id) cursor.execute(sql) m = cursor.fetchone() return render_template('comment/edit.html', m=m, cmt_id=cmt_id) if request.method == 'POST': content = request.form['content'] sql = ""UPDATE comment SET content = '%s' where cmt_id = '%d';"" \ % (content, cmt_id) cursor.execute(sql) conn.commit() sql = ""SELECT msg_id FROM comment where cmt_id = %d;"" % (cmt_id) cursor.execute(sql) m = cursor.fetchone() flash('Edit Success!') return redirect(url_for('comment.show', msg_id=m[0])) return render_template('comment/edit.html', m=m, cmt_id=cmt_id)","@mod.route('/edit/', methods=['GET', 'POST']) def edit(cmt_id): m = None if request.method == 'GET': cursor.execute(""SELECT * FROM comment where cmt_id = %s;"", (cmt_id,)) m = cursor.fetchone() return render_template('comment/edit.html', m=m, cmt_id=cmt_id) if request.method == 'POST': content = request.form['content'] cursor.execute(""UPDATE comment SET content = %s where cmt_id = %s;"", (content, cmt_id)) conn.commit() cursor.execute(""SELECT msg_id FROM comment where cmt_id = %s;"", (cmt_id,)) m = cursor.fetchone() flash('Edit Success!') return redirect(url_for('comment.show', msg_id=m[0])) return render_template('comment/edit.html', m=m, cmt_id=cmt_id)","{'deleted': [{'line_no': 5, 'char_start': 121, 'char_end': 189, 'line': ' sql = ""SELECT * FROM comment where cmt_id = %d;"" % (cmt_id)\n'}, {'line_no': 6, 'char_start': 189, 'char_end': 217, 'line': ' cursor.execute(sql)\n'}, {'line_no': 12, 'char_start': 395, 'char_end': 468, 'line': ' sql = ""UPDATE comment SET content = \'%s\' where cmt_id = \'%d\';"" \\\n'}, {'line_no': 13, 'char_start': 468, 'char_end': 500, 'line': ' % (content, cmt_id)\n'}, {'line_no': 14, 'char_start': 500, 'char_end': 528, 'line': ' cursor.execute(sql)\n'}, {'line_no': 16, 'char_start': 550, 'char_end': 623, 'line': ' sql = ""SELECT msg_id FROM comment where cmt_id = %d;"" % (cmt_id)\n'}, {'line_no': 17, 'char_start': 623, 'char_end': 651, 'line': ' cursor.execute(sql)\n'}], 'added': [{'line_no': 5, 'char_start': 121, 'char_end': 199, 'line': ' cursor.execute(""SELECT * FROM comment where cmt_id = %s;"", (cmt_id,))\n'}, {'line_no': 11, 'char_start': 377, 'char_end': 473, 'line': ' cursor.execute(""UPDATE comment SET content = %s where cmt_id = %s;"", (content, cmt_id))\n'}, {'line_no': 13, 'char_start': 495, 'char_end': 578, 'line': ' cursor.execute(""SELECT msg_id FROM comment where cmt_id = %s;"", (cmt_id,))\n'}]}","{'deleted': [{'char_start': 130, 'char_end': 135, 'chars': 'ql = '}, {'char_start': 174, 'char_end': 175, 'chars': 'd'}, {'char_start': 177, 'char_end': 179, 'chars': ' %'}, {'char_start': 188, 'char_end': 215, 'chars': '\n cursor.execute(sql'}, {'char_start': 404, 'char_end': 409, 'chars': 'ql = '}, {'char_start': 439, 'char_end': 440, 'chars': ""'""}, {'char_start': 442, 'char_end': 443, 'chars': ""'""}, {'char_start': 459, 'char_end': 460, 'chars': ""'""}, {'char_start': 461, 'char_end': 463, 'chars': ""d'""}, {'char_start': 465, 'char_end': 481, 'chars': ' \\\n %'}, {'char_start': 499, 'char_end': 526, 'chars': '\n cursor.execute(sql'}, {'char_start': 559, 'char_end': 564, 'chars': 'ql = '}, {'char_start': 608, 'char_end': 609, 'chars': 'd'}, {'char_start': 611, 'char_end': 613, 'chars': ' %'}, {'char_start': 622, 'char_end': 649, 'chars': '\n cursor.execute(sql'}], 'added': [{'char_start': 129, 'char_end': 132, 'chars': 'cur'}, {'char_start': 133, 'char_end': 144, 'chars': 'or.execute('}, {'char_start': 183, 'char_end': 184, 'chars': 's'}, {'char_start': 186, 'char_end': 187, 'chars': ','}, {'char_start': 195, 'char_end': 196, 'chars': ','}, {'char_start': 385, 'char_end': 388, 'chars': 'cur'}, {'char_start': 389, 'char_end': 400, 'chars': 'or.execute('}, {'char_start': 449, 'char_end': 450, 'chars': 's'}, {'char_start': 452, 'char_end': 453, 'chars': ','}, {'char_start': 503, 'char_end': 506, 'chars': 'cur'}, {'char_start': 507, 'char_end': 518, 'chars': 'or.execute('}, {'char_start': 562, 'char_end': 563, 'chars': 's'}, {'char_start': 565, 'char_end': 566, 'chars': ','}, {'char_start': 574, 'char_end': 575, 'chars': ','}]}",github.com/ulyssetsd/bjtu-sql/commit/17d7b21864b72ba5666f15236474a93268b32ec9,flaskr/flaskr/views/comment.py,cwe-089,219 cwe-125,Get8BIMProperty,"static MagickBooleanType Get8BIMProperty(const Image *image,const char *key, ExceptionInfo *exception) { char *attribute, format[MagickPathExtent], name[MagickPathExtent], *resource; const StringInfo *profile; const unsigned char *info; long start, stop; MagickBooleanType status; register ssize_t i; size_t length; ssize_t count, id, sub_number; /* There are no newlines in path names, so it's safe as terminator. */ profile=GetImageProfile(image,""8bim""); if (profile == (StringInfo *) NULL) return(MagickFalse); count=(ssize_t) sscanf(key,""8BIM:%ld,%ld:%1024[^\n]\n%1024[^\n]"",&start,&stop, name,format); if ((count != 2) && (count != 3) && (count != 4)) return(MagickFalse); if (count < 4) (void) CopyMagickString(format,""SVG"",MagickPathExtent); if (count < 3) *name='\0'; sub_number=1; if (*name == '#') sub_number=(ssize_t) StringToLong(&name[1]); sub_number=MagickMax(sub_number,1L); resource=(char *) NULL; status=MagickFalse; length=GetStringInfoLength(profile); info=GetStringInfoDatum(profile); while ((length > 0) && (status == MagickFalse)) { if (ReadPropertyByte(&info,&length) != (unsigned char) '8') continue; if (ReadPropertyByte(&info,&length) != (unsigned char) 'B') continue; if (ReadPropertyByte(&info,&length) != (unsigned char) 'I') continue; if (ReadPropertyByte(&info,&length) != (unsigned char) 'M') continue; id=(ssize_t) ReadPropertyMSBShort(&info,&length); if (id < (ssize_t) start) continue; if (id > (ssize_t) stop) continue; if (resource != (char *) NULL) resource=DestroyString(resource); count=(ssize_t) ReadPropertyByte(&info,&length); if ((count != 0) && ((size_t) count <= length)) { resource=(char *) NULL; if (~((size_t) count) >= (MagickPathExtent-1)) resource=(char *) AcquireQuantumMemory((size_t) count+ MagickPathExtent,sizeof(*resource)); if (resource != (char *) NULL) { for (i=0; i < (ssize_t) count; i++) resource[i]=(char) ReadPropertyByte(&info,&length); resource[count]='\0'; } } if ((count & 0x01) == 0) (void) ReadPropertyByte(&info,&length); count=(ssize_t) ReadPropertyMSBLong(&info,&length); if ((*name != '\0') && (*name != '#')) if ((resource == (char *) NULL) || (LocaleCompare(name,resource) != 0)) { /* No name match, scroll forward and try next. */ info+=count; length-=MagickMin(count,(ssize_t) length); continue; } if ((*name == '#') && (sub_number != 1)) { /* No numbered match, scroll forward and try next. */ sub_number--; info+=count; length-=MagickMin(count,(ssize_t) length); continue; } /* We have the resource of interest. */ attribute=(char *) NULL; if (~((size_t) count) >= (MagickPathExtent-1)) attribute=(char *) AcquireQuantumMemory((size_t) count+MagickPathExtent, sizeof(*attribute)); if (attribute != (char *) NULL) { (void) CopyMagickMemory(attribute,(char *) info,(size_t) count); attribute[count]='\0'; info+=count; length-=MagickMin(count,(ssize_t) length); if ((id <= 1999) || (id >= 2999)) (void) SetImageProperty((Image *) image,key,(const char *) attribute,exception); else { char *path; if (LocaleCompare(format,""svg"") == 0) path=TraceSVGClippath((unsigned char *) attribute,(size_t) count, image->columns,image->rows); else path=TracePSClippath((unsigned char *) attribute,(size_t) count); (void) SetImageProperty((Image *) image,key,(const char *) path, exception); path=DestroyString(path); } attribute=DestroyString(attribute); status=MagickTrue; } } if (resource != (char *) NULL) resource=DestroyString(resource); return(status); }","static MagickBooleanType Get8BIMProperty(const Image *image,const char *key, ExceptionInfo *exception) { char *attribute, format[MagickPathExtent], name[MagickPathExtent], *resource; const StringInfo *profile; const unsigned char *info; long start, stop; MagickBooleanType status; register ssize_t i; size_t length; ssize_t count, id, sub_number; /* There are no newlines in path names, so it's safe as terminator. */ profile=GetImageProfile(image,""8bim""); if (profile == (StringInfo *) NULL) return(MagickFalse); count=(ssize_t) sscanf(key,""8BIM:%ld,%ld:%1024[^\n]\n%1024[^\n]"",&start,&stop, name,format); if ((count != 2) && (count != 3) && (count != 4)) return(MagickFalse); if (count < 4) (void) CopyMagickString(format,""SVG"",MagickPathExtent); if (count < 3) *name='\0'; sub_number=1; if (*name == '#') sub_number=(ssize_t) StringToLong(&name[1]); sub_number=MagickMax(sub_number,1L); resource=(char *) NULL; status=MagickFalse; length=GetStringInfoLength(profile); info=GetStringInfoDatum(profile); while ((length > 0) && (status == MagickFalse)) { if (ReadPropertyByte(&info,&length) != (unsigned char) '8') continue; if (ReadPropertyByte(&info,&length) != (unsigned char) 'B') continue; if (ReadPropertyByte(&info,&length) != (unsigned char) 'I') continue; if (ReadPropertyByte(&info,&length) != (unsigned char) 'M') continue; id=(ssize_t) ReadPropertyMSBShort(&info,&length); if (id < (ssize_t) start) continue; if (id > (ssize_t) stop) continue; if (resource != (char *) NULL) resource=DestroyString(resource); count=(ssize_t) ReadPropertyByte(&info,&length); if ((count != 0) && ((size_t) count <= length)) { resource=(char *) NULL; if (~((size_t) count) >= (MagickPathExtent-1)) resource=(char *) AcquireQuantumMemory((size_t) count+ MagickPathExtent,sizeof(*resource)); if (resource != (char *) NULL) { for (i=0; i < (ssize_t) count; i++) resource[i]=(char) ReadPropertyByte(&info,&length); resource[count]='\0'; } } if ((count & 0x01) == 0) (void) ReadPropertyByte(&info,&length); count=(ssize_t) ReadPropertyMSBLong(&info,&length); if ((count < 0) || ((size_t) count > length)) { length=0; continue; } if ((*name != '\0') && (*name != '#')) if ((resource == (char *) NULL) || (LocaleCompare(name,resource) != 0)) { /* No name match, scroll forward and try next. */ info+=count; length-=MagickMin(count,(ssize_t) length); continue; } if ((*name == '#') && (sub_number != 1)) { /* No numbered match, scroll forward and try next. */ sub_number--; info+=count; length-=MagickMin(count,(ssize_t) length); continue; } /* We have the resource of interest. */ attribute=(char *) NULL; if (~((size_t) count) >= (MagickPathExtent-1)) attribute=(char *) AcquireQuantumMemory((size_t) count+MagickPathExtent, sizeof(*attribute)); if (attribute != (char *) NULL) { (void) CopyMagickMemory(attribute,(char *) info,(size_t) count); attribute[count]='\0'; info+=count; length-=MagickMin(count,(ssize_t) length); if ((id <= 1999) || (id >= 2999)) (void) SetImageProperty((Image *) image,key,(const char *) attribute,exception); else { char *path; if (LocaleCompare(format,""svg"") == 0) path=TraceSVGClippath((unsigned char *) attribute,(size_t) count, image->columns,image->rows); else path=TracePSClippath((unsigned char *) attribute,(size_t) count); (void) SetImageProperty((Image *) image,key,(const char *) path, exception); path=DestroyString(path); } attribute=DestroyString(attribute); status=MagickTrue; } } if (resource != (char *) NULL) resource=DestroyString(resource); return(status); }","{'deleted': [], 'added': [{'line_no': 90, 'char_start': 2403, 'char_end': 2453, 'line': ' if ((count < 0) || ((size_t) count > length))\n'}, {'line_no': 91, 'char_start': 2453, 'char_end': 2461, 'line': ' {\n'}, {'line_no': 92, 'char_start': 2461, 'char_end': 2480, 'line': ' length=0; \n'}, {'line_no': 93, 'char_start': 2480, 'char_end': 2498, 'line': ' continue;\n'}, {'line_no': 94, 'char_start': 2498, 'char_end': 2506, 'line': ' }\n'}]}","{'deleted': [], 'added': [{'char_start': 2412, 'char_end': 2515, 'chars': 'count < 0) || ((size_t) count > length))\n {\n length=0; \n continue;\n }\n if (('}]}",github.com/ImageMagick/ImageMagick/commit/dd84447b63a71fa8c3f47071b09454efc667767b,MagickCore/property.c,cwe-125,1133 cwe-125,SpliceImage,"MagickExport Image *SpliceImage(const Image *image, const RectangleInfo *geometry,ExceptionInfo *exception) { #define SpliceImageTag ""Splice/Image"" CacheView *image_view, *splice_view; Image *splice_image; MagickBooleanType status; MagickOffsetType progress; RectangleInfo splice_geometry; ssize_t y; /* Allocate splice image. */ assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),""%s"",image->filename); assert(geometry != (const RectangleInfo *) NULL); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); splice_geometry=(*geometry); splice_image=CloneImage(image,image->columns+splice_geometry.width, image->rows+splice_geometry.height,MagickTrue,exception); if (splice_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(splice_image,DirectClass,exception) == MagickFalse) { splice_image=DestroyImage(splice_image); return((Image *) NULL); } if ((IsPixelInfoGray(&splice_image->background_color) == MagickFalse) && (IsGrayColorspace(splice_image->colorspace) != MagickFalse)) (void) SetImageColorspace(splice_image,sRGBColorspace,exception); if ((splice_image->background_color.alpha_trait != UndefinedPixelTrait) && (splice_image->alpha_trait == UndefinedPixelTrait)) (void) SetImageAlpha(splice_image,OpaqueAlpha,exception); (void) SetImageBackgroundColor(splice_image,exception); /* Respect image geometry. */ switch (image->gravity) { default: case UndefinedGravity: case NorthWestGravity: break; case NorthGravity: { splice_geometry.x+=(ssize_t) splice_geometry.width/2; break; } case NorthEastGravity: { splice_geometry.x+=(ssize_t) splice_geometry.width; break; } case WestGravity: { splice_geometry.y+=(ssize_t) splice_geometry.width/2; break; } case CenterGravity: { splice_geometry.x+=(ssize_t) splice_geometry.width/2; splice_geometry.y+=(ssize_t) splice_geometry.height/2; break; } case EastGravity: { splice_geometry.x+=(ssize_t) splice_geometry.width; splice_geometry.y+=(ssize_t) splice_geometry.height/2; break; } case SouthWestGravity: { splice_geometry.y+=(ssize_t) splice_geometry.height; break; } case SouthGravity: { splice_geometry.x+=(ssize_t) splice_geometry.width/2; splice_geometry.y+=(ssize_t) splice_geometry.height; break; } case SouthEastGravity: { splice_geometry.x+=(ssize_t) splice_geometry.width; splice_geometry.y+=(ssize_t) splice_geometry.height; break; } } /* Splice image. */ status=MagickTrue; progress=0; image_view=AcquireVirtualCacheView(image,exception); splice_view=AcquireAuthenticCacheView(splice_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(image,splice_image,1,1) #endif for (y=0; y < (ssize_t) splice_geometry.y; y++) { register const Quantum *restrict p; register ssize_t x; register Quantum *restrict q; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); q=QueueCacheViewAuthenticPixels(splice_view,0,y,splice_image->columns,1, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < splice_geometry.x; x++) { register ssize_t i; if (GetPixelReadMask(image,p) == 0) { SetPixelBackgoundColor(splice_image,q); p+=GetPixelChannels(image); q+=GetPixelChannels(splice_image); continue; } for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel=GetPixelChannelChannel(image,i); PixelTrait traits=GetPixelChannelTraits(image,channel); PixelTrait splice_traits=GetPixelChannelTraits(splice_image,channel); if ((traits == UndefinedPixelTrait) || (splice_traits == UndefinedPixelTrait)) continue; SetPixelChannel(splice_image,channel,p[i],q); } SetPixelRed(splice_image,GetPixelRed(image,p),q); SetPixelGreen(splice_image,GetPixelGreen(image,p),q); SetPixelBlue(splice_image,GetPixelBlue(image,p),q); SetPixelAlpha(splice_image,GetPixelAlpha(image,p),q); p+=GetPixelChannels(image); q+=GetPixelChannels(splice_image); } for ( ; x < (ssize_t) (splice_geometry.x+splice_geometry.width); x++) q+=GetPixelChannels(splice_image); for ( ; x < (ssize_t) splice_image->columns; x++) { register ssize_t i; if (GetPixelReadMask(image,p) == 0) { SetPixelBackgoundColor(splice_image,q); p+=GetPixelChannels(image); q+=GetPixelChannels(splice_image); continue; } for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel=GetPixelChannelChannel(image,i); PixelTrait traits=GetPixelChannelTraits(image,channel); PixelTrait splice_traits=GetPixelChannelTraits(splice_image,channel); if ((traits == UndefinedPixelTrait) || (splice_traits == UndefinedPixelTrait)) continue; SetPixelChannel(splice_image,channel,p[i],q); } SetPixelRed(splice_image,GetPixelRed(image,p),q); SetPixelGreen(splice_image,GetPixelGreen(image,p),q); SetPixelBlue(splice_image,GetPixelBlue(image,p),q); SetPixelAlpha(splice_image,GetPixelAlpha(image,p),q); p+=GetPixelChannels(image); q+=GetPixelChannels(splice_image); } if (SyncCacheViewAuthenticPixels(splice_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_TransposeImage) #endif proceed=SetImageProgress(image,SpliceImageTag,progress++, splice_image->rows); if (proceed == MagickFalse) status=MagickFalse; } } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(image,splice_image,1,1) #endif for (y=(ssize_t) (splice_geometry.y+splice_geometry.height); y < (ssize_t) splice_image->rows; y++) { register const Quantum *restrict p; register ssize_t x; register Quantum *restrict q; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y-(ssize_t) splice_geometry.height, image->columns,1,exception); if ((y < 0) || (y >= (ssize_t) splice_image->rows)) continue; q=QueueCacheViewAuthenticPixels(splice_view,0,y,splice_image->columns,1, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < splice_geometry.x; x++) { register ssize_t i; if (GetPixelReadMask(image,q) == 0) { SetPixelBackgoundColor(splice_image,q); p+=GetPixelChannels(image); q+=GetPixelChannels(splice_image); continue; } for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel=GetPixelChannelChannel(image,i); PixelTrait traits=GetPixelChannelTraits(image,channel); PixelTrait splice_traits=GetPixelChannelTraits(splice_image,channel); if ((traits == UndefinedPixelTrait) || (splice_traits == UndefinedPixelTrait)) continue; SetPixelChannel(splice_image,channel,p[i],q); } SetPixelRed(splice_image,GetPixelRed(image,p),q); SetPixelGreen(splice_image,GetPixelGreen(image,p),q); SetPixelBlue(splice_image,GetPixelBlue(image,p),q); SetPixelAlpha(splice_image,GetPixelAlpha(image,p),q); p+=GetPixelChannels(image); q+=GetPixelChannels(splice_image); } for ( ; x < (ssize_t) (splice_geometry.x+splice_geometry.width); x++) q+=GetPixelChannels(splice_image); for ( ; x < (ssize_t) splice_image->columns; x++) { register ssize_t i; if (GetPixelReadMask(image,q) == 0) { SetPixelBackgoundColor(splice_image,q); p+=GetPixelChannels(image); q+=GetPixelChannels(splice_image); continue; } for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel=GetPixelChannelChannel(image,i); PixelTrait traits=GetPixelChannelTraits(image,channel); PixelTrait splice_traits=GetPixelChannelTraits(splice_image,channel); if ((traits == UndefinedPixelTrait) || (splice_traits == UndefinedPixelTrait)) continue; SetPixelChannel(splice_image,channel,p[i],q); } SetPixelRed(splice_image,GetPixelRed(image,p),q); SetPixelGreen(splice_image,GetPixelGreen(image,p),q); SetPixelBlue(splice_image,GetPixelBlue(image,p),q); SetPixelAlpha(splice_image,GetPixelAlpha(image,p),q); p+=GetPixelChannels(image); q+=GetPixelChannels(splice_image); } if (SyncCacheViewAuthenticPixels(splice_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_TransposeImage) #endif proceed=SetImageProgress(image,SpliceImageTag,progress++, splice_image->rows); if (proceed == MagickFalse) status=MagickFalse; } } splice_view=DestroyCacheView(splice_view); image_view=DestroyCacheView(image_view); if (status == MagickFalse) splice_image=DestroyImage(splice_image); return(splice_image); }","MagickExport Image *SpliceImage(const Image *image, const RectangleInfo *geometry,ExceptionInfo *exception) { #define SpliceImageTag ""Splice/Image"" CacheView *image_view, *splice_view; Image *splice_image; MagickBooleanType status; MagickOffsetType progress; RectangleInfo splice_geometry; ssize_t columns, y; /* Allocate splice image. */ assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),""%s"",image->filename); assert(geometry != (const RectangleInfo *) NULL); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); splice_geometry=(*geometry); splice_image=CloneImage(image,image->columns+splice_geometry.width, image->rows+splice_geometry.height,MagickTrue,exception); if (splice_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(splice_image,DirectClass,exception) == MagickFalse) { splice_image=DestroyImage(splice_image); return((Image *) NULL); } if ((IsPixelInfoGray(&splice_image->background_color) == MagickFalse) && (IsGrayColorspace(splice_image->colorspace) != MagickFalse)) (void) SetImageColorspace(splice_image,sRGBColorspace,exception); if ((splice_image->background_color.alpha_trait != UndefinedPixelTrait) && (splice_image->alpha_trait == UndefinedPixelTrait)) (void) SetImageAlpha(splice_image,OpaqueAlpha,exception); (void) SetImageBackgroundColor(splice_image,exception); /* Respect image geometry. */ switch (image->gravity) { default: case UndefinedGravity: case NorthWestGravity: break; case NorthGravity: { splice_geometry.x+=(ssize_t) splice_geometry.width/2; break; } case NorthEastGravity: { splice_geometry.x+=(ssize_t) splice_geometry.width; break; } case WestGravity: { splice_geometry.y+=(ssize_t) splice_geometry.width/2; break; } case CenterGravity: { splice_geometry.x+=(ssize_t) splice_geometry.width/2; splice_geometry.y+=(ssize_t) splice_geometry.height/2; break; } case EastGravity: { splice_geometry.x+=(ssize_t) splice_geometry.width; splice_geometry.y+=(ssize_t) splice_geometry.height/2; break; } case SouthWestGravity: { splice_geometry.y+=(ssize_t) splice_geometry.height; break; } case SouthGravity: { splice_geometry.x+=(ssize_t) splice_geometry.width/2; splice_geometry.y+=(ssize_t) splice_geometry.height; break; } case SouthEastGravity: { splice_geometry.x+=(ssize_t) splice_geometry.width; splice_geometry.y+=(ssize_t) splice_geometry.height; break; } } /* Splice image. */ status=MagickTrue; progress=0; columns=MagickMin(splice_geometry.x,(ssize_t) splice_image->columns); image_view=AcquireVirtualCacheView(image,exception); splice_view=AcquireAuthenticCacheView(splice_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(image,splice_image,1,1) #endif for (y=0; y < (ssize_t) splice_geometry.y; y++) { register const Quantum *restrict p; register ssize_t x; register Quantum *restrict q; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,splice_image->columns,1, exception); q=QueueCacheViewAuthenticPixels(splice_view,0,y,splice_image->columns,1, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < columns; x++) { register ssize_t i; if (GetPixelReadMask(image,p) == 0) { SetPixelBackgoundColor(splice_image,q); p+=GetPixelChannels(image); q+=GetPixelChannels(splice_image); continue; } for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel=GetPixelChannelChannel(image,i); PixelTrait traits=GetPixelChannelTraits(image,channel); PixelTrait splice_traits=GetPixelChannelTraits(splice_image,channel); if ((traits == UndefinedPixelTrait) || (splice_traits == UndefinedPixelTrait)) continue; SetPixelChannel(splice_image,channel,p[i],q); } SetPixelRed(splice_image,GetPixelRed(image,p),q); SetPixelGreen(splice_image,GetPixelGreen(image,p),q); SetPixelBlue(splice_image,GetPixelBlue(image,p),q); SetPixelAlpha(splice_image,GetPixelAlpha(image,p),q); p+=GetPixelChannels(image); q+=GetPixelChannels(splice_image); } for ( ; x < (ssize_t) (splice_geometry.x+splice_geometry.width); x++) q+=GetPixelChannels(splice_image); for ( ; x < (ssize_t) splice_image->columns; x++) { register ssize_t i; if (GetPixelReadMask(image,p) == 0) { SetPixelBackgoundColor(splice_image,q); p+=GetPixelChannels(image); q+=GetPixelChannels(splice_image); continue; } for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel=GetPixelChannelChannel(image,i); PixelTrait traits=GetPixelChannelTraits(image,channel); PixelTrait splice_traits=GetPixelChannelTraits(splice_image,channel); if ((traits == UndefinedPixelTrait) || (splice_traits == UndefinedPixelTrait)) continue; SetPixelChannel(splice_image,channel,p[i],q); } SetPixelRed(splice_image,GetPixelRed(image,p),q); SetPixelGreen(splice_image,GetPixelGreen(image,p),q); SetPixelBlue(splice_image,GetPixelBlue(image,p),q); SetPixelAlpha(splice_image,GetPixelAlpha(image,p),q); p+=GetPixelChannels(image); q+=GetPixelChannels(splice_image); } if (SyncCacheViewAuthenticPixels(splice_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_TransposeImage) #endif proceed=SetImageProgress(image,SpliceImageTag,progress++, splice_image->rows); if (proceed == MagickFalse) status=MagickFalse; } } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(image,splice_image,1,1) #endif for (y=(ssize_t) (splice_geometry.y+splice_geometry.height); y < (ssize_t) splice_image->rows; y++) { register const Quantum *restrict p; register ssize_t x; register Quantum *restrict q; if (status == MagickFalse) continue; if ((y < 0) || (y >= (ssize_t)splice_image->rows)) continue; p=GetCacheViewVirtualPixels(image_view,0,y-(ssize_t) splice_geometry.height, splice_image->columns,1,exception); q=QueueCacheViewAuthenticPixels(splice_view,0,y,splice_image->columns,1, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < columns; x++) { register ssize_t i; if (GetPixelReadMask(image,q) == 0) { SetPixelBackgoundColor(splice_image,q); p+=GetPixelChannels(image); q+=GetPixelChannels(splice_image); continue; } for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel=GetPixelChannelChannel(image,i); PixelTrait traits=GetPixelChannelTraits(image,channel); PixelTrait splice_traits=GetPixelChannelTraits(splice_image,channel); if ((traits == UndefinedPixelTrait) || (splice_traits == UndefinedPixelTrait)) continue; SetPixelChannel(splice_image,channel,p[i],q); } SetPixelRed(splice_image,GetPixelRed(image,p),q); SetPixelGreen(splice_image,GetPixelGreen(image,p),q); SetPixelBlue(splice_image,GetPixelBlue(image,p),q); SetPixelAlpha(splice_image,GetPixelAlpha(image,p),q); p+=GetPixelChannels(image); q+=GetPixelChannels(splice_image); } for ( ; x < (ssize_t) (splice_geometry.x+splice_geometry.width); x++) q+=GetPixelChannels(splice_image); for ( ; x < (ssize_t) splice_image->columns; x++) { register ssize_t i; if (GetPixelReadMask(image,q) == 0) { SetPixelBackgoundColor(splice_image,q); p+=GetPixelChannels(image); q+=GetPixelChannels(splice_image); continue; } for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel=GetPixelChannelChannel(image,i); PixelTrait traits=GetPixelChannelTraits(image,channel); PixelTrait splice_traits=GetPixelChannelTraits(splice_image,channel); if ((traits == UndefinedPixelTrait) || (splice_traits == UndefinedPixelTrait)) continue; SetPixelChannel(splice_image,channel,p[i],q); } SetPixelRed(splice_image,GetPixelRed(image,p),q); SetPixelGreen(splice_image,GetPixelGreen(image,p),q); SetPixelBlue(splice_image,GetPixelBlue(image,p),q); SetPixelAlpha(splice_image,GetPixelAlpha(image,p),q); p+=GetPixelChannels(image); q+=GetPixelChannels(splice_image); } if (SyncCacheViewAuthenticPixels(splice_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_TransposeImage) #endif proceed=SetImageProgress(image,SpliceImageTag,progress++, splice_image->rows); if (proceed == MagickFalse) status=MagickFalse; } } splice_view=DestroyCacheView(splice_view); image_view=DestroyCacheView(image_view); if (status == MagickFalse) splice_image=DestroyImage(splice_image); return(splice_image); }","{'deleted': [{'line_no': 130, 'char_start': 3435, 'char_end': 3511, 'line': ' p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);\n'}, {'line_no': 138, 'char_start': 3734, 'char_end': 3776, 'line': ' for (x=0; x < splice_geometry.x; x++)\n'}, {'line_no': 232, 'char_start': 6932, 'char_end': 7013, 'line': ' p=GetCacheViewVirtualPixels(image_view,0,y-(ssize_t) splice_geometry.height,\n'}, {'line_no': 233, 'char_start': 7013, 'char_end': 7048, 'line': ' image->columns,1,exception);\n'}, {'line_no': 234, 'char_start': 7048, 'char_end': 7104, 'line': ' if ((y < 0) || (y >= (ssize_t) splice_image->rows))\n'}, {'line_no': 243, 'char_start': 7343, 'char_end': 7385, 'line': ' for (x=0; x < splice_geometry.x; x++)\n'}], 'added': [{'line_no': 23, 'char_start': 343, 'char_end': 356, 'line': ' columns,\n'}, {'line_no': 112, 'char_start': 2947, 'char_end': 3019, 'line': ' columns=MagickMin(splice_geometry.x,(ssize_t) splice_image->columns);\n'}, {'line_no': 132, 'char_start': 3520, 'char_end': 3592, 'line': ' p=GetCacheViewVirtualPixels(image_view,0,y,splice_image->columns,1,\n'}, {'line_no': 133, 'char_start': 3592, 'char_end': 3610, 'line': ' exception);\n'}, {'line_no': 141, 'char_start': 3833, 'char_end': 3865, 'line': ' for (x=0; x < columns; x++)\n'}, {'line_no': 235, 'char_start': 7021, 'char_end': 7076, 'line': ' if ((y < 0) || (y >= (ssize_t)splice_image->rows))\n'}, {'line_no': 237, 'char_start': 7092, 'char_end': 7173, 'line': ' p=GetCacheViewVirtualPixels(image_view,0,y-(ssize_t) splice_geometry.height,\n'}, {'line_no': 238, 'char_start': 7173, 'char_end': 7215, 'line': ' splice_image->columns,1,exception);\n'}, {'line_no': 246, 'char_start': 7438, 'char_end': 7470, 'line': ' for (x=0; x < columns; x++)\n'}]}","{'deleted': [{'char_start': 3752, 'char_end': 3756, 'chars': 'spli'}, {'char_start': 3757, 'char_end': 3761, 'chars': 'e_ge'}, {'char_start': 3763, 'char_end': 3769, 'chars': 'etry.x'}, {'char_start': 7046, 'char_end': 7118, 'chars': ';\n if ((y < 0) || (y >= (ssize_t) splice_image->rows))\n continue'}, {'char_start': 7361, 'char_end': 7365, 'chars': 'spli'}, {'char_start': 7366, 'char_end': 7370, 'chars': 'e_ge'}, {'char_start': 7372, 'char_end': 7378, 'chars': 'etry.x'}], 'added': [{'char_start': 347, 'char_end': 360, 'chars': 'columns,\n '}, {'char_start': 2947, 'char_end': 3019, 'chars': ' columns=MagickMin(splice_geometry.x,(ssize_t) splice_image->columns);\n'}, {'char_start': 3567, 'char_end': 3574, 'chars': 'splice_'}, {'char_start': 3591, 'char_end': 3598, 'chars': '\n '}, {'char_start': 3853, 'char_end': 3855, 'chars': 'lu'}, {'char_start': 3856, 'char_end': 3858, 'chars': 'ns'}, {'char_start': 7021, 'char_end': 7092, 'chars': ' if ((y < 0) || (y >= (ssize_t)splice_image->rows))\n continue;\n'}, {'char_start': 7179, 'char_end': 7186, 'chars': 'splice_'}, {'char_start': 7458, 'char_end': 7460, 'chars': 'lu'}, {'char_start': 7461, 'char_end': 7463, 'chars': 'ns'}]}",github.com/ImageMagick/ImageMagick/commit/7b1cf5784b5bcd85aa9293ecf56769f68c037231,MagickCore/transform.c,cwe-125,2536 cwe-079,respond_error," def respond_error(self, context, exception): context.respond_server_error() stack = traceback.format_exc() return """"""

Server error

%s
                
"""""" % stack"," def respond_error(self, context, exception): context.respond_server_error() stack = traceback.format_exc() return """"""

Server error

%s
                
"""""" % cgi.escape(stack)","{'deleted': [{'line_no': 33, 'char_start': 871, 'char_end': 890, 'line': ' """""" % stack\n'}], 'added': [{'line_no': 33, 'char_start': 871, 'char_end': 902, 'line': ' """""" % cgi.escape(stack)'}]}","{'deleted': [], 'added': [{'char_start': 885, 'char_end': 896, 'chars': 'cgi.escape('}, {'char_start': 901, 'char_end': 902, 'chars': ')'}]}",github.com/Eugeny/ajenti/commit/d3fc5eb142ff16d55d158afb050af18d5ff09120,ajenti/routing.py,cwe-079,153 cwe-125,java_switch_op,"static int java_switch_op(RAnal *anal, RAnalOp *op, ut64 addr, const ut8 *data, int len) { ut8 op_byte = data[0]; ut64 offset = addr - java_get_method_start (); ut8 pos = (offset+1)%4 ? 1 + 4 - (offset+1)%4 : 1; if (op_byte == 0xaa) { // handle a table switch condition if (pos + 8 > len) { return op->size; } int min_val = (ut32)(UINT (data, pos + 4)), max_val = (ut32)(UINT (data, pos + 8)); ut32 default_loc = (ut32) (UINT (data, pos)), cur_case = 0; op->switch_op = r_anal_switch_op_new (addr, min_val, default_loc); RAnalCaseOp *caseop = NULL; pos += 12; if (max_val > min_val && ((max_val - min_val)<(UT16_MAX/4))) { //caseop = r_anal_switch_op_add_case(op->switch_op, addr+default_loc, -1, addr+offset); for (cur_case = 0; cur_case <= max_val - min_val; pos += 4, cur_case++) { //ut32 value = (ut32)(UINT (data, pos)); if (pos + 4 >= len) { // switch is too big cant read further break; } int offset = (int)(ut32)(R_BIN_JAVA_UINT (data, pos)); caseop = r_anal_switch_op_add_case (op->switch_op, addr + pos, cur_case + min_val, addr + offset); if (caseop) { caseop->bb_ref_to = addr+offset; caseop->bb_ref_from = addr; // TODO figure this one out } } } else { eprintf (""Invalid switch boundaries at 0x%""PFMT64x""\n"", addr); } } op->size = pos; return op->size; }","static int java_switch_op(RAnal *anal, RAnalOp *op, ut64 addr, const ut8 *data, int len) { ut8 op_byte = data[0]; ut64 offset = addr - java_get_method_start (); ut8 pos = (offset+1)%4 ? 1 + 4 - (offset+1)%4 : 1; if (op_byte == 0xaa) { // handle a table switch condition if (pos + 8 + 8 > len) { return op->size; } const int min_val = (ut32)(UINT (data, pos + 4)); const int max_val = (ut32)(UINT (data, pos + 8)); ut32 default_loc = (ut32) (UINT (data, pos)), cur_case = 0; op->switch_op = r_anal_switch_op_new (addr, min_val, default_loc); RAnalCaseOp *caseop = NULL; pos += 12; if (max_val > min_val && ((max_val - min_val)<(UT16_MAX/4))) { //caseop = r_anal_switch_op_add_case(op->switch_op, addr+default_loc, -1, addr+offset); for (cur_case = 0; cur_case <= max_val - min_val; pos += 4, cur_case++) { //ut32 value = (ut32)(UINT (data, pos)); if (pos + 4 >= len) { // switch is too big cant read further break; } int offset = (int)(ut32)(R_BIN_JAVA_UINT (data, pos)); caseop = r_anal_switch_op_add_case (op->switch_op, addr + pos, cur_case + min_val, addr + offset); if (caseop) { caseop->bb_ref_to = addr+offset; caseop->bb_ref_from = addr; // TODO figure this one out } } } else { eprintf (""Invalid switch boundaries at 0x%""PFMT64x""\n"", addr); } } op->size = pos; return op->size; }","{'deleted': [{'line_no': 8, 'char_start': 277, 'char_end': 300, 'line': '\t\tif (pos + 8 > len) {\n'}, {'line_no': 11, 'char_start': 324, 'char_end': 370, 'line': '\t\tint min_val = (ut32)(UINT (data, pos + 4)),\n'}, {'line_no': 12, 'char_start': 370, 'char_end': 413, 'line': '\t\t\tmax_val = (ut32)(UINT (data, pos + 8));\n'}], 'added': [{'line_no': 8, 'char_start': 277, 'char_end': 304, 'line': '\t\tif (pos + 8 + 8 > len) {\n'}, {'line_no': 11, 'char_start': 328, 'char_end': 380, 'line': '\t\tconst int min_val = (ut32)(UINT (data, pos + 4));\n'}, {'line_no': 12, 'char_start': 380, 'char_end': 432, 'line': '\t\tconst int max_val = (ut32)(UINT (data, pos + 8));\n'}]}","{'deleted': [{'char_start': 368, 'char_end': 369, 'chars': ','}, {'char_start': 372, 'char_end': 373, 'chars': '\t'}], 'added': [{'char_start': 291, 'char_end': 295, 'chars': '+ 8 '}, {'char_start': 330, 'char_end': 336, 'chars': 'const '}, {'char_start': 378, 'char_end': 379, 'chars': ';'}, {'char_start': 382, 'char_end': 392, 'chars': 'const int '}]}",github.com/radare/radare2/commit/224e6bc13fa353dd3b7f7a2334588f1c4229e58d,libr/anal/p/anal_java.c,cwe-125,489 cwe-416,get_task_ioprio,"static int get_task_ioprio(struct task_struct *p) { int ret; ret = security_task_getioprio(p); if (ret) goto out; ret = IOPRIO_PRIO_VALUE(IOPRIO_CLASS_NONE, IOPRIO_NORM); if (p->io_context) ret = p->io_context->ioprio; out: return ret; }","static int get_task_ioprio(struct task_struct *p) { int ret; ret = security_task_getioprio(p); if (ret) goto out; ret = IOPRIO_PRIO_VALUE(IOPRIO_CLASS_NONE, IOPRIO_NORM); task_lock(p); if (p->io_context) ret = p->io_context->ioprio; task_unlock(p); out: return ret; }","{'deleted': [], 'added': [{'line_no': 9, 'char_start': 178, 'char_end': 193, 'line': '\ttask_lock(p);\n'}, {'line_no': 12, 'char_start': 244, 'char_end': 261, 'line': '\ttask_unlock(p);\n'}]}","{'deleted': [], 'added': [{'char_start': 179, 'char_end': 194, 'chars': 'task_lock(p);\n\t'}, {'char_start': 242, 'char_end': 259, 'chars': ';\n\ttask_unlock(p)'}]}",github.com/torvalds/linux/commit/8ba8682107ee2ca3347354e018865d8e1967c5f4,block/ioprio.c,cwe-416,83 cwe-125,_6502_op,"static int _6502_op(RAnal *anal, RAnalOp *op, ut64 addr, const ut8 *data, int len) { char addrbuf[64]; const int buffsize = sizeof (addrbuf) - 1; memset (op, '\0', sizeof (RAnalOp)); op->size = snes_op_get_size (1, 1, &snes_op[data[0]]); //snes-arch is similiar to nes/6502 op->addr = addr; op->type = R_ANAL_OP_TYPE_UNK; op->id = data[0]; r_strbuf_init (&op->esil); switch (data[0]) { case 0x02: case 0x03: case 0x04: case 0x07: case 0x0b: case 0x0c: case 0x0f: case 0x12: case 0x13: case 0x14: case 0x17: case 0x1a: case 0x1b: case 0x1c: case 0x1f: case 0x22: case 0x23: case 0x27: case 0x2b: case 0x2f: case 0x32: case 0x33: case 0x34: case 0x37: case 0x3a: case 0x3b: case 0x3c: case 0x3f: case 0x42: case 0x43: case 0x44: case 0x47: case 0x4b: case 0x4f: case 0x52: case 0x53: case 0x54: case 0x57: case 0x5a: case 0x5b: case 0x5c: case 0x5f: case 0x62: case 0x63: case 0x64: case 0x67: case 0x6b: case 0x6f: case 0x72: case 0x73: case 0x74: case 0x77: case 0x7a: case 0x7b: case 0x7c: case 0x7f: case 0x80: case 0x82: case 0x83: case 0x87: case 0x89: case 0x8b: case 0x8f: case 0x92: case 0x93: case 0x97: case 0x9b: case 0x9c: case 0x9e: case 0x9f: case 0xa3: case 0xa7: case 0xab: case 0xaf: case 0xb2: case 0xb3: case 0xb7: case 0xbb: case 0xbf: case 0xc2: case 0xc3: case 0xc7: case 0xcb: case 0xcf: case 0xd2: case 0xd3: case 0xd4: case 0xd7: case 0xda: case 0xdb: case 0xdc: case 0xdf: case 0xe2: case 0xe3: case 0xe7: case 0xeb: case 0xef: case 0xf2: case 0xf3: case 0xf4: case 0xf7: case 0xfa: case 0xfb: case 0xfc: case 0xff: // undocumented or not-implemented opcodes for 6502. // some of them might be implemented in 65816 op->size = 1; op->type = R_ANAL_OP_TYPE_ILL; break; // BRK case 0x00: // brk op->cycles = 7; op->type = R_ANAL_OP_TYPE_SWI; // override 65816 code which seems to be wrong: size is 1, but pc = pc + 2 op->size = 1; // PC + 2 to Stack, P to Stack B=1 D=0 I=1. ""B"" is not a flag. Only its bit is pushed on the stack // PC was already incremented by one at this point. Needs to incremented once more // New PC is Interrupt Vector: $fffe. (FIXME: Confirm this is valid for all 6502) r_strbuf_set (&op->esil, "",1,I,=,0,D,=,flags,0x10,|,0x100,sp,+,=[1],pc,1,+,0xfe,sp,+,=[2],3,sp,-=,0xfffe,[2],pc,=""); break; // FLAGS case 0x78: // sei case 0x58: // cli case 0x38: // sec case 0x18: // clc case 0xf8: // sed case 0xd8: // cld case 0xb8: // clv op->cycles = 2; // FIXME: what opcode for this? op->type = R_ANAL_OP_TYPE_NOP; _6502_anal_esil_flags (op, data[0]); break; // BIT case 0x24: // bit $ff case 0x2c: // bit $ffff op->type = R_ANAL_OP_TYPE_MOV; _6502_anal_esil_get_addr_pattern3 (op, data, addrbuf, buffsize, 0); r_strbuf_setf (&op->esil, ""a,%s,[1],&,0x80,&,!,!,N,=,a,%s,[1],&,0x40,&,!,!,V,=,a,%s,[1],&,0xff,&,!,Z,="",addrbuf, addrbuf, addrbuf); break; // ADC case 0x69: // adc #$ff case 0x65: // adc $ff case 0x75: // adc $ff,x case 0x6d: // adc $ffff case 0x7d: // adc $ffff,x case 0x79: // adc $ffff,y case 0x61: // adc ($ff,x) case 0x71: // adc ($ff,y) // FIXME: update V // FIXME: support BCD mode op->type = R_ANAL_OP_TYPE_ADD; _6502_anal_esil_get_addr_pattern1 (op, data, addrbuf, buffsize); if (data[0] == 0x69) // immediate mode r_strbuf_setf (&op->esil, ""%s,a,+=,C,NUM,$c7,C,=,a,+=,$c7,C,|="", addrbuf); else r_strbuf_setf (&op->esil, ""%s,[1],a,+=,C,NUM,$c7,C,=,a,+=,$c7,C,|="", addrbuf); _6502_anal_update_flags (op, _6502_FLAGS_NZ); // fix Z r_strbuf_append (&op->esil, "",a,a,=,$z,Z,=""); break; // SBC case 0xe9: // sbc #$ff case 0xe5: // sbc $ff case 0xf5: // sbc $ff,x case 0xed: // sbc $ffff case 0xfd: // sbc $ffff,x case 0xf9: // sbc $ffff,y case 0xe1: // sbc ($ff,x) case 0xf1: // sbc ($ff,y) // FIXME: update V // FIXME: support BCD mode op->type = R_ANAL_OP_TYPE_SUB; _6502_anal_esil_get_addr_pattern1 (op, data, addrbuf, buffsize); if (data[0] == 0xe9) // immediate mode r_strbuf_setf (&op->esil, ""C,!,%s,+,a,-="", addrbuf); else r_strbuf_setf (&op->esil, ""C,!,%s,[1],+,a,-="", addrbuf); _6502_anal_update_flags (op, _6502_FLAGS_BNZ); // fix Z and revert C r_strbuf_append (&op->esil, "",a,a,=,$z,Z,=,C,!=""); break; // ORA case 0x09: // ora #$ff case 0x05: // ora $ff case 0x15: // ora $ff,x case 0x0d: // ora $ffff case 0x1d: // ora $ffff,x case 0x19: // ora $ffff,y case 0x01: // ora ($ff,x) case 0x11: // ora ($ff),y op->type = R_ANAL_OP_TYPE_OR; _6502_anal_esil_get_addr_pattern1 (op, data, addrbuf, buffsize); if (data[0] == 0x09) // immediate mode r_strbuf_setf (&op->esil, ""%s,a,|="", addrbuf); else r_strbuf_setf (&op->esil, ""%s,[1],a,|="", addrbuf); _6502_anal_update_flags (op, _6502_FLAGS_NZ); break; // AND case 0x29: // and #$ff case 0x25: // and $ff case 0x35: // and $ff,x case 0x2d: // and $ffff case 0x3d: // and $ffff,x case 0x39: // and $ffff,y case 0x21: // and ($ff,x) case 0x31: // and ($ff),y op->type = R_ANAL_OP_TYPE_AND; _6502_anal_esil_get_addr_pattern1 (op, data, addrbuf, buffsize); if (data[0] == 0x29) // immediate mode r_strbuf_setf (&op->esil, ""%s,a,&="", addrbuf); else r_strbuf_setf (&op->esil, ""%s,[1],a,&="", addrbuf); _6502_anal_update_flags (op, _6502_FLAGS_NZ); break; // EOR case 0x49: // eor #$ff case 0x45: // eor $ff case 0x55: // eor $ff,x case 0x4d: // eor $ffff case 0x5d: // eor $ffff,x case 0x59: // eor $ffff,y case 0x41: // eor ($ff,x) case 0x51: // eor ($ff),y op->type = R_ANAL_OP_TYPE_XOR; _6502_anal_esil_get_addr_pattern1 (op, data, addrbuf, buffsize); if (data[0] == 0x49) // immediate mode r_strbuf_setf (&op->esil, ""%s,a,^="", addrbuf); else r_strbuf_setf (&op->esil, ""%s,[1],a,^="", addrbuf); _6502_anal_update_flags (op, _6502_FLAGS_NZ); break; // ASL case 0x0a: // asl a case 0x06: // asl $ff case 0x16: // asl $ff,x case 0x0e: // asl $ffff case 0x1e: // asl $ffff,x op->type = R_ANAL_OP_TYPE_SHL; if (data[0] == 0x0a) { r_strbuf_set (&op->esil, ""1,a,<<=,$c7,C,=,a,a,=""); } else { _6502_anal_esil_get_addr_pattern2 (op, data, addrbuf, buffsize, 'x'); r_strbuf_setf (&op->esil, ""1,%s,[1],<<,%s,=[1],$c7,C,="", addrbuf, addrbuf); } _6502_anal_update_flags (op, _6502_FLAGS_NZ); break; // LSR case 0x4a: // lsr a case 0x46: // lsr $ff case 0x56: // lsr $ff,x case 0x4e: // lsr $ffff case 0x5e: // lsr $ffff,x op->type = R_ANAL_OP_TYPE_SHR; if (data[0] == 0x4a) { r_strbuf_set (&op->esil, ""1,a,&,C,=,1,a,>>=""); } else { _6502_anal_esil_get_addr_pattern2 (op, data, addrbuf, buffsize, 'x'); r_strbuf_setf (&op->esil, ""1,%s,[1],&,C,=,1,%s,[1],>>,%s,=[1]"", addrbuf, addrbuf, addrbuf); } _6502_anal_update_flags (op, _6502_FLAGS_NZ); break; // ROL case 0x2a: // rol a case 0x26: // rol $ff case 0x36: // rol $ff,x case 0x2e: // rol $ffff case 0x3e: // rol $ffff,x op->type = R_ANAL_OP_TYPE_ROL; if (data[0] == 0x2a) { r_strbuf_set (&op->esil, ""1,a,<<,C,|,a,=,$c7,C,=,a,a,=""); } else { _6502_anal_esil_get_addr_pattern2 (op, data, addrbuf, buffsize, 'x'); r_strbuf_setf (&op->esil, ""1,%s,[1],<<,C,|,%s,=[1],$c7,C,="", addrbuf, addrbuf); } _6502_anal_update_flags (op, _6502_FLAGS_NZ); break; // ROR case 0x6a: // ror a case 0x66: // ror $ff case 0x76: // ror $ff,x case 0x6e: // ror $ffff case 0x7e: // ror $ffff,x // uses N as temporary to hold C value. but in fact, // it is not temporary since in all ROR ops, N will have the value of C op->type = R_ANAL_OP_TYPE_ROR; if (data[0] == 0x6a) { r_strbuf_set (&op->esil, ""C,N,=,1,a,&,C,=,1,a,>>,7,N,<<,|,a,=""); } else { _6502_anal_esil_get_addr_pattern2 (op, data, addrbuf, buffsize, 'x'); r_strbuf_setf (&op->esil, ""C,N,=,1,%s,[1],&,C,=,1,%s,[1],>>,7,N,<<,|,%s,=[1]"", addrbuf, addrbuf, addrbuf); } _6502_anal_update_flags (op, _6502_FLAGS_NZ); break; // INC case 0xe6: // inc $ff case 0xf6: // inc $ff,x case 0xee: // inc $ffff case 0xfe: // inc $ffff,x op->type = R_ANAL_OP_TYPE_STORE; _6502_anal_esil_get_addr_pattern2 (op, data, addrbuf, buffsize, 'x'); r_strbuf_setf (&op->esil, ""%s,++=[1]"", addrbuf); _6502_anal_update_flags (op, _6502_FLAGS_NZ); break; // DEC case 0xc6: // dec $ff case 0xd6: // dec $ff,x case 0xce: // dec $ffff case 0xde: // dec $ffff,x op->type = R_ANAL_OP_TYPE_STORE; _6502_anal_esil_get_addr_pattern2 (op, data, addrbuf, buffsize, 'x'); r_strbuf_setf (&op->esil, ""%s,--=[1]"", addrbuf); _6502_anal_update_flags (op, _6502_FLAGS_NZ); break; // INX, INY case 0xe8: // inx case 0xc8: // iny op->cycles = 2; op->type = R_ANAL_OP_TYPE_STORE; _6502_anal_esil_inc_reg (op, data[0], ""+""); break; // DEX, DEY case 0xca: // dex case 0x88: // dey op->cycles = 2; op->type = R_ANAL_OP_TYPE_STORE; _6502_anal_esil_inc_reg (op, data[0], ""-""); break; // CMP case 0xc9: // cmp #$ff case 0xc5: // cmp $ff case 0xd5: // cmp $ff,x case 0xcd: // cmp $ffff case 0xdd: // cmp $ffff,x case 0xd9: // cmp $ffff,y case 0xc1: // cmp ($ff,x) case 0xd1: // cmp ($ff),y op->type = R_ANAL_OP_TYPE_CMP; _6502_anal_esil_get_addr_pattern1 (op, data, addrbuf, buffsize); if (data[0] == 0xc9) // immediate mode r_strbuf_setf (&op->esil, ""%s,a,=="", addrbuf); else r_strbuf_setf (&op->esil, ""%s,[1],a,=="", addrbuf); _6502_anal_update_flags (op, _6502_FLAGS_BNZ); // invert C, since C=1 when A-M >= 0 r_strbuf_append (&op->esil, "",C,!,C,=""); break; // CPX case 0xe0: // cpx #$ff case 0xe4: // cpx $ff case 0xec: // cpx $ffff op->type = R_ANAL_OP_TYPE_CMP; _6502_anal_esil_get_addr_pattern3 (op, data, addrbuf, buffsize, 0); if (data[0] == 0xe0) // immediate mode r_strbuf_setf (&op->esil, ""%s,x,=="", addrbuf); else r_strbuf_setf (&op->esil, ""%s,[1],x,=="", addrbuf); _6502_anal_update_flags (op, _6502_FLAGS_BNZ); // invert C, since C=1 when A-M >= 0 r_strbuf_append (&op->esil, "",C,!,C,=""); break; // CPY case 0xc0: // cpy #$ff case 0xc4: // cpy $ff case 0xcc: // cpy $ffff op->type = R_ANAL_OP_TYPE_CMP; _6502_anal_esil_get_addr_pattern3 (op, data, addrbuf, buffsize, 0); if (data[0] == 0xc0) // immediate mode r_strbuf_setf (&op->esil, ""%s,y,=="", addrbuf); else r_strbuf_setf (&op->esil, ""%s,[1],y,=="", addrbuf); _6502_anal_update_flags (op, _6502_FLAGS_BNZ); // invert C, since C=1 when A-M >= 0 r_strbuf_append (&op->esil, "",C,!,C,=""); break; // BRANCHES case 0x10: // bpl $ffff case 0x30: // bmi $ffff case 0x50: // bvc $ffff case 0x70: // bvs $ffff case 0x90: // bcc $ffff case 0xb0: // bcs $ffff case 0xd0: // bne $ffff case 0xf0: // beq $ffff // FIXME: Add 1 if branch occurs to same page. // FIXME: Add 2 if branch occurs to different page op->cycles = 2; op->failcycles = 3; op->type = R_ANAL_OP_TYPE_CJMP; if (data[1] <= 127) op->jump = addr + data[1] + op->size; else op->jump = addr - (256 - data[1]) + op->size; op->fail = addr + op->size; // FIXME: add a type of conditional // op->cond = R_ANAL_COND_LE; _6502_anal_esil_ccall (op, data[0]); break; // JSR case 0x20: // jsr $ffff op->cycles = 6; op->type = R_ANAL_OP_TYPE_CALL; op->jump = data[1] | data[2] << 8; op->stackop = R_ANAL_STACK_INC; op->stackptr = 2; // JSR pushes the address-1 of the next operation on to the stack before transferring program // control to the following address // stack is on page one and sp is an 8-bit reg: operations must be done like: sp + 0x100 r_strbuf_setf (&op->esil, ""1,pc,-,0xff,sp,+,=[2],0x%04x,pc,=,2,sp,-="", op->jump); break; // JMP case 0x4c: // jmp $ffff op->cycles = 3; op->type = R_ANAL_OP_TYPE_JMP; op->jump = data[1] | data[2] << 8; r_strbuf_setf (&op->esil, ""0x%04x,pc,="", op->jump); break; case 0x6c: // jmp ($ffff) op->cycles = 5; op->type = R_ANAL_OP_TYPE_UJMP; // FIXME: how to read memory? // op->jump = data[1] | data[2] << 8; r_strbuf_setf (&op->esil, ""0x%04x,[2],pc,="", data[1] | data[2] << 8); break; // RTS case 0x60: // rts op->eob = true; op->type = R_ANAL_OP_TYPE_RET; op->cycles = 6; op->stackop = R_ANAL_STACK_INC; op->stackptr = -2; // Operation: PC from Stack, PC + 1 -> PC // stack is on page one and sp is an 8-bit reg: operations must be done like: sp + 0x100 r_strbuf_set (&op->esil, ""0x101,sp,+,[2],pc,=,pc,++=,2,sp,+=""); break; // RTI case 0x40: // rti op->eob = true; op->type = R_ANAL_OP_TYPE_RET; op->cycles = 6; op->stackop = R_ANAL_STACK_INC; op->stackptr = -3; // Operation: P from Stack, PC from Stack // stack is on page one and sp is an 8-bit reg: operations must be done like: sp + 0x100 r_strbuf_set (&op->esil, ""0x101,sp,+,[1],flags,=,0x102,sp,+,[2],pc,=,3,sp,+=""); break; // NOP case 0xea: // nop op->type = R_ANAL_OP_TYPE_NOP; op->cycles = 2; break; // LDA case 0xa9: // lda #$ff case 0xa5: // lda $ff case 0xb5: // lda $ff,x case 0xad: // lda $ffff case 0xbd: // lda $ffff,x case 0xb9: // lda $ffff,y case 0xa1: // lda ($ff,x) case 0xb1: // lda ($ff),y op->type = R_ANAL_OP_TYPE_LOAD; _6502_anal_esil_get_addr_pattern1 (op, data, addrbuf, buffsize); if (data[0] == 0xa9) // immediate mode r_strbuf_setf (&op->esil, ""%s,a,="", addrbuf); else r_strbuf_setf (&op->esil, ""%s,[1],a,="", addrbuf); _6502_anal_update_flags (op, _6502_FLAGS_NZ); break; // LDX case 0xa2: // ldx #$ff case 0xa6: // ldx $ff case 0xb6: // ldx $ff,y case 0xae: // ldx $ffff case 0xbe: // ldx $ffff,y op->type = R_ANAL_OP_TYPE_LOAD; _6502_anal_esil_get_addr_pattern2 (op, data, addrbuf, buffsize, 'y'); if (data[0] == 0xa2) // immediate mode r_strbuf_setf (&op->esil, ""%s,x,="", addrbuf); else r_strbuf_setf (&op->esil, ""%s,[1],x,="", addrbuf); _6502_anal_update_flags (op, _6502_FLAGS_NZ); break; // LDY case 0xa0: // ldy #$ff case 0xa4: // ldy $ff case 0xb4: // ldy $ff,x case 0xac: // ldy $ffff case 0xbc: // ldy $ffff,x op->type = R_ANAL_OP_TYPE_LOAD; _6502_anal_esil_get_addr_pattern3 (op, data, addrbuf, buffsize, 'x'); if (data[0] == 0xa0) // immediate mode r_strbuf_setf (&op->esil, ""%s,y,="", addrbuf); else r_strbuf_setf (&op->esil, ""%s,[1],y,="", addrbuf); _6502_anal_update_flags (op, _6502_FLAGS_NZ); break; // STA case 0x85: // sta $ff case 0x95: // sta $ff,x case 0x8d: // sta $ffff case 0x9d: // sta $ffff,x case 0x99: // sta $ffff,y case 0x81: // sta ($ff,x) case 0x91: // sta ($ff),y op->type = R_ANAL_OP_TYPE_STORE; _6502_anal_esil_get_addr_pattern1 (op, data, addrbuf, buffsize); r_strbuf_setf (&op->esil, ""a,%s,=[1]"", addrbuf); break; // STX case 0x86: // stx $ff case 0x96: // stx $ff,y case 0x8e: // stx $ffff op->type = R_ANAL_OP_TYPE_STORE; _6502_anal_esil_get_addr_pattern2 (op, data, addrbuf, buffsize, 'y'); r_strbuf_setf (&op->esil, ""x,%s,=[1]"", addrbuf); break; // STY case 0x84: // sty $ff case 0x94: // sty $ff,x case 0x8c: // sty $ffff op->type = R_ANAL_OP_TYPE_STORE; _6502_anal_esil_get_addr_pattern3 (op, data, addrbuf, buffsize, 'x'); r_strbuf_setf (&op->esil, ""y,%s,=[1]"", addrbuf); break; // PHP/PHA case 0x08: // php case 0x48: // pha op->type = R_ANAL_OP_TYPE_PUSH; op->cycles = 3; op->stackop = R_ANAL_STACK_INC; op->stackptr = 1; _6502_anal_esil_push (op, data[0]); break; // PLP,PLA case 0x28: // plp case 0x68: // plp op->type = R_ANAL_OP_TYPE_POP; op->cycles = 4; op->stackop = R_ANAL_STACK_INC; op->stackptr = -1; _6502_anal_esil_pop (op, data[0]); break; // TAX,TYA,... case 0xaa: // tax case 0x8a: // txa case 0xa8: // tay case 0x98: // tya op->type = R_ANAL_OP_TYPE_MOV; op->cycles = 2; _6502_anal_esil_mov (op, data[0]); break; case 0x9a: // txs op->type = R_ANAL_OP_TYPE_MOV; op->cycles = 2; op->stackop = R_ANAL_STACK_SET; // FIXME: should I get register X a place it here? // op->stackptr = get_register_x(); _6502_anal_esil_mov (op, data[0]); break; case 0xba: // tsx op->type = R_ANAL_OP_TYPE_MOV; op->cycles = 2; op->stackop = R_ANAL_STACK_GET; _6502_anal_esil_mov (op, data[0]); break; } return op->size; }","static int _6502_op(RAnal *anal, RAnalOp *op, ut64 addr, const ut8 *data, int len) { char addrbuf[64]; const int buffsize = sizeof (addrbuf) - 1; memset (op, '\0', sizeof (RAnalOp)); op->size = snes_op_get_size (1, 1, &snes_op[data[0]]); //snes-arch is similiar to nes/6502 op->addr = addr; op->type = R_ANAL_OP_TYPE_UNK; op->id = data[0]; r_strbuf_init (&op->esil); switch (data[0]) { case 0x02: case 0x03: case 0x04: case 0x07: case 0x0b: case 0x0c: case 0x0f: case 0x12: case 0x13: case 0x14: case 0x17: case 0x1a: case 0x1b: case 0x1c: case 0x1f: case 0x22: case 0x23: case 0x27: case 0x2b: case 0x2f: case 0x32: case 0x33: case 0x34: case 0x37: case 0x3a: case 0x3b: case 0x3c: case 0x3f: case 0x42: case 0x43: case 0x44: case 0x47: case 0x4b: case 0x4f: case 0x52: case 0x53: case 0x54: case 0x57: case 0x5a: case 0x5b: case 0x5c: case 0x5f: case 0x62: case 0x63: case 0x64: case 0x67: case 0x6b: case 0x6f: case 0x72: case 0x73: case 0x74: case 0x77: case 0x7a: case 0x7b: case 0x7c: case 0x7f: case 0x80: case 0x82: case 0x83: case 0x87: case 0x89: case 0x8b: case 0x8f: case 0x92: case 0x93: case 0x97: case 0x9b: case 0x9c: case 0x9e: case 0x9f: case 0xa3: case 0xa7: case 0xab: case 0xaf: case 0xb2: case 0xb3: case 0xb7: case 0xbb: case 0xbf: case 0xc2: case 0xc3: case 0xc7: case 0xcb: case 0xcf: case 0xd2: case 0xd3: case 0xd4: case 0xd7: case 0xda: case 0xdb: case 0xdc: case 0xdf: case 0xe2: case 0xe3: case 0xe7: case 0xeb: case 0xef: case 0xf2: case 0xf3: case 0xf4: case 0xf7: case 0xfa: case 0xfb: case 0xfc: case 0xff: // undocumented or not-implemented opcodes for 6502. // some of them might be implemented in 65816 op->size = 1; op->type = R_ANAL_OP_TYPE_ILL; break; // BRK case 0x00: // brk op->cycles = 7; op->type = R_ANAL_OP_TYPE_SWI; // override 65816 code which seems to be wrong: size is 1, but pc = pc + 2 op->size = 1; // PC + 2 to Stack, P to Stack B=1 D=0 I=1. ""B"" is not a flag. Only its bit is pushed on the stack // PC was already incremented by one at this point. Needs to incremented once more // New PC is Interrupt Vector: $fffe. (FIXME: Confirm this is valid for all 6502) r_strbuf_set (&op->esil, "",1,I,=,0,D,=,flags,0x10,|,0x100,sp,+,=[1],pc,1,+,0xfe,sp,+,=[2],3,sp,-=,0xfffe,[2],pc,=""); break; // FLAGS case 0x78: // sei case 0x58: // cli case 0x38: // sec case 0x18: // clc case 0xf8: // sed case 0xd8: // cld case 0xb8: // clv op->cycles = 2; // FIXME: what opcode for this? op->type = R_ANAL_OP_TYPE_NOP; _6502_anal_esil_flags (op, data[0]); break; // BIT case 0x24: // bit $ff case 0x2c: // bit $ffff op->type = R_ANAL_OP_TYPE_MOV; _6502_anal_esil_get_addr_pattern3 (op, data, addrbuf, buffsize, 0); r_strbuf_setf (&op->esil, ""a,%s,[1],&,0x80,&,!,!,N,=,a,%s,[1],&,0x40,&,!,!,V,=,a,%s,[1],&,0xff,&,!,Z,="",addrbuf, addrbuf, addrbuf); break; // ADC case 0x69: // adc #$ff case 0x65: // adc $ff case 0x75: // adc $ff,x case 0x6d: // adc $ffff case 0x7d: // adc $ffff,x case 0x79: // adc $ffff,y case 0x61: // adc ($ff,x) case 0x71: // adc ($ff,y) // FIXME: update V // FIXME: support BCD mode op->type = R_ANAL_OP_TYPE_ADD; _6502_anal_esil_get_addr_pattern1 (op, data, addrbuf, buffsize); if (data[0] == 0x69) // immediate mode r_strbuf_setf (&op->esil, ""%s,a,+=,C,NUM,$c7,C,=,a,+=,$c7,C,|="", addrbuf); else r_strbuf_setf (&op->esil, ""%s,[1],a,+=,C,NUM,$c7,C,=,a,+=,$c7,C,|="", addrbuf); _6502_anal_update_flags (op, _6502_FLAGS_NZ); // fix Z r_strbuf_append (&op->esil, "",a,a,=,$z,Z,=""); break; // SBC case 0xe9: // sbc #$ff case 0xe5: // sbc $ff case 0xf5: // sbc $ff,x case 0xed: // sbc $ffff case 0xfd: // sbc $ffff,x case 0xf9: // sbc $ffff,y case 0xe1: // sbc ($ff,x) case 0xf1: // sbc ($ff,y) // FIXME: update V // FIXME: support BCD mode op->type = R_ANAL_OP_TYPE_SUB; _6502_anal_esil_get_addr_pattern1 (op, data, addrbuf, buffsize); if (data[0] == 0xe9) // immediate mode r_strbuf_setf (&op->esil, ""C,!,%s,+,a,-="", addrbuf); else r_strbuf_setf (&op->esil, ""C,!,%s,[1],+,a,-="", addrbuf); _6502_anal_update_flags (op, _6502_FLAGS_BNZ); // fix Z and revert C r_strbuf_append (&op->esil, "",a,a,=,$z,Z,=,C,!=""); break; // ORA case 0x09: // ora #$ff case 0x05: // ora $ff case 0x15: // ora $ff,x case 0x0d: // ora $ffff case 0x1d: // ora $ffff,x case 0x19: // ora $ffff,y case 0x01: // ora ($ff,x) case 0x11: // ora ($ff),y op->type = R_ANAL_OP_TYPE_OR; _6502_anal_esil_get_addr_pattern1 (op, data, addrbuf, buffsize); if (data[0] == 0x09) // immediate mode r_strbuf_setf (&op->esil, ""%s,a,|="", addrbuf); else r_strbuf_setf (&op->esil, ""%s,[1],a,|="", addrbuf); _6502_anal_update_flags (op, _6502_FLAGS_NZ); break; // AND case 0x29: // and #$ff case 0x25: // and $ff case 0x35: // and $ff,x case 0x2d: // and $ffff case 0x3d: // and $ffff,x case 0x39: // and $ffff,y case 0x21: // and ($ff,x) case 0x31: // and ($ff),y op->type = R_ANAL_OP_TYPE_AND; _6502_anal_esil_get_addr_pattern1 (op, data, addrbuf, buffsize); if (data[0] == 0x29) // immediate mode r_strbuf_setf (&op->esil, ""%s,a,&="", addrbuf); else r_strbuf_setf (&op->esil, ""%s,[1],a,&="", addrbuf); _6502_anal_update_flags (op, _6502_FLAGS_NZ); break; // EOR case 0x49: // eor #$ff case 0x45: // eor $ff case 0x55: // eor $ff,x case 0x4d: // eor $ffff case 0x5d: // eor $ffff,x case 0x59: // eor $ffff,y case 0x41: // eor ($ff,x) case 0x51: // eor ($ff),y op->type = R_ANAL_OP_TYPE_XOR; _6502_anal_esil_get_addr_pattern1 (op, data, addrbuf, buffsize); if (data[0] == 0x49) // immediate mode r_strbuf_setf (&op->esil, ""%s,a,^="", addrbuf); else r_strbuf_setf (&op->esil, ""%s,[1],a,^="", addrbuf); _6502_anal_update_flags (op, _6502_FLAGS_NZ); break; // ASL case 0x0a: // asl a case 0x06: // asl $ff case 0x16: // asl $ff,x case 0x0e: // asl $ffff case 0x1e: // asl $ffff,x op->type = R_ANAL_OP_TYPE_SHL; if (data[0] == 0x0a) { r_strbuf_set (&op->esil, ""1,a,<<=,$c7,C,=,a,a,=""); } else { _6502_anal_esil_get_addr_pattern2 (op, data, addrbuf, buffsize, 'x'); r_strbuf_setf (&op->esil, ""1,%s,[1],<<,%s,=[1],$c7,C,="", addrbuf, addrbuf); } _6502_anal_update_flags (op, _6502_FLAGS_NZ); break; // LSR case 0x4a: // lsr a case 0x46: // lsr $ff case 0x56: // lsr $ff,x case 0x4e: // lsr $ffff case 0x5e: // lsr $ffff,x op->type = R_ANAL_OP_TYPE_SHR; if (data[0] == 0x4a) { r_strbuf_set (&op->esil, ""1,a,&,C,=,1,a,>>=""); } else { _6502_anal_esil_get_addr_pattern2 (op, data, addrbuf, buffsize, 'x'); r_strbuf_setf (&op->esil, ""1,%s,[1],&,C,=,1,%s,[1],>>,%s,=[1]"", addrbuf, addrbuf, addrbuf); } _6502_anal_update_flags (op, _6502_FLAGS_NZ); break; // ROL case 0x2a: // rol a case 0x26: // rol $ff case 0x36: // rol $ff,x case 0x2e: // rol $ffff case 0x3e: // rol $ffff,x op->type = R_ANAL_OP_TYPE_ROL; if (data[0] == 0x2a) { r_strbuf_set (&op->esil, ""1,a,<<,C,|,a,=,$c7,C,=,a,a,=""); } else { _6502_anal_esil_get_addr_pattern2 (op, data, addrbuf, buffsize, 'x'); r_strbuf_setf (&op->esil, ""1,%s,[1],<<,C,|,%s,=[1],$c7,C,="", addrbuf, addrbuf); } _6502_anal_update_flags (op, _6502_FLAGS_NZ); break; // ROR case 0x6a: // ror a case 0x66: // ror $ff case 0x76: // ror $ff,x case 0x6e: // ror $ffff case 0x7e: // ror $ffff,x // uses N as temporary to hold C value. but in fact, // it is not temporary since in all ROR ops, N will have the value of C op->type = R_ANAL_OP_TYPE_ROR; if (data[0] == 0x6a) { r_strbuf_set (&op->esil, ""C,N,=,1,a,&,C,=,1,a,>>,7,N,<<,|,a,=""); } else { _6502_anal_esil_get_addr_pattern2 (op, data, addrbuf, buffsize, 'x'); r_strbuf_setf (&op->esil, ""C,N,=,1,%s,[1],&,C,=,1,%s,[1],>>,7,N,<<,|,%s,=[1]"", addrbuf, addrbuf, addrbuf); } _6502_anal_update_flags (op, _6502_FLAGS_NZ); break; // INC case 0xe6: // inc $ff case 0xf6: // inc $ff,x case 0xee: // inc $ffff case 0xfe: // inc $ffff,x op->type = R_ANAL_OP_TYPE_STORE; _6502_anal_esil_get_addr_pattern2 (op, data, addrbuf, buffsize, 'x'); r_strbuf_setf (&op->esil, ""%s,++=[1]"", addrbuf); _6502_anal_update_flags (op, _6502_FLAGS_NZ); break; // DEC case 0xc6: // dec $ff case 0xd6: // dec $ff,x case 0xce: // dec $ffff case 0xde: // dec $ffff,x op->type = R_ANAL_OP_TYPE_STORE; _6502_anal_esil_get_addr_pattern2 (op, data, addrbuf, buffsize, 'x'); r_strbuf_setf (&op->esil, ""%s,--=[1]"", addrbuf); _6502_anal_update_flags (op, _6502_FLAGS_NZ); break; // INX, INY case 0xe8: // inx case 0xc8: // iny op->cycles = 2; op->type = R_ANAL_OP_TYPE_STORE; _6502_anal_esil_inc_reg (op, data[0], ""+""); break; // DEX, DEY case 0xca: // dex case 0x88: // dey op->cycles = 2; op->type = R_ANAL_OP_TYPE_STORE; _6502_anal_esil_inc_reg (op, data[0], ""-""); break; // CMP case 0xc9: // cmp #$ff case 0xc5: // cmp $ff case 0xd5: // cmp $ff,x case 0xcd: // cmp $ffff case 0xdd: // cmp $ffff,x case 0xd9: // cmp $ffff,y case 0xc1: // cmp ($ff,x) case 0xd1: // cmp ($ff),y op->type = R_ANAL_OP_TYPE_CMP; _6502_anal_esil_get_addr_pattern1 (op, data, addrbuf, buffsize); if (data[0] == 0xc9) // immediate mode r_strbuf_setf (&op->esil, ""%s,a,=="", addrbuf); else r_strbuf_setf (&op->esil, ""%s,[1],a,=="", addrbuf); _6502_anal_update_flags (op, _6502_FLAGS_BNZ); // invert C, since C=1 when A-M >= 0 r_strbuf_append (&op->esil, "",C,!,C,=""); break; // CPX case 0xe0: // cpx #$ff case 0xe4: // cpx $ff case 0xec: // cpx $ffff op->type = R_ANAL_OP_TYPE_CMP; _6502_anal_esil_get_addr_pattern3 (op, data, addrbuf, buffsize, 0); if (data[0] == 0xe0) // immediate mode r_strbuf_setf (&op->esil, ""%s,x,=="", addrbuf); else r_strbuf_setf (&op->esil, ""%s,[1],x,=="", addrbuf); _6502_anal_update_flags (op, _6502_FLAGS_BNZ); // invert C, since C=1 when A-M >= 0 r_strbuf_append (&op->esil, "",C,!,C,=""); break; // CPY case 0xc0: // cpy #$ff case 0xc4: // cpy $ff case 0xcc: // cpy $ffff op->type = R_ANAL_OP_TYPE_CMP; _6502_anal_esil_get_addr_pattern3 (op, data, addrbuf, buffsize, 0); if (data[0] == 0xc0) // immediate mode r_strbuf_setf (&op->esil, ""%s,y,=="", addrbuf); else r_strbuf_setf (&op->esil, ""%s,[1],y,=="", addrbuf); _6502_anal_update_flags (op, _6502_FLAGS_BNZ); // invert C, since C=1 when A-M >= 0 r_strbuf_append (&op->esil, "",C,!,C,=""); break; // BRANCHES case 0x10: // bpl $ffff case 0x30: // bmi $ffff case 0x50: // bvc $ffff case 0x70: // bvs $ffff case 0x90: // bcc $ffff case 0xb0: // bcs $ffff case 0xd0: // bne $ffff case 0xf0: // beq $ffff // FIXME: Add 1 if branch occurs to same page. // FIXME: Add 2 if branch occurs to different page op->cycles = 2; op->failcycles = 3; op->type = R_ANAL_OP_TYPE_CJMP; if (len > 1) { if (data[1] <= 127) { op->jump = addr + data[1] + op->size; } else { op->jump = addr - (256 - data[1]) + op->size; } } else { op->jump = addr; } op->fail = addr + op->size; // FIXME: add a type of conditional // op->cond = R_ANAL_COND_LE; _6502_anal_esil_ccall (op, data[0]); break; // JSR case 0x20: // jsr $ffff op->cycles = 6; op->type = R_ANAL_OP_TYPE_CALL; op->jump = data[1] | data[2] << 8; op->stackop = R_ANAL_STACK_INC; op->stackptr = 2; // JSR pushes the address-1 of the next operation on to the stack before transferring program // control to the following address // stack is on page one and sp is an 8-bit reg: operations must be done like: sp + 0x100 r_strbuf_setf (&op->esil, ""1,pc,-,0xff,sp,+,=[2],0x%04x,pc,=,2,sp,-="", op->jump); break; // JMP case 0x4c: // jmp $ffff op->cycles = 3; op->type = R_ANAL_OP_TYPE_JMP; op->jump = data[1] | data[2] << 8; r_strbuf_setf (&op->esil, ""0x%04x,pc,="", op->jump); break; case 0x6c: // jmp ($ffff) op->cycles = 5; op->type = R_ANAL_OP_TYPE_UJMP; // FIXME: how to read memory? // op->jump = data[1] | data[2] << 8; r_strbuf_setf (&op->esil, ""0x%04x,[2],pc,="", data[1] | data[2] << 8); break; // RTS case 0x60: // rts op->eob = true; op->type = R_ANAL_OP_TYPE_RET; op->cycles = 6; op->stackop = R_ANAL_STACK_INC; op->stackptr = -2; // Operation: PC from Stack, PC + 1 -> PC // stack is on page one and sp is an 8-bit reg: operations must be done like: sp + 0x100 r_strbuf_set (&op->esil, ""0x101,sp,+,[2],pc,=,pc,++=,2,sp,+=""); break; // RTI case 0x40: // rti op->eob = true; op->type = R_ANAL_OP_TYPE_RET; op->cycles = 6; op->stackop = R_ANAL_STACK_INC; op->stackptr = -3; // Operation: P from Stack, PC from Stack // stack is on page one and sp is an 8-bit reg: operations must be done like: sp + 0x100 r_strbuf_set (&op->esil, ""0x101,sp,+,[1],flags,=,0x102,sp,+,[2],pc,=,3,sp,+=""); break; // NOP case 0xea: // nop op->type = R_ANAL_OP_TYPE_NOP; op->cycles = 2; break; // LDA case 0xa9: // lda #$ff case 0xa5: // lda $ff case 0xb5: // lda $ff,x case 0xad: // lda $ffff case 0xbd: // lda $ffff,x case 0xb9: // lda $ffff,y case 0xa1: // lda ($ff,x) case 0xb1: // lda ($ff),y op->type = R_ANAL_OP_TYPE_LOAD; _6502_anal_esil_get_addr_pattern1 (op, data, addrbuf, buffsize); if (data[0] == 0xa9) // immediate mode r_strbuf_setf (&op->esil, ""%s,a,="", addrbuf); else r_strbuf_setf (&op->esil, ""%s,[1],a,="", addrbuf); _6502_anal_update_flags (op, _6502_FLAGS_NZ); break; // LDX case 0xa2: // ldx #$ff case 0xa6: // ldx $ff case 0xb6: // ldx $ff,y case 0xae: // ldx $ffff case 0xbe: // ldx $ffff,y op->type = R_ANAL_OP_TYPE_LOAD; _6502_anal_esil_get_addr_pattern2 (op, data, addrbuf, buffsize, 'y'); if (data[0] == 0xa2) // immediate mode r_strbuf_setf (&op->esil, ""%s,x,="", addrbuf); else r_strbuf_setf (&op->esil, ""%s,[1],x,="", addrbuf); _6502_anal_update_flags (op, _6502_FLAGS_NZ); break; // LDY case 0xa0: // ldy #$ff case 0xa4: // ldy $ff case 0xb4: // ldy $ff,x case 0xac: // ldy $ffff case 0xbc: // ldy $ffff,x op->type = R_ANAL_OP_TYPE_LOAD; _6502_anal_esil_get_addr_pattern3 (op, data, addrbuf, buffsize, 'x'); if (data[0] == 0xa0) // immediate mode r_strbuf_setf (&op->esil, ""%s,y,="", addrbuf); else r_strbuf_setf (&op->esil, ""%s,[1],y,="", addrbuf); _6502_anal_update_flags (op, _6502_FLAGS_NZ); break; // STA case 0x85: // sta $ff case 0x95: // sta $ff,x case 0x8d: // sta $ffff case 0x9d: // sta $ffff,x case 0x99: // sta $ffff,y case 0x81: // sta ($ff,x) case 0x91: // sta ($ff),y op->type = R_ANAL_OP_TYPE_STORE; _6502_anal_esil_get_addr_pattern1 (op, data, addrbuf, buffsize); r_strbuf_setf (&op->esil, ""a,%s,=[1]"", addrbuf); break; // STX case 0x86: // stx $ff case 0x96: // stx $ff,y case 0x8e: // stx $ffff op->type = R_ANAL_OP_TYPE_STORE; _6502_anal_esil_get_addr_pattern2 (op, data, addrbuf, buffsize, 'y'); r_strbuf_setf (&op->esil, ""x,%s,=[1]"", addrbuf); break; // STY case 0x84: // sty $ff case 0x94: // sty $ff,x case 0x8c: // sty $ffff op->type = R_ANAL_OP_TYPE_STORE; _6502_anal_esil_get_addr_pattern3 (op, data, addrbuf, buffsize, 'x'); r_strbuf_setf (&op->esil, ""y,%s,=[1]"", addrbuf); break; // PHP/PHA case 0x08: // php case 0x48: // pha op->type = R_ANAL_OP_TYPE_PUSH; op->cycles = 3; op->stackop = R_ANAL_STACK_INC; op->stackptr = 1; _6502_anal_esil_push (op, data[0]); break; // PLP,PLA case 0x28: // plp case 0x68: // plp op->type = R_ANAL_OP_TYPE_POP; op->cycles = 4; op->stackop = R_ANAL_STACK_INC; op->stackptr = -1; _6502_anal_esil_pop (op, data[0]); break; // TAX,TYA,... case 0xaa: // tax case 0x8a: // txa case 0xa8: // tay case 0x98: // tya op->type = R_ANAL_OP_TYPE_MOV; op->cycles = 2; _6502_anal_esil_mov (op, data[0]); break; case 0x9a: // txs op->type = R_ANAL_OP_TYPE_MOV; op->cycles = 2; op->stackop = R_ANAL_STACK_SET; // FIXME: should I get register X a place it here? // op->stackptr = get_register_x(); _6502_anal_esil_mov (op, data[0]); break; case 0xba: // tsx op->type = R_ANAL_OP_TYPE_MOV; op->cycles = 2; op->stackop = R_ANAL_STACK_GET; _6502_anal_esil_mov (op, data[0]); break; } return op->size; }","{'deleted': [{'line_no': 397, 'char_start': 10823, 'char_end': 10845, 'line': '\t\tif (data[1] <= 127)\n'}, {'line_no': 398, 'char_start': 10845, 'char_end': 10886, 'line': '\t\t\top->jump = addr + data[1] + op->size;\n'}, {'line_no': 399, 'char_start': 10886, 'char_end': 10939, 'line': '\t\telse\top->jump = addr - (256 - data[1]) + op->size;\n'}], 'added': [{'line_no': 397, 'char_start': 10823, 'char_end': 10840, 'line': '\t\tif (len > 1) {\n'}, {'line_no': 398, 'char_start': 10840, 'char_end': 10865, 'line': '\t\t\tif (data[1] <= 127) {\n'}, {'line_no': 399, 'char_start': 10865, 'char_end': 10907, 'line': '\t\t\t\top->jump = addr + data[1] + op->size;\n'}, {'line_no': 400, 'char_start': 10907, 'char_end': 10919, 'line': '\t\t\t} else {\n'}, {'line_no': 401, 'char_start': 10919, 'char_end': 10969, 'line': '\t\t\t\top->jump = addr - (256 - data[1]) + op->size;\n'}, {'line_no': 402, 'char_start': 10969, 'char_end': 10974, 'line': '\t\t\t}\n'}, {'line_no': 403, 'char_start': 10974, 'char_end': 10985, 'line': '\t\t} else {\n'}, {'line_no': 404, 'char_start': 10985, 'char_end': 11005, 'line': '\t\t\top->jump = addr;\n'}, {'line_no': 405, 'char_start': 11005, 'char_end': 11009, 'line': '\t\t}\n'}]}","{'deleted': [], 'added': [{'char_start': 10829, 'char_end': 10847, 'chars': 'len > 1) {\n\t\t\tif ('}, {'char_start': 10862, 'char_end': 10864, 'chars': ' {'}, {'char_start': 10865, 'char_end': 10866, 'chars': '\t'}, {'char_start': 10909, 'char_end': 10912, 'chars': '\t} '}, {'char_start': 10916, 'char_end': 10922, 'chars': ' {\n\t\t\t'}, {'char_start': 10968, 'char_end': 11008, 'chars': '\n\t\t\t}\n\t\t} else {\n\t\t\top->jump = addr;\n\t\t}'}]}",github.com/radare/radare2/commit/bbb4af56003c1afdad67af0c4339267ca38b1017,libr/anal/p/anal_6502.c,cwe-125,7183 cwe-787,enl_ipc_get,"char *enl_ipc_get(const char *msg_data) { static char *message = NULL; static unsigned short len = 0; char buff[13], *ret_msg = NULL; register unsigned char i; unsigned char blen; if (msg_data == IPC_TIMEOUT) { return(IPC_TIMEOUT); } for (i = 0; i < 12; i++) { buff[i] = msg_data[i]; } buff[12] = 0; blen = strlen(buff); if (message != NULL) { len += blen; message = (char *) erealloc(message, len + 1); strcat(message, buff); } else { len = blen; message = (char *) emalloc(len + 1); strcpy(message, buff); } if (blen < 12) { ret_msg = message; message = NULL; D((""Received complete reply: \""%s\""\n"", ret_msg)); } return(ret_msg); }","char *enl_ipc_get(const char *msg_data) { static char *message = NULL; static size_t len = 0; char buff[13], *ret_msg = NULL; register unsigned char i; unsigned char blen; if (msg_data == IPC_TIMEOUT) { return(IPC_TIMEOUT); } for (i = 0; i < 12; i++) { buff[i] = msg_data[i]; } buff[12] = 0; blen = strlen(buff); if (message != NULL) { len += blen; message = (char *) erealloc(message, len + 1); strcat(message, buff); } else { len = blen; message = (char *) emalloc(len + 1); strcpy(message, buff); } if (blen < 12) { ret_msg = message; message = NULL; D((""Received complete reply: \""%s\""\n"", ret_msg)); } return(ret_msg); }","{'deleted': [{'line_no': 5, 'char_start': 73, 'char_end': 105, 'line': '\tstatic unsigned short len = 0;\n'}], 'added': [{'line_no': 5, 'char_start': 73, 'char_end': 97, 'line': '\tstatic size_t len = 0;\n'}]}","{'deleted': [{'char_start': 81, 'char_end': 83, 'chars': 'un'}, {'char_start': 85, 'char_end': 87, 'chars': 'gn'}, {'char_start': 88, 'char_end': 94, 'chars': 'd shor'}], 'added': [{'char_start': 83, 'char_end': 84, 'chars': 'z'}, {'char_start': 85, 'char_end': 86, 'chars': '_'}]}",github.com/derf/feh/commit/f7a547b7ef8fc8ebdeaa4c28515c9d72e592fb6d,src/wallpaper.c,cwe-787,218 cwe-089,get_user," def get_user(self): if not hasattr(self, '_user'): qs = ""select * from account_access where access_token = '%s'"" % self.access_token result = self.db.get(qs) if result: self._user = result else: self._user = None return self._user"," def get_user(self): if not hasattr(self, '_user'): qs = ""select * from account_access where access_token = %s"" result = self.db.get(qs, self.access_token) if result: self._user = result else: self._user = None return self._user","{'deleted': [{'line_no': 3, 'char_start': 63, 'char_end': 157, 'line': ' qs = ""select * from account_access where access_token = \'%s\'"" % self.access_token\n'}, {'line_no': 4, 'char_start': 157, 'char_end': 194, 'line': ' result = self.db.get(qs)\n'}], 'added': [{'line_no': 3, 'char_start': 63, 'char_end': 135, 'line': ' qs = ""select * from account_access where access_token = %s""\n'}, {'line_no': 4, 'char_start': 135, 'char_end': 191, 'line': ' result = self.db.get(qs, self.access_token)\n'}]}","{'deleted': [{'char_start': 131, 'char_end': 132, 'chars': ""'""}, {'char_start': 134, 'char_end': 135, 'chars': ""'""}, {'char_start': 136, 'char_end': 156, 'chars': ' % self.access_token'}], 'added': [{'char_start': 170, 'char_end': 189, 'chars': ', self.access_token'}]}",github.com/bonbondirac/tsunami/commit/396cc394bd6daaf0ee9c16b1b55a4082eeaac208,src/auth.py,cwe-089,71 cwe-476,rds_cmsg_atomic,"int rds_cmsg_atomic(struct rds_sock *rs, struct rds_message *rm, struct cmsghdr *cmsg) { struct page *page = NULL; struct rds_atomic_args *args; int ret = 0; if (cmsg->cmsg_len < CMSG_LEN(sizeof(struct rds_atomic_args)) || rm->atomic.op_active) return -EINVAL; args = CMSG_DATA(cmsg); /* Nonmasked & masked cmsg ops converted to masked hw ops */ switch (cmsg->cmsg_type) { case RDS_CMSG_ATOMIC_FADD: rm->atomic.op_type = RDS_ATOMIC_TYPE_FADD; rm->atomic.op_m_fadd.add = args->fadd.add; rm->atomic.op_m_fadd.nocarry_mask = 0; break; case RDS_CMSG_MASKED_ATOMIC_FADD: rm->atomic.op_type = RDS_ATOMIC_TYPE_FADD; rm->atomic.op_m_fadd.add = args->m_fadd.add; rm->atomic.op_m_fadd.nocarry_mask = args->m_fadd.nocarry_mask; break; case RDS_CMSG_ATOMIC_CSWP: rm->atomic.op_type = RDS_ATOMIC_TYPE_CSWP; rm->atomic.op_m_cswp.compare = args->cswp.compare; rm->atomic.op_m_cswp.swap = args->cswp.swap; rm->atomic.op_m_cswp.compare_mask = ~0; rm->atomic.op_m_cswp.swap_mask = ~0; break; case RDS_CMSG_MASKED_ATOMIC_CSWP: rm->atomic.op_type = RDS_ATOMIC_TYPE_CSWP; rm->atomic.op_m_cswp.compare = args->m_cswp.compare; rm->atomic.op_m_cswp.swap = args->m_cswp.swap; rm->atomic.op_m_cswp.compare_mask = args->m_cswp.compare_mask; rm->atomic.op_m_cswp.swap_mask = args->m_cswp.swap_mask; break; default: BUG(); /* should never happen */ } rm->atomic.op_notify = !!(args->flags & RDS_RDMA_NOTIFY_ME); rm->atomic.op_silent = !!(args->flags & RDS_RDMA_SILENT); rm->atomic.op_active = 1; rm->atomic.op_recverr = rs->rs_recverr; rm->atomic.op_sg = rds_message_alloc_sgs(rm, 1); if (!rm->atomic.op_sg) { ret = -ENOMEM; goto err; } /* verify 8 byte-aligned */ if (args->local_addr & 0x7) { ret = -EFAULT; goto err; } ret = rds_pin_pages(args->local_addr, 1, &page, 1); if (ret != 1) goto err; ret = 0; sg_set_page(rm->atomic.op_sg, page, 8, offset_in_page(args->local_addr)); if (rm->atomic.op_notify || rm->atomic.op_recverr) { /* We allocate an uninitialized notifier here, because * we don't want to do that in the completion handler. We * would have to use GFP_ATOMIC there, and don't want to deal * with failed allocations. */ rm->atomic.op_notifier = kmalloc(sizeof(*rm->atomic.op_notifier), GFP_KERNEL); if (!rm->atomic.op_notifier) { ret = -ENOMEM; goto err; } rm->atomic.op_notifier->n_user_token = args->user_token; rm->atomic.op_notifier->n_status = RDS_RDMA_SUCCESS; } rm->atomic.op_rkey = rds_rdma_cookie_key(args->cookie); rm->atomic.op_remote_addr = args->remote_addr + rds_rdma_cookie_offset(args->cookie); return ret; err: if (page) put_page(page); kfree(rm->atomic.op_notifier); return ret; }","int rds_cmsg_atomic(struct rds_sock *rs, struct rds_message *rm, struct cmsghdr *cmsg) { struct page *page = NULL; struct rds_atomic_args *args; int ret = 0; if (cmsg->cmsg_len < CMSG_LEN(sizeof(struct rds_atomic_args)) || rm->atomic.op_active) return -EINVAL; args = CMSG_DATA(cmsg); /* Nonmasked & masked cmsg ops converted to masked hw ops */ switch (cmsg->cmsg_type) { case RDS_CMSG_ATOMIC_FADD: rm->atomic.op_type = RDS_ATOMIC_TYPE_FADD; rm->atomic.op_m_fadd.add = args->fadd.add; rm->atomic.op_m_fadd.nocarry_mask = 0; break; case RDS_CMSG_MASKED_ATOMIC_FADD: rm->atomic.op_type = RDS_ATOMIC_TYPE_FADD; rm->atomic.op_m_fadd.add = args->m_fadd.add; rm->atomic.op_m_fadd.nocarry_mask = args->m_fadd.nocarry_mask; break; case RDS_CMSG_ATOMIC_CSWP: rm->atomic.op_type = RDS_ATOMIC_TYPE_CSWP; rm->atomic.op_m_cswp.compare = args->cswp.compare; rm->atomic.op_m_cswp.swap = args->cswp.swap; rm->atomic.op_m_cswp.compare_mask = ~0; rm->atomic.op_m_cswp.swap_mask = ~0; break; case RDS_CMSG_MASKED_ATOMIC_CSWP: rm->atomic.op_type = RDS_ATOMIC_TYPE_CSWP; rm->atomic.op_m_cswp.compare = args->m_cswp.compare; rm->atomic.op_m_cswp.swap = args->m_cswp.swap; rm->atomic.op_m_cswp.compare_mask = args->m_cswp.compare_mask; rm->atomic.op_m_cswp.swap_mask = args->m_cswp.swap_mask; break; default: BUG(); /* should never happen */ } rm->atomic.op_notify = !!(args->flags & RDS_RDMA_NOTIFY_ME); rm->atomic.op_silent = !!(args->flags & RDS_RDMA_SILENT); rm->atomic.op_active = 1; rm->atomic.op_recverr = rs->rs_recverr; rm->atomic.op_sg = rds_message_alloc_sgs(rm, 1); if (!rm->atomic.op_sg) { ret = -ENOMEM; goto err; } /* verify 8 byte-aligned */ if (args->local_addr & 0x7) { ret = -EFAULT; goto err; } ret = rds_pin_pages(args->local_addr, 1, &page, 1); if (ret != 1) goto err; ret = 0; sg_set_page(rm->atomic.op_sg, page, 8, offset_in_page(args->local_addr)); if (rm->atomic.op_notify || rm->atomic.op_recverr) { /* We allocate an uninitialized notifier here, because * we don't want to do that in the completion handler. We * would have to use GFP_ATOMIC there, and don't want to deal * with failed allocations. */ rm->atomic.op_notifier = kmalloc(sizeof(*rm->atomic.op_notifier), GFP_KERNEL); if (!rm->atomic.op_notifier) { ret = -ENOMEM; goto err; } rm->atomic.op_notifier->n_user_token = args->user_token; rm->atomic.op_notifier->n_status = RDS_RDMA_SUCCESS; } rm->atomic.op_rkey = rds_rdma_cookie_key(args->cookie); rm->atomic.op_remote_addr = args->remote_addr + rds_rdma_cookie_offset(args->cookie); return ret; err: if (page) put_page(page); rm->atomic.op_active = 0; kfree(rm->atomic.op_notifier); return ret; }","{'deleted': [], 'added': [{'line_no': 90, 'char_start': 2680, 'char_end': 2707, 'line': '\trm->atomic.op_active = 0;\n'}]}","{'deleted': [], 'added': [{'char_start': 2681, 'char_end': 2708, 'chars': 'rm->atomic.op_active = 0;\n\t'}]}",github.com/torvalds/linux/commit/7d11f77f84b27cef452cee332f4e469503084737,net/rds/rdma.c,cwe-476,867 cwe-089,userLogin," def userLogin(self): sqlName=""select count(*) from users where name='%s' and \ password='%s';""%(self.name,self.password) checkName=sql.queryDB(self.conn,sqlName) result=checkName[0][0] if result == 0: self.clean() return False else: return True"," def userLogin(self): sqlName=""select count(*) from users where name=%s and password=%s;"" params = [self.name,self.password] checkName=sql.queryDB(self.conn,sqlName,params) result=checkName[0][0] if result == 0: self.clean() return False else: return True","{'deleted': [{'line_no': 3, 'char_start': 26, 'char_end': 92, 'line': ' sqlName=""select count(*) from users where name=\'%s\' and \\\n'}, {'line_no': 4, 'char_start': 92, 'char_end': 150, 'line': ' password=\'%s\';""%(self.name,self.password)\n'}, {'line_no': 5, 'char_start': 150, 'char_end': 199, 'line': ' checkName=sql.queryDB(self.conn,sqlName)\n'}, {'line_no': 6, 'char_start': 199, 'char_end': 200, 'line': '\n'}], 'added': [{'line_no': 3, 'char_start': 26, 'char_end': 102, 'line': ' sqlName=""select count(*) from users where name=%s and password=%s;""\n'}, {'line_no': 4, 'char_start': 102, 'char_end': 145, 'line': ' params = [self.name,self.password]\n'}, {'line_no': 5, 'char_start': 145, 'char_end': 201, 'line': ' checkName=sql.queryDB(self.conn,sqlName,params)\n'}]}","{'deleted': [{'char_start': 81, 'char_end': 82, 'chars': ""'""}, {'char_start': 84, 'char_end': 85, 'chars': ""'""}, {'char_start': 90, 'char_end': 91, 'chars': '\\'}, {'char_start': 92, 'char_end': 100, 'chars': ' '}, {'char_start': 111, 'char_end': 116, 'chars': 'sword'}, {'char_start': 117, 'char_end': 125, 'chars': '\'%s\';""%('}, {'char_start': 148, 'char_end': 149, 'chars': ')'}, {'char_start': 198, 'char_end': 199, 'chars': '\n'}], 'added': [{'char_start': 101, 'char_end': 120, 'chars': '\n params = ['}, {'char_start': 143, 'char_end': 144, 'chars': ']'}, {'char_start': 192, 'char_end': 199, 'chars': ',params'}]}",github.com/ShaominLi/Twitter_project/commit/5329d91f9e569c95184053c8e7ef596949c33ce9,modules/users.py,cwe-089,77 cwe-476,run,"static int run(const CommandLineOptions& options) { IR::Module irModule; // Load the module. if(!loadModule(options.filename, irModule)) { return EXIT_FAILURE; } if(options.onlyCheck) { return EXIT_SUCCESS; } // Compile the module. Runtime::Module* module = nullptr; if(!options.precompiled) { module = Runtime::compileModule(irModule); } else { const UserSection* precompiledObjectSection = nullptr; for(const UserSection& userSection : irModule.userSections) { if(userSection.name == ""wavm.precompiled_object"") { precompiledObjectSection = &userSection; break; } } if(!precompiledObjectSection) { Log::printf(Log::error, ""Input file did not contain 'wavm.precompiled_object' section""); return EXIT_FAILURE; } else { module = Runtime::loadPrecompiledModule(irModule, precompiledObjectSection->data); } } // Link the module with the intrinsic modules. Compartment* compartment = Runtime::createCompartment(); Context* context = Runtime::createContext(compartment); RootResolver rootResolver(compartment); Emscripten::Instance* emscriptenInstance = nullptr; if(options.enableEmscripten) { emscriptenInstance = Emscripten::instantiate(compartment, irModule); if(emscriptenInstance) { rootResolver.moduleNameToInstanceMap.set(""env"", emscriptenInstance->env); rootResolver.moduleNameToInstanceMap.set(""asm2wasm"", emscriptenInstance->asm2wasm); rootResolver.moduleNameToInstanceMap.set(""global"", emscriptenInstance->global); } } if(options.enableThreadTest) { ModuleInstance* threadTestInstance = ThreadTest::instantiate(compartment); rootResolver.moduleNameToInstanceMap.set(""threadTest"", threadTestInstance); } LinkResult linkResult = linkModule(irModule, rootResolver); if(!linkResult.success) { Log::printf(Log::error, ""Failed to link module:\n""); for(auto& missingImport : linkResult.missingImports) { Log::printf(Log::error, ""Missing import: module=\""%s\"" export=\""%s\"" type=\""%s\""\n"", missingImport.moduleName.c_str(), missingImport.exportName.c_str(), asString(missingImport.type).c_str()); } return EXIT_FAILURE; } // Instantiate the module. ModuleInstance* moduleInstance = instantiateModule( compartment, module, std::move(linkResult.resolvedImports), options.filename); if(!moduleInstance) { return EXIT_FAILURE; } // Call the module start function, if it has one. FunctionInstance* startFunction = getStartFunction(moduleInstance); if(startFunction) { invokeFunctionChecked(context, startFunction, {}); } if(options.enableEmscripten) { // Call the Emscripten global initalizers. Emscripten::initializeGlobals(context, irModule, moduleInstance); } // Look up the function export to call. FunctionInstance* functionInstance; if(!options.functionName) { functionInstance = asFunctionNullable(getInstanceExport(moduleInstance, ""main"")); if(!functionInstance) { functionInstance = asFunctionNullable(getInstanceExport(moduleInstance, ""_main"")); } if(!functionInstance) { Log::printf(Log::error, ""Module does not export main function\n""); return EXIT_FAILURE; } } else { functionInstance = asFunctionNullable(getInstanceExport(moduleInstance, options.functionName)); if(!functionInstance) { Log::printf(Log::error, ""Module does not export '%s'\n"", options.functionName); return EXIT_FAILURE; } } FunctionType functionType = getFunctionType(functionInstance); // Set up the arguments for the invoke. std::vector invokeArgs; if(!options.functionName) { if(functionType.params().size() == 2) { MemoryInstance* defaultMemory = Runtime::getDefaultMemory(moduleInstance); if(!defaultMemory) { Log::printf( Log::error, ""Module does not declare a default memory object to put arguments in.\n""); return EXIT_FAILURE; } std::vector argStrings; argStrings.push_back(options.filename); char** args = options.args; while(*args) { argStrings.push_back(*args++); }; Emscripten::injectCommandArgs(emscriptenInstance, argStrings, invokeArgs); } else if(functionType.params().size() > 0) { Log::printf(Log::error, ""WebAssembly function requires %"" PRIu64 "" argument(s), but only 0 or 2 can be passed!"", functionType.params().size()); return EXIT_FAILURE; } } else { for(U32 i = 0; options.args[i]; ++i) { Value value; switch(functionType.params()[i]) { case ValueType::i32: value = (U32)atoi(options.args[i]); break; case ValueType::i64: value = (U64)atol(options.args[i]); break; case ValueType::f32: value = (F32)atof(options.args[i]); break; case ValueType::f64: value = atof(options.args[i]); break; case ValueType::v128: case ValueType::anyref: case ValueType::anyfunc: Errors::fatalf(""Cannot parse command-line argument for %s function parameter"", asString(functionType.params()[i])); default: Errors::unreachable(); } invokeArgs.push_back(value); } } // Invoke the function. Timing::Timer executionTimer; IR::ValueTuple functionResults = invokeFunctionChecked(context, functionInstance, invokeArgs); Timing::logTimer(""Invoked function"", executionTimer); if(options.functionName) { Log::printf(Log::debug, ""%s returned: %s\n"", options.functionName, asString(functionResults).c_str()); return EXIT_SUCCESS; } else if(functionResults.size() == 1 && functionResults[0].type == ValueType::i32) { return functionResults[0].i32; } else { return EXIT_SUCCESS; } }","static int run(const CommandLineOptions& options) { IR::Module irModule; // Load the module. if(!loadModule(options.filename, irModule)) { return EXIT_FAILURE; } if(options.onlyCheck) { return EXIT_SUCCESS; } // Compile the module. Runtime::Module* module = nullptr; if(!options.precompiled) { module = Runtime::compileModule(irModule); } else { const UserSection* precompiledObjectSection = nullptr; for(const UserSection& userSection : irModule.userSections) { if(userSection.name == ""wavm.precompiled_object"") { precompiledObjectSection = &userSection; break; } } if(!precompiledObjectSection) { Log::printf(Log::error, ""Input file did not contain 'wavm.precompiled_object' section""); return EXIT_FAILURE; } else { module = Runtime::loadPrecompiledModule(irModule, precompiledObjectSection->data); } } // Link the module with the intrinsic modules. Compartment* compartment = Runtime::createCompartment(); Context* context = Runtime::createContext(compartment); RootResolver rootResolver(compartment); Emscripten::Instance* emscriptenInstance = nullptr; if(options.enableEmscripten) { emscriptenInstance = Emscripten::instantiate(compartment, irModule); if(emscriptenInstance) { rootResolver.moduleNameToInstanceMap.set(""env"", emscriptenInstance->env); rootResolver.moduleNameToInstanceMap.set(""asm2wasm"", emscriptenInstance->asm2wasm); rootResolver.moduleNameToInstanceMap.set(""global"", emscriptenInstance->global); } } if(options.enableThreadTest) { ModuleInstance* threadTestInstance = ThreadTest::instantiate(compartment); rootResolver.moduleNameToInstanceMap.set(""threadTest"", threadTestInstance); } LinkResult linkResult = linkModule(irModule, rootResolver); if(!linkResult.success) { Log::printf(Log::error, ""Failed to link module:\n""); for(auto& missingImport : linkResult.missingImports) { Log::printf(Log::error, ""Missing import: module=\""%s\"" export=\""%s\"" type=\""%s\""\n"", missingImport.moduleName.c_str(), missingImport.exportName.c_str(), asString(missingImport.type).c_str()); } return EXIT_FAILURE; } // Instantiate the module. ModuleInstance* moduleInstance = instantiateModule( compartment, module, std::move(linkResult.resolvedImports), options.filename); if(!moduleInstance) { return EXIT_FAILURE; } // Call the module start function, if it has one. FunctionInstance* startFunction = getStartFunction(moduleInstance); if(startFunction) { invokeFunctionChecked(context, startFunction, {}); } if(options.enableEmscripten) { // Call the Emscripten global initalizers. Emscripten::initializeGlobals(context, irModule, moduleInstance); } // Look up the function export to call. FunctionInstance* functionInstance; if(!options.functionName) { functionInstance = asFunctionNullable(getInstanceExport(moduleInstance, ""main"")); if(!functionInstance) { functionInstance = asFunctionNullable(getInstanceExport(moduleInstance, ""_main"")); } if(!functionInstance) { Log::printf(Log::error, ""Module does not export main function\n""); return EXIT_FAILURE; } } else { functionInstance = asFunctionNullable(getInstanceExport(moduleInstance, options.functionName)); if(!functionInstance) { Log::printf(Log::error, ""Module does not export '%s'\n"", options.functionName); return EXIT_FAILURE; } } FunctionType functionType = getFunctionType(functionInstance); // Set up the arguments for the invoke. std::vector invokeArgs; if(!options.functionName) { if(functionType.params().size() == 2) { if(!emscriptenInstance) { Log::printf( Log::error, ""Module does not declare a default memory object to put arguments in.\n""); return EXIT_FAILURE; } else { std::vector argStrings; argStrings.push_back(options.filename); char** args = options.args; while(*args) { argStrings.push_back(*args++); }; wavmAssert(emscriptenInstance); Emscripten::injectCommandArgs(emscriptenInstance, argStrings, invokeArgs); } } else if(functionType.params().size() > 0) { Log::printf(Log::error, ""WebAssembly function requires %"" PRIu64 "" argument(s), but only 0 or 2 can be passed!"", functionType.params().size()); return EXIT_FAILURE; } } else { for(U32 i = 0; options.args[i]; ++i) { Value value; switch(functionType.params()[i]) { case ValueType::i32: value = (U32)atoi(options.args[i]); break; case ValueType::i64: value = (U64)atol(options.args[i]); break; case ValueType::f32: value = (F32)atof(options.args[i]); break; case ValueType::f64: value = atof(options.args[i]); break; case ValueType::v128: case ValueType::anyref: case ValueType::anyfunc: Errors::fatalf(""Cannot parse command-line argument for %s function parameter"", asString(functionType.params()[i])); default: Errors::unreachable(); } invokeArgs.push_back(value); } } // Invoke the function. Timing::Timer executionTimer; IR::ValueTuple functionResults = invokeFunctionChecked(context, functionInstance, invokeArgs); Timing::logTimer(""Invoked function"", executionTimer); if(options.functionName) { Log::printf(Log::debug, ""%s returned: %s\n"", options.functionName, asString(functionResults).c_str()); return EXIT_SUCCESS; } else if(functionResults.size() == 1 && functionResults[0].type == ValueType::i32) { return functionResults[0].i32; } else { return EXIT_SUCCESS; } }","{'deleted': [{'line_no': 119, 'char_start': 3608, 'char_end': 3686, 'line': '\t\t\tMemoryInstance* defaultMemory = Runtime::getDefaultMemory(moduleInstance);\n'}, {'line_no': 120, 'char_start': 3686, 'char_end': 3708, 'line': '\t\t\tif(!defaultMemory)\n'}, {'line_no': 128, 'char_start': 3858, 'char_end': 3898, 'line': '\t\t\tstd::vector argStrings;\n'}, {'line_no': 129, 'char_start': 3898, 'char_end': 3941, 'line': '\t\t\targStrings.push_back(options.filename);\n'}, {'line_no': 130, 'char_start': 3941, 'char_end': 3972, 'line': '\t\t\tchar** args = options.args;\n'}, {'line_no': 131, 'char_start': 3972, 'char_end': 4024, 'line': '\t\t\twhile(*args) { argStrings.push_back(*args++); };\n'}, {'line_no': 132, 'char_start': 4024, 'char_end': 4025, 'line': '\n'}, {'line_no': 133, 'char_start': 4025, 'char_end': 4103, 'line': '\t\t\tEmscripten::injectCommandArgs(emscriptenInstance, argStrings, invokeArgs);\n'}], 'added': [{'line_no': 119, 'char_start': 3608, 'char_end': 3635, 'line': '\t\t\tif(!emscriptenInstance)\n'}, {'line_no': 126, 'char_start': 3784, 'char_end': 3792, 'line': '\t\t\telse\n'}, {'line_no': 127, 'char_start': 3792, 'char_end': 3797, 'line': '\t\t\t{\n'}, {'line_no': 128, 'char_start': 3797, 'char_end': 3838, 'line': '\t\t\t\tstd::vector argStrings;\n'}, {'line_no': 129, 'char_start': 3838, 'char_end': 3882, 'line': '\t\t\t\targStrings.push_back(options.filename);\n'}, {'line_no': 130, 'char_start': 3882, 'char_end': 3914, 'line': '\t\t\t\tchar** args = options.args;\n'}, {'line_no': 131, 'char_start': 3914, 'char_end': 3967, 'line': '\t\t\t\twhile(*args) { argStrings.push_back(*args++); };\n'}, {'line_no': 133, 'char_start': 3968, 'char_end': 4004, 'line': '\t\t\t\twavmAssert(emscriptenInstance);\n'}, {'line_no': 134, 'char_start': 4004, 'char_end': 4083, 'line': '\t\t\t\tEmscripten::injectCommandArgs(emscriptenInstance, argStrings, invokeArgs);\n'}, {'line_no': 135, 'char_start': 4083, 'char_end': 4088, 'line': '\t\t\t}\n'}]}","{'deleted': [{'char_start': 3611, 'char_end': 3612, 'chars': 'M'}, {'char_start': 3614, 'char_end': 3619, 'chars': 'oryIn'}, {'char_start': 3620, 'char_end': 3623, 'chars': 'tan'}, {'char_start': 3624, 'char_end': 3638, 'chars': 'e* defaultMemo'}, {'char_start': 3639, 'char_end': 3647, 'chars': 'y = Runt'}, {'char_start': 3648, 'char_end': 3654, 'chars': 'me::ge'}, {'char_start': 3655, 'char_end': 3656, 'chars': 'D'}, {'char_start': 3657, 'char_end': 3675, 'chars': 'faultMemory(module'}, {'char_start': 3683, 'char_end': 3706, 'chars': ');\n\t\t\tif(!defaultMemory'}], 'added': [{'char_start': 3611, 'char_end': 3615, 'chars': 'if(!'}, {'char_start': 3621, 'char_end': 3622, 'chars': 'p'}, {'char_start': 3624, 'char_end': 3625, 'chars': 'n'}, {'char_start': 3784, 'char_end': 3791, 'chars': '\t\t\telse'}, {'char_start': 3795, 'char_end': 3801, 'chars': '{\n\t\t\t\t'}, {'char_start': 3838, 'char_end': 3839, 'chars': '\t'}, {'char_start': 3882, 'char_end': 3883, 'chars': '\t'}, {'char_start': 3917, 'char_end': 3918, 'chars': '\t'}, {'char_start': 3971, 'char_end': 4008, 'chars': '\twavmAssert(emscriptenInstance);\n\t\t\t\t'}, {'char_start': 4082, 'char_end': 4087, 'chars': '\n\t\t\t}'}]}",github.com/WAVM/WAVM/commit/31d670b6489e6d708c3b04b911cdf14ac43d846d,Programs/wavm/wavm.cpp,cwe-476,1429 cwe-125,gf_m2ts_process_pmt,"static void gf_m2ts_process_pmt(GF_M2TS_Demuxer *ts, GF_M2TS_SECTION_ES *pmt, GF_List *sections, u8 table_id, u16 ex_table_id, u8 version_number, u8 last_section_number, u32 status) { u32 info_length, pos, desc_len, evt_type, nb_es,i; u32 nb_sections; u32 data_size; u32 nb_hevc, nb_hevc_temp, nb_shvc, nb_shvc_temp, nb_mhvc, nb_mhvc_temp; unsigned char *data; GF_M2TS_Section *section; GF_Err e = GF_OK; /*wait for the last section */ if (!(status&GF_M2TS_TABLE_END)) return; nb_es = 0; /*skip if already received but no update detected (eg same data) */ if ((status&GF_M2TS_TABLE_REPEAT) && !(status&GF_M2TS_TABLE_UPDATE)) { if (ts->on_event) ts->on_event(ts, GF_M2TS_EVT_PMT_REPEAT, pmt->program); return; } if (pmt->sec->demux_restarted) { pmt->sec->demux_restarted = 0; return; } GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, (""[MPEG-2 TS] PMT Found or updated\n"")); nb_sections = gf_list_count(sections); if (nb_sections > 1) { GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, (""PMT on multiple sections not supported\n"")); } section = (GF_M2TS_Section *)gf_list_get(sections, 0); data = section->data; data_size = section->data_size; pmt->program->pcr_pid = ((data[0] & 0x1f) << 8) | data[1]; info_length = ((data[2]&0xf)<<8) | data[3]; if (info_length != 0) { /* ...Read Descriptors ... */ u8 tag, len; u32 first_loop_len = 0; tag = data[4]; len = data[5]; while (info_length > first_loop_len) { if (tag == GF_M2TS_MPEG4_IOD_DESCRIPTOR) { u32 size; GF_BitStream *iod_bs; iod_bs = gf_bs_new((char *)data+8, len-2, GF_BITSTREAM_READ); if (pmt->program->pmt_iod) gf_odf_desc_del((GF_Descriptor *)pmt->program->pmt_iod); e = gf_odf_parse_descriptor(iod_bs , (GF_Descriptor **) &pmt->program->pmt_iod, &size); gf_bs_del(iod_bs ); if (e==GF_OK) { /*remember program number for service/program selection*/ if (pmt->program->pmt_iod) pmt->program->pmt_iod->ServiceID = pmt->program->number; /*if empty IOD (freebox case), discard it and use dynamic declaration of object*/ if (!gf_list_count(pmt->program->pmt_iod->ESDescriptors)) { gf_odf_desc_del((GF_Descriptor *)pmt->program->pmt_iod); pmt->program->pmt_iod = NULL; } } } else if (tag == GF_M2TS_METADATA_POINTER_DESCRIPTOR) { GF_BitStream *metadatapd_bs; GF_M2TS_MetadataPointerDescriptor *metapd; metadatapd_bs = gf_bs_new((char *)data+6, len, GF_BITSTREAM_READ); metapd = gf_m2ts_read_metadata_pointer_descriptor(metadatapd_bs, len); gf_bs_del(metadatapd_bs); if (metapd->application_format_identifier == GF_M2TS_META_ID3 && metapd->format_identifier == GF_M2TS_META_ID3 && metapd->carriage_flag == METADATA_CARRIAGE_SAME_TS) { /*HLS ID3 Metadata */ pmt->program->metadata_pointer_descriptor = metapd; } else { /* don't know what to do with it for now, delete */ gf_m2ts_metadata_pointer_descriptor_del(metapd); } } else { GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, (""[MPEG-2 TS] Skipping descriptor (0x%x) and others not supported\n"", tag)); } first_loop_len += 2 + len; } } if (data_size <= 4 + info_length) return; data += 4 + info_length; data_size -= 4 + info_length; pos = 0; /* count de number of program related PMT received */ for(i=0; iprograms); i++) { GF_M2TS_Program *prog = (GF_M2TS_Program *)gf_list_get(ts->programs,i); if(prog->pmt_pid == pmt->pid) { break; } } nb_hevc = nb_hevc_temp = nb_shvc = nb_shvc_temp = nb_mhvc = nb_mhvc_temp = 0; while (poscc = -1; pes->flags = GF_M2TS_ES_IS_PES; if (inherit_pcr) pes->flags |= GF_M2TS_INHERIT_PCR; es = (GF_M2TS_ES *)pes; break; case GF_M2TS_PRIVATE_DATA: GF_SAFEALLOC(pes, GF_M2TS_PES); if (!pes) { GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (""[MPEG2TS] Failed to allocate ES for pid %d\n"", pid)); return; } pes->cc = -1; pes->flags = GF_M2TS_ES_IS_PES; es = (GF_M2TS_ES *)pes; break; /* Sections */ case GF_M2TS_SYSTEMS_MPEG4_SECTIONS: GF_SAFEALLOC(ses, GF_M2TS_SECTION_ES); if (!ses) { GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (""[MPEG2TS] Failed to allocate ES for pid %d\n"", pid)); return; } es = (GF_M2TS_ES *)ses; es->flags |= GF_M2TS_ES_IS_SECTION; /* carriage of ISO_IEC_14496 data in sections */ if (stream_type == GF_M2TS_SYSTEMS_MPEG4_SECTIONS) { /*MPEG-4 sections need to be fully checked: if one section is lost, this means we lost one SL packet in the AU so we must wait for the complete section again*/ ses->sec = gf_m2ts_section_filter_new(gf_m2ts_process_mpeg4section, 0); /*create OD container*/ if (!pmt->program->additional_ods) { pmt->program->additional_ods = gf_list_new(); ts->has_4on2 = 1; } } break; case GF_M2TS_13818_6_ANNEX_A: case GF_M2TS_13818_6_ANNEX_B: case GF_M2TS_13818_6_ANNEX_C: case GF_M2TS_13818_6_ANNEX_D: case GF_M2TS_PRIVATE_SECTION: case GF_M2TS_QUALITY_SEC: case GF_M2TS_MORE_SEC: GF_SAFEALLOC(ses, GF_M2TS_SECTION_ES); if (!ses) { GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (""[MPEG2TS] Failed to allocate ES for pid %d\n"", pid)); return; } es = (GF_M2TS_ES *)ses; es->flags |= GF_M2TS_ES_IS_SECTION; es->pid = pid; es->service_id = pmt->program->number; if (stream_type == GF_M2TS_PRIVATE_SECTION) { GF_LOG(GF_LOG_INFO, GF_LOG_CONTAINER, (""AIT sections on pid %d\n"", pid)); } else if (stream_type == GF_M2TS_QUALITY_SEC) { GF_LOG(GF_LOG_INFO, GF_LOG_CONTAINER, (""Quality metadata sections on pid %d\n"", pid)); } else if (stream_type == GF_M2TS_MORE_SEC) { GF_LOG(GF_LOG_INFO, GF_LOG_CONTAINER, (""MORE sections on pid %d\n"", pid)); } else { GF_LOG(GF_LOG_INFO, GF_LOG_CONTAINER, (""stream type DSM CC user private sections on pid %d \n"", pid)); } /* NULL means: trigger the call to on_event with DVB_GENERAL type and the raw section as payload */ ses->sec = gf_m2ts_section_filter_new(NULL, 1); //ses->sec->service_id = pmt->program->number; break; case GF_M2TS_MPE_SECTIONS: if (! ts->prefix_present) { GF_LOG(GF_LOG_INFO, GF_LOG_CONTAINER, (""stream type MPE found : pid = %d \n"", pid)); #ifdef GPAC_ENABLE_MPE es = gf_dvb_mpe_section_new(); if (es->flags & GF_M2TS_ES_IS_SECTION) { /* NULL means: trigger the call to on_event with DVB_GENERAL type and the raw section as payload */ ((GF_M2TS_SECTION_ES*)es)->sec = gf_m2ts_section_filter_new(NULL, 1); } #endif break; } default: GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, (""[MPEG-2 TS] Stream type (0x%x) for PID %d not supported\n"", stream_type, pid ) ); //GF_LOG(/*GF_LOG_WARNING*/GF_LOG_ERROR, GF_LOG_CONTAINER, (""[MPEG-2 TS] Stream type (0x%x) for PID %d not supported\n"", stream_type, pid ) ); break; } if (es) { es->stream_type = (stream_type==GF_M2TS_PRIVATE_DATA) ? 0 : stream_type; es->program = pmt->program; es->pid = pid; es->component_tag = -1; } pos += 5; data += 5; while (desc_len) { u8 tag = data[0]; u32 len = data[1]; if (es) { switch (tag) { case GF_M2TS_ISO_639_LANGUAGE_DESCRIPTOR: if (pes) pes->lang = GF_4CC(' ', data[2], data[3], data[4]); break; case GF_M2TS_MPEG4_SL_DESCRIPTOR: es->mpeg4_es_id = ( (u32) data[2] & 0x1f) << 8 | data[3]; es->flags |= GF_M2TS_ES_IS_SL; break; case GF_M2TS_REGISTRATION_DESCRIPTOR: reg_desc_format = GF_4CC(data[2], data[3], data[4], data[5]); /*cf http://www.smpte-ra.org/mpegreg/mpegreg.html*/ switch (reg_desc_format) { case GF_M2TS_RA_STREAM_AC3: es->stream_type = GF_M2TS_AUDIO_AC3; break; case GF_M2TS_RA_STREAM_VC1: es->stream_type = GF_M2TS_VIDEO_VC1; break; case GF_M2TS_RA_STREAM_GPAC: if (len==8) { es->stream_type = GF_4CC(data[6], data[7], data[8], data[9]); es->flags |= GF_M2TS_GPAC_CODEC_ID; break; } default: GF_LOG(GF_LOG_INFO, GF_LOG_CONTAINER, (""Unknown registration descriptor %s\n"", gf_4cc_to_str(reg_desc_format) )); break; } break; case GF_M2TS_DVB_EAC3_DESCRIPTOR: es->stream_type = GF_M2TS_AUDIO_EC3; break; case GF_M2TS_DVB_DATA_BROADCAST_ID_DESCRIPTOR: { u32 id = data[2]<<8 | data[3]; if ((id == 0xB) && ses && !ses->sec) { ses->sec = gf_m2ts_section_filter_new(NULL, 1); } } break; case GF_M2TS_DVB_SUBTITLING_DESCRIPTOR: if (pes) { pes->sub.language[0] = data[2]; pes->sub.language[1] = data[3]; pes->sub.language[2] = data[4]; pes->sub.type = data[5]; pes->sub.composition_page_id = (data[6]<<8) | data[7]; pes->sub.ancillary_page_id = (data[8]<<8) | data[9]; } es->stream_type = GF_M2TS_DVB_SUBTITLE; break; case GF_M2TS_DVB_STREAM_IDENTIFIER_DESCRIPTOR: { es->component_tag = data[2]; GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, (""Component Tag: %d on Program %d\n"", es->component_tag, es->program->number)); } break; case GF_M2TS_DVB_TELETEXT_DESCRIPTOR: es->stream_type = GF_M2TS_DVB_TELETEXT; break; case GF_M2TS_DVB_VBI_DATA_DESCRIPTOR: es->stream_type = GF_M2TS_DVB_VBI; break; case GF_M2TS_HIERARCHY_DESCRIPTOR: if (pes) { u8 hierarchy_embedded_layer_index; GF_BitStream *hbs = gf_bs_new((const char *)data, data_size, GF_BITSTREAM_READ); /*u32 skip = */gf_bs_read_int(hbs, 16); /*u8 res1 = */gf_bs_read_int(hbs, 1); /*u8 temp_scal = */gf_bs_read_int(hbs, 1); /*u8 spatial_scal = */gf_bs_read_int(hbs, 1); /*u8 quality_scal = */gf_bs_read_int(hbs, 1); /*u8 hierarchy_type = */gf_bs_read_int(hbs, 4); /*u8 res2 = */gf_bs_read_int(hbs, 2); /*u8 hierarchy_layer_index = */gf_bs_read_int(hbs, 6); /*u8 tref_not_present = */gf_bs_read_int(hbs, 1); /*u8 res3 = */gf_bs_read_int(hbs, 1); hierarchy_embedded_layer_index = gf_bs_read_int(hbs, 6); /*u8 res4 = */gf_bs_read_int(hbs, 2); /*u8 hierarchy_channel = */gf_bs_read_int(hbs, 6); gf_bs_del(hbs); pes->depends_on_pid = 1+hierarchy_embedded_layer_index; } break; case GF_M2TS_METADATA_DESCRIPTOR: { GF_BitStream *metadatad_bs; GF_M2TS_MetadataDescriptor *metad; metadatad_bs = gf_bs_new((char *)data+2, len, GF_BITSTREAM_READ); metad = gf_m2ts_read_metadata_descriptor(metadatad_bs, len); gf_bs_del(metadatad_bs); if (metad->application_format_identifier == GF_M2TS_META_ID3 && metad->format_identifier == GF_M2TS_META_ID3) { /*HLS ID3 Metadata */ if (pes) { pes->metadata_descriptor = metad; pes->stream_type = GF_M2TS_METADATA_ID3_HLS; } } else { /* don't know what to do with it for now, delete */ gf_m2ts_metadata_descriptor_del(metad); } } break; default: GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, (""[MPEG-2 TS] skipping descriptor (0x%x) not supported\n"", tag)); break; } } data += len+2; pos += len+2; if (desc_len < len+2) { GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (""[MPEG-2 TS] Invalid PMT es descriptor size for PID %d\n"", pid ) ); break; } desc_len-=len+2; } if (es && !es->stream_type) { gf_free(es); es = NULL; GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (""[MPEG-2 TS] Private Stream type (0x%x) for PID %d not supported\n"", stream_type, pid ) ); } if (!es) continue; if (ts->ess[pid]) { //this is component reuse across programs, overwrite the previously declared stream ... if (status & GF_M2TS_TABLE_FOUND) { GF_LOG(GF_LOG_INFO, GF_LOG_CONTAINER, (""[MPEG-2 TS] PID %d reused across programs %d and %d, not completely supported\n"", pid, ts->ess[pid]->program->number, es->program->number ) ); //add stream to program but don't reassign the pid table until the stream is playing (>GF_M2TS_PES_FRAMING_SKIP) gf_list_add(pmt->program->streams, es); if (!(es->flags & GF_M2TS_ES_IS_SECTION) ) gf_m2ts_set_pes_framing(pes, GF_M2TS_PES_FRAMING_SKIP); nb_es++; //skip assignment below es = NULL; } /*watchout for pmt update - FIXME this likely won't work in most cases*/ else { GF_M2TS_ES *o_es = ts->ess[es->pid]; if ((o_es->stream_type == es->stream_type) && ((o_es->flags & GF_M2TS_ES_STATIC_FLAGS_MASK) == (es->flags & GF_M2TS_ES_STATIC_FLAGS_MASK)) && (o_es->mpeg4_es_id == es->mpeg4_es_id) && ((o_es->flags & GF_M2TS_ES_IS_SECTION) || ((GF_M2TS_PES *)o_es)->lang == ((GF_M2TS_PES *)es)->lang) ) { gf_free(es); es = NULL; } else { gf_m2ts_es_del(o_es, ts); ts->ess[es->pid] = NULL; } } } if (es) { ts->ess[es->pid] = es; gf_list_add(pmt->program->streams, es); if (!(es->flags & GF_M2TS_ES_IS_SECTION) ) gf_m2ts_set_pes_framing(pes, GF_M2TS_PES_FRAMING_SKIP); nb_es++; } if (es->stream_type == GF_M2TS_VIDEO_HEVC) nb_hevc++; else if (es->stream_type == GF_M2TS_VIDEO_HEVC_TEMPORAL) nb_hevc_temp++; else if (es->stream_type == GF_M2TS_VIDEO_SHVC) nb_shvc++; else if (es->stream_type == GF_M2TS_VIDEO_SHVC_TEMPORAL) nb_shvc_temp++; else if (es->stream_type == GF_M2TS_VIDEO_MHVC) nb_mhvc++; else if (es->stream_type == GF_M2TS_VIDEO_MHVC_TEMPORAL) nb_mhvc_temp++; } //Table 2-139, implied hierarchy indexes if (nb_hevc_temp + nb_shvc + nb_shvc_temp + nb_mhvc+ nb_mhvc_temp) { for (i=0; iprogram->streams); i++) { GF_M2TS_PES *es = (GF_M2TS_PES *)gf_list_get(pmt->program->streams, i); if ( !(es->flags & GF_M2TS_ES_IS_PES)) continue; if (es->depends_on_pid) continue; switch (es->stream_type) { case GF_M2TS_VIDEO_HEVC_TEMPORAL: es->depends_on_pid = 1; break; case GF_M2TS_VIDEO_SHVC: if (!nb_hevc_temp) es->depends_on_pid = 1; else es->depends_on_pid = 2; break; case GF_M2TS_VIDEO_SHVC_TEMPORAL: es->depends_on_pid = 3; break; case GF_M2TS_VIDEO_MHVC: if (!nb_hevc_temp) es->depends_on_pid = 1; else es->depends_on_pid = 2; break; case GF_M2TS_VIDEO_MHVC_TEMPORAL: if (!nb_hevc_temp) es->depends_on_pid = 2; else es->depends_on_pid = 3; break; } } } if (nb_es) { u32 i; //translate hierarchy descriptors indexes into PIDs - check whether the PMT-index rules are the same for HEVC for (i=0; iprogram->streams); i++) { GF_M2TS_PES *an_es = NULL; GF_M2TS_PES *es = (GF_M2TS_PES *)gf_list_get(pmt->program->streams, i); if ( !(es->flags & GF_M2TS_ES_IS_PES)) continue; if (!es->depends_on_pid) continue; //fixeme we are not always assured that hierarchy_layer_index matches the stream index... //+1 is because our first stream is the PMT an_es = (GF_M2TS_PES *)gf_list_get(pmt->program->streams, es->depends_on_pid); if (an_es) { es->depends_on_pid = an_es->pid; } else { GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, (""[M2TS] Wrong dependency index in hierarchy descriptor, assuming non-scalable stream\n"")); es->depends_on_pid = 0; } } evt_type = (status&GF_M2TS_TABLE_FOUND) ? GF_M2TS_EVT_PMT_FOUND : GF_M2TS_EVT_PMT_UPDATE; if (ts->on_event) ts->on_event(ts, evt_type, pmt->program); } else { /* if we found no new ES it's simply a repeat of the PMT */ if (ts->on_event) ts->on_event(ts, GF_M2TS_EVT_PMT_REPEAT, pmt->program); } }","static void gf_m2ts_process_pmt(GF_M2TS_Demuxer *ts, GF_M2TS_SECTION_ES *pmt, GF_List *sections, u8 table_id, u16 ex_table_id, u8 version_number, u8 last_section_number, u32 status) { u32 info_length, pos, desc_len, evt_type, nb_es,i; u32 nb_sections; u32 data_size; u32 nb_hevc, nb_hevc_temp, nb_shvc, nb_shvc_temp, nb_mhvc, nb_mhvc_temp; unsigned char *data; GF_M2TS_Section *section; GF_Err e = GF_OK; /*wait for the last section */ if (!(status&GF_M2TS_TABLE_END)) return; nb_es = 0; /*skip if already received but no update detected (eg same data) */ if ((status&GF_M2TS_TABLE_REPEAT) && !(status&GF_M2TS_TABLE_UPDATE)) { if (ts->on_event) ts->on_event(ts, GF_M2TS_EVT_PMT_REPEAT, pmt->program); return; } if (pmt->sec->demux_restarted) { pmt->sec->demux_restarted = 0; return; } GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, (""[MPEG-2 TS] PMT Found or updated\n"")); nb_sections = gf_list_count(sections); if (nb_sections > 1) { GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, (""PMT on multiple sections not supported\n"")); } section = (GF_M2TS_Section *)gf_list_get(sections, 0); data = section->data; data_size = section->data_size; pmt->program->pcr_pid = ((data[0] & 0x1f) << 8) | data[1]; info_length = ((data[2]&0xf)<<8) | data[3]; if (info_length != 0) { /* ...Read Descriptors ... */ u8 tag, len; u32 first_loop_len = 0; tag = data[4]; len = data[5]; while (info_length > first_loop_len) { if (tag == GF_M2TS_MPEG4_IOD_DESCRIPTOR) { u32 size; GF_BitStream *iod_bs; iod_bs = gf_bs_new((char *)data+8, len-2, GF_BITSTREAM_READ); if (pmt->program->pmt_iod) gf_odf_desc_del((GF_Descriptor *)pmt->program->pmt_iod); e = gf_odf_parse_descriptor(iod_bs , (GF_Descriptor **) &pmt->program->pmt_iod, &size); gf_bs_del(iod_bs ); if (e==GF_OK) { /*remember program number for service/program selection*/ if (pmt->program->pmt_iod) pmt->program->pmt_iod->ServiceID = pmt->program->number; /*if empty IOD (freebox case), discard it and use dynamic declaration of object*/ if (!gf_list_count(pmt->program->pmt_iod->ESDescriptors)) { gf_odf_desc_del((GF_Descriptor *)pmt->program->pmt_iod); pmt->program->pmt_iod = NULL; } } } else if (tag == GF_M2TS_METADATA_POINTER_DESCRIPTOR) { GF_BitStream *metadatapd_bs; GF_M2TS_MetadataPointerDescriptor *metapd; metadatapd_bs = gf_bs_new((char *)data+6, len, GF_BITSTREAM_READ); metapd = gf_m2ts_read_metadata_pointer_descriptor(metadatapd_bs, len); gf_bs_del(metadatapd_bs); if (metapd->application_format_identifier == GF_M2TS_META_ID3 && metapd->format_identifier == GF_M2TS_META_ID3 && metapd->carriage_flag == METADATA_CARRIAGE_SAME_TS) { /*HLS ID3 Metadata */ pmt->program->metadata_pointer_descriptor = metapd; } else { /* don't know what to do with it for now, delete */ gf_m2ts_metadata_pointer_descriptor_del(metapd); } } else { GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, (""[MPEG-2 TS] Skipping descriptor (0x%x) and others not supported\n"", tag)); } first_loop_len += 2 + len; } } if (data_size <= 4 + info_length) return; data += 4 + info_length; data_size -= 4 + info_length; pos = 0; /* count de number of program related PMT received */ for(i=0; iprograms); i++) { GF_M2TS_Program *prog = (GF_M2TS_Program *)gf_list_get(ts->programs,i); if(prog->pmt_pid == pmt->pid) { break; } } nb_hevc = nb_hevc_temp = nb_shvc = nb_shvc_temp = nb_mhvc = nb_mhvc_temp = 0; while (poscc = -1; pes->flags = GF_M2TS_ES_IS_PES; if (inherit_pcr) pes->flags |= GF_M2TS_INHERIT_PCR; es = (GF_M2TS_ES *)pes; break; case GF_M2TS_PRIVATE_DATA: GF_SAFEALLOC(pes, GF_M2TS_PES); if (!pes) { GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (""[MPEG2TS] Failed to allocate ES for pid %d\n"", pid)); return; } pes->cc = -1; pes->flags = GF_M2TS_ES_IS_PES; es = (GF_M2TS_ES *)pes; break; /* Sections */ case GF_M2TS_SYSTEMS_MPEG4_SECTIONS: GF_SAFEALLOC(ses, GF_M2TS_SECTION_ES); if (!ses) { GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (""[MPEG2TS] Failed to allocate ES for pid %d\n"", pid)); return; } es = (GF_M2TS_ES *)ses; es->flags |= GF_M2TS_ES_IS_SECTION; /* carriage of ISO_IEC_14496 data in sections */ if (stream_type == GF_M2TS_SYSTEMS_MPEG4_SECTIONS) { /*MPEG-4 sections need to be fully checked: if one section is lost, this means we lost one SL packet in the AU so we must wait for the complete section again*/ ses->sec = gf_m2ts_section_filter_new(gf_m2ts_process_mpeg4section, 0); /*create OD container*/ if (!pmt->program->additional_ods) { pmt->program->additional_ods = gf_list_new(); ts->has_4on2 = 1; } } break; case GF_M2TS_13818_6_ANNEX_A: case GF_M2TS_13818_6_ANNEX_B: case GF_M2TS_13818_6_ANNEX_C: case GF_M2TS_13818_6_ANNEX_D: case GF_M2TS_PRIVATE_SECTION: case GF_M2TS_QUALITY_SEC: case GF_M2TS_MORE_SEC: GF_SAFEALLOC(ses, GF_M2TS_SECTION_ES); if (!ses) { GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (""[MPEG2TS] Failed to allocate ES for pid %d\n"", pid)); return; } es = (GF_M2TS_ES *)ses; es->flags |= GF_M2TS_ES_IS_SECTION; es->pid = pid; es->service_id = pmt->program->number; if (stream_type == GF_M2TS_PRIVATE_SECTION) { GF_LOG(GF_LOG_INFO, GF_LOG_CONTAINER, (""AIT sections on pid %d\n"", pid)); } else if (stream_type == GF_M2TS_QUALITY_SEC) { GF_LOG(GF_LOG_INFO, GF_LOG_CONTAINER, (""Quality metadata sections on pid %d\n"", pid)); } else if (stream_type == GF_M2TS_MORE_SEC) { GF_LOG(GF_LOG_INFO, GF_LOG_CONTAINER, (""MORE sections on pid %d\n"", pid)); } else { GF_LOG(GF_LOG_INFO, GF_LOG_CONTAINER, (""stream type DSM CC user private sections on pid %d \n"", pid)); } /* NULL means: trigger the call to on_event with DVB_GENERAL type and the raw section as payload */ ses->sec = gf_m2ts_section_filter_new(NULL, 1); //ses->sec->service_id = pmt->program->number; break; case GF_M2TS_MPE_SECTIONS: if (! ts->prefix_present) { GF_LOG(GF_LOG_INFO, GF_LOG_CONTAINER, (""stream type MPE found : pid = %d \n"", pid)); #ifdef GPAC_ENABLE_MPE es = gf_dvb_mpe_section_new(); if (es->flags & GF_M2TS_ES_IS_SECTION) { /* NULL means: trigger the call to on_event with DVB_GENERAL type and the raw section as payload */ ((GF_M2TS_SECTION_ES*)es)->sec = gf_m2ts_section_filter_new(NULL, 1); } #endif break; } default: GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, (""[MPEG-2 TS] Stream type (0x%x) for PID %d not supported\n"", stream_type, pid ) ); //GF_LOG(/*GF_LOG_WARNING*/GF_LOG_ERROR, GF_LOG_CONTAINER, (""[MPEG-2 TS] Stream type (0x%x) for PID %d not supported\n"", stream_type, pid ) ); break; } if (es) { es->stream_type = (stream_type==GF_M2TS_PRIVATE_DATA) ? 0 : stream_type; es->program = pmt->program; es->pid = pid; es->component_tag = -1; } pos += 5; data += 5; while (desc_len) { u8 tag = data[0]; u32 len = data[1]; if (es) { switch (tag) { case GF_M2TS_ISO_639_LANGUAGE_DESCRIPTOR: if (pes) pes->lang = GF_4CC(' ', data[2], data[3], data[4]); break; case GF_M2TS_MPEG4_SL_DESCRIPTOR: es->mpeg4_es_id = ( (u32) data[2] & 0x1f) << 8 | data[3]; es->flags |= GF_M2TS_ES_IS_SL; break; case GF_M2TS_REGISTRATION_DESCRIPTOR: reg_desc_format = GF_4CC(data[2], data[3], data[4], data[5]); /*cf http://www.smpte-ra.org/mpegreg/mpegreg.html*/ switch (reg_desc_format) { case GF_M2TS_RA_STREAM_AC3: es->stream_type = GF_M2TS_AUDIO_AC3; break; case GF_M2TS_RA_STREAM_VC1: es->stream_type = GF_M2TS_VIDEO_VC1; break; case GF_M2TS_RA_STREAM_GPAC: if (len==8) { es->stream_type = GF_4CC(data[6], data[7], data[8], data[9]); es->flags |= GF_M2TS_GPAC_CODEC_ID; break; } default: GF_LOG(GF_LOG_INFO, GF_LOG_CONTAINER, (""Unknown registration descriptor %s\n"", gf_4cc_to_str(reg_desc_format) )); break; } break; case GF_M2TS_DVB_EAC3_DESCRIPTOR: es->stream_type = GF_M2TS_AUDIO_EC3; break; case GF_M2TS_DVB_DATA_BROADCAST_ID_DESCRIPTOR: { u32 id = data[2]<<8 | data[3]; if ((id == 0xB) && ses && !ses->sec) { ses->sec = gf_m2ts_section_filter_new(NULL, 1); } } break; case GF_M2TS_DVB_SUBTITLING_DESCRIPTOR: if (pes) { pes->sub.language[0] = data[2]; pes->sub.language[1] = data[3]; pes->sub.language[2] = data[4]; pes->sub.type = data[5]; pes->sub.composition_page_id = (data[6]<<8) | data[7]; pes->sub.ancillary_page_id = (data[8]<<8) | data[9]; } es->stream_type = GF_M2TS_DVB_SUBTITLE; break; case GF_M2TS_DVB_STREAM_IDENTIFIER_DESCRIPTOR: { es->component_tag = data[2]; GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, (""Component Tag: %d on Program %d\n"", es->component_tag, es->program->number)); } break; case GF_M2TS_DVB_TELETEXT_DESCRIPTOR: es->stream_type = GF_M2TS_DVB_TELETEXT; break; case GF_M2TS_DVB_VBI_DATA_DESCRIPTOR: es->stream_type = GF_M2TS_DVB_VBI; break; case GF_M2TS_HIERARCHY_DESCRIPTOR: if (pes) { u8 hierarchy_embedded_layer_index; GF_BitStream *hbs = gf_bs_new((const char *)data, data_size, GF_BITSTREAM_READ); /*u32 skip = */gf_bs_read_int(hbs, 16); /*u8 res1 = */gf_bs_read_int(hbs, 1); /*u8 temp_scal = */gf_bs_read_int(hbs, 1); /*u8 spatial_scal = */gf_bs_read_int(hbs, 1); /*u8 quality_scal = */gf_bs_read_int(hbs, 1); /*u8 hierarchy_type = */gf_bs_read_int(hbs, 4); /*u8 res2 = */gf_bs_read_int(hbs, 2); /*u8 hierarchy_layer_index = */gf_bs_read_int(hbs, 6); /*u8 tref_not_present = */gf_bs_read_int(hbs, 1); /*u8 res3 = */gf_bs_read_int(hbs, 1); hierarchy_embedded_layer_index = gf_bs_read_int(hbs, 6); /*u8 res4 = */gf_bs_read_int(hbs, 2); /*u8 hierarchy_channel = */gf_bs_read_int(hbs, 6); gf_bs_del(hbs); pes->depends_on_pid = 1+hierarchy_embedded_layer_index; } break; case GF_M2TS_METADATA_DESCRIPTOR: { GF_BitStream *metadatad_bs; GF_M2TS_MetadataDescriptor *metad; metadatad_bs = gf_bs_new((char *)data+2, len, GF_BITSTREAM_READ); metad = gf_m2ts_read_metadata_descriptor(metadatad_bs, len); gf_bs_del(metadatad_bs); if (metad->application_format_identifier == GF_M2TS_META_ID3 && metad->format_identifier == GF_M2TS_META_ID3) { /*HLS ID3 Metadata */ if (pes) { pes->metadata_descriptor = metad; pes->stream_type = GF_M2TS_METADATA_ID3_HLS; } } else { /* don't know what to do with it for now, delete */ gf_m2ts_metadata_descriptor_del(metad); } } break; default: GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, (""[MPEG-2 TS] skipping descriptor (0x%x) not supported\n"", tag)); break; } } data += len+2; pos += len+2; if (desc_len < len+2) { GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (""[MPEG-2 TS] Invalid PMT es descriptor size for PID %d\n"", pid ) ); break; } desc_len-=len+2; } if (es && !es->stream_type) { gf_free(es); es = NULL; GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (""[MPEG-2 TS] Private Stream type (0x%x) for PID %d not supported\n"", stream_type, pid ) ); } if (!es) continue; if (ts->ess[pid]) { //this is component reuse across programs, overwrite the previously declared stream ... if (status & GF_M2TS_TABLE_FOUND) { GF_LOG(GF_LOG_INFO, GF_LOG_CONTAINER, (""[MPEG-2 TS] PID %d reused across programs %d and %d, not completely supported\n"", pid, ts->ess[pid]->program->number, es->program->number ) ); //add stream to program but don't reassign the pid table until the stream is playing (>GF_M2TS_PES_FRAMING_SKIP) gf_list_add(pmt->program->streams, es); if (!(es->flags & GF_M2TS_ES_IS_SECTION) ) gf_m2ts_set_pes_framing(pes, GF_M2TS_PES_FRAMING_SKIP); nb_es++; //skip assignment below es = NULL; } /*watchout for pmt update - FIXME this likely won't work in most cases*/ else { GF_M2TS_ES *o_es = ts->ess[es->pid]; if ((o_es->stream_type == es->stream_type) && ((o_es->flags & GF_M2TS_ES_STATIC_FLAGS_MASK) == (es->flags & GF_M2TS_ES_STATIC_FLAGS_MASK)) && (o_es->mpeg4_es_id == es->mpeg4_es_id) && ((o_es->flags & GF_M2TS_ES_IS_SECTION) || ((GF_M2TS_PES *)o_es)->lang == ((GF_M2TS_PES *)es)->lang) ) { gf_free(es); es = NULL; } else { gf_m2ts_es_del(o_es, ts); ts->ess[es->pid] = NULL; } } } if (es) { ts->ess[es->pid] = es; gf_list_add(pmt->program->streams, es); if (!(es->flags & GF_M2TS_ES_IS_SECTION) ) gf_m2ts_set_pes_framing(pes, GF_M2TS_PES_FRAMING_SKIP); nb_es++; if (es->stream_type == GF_M2TS_VIDEO_HEVC) nb_hevc++; else if (es->stream_type == GF_M2TS_VIDEO_HEVC_TEMPORAL) nb_hevc_temp++; else if (es->stream_type == GF_M2TS_VIDEO_SHVC) nb_shvc++; else if (es->stream_type == GF_M2TS_VIDEO_SHVC_TEMPORAL) nb_shvc_temp++; else if (es->stream_type == GF_M2TS_VIDEO_MHVC) nb_mhvc++; else if (es->stream_type == GF_M2TS_VIDEO_MHVC_TEMPORAL) nb_mhvc_temp++; } } //Table 2-139, implied hierarchy indexes if (nb_hevc_temp + nb_shvc + nb_shvc_temp + nb_mhvc+ nb_mhvc_temp) { for (i=0; iprogram->streams); i++) { GF_M2TS_PES *es = (GF_M2TS_PES *)gf_list_get(pmt->program->streams, i); if ( !(es->flags & GF_M2TS_ES_IS_PES)) continue; if (es->depends_on_pid) continue; switch (es->stream_type) { case GF_M2TS_VIDEO_HEVC_TEMPORAL: es->depends_on_pid = 1; break; case GF_M2TS_VIDEO_SHVC: if (!nb_hevc_temp) es->depends_on_pid = 1; else es->depends_on_pid = 2; break; case GF_M2TS_VIDEO_SHVC_TEMPORAL: es->depends_on_pid = 3; break; case GF_M2TS_VIDEO_MHVC: if (!nb_hevc_temp) es->depends_on_pid = 1; else es->depends_on_pid = 2; break; case GF_M2TS_VIDEO_MHVC_TEMPORAL: if (!nb_hevc_temp) es->depends_on_pid = 2; else es->depends_on_pid = 3; break; } } } if (nb_es) { u32 i; //translate hierarchy descriptors indexes into PIDs - check whether the PMT-index rules are the same for HEVC for (i=0; iprogram->streams); i++) { GF_M2TS_PES *an_es = NULL; GF_M2TS_PES *es = (GF_M2TS_PES *)gf_list_get(pmt->program->streams, i); if ( !(es->flags & GF_M2TS_ES_IS_PES)) continue; if (!es->depends_on_pid) continue; //fixeme we are not always assured that hierarchy_layer_index matches the stream index... //+1 is because our first stream is the PMT an_es = (GF_M2TS_PES *)gf_list_get(pmt->program->streams, es->depends_on_pid); if (an_es) { es->depends_on_pid = an_es->pid; } else { GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, (""[M2TS] Wrong dependency index in hierarchy descriptor, assuming non-scalable stream\n"")); es->depends_on_pid = 0; } } evt_type = (status&GF_M2TS_TABLE_FOUND) ? GF_M2TS_EVT_PMT_FOUND : GF_M2TS_EVT_PMT_UPDATE; if (ts->on_event) ts->on_event(ts, evt_type, pmt->program); } else { /* if we found no new ES it's simply a repeat of the PMT */ if (ts->on_event) ts->on_event(ts, GF_M2TS_EVT_PMT_REPEAT, pmt->program); } }","{'deleted': [{'line_no': 413, 'char_start': 14239, 'char_end': 14243, 'line': '\t\t}\n'}, {'line_no': 415, 'char_start': 14244, 'char_end': 14300, 'line': '\t\tif (es->stream_type == GF_M2TS_VIDEO_HEVC) nb_hevc++;\n'}, {'line_no': 416, 'char_start': 14300, 'char_end': 14375, 'line': '\t\telse if (es->stream_type == GF_M2TS_VIDEO_HEVC_TEMPORAL) nb_hevc_temp++;\n'}, {'line_no': 417, 'char_start': 14375, 'char_end': 14436, 'line': '\t\telse if (es->stream_type == GF_M2TS_VIDEO_SHVC) nb_shvc++;\n'}, {'line_no': 418, 'char_start': 14436, 'char_end': 14511, 'line': '\t\telse if (es->stream_type == GF_M2TS_VIDEO_SHVC_TEMPORAL) nb_shvc_temp++;\n'}, {'line_no': 419, 'char_start': 14511, 'char_end': 14572, 'line': '\t\telse if (es->stream_type == GF_M2TS_VIDEO_MHVC) nb_mhvc++;\n'}, {'line_no': 420, 'char_start': 14572, 'char_end': 14647, 'line': '\t\telse if (es->stream_type == GF_M2TS_VIDEO_MHVC_TEMPORAL) nb_mhvc_temp++;\n'}], 'added': [{'line_no': 414, 'char_start': 14240, 'char_end': 14297, 'line': '\t\t\tif (es->stream_type == GF_M2TS_VIDEO_HEVC) nb_hevc++;\n'}, {'line_no': 415, 'char_start': 14297, 'char_end': 14373, 'line': '\t\t\telse if (es->stream_type == GF_M2TS_VIDEO_HEVC_TEMPORAL) nb_hevc_temp++;\n'}, {'line_no': 416, 'char_start': 14373, 'char_end': 14435, 'line': '\t\t\telse if (es->stream_type == GF_M2TS_VIDEO_SHVC) nb_shvc++;\n'}, {'line_no': 417, 'char_start': 14435, 'char_end': 14511, 'line': '\t\t\telse if (es->stream_type == GF_M2TS_VIDEO_SHVC_TEMPORAL) nb_shvc_temp++;\n'}, {'line_no': 418, 'char_start': 14511, 'char_end': 14573, 'line': '\t\t\telse if (es->stream_type == GF_M2TS_VIDEO_MHVC) nb_mhvc++;\n'}, {'line_no': 419, 'char_start': 14573, 'char_end': 14649, 'line': '\t\t\telse if (es->stream_type == GF_M2TS_VIDEO_MHVC_TEMPORAL) nb_mhvc_temp++;\n'}, {'line_no': 420, 'char_start': 14649, 'char_end': 14653, 'line': '\t\t}\n'}]}","{'deleted': [{'char_start': 14239, 'char_end': 14240, 'chars': '\t'}, {'char_start': 14241, 'char_end': 14244, 'chars': '}\n\n'}], 'added': [{'char_start': 14240, 'char_end': 14241, 'chars': '\t'}, {'char_start': 14297, 'char_end': 14298, 'chars': '\t'}, {'char_start': 14373, 'char_end': 14374, 'chars': '\t'}, {'char_start': 14437, 'char_end': 14438, 'chars': '\t'}, {'char_start': 14511, 'char_end': 14512, 'chars': '\t'}, {'char_start': 14575, 'char_end': 14576, 'chars': '\t'}, {'char_start': 14648, 'char_end': 14652, 'chars': '\n\t\t}'}]}",github.com/gpac/gpac/commit/2320eb73afba753b39b7147be91f7be7afc0eeb7,src/media_tools/mpegts.c,cwe-125,5704 cwe-079,DeletionConfirmationDlg::DeletionConfirmationDlg," DeletionConfirmationDlg(QWidget *parent, const int &size, const QString &name, bool defaultDeleteFiles): QDialog(parent) { setupUi(this); if (size == 1) label->setText(tr(""Are you sure you want to delete '%1' from the transfer list?"", ""Are you sure you want to delete 'ubuntu-linux-iso' from the transfer list?"").arg(name)); else label->setText(tr(""Are you sure you want to delete these %1 torrents from the transfer list?"", ""Are you sure you want to delete these 5 torrents from the transfer list?"").arg(QString::number(size))); // Icons lbl_warn->setPixmap(GuiIconProvider::instance()->getIcon(""dialog-warning"").pixmap(lbl_warn->height())); lbl_warn->setFixedWidth(lbl_warn->height()); rememberBtn->setIcon(GuiIconProvider::instance()->getIcon(""object-locked"")); move(Utils::Misc::screenCenter(this)); checkPermDelete->setChecked(defaultDeleteFiles || Preferences::instance()->deleteTorrentFilesAsDefault()); connect(checkPermDelete, SIGNAL(clicked()), this, SLOT(updateRememberButtonState())); buttonBox->button(QDialogButtonBox::Cancel)->setFocus(); }"," DeletionConfirmationDlg(QWidget *parent, const int &size, const QString &name, bool defaultDeleteFiles): QDialog(parent) { setupUi(this); if (size == 1) label->setText(tr(""Are you sure you want to delete '%1' from the transfer list?"", ""Are you sure you want to delete 'ubuntu-linux-iso' from the transfer list?"").arg(Utils::String::toHtmlEscaped(name))); else label->setText(tr(""Are you sure you want to delete these %1 torrents from the transfer list?"", ""Are you sure you want to delete these 5 torrents from the transfer list?"").arg(QString::number(size))); // Icons lbl_warn->setPixmap(GuiIconProvider::instance()->getIcon(""dialog-warning"").pixmap(lbl_warn->height())); lbl_warn->setFixedWidth(lbl_warn->height()); rememberBtn->setIcon(GuiIconProvider::instance()->getIcon(""object-locked"")); move(Utils::Misc::screenCenter(this)); checkPermDelete->setChecked(defaultDeleteFiles || Preferences::instance()->deleteTorrentFilesAsDefault()); connect(checkPermDelete, SIGNAL(clicked()), this, SLOT(updateRememberButtonState())); buttonBox->button(QDialogButtonBox::Cancel)->setFocus(); }","{'deleted': [{'line_no': 4, 'char_start': 163, 'char_end': 341, 'line': ' label->setText(tr(""Are you sure you want to delete \'%1\' from the transfer list?"", ""Are you sure you want to delete \'ubuntu-linux-iso\' from the transfer list?"").arg(name));\n'}], 'added': [{'line_no': 4, 'char_start': 163, 'char_end': 371, 'line': ' label->setText(tr(""Are you sure you want to delete \'%1\' from the transfer list?"", ""Are you sure you want to delete \'ubuntu-linux-iso\' from the transfer list?"").arg(Utils::String::toHtmlEscaped(name)));\n'}]}","{'deleted': [], 'added': [{'char_start': 333, 'char_end': 362, 'chars': 'Utils::String::toHtmlEscaped('}, {'char_start': 366, 'char_end': 367, 'chars': ')'}]}",github.com/qbittorrent/qBittorrent/commit/6ca3e4f094da0a0017cb2d483ec1db6176bb0b16,src/gui/deletionconfirmationdlg.h,cwe-079,259 cwe-079,init_settings," def init_settings(self, ipython_app, kernel_manager, contents_manager, cluster_manager, session_manager, kernel_spec_manager, config_manager, log, base_url, default_url, settings_overrides, jinja_env_options=None): _template_path = settings_overrides.get( ""template_path"", ipython_app.template_file_path, ) if isinstance(_template_path, py3compat.string_types): _template_path = (_template_path,) template_path = [os.path.expanduser(path) for path in _template_path] jenv_opt = jinja_env_options if jinja_env_options else {} env = Environment(loader=FileSystemLoader(template_path), **jenv_opt) sys_info = get_sys_info() if sys_info['commit_source'] == 'repository': # don't cache (rely on 304) when working from master version_hash = '' else: # reset the cache on server restart version_hash = datetime.datetime.now().strftime(""%Y%m%d%H%M%S"") settings = dict( # basics log_function=log_request, base_url=base_url, default_url=default_url, template_path=template_path, static_path=ipython_app.static_file_path, static_handler_class = FileFindHandler, static_url_prefix = url_path_join(base_url,'/static/'), static_handler_args = { # don't cache custom.js 'no_cache_paths': [url_path_join(base_url, 'static', 'custom')], }, version_hash=version_hash, # authentication cookie_secret=ipython_app.cookie_secret, login_url=url_path_join(base_url,'/login'), login_handler_class=ipython_app.login_handler_class, logout_handler_class=ipython_app.logout_handler_class, password=ipython_app.password, # managers kernel_manager=kernel_manager, contents_manager=contents_manager, cluster_manager=cluster_manager, session_manager=session_manager, kernel_spec_manager=kernel_spec_manager, config_manager=config_manager, # IPython stuff jinja_template_vars=ipython_app.jinja_template_vars, nbextensions_path=ipython_app.nbextensions_path, websocket_url=ipython_app.websocket_url, mathjax_url=ipython_app.mathjax_url, config=ipython_app.config, jinja2_env=env, terminals_available=False, # Set later if terminals are available ) # allow custom overrides for the tornado web app. settings.update(settings_overrides) return settings"," def init_settings(self, ipython_app, kernel_manager, contents_manager, cluster_manager, session_manager, kernel_spec_manager, config_manager, log, base_url, default_url, settings_overrides, jinja_env_options=None): _template_path = settings_overrides.get( ""template_path"", ipython_app.template_file_path, ) if isinstance(_template_path, py3compat.string_types): _template_path = (_template_path,) template_path = [os.path.expanduser(path) for path in _template_path] jenv_opt = {""autoescape"": True} jenv_opt.update(jinja_env_options if jinja_env_options else {}) env = Environment(loader=FileSystemLoader(template_path), **jenv_opt) sys_info = get_sys_info() if sys_info['commit_source'] == 'repository': # don't cache (rely on 304) when working from master version_hash = '' else: # reset the cache on server restart version_hash = datetime.datetime.now().strftime(""%Y%m%d%H%M%S"") settings = dict( # basics log_function=log_request, base_url=base_url, default_url=default_url, template_path=template_path, static_path=ipython_app.static_file_path, static_handler_class = FileFindHandler, static_url_prefix = url_path_join(base_url,'/static/'), static_handler_args = { # don't cache custom.js 'no_cache_paths': [url_path_join(base_url, 'static', 'custom')], }, version_hash=version_hash, # authentication cookie_secret=ipython_app.cookie_secret, login_url=url_path_join(base_url,'/login'), login_handler_class=ipython_app.login_handler_class, logout_handler_class=ipython_app.logout_handler_class, password=ipython_app.password, # managers kernel_manager=kernel_manager, contents_manager=contents_manager, cluster_manager=cluster_manager, session_manager=session_manager, kernel_spec_manager=kernel_spec_manager, config_manager=config_manager, # IPython stuff jinja_template_vars=ipython_app.jinja_template_vars, nbextensions_path=ipython_app.nbextensions_path, websocket_url=ipython_app.websocket_url, mathjax_url=ipython_app.mathjax_url, config=ipython_app.config, jinja2_env=env, terminals_available=False, # Set later if terminals are available ) # allow custom overrides for the tornado web app. settings.update(settings_overrides) return settings","{'deleted': [{'line_no': 15, 'char_start': 629, 'char_end': 695, 'line': ' jenv_opt = jinja_env_options if jinja_env_options else {}\n'}], 'added': [{'line_no': 15, 'char_start': 629, 'char_end': 669, 'line': ' jenv_opt = {""autoescape"": True}\n'}, {'line_no': 16, 'char_start': 669, 'char_end': 741, 'line': ' jenv_opt.update(jinja_env_options if jinja_env_options else {})\n'}, {'line_no': 17, 'char_start': 741, 'char_end': 742, 'line': '\n'}]}","{'deleted': [], 'added': [{'char_start': 648, 'char_end': 693, 'chars': '{""autoescape"": True}\n jenv_opt.update('}, {'char_start': 739, 'char_end': 741, 'chars': ')\n'}]}",github.com/ipython/ipython/commit/3ab41641cf6fce3860c73d5cf4645aa12e1e5892,IPython/html/notebookapp.py,cwe-079,546 cwe-190,set_geometry,"static int set_geometry(unsigned int cmd, struct floppy_struct *g, int drive, int type, struct block_device *bdev) { int cnt; /* sanity checking for parameters. */ if (g->sect <= 0 || g->head <= 0 || /* check for zero in F_SECT_PER_TRACK */ (unsigned char)((g->sect << 2) >> FD_SIZECODE(g)) == 0 || g->track <= 0 || g->track > UDP->tracks >> STRETCH(g) || /* check if reserved bits are set */ (g->stretch & ~(FD_STRETCH | FD_SWAPSIDES | FD_SECTBASEMASK)) != 0) return -EINVAL; if (type) { if (!capable(CAP_SYS_ADMIN)) return -EPERM; mutex_lock(&open_lock); if (lock_fdc(drive)) { mutex_unlock(&open_lock); return -EINTR; } floppy_type[type] = *g; floppy_type[type].name = ""user format""; for (cnt = type << 2; cnt < (type << 2) + 4; cnt++) floppy_sizes[cnt] = floppy_sizes[cnt + 0x80] = floppy_type[type].size + 1; process_fd_request(); for (cnt = 0; cnt < N_DRIVE; cnt++) { struct block_device *bdev = opened_bdev[cnt]; if (!bdev || ITYPE(drive_state[cnt].fd_device) != type) continue; __invalidate_device(bdev, true); } mutex_unlock(&open_lock); } else { int oldStretch; if (lock_fdc(drive)) return -EINTR; if (cmd != FDDEFPRM) { /* notice a disk change immediately, else * we lose our settings immediately*/ if (poll_drive(true, FD_RAW_NEED_DISK) == -EINTR) return -EINTR; } oldStretch = g->stretch; user_params[drive] = *g; if (buffer_drive == drive) SUPBOUND(buffer_max, user_params[drive].sect); current_type[drive] = &user_params[drive]; floppy_sizes[drive] = user_params[drive].size; if (cmd == FDDEFPRM) DRS->keep_data = -1; else DRS->keep_data = 1; /* invalidation. Invalidate only when needed, i.e. * when there are already sectors in the buffer cache * whose number will change. This is useful, because * mtools often changes the geometry of the disk after * looking at the boot block */ if (DRS->maxblock > user_params[drive].sect || DRS->maxtrack || ((user_params[drive].sect ^ oldStretch) & (FD_SWAPSIDES | FD_SECTBASEMASK))) invalidate_drive(bdev); else process_fd_request(); } return 0; }","static int set_geometry(unsigned int cmd, struct floppy_struct *g, int drive, int type, struct block_device *bdev) { int cnt; /* sanity checking for parameters. */ if ((int)g->sect <= 0 || (int)g->head <= 0 || /* check for overflow in max_sector */ (int)(g->sect * g->head) <= 0 || /* check for zero in F_SECT_PER_TRACK */ (unsigned char)((g->sect << 2) >> FD_SIZECODE(g)) == 0 || g->track <= 0 || g->track > UDP->tracks >> STRETCH(g) || /* check if reserved bits are set */ (g->stretch & ~(FD_STRETCH | FD_SWAPSIDES | FD_SECTBASEMASK)) != 0) return -EINVAL; if (type) { if (!capable(CAP_SYS_ADMIN)) return -EPERM; mutex_lock(&open_lock); if (lock_fdc(drive)) { mutex_unlock(&open_lock); return -EINTR; } floppy_type[type] = *g; floppy_type[type].name = ""user format""; for (cnt = type << 2; cnt < (type << 2) + 4; cnt++) floppy_sizes[cnt] = floppy_sizes[cnt + 0x80] = floppy_type[type].size + 1; process_fd_request(); for (cnt = 0; cnt < N_DRIVE; cnt++) { struct block_device *bdev = opened_bdev[cnt]; if (!bdev || ITYPE(drive_state[cnt].fd_device) != type) continue; __invalidate_device(bdev, true); } mutex_unlock(&open_lock); } else { int oldStretch; if (lock_fdc(drive)) return -EINTR; if (cmd != FDDEFPRM) { /* notice a disk change immediately, else * we lose our settings immediately*/ if (poll_drive(true, FD_RAW_NEED_DISK) == -EINTR) return -EINTR; } oldStretch = g->stretch; user_params[drive] = *g; if (buffer_drive == drive) SUPBOUND(buffer_max, user_params[drive].sect); current_type[drive] = &user_params[drive]; floppy_sizes[drive] = user_params[drive].size; if (cmd == FDDEFPRM) DRS->keep_data = -1; else DRS->keep_data = 1; /* invalidation. Invalidate only when needed, i.e. * when there are already sectors in the buffer cache * whose number will change. This is useful, because * mtools often changes the geometry of the disk after * looking at the boot block */ if (DRS->maxblock > user_params[drive].sect || DRS->maxtrack || ((user_params[drive].sect ^ oldStretch) & (FD_SWAPSIDES | FD_SECTBASEMASK))) invalidate_drive(bdev); else process_fd_request(); } return 0; }","{'deleted': [{'line_no': 7, 'char_start': 177, 'char_end': 198, 'line': '\tif (g->sect <= 0 ||\n'}, {'line_no': 8, 'char_start': 198, 'char_end': 219, 'line': '\t g->head <= 0 ||\n'}], 'added': [{'line_no': 7, 'char_start': 177, 'char_end': 203, 'line': '\tif ((int)g->sect <= 0 ||\n'}, {'line_no': 8, 'char_start': 203, 'char_end': 229, 'line': '\t (int)g->head <= 0 ||\n'}, {'line_no': 9, 'char_start': 229, 'char_end': 273, 'line': '\t /* check for overflow in max_sector */\n'}, {'line_no': 10, 'char_start': 273, 'char_end': 311, 'line': '\t (int)(g->sect * g->head) <= 0 ||\n'}]}","{'deleted': [], 'added': [{'char_start': 182, 'char_end': 187, 'chars': '(int)'}, {'char_start': 208, 'char_end': 213, 'chars': '(int)'}, {'char_start': 220, 'char_end': 302, 'chars': ' <= 0 ||\n\t /* check for overflow in max_sector */\n\t (int)(g->sect * g->head)'}]}",github.com/torvalds/linux/commit/da99466ac243f15fbba65bd261bfc75ffa1532b6,drivers/block/floppy.c,cwe-190,676 cwe-476,chmd_read_headers,"static int chmd_read_headers(struct mspack_system *sys, struct mspack_file *fh, struct mschmd_header *chm, int entire) { unsigned int section, name_len, x, errors, num_chunks; unsigned char buf[0x54], *chunk = NULL, *name, *p, *end; struct mschmd_file *fi, *link = NULL; off_t offset, length; int num_entries; /* initialise pointers */ chm->files = NULL; chm->sysfiles = NULL; chm->chunk_cache = NULL; chm->sec0.base.chm = chm; chm->sec0.base.id = 0; chm->sec1.base.chm = chm; chm->sec1.base.id = 1; chm->sec1.content = NULL; chm->sec1.control = NULL; chm->sec1.spaninfo = NULL; chm->sec1.rtable = NULL; /* read the first header */ if (sys->read(fh, &buf[0], chmhead_SIZEOF) != chmhead_SIZEOF) { return MSPACK_ERR_READ; } /* check ITSF signature */ if (EndGetI32(&buf[chmhead_Signature]) != 0x46535449) { return MSPACK_ERR_SIGNATURE; } /* check both header GUIDs */ if (mspack_memcmp(&buf[chmhead_GUID1], &guids[0], 32L) != 0) { D((""incorrect GUIDs"")) return MSPACK_ERR_SIGNATURE; } chm->version = EndGetI32(&buf[chmhead_Version]); chm->timestamp = EndGetM32(&buf[chmhead_Timestamp]); chm->language = EndGetI32(&buf[chmhead_LanguageID]); if (chm->version > 3) { sys->message(fh, ""WARNING; CHM version > 3""); } /* read the header section table */ if (sys->read(fh, &buf[0], chmhst3_SIZEOF) != chmhst3_SIZEOF) { return MSPACK_ERR_READ; } /* chmhst3_OffsetCS0 does not exist in version 1 or 2 CHM files. * The offset will be corrected later, once HS1 is read. */ if (read_off64(&offset, &buf[chmhst_OffsetHS0], sys, fh) || read_off64(&chm->dir_offset, &buf[chmhst_OffsetHS1], sys, fh) || read_off64(&chm->sec0.offset, &buf[chmhst3_OffsetCS0], sys, fh)) { return MSPACK_ERR_DATAFORMAT; } /* seek to header section 0 */ if (sys->seek(fh, offset, MSPACK_SYS_SEEK_START)) { return MSPACK_ERR_SEEK; } /* read header section 0 */ if (sys->read(fh, &buf[0], chmhs0_SIZEOF) != chmhs0_SIZEOF) { return MSPACK_ERR_READ; } if (read_off64(&chm->length, &buf[chmhs0_FileLen], sys, fh)) { return MSPACK_ERR_DATAFORMAT; } /* seek to header section 1 */ if (sys->seek(fh, chm->dir_offset, MSPACK_SYS_SEEK_START)) { return MSPACK_ERR_SEEK; } /* read header section 1 */ if (sys->read(fh, &buf[0], chmhs1_SIZEOF) != chmhs1_SIZEOF) { return MSPACK_ERR_READ; } chm->dir_offset = sys->tell(fh); chm->chunk_size = EndGetI32(&buf[chmhs1_ChunkSize]); chm->density = EndGetI32(&buf[chmhs1_Density]); chm->depth = EndGetI32(&buf[chmhs1_Depth]); chm->index_root = EndGetI32(&buf[chmhs1_IndexRoot]); chm->num_chunks = EndGetI32(&buf[chmhs1_NumChunks]); chm->first_pmgl = EndGetI32(&buf[chmhs1_FirstPMGL]); chm->last_pmgl = EndGetI32(&buf[chmhs1_LastPMGL]); if (chm->version < 3) { /* versions before 3 don't have chmhst3_OffsetCS0 */ chm->sec0.offset = chm->dir_offset + (chm->chunk_size * chm->num_chunks); } /* check if content offset or file size is wrong */ if (chm->sec0.offset > chm->length) { D((""content section begins after file has ended"")) return MSPACK_ERR_DATAFORMAT; } /* ensure there are chunks and that chunk size is * large enough for signature and num_entries */ if (chm->chunk_size < (pmgl_Entries + 2)) { D((""chunk size not large enough"")) return MSPACK_ERR_DATAFORMAT; } if (chm->num_chunks == 0) { D((""no chunks"")) return MSPACK_ERR_DATAFORMAT; } /* The chunk_cache data structure is not great; large values for num_chunks * or num_chunks*chunk_size can exhaust all memory. Until a better chunk * cache is implemented, put arbitrary limits on num_chunks and chunk size. */ if (chm->num_chunks > 100000) { D((""more than 100,000 chunks"")) return MSPACK_ERR_DATAFORMAT; } if ((off_t)chm->chunk_size * (off_t)chm->num_chunks > chm->length) { D((""chunks larger than entire file"")) return MSPACK_ERR_DATAFORMAT; } /* common sense checks on header section 1 fields */ if ((chm->chunk_size & (chm->chunk_size - 1)) != 0) { sys->message(fh, ""WARNING; chunk size is not a power of two""); } if (chm->first_pmgl != 0) { sys->message(fh, ""WARNING; first PMGL chunk is not zero""); } if (chm->first_pmgl > chm->last_pmgl) { D((""first pmgl chunk is after last pmgl chunk"")) return MSPACK_ERR_DATAFORMAT; } if (chm->index_root != 0xFFFFFFFF && chm->index_root >= chm->num_chunks) { D((""index_root outside valid range"")) return MSPACK_ERR_DATAFORMAT; } /* if we are doing a quick read, stop here! */ if (!entire) { return MSPACK_ERR_OK; } /* seek to the first PMGL chunk, and reduce the number of chunks to read */ if ((x = chm->first_pmgl) != 0) { if (sys->seek(fh,(off_t) (x * chm->chunk_size), MSPACK_SYS_SEEK_CUR)) { return MSPACK_ERR_SEEK; } } num_chunks = chm->last_pmgl - x + 1; if (!(chunk = (unsigned char *) sys->alloc(sys, (size_t)chm->chunk_size))) { return MSPACK_ERR_NOMEMORY; } /* read and process all chunks from FirstPMGL to LastPMGL */ errors = 0; while (num_chunks--) { /* read next chunk */ if (sys->read(fh, chunk, (int)chm->chunk_size) != (int)chm->chunk_size) { sys->free(chunk); return MSPACK_ERR_READ; } /* process only directory (PMGL) chunks */ if (EndGetI32(&chunk[pmgl_Signature]) != 0x4C474D50) continue; if (EndGetI32(&chunk[pmgl_QuickRefSize]) < 2) { sys->message(fh, ""WARNING; PMGL quickref area is too small""); } if (EndGetI32(&chunk[pmgl_QuickRefSize]) > ((int)chm->chunk_size - pmgl_Entries)) { sys->message(fh, ""WARNING; PMGL quickref area is too large""); } p = &chunk[pmgl_Entries]; end = &chunk[chm->chunk_size - 2]; num_entries = EndGetI16(end); while (num_entries--) { READ_ENCINT(name_len); if (name_len > (unsigned int) (end - p)) goto chunk_end; /* consider blank filenames to be an error */ if (name_len == 0) goto chunk_end; name = p; p += name_len; READ_ENCINT(section); READ_ENCINT(offset); READ_ENCINT(length); /* empty files and directory names are stored as a file entry at * offset 0 with length 0. We want to keep empty files, but not * directory names, which end with a ""/"" */ if ((offset == 0) && (length == 0)) { if ((name_len > 0) && (name[name_len-1] == '/')) continue; } if (section > 1) { sys->message(fh, ""invalid section number '%u'."", section); continue; } if (!(fi = (struct mschmd_file *) sys->alloc(sys, sizeof(struct mschmd_file) + name_len + 1))) { sys->free(chunk); return MSPACK_ERR_NOMEMORY; } fi->next = NULL; fi->filename = (char *) &fi[1]; fi->section = ((section == 0) ? (struct mschmd_section *) (&chm->sec0) : (struct mschmd_section *) (&chm->sec1)); fi->offset = offset; fi->length = length; sys->copy(name, fi->filename, (size_t) name_len); fi->filename[name_len] = '\0'; if (name[0] == ':' && name[1] == ':') { /* system file */ if (mspack_memcmp(&name[2], &content_name[2], 31L) == 0) { if (mspack_memcmp(&name[33], &content_name[33], 8L) == 0) { chm->sec1.content = fi; } else if (mspack_memcmp(&name[33], &control_name[33], 11L) == 0) { chm->sec1.control = fi; } else if (mspack_memcmp(&name[33], &spaninfo_name[33], 8L) == 0) { chm->sec1.spaninfo = fi; } else if (mspack_memcmp(&name[33], &rtable_name[33], 72L) == 0) { chm->sec1.rtable = fi; } } fi->next = chm->sysfiles; chm->sysfiles = fi; } else { /* normal file */ if (link) link->next = fi; else chm->files = fi; link = fi; } } /* this is reached either when num_entries runs out, or if * reading data from the chunk reached a premature end of chunk */ chunk_end: if (num_entries >= 0) { D((""chunk ended before all entries could be read"")) errors++; } } sys->free(chunk); return (errors > 0) ? MSPACK_ERR_DATAFORMAT : MSPACK_ERR_OK; }","static int chmd_read_headers(struct mspack_system *sys, struct mspack_file *fh, struct mschmd_header *chm, int entire) { unsigned int section, name_len, x, errors, num_chunks; unsigned char buf[0x54], *chunk = NULL, *name, *p, *end; struct mschmd_file *fi, *link = NULL; off_t offset, length; int num_entries; /* initialise pointers */ chm->files = NULL; chm->sysfiles = NULL; chm->chunk_cache = NULL; chm->sec0.base.chm = chm; chm->sec0.base.id = 0; chm->sec1.base.chm = chm; chm->sec1.base.id = 1; chm->sec1.content = NULL; chm->sec1.control = NULL; chm->sec1.spaninfo = NULL; chm->sec1.rtable = NULL; /* read the first header */ if (sys->read(fh, &buf[0], chmhead_SIZEOF) != chmhead_SIZEOF) { return MSPACK_ERR_READ; } /* check ITSF signature */ if (EndGetI32(&buf[chmhead_Signature]) != 0x46535449) { return MSPACK_ERR_SIGNATURE; } /* check both header GUIDs */ if (mspack_memcmp(&buf[chmhead_GUID1], &guids[0], 32L) != 0) { D((""incorrect GUIDs"")) return MSPACK_ERR_SIGNATURE; } chm->version = EndGetI32(&buf[chmhead_Version]); chm->timestamp = EndGetM32(&buf[chmhead_Timestamp]); chm->language = EndGetI32(&buf[chmhead_LanguageID]); if (chm->version > 3) { sys->message(fh, ""WARNING; CHM version > 3""); } /* read the header section table */ if (sys->read(fh, &buf[0], chmhst3_SIZEOF) != chmhst3_SIZEOF) { return MSPACK_ERR_READ; } /* chmhst3_OffsetCS0 does not exist in version 1 or 2 CHM files. * The offset will be corrected later, once HS1 is read. */ if (read_off64(&offset, &buf[chmhst_OffsetHS0], sys, fh) || read_off64(&chm->dir_offset, &buf[chmhst_OffsetHS1], sys, fh) || read_off64(&chm->sec0.offset, &buf[chmhst3_OffsetCS0], sys, fh)) { return MSPACK_ERR_DATAFORMAT; } /* seek to header section 0 */ if (sys->seek(fh, offset, MSPACK_SYS_SEEK_START)) { return MSPACK_ERR_SEEK; } /* read header section 0 */ if (sys->read(fh, &buf[0], chmhs0_SIZEOF) != chmhs0_SIZEOF) { return MSPACK_ERR_READ; } if (read_off64(&chm->length, &buf[chmhs0_FileLen], sys, fh)) { return MSPACK_ERR_DATAFORMAT; } /* seek to header section 1 */ if (sys->seek(fh, chm->dir_offset, MSPACK_SYS_SEEK_START)) { return MSPACK_ERR_SEEK; } /* read header section 1 */ if (sys->read(fh, &buf[0], chmhs1_SIZEOF) != chmhs1_SIZEOF) { return MSPACK_ERR_READ; } chm->dir_offset = sys->tell(fh); chm->chunk_size = EndGetI32(&buf[chmhs1_ChunkSize]); chm->density = EndGetI32(&buf[chmhs1_Density]); chm->depth = EndGetI32(&buf[chmhs1_Depth]); chm->index_root = EndGetI32(&buf[chmhs1_IndexRoot]); chm->num_chunks = EndGetI32(&buf[chmhs1_NumChunks]); chm->first_pmgl = EndGetI32(&buf[chmhs1_FirstPMGL]); chm->last_pmgl = EndGetI32(&buf[chmhs1_LastPMGL]); if (chm->version < 3) { /* versions before 3 don't have chmhst3_OffsetCS0 */ chm->sec0.offset = chm->dir_offset + (chm->chunk_size * chm->num_chunks); } /* check if content offset or file size is wrong */ if (chm->sec0.offset > chm->length) { D((""content section begins after file has ended"")) return MSPACK_ERR_DATAFORMAT; } /* ensure there are chunks and that chunk size is * large enough for signature and num_entries */ if (chm->chunk_size < (pmgl_Entries + 2)) { D((""chunk size not large enough"")) return MSPACK_ERR_DATAFORMAT; } if (chm->num_chunks == 0) { D((""no chunks"")) return MSPACK_ERR_DATAFORMAT; } /* The chunk_cache data structure is not great; large values for num_chunks * or num_chunks*chunk_size can exhaust all memory. Until a better chunk * cache is implemented, put arbitrary limits on num_chunks and chunk size. */ if (chm->num_chunks > 100000) { D((""more than 100,000 chunks"")) return MSPACK_ERR_DATAFORMAT; } if ((off_t)chm->chunk_size * (off_t)chm->num_chunks > chm->length) { D((""chunks larger than entire file"")) return MSPACK_ERR_DATAFORMAT; } /* common sense checks on header section 1 fields */ if ((chm->chunk_size & (chm->chunk_size - 1)) != 0) { sys->message(fh, ""WARNING; chunk size is not a power of two""); } if (chm->first_pmgl != 0) { sys->message(fh, ""WARNING; first PMGL chunk is not zero""); } if (chm->first_pmgl > chm->last_pmgl) { D((""first pmgl chunk is after last pmgl chunk"")) return MSPACK_ERR_DATAFORMAT; } if (chm->index_root != 0xFFFFFFFF && chm->index_root >= chm->num_chunks) { D((""index_root outside valid range"")) return MSPACK_ERR_DATAFORMAT; } /* if we are doing a quick read, stop here! */ if (!entire) { return MSPACK_ERR_OK; } /* seek to the first PMGL chunk, and reduce the number of chunks to read */ if ((x = chm->first_pmgl) != 0) { if (sys->seek(fh,(off_t) (x * chm->chunk_size), MSPACK_SYS_SEEK_CUR)) { return MSPACK_ERR_SEEK; } } num_chunks = chm->last_pmgl - x + 1; if (!(chunk = (unsigned char *) sys->alloc(sys, (size_t)chm->chunk_size))) { return MSPACK_ERR_NOMEMORY; } /* read and process all chunks from FirstPMGL to LastPMGL */ errors = 0; while (num_chunks--) { /* read next chunk */ if (sys->read(fh, chunk, (int)chm->chunk_size) != (int)chm->chunk_size) { sys->free(chunk); return MSPACK_ERR_READ; } /* process only directory (PMGL) chunks */ if (EndGetI32(&chunk[pmgl_Signature]) != 0x4C474D50) continue; if (EndGetI32(&chunk[pmgl_QuickRefSize]) < 2) { sys->message(fh, ""WARNING; PMGL quickref area is too small""); } if (EndGetI32(&chunk[pmgl_QuickRefSize]) > ((int)chm->chunk_size - pmgl_Entries)) { sys->message(fh, ""WARNING; PMGL quickref area is too large""); } p = &chunk[pmgl_Entries]; end = &chunk[chm->chunk_size - 2]; num_entries = EndGetI16(end); while (num_entries--) { READ_ENCINT(name_len); if (name_len > (unsigned int) (end - p)) goto chunk_end; name = p; p += name_len; READ_ENCINT(section); READ_ENCINT(offset); READ_ENCINT(length); /* ignore blank or one-char (e.g. ""/"") filenames we'd return as blank */ if (name_len < 2 || !name[0] || !name[1]) continue; /* empty files and directory names are stored as a file entry at * offset 0 with length 0. We want to keep empty files, but not * directory names, which end with a ""/"" */ if ((offset == 0) && (length == 0)) { if ((name_len > 0) && (name[name_len-1] == '/')) continue; } if (section > 1) { sys->message(fh, ""invalid section number '%u'."", section); continue; } if (!(fi = (struct mschmd_file *) sys->alloc(sys, sizeof(struct mschmd_file) + name_len + 1))) { sys->free(chunk); return MSPACK_ERR_NOMEMORY; } fi->next = NULL; fi->filename = (char *) &fi[1]; fi->section = ((section == 0) ? (struct mschmd_section *) (&chm->sec0) : (struct mschmd_section *) (&chm->sec1)); fi->offset = offset; fi->length = length; sys->copy(name, fi->filename, (size_t) name_len); fi->filename[name_len] = '\0'; if (name[0] == ':' && name[1] == ':') { /* system file */ if (mspack_memcmp(&name[2], &content_name[2], 31L) == 0) { if (mspack_memcmp(&name[33], &content_name[33], 8L) == 0) { chm->sec1.content = fi; } else if (mspack_memcmp(&name[33], &control_name[33], 11L) == 0) { chm->sec1.control = fi; } else if (mspack_memcmp(&name[33], &spaninfo_name[33], 8L) == 0) { chm->sec1.spaninfo = fi; } else if (mspack_memcmp(&name[33], &rtable_name[33], 72L) == 0) { chm->sec1.rtable = fi; } } fi->next = chm->sysfiles; chm->sysfiles = fi; } else { /* normal file */ if (link) link->next = fi; else chm->files = fi; link = fi; } } /* this is reached either when num_entries runs out, or if * reading data from the chunk reached a premature end of chunk */ chunk_end: if (num_entries >= 0) { D((""chunk ended before all entries could be read"")) errors++; } } sys->free(chunk); return (errors > 0) ? MSPACK_ERR_DATAFORMAT : MSPACK_ERR_OK; }","{'deleted': [{'line_no': 189, 'char_start': 6005, 'char_end': 6057, 'line': ' /* consider blank filenames to be an error */\n'}, {'line_no': 190, 'char_start': 6057, 'char_end': 6098, 'line': ' if (name_len == 0) goto chunk_end;\n'}, {'line_no': 192, 'char_start': 6129, 'char_end': 6130, 'line': '\n'}], 'added': [{'line_no': 194, 'char_start': 6119, 'char_end': 6198, 'line': ' /* ignore blank or one-char (e.g. ""/"") filenames we\'d return as blank */\n'}, {'line_no': 195, 'char_start': 6198, 'char_end': 6256, 'line': ' if (name_len < 2 || !name[0] || !name[1]) continue;\n'}, {'line_no': 196, 'char_start': 6256, 'char_end': 6257, 'line': '\n'}]}","{'deleted': [{'char_start': 6011, 'char_end': 6104, 'chars': '/* consider blank filenames to be an error */\n if (name_len == 0) goto chunk_end;\n '}, {'char_start': 6128, 'char_end': 6129, 'chars': '\n'}], 'added': [{'char_start': 6116, 'char_end': 6254, 'chars': ';\n\n /* ignore blank or one-char (e.g. ""/"") filenames we\'d return as blank */\n if (name_len < 2 || !name[0] || !name[1]) continue'}]}",github.com/kyz/libmspack/commit/8759da8db6ec9e866cb8eb143313f397f925bb4f,libmspack/mspack/chmd.c,cwe-476,2672 cwe-190,layer_resize,"layer_resize(int layer, int x_size, int y_size) { int old_height; int old_width; struct map_tile* tile; int tile_width; int tile_height; struct map_tile* tilemap; struct map_trigger* trigger; struct map_zone* zone; int x, y, i; old_width = s_map->layers[layer].width; old_height = s_map->layers[layer].height; // allocate a new tilemap and copy the old layer tiles into it. we can't simply realloc // because the tilemap is a 2D array. if (!(tilemap = malloc(x_size * y_size * sizeof(struct map_tile)))) return false; for (x = 0; x < x_size; ++x) { for (y = 0; y < y_size; ++y) { if (x < old_width && y < old_height) { tilemap[x + y * x_size] = s_map->layers[layer].tilemap[x + y * old_width]; } else { tile = &tilemap[x + y * x_size]; tile->frames_left = tileset_get_delay(s_map->tileset, 0); tile->tile_index = 0; } } } // free the old tilemap and substitute the new one free(s_map->layers[layer].tilemap); s_map->layers[layer].tilemap = tilemap; s_map->layers[layer].width = x_size; s_map->layers[layer].height = y_size; // if we resize the largest layer, the overall map size will change. // recalcuate it. tileset_get_size(s_map->tileset, &tile_width, &tile_height); s_map->width = 0; s_map->height = 0; for (i = 0; i < s_map->num_layers; ++i) { if (!s_map->layers[i].is_parallax) { s_map->width = fmax(s_map->width, s_map->layers[i].width * tile_width); s_map->height = fmax(s_map->height, s_map->layers[i].height * tile_height); } } // ensure zones and triggers remain in-bounds. if any are completely // out-of-bounds, delete them. for (i = (int)vector_len(s_map->zones) - 1; i >= 0; --i) { zone = vector_get(s_map->zones, i); if (zone->bounds.x1 >= s_map->width || zone->bounds.y1 >= s_map->height) vector_remove(s_map->zones, i); else { if (zone->bounds.x2 > s_map->width) zone->bounds.x2 = s_map->width; if (zone->bounds.y2 > s_map->height) zone->bounds.y2 = s_map->height; } } for (i = (int)vector_len(s_map->triggers) - 1; i >= 0; --i) { trigger = vector_get(s_map->triggers, i); if (trigger->x >= s_map->width || trigger->y >= s_map->height) vector_remove(s_map->triggers, i); } return true; }","layer_resize(int layer, int x_size, int y_size) { int old_height; int old_width; struct map_tile* tile; int tile_width; int tile_height; struct map_tile* tilemap; struct map_trigger* trigger; struct map_zone* zone; size_t tilemap_size; int x, y, i; old_width = s_map->layers[layer].width; old_height = s_map->layers[layer].height; // allocate a new tilemap and copy the old layer tiles into it. we can't simply realloc // because the tilemap is a 2D array. tilemap_size = x_size * y_size * sizeof(struct map_tile); if (x_size == 0 || tilemap_size / x_size / sizeof(struct map_tile) != y_size || !(tilemap = malloc(tilemap_size))) return false; for (x = 0; x < x_size; ++x) { for (y = 0; y < y_size; ++y) { if (x < old_width && y < old_height) { tilemap[x + y * x_size] = s_map->layers[layer].tilemap[x + y * old_width]; } else { tile = &tilemap[x + y * x_size]; tile->frames_left = tileset_get_delay(s_map->tileset, 0); tile->tile_index = 0; } } } // free the old tilemap and substitute the new one free(s_map->layers[layer].tilemap); s_map->layers[layer].tilemap = tilemap; s_map->layers[layer].width = x_size; s_map->layers[layer].height = y_size; // if we resize the largest layer, the overall map size will change. // recalcuate it. tileset_get_size(s_map->tileset, &tile_width, &tile_height); s_map->width = 0; s_map->height = 0; for (i = 0; i < s_map->num_layers; ++i) { if (!s_map->layers[i].is_parallax) { s_map->width = fmax(s_map->width, s_map->layers[i].width * tile_width); s_map->height = fmax(s_map->height, s_map->layers[i].height * tile_height); } } // ensure zones and triggers remain in-bounds. if any are completely // out-of-bounds, delete them. for (i = (int)vector_len(s_map->zones) - 1; i >= 0; --i) { zone = vector_get(s_map->zones, i); if (zone->bounds.x1 >= s_map->width || zone->bounds.y1 >= s_map->height) vector_remove(s_map->zones, i); else { if (zone->bounds.x2 > s_map->width) zone->bounds.x2 = s_map->width; if (zone->bounds.y2 > s_map->height) zone->bounds.y2 = s_map->height; } } for (i = (int)vector_len(s_map->triggers) - 1; i >= 0; --i) { trigger = vector_get(s_map->triggers, i); if (trigger->x >= s_map->width || trigger->y >= s_map->height) vector_remove(s_map->triggers, i); } return true; }","{'deleted': [{'line_no': 19, 'char_start': 526, 'char_end': 595, 'line': '\tif (!(tilemap = malloc(x_size * y_size * sizeof(struct map_tile))))\n'}], 'added': [{'line_no': 11, 'char_start': 296, 'char_end': 331, 'line': '\tsize_t tilemap_size;\n'}, {'line_no': 20, 'char_start': 561, 'char_end': 620, 'line': '\ttilemap_size = x_size * y_size * sizeof(struct map_tile);\n'}, {'line_no': 21, 'char_start': 620, 'char_end': 698, 'line': '\tif (x_size == 0 || tilemap_size / x_size / sizeof(struct map_tile) != y_size\n'}, {'line_no': 22, 'char_start': 698, 'char_end': 738, 'line': '\t\t|| !(tilemap = malloc(tilemap_size)))\n'}]}","{'deleted': [{'char_start': 527, 'char_end': 533, 'chars': 'if (!('}, {'char_start': 546, 'char_end': 549, 'chars': 'loc'}, {'char_start': 557, 'char_end': 558, 'chars': '*'}, {'char_start': 559, 'char_end': 560, 'chars': 'y'}, {'char_start': 566, 'char_end': 567, 'chars': '*'}], 'added': [{'char_start': 296, 'char_end': 331, 'chars': '\tsize_t tilemap_size;\n'}, {'char_start': 569, 'char_end': 574, 'chars': '_size'}, {'char_start': 577, 'char_end': 609, 'chars': 'x_size * y_size * sizeof(struct '}, {'char_start': 611, 'char_end': 615, 'chars': 'p_ti'}, {'char_start': 616, 'char_end': 624, 'chars': 'e);\n\tif '}, {'char_start': 632, 'char_end': 652, 'chars': '== 0 || tilemap_size'}, {'char_start': 653, 'char_end': 656, 'chars': '/ x'}, {'char_start': 662, 'char_end': 663, 'chars': '/'}, {'char_start': 687, 'char_end': 734, 'chars': ' != y_size\n\t\t|| !(tilemap = malloc(tilemap_size'}]}",github.com/fatcerberus/minisphere/commit/252c1ca184cb38e1acb917aa0e451c5f08519996,src/minisphere/map_engine.c,cwe-190,719 cwe-089,patch," @jwt_required def patch(self, user_id): """""" Replaces information of corresponding user_id with request body """""" query = f""""""update users set user_id = %s """""" query += f""""""where user_id = '{user_id}'"""""" json_data = request.get_json() parameters = (json_data['user_id'], ) database_utilities.execute_query(query, parameters)"," @jwt_required def patch(self, user_id): """""" Replaces information of corresponding user_id with request body """""" query = f""""""update users set user_id = %s """""" query += f""""""where user_id = %s"""""" json_data = request.get_json() parameters = (json_data['user_id'], user_id) database_utilities.execute_query(query, parameters)","{'deleted': [{'line_no': 5, 'char_start': 182, 'char_end': 234, 'line': ' query += f""""""where user_id = \'{user_id}\'""""""\n'}, {'line_no': 7, 'char_start': 273, 'char_end': 319, 'line': "" parameters = (json_data['user_id'], )\n""}], 'added': [{'line_no': 5, 'char_start': 182, 'char_end': 225, 'line': ' query += f""""""where user_id = %s""""""\n'}, {'line_no': 7, 'char_start': 264, 'char_end': 317, 'line': "" parameters = (json_data['user_id'], user_id)\n""}]}","{'deleted': [{'char_start': 219, 'char_end': 222, 'chars': ""'{u""}, {'char_start': 223, 'char_end': 230, 'chars': ""er_id}'""}], 'added': [{'char_start': 219, 'char_end': 220, 'chars': '%'}, {'char_start': 308, 'char_end': 315, 'chars': 'user_id'}]}",github.com/sgosal2/tiger-boards-backend/commit/4670109dd613df2f2fe7e8403ebd149df2b55485,apis/users.py,cwe-089,82 cwe-125,load_tile,"static MagickBooleanType load_tile(Image *image,Image *tile_image, XCFDocInfo *inDocInfo,XCFLayerInfo *inLayerInfo,size_t data_length, ExceptionInfo *exception) { ssize_t y; register ssize_t x; register Quantum *q; ssize_t count; unsigned char *graydata; XCFPixelInfo *xcfdata, *xcfodata; xcfdata=(XCFPixelInfo *) AcquireQuantumMemory(data_length,sizeof(*xcfdata)); if (xcfdata == (XCFPixelInfo *) NULL) ThrowBinaryException(ResourceLimitError,""MemoryAllocationFailed"", image->filename); xcfodata=xcfdata; graydata=(unsigned char *) xcfdata; /* used by gray and indexed */ count=ReadBlob(image,data_length,(unsigned char *) xcfdata); if (count != (ssize_t) data_length) ThrowBinaryException(CorruptImageError,""NotEnoughPixelData"", image->filename); for (y=0; y < (ssize_t) tile_image->rows; y++) { q=GetAuthenticPixels(tile_image,0,y,tile_image->columns,1,exception); if (q == (Quantum *) NULL) break; if (inDocInfo->image_type == GIMP_GRAY) { for (x=0; x < (ssize_t) tile_image->columns; x++) { SetPixelGray(tile_image,ScaleCharToQuantum(*graydata),q); SetPixelAlpha(tile_image,ScaleCharToQuantum((unsigned char) inLayerInfo->alpha),q); graydata++; q+=GetPixelChannels(tile_image); } } else if (inDocInfo->image_type == GIMP_RGB) { for (x=0; x < (ssize_t) tile_image->columns; x++) { SetPixelRed(tile_image,ScaleCharToQuantum(xcfdata->red),q); SetPixelGreen(tile_image,ScaleCharToQuantum(xcfdata->green),q); SetPixelBlue(tile_image,ScaleCharToQuantum(xcfdata->blue),q); SetPixelAlpha(tile_image,xcfdata->alpha == 255U ? TransparentAlpha : ScaleCharToQuantum((unsigned char) inLayerInfo->alpha),q); xcfdata++; q+=GetPixelChannels(tile_image); } } if (SyncAuthenticPixels(tile_image,exception) == MagickFalse) break; } xcfodata=(XCFPixelInfo *) RelinquishMagickMemory(xcfodata); return MagickTrue; }","static MagickBooleanType load_tile(Image *image,Image *tile_image, XCFDocInfo *inDocInfo,XCFLayerInfo *inLayerInfo,size_t data_length, ExceptionInfo *exception) { ssize_t y; register ssize_t x; register Quantum *q; ssize_t count; unsigned char *graydata; XCFPixelInfo *xcfdata, *xcfodata; xcfdata=(XCFPixelInfo *) AcquireQuantumMemory(MagickMax(data_length, tile_image->columns*tile_image->rows),sizeof(*xcfdata)); if (xcfdata == (XCFPixelInfo *) NULL) ThrowBinaryException(ResourceLimitError,""MemoryAllocationFailed"", image->filename); xcfodata=xcfdata; graydata=(unsigned char *) xcfdata; /* used by gray and indexed */ count=ReadBlob(image,data_length,(unsigned char *) xcfdata); if (count != (ssize_t) data_length) ThrowBinaryException(CorruptImageError,""NotEnoughPixelData"", image->filename); for (y=0; y < (ssize_t) tile_image->rows; y++) { q=GetAuthenticPixels(tile_image,0,y,tile_image->columns,1,exception); if (q == (Quantum *) NULL) break; if (inDocInfo->image_type == GIMP_GRAY) { for (x=0; x < (ssize_t) tile_image->columns; x++) { SetPixelGray(tile_image,ScaleCharToQuantum(*graydata),q); SetPixelAlpha(tile_image,ScaleCharToQuantum((unsigned char) inLayerInfo->alpha),q); graydata++; q+=GetPixelChannels(tile_image); } } else if (inDocInfo->image_type == GIMP_RGB) { for (x=0; x < (ssize_t) tile_image->columns; x++) { SetPixelRed(tile_image,ScaleCharToQuantum(xcfdata->red),q); SetPixelGreen(tile_image,ScaleCharToQuantum(xcfdata->green),q); SetPixelBlue(tile_image,ScaleCharToQuantum(xcfdata->blue),q); SetPixelAlpha(tile_image,xcfdata->alpha == 255U ? TransparentAlpha : ScaleCharToQuantum((unsigned char) inLayerInfo->alpha),q); xcfdata++; q+=GetPixelChannels(tile_image); } } if (SyncAuthenticPixels(tile_image,exception) == MagickFalse) break; } xcfodata=(XCFPixelInfo *) RelinquishMagickMemory(xcfodata); return MagickTrue; }","{'deleted': [{'line_no': 24, 'char_start': 339, 'char_end': 418, 'line': ' xcfdata=(XCFPixelInfo *) AcquireQuantumMemory(data_length,sizeof(*xcfdata));\n'}], 'added': [{'line_no': 24, 'char_start': 339, 'char_end': 410, 'line': ' xcfdata=(XCFPixelInfo *) AcquireQuantumMemory(MagickMax(data_length,\n'}, {'line_no': 25, 'char_start': 410, 'char_end': 471, 'line': ' tile_image->columns*tile_image->rows),sizeof(*xcfdata));\n'}]}","{'deleted': [], 'added': [{'char_start': 387, 'char_end': 397, 'chars': 'MagickMax('}, {'char_start': 408, 'char_end': 451, 'chars': ',\n tile_image->columns*tile_image->rows)'}]}",github.com/ImageMagick/ImageMagick/commit/a2e1064f288a353bc5fef7f79ccb7683759e775c,coders/xcf.c,cwe-125,589 cwe-089,fetch_resultSet," def fetch_resultSet(self, session, id): self._openContainer(session) sid = str(id) if (self.idNormalizer is not None): sid = self.idNormalizer.process_string(session, sid) query = (""SELECT class, data FROM %s WHERE identifier = '%s';"" % (self.table, sid) ) res = self._query(query) try: rdict = res.dictresult()[0] except IndexError: raise ObjectDoesNotExistException('%s/%s' % (self.id, sid)) data = rdict['data'] try: ndata = pg.unescape_bytea(data) except: # Insufficient PyGreSQL version ndata = data.replace(""\\'"", ""'"") ndata = ndata.replace('\\000', '\x00') ndata = ndata.replace('\\012', '\n') # data is res.dictresult() cl = rdict['class'] rset = dynamic.buildObject(session, cl, [[]]) rset.deserialize(session, ndata) rset.id = id # Update expires now = time.time() nowStr = time.strftime(""%Y-%m-%d %H:%M:%S"", time.gmtime(now)) expires = now + self.get_default(session, 'expires', 600) rset.timeExpires = expires expiresStr = time.strftime(""%Y-%m-%d %H:%M:%S"", time.gmtime(expires)) query = (""UPDATE %s SET timeAccessed = '%s', expires = '%s' "" ""WHERE identifier = '%s';"" % (self.table, nowStr, expiresStr, sid) ) self._query(query) return rset"," def fetch_resultSet(self, session, id): self._openContainer(session) sid = str(id) if (self.idNormalizer is not None): sid = self.idNormalizer.process_string(session, sid) query = (""SELECT class, data FROM %s WHERE identifier = $1;"" % (self.table) ) res = self._query(query, sid) try: rdict = res.dictresult()[0] except IndexError: raise ObjectDoesNotExistException('%s/%s' % (self.id, sid)) data = rdict['data'] try: ndata = pg.unescape_bytea(data) except: # Insufficient PyGreSQL version ndata = data.replace(""\\'"", ""'"") ndata = ndata.replace('\\000', '\x00') ndata = ndata.replace('\\012', '\n') # data is res.dictresult() cl = rdict['class'] rset = dynamic.buildObject(session, cl, [[]]) rset.deserialize(session, ndata) rset.id = id # Update expires now = time.time() nowStr = time.strftime(""%Y-%m-%d %H:%M:%S"", time.gmtime(now)) expires = now + self.get_default(session, 'expires', 600) rset.timeExpires = expires expiresStr = time.strftime(""%Y-%m-%d %H:%M:%S"", time.gmtime(expires)) query = (""UPDATE %s SET timeAccessed = $1, expires = $2 "" ""WHERE identifier = $3;"" % (self.table) ) self._query(query, nowStr, expiresStr, sid) return rset","{'deleted': [{'line_no': 7, 'char_start': 213, 'char_end': 286, 'line': ' query = (""SELECT class, data FROM %s WHERE identifier = \'%s\';"" %\n'}, {'line_no': 8, 'char_start': 286, 'char_end': 321, 'line': ' (self.table, sid)\n'}, {'line_no': 10, 'char_start': 340, 'char_end': 373, 'line': ' res = self._query(query)\n'}, {'line_no': 38, 'char_start': 1291, 'char_end': 1361, 'line': ' query = (""UPDATE %s SET timeAccessed = \'%s\', expires = \'%s\' ""\n'}, {'line_no': 39, 'char_start': 1361, 'char_end': 1407, 'line': ' ""WHERE identifier = \'%s\';"" %\n'}, {'line_no': 40, 'char_start': 1407, 'char_end': 1462, 'line': ' (self.table, nowStr, expiresStr, sid)\n'}, {'line_no': 42, 'char_start': 1481, 'char_end': 1508, 'line': ' self._query(query)\n'}], 'added': [{'line_no': 7, 'char_start': 213, 'char_end': 284, 'line': ' query = (""SELECT class, data FROM %s WHERE identifier = $1;"" %\n'}, {'line_no': 8, 'char_start': 284, 'char_end': 314, 'line': ' (self.table)\n'}, {'line_no': 10, 'char_start': 333, 'char_end': 371, 'line': ' res = self._query(query, sid)\n'}, {'line_no': 38, 'char_start': 1289, 'char_end': 1355, 'line': ' query = (""UPDATE %s SET timeAccessed = $1, expires = $2 ""\n'}, {'line_no': 39, 'char_start': 1355, 'char_end': 1412, 'line': ' ""WHERE identifier = $3;"" % (self.table)\n'}, {'line_no': 41, 'char_start': 1431, 'char_end': 1483, 'line': ' self._query(query, nowStr, expiresStr, sid)\n'}]}","{'deleted': [{'char_start': 277, 'char_end': 281, 'chars': ""'%s'""}, {'char_start': 314, 'char_end': 319, 'chars': ', sid'}, {'char_start': 1338, 'char_end': 1342, 'chars': ""'%s'""}, {'char_start': 1354, 'char_end': 1358, 'chars': ""'%s'""}, {'char_start': 1398, 'char_end': 1402, 'chars': ""'%s'""}, {'char_start': 1406, 'char_end': 1423, 'chars': '\n '}, {'char_start': 1435, 'char_end': 1460, 'chars': ', nowStr, expiresStr, sid'}], 'added': [{'char_start': 277, 'char_end': 279, 'chars': '$1'}, {'char_start': 364, 'char_end': 369, 'chars': ', sid'}, {'char_start': 1336, 'char_end': 1338, 'chars': '$1'}, {'char_start': 1350, 'char_end': 1352, 'chars': '$2'}, {'char_start': 1392, 'char_end': 1394, 'chars': '$3'}, {'char_start': 1456, 'char_end': 1481, 'chars': ', nowStr, expiresStr, sid'}]}",github.com/cheshire3/cheshire3/commit/d350363b4ea10f102c24c8f26d7b76b006323e8e,cheshire3/sql/resultSetStore.py,cwe-089,382 cwe-079,get," @handler.unsupported_on_local_server @handler.get(handler.HTML) def get(self): """"""Handle a get request."""""" self.render( 'login.html', { 'apiKey': local_config.ProjectConfig().get('firebase.api_key'), 'authDomain': auth.auth_domain(), 'dest': self.request.get('dest'), })"," @handler.unsupported_on_local_server @handler.get(handler.HTML) def get(self): """"""Handle a get request."""""" dest = self.request.get('dest') base_handler.check_redirect_url(dest) self.render( 'login.html', { 'apiKey': local_config.ProjectConfig().get('firebase.api_key'), 'authDomain': auth.auth_domain(), 'dest': dest, })","{'deleted': [{'line_no': 9, 'char_start': 280, 'char_end': 326, 'line': "" 'dest': self.request.get('dest'),\n""}], 'added': [{'line_no': 5, 'char_start': 117, 'char_end': 153, 'line': "" dest = self.request.get('dest')\n""}, {'line_no': 6, 'char_start': 153, 'char_end': 195, 'line': ' base_handler.check_redirect_url(dest)\n'}, {'line_no': 7, 'char_start': 195, 'char_end': 196, 'line': '\n'}, {'line_no': 12, 'char_start': 359, 'char_end': 385, 'line': "" 'dest': dest,\n""}]}","{'deleted': [{'char_start': 300, 'char_end': 318, 'chars': ""self.request.get('""}, {'char_start': 322, 'char_end': 324, 'chars': ""')""}], 'added': [{'char_start': 121, 'char_end': 200, 'chars': ""dest = self.request.get('dest')\n base_handler.check_redirect_url(dest)\n\n ""}]}",github.com/google/clusterfuzz/commit/3d66c1146550eecd4e34d47332a8616b435a21fe,src/appengine/handlers/login.py,cwe-079,74 cwe-078,extend_volume," def extend_volume(self, volume, new_size): volume_name = self._get_3par_vol_name(volume['id']) old_size = volume.size growth_size = int(new_size) - old_size LOG.debug(""Extending Volume %s from %s to %s, by %s GB."" % (volume_name, old_size, new_size, growth_size)) try: self._cli_run(""growvv -f %s %sg"" % (volume_name, growth_size), None) except Exception: with excutils.save_and_reraise_exception(): LOG.error(_(""Error extending volume %s"") % volume)"," def extend_volume(self, volume, new_size): volume_name = self._get_3par_vol_name(volume['id']) old_size = volume.size growth_size = int(new_size) - old_size LOG.debug(""Extending Volume %s from %s to %s, by %s GB."" % (volume_name, old_size, new_size, growth_size)) try: self._cli_run(['growvv', '-f', volume_name, '%dg' % growth_size]) except Exception: with excutils.save_and_reraise_exception(): LOG.error(_(""Error extending volume %s"") % volume)","{'deleted': [{'line_no': 8, 'char_start': 331, 'char_end': 406, 'line': ' self._cli_run(""growvv -f %s %sg"" % (volume_name, growth_size),\n'}, {'line_no': 9, 'char_start': 406, 'char_end': 438, 'line': ' None)\n'}], 'added': [{'line_no': 8, 'char_start': 331, 'char_end': 409, 'line': "" self._cli_run(['growvv', '-f', volume_name, '%dg' % growth_size])\n""}]}","{'deleted': [{'char_start': 357, 'char_end': 358, 'chars': '""'}, {'char_start': 367, 'char_end': 375, 'chars': ' %s %sg""'}, {'char_start': 376, 'char_end': 379, 'chars': '% ('}, {'char_start': 403, 'char_end': 436, 'chars': '),\n None'}], 'added': [{'char_start': 357, 'char_end': 359, 'chars': ""['""}, {'char_start': 365, 'char_end': 367, 'chars': ""',""}, {'char_start': 368, 'char_end': 369, 'chars': ""'""}, {'char_start': 371, 'char_end': 373, 'chars': ""',""}, {'char_start': 387, 'char_end': 395, 'chars': ""'%dg' % ""}, {'char_start': 406, 'char_end': 407, 'chars': ']'}]}",github.com/thatsdone/cinder/commit/c55589b131828f3a595903f6796cb2d0babb772f,cinder/volume/drivers/san/hp/hp_3par_common.py,cwe-078,139 cwe-476,rfcomm_sock_bind,"static int rfcomm_sock_bind(struct socket *sock, struct sockaddr *addr, int addr_len) { struct sockaddr_rc *sa = (struct sockaddr_rc *) addr; struct sock *sk = sock->sk; int chan = sa->rc_channel; int err = 0; BT_DBG(""sk %p %pMR"", sk, &sa->rc_bdaddr); if (!addr || addr->sa_family != AF_BLUETOOTH) return -EINVAL; lock_sock(sk); if (sk->sk_state != BT_OPEN) { err = -EBADFD; goto done; } if (sk->sk_type != SOCK_STREAM) { err = -EINVAL; goto done; } write_lock(&rfcomm_sk_list.lock); if (chan && __rfcomm_get_listen_sock_by_addr(chan, &sa->rc_bdaddr)) { err = -EADDRINUSE; } else { /* Save source address */ bacpy(&rfcomm_pi(sk)->src, &sa->rc_bdaddr); rfcomm_pi(sk)->channel = chan; sk->sk_state = BT_BOUND; } write_unlock(&rfcomm_sk_list.lock); done: release_sock(sk); return err; }","static int rfcomm_sock_bind(struct socket *sock, struct sockaddr *addr, int addr_len) { struct sockaddr_rc sa; struct sock *sk = sock->sk; int len, err = 0; if (!addr || addr->sa_family != AF_BLUETOOTH) return -EINVAL; memset(&sa, 0, sizeof(sa)); len = min_t(unsigned int, sizeof(sa), addr_len); memcpy(&sa, addr, len); BT_DBG(""sk %p %pMR"", sk, &sa.rc_bdaddr); lock_sock(sk); if (sk->sk_state != BT_OPEN) { err = -EBADFD; goto done; } if (sk->sk_type != SOCK_STREAM) { err = -EINVAL; goto done; } write_lock(&rfcomm_sk_list.lock); if (sa.rc_channel && __rfcomm_get_listen_sock_by_addr(sa.rc_channel, &sa.rc_bdaddr)) { err = -EADDRINUSE; } else { /* Save source address */ bacpy(&rfcomm_pi(sk)->src, &sa.rc_bdaddr); rfcomm_pi(sk)->channel = sa.rc_channel; sk->sk_state = BT_BOUND; } write_unlock(&rfcomm_sk_list.lock); done: release_sock(sk); return err; }","{'deleted': [{'line_no': 3, 'char_start': 88, 'char_end': 143, 'line': '\tstruct sockaddr_rc *sa = (struct sockaddr_rc *) addr;\n'}, {'line_no': 5, 'char_start': 172, 'char_end': 200, 'line': '\tint chan = sa->rc_channel;\n'}, {'line_no': 6, 'char_start': 200, 'char_end': 214, 'line': '\tint err = 0;\n'}, {'line_no': 7, 'char_start': 214, 'char_end': 215, 'line': '\n'}, {'line_no': 8, 'char_start': 215, 'char_end': 258, 'line': '\tBT_DBG(""sk %p %pMR"", sk, &sa->rc_bdaddr);\n'}, {'line_no': 27, 'char_start': 513, 'char_end': 584, 'line': '\tif (chan && __rfcomm_get_listen_sock_by_addr(chan, &sa->rc_bdaddr)) {\n'}, {'line_no': 31, 'char_start': 643, 'char_end': 689, 'line': '\t\tbacpy(&rfcomm_pi(sk)->src, &sa->rc_bdaddr);\n'}, {'line_no': 32, 'char_start': 689, 'char_end': 722, 'line': '\t\trfcomm_pi(sk)->channel = chan;\n'}], 'added': [{'line_no': 3, 'char_start': 88, 'char_end': 112, 'line': '\tstruct sockaddr_rc sa;\n'}, {'line_no': 5, 'char_start': 141, 'char_end': 160, 'line': '\tint len, err = 0;\n'}, {'line_no': 10, 'char_start': 227, 'char_end': 256, 'line': '\tmemset(&sa, 0, sizeof(sa));\n'}, {'line_no': 11, 'char_start': 256, 'char_end': 306, 'line': '\tlen = min_t(unsigned int, sizeof(sa), addr_len);\n'}, {'line_no': 12, 'char_start': 306, 'char_end': 331, 'line': '\tmemcpy(&sa, addr, len);\n'}, {'line_no': 13, 'char_start': 331, 'char_end': 332, 'line': '\n'}, {'line_no': 14, 'char_start': 332, 'char_end': 374, 'line': '\tBT_DBG(""sk %p %pMR"", sk, &sa.rc_bdaddr);\n'}, {'line_no': 15, 'char_start': 374, 'char_end': 375, 'line': '\n'}, {'line_no': 30, 'char_start': 563, 'char_end': 585, 'line': '\tif (sa.rc_channel &&\n'}, {'line_no': 31, 'char_start': 585, 'char_end': 656, 'line': '\t __rfcomm_get_listen_sock_by_addr(sa.rc_channel, &sa.rc_bdaddr)) {\n'}, {'line_no': 35, 'char_start': 715, 'char_end': 760, 'line': '\t\tbacpy(&rfcomm_pi(sk)->src, &sa.rc_bdaddr);\n'}, {'line_no': 36, 'char_start': 760, 'char_end': 802, 'line': '\t\trfcomm_pi(sk)->channel = sa.rc_channel;\n'}]}","{'deleted': [{'char_start': 108, 'char_end': 109, 'chars': '*'}, {'char_start': 111, 'char_end': 141, 'chars': ' = (struct sockaddr_rc *) addr'}, {'char_start': 177, 'char_end': 197, 'chars': 'chan = sa->rc_channe'}, {'char_start': 198, 'char_end': 202, 'chars': ';\n\ti'}, {'char_start': 203, 'char_end': 204, 'chars': 't'}, {'char_start': 216, 'char_end': 260, 'chars': 'BT_DBG(""sk %p %pMR"", sk, &sa->rc_bdaddr);\n\n\t'}, {'char_start': 568, 'char_end': 570, 'chars': '->'}, {'char_start': 675, 'char_end': 677, 'chars': '->'}], 'added': [{'char_start': 146, 'char_end': 147, 'chars': 'l'}, {'char_start': 149, 'char_end': 150, 'chars': ','}, {'char_start': 228, 'char_end': 376, 'chars': 'memset(&sa, 0, sizeof(sa));\n\tlen = min_t(unsigned int, sizeof(sa), addr_len);\n\tmemcpy(&sa, addr, len);\n\n\tBT_DBG(""sk %p %pMR"", sk, &sa.rc_bdaddr);\n\n\t'}, {'char_start': 568, 'char_end': 574, 'chars': 'sa.rc_'}, {'char_start': 578, 'char_end': 581, 'chars': 'nel'}, {'char_start': 584, 'char_end': 589, 'chars': '\n\t '}, {'char_start': 623, 'char_end': 629, 'chars': 'sa.rc_'}, {'char_start': 633, 'char_end': 636, 'chars': 'nel'}, {'char_start': 641, 'char_end': 642, 'chars': '.'}, {'char_start': 747, 'char_end': 748, 'chars': '.'}, {'char_start': 787, 'char_end': 793, 'chars': 'sa.rc_'}, {'char_start': 797, 'char_end': 800, 'chars': 'nel'}]}",github.com/torvalds/linux/commit/951b6a0717db97ce420547222647bcc40bf1eacd,net/bluetooth/rfcomm/sock.c,cwe-476,262 cwe-078,poll," def poll(self, poll_input): username = poll_input.credentials.username password = poll_input.credentials.password domain = poll_input.credentials.domain if domain is None: opt_str = '--ignore-certificate --authonly -u {} -p {} {}:{}' options = opt_str.format( username, password, poll_input.server, poll_input.port) else: opt_str = '--ignore-certificate --authonly -d {} -u {} -p {} {}:{}' options = opt_str.format( domain.domain, username, password, poll_input.server, poll_input.port) try: output = subprocess.check_output('timeout {} xfreerdp {}'.format(poll_input.timeout, options), shell=True, stderr=subprocess.STDOUT) result = RdpPollResult(True) return result except Exception as e: if ('connected to' in str(e.output) and 'Authentication failure' not in str(e.output)) or (e.returncode == 131 and 'negotiation' in str(e.output)): result = RdpPollResult(True) return result print(""{{{{%s}}}}"" % e.output) result = RdpPollResult(False, e) return result"," def poll(self, poll_input): username = poll_input.credentials.username password = poll_input.credentials.password domain = poll_input.credentials.domain if domain is None: opt_str = '--ignore-certificate --authonly -u \'{}\' -p \'{}\' {}:{}' options = opt_str.format( username, password, poll_input.server, poll_input.port) else: opt_str = '--ignore-certificate --authonly -d {} -u \'{}\' -p \'{}\' {}:{}' options = opt_str.format( domain.domain, username, password, poll_input.server, poll_input.port) try: output = subprocess.check_output('timeout {} xfreerdp {}'.format(poll_input.timeout, options), shell=True, stderr=subprocess.STDOUT) result = RdpPollResult(True) return result except Exception as e: if ('connected to' in str(e.output) and 'Authentication failure' not in str(e.output)) or (e.returncode == 131 and 'negotiation' in str(e.output)): result = RdpPollResult(True) return result print(""{{{{%s}}}}"" % e.output) result = RdpPollResult(False, e) return result","{'deleted': [{'line_no': 7, 'char_start': 217, 'char_end': 291, 'line': "" opt_str = '--ignore-certificate --authonly -u {} -p {} {}:{}'\n""}, {'line_no': 12, 'char_start': 439, 'char_end': 519, 'line': "" opt_str = '--ignore-certificate --authonly -d {} -u {} -p {} {}:{}'\n""}], 'added': [{'line_no': 7, 'char_start': 217, 'char_end': 299, 'line': "" opt_str = '--ignore-certificate --authonly -u \\'{}\\' -p \\'{}\\' {}:{}'\n""}, {'line_no': 12, 'char_start': 447, 'char_end': 535, 'line': "" opt_str = '--ignore-certificate --authonly -d {} -u \\'{}\\' -p \\'{}\\' {}:{}'\n""}]}","{'deleted': [], 'added': [{'char_start': 275, 'char_end': 277, 'chars': ""\\'""}, {'char_start': 279, 'char_end': 281, 'chars': ""\\'""}, {'char_start': 285, 'char_end': 287, 'chars': ""\\'""}, {'char_start': 289, 'char_end': 291, 'chars': ""\\'""}, {'char_start': 511, 'char_end': 513, 'chars': ""\\'""}, {'char_start': 515, 'char_end': 517, 'chars': ""\\'""}, {'char_start': 521, 'char_end': 523, 'chars': ""\\'""}, {'char_start': 525, 'char_end': 527, 'chars': ""\\'""}]}",github.com/DSU-DefSecClub/ScoringEngine/commit/010eefe1ad416c0bdaa16fd59eca0dc8e3086a13,polling/poll_rdp.py,cwe-078,265 cwe-787,gps_tracker,"void gps_tracker( void ) { ssize_t unused; int gpsd_sock; char line[256], *temp; struct sockaddr_in gpsd_addr; int ret, is_json, pos; fd_set read_fd; struct timeval timeout; /* attempt to connect to localhost, port 2947 */ pos = 0; gpsd_sock = socket( AF_INET, SOCK_STREAM, 0 ); if( gpsd_sock < 0 ) { return; } gpsd_addr.sin_family = AF_INET; gpsd_addr.sin_port = htons( 2947 ); gpsd_addr.sin_addr.s_addr = inet_addr( ""127.0.0.1"" ); if( connect( gpsd_sock, (struct sockaddr *) &gpsd_addr, sizeof( gpsd_addr ) ) < 0 ) { return; } // Check if it's GPSd < 2.92 or the new one // 2.92+ immediately send stuff // < 2.92 requires to send PVTAD command FD_ZERO(&read_fd); FD_SET(gpsd_sock, &read_fd); timeout.tv_sec = 1; timeout.tv_usec = 0; is_json = select(gpsd_sock + 1, &read_fd, NULL, NULL, &timeout); if (is_json) { /* {""class"":""VERSION"",""release"":""2.95"",""rev"":""2010-11-16T21:12:35"",""proto_major"":3,""proto_minor"":3} ?WATCH={""json"":true}; {""class"":""DEVICES"",""devices"":[]} */ // Get the crap and ignore it: {""class"":""VERSION"",""release"":""2.95"",""rev"":""2010-11-16T21:12:35"",""proto_major"":3,""proto_minor"":3} if( recv( gpsd_sock, line, sizeof( line ) - 1, 0 ) <= 0 ) return; is_json = (line[0] == '{'); if (is_json) { // Send ?WATCH={""json"":true}; memset( line, 0, sizeof( line ) ); strcpy(line, ""?WATCH={\""json\"":true};\n""); if( send( gpsd_sock, line, 22, 0 ) != 22 ) return; // Check that we have devices memset(line, 0, sizeof(line)); if( recv( gpsd_sock, line, sizeof( line ) - 1, 0 ) <= 0 ) return; // Stop processing if there is no device if (strncmp(line, ""{\""class\"":\""DEVICES\"",\""devices\"":[]}"", 32) == 0) { close(gpsd_sock); return; } else { pos = strlen(line); } } } /* loop reading the GPS coordinates */ while( G.do_exit == 0 ) { usleep( 500000 ); memset( G.gps_loc, 0, sizeof( float ) * 5 ); /* read position, speed, heading, altitude */ if (is_json) { // Format definition: http://catb.org/gpsd/gpsd_json.html if (pos == sizeof( line )) { memset(line, 0, sizeof(line)); pos = 0; } // New version, JSON if( recv( gpsd_sock, line + pos, sizeof( line ) - 1, 0 ) <= 0 ) return; // search for TPV class: {""class"":""TPV"" temp = strstr(line, ""{\""class\"":\""TPV\""""); if (temp == NULL) { continue; } // Make sure the data we have is complete if (strchr(temp, '}') == NULL) { // Move the data at the beginning of the buffer; pos = strlen(temp); if (temp != line) { memmove(line, temp, pos); memset(line + pos, 0, sizeof(line) - pos); } } // Example line: {""class"":""TPV"",""tag"":""MID2"",""device"":""/dev/ttyUSB0"",""time"":1350957517.000,""ept"":0.005,""lat"":46.878936576,""lon"":-115.832602964,""alt"":1968.382,""track"":0.0000,""speed"":0.000,""climb"":0.000,""mode"":3} // Latitude temp = strstr(temp, ""\""lat\"":""); if (temp == NULL) { continue; } ret = sscanf(temp + 6, ""%f"", &G.gps_loc[0]); // Longitude temp = strstr(temp, ""\""lon\"":""); if (temp == NULL) { continue; } ret = sscanf(temp + 6, ""%f"", &G.gps_loc[1]); // Altitude temp = strstr(temp, ""\""alt\"":""); if (temp == NULL) { continue; } ret = sscanf(temp + 6, ""%f"", &G.gps_loc[4]); // Speed temp = strstr(temp, ""\""speed\"":""); if (temp == NULL) { continue; } ret = sscanf(temp + 6, ""%f"", &G.gps_loc[2]); // No more heading // Get the next TPV class temp = strstr(temp, ""{\""class\"":\""TPV\""""); if (temp == NULL) { memset( line, 0, sizeof( line ) ); pos = 0; } else { pos = strlen(temp); memmove(line, temp, pos); memset(line + pos, 0, sizeof(line) - pos); } } else { memset( line, 0, sizeof( line ) ); snprintf( line, sizeof( line ) - 1, ""PVTAD\r\n"" ); if( send( gpsd_sock, line, 7, 0 ) != 7 ) return; memset( line, 0, sizeof( line ) ); if( recv( gpsd_sock, line, sizeof( line ) - 1, 0 ) <= 0 ) return; if( memcmp( line, ""GPSD,P="", 7 ) != 0 ) continue; /* make sure the coordinates are present */ if( line[7] == '?' ) continue; ret = sscanf( line + 7, ""%f %f"", &G.gps_loc[0], &G.gps_loc[1] ); if( ( temp = strstr( line, ""V="" ) ) == NULL ) continue; ret = sscanf( temp + 2, ""%f"", &G.gps_loc[2] ); /* speed */ if( ( temp = strstr( line, ""T="" ) ) == NULL ) continue; ret = sscanf( temp + 2, ""%f"", &G.gps_loc[3] ); /* heading */ if( ( temp = strstr( line, ""A="" ) ) == NULL ) continue; ret = sscanf( temp + 2, ""%f"", &G.gps_loc[4] ); /* altitude */ } if (G.record_data) fputs( line, G.f_gps ); G.save_gps = 1; if (G.do_exit == 0) { unused = write( G.gc_pipe[1], G.gps_loc, sizeof( float ) * 5 ); kill( getppid(), SIGUSR2 ); } } }","void gps_tracker( void ) { ssize_t unused; int gpsd_sock; char line[256], *temp; struct sockaddr_in gpsd_addr; int ret, is_json, pos; fd_set read_fd; struct timeval timeout; /* attempt to connect to localhost, port 2947 */ pos = 0; gpsd_sock = socket( AF_INET, SOCK_STREAM, 0 ); if( gpsd_sock < 0 ) { return; } gpsd_addr.sin_family = AF_INET; gpsd_addr.sin_port = htons( 2947 ); gpsd_addr.sin_addr.s_addr = inet_addr( ""127.0.0.1"" ); if( connect( gpsd_sock, (struct sockaddr *) &gpsd_addr, sizeof( gpsd_addr ) ) < 0 ) { return; } // Check if it's GPSd < 2.92 or the new one // 2.92+ immediately send stuff // < 2.92 requires to send PVTAD command FD_ZERO(&read_fd); FD_SET(gpsd_sock, &read_fd); timeout.tv_sec = 1; timeout.tv_usec = 0; is_json = select(gpsd_sock + 1, &read_fd, NULL, NULL, &timeout); if (is_json) { /* {""class"":""VERSION"",""release"":""2.95"",""rev"":""2010-11-16T21:12:35"",""proto_major"":3,""proto_minor"":3} ?WATCH={""json"":true}; {""class"":""DEVICES"",""devices"":[]} */ // Get the crap and ignore it: {""class"":""VERSION"",""release"":""2.95"",""rev"":""2010-11-16T21:12:35"",""proto_major"":3,""proto_minor"":3} if( recv( gpsd_sock, line, sizeof( line ) - 1, 0 ) <= 0 ) return; is_json = (line[0] == '{'); if (is_json) { // Send ?WATCH={""json"":true}; memset( line, 0, sizeof( line ) ); strcpy(line, ""?WATCH={\""json\"":true};\n""); if( send( gpsd_sock, line, 22, 0 ) != 22 ) return; // Check that we have devices memset(line, 0, sizeof(line)); if( recv( gpsd_sock, line, sizeof( line ) - 1, 0 ) <= 0 ) return; // Stop processing if there is no device if (strncmp(line, ""{\""class\"":\""DEVICES\"",\""devices\"":[]}"", 32) == 0) { close(gpsd_sock); return; } else { pos = strlen(line); } } } /* loop reading the GPS coordinates */ while( G.do_exit == 0 ) { usleep( 500000 ); memset( G.gps_loc, 0, sizeof( float ) * 5 ); /* read position, speed, heading, altitude */ if (is_json) { // Format definition: http://catb.org/gpsd/gpsd_json.html if (pos == sizeof( line )) { memset(line, 0, sizeof(line)); pos = 0; } // New version, JSON if( recv( gpsd_sock, line + pos, sizeof( line ) - pos - 1, 0 ) <= 0 ) return; // search for TPV class: {""class"":""TPV"" temp = strstr(line, ""{\""class\"":\""TPV\""""); if (temp == NULL) { continue; } // Make sure the data we have is complete if (strchr(temp, '}') == NULL) { // Move the data at the beginning of the buffer; pos = strlen(temp); if (temp != line) { memmove(line, temp, pos); memset(line + pos, 0, sizeof(line) - pos); } } // Example line: {""class"":""TPV"",""tag"":""MID2"",""device"":""/dev/ttyUSB0"",""time"":1350957517.000,""ept"":0.005,""lat"":46.878936576,""lon"":-115.832602964,""alt"":1968.382,""track"":0.0000,""speed"":0.000,""climb"":0.000,""mode"":3} // Latitude temp = strstr(temp, ""\""lat\"":""); if (temp == NULL) { continue; } ret = sscanf(temp + 6, ""%f"", &G.gps_loc[0]); // Longitude temp = strstr(temp, ""\""lon\"":""); if (temp == NULL) { continue; } ret = sscanf(temp + 6, ""%f"", &G.gps_loc[1]); // Altitude temp = strstr(temp, ""\""alt\"":""); if (temp == NULL) { continue; } ret = sscanf(temp + 6, ""%f"", &G.gps_loc[4]); // Speed temp = strstr(temp, ""\""speed\"":""); if (temp == NULL) { continue; } ret = sscanf(temp + 6, ""%f"", &G.gps_loc[2]); // No more heading // Get the next TPV class temp = strstr(temp, ""{\""class\"":\""TPV\""""); if (temp == NULL) { memset( line, 0, sizeof( line ) ); pos = 0; } else { pos = strlen(temp); memmove(line, temp, pos); memset(line + pos, 0, sizeof(line) - pos); } } else { memset( line, 0, sizeof( line ) ); snprintf( line, sizeof( line ) - 1, ""PVTAD\r\n"" ); if( send( gpsd_sock, line, 7, 0 ) != 7 ) return; memset( line, 0, sizeof( line ) ); if( recv( gpsd_sock, line, sizeof( line ) - 1, 0 ) <= 0 ) return; if( memcmp( line, ""GPSD,P="", 7 ) != 0 ) continue; /* make sure the coordinates are present */ if( line[7] == '?' ) continue; ret = sscanf( line + 7, ""%f %f"", &G.gps_loc[0], &G.gps_loc[1] ); if( ( temp = strstr( line, ""V="" ) ) == NULL ) continue; ret = sscanf( temp + 2, ""%f"", &G.gps_loc[2] ); /* speed */ if( ( temp = strstr( line, ""T="" ) ) == NULL ) continue; ret = sscanf( temp + 2, ""%f"", &G.gps_loc[3] ); /* heading */ if( ( temp = strstr( line, ""A="" ) ) == NULL ) continue; ret = sscanf( temp + 2, ""%f"", &G.gps_loc[4] ); /* altitude */ } if (G.record_data) fputs( line, G.f_gps ); G.save_gps = 1; if (G.do_exit == 0) { unused = write( G.gc_pipe[1], G.gps_loc, sizeof( float ) * 5 ); kill( getppid(), SIGUSR2 ); } } }","{'deleted': [{'line_no': 89, 'char_start': 2379, 'char_end': 2452, 'line': ' \tif( recv( gpsd_sock, line + pos, sizeof( line ) - 1, 0 ) <= 0 )\n'}], 'added': [{'line_no': 89, 'char_start': 2379, 'char_end': 2458, 'line': ' \tif( recv( gpsd_sock, line + pos, sizeof( line ) - pos - 1, 0 ) <= 0 )\n'}]}","{'deleted': [], 'added': [{'char_start': 2438, 'char_end': 2444, 'chars': 'pos - '}]}",github.com/aircrack-ng/aircrack-ng/commit/ff70494dd389ba570dbdbf36f217c28d4381c6b5/,src/airodump-ng.c,cwe-787,1755 cwe-089,add_post,"def add_post(content): """"""Add a post to the 'database' with the current timestamp."""""" db = psycopg2.connect(database=DBNAME) c = db.cursor() c.execute(""insert into posts values('%s')"" % content) db.commit() db.close()","def add_post(content): """"""Add a post to the 'database' with the current timestamp."""""" db = psycopg2.connect(database=DBNAME) c = db.cursor() c.execute(""insert into posts values(%s)"",(content,)) db.commit() db.close()","{'deleted': [{'line_no': 5, 'char_start': 147, 'char_end': 203, 'line': ' c.execute(""insert into posts values(\'%s\')"" % content)\n'}], 'added': [{'line_no': 5, 'char_start': 147, 'char_end': 202, 'line': ' c.execute(""insert into posts values(%s)"",(content,))\n'}]}","{'deleted': [{'char_start': 185, 'char_end': 186, 'chars': ""'""}, {'char_start': 188, 'char_end': 189, 'chars': ""'""}, {'char_start': 191, 'char_end': 194, 'chars': ' % '}], 'added': [{'char_start': 189, 'char_end': 191, 'chars': ',('}, {'char_start': 198, 'char_end': 200, 'chars': ',)'}]}",github.com/tfalbo/SuzyMakeup/commit/1a5d6ccf02bec303d454f87a6bb39baed30c205f,vagrant/forum/forumdb.py,cwe-089,58 cwe-089,add_input," def add_input(self, data): connection = self.connect() try: # The following introduces a deliberate security flaw - SQL Injection query = ""INSERT INTO crimes (description) VALUES ('{}');"".format(data) with connection.cursor() as cursor: cursor.execute(query) connection.commit() finally: connection.close()"," def add_input(self, data): connection = self.connect() try: # The following introduces a deliberate security flaw - SQL Injection query = ""INSERT INTO crimes (description) VALUES (%s);"" with connection.cursor() as cursor: cursor.execute(query, data) connection.commit() finally: connection.close()","{'deleted': [{'line_no': 5, 'char_start': 162, 'char_end': 245, 'line': ' query = ""INSERT INTO crimes (description) VALUES (\'{}\');"".format(data)\n'}, {'line_no': 7, 'char_start': 293, 'char_end': 331, 'line': ' cursor.execute(query)\n'}], 'added': [{'line_no': 5, 'char_start': 162, 'char_end': 230, 'line': ' query = ""INSERT INTO crimes (description) VALUES (%s);""\n'}, {'line_no': 7, 'char_start': 278, 'char_end': 322, 'line': ' cursor.execute(query, data)\n'}]}","{'deleted': [{'char_start': 224, 'char_end': 228, 'chars': ""'{}'""}, {'char_start': 231, 'char_end': 244, 'chars': '.format(data)'}], 'added': [{'char_start': 224, 'char_end': 226, 'chars': '%s'}, {'char_start': 314, 'char_end': 320, 'chars': ', data'}]}",github.com/rwolf527/crimemap/commit/50b0695e0b4c46165e6146f6fac4cd6871d9fdf6,dbhelper.py,cwe-089,72 cwe-089,shame_ask,"def shame_ask(name): db = db_connect() cursor = db.cursor() try: cursor.execute(''' SELECT shame FROM people WHERE name='{}' '''.format(name)) shame = cursor.fetchone() db.close() if shame is None: logger.debug('No shame found for name {}'.format(name)) return shame else: shame = shame[0] logger.debug('shame of {} found for name {}'.format(shame, name)) return shame except Exception as e: logger.error('Execution failed with error: {}'.format(e)) raise","def shame_ask(name): db = db_connect() cursor = db.cursor() try: cursor.execute(''' SELECT shame FROM people WHERE name=%(name)s ''', (name, )) shame = cursor.fetchone() db.close() if shame is None: logger.debug('No shame found for name {}'.format(name)) return shame else: shame = shame[0] logger.debug('shame of {} found for name {}'.format(shame, name)) return shame except Exception as e: logger.error('Execution failed with error: {}'.format(e)) raise","{'deleted': [{'line_no': 6, 'char_start': 104, 'char_end': 157, 'line': "" SELECT shame FROM people WHERE name='{}'\n""}, {'line_no': 7, 'char_start': 157, 'char_end': 187, 'line': "" '''.format(name))\n""}], 'added': [{'line_no': 6, 'char_start': 104, 'char_end': 161, 'line': ' SELECT shame FROM people WHERE name=%(name)s\n'}, {'line_no': 7, 'char_start': 161, 'char_end': 188, 'line': "" ''', (name, ))\n""}]}","{'deleted': [{'char_start': 152, 'char_end': 156, 'chars': ""'{}'""}, {'char_start': 172, 'char_end': 179, 'chars': '.format'}], 'added': [{'char_start': 152, 'char_end': 160, 'chars': '%(name)s'}, {'char_start': 176, 'char_end': 178, 'chars': ', '}, {'char_start': 183, 'char_end': 185, 'chars': ', '}]}",github.com/tylarb/KarmaBoi-PCF/commit/c1d00a27d7f6b7eb6f15a3dacd4269654a32c10a,KarmaBoi/dbopts.py,cwe-089,127 cwe-125,sctp_sf_ootb,"sctp_disposition_t sctp_sf_ootb(struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, const sctp_subtype_t type, void *arg, sctp_cmd_seq_t *commands) { struct sctp_chunk *chunk = arg; struct sk_buff *skb = chunk->skb; sctp_chunkhdr_t *ch; sctp_errhdr_t *err; __u8 *ch_end; int ootb_shut_ack = 0; int ootb_cookie_ack = 0; SCTP_INC_STATS(net, SCTP_MIB_OUTOFBLUES); ch = (sctp_chunkhdr_t *) chunk->chunk_hdr; do { /* Report violation if the chunk is less then minimal */ if (ntohs(ch->length) < sizeof(sctp_chunkhdr_t)) return sctp_sf_violation_chunklen(net, ep, asoc, type, arg, commands); /* Now that we know we at least have a chunk header, * do things that are type appropriate. */ if (SCTP_CID_SHUTDOWN_ACK == ch->type) ootb_shut_ack = 1; /* RFC 2960, Section 3.3.7 * Moreover, under any circumstances, an endpoint that * receives an ABORT MUST NOT respond to that ABORT by * sending an ABORT of its own. */ if (SCTP_CID_ABORT == ch->type) return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands); /* RFC 8.4, 7) If the packet contains a ""Stale cookie"" ERROR * or a COOKIE ACK the SCTP Packet should be silently * discarded. */ if (SCTP_CID_COOKIE_ACK == ch->type) ootb_cookie_ack = 1; if (SCTP_CID_ERROR == ch->type) { sctp_walk_errors(err, ch) { if (SCTP_ERROR_STALE_COOKIE == err->cause) { ootb_cookie_ack = 1; break; } } } /* Report violation if chunk len overflows */ ch_end = ((__u8 *)ch) + SCTP_PAD4(ntohs(ch->length)); if (ch_end > skb_tail_pointer(skb)) return sctp_sf_violation_chunklen(net, ep, asoc, type, arg, commands); ch = (sctp_chunkhdr_t *) ch_end; } while (ch_end < skb_tail_pointer(skb)); if (ootb_shut_ack) return sctp_sf_shut_8_4_5(net, ep, asoc, type, arg, commands); else if (ootb_cookie_ack) return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands); else return sctp_sf_tabort_8_4_8(net, ep, asoc, type, arg, commands); }","sctp_disposition_t sctp_sf_ootb(struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, const sctp_subtype_t type, void *arg, sctp_cmd_seq_t *commands) { struct sctp_chunk *chunk = arg; struct sk_buff *skb = chunk->skb; sctp_chunkhdr_t *ch; sctp_errhdr_t *err; __u8 *ch_end; int ootb_shut_ack = 0; int ootb_cookie_ack = 0; SCTP_INC_STATS(net, SCTP_MIB_OUTOFBLUES); ch = (sctp_chunkhdr_t *) chunk->chunk_hdr; do { /* Report violation if the chunk is less then minimal */ if (ntohs(ch->length) < sizeof(sctp_chunkhdr_t)) return sctp_sf_violation_chunklen(net, ep, asoc, type, arg, commands); /* Report violation if chunk len overflows */ ch_end = ((__u8 *)ch) + SCTP_PAD4(ntohs(ch->length)); if (ch_end > skb_tail_pointer(skb)) return sctp_sf_violation_chunklen(net, ep, asoc, type, arg, commands); /* Now that we know we at least have a chunk header, * do things that are type appropriate. */ if (SCTP_CID_SHUTDOWN_ACK == ch->type) ootb_shut_ack = 1; /* RFC 2960, Section 3.3.7 * Moreover, under any circumstances, an endpoint that * receives an ABORT MUST NOT respond to that ABORT by * sending an ABORT of its own. */ if (SCTP_CID_ABORT == ch->type) return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands); /* RFC 8.4, 7) If the packet contains a ""Stale cookie"" ERROR * or a COOKIE ACK the SCTP Packet should be silently * discarded. */ if (SCTP_CID_COOKIE_ACK == ch->type) ootb_cookie_ack = 1; if (SCTP_CID_ERROR == ch->type) { sctp_walk_errors(err, ch) { if (SCTP_ERROR_STALE_COOKIE == err->cause) { ootb_cookie_ack = 1; break; } } } ch = (sctp_chunkhdr_t *) ch_end; } while (ch_end < skb_tail_pointer(skb)); if (ootb_shut_ack) return sctp_sf_shut_8_4_5(net, ep, asoc, type, arg, commands); else if (ootb_cookie_ack) return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands); else return sctp_sf_tabort_8_4_8(net, ep, asoc, type, arg, commands); }","{'deleted': [{'line_no': 56, 'char_start': 1500, 'char_end': 1548, 'line': '\t\t/* Report violation if chunk len overflows */\n'}, {'line_no': 57, 'char_start': 1548, 'char_end': 1604, 'line': '\t\tch_end = ((__u8 *)ch) + SCTP_PAD4(ntohs(ch->length));\n'}, {'line_no': 58, 'char_start': 1604, 'char_end': 1642, 'line': '\t\tif (ch_end > skb_tail_pointer(skb))\n'}, {'line_no': 59, 'char_start': 1642, 'char_end': 1705, 'line': '\t\t\treturn sctp_sf_violation_chunklen(net, ep, asoc, type, arg,\n'}, {'line_no': 60, 'char_start': 1705, 'char_end': 1724, 'line': '\t\t\t\t\t\t commands);\n'}, {'line_no': 61, 'char_start': 1724, 'char_end': 1725, 'line': '\n'}], 'added': [{'line_no': 25, 'char_start': 668, 'char_end': 716, 'line': '\t\t/* Report violation if chunk len overflows */\n'}, {'line_no': 26, 'char_start': 716, 'char_end': 772, 'line': '\t\tch_end = ((__u8 *)ch) + SCTP_PAD4(ntohs(ch->length));\n'}, {'line_no': 27, 'char_start': 772, 'char_end': 810, 'line': '\t\tif (ch_end > skb_tail_pointer(skb))\n'}, {'line_no': 28, 'char_start': 810, 'char_end': 873, 'line': '\t\t\treturn sctp_sf_violation_chunklen(net, ep, asoc, type, arg,\n'}, {'line_no': 29, 'char_start': 873, 'char_end': 892, 'line': '\t\t\t\t\t\t commands);\n'}, {'line_no': 30, 'char_start': 892, 'char_end': 893, 'line': '\n'}]}","{'deleted': [{'char_start': 1498, 'char_end': 1723, 'chars': '\n\n\t\t/* Report violation if chunk len overflows */\n\t\tch_end = ((__u8 *)ch) + SCTP_PAD4(ntohs(ch->length));\n\t\tif (ch_end > skb_tail_pointer(skb))\n\t\t\treturn sctp_sf_violation_chunklen(net, ep, asoc, type, arg,\n\t\t\t\t\t\t commands);'}], 'added': [{'char_start': 673, 'char_end': 898, 'chars': 'Report violation if chunk len overflows */\n\t\tch_end = ((__u8 *)ch) + SCTP_PAD4(ntohs(ch->length));\n\t\tif (ch_end > skb_tail_pointer(skb))\n\t\t\treturn sctp_sf_violation_chunklen(net, ep, asoc, type, arg,\n\t\t\t\t\t\t commands);\n\n\t\t/* '}]}",github.com/torvalds/linux/commit/bf911e985d6bbaa328c20c3e05f4eb03de11fdd6,net/sctp/sm_statefuns.c,cwe-125,670 cwe-078,repack,"def repack(host, targets, channel='stable'): url = 'https://static.rust-lang.org/dist/channel-rust-' + channel + '.toml' req = requests.get(url) req.raise_for_status() manifest = toml.loads(req.content) if manifest['manifest-version'] != '2': print('ERROR: unrecognized manifest version %s.' % manifest['manifest-version']) return print('Using manifest for rust %s as of %s.' % (channel, manifest['date'])) rustc_version, rustc = package(manifest, 'rustc', host) if rustc['available']: print('rustc %s\n %s\n %s' % (rustc_version, rustc['url'], rustc['hash'])) fetch(rustc['url']) cargo_version, cargo = package(manifest, 'cargo', host) if cargo['available']: print('cargo %s\n %s\n %s' % (cargo_version, cargo['url'], cargo['hash'])) fetch(cargo['url']) stds = [] for target in targets: version, info = package(manifest, 'rust-std', target) if info['available']: print('rust-std %s\n %s\n %s' % (version, info['url'], info['hash'])) fetch(info['url']) stds.append(info) print('Installing packages...') tar_basename = 'rustc-%s-repack' % host install_dir = 'rustc' os.system('rm -rf %s' % install_dir) install(os.path.basename(rustc['url']), install_dir) install(os.path.basename(cargo['url']), install_dir) for std in stds: install(os.path.basename(std['url']), install_dir) print('Tarring %s...' % tar_basename) os.system('tar cjf %s.tar.bz2 %s/*' % (tar_basename, install_dir)) os.system('rm -rf %s' % install_dir)","def repack(host, targets, channel='stable'): print(""Repacking rust for %s..."" % host) url = 'https://static.rust-lang.org/dist/channel-rust-' + channel + '.toml' req = requests.get(url) req.raise_for_status() manifest = toml.loads(req.content) if manifest['manifest-version'] != '2': print('ERROR: unrecognized manifest version %s.' % manifest['manifest-version']) return print('Using manifest for rust %s as of %s.' % (channel, manifest['date'])) rustc_version, rustc = package(manifest, 'rustc', host) if rustc['available']: print('rustc %s\n %s\n %s' % (rustc_version, rustc['url'], rustc['hash'])) fetch(rustc['url']) cargo_version, cargo = package(manifest, 'cargo', host) if cargo['available']: print('cargo %s\n %s\n %s' % (cargo_version, cargo['url'], cargo['hash'])) fetch(cargo['url']) stds = [] for target in targets: version, info = package(manifest, 'rust-std', target) if info['available']: print('rust-std %s\n %s\n %s' % (version, info['url'], info['hash'])) fetch(info['url']) stds.append(info) print('Installing packages...') tar_basename = 'rustc-%s-repack' % host install_dir = 'rustc' subprocess.check_call(['rm', '-rf', install_dir]) install(os.path.basename(rustc['url']), install_dir) install(os.path.basename(cargo['url']), install_dir) for std in stds: install(os.path.basename(std['url']), install_dir) print('Tarring %s...' % tar_basename) subprocess.check_call(['tar', 'cjf', tar_basename + '.tar.bz2', install_dir]) subprocess.check_call(['rm', '-rf', install_dir])","{'deleted': [{'line_no': 28, 'char_start': 1161, 'char_end': 1200, 'line': "" os.system('rm -rf %s' % install_dir)\n""}, {'line_no': 34, 'char_start': 1424, 'char_end': 1493, 'line': "" os.system('tar cjf %s.tar.bz2 %s/*' % (tar_basename, install_dir))\n""}, {'line_no': 35, 'char_start': 1493, 'char_end': 1531, 'line': "" os.system('rm -rf %s' % install_dir)\n""}], 'added': [{'line_no': 2, 'char_start': 45, 'char_end': 88, 'line': ' print(""Repacking rust for %s..."" % host)\n'}, {'line_no': 29, 'char_start': 1204, 'char_end': 1256, 'line': "" subprocess.check_call(['rm', '-rf', install_dir])\n""}, {'line_no': 35, 'char_start': 1480, 'char_end': 1560, 'line': "" subprocess.check_call(['tar', 'cjf', tar_basename + '.tar.bz2', install_dir])\n""}, {'line_no': 36, 'char_start': 1560, 'char_end': 1611, 'line': "" subprocess.check_call(['rm', '-rf', install_dir])\n""}]}","{'deleted': [{'char_start': 1166, 'char_end': 1170, 'chars': 'syst'}, {'char_start': 1171, 'char_end': 1172, 'chars': 'm'}, {'char_start': 1180, 'char_end': 1183, 'chars': ' %s'}, {'char_start': 1184, 'char_end': 1186, 'chars': ' %'}, {'char_start': 1426, 'char_end': 1427, 'chars': 'o'}, {'char_start': 1428, 'char_end': 1429, 'chars': '.'}, {'char_start': 1430, 'char_end': 1431, 'chars': 'y'}, {'char_start': 1432, 'char_end': 1433, 'chars': 't'}, {'char_start': 1434, 'char_end': 1435, 'chars': 'm'}, {'char_start': 1444, 'char_end': 1460, 'chars': ' %s.tar.bz2 %s/*'}, {'char_start': 1462, 'char_end': 1465, 'chars': '% ('}, {'char_start': 1490, 'char_end': 1491, 'chars': ')'}, {'char_start': 1498, 'char_end': 1502, 'chars': 'syst'}, {'char_start': 1503, 'char_end': 1504, 'chars': 'm'}, {'char_start': 1512, 'char_end': 1515, 'chars': ' %s'}, {'char_start': 1516, 'char_end': 1518, 'chars': ' %'}], 'added': [{'char_start': 47, 'char_end': 90, 'chars': 'print(""Repacking rust for %s..."" % host)\n '}, {'char_start': 1206, 'char_end': 1211, 'chars': 'subpr'}, {'char_start': 1212, 'char_end': 1214, 'chars': 'ce'}, {'char_start': 1216, 'char_end': 1219, 'chars': '.ch'}, {'char_start': 1220, 'char_end': 1227, 'chars': 'ck_call'}, {'char_start': 1228, 'char_end': 1229, 'chars': '['}, {'char_start': 1232, 'char_end': 1234, 'chars': ""',""}, {'char_start': 1235, 'char_end': 1236, 'chars': ""'""}, {'char_start': 1240, 'char_end': 1241, 'chars': ','}, {'char_start': 1253, 'char_end': 1254, 'chars': ']'}, {'char_start': 1482, 'char_end': 1487, 'chars': 'subpr'}, {'char_start': 1488, 'char_end': 1491, 'chars': 'ces'}, {'char_start': 1493, 'char_end': 1495, 'chars': 'ch'}, {'char_start': 1496, 'char_end': 1503, 'chars': 'ck_call'}, {'char_start': 1504, 'char_end': 1505, 'chars': '['}, {'char_start': 1509, 'char_end': 1511, 'chars': ""',""}, {'char_start': 1512, 'char_end': 1513, 'chars': ""'""}, {'char_start': 1517, 'char_end': 1518, 'chars': ','}, {'char_start': 1531, 'char_end': 1544, 'chars': "" + '.tar.bz2'""}, {'char_start': 1557, 'char_end': 1558, 'chars': ']'}, {'char_start': 1562, 'char_end': 1567, 'chars': 'subpr'}, {'char_start': 1568, 'char_end': 1570, 'chars': 'ce'}, {'char_start': 1572, 'char_end': 1575, 'chars': '.ch'}, {'char_start': 1576, 'char_end': 1583, 'chars': 'ck_call'}, {'char_start': 1584, 'char_end': 1585, 'chars': '['}, {'char_start': 1588, 'char_end': 1590, 'chars': ""',""}, {'char_start': 1591, 'char_end': 1592, 'chars': ""'""}, {'char_start': 1596, 'char_end': 1597, 'chars': ','}, {'char_start': 1609, 'char_end': 1610, 'chars': ']'}]}",github.com/rillian/rust-build/commit/b8af51e5811fcb35eff9e1e3e91c98490e7a7dcb,repack_rust.py,cwe-078,443 cwe-079,commentcounts,"@register.tag @basictag(takes_context=True) def commentcounts(context, filediff, interfilediff=None): """""" Returns a JSON array of current comments for a filediff, sorted by line number. Each entry in the array has a dictionary containing the following keys: =========== ================================================== Key Description =========== ================================================== comment_id The ID of the comment text The text of the comment line The first line number num_lines The number of lines this comment spans user A dictionary containing ""username"" and ""name"" keys for the user url The URL to the comment localdraft True if this is the current user's draft comment =========== ================================================== """""" comment_dict = {} user = context.get('user', None) if interfilediff: query = Comment.objects.filter(filediff=filediff, interfilediff=interfilediff) else: query = Comment.objects.filter(filediff=filediff, interfilediff__isnull=True) for comment in query: review = get_object_or_none(comment.review) if review and (review.public or review.user == user): key = (comment.first_line, comment.num_lines) comment_dict.setdefault(key, []).append({ 'comment_id': comment.id, 'text': comment.text, 'line': comment.first_line, 'num_lines': comment.num_lines, 'user': { 'username': review.user.username, 'name': review.user.get_full_name() or review.user.username, }, #'timestamp': comment.timestamp, 'url': comment.get_review_url(), 'localdraft': review.user == user and \ not review.public, }) comments_array = [] for key, value in comment_dict.iteritems(): comments_array.append({ 'linenum': key[0], 'num_lines': key[1], 'comments': value, }) comments_array.sort(cmp=lambda x, y: cmp(x['linenum'], y['linenum'] or cmp(x['num_lines'], y['num_lines']))) return simplejson.dumps(comments_array)","@register.tag @basictag(takes_context=True) def commentcounts(context, filediff, interfilediff=None): """""" Returns a JSON array of current comments for a filediff, sorted by line number. Each entry in the array has a dictionary containing the following keys: =========== ================================================== Key Description =========== ================================================== comment_id The ID of the comment text The text of the comment line The first line number num_lines The number of lines this comment spans user A dictionary containing ""username"" and ""name"" keys for the user url The URL to the comment localdraft True if this is the current user's draft comment =========== ================================================== """""" comment_dict = {} user = context.get('user', None) if interfilediff: query = Comment.objects.filter(filediff=filediff, interfilediff=interfilediff) else: query = Comment.objects.filter(filediff=filediff, interfilediff__isnull=True) for comment in query: review = get_object_or_none(comment.review) if review and (review.public or review.user == user): key = (comment.first_line, comment.num_lines) comment_dict.setdefault(key, []).append({ 'comment_id': comment.id, 'text': escape(comment.text), 'line': comment.first_line, 'num_lines': comment.num_lines, 'user': { 'username': review.user.username, 'name': review.user.get_full_name() or review.user.username, }, #'timestamp': comment.timestamp, 'url': comment.get_review_url(), 'localdraft': review.user == user and \ not review.public, }) comments_array = [] for key, value in comment_dict.iteritems(): comments_array.append({ 'linenum': key[0], 'num_lines': key[1], 'comments': value, }) comments_array.sort(cmp=lambda x, y: cmp(x['linenum'], y['linenum'] or cmp(x['num_lines'], y['num_lines']))) return simplejson.dumps(comments_array)","{'deleted': [{'line_no': 41, 'char_start': 1548, 'char_end': 1586, 'line': "" 'text': comment.text,\n""}], 'added': [{'line_no': 41, 'char_start': 1548, 'char_end': 1594, 'line': "" 'text': escape(comment.text),\n""}]}","{'deleted': [], 'added': [{'char_start': 1572, 'char_end': 1579, 'chars': 'escape('}, {'char_start': 1591, 'char_end': 1592, 'chars': ')'}]}",github.com/reviewboard/reviewboard/commit/7a0a9d94555502278534dedcf2d75e9fccce8c3d,reviewboard/reviews/templatetags/reviewtags.py,cwe-079,469 cwe-089,summary,"@app.route('/summary', methods=['GET']) def summary(): if 'username' in session: conn = mysql.connect() cursor = conn.cursor() #select the maximum score from the results table cursor.execute(""SELECT courseConcentration FROM results WHERE total = (SELECT MAX(total) FROM (SELECT * FROM results WHERE courseId > 4) Temp) and courseId > 4 and emailAccount='"" + session['username'] + ""'""); courseConcentration = cursor.fetchone() return render_template('summary.html', courseConcentration = courseConcentration[0]) return redirect(url_for('login'))","@app.route('/summary', methods=['GET']) def summary(): if 'username' in session: conn = mysql.connect() cursor = conn.cursor() #select the maximum score from the results table cursor.execute(""SELECT courseConcentration FROM results WHERE total = (SELECT MAX(total) FROM (SELECT * FROM results WHERE courseId > 4) Temp) and courseId > 4 and emailAccount=%s"", (session['username'])); courseConcentration = cursor.fetchone() return render_template('summary.html', courseConcentration = courseConcentration[0]) return redirect(url_for('login'))","{'deleted': [{'line_no': 9, 'char_start': 185, 'char_end': 397, 'line': '\t\tcursor.execute(""SELECT courseConcentration FROM results WHERE total = (SELECT MAX(total) FROM (SELECT * FROM results WHERE courseId > 4) Temp) and courseId > 4 and emailAccount=\'"" + session[\'username\'] + ""\'"");\n'}], 'added': [{'line_no': 9, 'char_start': 185, 'char_end': 393, 'line': '\t\tcursor.execute(""SELECT courseConcentration FROM results WHERE total = (SELECT MAX(total) FROM (SELECT * FROM results WHERE courseId > 4) Temp) and courseId > 4 and emailAccount=%s"", (session[\'username\']));\n'}]}","{'deleted': [{'char_start': 364, 'char_end': 365, 'chars': ""'""}, {'char_start': 367, 'char_end': 369, 'chars': '+ '}, {'char_start': 388, 'char_end': 394, 'chars': ' + ""\'""'}], 'added': [{'char_start': 364, 'char_end': 366, 'chars': '%s'}, {'char_start': 367, 'char_end': 368, 'chars': ','}, {'char_start': 369, 'char_end': 370, 'chars': '('}, {'char_start': 389, 'char_end': 390, 'chars': ')'}]}",github.com/CaitlinKennedy/Tech-Track/commit/20ef2d4010f9497b8221524edd0c706e2c6a4147,src/tech_track.py,cwe-089,125 cwe-125,concat_hash_string,"static u_int16_t concat_hash_string(struct ndpi_packet_struct *packet, char *buf, u_int8_t client_hash) { u_int16_t offset = 22, buf_out_len = 0; if(offset+sizeof(u_int32_t) >= packet->payload_packet_len) goto invalid_payload; u_int32_t len = ntohl(*(u_int32_t*)&packet->payload[offset]); offset += 4; /* -1 for ';' */ if((offset >= packet->payload_packet_len) || (len >= packet->payload_packet_len-offset-1)) goto invalid_payload; /* ssh.kex_algorithms [C/S] */ strncpy(buf, (const char *)&packet->payload[offset], buf_out_len = len); buf[buf_out_len++] = ';'; offset += len; /* ssh.server_host_key_algorithms [None] */ len = ntohl(*(u_int32_t*)&packet->payload[offset]); offset += 4 + len; /* ssh.encryption_algorithms_client_to_server [C] */ len = ntohl(*(u_int32_t*)&packet->payload[offset]); if(client_hash) { offset += 4; if((offset >= packet->payload_packet_len) || (len >= packet->payload_packet_len-offset-1)) goto invalid_payload; strncpy(&buf[buf_out_len], (const char *)&packet->payload[offset], len); buf_out_len += len; buf[buf_out_len++] = ';'; offset += len; } else offset += 4 + len; /* ssh.encryption_algorithms_server_to_client [S] */ len = ntohl(*(u_int32_t*)&packet->payload[offset]); if(!client_hash) { offset += 4; if((offset >= packet->payload_packet_len) || (len >= packet->payload_packet_len-offset-1)) goto invalid_payload; strncpy(&buf[buf_out_len], (const char *)&packet->payload[offset], len); buf_out_len += len; buf[buf_out_len++] = ';'; offset += len; } else offset += 4 + len; /* ssh.mac_algorithms_client_to_server [C] */ len = ntohl(*(u_int32_t*)&packet->payload[offset]); if(client_hash) { offset += 4; if((offset >= packet->payload_packet_len) || (len >= packet->payload_packet_len-offset-1)) goto invalid_payload; strncpy(&buf[buf_out_len], (const char *)&packet->payload[offset], len); buf_out_len += len; buf[buf_out_len++] = ';'; offset += len; } else offset += 4 + len; /* ssh.mac_algorithms_server_to_client [S] */ len = ntohl(*(u_int32_t*)&packet->payload[offset]); if(!client_hash) { offset += 4; if((offset >= packet->payload_packet_len) || (len >= packet->payload_packet_len-offset-1)) goto invalid_payload; strncpy(&buf[buf_out_len], (const char *)&packet->payload[offset], len); buf_out_len += len; buf[buf_out_len++] = ';'; offset += len; } else offset += 4 + len; /* ssh.compression_algorithms_client_to_server [C] */ if(offset+sizeof(u_int32_t) >= packet->payload_packet_len) goto invalid_payload; len = ntohl(*(u_int32_t*)&packet->payload[offset]); if(client_hash) { offset += 4; if((offset >= packet->payload_packet_len) || (len >= packet->payload_packet_len-offset-1)) goto invalid_payload; strncpy(&buf[buf_out_len], (const char *)&packet->payload[offset], len); buf_out_len += len; offset += len; } else offset += 4 + len; /* ssh.compression_algorithms_server_to_client [S] */ len = ntohl(*(u_int32_t*)&packet->payload[offset]); if(!client_hash) { offset += 4; if((offset >= packet->payload_packet_len) || (len >= packet->payload_packet_len-offset-1)) goto invalid_payload; strncpy(&buf[buf_out_len], (const char *)&packet->payload[offset], len); buf_out_len += len; offset += len; } else offset += 4 + len; /* ssh.languages_client_to_server [None] */ /* ssh.languages_server_to_client [None] */ #ifdef SSH_DEBUG printf(""[SSH] %s\n"", buf); #endif return(buf_out_len); invalid_payload: #ifdef SSH_DEBUG printf(""[SSH] Invalid packet payload\n""); #endif return(0); }","static u_int16_t concat_hash_string(struct ndpi_packet_struct *packet, char *buf, u_int8_t client_hash) { u_int16_t offset = 22, buf_out_len = 0; if(offset+sizeof(u_int32_t) >= packet->payload_packet_len) goto invalid_payload; u_int32_t len = ntohl(*(u_int32_t*)&packet->payload[offset]); offset += 4; /* -1 for ';' */ if((offset >= packet->payload_packet_len) || (len >= packet->payload_packet_len-offset-1)) goto invalid_payload; /* ssh.kex_algorithms [C/S] */ strncpy(buf, (const char *)&packet->payload[offset], buf_out_len = len); buf[buf_out_len++] = ';'; offset += len; if(offset+sizeof(u_int32_t) >= packet->payload_packet_len) goto invalid_payload; /* ssh.server_host_key_algorithms [None] */ len = ntohl(*(u_int32_t*)&packet->payload[offset]); offset += 4 + len; if(offset+sizeof(u_int32_t) >= packet->payload_packet_len) goto invalid_payload; /* ssh.encryption_algorithms_client_to_server [C] */ len = ntohl(*(u_int32_t*)&packet->payload[offset]); if(client_hash) { offset += 4; if((offset >= packet->payload_packet_len) || (len >= packet->payload_packet_len-offset-1)) goto invalid_payload; strncpy(&buf[buf_out_len], (const char *)&packet->payload[offset], len); buf_out_len += len; buf[buf_out_len++] = ';'; offset += len; } else offset += 4 + len; if(offset+sizeof(u_int32_t) >= packet->payload_packet_len) goto invalid_payload; /* ssh.encryption_algorithms_server_to_client [S] */ len = ntohl(*(u_int32_t*)&packet->payload[offset]); if(!client_hash) { offset += 4; if((offset >= packet->payload_packet_len) || (len >= packet->payload_packet_len-offset-1)) goto invalid_payload; strncpy(&buf[buf_out_len], (const char *)&packet->payload[offset], len); buf_out_len += len; buf[buf_out_len++] = ';'; offset += len; } else offset += 4 + len; if(offset+sizeof(u_int32_t) >= packet->payload_packet_len) goto invalid_payload; /* ssh.mac_algorithms_client_to_server [C] */ len = ntohl(*(u_int32_t*)&packet->payload[offset]); if(client_hash) { offset += 4; if((offset >= packet->payload_packet_len) || (len >= packet->payload_packet_len-offset-1)) goto invalid_payload; strncpy(&buf[buf_out_len], (const char *)&packet->payload[offset], len); buf_out_len += len; buf[buf_out_len++] = ';'; offset += len; } else offset += 4 + len; if(offset+sizeof(u_int32_t) >= packet->payload_packet_len) goto invalid_payload; /* ssh.mac_algorithms_server_to_client [S] */ len = ntohl(*(u_int32_t*)&packet->payload[offset]); if(!client_hash) { offset += 4; if((offset >= packet->payload_packet_len) || (len >= packet->payload_packet_len-offset-1)) goto invalid_payload; strncpy(&buf[buf_out_len], (const char *)&packet->payload[offset], len); buf_out_len += len; buf[buf_out_len++] = ';'; offset += len; } else offset += 4 + len; /* ssh.compression_algorithms_client_to_server [C] */ if(offset+sizeof(u_int32_t) >= packet->payload_packet_len) goto invalid_payload; len = ntohl(*(u_int32_t*)&packet->payload[offset]); if(client_hash) { offset += 4; if((offset >= packet->payload_packet_len) || (len >= packet->payload_packet_len-offset-1)) goto invalid_payload; strncpy(&buf[buf_out_len], (const char *)&packet->payload[offset], len); buf_out_len += len; offset += len; } else offset += 4 + len; if(offset+sizeof(u_int32_t) >= packet->payload_packet_len) goto invalid_payload; /* ssh.compression_algorithms_server_to_client [S] */ len = ntohl(*(u_int32_t*)&packet->payload[offset]); if(!client_hash) { offset += 4; if((offset >= packet->payload_packet_len) || (len >= packet->payload_packet_len-offset-1)) goto invalid_payload; strncpy(&buf[buf_out_len], (const char *)&packet->payload[offset], len); buf_out_len += len; offset += len; } else offset += 4 + len; /* ssh.languages_client_to_server [None] */ /* ssh.languages_server_to_client [None] */ #ifdef SSH_DEBUG printf(""[SSH] %s\n"", buf); #endif return(buf_out_len); invalid_payload: #ifdef SSH_DEBUG printf(""[SSH] Invalid packet payload\n""); #endif return(0); }","{'deleted': [], 'added': [{'line_no': 18, 'char_start': 615, 'char_end': 676, 'line': ' if(offset+sizeof(u_int32_t) >= packet->payload_packet_len)\n'}, {'line_no': 19, 'char_start': 676, 'char_end': 702, 'line': ' goto invalid_payload;\n'}, {'line_no': 24, 'char_start': 824, 'char_end': 885, 'line': ' if(offset+sizeof(u_int32_t) >= packet->payload_packet_len)\n'}, {'line_no': 25, 'char_start': 885, 'char_end': 911, 'line': ' goto invalid_payload;\n'}, {'line_no': 42, 'char_start': 1366, 'char_end': 1427, 'line': ' if(offset+sizeof(u_int32_t) >= packet->payload_packet_len)\n'}, {'line_no': 43, 'char_start': 1427, 'char_end': 1453, 'line': ' goto invalid_payload;\n'}, {'line_no': 60, 'char_start': 1909, 'char_end': 1970, 'line': ' if(offset+sizeof(u_int32_t) >= packet->payload_packet_len)\n'}, {'line_no': 61, 'char_start': 1970, 'char_end': 1996, 'line': ' goto invalid_payload;\n'}, {'line_no': 78, 'char_start': 2444, 'char_end': 2505, 'line': ' if(offset+sizeof(u_int32_t) >= packet->payload_packet_len)\n'}, {'line_no': 79, 'char_start': 2505, 'char_end': 2531, 'line': ' goto invalid_payload;\n'}, {'line_no': 113, 'char_start': 3493, 'char_end': 3554, 'line': ' if(offset+sizeof(u_int32_t) >= packet->payload_packet_len)\n'}, {'line_no': 114, 'char_start': 3554, 'char_end': 3580, 'line': ' goto invalid_payload;\n'}]}","{'deleted': [], 'added': [{'char_start': 617, 'char_end': 704, 'chars': 'if(offset+sizeof(u_int32_t) >= packet->payload_packet_len)\n goto invalid_payload;\n '}, {'char_start': 823, 'char_end': 910, 'chars': '\n if(offset+sizeof(u_int32_t) >= packet->payload_packet_len)\n goto invalid_payload;'}, {'char_start': 1366, 'char_end': 1453, 'chars': ' if(offset+sizeof(u_int32_t) >= packet->payload_packet_len)\n goto invalid_payload;\n'}, {'char_start': 1909, 'char_end': 1996, 'chars': ' if(offset+sizeof(u_int32_t) >= packet->payload_packet_len)\n goto invalid_payload;\n'}, {'char_start': 2444, 'char_end': 2531, 'chars': ' if(offset+sizeof(u_int32_t) >= packet->payload_packet_len)\n goto invalid_payload;\n'}, {'char_start': 3492, 'char_end': 3579, 'chars': '\n if(offset+sizeof(u_int32_t) >= packet->payload_packet_len)\n goto invalid_payload;'}]}",github.com/ntop/nDPI/commit/3bbb0cd3296023f6f922c71d21a1c374d2b0a435,src/lib/protocols/ssh.c,cwe-125,1049 cwe-089,reportMatch,"def reportMatch(winner, loser): """"""Records the outcome of a single match between two players. Args: winner: the id number of the player who won loser: the id number of the player who lost """""" try: int(winner) int(loser) except ValueError: raise ValueError( ""\""winner\"" and/or \""loser\"" input are not integers.\n"" ""Please use the id number of each player to report match results."" ) w = str(winner) l = str(loser) db = connect() c = db.cursor() statement = ""INSERT INTO matches values ({w}, {l})"".format(w=w, l=l) c.execute(statement) db.commit() db.close()","def reportMatch(winner, loser): """"""Records the outcome of a single match between two players. Args: winner: the id number of the player who won loser: the id number of the player who lost """""" try: int(winner) int(loser) except ValueError: raise ValueError( ""\""winner\"" and/or \""loser\"" input are not integers.\n"" ""Please use the id number of each player to report match results."" ) w = str(winner) l = str(loser) db = connect() c = db.cursor() c.execute(""INSERT INTO matches values (%s, %s)"", (w,l)) db.commit() db.close()","{'deleted': [{'line_no': 20, 'char_start': 551, 'char_end': 624, 'line': ' statement = ""INSERT INTO matches values ({w}, {l})"".format(w=w, l=l)\n'}, {'line_no': 21, 'char_start': 624, 'char_end': 649, 'line': ' c.execute(statement)\n'}], 'added': [{'line_no': 20, 'char_start': 551, 'char_end': 611, 'line': ' c.execute(""INSERT INTO matches values (%s, %s)"", (w,l))\n'}]}","{'deleted': [{'char_start': 555, 'char_end': 559, 'chars': 'stat'}, {'char_start': 560, 'char_end': 561, 'chars': 'm'}, {'char_start': 562, 'char_end': 563, 'chars': 'n'}, {'char_start': 564, 'char_end': 567, 'chars': ' = '}, {'char_start': 596, 'char_end': 599, 'chars': '{w}'}, {'char_start': 601, 'char_end': 604, 'chars': '{l}'}, {'char_start': 606, 'char_end': 613, 'chars': '.format'}, {'char_start': 615, 'char_end': 617, 'chars': '=w'}, {'char_start': 618, 'char_end': 621, 'chars': ' l='}, {'char_start': 623, 'char_end': 647, 'chars': '\n c.execute(statement'}], 'added': [{'char_start': 555, 'char_end': 557, 'chars': 'c.'}, {'char_start': 558, 'char_end': 559, 'chars': 'x'}, {'char_start': 560, 'char_end': 562, 'chars': 'cu'}, {'char_start': 563, 'char_end': 565, 'chars': 'e('}, {'char_start': 594, 'char_end': 596, 'chars': '%s'}, {'char_start': 598, 'char_end': 600, 'chars': '%s'}, {'char_start': 602, 'char_end': 604, 'chars': ', '}]}",github.com/tdnelson2/tournament-db/commit/00f3caeed0e12e806c2808d100908698777d9e98,tournament.py,cwe-089,166 cwe-125,wrap_lines_smart,"wrap_lines_smart(ASS_Renderer *render_priv, double max_text_width) { int i; GlyphInfo *cur, *s1, *e1, *s2, *s3; int last_space; int break_type; int exit; double pen_shift_x; double pen_shift_y; int cur_line; int run_offset; TextInfo *text_info = &render_priv->text_info; last_space = -1; text_info->n_lines = 1; break_type = 0; s1 = text_info->glyphs; // current line start for (i = 0; i < text_info->length; ++i) { int break_at = -1; double s_offset, len; cur = text_info->glyphs + i; s_offset = d6_to_double(s1->bbox.xMin + s1->pos.x); len = d6_to_double(cur->bbox.xMax + cur->pos.x) - s_offset; if (cur->symbol == '\n') { break_type = 2; break_at = i; ass_msg(render_priv->library, MSGL_DBG2, ""forced line break at %d"", break_at); } else if (cur->symbol == ' ') { last_space = i; } else if (len >= max_text_width && (render_priv->state.wrap_style != 2)) { break_type = 1; break_at = last_space; if (break_at >= 0) ass_msg(render_priv->library, MSGL_DBG2, ""line break at %d"", break_at); } if (break_at != -1) { // need to use one more line // marking break_at+1 as start of a new line int lead = break_at + 1; // the first symbol of the new line if (text_info->n_lines >= text_info->max_lines) { // Raise maximum number of lines text_info->max_lines *= 2; text_info->lines = realloc(text_info->lines, sizeof(LineInfo) * text_info->max_lines); } if (lead < text_info->length) { text_info->glyphs[lead].linebreak = break_type; last_space = -1; s1 = text_info->glyphs + lead; text_info->n_lines++; } } } #define DIFF(x,y) (((x) < (y)) ? (y - x) : (x - y)) exit = 0; while (!exit && render_priv->state.wrap_style != 1) { exit = 1; s3 = text_info->glyphs; s1 = s2 = 0; for (i = 0; i <= text_info->length; ++i) { cur = text_info->glyphs + i; if ((i == text_info->length) || cur->linebreak) { s1 = s2; s2 = s3; s3 = cur; if (s1 && (s2->linebreak == 1)) { // have at least 2 lines, and linebreak is 'soft' double l1, l2, l1_new, l2_new; GlyphInfo *w = s2; do { --w; } while ((w > s1) && (w->symbol == ' ')); while ((w > s1) && (w->symbol != ' ')) { --w; } e1 = w; while ((e1 > s1) && (e1->symbol == ' ')) { --e1; } if (w->symbol == ' ') ++w; l1 = d6_to_double(((s2 - 1)->bbox.xMax + (s2 - 1)->pos.x) - (s1->bbox.xMin + s1->pos.x)); l2 = d6_to_double(((s3 - 1)->bbox.xMax + (s3 - 1)->pos.x) - (s2->bbox.xMin + s2->pos.x)); l1_new = d6_to_double( (e1->bbox.xMax + e1->pos.x) - (s1->bbox.xMin + s1->pos.x)); l2_new = d6_to_double( ((s3 - 1)->bbox.xMax + (s3 - 1)->pos.x) - (w->bbox.xMin + w->pos.x)); if (DIFF(l1_new, l2_new) < DIFF(l1, l2)) { w->linebreak = 1; s2->linebreak = 0; exit = 0; } } } if (i == text_info->length) break; } } assert(text_info->n_lines >= 1); #undef DIFF measure_text(render_priv); trim_whitespace(render_priv); cur_line = 1; run_offset = 0; i = 0; cur = text_info->glyphs + i; while (i < text_info->length && cur->skip) cur = text_info->glyphs + ++i; pen_shift_x = d6_to_double(-cur->pos.x); pen_shift_y = 0.; for (i = 0; i < text_info->length; ++i) { cur = text_info->glyphs + i; if (cur->linebreak) { while (i < text_info->length && cur->skip && cur->symbol != '\n') cur = text_info->glyphs + ++i; double height = text_info->lines[cur_line - 1].desc + text_info->lines[cur_line].asc; text_info->lines[cur_line - 1].len = i - text_info->lines[cur_line - 1].offset; text_info->lines[cur_line].offset = i; cur_line++; run_offset++; pen_shift_x = d6_to_double(-cur->pos.x); pen_shift_y += height + render_priv->settings.line_spacing; } cur->pos.x += double_to_d6(pen_shift_x); cur->pos.y += double_to_d6(pen_shift_y); } text_info->lines[cur_line - 1].len = text_info->length - text_info->lines[cur_line - 1].offset; #if 0 // print line info for (i = 0; i < text_info->n_lines; i++) { printf(""line %d offset %d length %d\n"", i, text_info->lines[i].offset, text_info->lines[i].len); } #endif }","wrap_lines_smart(ASS_Renderer *render_priv, double max_text_width) { int i; GlyphInfo *cur, *s1, *e1, *s2, *s3; int last_space; int break_type; int exit; double pen_shift_x; double pen_shift_y; int cur_line; int run_offset; TextInfo *text_info = &render_priv->text_info; last_space = -1; text_info->n_lines = 1; break_type = 0; s1 = text_info->glyphs; // current line start for (i = 0; i < text_info->length; ++i) { int break_at = -1; double s_offset, len; cur = text_info->glyphs + i; s_offset = d6_to_double(s1->bbox.xMin + s1->pos.x); len = d6_to_double(cur->bbox.xMax + cur->pos.x) - s_offset; if (cur->symbol == '\n') { break_type = 2; break_at = i; ass_msg(render_priv->library, MSGL_DBG2, ""forced line break at %d"", break_at); } else if (cur->symbol == ' ') { last_space = i; } else if (len >= max_text_width && (render_priv->state.wrap_style != 2)) { break_type = 1; break_at = last_space; if (break_at >= 0) ass_msg(render_priv->library, MSGL_DBG2, ""line break at %d"", break_at); } if (break_at != -1) { // need to use one more line // marking break_at+1 as start of a new line int lead = break_at + 1; // the first symbol of the new line if (text_info->n_lines >= text_info->max_lines) { // Raise maximum number of lines text_info->max_lines *= 2; text_info->lines = realloc(text_info->lines, sizeof(LineInfo) * text_info->max_lines); } if (lead < text_info->length) { text_info->glyphs[lead].linebreak = break_type; last_space = -1; s1 = text_info->glyphs + lead; text_info->n_lines++; } } } #define DIFF(x,y) (((x) < (y)) ? (y - x) : (x - y)) exit = 0; while (!exit && render_priv->state.wrap_style != 1) { exit = 1; s3 = text_info->glyphs; s1 = s2 = 0; for (i = 0; i <= text_info->length; ++i) { cur = text_info->glyphs + i; if ((i == text_info->length) || cur->linebreak) { s1 = s2; s2 = s3; s3 = cur; if (s1 && (s2->linebreak == 1)) { // have at least 2 lines, and linebreak is 'soft' double l1, l2, l1_new, l2_new; GlyphInfo *w = s2; do { --w; } while ((w > s1) && (w->symbol == ' ')); while ((w > s1) && (w->symbol != ' ')) { --w; } e1 = w; while ((e1 > s1) && (e1->symbol == ' ')) { --e1; } if (w->symbol == ' ') ++w; l1 = d6_to_double(((s2 - 1)->bbox.xMax + (s2 - 1)->pos.x) - (s1->bbox.xMin + s1->pos.x)); l2 = d6_to_double(((s3 - 1)->bbox.xMax + (s3 - 1)->pos.x) - (s2->bbox.xMin + s2->pos.x)); l1_new = d6_to_double( (e1->bbox.xMax + e1->pos.x) - (s1->bbox.xMin + s1->pos.x)); l2_new = d6_to_double( ((s3 - 1)->bbox.xMax + (s3 - 1)->pos.x) - (w->bbox.xMin + w->pos.x)); if (DIFF(l1_new, l2_new) < DIFF(l1, l2) && w > text_info->glyphs) { if (w->linebreak) text_info->n_lines--; w->linebreak = 1; s2->linebreak = 0; exit = 0; } } } if (i == text_info->length) break; } } assert(text_info->n_lines >= 1); #undef DIFF measure_text(render_priv); trim_whitespace(render_priv); cur_line = 1; run_offset = 0; i = 0; cur = text_info->glyphs + i; while (i < text_info->length && cur->skip) cur = text_info->glyphs + ++i; pen_shift_x = d6_to_double(-cur->pos.x); pen_shift_y = 0.; for (i = 0; i < text_info->length; ++i) { cur = text_info->glyphs + i; if (cur->linebreak) { while (i < text_info->length && cur->skip && cur->symbol != '\n') cur = text_info->glyphs + ++i; double height = text_info->lines[cur_line - 1].desc + text_info->lines[cur_line].asc; text_info->lines[cur_line - 1].len = i - text_info->lines[cur_line - 1].offset; text_info->lines[cur_line].offset = i; cur_line++; run_offset++; pen_shift_x = d6_to_double(-cur->pos.x); pen_shift_y += height + render_priv->settings.line_spacing; } cur->pos.x += double_to_d6(pen_shift_x); cur->pos.y += double_to_d6(pen_shift_y); } text_info->lines[cur_line - 1].len = text_info->length - text_info->lines[cur_line - 1].offset; #if 0 // print line info for (i = 0; i < text_info->n_lines; i++) { printf(""line %d offset %d length %d\n"", i, text_info->lines[i].offset, text_info->lines[i].len); } #endif }","{'deleted': [{'line_no': 100, 'char_start': 3756, 'char_end': 3819, 'line': ' if (DIFF(l1_new, l2_new) < DIFF(l1, l2)) {\n'}], 'added': [{'line_no': 100, 'char_start': 3756, 'char_end': 3844, 'line': ' if (DIFF(l1_new, l2_new) < DIFF(l1, l2) && w > text_info->glyphs) {\n'}, {'line_no': 101, 'char_start': 3844, 'char_end': 3886, 'line': ' if (w->linebreak)\n'}, {'line_no': 102, 'char_start': 3886, 'char_end': 3936, 'line': ' text_info->n_lines--;\n'}]}","{'deleted': [], 'added': [{'char_start': 3815, 'char_end': 3840, 'chars': ' && w > text_info->glyphs'}, {'char_start': 3843, 'char_end': 3935, 'chars': '\n if (w->linebreak)\n text_info->n_lines--;'}]}",github.com/libass/libass/commit/b72b283b936a600c730e00875d7d067bded3fc26,libass/ass_render.c,cwe-125,1486 cwe-476,daemon_AuthUserPwd,"daemon_AuthUserPwd(char *username, char *password, char *errbuf) { #ifdef _WIN32 /* * Warning: the user which launches the process must have the * SE_TCB_NAME right. * This corresponds to have the ""Act as part of the Operating System"" * turned on (administrative tools, local security settings, local * policies, user right assignment) * However, it seems to me that if you run it as a service, this * right should be provided by default. * * XXX - hopefully, this returns errors such as ERROR_LOGON_FAILURE, * which merely indicates that the user name or password is * incorrect, not whether it's the user name or the password * that's incorrect, so a client that's trying to brute-force * accounts doesn't know whether it's the user name or the * password that's incorrect, so it doesn't know whether to * stop trying to log in with a given user name and move on * to another user name. */ HANDLE Token; if (LogonUser(username, ""."", password, LOGON32_LOGON_NETWORK, LOGON32_PROVIDER_DEFAULT, &Token) == 0) { pcap_fmt_errmsg_for_win32_err(errbuf, PCAP_ERRBUF_SIZE, GetLastError(), ""LogonUser() failed""); return -1; } // This call should change the current thread to the selected user. // I didn't test it. if (ImpersonateLoggedOnUser(Token) == 0) { pcap_fmt_errmsg_for_win32_err(errbuf, PCAP_ERRBUF_SIZE, GetLastError(), ""ImpersonateLoggedOnUser() failed""); CloseHandle(Token); return -1; } CloseHandle(Token); return 0; #else /* * See * * http://www.unixpapa.com/incnote/passwd.html * * We use the Solaris/Linux shadow password authentication if * we have getspnam(), otherwise we just do traditional * authentication, which, on some platforms, might work, even * with shadow passwords, if we're running as root. Traditional * authenticaion won't work if we're not running as root, as * I think these days all UN*Xes either won't return the password * at all with getpwnam() or will only do so if you're root. * * XXX - perhaps what we *should* be using is PAM, if we have * it. That might hide all the details of username/password * authentication, whether it's done with a visible-to-root- * only password database or some other authentication mechanism, * behind its API. */ struct passwd *user; char *user_password; #ifdef HAVE_GETSPNAM struct spwd *usersp; #endif // This call is needed to get the uid if ((user = getpwnam(username)) == NULL) { pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, ""Authentication failed: user name or password incorrect""); return -1; } #ifdef HAVE_GETSPNAM // This call is needed to get the password; otherwise 'x' is returned if ((usersp = getspnam(username)) == NULL) { pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, ""Authentication failed: user name or password incorrect""); return -1; } user_password = usersp->sp_pwdp; #else /* * XXX - what about other platforms? * The unixpapa.com page claims this Just Works on *BSD if you're * running as root - it's from 2000, so it doesn't indicate whether * macOS (which didn't come out until 2001, under the name Mac OS * X) behaves like the *BSDs or not, and might also work on AIX. * HP-UX does something else. * * Again, hopefully PAM hides all that. */ user_password = user->pw_passwd; #endif if (strcmp(user_password, (char *) crypt(password, user_password)) != 0) { pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, ""Authentication failed: user name or password incorrect""); return -1; } if (setuid(user->pw_uid)) { pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE, errno, ""setuid""); return -1; } /* if (setgid(user->pw_gid)) { pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE, errno, ""setgid""); return -1; } */ return 0; #endif }","daemon_AuthUserPwd(char *username, char *password, char *errbuf) { #ifdef _WIN32 /* * Warning: the user which launches the process must have the * SE_TCB_NAME right. * This corresponds to have the ""Act as part of the Operating System"" * turned on (administrative tools, local security settings, local * policies, user right assignment) * However, it seems to me that if you run it as a service, this * right should be provided by default. * * XXX - hopefully, this returns errors such as ERROR_LOGON_FAILURE, * which merely indicates that the user name or password is * incorrect, not whether it's the user name or the password * that's incorrect, so a client that's trying to brute-force * accounts doesn't know whether it's the user name or the * password that's incorrect, so it doesn't know whether to * stop trying to log in with a given user name and move on * to another user name. */ HANDLE Token; if (LogonUser(username, ""."", password, LOGON32_LOGON_NETWORK, LOGON32_PROVIDER_DEFAULT, &Token) == 0) { pcap_fmt_errmsg_for_win32_err(errbuf, PCAP_ERRBUF_SIZE, GetLastError(), ""LogonUser() failed""); return -1; } // This call should change the current thread to the selected user. // I didn't test it. if (ImpersonateLoggedOnUser(Token) == 0) { pcap_fmt_errmsg_for_win32_err(errbuf, PCAP_ERRBUF_SIZE, GetLastError(), ""ImpersonateLoggedOnUser() failed""); CloseHandle(Token); return -1; } CloseHandle(Token); return 0; #else /* * See * * http://www.unixpapa.com/incnote/passwd.html * * We use the Solaris/Linux shadow password authentication if * we have getspnam(), otherwise we just do traditional * authentication, which, on some platforms, might work, even * with shadow passwords, if we're running as root. Traditional * authenticaion won't work if we're not running as root, as * I think these days all UN*Xes either won't return the password * at all with getpwnam() or will only do so if you're root. * * XXX - perhaps what we *should* be using is PAM, if we have * it. That might hide all the details of username/password * authentication, whether it's done with a visible-to-root- * only password database or some other authentication mechanism, * behind its API. */ struct passwd *user; char *user_password; #ifdef HAVE_GETSPNAM struct spwd *usersp; #endif char *crypt_password; // This call is needed to get the uid if ((user = getpwnam(username)) == NULL) { pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, ""Authentication failed: user name or password incorrect""); return -1; } #ifdef HAVE_GETSPNAM // This call is needed to get the password; otherwise 'x' is returned if ((usersp = getspnam(username)) == NULL) { pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, ""Authentication failed: user name or password incorrect""); return -1; } user_password = usersp->sp_pwdp; #else /* * XXX - what about other platforms? * The unixpapa.com page claims this Just Works on *BSD if you're * running as root - it's from 2000, so it doesn't indicate whether * macOS (which didn't come out until 2001, under the name Mac OS * X) behaves like the *BSDs or not, and might also work on AIX. * HP-UX does something else. * * Again, hopefully PAM hides all that. */ user_password = user->pw_passwd; #endif crypt_password = crypt(password, user_password); if (crypt_password == NULL) { pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, ""Authentication failed""); return -1; } if (strcmp(user_password, crypt_password) != 0) { pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, ""Authentication failed: user name or password incorrect""); return -1; } if (setuid(user->pw_uid)) { pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE, errno, ""setuid""); return -1; } /* if (setgid(user->pw_gid)) { pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE, errno, ""setgid""); return -1; } */ return 0; #endif }","{'deleted': [{'line_no': 98, 'char_start': 3317, 'char_end': 3391, 'line': '\tif (strcmp(user_password, (char *) crypt(password, user_password)) != 0)\n'}], 'added': [{'line_no': 68, 'char_start': 2384, 'char_end': 2407, 'line': '\tchar *crypt_password;\n'}, {'line_no': 99, 'char_start': 3340, 'char_end': 3390, 'line': '\tcrypt_password = crypt(password, user_password);\n'}, {'line_no': 100, 'char_start': 3390, 'char_end': 3419, 'line': '\tif (crypt_password == NULL)\n'}, {'line_no': 101, 'char_start': 3419, 'char_end': 3422, 'line': '\t{\n'}, {'line_no': 102, 'char_start': 3422, 'char_end': 3490, 'line': '\t\tpcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, ""Authentication failed"");\n'}, {'line_no': 103, 'char_start': 3490, 'char_end': 3503, 'line': '\t\treturn -1;\n'}, {'line_no': 104, 'char_start': 3503, 'char_end': 3506, 'line': '\t}\n'}, {'line_no': 105, 'char_start': 3506, 'char_end': 3555, 'line': '\tif (strcmp(user_password, crypt_password) != 0)\n'}]}","{'deleted': [{'char_start': 3318, 'char_end': 3323, 'chars': 'if (s'}, {'char_start': 3326, 'char_end': 3327, 'chars': 'm'}, {'char_start': 3342, 'char_end': 3343, 'chars': ','}, {'char_start': 3346, 'char_end': 3347, 'chars': 'h'}, {'char_start': 3350, 'char_end': 3351, 'chars': '*'}, {'char_start': 3355, 'char_end': 3357, 'chars': 'yp'}, {'char_start': 3369, 'char_end': 3372, 'chars': 'use'}, {'char_start': 3382, 'char_end': 3383, 'chars': ')'}], 'added': [{'char_start': 2384, 'char_end': 2407, 'chars': '\tchar *crypt_password;\n'}, {'char_start': 3341, 'char_end': 3350, 'chars': 'crypt_pas'}, {'char_start': 3351, 'char_end': 3353, 'chars': 'wo'}, {'char_start': 3354, 'char_end': 3358, 'chars': 'd = '}, {'char_start': 3359, 'char_end': 3361, 'chars': 'ry'}, {'char_start': 3362, 'char_end': 3363, 'chars': 't'}, {'char_start': 3364, 'char_end': 3374, 'chars': 'password, '}, {'char_start': 3387, 'char_end': 3393, 'chars': ');\n\tif'}, {'char_start': 3396, 'char_end': 3402, 'chars': 'rypt_p'}, {'char_start': 3403, 'char_end': 3407, 'chars': 'sswo'}, {'char_start': 3408, 'char_end': 3409, 'chars': 'd'}, {'char_start': 3410, 'char_end': 3417, 'chars': '== NULL'}, {'char_start': 3418, 'char_end': 3445, 'chars': '\n\t{\n\t\tpcap_snprintf(errbuf,'}, {'char_start': 3446, 'char_end': 3473, 'chars': 'PCAP_ERRBUF_SIZE, ""Authenti'}, {'char_start': 3474, 'char_end': 3492, 'chars': 'ation failed"");\n\t\t'}, {'char_start': 3493, 'char_end': 3512, 'chars': 'eturn -1;\n\t}\n\tif (s'}, {'char_start': 3513, 'char_end': 3517, 'chars': 'rcmp'}, {'char_start': 3518, 'char_end': 3523, 'chars': 'user_'}, {'char_start': 3533, 'char_end': 3534, 'chars': 'c'}, {'char_start': 3535, 'char_end': 3538, 'chars': 'ypt'}]}",github.com/the-tcpdump-group/libpcap/commit/437b273761adedcbd880f714bfa44afeec186a31,rpcapd/daemon.c,cwe-476,1050 cwe-078,_cli_run," def _cli_run(self, verb, cli_args): """"""Runs a CLI command over SSH, without doing any result parsing."""""" cli_arg_strings = [] if cli_args: for k, v in cli_args.items(): if k == '': cli_arg_strings.append("" %s"" % k) else: cli_arg_strings.append("" %s=%s"" % (k, v)) cmd = verb + ''.join(cli_arg_strings) LOG.debug(""SSH CMD = %s "" % cmd) (stdout, stderr) = self._run_ssh(cmd, False) # we have to strip out the input and exit lines tmp = stdout.split(""\r\n"") out = tmp[5:len(tmp) - 2] return out"," def _cli_run(self, cmd): """"""Runs a CLI command over SSH, without doing any result parsing."""""" LOG.debug(""SSH CMD = %s "" % cmd) (stdout, stderr) = self._run_ssh(cmd, False) # we have to strip out the input and exit lines tmp = stdout.split(""\r\n"") out = tmp[5:len(tmp) - 2] return out","{'deleted': [{'line_no': 1, 'char_start': 0, 'char_end': 40, 'line': ' def _cli_run(self, verb, cli_args):\n'}, {'line_no': 3, 'char_start': 117, 'char_end': 146, 'line': ' cli_arg_strings = []\n'}, {'line_no': 4, 'char_start': 146, 'char_end': 167, 'line': ' if cli_args:\n'}, {'line_no': 5, 'char_start': 167, 'char_end': 209, 'line': ' for k, v in cli_args.items():\n'}, {'line_no': 6, 'char_start': 209, 'char_end': 237, 'line': "" if k == '':\n""}, {'line_no': 7, 'char_start': 237, 'char_end': 291, 'line': ' cli_arg_strings.append("" %s"" % k)\n'}, {'line_no': 8, 'char_start': 291, 'char_end': 313, 'line': ' else:\n'}, {'line_no': 9, 'char_start': 313, 'char_end': 375, 'line': ' cli_arg_strings.append("" %s=%s"" % (k, v))\n'}, {'line_no': 10, 'char_start': 375, 'char_end': 376, 'line': '\n'}, {'line_no': 11, 'char_start': 376, 'char_end': 422, 'line': "" cmd = verb + ''.join(cli_arg_strings)\n""}], 'added': [{'line_no': 1, 'char_start': 0, 'char_end': 29, 'line': ' def _cli_run(self, cmd):\n'}]}","{'deleted': [{'char_start': 23, 'char_end': 29, 'chars': 'verb, '}, {'char_start': 30, 'char_end': 37, 'chars': 'li_args'}, {'char_start': 116, 'char_end': 421, 'chars': '\n cli_arg_strings = []\n if cli_args:\n for k, v in cli_args.items():\n if k == \'\':\n cli_arg_strings.append("" %s"" % k)\n else:\n cli_arg_strings.append("" %s=%s"" % (k, v))\n\n cmd = verb + \'\'.join(cli_arg_strings)'}], 'added': [{'char_start': 24, 'char_end': 26, 'chars': 'md'}]}",github.com/thatsdone/cinder/commit/c55589b131828f3a595903f6796cb2d0babb772f,cinder/volume/drivers/san/hp/hp_3par_common.py,cwe-078,162 cwe-125,string_scan_range,"static int string_scan_range(RList *list, const ut8 *buf, int min, const ut64 from, const ut64 to, int type) { ut8 tmp[R_STRING_SCAN_BUFFER_SIZE]; ut64 str_start, needle = from; int count = 0, i, rc, runes; int str_type = R_STRING_TYPE_DETECT; if (type == -1) { type = R_STRING_TYPE_DETECT; } if (!buf || !min) { return -1; } while (needle < to) { rc = r_utf8_decode (buf + needle, to - needle, NULL); if (!rc) { needle++; continue; } if (type == R_STRING_TYPE_DETECT) { char *w = (char *)buf + needle + rc; if ((to - needle) > 4) { bool is_wide32 = needle + rc + 2 < to && !w[0] && !w[1] && !w[2] && w[3] && !w[4]; if (is_wide32) { str_type = R_STRING_TYPE_WIDE32; } else { bool is_wide = needle + rc + 2 < to && !w[0] && w[1] && !w[2]; str_type = is_wide? R_STRING_TYPE_WIDE: R_STRING_TYPE_ASCII; } } else { str_type = R_STRING_TYPE_ASCII; } } else { str_type = type; } runes = 0; str_start = needle; /* Eat a whole C string */ for (rc = i = 0; i < sizeof (tmp) - 3 && needle < to; i += rc) { RRune r = {0}; if (str_type == R_STRING_TYPE_WIDE32) { rc = r_utf32le_decode (buf + needle, to - needle, &r); if (rc) { rc = 4; } } else if (str_type == R_STRING_TYPE_WIDE) { rc = r_utf16le_decode (buf + needle, to - needle, &r); if (rc == 1) { rc = 2; } } else { rc = r_utf8_decode (buf + needle, to - needle, &r); if (rc > 1) { str_type = R_STRING_TYPE_UTF8; } } /* Invalid sequence detected */ if (!rc) { needle++; break; } needle += rc; if (r_isprint (r)) { if (str_type == R_STRING_TYPE_WIDE32) { if (r == 0xff) { r = 0; } } rc = r_utf8_encode (&tmp[i], r); runes++; /* Print the escape code */ } else if (r && r < 0x100 && strchr (""\b\v\f\n\r\t\a\e"", (char)r)) { if ((i + 32) < sizeof (tmp) && r < 28) { tmp[i + 0] = '\\'; tmp[i + 1] = "" abtnvfr e""[r]; } else { // string too long break; } rc = 2; runes++; } else { /* \0 marks the end of C-strings */ break; } } tmp[i++] = '\0'; if (runes >= min) { if (str_type == R_STRING_TYPE_ASCII) { // reduce false positives int j; for (j = 0; j < i; j++) { char ch = tmp[j]; if (ch != '\n' && ch != '\r' && ch != '\t') { if (!IS_PRINTABLE (tmp[j])) { continue; } } } } if (list) { RBinString *new = R_NEW0 (RBinString); if (!new) { break; } new->type = str_type; new->length = runes; new->size = needle - str_start; new->ordinal = count++; // TODO: move into adjust_offset switch (str_type) { case R_STRING_TYPE_WIDE: { const ut8 *p = buf + str_start - 2; if (p[0] == 0xff && p[1] == 0xfe) { str_start -= 2; // \xff\xfe } } break; case R_STRING_TYPE_WIDE32: { const ut8 *p = buf + str_start - 4; if (p[0] == 0xff && p[1] == 0xfe) { str_start -= 4; // \xff\xfe\x00\x00 } } break; } new->paddr = new->vaddr = str_start; new->string = r_str_ndup ((const char *)tmp, i); r_list_append (list, new); } else { // DUMP TO STDOUT. raw dumping for rabin2 -zzz printf (""0x%08"" PFMT64x "" %s\n"", str_start, tmp); } } } return count; }","static int string_scan_range(RList *list, const ut8 *buf, int min, const ut64 from, const ut64 to, int type) { ut8 tmp[R_STRING_SCAN_BUFFER_SIZE]; ut64 str_start, needle = from; int count = 0, i, rc, runes; int str_type = R_STRING_TYPE_DETECT; if (type == -1) { type = R_STRING_TYPE_DETECT; } if (!buf || !min) { return -1; } while (needle < to) { rc = r_utf8_decode (buf + needle, to - needle, NULL); if (!rc) { needle++; continue; } if (type == R_STRING_TYPE_DETECT) { char *w = (char *)buf + needle + rc; if ((to - needle) > 4) { bool is_wide32 = needle + rc + 2 < to && !w[0] && !w[1] && !w[2] && w[3] && !w[4]; if (is_wide32) { str_type = R_STRING_TYPE_WIDE32; } else { bool is_wide = needle + rc + 2 < to && !w[0] && w[1] && !w[2]; str_type = is_wide? R_STRING_TYPE_WIDE: R_STRING_TYPE_ASCII; } } else { str_type = R_STRING_TYPE_ASCII; } } else { str_type = type; } runes = 0; str_start = needle; /* Eat a whole C string */ for (rc = i = 0; i < sizeof (tmp) - 3 && needle < to; i += rc) { RRune r = {0}; if (str_type == R_STRING_TYPE_WIDE32) { rc = r_utf32le_decode (buf + needle, to - needle, &r); if (rc) { rc = 4; } } else if (str_type == R_STRING_TYPE_WIDE) { rc = r_utf16le_decode (buf + needle, to - needle, &r); if (rc == 1) { rc = 2; } } else { rc = r_utf8_decode (buf + needle, to - needle, &r); if (rc > 1) { str_type = R_STRING_TYPE_UTF8; } } /* Invalid sequence detected */ if (!rc) { needle++; break; } needle += rc; if (r_isprint (r)) { if (str_type == R_STRING_TYPE_WIDE32) { if (r == 0xff) { r = 0; } } rc = r_utf8_encode (&tmp[i], r); runes++; /* Print the escape code */ } else if (r && r < 0x100 && strchr (""\b\v\f\n\r\t\a\e"", (char)r)) { if ((i + 32) < sizeof (tmp) && r < 28) { tmp[i + 0] = '\\'; tmp[i + 1] = "" abtnvfr e""[r]; } else { // string too long break; } rc = 2; runes++; } else { /* \0 marks the end of C-strings */ break; } } tmp[i++] = '\0'; if (runes >= min) { if (str_type == R_STRING_TYPE_ASCII) { // reduce false positives int j; for (j = 0; j < i; j++) { char ch = tmp[j]; if (ch != '\n' && ch != '\r' && ch != '\t') { if (!IS_PRINTABLE (tmp[j])) { continue; } } } } if (list) { RBinString *new = R_NEW0 (RBinString); if (!new) { break; } new->type = str_type; new->length = runes; new->size = needle - str_start; new->ordinal = count++; // TODO: move into adjust_offset switch (str_type) { case R_STRING_TYPE_WIDE: if (str_start > 1) { const ut8 *p = buf + str_start - 2; if (p[0] == 0xff && p[1] == 0xfe) { str_start -= 2; // \xff\xfe } } break; case R_STRING_TYPE_WIDE32: if (str_start > 3) { const ut8 *p = buf + str_start - 4; if (p[0] == 0xff && p[1] == 0xfe) { str_start -= 4; // \xff\xfe\x00\x00 } } break; } new->paddr = new->vaddr = str_start; new->string = r_str_ndup ((const char *)tmp, i); r_list_append (list, new); } else { // DUMP TO STDOUT. raw dumping for rabin2 -zzz printf (""0x%08"" PFMT64x "" %s\n"", str_start, tmp); } } } return count; }","{'deleted': [{'line_no': 123, 'char_start': 2779, 'char_end': 2786, 'line': '\t\t\t\t\t{\n'}, {'line_no': 124, 'char_start': 2786, 'char_end': 2829, 'line': '\t\t\t\t\t\tconst ut8 *p = buf + str_start - 2;\n'}, {'line_no': 131, 'char_start': 2964, 'char_end': 2971, 'line': '\t\t\t\t\t{\n'}, {'line_no': 132, 'char_start': 2971, 'char_end': 3014, 'line': '\t\t\t\t\t\tconst ut8 *p = buf + str_start - 4;\n'}], 'added': [{'line_no': 123, 'char_start': 2779, 'char_end': 2805, 'line': '\t\t\t\t\tif (str_start > 1) {\n'}, {'line_no': 124, 'char_start': 2805, 'char_end': 2847, 'line': '\t\t\t\t\t\tconst ut8 *p = buf + str_start - 2;\n'}, {'line_no': 131, 'char_start': 2982, 'char_end': 3008, 'line': '\t\t\t\t\tif (str_start > 3) {\n'}, {'line_no': 132, 'char_start': 3008, 'char_end': 3050, 'line': '\t\t\t\t\t\tconst ut8 *p = buf + str_start - 4;\n'}]}","{'deleted': [{'char_start': 2810, 'char_end': 2811, 'chars': ' '}, {'char_start': 2995, 'char_end': 2996, 'chars': ' '}], 'added': [{'char_start': 2784, 'char_end': 2803, 'chars': 'if (str_start > 1) '}, {'char_start': 2987, 'char_end': 3006, 'chars': 'if (str_start > 3) '}]}",github.com/radare/radare2/commit/d31c4d3cbdbe01ea3ded16a584de94149ecd31d9,libr/bin/bin.c,cwe-125,1243 cwe-787,blosc_c,"static int blosc_c(struct thread_context* thread_context, int32_t bsize, int32_t leftoverblock, int32_t ntbytes, int32_t maxbytes, const uint8_t* src, const int32_t offset, uint8_t* dest, uint8_t* tmp, uint8_t* tmp2) { blosc2_context* context = thread_context->parent_context; int dont_split = (context->header_flags & 0x10) >> 4; int dict_training = context->use_dict && context->dict_cdict == NULL; int32_t j, neblock, nstreams; int32_t cbytes; /* number of compressed bytes in split */ int32_t ctbytes = 0; /* number of compressed bytes in block */ int64_t maxout; int32_t typesize = context->typesize; const char* compname; int accel; const uint8_t* _src; uint8_t *_tmp = tmp, *_tmp2 = tmp2; uint8_t *_tmp3 = thread_context->tmp4; int last_filter_index = last_filter(context->filters, 'c'); bool memcpyed = context->header_flags & (uint8_t)BLOSC_MEMCPYED; if (last_filter_index >= 0 || context->prefilter != NULL) { /* Apply the filter pipeline just for the prefilter */ if (memcpyed && context->prefilter != NULL) { // We only need the prefilter output _src = pipeline_c(thread_context, bsize, src, offset, dest, _tmp2, _tmp3); if (_src == NULL) { return -9; // signals a problem with the filter pipeline } return bsize; } /* Apply regular filter pipeline */ _src = pipeline_c(thread_context, bsize, src, offset, _tmp, _tmp2, _tmp3); if (_src == NULL) { return -9; // signals a problem with the filter pipeline } } else { _src = src + offset; } assert(context->clevel > 0); /* Calculate acceleration for different compressors */ accel = get_accel(context); /* The number of compressed data streams for this block */ if (!dont_split && !leftoverblock && !dict_training) { nstreams = (int32_t)typesize; } else { nstreams = 1; } neblock = bsize / nstreams; for (j = 0; j < nstreams; j++) { if (!dict_training) { dest += sizeof(int32_t); ntbytes += sizeof(int32_t); ctbytes += sizeof(int32_t); } // See if we have a run here const uint8_t* ip = (uint8_t*)_src + j * neblock; const uint8_t* ipbound = (uint8_t*)_src + (j + 1) * neblock; if (get_run(ip, ipbound)) { // A run. Encode the repeated byte as a negative length in the length of the split. int32_t value = _src[j * neblock]; _sw32(dest - 4, -value); continue; } maxout = neblock; #if defined(HAVE_SNAPPY) if (context->compcode == BLOSC_SNAPPY) { maxout = (int32_t)snappy_max_compressed_length((size_t)neblock); } #endif /* HAVE_SNAPPY */ if (ntbytes + maxout > maxbytes) { /* avoid buffer * overrun */ maxout = (int64_t)maxbytes - (int64_t)ntbytes; if (maxout <= 0) { return 0; /* non-compressible block */ } } if (dict_training) { // We are in the build dict state, so don't compress // TODO: copy only a percentage for sampling memcpy(dest, _src + j * neblock, (unsigned int)neblock); cbytes = (int32_t)neblock; } else if (context->compcode == BLOSC_BLOSCLZ) { cbytes = blosclz_compress(context->clevel, _src + j * neblock, (int)neblock, dest, (int)maxout); } #if defined(HAVE_LZ4) else if (context->compcode == BLOSC_LZ4) { void *hash_table = NULL; #ifdef HAVE_IPP hash_table = (void*)thread_context->lz4_hash_table; #endif cbytes = lz4_wrap_compress((char*)_src + j * neblock, (size_t)neblock, (char*)dest, (size_t)maxout, accel, hash_table); } else if (context->compcode == BLOSC_LZ4HC) { cbytes = lz4hc_wrap_compress((char*)_src + j * neblock, (size_t)neblock, (char*)dest, (size_t)maxout, context->clevel); } #endif /* HAVE_LZ4 */ #if defined(HAVE_LIZARD) else if (context->compcode == BLOSC_LIZARD) { cbytes = lizard_wrap_compress((char*)_src + j * neblock, (size_t)neblock, (char*)dest, (size_t)maxout, accel); } #endif /* HAVE_LIZARD */ #if defined(HAVE_SNAPPY) else if (context->compcode == BLOSC_SNAPPY) { cbytes = snappy_wrap_compress((char*)_src + j * neblock, (size_t)neblock, (char*)dest, (size_t)maxout); } #endif /* HAVE_SNAPPY */ #if defined(HAVE_ZLIB) else if (context->compcode == BLOSC_ZLIB) { cbytes = zlib_wrap_compress((char*)_src + j * neblock, (size_t)neblock, (char*)dest, (size_t)maxout, context->clevel); } #endif /* HAVE_ZLIB */ #if defined(HAVE_ZSTD) else if (context->compcode == BLOSC_ZSTD) { cbytes = zstd_wrap_compress(thread_context, (char*)_src + j * neblock, (size_t)neblock, (char*)dest, (size_t)maxout, context->clevel); } #endif /* HAVE_ZSTD */ else { blosc_compcode_to_compname(context->compcode, &compname); fprintf(stderr, ""Blosc has not been compiled with '%s' "", compname); fprintf(stderr, ""compression support. Please use one having it.""); return -5; /* signals no compression support */ } if (cbytes > maxout) { /* Buffer overrun caused by compression (should never happen) */ return -1; } if (cbytes < 0) { /* cbytes should never be negative */ return -2; } if (!dict_training) { if (cbytes == 0 || cbytes == neblock) { /* The compressor has been unable to compress data at all. */ /* Before doing the copy, check that we are not running into a buffer overflow. */ if ((ntbytes + neblock) > maxbytes) { return 0; /* Non-compressible data */ } memcpy(dest, _src + j * neblock, (unsigned int)neblock); cbytes = neblock; } _sw32(dest - 4, cbytes); } dest += cbytes; ntbytes += cbytes; ctbytes += cbytes; } /* Closes j < nstreams */ //printf(""c%d"", ctbytes); return ctbytes; }","static int blosc_c(struct thread_context* thread_context, int32_t bsize, int32_t leftoverblock, int32_t ntbytes, int32_t destsize, const uint8_t* src, const int32_t offset, uint8_t* dest, uint8_t* tmp, uint8_t* tmp2) { blosc2_context* context = thread_context->parent_context; int dont_split = (context->header_flags & 0x10) >> 4; int dict_training = context->use_dict && context->dict_cdict == NULL; int32_t j, neblock, nstreams; int32_t cbytes; /* number of compressed bytes in split */ int32_t ctbytes = 0; /* number of compressed bytes in block */ int64_t maxout; int32_t typesize = context->typesize; const char* compname; int accel; const uint8_t* _src; uint8_t *_tmp = tmp, *_tmp2 = tmp2; uint8_t *_tmp3 = thread_context->tmp4; int last_filter_index = last_filter(context->filters, 'c'); bool memcpyed = context->header_flags & (uint8_t)BLOSC_MEMCPYED; if (last_filter_index >= 0 || context->prefilter != NULL) { /* Apply the filter pipeline just for the prefilter */ if (memcpyed && context->prefilter != NULL) { // We only need the prefilter output _src = pipeline_c(thread_context, bsize, src, offset, dest, _tmp2, _tmp3); if (_src == NULL) { return -9; // signals a problem with the filter pipeline } return bsize; } /* Apply regular filter pipeline */ _src = pipeline_c(thread_context, bsize, src, offset, _tmp, _tmp2, _tmp3); if (_src == NULL) { return -9; // signals a problem with the filter pipeline } } else { _src = src + offset; } assert(context->clevel > 0); /* Calculate acceleration for different compressors */ accel = get_accel(context); /* The number of compressed data streams for this block */ if (!dont_split && !leftoverblock && !dict_training) { nstreams = (int32_t)typesize; } else { nstreams = 1; } neblock = bsize / nstreams; for (j = 0; j < nstreams; j++) { if (!dict_training) { dest += sizeof(int32_t); ntbytes += sizeof(int32_t); ctbytes += sizeof(int32_t); } // See if we have a run here const uint8_t* ip = (uint8_t*)_src + j * neblock; const uint8_t* ipbound = (uint8_t*)_src + (j + 1) * neblock; if (get_run(ip, ipbound)) { // A run. Encode the repeated byte as a negative length in the length of the split. int32_t value = _src[j * neblock]; if (ntbytes > destsize) { /* Not enough space to write out compressed block size */ return -1; } _sw32(dest - 4, -value); continue; } maxout = neblock; #if defined(HAVE_SNAPPY) if (context->compcode == BLOSC_SNAPPY) { maxout = (int32_t)snappy_max_compressed_length((size_t)neblock); } #endif /* HAVE_SNAPPY */ if (ntbytes + maxout > destsize) { /* avoid buffer * overrun */ maxout = (int64_t)destsize - (int64_t)ntbytes; if (maxout <= 0) { return 0; /* non-compressible block */ } } if (dict_training) { // We are in the build dict state, so don't compress // TODO: copy only a percentage for sampling memcpy(dest, _src + j * neblock, (unsigned int)neblock); cbytes = (int32_t)neblock; } else if (context->compcode == BLOSC_BLOSCLZ) { cbytes = blosclz_compress(context->clevel, _src + j * neblock, (int)neblock, dest, (int)maxout); } #if defined(HAVE_LZ4) else if (context->compcode == BLOSC_LZ4) { void *hash_table = NULL; #ifdef HAVE_IPP hash_table = (void*)thread_context->lz4_hash_table; #endif cbytes = lz4_wrap_compress((char*)_src + j * neblock, (size_t)neblock, (char*)dest, (size_t)maxout, accel, hash_table); } else if (context->compcode == BLOSC_LZ4HC) { cbytes = lz4hc_wrap_compress((char*)_src + j * neblock, (size_t)neblock, (char*)dest, (size_t)maxout, context->clevel); } #endif /* HAVE_LZ4 */ #if defined(HAVE_LIZARD) else if (context->compcode == BLOSC_LIZARD) { cbytes = lizard_wrap_compress((char*)_src + j * neblock, (size_t)neblock, (char*)dest, (size_t)maxout, accel); } #endif /* HAVE_LIZARD */ #if defined(HAVE_SNAPPY) else if (context->compcode == BLOSC_SNAPPY) { cbytes = snappy_wrap_compress((char*)_src + j * neblock, (size_t)neblock, (char*)dest, (size_t)maxout); } #endif /* HAVE_SNAPPY */ #if defined(HAVE_ZLIB) else if (context->compcode == BLOSC_ZLIB) { cbytes = zlib_wrap_compress((char*)_src + j * neblock, (size_t)neblock, (char*)dest, (size_t)maxout, context->clevel); } #endif /* HAVE_ZLIB */ #if defined(HAVE_ZSTD) else if (context->compcode == BLOSC_ZSTD) { cbytes = zstd_wrap_compress(thread_context, (char*)_src + j * neblock, (size_t)neblock, (char*)dest, (size_t)maxout, context->clevel); } #endif /* HAVE_ZSTD */ else { blosc_compcode_to_compname(context->compcode, &compname); fprintf(stderr, ""Blosc has not been compiled with '%s' "", compname); fprintf(stderr, ""compression support. Please use one having it.""); return -5; /* signals no compression support */ } if (cbytes > maxout) { /* Buffer overrun caused by compression (should never happen) */ return -1; } if (cbytes < 0) { /* cbytes should never be negative */ return -2; } if (!dict_training) { if (cbytes == 0 || cbytes == neblock) { /* The compressor has been unable to compress data at all. */ /* Before doing the copy, check that we are not running into a buffer overflow. */ if ((ntbytes + neblock) > destsize) { return 0; /* Non-compressible data */ } memcpy(dest, _src + j * neblock, (unsigned int)neblock); cbytes = neblock; } _sw32(dest - 4, cbytes); } dest += cbytes; ntbytes += cbytes; ctbytes += cbytes; } /* Closes j < nstreams */ //printf(""c%d"", ctbytes); return ctbytes; }","{'deleted': [{'line_no': 2, 'char_start': 73, 'char_end': 150, 'line': ' int32_t leftoverblock, int32_t ntbytes, int32_t maxbytes,\n'}, {'line_no': 78, 'char_start': 2729, 'char_end': 2768, 'line': ' if (ntbytes + maxout > maxbytes) {\n'}, {'line_no': 80, 'char_start': 2803, 'char_end': 2856, 'line': ' maxout = (int64_t)maxbytes - (int64_t)ntbytes;\n'}, {'line_no': 155, 'char_start': 5822, 'char_end': 5868, 'line': ' if ((ntbytes + neblock) > maxbytes) {\n'}], 'added': [{'line_no': 2, 'char_start': 73, 'char_end': 150, 'line': ' int32_t leftoverblock, int32_t ntbytes, int32_t destsize,\n'}, {'line_no': 68, 'char_start': 2476, 'char_end': 2508, 'line': ' if (ntbytes > destsize) {\n'}, {'line_no': 69, 'char_start': 2508, 'char_end': 2574, 'line': ' /* Not enough space to write out compressed block size */\n'}, {'line_no': 70, 'char_start': 2574, 'char_end': 2593, 'line': ' return -1;\n'}, {'line_no': 71, 'char_start': 2593, 'char_end': 2601, 'line': ' }\n'}, {'line_no': 82, 'char_start': 2854, 'char_end': 2893, 'line': ' if (ntbytes + maxout > destsize) {\n'}, {'line_no': 84, 'char_start': 2928, 'char_end': 2981, 'line': ' maxout = (int64_t)destsize - (int64_t)ntbytes;\n'}, {'line_no': 159, 'char_start': 5947, 'char_end': 5993, 'line': ' if ((ntbytes + neblock) > destsize) {\n'}]}","{'deleted': [{'char_start': 140, 'char_end': 146, 'chars': 'maxbyt'}, {'char_start': 2756, 'char_end': 2762, 'chars': 'maxbyt'}, {'char_start': 2827, 'char_end': 2833, 'chars': 'maxbyt'}, {'char_start': 5856, 'char_end': 5862, 'chars': 'maxbyt'}], 'added': [{'char_start': 140, 'char_end': 143, 'chars': 'des'}, {'char_start': 144, 'char_end': 147, 'chars': 'siz'}, {'char_start': 2482, 'char_end': 2607, 'chars': 'if (ntbytes > destsize) {\n /* Not enough space to write out compressed block size */\n return -1;\n }\n '}, {'char_start': 2881, 'char_end': 2884, 'chars': 'des'}, {'char_start': 2885, 'char_end': 2888, 'chars': 'siz'}, {'char_start': 2952, 'char_end': 2955, 'chars': 'des'}, {'char_start': 2956, 'char_end': 2959, 'chars': 'siz'}, {'char_start': 5981, 'char_end': 5984, 'chars': 'des'}, {'char_start': 5985, 'char_end': 5988, 'chars': 'siz'}]}",github.com/Blosc/c-blosc2/commit/c4c6470e88210afc95262c8b9fcc27e30ca043ee,blosc/blosc2.c,cwe-787,1796 cwe-416,mark_context_stack,"mark_context_stack(mrb_state *mrb, struct mrb_context *c) { size_t i; size_t e; if (c->stack == NULL) return; e = c->stack - c->stbase; if (c->ci) e += c->ci->nregs; if (c->stbase + e > c->stend) e = c->stend - c->stbase; for (i=0; istbase[i]; if (!mrb_immediate_p(v)) { if (mrb_basic_ptr(v)->tt == MRB_TT_FREE) { c->stbase[i] = mrb_nil_value(); } else { mrb_gc_mark(mrb, mrb_basic_ptr(v)); } } } }","mark_context_stack(mrb_state *mrb, struct mrb_context *c) { size_t i; size_t e; mrb_value nil; if (c->stack == NULL) return; e = c->stack - c->stbase; if (c->ci) e += c->ci->nregs; if (c->stbase + e > c->stend) e = c->stend - c->stbase; for (i=0; istbase[i]; if (!mrb_immediate_p(v)) { mrb_gc_mark(mrb, mrb_basic_ptr(v)); } } e = c->stend - c->stbase; nil = mrb_nil_value(); for (; istbase[i] = nil; } }","{'deleted': [{'line_no': 14, 'char_start': 323, 'char_end': 372, 'line': ' if (mrb_basic_ptr(v)->tt == MRB_TT_FREE) {\n'}, {'line_no': 15, 'char_start': 372, 'char_end': 412, 'line': ' c->stbase[i] = mrb_nil_value();\n'}, {'line_no': 16, 'char_start': 412, 'char_end': 420, 'line': ' }\n'}, {'line_no': 17, 'char_start': 420, 'char_end': 433, 'line': ' else {\n'}, {'line_no': 18, 'char_start': 433, 'char_end': 477, 'line': ' mrb_gc_mark(mrb, mrb_basic_ptr(v));\n'}, {'line_no': 19, 'char_start': 477, 'char_end': 485, 'line': ' }\n'}], 'added': [{'line_no': 5, 'char_start': 84, 'char_end': 101, 'line': ' mrb_value nil;\n'}, {'line_no': 15, 'char_start': 340, 'char_end': 382, 'line': ' mrb_gc_mark(mrb, mrb_basic_ptr(v));\n'}, {'line_no': 18, 'char_start': 392, 'char_end': 420, 'line': ' e = c->stend - c->stbase;\n'}, {'line_no': 19, 'char_start': 420, 'char_end': 445, 'line': ' nil = mrb_nil_value();\n'}, {'line_no': 20, 'char_start': 445, 'char_end': 466, 'line': ' for (; istbase[i] = nil;\n'}, {'line_no': 22, 'char_start': 490, 'char_end': 494, 'line': ' }\n'}]}","{'deleted': [{'char_start': 329, 'char_end': 331, 'chars': 'if'}, {'char_start': 332, 'char_end': 333, 'chars': '('}, {'char_start': 349, 'char_end': 353, 'chars': '->tt'}, {'char_start': 354, 'char_end': 356, 'chars': '=='}, {'char_start': 357, 'char_end': 369, 'chars': 'MRB_TT_FREE)'}, {'char_start': 370, 'char_end': 371, 'chars': '{'}, {'char_start': 389, 'char_end': 390, 'chars': '['}, {'char_start': 391, 'char_end': 392, 'chars': ']'}, {'char_start': 414, 'char_end': 424, 'chars': ' }\n '}, {'char_start': 427, 'char_end': 430, 'chars': 'lse'}, {'char_start': 433, 'char_end': 436, 'chars': ' '}, {'char_start': 440, 'char_end': 446, 'chars': ' mrb_g'}, {'char_start': 447, 'char_end': 462, 'chars': '_mark(mrb, mrb_'}, {'char_start': 466, 'char_end': 477, 'chars': 'c_ptr(v));\n'}, {'char_start': 478, 'char_end': 485, 'chars': ' }\n'}, {'char_start': 486, 'char_end': 490, 'chars': ' }'}], 'added': [{'char_start': 84, 'char_end': 101, 'chars': ' mrb_value nil;\n'}, {'char_start': 346, 'char_end': 357, 'chars': 'mrb_gc_mark'}, {'char_start': 358, 'char_end': 363, 'chars': 'mrb, '}, {'char_start': 379, 'char_end': 382, 'chars': ');\n'}, {'char_start': 383, 'char_end': 384, 'chars': ' '}, {'char_start': 386, 'char_end': 387, 'chars': '}'}, {'char_start': 390, 'char_end': 392, 'chars': '}\n'}, {'char_start': 394, 'char_end': 395, 'chars': 'e'}, {'char_start': 396, 'char_end': 397, 'chars': '='}, {'char_start': 398, 'char_end': 406, 'chars': 'c->stend'}, {'char_start': 407, 'char_end': 408, 'chars': '-'}, {'char_start': 418, 'char_end': 423, 'chars': ';\n n'}, {'char_start': 424, 'char_end': 425, 'chars': 'l'}, {'char_start': 447, 'char_end': 450, 'chars': 'for'}, {'char_start': 451, 'char_end': 453, 'chars': '(;'}, {'char_start': 454, 'char_end': 458, 'chars': 'ist'}, {'char_start': 478, 'char_end': 480, 'chars': 'e['}, {'char_start': 481, 'char_end': 482, 'chars': ']'}, {'char_start': 483, 'char_end': 484, 'chars': '='}, {'char_start': 485, 'char_end': 489, 'chars': 'nil;'}]}",github.com/mruby/mruby/commit/5c114c91d4ff31859fcd84cf8bf349b737b90d99,src/gc.c,cwe-416,183 cwe-089,tid_to_tid_num," def tid_to_tid_num(self, tid): ''' Returns tid_num, given tid. ''' q = ""SELECT rowid FROM tids WHERE tid = '"" + tid + ""'"" self.query(q) return self.c.fetchone()[0]"," def tid_to_tid_num(self, tid): ''' Returns tid_num, given tid. ''' q = ""SELECT rowid FROM tids WHERE tid = ?"" self.query(q, tid) return self.c.fetchone()[0]","{'deleted': [{'line_no': 4, 'char_start': 80, 'char_end': 143, 'line': ' q = ""SELECT rowid FROM tids WHERE tid = \'"" + tid + ""\'""\n'}, {'line_no': 5, 'char_start': 143, 'char_end': 165, 'line': ' self.query(q)\n'}], 'added': [{'line_no': 4, 'char_start': 80, 'char_end': 131, 'line': ' q = ""SELECT rowid FROM tids WHERE tid = ?""\n'}, {'line_no': 5, 'char_start': 131, 'char_end': 158, 'line': ' self.query(q, tid)\n'}]}","{'deleted': [{'char_start': 128, 'char_end': 141, 'chars': '\'"" + tid + ""\''}], 'added': [{'char_start': 128, 'char_end': 129, 'chars': '?'}, {'char_start': 151, 'char_end': 156, 'chars': ', tid'}]}",github.com/pukkapies/urop2019/commit/3ca2e2c291d2d5fe262d20a8e0520bdfb622432b,modules/query_lastfm.py,cwe-089,52 cwe-476,parse_class,"static void parse_class(RBinFile *binfile, RBinDexObj *bin, RBinDexClass *c, int class_index, int *methods, int *sym_count) { struct r_bin_t *rbin = binfile->rbin; char *class_name; int z; const ut8 *p, *p_end; if (!c) { return; } class_name = dex_class_name (bin, c); class_name = r_str_replace (class_name, "";"", """", 0); //TODO: move to func if (!class_name || !*class_name) { return; } RBinClass *cls = R_NEW0 (RBinClass); if (!cls) { return; } cls->name = class_name; cls->index = class_index; cls->addr = bin->header.class_offset + class_index * DEX_CLASS_SIZE; cls->methods = r_list_new (); if (!cls->methods) { free (cls); return; } cls->fields = r_list_new (); if (!cls->fields) { r_list_free (cls->methods); free (cls); return; } r_list_append (bin->classes_list, cls); if (dexdump) { rbin->cb_printf ("" Class descriptor : '%s;'\n"", class_name); rbin->cb_printf ( "" Access flags : 0x%04x (%s)\n"", c->access_flags, createAccessFlagStr (c->access_flags, kAccessForClass)); rbin->cb_printf ("" Superclass : '%s'\n"", dex_class_super_name (bin, c)); rbin->cb_printf ("" Interfaces -\n""); } if (c->interfaces_offset > 0 && bin->header.data_offset < c->interfaces_offset && c->interfaces_offset < bin->header.data_offset + bin->header.data_size) { p = r_buf_get_at (binfile->buf, c->interfaces_offset, NULL); int types_list_size = r_read_le32(p); if (types_list_size < 0 || types_list_size >= bin->header.types_size ) { return; } for (z = 0; z < types_list_size; z++) { int t = r_read_le16 (p + 4 + z * 2); if (t > 0 && t < bin->header.types_size ) { int tid = bin->types[t].descriptor_id; if (dexdump) { rbin->cb_printf ( "" #%d : '%s'\n"", z, getstr (bin, tid)); } } } } // TODO: this is quite ugly if (!c || !c->class_data_offset) { if (dexdump) { rbin->cb_printf ( "" Static fields -\n Instance fields "" ""-\n Direct methods -\n Virtual methods "" ""-\n""); } } else { // TODO: move to func, def or inline // class_data_offset => [class_offset, class_defs_off+class_defs_size*32] if (bin->header.class_offset > c->class_data_offset || c->class_data_offset < bin->header.class_offset + bin->header.class_size * DEX_CLASS_SIZE) { return; } p = r_buf_get_at (binfile->buf, c->class_data_offset, NULL); p_end = p + binfile->buf->length - c->class_data_offset; //XXX check for NULL!! c->class_data = (struct dex_class_data_item_t *)malloc ( sizeof (struct dex_class_data_item_t)); p = r_uleb128 (p, p_end - p, &c->class_data->static_fields_size); p = r_uleb128 (p, p_end - p, &c->class_data->instance_fields_size); p = r_uleb128 (p, p_end - p, &c->class_data->direct_methods_size); p = r_uleb128 (p, p_end - p, &c->class_data->virtual_methods_size); if (dexdump) { rbin->cb_printf ("" Static fields -\n""); } p = parse_dex_class_fields ( binfile, bin, c, cls, p, p_end, sym_count, c->class_data->static_fields_size, true); if (dexdump) { rbin->cb_printf ("" Instance fields -\n""); } p = parse_dex_class_fields ( binfile, bin, c, cls, p, p_end, sym_count, c->class_data->instance_fields_size, false); if (dexdump) { rbin->cb_printf ("" Direct methods -\n""); } p = parse_dex_class_method ( binfile, bin, c, cls, p, p_end, sym_count, c->class_data->direct_methods_size, methods, true); if (dexdump) { rbin->cb_printf ("" Virtual methods -\n""); } p = parse_dex_class_method ( binfile, bin, c, cls, p, p_end, sym_count, c->class_data->virtual_methods_size, methods, false); } if (dexdump) { char *source_file = getstr (bin, c->source_file); if (!source_file) { rbin->cb_printf ( "" source_file_idx : %d (unknown)\n\n"", c->source_file); } else { rbin->cb_printf ("" source_file_idx : %d (%s)\n\n"", c->source_file, source_file); } } // TODO:!!!! // FIX: FREE BEFORE ALLOCATE!!! //free (class_name); }","static void parse_class(RBinFile *binfile, RBinDexObj *bin, RBinDexClass *c, int class_index, int *methods, int *sym_count) { struct r_bin_t *rbin = binfile->rbin; char *class_name; int z; const ut8 *p, *p_end; if (!c) { return; } class_name = dex_class_name (bin, c); class_name = r_str_replace (class_name, "";"", """", 0); //TODO: move to func if (!class_name || !*class_name) { return; } RBinClass *cls = R_NEW0 (RBinClass); if (!cls) { return; } cls->name = class_name; cls->index = class_index; cls->addr = bin->header.class_offset + class_index * DEX_CLASS_SIZE; cls->methods = r_list_new (); if (!cls->methods) { free (cls); return; } cls->fields = r_list_new (); if (!cls->fields) { r_list_free (cls->methods); free (cls); return; } r_list_append (bin->classes_list, cls); if (dexdump) { rbin->cb_printf ("" Class descriptor : '%s;'\n"", class_name); rbin->cb_printf ( "" Access flags : 0x%04x (%s)\n"", c->access_flags, createAccessFlagStr (c->access_flags, kAccessForClass)); rbin->cb_printf ("" Superclass : '%s'\n"", dex_class_super_name (bin, c)); rbin->cb_printf ("" Interfaces -\n""); } if (c->interfaces_offset > 0 && bin->header.data_offset < c->interfaces_offset && c->interfaces_offset < bin->header.data_offset + bin->header.data_size) { p = r_buf_get_at (binfile->buf, c->interfaces_offset, NULL); int types_list_size = r_read_le32 (p); if (types_list_size < 0 || types_list_size >= bin->header.types_size ) { return; } for (z = 0; z < types_list_size; z++) { int t = r_read_le16 (p + 4 + z * 2); if (t > 0 && t < bin->header.types_size ) { int tid = bin->types[t].descriptor_id; if (dexdump) { rbin->cb_printf ( "" #%d : '%s'\n"", z, getstr (bin, tid)); } } } } // TODO: this is quite ugly if (!c || !c->class_data_offset) { if (dexdump) { rbin->cb_printf ( "" Static fields -\n Instance fields "" ""-\n Direct methods -\n Virtual methods "" ""-\n""); } } else { // TODO: move to func, def or inline // class_data_offset => [class_offset, class_defs_off+class_defs_size*32] if (bin->header.class_offset > c->class_data_offset || c->class_data_offset < bin->header.class_offset + bin->header.class_size * DEX_CLASS_SIZE) { return; } p = r_buf_get_at (binfile->buf, c->class_data_offset, NULL); p_end = p + binfile->buf->length - c->class_data_offset; //XXX check for NULL!! c->class_data = (struct dex_class_data_item_t *)malloc ( sizeof (struct dex_class_data_item_t)); p = r_uleb128 (p, p_end - p, &c->class_data->static_fields_size); p = r_uleb128 (p, p_end - p, &c->class_data->instance_fields_size); p = r_uleb128 (p, p_end - p, &c->class_data->direct_methods_size); p = r_uleb128 (p, p_end - p, &c->class_data->virtual_methods_size); if (dexdump) { rbin->cb_printf ("" Static fields -\n""); } p = parse_dex_class_fields ( binfile, bin, c, cls, p, p_end, sym_count, c->class_data->static_fields_size, true); if (dexdump) { rbin->cb_printf ("" Instance fields -\n""); } p = parse_dex_class_fields ( binfile, bin, c, cls, p, p_end, sym_count, c->class_data->instance_fields_size, false); if (dexdump) { rbin->cb_printf ("" Direct methods -\n""); } p = parse_dex_class_method ( binfile, bin, c, cls, p, p_end, sym_count, c->class_data->direct_methods_size, methods, true); if (dexdump) { rbin->cb_printf ("" Virtual methods -\n""); } p = parse_dex_class_method ( binfile, bin, c, cls, p, p_end, sym_count, c->class_data->virtual_methods_size, methods, false); } if (dexdump) { char *source_file = getstr (bin, c->source_file); if (!source_file) { rbin->cb_printf ( "" source_file_idx : %d (unknown)\n\n"", c->source_file); } else { rbin->cb_printf ("" source_file_idx : %d (%s)\n\n"", c->source_file, source_file); } } // TODO:!!!! // FIX: FREE BEFORE ALLOCATE!!! //free (class_name); }","{'deleted': [{'line_no': 54, 'char_start': 1421, 'char_end': 1461, 'line': '\t\tint types_list_size = r_read_le32(p);\n'}], 'added': [{'line_no': 54, 'char_start': 1421, 'char_end': 1462, 'line': '\t\tint types_list_size = r_read_le32 (p);\n'}]}","{'deleted': [], 'added': [{'char_start': 1456, 'char_end': 1457, 'chars': ' '}]}",github.com/radare/radare2/commit/1ea23bd6040441a21fbcfba69dce9a01af03f989,libr/bin/p/bin_dex.c,cwe-476,1339 cwe-476,php_wddx_pop_element," */ static void php_wddx_pop_element(void *user_data, const XML_Char *name) { st_entry *ent1, *ent2; wddx_stack *stack = (wddx_stack *)user_data; HashTable *target_hash; zend_class_entry **pce; zval *obj; zval *tmp; TSRMLS_FETCH(); /* OBJECTS_FIXME */ if (stack->top == 0) { return; } if (!strcmp(name, EL_STRING) || !strcmp(name, EL_NUMBER) || !strcmp(name, EL_BOOLEAN) || !strcmp(name, EL_NULL) || !strcmp(name, EL_ARRAY) || !strcmp(name, EL_STRUCT) || !strcmp(name, EL_RECORDSET) || !strcmp(name, EL_BINARY) || !strcmp(name, EL_DATETIME)) { wddx_stack_top(stack, (void**)&ent1); if (!ent1->data) { if (stack->top > 1) { stack->top--; } else { stack->done = 1; } efree(ent1); return; } if (!strcmp(name, EL_BINARY)) { int new_len=0; unsigned char *new_str; new_str = php_base64_decode(Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data), &new_len); STR_FREE(Z_STRVAL_P(ent1->data)); Z_STRVAL_P(ent1->data) = new_str; Z_STRLEN_P(ent1->data) = new_len; } /* Call __wakeup() method on the object. */ if (Z_TYPE_P(ent1->data) == IS_OBJECT) { zval *fname, *retval = NULL; MAKE_STD_ZVAL(fname); ZVAL_STRING(fname, ""__wakeup"", 1); call_user_function_ex(NULL, &ent1->data, fname, &retval, 0, 0, 0, NULL TSRMLS_CC); zval_dtor(fname); FREE_ZVAL(fname); if (retval) { zval_ptr_dtor(&retval); } } if (stack->top > 1) { stack->top--; wddx_stack_top(stack, (void**)&ent2); /* if non-existent field */ if (ent2->type == ST_FIELD && ent2->data == NULL) { zval_ptr_dtor(&ent1->data); efree(ent1); return; } if (Z_TYPE_P(ent2->data) == IS_ARRAY || Z_TYPE_P(ent2->data) == IS_OBJECT) { target_hash = HASH_OF(ent2->data); if (ent1->varname) { if (!strcmp(ent1->varname, PHP_CLASS_NAME_VAR) && Z_TYPE_P(ent1->data) == IS_STRING && Z_STRLEN_P(ent1->data) && ent2->type == ST_STRUCT && Z_TYPE_P(ent2->data) == IS_ARRAY) { zend_bool incomplete_class = 0; zend_str_tolower(Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data)); if (zend_hash_find(EG(class_table), Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data)+1, (void **) &pce)==FAILURE) { incomplete_class = 1; pce = &PHP_IC_ENTRY; } /* Initialize target object */ MAKE_STD_ZVAL(obj); object_init_ex(obj, *pce); /* Merge current hashtable with object's default properties */ zend_hash_merge(Z_OBJPROP_P(obj), Z_ARRVAL_P(ent2->data), (void (*)(void *)) zval_add_ref, (void *) &tmp, sizeof(zval *), 0); if (incomplete_class) { php_store_class_name(obj, Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data)); } /* Clean up old array entry */ zval_ptr_dtor(&ent2->data); /* Set stack entry to point to the newly created object */ ent2->data = obj; /* Clean up class name var entry */ zval_ptr_dtor(&ent1->data); } else if (Z_TYPE_P(ent2->data) == IS_OBJECT) { zend_class_entry *old_scope = EG(scope); EG(scope) = Z_OBJCE_P(ent2->data); Z_DELREF_P(ent1->data); add_property_zval(ent2->data, ent1->varname, ent1->data); EG(scope) = old_scope; } else { zend_symtable_update(target_hash, ent1->varname, strlen(ent1->varname)+1, &ent1->data, sizeof(zval *), NULL); } efree(ent1->varname); } else { zend_hash_next_index_insert(target_hash, &ent1->data, sizeof(zval *), NULL); } } efree(ent1); } else { stack->done = 1; } } else if (!strcmp(name, EL_VAR) && stack->varname) { efree(stack->varname); stack->varname = NULL; } else if (!strcmp(name, EL_FIELD)) { st_entry *ent; wddx_stack_top(stack, (void **)&ent); efree(ent); stack->top--; }"," */ static void php_wddx_pop_element(void *user_data, const XML_Char *name) { st_entry *ent1, *ent2; wddx_stack *stack = (wddx_stack *)user_data; HashTable *target_hash; zend_class_entry **pce; zval *obj; zval *tmp; TSRMLS_FETCH(); /* OBJECTS_FIXME */ if (stack->top == 0) { return; } if (!strcmp(name, EL_STRING) || !strcmp(name, EL_NUMBER) || !strcmp(name, EL_BOOLEAN) || !strcmp(name, EL_NULL) || !strcmp(name, EL_ARRAY) || !strcmp(name, EL_STRUCT) || !strcmp(name, EL_RECORDSET) || !strcmp(name, EL_BINARY) || !strcmp(name, EL_DATETIME)) { wddx_stack_top(stack, (void**)&ent1); if (!ent1->data) { if (stack->top > 1) { stack->top--; } else { stack->done = 1; } efree(ent1); return; } if (!strcmp(name, EL_BINARY)) { int new_len=0; unsigned char *new_str; new_str = php_base64_decode(Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data), &new_len); STR_FREE(Z_STRVAL_P(ent1->data)); if (new_str) { Z_STRVAL_P(ent1->data) = new_str; Z_STRLEN_P(ent1->data) = new_len; } else { ZVAL_EMPTY_STRING(ent1->data); } } /* Call __wakeup() method on the object. */ if (Z_TYPE_P(ent1->data) == IS_OBJECT) { zval *fname, *retval = NULL; MAKE_STD_ZVAL(fname); ZVAL_STRING(fname, ""__wakeup"", 1); call_user_function_ex(NULL, &ent1->data, fname, &retval, 0, 0, 0, NULL TSRMLS_CC); zval_dtor(fname); FREE_ZVAL(fname); if (retval) { zval_ptr_dtor(&retval); } } if (stack->top > 1) { stack->top--; wddx_stack_top(stack, (void**)&ent2); /* if non-existent field */ if (ent2->type == ST_FIELD && ent2->data == NULL) { zval_ptr_dtor(&ent1->data); efree(ent1); return; } if (Z_TYPE_P(ent2->data) == IS_ARRAY || Z_TYPE_P(ent2->data) == IS_OBJECT) { target_hash = HASH_OF(ent2->data); if (ent1->varname) { if (!strcmp(ent1->varname, PHP_CLASS_NAME_VAR) && Z_TYPE_P(ent1->data) == IS_STRING && Z_STRLEN_P(ent1->data) && ent2->type == ST_STRUCT && Z_TYPE_P(ent2->data) == IS_ARRAY) { zend_bool incomplete_class = 0; zend_str_tolower(Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data)); if (zend_hash_find(EG(class_table), Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data)+1, (void **) &pce)==FAILURE) { incomplete_class = 1; pce = &PHP_IC_ENTRY; } /* Initialize target object */ MAKE_STD_ZVAL(obj); object_init_ex(obj, *pce); /* Merge current hashtable with object's default properties */ zend_hash_merge(Z_OBJPROP_P(obj), Z_ARRVAL_P(ent2->data), (void (*)(void *)) zval_add_ref, (void *) &tmp, sizeof(zval *), 0); if (incomplete_class) { php_store_class_name(obj, Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data)); } /* Clean up old array entry */ zval_ptr_dtor(&ent2->data); /* Set stack entry to point to the newly created object */ ent2->data = obj; /* Clean up class name var entry */ zval_ptr_dtor(&ent1->data); } else if (Z_TYPE_P(ent2->data) == IS_OBJECT) { zend_class_entry *old_scope = EG(scope); EG(scope) = Z_OBJCE_P(ent2->data); Z_DELREF_P(ent1->data); add_property_zval(ent2->data, ent1->varname, ent1->data); EG(scope) = old_scope; } else { zend_symtable_update(target_hash, ent1->varname, strlen(ent1->varname)+1, &ent1->data, sizeof(zval *), NULL); } efree(ent1->varname); } else { zend_hash_next_index_insert(target_hash, &ent1->data, sizeof(zval *), NULL); } } efree(ent1); } else { stack->done = 1; } } else if (!strcmp(name, EL_VAR) && stack->varname) { efree(stack->varname); stack->varname = NULL; } else if (!strcmp(name, EL_FIELD)) { st_entry *ent; wddx_stack_top(stack, (void **)&ent); efree(ent); stack->top--; }","{'deleted': [{'line_no': 40, 'char_start': 966, 'char_end': 1003, 'line': '\t\t\tZ_STRVAL_P(ent1->data) = new_str;\n'}, {'line_no': 41, 'char_start': 1003, 'char_end': 1040, 'line': '\t\t\tZ_STRLEN_P(ent1->data) = new_len;\n'}], 'added': [{'line_no': 40, 'char_start': 966, 'char_end': 984, 'line': '\t\t\tif (new_str) {\n'}, {'line_no': 41, 'char_start': 984, 'char_end': 1022, 'line': '\t\t\t\tZ_STRVAL_P(ent1->data) = new_str;\n'}, {'line_no': 42, 'char_start': 1022, 'char_end': 1060, 'line': '\t\t\t\tZ_STRLEN_P(ent1->data) = new_len;\n'}, {'line_no': 43, 'char_start': 1060, 'char_end': 1072, 'line': '\t\t\t} else {\n'}, {'line_no': 44, 'char_start': 1072, 'char_end': 1107, 'line': '\t\t\t\tZVAL_EMPTY_STRING(ent1->data);\n'}, {'line_no': 45, 'char_start': 1107, 'char_end': 1112, 'line': '\t\t\t}\n'}]}","{'deleted': [], 'added': [{'char_start': 969, 'char_end': 988, 'chars': 'if (new_str) {\n\t\t\t\t'}, {'char_start': 1025, 'char_end': 1026, 'chars': '\t'}, {'char_start': 1059, 'char_end': 1111, 'chars': '\n\t\t\t} else {\n\t\t\t\tZVAL_EMPTY_STRING(ent1->data);\n\t\t\t}'}]}",github.com/php/php-src/commit/698a691724c0a949295991e5df091ce16f899e02,ext/wddx/wddx.c,cwe-476,1241 cwe-476,big_key_init,"static int __init big_key_init(void) { return register_key_type(&key_type_big_key); }","static int __init big_key_init(void) { struct crypto_skcipher *cipher; struct crypto_rng *rng; int ret; rng = crypto_alloc_rng(big_key_rng_name, 0, 0); if (IS_ERR(rng)) { pr_err(""Can't alloc rng: %ld\n"", PTR_ERR(rng)); return PTR_ERR(rng); } big_key_rng = rng; /* seed RNG */ ret = crypto_rng_reset(rng, NULL, crypto_rng_seedsize(rng)); if (ret) { pr_err(""Can't reset rng: %d\n"", ret); goto error_rng; } /* init block cipher */ cipher = crypto_alloc_skcipher(big_key_alg_name, 0, CRYPTO_ALG_ASYNC); if (IS_ERR(cipher)) { ret = PTR_ERR(cipher); pr_err(""Can't alloc crypto: %d\n"", ret); goto error_rng; } big_key_skcipher = cipher; ret = register_key_type(&key_type_big_key); if (ret < 0) { pr_err(""Can't register type: %d\n"", ret); goto error_cipher; } return 0; error_cipher: crypto_free_skcipher(big_key_skcipher); error_rng: crypto_free_rng(big_key_rng); return ret; }","{'deleted': [{'line_no': 3, 'char_start': 39, 'char_end': 85, 'line': '\treturn register_key_type(&key_type_big_key);\n'}, {'line_no': 4, 'char_start': 85, 'char_end': 86, 'line': '}\n'}], 'added': []}","{'deleted': [], 'added': [{'char_start': 40, 'char_end': 42, 'chars': 'st'}, {'char_start': 43, 'char_end': 68, 'chars': 'uct crypto_skcipher *ciph'}, {'char_start': 69, 'char_end': 74, 'chars': 'r;\n\ts'}, {'char_start': 75, 'char_end': 76, 'chars': 'r'}, {'char_start': 77, 'char_end': 87, 'chars': 'ct crypto_'}, {'char_start': 89, 'char_end': 672, 'chars': 'g *rng;\n\tint ret;\n\n\trng = crypto_alloc_rng(big_key_rng_name, 0, 0);\n\tif (IS_ERR(rng)) {\n\t\tpr_err(""Can\'t alloc rng: %ld\\n"", PTR_ERR(rng));\n\t\treturn PTR_ERR(rng);\n\t}\n\n\tbig_key_rng = rng;\n\n\t/* seed RNG */\n\tret = crypto_rng_reset(rng, NULL, crypto_rng_seedsize(rng));\n\tif (ret) {\n\t\tpr_err(""Can\'t reset rng: %d\\n"", ret);\n\t\tgoto error_rng;\n\t}\n\n\t/* init block cipher */\n\tcipher = crypto_alloc_skcipher(big_key_alg_name, 0, CRYPTO_ALG_ASYNC);\n\tif (IS_ERR(cipher)) {\n\t\tret = PTR_ERR(cipher);\n\t\tpr_err(""Can\'t alloc crypto: %d\\n"", ret);\n\t\tgoto error_rng;\n\t}\n\n\tbig_key_skcipher = cipher;\n\n\tret ='}, {'char_start': 709, 'char_end': 916, 'chars': ';\n\tif (ret < 0) {\n\t\tpr_err(""Can\'t register type: %d\\n"", ret);\n\t\tgoto error_cipher;\n\t}\n\n\treturn 0;\n\nerror_cipher:\n\tcrypto_free_skcipher(big_key_skcipher);\nerror_rng:\n\tcrypto_free_rng(big_key_rng);\n\treturn ret'}]}",github.com/torvalds/linux/commit/7df3e59c3d1df4f87fe874c7956ef7a3d2f4d5fb,security/keys/big_key.c,cwe-476,21 cwe-416,ndpi_reset_packet_line_info,"static void ndpi_reset_packet_line_info(struct ndpi_packet_struct *packet) { packet->parsed_lines = 0, packet->empty_line_position_set = 0, packet->host_line.ptr = NULL, packet->host_line.len = 0, packet->referer_line.ptr = NULL, packet->referer_line.len = 0, packet->content_line.ptr = NULL, packet->content_line.len = 0, packet->accept_line.ptr = NULL, packet->accept_line.len = 0, packet->user_agent_line.ptr = NULL, packet->user_agent_line.len = 0, packet->http_url_name.ptr = NULL, packet->http_url_name.len = 0, packet->http_encoding.ptr = NULL, packet->http_encoding.len = 0, packet->http_transfer_encoding.ptr = NULL, packet->http_transfer_encoding.len = 0, packet->http_contentlen.ptr = NULL, packet->http_contentlen.len = 0, packet->http_cookie.ptr = NULL, packet->http_cookie.len = 0, packet->http_origin.len = 0, packet->http_origin.ptr = NULL, packet->http_x_session_type.ptr = NULL, packet->http_x_session_type.len = 0, packet->server_line.ptr = NULL, packet->server_line.len = 0, packet->http_method.ptr = NULL, packet->http_method.len = 0, packet->http_response.ptr = NULL, packet->http_response.len = 0, packet->http_num_headers = 0; }","static void ndpi_reset_packet_line_info(struct ndpi_packet_struct *packet) { packet->parsed_lines = 0, packet->empty_line_position_set = 0, packet->host_line.ptr = NULL, packet->host_line.len = 0, packet->referer_line.ptr = NULL, packet->referer_line.len = 0, packet->content_line.ptr = NULL, packet->content_line.len = 0, packet->accept_line.ptr = NULL, packet->accept_line.len = 0, packet->user_agent_line.ptr = NULL, packet->user_agent_line.len = 0, packet->http_url_name.ptr = NULL, packet->http_url_name.len = 0, packet->http_encoding.ptr = NULL, packet->http_encoding.len = 0, packet->http_transfer_encoding.ptr = NULL, packet->http_transfer_encoding.len = 0, packet->http_contentlen.ptr = NULL, packet->http_contentlen.len = 0, packet->content_disposition_line.ptr = NULL, packet->content_disposition_line.len = 0, packet->http_cookie.ptr = NULL, packet->http_cookie.len = 0, packet->http_origin.len = 0, packet->http_origin.ptr = NULL, packet->http_x_session_type.ptr = NULL, packet->http_x_session_type.len = 0, packet->server_line.ptr = NULL, packet->server_line.len = 0, packet->http_method.ptr = NULL, packet->http_method.len = 0, packet->http_response.ptr = NULL, packet->http_response.len = 0, packet->http_num_headers = 0; }","{'deleted': [{'line_no': 8, 'char_start': 688, 'char_end': 793, 'line': ' packet->http_contentlen.ptr = NULL, packet->http_contentlen.len = 0, packet->http_cookie.ptr = NULL,\n'}], 'added': [{'line_no': 8, 'char_start': 688, 'char_end': 806, 'line': ' packet->http_contentlen.ptr = NULL, packet->http_contentlen.len = 0, packet->content_disposition_line.ptr = NULL,\n'}, {'line_no': 9, 'char_start': 806, 'char_end': 884, 'line': ' packet->content_disposition_line.len = 0, packet->http_cookie.ptr = NULL,\n'}]}","{'deleted': [], 'added': [{'char_start': 769, 'char_end': 860, 'chars': 'content_disposition_line.ptr = NULL,\n packet->content_disposition_line.len = 0, packet->'}]}",github.com/ntop/nDPI/commit/6a9f5e4f7c3fd5ddab3e6727b071904d76773952,src/lib/ndpi_main.c,cwe-416,323 cwe-125,getToken,"static x86newTokenType getToken(const char *str, size_t *begin, size_t *end) { // Skip whitespace while (begin && isspace ((ut8)str[*begin])) { ++(*begin); } if (!str[*begin]) { // null byte *end = *begin; return TT_EOF; } else if (isalpha ((ut8)str[*begin])) { // word token *end = *begin; while (end && isalnum ((ut8)str[*end])) { ++(*end); } return TT_WORD; } else if (isdigit ((ut8)str[*begin])) { // number token *end = *begin; while (end && isalnum ((ut8)str[*end])) { // accept alphanumeric characters, because hex. ++(*end); } return TT_NUMBER; } else { // special character: [, ], +, *, ... *end = *begin + 1; return TT_SPECIAL; } }","static x86newTokenType getToken(const char *str, size_t *begin, size_t *end) { if (*begin > strlen (str)) { return TT_EOF; } // Skip whitespace while (begin && str[*begin] && isspace ((ut8)str[*begin])) { ++(*begin); } if (!str[*begin]) { // null byte *end = *begin; return TT_EOF; } if (isalpha ((ut8)str[*begin])) { // word token *end = *begin; while (end && str[*end] && isalnum ((ut8)str[*end])) { ++(*end); } return TT_WORD; } if (isdigit ((ut8)str[*begin])) { // number token *end = *begin; while (end && isalnum ((ut8)str[*end])) { // accept alphanumeric characters, because hex. ++(*end); } return TT_NUMBER; } else { // special character: [, ], +, *, ... *end = *begin + 1; return TT_SPECIAL; } }","{'deleted': [{'line_no': 3, 'char_start': 99, 'char_end': 146, 'line': '\twhile (begin && isspace ((ut8)str[*begin])) {\n'}, {'line_no': 10, 'char_start': 247, 'char_end': 305, 'line': '\t} else if (isalpha ((ut8)str[*begin])) { // word token\n'}, {'line_no': 12, 'char_start': 322, 'char_end': 366, 'line': '\t\twhile (end && isalnum ((ut8)str[*end])) {\n'}, {'line_no': 16, 'char_start': 401, 'char_end': 461, 'line': '\t} else if (isdigit ((ut8)str[*begin])) { // number token\n'}], 'added': [{'line_no': 2, 'char_start': 79, 'char_end': 109, 'line': '\tif (*begin > strlen (str)) {\n'}, {'line_no': 3, 'char_start': 109, 'char_end': 126, 'line': '\t\treturn TT_EOF;\n'}, {'line_no': 4, 'char_start': 126, 'char_end': 129, 'line': '\t}\n'}, {'line_no': 6, 'char_start': 149, 'char_end': 211, 'line': '\twhile (begin && str[*begin] && isspace ((ut8)str[*begin])) {\n'}, {'line_no': 13, 'char_start': 312, 'char_end': 315, 'line': '\t}\n'}, {'line_no': 14, 'char_start': 315, 'char_end': 366, 'line': '\tif (isalpha ((ut8)str[*begin])) { // word token\n'}, {'line_no': 16, 'char_start': 383, 'char_end': 440, 'line': '\t\twhile (end && str[*end] && isalnum ((ut8)str[*end])) {\n'}, {'line_no': 20, 'char_start': 475, 'char_end': 478, 'line': '\t}\n'}, {'line_no': 21, 'char_start': 478, 'char_end': 531, 'line': '\tif (isdigit ((ut8)str[*begin])) { // number token\n'}]}","{'deleted': [{'char_start': 249, 'char_end': 255, 'chars': ' else '}, {'char_start': 403, 'char_end': 409, 'chars': ' else '}], 'added': [{'char_start': 80, 'char_end': 130, 'chars': 'if (*begin > strlen (str)) {\n\t\treturn TT_EOF;\n\t}\n\t'}, {'char_start': 162, 'char_end': 177, 'chars': ' && str[*begin]'}, {'char_start': 314, 'char_end': 316, 'chars': '\n\t'}, {'char_start': 395, 'char_end': 408, 'chars': ' && str[*end]'}, {'char_start': 477, 'char_end': 479, 'chars': '\n\t'}]}",github.com/radare/radare2/commit/66191f780863ea8c66ace4040d0d04a8842e8432,libr/asm/p/asm_x86_nz.c,cwe-125,236 cwe-787,FromkLinuxSockAddr,"bool FromkLinuxSockAddr(const struct klinux_sockaddr *input, socklen_t input_len, struct sockaddr *output, socklen_t *output_len, void (*abort_handler)(const char *)) { if (!input || !output || !output_len || input_len == 0) { output = nullptr; return false; } int16_t klinux_family = input->klinux_sa_family; if (klinux_family == kLinux_AF_UNIX) { struct klinux_sockaddr_un *klinux_sockaddr_un_in = const_cast( reinterpret_cast(input)); struct sockaddr_un sockaddr_un_out; sockaddr_un_out.sun_family = AF_UNIX; InitializeToZeroArray(sockaddr_un_out.sun_path); ReinterpretCopyArray( sockaddr_un_out.sun_path, klinux_sockaddr_un_in->klinux_sun_path, std::min(sizeof(sockaddr_un_out.sun_path), sizeof(klinux_sockaddr_un_in->klinux_sun_path))); CopySockaddr(&sockaddr_un_out, sizeof(sockaddr_un_out), output, output_len); } else if (klinux_family == kLinux_AF_INET) { struct klinux_sockaddr_in *klinux_sockaddr_in_in = const_cast( reinterpret_cast(input)); struct sockaddr_in sockaddr_in_out; sockaddr_in_out.sin_family = AF_INET; sockaddr_in_out.sin_port = klinux_sockaddr_in_in->klinux_sin_port; InitializeToZeroSingle(&sockaddr_in_out.sin_addr); ReinterpretCopySingle(&sockaddr_in_out.sin_addr, &klinux_sockaddr_in_in->klinux_sin_addr); InitializeToZeroArray(sockaddr_in_out.sin_zero); ReinterpretCopyArray(sockaddr_in_out.sin_zero, klinux_sockaddr_in_in->klinux_sin_zero); CopySockaddr(&sockaddr_in_out, sizeof(sockaddr_in_out), output, output_len); } else if (klinux_family == kLinux_AF_INET6) { struct klinux_sockaddr_in6 *klinux_sockaddr_in6_in = const_cast( reinterpret_cast(input)); struct sockaddr_in6 sockaddr_in6_out; sockaddr_in6_out.sin6_family = AF_INET6; sockaddr_in6_out.sin6_port = klinux_sockaddr_in6_in->klinux_sin6_port; sockaddr_in6_out.sin6_flowinfo = klinux_sockaddr_in6_in->klinux_sin6_flowinfo; sockaddr_in6_out.sin6_scope_id = klinux_sockaddr_in6_in->klinux_sin6_scope_id; InitializeToZeroSingle(&sockaddr_in6_out.sin6_addr); ReinterpretCopySingle(&sockaddr_in6_out.sin6_addr, &klinux_sockaddr_in6_in->klinux_sin6_addr); CopySockaddr(&sockaddr_in6_out, sizeof(sockaddr_in6_out), output, output_len); } else if (klinux_family == kLinux_AF_UNSPEC) { output = nullptr; *output_len = 0; } else { if (abort_handler != nullptr) { std::string message = absl::StrCat( ""Type conversion error - Unsupported AF family: "", klinux_family); abort_handler(message.c_str()); } else { abort(); } } return true; }","bool FromkLinuxSockAddr(const struct klinux_sockaddr *input, socklen_t input_len, struct sockaddr *output, socklen_t *output_len, void (*abort_handler)(const char *)) { if (!input || !output || !output_len || input_len == 0) { output = nullptr; return false; } int16_t klinux_family = input->klinux_sa_family; if (klinux_family == kLinux_AF_UNIX) { if (input_len < sizeof(struct klinux_sockaddr_un)) { return false; } struct klinux_sockaddr_un *klinux_sockaddr_un_in = const_cast( reinterpret_cast(input)); struct sockaddr_un sockaddr_un_out; sockaddr_un_out.sun_family = AF_UNIX; InitializeToZeroArray(sockaddr_un_out.sun_path); ReinterpretCopyArray( sockaddr_un_out.sun_path, klinux_sockaddr_un_in->klinux_sun_path, std::min(sizeof(sockaddr_un_out.sun_path), sizeof(klinux_sockaddr_un_in->klinux_sun_path))); CopySockaddr(&sockaddr_un_out, sizeof(sockaddr_un_out), output, output_len); } else if (klinux_family == kLinux_AF_INET) { if (input_len < sizeof(struct klinux_sockaddr_in)) { return false; } struct klinux_sockaddr_in *klinux_sockaddr_in_in = const_cast( reinterpret_cast(input)); struct sockaddr_in sockaddr_in_out; sockaddr_in_out.sin_family = AF_INET; sockaddr_in_out.sin_port = klinux_sockaddr_in_in->klinux_sin_port; InitializeToZeroSingle(&sockaddr_in_out.sin_addr); ReinterpretCopySingle(&sockaddr_in_out.sin_addr, &klinux_sockaddr_in_in->klinux_sin_addr); InitializeToZeroArray(sockaddr_in_out.sin_zero); ReinterpretCopyArray(sockaddr_in_out.sin_zero, klinux_sockaddr_in_in->klinux_sin_zero); CopySockaddr(&sockaddr_in_out, sizeof(sockaddr_in_out), output, output_len); } else if (klinux_family == kLinux_AF_INET6) { if (input_len < sizeof(struct klinux_sockaddr_in6)) { return false; } struct klinux_sockaddr_in6 *klinux_sockaddr_in6_in = const_cast( reinterpret_cast(input)); struct sockaddr_in6 sockaddr_in6_out; sockaddr_in6_out.sin6_family = AF_INET6; sockaddr_in6_out.sin6_port = klinux_sockaddr_in6_in->klinux_sin6_port; sockaddr_in6_out.sin6_flowinfo = klinux_sockaddr_in6_in->klinux_sin6_flowinfo; sockaddr_in6_out.sin6_scope_id = klinux_sockaddr_in6_in->klinux_sin6_scope_id; InitializeToZeroSingle(&sockaddr_in6_out.sin6_addr); ReinterpretCopySingle(&sockaddr_in6_out.sin6_addr, &klinux_sockaddr_in6_in->klinux_sin6_addr); CopySockaddr(&sockaddr_in6_out, sizeof(sockaddr_in6_out), output, output_len); } else if (klinux_family == kLinux_AF_UNSPEC) { output = nullptr; *output_len = 0; } else { if (abort_handler != nullptr) { std::string message = absl::StrCat( ""Type conversion error - Unsupported AF family: "", klinux_family); abort_handler(message.c_str()); } else { abort(); } } return true; }","{'deleted': [], 'added': [{'line_no': 12, 'char_start': 438, 'char_end': 495, 'line': ' if (input_len < sizeof(struct klinux_sockaddr_un)) {\n'}, {'line_no': 13, 'char_start': 495, 'char_end': 515, 'line': ' return false;\n'}, {'line_no': 14, 'char_start': 515, 'char_end': 521, 'line': ' }\n'}, {'line_no': 15, 'char_start': 521, 'char_end': 522, 'line': '\n'}, {'line_no': 29, 'char_start': 1182, 'char_end': 1239, 'line': ' if (input_len < sizeof(struct klinux_sockaddr_in)) {\n'}, {'line_no': 30, 'char_start': 1239, 'char_end': 1259, 'line': ' return false;\n'}, {'line_no': 31, 'char_start': 1259, 'char_end': 1265, 'line': ' }\n'}, {'line_no': 47, 'char_start': 2072, 'char_end': 2130, 'line': ' if (input_len < sizeof(struct klinux_sockaddr_in6)) {\n'}, {'line_no': 48, 'char_start': 2130, 'char_end': 2150, 'line': ' return false;\n'}, {'line_no': 49, 'char_start': 2150, 'char_end': 2156, 'line': ' }\n'}, {'line_no': 50, 'char_start': 2156, 'char_end': 2157, 'line': '\n'}]}","{'deleted': [{'char_start': 493, 'char_end': 493, 'chars': ''}, {'char_start': 1856, 'char_end': 1856, 'chars': ''}], 'added': [{'char_start': 442, 'char_end': 526, 'chars': 'if (input_len < sizeof(struct klinux_sockaddr_un)) {\n return false;\n }\n\n '}, {'char_start': 1182, 'char_end': 1265, 'chars': ' if (input_len < sizeof(struct klinux_sockaddr_in)) {\n return false;\n }\n'}, {'char_start': 2071, 'char_end': 2156, 'chars': '\n if (input_len < sizeof(struct klinux_sockaddr_in6)) {\n return false;\n }\n'}]}",github.com/google/asylo/commit/bda9772e7872b0d2b9bee32930cf7a4983837b39,asylo/platform/system_call/type_conversions/manual_types_functions.cc,cwe-787,755 cwe-190,process_get_command,"static inline void process_get_command(conn *c, token_t *tokens, size_t ntokens, bool return_cas) { char *key; size_t nkey; int i = 0; item *it; token_t *key_token = &tokens[KEY_TOKEN]; char *suffix; assert(c != NULL); do { while(key_token->length != 0) { key = key_token->value; nkey = key_token->length; if(nkey > KEY_MAX_LENGTH) { out_string(c, ""CLIENT_ERROR bad command line format""); while (i-- > 0) { item_remove(*(c->ilist + i)); } return; } it = item_get(key, nkey, c, DO_UPDATE); if (settings.detail_enabled) { stats_prefix_record_get(key, nkey, NULL != it); } if (it) { if (i >= c->isize) { item **new_list = realloc(c->ilist, sizeof(item *) * c->isize * 2); if (new_list) { c->isize *= 2; c->ilist = new_list; } else { STATS_LOCK(); stats.malloc_fails++; STATS_UNLOCK(); item_remove(it); break; } } /* * Construct the response. Each hit adds three elements to the * outgoing data list: * ""VALUE "" * key * "" "" + flags + "" "" + data length + ""\r\n"" + data (with \r\n) */ if (return_cas || !settings.inline_ascii_response) { MEMCACHED_COMMAND_GET(c->sfd, ITEM_key(it), it->nkey, it->nbytes, ITEM_get_cas(it)); /* Goofy mid-flight realloc. */ if (i >= c->suffixsize) { char **new_suffix_list = realloc(c->suffixlist, sizeof(char *) * c->suffixsize * 2); if (new_suffix_list) { c->suffixsize *= 2; c->suffixlist = new_suffix_list; } else { STATS_LOCK(); stats.malloc_fails++; STATS_UNLOCK(); item_remove(it); break; } } suffix = do_cache_alloc(c->thread->suffix_cache); if (suffix == NULL) { STATS_LOCK(); stats.malloc_fails++; STATS_UNLOCK(); out_of_memory(c, ""SERVER_ERROR out of memory making CAS suffix""); item_remove(it); while (i-- > 0) { item_remove(*(c->ilist + i)); } return; } *(c->suffixlist + i) = suffix; int suffix_len = make_ascii_get_suffix(suffix, it, return_cas); if (add_iov(c, ""VALUE "", 6) != 0 || add_iov(c, ITEM_key(it), it->nkey) != 0 || (settings.inline_ascii_response && add_iov(c, ITEM_suffix(it), it->nsuffix - 2) != 0) || add_iov(c, suffix, suffix_len) != 0) { item_remove(it); break; } if ((it->it_flags & ITEM_CHUNKED) == 0) { add_iov(c, ITEM_data(it), it->nbytes); } else if (add_chunked_item_iovs(c, it, it->nbytes) != 0) { item_remove(it); break; } } else { MEMCACHED_COMMAND_GET(c->sfd, ITEM_key(it), it->nkey, it->nbytes, ITEM_get_cas(it)); if (add_iov(c, ""VALUE "", 6) != 0 || add_iov(c, ITEM_key(it), it->nkey) != 0) { item_remove(it); break; } if ((it->it_flags & ITEM_CHUNKED) == 0) { if (add_iov(c, ITEM_suffix(it), it->nsuffix + it->nbytes) != 0) { item_remove(it); break; } } else if (add_iov(c, ITEM_suffix(it), it->nsuffix) != 0 || add_chunked_item_iovs(c, it, it->nbytes) != 0) { item_remove(it); break; } } if (settings.verbose > 1) { int ii; fprintf(stderr, "">%d sending key "", c->sfd); for (ii = 0; ii < it->nkey; ++ii) { fprintf(stderr, ""%c"", key[ii]); } fprintf(stderr, ""\n""); } /* item_get() has incremented it->refcount for us */ pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.slab_stats[ITEM_clsid(it)].get_hits++; c->thread->stats.get_cmds++; pthread_mutex_unlock(&c->thread->stats.mutex); *(c->ilist + i) = it; i++; } else { pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.get_misses++; c->thread->stats.get_cmds++; pthread_mutex_unlock(&c->thread->stats.mutex); MEMCACHED_COMMAND_GET(c->sfd, key, nkey, -1, 0); } key_token++; } /* * If the command string hasn't been fully processed, get the next set * of tokens. */ if(key_token->value != NULL) { ntokens = tokenize_command(key_token->value, tokens, MAX_TOKENS); key_token = tokens; } } while(key_token->value != NULL); c->icurr = c->ilist; c->ileft = i; if (return_cas || !settings.inline_ascii_response) { c->suffixcurr = c->suffixlist; c->suffixleft = i; } if (settings.verbose > 1) fprintf(stderr, "">%d END\n"", c->sfd); /* If the loop was terminated because of out-of-memory, it is not reliable to add END\r\n to the buffer, because it might not end in \r\n. So we send SERVER_ERROR instead. */ if (key_token->value != NULL || add_iov(c, ""END\r\n"", 5) != 0 || (IS_UDP(c->transport) && build_udp_headers(c) != 0)) { out_of_memory(c, ""SERVER_ERROR out of memory writing get response""); } else { conn_set_state(c, conn_mwrite); c->msgcurr = 0; } }","static inline void process_get_command(conn *c, token_t *tokens, size_t ntokens, bool return_cas) { char *key; size_t nkey; int i = 0; item *it; token_t *key_token = &tokens[KEY_TOKEN]; char *suffix; assert(c != NULL); do { while(key_token->length != 0) { key = key_token->value; nkey = key_token->length; if(nkey > KEY_MAX_LENGTH) { out_string(c, ""CLIENT_ERROR bad command line format""); while (i-- > 0) { item_remove(*(c->ilist + i)); } return; } it = limited_get(key, nkey, c); if (settings.detail_enabled) { stats_prefix_record_get(key, nkey, NULL != it); } if (it) { if (i >= c->isize) { item **new_list = realloc(c->ilist, sizeof(item *) * c->isize * 2); if (new_list) { c->isize *= 2; c->ilist = new_list; } else { STATS_LOCK(); stats.malloc_fails++; STATS_UNLOCK(); item_remove(it); break; } } /* * Construct the response. Each hit adds three elements to the * outgoing data list: * ""VALUE "" * key * "" "" + flags + "" "" + data length + ""\r\n"" + data (with \r\n) */ if (return_cas || !settings.inline_ascii_response) { MEMCACHED_COMMAND_GET(c->sfd, ITEM_key(it), it->nkey, it->nbytes, ITEM_get_cas(it)); /* Goofy mid-flight realloc. */ if (i >= c->suffixsize) { char **new_suffix_list = realloc(c->suffixlist, sizeof(char *) * c->suffixsize * 2); if (new_suffix_list) { c->suffixsize *= 2; c->suffixlist = new_suffix_list; } else { STATS_LOCK(); stats.malloc_fails++; STATS_UNLOCK(); item_remove(it); break; } } suffix = do_cache_alloc(c->thread->suffix_cache); if (suffix == NULL) { STATS_LOCK(); stats.malloc_fails++; STATS_UNLOCK(); out_of_memory(c, ""SERVER_ERROR out of memory making CAS suffix""); item_remove(it); while (i-- > 0) { item_remove(*(c->ilist + i)); } return; } *(c->suffixlist + i) = suffix; int suffix_len = make_ascii_get_suffix(suffix, it, return_cas); if (add_iov(c, ""VALUE "", 6) != 0 || add_iov(c, ITEM_key(it), it->nkey) != 0 || (settings.inline_ascii_response && add_iov(c, ITEM_suffix(it), it->nsuffix - 2) != 0) || add_iov(c, suffix, suffix_len) != 0) { item_remove(it); break; } if ((it->it_flags & ITEM_CHUNKED) == 0) { add_iov(c, ITEM_data(it), it->nbytes); } else if (add_chunked_item_iovs(c, it, it->nbytes) != 0) { item_remove(it); break; } } else { MEMCACHED_COMMAND_GET(c->sfd, ITEM_key(it), it->nkey, it->nbytes, ITEM_get_cas(it)); if (add_iov(c, ""VALUE "", 6) != 0 || add_iov(c, ITEM_key(it), it->nkey) != 0) { item_remove(it); break; } if ((it->it_flags & ITEM_CHUNKED) == 0) { if (add_iov(c, ITEM_suffix(it), it->nsuffix + it->nbytes) != 0) { item_remove(it); break; } } else if (add_iov(c, ITEM_suffix(it), it->nsuffix) != 0 || add_chunked_item_iovs(c, it, it->nbytes) != 0) { item_remove(it); break; } } if (settings.verbose > 1) { int ii; fprintf(stderr, "">%d sending key "", c->sfd); for (ii = 0; ii < it->nkey; ++ii) { fprintf(stderr, ""%c"", key[ii]); } fprintf(stderr, ""\n""); } /* item_get() has incremented it->refcount for us */ pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.slab_stats[ITEM_clsid(it)].get_hits++; c->thread->stats.get_cmds++; pthread_mutex_unlock(&c->thread->stats.mutex); *(c->ilist + i) = it; i++; } else { pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.get_misses++; c->thread->stats.get_cmds++; pthread_mutex_unlock(&c->thread->stats.mutex); MEMCACHED_COMMAND_GET(c->sfd, key, nkey, -1, 0); } key_token++; } /* * If the command string hasn't been fully processed, get the next set * of tokens. */ if(key_token->value != NULL) { ntokens = tokenize_command(key_token->value, tokens, MAX_TOKENS); key_token = tokens; } } while(key_token->value != NULL); c->icurr = c->ilist; c->ileft = i; if (return_cas || !settings.inline_ascii_response) { c->suffixcurr = c->suffixlist; c->suffixleft = i; } if (settings.verbose > 1) fprintf(stderr, "">%d END\n"", c->sfd); /* If the loop was terminated because of out-of-memory, it is not reliable to add END\r\n to the buffer, because it might not end in \r\n. So we send SERVER_ERROR instead. */ if (key_token->value != NULL || add_iov(c, ""END\r\n"", 5) != 0 || (IS_UDP(c->transport) && build_udp_headers(c) != 0)) { out_of_memory(c, ""SERVER_ERROR out of memory writing get response""); } else { conn_set_state(c, conn_mwrite); c->msgcurr = 0; } }","{'deleted': [{'line_no': 24, 'char_start': 625, 'char_end': 677, 'line': ' it = item_get(key, nkey, c, DO_UPDATE);\n'}], 'added': [{'line_no': 24, 'char_start': 625, 'char_end': 669, 'line': ' it = limited_get(key, nkey, c);\n'}]}","{'deleted': [{'char_start': 645, 'char_end': 646, 'chars': 'm'}, {'char_start': 663, 'char_end': 674, 'chars': ', DO_UPDATE'}], 'added': [{'char_start': 642, 'char_end': 645, 'chars': 'lim'}, {'char_start': 648, 'char_end': 649, 'chars': 'd'}]}",github.com/memcached/memcached/commit/a8c4a82787b8b6c256d61bd5c42fb7f92d1bae00,memcached.c,cwe-190,1494 cwe-089,compare_and_update," @staticmethod def compare_and_update(user, message): """""" This method compare a user object from the bot and his info from the Telegram message to check whether a user has changed his bio or not. If yes, the user object that represents him in the bot will be updated accordingly. Now this function is called only when a user asks the bot for showing the most popular cams :param user: user object that represents a Telegram user in this bot :param message: object from Telegram that contains info about user's message and about himself :return: None """""" log.info('Checking whether user have changed his info or not...') msg = message.from_user usr_from_message = User(message.chat.id, msg.first_name, msg.username, msg.last_name) if user.chat_id != usr_from_message.chat_id: log.error(""Wrong user to compare!"") return if user.first_name != usr_from_message.first_name: user.first_name = usr_from_message.first_name elif user.nickname != usr_from_message.nickname: user.nickname = usr_from_message.nickname elif user.last_name != usr_from_message.last_name: user.last_name = usr_from_message.last_name else: log.debug(""User's info hasn't changed"") return log.info(""User has changed his info"") log.debug(""Updating user's info in the database..."") query = (f""UPDATE users "" f""SET first_name='{user.first_name}', "" f""nickname='{user.nickname}', "" f""last_name='{user.last_name}' "" f""WHERE chat_id={user.chat_id}"") try: db.add(query) except DatabaseError: log.error(""Could not update info about %s in the database"", user) else: log.debug(""User's info has been updated"")"," @staticmethod def compare_and_update(user, message): """""" This method compare a user object from the bot and his info from the Telegram message to check whether a user has changed his bio or not. If yes, the user object that represents him in the bot will be updated accordingly. Now this function is called only when a user asks the bot for showing the most popular cams :param user: user object that represents a Telegram user in this bot :param message: object from Telegram that contains info about user's message and about himself :return: None """""" log.info('Checking whether user have changed his info or not...') msg = message.from_user usr_from_message = User(message.chat.id, msg.first_name, msg.username, msg.last_name) if user.chat_id != usr_from_message.chat_id: log.error(""Wrong user to compare!"") return if user.first_name != usr_from_message.first_name: user.first_name = usr_from_message.first_name elif user.nickname != usr_from_message.nickname: user.nickname = usr_from_message.nickname elif user.last_name != usr_from_message.last_name: user.last_name = usr_from_message.last_name else: log.debug(""User's info hasn't changed"") return log.info(""User has changed his info"") log.debug(""Updating user's info in the database..."") query = (f""UPDATE users "" f""SET first_name=%s, "" f""nickname=%s, "" f""last_name=%s "" f""WHERE chat_id=%s"") parameters = (user.first_name, user.nickname, user.last_name, user.chat_id) try: db.add(query, parameters) except DatabaseError: log.error(""Could not update info about %s in the database"", user) else: log.debug(""User's info has been updated"")","{'deleted': [{'line_no': 41, 'char_start': 1578, 'char_end': 1635, 'line': ' f""SET first_name=\'{user.first_name}\', ""\n'}, {'line_no': 42, 'char_start': 1635, 'char_end': 1684, 'line': ' f""nickname=\'{user.nickname}\', ""\n'}, {'line_no': 43, 'char_start': 1684, 'char_end': 1734, 'line': ' f""last_name=\'{user.last_name}\' ""\n'}, {'line_no': 44, 'char_start': 1734, 'char_end': 1784, 'line': ' f""WHERE chat_id={user.chat_id}"")\n'}, {'line_no': 47, 'char_start': 1798, 'char_end': 1824, 'line': ' db.add(query)\n'}], 'added': [{'line_no': 41, 'char_start': 1578, 'char_end': 1618, 'line': ' f""SET first_name=%s, ""\n'}, {'line_no': 42, 'char_start': 1618, 'char_end': 1652, 'line': ' f""nickname=%s, ""\n'}, {'line_no': 43, 'char_start': 1652, 'char_end': 1686, 'line': ' f""last_name=%s ""\n'}, {'line_no': 44, 'char_start': 1686, 'char_end': 1724, 'line': ' f""WHERE chat_id=%s"")\n'}, {'line_no': 45, 'char_start': 1724, 'char_end': 1725, 'line': '\n'}, {'line_no': 46, 'char_start': 1725, 'char_end': 1795, 'line': ' parameters = (user.first_name, user.nickname, user.last_name,\n'}, {'line_no': 47, 'char_start': 1795, 'char_end': 1831, 'line': ' user.chat_id)\n'}, {'line_no': 50, 'char_start': 1845, 'char_end': 1883, 'line': ' db.add(query, parameters)\n'}]}","{'deleted': [{'char_start': 1612, 'char_end': 1615, 'chars': ""'{u""}, {'char_start': 1616, 'char_end': 1631, 'chars': ""er.first_name}'""}, {'char_start': 1663, 'char_end': 1666, 'chars': ""'{u""}, {'char_start': 1667, 'char_end': 1680, 'chars': ""er.nickname}'""}, {'char_start': 1713, 'char_end': 1722, 'chars': ""'{user.la""}, {'char_start': 1723, 'char_end': 1731, 'chars': ""t_name}'""}, {'char_start': 1767, 'char_end': 1768, 'chars': '{'}, {'char_start': 1780, 'char_end': 1782, 'chars': '}""'}], 'added': [{'char_start': 1612, 'char_end': 1613, 'chars': '%'}, {'char_start': 1646, 'char_end': 1647, 'chars': '%'}, {'char_start': 1681, 'char_end': 1682, 'chars': '%'}, {'char_start': 1719, 'char_end': 1817, 'chars': '%s"")\n\n parameters = (user.first_name, user.nickname, user.last_name,\n '}, {'char_start': 1869, 'char_end': 1881, 'chars': ', parameters'}]}",github.com/RandyRomero/photoGPSbot/commit/0e9f57f13e61863b3672f5730e27f149da00786a,photogpsbot/users.py,cwe-089,401 cwe-125,string_scan_range,"static int string_scan_range(RList *list, RBinFile *bf, int min, const ut64 from, const ut64 to, int type) { ut8 tmp[R_STRING_SCAN_BUFFER_SIZE]; ut64 str_start, needle = from; int count = 0, i, rc, runes; int str_type = R_STRING_TYPE_DETECT; if (type == -1) { type = R_STRING_TYPE_DETECT; } if (from >= to) { eprintf (""Invalid range to find strings 0x%llx .. 0x%llx\n"", from, to); return -1; } ut8 *buf = calloc (to - from, 1); if (!buf || !min) { return -1; } r_buf_read_at (bf->buf, from, buf, to - from); // may oobread while (needle < to) { rc = r_utf8_decode (buf + needle - from, to - needle, NULL); if (!rc) { needle++; continue; } if (type == R_STRING_TYPE_DETECT) { char *w = (char *)buf + needle + rc - from; if ((to - needle) > 5) { bool is_wide32 = needle + rc + 2 < to && !w[0] && !w[1] && !w[2] && w[3] && !w[4]; if (is_wide32) { str_type = R_STRING_TYPE_WIDE32; } else { bool is_wide = needle + rc + 2 < to && !w[0] && w[1] && !w[2]; str_type = is_wide? R_STRING_TYPE_WIDE: R_STRING_TYPE_ASCII; } } else { str_type = R_STRING_TYPE_ASCII; } } else { str_type = type; } runes = 0; str_start = needle; /* Eat a whole C string */ for (rc = i = 0; i < sizeof (tmp) - 3 && needle < to; i += rc) { RRune r = {0}; if (str_type == R_STRING_TYPE_WIDE32) { rc = r_utf32le_decode (buf + needle - from, to - needle, &r); if (rc) { rc = 4; } } else if (str_type == R_STRING_TYPE_WIDE) { rc = r_utf16le_decode (buf + needle - from, to - needle, &r); if (rc == 1) { rc = 2; } } else { rc = r_utf8_decode (buf + needle - from, to - needle, &r); if (rc > 1) { str_type = R_STRING_TYPE_UTF8; } } /* Invalid sequence detected */ if (!rc) { needle++; break; } needle += rc; if (r_isprint (r) && r != '\\') { if (str_type == R_STRING_TYPE_WIDE32) { if (r == 0xff) { r = 0; } } rc = r_utf8_encode (&tmp[i], r); runes++; /* Print the escape code */ } else if (r && r < 0x100 && strchr (""\b\v\f\n\r\t\a\033\\"", (char)r)) { if ((i + 32) < sizeof (tmp) && r < 93) { tmp[i + 0] = '\\'; tmp[i + 1] = "" abtnvfr e "" "" "" "" "" "" \\""[r]; } else { // string too long break; } rc = 2; runes++; } else { /* \0 marks the end of C-strings */ break; } } tmp[i++] = '\0'; if (runes >= min) { if (str_type == R_STRING_TYPE_ASCII) { // reduce false positives int j; for (j = 0; j < i; j++) { char ch = tmp[j]; if (ch != '\n' && ch != '\r' && ch != '\t') { if (!IS_PRINTABLE (tmp[j])) { continue; } } } } RBinString *bs = R_NEW0 (RBinString); if (!bs) { break; } bs->type = str_type; bs->length = runes; bs->size = needle - str_start; bs->ordinal = count++; // TODO: move into adjust_offset switch (str_type) { case R_STRING_TYPE_WIDE: if (str_start -from> 1) { const ut8 *p = buf + str_start - 2 - from; if (p[0] == 0xff && p[1] == 0xfe) { str_start -= 2; // \xff\xfe } } break; case R_STRING_TYPE_WIDE32: if (str_start -from> 3) { const ut8 *p = buf + str_start - 4 - from; if (p[0] == 0xff && p[1] == 0xfe) { str_start -= 4; // \xff\xfe\x00\x00 } } break; } bs->paddr = bs->vaddr = str_start; bs->string = r_str_ndup ((const char *)tmp, i); if (list) { r_list_append (list, bs); } else { print_string (bs, bf); r_bin_string_free (bs); } } } free (buf); return count; }","static int string_scan_range(RList *list, RBinFile *bf, int min, const ut64 from, const ut64 to, int type) { ut8 tmp[R_STRING_SCAN_BUFFER_SIZE]; ut64 str_start, needle = from; int count = 0, i, rc, runes; int str_type = R_STRING_TYPE_DETECT; if (type == -1) { type = R_STRING_TYPE_DETECT; } if (from >= to) { eprintf (""Invalid range to find strings 0x%llx .. 0x%llx\n"", from, to); return -1; } int len = to - from; ut8 *buf = calloc (len, 1); if (!buf || !min) { return -1; } r_buf_read_at (bf->buf, from, buf, len); // may oobread while (needle < to) { rc = r_utf8_decode (buf + needle - from, to - needle, NULL); if (!rc) { needle++; continue; } if (type == R_STRING_TYPE_DETECT) { char *w = (char *)buf + needle + rc - from; if ((to - needle) > 5 + rc) { bool is_wide32 = (needle + rc + 2 < to) && (!w[0] && !w[1] && !w[2] && w[3] && !w[4]); if (is_wide32) { str_type = R_STRING_TYPE_WIDE32; } else { bool is_wide = needle + rc + 2 < to && !w[0] && w[1] && !w[2]; str_type = is_wide? R_STRING_TYPE_WIDE: R_STRING_TYPE_ASCII; } } else { str_type = R_STRING_TYPE_ASCII; } } else { str_type = type; } runes = 0; str_start = needle; /* Eat a whole C string */ for (rc = i = 0; i < sizeof (tmp) - 3 && needle < to; i += rc) { RRune r = {0}; if (str_type == R_STRING_TYPE_WIDE32) { rc = r_utf32le_decode (buf + needle - from, to - needle, &r); if (rc) { rc = 4; } } else if (str_type == R_STRING_TYPE_WIDE) { rc = r_utf16le_decode (buf + needle - from, to - needle, &r); if (rc == 1) { rc = 2; } } else { rc = r_utf8_decode (buf + needle - from, to - needle, &r); if (rc > 1) { str_type = R_STRING_TYPE_UTF8; } } /* Invalid sequence detected */ if (!rc) { needle++; break; } needle += rc; if (r_isprint (r) && r != '\\') { if (str_type == R_STRING_TYPE_WIDE32) { if (r == 0xff) { r = 0; } } rc = r_utf8_encode (&tmp[i], r); runes++; /* Print the escape code */ } else if (r && r < 0x100 && strchr (""\b\v\f\n\r\t\a\033\\"", (char)r)) { if ((i + 32) < sizeof (tmp) && r < 93) { tmp[i + 0] = '\\'; tmp[i + 1] = "" abtnvfr e "" "" "" "" "" "" \\""[r]; } else { // string too long break; } rc = 2; runes++; } else { /* \0 marks the end of C-strings */ break; } } tmp[i++] = '\0'; if (runes >= min) { if (str_type == R_STRING_TYPE_ASCII) { // reduce false positives int j; for (j = 0; j < i; j++) { char ch = tmp[j]; if (ch != '\n' && ch != '\r' && ch != '\t') { if (!IS_PRINTABLE (tmp[j])) { continue; } } } } RBinString *bs = R_NEW0 (RBinString); if (!bs) { break; } bs->type = str_type; bs->length = runes; bs->size = needle - str_start; bs->ordinal = count++; // TODO: move into adjust_offset switch (str_type) { case R_STRING_TYPE_WIDE: if (str_start -from> 1) { const ut8 *p = buf + str_start - 2 - from; if (p[0] == 0xff && p[1] == 0xfe) { str_start -= 2; // \xff\xfe } } break; case R_STRING_TYPE_WIDE32: if (str_start -from> 3) { const ut8 *p = buf + str_start - 4 - from; if (p[0] == 0xff && p[1] == 0xfe) { str_start -= 4; // \xff\xfe\x00\x00 } } break; } bs->paddr = bs->vaddr = str_start; bs->string = r_str_ndup ((const char *)tmp, i); if (list) { r_list_append (list, bs); } else { print_string (bs, bf); r_bin_string_free (bs); } } } free (buf); return count; }","{'deleted': [{'line_no': 15, 'char_start': 418, 'char_end': 453, 'line': '\tut8 *buf = calloc (to - from, 1);\n'}, {'line_no': 19, 'char_start': 490, 'char_end': 538, 'line': '\tr_buf_read_at (bf->buf, from, buf, to - from);\n'}, {'line_no': 29, 'char_start': 768, 'char_end': 796, 'line': '\t\t\tif ((to - needle) > 5) {\n'}, {'line_no': 30, 'char_start': 796, 'char_end': 883, 'line': '\t\t\t\tbool is_wide32 = needle + rc + 2 < to && !w[0] && !w[1] && !w[2] && w[3] && !w[4];\n'}], 'added': [{'line_no': 15, 'char_start': 418, 'char_end': 440, 'line': '\tint len = to - from;\n'}, {'line_no': 16, 'char_start': 440, 'char_end': 469, 'line': '\tut8 *buf = calloc (len, 1);\n'}, {'line_no': 20, 'char_start': 506, 'char_end': 548, 'line': '\tr_buf_read_at (bf->buf, from, buf, len);\n'}, {'line_no': 30, 'char_start': 778, 'char_end': 811, 'line': '\t\t\tif ((to - needle) > 5 + rc) {\n'}, {'line_no': 31, 'char_start': 811, 'char_end': 902, 'line': '\t\t\t\tbool is_wide32 = (needle + rc + 2 < to) && (!w[0] && !w[1] && !w[2] && w[3] && !w[4]);\n'}]}","{'deleted': [{'char_start': 438, 'char_end': 447, 'chars': 'to - from'}, {'char_start': 526, 'char_end': 535, 'chars': 'to - from'}], 'added': [{'char_start': 419, 'char_end': 441, 'chars': 'int len = to - from;\n\t'}, {'char_start': 460, 'char_end': 463, 'chars': 'len'}, {'char_start': 542, 'char_end': 545, 'chars': 'len'}, {'char_start': 802, 'char_end': 807, 'chars': ' + rc'}, {'char_start': 832, 'char_end': 833, 'chars': '('}, {'char_start': 853, 'char_end': 854, 'chars': ')'}, {'char_start': 858, 'char_end': 859, 'chars': '('}, {'char_start': 899, 'char_end': 900, 'chars': ')'}]}",github.com/radare/radare2/commit/3fcf41ed96ffa25b38029449520c8d0a198745f3,libr/bin/file.c,cwe-125,1357 cwe-125,uas_switch_interface,"static int uas_switch_interface(struct usb_device *udev, struct usb_interface *intf) { int alt; alt = uas_find_uas_alt_setting(intf); if (alt < 0) return alt; return usb_set_interface(udev, intf->altsetting[0].desc.bInterfaceNumber, alt); }","static int uas_switch_interface(struct usb_device *udev, struct usb_interface *intf) { struct usb_host_interface *alt; alt = uas_find_uas_alt_setting(intf); if (!alt) return -ENODEV; return usb_set_interface(udev, alt->desc.bInterfaceNumber, alt->desc.bAlternateSetting); }","{'deleted': [{'line_no': 4, 'char_start': 91, 'char_end': 101, 'line': '\tint alt;\n'}, {'line_no': 7, 'char_start': 141, 'char_end': 155, 'line': '\tif (alt < 0)\n'}, {'line_no': 8, 'char_start': 155, 'char_end': 169, 'line': '\t\treturn alt;\n'}, {'line_no': 10, 'char_start': 170, 'char_end': 202, 'line': '\treturn usb_set_interface(udev,\n'}, {'line_no': 11, 'char_start': 202, 'char_end': 254, 'line': '\t\t\tintf->altsetting[0].desc.bInterfaceNumber, alt);\n'}], 'added': [{'line_no': 4, 'char_start': 91, 'char_end': 124, 'line': '\tstruct usb_host_interface *alt;\n'}, {'line_no': 7, 'char_start': 164, 'char_end': 175, 'line': '\tif (!alt)\n'}, {'line_no': 8, 'char_start': 175, 'char_end': 193, 'line': '\t\treturn -ENODEV;\n'}, {'line_no': 10, 'char_start': 194, 'char_end': 254, 'line': '\treturn usb_set_interface(udev, alt->desc.bInterfaceNumber,\n'}, {'line_no': 11, 'char_start': 254, 'char_end': 287, 'line': '\t\t\talt->desc.bAlternateSetting);\n'}]}","{'deleted': [{'char_start': 149, 'char_end': 153, 'chars': ' < 0'}, {'char_start': 164, 'char_end': 167, 'chars': 'alt'}, {'char_start': 201, 'char_end': 211, 'chars': '\n\t\t\tintf->'}, {'char_start': 214, 'char_end': 225, 'chars': 'setting[0].'}, {'char_start': 247, 'char_end': 248, 'chars': ' '}], 'added': [{'char_start': 92, 'char_end': 108, 'chars': 'struct usb_host_'}, {'char_start': 111, 'char_end': 117, 'chars': 'erface'}, {'char_start': 118, 'char_end': 119, 'chars': '*'}, {'char_start': 169, 'char_end': 170, 'chars': '!'}, {'char_start': 184, 'char_end': 191, 'chars': '-ENODEV'}, {'char_start': 225, 'char_end': 228, 'chars': ' al'}, {'char_start': 253, 'char_end': 257, 'chars': '\n\t\t\t'}, {'char_start': 260, 'char_end': 284, 'chars': '->desc.bAlternateSetting'}]}",github.com/torvalds/linux/commit/786de92b3cb26012d3d0f00ee37adf14527f35c4,drivers/usb/storage/uas.c,cwe-125,72 cwe-078,resolve_hostname,"@then(parsers.parse(""the hostname '{hostname}' should be resolved"")) def resolve_hostname(busybox_pod, host, hostname): with host.sudo(): # test dns resolve cmd_nslookup = (""kubectl --kubeconfig=/etc/kubernetes/admin.conf"" "" exec -ti {0} nslookup {1}"".format( pod_name, hostname)) res = host.run(cmd_nslookup) assert res.rc == 0, ""Cannot resolve {}"".format(hostname)","@then(parsers.parse(""the hostname '{hostname}' should be resolved"")) def resolve_hostname(busybox_pod, host, hostname): with host.sudo(): # test dns resolve result = host.run( ""kubectl --kubeconfig=/etc/kubernetes/admin.conf "" ""exec -ti %s nslookup %s"", busybox_pod, hostname, ) assert result.rc == 0, ""Cannot resolve {}"".format(hostname)","{'deleted': [{'line_no': 3, 'char_start': 120, 'char_end': 146, 'line': ' with host.sudo():\n'}, {'line_no': 5, 'char_start': 177, 'char_end': 255, 'line': ' cmd_nslookup = (""kubectl --kubeconfig=/etc/kubernetes/admin.conf""\n'}, {'line_no': 6, 'char_start': 255, 'char_end': 320, 'line': ' "" exec -ti {0} nslookup {1}"".format(\n'}, {'line_no': 7, 'char_start': 320, 'char_end': 362, 'line': ' pod_name,\n'}, {'line_no': 8, 'char_start': 362, 'char_end': 405, 'line': ' hostname))\n'}, {'line_no': 9, 'char_start': 405, 'char_end': 446, 'line': ' res = host.run(cmd_nslookup)\n'}, {'line_no': 10, 'char_start': 446, 'char_end': 514, 'line': ' assert res.rc == 0, ""Cannot resolve {}"".format(hostname)\n'}], 'added': [{'line_no': 3, 'char_start': 120, 'char_end': 142, 'line': ' with host.sudo():\n'}, {'line_no': 5, 'char_start': 169, 'char_end': 196, 'line': ' result = host.run(\n'}, {'line_no': 6, 'char_start': 196, 'char_end': 259, 'line': ' ""kubectl --kubeconfig=/etc/kubernetes/admin.conf ""\n'}, {'line_no': 7, 'char_start': 259, 'char_end': 298, 'line': ' ""exec -ti %s nslookup %s"",\n'}, {'line_no': 8, 'char_start': 298, 'char_end': 323, 'line': ' busybox_pod,\n'}, {'line_no': 9, 'char_start': 323, 'char_end': 345, 'line': ' hostname,\n'}, {'line_no': 10, 'char_start': 345, 'char_end': 355, 'line': ' )\n'}, {'line_no': 11, 'char_start': 355, 'char_end': 356, 'line': '\n'}, {'line_no': 12, 'char_start': 356, 'char_end': 423, 'line': ' assert result.rc == 0, ""Cannot resolve {}"".format(hostname)'}]}","{'deleted': [{'char_start': 124, 'char_end': 128, 'chars': ' '}, {'char_start': 146, 'char_end': 150, 'chars': ' '}, {'char_start': 189, 'char_end': 201, 'chars': 'cmd_nslookup'}, {'char_start': 202, 'char_end': 203, 'chars': '='}, {'char_start': 204, 'char_end': 205, 'chars': '('}, {'char_start': 255, 'char_end': 265, 'chars': ' '}, {'char_start': 277, 'char_end': 283, 'chars': ' '}, {'char_start': 284, 'char_end': 285, 'chars': ' '}, {'char_start': 294, 'char_end': 297, 'chars': '{0}'}, {'char_start': 307, 'char_end': 310, 'chars': '{1}'}, {'char_start': 311, 'char_end': 319, 'chars': '.format('}, {'char_start': 332, 'char_end': 352, 'chars': ' '}, {'char_start': 355, 'char_end': 360, 'chars': '_name'}, {'char_start': 374, 'char_end': 394, 'chars': ' '}, {'char_start': 402, 'char_end': 404, 'chars': '))'}, {'char_start': 405, 'char_end': 406, 'chars': ' '}, {'char_start': 414, 'char_end': 444, 'chars': ' res = host.run(cmd_nslookup'}, {'char_start': 446, 'char_end': 450, 'chars': ' '}], 'added': [{'char_start': 177, 'char_end': 179, 'chars': 're'}, {'char_start': 180, 'char_end': 181, 'chars': 'u'}, {'char_start': 182, 'char_end': 187, 'chars': 't = h'}, {'char_start': 188, 'char_end': 192, 'chars': 'st.r'}, {'char_start': 193, 'char_end': 206, 'chars': 'n(\n '}, {'char_start': 256, 'char_end': 257, 'chars': ' '}, {'char_start': 281, 'char_end': 283, 'chars': '%s'}, {'char_start': 293, 'char_end': 295, 'chars': '%s'}, {'char_start': 296, 'char_end': 297, 'chars': ','}, {'char_start': 310, 'char_end': 318, 'chars': 'busybox_'}, {'char_start': 343, 'char_end': 344, 'chars': ','}, {'char_start': 355, 'char_end': 356, 'chars': '\n'}, {'char_start': 374, 'char_end': 377, 'chars': 'ult'}]}",github.com/scality/metalk8s/commit/82d92836d4ff78c623a0e06302c94cfa5ff79908,tests/post/steps/test_dns.py,cwe-078,101 cwe-089,delete_data," def delete_data(self, session, id): self._openContainer(session) sid = str(id) if (self.idNormalizer is not None): sid = self.idNormalizer.process_string(session, str(id)) query = ""DELETE FROM %s WHERE identifier = '%s';"" % (self.table, sid) self._query(query) return None"," def delete_data(self, session, id): self._openContainer(session) sid = str(id) if (self.idNormalizer is not None): sid = self.idNormalizer.process_string(session, str(id)) query = ""DELETE FROM %s WHERE identifier = $1;"" % (self.table) self._query(query, sid) return None","{'deleted': [{'line_no': 6, 'char_start': 212, 'char_end': 290, 'line': ' query = ""DELETE FROM %s WHERE identifier = \'%s\';"" % (self.table, sid)\n'}, {'line_no': 7, 'char_start': 290, 'char_end': 317, 'line': ' self._query(query)\n'}], 'added': [{'line_no': 6, 'char_start': 212, 'char_end': 283, 'line': ' query = ""DELETE FROM %s WHERE identifier = $1;"" % (self.table)\n'}, {'line_no': 7, 'char_start': 283, 'char_end': 315, 'line': ' self._query(query, sid)\n'}]}","{'deleted': [{'char_start': 263, 'char_end': 267, 'chars': ""'%s'""}, {'char_start': 283, 'char_end': 288, 'chars': ', sid'}], 'added': [{'char_start': 263, 'char_end': 265, 'chars': '$1'}, {'char_start': 308, 'char_end': 313, 'chars': ', sid'}]}",github.com/cheshire3/cheshire3/commit/d350363b4ea10f102c24c8f26d7b76b006323e8e,cheshire3/sql/postgresStore.py,cwe-089,79 cwe-476,dex_parse_debug_item,"static void dex_parse_debug_item(RBinFile *binfile, RBinDexObj *bin, RBinDexClass *c, int MI, int MA, int paddr, int ins_size, int insns_size, char *class_name, int regsz, int debug_info_off) { struct r_bin_t *rbin = binfile->rbin; const ut8 *p4 = r_buf_get_at (binfile->buf, debug_info_off, NULL); const ut8 *p4_end = p4 + binfile->buf->length - debug_info_off; ut64 line_start; ut64 parameters_size; ut64 param_type_idx; ut16 argReg = regsz - ins_size; ut64 source_file_idx = c->source_file; RList *params, *debug_positions, *emitted_debug_locals = NULL; bool keep = true; if (argReg > regsz) { return; // this return breaks tests } p4 = r_uleb128 (p4, p4_end - p4, &line_start); p4 = r_uleb128 (p4, p4_end - p4, ¶meters_size); // TODO: check when we should use source_file // The state machine consists of five registers ut32 address = 0; ut32 line = line_start; if (!(debug_positions = r_list_newf ((RListFree)free))) { return; } if (!(emitted_debug_locals = r_list_newf ((RListFree)free))) { r_list_free (debug_positions); return; } struct dex_debug_local_t debug_locals[regsz]; memset (debug_locals, 0, sizeof (struct dex_debug_local_t) * regsz); if (!(MA & 0x0008)) { debug_locals[argReg].name = ""this""; debug_locals[argReg].descriptor = r_str_newf(""%s;"", class_name); debug_locals[argReg].startAddress = 0; debug_locals[argReg].signature = NULL; debug_locals[argReg].live = true; argReg++; } if (!(params = dex_method_signature2 (bin, MI))) { r_list_free (debug_positions); r_list_free (emitted_debug_locals); return; } RListIter *iter = r_list_iterator (params); char *name; char *type; int reg; r_list_foreach (params, iter, type) { if ((argReg >= regsz) || !type || parameters_size <= 0) { r_list_free (debug_positions); r_list_free (params); r_list_free (emitted_debug_locals); return; } p4 = r_uleb128 (p4, p4_end - p4, ¶m_type_idx); // read uleb128p1 param_type_idx -= 1; name = getstr (bin, param_type_idx); reg = argReg; switch (type[0]) { case 'D': case 'J': argReg += 2; break; default: argReg += 1; break; } if (name) { debug_locals[reg].name = name; debug_locals[reg].descriptor = type; debug_locals[reg].signature = NULL; debug_locals[reg].startAddress = address; debug_locals[reg].live = true; } --parameters_size; } ut8 opcode = *(p4++) & 0xff; while (keep) { switch (opcode) { case 0x0: // DBG_END_SEQUENCE keep = false; break; case 0x1: // DBG_ADVANCE_PC { ut64 addr_diff; p4 = r_uleb128 (p4, p4_end - p4, &addr_diff); address += addr_diff; } break; case 0x2: // DBG_ADVANCE_LINE { st64 line_diff = r_sleb128 (&p4, p4_end); line += line_diff; } break; case 0x3: // DBG_START_LOCAL { ut64 register_num; ut64 name_idx; ut64 type_idx; p4 = r_uleb128 (p4, p4_end - p4, ®ister_num); p4 = r_uleb128 (p4, p4_end - p4, &name_idx); name_idx -= 1; p4 = r_uleb128 (p4, p4_end - p4, &type_idx); type_idx -= 1; if (register_num >= regsz) { r_list_free (debug_positions); r_list_free (params); return; } // Emit what was previously there, if anything // emitLocalCbIfLive if (debug_locals[register_num].live) { struct dex_debug_local_t *local = malloc ( sizeof (struct dex_debug_local_t)); if (!local) { keep = false; break; } local->name = debug_locals[register_num].name; local->descriptor = debug_locals[register_num].descriptor; local->startAddress = debug_locals[register_num].startAddress; local->signature = debug_locals[register_num].signature; local->live = true; local->reg = register_num; local->endAddress = address; r_list_append (emitted_debug_locals, local); } debug_locals[register_num].name = getstr (bin, name_idx); debug_locals[register_num].descriptor = dex_type_descriptor (bin, type_idx); debug_locals[register_num].startAddress = address; debug_locals[register_num].signature = NULL; debug_locals[register_num].live = true; //eprintf(""DBG_START_LOCAL %x %x %x\n"", register_num, name_idx, type_idx); } break; case 0x4: //DBG_START_LOCAL_EXTENDED { ut64 register_num; ut64 name_idx; ut64 type_idx; ut64 sig_idx; p4 = r_uleb128 (p4, p4_end - p4, ®ister_num); p4 = r_uleb128 (p4, p4_end - p4, &name_idx); name_idx -= 1; p4 = r_uleb128 (p4, p4_end - p4, &type_idx); type_idx -= 1; p4 = r_uleb128 (p4, p4_end - p4, &sig_idx); sig_idx -= 1; if (register_num >= regsz) { r_list_free (debug_positions); r_list_free (params); return; } // Emit what was previously there, if anything // emitLocalCbIfLive if (debug_locals[register_num].live) { struct dex_debug_local_t *local = malloc ( sizeof (struct dex_debug_local_t)); if (!local) { keep = false; break; } local->name = debug_locals[register_num].name; local->descriptor = debug_locals[register_num].descriptor; local->startAddress = debug_locals[register_num].startAddress; local->signature = debug_locals[register_num].signature; local->live = true; local->reg = register_num; local->endAddress = address; r_list_append (emitted_debug_locals, local); } debug_locals[register_num].name = getstr (bin, name_idx); debug_locals[register_num].descriptor = dex_type_descriptor (bin, type_idx); debug_locals[register_num].startAddress = address; debug_locals[register_num].signature = getstr (bin, sig_idx); debug_locals[register_num].live = true; } break; case 0x5: // DBG_END_LOCAL { ut64 register_num; p4 = r_uleb128 (p4, p4_end - p4, ®ister_num); // emitLocalCbIfLive if (debug_locals[register_num].live) { struct dex_debug_local_t *local = malloc ( sizeof (struct dex_debug_local_t)); if (!local) { keep = false; break; } local->name = debug_locals[register_num].name; local->descriptor = debug_locals[register_num].descriptor; local->startAddress = debug_locals[register_num].startAddress; local->signature = debug_locals[register_num].signature; local->live = true; local->reg = register_num; local->endAddress = address; r_list_append (emitted_debug_locals, local); } debug_locals[register_num].live = false; } break; case 0x6: // DBG_RESTART_LOCAL { ut64 register_num; p4 = r_uleb128 (p4, p4_end - p4, ®ister_num); if (!debug_locals[register_num].live) { debug_locals[register_num].startAddress = address; debug_locals[register_num].live = true; } } break; case 0x7: //DBG_SET_PROLOGUE_END break; case 0x8: //DBG_SET_PROLOGUE_BEGIN break; case 0x9: { p4 = r_uleb128 (p4, p4_end - p4, &source_file_idx); source_file_idx--; } break; default: { int adjusted_opcode = opcode - 0x0a; address += (adjusted_opcode / 15); line += -4 + (adjusted_opcode % 15); struct dex_debug_position_t *position = malloc (sizeof (struct dex_debug_position_t)); if (!position) { keep = false; break; } position->source_file_idx = source_file_idx; position->address = address; position->line = line; r_list_append (debug_positions, position); } break; } opcode = *(p4++) & 0xff; } if (!binfile->sdb_addrinfo) { binfile->sdb_addrinfo = sdb_new0 (); } char *fileline; char offset[64]; char *offset_ptr; RListIter *iter1; struct dex_debug_position_t *pos; r_list_foreach (debug_positions, iter1, pos) { fileline = r_str_newf (""%s|%""PFMT64d, getstr (bin, pos->source_file_idx), pos->line); offset_ptr = sdb_itoa (pos->address + paddr, offset, 16); sdb_set (binfile->sdb_addrinfo, offset_ptr, fileline, 0); sdb_set (binfile->sdb_addrinfo, fileline, offset_ptr, 0); } if (!dexdump) { r_list_free (debug_positions); r_list_free (emitted_debug_locals); r_list_free (params); return; } RListIter *iter2; struct dex_debug_position_t *position; rbin->cb_printf ("" positions :\n""); r_list_foreach (debug_positions, iter2, position) { rbin->cb_printf ("" 0x%04llx line=%llu\n"", position->address, position->line); } rbin->cb_printf ("" locals :\n""); RListIter *iter3; struct dex_debug_local_t *local; r_list_foreach (emitted_debug_locals, iter3, local) { if (local->signature) { rbin->cb_printf ( "" 0x%04x - 0x%04x reg=%d %s %s %s\n"", local->startAddress, local->endAddress, local->reg, local->name, local->descriptor, local->signature); } else { rbin->cb_printf ( "" 0x%04x - 0x%04x reg=%d %s %s\n"", local->startAddress, local->endAddress, local->reg, local->name, local->descriptor); } } for (reg = 0; reg < regsz; reg++) { if (debug_locals[reg].live) { if (debug_locals[reg].signature) { rbin->cb_printf ( "" 0x%04x - 0x%04x reg=%d %s %s "" ""%s\n"", debug_locals[reg].startAddress, insns_size, reg, debug_locals[reg].name, debug_locals[reg].descriptor, debug_locals[reg].signature); } else { rbin->cb_printf ( "" 0x%04x - 0x%04x reg=%d %s %s"" ""\n"", debug_locals[reg].startAddress, insns_size, reg, debug_locals[reg].name, debug_locals[reg].descriptor); } } } r_list_free (debug_positions); r_list_free (emitted_debug_locals); r_list_free (params); }","static void dex_parse_debug_item(RBinFile *binfile, RBinDexObj *bin, RBinDexClass *c, int MI, int MA, int paddr, int ins_size, int insns_size, char *class_name, int regsz, int debug_info_off) { struct r_bin_t *rbin = binfile->rbin; const ut8 *p4 = r_buf_get_at (binfile->buf, debug_info_off, NULL); const ut8 *p4_end = p4 + binfile->buf->length - debug_info_off; ut64 line_start; ut64 parameters_size; ut64 param_type_idx; ut16 argReg = regsz - ins_size; ut64 source_file_idx = c->source_file; RList *params, *debug_positions, *emitted_debug_locals = NULL; bool keep = true; if (argReg > regsz) { return; // this return breaks tests } p4 = r_uleb128 (p4, p4_end - p4, &line_start); p4 = r_uleb128 (p4, p4_end - p4, ¶meters_size); // TODO: check when we should use source_file // The state machine consists of five registers ut32 address = 0; ut32 line = line_start; if (!(debug_positions = r_list_newf ((RListFree)free))) { return; } if (!(emitted_debug_locals = r_list_newf ((RListFree)free))) { r_list_free (debug_positions); return; } struct dex_debug_local_t debug_locals[regsz]; memset (debug_locals, 0, sizeof (struct dex_debug_local_t) * regsz); if (!(MA & 0x0008)) { debug_locals[argReg].name = ""this""; debug_locals[argReg].descriptor = r_str_newf(""%s;"", class_name); debug_locals[argReg].startAddress = 0; debug_locals[argReg].signature = NULL; debug_locals[argReg].live = true; argReg++; } if (!(params = dex_method_signature2 (bin, MI))) { r_list_free (debug_positions); r_list_free (emitted_debug_locals); return; } RListIter *iter = r_list_iterator (params); char *name; char *type; int reg; r_list_foreach (params, iter, type) { if ((argReg >= regsz) || !type || parameters_size <= 0) { r_list_free (debug_positions); r_list_free (params); r_list_free (emitted_debug_locals); return; } p4 = r_uleb128 (p4, p4_end - p4, ¶m_type_idx); // read uleb128p1 param_type_idx -= 1; name = getstr (bin, param_type_idx); reg = argReg; switch (type[0]) { case 'D': case 'J': argReg += 2; break; default: argReg += 1; break; } if (name) { debug_locals[reg].name = name; debug_locals[reg].descriptor = type; debug_locals[reg].signature = NULL; debug_locals[reg].startAddress = address; debug_locals[reg].live = true; } --parameters_size; } if (p4 <= 0) { return; } ut8 opcode = *(p4++) & 0xff; while (keep) { switch (opcode) { case 0x0: // DBG_END_SEQUENCE keep = false; break; case 0x1: // DBG_ADVANCE_PC { ut64 addr_diff; p4 = r_uleb128 (p4, p4_end - p4, &addr_diff); address += addr_diff; } break; case 0x2: // DBG_ADVANCE_LINE { st64 line_diff = r_sleb128 (&p4, p4_end); line += line_diff; } break; case 0x3: // DBG_START_LOCAL { ut64 register_num; ut64 name_idx; ut64 type_idx; p4 = r_uleb128 (p4, p4_end - p4, ®ister_num); p4 = r_uleb128 (p4, p4_end - p4, &name_idx); name_idx -= 1; p4 = r_uleb128 (p4, p4_end - p4, &type_idx); type_idx -= 1; if (register_num >= regsz) { r_list_free (debug_positions); r_list_free (params); return; } // Emit what was previously there, if anything // emitLocalCbIfLive if (debug_locals[register_num].live) { struct dex_debug_local_t *local = malloc ( sizeof (struct dex_debug_local_t)); if (!local) { keep = false; break; } local->name = debug_locals[register_num].name; local->descriptor = debug_locals[register_num].descriptor; local->startAddress = debug_locals[register_num].startAddress; local->signature = debug_locals[register_num].signature; local->live = true; local->reg = register_num; local->endAddress = address; r_list_append (emitted_debug_locals, local); } debug_locals[register_num].name = getstr (bin, name_idx); debug_locals[register_num].descriptor = dex_type_descriptor (bin, type_idx); debug_locals[register_num].startAddress = address; debug_locals[register_num].signature = NULL; debug_locals[register_num].live = true; //eprintf(""DBG_START_LOCAL %x %x %x\n"", register_num, name_idx, type_idx); } break; case 0x4: //DBG_START_LOCAL_EXTENDED { ut64 register_num; ut64 name_idx; ut64 type_idx; ut64 sig_idx; p4 = r_uleb128 (p4, p4_end - p4, ®ister_num); p4 = r_uleb128 (p4, p4_end - p4, &name_idx); name_idx -= 1; p4 = r_uleb128 (p4, p4_end - p4, &type_idx); type_idx -= 1; p4 = r_uleb128 (p4, p4_end - p4, &sig_idx); sig_idx -= 1; if (register_num >= regsz) { r_list_free (debug_positions); r_list_free (params); return; } // Emit what was previously there, if anything // emitLocalCbIfLive if (debug_locals[register_num].live) { struct dex_debug_local_t *local = malloc ( sizeof (struct dex_debug_local_t)); if (!local) { keep = false; break; } local->name = debug_locals[register_num].name; local->descriptor = debug_locals[register_num].descriptor; local->startAddress = debug_locals[register_num].startAddress; local->signature = debug_locals[register_num].signature; local->live = true; local->reg = register_num; local->endAddress = address; r_list_append (emitted_debug_locals, local); } debug_locals[register_num].name = getstr (bin, name_idx); debug_locals[register_num].descriptor = dex_type_descriptor (bin, type_idx); debug_locals[register_num].startAddress = address; debug_locals[register_num].signature = getstr (bin, sig_idx); debug_locals[register_num].live = true; } break; case 0x5: // DBG_END_LOCAL { ut64 register_num; p4 = r_uleb128 (p4, p4_end - p4, ®ister_num); // emitLocalCbIfLive if (debug_locals[register_num].live) { struct dex_debug_local_t *local = malloc ( sizeof (struct dex_debug_local_t)); if (!local) { keep = false; break; } local->name = debug_locals[register_num].name; local->descriptor = debug_locals[register_num].descriptor; local->startAddress = debug_locals[register_num].startAddress; local->signature = debug_locals[register_num].signature; local->live = true; local->reg = register_num; local->endAddress = address; r_list_append (emitted_debug_locals, local); } debug_locals[register_num].live = false; } break; case 0x6: // DBG_RESTART_LOCAL { ut64 register_num; p4 = r_uleb128 (p4, p4_end - p4, ®ister_num); if (!debug_locals[register_num].live) { debug_locals[register_num].startAddress = address; debug_locals[register_num].live = true; } } break; case 0x7: //DBG_SET_PROLOGUE_END break; case 0x8: //DBG_SET_PROLOGUE_BEGIN break; case 0x9: { p4 = r_uleb128 (p4, p4_end - p4, &source_file_idx); source_file_idx--; } break; default: { int adjusted_opcode = opcode - 0x0a; address += (adjusted_opcode / 15); line += -4 + (adjusted_opcode % 15); struct dex_debug_position_t *position = malloc (sizeof (struct dex_debug_position_t)); if (!position) { keep = false; break; } position->source_file_idx = source_file_idx; position->address = address; position->line = line; r_list_append (debug_positions, position); } break; } opcode = *(p4++) & 0xff; } if (!binfile->sdb_addrinfo) { binfile->sdb_addrinfo = sdb_new0 (); } char *fileline; char offset[64]; char *offset_ptr; RListIter *iter1; struct dex_debug_position_t *pos; r_list_foreach (debug_positions, iter1, pos) { fileline = r_str_newf (""%s|%""PFMT64d, getstr (bin, pos->source_file_idx), pos->line); offset_ptr = sdb_itoa (pos->address + paddr, offset, 16); sdb_set (binfile->sdb_addrinfo, offset_ptr, fileline, 0); sdb_set (binfile->sdb_addrinfo, fileline, offset_ptr, 0); } if (!dexdump) { r_list_free (debug_positions); r_list_free (emitted_debug_locals); r_list_free (params); return; } RListIter *iter2; struct dex_debug_position_t *position; rbin->cb_printf ("" positions :\n""); r_list_foreach (debug_positions, iter2, position) { rbin->cb_printf ("" 0x%04llx line=%llu\n"", position->address, position->line); } rbin->cb_printf ("" locals :\n""); RListIter *iter3; struct dex_debug_local_t *local; r_list_foreach (emitted_debug_locals, iter3, local) { if (local->signature) { rbin->cb_printf ( "" 0x%04x - 0x%04x reg=%d %s %s %s\n"", local->startAddress, local->endAddress, local->reg, local->name, local->descriptor, local->signature); } else { rbin->cb_printf ( "" 0x%04x - 0x%04x reg=%d %s %s\n"", local->startAddress, local->endAddress, local->reg, local->name, local->descriptor); } } for (reg = 0; reg < regsz; reg++) { if (debug_locals[reg].live) { if (debug_locals[reg].signature) { rbin->cb_printf ( "" 0x%04x - 0x%04x reg=%d %s %s "" ""%s\n"", debug_locals[reg].startAddress, insns_size, reg, debug_locals[reg].name, debug_locals[reg].descriptor, debug_locals[reg].signature); } else { rbin->cb_printf ( "" 0x%04x - 0x%04x reg=%d %s %s"" ""\n"", debug_locals[reg].startAddress, insns_size, reg, debug_locals[reg].name, debug_locals[reg].descriptor); } } } r_list_free (debug_positions); r_list_free (emitted_debug_locals); r_list_free (params); }","{'deleted': [], 'added': [{'line_no': 83, 'char_start': 2398, 'char_end': 2414, 'line': '\tif (p4 <= 0) {\n'}, {'line_no': 84, 'char_start': 2414, 'char_end': 2424, 'line': '\t\treturn;\n'}, {'line_no': 85, 'char_start': 2424, 'char_end': 2427, 'line': '\t}\n'}]}","{'deleted': [], 'added': [{'char_start': 2399, 'char_end': 2428, 'chars': 'if (p4 <= 0) {\n\t\treturn;\n\t}\n\t'}]}",github.com/radare/radare2/commit/252afb1cff9676f3ae1f341a28448bf2c8b6e308,libr/bin/p/bin_dex.c,cwe-476,3035 cwe-089,update_title," def update_title(self, title = None): if (not self.title): self.title = title # This will fall to a sql injection sql = ""UPDATE jdk_entries SET title = '"" + self.title + ""'"" + \ ""WHERE jdk_entries.id = '"" + self.entry_id + ""';"" db_execute(sql) self.update_date_modified() return None"," def update_title(self, title = None): if (not self.title): self.title = title quote_tuple = self.title, self.entry_id # This will fall to a sql injection sql = ""UPDATE jdk_entries SET title = ?"" + \ ""WHERE jdk_entries.id = ?;"" db_execute(sql, quote_tuple) self.update_date_modified() return None","{'deleted': [{'line_no': 6, 'char_start': 132, 'char_end': 200, 'line': ' sql = ""UPDATE jdk_entries SET title = \'"" + self.title + ""\'"" + \\\n'}, {'line_no': 7, 'char_start': 200, 'char_end': 261, 'line': ' ""WHERE jdk_entries.id = \'"" + self.entry_id + ""\';"" \n'}, {'line_no': 9, 'char_start': 262, 'char_end': 282, 'line': ' db_execute(sql)\n'}], 'added': [{'line_no': 5, 'char_start': 91, 'char_end': 135, 'line': ' quote_tuple = self.title, self.entry_id\n'}, {'line_no': 6, 'char_start': 135, 'char_end': 136, 'line': '\n'}, {'line_no': 8, 'char_start': 177, 'char_end': 226, 'line': ' sql = ""UPDATE jdk_entries SET title = ?"" + \\\n'}, {'line_no': 9, 'char_start': 226, 'char_end': 265, 'line': ' ""WHERE jdk_entries.id = ?;"" \n'}, {'line_no': 11, 'char_start': 266, 'char_end': 299, 'line': ' db_execute(sql, quote_tuple)\n'}]}","{'deleted': [{'char_start': 174, 'char_end': 194, 'chars': '\'"" + self.title + ""\''}, {'char_start': 234, 'char_end': 257, 'chars': '\'"" + self.entry_id + ""\''}], 'added': [{'char_start': 95, 'char_end': 140, 'chars': 'quote_tuple = self.title, self.entry_id\n\n '}, {'char_start': 219, 'char_end': 220, 'chars': '?'}, {'char_start': 260, 'char_end': 261, 'chars': '?'}, {'char_start': 284, 'char_end': 297, 'chars': ', quote_tuple'}]}",github.com/peterlebrun/jdk/commit/000238566fbe55ba09676c3d57af04ae207235ae,entry.py,cwe-089,85 cwe-089,user_verify," def user_verify(self): eid = self.email code = self.password if eid.strip() == '': return if code.strip() == '': return query = '''select * from usr where email like\''''+eid+'\'' cursor = g.conn.execute(query) for row in cursor: key = str(row.password) if key.strip() == code.strip(): self.name = str(row.name) self.email = eid self.id = eid self.valid = True break"," def user_verify(self): eid = self.email code = self.password if eid.strip() == '': return if code.strip() == '': return query = 'select * from usr where email like %s' cursor = g.conn.execute(query, (eid, )) for row in cursor: key = str(row.password) if key.strip() == code.strip(): self.name = str(row.name) self.email = eid self.id = eid self.valid = True break","{'deleted': [{'line_no': 8, 'char_start': 180, 'char_end': 248, 'line': "" query = '''select * from usr where email like\\''''+eid+'\\''\n""}, {'line_no': 9, 'char_start': 248, 'char_end': 287, 'line': ' cursor = g.conn.execute(query)\n'}], 'added': [{'line_no': 8, 'char_start': 180, 'char_end': 236, 'line': "" query = 'select * from usr where email like %s'\n""}, {'line_no': 9, 'char_start': 236, 'char_end': 284, 'line': ' cursor = g.conn.execute(query, (eid, ))\n'}]}","{'deleted': [{'char_start': 197, 'char_end': 199, 'chars': ""''""}, {'char_start': 233, 'char_end': 246, 'chars': ""\\''''+eid+'\\'""}], 'added': [{'char_start': 231, 'char_end': 234, 'chars': ' %s'}, {'char_start': 273, 'char_end': 282, 'chars': ', (eid, )'}]}",github.com/Daniel-Bu/w4111-project1/commit/fe04bedc72e62fd4c4ee046a9af29fd81e9b3340,Web-app/User.py,cwe-089,115 cwe-416,usb_console_setup,"static int usb_console_setup(struct console *co, char *options) { struct usbcons_info *info = &usbcons_info; int baud = 9600; int bits = 8; int parity = 'n'; int doflow = 0; int cflag = CREAD | HUPCL | CLOCAL; char *s; struct usb_serial *serial; struct usb_serial_port *port; int retval; struct tty_struct *tty = NULL; struct ktermios dummy; if (options) { baud = simple_strtoul(options, NULL, 10); s = options; while (*s >= '0' && *s <= '9') s++; if (*s) parity = *s++; if (*s) bits = *s++ - '0'; if (*s) doflow = (*s++ == 'r'); } /* Sane default */ if (baud == 0) baud = 9600; switch (bits) { case 7: cflag |= CS7; break; default: case 8: cflag |= CS8; break; } switch (parity) { case 'o': case 'O': cflag |= PARODD; break; case 'e': case 'E': cflag |= PARENB; break; } co->cflag = cflag; /* * no need to check the index here: if the index is wrong, console * code won't call us */ port = usb_serial_port_get_by_minor(co->index); if (port == NULL) { /* no device is connected yet, sorry :( */ pr_err(""No USB device connected to ttyUSB%i\n"", co->index); return -ENODEV; } serial = port->serial; retval = usb_autopm_get_interface(serial->interface); if (retval) goto error_get_interface; tty_port_tty_set(&port->port, NULL); info->port = port; ++port->port.count; if (!tty_port_initialized(&port->port)) { if (serial->type->set_termios) { /* * allocate a fake tty so the driver can initialize * the termios structure, then later call set_termios to * configure according to command line arguments */ tty = kzalloc(sizeof(*tty), GFP_KERNEL); if (!tty) { retval = -ENOMEM; goto reset_open_count; } kref_init(&tty->kref); tty->driver = usb_serial_tty_driver; tty->index = co->index; init_ldsem(&tty->ldisc_sem); spin_lock_init(&tty->files_lock); INIT_LIST_HEAD(&tty->tty_files); kref_get(&tty->driver->kref); __module_get(tty->driver->owner); tty->ops = &usb_console_fake_tty_ops; tty_init_termios(tty); tty_port_tty_set(&port->port, tty); } /* only call the device specific open if this * is the first time the port is opened */ retval = serial->type->open(NULL, port); if (retval) { dev_err(&port->dev, ""could not open USB console port\n""); goto fail; } if (serial->type->set_termios) { tty->termios.c_cflag = cflag; tty_termios_encode_baud_rate(&tty->termios, baud, baud); memset(&dummy, 0, sizeof(struct ktermios)); serial->type->set_termios(tty, port, &dummy); tty_port_tty_set(&port->port, NULL); tty_kref_put(tty); } tty_port_set_initialized(&port->port, 1); } /* Now that any required fake tty operations are completed restore * the tty port count */ --port->port.count; /* The console is special in terms of closing the device so * indicate this port is now acting as a system console. */ port->port.console = 1; mutex_unlock(&serial->disc_mutex); return retval; fail: tty_port_tty_set(&port->port, NULL); tty_kref_put(tty); reset_open_count: port->port.count = 0; usb_autopm_put_interface(serial->interface); error_get_interface: usb_serial_put(serial); mutex_unlock(&serial->disc_mutex); return retval; }","static int usb_console_setup(struct console *co, char *options) { struct usbcons_info *info = &usbcons_info; int baud = 9600; int bits = 8; int parity = 'n'; int doflow = 0; int cflag = CREAD | HUPCL | CLOCAL; char *s; struct usb_serial *serial; struct usb_serial_port *port; int retval; struct tty_struct *tty = NULL; struct ktermios dummy; if (options) { baud = simple_strtoul(options, NULL, 10); s = options; while (*s >= '0' && *s <= '9') s++; if (*s) parity = *s++; if (*s) bits = *s++ - '0'; if (*s) doflow = (*s++ == 'r'); } /* Sane default */ if (baud == 0) baud = 9600; switch (bits) { case 7: cflag |= CS7; break; default: case 8: cflag |= CS8; break; } switch (parity) { case 'o': case 'O': cflag |= PARODD; break; case 'e': case 'E': cflag |= PARENB; break; } co->cflag = cflag; /* * no need to check the index here: if the index is wrong, console * code won't call us */ port = usb_serial_port_get_by_minor(co->index); if (port == NULL) { /* no device is connected yet, sorry :( */ pr_err(""No USB device connected to ttyUSB%i\n"", co->index); return -ENODEV; } serial = port->serial; retval = usb_autopm_get_interface(serial->interface); if (retval) goto error_get_interface; tty_port_tty_set(&port->port, NULL); info->port = port; ++port->port.count; if (!tty_port_initialized(&port->port)) { if (serial->type->set_termios) { /* * allocate a fake tty so the driver can initialize * the termios structure, then later call set_termios to * configure according to command line arguments */ tty = kzalloc(sizeof(*tty), GFP_KERNEL); if (!tty) { retval = -ENOMEM; goto reset_open_count; } kref_init(&tty->kref); tty->driver = usb_serial_tty_driver; tty->index = co->index; init_ldsem(&tty->ldisc_sem); spin_lock_init(&tty->files_lock); INIT_LIST_HEAD(&tty->tty_files); kref_get(&tty->driver->kref); __module_get(tty->driver->owner); tty->ops = &usb_console_fake_tty_ops; tty_init_termios(tty); tty_port_tty_set(&port->port, tty); } /* only call the device specific open if this * is the first time the port is opened */ retval = serial->type->open(NULL, port); if (retval) { dev_err(&port->dev, ""could not open USB console port\n""); goto fail; } if (serial->type->set_termios) { tty->termios.c_cflag = cflag; tty_termios_encode_baud_rate(&tty->termios, baud, baud); memset(&dummy, 0, sizeof(struct ktermios)); serial->type->set_termios(tty, port, &dummy); tty_port_tty_set(&port->port, NULL); tty_kref_put(tty); } tty_port_set_initialized(&port->port, 1); } /* Now that any required fake tty operations are completed restore * the tty port count */ --port->port.count; /* The console is special in terms of closing the device so * indicate this port is now acting as a system console. */ port->port.console = 1; mutex_unlock(&serial->disc_mutex); return retval; fail: tty_port_tty_set(&port->port, NULL); tty_kref_put(tty); reset_open_count: port->port.count = 0; info->port = NULL; usb_autopm_put_interface(serial->interface); error_get_interface: usb_serial_put(serial); mutex_unlock(&serial->disc_mutex); return retval; }","{'deleted': [], 'added': [{'line_no': 132, 'char_start': 3110, 'char_end': 3130, 'line': '\tinfo->port = NULL;\n'}]}","{'deleted': [], 'added': [{'char_start': 3111, 'char_end': 3131, 'chars': 'info->port = NULL;\n\t'}]}",github.com/torvalds/linux/commit/299d7572e46f98534033a9e65973f13ad1ce9047,drivers/usb/serial/console.c,cwe-416,1003 cwe-089,add_input," def add_input(self, data): connection = self.connects() try: # The following introduces a deliberate security flaw. See section on SQL injecton below query = ""INSERT INTO crimes (description) VALUES ('{}');"".format( data) with connection.cursor() as cursor: cursor.execute(query) connection.commit() finally: connection.close()"," def add_input(self, data): connection = self.connects() try: # The following introduces a deliberate security flaw. See section on SQL injecton below query = ""INSERT INTO crimes (description) VALUES (%s);"" with connection.cursor() as cursor: cursor.execute(query, data) connection.commit() finally: connection.close()","{'deleted': [{'line_no': 5, 'char_start': 182, 'char_end': 260, 'line': ' query = ""INSERT INTO crimes (description) VALUES (\'{}\');"".format(\n'}, {'line_no': 6, 'char_start': 260, 'char_end': 282, 'line': ' data)\n'}, {'line_no': 8, 'char_start': 330, 'char_end': 368, 'line': ' cursor.execute(query)\n'}], 'added': [{'line_no': 5, 'char_start': 182, 'char_end': 250, 'line': ' query = ""INSERT INTO crimes (description) VALUES (%s);""\n'}, {'line_no': 7, 'char_start': 298, 'char_end': 342, 'line': ' cursor.execute(query, data)\n'}]}","{'deleted': [{'char_start': 244, 'char_end': 248, 'chars': ""'{}'""}, {'char_start': 251, 'char_end': 281, 'chars': '.format(\n data)'}], 'added': [{'char_start': 244, 'char_end': 246, 'chars': '%s'}, {'char_start': 334, 'char_end': 340, 'chars': ', data'}]}",github.com/JeremiahO/crimemap/commit/c17537fcd7aa4e2a26f7ca5cefaeb356ff646858,dbhelper.py,cwe-089,80 cwe-125,jpc_pi_nextrpcl,"static int jpc_pi_nextrpcl(register jpc_pi_t *pi) { int rlvlno; jpc_pirlvl_t *pirlvl; jpc_pchg_t *pchg; int prchind; int prcvind; int *prclyrno; int compno; jpc_picomp_t *picomp; int xstep; int ystep; uint_fast32_t r; uint_fast32_t rpx; uint_fast32_t rpy; uint_fast32_t trx0; uint_fast32_t try0; pchg = pi->pchg; if (!pi->prgvolfirst) { goto skip; } else { pi->xstep = 0; pi->ystep = 0; for (compno = 0, picomp = pi->picomps; compno < pi->numcomps; ++compno, ++picomp) { for (rlvlno = 0, pirlvl = picomp->pirlvls; rlvlno < picomp->numrlvls; ++rlvlno, ++pirlvl) { // Check for the potential for overflow problems. if (pirlvl->prcwidthexpn + pi->picomp->numrlvls > JAS_UINTFAST32_NUMBITS - 2 || pirlvl->prcheightexpn + pi->picomp->numrlvls > JAS_UINTFAST32_NUMBITS - 2) { return -1; } xstep = picomp->hsamp * (JAS_CAST(uint_fast32_t, 1) << (pirlvl->prcwidthexpn + picomp->numrlvls - rlvlno - 1)); ystep = picomp->vsamp * (JAS_CAST(uint_fast32_t, 1) << (pirlvl->prcheightexpn + picomp->numrlvls - rlvlno - 1)); pi->xstep = (!pi->xstep) ? xstep : JAS_MIN(pi->xstep, xstep); pi->ystep = (!pi->ystep) ? ystep : JAS_MIN(pi->ystep, ystep); } } pi->prgvolfirst = 0; } for (pi->rlvlno = pchg->rlvlnostart; pi->rlvlno < pchg->rlvlnoend && pi->rlvlno < pi->maxrlvls; ++pi->rlvlno) { for (pi->y = pi->ystart; pi->y < pi->yend; pi->y += pi->ystep - (pi->y % pi->ystep)) { for (pi->x = pi->xstart; pi->x < pi->xend; pi->x += pi->xstep - (pi->x % pi->xstep)) { for (pi->compno = pchg->compnostart, pi->picomp = &pi->picomps[pi->compno]; pi->compno < JAS_CAST(int, pchg->compnoend) && pi->compno < pi->numcomps; ++pi->compno, ++pi->picomp) { if (pi->rlvlno >= pi->picomp->numrlvls) { continue; } pi->pirlvl = &pi->picomp->pirlvls[pi->rlvlno]; if (pi->pirlvl->numprcs == 0) { continue; } r = pi->picomp->numrlvls - 1 - pi->rlvlno; rpx = r + pi->pirlvl->prcwidthexpn; rpy = r + pi->pirlvl->prcheightexpn; trx0 = JPC_CEILDIV(pi->xstart, pi->picomp->hsamp << r); try0 = JPC_CEILDIV(pi->ystart, pi->picomp->vsamp << r); if (((pi->x == pi->xstart && ((trx0 << r) % (JAS_CAST(uint_fast32_t, 1) << rpx))) || !(pi->x % (JAS_CAST(uint_fast32_t, 1) << rpx))) && ((pi->y == pi->ystart && ((try0 << r) % (JAS_CAST(uint_fast32_t, 1) << rpy))) || !(pi->y % (JAS_CAST(uint_fast32_t, 1) << rpy)))) { prchind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->x, pi->picomp->hsamp << r), pi->pirlvl->prcwidthexpn) - JPC_FLOORDIVPOW2(trx0, pi->pirlvl->prcwidthexpn); prcvind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->y, pi->picomp->vsamp << r), pi->pirlvl->prcheightexpn) - JPC_FLOORDIVPOW2(try0, pi->pirlvl->prcheightexpn); pi->prcno = prcvind * pi->pirlvl->numhprcs + prchind; assert(pi->prcno < pi->pirlvl->numprcs); for (pi->lyrno = 0; pi->lyrno < pi->numlyrs && pi->lyrno < JAS_CAST(int, pchg->lyrnoend); ++pi->lyrno) { prclyrno = &pi->pirlvl->prclyrnos[pi->prcno]; if (pi->lyrno >= *prclyrno) { ++(*prclyrno); return 0; } skip: ; } } } } } } return 1; }","static int jpc_pi_nextrpcl(register jpc_pi_t *pi) { int rlvlno; jpc_pirlvl_t *pirlvl; jpc_pchg_t *pchg; int prchind; int prcvind; int *prclyrno; int compno; jpc_picomp_t *picomp; int xstep; int ystep; uint_fast32_t r; uint_fast32_t rpx; uint_fast32_t rpy; uint_fast32_t trx0; uint_fast32_t try0; pchg = pi->pchg; if (!pi->prgvolfirst) { goto skip; } else { pi->xstep = 0; pi->ystep = 0; for (compno = 0, picomp = pi->picomps; compno < pi->numcomps; ++compno, ++picomp) { for (rlvlno = 0, pirlvl = picomp->pirlvls; rlvlno < picomp->numrlvls; ++rlvlno, ++pirlvl) { // Check for the potential for overflow problems. if (pirlvl->prcwidthexpn + picomp->numrlvls > JAS_UINTFAST32_NUMBITS - 2 || pirlvl->prcheightexpn + picomp->numrlvls > JAS_UINTFAST32_NUMBITS - 2) { return -1; } xstep = picomp->hsamp * (JAS_CAST(uint_fast32_t, 1) << (pirlvl->prcwidthexpn + picomp->numrlvls - rlvlno - 1)); ystep = picomp->vsamp * (JAS_CAST(uint_fast32_t, 1) << (pirlvl->prcheightexpn + picomp->numrlvls - rlvlno - 1)); pi->xstep = (!pi->xstep) ? xstep : JAS_MIN(pi->xstep, xstep); pi->ystep = (!pi->ystep) ? ystep : JAS_MIN(pi->ystep, ystep); } } pi->prgvolfirst = 0; } for (pi->rlvlno = pchg->rlvlnostart; pi->rlvlno < pchg->rlvlnoend && pi->rlvlno < pi->maxrlvls; ++pi->rlvlno) { for (pi->y = pi->ystart; pi->y < pi->yend; pi->y += pi->ystep - (pi->y % pi->ystep)) { for (pi->x = pi->xstart; pi->x < pi->xend; pi->x += pi->xstep - (pi->x % pi->xstep)) { for (pi->compno = pchg->compnostart, pi->picomp = &pi->picomps[pi->compno]; pi->compno < JAS_CAST(int, pchg->compnoend) && pi->compno < pi->numcomps; ++pi->compno, ++pi->picomp) { if (pi->rlvlno >= pi->picomp->numrlvls) { continue; } pi->pirlvl = &pi->picomp->pirlvls[pi->rlvlno]; if (pi->pirlvl->numprcs == 0) { continue; } r = pi->picomp->numrlvls - 1 - pi->rlvlno; rpx = r + pi->pirlvl->prcwidthexpn; rpy = r + pi->pirlvl->prcheightexpn; trx0 = JPC_CEILDIV(pi->xstart, pi->picomp->hsamp << r); try0 = JPC_CEILDIV(pi->ystart, pi->picomp->vsamp << r); if (((pi->x == pi->xstart && ((trx0 << r) % (JAS_CAST(uint_fast32_t, 1) << rpx))) || !(pi->x % (JAS_CAST(uint_fast32_t, 1) << rpx))) && ((pi->y == pi->ystart && ((try0 << r) % (JAS_CAST(uint_fast32_t, 1) << rpy))) || !(pi->y % (JAS_CAST(uint_fast32_t, 1) << rpy)))) { prchind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->x, pi->picomp->hsamp << r), pi->pirlvl->prcwidthexpn) - JPC_FLOORDIVPOW2(trx0, pi->pirlvl->prcwidthexpn); prcvind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->y, pi->picomp->vsamp << r), pi->pirlvl->prcheightexpn) - JPC_FLOORDIVPOW2(try0, pi->pirlvl->prcheightexpn); pi->prcno = prcvind * pi->pirlvl->numhprcs + prchind; assert(pi->prcno < pi->pirlvl->numprcs); for (pi->lyrno = 0; pi->lyrno < pi->numlyrs && pi->lyrno < JAS_CAST(int, pchg->lyrnoend); ++pi->lyrno) { prclyrno = &pi->pirlvl->prclyrnos[pi->prcno]; if (pi->lyrno >= *prclyrno) { ++(*prclyrno); return 0; } skip: ; } } } } } } return 1; }","{'deleted': [{'line_no': 30, 'char_start': 656, 'char_end': 710, 'line': '\t\t\t\tif (pirlvl->prcwidthexpn + pi->picomp->numrlvls >\n'}, {'line_no': 32, 'char_start': 746, 'char_end': 799, 'line': '\t\t\t\t pirlvl->prcheightexpn + pi->picomp->numrlvls >\n'}], 'added': [{'line_no': 30, 'char_start': 656, 'char_end': 706, 'line': '\t\t\t\tif (pirlvl->prcwidthexpn + picomp->numrlvls >\n'}, {'line_no': 32, 'char_start': 742, 'char_end': 791, 'line': '\t\t\t\t pirlvl->prcheightexpn + picomp->numrlvls >\n'}]}","{'deleted': [{'char_start': 689, 'char_end': 693, 'chars': '->pi'}, {'char_start': 776, 'char_end': 780, 'chars': 'pi->'}], 'added': []}",github.com/mdadams/jasper/commit/f25486c3d4aa472fec79150f2c41ed4333395d3d,src/libjasper/jpc/jpc_t2cod.c,cwe-125,1363 cwe-476,avcodec_open2,"int attribute_align_arg avcodec_open2(AVCodecContext *avctx, const AVCodec *codec, AVDictionary **options) { int ret = 0; int codec_init_ok = 0; AVDictionary *tmp = NULL; const AVPixFmtDescriptor *pixdesc; if (avcodec_is_open(avctx)) return 0; if ((!codec && !avctx->codec)) { av_log(avctx, AV_LOG_ERROR, ""No codec provided to avcodec_open2()\n""); return AVERROR(EINVAL); } if ((codec && avctx->codec && codec != avctx->codec)) { av_log(avctx, AV_LOG_ERROR, ""This AVCodecContext was allocated for %s, "" ""but %s passed to avcodec_open2()\n"", avctx->codec->name, codec->name); return AVERROR(EINVAL); } if (!codec) codec = avctx->codec; if (avctx->extradata_size < 0 || avctx->extradata_size >= FF_MAX_EXTRADATA_SIZE) return AVERROR(EINVAL); if (options) av_dict_copy(&tmp, *options, 0); ff_lock_avcodec(avctx, codec); avctx->internal = av_mallocz(sizeof(*avctx->internal)); if (!avctx->internal) { ret = AVERROR(ENOMEM); goto end; } avctx->internal->pool = av_mallocz(sizeof(*avctx->internal->pool)); if (!avctx->internal->pool) { ret = AVERROR(ENOMEM); goto free_and_end; } avctx->internal->to_free = av_frame_alloc(); if (!avctx->internal->to_free) { ret = AVERROR(ENOMEM); goto free_and_end; } avctx->internal->compat_decode_frame = av_frame_alloc(); if (!avctx->internal->compat_decode_frame) { ret = AVERROR(ENOMEM); goto free_and_end; } avctx->internal->buffer_frame = av_frame_alloc(); if (!avctx->internal->buffer_frame) { ret = AVERROR(ENOMEM); goto free_and_end; } avctx->internal->buffer_pkt = av_packet_alloc(); if (!avctx->internal->buffer_pkt) { ret = AVERROR(ENOMEM); goto free_and_end; } avctx->internal->ds.in_pkt = av_packet_alloc(); if (!avctx->internal->ds.in_pkt) { ret = AVERROR(ENOMEM); goto free_and_end; } avctx->internal->last_pkt_props = av_packet_alloc(); if (!avctx->internal->last_pkt_props) { ret = AVERROR(ENOMEM); goto free_and_end; } avctx->internal->skip_samples_multiplier = 1; if (codec->priv_data_size > 0) { if (!avctx->priv_data) { avctx->priv_data = av_mallocz(codec->priv_data_size); if (!avctx->priv_data) { ret = AVERROR(ENOMEM); goto end; } if (codec->priv_class) { *(const AVClass **)avctx->priv_data = codec->priv_class; av_opt_set_defaults(avctx->priv_data); } } if (codec->priv_class && (ret = av_opt_set_dict(avctx->priv_data, &tmp)) < 0) goto free_and_end; } else { avctx->priv_data = NULL; } if ((ret = av_opt_set_dict(avctx, &tmp)) < 0) goto free_and_end; if (avctx->codec_whitelist && av_match_list(codec->name, avctx->codec_whitelist, ',') <= 0) { av_log(avctx, AV_LOG_ERROR, ""Codec (%s) not on whitelist \'%s\'\n"", codec->name, avctx->codec_whitelist); ret = AVERROR(EINVAL); goto free_and_end; } // only call ff_set_dimensions() for non H.264/VP6F/DXV codecs so as not to overwrite previously setup dimensions if (!(avctx->coded_width && avctx->coded_height && avctx->width && avctx->height && (avctx->codec_id == AV_CODEC_ID_H264 || avctx->codec_id == AV_CODEC_ID_VP6F || avctx->codec_id == AV_CODEC_ID_DXV))) { if (avctx->coded_width && avctx->coded_height) ret = ff_set_dimensions(avctx, avctx->coded_width, avctx->coded_height); else if (avctx->width && avctx->height) ret = ff_set_dimensions(avctx, avctx->width, avctx->height); if (ret < 0) goto free_and_end; } if ((avctx->coded_width || avctx->coded_height || avctx->width || avctx->height) && ( av_image_check_size2(avctx->coded_width, avctx->coded_height, avctx->max_pixels, AV_PIX_FMT_NONE, 0, avctx) < 0 || av_image_check_size2(avctx->width, avctx->height, avctx->max_pixels, AV_PIX_FMT_NONE, 0, avctx) < 0)) { av_log(avctx, AV_LOG_WARNING, ""Ignoring invalid width/height values\n""); ff_set_dimensions(avctx, 0, 0); } if (avctx->width > 0 && avctx->height > 0) { if (av_image_check_sar(avctx->width, avctx->height, avctx->sample_aspect_ratio) < 0) { av_log(avctx, AV_LOG_WARNING, ""ignoring invalid SAR: %u/%u\n"", avctx->sample_aspect_ratio.num, avctx->sample_aspect_ratio.den); avctx->sample_aspect_ratio = (AVRational){ 0, 1 }; } } /* if the decoder init function was already called previously, * free the already allocated subtitle_header before overwriting it */ if (av_codec_is_decoder(codec)) av_freep(&avctx->subtitle_header); if (avctx->channels > FF_SANE_NB_CHANNELS) { av_log(avctx, AV_LOG_ERROR, ""Too many channels: %d\n"", avctx->channels); ret = AVERROR(EINVAL); goto free_and_end; } avctx->codec = codec; if ((avctx->codec_type == AVMEDIA_TYPE_UNKNOWN || avctx->codec_type == codec->type) && avctx->codec_id == AV_CODEC_ID_NONE) { avctx->codec_type = codec->type; avctx->codec_id = codec->id; } if (avctx->codec_id != codec->id || (avctx->codec_type != codec->type && avctx->codec_type != AVMEDIA_TYPE_ATTACHMENT)) { av_log(avctx, AV_LOG_ERROR, ""Codec type or id mismatches\n""); ret = AVERROR(EINVAL); goto free_and_end; } avctx->frame_number = 0; avctx->codec_descriptor = avcodec_descriptor_get(avctx->codec_id); if ((avctx->codec->capabilities & AV_CODEC_CAP_EXPERIMENTAL) && avctx->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) { const char *codec_string = av_codec_is_encoder(codec) ? ""encoder"" : ""decoder""; AVCodec *codec2; av_log(avctx, AV_LOG_ERROR, ""The %s '%s' is experimental but experimental codecs are not enabled, "" ""add '-strict %d' if you want to use it.\n"", codec_string, codec->name, FF_COMPLIANCE_EXPERIMENTAL); codec2 = av_codec_is_encoder(codec) ? avcodec_find_encoder(codec->id) : avcodec_find_decoder(codec->id); if (!(codec2->capabilities & AV_CODEC_CAP_EXPERIMENTAL)) av_log(avctx, AV_LOG_ERROR, ""Alternatively use the non experimental %s '%s'.\n"", codec_string, codec2->name); ret = AVERROR_EXPERIMENTAL; goto free_and_end; } if (avctx->codec_type == AVMEDIA_TYPE_AUDIO && (!avctx->time_base.num || !avctx->time_base.den)) { avctx->time_base.num = 1; avctx->time_base.den = avctx->sample_rate; } if (!HAVE_THREADS) av_log(avctx, AV_LOG_WARNING, ""Warning: not compiled with thread support, using thread emulation\n""); if (CONFIG_FRAME_THREAD_ENCODER && av_codec_is_encoder(avctx->codec)) { ff_unlock_avcodec(codec); //we will instantiate a few encoders thus kick the counter to prevent false detection of a problem ret = ff_frame_thread_encoder_init(avctx, options ? *options : NULL); ff_lock_avcodec(avctx, codec); if (ret < 0) goto free_and_end; } if (av_codec_is_decoder(avctx->codec)) { ret = ff_decode_bsfs_init(avctx); if (ret < 0) goto free_and_end; } if (HAVE_THREADS && !(avctx->internal->frame_thread_encoder && (avctx->active_thread_type&FF_THREAD_FRAME))) { ret = ff_thread_init(avctx); if (ret < 0) { goto free_and_end; } } if (!HAVE_THREADS && !(codec->capabilities & AV_CODEC_CAP_AUTO_THREADS)) avctx->thread_count = 1; if (avctx->codec->max_lowres < avctx->lowres || avctx->lowres < 0) { av_log(avctx, AV_LOG_WARNING, ""The maximum value for lowres supported by the decoder is %d\n"", avctx->codec->max_lowres); avctx->lowres = avctx->codec->max_lowres; } if (av_codec_is_encoder(avctx->codec)) { int i; #if FF_API_CODED_FRAME FF_DISABLE_DEPRECATION_WARNINGS avctx->coded_frame = av_frame_alloc(); if (!avctx->coded_frame) { ret = AVERROR(ENOMEM); goto free_and_end; } FF_ENABLE_DEPRECATION_WARNINGS #endif if (avctx->time_base.num <= 0 || avctx->time_base.den <= 0) { av_log(avctx, AV_LOG_ERROR, ""The encoder timebase is not set.\n""); ret = AVERROR(EINVAL); goto free_and_end; } if (avctx->codec->sample_fmts) { for (i = 0; avctx->codec->sample_fmts[i] != AV_SAMPLE_FMT_NONE; i++) { if (avctx->sample_fmt == avctx->codec->sample_fmts[i]) break; if (avctx->channels == 1 && av_get_planar_sample_fmt(avctx->sample_fmt) == av_get_planar_sample_fmt(avctx->codec->sample_fmts[i])) { avctx->sample_fmt = avctx->codec->sample_fmts[i]; break; } } if (avctx->codec->sample_fmts[i] == AV_SAMPLE_FMT_NONE) { char buf[128]; snprintf(buf, sizeof(buf), ""%d"", avctx->sample_fmt); av_log(avctx, AV_LOG_ERROR, ""Specified sample format %s is invalid or not supported\n"", (char *)av_x_if_null(av_get_sample_fmt_name(avctx->sample_fmt), buf)); ret = AVERROR(EINVAL); goto free_and_end; } } if (avctx->codec->pix_fmts) { for (i = 0; avctx->codec->pix_fmts[i] != AV_PIX_FMT_NONE; i++) if (avctx->pix_fmt == avctx->codec->pix_fmts[i]) break; if (avctx->codec->pix_fmts[i] == AV_PIX_FMT_NONE && !((avctx->codec_id == AV_CODEC_ID_MJPEG || avctx->codec_id == AV_CODEC_ID_LJPEG) && avctx->strict_std_compliance <= FF_COMPLIANCE_UNOFFICIAL)) { char buf[128]; snprintf(buf, sizeof(buf), ""%d"", avctx->pix_fmt); av_log(avctx, AV_LOG_ERROR, ""Specified pixel format %s is invalid or not supported\n"", (char *)av_x_if_null(av_get_pix_fmt_name(avctx->pix_fmt), buf)); ret = AVERROR(EINVAL); goto free_and_end; } if (avctx->codec->pix_fmts[i] == AV_PIX_FMT_YUVJ420P || avctx->codec->pix_fmts[i] == AV_PIX_FMT_YUVJ411P || avctx->codec->pix_fmts[i] == AV_PIX_FMT_YUVJ422P || avctx->codec->pix_fmts[i] == AV_PIX_FMT_YUVJ440P || avctx->codec->pix_fmts[i] == AV_PIX_FMT_YUVJ444P) avctx->color_range = AVCOL_RANGE_JPEG; } if (avctx->codec->supported_samplerates) { for (i = 0; avctx->codec->supported_samplerates[i] != 0; i++) if (avctx->sample_rate == avctx->codec->supported_samplerates[i]) break; if (avctx->codec->supported_samplerates[i] == 0) { av_log(avctx, AV_LOG_ERROR, ""Specified sample rate %d is not supported\n"", avctx->sample_rate); ret = AVERROR(EINVAL); goto free_and_end; } } if (avctx->sample_rate < 0) { av_log(avctx, AV_LOG_ERROR, ""Specified sample rate %d is not supported\n"", avctx->sample_rate); ret = AVERROR(EINVAL); goto free_and_end; } if (avctx->codec->channel_layouts) { if (!avctx->channel_layout) { av_log(avctx, AV_LOG_WARNING, ""Channel layout not specified\n""); } else { for (i = 0; avctx->codec->channel_layouts[i] != 0; i++) if (avctx->channel_layout == avctx->codec->channel_layouts[i]) break; if (avctx->codec->channel_layouts[i] == 0) { char buf[512]; av_get_channel_layout_string(buf, sizeof(buf), -1, avctx->channel_layout); av_log(avctx, AV_LOG_ERROR, ""Specified channel layout '%s' is not supported\n"", buf); ret = AVERROR(EINVAL); goto free_and_end; } } } if (avctx->channel_layout && avctx->channels) { int channels = av_get_channel_layout_nb_channels(avctx->channel_layout); if (channels != avctx->channels) { char buf[512]; av_get_channel_layout_string(buf, sizeof(buf), -1, avctx->channel_layout); av_log(avctx, AV_LOG_ERROR, ""Channel layout '%s' with %d channels does not match number of specified channels %d\n"", buf, channels, avctx->channels); ret = AVERROR(EINVAL); goto free_and_end; } } else if (avctx->channel_layout) { avctx->channels = av_get_channel_layout_nb_channels(avctx->channel_layout); } if (avctx->channels < 0) { av_log(avctx, AV_LOG_ERROR, ""Specified number of channels %d is not supported\n"", avctx->channels); ret = AVERROR(EINVAL); goto free_and_end; } if(avctx->codec_type == AVMEDIA_TYPE_VIDEO) { pixdesc = av_pix_fmt_desc_get(avctx->pix_fmt); if ( avctx->bits_per_raw_sample < 0 || (avctx->bits_per_raw_sample > 8 && pixdesc->comp[0].depth <= 8)) { av_log(avctx, AV_LOG_WARNING, ""Specified bit depth %d not possible with the specified pixel formats depth %d\n"", avctx->bits_per_raw_sample, pixdesc->comp[0].depth); avctx->bits_per_raw_sample = pixdesc->comp[0].depth; } if (avctx->width <= 0 || avctx->height <= 0) { av_log(avctx, AV_LOG_ERROR, ""dimensions not set\n""); ret = AVERROR(EINVAL); goto free_and_end; } } if ( (avctx->codec_type == AVMEDIA_TYPE_VIDEO || avctx->codec_type == AVMEDIA_TYPE_AUDIO) && avctx->bit_rate>0 && avctx->bit_rate<1000) { av_log(avctx, AV_LOG_WARNING, ""Bitrate %""PRId64"" is extremely low, maybe you mean %""PRId64""k\n"", avctx->bit_rate, avctx->bit_rate); } if (!avctx->rc_initial_buffer_occupancy) avctx->rc_initial_buffer_occupancy = avctx->rc_buffer_size * 3LL / 4; if (avctx->ticks_per_frame && avctx->time_base.num && avctx->ticks_per_frame > INT_MAX / avctx->time_base.num) { av_log(avctx, AV_LOG_ERROR, ""ticks_per_frame %d too large for the timebase %d/%d."", avctx->ticks_per_frame, avctx->time_base.num, avctx->time_base.den); goto free_and_end; } if (avctx->hw_frames_ctx) { AVHWFramesContext *frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data; if (frames_ctx->format != avctx->pix_fmt) { av_log(avctx, AV_LOG_ERROR, ""Mismatching AVCodecContext.pix_fmt and AVHWFramesContext.format\n""); ret = AVERROR(EINVAL); goto free_and_end; } if (avctx->sw_pix_fmt != AV_PIX_FMT_NONE && avctx->sw_pix_fmt != frames_ctx->sw_format) { av_log(avctx, AV_LOG_ERROR, ""Mismatching AVCodecContext.sw_pix_fmt (%s) "" ""and AVHWFramesContext.sw_format (%s)\n"", av_get_pix_fmt_name(avctx->sw_pix_fmt), av_get_pix_fmt_name(frames_ctx->sw_format)); ret = AVERROR(EINVAL); goto free_and_end; } avctx->sw_pix_fmt = frames_ctx->sw_format; } } avctx->pts_correction_num_faulty_pts = avctx->pts_correction_num_faulty_dts = 0; avctx->pts_correction_last_pts = avctx->pts_correction_last_dts = INT64_MIN; if ( !CONFIG_GRAY && avctx->flags & AV_CODEC_FLAG_GRAY && avctx->codec_descriptor->type == AVMEDIA_TYPE_VIDEO) av_log(avctx, AV_LOG_WARNING, ""gray decoding requested but not enabled at configuration time\n""); if ( avctx->codec->init && (!(avctx->active_thread_type&FF_THREAD_FRAME) || avctx->internal->frame_thread_encoder)) { ret = avctx->codec->init(avctx); if (ret < 0) { goto free_and_end; } codec_init_ok = 1; } ret=0; if (av_codec_is_decoder(avctx->codec)) { if (!avctx->bit_rate) avctx->bit_rate = get_bit_rate(avctx); /* validate channel layout from the decoder */ if (avctx->channel_layout) { int channels = av_get_channel_layout_nb_channels(avctx->channel_layout); if (!avctx->channels) avctx->channels = channels; else if (channels != avctx->channels) { char buf[512]; av_get_channel_layout_string(buf, sizeof(buf), -1, avctx->channel_layout); av_log(avctx, AV_LOG_WARNING, ""Channel layout '%s' with %d channels does not match specified number of channels %d: "" ""ignoring specified channel layout\n"", buf, channels, avctx->channels); avctx->channel_layout = 0; } } if (avctx->channels && avctx->channels < 0 || avctx->channels > FF_SANE_NB_CHANNELS) { ret = AVERROR(EINVAL); goto free_and_end; } if (avctx->bits_per_coded_sample < 0) { ret = AVERROR(EINVAL); goto free_and_end; } if (avctx->sub_charenc) { if (avctx->codec_type != AVMEDIA_TYPE_SUBTITLE) { av_log(avctx, AV_LOG_ERROR, ""Character encoding is only "" ""supported with subtitles codecs\n""); ret = AVERROR(EINVAL); goto free_and_end; } else if (avctx->codec_descriptor->props & AV_CODEC_PROP_BITMAP_SUB) { av_log(avctx, AV_LOG_WARNING, ""Codec '%s' is bitmap-based, "" ""subtitles character encoding will be ignored\n"", avctx->codec_descriptor->name); avctx->sub_charenc_mode = FF_SUB_CHARENC_MODE_DO_NOTHING; } else { /* input character encoding is set for a text based subtitle * codec at this point */ if (avctx->sub_charenc_mode == FF_SUB_CHARENC_MODE_AUTOMATIC) avctx->sub_charenc_mode = FF_SUB_CHARENC_MODE_PRE_DECODER; if (avctx->sub_charenc_mode == FF_SUB_CHARENC_MODE_PRE_DECODER) { #if CONFIG_ICONV iconv_t cd = iconv_open(""UTF-8"", avctx->sub_charenc); if (cd == (iconv_t)-1) { ret = AVERROR(errno); av_log(avctx, AV_LOG_ERROR, ""Unable to open iconv context "" ""with input character encoding \""%s\""\n"", avctx->sub_charenc); goto free_and_end; } iconv_close(cd); #else av_log(avctx, AV_LOG_ERROR, ""Character encoding subtitles "" ""conversion needs a libavcodec built with iconv support "" ""for this codec\n""); ret = AVERROR(ENOSYS); goto free_and_end; #endif } } } #if FF_API_AVCTX_TIMEBASE if (avctx->framerate.num > 0 && avctx->framerate.den > 0) avctx->time_base = av_inv_q(av_mul_q(avctx->framerate, (AVRational){avctx->ticks_per_frame, 1})); #endif } if (codec->priv_data_size > 0 && avctx->priv_data && codec->priv_class) { av_assert0(*(const AVClass **)avctx->priv_data == codec->priv_class); } end: ff_unlock_avcodec(codec); if (options) { av_dict_free(options); *options = tmp; } return ret; free_and_end: if (avctx->codec && (codec_init_ok || (avctx->codec->caps_internal & FF_CODEC_CAP_INIT_CLEANUP))) avctx->codec->close(avctx); if (codec->priv_class && codec->priv_data_size) av_opt_free(avctx->priv_data); av_opt_free(avctx); #if FF_API_CODED_FRAME FF_DISABLE_DEPRECATION_WARNINGS av_frame_free(&avctx->coded_frame); FF_ENABLE_DEPRECATION_WARNINGS #endif av_dict_free(&tmp); av_freep(&avctx->priv_data); if (avctx->internal) { av_frame_free(&avctx->internal->to_free); av_frame_free(&avctx->internal->compat_decode_frame); av_frame_free(&avctx->internal->buffer_frame); av_packet_free(&avctx->internal->buffer_pkt); av_packet_free(&avctx->internal->last_pkt_props); av_packet_free(&avctx->internal->ds.in_pkt); ff_decode_bsfs_uninit(avctx); av_freep(&avctx->internal->pool); } av_freep(&avctx->internal); avctx->codec = NULL; goto end; }","int attribute_align_arg avcodec_open2(AVCodecContext *avctx, const AVCodec *codec, AVDictionary **options) { int ret = 0; int codec_init_ok = 0; AVDictionary *tmp = NULL; const AVPixFmtDescriptor *pixdesc; if (avcodec_is_open(avctx)) return 0; if ((!codec && !avctx->codec)) { av_log(avctx, AV_LOG_ERROR, ""No codec provided to avcodec_open2()\n""); return AVERROR(EINVAL); } if ((codec && avctx->codec && codec != avctx->codec)) { av_log(avctx, AV_LOG_ERROR, ""This AVCodecContext was allocated for %s, "" ""but %s passed to avcodec_open2()\n"", avctx->codec->name, codec->name); return AVERROR(EINVAL); } if (!codec) codec = avctx->codec; if (avctx->extradata_size < 0 || avctx->extradata_size >= FF_MAX_EXTRADATA_SIZE) return AVERROR(EINVAL); if (options) av_dict_copy(&tmp, *options, 0); ff_lock_avcodec(avctx, codec); avctx->internal = av_mallocz(sizeof(*avctx->internal)); if (!avctx->internal) { ret = AVERROR(ENOMEM); goto end; } avctx->internal->pool = av_mallocz(sizeof(*avctx->internal->pool)); if (!avctx->internal->pool) { ret = AVERROR(ENOMEM); goto free_and_end; } avctx->internal->to_free = av_frame_alloc(); if (!avctx->internal->to_free) { ret = AVERROR(ENOMEM); goto free_and_end; } avctx->internal->compat_decode_frame = av_frame_alloc(); if (!avctx->internal->compat_decode_frame) { ret = AVERROR(ENOMEM); goto free_and_end; } avctx->internal->buffer_frame = av_frame_alloc(); if (!avctx->internal->buffer_frame) { ret = AVERROR(ENOMEM); goto free_and_end; } avctx->internal->buffer_pkt = av_packet_alloc(); if (!avctx->internal->buffer_pkt) { ret = AVERROR(ENOMEM); goto free_and_end; } avctx->internal->ds.in_pkt = av_packet_alloc(); if (!avctx->internal->ds.in_pkt) { ret = AVERROR(ENOMEM); goto free_and_end; } avctx->internal->last_pkt_props = av_packet_alloc(); if (!avctx->internal->last_pkt_props) { ret = AVERROR(ENOMEM); goto free_and_end; } avctx->internal->skip_samples_multiplier = 1; if (codec->priv_data_size > 0) { if (!avctx->priv_data) { avctx->priv_data = av_mallocz(codec->priv_data_size); if (!avctx->priv_data) { ret = AVERROR(ENOMEM); goto end; } if (codec->priv_class) { *(const AVClass **)avctx->priv_data = codec->priv_class; av_opt_set_defaults(avctx->priv_data); } } if (codec->priv_class && (ret = av_opt_set_dict(avctx->priv_data, &tmp)) < 0) goto free_and_end; } else { avctx->priv_data = NULL; } if ((ret = av_opt_set_dict(avctx, &tmp)) < 0) goto free_and_end; if (avctx->codec_whitelist && av_match_list(codec->name, avctx->codec_whitelist, ',') <= 0) { av_log(avctx, AV_LOG_ERROR, ""Codec (%s) not on whitelist \'%s\'\n"", codec->name, avctx->codec_whitelist); ret = AVERROR(EINVAL); goto free_and_end; } // only call ff_set_dimensions() for non H.264/VP6F/DXV codecs so as not to overwrite previously setup dimensions if (!(avctx->coded_width && avctx->coded_height && avctx->width && avctx->height && (avctx->codec_id == AV_CODEC_ID_H264 || avctx->codec_id == AV_CODEC_ID_VP6F || avctx->codec_id == AV_CODEC_ID_DXV))) { if (avctx->coded_width && avctx->coded_height) ret = ff_set_dimensions(avctx, avctx->coded_width, avctx->coded_height); else if (avctx->width && avctx->height) ret = ff_set_dimensions(avctx, avctx->width, avctx->height); if (ret < 0) goto free_and_end; } if ((avctx->coded_width || avctx->coded_height || avctx->width || avctx->height) && ( av_image_check_size2(avctx->coded_width, avctx->coded_height, avctx->max_pixels, AV_PIX_FMT_NONE, 0, avctx) < 0 || av_image_check_size2(avctx->width, avctx->height, avctx->max_pixels, AV_PIX_FMT_NONE, 0, avctx) < 0)) { av_log(avctx, AV_LOG_WARNING, ""Ignoring invalid width/height values\n""); ff_set_dimensions(avctx, 0, 0); } if (avctx->width > 0 && avctx->height > 0) { if (av_image_check_sar(avctx->width, avctx->height, avctx->sample_aspect_ratio) < 0) { av_log(avctx, AV_LOG_WARNING, ""ignoring invalid SAR: %u/%u\n"", avctx->sample_aspect_ratio.num, avctx->sample_aspect_ratio.den); avctx->sample_aspect_ratio = (AVRational){ 0, 1 }; } } /* if the decoder init function was already called previously, * free the already allocated subtitle_header before overwriting it */ if (av_codec_is_decoder(codec)) av_freep(&avctx->subtitle_header); if (avctx->channels > FF_SANE_NB_CHANNELS) { av_log(avctx, AV_LOG_ERROR, ""Too many channels: %d\n"", avctx->channels); ret = AVERROR(EINVAL); goto free_and_end; } avctx->codec = codec; if ((avctx->codec_type == AVMEDIA_TYPE_UNKNOWN || avctx->codec_type == codec->type) && avctx->codec_id == AV_CODEC_ID_NONE) { avctx->codec_type = codec->type; avctx->codec_id = codec->id; } if (avctx->codec_id != codec->id || (avctx->codec_type != codec->type && avctx->codec_type != AVMEDIA_TYPE_ATTACHMENT)) { av_log(avctx, AV_LOG_ERROR, ""Codec type or id mismatches\n""); ret = AVERROR(EINVAL); goto free_and_end; } avctx->frame_number = 0; avctx->codec_descriptor = avcodec_descriptor_get(avctx->codec_id); if ((avctx->codec->capabilities & AV_CODEC_CAP_EXPERIMENTAL) && avctx->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) { const char *codec_string = av_codec_is_encoder(codec) ? ""encoder"" : ""decoder""; AVCodec *codec2; av_log(avctx, AV_LOG_ERROR, ""The %s '%s' is experimental but experimental codecs are not enabled, "" ""add '-strict %d' if you want to use it.\n"", codec_string, codec->name, FF_COMPLIANCE_EXPERIMENTAL); codec2 = av_codec_is_encoder(codec) ? avcodec_find_encoder(codec->id) : avcodec_find_decoder(codec->id); if (!(codec2->capabilities & AV_CODEC_CAP_EXPERIMENTAL)) av_log(avctx, AV_LOG_ERROR, ""Alternatively use the non experimental %s '%s'.\n"", codec_string, codec2->name); ret = AVERROR_EXPERIMENTAL; goto free_and_end; } if (avctx->codec_type == AVMEDIA_TYPE_AUDIO && (!avctx->time_base.num || !avctx->time_base.den)) { avctx->time_base.num = 1; avctx->time_base.den = avctx->sample_rate; } if (!HAVE_THREADS) av_log(avctx, AV_LOG_WARNING, ""Warning: not compiled with thread support, using thread emulation\n""); if (CONFIG_FRAME_THREAD_ENCODER && av_codec_is_encoder(avctx->codec)) { ff_unlock_avcodec(codec); //we will instantiate a few encoders thus kick the counter to prevent false detection of a problem ret = ff_frame_thread_encoder_init(avctx, options ? *options : NULL); ff_lock_avcodec(avctx, codec); if (ret < 0) goto free_and_end; } if (av_codec_is_decoder(avctx->codec)) { ret = ff_decode_bsfs_init(avctx); if (ret < 0) goto free_and_end; } if (HAVE_THREADS && !(avctx->internal->frame_thread_encoder && (avctx->active_thread_type&FF_THREAD_FRAME))) { ret = ff_thread_init(avctx); if (ret < 0) { goto free_and_end; } } if (!HAVE_THREADS && !(codec->capabilities & AV_CODEC_CAP_AUTO_THREADS)) avctx->thread_count = 1; if (avctx->codec->max_lowres < avctx->lowres || avctx->lowres < 0) { av_log(avctx, AV_LOG_WARNING, ""The maximum value for lowres supported by the decoder is %d\n"", avctx->codec->max_lowres); avctx->lowres = avctx->codec->max_lowres; } if (av_codec_is_encoder(avctx->codec)) { int i; #if FF_API_CODED_FRAME FF_DISABLE_DEPRECATION_WARNINGS avctx->coded_frame = av_frame_alloc(); if (!avctx->coded_frame) { ret = AVERROR(ENOMEM); goto free_and_end; } FF_ENABLE_DEPRECATION_WARNINGS #endif if (avctx->time_base.num <= 0 || avctx->time_base.den <= 0) { av_log(avctx, AV_LOG_ERROR, ""The encoder timebase is not set.\n""); ret = AVERROR(EINVAL); goto free_and_end; } if (avctx->codec->sample_fmts) { for (i = 0; avctx->codec->sample_fmts[i] != AV_SAMPLE_FMT_NONE; i++) { if (avctx->sample_fmt == avctx->codec->sample_fmts[i]) break; if (avctx->channels == 1 && av_get_planar_sample_fmt(avctx->sample_fmt) == av_get_planar_sample_fmt(avctx->codec->sample_fmts[i])) { avctx->sample_fmt = avctx->codec->sample_fmts[i]; break; } } if (avctx->codec->sample_fmts[i] == AV_SAMPLE_FMT_NONE) { char buf[128]; snprintf(buf, sizeof(buf), ""%d"", avctx->sample_fmt); av_log(avctx, AV_LOG_ERROR, ""Specified sample format %s is invalid or not supported\n"", (char *)av_x_if_null(av_get_sample_fmt_name(avctx->sample_fmt), buf)); ret = AVERROR(EINVAL); goto free_and_end; } } if (avctx->codec->pix_fmts) { for (i = 0; avctx->codec->pix_fmts[i] != AV_PIX_FMT_NONE; i++) if (avctx->pix_fmt == avctx->codec->pix_fmts[i]) break; if (avctx->codec->pix_fmts[i] == AV_PIX_FMT_NONE && !((avctx->codec_id == AV_CODEC_ID_MJPEG || avctx->codec_id == AV_CODEC_ID_LJPEG) && avctx->strict_std_compliance <= FF_COMPLIANCE_UNOFFICIAL)) { char buf[128]; snprintf(buf, sizeof(buf), ""%d"", avctx->pix_fmt); av_log(avctx, AV_LOG_ERROR, ""Specified pixel format %s is invalid or not supported\n"", (char *)av_x_if_null(av_get_pix_fmt_name(avctx->pix_fmt), buf)); ret = AVERROR(EINVAL); goto free_and_end; } if (avctx->codec->pix_fmts[i] == AV_PIX_FMT_YUVJ420P || avctx->codec->pix_fmts[i] == AV_PIX_FMT_YUVJ411P || avctx->codec->pix_fmts[i] == AV_PIX_FMT_YUVJ422P || avctx->codec->pix_fmts[i] == AV_PIX_FMT_YUVJ440P || avctx->codec->pix_fmts[i] == AV_PIX_FMT_YUVJ444P) avctx->color_range = AVCOL_RANGE_JPEG; } if (avctx->codec->supported_samplerates) { for (i = 0; avctx->codec->supported_samplerates[i] != 0; i++) if (avctx->sample_rate == avctx->codec->supported_samplerates[i]) break; if (avctx->codec->supported_samplerates[i] == 0) { av_log(avctx, AV_LOG_ERROR, ""Specified sample rate %d is not supported\n"", avctx->sample_rate); ret = AVERROR(EINVAL); goto free_and_end; } } if (avctx->sample_rate < 0) { av_log(avctx, AV_LOG_ERROR, ""Specified sample rate %d is not supported\n"", avctx->sample_rate); ret = AVERROR(EINVAL); goto free_and_end; } if (avctx->codec->channel_layouts) { if (!avctx->channel_layout) { av_log(avctx, AV_LOG_WARNING, ""Channel layout not specified\n""); } else { for (i = 0; avctx->codec->channel_layouts[i] != 0; i++) if (avctx->channel_layout == avctx->codec->channel_layouts[i]) break; if (avctx->codec->channel_layouts[i] == 0) { char buf[512]; av_get_channel_layout_string(buf, sizeof(buf), -1, avctx->channel_layout); av_log(avctx, AV_LOG_ERROR, ""Specified channel layout '%s' is not supported\n"", buf); ret = AVERROR(EINVAL); goto free_and_end; } } } if (avctx->channel_layout && avctx->channels) { int channels = av_get_channel_layout_nb_channels(avctx->channel_layout); if (channels != avctx->channels) { char buf[512]; av_get_channel_layout_string(buf, sizeof(buf), -1, avctx->channel_layout); av_log(avctx, AV_LOG_ERROR, ""Channel layout '%s' with %d channels does not match number of specified channels %d\n"", buf, channels, avctx->channels); ret = AVERROR(EINVAL); goto free_and_end; } } else if (avctx->channel_layout) { avctx->channels = av_get_channel_layout_nb_channels(avctx->channel_layout); } if (avctx->channels < 0) { av_log(avctx, AV_LOG_ERROR, ""Specified number of channels %d is not supported\n"", avctx->channels); ret = AVERROR(EINVAL); goto free_and_end; } if(avctx->codec_type == AVMEDIA_TYPE_VIDEO) { pixdesc = av_pix_fmt_desc_get(avctx->pix_fmt); if ( avctx->bits_per_raw_sample < 0 || (avctx->bits_per_raw_sample > 8 && pixdesc->comp[0].depth <= 8)) { av_log(avctx, AV_LOG_WARNING, ""Specified bit depth %d not possible with the specified pixel formats depth %d\n"", avctx->bits_per_raw_sample, pixdesc->comp[0].depth); avctx->bits_per_raw_sample = pixdesc->comp[0].depth; } if (avctx->width <= 0 || avctx->height <= 0) { av_log(avctx, AV_LOG_ERROR, ""dimensions not set\n""); ret = AVERROR(EINVAL); goto free_and_end; } } if ( (avctx->codec_type == AVMEDIA_TYPE_VIDEO || avctx->codec_type == AVMEDIA_TYPE_AUDIO) && avctx->bit_rate>0 && avctx->bit_rate<1000) { av_log(avctx, AV_LOG_WARNING, ""Bitrate %""PRId64"" is extremely low, maybe you mean %""PRId64""k\n"", avctx->bit_rate, avctx->bit_rate); } if (!avctx->rc_initial_buffer_occupancy) avctx->rc_initial_buffer_occupancy = avctx->rc_buffer_size * 3LL / 4; if (avctx->ticks_per_frame && avctx->time_base.num && avctx->ticks_per_frame > INT_MAX / avctx->time_base.num) { av_log(avctx, AV_LOG_ERROR, ""ticks_per_frame %d too large for the timebase %d/%d."", avctx->ticks_per_frame, avctx->time_base.num, avctx->time_base.den); goto free_and_end; } if (avctx->hw_frames_ctx) { AVHWFramesContext *frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data; if (frames_ctx->format != avctx->pix_fmt) { av_log(avctx, AV_LOG_ERROR, ""Mismatching AVCodecContext.pix_fmt and AVHWFramesContext.format\n""); ret = AVERROR(EINVAL); goto free_and_end; } if (avctx->sw_pix_fmt != AV_PIX_FMT_NONE && avctx->sw_pix_fmt != frames_ctx->sw_format) { av_log(avctx, AV_LOG_ERROR, ""Mismatching AVCodecContext.sw_pix_fmt (%s) "" ""and AVHWFramesContext.sw_format (%s)\n"", av_get_pix_fmt_name(avctx->sw_pix_fmt), av_get_pix_fmt_name(frames_ctx->sw_format)); ret = AVERROR(EINVAL); goto free_and_end; } avctx->sw_pix_fmt = frames_ctx->sw_format; } } avctx->pts_correction_num_faulty_pts = avctx->pts_correction_num_faulty_dts = 0; avctx->pts_correction_last_pts = avctx->pts_correction_last_dts = INT64_MIN; if ( !CONFIG_GRAY && avctx->flags & AV_CODEC_FLAG_GRAY && avctx->codec_descriptor->type == AVMEDIA_TYPE_VIDEO) av_log(avctx, AV_LOG_WARNING, ""gray decoding requested but not enabled at configuration time\n""); if ( avctx->codec->init && (!(avctx->active_thread_type&FF_THREAD_FRAME) || avctx->internal->frame_thread_encoder)) { ret = avctx->codec->init(avctx); if (ret < 0) { goto free_and_end; } codec_init_ok = 1; } ret=0; if (av_codec_is_decoder(avctx->codec)) { if (!avctx->bit_rate) avctx->bit_rate = get_bit_rate(avctx); /* validate channel layout from the decoder */ if (avctx->channel_layout) { int channels = av_get_channel_layout_nb_channels(avctx->channel_layout); if (!avctx->channels) avctx->channels = channels; else if (channels != avctx->channels) { char buf[512]; av_get_channel_layout_string(buf, sizeof(buf), -1, avctx->channel_layout); av_log(avctx, AV_LOG_WARNING, ""Channel layout '%s' with %d channels does not match specified number of channels %d: "" ""ignoring specified channel layout\n"", buf, channels, avctx->channels); avctx->channel_layout = 0; } } if (avctx->channels && avctx->channels < 0 || avctx->channels > FF_SANE_NB_CHANNELS) { ret = AVERROR(EINVAL); goto free_and_end; } if (avctx->bits_per_coded_sample < 0) { ret = AVERROR(EINVAL); goto free_and_end; } if (avctx->sub_charenc) { if (avctx->codec_type != AVMEDIA_TYPE_SUBTITLE) { av_log(avctx, AV_LOG_ERROR, ""Character encoding is only "" ""supported with subtitles codecs\n""); ret = AVERROR(EINVAL); goto free_and_end; } else if (avctx->codec_descriptor->props & AV_CODEC_PROP_BITMAP_SUB) { av_log(avctx, AV_LOG_WARNING, ""Codec '%s' is bitmap-based, "" ""subtitles character encoding will be ignored\n"", avctx->codec_descriptor->name); avctx->sub_charenc_mode = FF_SUB_CHARENC_MODE_DO_NOTHING; } else { /* input character encoding is set for a text based subtitle * codec at this point */ if (avctx->sub_charenc_mode == FF_SUB_CHARENC_MODE_AUTOMATIC) avctx->sub_charenc_mode = FF_SUB_CHARENC_MODE_PRE_DECODER; if (avctx->sub_charenc_mode == FF_SUB_CHARENC_MODE_PRE_DECODER) { #if CONFIG_ICONV iconv_t cd = iconv_open(""UTF-8"", avctx->sub_charenc); if (cd == (iconv_t)-1) { ret = AVERROR(errno); av_log(avctx, AV_LOG_ERROR, ""Unable to open iconv context "" ""with input character encoding \""%s\""\n"", avctx->sub_charenc); goto free_and_end; } iconv_close(cd); #else av_log(avctx, AV_LOG_ERROR, ""Character encoding subtitles "" ""conversion needs a libavcodec built with iconv support "" ""for this codec\n""); ret = AVERROR(ENOSYS); goto free_and_end; #endif } } } #if FF_API_AVCTX_TIMEBASE if (avctx->framerate.num > 0 && avctx->framerate.den > 0) avctx->time_base = av_inv_q(av_mul_q(avctx->framerate, (AVRational){avctx->ticks_per_frame, 1})); #endif } if (codec->priv_data_size > 0 && avctx->priv_data && codec->priv_class) { av_assert0(*(const AVClass **)avctx->priv_data == codec->priv_class); } end: ff_unlock_avcodec(codec); if (options) { av_dict_free(options); *options = tmp; } return ret; free_and_end: if (avctx->codec && avctx->codec->close && (codec_init_ok || (avctx->codec->caps_internal & FF_CODEC_CAP_INIT_CLEANUP))) avctx->codec->close(avctx); if (codec->priv_class && codec->priv_data_size) av_opt_free(avctx->priv_data); av_opt_free(avctx); #if FF_API_CODED_FRAME FF_DISABLE_DEPRECATION_WARNINGS av_frame_free(&avctx->coded_frame); FF_ENABLE_DEPRECATION_WARNINGS #endif av_dict_free(&tmp); av_freep(&avctx->priv_data); if (avctx->internal) { av_frame_free(&avctx->internal->to_free); av_frame_free(&avctx->internal->compat_decode_frame); av_frame_free(&avctx->internal->buffer_frame); av_packet_free(&avctx->internal->buffer_pkt); av_packet_free(&avctx->internal->last_pkt_props); av_packet_free(&avctx->internal->ds.in_pkt); ff_decode_bsfs_uninit(avctx); av_freep(&avctx->internal->pool); } av_freep(&avctx->internal); avctx->codec = NULL; goto end; }","{'deleted': [{'line_no': 486, 'char_start': 20499, 'char_end': 20523, 'line': ' if (avctx->codec &&\n'}], 'added': [{'line_no': 486, 'char_start': 20499, 'char_end': 20546, 'line': ' if (avctx->codec && avctx->codec->close &&\n'}]}","{'deleted': [], 'added': [{'char_start': 20522, 'char_end': 20545, 'chars': ' avctx->codec->close &&'}]}",github.com/FFmpeg/FFmpeg/commit/8df6884832ec413cf032dfaa45c23b1c7876670c,libavcodec/utils.c,cwe-476,5416 cwe-089,top_proxies,"@app.route('/top_proxies') def top_proxies(): con = psycopg2.connect(**config.POSTGRES) cur = con.cursor() query = ""SELECT sum(amount) FROM holders"" cur.execute(query) total = cur.fetchone() total_votes = total[0] query = ""SELECT voting_as FROM holders WHERE voting_as<>'1.2.5' group by voting_as"" cur.execute(query) results = cur.fetchall() #con.close() proxies = [] for p in range(0, len(results)): proxy_line = [0] * 5 proxy_id = results[p][0] proxy_line[0] = proxy_id query = ""SELECT account_name, amount FROM holders WHERE account_id='""+proxy_id+""' LIMIT 1"" cur.execute(query) proxy = cur.fetchone() try: proxy_name = proxy[0] proxy_amount = proxy[1] except: proxy_name = ""unknown"" proxy_amount = 0 proxy_line[1] = proxy_name query = ""SELECT amount, account_id FROM holders WHERE voting_as='""+proxy_id+""'"" cur.execute(query) results2 = cur.fetchall() proxy_line[2] = int(proxy_amount) for p2 in range(0, len(results2)): amount = results2[p2][0] account_id = results2[p2][1] proxy_line[2] = proxy_line[2] + int(amount) # total proxy votes proxy_line[3] = proxy_line[3] + 1 # followers if proxy_line[3] > 2: percentage = float(float(proxy_line[2]) * 100.0/ float(total_votes)) proxy_line[4] = percentage proxies.append(proxy_line) con.close() proxies = sorted(proxies, key=lambda k: int(k[2])) r_proxies = proxies[::-1] return jsonify(filter(None, r_proxies))","@app.route('/top_proxies') def top_proxies(): con = psycopg2.connect(**config.POSTGRES) cur = con.cursor() query = ""SELECT sum(amount) FROM holders"" cur.execute(query) total = cur.fetchone() total_votes = total[0] query = ""SELECT voting_as FROM holders WHERE voting_as<>'1.2.5' group by voting_as"" cur.execute(query) results = cur.fetchall() #con.close() proxies = [] for p in range(0, len(results)): proxy_line = [0] * 5 proxy_id = results[p][0] proxy_line[0] = proxy_id query = ""SELECT account_name, amount FROM holders WHERE account_id=%s LIMIT 1"" cur.execute(query, (proxy_id,)) proxy = cur.fetchone() try: proxy_name = proxy[0] proxy_amount = proxy[1] except: proxy_name = ""unknown"" proxy_amount = 0 proxy_line[1] = proxy_name query = ""SELECT amount, account_id FROM holders WHERE voting_as=%s"" cur.execute(query, (proxy_id,)) results2 = cur.fetchall() proxy_line[2] = int(proxy_amount) for p2 in range(0, len(results2)): amount = results2[p2][0] account_id = results2[p2][1] proxy_line[2] = proxy_line[2] + int(amount) # total proxy votes proxy_line[3] = proxy_line[3] + 1 # followers if proxy_line[3] > 2: percentage = float(float(proxy_line[2]) * 100.0/ float(total_votes)) proxy_line[4] = percentage proxies.append(proxy_line) con.close() proxies = sorted(proxies, key=lambda k: int(k[2])) r_proxies = proxies[::-1] return jsonify(filter(None, r_proxies))","{'deleted': [{'line_no': 25, 'char_start': 551, 'char_end': 650, 'line': ' query = ""SELECT account_name, amount FROM holders WHERE account_id=\'""+proxy_id+""\' LIMIT 1""\n'}, {'line_no': 26, 'char_start': 650, 'char_end': 677, 'line': ' cur.execute(query)\n'}, {'line_no': 39, 'char_start': 910, 'char_end': 998, 'line': ' query = ""SELECT amount, account_id FROM holders WHERE voting_as=\'""+proxy_id+""\'""\n'}, {'line_no': 40, 'char_start': 998, 'char_end': 1025, 'line': ' cur.execute(query)\n'}], 'added': [{'line_no': 25, 'char_start': 551, 'char_end': 638, 'line': ' query = ""SELECT account_name, amount FROM holders WHERE account_id=%s LIMIT 1""\n'}, {'line_no': 26, 'char_start': 638, 'char_end': 678, 'line': ' cur.execute(query, (proxy_id,))\n'}, {'line_no': 39, 'char_start': 911, 'char_end': 987, 'line': ' query = ""SELECT amount, account_id FROM holders WHERE voting_as=%s""\n'}, {'line_no': 40, 'char_start': 987, 'char_end': 1027, 'line': ' cur.execute(query, (proxy_id,))\n'}]}","{'deleted': [{'char_start': 626, 'char_end': 640, 'chars': '\'""+proxy_id+""\''}, {'char_start': 982, 'char_end': 996, 'chars': '\'""+proxy_id+""\''}], 'added': [{'char_start': 626, 'char_end': 628, 'chars': '%s'}, {'char_start': 663, 'char_end': 676, 'chars': ', (proxy_id,)'}, {'char_start': 983, 'char_end': 985, 'chars': '%s'}, {'char_start': 1012, 'char_end': 1025, 'chars': ', (proxy_id,)'}]}",github.com/VinChain/vinchain-python-api-backend/commit/b78088a551fbb712121269c6eb7f43ede120ff60,api.py,cwe-089,429 cwe-089,add_consumption_data_row," def add_consumption_data_row(self, ts, energy_used, power_used): if power_used > 0: query = ''' INSERT OR IGNORE INTO Consumption ( TimeStamp, EnergyUsed, PowerUsed ) VALUES ( %s, %s, %s ); ''' % (ts, 0, 0) self.c.execute(query) query = ''' UPDATE Consumption SET EnergyUsed = EnergyUsed + %s, PowerUsed = PowerUsed + %s WHERE TimeStamp = %s; ''' % (energy_used, power_used, ts) self.c.execute(query) self.db.commit()"," def add_consumption_data_row(self, ts, energy_used, power_used): if power_used > 0: query = ''' INSERT OR IGNORE INTO Consumption ( TimeStamp, EnergyUsed, PowerUsed ) VALUES ( ?, ?, ? ); ''' self.c.execute(query, (ts, 0, 0)) query = ''' UPDATE Consumption SET EnergyUsed = EnergyUsed + ?, PowerUsed = PowerUsed + ? WHERE TimeStamp=?; ''' self.c.execute(query, (energy_used, power_used, ts)) self.db.commit()","{'deleted': [{'line_no': 11, 'char_start': 326, 'char_end': 350, 'line': ' %s,\n'}, {'line_no': 12, 'char_start': 350, 'char_end': 374, 'line': ' %s,\n'}, {'line_no': 13, 'char_start': 374, 'char_end': 397, 'line': ' %s\n'}, {'line_no': 15, 'char_start': 416, 'char_end': 445, 'line': "" ''' % (ts, 0, 0)\n""}, {'line_no': 16, 'char_start': 445, 'char_end': 479, 'line': ' self.c.execute(query)\n'}, {'line_no': 20, 'char_start': 544, 'char_end': 590, 'line': ' EnergyUsed = EnergyUsed + %s,\n'}, {'line_no': 21, 'char_start': 590, 'char_end': 633, 'line': ' PowerUsed = PowerUsed + %s\n'}, {'line_no': 22, 'char_start': 633, 'char_end': 671, 'line': ' WHERE TimeStamp = %s;\n'}, {'line_no': 23, 'char_start': 671, 'char_end': 719, 'line': "" ''' % (energy_used, power_used, ts)\n""}, {'line_no': 25, 'char_start': 720, 'char_end': 754, 'line': ' self.c.execute(query)\n'}], 'added': [{'line_no': 11, 'char_start': 326, 'char_end': 349, 'line': ' ?,\n'}, {'line_no': 12, 'char_start': 349, 'char_end': 372, 'line': ' ?,\n'}, {'line_no': 13, 'char_start': 372, 'char_end': 394, 'line': ' ?\n'}, {'line_no': 15, 'char_start': 413, 'char_end': 429, 'line': "" '''\n""}, {'line_no': 16, 'char_start': 429, 'char_end': 475, 'line': ' self.c.execute(query, (ts, 0, 0))\n'}, {'line_no': 20, 'char_start': 540, 'char_end': 585, 'line': ' EnergyUsed = EnergyUsed + ?,\n'}, {'line_no': 21, 'char_start': 585, 'char_end': 627, 'line': ' PowerUsed = PowerUsed + ?\n'}, {'line_no': 22, 'char_start': 627, 'char_end': 662, 'line': ' WHERE TimeStamp=?;\n'}, {'line_no': 23, 'char_start': 662, 'char_end': 678, 'line': "" '''\n""}, {'line_no': 25, 'char_start': 679, 'char_end': 744, 'line': ' self.c.execute(query, (energy_used, power_used, ts))\n'}]}","{'deleted': [{'char_start': 346, 'char_end': 348, 'chars': '%s'}, {'char_start': 370, 'char_end': 372, 'chars': '%s'}, {'char_start': 394, 'char_end': 396, 'chars': '%s'}, {'char_start': 431, 'char_end': 444, 'chars': ' % (ts, 0, 0)'}, {'char_start': 586, 'char_end': 588, 'chars': '%s'}, {'char_start': 630, 'char_end': 632, 'chars': '%s'}, {'char_start': 664, 'char_end': 665, 'chars': ' '}, {'char_start': 666, 'char_end': 669, 'chars': ' %s'}, {'char_start': 686, 'char_end': 718, 'chars': ' % (energy_used, power_used, ts)'}], 'added': [{'char_start': 346, 'char_end': 347, 'chars': '?'}, {'char_start': 369, 'char_end': 370, 'chars': '?'}, {'char_start': 392, 'char_end': 393, 'chars': '?'}, {'char_start': 461, 'char_end': 473, 'chars': ', (ts, 0, 0)'}, {'char_start': 582, 'char_end': 583, 'chars': '?'}, {'char_start': 625, 'char_end': 626, 'chars': '?'}, {'char_start': 659, 'char_end': 660, 'chars': '?'}, {'char_start': 711, 'char_end': 742, 'chars': ', (energy_used, power_used, ts)'}]}",github.com/philipptrenz/s0-bridge/commit/269b48caa05377b7c58c3e6d1622a4429cb5ba65,util/database.py,cwe-089,144 cwe-089,get_current_state,"def get_current_state(chat_id): settings = sqlite3.connect(os.path.abspath(os.path.dirname(__file__))+""\\bases\\settings.db"") conn = settings.cursor() conn.execute(""select * from users where chat_id = '"" + str(chat_id) + ""'"") name = conn.fetchone() if name != None: return name[4] else: return False settings.close()","def get_current_state(chat_id): settings = sqlite3.connect(os.path.abspath(os.path.dirname(__file__))+""\\bases\\settings.db"") conn = settings.cursor() conn.execute(""select * from users where chat_id = ?"", (str(chat_id),)) name = conn.fetchone() if name != None: return name[4] else: return False settings.close()","{'deleted': [{'line_no': 4, 'char_start': 159, 'char_end': 238, 'line': ' conn.execute(""select * from users where chat_id = \'"" + str(chat_id) + ""\'"")\n'}], 'added': [{'line_no': 4, 'char_start': 159, 'char_end': 234, 'line': ' conn.execute(""select * from users where chat_id = ?"", (str(chat_id),))\n'}]}","{'deleted': [{'char_start': 213, 'char_end': 214, 'chars': ""'""}, {'char_start': 215, 'char_end': 217, 'chars': ' +'}, {'char_start': 230, 'char_end': 236, 'chars': ' + ""\'""'}], 'added': [{'char_start': 213, 'char_end': 214, 'chars': '?'}, {'char_start': 215, 'char_end': 216, 'chars': ','}, {'char_start': 217, 'char_end': 218, 'chars': '('}, {'char_start': 230, 'char_end': 232, 'chars': ',)'}]}",github.com/lissrbay/codeforces_bot/commit/cc7f5143445a0030b1149ac60a65b1b1b9c92a90,bot.py,cwe-089,85 cwe-125,SyncExifProfile,"MagickBooleanType SyncExifProfile(Image *image,StringInfo *profile) { #define MaxDirectoryStack 16 #define EXIF_DELIMITER ""\n"" #define EXIF_NUM_FORMATS 12 #define TAG_EXIF_OFFSET 0x8769 #define TAG_INTEROP_OFFSET 0xa005 typedef struct _DirectoryInfo { unsigned char *directory; size_t entry; } DirectoryInfo; DirectoryInfo directory_stack[MaxDirectoryStack]; EndianType endian; size_t entry, length, number_entries; ssize_t id, level, offset; static int format_bytes[] = {0, 1, 1, 2, 4, 8, 1, 1, 2, 4, 8, 4, 8}; unsigned char *directory, *exif; /* Set EXIF resolution tag. */ length=GetStringInfoLength(profile); exif=GetStringInfoDatum(profile); if (length < 16) return(MagickFalse); id=(ssize_t) ReadProfileShort(LSBEndian,exif); if ((id != 0x4949) && (id != 0x4D4D)) { while (length != 0) { if (ReadProfileByte(&exif,&length) != 0x45) continue; if (ReadProfileByte(&exif,&length) != 0x78) continue; if (ReadProfileByte(&exif,&length) != 0x69) continue; if (ReadProfileByte(&exif,&length) != 0x66) continue; if (ReadProfileByte(&exif,&length) != 0x00) continue; if (ReadProfileByte(&exif,&length) != 0x00) continue; break; } if (length < 16) return(MagickFalse); id=(ssize_t) ReadProfileShort(LSBEndian,exif); } endian=LSBEndian; if (id == 0x4949) endian=LSBEndian; else if (id == 0x4D4D) endian=MSBEndian; else return(MagickFalse); if (ReadProfileShort(endian,exif+2) != 0x002a) return(MagickFalse); /* This the offset to the first IFD. */ offset=(ssize_t) ReadProfileLong(endian,exif+4); if ((offset < 0) || (size_t) offset >= length) return(MagickFalse); directory=exif+offset; level=0; entry=0; do { if (level > 0) { level--; directory=directory_stack[level].directory; entry=directory_stack[level].entry; } if ((directory < exif) || (directory > (exif+length-2))) break; /* Determine how many entries there are in the current IFD. */ number_entries=ReadProfileShort(endian,directory); for ( ; entry < number_entries; entry++) { int components; register unsigned char *p, *q; size_t number_bytes; ssize_t format, tag_value; q=(unsigned char *) (directory+2+(12*entry)); if (q > (exif+length-12)) break; /* corrupt EXIF */ tag_value=(ssize_t) ReadProfileShort(endian,q); format=(ssize_t) ReadProfileShort(endian,q+2); if ((format-1) >= EXIF_NUM_FORMATS) break; components=(ssize_t) ReadProfileLong(endian,q+4); if (components < 0) break; /* corrupt EXIF */ number_bytes=(size_t) components*format_bytes[format]; if ((ssize_t) number_bytes < components) break; /* prevent overflow */ if (number_bytes <= 4) p=q+8; else { /* The directory entry contains an offset. */ offset=(ssize_t) ReadProfileLong(endian,q+8); if ((size_t) (offset+number_bytes) > length) continue; if (~length < number_bytes) continue; /* prevent overflow */ p=(unsigned char *) (exif+offset); } switch (tag_value) { case 0x011a: { (void) WriteProfileLong(endian,(size_t) (image->resolution.x+0.5),p); (void) WriteProfileLong(endian,1UL,p+4); break; } case 0x011b: { (void) WriteProfileLong(endian,(size_t) (image->resolution.y+0.5),p); (void) WriteProfileLong(endian,1UL,p+4); break; } case 0x0112: { if (number_bytes == 4) { (void) WriteProfileLong(endian,(size_t) image->orientation,p); break; } (void) WriteProfileShort(endian,(unsigned short) image->orientation, p); break; } case 0x0128: { if (number_bytes == 4) { (void) WriteProfileLong(endian,(size_t) (image->units+1),p); break; } (void) WriteProfileShort(endian,(unsigned short) (image->units+1),p); break; } default: break; } if ((tag_value == TAG_EXIF_OFFSET) || (tag_value == TAG_INTEROP_OFFSET)) { offset=(ssize_t) ReadProfileLong(endian,p); if (((size_t) offset < length) && (level < (MaxDirectoryStack-2))) { directory_stack[level].directory=directory; entry++; directory_stack[level].entry=entry; level++; directory_stack[level].directory=exif+offset; directory_stack[level].entry=0; level++; if ((directory+2+(12*number_entries)) > (exif+length)) break; offset=(ssize_t) ReadProfileLong(endian,directory+2+(12* number_entries)); if ((offset != 0) && ((size_t) offset < length) && (level < (MaxDirectoryStack-2))) { directory_stack[level].directory=exif+offset; directory_stack[level].entry=0; level++; } } break; } } } while (level > 0); return(MagickTrue); }","MagickBooleanType SyncExifProfile(Image *image,StringInfo *profile) { #define MaxDirectoryStack 16 #define EXIF_DELIMITER ""\n"" #define EXIF_NUM_FORMATS 12 #define TAG_EXIF_OFFSET 0x8769 #define TAG_INTEROP_OFFSET 0xa005 typedef struct _DirectoryInfo { unsigned char *directory; size_t entry; } DirectoryInfo; DirectoryInfo directory_stack[MaxDirectoryStack]; EndianType endian; size_t entry, length, number_entries; ssize_t id, level, offset; static int format_bytes[] = {0, 1, 1, 2, 4, 8, 1, 1, 2, 4, 8, 4, 8}; unsigned char *directory, *exif; /* Set EXIF resolution tag. */ length=GetStringInfoLength(profile); exif=GetStringInfoDatum(profile); if (length < 16) return(MagickFalse); id=(ssize_t) ReadProfileShort(LSBEndian,exif); if ((id != 0x4949) && (id != 0x4D4D)) { while (length != 0) { if (ReadProfileByte(&exif,&length) != 0x45) continue; if (ReadProfileByte(&exif,&length) != 0x78) continue; if (ReadProfileByte(&exif,&length) != 0x69) continue; if (ReadProfileByte(&exif,&length) != 0x66) continue; if (ReadProfileByte(&exif,&length) != 0x00) continue; if (ReadProfileByte(&exif,&length) != 0x00) continue; break; } if (length < 16) return(MagickFalse); id=(ssize_t) ReadProfileShort(LSBEndian,exif); } endian=LSBEndian; if (id == 0x4949) endian=LSBEndian; else if (id == 0x4D4D) endian=MSBEndian; else return(MagickFalse); if (ReadProfileShort(endian,exif+2) != 0x002a) return(MagickFalse); /* This the offset to the first IFD. */ offset=(ssize_t) ReadProfileLong(endian,exif+4); if ((offset < 0) || (size_t) offset >= length) return(MagickFalse); directory=exif+offset; level=0; entry=0; do { if (level > 0) { level--; directory=directory_stack[level].directory; entry=directory_stack[level].entry; } if ((directory < exif) || (directory > (exif+length-2))) break; /* Determine how many entries there are in the current IFD. */ number_entries=ReadProfileShort(endian,directory); for ( ; entry < number_entries; entry++) { int components; register unsigned char *p, *q; size_t number_bytes; ssize_t format, tag_value; q=(unsigned char *) (directory+2+(12*entry)); if (q > (exif+length-12)) break; /* corrupt EXIF */ tag_value=(ssize_t) ReadProfileShort(endian,q); format=(ssize_t) ReadProfileShort(endian,q+2); if ((format < 0) || ((format-1) >= EXIF_NUM_FORMATS)) break; components=(ssize_t) ReadProfileLong(endian,q+4); if (components < 0) break; /* corrupt EXIF */ number_bytes=(size_t) components*format_bytes[format]; if ((ssize_t) number_bytes < components) break; /* prevent overflow */ if (number_bytes <= 4) p=q+8; else { /* The directory entry contains an offset. */ offset=(ssize_t) ReadProfileLong(endian,q+8); if ((size_t) (offset+number_bytes) > length) continue; if (~length < number_bytes) continue; /* prevent overflow */ p=(unsigned char *) (exif+offset); } switch (tag_value) { case 0x011a: { (void) WriteProfileLong(endian,(size_t) (image->resolution.x+0.5),p); (void) WriteProfileLong(endian,1UL,p+4); break; } case 0x011b: { (void) WriteProfileLong(endian,(size_t) (image->resolution.y+0.5),p); (void) WriteProfileLong(endian,1UL,p+4); break; } case 0x0112: { if (number_bytes == 4) { (void) WriteProfileLong(endian,(size_t) image->orientation,p); break; } (void) WriteProfileShort(endian,(unsigned short) image->orientation, p); break; } case 0x0128: { if (number_bytes == 4) { (void) WriteProfileLong(endian,(size_t) (image->units+1),p); break; } (void) WriteProfileShort(endian,(unsigned short) (image->units+1),p); break; } default: break; } if ((tag_value == TAG_EXIF_OFFSET) || (tag_value == TAG_INTEROP_OFFSET)) { offset=(ssize_t) ReadProfileLong(endian,p); if (((size_t) offset < length) && (level < (MaxDirectoryStack-2))) { directory_stack[level].directory=directory; entry++; directory_stack[level].entry=entry; level++; directory_stack[level].directory=exif+offset; directory_stack[level].entry=0; level++; if ((directory+2+(12*number_entries)) > (exif+length)) break; offset=(ssize_t) ReadProfileLong(endian,directory+2+(12* number_entries)); if ((offset != 0) && ((size_t) offset < length) && (level < (MaxDirectoryStack-2))) { directory_stack[level].directory=exif+offset; directory_stack[level].entry=0; level++; } } break; } } } while (level > 0); return(MagickTrue); }","{'deleted': [{'line_no': 125, 'char_start': 2750, 'char_end': 2792, 'line': ' if ((format-1) >= EXIF_NUM_FORMATS)\n'}], 'added': [{'line_no': 125, 'char_start': 2750, 'char_end': 2810, 'line': ' if ((format < 0) || ((format-1) >= EXIF_NUM_FORMATS))\n'}]}","{'deleted': [], 'added': [{'char_start': 2767, 'char_end': 2784, 'chars': ' < 0) || ((format'}, {'char_start': 2807, 'char_end': 2808, 'chars': ')'}]}",github.com/ImageMagick/ImageMagick/commit/a7bb158b7bedd1449a34432feb3a67c8f1873bfa,MagickCore/profile.c,cwe-125,1540 cwe-125,usb_get_bos_descriptor,"int usb_get_bos_descriptor(struct usb_device *dev) { struct device *ddev = &dev->dev; struct usb_bos_descriptor *bos; struct usb_dev_cap_header *cap; unsigned char *buffer; int length, total_len, num, i; int ret; bos = kzalloc(sizeof(struct usb_bos_descriptor), GFP_KERNEL); if (!bos) return -ENOMEM; /* Get BOS descriptor */ ret = usb_get_descriptor(dev, USB_DT_BOS, 0, bos, USB_DT_BOS_SIZE); if (ret < USB_DT_BOS_SIZE) { dev_err(ddev, ""unable to get BOS descriptor\n""); if (ret >= 0) ret = -ENOMSG; kfree(bos); return ret; } length = bos->bLength; total_len = le16_to_cpu(bos->wTotalLength); num = bos->bNumDeviceCaps; kfree(bos); if (total_len < length) return -EINVAL; dev->bos = kzalloc(sizeof(struct usb_host_bos), GFP_KERNEL); if (!dev->bos) return -ENOMEM; /* Now let's get the whole BOS descriptor set */ buffer = kzalloc(total_len, GFP_KERNEL); if (!buffer) { ret = -ENOMEM; goto err; } dev->bos->desc = (struct usb_bos_descriptor *)buffer; ret = usb_get_descriptor(dev, USB_DT_BOS, 0, buffer, total_len); if (ret < total_len) { dev_err(ddev, ""unable to get BOS descriptor set\n""); if (ret >= 0) ret = -ENOMSG; goto err; } total_len -= length; for (i = 0; i < num; i++) { buffer += length; cap = (struct usb_dev_cap_header *)buffer; length = cap->bLength; if (total_len < length) break; total_len -= length; if (cap->bDescriptorType != USB_DT_DEVICE_CAPABILITY) { dev_warn(ddev, ""descriptor type invalid, skip\n""); continue; } switch (cap->bDevCapabilityType) { case USB_CAP_TYPE_WIRELESS_USB: /* Wireless USB cap descriptor is handled by wusb */ break; case USB_CAP_TYPE_EXT: dev->bos->ext_cap = (struct usb_ext_cap_descriptor *)buffer; break; case USB_SS_CAP_TYPE: dev->bos->ss_cap = (struct usb_ss_cap_descriptor *)buffer; break; case USB_SSP_CAP_TYPE: dev->bos->ssp_cap = (struct usb_ssp_cap_descriptor *)buffer; break; case CONTAINER_ID_TYPE: dev->bos->ss_id = (struct usb_ss_container_id_descriptor *)buffer; break; case USB_PTM_CAP_TYPE: dev->bos->ptm_cap = (struct usb_ptm_cap_descriptor *)buffer; default: break; } } return 0; err: usb_release_bos_descriptor(dev); return ret; }","int usb_get_bos_descriptor(struct usb_device *dev) { struct device *ddev = &dev->dev; struct usb_bos_descriptor *bos; struct usb_dev_cap_header *cap; unsigned char *buffer; int length, total_len, num, i; int ret; bos = kzalloc(sizeof(struct usb_bos_descriptor), GFP_KERNEL); if (!bos) return -ENOMEM; /* Get BOS descriptor */ ret = usb_get_descriptor(dev, USB_DT_BOS, 0, bos, USB_DT_BOS_SIZE); if (ret < USB_DT_BOS_SIZE) { dev_err(ddev, ""unable to get BOS descriptor\n""); if (ret >= 0) ret = -ENOMSG; kfree(bos); return ret; } length = bos->bLength; total_len = le16_to_cpu(bos->wTotalLength); num = bos->bNumDeviceCaps; kfree(bos); if (total_len < length) return -EINVAL; dev->bos = kzalloc(sizeof(struct usb_host_bos), GFP_KERNEL); if (!dev->bos) return -ENOMEM; /* Now let's get the whole BOS descriptor set */ buffer = kzalloc(total_len, GFP_KERNEL); if (!buffer) { ret = -ENOMEM; goto err; } dev->bos->desc = (struct usb_bos_descriptor *)buffer; ret = usb_get_descriptor(dev, USB_DT_BOS, 0, buffer, total_len); if (ret < total_len) { dev_err(ddev, ""unable to get BOS descriptor set\n""); if (ret >= 0) ret = -ENOMSG; goto err; } total_len -= length; for (i = 0; i < num; i++) { buffer += length; cap = (struct usb_dev_cap_header *)buffer; if (total_len < sizeof(*cap) || total_len < cap->bLength) { dev->bos->desc->bNumDeviceCaps = i; break; } length = cap->bLength; total_len -= length; if (cap->bDescriptorType != USB_DT_DEVICE_CAPABILITY) { dev_warn(ddev, ""descriptor type invalid, skip\n""); continue; } switch (cap->bDevCapabilityType) { case USB_CAP_TYPE_WIRELESS_USB: /* Wireless USB cap descriptor is handled by wusb */ break; case USB_CAP_TYPE_EXT: dev->bos->ext_cap = (struct usb_ext_cap_descriptor *)buffer; break; case USB_SS_CAP_TYPE: dev->bos->ss_cap = (struct usb_ss_cap_descriptor *)buffer; break; case USB_SSP_CAP_TYPE: dev->bos->ssp_cap = (struct usb_ssp_cap_descriptor *)buffer; break; case CONTAINER_ID_TYPE: dev->bos->ss_id = (struct usb_ss_container_id_descriptor *)buffer; break; case USB_PTM_CAP_TYPE: dev->bos->ptm_cap = (struct usb_ptm_cap_descriptor *)buffer; default: break; } } return 0; err: usb_release_bos_descriptor(dev); return ret; }","{'deleted': [{'line_no': 55, 'char_start': 1313, 'char_end': 1338, 'line': '\t\tlength = cap->bLength;\n'}, {'line_no': 57, 'char_start': 1339, 'char_end': 1365, 'line': '\t\tif (total_len < length)\n'}], 'added': [{'line_no': 56, 'char_start': 1314, 'char_end': 1376, 'line': '\t\tif (total_len < sizeof(*cap) || total_len < cap->bLength) {\n'}, {'line_no': 57, 'char_start': 1376, 'char_end': 1415, 'line': '\t\t\tdev->bos->desc->bNumDeviceCaps = i;\n'}, {'line_no': 59, 'char_start': 1425, 'char_end': 1429, 'line': '\t\t}\n'}, {'line_no': 60, 'char_start': 1429, 'char_end': 1454, 'line': '\t\tlength = cap->bLength;\n'}]}","{'deleted': [{'char_start': 1318, 'char_end': 1321, 'chars': 'gth'}, {'char_start': 1322, 'char_end': 1323, 'chars': '='}, {'char_start': 1327, 'char_end': 1343, 'chars': '->bLength;\n\n\t\tif'}, {'char_start': 1344, 'char_end': 1345, 'chars': '('}, {'char_start': 1357, 'char_end': 1358, 'chars': 'l'}], 'added': [{'char_start': 1313, 'char_end': 1314, 'chars': '\n'}, {'char_start': 1316, 'char_end': 1326, 'chars': 'if (total_'}, {'char_start': 1330, 'char_end': 1331, 'chars': '<'}, {'char_start': 1332, 'char_end': 1340, 'chars': 'sizeof(*'}, {'char_start': 1343, 'char_end': 1347, 'chars': ') ||'}, {'char_start': 1360, 'char_end': 1367, 'chars': 'cap->bL'}, {'char_start': 1373, 'char_end': 1414, 'chars': ' {\n\t\t\tdev->bos->desc->bNumDeviceCaps = i;'}, {'char_start': 1423, 'char_end': 1452, 'chars': ';\n\t\t}\n\t\tlength = cap->bLength'}]}",github.com/torvalds/linux/commit/1c0edc3633b56000e18d82fc241e3995ca18a69e,drivers/usb/core/config.c,cwe-125,667 cwe-089,stats,"@bot.message_handler(commands=['stats']) def stats(message): settings = sqlite3.connect(os.path.abspath(os.path.dirname(__file__)) + ""\\bases\\settings.db"") conn = settings.cursor() conn.execute(""select * from users where chat_id = '"" + str(message.chat.id) + ""'"") name = conn.fetchone() settings.close() if name != None: bases.update.update_user(name[1], name[0], name[2]) bases.problem.create_text_stats(name[1]) img = open(os.path.abspath(os.path.dirname(__file__)) + ""\\bases\\users\\"" + name[1] + "".png"", ""rb"") bot.send_photo(message.chat.id, img) img.close() if bases.problem.create_stats_picture(name[1]): bot.send_message(message.chat.id, ""Sorry, you haven't solved tasks."") return 0 img = open(os.path.abspath(os.path.dirname(__file__)) + ""\\bases\\users\\"" + name[1] + "".png"", ""rb"") bot.send_photo(message.chat.id, img) img.close() else: bot.send_message(message.chat.id, ""You should login before getting statistic."")","@bot.message_handler(commands=['stats']) def stats(message): settings = sqlite3.connect(os.path.abspath(os.path.dirname(__file__)) + ""\\bases\\settings.db"") conn = settings.cursor() conn.execute(""select * from users where chat_id = ?"", (str(message.chat.id),)) name = conn.fetchone() settings.close() if name != None: bases.update.update_user(name[1], name[0], name[2]) bases.problem.create_text_stats(name[1]) img = open(os.path.abspath(os.path.dirname(__file__)) + ""\\bases\\users\\"" + name[1] + "".png"", ""rb"") bot.send_photo(message.chat.id, img) img.close() if bases.problem.create_stats_picture(name[1]): bot.send_message(message.chat.id, ""Sorry, you haven't solved tasks."") return 0 img = open(os.path.abspath(os.path.dirname(__file__)) + ""\\bases\\users\\"" + name[1] + "".png"", ""rb"") bot.send_photo(message.chat.id, img) img.close() else: bot.send_message(message.chat.id, ""You should login before getting statistic."")","{'deleted': [{'line_no': 5, 'char_start': 190, 'char_end': 277, 'line': ' conn.execute(""select * from users where chat_id = \'"" + str(message.chat.id) + ""\'"")\n'}], 'added': [{'line_no': 5, 'char_start': 190, 'char_end': 273, 'line': ' conn.execute(""select * from users where chat_id = ?"", (str(message.chat.id),))\n'}]}","{'deleted': [{'char_start': 244, 'char_end': 245, 'chars': ""'""}, {'char_start': 246, 'char_end': 248, 'chars': ' +'}, {'char_start': 269, 'char_end': 275, 'chars': ' + ""\'""'}], 'added': [{'char_start': 244, 'char_end': 245, 'chars': '?'}, {'char_start': 246, 'char_end': 247, 'chars': ','}, {'char_start': 248, 'char_end': 249, 'chars': '('}, {'char_start': 269, 'char_end': 271, 'chars': ',)'}]}",github.com/lissrbay/codeforces_bot/commit/cc7f5143445a0030b1149ac60a65b1b1b9c92a90,bot.py,cwe-089,247 cwe-787,input_csi_dispatch_sgr_colon,"input_csi_dispatch_sgr_colon(struct input_ctx *ictx, u_int i) { struct grid_cell *gc = &ictx->cell.cell; char *s = ictx->param_list[i].str, *copy, *ptr, *out; int p[8]; u_int n; const char *errstr; for (n = 0; n < nitems(p); n++) p[n] = -1; n = 0; ptr = copy = xstrdup(s); while ((out = strsep(&ptr, "":"")) != NULL) { if (*out != '\0') { p[n++] = strtonum(out, 0, INT_MAX, &errstr); if (errstr != NULL || n == nitems(p)) { free(copy); return; } } else n++; log_debug(""%s: %u = %d"", __func__, n - 1, p[n - 1]); } free(copy); if (n == 0) return; if (p[0] == 4) { if (n != 2) return; switch (p[1]) { case 0: gc->attr &= ~GRID_ATTR_ALL_UNDERSCORE; break; case 1: gc->attr &= ~GRID_ATTR_ALL_UNDERSCORE; gc->attr |= GRID_ATTR_UNDERSCORE; break; case 2: gc->attr &= ~GRID_ATTR_ALL_UNDERSCORE; gc->attr |= GRID_ATTR_UNDERSCORE_2; break; case 3: gc->attr &= ~GRID_ATTR_ALL_UNDERSCORE; gc->attr |= GRID_ATTR_UNDERSCORE_3; break; case 4: gc->attr &= ~GRID_ATTR_ALL_UNDERSCORE; gc->attr |= GRID_ATTR_UNDERSCORE_4; break; case 5: gc->attr &= ~GRID_ATTR_ALL_UNDERSCORE; gc->attr |= GRID_ATTR_UNDERSCORE_5; break; } return; } if (n < 2 || (p[0] != 38 && p[0] != 48 && p[0] != 58)) return; switch (p[1]) { case 2: if (n < 3) break; if (n == 5) i = 2; else i = 3; if (n < i + 3) break; input_csi_dispatch_sgr_rgb_do(ictx, p[0], p[i], p[i + 1], p[i + 2]); break; case 5: if (n < 3) break; input_csi_dispatch_sgr_256_do(ictx, p[0], p[2]); break; } }","input_csi_dispatch_sgr_colon(struct input_ctx *ictx, u_int i) { struct grid_cell *gc = &ictx->cell.cell; char *s = ictx->param_list[i].str, *copy, *ptr, *out; int p[8]; u_int n; const char *errstr; for (n = 0; n < nitems(p); n++) p[n] = -1; n = 0; ptr = copy = xstrdup(s); while ((out = strsep(&ptr, "":"")) != NULL) { if (*out != '\0') { p[n++] = strtonum(out, 0, INT_MAX, &errstr); if (errstr != NULL || n == nitems(p)) { free(copy); return; } } else { n++; if (n == nitems(p)) { free(copy); return; } } log_debug(""%s: %u = %d"", __func__, n - 1, p[n - 1]); } free(copy); if (n == 0) return; if (p[0] == 4) { if (n != 2) return; switch (p[1]) { case 0: gc->attr &= ~GRID_ATTR_ALL_UNDERSCORE; break; case 1: gc->attr &= ~GRID_ATTR_ALL_UNDERSCORE; gc->attr |= GRID_ATTR_UNDERSCORE; break; case 2: gc->attr &= ~GRID_ATTR_ALL_UNDERSCORE; gc->attr |= GRID_ATTR_UNDERSCORE_2; break; case 3: gc->attr &= ~GRID_ATTR_ALL_UNDERSCORE; gc->attr |= GRID_ATTR_UNDERSCORE_3; break; case 4: gc->attr &= ~GRID_ATTR_ALL_UNDERSCORE; gc->attr |= GRID_ATTR_UNDERSCORE_4; break; case 5: gc->attr &= ~GRID_ATTR_ALL_UNDERSCORE; gc->attr |= GRID_ATTR_UNDERSCORE_5; break; } return; } if (n < 2 || (p[0] != 38 && p[0] != 48 && p[0] != 58)) return; switch (p[1]) { case 2: if (n < 3) break; if (n == 5) i = 2; else i = 3; if (n < i + 3) break; input_csi_dispatch_sgr_rgb_do(ictx, p[0], p[i], p[i + 1], p[i + 2]); break; case 5: if (n < 3) break; input_csi_dispatch_sgr_256_do(ictx, p[0], p[2]); break; } }","{'deleted': [{'line_no': 21, 'char_start': 485, 'char_end': 494, 'line': '\t\t} else\n'}], 'added': [{'line_no': 21, 'char_start': 485, 'char_end': 496, 'line': '\t\t} else {\n'}, {'line_no': 23, 'char_start': 504, 'char_end': 529, 'line': '\t\t\tif (n == nitems(p)) {\n'}, {'line_no': 24, 'char_start': 529, 'char_end': 545, 'line': '\t\t\t\tfree(copy);\n'}, {'line_no': 25, 'char_start': 545, 'char_end': 557, 'line': '\t\t\t\treturn;\n'}, {'line_no': 26, 'char_start': 557, 'char_end': 562, 'line': '\t\t\t}\n'}, {'line_no': 27, 'char_start': 562, 'char_end': 566, 'line': '\t\t}\n'}]}","{'deleted': [], 'added': [{'char_start': 493, 'char_end': 495, 'chars': ' {'}, {'char_start': 503, 'char_end': 565, 'chars': '\n\t\t\tif (n == nitems(p)) {\n\t\t\t\tfree(copy);\n\t\t\t\treturn;\n\t\t\t}\n\t\t}'}]}",github.com/tmux/tmux/commit/a868bacb46e3c900530bed47a1c6f85b0fbe701c,input.c,cwe-787,636 cwe-416,__ns_get_path,"static void *__ns_get_path(struct path *path, struct ns_common *ns) { struct vfsmount *mnt = nsfs_mnt; struct qstr qname = { .name = """", }; struct dentry *dentry; struct inode *inode; unsigned long d; rcu_read_lock(); d = atomic_long_read(&ns->stashed); if (!d) goto slow; dentry = (struct dentry *)d; if (!lockref_get_not_dead(&dentry->d_lockref)) goto slow; rcu_read_unlock(); ns->ops->put(ns); got_it: path->mnt = mntget(mnt); path->dentry = dentry; return NULL; slow: rcu_read_unlock(); inode = new_inode_pseudo(mnt->mnt_sb); if (!inode) { ns->ops->put(ns); return ERR_PTR(-ENOMEM); } inode->i_ino = ns->inum; inode->i_mtime = inode->i_atime = inode->i_ctime = current_time(inode); inode->i_flags |= S_IMMUTABLE; inode->i_mode = S_IFREG | S_IRUGO; inode->i_fop = &ns_file_operations; inode->i_private = ns; dentry = d_alloc_pseudo(mnt->mnt_sb, &qname); if (!dentry) { iput(inode); return ERR_PTR(-ENOMEM); } d_instantiate(dentry, inode); dentry->d_fsdata = (void *)ns->ops; d = atomic_long_cmpxchg(&ns->stashed, 0, (unsigned long)dentry); if (d) { d_delete(dentry); /* make sure ->d_prune() does nothing */ dput(dentry); cpu_relax(); return ERR_PTR(-EAGAIN); } goto got_it; }","static void *__ns_get_path(struct path *path, struct ns_common *ns) { struct vfsmount *mnt = nsfs_mnt; struct qstr qname = { .name = """", }; struct dentry *dentry; struct inode *inode; unsigned long d; rcu_read_lock(); d = atomic_long_read(&ns->stashed); if (!d) goto slow; dentry = (struct dentry *)d; if (!lockref_get_not_dead(&dentry->d_lockref)) goto slow; rcu_read_unlock(); ns->ops->put(ns); got_it: path->mnt = mntget(mnt); path->dentry = dentry; return NULL; slow: rcu_read_unlock(); inode = new_inode_pseudo(mnt->mnt_sb); if (!inode) { ns->ops->put(ns); return ERR_PTR(-ENOMEM); } inode->i_ino = ns->inum; inode->i_mtime = inode->i_atime = inode->i_ctime = current_time(inode); inode->i_flags |= S_IMMUTABLE; inode->i_mode = S_IFREG | S_IRUGO; inode->i_fop = &ns_file_operations; inode->i_private = ns; dentry = d_alloc_pseudo(mnt->mnt_sb, &qname); if (!dentry) { iput(inode); return ERR_PTR(-ENOMEM); } d_instantiate(dentry, inode); dentry->d_flags |= DCACHE_RCUACCESS; dentry->d_fsdata = (void *)ns->ops; d = atomic_long_cmpxchg(&ns->stashed, 0, (unsigned long)dentry); if (d) { d_delete(dentry); /* make sure ->d_prune() does nothing */ dput(dentry); cpu_relax(); return ERR_PTR(-EAGAIN); } goto got_it; }","{'deleted': [], 'added': [{'line_no': 42, 'char_start': 985, 'char_end': 1023, 'line': '\tdentry->d_flags |= DCACHE_RCUACCESS;\n'}]}","{'deleted': [], 'added': [{'char_start': 997, 'char_end': 1035, 'chars': 'lags |= DCACHE_RCUACCESS;\n\tdentry->d_f'}]}",github.com/torvalds/linux/commit/073c516ff73557a8f7315066856c04b50383ac34,fs/nsfs.c,cwe-416,399 cwe-125,WriteTIFFImage,"static MagickBooleanType WriteTIFFImage(const ImageInfo *image_info, Image *image) { const char *mode, *option; CompressionType compression; EndianType endian_type; MagickBooleanType debug, status; MagickOffsetType scene; QuantumInfo *quantum_info; QuantumType quantum_type; register ssize_t i; size_t imageListLength; ssize_t y; TIFF *tiff; TIFFInfo tiff_info; uint16 bits_per_sample, compress_tag, endian, photometric, predictor; unsigned char *pixels; /* Open TIFF file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),""%s"",image->filename); status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception); if (status == MagickFalse) return(status); (void) SetMagickThreadValue(tiff_exception,&image->exception); endian_type=UndefinedEndian; option=GetImageOption(image_info,""tiff:endian""); if (option != (const char *) NULL) { if (LocaleNCompare(option,""msb"",3) == 0) endian_type=MSBEndian; if (LocaleNCompare(option,""lsb"",3) == 0) endian_type=LSBEndian;; } switch (endian_type) { case LSBEndian: mode=""wl""; break; case MSBEndian: mode=""wb""; break; default: mode=""w""; break; } #if defined(TIFF_VERSION_BIG) if (LocaleCompare(image_info->magick,""TIFF64"") == 0) switch (endian_type) { case LSBEndian: mode=""wl8""; break; case MSBEndian: mode=""wb8""; break; default: mode=""w8""; break; } #endif tiff=TIFFClientOpen(image->filename,mode,(thandle_t) image,TIFFReadBlob, TIFFWriteBlob,TIFFSeekBlob,TIFFCloseBlob,TIFFGetBlobSize,TIFFMapBlob, TIFFUnmapBlob); if (tiff == (TIFF *) NULL) return(MagickFalse); if (image->exception.severity > ErrorException) { TIFFClose(tiff); return(MagickFalse); } (void) DeleteImageProfile(image,""tiff:37724""); scene=0; debug=IsEventLogging(); (void) debug; imageListLength=GetImageListLength(image); do { /* Initialize TIFF fields. */ if ((image_info->type != UndefinedType) && (image_info->type != OptimizeType)) (void) SetImageType(image,image_info->type); compression=UndefinedCompression; if (image->compression != JPEGCompression) compression=image->compression; if (image_info->compression != UndefinedCompression) compression=image_info->compression; switch (compression) { case FaxCompression: case Group4Compression: { (void) SetImageType(image,BilevelType); (void) SetImageDepth(image,1); break; } case JPEGCompression: { (void) SetImageStorageClass(image,DirectClass); (void) SetImageDepth(image,8); break; } default: break; } quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,""MemoryAllocationFailed""); if ((image->storage_class != PseudoClass) && (image->depth >= 32) && (quantum_info->format == UndefinedQuantumFormat) && (IsHighDynamicRangeImage(image,&image->exception) != MagickFalse)) { status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat); if (status == MagickFalse) { quantum_info=DestroyQuantumInfo(quantum_info); ThrowWriterException(ResourceLimitError,""MemoryAllocationFailed""); } } if ((LocaleCompare(image_info->magick,""PTIF"") == 0) && (GetPreviousImageInList(image) != (Image *) NULL)) (void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_REDUCEDIMAGE); if ((image->columns != (uint32) image->columns) || (image->rows != (uint32) image->rows)) ThrowWriterException(ImageError,""WidthOrHeightExceedsLimit""); (void) TIFFSetField(tiff,TIFFTAG_IMAGELENGTH,(uint32) image->rows); (void) TIFFSetField(tiff,TIFFTAG_IMAGEWIDTH,(uint32) image->columns); switch (compression) { case FaxCompression: { compress_tag=COMPRESSION_CCITTFAX3; option=GetImageOption(image_info,""quantum:polarity""); if (option == (const char *) NULL) SetQuantumMinIsWhite(quantum_info,MagickTrue); break; } case Group4Compression: { compress_tag=COMPRESSION_CCITTFAX4; option=GetImageOption(image_info,""quantum:polarity""); if (option == (const char *) NULL) SetQuantumMinIsWhite(quantum_info,MagickTrue); break; } #if defined(COMPRESSION_JBIG) case JBIG1Compression: { compress_tag=COMPRESSION_JBIG; break; } #endif case JPEGCompression: { compress_tag=COMPRESSION_JPEG; break; } #if defined(COMPRESSION_LZMA) case LZMACompression: { compress_tag=COMPRESSION_LZMA; break; } #endif case LZWCompression: { compress_tag=COMPRESSION_LZW; break; } case RLECompression: { compress_tag=COMPRESSION_PACKBITS; break; } #if defined(COMPRESSION_WEBP) case WebPCompression: { compress_tag=COMPRESSION_WEBP; break; } #endif case ZipCompression: { compress_tag=COMPRESSION_ADOBE_DEFLATE; break; } #if defined(COMPRESSION_ZSTD) case ZstdCompression: { compress_tag=COMPRESSION_ZSTD; break; } #endif case NoCompression: default: { compress_tag=COMPRESSION_NONE; break; } } #if defined(MAGICKCORE_HAVE_TIFFISCODECCONFIGURED) || (TIFFLIB_VERSION > 20040919) if ((compress_tag != COMPRESSION_NONE) && (TIFFIsCODECConfigured(compress_tag) == 0)) { (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,""CompressionNotSupported"",""`%s'"",CommandOptionToMnemonic( MagickCompressOptions,(ssize_t) compression)); compress_tag=COMPRESSION_NONE; } #else switch (compress_tag) { #if defined(CCITT_SUPPORT) case COMPRESSION_CCITTFAX3: case COMPRESSION_CCITTFAX4: #endif #if defined(YCBCR_SUPPORT) && defined(JPEG_SUPPORT) case COMPRESSION_JPEG: #endif #if defined(LZMA_SUPPORT) && defined(COMPRESSION_LZMA) case COMPRESSION_LZMA: #endif #if defined(LZW_SUPPORT) case COMPRESSION_LZW: #endif #if defined(PACKBITS_SUPPORT) case COMPRESSION_PACKBITS: #endif #if defined(ZIP_SUPPORT) case COMPRESSION_ADOBE_DEFLATE: #endif case COMPRESSION_NONE: break; default: { (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,""CompressionNotSupported"",""`%s'"",CommandOptionToMnemonic( MagickCompressOptions,(ssize_t) compression)); compress_tag=COMPRESSION_NONE; break; } } #endif if (image->colorspace == CMYKColorspace) { photometric=PHOTOMETRIC_SEPARATED; (void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,4); (void) TIFFSetField(tiff,TIFFTAG_INKSET,INKSET_CMYK); } else { /* Full color TIFF raster. */ if (image->colorspace == LabColorspace) { photometric=PHOTOMETRIC_CIELAB; EncodeLabImage(image,&image->exception); } else if (image->colorspace == YCbCrColorspace) { photometric=PHOTOMETRIC_YCBCR; (void) TIFFSetField(tiff,TIFFTAG_YCBCRSUBSAMPLING,1,1); (void) SetImageStorageClass(image,DirectClass); (void) SetImageDepth(image,8); } else photometric=PHOTOMETRIC_RGB; (void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,3); if ((image_info->type != TrueColorType) && (image_info->type != TrueColorMatteType)) { if ((image_info->type != PaletteType) && (SetImageGray(image,&image->exception) != MagickFalse)) { photometric=(uint16) (quantum_info->min_is_white != MagickFalse ? PHOTOMETRIC_MINISWHITE : PHOTOMETRIC_MINISBLACK); (void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,1); if ((image->depth == 1) && (image->matte == MagickFalse)) SetImageMonochrome(image,&image->exception); } else if (image->storage_class == PseudoClass) { size_t depth; /* Colormapped TIFF raster. */ (void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,1); photometric=PHOTOMETRIC_PALETTE; depth=1; while ((GetQuantumRange(depth)+1) < image->colors) depth<<=1; status=SetQuantumDepth(image,quantum_info,depth); if (status == MagickFalse) ThrowWriterException(ResourceLimitError, ""MemoryAllocationFailed""); } } } (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_FILLORDER,&endian); if ((compress_tag == COMPRESSION_CCITTFAX3) || (compress_tag == COMPRESSION_CCITTFAX4)) { if ((photometric != PHOTOMETRIC_MINISWHITE) && (photometric != PHOTOMETRIC_MINISBLACK)) { compress_tag=COMPRESSION_NONE; endian=FILLORDER_MSB2LSB; } } option=GetImageOption(image_info,""tiff:fill-order""); if (option != (const char *) NULL) { if (LocaleNCompare(option,""msb"",3) == 0) endian=FILLORDER_MSB2LSB; if (LocaleNCompare(option,""lsb"",3) == 0) endian=FILLORDER_LSB2MSB; } (void) TIFFSetField(tiff,TIFFTAG_COMPRESSION,compress_tag); (void) TIFFSetField(tiff,TIFFTAG_FILLORDER,endian); (void) TIFFSetField(tiff,TIFFTAG_BITSPERSAMPLE,quantum_info->depth); if (image->matte != MagickFalse) { uint16 extra_samples, sample_info[1], samples_per_pixel; /* TIFF has a matte channel. */ extra_samples=1; sample_info[0]=EXTRASAMPLE_UNASSALPHA; option=GetImageOption(image_info,""tiff:alpha""); if (option != (const char *) NULL) { if (LocaleCompare(option,""associated"") == 0) sample_info[0]=EXTRASAMPLE_ASSOCALPHA; else if (LocaleCompare(option,""unspecified"") == 0) sample_info[0]=EXTRASAMPLE_UNSPECIFIED; } (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLESPERPIXEL, &samples_per_pixel); (void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,samples_per_pixel+1); (void) TIFFSetField(tiff,TIFFTAG_EXTRASAMPLES,extra_samples, &sample_info); if (sample_info[0] == EXTRASAMPLE_ASSOCALPHA) SetQuantumAlphaType(quantum_info,AssociatedQuantumAlpha); } (void) TIFFSetField(tiff,TIFFTAG_PHOTOMETRIC,photometric); switch (quantum_info->format) { case FloatingPointQuantumFormat: { (void) TIFFSetField(tiff,TIFFTAG_SAMPLEFORMAT,SAMPLEFORMAT_IEEEFP); (void) TIFFSetField(tiff,TIFFTAG_SMINSAMPLEVALUE,quantum_info->minimum); (void) TIFFSetField(tiff,TIFFTAG_SMAXSAMPLEVALUE,quantum_info->maximum); break; } case SignedQuantumFormat: { (void) TIFFSetField(tiff,TIFFTAG_SAMPLEFORMAT,SAMPLEFORMAT_INT); break; } case UnsignedQuantumFormat: { (void) TIFFSetField(tiff,TIFFTAG_SAMPLEFORMAT,SAMPLEFORMAT_UINT); break; } default: break; } (void) TIFFSetField(tiff,TIFFTAG_PLANARCONFIG,PLANARCONFIG_CONTIG); if (photometric == PHOTOMETRIC_RGB) if ((image_info->interlace == PlaneInterlace) || (image_info->interlace == PartitionInterlace)) (void) TIFFSetField(tiff,TIFFTAG_PLANARCONFIG,PLANARCONFIG_SEPARATE); predictor=0; switch (compress_tag) { case COMPRESSION_JPEG: { #if defined(JPEG_SUPPORT) if (image_info->quality != UndefinedCompressionQuality) (void) TIFFSetField(tiff,TIFFTAG_JPEGQUALITY,image_info->quality); (void) TIFFSetField(tiff,TIFFTAG_JPEGCOLORMODE,JPEGCOLORMODE_RAW); if (IssRGBCompatibleColorspace(image->colorspace) != MagickFalse) { const char *value; (void) TIFFSetField(tiff,TIFFTAG_JPEGCOLORMODE,JPEGCOLORMODE_RGB); if (image->colorspace == YCbCrColorspace) { const char *sampling_factor; GeometryInfo geometry_info; MagickStatusType flags; sampling_factor=(const char *) NULL; value=GetImageProperty(image,""jpeg:sampling-factor""); if (value != (char *) NULL) { sampling_factor=value; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" Input sampling-factors=%s"",sampling_factor); } if (image_info->sampling_factor != (char *) NULL) sampling_factor=image_info->sampling_factor; if (sampling_factor != (const char *) NULL) { flags=ParseGeometry(sampling_factor,&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=geometry_info.rho; (void) TIFFSetField(tiff,TIFFTAG_YCBCRSUBSAMPLING,(uint16) geometry_info.rho,(uint16) geometry_info.sigma); } } } (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE, &bits_per_sample); if (bits_per_sample == 12) (void) TIFFSetField(tiff,TIFFTAG_JPEGTABLESMODE,JPEGTABLESMODE_QUANT); #endif break; } case COMPRESSION_ADOBE_DEFLATE: { (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE, &bits_per_sample); if (((photometric == PHOTOMETRIC_RGB) || (photometric == PHOTOMETRIC_SEPARATED) || (photometric == PHOTOMETRIC_MINISBLACK)) && ((bits_per_sample == 8) || (bits_per_sample == 16))) predictor=PREDICTOR_HORIZONTAL; (void) TIFFSetField(tiff,TIFFTAG_ZIPQUALITY,(long) ( image_info->quality == UndefinedCompressionQuality ? 7 : MagickMin((ssize_t) image_info->quality/10,9))); break; } case COMPRESSION_CCITTFAX3: { /* Byte-aligned EOL. */ (void) TIFFSetField(tiff,TIFFTAG_GROUP3OPTIONS,4); break; } case COMPRESSION_CCITTFAX4: break; #if defined(LZMA_SUPPORT) && defined(COMPRESSION_LZMA) case COMPRESSION_LZMA: { if (((photometric == PHOTOMETRIC_RGB) || (photometric == PHOTOMETRIC_SEPARATED) || (photometric == PHOTOMETRIC_MINISBLACK)) && ((bits_per_sample == 8) || (bits_per_sample == 16))) predictor=PREDICTOR_HORIZONTAL; (void) TIFFSetField(tiff,TIFFTAG_LZMAPRESET,(long) ( image_info->quality == UndefinedCompressionQuality ? 7 : MagickMin((ssize_t) image_info->quality/10,9))); break; } #endif case COMPRESSION_LZW: { (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE, &bits_per_sample); if (((photometric == PHOTOMETRIC_RGB) || (photometric == PHOTOMETRIC_SEPARATED) || (photometric == PHOTOMETRIC_MINISBLACK)) && ((bits_per_sample == 8) || (bits_per_sample == 16))) predictor=PREDICTOR_HORIZONTAL; break; } #if defined(WEBP_SUPPORT) && defined(COMPRESSION_WEBP) case COMPRESSION_WEBP: { (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE, &bits_per_sample); if (((photometric == PHOTOMETRIC_RGB) || (photometric == PHOTOMETRIC_SEPARATED) || (photometric == PHOTOMETRIC_MINISBLACK)) && ((bits_per_sample == 8) || (bits_per_sample == 16))) predictor=PREDICTOR_HORIZONTAL; (void) TIFFSetField(tiff,TIFFTAG_WEBP_LEVEL,mage_info->quality); if (image_info->quality >= 100) (void) TIFFSetField(tiff,TIFFTAG_WEBP_LOSSLESS,1); break; } #endif #if defined(ZSTD_SUPPORT) && defined(COMPRESSION_ZSTD) case COMPRESSION_ZSTD: { (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE, &bits_per_sample); if (((photometric == PHOTOMETRIC_RGB) || (photometric == PHOTOMETRIC_SEPARATED) || (photometric == PHOTOMETRIC_MINISBLACK)) && ((bits_per_sample == 8) || (bits_per_sample == 16))) predictor=PREDICTOR_HORIZONTAL; (void) TIFFSetField(tiff,TIFFTAG_ZSTD_LEVEL,22*image_info->quality/ 100.0); break; } #endif default: break; } option=GetImageOption(image_info,""tiff:predictor""); if (option != (const char * ) NULL) predictor=(size_t) strtol(option,(char **) NULL,10); if (predictor != 0) (void) TIFFSetField(tiff,TIFFTAG_PREDICTOR,predictor); if ((image->x_resolution != 0.0) && (image->y_resolution != 0.0)) { unsigned short units; /* Set image resolution. */ units=RESUNIT_NONE; if (image->units == PixelsPerInchResolution) units=RESUNIT_INCH; if (image->units == PixelsPerCentimeterResolution) units=RESUNIT_CENTIMETER; (void) TIFFSetField(tiff,TIFFTAG_RESOLUTIONUNIT,(uint16) units); (void) TIFFSetField(tiff,TIFFTAG_XRESOLUTION,image->x_resolution); (void) TIFFSetField(tiff,TIFFTAG_YRESOLUTION,image->y_resolution); if ((image->page.x < 0) || (image->page.y < 0)) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,""TIFF: negative image positions unsupported"",""%s"", image->filename); if ((image->page.x > 0) && (image->x_resolution > 0.0)) { /* Set horizontal image position. */ (void) TIFFSetField(tiff,TIFFTAG_XPOSITION,(float) image->page.x/ image->x_resolution); } if ((image->page.y > 0) && (image->y_resolution > 0.0)) { /* Set vertical image position. */ (void) TIFFSetField(tiff,TIFFTAG_YPOSITION,(float) image->page.y/ image->y_resolution); } } if (image->chromaticity.white_point.x != 0.0) { float chromaticity[6]; /* Set image chromaticity. */ chromaticity[0]=(float) image->chromaticity.red_primary.x; chromaticity[1]=(float) image->chromaticity.red_primary.y; chromaticity[2]=(float) image->chromaticity.green_primary.x; chromaticity[3]=(float) image->chromaticity.green_primary.y; chromaticity[4]=(float) image->chromaticity.blue_primary.x; chromaticity[5]=(float) image->chromaticity.blue_primary.y; (void) TIFFSetField(tiff,TIFFTAG_PRIMARYCHROMATICITIES,chromaticity); chromaticity[0]=(float) image->chromaticity.white_point.x; chromaticity[1]=(float) image->chromaticity.white_point.y; (void) TIFFSetField(tiff,TIFFTAG_WHITEPOINT,chromaticity); } if ((LocaleCompare(image_info->magick,""PTIF"") != 0) && (image_info->adjoin != MagickFalse) && (imageListLength > 1)) { (void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_PAGE); if (image->scene != 0) (void) TIFFSetField(tiff,TIFFTAG_PAGENUMBER,(uint16) image->scene, imageListLength); } if (image->orientation != UndefinedOrientation) (void) TIFFSetField(tiff,TIFFTAG_ORIENTATION,(uint16) image->orientation); else (void) TIFFSetField(tiff,TIFFTAG_ORIENTATION,ORIENTATION_TOPLEFT); (void) TIFFSetProfiles(tiff,image); { uint16 page, pages; page=(uint16) scene; pages=(uint16) imageListLength; if ((LocaleCompare(image_info->magick,""PTIF"") != 0) && (image_info->adjoin != MagickFalse) && (pages > 1)) (void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_PAGE); (void) TIFFSetField(tiff,TIFFTAG_PAGENUMBER,page,pages); } (void) TIFFSetProperties(tiff,image_info,image); DisableMSCWarning(4127) if (0) RestoreMSCWarning (void) TIFFSetEXIFProperties(tiff,image); /* Write image scanlines. */ if (GetTIFFInfo(image_info,tiff,&tiff_info) == MagickFalse) ThrowWriterException(ResourceLimitError,""MemoryAllocationFailed""); quantum_info->endian=LSBEndian; pixels=GetQuantumPixels(quantum_info); tiff_info.scanline=GetQuantumPixels(quantum_info); switch (photometric) { case PHOTOMETRIC_CIELAB: case PHOTOMETRIC_YCBCR: case PHOTOMETRIC_RGB: { /* RGB TIFF image. */ switch (image_info->interlace) { case NoInterlace: default: { quantum_type=RGBQuantum; if (image->matte != MagickFalse) quantum_type=RGBAQuantum; for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,quantum_type,pixels,&image->exception); if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } break; } case PlaneInterlace: case PartitionInterlace: { /* Plane interlacing: RRRRRR...GGGGGG...BBBBBB... */ for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,RedQuantum,pixels,&image->exception); if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,100,400); if (status == MagickFalse) break; } for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,GreenQuantum,pixels,&image->exception); if (TIFFWritePixels(tiff,&tiff_info,y,1,image) == -1) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,200,400); if (status == MagickFalse) break; } for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,BlueQuantum,pixels,&image->exception); if (TIFFWritePixels(tiff,&tiff_info,y,2,image) == -1) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,300,400); if (status == MagickFalse) break; } if (image->matte != MagickFalse) for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1, &image->exception); if (p == (const PixelPacket *) NULL) break; (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,AlphaQuantum,pixels,&image->exception); if (TIFFWritePixels(tiff,&tiff_info,y,3,image) == -1) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,400,400); if (status == MagickFalse) break; } break; } } break; } case PHOTOMETRIC_SEPARATED: { /* CMYK TIFF image. */ quantum_type=CMYKQuantum; if (image->matte != MagickFalse) quantum_type=CMYKAQuantum; if (image->colorspace != CMYKColorspace) (void) TransformImageColorspace(image,CMYKColorspace); for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,quantum_type,pixels,&image->exception); if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case PHOTOMETRIC_PALETTE: { uint16 *blue, *green, *red; /* Colormapped TIFF image. */ red=(uint16 *) AcquireQuantumMemory(65536,sizeof(*red)); green=(uint16 *) AcquireQuantumMemory(65536,sizeof(*green)); blue=(uint16 *) AcquireQuantumMemory(65536,sizeof(*blue)); if ((red == (uint16 *) NULL) || (green == (uint16 *) NULL) || (blue == (uint16 *) NULL)) { if (red != (uint16 *) NULL) red=(uint16 *) RelinquishMagickMemory(red); if (green != (uint16 *) NULL) green=(uint16 *) RelinquishMagickMemory(green); if (blue != (uint16 *) NULL) blue=(uint16 *) RelinquishMagickMemory(blue); ThrowWriterException(ResourceLimitError,""MemoryAllocationFailed""); } /* Initialize TIFF colormap. */ (void) memset(red,0,65536*sizeof(*red)); (void) memset(green,0,65536*sizeof(*green)); (void) memset(blue,0,65536*sizeof(*blue)); for (i=0; i < (ssize_t) image->colors; i++) { red[i]=ScaleQuantumToShort(image->colormap[i].red); green[i]=ScaleQuantumToShort(image->colormap[i].green); blue[i]=ScaleQuantumToShort(image->colormap[i].blue); } (void) TIFFSetField(tiff,TIFFTAG_COLORMAP,red,green,blue); red=(uint16 *) RelinquishMagickMemory(red); green=(uint16 *) RelinquishMagickMemory(green); blue=(uint16 *) RelinquishMagickMemory(blue); } default: { /* Convert PseudoClass packets to contiguous grayscale scanlines. */ quantum_type=IndexQuantum; if (image->matte != MagickFalse) { if (photometric != PHOTOMETRIC_PALETTE) quantum_type=GrayAlphaQuantum; else quantum_type=IndexAlphaQuantum; } else if (photometric != PHOTOMETRIC_PALETTE) quantum_type=GrayQuantum; for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,quantum_type,pixels,&image->exception); if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } } quantum_info=DestroyQuantumInfo(quantum_info); if (image->colorspace == LabColorspace) DecodeLabImage(image,&image->exception); DestroyTIFFInfo(&tiff_info); if (image->exception.severity > ErrorException) break; DisableMSCWarning(4127) if (0 && (image_info->verbose != MagickFalse)) RestoreMSCWarning TIFFPrintDirectory(tiff,stdout,MagickFalse); (void) TIFFWriteDirectory(tiff); image=SyncNextImageInList(image); if (image == (Image *) NULL) break; status=SetImageProgress(image,SaveImagesTag,scene++,imageListLength); if (status == MagickFalse) break; } while (image_info->adjoin != MagickFalse); TIFFClose(tiff); return(image->exception.severity > ErrorException ? MagickFalse : MagickTrue); }","static MagickBooleanType WriteTIFFImage(const ImageInfo *image_info, Image *image) { const char *mode, *option; CompressionType compression; EndianType endian_type; MagickBooleanType debug, status; MagickOffsetType scene; QuantumInfo *quantum_info; QuantumType quantum_type; register ssize_t i; size_t imageListLength; ssize_t y; TIFF *tiff; TIFFInfo tiff_info; uint16 bits_per_sample, compress_tag, endian, photometric, predictor; unsigned char *pixels; /* Open TIFF file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),""%s"",image->filename); status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception); if (status == MagickFalse) return(status); (void) SetMagickThreadValue(tiff_exception,&image->exception); endian_type=UndefinedEndian; option=GetImageOption(image_info,""tiff:endian""); if (option != (const char *) NULL) { if (LocaleNCompare(option,""msb"",3) == 0) endian_type=MSBEndian; if (LocaleNCompare(option,""lsb"",3) == 0) endian_type=LSBEndian;; } switch (endian_type) { case LSBEndian: mode=""wl""; break; case MSBEndian: mode=""wb""; break; default: mode=""w""; break; } #if defined(TIFF_VERSION_BIG) if (LocaleCompare(image_info->magick,""TIFF64"") == 0) switch (endian_type) { case LSBEndian: mode=""wl8""; break; case MSBEndian: mode=""wb8""; break; default: mode=""w8""; break; } #endif tiff=TIFFClientOpen(image->filename,mode,(thandle_t) image,TIFFReadBlob, TIFFWriteBlob,TIFFSeekBlob,TIFFCloseBlob,TIFFGetBlobSize,TIFFMapBlob, TIFFUnmapBlob); if (tiff == (TIFF *) NULL) return(MagickFalse); if (image->exception.severity > ErrorException) { TIFFClose(tiff); return(MagickFalse); } (void) DeleteImageProfile(image,""tiff:37724""); scene=0; debug=IsEventLogging(); (void) debug; imageListLength=GetImageListLength(image); do { /* Initialize TIFF fields. */ if ((image_info->type != UndefinedType) && (image_info->type != OptimizeType)) (void) SetImageType(image,image_info->type); compression=UndefinedCompression; if (image->compression != JPEGCompression) compression=image->compression; if (image_info->compression != UndefinedCompression) compression=image_info->compression; switch (compression) { case FaxCompression: case Group4Compression: { (void) SetImageType(image,BilevelType); (void) SetImageDepth(image,1); break; } case JPEGCompression: { (void) SetImageStorageClass(image,DirectClass); (void) SetImageDepth(image,8); break; } default: break; } quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,""MemoryAllocationFailed""); if ((image->storage_class != PseudoClass) && (image->depth >= 32) && (quantum_info->format == UndefinedQuantumFormat) && (IsHighDynamicRangeImage(image,&image->exception) != MagickFalse)) { status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat); if (status == MagickFalse) { quantum_info=DestroyQuantumInfo(quantum_info); ThrowWriterException(ResourceLimitError,""MemoryAllocationFailed""); } } if ((LocaleCompare(image_info->magick,""PTIF"") == 0) && (GetPreviousImageInList(image) != (Image *) NULL)) (void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_REDUCEDIMAGE); if ((image->columns != (uint32) image->columns) || (image->rows != (uint32) image->rows)) ThrowWriterException(ImageError,""WidthOrHeightExceedsLimit""); (void) TIFFSetField(tiff,TIFFTAG_IMAGELENGTH,(uint32) image->rows); (void) TIFFSetField(tiff,TIFFTAG_IMAGEWIDTH,(uint32) image->columns); switch (compression) { case FaxCompression: { compress_tag=COMPRESSION_CCITTFAX3; option=GetImageOption(image_info,""quantum:polarity""); if (option == (const char *) NULL) SetQuantumMinIsWhite(quantum_info,MagickTrue); break; } case Group4Compression: { compress_tag=COMPRESSION_CCITTFAX4; option=GetImageOption(image_info,""quantum:polarity""); if (option == (const char *) NULL) SetQuantumMinIsWhite(quantum_info,MagickTrue); break; } #if defined(COMPRESSION_JBIG) case JBIG1Compression: { compress_tag=COMPRESSION_JBIG; break; } #endif case JPEGCompression: { compress_tag=COMPRESSION_JPEG; break; } #if defined(COMPRESSION_LZMA) case LZMACompression: { compress_tag=COMPRESSION_LZMA; break; } #endif case LZWCompression: { compress_tag=COMPRESSION_LZW; break; } case RLECompression: { compress_tag=COMPRESSION_PACKBITS; break; } #if defined(COMPRESSION_WEBP) case WebPCompression: { compress_tag=COMPRESSION_WEBP; break; } #endif case ZipCompression: { compress_tag=COMPRESSION_ADOBE_DEFLATE; break; } #if defined(COMPRESSION_ZSTD) case ZstdCompression: { compress_tag=COMPRESSION_ZSTD; break; } #endif case NoCompression: default: { compress_tag=COMPRESSION_NONE; break; } } #if defined(MAGICKCORE_HAVE_TIFFISCODECCONFIGURED) || (TIFFLIB_VERSION > 20040919) if ((compress_tag != COMPRESSION_NONE) && (TIFFIsCODECConfigured(compress_tag) == 0)) { (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,""CompressionNotSupported"",""`%s'"",CommandOptionToMnemonic( MagickCompressOptions,(ssize_t) compression)); compress_tag=COMPRESSION_NONE; } #else switch (compress_tag) { #if defined(CCITT_SUPPORT) case COMPRESSION_CCITTFAX3: case COMPRESSION_CCITTFAX4: #endif #if defined(YCBCR_SUPPORT) && defined(JPEG_SUPPORT) case COMPRESSION_JPEG: #endif #if defined(LZMA_SUPPORT) && defined(COMPRESSION_LZMA) case COMPRESSION_LZMA: #endif #if defined(LZW_SUPPORT) case COMPRESSION_LZW: #endif #if defined(PACKBITS_SUPPORT) case COMPRESSION_PACKBITS: #endif #if defined(ZIP_SUPPORT) case COMPRESSION_ADOBE_DEFLATE: #endif case COMPRESSION_NONE: break; default: { (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,""CompressionNotSupported"",""`%s'"",CommandOptionToMnemonic( MagickCompressOptions,(ssize_t) compression)); compress_tag=COMPRESSION_NONE; break; } } #endif if (image->colorspace == CMYKColorspace) { photometric=PHOTOMETRIC_SEPARATED; (void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,4); (void) TIFFSetField(tiff,TIFFTAG_INKSET,INKSET_CMYK); } else { /* Full color TIFF raster. */ if (image->colorspace == LabColorspace) { photometric=PHOTOMETRIC_CIELAB; EncodeLabImage(image,&image->exception); } else if (image->colorspace == YCbCrColorspace) { photometric=PHOTOMETRIC_YCBCR; (void) TIFFSetField(tiff,TIFFTAG_YCBCRSUBSAMPLING,1,1); (void) SetImageStorageClass(image,DirectClass); (void) SetImageDepth(image,8); } else photometric=PHOTOMETRIC_RGB; (void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,3); if ((image_info->type != TrueColorType) && (image_info->type != TrueColorMatteType)) { if ((image_info->type != PaletteType) && (SetImageGray(image,&image->exception) != MagickFalse)) { photometric=(uint16) (quantum_info->min_is_white != MagickFalse ? PHOTOMETRIC_MINISWHITE : PHOTOMETRIC_MINISBLACK); (void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,1); if ((image->depth == 1) && (image->matte == MagickFalse)) SetImageMonochrome(image,&image->exception); } else if (image->storage_class == PseudoClass) { size_t depth; /* Colormapped TIFF raster. */ (void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,1); photometric=PHOTOMETRIC_PALETTE; depth=1; while ((GetQuantumRange(depth)+1) < image->colors) depth<<=1; status=SetQuantumDepth(image,quantum_info,depth); if (status == MagickFalse) ThrowWriterException(ResourceLimitError, ""MemoryAllocationFailed""); } } } (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_FILLORDER,&endian); if ((compress_tag == COMPRESSION_CCITTFAX3) || (compress_tag == COMPRESSION_CCITTFAX4)) { if ((photometric != PHOTOMETRIC_MINISWHITE) && (photometric != PHOTOMETRIC_MINISBLACK)) { compress_tag=COMPRESSION_NONE; endian=FILLORDER_MSB2LSB; } } option=GetImageOption(image_info,""tiff:fill-order""); if (option != (const char *) NULL) { if (LocaleNCompare(option,""msb"",3) == 0) endian=FILLORDER_MSB2LSB; if (LocaleNCompare(option,""lsb"",3) == 0) endian=FILLORDER_LSB2MSB; } (void) TIFFSetField(tiff,TIFFTAG_COMPRESSION,compress_tag); (void) TIFFSetField(tiff,TIFFTAG_FILLORDER,endian); (void) TIFFSetField(tiff,TIFFTAG_BITSPERSAMPLE,quantum_info->depth); if (image->matte != MagickFalse) { uint16 extra_samples, sample_info[1], samples_per_pixel; /* TIFF has a matte channel. */ extra_samples=1; sample_info[0]=EXTRASAMPLE_UNASSALPHA; option=GetImageOption(image_info,""tiff:alpha""); if (option != (const char *) NULL) { if (LocaleCompare(option,""associated"") == 0) sample_info[0]=EXTRASAMPLE_ASSOCALPHA; else if (LocaleCompare(option,""unspecified"") == 0) sample_info[0]=EXTRASAMPLE_UNSPECIFIED; } (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLESPERPIXEL, &samples_per_pixel); (void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,samples_per_pixel+1); (void) TIFFSetField(tiff,TIFFTAG_EXTRASAMPLES,extra_samples, &sample_info); if (sample_info[0] == EXTRASAMPLE_ASSOCALPHA) SetQuantumAlphaType(quantum_info,AssociatedQuantumAlpha); } (void) TIFFSetField(tiff,TIFFTAG_PHOTOMETRIC,photometric); switch (quantum_info->format) { case FloatingPointQuantumFormat: { (void) TIFFSetField(tiff,TIFFTAG_SAMPLEFORMAT,SAMPLEFORMAT_IEEEFP); (void) TIFFSetField(tiff,TIFFTAG_SMINSAMPLEVALUE,quantum_info->minimum); (void) TIFFSetField(tiff,TIFFTAG_SMAXSAMPLEVALUE,quantum_info->maximum); break; } case SignedQuantumFormat: { (void) TIFFSetField(tiff,TIFFTAG_SAMPLEFORMAT,SAMPLEFORMAT_INT); break; } case UnsignedQuantumFormat: { (void) TIFFSetField(tiff,TIFFTAG_SAMPLEFORMAT,SAMPLEFORMAT_UINT); break; } default: break; } (void) TIFFSetField(tiff,TIFFTAG_PLANARCONFIG,PLANARCONFIG_CONTIG); if (photometric == PHOTOMETRIC_RGB) if ((image_info->interlace == PlaneInterlace) || (image_info->interlace == PartitionInterlace)) (void) TIFFSetField(tiff,TIFFTAG_PLANARCONFIG,PLANARCONFIG_SEPARATE); predictor=0; switch (compress_tag) { case COMPRESSION_JPEG: { #if defined(JPEG_SUPPORT) if (image_info->quality != UndefinedCompressionQuality) (void) TIFFSetField(tiff,TIFFTAG_JPEGQUALITY,image_info->quality); (void) TIFFSetField(tiff,TIFFTAG_JPEGCOLORMODE,JPEGCOLORMODE_RAW); if (IssRGBCompatibleColorspace(image->colorspace) != MagickFalse) { const char *value; (void) TIFFSetField(tiff,TIFFTAG_JPEGCOLORMODE,JPEGCOLORMODE_RGB); if (image->colorspace == YCbCrColorspace) { const char *sampling_factor; GeometryInfo geometry_info; MagickStatusType flags; sampling_factor=(const char *) NULL; value=GetImageProperty(image,""jpeg:sampling-factor""); if (value != (char *) NULL) { sampling_factor=value; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" Input sampling-factors=%s"",sampling_factor); } if (image_info->sampling_factor != (char *) NULL) sampling_factor=image_info->sampling_factor; if (sampling_factor != (const char *) NULL) { flags=ParseGeometry(sampling_factor,&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=geometry_info.rho; (void) TIFFSetField(tiff,TIFFTAG_YCBCRSUBSAMPLING,(uint16) geometry_info.rho,(uint16) geometry_info.sigma); } } } (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE, &bits_per_sample); if (bits_per_sample == 12) (void) TIFFSetField(tiff,TIFFTAG_JPEGTABLESMODE,JPEGTABLESMODE_QUANT); #endif break; } case COMPRESSION_ADOBE_DEFLATE: { (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE, &bits_per_sample); if (((photometric == PHOTOMETRIC_RGB) || (photometric == PHOTOMETRIC_SEPARATED) || (photometric == PHOTOMETRIC_MINISBLACK)) && ((bits_per_sample == 8) || (bits_per_sample == 16))) predictor=PREDICTOR_HORIZONTAL; (void) TIFFSetField(tiff,TIFFTAG_ZIPQUALITY,(long) ( image_info->quality == UndefinedCompressionQuality ? 7 : MagickMin((ssize_t) image_info->quality/10,9))); break; } case COMPRESSION_CCITTFAX3: { /* Byte-aligned EOL. */ (void) TIFFSetField(tiff,TIFFTAG_GROUP3OPTIONS,4); break; } case COMPRESSION_CCITTFAX4: break; #if defined(LZMA_SUPPORT) && defined(COMPRESSION_LZMA) case COMPRESSION_LZMA: { if (((photometric == PHOTOMETRIC_RGB) || (photometric == PHOTOMETRIC_SEPARATED) || (photometric == PHOTOMETRIC_MINISBLACK)) && ((bits_per_sample == 8) || (bits_per_sample == 16))) predictor=PREDICTOR_HORIZONTAL; (void) TIFFSetField(tiff,TIFFTAG_LZMAPRESET,(long) ( image_info->quality == UndefinedCompressionQuality ? 7 : MagickMin((ssize_t) image_info->quality/10,9))); break; } #endif case COMPRESSION_LZW: { (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE, &bits_per_sample); if (((photometric == PHOTOMETRIC_RGB) || (photometric == PHOTOMETRIC_SEPARATED) || (photometric == PHOTOMETRIC_MINISBLACK)) && ((bits_per_sample == 8) || (bits_per_sample == 16))) predictor=PREDICTOR_HORIZONTAL; break; } #if defined(WEBP_SUPPORT) && defined(COMPRESSION_WEBP) case COMPRESSION_WEBP: { (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE, &bits_per_sample); if (((photometric == PHOTOMETRIC_RGB) || (photometric == PHOTOMETRIC_SEPARATED) || (photometric == PHOTOMETRIC_MINISBLACK)) && ((bits_per_sample == 8) || (bits_per_sample == 16))) predictor=PREDICTOR_HORIZONTAL; (void) TIFFSetField(tiff,TIFFTAG_WEBP_LEVEL,mage_info->quality); if (image_info->quality >= 100) (void) TIFFSetField(tiff,TIFFTAG_WEBP_LOSSLESS,1); break; } #endif #if defined(ZSTD_SUPPORT) && defined(COMPRESSION_ZSTD) case COMPRESSION_ZSTD: { (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE, &bits_per_sample); if (((photometric == PHOTOMETRIC_RGB) || (photometric == PHOTOMETRIC_SEPARATED) || (photometric == PHOTOMETRIC_MINISBLACK)) && ((bits_per_sample == 8) || (bits_per_sample == 16))) predictor=PREDICTOR_HORIZONTAL; (void) TIFFSetField(tiff,TIFFTAG_ZSTD_LEVEL,22*image_info->quality/ 100.0); break; } #endif default: break; } option=GetImageOption(image_info,""tiff:predictor""); if (option != (const char * ) NULL) predictor=(size_t) strtol(option,(char **) NULL,10); if (predictor != 0) (void) TIFFSetField(tiff,TIFFTAG_PREDICTOR,predictor); if ((image->x_resolution != 0.0) && (image->y_resolution != 0.0)) { unsigned short units; /* Set image resolution. */ units=RESUNIT_NONE; if (image->units == PixelsPerInchResolution) units=RESUNIT_INCH; if (image->units == PixelsPerCentimeterResolution) units=RESUNIT_CENTIMETER; (void) TIFFSetField(tiff,TIFFTAG_RESOLUTIONUNIT,(uint16) units); (void) TIFFSetField(tiff,TIFFTAG_XRESOLUTION,image->x_resolution); (void) TIFFSetField(tiff,TIFFTAG_YRESOLUTION,image->y_resolution); if ((image->page.x < 0) || (image->page.y < 0)) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,""TIFF: negative image positions unsupported"",""%s"", image->filename); if ((image->page.x > 0) && (image->x_resolution > 0.0)) { /* Set horizontal image position. */ (void) TIFFSetField(tiff,TIFFTAG_XPOSITION,(float) image->page.x/ image->x_resolution); } if ((image->page.y > 0) && (image->y_resolution > 0.0)) { /* Set vertical image position. */ (void) TIFFSetField(tiff,TIFFTAG_YPOSITION,(float) image->page.y/ image->y_resolution); } } if (image->chromaticity.white_point.x != 0.0) { float chromaticity[6]; /* Set image chromaticity. */ chromaticity[0]=(float) image->chromaticity.red_primary.x; chromaticity[1]=(float) image->chromaticity.red_primary.y; chromaticity[2]=(float) image->chromaticity.green_primary.x; chromaticity[3]=(float) image->chromaticity.green_primary.y; chromaticity[4]=(float) image->chromaticity.blue_primary.x; chromaticity[5]=(float) image->chromaticity.blue_primary.y; (void) TIFFSetField(tiff,TIFFTAG_PRIMARYCHROMATICITIES,chromaticity); chromaticity[0]=(float) image->chromaticity.white_point.x; chromaticity[1]=(float) image->chromaticity.white_point.y; (void) TIFFSetField(tiff,TIFFTAG_WHITEPOINT,chromaticity); } if ((LocaleCompare(image_info->magick,""PTIF"") != 0) && (image_info->adjoin != MagickFalse) && (imageListLength > 1)) { (void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_PAGE); if (image->scene != 0) (void) TIFFSetField(tiff,TIFFTAG_PAGENUMBER,(uint16) image->scene, imageListLength); } if (image->orientation != UndefinedOrientation) (void) TIFFSetField(tiff,TIFFTAG_ORIENTATION,(uint16) image->orientation); else (void) TIFFSetField(tiff,TIFFTAG_ORIENTATION,ORIENTATION_TOPLEFT); (void) TIFFSetProfiles(tiff,image); { uint16 page, pages; page=(uint16) scene; pages=(uint16) imageListLength; if ((LocaleCompare(image_info->magick,""PTIF"") != 0) && (image_info->adjoin != MagickFalse) && (pages > 1)) (void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_PAGE); (void) TIFFSetField(tiff,TIFFTAG_PAGENUMBER,page,pages); } (void) TIFFSetProperties(tiff,image_info,image); DisableMSCWarning(4127) if (0) RestoreMSCWarning (void) TIFFSetEXIFProperties(tiff,image); /* Write image scanlines. */ if (GetTIFFInfo(image_info,tiff,&tiff_info) == MagickFalse) ThrowWriterException(ResourceLimitError,""MemoryAllocationFailed""); quantum_info->endian=LSBEndian; pixels=GetQuantumPixels(quantum_info); tiff_info.scanline=GetQuantumPixels(quantum_info); switch (photometric) { case PHOTOMETRIC_CIELAB: case PHOTOMETRIC_YCBCR: case PHOTOMETRIC_RGB: { /* RGB TIFF image. */ switch (image_info->interlace) { case NoInterlace: default: { quantum_type=RGBQuantum; if (image->matte != MagickFalse) quantum_type=RGBAQuantum; for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,quantum_type,pixels,&image->exception); if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } break; } case PlaneInterlace: case PartitionInterlace: { /* Plane interlacing: RRRRRR...GGGGGG...BBBBBB... */ for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,RedQuantum,pixels,&image->exception); if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,100,400); if (status == MagickFalse) break; } for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,GreenQuantum,pixels,&image->exception); if (TIFFWritePixels(tiff,&tiff_info,y,1,image) == -1) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,200,400); if (status == MagickFalse) break; } for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,BlueQuantum,pixels,&image->exception); if (TIFFWritePixels(tiff,&tiff_info,y,2,image) == -1) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,300,400); if (status == MagickFalse) break; } if (image->matte != MagickFalse) for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1, &image->exception); if (p == (const PixelPacket *) NULL) break; (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,AlphaQuantum,pixels,&image->exception); if (TIFFWritePixels(tiff,&tiff_info,y,3,image) == -1) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,400,400); if (status == MagickFalse) break; } break; } } break; } case PHOTOMETRIC_SEPARATED: { /* CMYK TIFF image. */ quantum_type=CMYKQuantum; if (image->matte != MagickFalse) quantum_type=CMYKAQuantum; if (image->colorspace != CMYKColorspace) (void) TransformImageColorspace(image,CMYKColorspace); for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,quantum_type,pixels,&image->exception); if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case PHOTOMETRIC_PALETTE: { uint16 *blue, *green, *red; /* Colormapped TIFF image. */ red=(uint16 *) AcquireQuantumMemory(65536,sizeof(*red)); green=(uint16 *) AcquireQuantumMemory(65536,sizeof(*green)); blue=(uint16 *) AcquireQuantumMemory(65536,sizeof(*blue)); if ((red == (uint16 *) NULL) || (green == (uint16 *) NULL) || (blue == (uint16 *) NULL)) { if (red != (uint16 *) NULL) red=(uint16 *) RelinquishMagickMemory(red); if (green != (uint16 *) NULL) green=(uint16 *) RelinquishMagickMemory(green); if (blue != (uint16 *) NULL) blue=(uint16 *) RelinquishMagickMemory(blue); ThrowWriterException(ResourceLimitError,""MemoryAllocationFailed""); } /* Initialize TIFF colormap. */ (void) memset(red,0,65536*sizeof(*red)); (void) memset(green,0,65536*sizeof(*green)); (void) memset(blue,0,65536*sizeof(*blue)); for (i=0; i < (ssize_t) image->colors; i++) { red[i]=ScaleQuantumToShort(image->colormap[i].red); green[i]=ScaleQuantumToShort(image->colormap[i].green); blue[i]=ScaleQuantumToShort(image->colormap[i].blue); } (void) TIFFSetField(tiff,TIFFTAG_COLORMAP,red,green,blue); red=(uint16 *) RelinquishMagickMemory(red); green=(uint16 *) RelinquishMagickMemory(green); blue=(uint16 *) RelinquishMagickMemory(blue); } default: { /* Convert PseudoClass packets to contiguous grayscale scanlines. */ quantum_type=IndexQuantum; if (image->matte != MagickFalse) { if (photometric != PHOTOMETRIC_PALETTE) quantum_type=GrayAlphaQuantum; else quantum_type=IndexAlphaQuantum; } else if (photometric != PHOTOMETRIC_PALETTE) quantum_type=GrayQuantum; for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,quantum_type,pixels,&image->exception); if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } } quantum_info=DestroyQuantumInfo(quantum_info); if (image->colorspace == LabColorspace) DecodeLabImage(image,&image->exception); DestroyTIFFInfo(&tiff_info); DisableMSCWarning(4127) if (0 && (image_info->verbose != MagickFalse)) RestoreMSCWarning TIFFPrintDirectory(tiff,stdout,MagickFalse); if (TIFFWriteDirectory(tiff) == 0) { status=MagickFalse; break; } image=SyncNextImageInList(image); if (image == (Image *) NULL) break; status=SetImageProgress(image,SaveImagesTag,scene++,imageListLength); if (status == MagickFalse) break; } while (image_info->adjoin != MagickFalse); TIFFClose(tiff); return(status); }","{'deleted': [{'line_no': 893, 'char_start': 30340, 'char_end': 30392, 'line': ' if (image->exception.severity > ErrorException)\n'}, {'line_no': 894, 'char_start': 30392, 'char_end': 30405, 'line': ' break;\n'}, {'line_no': 899, 'char_start': 30549, 'char_end': 30586, 'line': ' (void) TIFFWriteDirectory(tiff);\n'}, {'line_no': 908, 'char_start': 30854, 'char_end': 30935, 'line': ' return(image->exception.severity > ErrorException ? MagickFalse : MagickTrue);\n'}], 'added': [{'line_no': 897, 'char_start': 30484, 'char_end': 30523, 'line': ' if (TIFFWriteDirectory(tiff) == 0)\n'}, {'line_no': 898, 'char_start': 30523, 'char_end': 30531, 'line': ' {\n'}, {'line_no': 899, 'char_start': 30531, 'char_end': 30559, 'line': ' status=MagickFalse;\n'}, {'line_no': 900, 'char_start': 30559, 'char_end': 30574, 'line': ' break;\n'}, {'line_no': 901, 'char_start': 30574, 'char_end': 30582, 'line': ' }\n'}, {'line_no': 910, 'char_start': 30850, 'char_end': 30868, 'line': ' return(status);\n'}]}","{'deleted': [{'char_start': 30340, 'char_end': 30405, 'chars': ' if (image->exception.severity > ErrorException)\n break;\n'}, {'char_start': 30553, 'char_end': 30556, 'chars': '(vo'}, {'char_start': 30557, 'char_end': 30559, 'chars': 'd)'}, {'char_start': 30863, 'char_end': 30880, 'chars': 'image->exception.'}, {'char_start': 30881, 'char_end': 30886, 'chars': 'everi'}, {'char_start': 30887, 'char_end': 30901, 'chars': 'y > ErrorExcep'}, {'char_start': 30902, 'char_end': 30917, 'chars': 'ion ? MagickFal'}, {'char_start': 30918, 'char_end': 30932, 'chars': 'e : MagickTrue'}], 'added': [{'char_start': 30489, 'char_end': 30490, 'chars': 'f'}, {'char_start': 30491, 'char_end': 30492, 'chars': '('}, {'char_start': 30516, 'char_end': 30557, 'chars': ' == 0)\n {\n status=MagickFalse'}, {'char_start': 30559, 'char_end': 30582, 'chars': ' break;\n }\n'}, {'char_start': 30862, 'char_end': 30864, 'chars': 'tu'}]}",github.com/ImageMagick/ImageMagick6/commit/3c53413eb544cc567309b4c86485eae43e956112,coders/tiff.c,cwe-125,7681 cwe-089,__init__.callback," def callback(recipeName): menu.pack_forget() viewRecipeFrame.pack(expand=True, fill='both') groceryButton.pack_forget() database_file = ""meal_planner.db"" print(recipeName) with sqlite3.connect(database_file) as conn: cursor = conn.cursor() selection = cursor.execute(""""""SELECT * FROM recipe WHERE name = """""" + ""\"""" + recipeName + ""\"""") for result in [selection]: for row in result.fetchall(): name = row[0] time = row[1] servings = row[2] ingredients = row[4] directions = row[5] string = (""Name: {} \n Cook time: {} \n Number of Servings: {} \n "".format(name, time, servings)) secondString = (""Ingredients: {}"".format(ingredients)) thirdString = (""Directions: {}"".format(directions)) Label(viewRecipeFrame, text=string, font=MEDIUM_FONT, bg=""#f8f8f8"", fg=""#000000"").pack(side=TOP) Label(viewRecipeFrame, text=secondString, font=MEDIUM_FONT, bg=""#f8f8f8"", fg=""#000000"").pack(side=TOP) Label(viewRecipeFrame, text=thirdString, font=MEDIUM_FONT, bg=""#f8f8f8"", fg=""#000000"").pack(side=TOP) returnButton = Button(menuFrame, text = ""Return to Menu"", highlightbackground=""#e7e7e7"", command=lambda: [viewRecipeFrame.pack_forget(), menu.pack(), returnButton.pack_forget(), label.configure(text=""Meal Planer""), groceryButton.pack(side=RIGHT)]) returnButton.pack(side=RIGHT)"," def callback(recipeName): menu.pack_forget() viewRecipeFrame.pack(expand=True, fill='both') groceryButton.pack_forget() database_file = ""meal_planner.db"" print(recipeName) with sqlite3.connect(database_file) as conn: cursor = conn.cursor() selection = cursor.execute(""""""SELECT * FROM recipe WHERE name = ?;"""""", (recipeName, )) for result in [selection]: for row in result.fetchall(): name = row[0] time = row[1] servings = row[2] ingredients = row[4] directions = row[5] string = (""Name: {} \n Cook time: {} \n Number of Servings: {} \n "".format(name, time, servings)) secondString = (""Ingredients: {}"".format(ingredients)) thirdString = (""Directions: {}"".format(directions)) Label(viewRecipeFrame, text=string, font=MEDIUM_FONT, bg=""#f8f8f8"", fg=""#000000"").pack(side=TOP) Label(viewRecipeFrame, text=secondString, font=MEDIUM_FONT, bg=""#f8f8f8"", fg=""#000000"").pack(side=TOP) Label(viewRecipeFrame, text=thirdString, font=MEDIUM_FONT, bg=""#f8f8f8"", fg=""#000000"").pack(side=TOP) returnButton = Button(menuFrame, text = ""Return to Menu"", highlightbackground=""#e7e7e7"", command=lambda: [viewRecipeFrame.pack_forget(), menu.pack(), returnButton.pack_forget(), label.configure(text=""Meal Planer""), groceryButton.pack(side=RIGHT)]) returnButton.pack(side=RIGHT)","{'deleted': [{'line_no': 9, 'char_start': 336, 'char_end': 448, 'line': ' selection = cursor.execute(""""""SELECT * FROM recipe WHERE name = """""" + ""\\"""" + recipeName + ""\\"""")\n'}], 'added': [{'line_no': 9, 'char_start': 336, 'char_end': 439, 'line': ' selection = cursor.execute(""""""SELECT * FROM recipe WHERE name = ?;"""""", (recipeName, ))\n'}]}","{'deleted': [{'char_start': 419, 'char_end': 421, 'chars': ' +'}, {'char_start': 422, 'char_end': 429, 'chars': '""\\"""" + '}, {'char_start': 439, 'char_end': 441, 'chars': ' +'}, {'char_start': 442, 'char_end': 446, 'chars': '""\\""""'}], 'added': [{'char_start': 416, 'char_end': 418, 'chars': '?;'}, {'char_start': 421, 'char_end': 422, 'chars': ','}, {'char_start': 423, 'char_end': 424, 'chars': '('}, {'char_start': 434, 'char_end': 435, 'chars': ','}, {'char_start': 436, 'char_end': 437, 'chars': ')'}]}",github.com/trishamoyer/RecipePlanner-Python/commit/44d2ce370715d9344fad34b3b749322ab095a925,mealPlan.py,cwe-089,377 cwe-190,ImagingLibTiffDecode,"int ImagingLibTiffDecode(Imaging im, ImagingCodecState state, UINT8* buffer, Py_ssize_t bytes) { TIFFSTATE *clientstate = (TIFFSTATE *)state->context; char *filename = ""tempfile.tif""; char *mode = ""r""; TIFF *tiff; /* buffer is the encoded file, bytes is the length of the encoded file */ /* it all ends up in state->buffer, which is a uint8* from Imaging.h */ TRACE((""in decoder: bytes %d\n"", bytes)); TRACE((""State: count %d, state %d, x %d, y %d, ystep %d\n"", state->count, state->state, state->x, state->y, state->ystep)); TRACE((""State: xsize %d, ysize %d, xoff %d, yoff %d \n"", state->xsize, state->ysize, state->xoff, state->yoff)); TRACE((""State: bits %d, bytes %d \n"", state->bits, state->bytes)); TRACE((""Buffer: %p: %c%c%c%c\n"", buffer, (char)buffer[0], (char)buffer[1],(char)buffer[2], (char)buffer[3])); TRACE((""State->Buffer: %c%c%c%c\n"", (char)state->buffer[0], (char)state->buffer[1],(char)state->buffer[2], (char)state->buffer[3])); TRACE((""Image: mode %s, type %d, bands: %d, xsize %d, ysize %d \n"", im->mode, im->type, im->bands, im->xsize, im->ysize)); TRACE((""Image: image8 %p, image32 %p, image %p, block %p \n"", im->image8, im->image32, im->image, im->block)); TRACE((""Image: pixelsize: %d, linesize %d \n"", im->pixelsize, im->linesize)); dump_state(clientstate); clientstate->size = bytes; clientstate->eof = clientstate->size; clientstate->loc = 0; clientstate->data = (tdata_t)buffer; clientstate->flrealloc = 0; dump_state(clientstate); TIFFSetWarningHandler(NULL); TIFFSetWarningHandlerExt(NULL); if (clientstate->fp) { TRACE((""Opening using fd: %d\n"",clientstate->fp)); lseek(clientstate->fp,0,SEEK_SET); // Sometimes, I get it set to the end. tiff = TIFFFdOpen(clientstate->fp, filename, mode); } else { TRACE((""Opening from string\n"")); tiff = TIFFClientOpen(filename, mode, (thandle_t) clientstate, _tiffReadProc, _tiffWriteProc, _tiffSeekProc, _tiffCloseProc, _tiffSizeProc, _tiffMapProc, _tiffUnmapProc); } if (!tiff){ TRACE((""Error, didn't get the tiff\n"")); state->errcode = IMAGING_CODEC_BROKEN; return -1; } if (clientstate->ifd){ int rv; uint32 ifdoffset = clientstate->ifd; TRACE((""reading tiff ifd %u\n"", ifdoffset)); rv = TIFFSetSubDirectory(tiff, ifdoffset); if (!rv){ TRACE((""error in TIFFSetSubDirectory"")); return -1; } } if (TIFFIsTiled(tiff)) { UINT32 x, y, tile_y, row_byte_size; UINT32 tile_width, tile_length, current_tile_width; UINT8 *new_data; TIFFGetField(tiff, TIFFTAG_TILEWIDTH, &tile_width); TIFFGetField(tiff, TIFFTAG_TILELENGTH, &tile_length); // We could use TIFFTileSize, but for YCbCr data it returns subsampled data size row_byte_size = (tile_width * state->bits + 7) / 8; state->bytes = row_byte_size * tile_length; /* overflow check for malloc */ if (state->bytes > INT_MAX - 1) { state->errcode = IMAGING_CODEC_MEMORY; TIFFClose(tiff); return -1; } /* realloc to fit whole tile */ new_data = realloc (state->buffer, state->bytes); if (!new_data) { state->errcode = IMAGING_CODEC_MEMORY; TIFFClose(tiff); return -1; } state->buffer = new_data; TRACE((""TIFFTileSize: %d\n"", state->bytes)); for (y = state->yoff; y < state->ysize; y += tile_length) { for (x = state->xoff; x < state->xsize; x += tile_width) { if (ReadTile(tiff, x, y, (UINT32*) state->buffer) == -1) { TRACE((""Decode Error, Tile at %dx%d\n"", x, y)); state->errcode = IMAGING_CODEC_BROKEN; TIFFClose(tiff); return -1; } TRACE((""Read tile at %dx%d; \n\n"", x, y)); current_tile_width = min(tile_width, state->xsize - x); // iterate over each line in the tile and stuff data into image for (tile_y = 0; tile_y < min(tile_length, state->ysize - y); tile_y++) { TRACE((""Writing tile data at %dx%d using tile_width: %d; \n"", tile_y + y, x, current_tile_width)); // UINT8 * bbb = state->buffer + tile_y * row_byte_size; // TRACE((""chars: %x%x%x%x\n"", ((UINT8 *)bbb)[0], ((UINT8 *)bbb)[1], ((UINT8 *)bbb)[2], ((UINT8 *)bbb)[3])); state->shuffle((UINT8*) im->image[tile_y + y] + x * im->pixelsize, state->buffer + tile_y * row_byte_size, current_tile_width ); } } } } else { UINT32 strip_row, row_byte_size; UINT8 *new_data; UINT32 rows_per_strip; int ret; ret = TIFFGetField(tiff, TIFFTAG_ROWSPERSTRIP, &rows_per_strip); if (ret != 1) { rows_per_strip = state->ysize; } TRACE((""RowsPerStrip: %u \n"", rows_per_strip)); // We could use TIFFStripSize, but for YCbCr data it returns subsampled data size row_byte_size = (state->xsize * state->bits + 7) / 8; state->bytes = rows_per_strip * row_byte_size; TRACE((""StripSize: %d \n"", state->bytes)); /* realloc to fit whole strip */ new_data = realloc (state->buffer, state->bytes); if (!new_data) { state->errcode = IMAGING_CODEC_MEMORY; TIFFClose(tiff); return -1; } state->buffer = new_data; for (; state->y < state->ysize; state->y += rows_per_strip) { if (ReadStrip(tiff, state->y, (UINT32 *)state->buffer) == -1) { TRACE((""Decode Error, strip %d\n"", TIFFComputeStrip(tiff, state->y, 0))); state->errcode = IMAGING_CODEC_BROKEN; TIFFClose(tiff); return -1; } TRACE((""Decoded strip for row %d \n"", state->y)); // iterate over each row in the strip and stuff data into image for (strip_row = 0; strip_row < min(rows_per_strip, state->ysize - state->y); strip_row++) { TRACE((""Writing data into line %d ; \n"", state->y + strip_row)); // UINT8 * bbb = state->buffer + strip_row * (state->bytes / rows_per_strip); // TRACE((""chars: %x %x %x %x\n"", ((UINT8 *)bbb)[0], ((UINT8 *)bbb)[1], ((UINT8 *)bbb)[2], ((UINT8 *)bbb)[3])); state->shuffle((UINT8*) im->image[state->y + state->yoff + strip_row] + state->xoff * im->pixelsize, state->buffer + strip_row * row_byte_size, state->xsize); } } } TIFFClose(tiff); TRACE((""Done Decoding, Returning \n"")); // Returning -1 here to force ImageFile.load to break, rather than // even think about looping back around. return -1; }","int ImagingLibTiffDecode(Imaging im, ImagingCodecState state, UINT8* buffer, Py_ssize_t bytes) { TIFFSTATE *clientstate = (TIFFSTATE *)state->context; char *filename = ""tempfile.tif""; char *mode = ""r""; TIFF *tiff; /* buffer is the encoded file, bytes is the length of the encoded file */ /* it all ends up in state->buffer, which is a uint8* from Imaging.h */ TRACE((""in decoder: bytes %d\n"", bytes)); TRACE((""State: count %d, state %d, x %d, y %d, ystep %d\n"", state->count, state->state, state->x, state->y, state->ystep)); TRACE((""State: xsize %d, ysize %d, xoff %d, yoff %d \n"", state->xsize, state->ysize, state->xoff, state->yoff)); TRACE((""State: bits %d, bytes %d \n"", state->bits, state->bytes)); TRACE((""Buffer: %p: %c%c%c%c\n"", buffer, (char)buffer[0], (char)buffer[1],(char)buffer[2], (char)buffer[3])); TRACE((""State->Buffer: %c%c%c%c\n"", (char)state->buffer[0], (char)state->buffer[1],(char)state->buffer[2], (char)state->buffer[3])); TRACE((""Image: mode %s, type %d, bands: %d, xsize %d, ysize %d \n"", im->mode, im->type, im->bands, im->xsize, im->ysize)); TRACE((""Image: image8 %p, image32 %p, image %p, block %p \n"", im->image8, im->image32, im->image, im->block)); TRACE((""Image: pixelsize: %d, linesize %d \n"", im->pixelsize, im->linesize)); dump_state(clientstate); clientstate->size = bytes; clientstate->eof = clientstate->size; clientstate->loc = 0; clientstate->data = (tdata_t)buffer; clientstate->flrealloc = 0; dump_state(clientstate); TIFFSetWarningHandler(NULL); TIFFSetWarningHandlerExt(NULL); if (clientstate->fp) { TRACE((""Opening using fd: %d\n"",clientstate->fp)); lseek(clientstate->fp,0,SEEK_SET); // Sometimes, I get it set to the end. tiff = TIFFFdOpen(clientstate->fp, filename, mode); } else { TRACE((""Opening from string\n"")); tiff = TIFFClientOpen(filename, mode, (thandle_t) clientstate, _tiffReadProc, _tiffWriteProc, _tiffSeekProc, _tiffCloseProc, _tiffSizeProc, _tiffMapProc, _tiffUnmapProc); } if (!tiff){ TRACE((""Error, didn't get the tiff\n"")); state->errcode = IMAGING_CODEC_BROKEN; return -1; } if (clientstate->ifd){ int rv; uint32 ifdoffset = clientstate->ifd; TRACE((""reading tiff ifd %u\n"", ifdoffset)); rv = TIFFSetSubDirectory(tiff, ifdoffset); if (!rv){ TRACE((""error in TIFFSetSubDirectory"")); return -1; } } if (TIFFIsTiled(tiff)) { UINT32 x, y, tile_y, row_byte_size; UINT32 tile_width, tile_length, current_tile_width; UINT8 *new_data; TIFFGetField(tiff, TIFFTAG_TILEWIDTH, &tile_width); TIFFGetField(tiff, TIFFTAG_TILELENGTH, &tile_length); // We could use TIFFTileSize, but for YCbCr data it returns subsampled data size row_byte_size = (tile_width * state->bits + 7) / 8; /* overflow check for realloc */ if (INT_MAX / row_byte_size < tile_length) { state->errcode = IMAGING_CODEC_MEMORY; TIFFClose(tiff); return -1; } state->bytes = row_byte_size * tile_length; /* realloc to fit whole tile */ /* malloc check above */ new_data = realloc (state->buffer, state->bytes); if (!new_data) { state->errcode = IMAGING_CODEC_MEMORY; TIFFClose(tiff); return -1; } state->buffer = new_data; TRACE((""TIFFTileSize: %d\n"", state->bytes)); for (y = state->yoff; y < state->ysize; y += tile_length) { for (x = state->xoff; x < state->xsize; x += tile_width) { if (ReadTile(tiff, x, y, (UINT32*) state->buffer) == -1) { TRACE((""Decode Error, Tile at %dx%d\n"", x, y)); state->errcode = IMAGING_CODEC_BROKEN; TIFFClose(tiff); return -1; } TRACE((""Read tile at %dx%d; \n\n"", x, y)); current_tile_width = min(tile_width, state->xsize - x); // iterate over each line in the tile and stuff data into image for (tile_y = 0; tile_y < min(tile_length, state->ysize - y); tile_y++) { TRACE((""Writing tile data at %dx%d using tile_width: %d; \n"", tile_y + y, x, current_tile_width)); // UINT8 * bbb = state->buffer + tile_y * row_byte_size; // TRACE((""chars: %x%x%x%x\n"", ((UINT8 *)bbb)[0], ((UINT8 *)bbb)[1], ((UINT8 *)bbb)[2], ((UINT8 *)bbb)[3])); state->shuffle((UINT8*) im->image[tile_y + y] + x * im->pixelsize, state->buffer + tile_y * row_byte_size, current_tile_width ); } } } } else { UINT32 strip_row, row_byte_size; UINT8 *new_data; UINT32 rows_per_strip; int ret; ret = TIFFGetField(tiff, TIFFTAG_ROWSPERSTRIP, &rows_per_strip); if (ret != 1) { rows_per_strip = state->ysize; } TRACE((""RowsPerStrip: %u \n"", rows_per_strip)); // We could use TIFFStripSize, but for YCbCr data it returns subsampled data size row_byte_size = (state->xsize * state->bits + 7) / 8; /* overflow check for realloc */ if (INT_MAX / row_byte_size < rows_per_strip) { state->errcode = IMAGING_CODEC_MEMORY; TIFFClose(tiff); return -1; } state->bytes = rows_per_strip * row_byte_size; TRACE((""StripSize: %d \n"", state->bytes)); /* realloc to fit whole strip */ /* malloc check above */ new_data = realloc (state->buffer, state->bytes); if (!new_data) { state->errcode = IMAGING_CODEC_MEMORY; TIFFClose(tiff); return -1; } state->buffer = new_data; for (; state->y < state->ysize; state->y += rows_per_strip) { if (ReadStrip(tiff, state->y, (UINT32 *)state->buffer) == -1) { TRACE((""Decode Error, strip %d\n"", TIFFComputeStrip(tiff, state->y, 0))); state->errcode = IMAGING_CODEC_BROKEN; TIFFClose(tiff); return -1; } TRACE((""Decoded strip for row %d \n"", state->y)); // iterate over each row in the strip and stuff data into image for (strip_row = 0; strip_row < min(rows_per_strip, state->ysize - state->y); strip_row++) { TRACE((""Writing data into line %d ; \n"", state->y + strip_row)); // UINT8 * bbb = state->buffer + strip_row * (state->bytes / rows_per_strip); // TRACE((""chars: %x %x %x %x\n"", ((UINT8 *)bbb)[0], ((UINT8 *)bbb)[1], ((UINT8 *)bbb)[2], ((UINT8 *)bbb)[3])); state->shuffle((UINT8*) im->image[state->y + state->yoff + strip_row] + state->xoff * im->pixelsize, state->buffer + strip_row * row_byte_size, state->xsize); } } } TIFFClose(tiff); TRACE((""Done Decoding, Returning \n"")); // Returning -1 here to force ImageFile.load to break, rather than // even think about looping back around. return -1; }","{'deleted': [{'line_no': 76, 'char_start': 3145, 'char_end': 3197, 'line': ' state->bytes = row_byte_size * tile_length;\n'}, {'line_no': 78, 'char_start': 3198, 'char_end': 3238, 'line': ' /* overflow check for malloc */\n'}, {'line_no': 79, 'char_start': 3238, 'char_end': 3280, 'line': ' if (state->bytes > INT_MAX - 1) {\n'}], 'added': [{'line_no': 77, 'char_start': 3146, 'char_end': 3187, 'line': ' /* overflow check for realloc */\n'}, {'line_no': 78, 'char_start': 3187, 'char_end': 3240, 'line': ' if (INT_MAX / row_byte_size < tile_length) {\n'}, {'line_no': 83, 'char_start': 3353, 'char_end': 3362, 'line': ' \n'}, {'line_no': 84, 'char_start': 3362, 'char_end': 3414, 'line': ' state->bytes = row_byte_size * tile_length;\n'}, {'line_no': 87, 'char_start': 3455, 'char_end': 3488, 'line': ' /* malloc check above */\n'}, {'line_no': 140, 'char_start': 5576, 'char_end': 5577, 'line': '\n'}, {'line_no': 141, 'char_start': 5577, 'char_end': 5618, 'line': ' /* overflow check for realloc */\n'}, {'line_no': 142, 'char_start': 5618, 'char_end': 5674, 'line': ' if (INT_MAX / row_byte_size < rows_per_strip) {\n'}, {'line_no': 143, 'char_start': 5674, 'char_end': 5725, 'line': ' state->errcode = IMAGING_CODEC_MEMORY;\n'}, {'line_no': 144, 'char_start': 5725, 'char_end': 5754, 'line': ' TIFFClose(tiff);\n'}, {'line_no': 145, 'char_start': 5754, 'char_end': 5777, 'line': ' return -1;\n'}, {'line_no': 146, 'char_start': 5777, 'char_end': 5787, 'line': ' }\n'}, {'line_no': 147, 'char_start': 5787, 'char_end': 5796, 'line': ' \n'}, {'line_no': 153, 'char_start': 5945, 'char_end': 5978, 'line': ' /* malloc check above */\n'}]}","{'deleted': [{'char_start': 3145, 'char_end': 3197, 'chars': ' state->bytes = row_byte_size * tile_length;\n'}, {'char_start': 3228, 'char_end': 3229, 'chars': 'm'}, {'char_start': 3250, 'char_end': 3265, 'chars': 'state->bytes > '}, {'char_start': 3273, 'char_end': 3274, 'chars': '-'}, {'char_start': 3275, 'char_end': 3276, 'chars': '1'}], 'added': [{'char_start': 3176, 'char_end': 3178, 'chars': 're'}, {'char_start': 3207, 'char_end': 3224, 'chars': '/ row_byte_size <'}, {'char_start': 3225, 'char_end': 3236, 'chars': 'tile_length'}, {'char_start': 3353, 'char_end': 3414, 'chars': ' \n state->bytes = row_byte_size * tile_length;\n'}, {'char_start': 3450, 'char_end': 3483, 'chars': 'e */\n /* malloc check abov'}, {'char_start': 5576, 'char_end': 5796, 'chars': '\n /* overflow check for realloc */\n if (INT_MAX / row_byte_size < rows_per_strip) {\n state->errcode = IMAGING_CODEC_MEMORY;\n TIFFClose(tiff);\n return -1;\n }\n \n'}, {'char_start': 5941, 'char_end': 5974, 'chars': ' */\n /* malloc check above'}]}",github.com/python-pillow/Pillow/commit/4e2def2539ec13e53a82e06c4b3daf00454100c4,src/libImaging/TiffDecode.c,cwe-190,1977 cwe-787,make_canonical,"make_canonical(struct ly_ctx *ctx, int type, const char **value, void *data1, void *data2) { const uint16_t buf_len = 511; char buf[buf_len + 1]; struct lys_type_bit **bits = NULL; struct lyxp_expr *exp; const char *module_name, *cur_expr, *end; int i, j, count; int64_t num; uint64_t unum; uint8_t c; #define LOGBUF(str) LOGERR(ctx, LY_EINVAL, ""Value \""%s\"" is too long."", str) switch (type) { case LY_TYPE_BITS: bits = (struct lys_type_bit **)data1; count = *((int *)data2); /* in canonical form, the bits are ordered by their position */ buf[0] = '\0'; for (i = 0; i < count; i++) { if (!bits[i]) { /* bit not set */ continue; } if (buf[0]) { LY_CHECK_ERR_RETURN(strlen(buf) + 1 + strlen(bits[i]->name) > buf_len, LOGBUF(bits[i]->name), -1); sprintf(buf + strlen(buf), "" %s"", bits[i]->name); } else { LY_CHECK_ERR_RETURN(strlen(bits[i]->name) > buf_len, LOGBUF(bits[i]->name), -1); strcpy(buf, bits[i]->name); } } break; case LY_TYPE_IDENT: module_name = (const char *)data1; /* identity must always have a prefix */ if (!strchr(*value, ':')) { sprintf(buf, ""%s:%s"", module_name, *value); } else { strcpy(buf, *value); } break; case LY_TYPE_INST: exp = lyxp_parse_expr(ctx, *value); LY_CHECK_ERR_RETURN(!exp, LOGINT(ctx), -1); module_name = NULL; count = 0; for (i = 0; (unsigned)i < exp->used; ++i) { cur_expr = &exp->expr[exp->expr_pos[i]]; /* copy WS */ if (i && ((end = exp->expr + exp->expr_pos[i - 1] + exp->tok_len[i - 1]) != cur_expr)) { if (count + (cur_expr - end) > buf_len) { lyxp_expr_free(exp); LOGBUF(end); return -1; } strncpy(&buf[count], end, cur_expr - end); count += cur_expr - end; } if ((exp->tokens[i] == LYXP_TOKEN_NAMETEST) && (end = strnchr(cur_expr, ':', exp->tok_len[i]))) { /* get the module name with "":"" */ ++end; j = end - cur_expr; if (!module_name || strncmp(cur_expr, module_name, j)) { /* print module name with colon, it does not equal to the parent one */ if (count + j > buf_len) { lyxp_expr_free(exp); LOGBUF(cur_expr); return -1; } strncpy(&buf[count], cur_expr, j); count += j; } module_name = cur_expr; /* copy the rest */ if (count + (exp->tok_len[i] - j) > buf_len) { lyxp_expr_free(exp); LOGBUF(end); return -1; } strncpy(&buf[count], end, exp->tok_len[i] - j); count += exp->tok_len[i] - j; } else { if (count + exp->tok_len[i] > buf_len) { lyxp_expr_free(exp); LOGBUF(&exp->expr[exp->expr_pos[i]]); return -1; } strncpy(&buf[count], &exp->expr[exp->expr_pos[i]], exp->tok_len[i]); count += exp->tok_len[i]; } } if (count > buf_len) { LOGINT(ctx); lyxp_expr_free(exp); return -1; } buf[count] = '\0'; lyxp_expr_free(exp); break; case LY_TYPE_DEC64: num = *((int64_t *)data1); c = *((uint8_t *)data2); if (num) { count = sprintf(buf, ""%""PRId64"" "", num); if ( (num > 0 && (count - 1) <= c) || (count - 2) <= c ) { /* we have 0. value, print the value with the leading zeros * (one for 0. and also keep the correct with of num according * to fraction-digits value) * for (num<0) - extra character for '-' sign */ count = sprintf(buf, ""%0*""PRId64"" "", (num > 0) ? (c + 1) : (c + 2), num); } for (i = c, j = 1; i > 0 ; i--) { if (j && i > 1 && buf[count - 2] == '0') { /* we have trailing zero to skip */ buf[count - 1] = '\0'; } else { j = 0; buf[count - 1] = buf[count - 2]; } count--; } buf[count - 1] = '.'; } else { /* zero */ sprintf(buf, ""0.0""); } break; case LY_TYPE_INT8: case LY_TYPE_INT16: case LY_TYPE_INT32: case LY_TYPE_INT64: num = *((int64_t *)data1); sprintf(buf, ""%""PRId64, num); break; case LY_TYPE_UINT8: case LY_TYPE_UINT16: case LY_TYPE_UINT32: case LY_TYPE_UINT64: unum = *((uint64_t *)data1); sprintf(buf, ""%""PRIu64, unum); break; default: /* should not be even called - just do nothing */ return 0; } if (strcmp(buf, *value)) { lydict_remove(ctx, *value); *value = lydict_insert(ctx, buf, 0); return 1; } return 0; #undef LOGBUF }","make_canonical(struct ly_ctx *ctx, int type, const char **value, void *data1, void *data2) { const uint16_t buf_len = 511; char buf[buf_len + 1]; struct lys_type_bit **bits = NULL; struct lyxp_expr *exp; const char *module_name, *cur_expr, *end; int i, j, count; int64_t num; uint64_t unum; uint8_t c; #define LOGBUF(str) LOGERR(ctx, LY_EINVAL, ""Value \""%s\"" is too long."", str) switch (type) { case LY_TYPE_BITS: bits = (struct lys_type_bit **)data1; count = *((int *)data2); /* in canonical form, the bits are ordered by their position */ buf[0] = '\0'; for (i = 0; i < count; i++) { if (!bits[i]) { /* bit not set */ continue; } if (buf[0]) { LY_CHECK_ERR_RETURN(strlen(buf) + 1 + strlen(bits[i]->name) > buf_len, LOGBUF(bits[i]->name), -1); sprintf(buf + strlen(buf), "" %s"", bits[i]->name); } else { LY_CHECK_ERR_RETURN(strlen(bits[i]->name) > buf_len, LOGBUF(bits[i]->name), -1); strcpy(buf, bits[i]->name); } } break; case LY_TYPE_IDENT: module_name = (const char *)data1; /* identity must always have a prefix */ if (!strchr(*value, ':')) { LY_CHECK_ERR_RETURN(strlen(module_name) + 1 + strlen(*value) > buf_len, LOGBUF(*value), -1); sprintf(buf, ""%s:%s"", module_name, *value); } else { LY_CHECK_ERR_RETURN(strlen(*value) > buf_len, LOGBUF(*value), -1); strcpy(buf, *value); } break; case LY_TYPE_INST: exp = lyxp_parse_expr(ctx, *value); LY_CHECK_ERR_RETURN(!exp, LOGINT(ctx), -1); module_name = NULL; count = 0; for (i = 0; (unsigned)i < exp->used; ++i) { cur_expr = &exp->expr[exp->expr_pos[i]]; /* copy WS */ if (i && ((end = exp->expr + exp->expr_pos[i - 1] + exp->tok_len[i - 1]) != cur_expr)) { if (count + (cur_expr - end) > buf_len) { lyxp_expr_free(exp); LOGBUF(end); return -1; } strncpy(&buf[count], end, cur_expr - end); count += cur_expr - end; } if ((exp->tokens[i] == LYXP_TOKEN_NAMETEST) && (end = strnchr(cur_expr, ':', exp->tok_len[i]))) { /* get the module name with "":"" */ ++end; j = end - cur_expr; if (!module_name || strncmp(cur_expr, module_name, j)) { /* print module name with colon, it does not equal to the parent one */ if (count + j > buf_len) { lyxp_expr_free(exp); LOGBUF(cur_expr); return -1; } strncpy(&buf[count], cur_expr, j); count += j; } module_name = cur_expr; /* copy the rest */ if (count + (exp->tok_len[i] - j) > buf_len) { lyxp_expr_free(exp); LOGBUF(end); return -1; } strncpy(&buf[count], end, exp->tok_len[i] - j); count += exp->tok_len[i] - j; } else { if (count + exp->tok_len[i] > buf_len) { lyxp_expr_free(exp); LOGBUF(&exp->expr[exp->expr_pos[i]]); return -1; } strncpy(&buf[count], &exp->expr[exp->expr_pos[i]], exp->tok_len[i]); count += exp->tok_len[i]; } } if (count > buf_len) { LOGINT(ctx); lyxp_expr_free(exp); return -1; } buf[count] = '\0'; lyxp_expr_free(exp); break; case LY_TYPE_DEC64: num = *((int64_t *)data1); c = *((uint8_t *)data2); if (num) { count = sprintf(buf, ""%""PRId64"" "", num); if ( (num > 0 && (count - 1) <= c) || (count - 2) <= c ) { /* we have 0. value, print the value with the leading zeros * (one for 0. and also keep the correct with of num according * to fraction-digits value) * for (num<0) - extra character for '-' sign */ count = sprintf(buf, ""%0*""PRId64"" "", (num > 0) ? (c + 1) : (c + 2), num); } for (i = c, j = 1; i > 0 ; i--) { if (j && i > 1 && buf[count - 2] == '0') { /* we have trailing zero to skip */ buf[count - 1] = '\0'; } else { j = 0; buf[count - 1] = buf[count - 2]; } count--; } buf[count - 1] = '.'; } else { /* zero */ sprintf(buf, ""0.0""); } break; case LY_TYPE_INT8: case LY_TYPE_INT16: case LY_TYPE_INT32: case LY_TYPE_INT64: num = *((int64_t *)data1); sprintf(buf, ""%""PRId64, num); break; case LY_TYPE_UINT8: case LY_TYPE_UINT16: case LY_TYPE_UINT32: case LY_TYPE_UINT64: unum = *((uint64_t *)data1); sprintf(buf, ""%""PRIu64, unum); break; default: /* should not be even called - just do nothing */ return 0; } if (strcmp(buf, *value)) { lydict_remove(ctx, *value); *value = lydict_insert(ctx, buf, 0); return 1; } return 0; #undef LOGBUF }","{'deleted': [], 'added': [{'line_no': 40, 'char_start': 1335, 'char_end': 1440, 'line': ' LY_CHECK_ERR_RETURN(strlen(module_name) + 1 + strlen(*value) > buf_len, LOGBUF(*value), -1);\n'}, {'line_no': 43, 'char_start': 1513, 'char_end': 1592, 'line': ' LY_CHECK_ERR_RETURN(strlen(*value) > buf_len, LOGBUF(*value), -1);\n'}]}","{'deleted': [], 'added': [{'char_start': 1347, 'char_end': 1452, 'chars': 'LY_CHECK_ERR_RETURN(strlen(module_name) + 1 + strlen(*value) > buf_len, LOGBUF(*value), -1);\n '}, {'char_start': 1512, 'char_end': 1591, 'chars': '\n LY_CHECK_ERR_RETURN(strlen(*value) > buf_len, LOGBUF(*value), -1);'}]}",github.com/CESNET/libyang/commit/6980afae2ff9fcd6d67508b0a3f694d75fd059d6,src/parser.c,cwe-787,1424 cwe-476,AP4_AtomSampleTable::GetSample,"AP4_AtomSampleTable::GetSample(AP4_Ordinal index, AP4_Sample& sample) { AP4_Result result; // check that we have an stsc atom if (!m_StscAtom) { return AP4_ERROR_INVALID_FORMAT; } // check that we have a chunk offset table if (m_StcoAtom == NULL && m_Co64Atom == NULL) { return AP4_ERROR_INVALID_FORMAT; } // MP4 uses 1-based indexes internally, so adjust by one index++; // find out in which chunk this sample is located AP4_Ordinal chunk, skip, desc; result = m_StscAtom->GetChunkForSample(index, chunk, skip, desc); if (AP4_FAILED(result)) return result; // check that the result is within bounds if (skip > index) return AP4_ERROR_INTERNAL; // get the atom offset for this chunk AP4_UI64 offset; if (m_StcoAtom) { AP4_UI32 offset_32; result = m_StcoAtom->GetChunkOffset(chunk, offset_32); offset = offset_32; } else { result = m_Co64Atom->GetChunkOffset(chunk, offset); } if (AP4_FAILED(result)) return result; // compute the additional offset inside the chunk for (unsigned int i = index-skip; i < index; i++) { AP4_Size size = 0; if (m_StszAtom) { result = m_StszAtom->GetSampleSize(i, size); } else if (m_Stz2Atom) { result = m_Stz2Atom->GetSampleSize(i, size); } else { result = AP4_ERROR_INVALID_FORMAT; } if (AP4_FAILED(result)) return result; offset += size; } // set the description index sample.SetDescriptionIndex(desc-1); // adjust for 0-based indexes // set the dts and cts AP4_UI32 cts_offset = 0; AP4_UI64 dts = 0; AP4_UI32 duration = 0; result = m_SttsAtom->GetDts(index, dts, &duration); if (AP4_FAILED(result)) return result; sample.SetDuration(duration); sample.SetDts(dts); if (m_CttsAtom == NULL) { sample.SetCts(dts); } else { result = m_CttsAtom->GetCtsOffset(index, cts_offset); if (AP4_FAILED(result)) return result; sample.SetCtsDelta(cts_offset); } // set the size AP4_Size sample_size = 0; if (m_StszAtom) { result = m_StszAtom->GetSampleSize(index, sample_size); } else if (m_Stz2Atom) { result = m_Stz2Atom->GetSampleSize(index, sample_size); } else { result = AP4_ERROR_INVALID_FORMAT; } if (AP4_FAILED(result)) return result; sample.SetSize(sample_size); // set the sync flag if (m_StssAtom == NULL) { sample.SetSync(true); } else { sample.SetSync(m_StssAtom->IsSampleSync(index)); } // set the offset sample.SetOffset(offset); // set the data stream sample.SetDataStream(m_SampleStream); return AP4_SUCCESS; }","AP4_AtomSampleTable::GetSample(AP4_Ordinal index, AP4_Sample& sample) { AP4_Result result; // check that we have an stsc atom if (!m_StscAtom) { return AP4_ERROR_INVALID_FORMAT; } // check that we have a chunk offset table if (m_StcoAtom == NULL && m_Co64Atom == NULL) { return AP4_ERROR_INVALID_FORMAT; } // MP4 uses 1-based indexes internally, so adjust by one index++; // find out in which chunk this sample is located AP4_Ordinal chunk, skip, desc; result = m_StscAtom->GetChunkForSample(index, chunk, skip, desc); if (AP4_FAILED(result)) return result; // check that the result is within bounds if (skip > index) return AP4_ERROR_INTERNAL; // get the atom offset for this chunk AP4_UI64 offset; if (m_StcoAtom) { AP4_UI32 offset_32; result = m_StcoAtom->GetChunkOffset(chunk, offset_32); offset = offset_32; } else { result = m_Co64Atom->GetChunkOffset(chunk, offset); } if (AP4_FAILED(result)) return result; // compute the additional offset inside the chunk for (unsigned int i = index-skip; i < index; i++) { AP4_Size size = 0; if (m_StszAtom) { result = m_StszAtom->GetSampleSize(i, size); } else if (m_Stz2Atom) { result = m_Stz2Atom->GetSampleSize(i, size); } else { result = AP4_ERROR_INVALID_FORMAT; } if (AP4_FAILED(result)) return result; offset += size; } // set the description index sample.SetDescriptionIndex(desc-1); // adjust for 0-based indexes // set the dts and cts AP4_UI32 cts_offset = 0; AP4_UI64 dts = 0; AP4_UI32 duration = 0; if (m_SttsAtom) { result = m_SttsAtom->GetDts(index, dts, &duration); if (AP4_FAILED(result)) return result; } sample.SetDuration(duration); sample.SetDts(dts); if (m_CttsAtom == NULL) { sample.SetCts(dts); } else { result = m_CttsAtom->GetCtsOffset(index, cts_offset); if (AP4_FAILED(result)) return result; sample.SetCtsDelta(cts_offset); } // set the size AP4_Size sample_size = 0; if (m_StszAtom) { result = m_StszAtom->GetSampleSize(index, sample_size); } else if (m_Stz2Atom) { result = m_Stz2Atom->GetSampleSize(index, sample_size); } else { result = AP4_ERROR_INVALID_FORMAT; } if (AP4_FAILED(result)) return result; sample.SetSize(sample_size); // set the sync flag if (m_StssAtom == NULL) { sample.SetSync(true); } else { sample.SetSync(m_StssAtom->IsSampleSync(index)); } // set the offset sample.SetOffset(offset); // set the data stream sample.SetDataStream(m_SampleStream); return AP4_SUCCESS; }","{'deleted': [{'line_no': 59, 'char_start': 1780, 'char_end': 1836, 'line': ' result = m_SttsAtom->GetDts(index, dts, &duration);\n'}, {'line_no': 60, 'char_start': 1836, 'char_end': 1879, 'line': ' if (AP4_FAILED(result)) return result;\n'}], 'added': [{'line_no': 59, 'char_start': 1780, 'char_end': 1802, 'line': ' if (m_SttsAtom) {\n'}, {'line_no': 60, 'char_start': 1802, 'char_end': 1862, 'line': ' result = m_SttsAtom->GetDts(index, dts, &duration);\n'}, {'line_no': 61, 'char_start': 1862, 'char_end': 1909, 'line': ' if (AP4_FAILED(result)) return result;\n'}, {'line_no': 62, 'char_start': 1909, 'char_end': 1915, 'line': ' }\n'}]}","{'deleted': [], 'added': [{'char_start': 1784, 'char_end': 1810, 'chars': 'if (m_SttsAtom) {\n '}, {'char_start': 1866, 'char_end': 1870, 'chars': ' '}, {'char_start': 1908, 'char_end': 1914, 'chars': '\n }'}]}",github.com/axiomatic-systems/Bento4/commit/2f267f89f957088197f4b1fc254632d1645b415d,Source/C++/Core/Ap4AtomSampleTable.cpp,cwe-476,791 cwe-476,ReadPSDChannel,"static MagickBooleanType ReadPSDChannel(Image *image, const ImageInfo *image_info,const PSDInfo *psd_info,LayerInfo* layer_info, const size_t channel,const PSDCompressionType compression, ExceptionInfo *exception) { Image *channel_image, *mask; MagickOffsetType offset; MagickBooleanType status; channel_image=image; mask=(Image *) NULL; if (layer_info->channel_info[channel].type < -1) { const char *option; /* Ignore mask that is not a user supplied layer mask, if the mask is disabled or if the flags have unsupported values. */ option=GetImageOption(image_info,""psd:preserve-opacity-mask""); if ((layer_info->channel_info[channel].type != -2) || (layer_info->mask.flags > 2) || ((layer_info->mask.flags & 0x02) && (IsStringTrue(option) == MagickFalse))) { SeekBlob(image,layer_info->channel_info[channel].size-2,SEEK_CUR); return(MagickTrue); } mask=CloneImage(image,layer_info->mask.page.width, layer_info->mask.page.height,MagickFalse,exception); mask->matte=MagickFalse; channel_image=mask; } offset=TellBlob(image); status=MagickTrue; switch(compression) { case Raw: status=ReadPSDChannelRaw(channel_image,psd_info->channels, layer_info->channel_info[channel].type,exception); break; case RLE: { MagickOffsetType *sizes; sizes=ReadPSDRLESizes(channel_image,psd_info,channel_image->rows); if (sizes == (MagickOffsetType *) NULL) ThrowBinaryException(ResourceLimitError,""MemoryAllocationFailed"", image->filename); status=ReadPSDChannelRLE(channel_image,psd_info, layer_info->channel_info[channel].type,sizes,exception); sizes=(MagickOffsetType *) RelinquishMagickMemory(sizes); } break; case ZipWithPrediction: case ZipWithoutPrediction: #ifdef MAGICKCORE_ZLIB_DELEGATE status=ReadPSDChannelZip(channel_image,layer_info->channels, layer_info->channel_info[channel].type,compression, layer_info->channel_info[channel].size-2,exception); #else (void) ThrowMagickException(exception,GetMagickModule(), MissingDelegateWarning,""DelegateLibrarySupportNotBuiltIn"", ""'%s' (ZLIB)"",image->filename); #endif break; default: (void) ThrowMagickException(exception,GetMagickModule(),TypeWarning, ""CompressionNotSupported"",""'%.20g'"",(double) compression); break; } SeekBlob(image,offset+layer_info->channel_info[channel].size-2,SEEK_SET); if (status == MagickFalse) { if (mask != (Image *) NULL) DestroyImage(mask); ThrowBinaryException(CoderError,""UnableToDecompressImage"", image->filename); } layer_info->mask.image=mask; return(status); }","static MagickBooleanType ReadPSDChannel(Image *image, const ImageInfo *image_info,const PSDInfo *psd_info,LayerInfo* layer_info, const size_t channel,const PSDCompressionType compression, ExceptionInfo *exception) { Image *channel_image, *mask; MagickOffsetType offset; MagickBooleanType status; channel_image=image; mask=(Image *) NULL; if (layer_info->channel_info[channel].type < -1) { const char *option; /* Ignore mask that is not a user supplied layer mask, if the mask is disabled or if the flags have unsupported values. */ option=GetImageOption(image_info,""psd:preserve-opacity-mask""); if ((layer_info->channel_info[channel].type != -2) || (layer_info->mask.flags > 2) || ((layer_info->mask.flags & 0x02) && (IsStringTrue(option) == MagickFalse))) { SeekBlob(image,layer_info->channel_info[channel].size-2,SEEK_CUR); return(MagickTrue); } mask=CloneImage(image,layer_info->mask.page.width, layer_info->mask.page.height,MagickFalse,exception); if (mask != (Image *) NULL) { mask->matte=MagickFalse; channel_image=mask; } } offset=TellBlob(image); status=MagickTrue; switch(compression) { case Raw: status=ReadPSDChannelRaw(channel_image,psd_info->channels, layer_info->channel_info[channel].type,exception); break; case RLE: { MagickOffsetType *sizes; sizes=ReadPSDRLESizes(channel_image,psd_info,channel_image->rows); if (sizes == (MagickOffsetType *) NULL) ThrowBinaryException(ResourceLimitError,""MemoryAllocationFailed"", image->filename); status=ReadPSDChannelRLE(channel_image,psd_info, layer_info->channel_info[channel].type,sizes,exception); sizes=(MagickOffsetType *) RelinquishMagickMemory(sizes); } break; case ZipWithPrediction: case ZipWithoutPrediction: #ifdef MAGICKCORE_ZLIB_DELEGATE status=ReadPSDChannelZip(channel_image,layer_info->channels, layer_info->channel_info[channel].type,compression, layer_info->channel_info[channel].size-2,exception); #else (void) ThrowMagickException(exception,GetMagickModule(), MissingDelegateWarning,""DelegateLibrarySupportNotBuiltIn"", ""'%s' (ZLIB)"",image->filename); #endif break; default: (void) ThrowMagickException(exception,GetMagickModule(),TypeWarning, ""CompressionNotSupported"",""'%.20g'"",(double) compression); break; } SeekBlob(image,offset+layer_info->channel_info[channel].size-2,SEEK_SET); if (status == MagickFalse) { if (mask != (Image *) NULL) DestroyImage(mask); ThrowBinaryException(CoderError,""UnableToDecompressImage"", image->filename); } layer_info->mask.image=mask; return(status); }","{'deleted': [{'line_no': 36, 'char_start': 1110, 'char_end': 1141, 'line': ' mask->matte=MagickFalse;\n'}, {'line_no': 37, 'char_start': 1141, 'char_end': 1167, 'line': ' channel_image=mask;\n'}], 'added': [{'line_no': 36, 'char_start': 1110, 'char_end': 1144, 'line': ' if (mask != (Image *) NULL)\n'}, {'line_no': 37, 'char_start': 1144, 'char_end': 1154, 'line': ' {\n'}, {'line_no': 38, 'char_start': 1154, 'char_end': 1189, 'line': ' mask->matte=MagickFalse;\n'}, {'line_no': 39, 'char_start': 1189, 'char_end': 1219, 'line': ' channel_image=mask;\n'}, {'line_no': 40, 'char_start': 1219, 'char_end': 1229, 'line': ' }\n'}]}","{'deleted': [], 'added': [{'char_start': 1116, 'char_end': 1164, 'chars': 'if (mask != (Image *) NULL)\n {\n '}, {'char_start': 1195, 'char_end': 1199, 'chars': ' '}, {'char_start': 1218, 'char_end': 1228, 'chars': '\n }'}]}",github.com/ImageMagick/ImageMagick/commit/7f2dc7a1afc067d0c89f12c82bcdec0445fb1b94,coders/psd.c,cwe-476,705 cwe-476,generatePreview,"generatePreview (const char inFileName[], float exposure, int previewWidth, int &previewHeight, Array2D &previewPixels) { // // Read the input file // RgbaInputFile in (inFileName); Box2i dw = in.dataWindow(); float a = in.pixelAspectRatio(); int w = dw.max.x - dw.min.x + 1; int h = dw.max.y - dw.min.y + 1; Array2D pixels (h, w); in.setFrameBuffer (ComputeBasePointer (&pixels[0][0], dw), 1, w); in.readPixels (dw.min.y, dw.max.y); // // Make a preview image // previewHeight = max (int (h / (w * a) * previewWidth + .5f), 1); previewPixels.resizeErase (previewHeight, previewWidth); float fx = (previewWidth > 0)? (float (w - 1) / (previewWidth - 1)): 1; float fy = (previewHeight > 0)? (float (h - 1) / (previewHeight - 1)): 1; float m = Math::pow (2.f, IMATH_NAMESPACE::clamp (exposure + 2.47393f, -20.f, 20.f)); for (int y = 0; y < previewHeight; ++y) { for (int x = 0; x < previewWidth; ++x) { PreviewRgba &preview = previewPixels[y][x]; const Rgba &pixel = pixels[int (y * fy + .5f)][int (x * fx + .5f)]; preview.r = gamma (pixel.r, m); preview.g = gamma (pixel.g, m); preview.b = gamma (pixel.b, m); preview.a = int (IMATH_NAMESPACE::clamp (pixel.a * 255.f, 0.f, 255.f) + .5f); } } }","generatePreview (const char inFileName[], float exposure, int previewWidth, int &previewHeight, Array2D &previewPixels) { // // Read the input file // RgbaInputFile in (inFileName); Box2i dw = in.dataWindow(); float a = in.pixelAspectRatio(); int w = dw.max.x - dw.min.x + 1; int h = dw.max.y - dw.min.y + 1; Array2D pixels (h, w); in.setFrameBuffer (ComputeBasePointer (&pixels[0][0], dw), 1, w); in.readPixels (dw.min.y, dw.max.y); // // Make a preview image // previewHeight = max (int (h / (w * a) * previewWidth + .5f), 1); previewPixels.resizeErase (previewHeight, previewWidth); float fx = (previewWidth > 1)? (float (w - 1) / (previewWidth - 1)): 1; float fy = (previewHeight > 1)? (float (h - 1) / (previewHeight - 1)): 1; float m = Math::pow (2.f, IMATH_NAMESPACE::clamp (exposure + 2.47393f, -20.f, 20.f)); for (int y = 0; y < previewHeight; ++y) { for (int x = 0; x < previewWidth; ++x) { PreviewRgba &preview = previewPixels[y][x]; const Rgba &pixel = pixels[int (y * fy + .5f)][int (x * fx + .5f)]; preview.r = gamma (pixel.r, m); preview.g = gamma (pixel.g, m); preview.b = gamma (pixel.b, m); preview.a = int (IMATH_NAMESPACE::clamp (pixel.a * 255.f, 0.f, 255.f) + .5f); } } }","{'deleted': [{'line_no': 29, 'char_start': 689, 'char_end': 767, 'line': ' float fx = (previewWidth > 0)? (float (w - 1) / (previewWidth - 1)): 1;\n'}, {'line_no': 30, 'char_start': 767, 'char_end': 845, 'line': ' float fy = (previewHeight > 0)? (float (h - 1) / (previewHeight - 1)): 1;\n'}], 'added': [{'line_no': 29, 'char_start': 689, 'char_end': 767, 'line': ' float fx = (previewWidth > 1)? (float (w - 1) / (previewWidth - 1)): 1;\n'}, {'line_no': 30, 'char_start': 767, 'char_end': 845, 'line': ' float fy = (previewHeight > 1)? (float (h - 1) / (previewHeight - 1)): 1;\n'}]}","{'deleted': [{'char_start': 721, 'char_end': 722, 'chars': '0'}, {'char_start': 799, 'char_end': 800, 'chars': '0'}], 'added': [{'char_start': 721, 'char_end': 722, 'chars': '1'}, {'char_start': 799, 'char_end': 800, 'chars': '1'}]}",github.com/AcademySoftwareFoundation/openexr/commit/74504503cff86e986bac441213c403b0ba28d58f,OpenEXR/exrmakepreview/makePreview.cpp,cwe-476,462 cwe-476,changedline,"static int changedline (const Proto *p, int oldpc, int newpc) { while (oldpc++ < newpc) { if (p->lineinfo[oldpc] != 0) return (luaG_getfuncline(p, oldpc - 1) != luaG_getfuncline(p, newpc)); } return 0; /* no line changes in the way */ }","static int changedline (const Proto *p, int oldpc, int newpc) { if (p->lineinfo == NULL) /* no debug information? */ return 0; while (oldpc++ < newpc) { if (p->lineinfo[oldpc] != 0) return (luaG_getfuncline(p, oldpc - 1) != luaG_getfuncline(p, newpc)); } return 0; /* no line changes between positions */ }","{'deleted': [{'line_no': 6, 'char_start': 206, 'char_end': 252, 'line': ' return 0; /* no line changes in the way */\n'}], 'added': [{'line_no': 2, 'char_start': 64, 'char_end': 120, 'line': ' if (p->lineinfo == NULL) /* no debug information? */\n'}, {'line_no': 3, 'char_start': 120, 'char_end': 134, 'line': ' return 0;\n'}, {'line_no': 8, 'char_start': 276, 'char_end': 329, 'line': ' return 0; /* no line changes between positions */\n'}]}","{'deleted': [{'char_start': 238, 'char_end': 239, 'chars': 'i'}, {'char_start': 242, 'char_end': 248, 'chars': 'he way'}], 'added': [{'char_start': 66, 'char_end': 136, 'chars': 'if (p->lineinfo == NULL) /* no debug information? */\n return 0;\n '}, {'char_start': 308, 'char_end': 310, 'chars': 'be'}, {'char_start': 311, 'char_end': 312, 'chars': 'w'}, {'char_start': 313, 'char_end': 315, 'chars': 'en'}, {'char_start': 316, 'char_end': 325, 'chars': 'positions'}]}",github.com/lua/lua/commit/ae5b5ba529753c7a653901ffc29b5ea24c3fdf3a,ldebug.c,cwe-476,89 cwe-416,usb_sg_cancel,"void usb_sg_cancel(struct usb_sg_request *io) { unsigned long flags; int i, retval; spin_lock_irqsave(&io->lock, flags); if (io->status) { spin_unlock_irqrestore(&io->lock, flags); return; } /* shut everything down */ io->status = -ECONNRESET; spin_unlock_irqrestore(&io->lock, flags); for (i = io->entries - 1; i >= 0; --i) { usb_block_urb(io->urbs[i]); retval = usb_unlink_urb(io->urbs[i]); if (retval != -EINPROGRESS && retval != -ENODEV && retval != -EBUSY && retval != -EIDRM) dev_warn(&io->dev->dev, ""%s, unlink --> %d\n"", __func__, retval); } }","void usb_sg_cancel(struct usb_sg_request *io) { unsigned long flags; int i, retval; spin_lock_irqsave(&io->lock, flags); if (io->status || io->count == 0) { spin_unlock_irqrestore(&io->lock, flags); return; } /* shut everything down */ io->status = -ECONNRESET; io->count++; /* Keep the request alive until we're done */ spin_unlock_irqrestore(&io->lock, flags); for (i = io->entries - 1; i >= 0; --i) { usb_block_urb(io->urbs[i]); retval = usb_unlink_urb(io->urbs[i]); if (retval != -EINPROGRESS && retval != -ENODEV && retval != -EBUSY && retval != -EIDRM) dev_warn(&io->dev->dev, ""%s, unlink --> %d\n"", __func__, retval); } spin_lock_irqsave(&io->lock, flags); io->count--; if (!io->count) complete(&io->complete); spin_unlock_irqrestore(&io->lock, flags); }","{'deleted': [{'line_no': 7, 'char_start': 125, 'char_end': 144, 'line': '\tif (io->status) {\n'}], 'added': [{'line_no': 7, 'char_start': 125, 'char_end': 162, 'line': '\tif (io->status || io->count == 0) {\n'}, {'line_no': 13, 'char_start': 274, 'char_end': 335, 'line': ""\tio->count++;\t\t/* Keep the request alive until we're done */\n""}, {'line_no': 27, 'char_start': 678, 'char_end': 679, 'line': '\n'}, {'line_no': 28, 'char_start': 679, 'char_end': 717, 'line': '\tspin_lock_irqsave(&io->lock, flags);\n'}, {'line_no': 29, 'char_start': 717, 'char_end': 731, 'line': '\tio->count--;\n'}, {'line_no': 30, 'char_start': 731, 'char_end': 748, 'line': '\tif (!io->count)\n'}, {'line_no': 31, 'char_start': 748, 'char_end': 775, 'line': '\t\tcomplete(&io->complete);\n'}, {'line_no': 32, 'char_start': 775, 'char_end': 818, 'line': '\tspin_unlock_irqrestore(&io->lock, flags);\n'}]}","{'deleted': [], 'added': [{'char_start': 140, 'char_end': 158, 'chars': ' || io->count == 0'}, {'char_start': 273, 'char_end': 334, 'chars': ""\n\tio->count++;\t\t/* Keep the request alive until we're done */""}, {'char_start': 677, 'char_end': 817, 'chars': '\n\n\tspin_lock_irqsave(&io->lock, flags);\n\tio->count--;\n\tif (!io->count)\n\t\tcomplete(&io->complete);\n\tspin_unlock_irqrestore(&io->lock, flags);'}]}",github.com/torvalds/linux/commit/056ad39ee9253873522f6469c3364964a322912b,drivers/usb/core/message.c,cwe-416,193 cwe-416,hci_uart_set_proto,"static int hci_uart_set_proto(struct hci_uart *hu, int id) { const struct hci_uart_proto *p; int err; p = hci_uart_get_proto(id); if (!p) return -EPROTONOSUPPORT; hu->proto = p; set_bit(HCI_UART_PROTO_READY, &hu->flags); err = hci_uart_register_dev(hu); if (err) { clear_bit(HCI_UART_PROTO_READY, &hu->flags); return err; } return 0; }","static int hci_uart_set_proto(struct hci_uart *hu, int id) { const struct hci_uart_proto *p; int err; p = hci_uart_get_proto(id); if (!p) return -EPROTONOSUPPORT; hu->proto = p; err = hci_uart_register_dev(hu); if (err) { return err; } set_bit(HCI_UART_PROTO_READY, &hu->flags); return 0; }","{'deleted': [{'line_no': 11, 'char_start': 187, 'char_end': 231, 'line': '\tset_bit(HCI_UART_PROTO_READY, &hu->flags);\n'}, {'line_no': 15, 'char_start': 278, 'char_end': 325, 'line': '\t\tclear_bit(HCI_UART_PROTO_READY, &hu->flags);\n'}], 'added': [{'line_no': 17, 'char_start': 252, 'char_end': 296, 'line': '\tset_bit(HCI_UART_PROTO_READY, &hu->flags);\n'}]}","{'deleted': [{'char_start': 187, 'char_end': 231, 'chars': '\tset_bit(HCI_UART_PROTO_READY, &hu->flags);\n'}, {'char_start': 280, 'char_end': 282, 'chars': 'cl'}, {'char_start': 283, 'char_end': 284, 'chars': 'a'}, {'char_start': 324, 'char_end': 342, 'chars': '\n\t\treturn err;\n\t}\n'}], 'added': [{'char_start': 236, 'char_end': 237, 'chars': 'r'}, {'char_start': 238, 'char_end': 245, 'chars': 'turn er'}, {'char_start': 246, 'char_end': 256, 'chars': ';\n\t}\n\n\tset'}]}",github.com/torvalds/linux/commit/56897b217a1d0a91c9920cb418d6b3fe922f590a,drivers/bluetooth/hci_ldisc.c,cwe-416,112 cwe-078,test_create_host," def test_create_host(self): self.flags(lock_path=self.tempdir) #record self.clear_mox() self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, ""get_cpg"", self.fake_get_cpg) self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, ""get_domain"", self.fake_get_domain) _run_ssh = self.mox.CreateMock(hpdriver.hpcommon.HP3PARCommon._run_ssh) self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, ""_run_ssh"", _run_ssh) show_host_cmd = 'showhost -verbose fakehost' _run_ssh(show_host_cmd, False).AndReturn([pack('no hosts listed'), '']) create_host_cmd = ('createhost -iscsi -persona 1 -domain ' '(\'OpenStack\',) ' 'fakehost iqn.1993-08.org.debian:01:222') _run_ssh(create_host_cmd, False).AndReturn([CLI_CR, '']) _run_ssh(show_host_cmd, False).AndReturn([pack(ISCSI_HOST_RET), '']) self.mox.ReplayAll() host = self.driver._create_host(self.volume, self.connector) self.assertEqual(host['name'], self.FAKE_HOST)"," def test_create_host(self): self.flags(lock_path=self.tempdir) #record self.clear_mox() self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, ""get_cpg"", self.fake_get_cpg) self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, ""get_domain"", self.fake_get_domain) _run_ssh = self.mox.CreateMock(hpdriver.hpcommon.HP3PARCommon._run_ssh) self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, ""_run_ssh"", _run_ssh) show_host_cmd = ['showhost', '-verbose', 'fakehost'] _run_ssh(show_host_cmd, False).AndReturn([pack('no hosts listed'), '']) create_host_cmd = (['createhost', '-iscsi', '-persona', '1', '-domain', ('OpenStack',), 'fakehost', 'iqn.1993-08.org.debian:01:222']) _run_ssh(create_host_cmd, False).AndReturn([CLI_CR, '']) _run_ssh(show_host_cmd, False).AndReturn([pack(ISCSI_HOST_RET), '']) self.mox.ReplayAll() host = self.driver._create_host(self.volume, self.connector) self.assertEqual(host['name'], self.FAKE_HOST)","{'deleted': [{'line_no': 13, 'char_start': 497, 'char_end': 550, 'line': "" show_host_cmd = 'showhost -verbose fakehost'\n""}, {'line_no': 16, 'char_start': 631, 'char_end': 698, 'line': "" create_host_cmd = ('createhost -iscsi -persona 1 -domain '\n""}, {'line_no': 17, 'char_start': 698, 'char_end': 745, 'line': "" '(\\'OpenStack\\',) '\n""}, {'line_no': 18, 'char_start': 745, 'char_end': 814, 'line': "" 'fakehost iqn.1993-08.org.debian:01:222')\n""}], 'added': [{'line_no': 13, 'char_start': 497, 'char_end': 558, 'line': "" show_host_cmd = ['showhost', '-verbose', 'fakehost']\n""}, {'line_no': 16, 'char_start': 639, 'char_end': 719, 'line': "" create_host_cmd = (['createhost', '-iscsi', '-persona', '1', '-domain',\n""}, {'line_no': 17, 'char_start': 719, 'char_end': 775, 'line': "" ('OpenStack',), 'fakehost',\n""}, {'line_no': 18, 'char_start': 775, 'char_end': 837, 'line': "" 'iqn.1993-08.org.debian:01:222'])\n""}]}","{'deleted': [{'char_start': 695, 'char_end': 696, 'chars': ' '}, {'char_start': 725, 'char_end': 726, 'chars': ""'""}, {'char_start': 727, 'char_end': 728, 'chars': '\\'}, {'char_start': 738, 'char_end': 739, 'chars': '\\'}, {'char_start': 772, 'char_end': 781, 'chars': ""'fakehost""}], 'added': [{'char_start': 521, 'char_end': 522, 'chars': '['}, {'char_start': 531, 'char_end': 533, 'chars': ""',""}, {'char_start': 534, 'char_end': 535, 'chars': ""'""}, {'char_start': 543, 'char_end': 545, 'chars': ""',""}, {'char_start': 546, 'char_end': 547, 'chars': ""'""}, {'char_start': 556, 'char_end': 557, 'chars': ']'}, {'char_start': 666, 'char_end': 667, 'chars': '['}, {'char_start': 678, 'char_end': 680, 'chars': ""',""}, {'char_start': 681, 'char_end': 682, 'chars': ""'""}, {'char_start': 688, 'char_end': 690, 'chars': ""',""}, {'char_start': 691, 'char_end': 692, 'chars': ""'""}, {'char_start': 700, 'char_end': 702, 'chars': ""',""}, {'char_start': 703, 'char_end': 704, 'chars': ""'""}, {'char_start': 705, 'char_end': 707, 'chars': ""',""}, {'char_start': 708, 'char_end': 709, 'chars': ""'""}, {'char_start': 717, 'char_end': 718, 'chars': ','}, {'char_start': 719, 'char_end': 720, 'chars': ' '}, {'char_start': 761, 'char_end': 762, 'chars': ','}, {'char_start': 764, 'char_end': 774, 'chars': ""fakehost',""}, {'char_start': 775, 'char_end': 776, 'chars': ' '}, {'char_start': 834, 'char_end': 835, 'chars': ']'}]}",github.com/thatsdone/cinder/commit/c55589b131828f3a595903f6796cb2d0babb772f,cinder/tests/test_hp3par.py,cwe-078,285 cwe-089,also_add,"def also_add(name, also): db = db_connect() cursor = db.cursor() try: cursor.execute(''' INSERT INTO isalso(name,also) VALUES('{}','{}') '''.format(name, also)) db.commit() logger.debug('added to isalso name {} with value {}'.format( name, also)) db.close() except Exception as e: logger.error('Execution failed with error: {}'.format(e)) raise","def also_add(name, also): db = db_connect() cursor = db.cursor() try: cursor.execute(''' INSERT INTO isalso(name,also) VALUES(%(name)s,%(also)s) ''', ( name, also, )) db.commit() logger.debug('added to isalso name {} with value {}'.format( name, also)) db.close() except Exception as e: logger.error('Execution failed with error: {}'.format(e)) raise","{'deleted': [{'line_no': 6, 'char_start': 109, 'char_end': 169, 'line': "" INSERT INTO isalso(name,also) VALUES('{}','{}')\n""}, {'line_no': 7, 'char_start': 169, 'char_end': 205, 'line': "" '''.format(name, also))\n""}], 'added': [{'line_no': 6, 'char_start': 109, 'char_end': 177, 'line': ' INSERT INTO isalso(name,also) VALUES(%(name)s,%(also)s)\n'}, {'line_no': 7, 'char_start': 177, 'char_end': 196, 'line': "" ''', (\n""}, {'line_no': 8, 'char_start': 196, 'char_end': 214, 'line': ' name,\n'}, {'line_no': 9, 'char_start': 214, 'char_end': 232, 'line': ' also,\n'}, {'line_no': 10, 'char_start': 232, 'char_end': 243, 'line': ' ))\n'}]}","{'deleted': [{'char_start': 158, 'char_end': 162, 'chars': ""'{}'""}, {'char_start': 163, 'char_end': 167, 'chars': ""'{}'""}, {'char_start': 184, 'char_end': 191, 'chars': '.format'}], 'added': [{'char_start': 158, 'char_end': 166, 'chars': '%(name)s'}, {'char_start': 167, 'char_end': 175, 'chars': '%(also)s'}, {'char_start': 192, 'char_end': 194, 'chars': ', '}, {'char_start': 195, 'char_end': 208, 'chars': '\n '}, {'char_start': 213, 'char_end': 225, 'chars': '\n '}, {'char_start': 230, 'char_end': 240, 'chars': ',\n '}]}",github.com/tylarb/KarmaBoi-PCF/commit/c1d00a27d7f6b7eb6f15a3dacd4269654a32c10a,KarmaBoi/dbopts.py,cwe-089,98 cwe-079,edit_workflow,"@check_document_access_permission() def edit_workflow(request): workflow_id = request.GET.get('workflow') if workflow_id: wid = {} if workflow_id.isdigit(): wid['id'] = workflow_id else: wid['uuid'] = workflow_id doc = Document2.objects.get(type='oozie-workflow2', **wid) workflow = Workflow(document=doc) else: doc = None workflow = Workflow() workflow.set_workspace(request.user) workflow.check_workspace(request.fs, request.user) workflow_data = workflow.get_data() api = get_oozie(request.user) credentials = Credentials() try: credentials.fetch(api) except Exception, e: LOG.error(smart_str(e)) return render('editor/workflow_editor.mako', request, { 'layout_json': json.dumps(workflow_data['layout']), 'workflow_json': json.dumps(workflow_data['workflow']), 'credentials_json': json.dumps(credentials.credentials.keys()), 'workflow_properties_json': json.dumps(WORKFLOW_NODE_PROPERTIES), 'doc1_id': doc.doc.get().id if doc else -1, 'subworkflows_json': json.dumps(_get_workflows(request.user)), 'can_edit_json': json.dumps(doc is None or doc.doc.get().is_editable(request.user)) })","@check_document_access_permission() def edit_workflow(request): workflow_id = request.GET.get('workflow') if workflow_id: wid = {} if workflow_id.isdigit(): wid['id'] = workflow_id else: wid['uuid'] = workflow_id doc = Document2.objects.get(type='oozie-workflow2', **wid) workflow = Workflow(document=doc) else: doc = None workflow = Workflow() workflow.set_workspace(request.user) workflow.check_workspace(request.fs, request.user) workflow_data = workflow.get_data() api = get_oozie(request.user) credentials = Credentials() try: credentials.fetch(api) except Exception, e: LOG.error(smart_str(e)) return render('editor/workflow_editor.mako', request, { 'layout_json': json.dumps(workflow_data['layout'], cls=JSONEncoderForHTML), 'workflow_json': json.dumps(workflow_data['workflow'], cls=JSONEncoderForHTML), 'credentials_json': json.dumps(credentials.credentials.keys(), cls=JSONEncoderForHTML), 'workflow_properties_json': json.dumps(WORKFLOW_NODE_PROPERTIES, cls=JSONEncoderForHTML), 'doc1_id': doc.doc.get().id if doc else -1, 'subworkflows_json': json.dumps(_get_workflows(request.user), cls=JSONEncoderForHTML), 'can_edit_json': json.dumps(doc is None or doc.doc.get().is_editable(request.user)) })","{'deleted': [{'line_no': 30, 'char_start': 743, 'char_end': 801, 'line': "" 'layout_json': json.dumps(workflow_data['layout']),\n""}, {'line_no': 31, 'char_start': 801, 'char_end': 863, 'line': "" 'workflow_json': json.dumps(workflow_data['workflow']),\n""}, {'line_no': 32, 'char_start': 863, 'char_end': 933, 'line': "" 'credentials_json': json.dumps(credentials.credentials.keys()),\n""}, {'line_no': 33, 'char_start': 933, 'char_end': 1005, 'line': "" 'workflow_properties_json': json.dumps(WORKFLOW_NODE_PROPERTIES),\n""}, {'line_no': 35, 'char_start': 1055, 'char_end': 1124, 'line': "" 'subworkflows_json': json.dumps(_get_workflows(request.user)),\n""}], 'added': [{'line_no': 30, 'char_start': 743, 'char_end': 825, 'line': "" 'layout_json': json.dumps(workflow_data['layout'], cls=JSONEncoderForHTML),\n""}, {'line_no': 31, 'char_start': 825, 'char_end': 911, 'line': "" 'workflow_json': json.dumps(workflow_data['workflow'], cls=JSONEncoderForHTML),\n""}, {'line_no': 32, 'char_start': 911, 'char_end': 1005, 'line': "" 'credentials_json': json.dumps(credentials.credentials.keys(), cls=JSONEncoderForHTML),\n""}, {'line_no': 33, 'char_start': 1005, 'char_end': 1101, 'line': "" 'workflow_properties_json': json.dumps(WORKFLOW_NODE_PROPERTIES, cls=JSONEncoderForHTML),\n""}, {'line_no': 35, 'char_start': 1151, 'char_end': 1244, 'line': "" 'subworkflows_json': json.dumps(_get_workflows(request.user), cls=JSONEncoderForHTML),\n""}]}","{'deleted': [], 'added': [{'char_start': 798, 'char_end': 822, 'chars': ', cls=JSONEncoderForHTML'}, {'char_start': 884, 'char_end': 908, 'chars': ', cls=JSONEncoderForHTML'}, {'char_start': 978, 'char_end': 1002, 'chars': ', cls=JSONEncoderForHTML'}, {'char_start': 1074, 'char_end': 1098, 'chars': ', cls=JSONEncoderForHTML'}, {'char_start': 1217, 'char_end': 1241, 'chars': ', cls=JSONEncoderForHTML'}]}",github.com/gethue/hue/commit/6641c62beaa1468082e47d82da5ed758d11c7735,apps/oozie/src/oozie/views/editor2.py,cwe-079,284 cwe-190,Perl_re_op_compile,"REGEXP * Perl_re_op_compile(pTHX_ SV ** const patternp, int pat_count, OP *expr, const regexp_engine* eng, REGEXP *old_re, bool *is_bare_re, const U32 orig_rx_flags, const U32 pm_flags) { dVAR; REGEXP *Rx; /* Capital 'R' means points to a REGEXP */ STRLEN plen; char *exp; regnode *scan; I32 flags; SSize_t minlen = 0; U32 rx_flags; SV *pat; SV** new_patternp = patternp; /* these are all flags - maybe they should be turned * into a single int with different bit masks */ I32 sawlookahead = 0; I32 sawplus = 0; I32 sawopen = 0; I32 sawminmod = 0; regex_charset initial_charset = get_regex_charset(orig_rx_flags); bool recompile = 0; bool runtime_code = 0; scan_data_t data; RExC_state_t RExC_state; RExC_state_t * const pRExC_state = &RExC_state; #ifdef TRIE_STUDY_OPT int restudied = 0; RExC_state_t copyRExC_state; #endif GET_RE_DEBUG_FLAGS_DECL; PERL_ARGS_ASSERT_RE_OP_COMPILE; DEBUG_r(if (!PL_colorset) reginitcolors()); /* Initialize these here instead of as-needed, as is quick and avoids * having to test them each time otherwise */ if (! PL_InBitmap) { #ifdef DEBUGGING char * dump_len_string; #endif /* This is calculated here, because the Perl program that generates the * static global ones doesn't currently have access to * NUM_ANYOF_CODE_POINTS */ PL_InBitmap = _new_invlist(2); PL_InBitmap = _add_range_to_invlist(PL_InBitmap, 0, NUM_ANYOF_CODE_POINTS - 1); #ifdef DEBUGGING dump_len_string = PerlEnv_getenv(""PERL_DUMP_RE_MAX_LEN""); if ( ! dump_len_string || ! grok_atoUV(dump_len_string, (UV *)&PL_dump_re_max_len, NULL)) { PL_dump_re_max_len = 60; /* A reasonable default */ } #endif } pRExC_state->warn_text = NULL; pRExC_state->unlexed_names = NULL; pRExC_state->code_blocks = NULL; if (is_bare_re) *is_bare_re = FALSE; if (expr && (expr->op_type == OP_LIST || (expr->op_type == OP_NULL && expr->op_targ == OP_LIST))) { /* allocate code_blocks if needed */ OP *o; int ncode = 0; for (o = cLISTOPx(expr)->op_first; o; o = OpSIBLING(o)) if (o->op_type == OP_NULL && (o->op_flags & OPf_SPECIAL)) ncode++; /* count of DO blocks */ if (ncode) pRExC_state->code_blocks = S_alloc_code_blocks(aTHX_ ncode); } if (!pat_count) { /* compile-time pattern with just OP_CONSTs and DO blocks */ int n; OP *o; /* find how many CONSTs there are */ assert(expr); n = 0; if (expr->op_type == OP_CONST) n = 1; else for (o = cLISTOPx(expr)->op_first; o; o = OpSIBLING(o)) { if (o->op_type == OP_CONST) n++; } /* fake up an SV array */ assert(!new_patternp); Newx(new_patternp, n, SV*); SAVEFREEPV(new_patternp); pat_count = n; n = 0; if (expr->op_type == OP_CONST) new_patternp[n] = cSVOPx_sv(expr); else for (o = cLISTOPx(expr)->op_first; o; o = OpSIBLING(o)) { if (o->op_type == OP_CONST) new_patternp[n++] = cSVOPo_sv; } } DEBUG_PARSE_r(Perl_re_printf( aTHX_ ""Assembling pattern from %d elements%s\n"", pat_count, orig_rx_flags & RXf_SPLIT ? "" for split"" : """")); /* set expr to the first arg op */ if (pRExC_state->code_blocks && pRExC_state->code_blocks->count && expr->op_type != OP_CONST) { expr = cLISTOPx(expr)->op_first; assert( expr->op_type == OP_PUSHMARK || (expr->op_type == OP_NULL && expr->op_targ == OP_PUSHMARK) || expr->op_type == OP_PADRANGE); expr = OpSIBLING(expr); } pat = S_concat_pat(aTHX_ pRExC_state, NULL, new_patternp, pat_count, expr, &recompile, NULL); /* handle bare (possibly after overloading) regex: foo =~ $re */ { SV *re = pat; if (SvROK(re)) re = SvRV(re); if (SvTYPE(re) == SVt_REGEXP) { if (is_bare_re) *is_bare_re = TRUE; SvREFCNT_inc(re); DEBUG_PARSE_r(Perl_re_printf( aTHX_ ""Precompiled pattern%s\n"", orig_rx_flags & RXf_SPLIT ? "" for split"" : """")); return (REGEXP*)re; } } exp = SvPV_nomg(pat, plen); if (!eng->op_comp) { if ((SvUTF8(pat) && IN_BYTES) || SvGMAGICAL(pat) || SvAMAGIC(pat)) { /* make a temporary copy; either to convert to bytes, * or to avoid repeating get-magic / overloaded stringify */ pat = newSVpvn_flags(exp, plen, SVs_TEMP | (IN_BYTES ? 0 : SvUTF8(pat))); } return CALLREGCOMP_ENG(eng, pat, orig_rx_flags); } /* ignore the utf8ness if the pattern is 0 length */ RExC_utf8 = RExC_orig_utf8 = (plen == 0 || IN_BYTES) ? 0 : SvUTF8(pat); RExC_uni_semantics = 0; RExC_contains_locale = 0; RExC_strict = cBOOL(pm_flags & RXf_PMf_STRICT); RExC_in_script_run = 0; RExC_study_started = 0; pRExC_state->runtime_code_qr = NULL; RExC_frame_head= NULL; RExC_frame_last= NULL; RExC_frame_count= 0; RExC_latest_warn_offset = 0; RExC_use_BRANCHJ = 0; RExC_total_parens = 0; RExC_open_parens = NULL; RExC_close_parens = NULL; RExC_paren_names = NULL; RExC_size = 0; RExC_seen_d_op = FALSE; #ifdef DEBUGGING RExC_paren_name_list = NULL; #endif DEBUG_r({ RExC_mysv1= sv_newmortal(); RExC_mysv2= sv_newmortal(); }); DEBUG_COMPILE_r({ SV *dsv= sv_newmortal(); RE_PV_QUOTED_DECL(s, RExC_utf8, dsv, exp, plen, PL_dump_re_max_len); Perl_re_printf( aTHX_ ""%sCompiling REx%s %s\n"", PL_colors[4], PL_colors[5], s); }); /* we jump here if we have to recompile, e.g., from upgrading the pattern * to utf8 */ if ((pm_flags & PMf_USE_RE_EVAL) /* this second condition covers the non-regex literal case, * i.e. $foo =~ '(?{})'. */ || (IN_PERL_COMPILETIME && (PL_hints & HINT_RE_EVAL)) ) runtime_code = S_has_runtime_code(aTHX_ pRExC_state, exp, plen); redo_parse: /* return old regex if pattern hasn't changed */ /* XXX: note in the below we have to check the flags as well as the * pattern. * * Things get a touch tricky as we have to compare the utf8 flag * independently from the compile flags. */ if ( old_re && !recompile && !!RX_UTF8(old_re) == !!RExC_utf8 && ( RX_COMPFLAGS(old_re) == ( orig_rx_flags & RXf_PMf_FLAGCOPYMASK ) ) && RX_PRECOMP(old_re) && RX_PRELEN(old_re) == plen && memEQ(RX_PRECOMP(old_re), exp, plen) && !runtime_code /* with runtime code, always recompile */ ) { return old_re; } /* Allocate the pattern's SV */ RExC_rx_sv = Rx = (REGEXP*) newSV_type(SVt_REGEXP); RExC_rx = ReANY(Rx); if ( RExC_rx == NULL ) FAIL(""Regexp out of space""); rx_flags = orig_rx_flags; if ( (UTF || RExC_uni_semantics) && initial_charset == REGEX_DEPENDS_CHARSET) { /* Set to use unicode semantics if the pattern is in utf8 and has the * 'depends' charset specified, as it means unicode when utf8 */ set_regex_charset(&rx_flags, REGEX_UNICODE_CHARSET); RExC_uni_semantics = 1; } RExC_pm_flags = pm_flags; if (runtime_code) { assert(TAINTING_get || !TAINT_get); if (TAINT_get) Perl_croak(aTHX_ ""Eval-group in insecure regular expression""); if (!S_compile_runtime_code(aTHX_ pRExC_state, exp, plen)) { /* whoops, we have a non-utf8 pattern, whilst run-time code * got compiled as utf8. Try again with a utf8 pattern */ S_pat_upgrade_to_utf8(aTHX_ pRExC_state, &exp, &plen, pRExC_state->code_blocks ? pRExC_state->code_blocks->count : 0); goto redo_parse; } } assert(!pRExC_state->runtime_code_qr); RExC_sawback = 0; RExC_seen = 0; RExC_maxlen = 0; RExC_in_lookbehind = 0; RExC_seen_zerolen = *exp == '^' ? -1 : 0; #ifdef EBCDIC RExC_recode_x_to_native = 0; #endif RExC_in_multi_char_class = 0; RExC_start = RExC_copy_start_in_constructed = RExC_copy_start_in_input = RExC_precomp = exp; RExC_precomp_end = RExC_end = exp + plen; RExC_nestroot = 0; RExC_whilem_seen = 0; RExC_end_op = NULL; RExC_recurse = NULL; RExC_study_chunk_recursed = NULL; RExC_study_chunk_recursed_bytes= 0; RExC_recurse_count = 0; pRExC_state->code_index = 0; /* Initialize the string in the compiled pattern. This is so that there is * something to output if necessary */ set_regex_pv(pRExC_state, Rx); DEBUG_PARSE_r({ Perl_re_printf( aTHX_ ""Starting parse and generation\n""); RExC_lastnum=0; RExC_lastparse=NULL; }); /* Allocate space and zero-initialize. Note, the two step process of zeroing when in debug mode, thus anything assigned has to happen after that */ if (! RExC_size) { /* On the first pass of the parse, we guess how big this will be. Then * we grow in one operation to that amount and then give it back. As * we go along, we re-allocate what we need. * * XXX Currently the guess is essentially that the pattern will be an * EXACT node with one byte input, one byte output. This is crude, and * better heuristics are welcome. * * On any subsequent passes, we guess what we actually computed in the * latest earlier pass. Such a pass probably didn't complete so is * missing stuff. We could improve those guesses by knowing where the * parse stopped, and use the length so far plus apply the above * assumption to what's left. */ RExC_size = STR_SZ(RExC_end - RExC_start); } Newxc(RExC_rxi, sizeof(regexp_internal) + RExC_size, char, regexp_internal); if ( RExC_rxi == NULL ) FAIL(""Regexp out of space""); Zero(RExC_rxi, sizeof(regexp_internal) + RExC_size, char); RXi_SET( RExC_rx, RExC_rxi ); /* We start from 0 (over from 0 in the case this is a reparse. The first * node parsed will give back any excess memory we have allocated so far). * */ RExC_size = 0; /* non-zero initialization begins here */ RExC_rx->engine= eng; RExC_rx->extflags = rx_flags; RXp_COMPFLAGS(RExC_rx) = orig_rx_flags & RXf_PMf_FLAGCOPYMASK; if (pm_flags & PMf_IS_QR) { RExC_rxi->code_blocks = pRExC_state->code_blocks; if (RExC_rxi->code_blocks) { RExC_rxi->code_blocks->refcnt++; } } RExC_rx->intflags = 0; RExC_flags = rx_flags; /* don't let top level (?i) bleed */ RExC_parse = exp; /* This NUL is guaranteed because the pattern comes from an SV*, and the sv * code makes sure the final byte is an uncounted NUL. But should this * ever not be the case, lots of things could read beyond the end of the * buffer: loops like * while(isFOO(*RExC_parse)) RExC_parse++; * strchr(RExC_parse, ""foo""); * etc. So it is worth noting. */ assert(*RExC_end == '\0'); RExC_naughty = 0; RExC_npar = 1; RExC_parens_buf_size = 0; RExC_emit_start = RExC_rxi->program; pRExC_state->code_index = 0; *((char*) RExC_emit_start) = (char) REG_MAGIC; RExC_emit = 1; /* Do the parse */ if (reg(pRExC_state, 0, &flags, 1)) { /* Success!, But we may need to redo the parse knowing how many parens * there actually are */ if (IN_PARENS_PASS) { flags |= RESTART_PARSE; } /* We have that number in RExC_npar */ RExC_total_parens = RExC_npar; } else if (! MUST_RESTART(flags)) { ReREFCNT_dec(Rx); Perl_croak(aTHX_ ""panic: reg returned failure to re_op_compile, flags=%#"" UVxf, (UV) flags); } /* Here, we either have success, or we have to redo the parse for some reason */ if (MUST_RESTART(flags)) { /* It's possible to write a regexp in ascii that represents Unicode codepoints outside of the byte range, such as via \x{100}. If we detect such a sequence we have to convert the entire pattern to utf8 and then recompile, as our sizing calculation will have been based on 1 byte == 1 character, but we will need to use utf8 to encode at least some part of the pattern, and therefore must convert the whole thing. -- dmq */ if (flags & NEED_UTF8) { /* We have stored the offset of the final warning output so far. * That must be adjusted. Any variant characters between the start * of the pattern and this warning count for 2 bytes in the final, * so just add them again */ if (UNLIKELY(RExC_latest_warn_offset > 0)) { RExC_latest_warn_offset += variant_under_utf8_count((U8 *) exp, (U8 *) exp + RExC_latest_warn_offset); } S_pat_upgrade_to_utf8(aTHX_ pRExC_state, &exp, &plen, pRExC_state->code_blocks ? pRExC_state->code_blocks->count : 0); DEBUG_PARSE_r(Perl_re_printf( aTHX_ ""Need to redo parse after upgrade\n"")); } else { DEBUG_PARSE_r(Perl_re_printf( aTHX_ ""Need to redo parse\n"")); } if (ALL_PARENS_COUNTED) { /* Make enough room for all the known parens, and zero it */ Renew(RExC_open_parens, RExC_total_parens, regnode_offset); Zero(RExC_open_parens, RExC_total_parens, regnode_offset); RExC_open_parens[0] = 1; /* +1 for REG_MAGIC */ Renew(RExC_close_parens, RExC_total_parens, regnode_offset); Zero(RExC_close_parens, RExC_total_parens, regnode_offset); } else { /* Parse did not complete. Reinitialize the parentheses structures */ RExC_total_parens = 0; if (RExC_open_parens) { Safefree(RExC_open_parens); RExC_open_parens = NULL; } if (RExC_close_parens) { Safefree(RExC_close_parens); RExC_close_parens = NULL; } } /* Clean up what we did in this parse */ SvREFCNT_dec_NN(RExC_rx_sv); goto redo_parse; } /* Here, we have successfully parsed and generated the pattern's program * for the regex engine. We are ready to finish things up and look for * optimizations. */ /* Update the string to compile, with correct modifiers, etc */ set_regex_pv(pRExC_state, Rx); RExC_rx->nparens = RExC_total_parens - 1; /* Uses the upper 4 bits of the FLAGS field, so keep within that size */ if (RExC_whilem_seen > 15) RExC_whilem_seen = 15; DEBUG_PARSE_r({ Perl_re_printf( aTHX_ ""Required size %"" IVdf "" nodes\n"", (IV)RExC_size); RExC_lastnum=0; RExC_lastparse=NULL; }); #ifdef RE_TRACK_PATTERN_OFFSETS DEBUG_OFFSETS_r(Perl_re_printf( aTHX_ ""%s %"" UVuf "" bytes for offset annotations.\n"", RExC_offsets ? ""Got"" : ""Couldn't get"", (UV)((RExC_offsets[0] * 2 + 1)))); DEBUG_OFFSETS_r(if (RExC_offsets) { const STRLEN len = RExC_offsets[0]; STRLEN i; GET_RE_DEBUG_FLAGS_DECL; Perl_re_printf( aTHX_ ""Offsets: [%"" UVuf ""]\n\t"", (UV)RExC_offsets[0]); for (i = 1; i <= len; i++) { if (RExC_offsets[i*2-1] || RExC_offsets[i*2]) Perl_re_printf( aTHX_ ""%"" UVuf "":%"" UVuf ""[%"" UVuf ""] "", (UV)i, (UV)RExC_offsets[i*2-1], (UV)RExC_offsets[i*2]); } Perl_re_printf( aTHX_ ""\n""); }); #else SetProgLen(RExC_rxi,RExC_size); #endif DEBUG_OPTIMISE_r( Perl_re_printf( aTHX_ ""Starting post parse optimization\n""); ); /* XXXX To minimize changes to RE engine we always allocate 3-units-long substrs field. */ Newx(RExC_rx->substrs, 1, struct reg_substr_data); if (RExC_recurse_count) { Newx(RExC_recurse, RExC_recurse_count, regnode *); SAVEFREEPV(RExC_recurse); } if (RExC_seen & REG_RECURSE_SEEN) { /* Note, RExC_total_parens is 1 + the number of parens in a pattern. * So its 1 if there are no parens. */ RExC_study_chunk_recursed_bytes= (RExC_total_parens >> 3) + ((RExC_total_parens & 0x07) != 0); Newx(RExC_study_chunk_recursed, RExC_study_chunk_recursed_bytes * RExC_total_parens, U8); SAVEFREEPV(RExC_study_chunk_recursed); } reStudy: RExC_rx->minlen = minlen = sawlookahead = sawplus = sawopen = sawminmod = 0; DEBUG_r( RExC_study_chunk_recursed_count= 0; ); Zero(RExC_rx->substrs, 1, struct reg_substr_data); if (RExC_study_chunk_recursed) { Zero(RExC_study_chunk_recursed, RExC_study_chunk_recursed_bytes * RExC_total_parens, U8); } #ifdef TRIE_STUDY_OPT if (!restudied) { StructCopy(&zero_scan_data, &data, scan_data_t); copyRExC_state = RExC_state; } else { U32 seen=RExC_seen; DEBUG_OPTIMISE_r(Perl_re_printf( aTHX_ ""Restudying\n"")); RExC_state = copyRExC_state; if (seen & REG_TOP_LEVEL_BRANCHES_SEEN) RExC_seen |= REG_TOP_LEVEL_BRANCHES_SEEN; else RExC_seen &= ~REG_TOP_LEVEL_BRANCHES_SEEN; StructCopy(&zero_scan_data, &data, scan_data_t); } #else StructCopy(&zero_scan_data, &data, scan_data_t); #endif /* Dig out information for optimizations. */ RExC_rx->extflags = RExC_flags; /* was pm_op */ /*dmq: removed as part of de-PMOP: pm->op_pmflags = RExC_flags; */ if (UTF) SvUTF8_on(Rx); /* Unicode in it? */ RExC_rxi->regstclass = NULL; if (RExC_naughty >= TOO_NAUGHTY) /* Probably an expensive pattern. */ RExC_rx->intflags |= PREGf_NAUGHTY; scan = RExC_rxi->program + 1; /* First BRANCH. */ /* testing for BRANCH here tells us whether there is ""must appear"" data in the pattern. If there is then we can use it for optimisations */ if (!(RExC_seen & REG_TOP_LEVEL_BRANCHES_SEEN)) { /* Only one top-level choice. */ SSize_t fake; STRLEN longest_length[2]; regnode_ssc ch_class; /* pointed to by data */ int stclass_flag; SSize_t last_close = 0; /* pointed to by data */ regnode *first= scan; regnode *first_next= regnext(first); int i; /* * Skip introductions and multiplicators >= 1 * so that we can extract the 'meat' of the pattern that must * match in the large if() sequence following. * NOTE that EXACT is NOT covered here, as it is normally * picked up by the optimiser separately. * * This is unfortunate as the optimiser isnt handling lookahead * properly currently. * */ while ((OP(first) == OPEN && (sawopen = 1)) || /* An OR of *one* alternative - should not happen now. */ (OP(first) == BRANCH && OP(first_next) != BRANCH) || /* for now we can't handle lookbehind IFMATCH*/ (OP(first) == IFMATCH && !first->flags && (sawlookahead = 1)) || (OP(first) == PLUS) || (OP(first) == MINMOD) || /* An {n,m} with n>0 */ (PL_regkind[OP(first)] == CURLY && ARG1(first) > 0) || (OP(first) == NOTHING && PL_regkind[OP(first_next)] != END )) { /* * the only op that could be a regnode is PLUS, all the rest * will be regnode_1 or regnode_2. * * (yves doesn't think this is true) */ if (OP(first) == PLUS) sawplus = 1; else { if (OP(first) == MINMOD) sawminmod = 1; first += regarglen[OP(first)]; } first = NEXTOPER(first); first_next= regnext(first); } /* Starting-point info. */ again: DEBUG_PEEP(""first:"", first, 0, 0); /* Ignore EXACT as we deal with it later. */ if (PL_regkind[OP(first)] == EXACT) { if ( OP(first) == EXACT || OP(first) == EXACT_ONLY8 || OP(first) == EXACTL) { NOOP; /* Empty, get anchored substr later. */ } else RExC_rxi->regstclass = first; } #ifdef TRIE_STCLASS else if (PL_regkind[OP(first)] == TRIE && ((reg_trie_data *)RExC_rxi->data->data[ ARG(first) ])->minlen>0) { /* this can happen only on restudy */ RExC_rxi->regstclass = construct_ahocorasick_from_trie(pRExC_state, (regnode *)first, 0); } #endif else if (REGNODE_SIMPLE(OP(first))) RExC_rxi->regstclass = first; else if (PL_regkind[OP(first)] == BOUND || PL_regkind[OP(first)] == NBOUND) RExC_rxi->regstclass = first; else if (PL_regkind[OP(first)] == BOL) { RExC_rx->intflags |= (OP(first) == MBOL ? PREGf_ANCH_MBOL : PREGf_ANCH_SBOL); first = NEXTOPER(first); goto again; } else if (OP(first) == GPOS) { RExC_rx->intflags |= PREGf_ANCH_GPOS; first = NEXTOPER(first); goto again; } else if ((!sawopen || !RExC_sawback) && !sawlookahead && (OP(first) == STAR && PL_regkind[OP(NEXTOPER(first))] == REG_ANY) && !(RExC_rx->intflags & PREGf_ANCH) && !pRExC_state->code_blocks) { /* turn .* into ^.* with an implied $*=1 */ const int type = (OP(NEXTOPER(first)) == REG_ANY) ? PREGf_ANCH_MBOL : PREGf_ANCH_SBOL; RExC_rx->intflags |= (type | PREGf_IMPLICIT); first = NEXTOPER(first); goto again; } if (sawplus && !sawminmod && !sawlookahead && (!sawopen || !RExC_sawback) && !pRExC_state->code_blocks) /* May examine pos and $& */ /* x+ must match at the 1st pos of run of x's */ RExC_rx->intflags |= PREGf_SKIP; /* Scan is after the zeroth branch, first is atomic matcher. */ #ifdef TRIE_STUDY_OPT DEBUG_PARSE_r( if (!restudied) Perl_re_printf( aTHX_ ""first at %"" IVdf ""\n"", (IV)(first - scan + 1)) ); #else DEBUG_PARSE_r( Perl_re_printf( aTHX_ ""first at %"" IVdf ""\n"", (IV)(first - scan + 1)) ); #endif /* * If there's something expensive in the r.e., find the * longest literal string that must appear and make it the * regmust. Resolve ties in favor of later strings, since * the regstart check works with the beginning of the r.e. * and avoiding duplication strengthens checking. Not a * strong reason, but sufficient in the absence of others. * [Now we resolve ties in favor of the earlier string if * it happens that c_offset_min has been invalidated, since the * earlier string may buy us something the later one won't.] */ data.substrs[0].str = newSVpvs(""""); data.substrs[1].str = newSVpvs(""""); data.last_found = newSVpvs(""""); data.cur_is_floating = 0; /* initially any found substring is fixed */ ENTER_with_name(""study_chunk""); SAVEFREESV(data.substrs[0].str); SAVEFREESV(data.substrs[1].str); SAVEFREESV(data.last_found); first = scan; if (!RExC_rxi->regstclass) { ssc_init(pRExC_state, &ch_class); data.start_class = &ch_class; stclass_flag = SCF_DO_STCLASS_AND; } else /* XXXX Check for BOUND? */ stclass_flag = 0; data.last_closep = &last_close; DEBUG_RExC_seen(); /* * MAIN ENTRY FOR study_chunk() FOR m/PATTERN/ * (NO top level branches) */ minlen = study_chunk(pRExC_state, &first, &minlen, &fake, scan + RExC_size, /* Up to end */ &data, -1, 0, NULL, SCF_DO_SUBSTR | SCF_WHILEM_VISITED_POS | stclass_flag | (restudied ? SCF_TRIE_DOING_RESTUDY : 0), 0); CHECK_RESTUDY_GOTO_butfirst(LEAVE_with_name(""study_chunk"")); if ( RExC_total_parens == 1 && !data.cur_is_floating && data.last_start_min == 0 && data.last_end > 0 && !RExC_seen_zerolen && !(RExC_seen & REG_VERBARG_SEEN) && !(RExC_seen & REG_GPOS_SEEN) ){ RExC_rx->extflags |= RXf_CHECK_ALL; } scan_commit(pRExC_state, &data,&minlen, 0); /* XXX this is done in reverse order because that's the way the * code was before it was parameterised. Don't know whether it * actually needs doing in reverse order. DAPM */ for (i = 1; i >= 0; i--) { longest_length[i] = CHR_SVLEN(data.substrs[i].str); if ( !( i && SvCUR(data.substrs[0].str) /* ok to leave SvCUR */ && data.substrs[0].min_offset == data.substrs[1].min_offset && SvCUR(data.substrs[0].str) == SvCUR(data.substrs[1].str) ) && S_setup_longest (aTHX_ pRExC_state, &(RExC_rx->substrs->data[i]), &(data.substrs[i]), longest_length[i])) { RExC_rx->substrs->data[i].min_offset = data.substrs[i].min_offset - data.substrs[i].lookbehind; RExC_rx->substrs->data[i].max_offset = data.substrs[i].max_offset; /* Don't offset infinity */ if (data.substrs[i].max_offset < SSize_t_MAX) RExC_rx->substrs->data[i].max_offset -= data.substrs[i].lookbehind; SvREFCNT_inc_simple_void_NN(data.substrs[i].str); } else { RExC_rx->substrs->data[i].substr = NULL; RExC_rx->substrs->data[i].utf8_substr = NULL; longest_length[i] = 0; } } LEAVE_with_name(""study_chunk""); if (RExC_rxi->regstclass && (OP(RExC_rxi->regstclass) == REG_ANY || OP(RExC_rxi->regstclass) == SANY)) RExC_rxi->regstclass = NULL; if ((!(RExC_rx->substrs->data[0].substr || RExC_rx->substrs->data[0].utf8_substr) || RExC_rx->substrs->data[0].min_offset) && stclass_flag && ! (ANYOF_FLAGS(data.start_class) & SSC_MATCHES_EMPTY_STRING) && is_ssc_worth_it(pRExC_state, data.start_class)) { const U32 n = add_data(pRExC_state, STR_WITH_LEN(""f"")); ssc_finalize(pRExC_state, data.start_class); Newx(RExC_rxi->data->data[n], 1, regnode_ssc); StructCopy(data.start_class, (regnode_ssc*)RExC_rxi->data->data[n], regnode_ssc); RExC_rxi->regstclass = (regnode*)RExC_rxi->data->data[n]; RExC_rx->intflags &= ~PREGf_SKIP; /* Used in find_byclass(). */ DEBUG_COMPILE_r({ SV *sv = sv_newmortal(); regprop(RExC_rx, sv, (regnode*)data.start_class, NULL, pRExC_state); Perl_re_printf( aTHX_ ""synthetic stclass \""%s\"".\n"", SvPVX_const(sv));}); data.start_class = NULL; } /* A temporary algorithm prefers floated substr to fixed one of * same length to dig more info. */ i = (longest_length[0] <= longest_length[1]); RExC_rx->substrs->check_ix = i; RExC_rx->check_end_shift = RExC_rx->substrs->data[i].end_shift; RExC_rx->check_substr = RExC_rx->substrs->data[i].substr; RExC_rx->check_utf8 = RExC_rx->substrs->data[i].utf8_substr; RExC_rx->check_offset_min = RExC_rx->substrs->data[i].min_offset; RExC_rx->check_offset_max = RExC_rx->substrs->data[i].max_offset; if (!i && (RExC_rx->intflags & (PREGf_ANCH_SBOL|PREGf_ANCH_GPOS))) RExC_rx->intflags |= PREGf_NOSCAN; if ((RExC_rx->check_substr || RExC_rx->check_utf8) ) { RExC_rx->extflags |= RXf_USE_INTUIT; if (SvTAIL(RExC_rx->check_substr ? RExC_rx->check_substr : RExC_rx->check_utf8)) RExC_rx->extflags |= RXf_INTUIT_TAIL; } /* XXX Unneeded? dmq (shouldn't as this is handled elsewhere) if ( (STRLEN)minlen < longest_length[1] ) minlen= longest_length[1]; if ( (STRLEN)minlen < longest_length[0] ) minlen= longest_length[0]; */ } else { /* Several toplevels. Best we can is to set minlen. */ SSize_t fake; regnode_ssc ch_class; SSize_t last_close = 0; DEBUG_PARSE_r(Perl_re_printf( aTHX_ ""\nMulti Top Level\n"")); scan = RExC_rxi->program + 1; ssc_init(pRExC_state, &ch_class); data.start_class = &ch_class; data.last_closep = &last_close; DEBUG_RExC_seen(); /* * MAIN ENTRY FOR study_chunk() FOR m/P1|P2|.../ * (patterns WITH top level branches) */ minlen = study_chunk(pRExC_state, &scan, &minlen, &fake, scan + RExC_size, &data, -1, 0, NULL, SCF_DO_STCLASS_AND|SCF_WHILEM_VISITED_POS|(restudied ? SCF_TRIE_DOING_RESTUDY : 0), 0); CHECK_RESTUDY_GOTO_butfirst(NOOP); RExC_rx->check_substr = NULL; RExC_rx->check_utf8 = NULL; RExC_rx->substrs->data[0].substr = NULL; RExC_rx->substrs->data[0].utf8_substr = NULL; RExC_rx->substrs->data[1].substr = NULL; RExC_rx->substrs->data[1].utf8_substr = NULL; if (! (ANYOF_FLAGS(data.start_class) & SSC_MATCHES_EMPTY_STRING) && is_ssc_worth_it(pRExC_state, data.start_class)) { const U32 n = add_data(pRExC_state, STR_WITH_LEN(""f"")); ssc_finalize(pRExC_state, data.start_class); Newx(RExC_rxi->data->data[n], 1, regnode_ssc); StructCopy(data.start_class, (regnode_ssc*)RExC_rxi->data->data[n], regnode_ssc); RExC_rxi->regstclass = (regnode*)RExC_rxi->data->data[n]; RExC_rx->intflags &= ~PREGf_SKIP; /* Used in find_byclass(). */ DEBUG_COMPILE_r({ SV* sv = sv_newmortal(); regprop(RExC_rx, sv, (regnode*)data.start_class, NULL, pRExC_state); Perl_re_printf( aTHX_ ""synthetic stclass \""%s\"".\n"", SvPVX_const(sv));}); data.start_class = NULL; } } if (RExC_seen & REG_UNBOUNDED_QUANTIFIER_SEEN) { RExC_rx->extflags |= RXf_UNBOUNDED_QUANTIFIER_SEEN; RExC_rx->maxlen = REG_INFTY; } else { RExC_rx->maxlen = RExC_maxlen; } /* Guard against an embedded (?=) or (?<=) with a longer minlen than the ""real"" pattern. */ DEBUG_OPTIMISE_r({ Perl_re_printf( aTHX_ ""minlen: %"" IVdf "" RExC_rx->minlen:%"" IVdf "" maxlen:%"" IVdf ""\n"", (IV)minlen, (IV)RExC_rx->minlen, (IV)RExC_maxlen); }); RExC_rx->minlenret = minlen; if (RExC_rx->minlen < minlen) RExC_rx->minlen = minlen; if (RExC_seen & REG_RECURSE_SEEN ) { RExC_rx->intflags |= PREGf_RECURSE_SEEN; Newx(RExC_rx->recurse_locinput, RExC_rx->nparens + 1, char *); } if (RExC_seen & REG_GPOS_SEEN) RExC_rx->intflags |= PREGf_GPOS_SEEN; if (RExC_seen & REG_LOOKBEHIND_SEEN) RExC_rx->extflags |= RXf_NO_INPLACE_SUBST; /* inplace might break the lookbehind */ if (pRExC_state->code_blocks) RExC_rx->extflags |= RXf_EVAL_SEEN; if (RExC_seen & REG_VERBARG_SEEN) { RExC_rx->intflags |= PREGf_VERBARG_SEEN; RExC_rx->extflags |= RXf_NO_INPLACE_SUBST; /* don't understand this! Yves */ } if (RExC_seen & REG_CUTGROUP_SEEN) RExC_rx->intflags |= PREGf_CUTGROUP_SEEN; if (pm_flags & PMf_USE_RE_EVAL) RExC_rx->intflags |= PREGf_USE_RE_EVAL; if (RExC_paren_names) RXp_PAREN_NAMES(RExC_rx) = MUTABLE_HV(SvREFCNT_inc(RExC_paren_names)); else RXp_PAREN_NAMES(RExC_rx) = NULL; /* If we have seen an anchor in our pattern then we set the extflag RXf_IS_ANCHORED * so it can be used in pp.c */ if (RExC_rx->intflags & PREGf_ANCH) RExC_rx->extflags |= RXf_IS_ANCHORED; { /* this is used to identify ""special"" patterns that might result * in Perl NOT calling the regex engine and instead doing the match ""itself"", * particularly special cases in split//. By having the regex compiler * do this pattern matching at a regop level (instead of by inspecting the pattern) * we avoid weird issues with equivalent patterns resulting in different behavior, * AND we allow non Perl engines to get the same optimizations by the setting the * flags appropriately - Yves */ regnode *first = RExC_rxi->program + 1; U8 fop = OP(first); regnode *next = regnext(first); U8 nop = OP(next); if (PL_regkind[fop] == NOTHING && nop == END) RExC_rx->extflags |= RXf_NULL; else if ((fop == MBOL || (fop == SBOL && !first->flags)) && nop == END) /* when fop is SBOL first->flags will be true only when it was * produced by parsing /\A/, and not when parsing /^/. This is * very important for the split code as there we want to * treat /^/ as /^/m, but we do not want to treat /\A/ as /^/m. * See rt #122761 for more details. -- Yves */ RExC_rx->extflags |= RXf_START_ONLY; else if (fop == PLUS && PL_regkind[nop] == POSIXD && FLAGS(next) == _CC_SPACE && nop == END) RExC_rx->extflags |= RXf_WHITE; else if ( RExC_rx->extflags & RXf_SPLIT && (fop == EXACT || fop == EXACT_ONLY8 || fop == EXACTL) && STR_LEN(first) == 1 && *(STRING(first)) == ' ' && nop == END ) RExC_rx->extflags |= (RXf_SKIPWHITE|RXf_WHITE); } if (RExC_contains_locale) { RXp_EXTFLAGS(RExC_rx) |= RXf_TAINTED; } #ifdef DEBUGGING if (RExC_paren_names) { RExC_rxi->name_list_idx = add_data( pRExC_state, STR_WITH_LEN(""a"")); RExC_rxi->data->data[RExC_rxi->name_list_idx] = (void*)SvREFCNT_inc(RExC_paren_name_list); } else #endif RExC_rxi->name_list_idx = 0; while ( RExC_recurse_count > 0 ) { const regnode *scan = RExC_recurse[ --RExC_recurse_count ]; /* * This data structure is set up in study_chunk() and is used * to calculate the distance between a GOSUB regopcode and * the OPEN/CURLYM (CURLYM's are special and can act like OPEN's) * it refers to. * * If for some reason someone writes code that optimises * away a GOSUB opcode then the assert should be changed to * an if(scan) to guard the ARG2L_SET() - Yves * */ assert(scan && OP(scan) == GOSUB); ARG2L_SET( scan, RExC_open_parens[ARG(scan)] - REGNODE_OFFSET(scan)); } Newxz(RExC_rx->offs, RExC_total_parens, regexp_paren_pair); /* assume we don't need to swap parens around before we match */ DEBUG_TEST_r({ Perl_re_printf( aTHX_ ""study_chunk_recursed_count: %lu\n"", (unsigned long)RExC_study_chunk_recursed_count); }); DEBUG_DUMP_r({ DEBUG_RExC_seen(); Perl_re_printf( aTHX_ ""Final program:\n""); regdump(RExC_rx); }); if (RExC_open_parens) { Safefree(RExC_open_parens); RExC_open_parens = NULL; } if (RExC_close_parens) { Safefree(RExC_close_parens); RExC_close_parens = NULL; } #ifdef USE_ITHREADS /* under ithreads the ?pat? PMf_USED flag on the pmop is simulated * by setting the regexp SV to readonly-only instead. If the * pattern's been recompiled, the USEDness should remain. */ if (old_re && SvREADONLY(old_re)) SvREADONLY_on(Rx); #endif return Rx;","REGEXP * Perl_re_op_compile(pTHX_ SV ** const patternp, int pat_count, OP *expr, const regexp_engine* eng, REGEXP *old_re, bool *is_bare_re, const U32 orig_rx_flags, const U32 pm_flags) { dVAR; REGEXP *Rx; /* Capital 'R' means points to a REGEXP */ STRLEN plen; char *exp; regnode *scan; I32 flags; SSize_t minlen = 0; U32 rx_flags; SV *pat; SV** new_patternp = patternp; /* these are all flags - maybe they should be turned * into a single int with different bit masks */ I32 sawlookahead = 0; I32 sawplus = 0; I32 sawopen = 0; I32 sawminmod = 0; regex_charset initial_charset = get_regex_charset(orig_rx_flags); bool recompile = 0; bool runtime_code = 0; scan_data_t data; RExC_state_t RExC_state; RExC_state_t * const pRExC_state = &RExC_state; #ifdef TRIE_STUDY_OPT int restudied = 0; RExC_state_t copyRExC_state; #endif GET_RE_DEBUG_FLAGS_DECL; PERL_ARGS_ASSERT_RE_OP_COMPILE; DEBUG_r(if (!PL_colorset) reginitcolors()); /* Initialize these here instead of as-needed, as is quick and avoids * having to test them each time otherwise */ if (! PL_InBitmap) { #ifdef DEBUGGING char * dump_len_string; #endif /* This is calculated here, because the Perl program that generates the * static global ones doesn't currently have access to * NUM_ANYOF_CODE_POINTS */ PL_InBitmap = _new_invlist(2); PL_InBitmap = _add_range_to_invlist(PL_InBitmap, 0, NUM_ANYOF_CODE_POINTS - 1); #ifdef DEBUGGING dump_len_string = PerlEnv_getenv(""PERL_DUMP_RE_MAX_LEN""); if ( ! dump_len_string || ! grok_atoUV(dump_len_string, (UV *)&PL_dump_re_max_len, NULL)) { PL_dump_re_max_len = 60; /* A reasonable default */ } #endif } pRExC_state->warn_text = NULL; pRExC_state->unlexed_names = NULL; pRExC_state->code_blocks = NULL; if (is_bare_re) *is_bare_re = FALSE; if (expr && (expr->op_type == OP_LIST || (expr->op_type == OP_NULL && expr->op_targ == OP_LIST))) { /* allocate code_blocks if needed */ OP *o; int ncode = 0; for (o = cLISTOPx(expr)->op_first; o; o = OpSIBLING(o)) if (o->op_type == OP_NULL && (o->op_flags & OPf_SPECIAL)) ncode++; /* count of DO blocks */ if (ncode) pRExC_state->code_blocks = S_alloc_code_blocks(aTHX_ ncode); } if (!pat_count) { /* compile-time pattern with just OP_CONSTs and DO blocks */ int n; OP *o; /* find how many CONSTs there are */ assert(expr); n = 0; if (expr->op_type == OP_CONST) n = 1; else for (o = cLISTOPx(expr)->op_first; o; o = OpSIBLING(o)) { if (o->op_type == OP_CONST) n++; } /* fake up an SV array */ assert(!new_patternp); Newx(new_patternp, n, SV*); SAVEFREEPV(new_patternp); pat_count = n; n = 0; if (expr->op_type == OP_CONST) new_patternp[n] = cSVOPx_sv(expr); else for (o = cLISTOPx(expr)->op_first; o; o = OpSIBLING(o)) { if (o->op_type == OP_CONST) new_patternp[n++] = cSVOPo_sv; } } DEBUG_PARSE_r(Perl_re_printf( aTHX_ ""Assembling pattern from %d elements%s\n"", pat_count, orig_rx_flags & RXf_SPLIT ? "" for split"" : """")); /* set expr to the first arg op */ if (pRExC_state->code_blocks && pRExC_state->code_blocks->count && expr->op_type != OP_CONST) { expr = cLISTOPx(expr)->op_first; assert( expr->op_type == OP_PUSHMARK || (expr->op_type == OP_NULL && expr->op_targ == OP_PUSHMARK) || expr->op_type == OP_PADRANGE); expr = OpSIBLING(expr); } pat = S_concat_pat(aTHX_ pRExC_state, NULL, new_patternp, pat_count, expr, &recompile, NULL); /* handle bare (possibly after overloading) regex: foo =~ $re */ { SV *re = pat; if (SvROK(re)) re = SvRV(re); if (SvTYPE(re) == SVt_REGEXP) { if (is_bare_re) *is_bare_re = TRUE; SvREFCNT_inc(re); DEBUG_PARSE_r(Perl_re_printf( aTHX_ ""Precompiled pattern%s\n"", orig_rx_flags & RXf_SPLIT ? "" for split"" : """")); return (REGEXP*)re; } } exp = SvPV_nomg(pat, plen); if (!eng->op_comp) { if ((SvUTF8(pat) && IN_BYTES) || SvGMAGICAL(pat) || SvAMAGIC(pat)) { /* make a temporary copy; either to convert to bytes, * or to avoid repeating get-magic / overloaded stringify */ pat = newSVpvn_flags(exp, plen, SVs_TEMP | (IN_BYTES ? 0 : SvUTF8(pat))); } return CALLREGCOMP_ENG(eng, pat, orig_rx_flags); } /* ignore the utf8ness if the pattern is 0 length */ RExC_utf8 = RExC_orig_utf8 = (plen == 0 || IN_BYTES) ? 0 : SvUTF8(pat); RExC_uni_semantics = 0; RExC_contains_locale = 0; RExC_strict = cBOOL(pm_flags & RXf_PMf_STRICT); RExC_in_script_run = 0; RExC_study_started = 0; pRExC_state->runtime_code_qr = NULL; RExC_frame_head= NULL; RExC_frame_last= NULL; RExC_frame_count= 0; RExC_latest_warn_offset = 0; RExC_use_BRANCHJ = 0; RExC_total_parens = 0; RExC_open_parens = NULL; RExC_close_parens = NULL; RExC_paren_names = NULL; RExC_size = 0; RExC_seen_d_op = FALSE; #ifdef DEBUGGING RExC_paren_name_list = NULL; #endif DEBUG_r({ RExC_mysv1= sv_newmortal(); RExC_mysv2= sv_newmortal(); }); DEBUG_COMPILE_r({ SV *dsv= sv_newmortal(); RE_PV_QUOTED_DECL(s, RExC_utf8, dsv, exp, plen, PL_dump_re_max_len); Perl_re_printf( aTHX_ ""%sCompiling REx%s %s\n"", PL_colors[4], PL_colors[5], s); }); /* we jump here if we have to recompile, e.g., from upgrading the pattern * to utf8 */ if ((pm_flags & PMf_USE_RE_EVAL) /* this second condition covers the non-regex literal case, * i.e. $foo =~ '(?{})'. */ || (IN_PERL_COMPILETIME && (PL_hints & HINT_RE_EVAL)) ) runtime_code = S_has_runtime_code(aTHX_ pRExC_state, exp, plen); redo_parse: /* return old regex if pattern hasn't changed */ /* XXX: note in the below we have to check the flags as well as the * pattern. * * Things get a touch tricky as we have to compare the utf8 flag * independently from the compile flags. */ if ( old_re && !recompile && !!RX_UTF8(old_re) == !!RExC_utf8 && ( RX_COMPFLAGS(old_re) == ( orig_rx_flags & RXf_PMf_FLAGCOPYMASK ) ) && RX_PRECOMP(old_re) && RX_PRELEN(old_re) == plen && memEQ(RX_PRECOMP(old_re), exp, plen) && !runtime_code /* with runtime code, always recompile */ ) { return old_re; } /* Allocate the pattern's SV */ RExC_rx_sv = Rx = (REGEXP*) newSV_type(SVt_REGEXP); RExC_rx = ReANY(Rx); if ( RExC_rx == NULL ) FAIL(""Regexp out of space""); rx_flags = orig_rx_flags; if ( (UTF || RExC_uni_semantics) && initial_charset == REGEX_DEPENDS_CHARSET) { /* Set to use unicode semantics if the pattern is in utf8 and has the * 'depends' charset specified, as it means unicode when utf8 */ set_regex_charset(&rx_flags, REGEX_UNICODE_CHARSET); RExC_uni_semantics = 1; } RExC_pm_flags = pm_flags; if (runtime_code) { assert(TAINTING_get || !TAINT_get); if (TAINT_get) Perl_croak(aTHX_ ""Eval-group in insecure regular expression""); if (!S_compile_runtime_code(aTHX_ pRExC_state, exp, plen)) { /* whoops, we have a non-utf8 pattern, whilst run-time code * got compiled as utf8. Try again with a utf8 pattern */ S_pat_upgrade_to_utf8(aTHX_ pRExC_state, &exp, &plen, pRExC_state->code_blocks ? pRExC_state->code_blocks->count : 0); goto redo_parse; } } assert(!pRExC_state->runtime_code_qr); RExC_sawback = 0; RExC_seen = 0; RExC_maxlen = 0; RExC_in_lookbehind = 0; RExC_seen_zerolen = *exp == '^' ? -1 : 0; #ifdef EBCDIC RExC_recode_x_to_native = 0; #endif RExC_in_multi_char_class = 0; RExC_start = RExC_copy_start_in_constructed = RExC_copy_start_in_input = RExC_precomp = exp; RExC_precomp_end = RExC_end = exp + plen; RExC_nestroot = 0; RExC_whilem_seen = 0; RExC_end_op = NULL; RExC_recurse = NULL; RExC_study_chunk_recursed = NULL; RExC_study_chunk_recursed_bytes= 0; RExC_recurse_count = 0; pRExC_state->code_index = 0; /* Initialize the string in the compiled pattern. This is so that there is * something to output if necessary */ set_regex_pv(pRExC_state, Rx); DEBUG_PARSE_r({ Perl_re_printf( aTHX_ ""Starting parse and generation\n""); RExC_lastnum=0; RExC_lastparse=NULL; }); /* Allocate space and zero-initialize. Note, the two step process of zeroing when in debug mode, thus anything assigned has to happen after that */ if (! RExC_size) { /* On the first pass of the parse, we guess how big this will be. Then * we grow in one operation to that amount and then give it back. As * we go along, we re-allocate what we need. * * XXX Currently the guess is essentially that the pattern will be an * EXACT node with one byte input, one byte output. This is crude, and * better heuristics are welcome. * * On any subsequent passes, we guess what we actually computed in the * latest earlier pass. Such a pass probably didn't complete so is * missing stuff. We could improve those guesses by knowing where the * parse stopped, and use the length so far plus apply the above * assumption to what's left. */ RExC_size = STR_SZ(RExC_end - RExC_start); } Newxc(RExC_rxi, sizeof(regexp_internal) + RExC_size, char, regexp_internal); if ( RExC_rxi == NULL ) FAIL(""Regexp out of space""); Zero(RExC_rxi, sizeof(regexp_internal) + RExC_size, char); RXi_SET( RExC_rx, RExC_rxi ); /* We start from 0 (over from 0 in the case this is a reparse. The first * node parsed will give back any excess memory we have allocated so far). * */ RExC_size = 0; /* non-zero initialization begins here */ RExC_rx->engine= eng; RExC_rx->extflags = rx_flags; RXp_COMPFLAGS(RExC_rx) = orig_rx_flags & RXf_PMf_FLAGCOPYMASK; if (pm_flags & PMf_IS_QR) { RExC_rxi->code_blocks = pRExC_state->code_blocks; if (RExC_rxi->code_blocks) { RExC_rxi->code_blocks->refcnt++; } } RExC_rx->intflags = 0; RExC_flags = rx_flags; /* don't let top level (?i) bleed */ RExC_parse = exp; /* This NUL is guaranteed because the pattern comes from an SV*, and the sv * code makes sure the final byte is an uncounted NUL. But should this * ever not be the case, lots of things could read beyond the end of the * buffer: loops like * while(isFOO(*RExC_parse)) RExC_parse++; * strchr(RExC_parse, ""foo""); * etc. So it is worth noting. */ assert(*RExC_end == '\0'); RExC_naughty = 0; RExC_npar = 1; RExC_parens_buf_size = 0; RExC_emit_start = RExC_rxi->program; pRExC_state->code_index = 0; *((char*) RExC_emit_start) = (char) REG_MAGIC; RExC_emit = 1; /* Do the parse */ if (reg(pRExC_state, 0, &flags, 1)) { /* Success!, But we may need to redo the parse knowing how many parens * there actually are */ if (IN_PARENS_PASS) { flags |= RESTART_PARSE; } /* We have that number in RExC_npar */ RExC_total_parens = RExC_npar; /* XXX For backporting, use long jumps if there is any possibility of * overflow */ if (RExC_size > U16_MAX && ! RExC_use_BRANCHJ) { RExC_use_BRANCHJ = TRUE; flags |= RESTART_PARSE; } } else if (! MUST_RESTART(flags)) { ReREFCNT_dec(Rx); Perl_croak(aTHX_ ""panic: reg returned failure to re_op_compile, flags=%#"" UVxf, (UV) flags); } /* Here, we either have success, or we have to redo the parse for some reason */ if (MUST_RESTART(flags)) { /* It's possible to write a regexp in ascii that represents Unicode codepoints outside of the byte range, such as via \x{100}. If we detect such a sequence we have to convert the entire pattern to utf8 and then recompile, as our sizing calculation will have been based on 1 byte == 1 character, but we will need to use utf8 to encode at least some part of the pattern, and therefore must convert the whole thing. -- dmq */ if (flags & NEED_UTF8) { /* We have stored the offset of the final warning output so far. * That must be adjusted. Any variant characters between the start * of the pattern and this warning count for 2 bytes in the final, * so just add them again */ if (UNLIKELY(RExC_latest_warn_offset > 0)) { RExC_latest_warn_offset += variant_under_utf8_count((U8 *) exp, (U8 *) exp + RExC_latest_warn_offset); } S_pat_upgrade_to_utf8(aTHX_ pRExC_state, &exp, &plen, pRExC_state->code_blocks ? pRExC_state->code_blocks->count : 0); DEBUG_PARSE_r(Perl_re_printf( aTHX_ ""Need to redo parse after upgrade\n"")); } else { DEBUG_PARSE_r(Perl_re_printf( aTHX_ ""Need to redo parse\n"")); } if (ALL_PARENS_COUNTED) { /* Make enough room for all the known parens, and zero it */ Renew(RExC_open_parens, RExC_total_parens, regnode_offset); Zero(RExC_open_parens, RExC_total_parens, regnode_offset); RExC_open_parens[0] = 1; /* +1 for REG_MAGIC */ Renew(RExC_close_parens, RExC_total_parens, regnode_offset); Zero(RExC_close_parens, RExC_total_parens, regnode_offset); } else { /* Parse did not complete. Reinitialize the parentheses structures */ RExC_total_parens = 0; if (RExC_open_parens) { Safefree(RExC_open_parens); RExC_open_parens = NULL; } if (RExC_close_parens) { Safefree(RExC_close_parens); RExC_close_parens = NULL; } } /* Clean up what we did in this parse */ SvREFCNT_dec_NN(RExC_rx_sv); goto redo_parse; } /* Here, we have successfully parsed and generated the pattern's program * for the regex engine. We are ready to finish things up and look for * optimizations. */ /* Update the string to compile, with correct modifiers, etc */ set_regex_pv(pRExC_state, Rx); RExC_rx->nparens = RExC_total_parens - 1; /* Uses the upper 4 bits of the FLAGS field, so keep within that size */ if (RExC_whilem_seen > 15) RExC_whilem_seen = 15; DEBUG_PARSE_r({ Perl_re_printf( aTHX_ ""Required size %"" IVdf "" nodes\n"", (IV)RExC_size); RExC_lastnum=0; RExC_lastparse=NULL; }); #ifdef RE_TRACK_PATTERN_OFFSETS DEBUG_OFFSETS_r(Perl_re_printf( aTHX_ ""%s %"" UVuf "" bytes for offset annotations.\n"", RExC_offsets ? ""Got"" : ""Couldn't get"", (UV)((RExC_offsets[0] * 2 + 1)))); DEBUG_OFFSETS_r(if (RExC_offsets) { const STRLEN len = RExC_offsets[0]; STRLEN i; GET_RE_DEBUG_FLAGS_DECL; Perl_re_printf( aTHX_ ""Offsets: [%"" UVuf ""]\n\t"", (UV)RExC_offsets[0]); for (i = 1; i <= len; i++) { if (RExC_offsets[i*2-1] || RExC_offsets[i*2]) Perl_re_printf( aTHX_ ""%"" UVuf "":%"" UVuf ""[%"" UVuf ""] "", (UV)i, (UV)RExC_offsets[i*2-1], (UV)RExC_offsets[i*2]); } Perl_re_printf( aTHX_ ""\n""); }); #else SetProgLen(RExC_rxi,RExC_size); #endif DEBUG_OPTIMISE_r( Perl_re_printf( aTHX_ ""Starting post parse optimization\n""); ); /* XXXX To minimize changes to RE engine we always allocate 3-units-long substrs field. */ Newx(RExC_rx->substrs, 1, struct reg_substr_data); if (RExC_recurse_count) { Newx(RExC_recurse, RExC_recurse_count, regnode *); SAVEFREEPV(RExC_recurse); } if (RExC_seen & REG_RECURSE_SEEN) { /* Note, RExC_total_parens is 1 + the number of parens in a pattern. * So its 1 if there are no parens. */ RExC_study_chunk_recursed_bytes= (RExC_total_parens >> 3) + ((RExC_total_parens & 0x07) != 0); Newx(RExC_study_chunk_recursed, RExC_study_chunk_recursed_bytes * RExC_total_parens, U8); SAVEFREEPV(RExC_study_chunk_recursed); } reStudy: RExC_rx->minlen = minlen = sawlookahead = sawplus = sawopen = sawminmod = 0; DEBUG_r( RExC_study_chunk_recursed_count= 0; ); Zero(RExC_rx->substrs, 1, struct reg_substr_data); if (RExC_study_chunk_recursed) { Zero(RExC_study_chunk_recursed, RExC_study_chunk_recursed_bytes * RExC_total_parens, U8); } #ifdef TRIE_STUDY_OPT if (!restudied) { StructCopy(&zero_scan_data, &data, scan_data_t); copyRExC_state = RExC_state; } else { U32 seen=RExC_seen; DEBUG_OPTIMISE_r(Perl_re_printf( aTHX_ ""Restudying\n"")); RExC_state = copyRExC_state; if (seen & REG_TOP_LEVEL_BRANCHES_SEEN) RExC_seen |= REG_TOP_LEVEL_BRANCHES_SEEN; else RExC_seen &= ~REG_TOP_LEVEL_BRANCHES_SEEN; StructCopy(&zero_scan_data, &data, scan_data_t); } #else StructCopy(&zero_scan_data, &data, scan_data_t); #endif /* Dig out information for optimizations. */ RExC_rx->extflags = RExC_flags; /* was pm_op */ /*dmq: removed as part of de-PMOP: pm->op_pmflags = RExC_flags; */ if (UTF) SvUTF8_on(Rx); /* Unicode in it? */ RExC_rxi->regstclass = NULL; if (RExC_naughty >= TOO_NAUGHTY) /* Probably an expensive pattern. */ RExC_rx->intflags |= PREGf_NAUGHTY; scan = RExC_rxi->program + 1; /* First BRANCH. */ /* testing for BRANCH here tells us whether there is ""must appear"" data in the pattern. If there is then we can use it for optimisations */ if (!(RExC_seen & REG_TOP_LEVEL_BRANCHES_SEEN)) { /* Only one top-level choice. */ SSize_t fake; STRLEN longest_length[2]; regnode_ssc ch_class; /* pointed to by data */ int stclass_flag; SSize_t last_close = 0; /* pointed to by data */ regnode *first= scan; regnode *first_next= regnext(first); int i; /* * Skip introductions and multiplicators >= 1 * so that we can extract the 'meat' of the pattern that must * match in the large if() sequence following. * NOTE that EXACT is NOT covered here, as it is normally * picked up by the optimiser separately. * * This is unfortunate as the optimiser isnt handling lookahead * properly currently. * */ while ((OP(first) == OPEN && (sawopen = 1)) || /* An OR of *one* alternative - should not happen now. */ (OP(first) == BRANCH && OP(first_next) != BRANCH) || /* for now we can't handle lookbehind IFMATCH*/ (OP(first) == IFMATCH && !first->flags && (sawlookahead = 1)) || (OP(first) == PLUS) || (OP(first) == MINMOD) || /* An {n,m} with n>0 */ (PL_regkind[OP(first)] == CURLY && ARG1(first) > 0) || (OP(first) == NOTHING && PL_regkind[OP(first_next)] != END )) { /* * the only op that could be a regnode is PLUS, all the rest * will be regnode_1 or regnode_2. * * (yves doesn't think this is true) */ if (OP(first) == PLUS) sawplus = 1; else { if (OP(first) == MINMOD) sawminmod = 1; first += regarglen[OP(first)]; } first = NEXTOPER(first); first_next= regnext(first); } /* Starting-point info. */ again: DEBUG_PEEP(""first:"", first, 0, 0); /* Ignore EXACT as we deal with it later. */ if (PL_regkind[OP(first)] == EXACT) { if ( OP(first) == EXACT || OP(first) == EXACT_ONLY8 || OP(first) == EXACTL) { NOOP; /* Empty, get anchored substr later. */ } else RExC_rxi->regstclass = first; } #ifdef TRIE_STCLASS else if (PL_regkind[OP(first)] == TRIE && ((reg_trie_data *)RExC_rxi->data->data[ ARG(first) ])->minlen>0) { /* this can happen only on restudy */ RExC_rxi->regstclass = construct_ahocorasick_from_trie(pRExC_state, (regnode *)first, 0); } #endif else if (REGNODE_SIMPLE(OP(first))) RExC_rxi->regstclass = first; else if (PL_regkind[OP(first)] == BOUND || PL_regkind[OP(first)] == NBOUND) RExC_rxi->regstclass = first; else if (PL_regkind[OP(first)] == BOL) { RExC_rx->intflags |= (OP(first) == MBOL ? PREGf_ANCH_MBOL : PREGf_ANCH_SBOL); first = NEXTOPER(first); goto again; } else if (OP(first) == GPOS) { RExC_rx->intflags |= PREGf_ANCH_GPOS; first = NEXTOPER(first); goto again; } else if ((!sawopen || !RExC_sawback) && !sawlookahead && (OP(first) == STAR && PL_regkind[OP(NEXTOPER(first))] == REG_ANY) && !(RExC_rx->intflags & PREGf_ANCH) && !pRExC_state->code_blocks) { /* turn .* into ^.* with an implied $*=1 */ const int type = (OP(NEXTOPER(first)) == REG_ANY) ? PREGf_ANCH_MBOL : PREGf_ANCH_SBOL; RExC_rx->intflags |= (type | PREGf_IMPLICIT); first = NEXTOPER(first); goto again; } if (sawplus && !sawminmod && !sawlookahead && (!sawopen || !RExC_sawback) && !pRExC_state->code_blocks) /* May examine pos and $& */ /* x+ must match at the 1st pos of run of x's */ RExC_rx->intflags |= PREGf_SKIP; /* Scan is after the zeroth branch, first is atomic matcher. */ #ifdef TRIE_STUDY_OPT DEBUG_PARSE_r( if (!restudied) Perl_re_printf( aTHX_ ""first at %"" IVdf ""\n"", (IV)(first - scan + 1)) ); #else DEBUG_PARSE_r( Perl_re_printf( aTHX_ ""first at %"" IVdf ""\n"", (IV)(first - scan + 1)) ); #endif /* * If there's something expensive in the r.e., find the * longest literal string that must appear and make it the * regmust. Resolve ties in favor of later strings, since * the regstart check works with the beginning of the r.e. * and avoiding duplication strengthens checking. Not a * strong reason, but sufficient in the absence of others. * [Now we resolve ties in favor of the earlier string if * it happens that c_offset_min has been invalidated, since the * earlier string may buy us something the later one won't.] */ data.substrs[0].str = newSVpvs(""""); data.substrs[1].str = newSVpvs(""""); data.last_found = newSVpvs(""""); data.cur_is_floating = 0; /* initially any found substring is fixed */ ENTER_with_name(""study_chunk""); SAVEFREESV(data.substrs[0].str); SAVEFREESV(data.substrs[1].str); SAVEFREESV(data.last_found); first = scan; if (!RExC_rxi->regstclass) { ssc_init(pRExC_state, &ch_class); data.start_class = &ch_class; stclass_flag = SCF_DO_STCLASS_AND; } else /* XXXX Check for BOUND? */ stclass_flag = 0; data.last_closep = &last_close; DEBUG_RExC_seen(); /* * MAIN ENTRY FOR study_chunk() FOR m/PATTERN/ * (NO top level branches) */ minlen = study_chunk(pRExC_state, &first, &minlen, &fake, scan + RExC_size, /* Up to end */ &data, -1, 0, NULL, SCF_DO_SUBSTR | SCF_WHILEM_VISITED_POS | stclass_flag | (restudied ? SCF_TRIE_DOING_RESTUDY : 0), 0); CHECK_RESTUDY_GOTO_butfirst(LEAVE_with_name(""study_chunk"")); if ( RExC_total_parens == 1 && !data.cur_is_floating && data.last_start_min == 0 && data.last_end > 0 && !RExC_seen_zerolen && !(RExC_seen & REG_VERBARG_SEEN) && !(RExC_seen & REG_GPOS_SEEN) ){ RExC_rx->extflags |= RXf_CHECK_ALL; } scan_commit(pRExC_state, &data,&minlen, 0); /* XXX this is done in reverse order because that's the way the * code was before it was parameterised. Don't know whether it * actually needs doing in reverse order. DAPM */ for (i = 1; i >= 0; i--) { longest_length[i] = CHR_SVLEN(data.substrs[i].str); if ( !( i && SvCUR(data.substrs[0].str) /* ok to leave SvCUR */ && data.substrs[0].min_offset == data.substrs[1].min_offset && SvCUR(data.substrs[0].str) == SvCUR(data.substrs[1].str) ) && S_setup_longest (aTHX_ pRExC_state, &(RExC_rx->substrs->data[i]), &(data.substrs[i]), longest_length[i])) { RExC_rx->substrs->data[i].min_offset = data.substrs[i].min_offset - data.substrs[i].lookbehind; RExC_rx->substrs->data[i].max_offset = data.substrs[i].max_offset; /* Don't offset infinity */ if (data.substrs[i].max_offset < SSize_t_MAX) RExC_rx->substrs->data[i].max_offset -= data.substrs[i].lookbehind; SvREFCNT_inc_simple_void_NN(data.substrs[i].str); } else { RExC_rx->substrs->data[i].substr = NULL; RExC_rx->substrs->data[i].utf8_substr = NULL; longest_length[i] = 0; } } LEAVE_with_name(""study_chunk""); if (RExC_rxi->regstclass && (OP(RExC_rxi->regstclass) == REG_ANY || OP(RExC_rxi->regstclass) == SANY)) RExC_rxi->regstclass = NULL; if ((!(RExC_rx->substrs->data[0].substr || RExC_rx->substrs->data[0].utf8_substr) || RExC_rx->substrs->data[0].min_offset) && stclass_flag && ! (ANYOF_FLAGS(data.start_class) & SSC_MATCHES_EMPTY_STRING) && is_ssc_worth_it(pRExC_state, data.start_class)) { const U32 n = add_data(pRExC_state, STR_WITH_LEN(""f"")); ssc_finalize(pRExC_state, data.start_class); Newx(RExC_rxi->data->data[n], 1, regnode_ssc); StructCopy(data.start_class, (regnode_ssc*)RExC_rxi->data->data[n], regnode_ssc); RExC_rxi->regstclass = (regnode*)RExC_rxi->data->data[n]; RExC_rx->intflags &= ~PREGf_SKIP; /* Used in find_byclass(). */ DEBUG_COMPILE_r({ SV *sv = sv_newmortal(); regprop(RExC_rx, sv, (regnode*)data.start_class, NULL, pRExC_state); Perl_re_printf( aTHX_ ""synthetic stclass \""%s\"".\n"", SvPVX_const(sv));}); data.start_class = NULL; } /* A temporary algorithm prefers floated substr to fixed one of * same length to dig more info. */ i = (longest_length[0] <= longest_length[1]); RExC_rx->substrs->check_ix = i; RExC_rx->check_end_shift = RExC_rx->substrs->data[i].end_shift; RExC_rx->check_substr = RExC_rx->substrs->data[i].substr; RExC_rx->check_utf8 = RExC_rx->substrs->data[i].utf8_substr; RExC_rx->check_offset_min = RExC_rx->substrs->data[i].min_offset; RExC_rx->check_offset_max = RExC_rx->substrs->data[i].max_offset; if (!i && (RExC_rx->intflags & (PREGf_ANCH_SBOL|PREGf_ANCH_GPOS))) RExC_rx->intflags |= PREGf_NOSCAN; if ((RExC_rx->check_substr || RExC_rx->check_utf8) ) { RExC_rx->extflags |= RXf_USE_INTUIT; if (SvTAIL(RExC_rx->check_substr ? RExC_rx->check_substr : RExC_rx->check_utf8)) RExC_rx->extflags |= RXf_INTUIT_TAIL; } /* XXX Unneeded? dmq (shouldn't as this is handled elsewhere) if ( (STRLEN)minlen < longest_length[1] ) minlen= longest_length[1]; if ( (STRLEN)minlen < longest_length[0] ) minlen= longest_length[0]; */ } else { /* Several toplevels. Best we can is to set minlen. */ SSize_t fake; regnode_ssc ch_class; SSize_t last_close = 0; DEBUG_PARSE_r(Perl_re_printf( aTHX_ ""\nMulti Top Level\n"")); scan = RExC_rxi->program + 1; ssc_init(pRExC_state, &ch_class); data.start_class = &ch_class; data.last_closep = &last_close; DEBUG_RExC_seen(); /* * MAIN ENTRY FOR study_chunk() FOR m/P1|P2|.../ * (patterns WITH top level branches) */ minlen = study_chunk(pRExC_state, &scan, &minlen, &fake, scan + RExC_size, &data, -1, 0, NULL, SCF_DO_STCLASS_AND|SCF_WHILEM_VISITED_POS|(restudied ? SCF_TRIE_DOING_RESTUDY : 0), 0); CHECK_RESTUDY_GOTO_butfirst(NOOP); RExC_rx->check_substr = NULL; RExC_rx->check_utf8 = NULL; RExC_rx->substrs->data[0].substr = NULL; RExC_rx->substrs->data[0].utf8_substr = NULL; RExC_rx->substrs->data[1].substr = NULL; RExC_rx->substrs->data[1].utf8_substr = NULL; if (! (ANYOF_FLAGS(data.start_class) & SSC_MATCHES_EMPTY_STRING) && is_ssc_worth_it(pRExC_state, data.start_class)) { const U32 n = add_data(pRExC_state, STR_WITH_LEN(""f"")); ssc_finalize(pRExC_state, data.start_class); Newx(RExC_rxi->data->data[n], 1, regnode_ssc); StructCopy(data.start_class, (regnode_ssc*)RExC_rxi->data->data[n], regnode_ssc); RExC_rxi->regstclass = (regnode*)RExC_rxi->data->data[n]; RExC_rx->intflags &= ~PREGf_SKIP; /* Used in find_byclass(). */ DEBUG_COMPILE_r({ SV* sv = sv_newmortal(); regprop(RExC_rx, sv, (regnode*)data.start_class, NULL, pRExC_state); Perl_re_printf( aTHX_ ""synthetic stclass \""%s\"".\n"", SvPVX_const(sv));}); data.start_class = NULL; } } if (RExC_seen & REG_UNBOUNDED_QUANTIFIER_SEEN) { RExC_rx->extflags |= RXf_UNBOUNDED_QUANTIFIER_SEEN; RExC_rx->maxlen = REG_INFTY; } else { RExC_rx->maxlen = RExC_maxlen; } /* Guard against an embedded (?=) or (?<=) with a longer minlen than the ""real"" pattern. */ DEBUG_OPTIMISE_r({ Perl_re_printf( aTHX_ ""minlen: %"" IVdf "" RExC_rx->minlen:%"" IVdf "" maxlen:%"" IVdf ""\n"", (IV)minlen, (IV)RExC_rx->minlen, (IV)RExC_maxlen); }); RExC_rx->minlenret = minlen; if (RExC_rx->minlen < minlen) RExC_rx->minlen = minlen; if (RExC_seen & REG_RECURSE_SEEN ) { RExC_rx->intflags |= PREGf_RECURSE_SEEN; Newx(RExC_rx->recurse_locinput, RExC_rx->nparens + 1, char *); } if (RExC_seen & REG_GPOS_SEEN) RExC_rx->intflags |= PREGf_GPOS_SEEN; if (RExC_seen & REG_LOOKBEHIND_SEEN) RExC_rx->extflags |= RXf_NO_INPLACE_SUBST; /* inplace might break the lookbehind */ if (pRExC_state->code_blocks) RExC_rx->extflags |= RXf_EVAL_SEEN; if (RExC_seen & REG_VERBARG_SEEN) { RExC_rx->intflags |= PREGf_VERBARG_SEEN; RExC_rx->extflags |= RXf_NO_INPLACE_SUBST; /* don't understand this! Yves */ } if (RExC_seen & REG_CUTGROUP_SEEN) RExC_rx->intflags |= PREGf_CUTGROUP_SEEN; if (pm_flags & PMf_USE_RE_EVAL) RExC_rx->intflags |= PREGf_USE_RE_EVAL; if (RExC_paren_names) RXp_PAREN_NAMES(RExC_rx) = MUTABLE_HV(SvREFCNT_inc(RExC_paren_names)); else RXp_PAREN_NAMES(RExC_rx) = NULL; /* If we have seen an anchor in our pattern then we set the extflag RXf_IS_ANCHORED * so it can be used in pp.c */ if (RExC_rx->intflags & PREGf_ANCH) RExC_rx->extflags |= RXf_IS_ANCHORED; { /* this is used to identify ""special"" patterns that might result * in Perl NOT calling the regex engine and instead doing the match ""itself"", * particularly special cases in split//. By having the regex compiler * do this pattern matching at a regop level (instead of by inspecting the pattern) * we avoid weird issues with equivalent patterns resulting in different behavior, * AND we allow non Perl engines to get the same optimizations by the setting the * flags appropriately - Yves */ regnode *first = RExC_rxi->program + 1; U8 fop = OP(first); regnode *next = regnext(first); U8 nop = OP(next); if (PL_regkind[fop] == NOTHING && nop == END) RExC_rx->extflags |= RXf_NULL; else if ((fop == MBOL || (fop == SBOL && !first->flags)) && nop == END) /* when fop is SBOL first->flags will be true only when it was * produced by parsing /\A/, and not when parsing /^/. This is * very important for the split code as there we want to * treat /^/ as /^/m, but we do not want to treat /\A/ as /^/m. * See rt #122761 for more details. -- Yves */ RExC_rx->extflags |= RXf_START_ONLY; else if (fop == PLUS && PL_regkind[nop] == POSIXD && FLAGS(next) == _CC_SPACE && nop == END) RExC_rx->extflags |= RXf_WHITE; else if ( RExC_rx->extflags & RXf_SPLIT && (fop == EXACT || fop == EXACT_ONLY8 || fop == EXACTL) && STR_LEN(first) == 1 && *(STRING(first)) == ' ' && nop == END ) RExC_rx->extflags |= (RXf_SKIPWHITE|RXf_WHITE); } if (RExC_contains_locale) { RXp_EXTFLAGS(RExC_rx) |= RXf_TAINTED; } #ifdef DEBUGGING if (RExC_paren_names) { RExC_rxi->name_list_idx = add_data( pRExC_state, STR_WITH_LEN(""a"")); RExC_rxi->data->data[RExC_rxi->name_list_idx] = (void*)SvREFCNT_inc(RExC_paren_name_list); } else #endif RExC_rxi->name_list_idx = 0; while ( RExC_recurse_count > 0 ) { const regnode *scan = RExC_recurse[ --RExC_recurse_count ]; /* * This data structure is set up in study_chunk() and is used * to calculate the distance between a GOSUB regopcode and * the OPEN/CURLYM (CURLYM's are special and can act like OPEN's) * it refers to. * * If for some reason someone writes code that optimises * away a GOSUB opcode then the assert should be changed to * an if(scan) to guard the ARG2L_SET() - Yves * */ assert(scan && OP(scan) == GOSUB); ARG2L_SET( scan, RExC_open_parens[ARG(scan)] - REGNODE_OFFSET(scan)); } Newxz(RExC_rx->offs, RExC_total_parens, regexp_paren_pair); /* assume we don't need to swap parens around before we match */ DEBUG_TEST_r({ Perl_re_printf( aTHX_ ""study_chunk_recursed_count: %lu\n"", (unsigned long)RExC_study_chunk_recursed_count); }); DEBUG_DUMP_r({ DEBUG_RExC_seen(); Perl_re_printf( aTHX_ ""Final program:\n""); regdump(RExC_rx); }); if (RExC_open_parens) { Safefree(RExC_open_parens); RExC_open_parens = NULL; } if (RExC_close_parens) { Safefree(RExC_close_parens); RExC_close_parens = NULL; } #ifdef USE_ITHREADS /* under ithreads the ?pat? PMf_USED flag on the pmop is simulated * by setting the regexp SV to readonly-only instead. If the * pattern's been recompiled, the USEDness should remain. */ if (old_re && SvREADONLY(old_re)) SvREADONLY_on(Rx); #endif return Rx;","{'deleted': [], 'added': [{'line_no': 381, 'char_start': 12024, 'char_end': 12025, 'line': '\n'}, {'line_no': 382, 'char_start': 12025, 'char_end': 12103, 'line': ' /* XXX For backporting, use long jumps if there is any possibility of\n'}, {'line_no': 383, 'char_start': 12103, 'char_end': 12126, 'line': ' * overflow */\n'}, {'line_no': 384, 'char_start': 12126, 'char_end': 12183, 'line': ' if (RExC_size > U16_MAX && ! RExC_use_BRANCHJ) {\n'}, {'line_no': 385, 'char_start': 12183, 'char_end': 12220, 'line': ' RExC_use_BRANCHJ = TRUE;\n'}, {'line_no': 386, 'char_start': 12220, 'char_end': 12256, 'line': ' flags |= RESTART_PARSE;\n'}, {'line_no': 387, 'char_start': 12256, 'char_end': 12266, 'line': ' }\n'}]}","{'deleted': [], 'added': [{'char_start': 12024, 'char_end': 12266, 'chars': '\n /* XXX For backporting, use long jumps if there is any possibility of\n * overflow */\n if (RExC_size > U16_MAX && ! RExC_use_BRANCHJ) {\n RExC_use_BRANCHJ = TRUE;\n flags |= RESTART_PARSE;\n }\n'}]}",github.com/perl/perl5/commit/3295b48defa0f8570114877b063fe546dd348b3c,regcomp.c,cwe-190,10428 cwe-022,Utility::UnZip,"bool Utility::UnZip(const QString &zippath, const QString &destpath) { int res = 0; QDir dir(destpath); if (!cp437) { cp437 = new QCodePage437Codec(); } #ifdef Q_OS_WIN32 zlib_filefunc64_def ffunc; fill_win32_filefunc64W(&ffunc); unzFile zfile = unzOpen2_64(Utility::QStringToStdWString(QDir::toNativeSeparators(zippath)).c_str(), &ffunc); #else unzFile zfile = unzOpen64(QDir::toNativeSeparators(zippath).toUtf8().constData()); #endif if ((zfile == NULL) || (!IsFileReadable(zippath)) || (!dir.exists())) { return false; } res = unzGoToFirstFile(zfile); if (res == UNZ_OK) { do { // Get the name of the file in the archive. char file_name[MAX_PATH] = {0}; unz_file_info64 file_info; unzGetCurrentFileInfo64(zfile, &file_info, file_name, MAX_PATH, NULL, 0, NULL, 0); QString qfile_name; QString cp437_file_name; qfile_name = QString::fromUtf8(file_name); if (!(file_info.flag & (1<<11))) { // General purpose bit 11 says the filename is utf-8 encoded. If not set then // IBM 437 encoding might be used. cp437_file_name = cp437->toUnicode(file_name); } // If there is no file name then we can't do anything with it. if (!qfile_name.isEmpty()) { // We use the dir object to create the path in the temporary directory. // Unfortunately, we need a dir ojbect to do this as it's not a static function. // Full file path in the temporary directory. QString file_path = destpath + ""/"" + qfile_name; QFileInfo qfile_info(file_path); // Is this entry a directory? if (file_info.uncompressed_size == 0 && qfile_name.endsWith('/')) { dir.mkpath(qfile_name); continue; } else { dir.mkpath(qfile_info.path()); } // Open the file entry in the archive for reading. if (unzOpenCurrentFile(zfile) != UNZ_OK) { unzClose(zfile); return false; } // Open the file on disk to write the entry in the archive to. QFile entry(file_path); if (!entry.open(QIODevice::WriteOnly | QIODevice::Truncate)) { unzCloseCurrentFile(zfile); unzClose(zfile); return false; } // Buffered reading and writing. char buff[BUFF_SIZE] = {0}; int read = 0; while ((read = unzReadCurrentFile(zfile, buff, BUFF_SIZE)) > 0) { entry.write(buff, read); } entry.close(); // Read errors are marked by a negative read amount. if (read < 0) { unzCloseCurrentFile(zfile); unzClose(zfile); return false; } // The file was read but the CRC did not match. // We don't check the read file size vs the uncompressed file size // because if they're different there should be a CRC error. if (unzCloseCurrentFile(zfile) == UNZ_CRCERROR) { unzClose(zfile); return false; } if (!cp437_file_name.isEmpty() && cp437_file_name != qfile_name) { QString cp437_file_path = destpath + ""/"" + cp437_file_name; QFile::copy(file_path, cp437_file_path); } } } while ((res = unzGoToNextFile(zfile)) == UNZ_OK); } if (res != UNZ_END_OF_LIST_OF_FILE) { unzClose(zfile); return false; } unzClose(zfile); return true; }","bool Utility::UnZip(const QString &zippath, const QString &destpath) { int res = 0; QDir dir(destpath); if (!cp437) { cp437 = new QCodePage437Codec(); } #ifdef Q_OS_WIN32 zlib_filefunc64_def ffunc; fill_win32_filefunc64W(&ffunc); unzFile zfile = unzOpen2_64(Utility::QStringToStdWString(QDir::toNativeSeparators(zippath)).c_str(), &ffunc); #else unzFile zfile = unzOpen64(QDir::toNativeSeparators(zippath).toUtf8().constData()); #endif if ((zfile == NULL) || (!IsFileReadable(zippath)) || (!dir.exists())) { return false; } res = unzGoToFirstFile(zfile); if (res == UNZ_OK) { do { // Get the name of the file in the archive. char file_name[MAX_PATH] = {0}; unz_file_info64 file_info; unzGetCurrentFileInfo64(zfile, &file_info, file_name, MAX_PATH, NULL, 0, NULL, 0); QString qfile_name; QString cp437_file_name; qfile_name = QString::fromUtf8(file_name); if (!(file_info.flag & (1<<11))) { // General purpose bit 11 says the filename is utf-8 encoded. If not set then // IBM 437 encoding might be used. cp437_file_name = cp437->toUnicode(file_name); } // If there is no file name then we can't do anything with it. if (!qfile_name.isEmpty()) { // for security reasons against maliciously crafted zip archives // we need the file path to always be inside the target folder // and not outside, so we will remove all illegal backslashes // and all relative upward paths segments ""/../"" from the zip's local // file name/path before prepending the target folder to create // the final path QString original_path = qfile_name; bool evil_or_corrupt_epub = false; if (qfile_name.contains(""\\"")) evil_or_corrupt_epub = true; qfile_name = ""/"" + qfile_name.replace(""\\"",""""); if (qfile_name.contains(""/../"")) evil_or_corrupt_epub = true; qfile_name = qfile_name.replace(""/../"",""/""); while(qfile_name.startsWith(""/"")) { qfile_name = qfile_name.remove(0,1); } if (cp437_file_name.contains(""\\"")) evil_or_corrupt_epub = true; cp437_file_name = ""/"" + cp437_file_name.replace(""\\"",""""); if (cp437_file_name.contains(""/../"")) evil_or_corrupt_epub = true; cp437_file_name = cp437_file_name.replace(""/../"",""/""); while(cp437_file_name.startsWith(""/"")) { cp437_file_name = cp437_file_name.remove(0,1); } if (evil_or_corrupt_epub) { unzCloseCurrentFile(zfile); unzClose(zfile); // throw (UNZIPLoadParseError(QString(QObject::tr(""Possible evil or corrupt zip file name: %1"")).arg(original_path).toStdString())); return false; } // We use the dir object to create the path in the temporary directory. // Unfortunately, we need a dir ojbect to do this as it's not a static function. // Full file path in the temporary directory. QString file_path = destpath + ""/"" + qfile_name; QFileInfo qfile_info(file_path); // Is this entry a directory? if (file_info.uncompressed_size == 0 && qfile_name.endsWith('/')) { dir.mkpath(qfile_name); continue; } else { dir.mkpath(qfile_info.path()); } // Open the file entry in the archive for reading. if (unzOpenCurrentFile(zfile) != UNZ_OK) { unzClose(zfile); return false; } // Open the file on disk to write the entry in the archive to. QFile entry(file_path); if (!entry.open(QIODevice::WriteOnly | QIODevice::Truncate)) { unzCloseCurrentFile(zfile); unzClose(zfile); return false; } // Buffered reading and writing. char buff[BUFF_SIZE] = {0}; int read = 0; while ((read = unzReadCurrentFile(zfile, buff, BUFF_SIZE)) > 0) { entry.write(buff, read); } entry.close(); // Read errors are marked by a negative read amount. if (read < 0) { unzCloseCurrentFile(zfile); unzClose(zfile); return false; } // The file was read but the CRC did not match. // We don't check the read file size vs the uncompressed file size // because if they're different there should be a CRC error. if (unzCloseCurrentFile(zfile) == UNZ_CRCERROR) { unzClose(zfile); return false; } if (!cp437_file_name.isEmpty() && cp437_file_name != qfile_name) { QString cp437_file_path = destpath + ""/"" + cp437_file_name; QFile::copy(file_path, cp437_file_path); } } } while ((res = unzGoToNextFile(zfile)) == UNZ_OK); } if (res != UNZ_END_OF_LIST_OF_FILE) { unzClose(zfile); return false; } unzClose(zfile); return true; }","{'deleted': [], 'added': [{'line_no': 39, 'char_start': 1400, 'char_end': 1401, 'line': '\n'}, {'line_no': 46, 'char_start': 1800, 'char_end': 1801, 'line': '\n'}, {'line_no': 47, 'char_start': 1801, 'char_end': 1846, 'line': '\t QString original_path = qfile_name;\n'}, {'line_no': 48, 'char_start': 1846, 'char_end': 1890, 'line': '\t bool evil_or_corrupt_epub = false;\n'}, {'line_no': 49, 'char_start': 1890, 'char_end': 1891, 'line': '\n'}, {'line_no': 50, 'char_start': 1891, 'char_end': 1961, 'line': '\t if (qfile_name.contains(""\\\\"")) evil_or_corrupt_epub = true; \n'}, {'line_no': 51, 'char_start': 1961, 'char_end': 2018, 'line': '\t qfile_name = ""/"" + qfile_name.replace(""\\\\"","""");\n'}, {'line_no': 52, 'char_start': 2018, 'char_end': 2019, 'line': '\n'}, {'line_no': 53, 'char_start': 2019, 'char_end': 2090, 'line': '\t if (qfile_name.contains(""/../"")) evil_or_corrupt_epub = true;\n'}, {'line_no': 54, 'char_start': 2090, 'char_end': 2144, 'line': '\t qfile_name = qfile_name.replace(""/../"",""/"");\n'}, {'line_no': 55, 'char_start': 2144, 'char_end': 2145, 'line': '\n'}, {'line_no': 56, 'char_start': 2145, 'char_end': 2191, 'line': '\t while(qfile_name.startsWith(""/"")) { \n'}, {'line_no': 57, 'char_start': 2191, 'char_end': 2232, 'line': '\t\t qfile_name = qfile_name.remove(0,1);\n'}, {'line_no': 58, 'char_start': 2232, 'char_end': 2243, 'line': '\t }\n'}, {'line_no': 59, 'char_start': 2243, 'char_end': 2260, 'line': ' \n'}, {'line_no': 60, 'char_start': 2260, 'char_end': 2335, 'line': '\t if (cp437_file_name.contains(""\\\\"")) evil_or_corrupt_epub = true; \n'}, {'line_no': 61, 'char_start': 2335, 'char_end': 2402, 'line': '\t cp437_file_name = ""/"" + cp437_file_name.replace(""\\\\"","""");\n'}, {'line_no': 62, 'char_start': 2402, 'char_end': 2403, 'line': '\n'}, {'line_no': 63, 'char_start': 2403, 'char_end': 2479, 'line': '\t if (cp437_file_name.contains(""/../"")) evil_or_corrupt_epub = true;\n'}, {'line_no': 64, 'char_start': 2479, 'char_end': 2543, 'line': '\t cp437_file_name = cp437_file_name.replace(""/../"",""/"");\n'}, {'line_no': 65, 'char_start': 2543, 'char_end': 2544, 'line': '\n'}, {'line_no': 66, 'char_start': 2544, 'char_end': 2595, 'line': '\t while(cp437_file_name.startsWith(""/"")) { \n'}, {'line_no': 67, 'char_start': 2595, 'char_end': 2646, 'line': '\t\t cp437_file_name = cp437_file_name.remove(0,1);\n'}, {'line_no': 68, 'char_start': 2646, 'char_end': 2657, 'line': '\t }\n'}, {'line_no': 69, 'char_start': 2657, 'char_end': 2658, 'line': '\n'}, {'line_no': 70, 'char_start': 2658, 'char_end': 2695, 'line': '\t if (evil_or_corrupt_epub) {\n'}, {'line_no': 71, 'char_start': 2695, 'char_end': 2729, 'line': '\t\t unzCloseCurrentFile(zfile);\n'}, {'line_no': 72, 'char_start': 2729, 'char_end': 2752, 'line': '\t\t unzClose(zfile);\n'}, {'line_no': 74, 'char_start': 2891, 'char_end': 2925, 'line': ' return false;\n'}, {'line_no': 75, 'char_start': 2925, 'char_end': 2936, 'line': '\t }\n'}, {'line_no': 76, 'char_start': 2936, 'char_end': 2937, 'line': '\n'}]}","{'deleted': [], 'added': [{'char_start': 1400, 'char_end': 2937, 'chars': '\n\t // for security reasons against maliciously crafted zip archives\n\t // we need the file path to always be inside the target folder \n\t // and not outside, so we will remove all illegal backslashes\n\t // and all relative upward paths segments ""/../"" from the zip\'s local \n\t // file name/path before prepending the target folder to create \n\t // the final path\n\n\t QString original_path = qfile_name;\n\t bool evil_or_corrupt_epub = false;\n\n\t if (qfile_name.contains(""\\\\"")) evil_or_corrupt_epub = true; \n\t qfile_name = ""/"" + qfile_name.replace(""\\\\"","""");\n\n\t if (qfile_name.contains(""/../"")) evil_or_corrupt_epub = true;\n\t qfile_name = qfile_name.replace(""/../"",""/"");\n\n\t while(qfile_name.startsWith(""/"")) { \n\t\t qfile_name = qfile_name.remove(0,1);\n\t }\n \n\t if (cp437_file_name.contains(""\\\\"")) evil_or_corrupt_epub = true; \n\t cp437_file_name = ""/"" + cp437_file_name.replace(""\\\\"","""");\n\n\t if (cp437_file_name.contains(""/../"")) evil_or_corrupt_epub = true;\n\t cp437_file_name = cp437_file_name.replace(""/../"",""/"");\n\n\t while(cp437_file_name.startsWith(""/"")) { \n\t\t cp437_file_name = cp437_file_name.remove(0,1);\n\t }\n\n\t if (evil_or_corrupt_epub) {\n\t\t unzCloseCurrentFile(zfile);\n\t\t unzClose(zfile);\n\t\t // throw (UNZIPLoadParseError(QString(QObject::tr(""Possible evil or corrupt zip file name: %1"")).arg(original_path).toStdString()));\n return false;\n\t }\n\n'}]}",github.com/Sigil-Ebook/Sigil/commit/0979ba8d10c96ebca330715bfd4494ea0e019a8f,src/Misc/Utility.cpp,cwe-022,928 cwe-190,ApplyEvaluateOperator,"static MagickRealType ApplyEvaluateOperator(RandomInfo *random_info, const Quantum pixel,const MagickEvaluateOperator op, const MagickRealType value) { MagickRealType result; result=0.0; switch (op) { case UndefinedEvaluateOperator: break; case AbsEvaluateOperator: { result=(MagickRealType) fabs((double) (pixel+value)); break; } case AddEvaluateOperator: { result=(MagickRealType) (pixel+value); break; } case AddModulusEvaluateOperator: { /* This returns a 'floored modulus' of the addition which is a positive result. It differs from % or fmod() which returns a 'truncated modulus' result, where floor() is replaced by trunc() and could return a negative result (which is clipped). */ result=pixel+value; result-=(QuantumRange+1.0)*floor((double) result/(QuantumRange+1.0)); break; } case AndEvaluateOperator: { result=(MagickRealType) ((size_t) pixel & (size_t) (value+0.5)); break; } case CosineEvaluateOperator: { result=(MagickRealType) (QuantumRange*(0.5*cos((double) (2.0*MagickPI* QuantumScale*pixel*value))+0.5)); break; } case DivideEvaluateOperator: { result=pixel/(value == 0.0 ? 1.0 : value); break; } case ExponentialEvaluateOperator: { result=(MagickRealType) (QuantumRange*exp((double) (value*QuantumScale* pixel))); break; } case GaussianNoiseEvaluateOperator: { result=(MagickRealType) GenerateDifferentialNoise(random_info,pixel, GaussianNoise,value); break; } case ImpulseNoiseEvaluateOperator: { result=(MagickRealType) GenerateDifferentialNoise(random_info,pixel, ImpulseNoise,value); break; } case LaplacianNoiseEvaluateOperator: { result=(MagickRealType) GenerateDifferentialNoise(random_info,pixel, LaplacianNoise,value); break; } case LeftShiftEvaluateOperator: { result=(MagickRealType) ((size_t) pixel << (size_t) (value+0.5)); break; } case LogEvaluateOperator: { if ((QuantumScale*pixel) >= MagickEpsilon) result=(MagickRealType) (QuantumRange*log((double) (QuantumScale*value* pixel+1.0))/log((double) (value+1.0))); break; } case MaxEvaluateOperator: { result=(MagickRealType) EvaluateMax((double) pixel,value); break; } case MeanEvaluateOperator: { result=(MagickRealType) (pixel+value); break; } case MedianEvaluateOperator: { result=(MagickRealType) (pixel+value); break; } case MinEvaluateOperator: { result=(MagickRealType) MagickMin((double) pixel,value); break; } case MultiplicativeNoiseEvaluateOperator: { result=(MagickRealType) GenerateDifferentialNoise(random_info,pixel, MultiplicativeGaussianNoise,value); break; } case MultiplyEvaluateOperator: { result=(MagickRealType) (value*pixel); break; } case OrEvaluateOperator: { result=(MagickRealType) ((size_t) pixel | (size_t) (value+0.5)); break; } case PoissonNoiseEvaluateOperator: { result=(MagickRealType) GenerateDifferentialNoise(random_info,pixel, PoissonNoise,value); break; } case PowEvaluateOperator: { result=(MagickRealType) (QuantumRange*pow((double) (QuantumScale*pixel), (double) value)); break; } case RightShiftEvaluateOperator: { result=(MagickRealType) ((size_t) pixel >> (size_t) (value+0.5)); break; } case RootMeanSquareEvaluateOperator: { result=(MagickRealType) (pixel*pixel+value); break; } case SetEvaluateOperator: { result=value; break; } case SineEvaluateOperator: { result=(MagickRealType) (QuantumRange*(0.5*sin((double) (2.0*MagickPI* QuantumScale*pixel*value))+0.5)); break; } case SubtractEvaluateOperator: { result=(MagickRealType) (pixel-value); break; } case SumEvaluateOperator: { result=(MagickRealType) (pixel+value); break; } case ThresholdEvaluateOperator: { result=(MagickRealType) (((MagickRealType) pixel <= value) ? 0 : QuantumRange); break; } case ThresholdBlackEvaluateOperator: { result=(MagickRealType) (((MagickRealType) pixel <= value) ? 0 : pixel); break; } case ThresholdWhiteEvaluateOperator: { result=(MagickRealType) (((MagickRealType) pixel > value) ? QuantumRange : pixel); break; } case UniformNoiseEvaluateOperator: { result=(MagickRealType) GenerateDifferentialNoise(random_info,pixel, UniformNoise,value); break; } case XorEvaluateOperator: { result=(MagickRealType) ((size_t) pixel ^ (size_t) (value+0.5)); break; } } return(result); }","static MagickRealType ApplyEvaluateOperator(RandomInfo *random_info, const Quantum pixel,const MagickEvaluateOperator op, const MagickRealType value) { MagickRealType result; result=0.0; switch (op) { case UndefinedEvaluateOperator: break; case AbsEvaluateOperator: { result=(MagickRealType) fabs((double) (pixel+value)); break; } case AddEvaluateOperator: { result=(MagickRealType) (pixel+value); break; } case AddModulusEvaluateOperator: { /* This returns a 'floored modulus' of the addition which is a positive result. It differs from % or fmod() which returns a 'truncated modulus' result, where floor() is replaced by trunc() and could return a negative result (which is clipped). */ result=pixel+value; result-=(QuantumRange+1.0)*floor((double) result/(QuantumRange+1.0)); break; } case AndEvaluateOperator: { result=(MagickRealType) ((ssize_t) pixel & (ssize_t) (value+0.5)); break; } case CosineEvaluateOperator: { result=(MagickRealType) (QuantumRange*(0.5*cos((double) (2.0*MagickPI* QuantumScale*pixel*value))+0.5)); break; } case DivideEvaluateOperator: { result=pixel/(value == 0.0 ? 1.0 : value); break; } case ExponentialEvaluateOperator: { result=(MagickRealType) (QuantumRange*exp((double) (value*QuantumScale* pixel))); break; } case GaussianNoiseEvaluateOperator: { result=(MagickRealType) GenerateDifferentialNoise(random_info,pixel, GaussianNoise,value); break; } case ImpulseNoiseEvaluateOperator: { result=(MagickRealType) GenerateDifferentialNoise(random_info,pixel, ImpulseNoise,value); break; } case LaplacianNoiseEvaluateOperator: { result=(MagickRealType) GenerateDifferentialNoise(random_info,pixel, LaplacianNoise,value); break; } case LeftShiftEvaluateOperator: { result=(MagickRealType) ((ssize_t) pixel << (ssize_t) (value+0.5)); break; } case LogEvaluateOperator: { if ((QuantumScale*pixel) >= MagickEpsilon) result=(MagickRealType) (QuantumRange*log((double) (QuantumScale*value* pixel+1.0))/log((double) (value+1.0))); break; } case MaxEvaluateOperator: { result=(MagickRealType) EvaluateMax((double) pixel,value); break; } case MeanEvaluateOperator: { result=(MagickRealType) (pixel+value); break; } case MedianEvaluateOperator: { result=(MagickRealType) (pixel+value); break; } case MinEvaluateOperator: { result=(MagickRealType) MagickMin((double) pixel,value); break; } case MultiplicativeNoiseEvaluateOperator: { result=(MagickRealType) GenerateDifferentialNoise(random_info,pixel, MultiplicativeGaussianNoise,value); break; } case MultiplyEvaluateOperator: { result=(MagickRealType) (value*pixel); break; } case OrEvaluateOperator: { result=(MagickRealType) ((ssize_t) pixel | (ssize_t) (value+0.5)); break; } case PoissonNoiseEvaluateOperator: { result=(MagickRealType) GenerateDifferentialNoise(random_info,pixel, PoissonNoise,value); break; } case PowEvaluateOperator: { result=(MagickRealType) (QuantumRange*pow((double) (QuantumScale*pixel), (double) value)); break; } case RightShiftEvaluateOperator: { result=(MagickRealType) ((ssize_t) pixel >> (ssize_t) (value+0.5)); break; } case RootMeanSquareEvaluateOperator: { result=(MagickRealType) (pixel*pixel+value); break; } case SetEvaluateOperator: { result=value; break; } case SineEvaluateOperator: { result=(MagickRealType) (QuantumRange*(0.5*sin((double) (2.0*MagickPI* QuantumScale*pixel*value))+0.5)); break; } case SubtractEvaluateOperator: { result=(MagickRealType) (pixel-value); break; } case SumEvaluateOperator: { result=(MagickRealType) (pixel+value); break; } case ThresholdEvaluateOperator: { result=(MagickRealType) (((MagickRealType) pixel <= value) ? 0 : QuantumRange); break; } case ThresholdBlackEvaluateOperator: { result=(MagickRealType) (((MagickRealType) pixel <= value) ? 0 : pixel); break; } case ThresholdWhiteEvaluateOperator: { result=(MagickRealType) (((MagickRealType) pixel > value) ? QuantumRange : pixel); break; } case UniformNoiseEvaluateOperator: { result=(MagickRealType) GenerateDifferentialNoise(random_info,pixel, UniformNoise,value); break; } case XorEvaluateOperator: { result=(MagickRealType) ((ssize_t) pixel ^ (ssize_t) (value+0.5)); break; } } return(result); }","{'deleted': [{'line_no': 37, 'char_start': 975, 'char_end': 1046, 'line': ' result=(MagickRealType) ((size_t) pixel & (size_t) (value+0.5));\n'}, {'line_no': 77, 'char_start': 2060, 'char_end': 2132, 'line': ' result=(MagickRealType) ((size_t) pixel << (size_t) (value+0.5));\n'}, {'line_no': 120, 'char_start': 3157, 'char_end': 3228, 'line': ' result=(MagickRealType) ((size_t) pixel | (size_t) (value+0.5));\n'}, {'line_no': 137, 'char_start': 3618, 'char_end': 3690, 'line': ' result=(MagickRealType) ((size_t) pixel >> (size_t) (value+0.5));\n'}, {'line_no': 191, 'char_start': 4948, 'char_end': 5019, 'line': ' result=(MagickRealType) ((size_t) pixel ^ (size_t) (value+0.5));\n'}], 'added': [{'line_no': 37, 'char_start': 975, 'char_end': 1048, 'line': ' result=(MagickRealType) ((ssize_t) pixel & (ssize_t) (value+0.5));\n'}, {'line_no': 77, 'char_start': 2062, 'char_end': 2136, 'line': ' result=(MagickRealType) ((ssize_t) pixel << (ssize_t) (value+0.5));\n'}, {'line_no': 120, 'char_start': 3161, 'char_end': 3234, 'line': ' result=(MagickRealType) ((ssize_t) pixel | (ssize_t) (value+0.5));\n'}, {'line_no': 137, 'char_start': 3624, 'char_end': 3698, 'line': ' result=(MagickRealType) ((ssize_t) pixel >> (ssize_t) (value+0.5));\n'}, {'line_no': 191, 'char_start': 4956, 'char_end': 5029, 'line': ' result=(MagickRealType) ((ssize_t) pixel ^ (ssize_t) (value+0.5));\n'}]}","{'deleted': [], 'added': [{'char_start': 1008, 'char_end': 1009, 'chars': 's'}, {'char_start': 1025, 'char_end': 1026, 'chars': 's'}, {'char_start': 2095, 'char_end': 2096, 'chars': 's'}, {'char_start': 2113, 'char_end': 2114, 'chars': 's'}, {'char_start': 3194, 'char_end': 3195, 'chars': 's'}, {'char_start': 3211, 'char_end': 3212, 'chars': 's'}, {'char_start': 3657, 'char_end': 3658, 'chars': 's'}, {'char_start': 3675, 'char_end': 3676, 'chars': 's'}, {'char_start': 4989, 'char_end': 4990, 'chars': 's'}, {'char_start': 5006, 'char_end': 5007, 'chars': 's'}]}",github.com/ImageMagick/ImageMagick6/commit/3e21bc8a58b4ae38d24c7e283837cc279f35b6a5,magick/statistic.c,cwe-190,1303 cwe-079,nav_path,"def nav_path(request): """"""Return current path as list of items with ""name"" and ""href"" members The href members are view_directory links for directories and view_log links for files, but are set to None when the link would point to the current view"""""" if not request.repos: return [] is_dir = request.pathtype == vclib.DIR # add root item items = [] root_item = _item(name=request.server.escape(request.repos.name), href=None) if request.path_parts or request.view_func is not view_directory: root_item.href = request.get_url(view_func=view_directory, where='', pathtype=vclib.DIR, params={}, escape=1) items.append(root_item) # add path part items path_parts = [] for part in request.path_parts: path_parts.append(part) is_last = len(path_parts) == len(request.path_parts) item = _item(name=part, href=None) if not is_last or (is_dir and request.view_func is not view_directory): item.href = request.get_url(view_func=view_directory, where=_path_join(path_parts), pathtype=vclib.DIR, params={}, escape=1) elif not is_dir and request.view_func is not view_log: item.href = request.get_url(view_func=view_log, where=_path_join(path_parts), pathtype=vclib.FILE, params={}, escape=1) items.append(item) return items","def nav_path(request): """"""Return current path as list of items with ""name"" and ""href"" members The href members are view_directory links for directories and view_log links for files, but are set to None when the link would point to the current view"""""" if not request.repos: return [] is_dir = request.pathtype == vclib.DIR # add root item items = [] root_item = _item(name=request.server.escape(request.repos.name), href=None) if request.path_parts or request.view_func is not view_directory: root_item.href = request.get_url(view_func=view_directory, where='', pathtype=vclib.DIR, params={}, escape=1) items.append(root_item) # add path part items path_parts = [] for part in request.path_parts: path_parts.append(part) is_last = len(path_parts) == len(request.path_parts) item = _item(name=request.server.escape(part), href=None) if not is_last or (is_dir and request.view_func is not view_directory): item.href = request.get_url(view_func=view_directory, where=_path_join(path_parts), pathtype=vclib.DIR, params={}, escape=1) elif not is_dir and request.view_func is not view_log: item.href = request.get_url(view_func=view_log, where=_path_join(path_parts), pathtype=vclib.FILE, params={}, escape=1) items.append(item) return items","{'deleted': [{'line_no': 28, 'char_start': 897, 'char_end': 936, 'line': ' item = _item(name=part, href=None)\n'}], 'added': [{'line_no': 28, 'char_start': 897, 'char_end': 959, 'line': ' item = _item(name=request.server.escape(part), href=None)\n'}]}","{'deleted': [], 'added': [{'char_start': 919, 'char_end': 941, 'chars': 'request.server.escape('}, {'char_start': 945, 'char_end': 946, 'chars': ')'}]}",github.com/viewvc/viewvc/commit/9dcfc7daa4c940992920d3b2fbd317da20e44aad,lib/viewvc.py,cwe-079,330 cwe-476,handle_client_startup,"static bool handle_client_startup(PgSocket *client, PktHdr *pkt) { const char *passwd; const uint8_t *key; bool ok; SBuf *sbuf = &client->sbuf; /* don't tolerate partial packets */ if (incomplete_pkt(pkt)) { disconnect_client(client, true, ""client sent partial pkt in startup phase""); return false; } if (client->wait_for_welcome) { if (finish_client_login(client)) { /* the packet was already parsed */ sbuf_prepare_skip(sbuf, pkt->len); return true; } else return false; } switch (pkt->type) { case PKT_SSLREQ: slog_noise(client, ""C: req SSL""); slog_noise(client, ""P: nak""); /* reject SSL attempt */ if (!sbuf_answer(&client->sbuf, ""N"", 1)) { disconnect_client(client, false, ""failed to nak SSL""); return false; } break; case PKT_STARTUP_V2: disconnect_client(client, true, ""Old V2 protocol not supported""); return false; case PKT_STARTUP: if (client->pool) { disconnect_client(client, true, ""client re-sent startup pkt""); return false; } if (!decide_startup_pool(client, pkt)) return false; if (client->pool->db->admin) { if (!admin_pre_login(client)) return false; } if (cf_auth_type <= AUTH_TRUST || client->own_user) { if (!finish_client_login(client)) return false; } else { if (!send_client_authreq(client)) { disconnect_client(client, false, ""failed to send auth req""); return false; } } break; case 'p': /* PasswordMessage */ /* haven't requested it */ if (cf_auth_type <= AUTH_TRUST) { disconnect_client(client, true, ""unrequested passwd pkt""); return false; } ok = mbuf_get_string(&pkt->data, &passwd); if (ok && check_client_passwd(client, passwd)) { if (!finish_client_login(client)) return false; } else { disconnect_client(client, true, ""Auth failed""); return false; } break; case PKT_CANCEL: if (mbuf_avail_for_read(&pkt->data) == BACKENDKEY_LEN && mbuf_get_bytes(&pkt->data, BACKENDKEY_LEN, &key)) { memcpy(client->cancel_key, key, BACKENDKEY_LEN); accept_cancel_request(client); } else disconnect_client(client, false, ""bad cancel request""); return false; default: disconnect_client(client, false, ""bad packet""); return false; } sbuf_prepare_skip(sbuf, pkt->len); client->request_time = get_cached_time(); return true; }","static bool handle_client_startup(PgSocket *client, PktHdr *pkt) { const char *passwd; const uint8_t *key; bool ok; SBuf *sbuf = &client->sbuf; /* don't tolerate partial packets */ if (incomplete_pkt(pkt)) { disconnect_client(client, true, ""client sent partial pkt in startup phase""); return false; } if (client->wait_for_welcome) { if (finish_client_login(client)) { /* the packet was already parsed */ sbuf_prepare_skip(sbuf, pkt->len); return true; } else return false; } switch (pkt->type) { case PKT_SSLREQ: slog_noise(client, ""C: req SSL""); slog_noise(client, ""P: nak""); /* reject SSL attempt */ if (!sbuf_answer(&client->sbuf, ""N"", 1)) { disconnect_client(client, false, ""failed to nak SSL""); return false; } break; case PKT_STARTUP_V2: disconnect_client(client, true, ""Old V2 protocol not supported""); return false; case PKT_STARTUP: if (client->pool) { disconnect_client(client, true, ""client re-sent startup pkt""); return false; } if (!decide_startup_pool(client, pkt)) return false; if (client->pool->db->admin) { if (!admin_pre_login(client)) return false; } if (cf_auth_type <= AUTH_TRUST || client->own_user) { if (!finish_client_login(client)) return false; } else { if (!send_client_authreq(client)) { disconnect_client(client, false, ""failed to send auth req""); return false; } } break; case 'p': /* PasswordMessage */ /* too early */ if (!client->auth_user) { disconnect_client(client, true, ""client password pkt before startup packet""); return false; } /* haven't requested it */ if (cf_auth_type <= AUTH_TRUST) { disconnect_client(client, true, ""unrequested passwd pkt""); return false; } ok = mbuf_get_string(&pkt->data, &passwd); if (ok && check_client_passwd(client, passwd)) { if (!finish_client_login(client)) return false; } else { disconnect_client(client, true, ""Auth failed""); return false; } break; case PKT_CANCEL: if (mbuf_avail_for_read(&pkt->data) == BACKENDKEY_LEN && mbuf_get_bytes(&pkt->data, BACKENDKEY_LEN, &key)) { memcpy(client->cancel_key, key, BACKENDKEY_LEN); accept_cancel_request(client); } else disconnect_client(client, false, ""bad cancel request""); return false; default: disconnect_client(client, false, ""bad packet""); return false; } sbuf_prepare_skip(sbuf, pkt->len); client->request_time = get_cached_time(); return true; }","{'deleted': [], 'added': [{'line_no': 63, 'char_start': 1457, 'char_end': 1475, 'line': '\t\t/* too early */\n'}, {'line_no': 64, 'char_start': 1475, 'char_end': 1503, 'line': '\t\tif (!client->auth_user) {\n'}, {'line_no': 65, 'char_start': 1503, 'char_end': 1584, 'line': '\t\t\tdisconnect_client(client, true, ""client password pkt before startup packet"");\n'}, {'line_no': 66, 'char_start': 1584, 'char_end': 1601, 'line': '\t\t\treturn false;\n'}, {'line_no': 67, 'char_start': 1601, 'char_end': 1605, 'line': '\t\t}\n'}, {'line_no': 68, 'char_start': 1605, 'char_end': 1606, 'line': '\n'}]}","{'deleted': [], 'added': [{'char_start': 1462, 'char_end': 1611, 'chars': 'too early */\n\t\tif (!client->auth_user) {\n\t\t\tdisconnect_client(client, true, ""client password pkt before startup packet"");\n\t\t\treturn false;\n\t\t}\n\n\t\t/* '}]}",github.com/pgbouncer/pgbouncer/commit/74d6e5f7de5ec736f71204b7b422af7380c19ac5,src/client.c,cwe-476,656 cwe-476,exprListAppendList,"static ExprList *exprListAppendList( Parse *pParse, /* Parsing context */ ExprList *pList, /* List to which to append. Might be NULL */ ExprList *pAppend, /* List of values to append. Might be NULL */ int bIntToNull ){ if( pAppend ){ int i; int nInit = pList ? pList->nExpr : 0; for(i=0; inExpr; i++){ Expr *pDup = sqlite3ExprDup(pParse->db, pAppend->a[i].pExpr, 0); if( bIntToNull && pDup && pDup->op==TK_INTEGER ){ pDup->op = TK_NULL; pDup->flags &= ~(EP_IntValue|EP_IsTrue|EP_IsFalse); } pList = sqlite3ExprListAppend(pParse, pList, pDup); if( pList ) pList->a[nInit+i].sortFlags = pAppend->a[i].sortFlags; } } return pList; }","static ExprList *exprListAppendList( Parse *pParse, /* Parsing context */ ExprList *pList, /* List to which to append. Might be NULL */ ExprList *pAppend, /* List of values to append. Might be NULL */ int bIntToNull ){ if( pAppend ){ int i; int nInit = pList ? pList->nExpr : 0; for(i=0; inExpr; i++){ Expr *pDup = sqlite3ExprDup(pParse->db, pAppend->a[i].pExpr, 0); assert( pDup==0 || !ExprHasProperty(pDup, EP_MemToken) ); if( bIntToNull && pDup && pDup->op==TK_INTEGER ){ pDup->op = TK_NULL; pDup->flags &= ~(EP_IntValue|EP_IsTrue|EP_IsFalse); pDup->u.zToken = 0; } pList = sqlite3ExprListAppend(pParse, pList, pDup); if( pList ) pList->a[nInit+i].sortFlags = pAppend->a[i].sortFlags; } } return pList; }","{'deleted': [], 'added': [{'line_no': 12, 'char_start': 426, 'char_end': 490, 'line': ' assert( pDup==0 || !ExprHasProperty(pDup, EP_MemToken) );\n'}, {'line_no': 16, 'char_start': 634, 'char_end': 662, 'line': ' pDup->u.zToken = 0;\n'}]}","{'deleted': [], 'added': [{'char_start': 432, 'char_end': 496, 'chars': 'assert( pDup==0 || !ExprHasProperty(pDup, EP_MemToken) );\n '}, {'char_start': 632, 'char_end': 660, 'chars': ';\n pDup->u.zToken = 0'}]}",github.com/sqlite/sqlite/commit/75e95e1fcd52d3ec8282edb75ac8cd0814095d54,src/window.c,cwe-476,238 cwe-787,cbs_jpeg_split_fragment,"static int cbs_jpeg_split_fragment(CodedBitstreamContext *ctx, CodedBitstreamFragment *frag, int header) { AVBufferRef *data_ref; uint8_t *data; size_t data_size; int unit, start, end, marker, next_start, next_marker; int err, i, j, length; if (frag->data_size < 4) { // Definitely too short to be meaningful. return AVERROR_INVALIDDATA; } for (i = 0; i + 1 < frag->data_size && frag->data[i] != 0xff; i++); if (i > 0) { av_log(ctx->log_ctx, AV_LOG_WARNING, ""Discarding %d bytes at "" ""beginning of image.\n"", i); } for (++i; i + 1 < frag->data_size && frag->data[i] == 0xff; i++); if (i + 1 >= frag->data_size && frag->data[i]) { av_log(ctx->log_ctx, AV_LOG_ERROR, ""Invalid JPEG image: "" ""no SOI marker found.\n""); return AVERROR_INVALIDDATA; } marker = frag->data[i]; if (marker != JPEG_MARKER_SOI) { av_log(ctx->log_ctx, AV_LOG_ERROR, ""Invalid JPEG image: first "" ""marker is %02x, should be SOI.\n"", marker); return AVERROR_INVALIDDATA; } for (++i; i + 1 < frag->data_size && frag->data[i] == 0xff; i++); if (i + 1 >= frag->data_size) { av_log(ctx->log_ctx, AV_LOG_ERROR, ""Invalid JPEG image: "" ""no image content found.\n""); return AVERROR_INVALIDDATA; } marker = frag->data[i]; start = i + 1; for (unit = 0;; unit++) { if (marker == JPEG_MARKER_EOI) { break; } else if (marker == JPEG_MARKER_SOS) { for (i = start; i + 1 < frag->data_size; i++) { if (frag->data[i] != 0xff) continue; end = i; for (++i; i + 1 < frag->data_size && frag->data[i] == 0xff; i++); if (i + 1 >= frag->data_size) { next_marker = -1; } else { if (frag->data[i] == 0x00) continue; next_marker = frag->data[i]; next_start = i + 1; } break; } } else { i = start; if (i + 2 > frag->data_size) { av_log(ctx->log_ctx, AV_LOG_ERROR, ""Invalid JPEG image: "" ""truncated at %02x marker.\n"", marker); return AVERROR_INVALIDDATA; } length = AV_RB16(frag->data + i); if (i + length > frag->data_size) { av_log(ctx->log_ctx, AV_LOG_ERROR, ""Invalid JPEG image: "" ""truncated at %02x marker segment.\n"", marker); return AVERROR_INVALIDDATA; } end = start + length; i = end; if (frag->data[i] != 0xff) { next_marker = -1; } else { for (++i; i + 1 < frag->data_size && frag->data[i] == 0xff; i++); if (i + 1 >= frag->data_size) { next_marker = -1; } else { next_marker = frag->data[i]; next_start = i + 1; } } } if (marker == JPEG_MARKER_SOS) { length = AV_RB16(frag->data + start); data_ref = NULL; data = av_malloc(end - start + AV_INPUT_BUFFER_PADDING_SIZE); if (!data) return AVERROR(ENOMEM); memcpy(data, frag->data + start, length); for (i = start + length, j = length; i < end; i++, j++) { if (frag->data[i] == 0xff) { while (frag->data[i] == 0xff) ++i; data[j] = 0xff; } else { data[j] = frag->data[i]; } } data_size = j; memset(data + data_size, 0, AV_INPUT_BUFFER_PADDING_SIZE); } else { data = frag->data + start; data_size = end - start; data_ref = frag->data_ref; } err = ff_cbs_insert_unit_data(ctx, frag, unit, marker, data, data_size, data_ref); if (err < 0) return err; if (next_marker == -1) break; marker = next_marker; start = next_start; } return 0; }","static int cbs_jpeg_split_fragment(CodedBitstreamContext *ctx, CodedBitstreamFragment *frag, int header) { AVBufferRef *data_ref; uint8_t *data; size_t data_size; int unit, start, end, marker, next_start, next_marker; int err, i, j, length; if (frag->data_size < 4) { // Definitely too short to be meaningful. return AVERROR_INVALIDDATA; } for (i = 0; i + 1 < frag->data_size && frag->data[i] != 0xff; i++); if (i > 0) { av_log(ctx->log_ctx, AV_LOG_WARNING, ""Discarding %d bytes at "" ""beginning of image.\n"", i); } for (++i; i + 1 < frag->data_size && frag->data[i] == 0xff; i++); if (i + 1 >= frag->data_size && frag->data[i]) { av_log(ctx->log_ctx, AV_LOG_ERROR, ""Invalid JPEG image: "" ""no SOI marker found.\n""); return AVERROR_INVALIDDATA; } marker = frag->data[i]; if (marker != JPEG_MARKER_SOI) { av_log(ctx->log_ctx, AV_LOG_ERROR, ""Invalid JPEG image: first "" ""marker is %02x, should be SOI.\n"", marker); return AVERROR_INVALIDDATA; } for (++i; i + 1 < frag->data_size && frag->data[i] == 0xff; i++); if (i + 1 >= frag->data_size) { av_log(ctx->log_ctx, AV_LOG_ERROR, ""Invalid JPEG image: "" ""no image content found.\n""); return AVERROR_INVALIDDATA; } marker = frag->data[i]; start = i + 1; for (unit = 0;; unit++) { if (marker == JPEG_MARKER_EOI) { break; } else if (marker == JPEG_MARKER_SOS) { for (i = start; i + 1 < frag->data_size; i++) { if (frag->data[i] != 0xff) continue; end = i; for (++i; i + 1 < frag->data_size && frag->data[i] == 0xff; i++); if (i + 1 >= frag->data_size) { next_marker = -1; } else { if (frag->data[i] == 0x00) continue; next_marker = frag->data[i]; next_start = i + 1; } break; } } else { i = start; if (i + 2 > frag->data_size) { av_log(ctx->log_ctx, AV_LOG_ERROR, ""Invalid JPEG image: "" ""truncated at %02x marker.\n"", marker); return AVERROR_INVALIDDATA; } length = AV_RB16(frag->data + i); if (i + length > frag->data_size) { av_log(ctx->log_ctx, AV_LOG_ERROR, ""Invalid JPEG image: "" ""truncated at %02x marker segment.\n"", marker); return AVERROR_INVALIDDATA; } end = start + length; i = end; if (frag->data[i] != 0xff) { next_marker = -1; } else { for (++i; i + 1 < frag->data_size && frag->data[i] == 0xff; i++); if (i + 1 >= frag->data_size) { next_marker = -1; } else { next_marker = frag->data[i]; next_start = i + 1; } } } if (marker == JPEG_MARKER_SOS) { length = AV_RB16(frag->data + start); if (length > end - start) return AVERROR_INVALIDDATA; data_ref = NULL; data = av_malloc(end - start + AV_INPUT_BUFFER_PADDING_SIZE); if (!data) return AVERROR(ENOMEM); memcpy(data, frag->data + start, length); for (i = start + length, j = length; i < end; i++, j++) { if (frag->data[i] == 0xff) { while (frag->data[i] == 0xff) ++i; data[j] = 0xff; } else { data[j] = frag->data[i]; } } data_size = j; memset(data + data_size, 0, AV_INPUT_BUFFER_PADDING_SIZE); } else { data = frag->data + start; data_size = end - start; data_ref = frag->data_ref; } err = ff_cbs_insert_unit_data(ctx, frag, unit, marker, data, data_size, data_ref); if (err < 0) return err; if (next_marker == -1) break; marker = next_marker; start = next_start; } return 0; }","{'deleted': [], 'added': [{'line_no': 95, 'char_start': 3398, 'char_end': 3436, 'line': ' if (length > end - start)\n'}, {'line_no': 96, 'char_start': 3436, 'char_end': 3480, 'line': ' return AVERROR_INVALIDDATA;\n'}, {'line_no': 97, 'char_start': 3480, 'char_end': 3481, 'line': '\n'}]}","{'deleted': [], 'added': [{'char_start': 3410, 'char_end': 3493, 'chars': 'if (length > end - start)\n return AVERROR_INVALIDDATA;\n\n '}]}",github.com/FFmpeg/FFmpeg/commit/1812352d767ccf5431aa440123e2e260a4db2726,libavcodec/cbs_jpeg.c,cwe-787,1126 cwe-078,_add_chapsecret_to_host," def _add_chapsecret_to_host(self, host_name): """"""Generate and store a randomly-generated CHAP secret for the host."""""" chap_secret = utils.generate_password() ssh_cmd = ('svctask chhost -chapsecret ""%(chap_secret)s"" %(host_name)s' % {'chap_secret': chap_secret, 'host_name': host_name}) out, err = self._run_ssh(ssh_cmd) # No output should be returned from chhost self._assert_ssh_return(len(out.strip()) == 0, '_add_chapsecret_to_host', ssh_cmd, out, err) return chap_secret"," def _add_chapsecret_to_host(self, host_name): """"""Generate and store a randomly-generated CHAP secret for the host."""""" chap_secret = utils.generate_password() ssh_cmd = ['svctask', 'chhost', '-chapsecret', chap_secret, host_name] out, err = self._run_ssh(ssh_cmd) # No output should be returned from chhost self._assert_ssh_return(len(out.strip()) == 0, '_add_chapsecret_to_host', ssh_cmd, out, err) return chap_secret","{'deleted': [{'line_no': 5, 'char_start': 179, 'char_end': 259, 'line': ' ssh_cmd = (\'svctask chhost -chapsecret ""%(chap_secret)s"" %(host_name)s\'\n'}, {'line_no': 6, 'char_start': 259, 'char_end': 334, 'line': "" % {'chap_secret': chap_secret, 'host_name': host_name})\n""}], 'added': [{'line_no': 5, 'char_start': 179, 'char_end': 258, 'line': "" ssh_cmd = ['svctask', 'chhost', '-chapsecret', chap_secret, host_name]\n""}]}","{'deleted': [{'char_start': 197, 'char_end': 198, 'chars': '('}, {'char_start': 206, 'char_end': 225, 'chars': ' chhost -chapsecret'}, {'char_start': 226, 'char_end': 229, 'chars': '""%('}, {'char_start': 231, 'char_end': 246, 'chars': 'ap_secret)s"" %('}, {'char_start': 250, 'char_end': 257, 'chars': '_name)s'}, {'char_start': 258, 'char_end': 279, 'chars': '\n %'}, {'char_start': 280, 'char_end': 281, 'chars': '{'}, {'char_start': 286, 'char_end': 287, 'chars': '_'}, {'char_start': 294, 'char_end': 295, 'chars': ':'}, {'char_start': 309, 'char_end': 310, 'chars': ""'""}, {'char_start': 319, 'char_end': 333, 'chars': ""': host_name})""}], 'added': [{'char_start': 197, 'char_end': 198, 'chars': '['}, {'char_start': 206, 'char_end': 208, 'chars': ""',""}, {'char_start': 209, 'char_end': 210, 'chars': ""'""}, {'char_start': 217, 'char_end': 218, 'chars': ','}, {'char_start': 220, 'char_end': 221, 'chars': '-'}, {'char_start': 232, 'char_end': 233, 'chars': ','}, {'char_start': 256, 'char_end': 257, 'chars': ']'}]}",github.com/thatsdone/cinder/commit/f752302d181583a95cf44354aea607ce9d9283f4,cinder/volume/drivers/storwize_svc.py,cwe-078,136 cwe-416,PHP_MINIT_FUNCTION,"PHP_MINIT_FUNCTION(spl_array) { REGISTER_SPL_STD_CLASS_EX(ArrayObject, spl_array_object_new, spl_funcs_ArrayObject); REGISTER_SPL_IMPLEMENTS(ArrayObject, Aggregate); REGISTER_SPL_IMPLEMENTS(ArrayObject, ArrayAccess); REGISTER_SPL_IMPLEMENTS(ArrayObject, Serializable); REGISTER_SPL_IMPLEMENTS(ArrayObject, Countable); memcpy(&spl_handler_ArrayObject, zend_get_std_object_handlers(), sizeof(zend_object_handlers)); spl_handler_ArrayObject.clone_obj = spl_array_object_clone; spl_handler_ArrayObject.read_dimension = spl_array_read_dimension; spl_handler_ArrayObject.write_dimension = spl_array_write_dimension; spl_handler_ArrayObject.unset_dimension = spl_array_unset_dimension; spl_handler_ArrayObject.has_dimension = spl_array_has_dimension; spl_handler_ArrayObject.count_elements = spl_array_object_count_elements; spl_handler_ArrayObject.get_properties = spl_array_get_properties; spl_handler_ArrayObject.get_debug_info = spl_array_get_debug_info; spl_handler_ArrayObject.get_gc = spl_array_get_gc; spl_handler_ArrayObject.read_property = spl_array_read_property; spl_handler_ArrayObject.write_property = spl_array_write_property; spl_handler_ArrayObject.get_property_ptr_ptr = spl_array_get_property_ptr_ptr; spl_handler_ArrayObject.has_property = spl_array_has_property; spl_handler_ArrayObject.unset_property = spl_array_unset_property; spl_handler_ArrayObject.compare_objects = spl_array_compare_objects; REGISTER_SPL_STD_CLASS_EX(ArrayIterator, spl_array_object_new, spl_funcs_ArrayIterator); REGISTER_SPL_IMPLEMENTS(ArrayIterator, Iterator); REGISTER_SPL_IMPLEMENTS(ArrayIterator, ArrayAccess); REGISTER_SPL_IMPLEMENTS(ArrayIterator, SeekableIterator); REGISTER_SPL_IMPLEMENTS(ArrayIterator, Serializable); REGISTER_SPL_IMPLEMENTS(ArrayIterator, Countable); memcpy(&spl_handler_ArrayIterator, &spl_handler_ArrayObject, sizeof(zend_object_handlers)); spl_ce_ArrayIterator->get_iterator = spl_array_get_iterator; REGISTER_SPL_SUB_CLASS_EX(RecursiveArrayIterator, ArrayIterator, spl_array_object_new, spl_funcs_RecursiveArrayIterator); REGISTER_SPL_IMPLEMENTS(RecursiveArrayIterator, RecursiveIterator); spl_ce_RecursiveArrayIterator->get_iterator = spl_array_get_iterator; REGISTER_SPL_CLASS_CONST_LONG(ArrayObject, ""STD_PROP_LIST"", SPL_ARRAY_STD_PROP_LIST); REGISTER_SPL_CLASS_CONST_LONG(ArrayObject, ""ARRAY_AS_PROPS"", SPL_ARRAY_ARRAY_AS_PROPS); REGISTER_SPL_CLASS_CONST_LONG(ArrayIterator, ""STD_PROP_LIST"", SPL_ARRAY_STD_PROP_LIST); REGISTER_SPL_CLASS_CONST_LONG(ArrayIterator, ""ARRAY_AS_PROPS"", SPL_ARRAY_ARRAY_AS_PROPS); REGISTER_SPL_CLASS_CONST_LONG(RecursiveArrayIterator, ""CHILD_ARRAYS_ONLY"", SPL_ARRAY_CHILD_ARRAYS_ONLY); return SUCCESS; }","PHP_MINIT_FUNCTION(spl_array) { REGISTER_SPL_STD_CLASS_EX(ArrayObject, spl_array_object_new, spl_funcs_ArrayObject); REGISTER_SPL_IMPLEMENTS(ArrayObject, Aggregate); REGISTER_SPL_IMPLEMENTS(ArrayObject, ArrayAccess); REGISTER_SPL_IMPLEMENTS(ArrayObject, Serializable); REGISTER_SPL_IMPLEMENTS(ArrayObject, Countable); memcpy(&spl_handler_ArrayObject, zend_get_std_object_handlers(), sizeof(zend_object_handlers)); spl_handler_ArrayObject.clone_obj = spl_array_object_clone; spl_handler_ArrayObject.read_dimension = spl_array_read_dimension; spl_handler_ArrayObject.write_dimension = spl_array_write_dimension; spl_handler_ArrayObject.unset_dimension = spl_array_unset_dimension; spl_handler_ArrayObject.has_dimension = spl_array_has_dimension; spl_handler_ArrayObject.count_elements = spl_array_object_count_elements; spl_handler_ArrayObject.get_properties = spl_array_get_properties; spl_handler_ArrayObject.get_debug_info = spl_array_get_debug_info; spl_handler_ArrayObject.get_gc = spl_array_get_gc; spl_handler_ArrayObject.read_property = spl_array_read_property; spl_handler_ArrayObject.write_property = spl_array_write_property; spl_handler_ArrayObject.get_property_ptr_ptr = spl_array_get_property_ptr_ptr; spl_handler_ArrayObject.has_property = spl_array_has_property; spl_handler_ArrayObject.unset_property = spl_array_unset_property; spl_handler_ArrayObject.compare_objects = spl_array_compare_objects; REGISTER_SPL_STD_CLASS_EX(ArrayIterator, spl_array_object_new, spl_funcs_ArrayIterator); REGISTER_SPL_IMPLEMENTS(ArrayIterator, Iterator); REGISTER_SPL_IMPLEMENTS(ArrayIterator, ArrayAccess); REGISTER_SPL_IMPLEMENTS(ArrayIterator, SeekableIterator); REGISTER_SPL_IMPLEMENTS(ArrayIterator, Serializable); REGISTER_SPL_IMPLEMENTS(ArrayIterator, Countable); memcpy(&spl_handler_ArrayIterator, &spl_handler_ArrayObject, sizeof(zend_object_handlers)); spl_ce_ArrayIterator->get_iterator = spl_array_get_iterator; REGISTER_SPL_SUB_CLASS_EX(RecursiveArrayIterator, ArrayIterator, spl_array_object_new, spl_funcs_RecursiveArrayIterator); REGISTER_SPL_IMPLEMENTS(RecursiveArrayIterator, RecursiveIterator); spl_ce_RecursiveArrayIterator->get_iterator = spl_array_get_iterator; REGISTER_SPL_CLASS_CONST_LONG(ArrayObject, ""STD_PROP_LIST"", SPL_ARRAY_STD_PROP_LIST); REGISTER_SPL_CLASS_CONST_LONG(ArrayObject, ""ARRAY_AS_PROPS"", SPL_ARRAY_ARRAY_AS_PROPS); REGISTER_SPL_CLASS_CONST_LONG(ArrayIterator, ""STD_PROP_LIST"", SPL_ARRAY_STD_PROP_LIST); REGISTER_SPL_CLASS_CONST_LONG(ArrayIterator, ""ARRAY_AS_PROPS"", SPL_ARRAY_ARRAY_AS_PROPS); REGISTER_SPL_CLASS_CONST_LONG(RecursiveArrayIterator, ""CHILD_ARRAYS_ONLY"", SPL_ARRAY_CHILD_ARRAYS_ONLY); return SUCCESS; }","{'deleted': [], 'added': [{'line_no': 19, 'char_start': 968, 'char_end': 1020, 'line': '\tspl_handler_ArrayObject.get_gc = spl_array_get_gc;\n'}]}","{'deleted': [], 'added': []}",github.com/php/php-src/commit/3f627e580acfdaf0595ae3b115b8bec677f203ee?w=1,ext/spl/spl_array.c,cwe-416,600 cwe-089,add_item," def add_item(self, item): """"""""Add new item."""""" if self.connection: self.cursor.execute('insert into item (name, shoppinglistid) values (""%s"", ""%s"")' % (item[0], item[1])) self.connection.commit()"," def add_item(self, item): """"""""Add new item."""""" if self.connection: t = (item[0], item[1], ) self.cursor.execute('insert into item (name, shoppinglistid) values (?, ?)', t) self.connection.commit()","{'deleted': [{'line_no': 4, 'char_start': 87, 'char_end': 203, 'line': ' self.cursor.execute(\'insert into item (name, shoppinglistid) values (""%s"", ""%s"")\' % (item[0], item[1]))\n'}], 'added': [{'line_no': 4, 'char_start': 87, 'char_end': 124, 'line': ' t = (item[0], item[1], )\n'}, {'line_no': 5, 'char_start': 124, 'char_end': 216, 'line': "" self.cursor.execute('insert into item (name, shoppinglistid) values (?, ?)', t)\n""}]}","{'deleted': [{'char_start': 168, 'char_end': 172, 'chars': '""%s""'}, {'char_start': 174, 'char_end': 178, 'chars': '""%s""'}, {'char_start': 180, 'char_end': 191, 'chars': ' % (item[0]'}, {'char_start': 193, 'char_end': 194, 'chars': 'i'}, {'char_start': 195, 'char_end': 201, 'chars': 'em[1])'}], 'added': [{'char_start': 99, 'char_end': 136, 'chars': 't = (item[0], item[1], )\n '}, {'char_start': 205, 'char_end': 206, 'chars': '?'}, {'char_start': 208, 'char_end': 209, 'chars': '?'}]}",github.com/ecosl-developers/ecosl/commit/8af050a513338bf68ff2a243e4a2482d24e9aa3a,ecosldb/ecosldb.py,cwe-089,58 cwe-416,SMB2_read,"SMB2_read(const unsigned int xid, struct cifs_io_parms *io_parms, unsigned int *nbytes, char **buf, int *buf_type) { struct smb_rqst rqst; int resp_buftype, rc = -EACCES; struct smb2_read_plain_req *req = NULL; struct smb2_read_rsp *rsp = NULL; struct kvec iov[1]; struct kvec rsp_iov; unsigned int total_len; int flags = CIFS_LOG_ERROR; struct cifs_ses *ses = io_parms->tcon->ses; *nbytes = 0; rc = smb2_new_read_req((void **)&req, &total_len, io_parms, NULL, 0, 0); if (rc) return rc; if (smb3_encryption_required(io_parms->tcon)) flags |= CIFS_TRANSFORM_REQ; iov[0].iov_base = (char *)req; iov[0].iov_len = total_len; memset(&rqst, 0, sizeof(struct smb_rqst)); rqst.rq_iov = iov; rqst.rq_nvec = 1; rc = cifs_send_recv(xid, ses, &rqst, &resp_buftype, flags, &rsp_iov); cifs_small_buf_release(req); rsp = (struct smb2_read_rsp *)rsp_iov.iov_base; if (rc) { if (rc != -ENODATA) { cifs_stats_fail_inc(io_parms->tcon, SMB2_READ_HE); cifs_dbg(VFS, ""Send error in read = %d\n"", rc); trace_smb3_read_err(xid, req->PersistentFileId, io_parms->tcon->tid, ses->Suid, io_parms->offset, io_parms->length, rc); } else trace_smb3_read_done(xid, req->PersistentFileId, io_parms->tcon->tid, ses->Suid, io_parms->offset, 0); free_rsp_buf(resp_buftype, rsp_iov.iov_base); return rc == -ENODATA ? 0 : rc; } else trace_smb3_read_done(xid, req->PersistentFileId, io_parms->tcon->tid, ses->Suid, io_parms->offset, io_parms->length); *nbytes = le32_to_cpu(rsp->DataLength); if ((*nbytes > CIFS_MAX_MSGSIZE) || (*nbytes > io_parms->length)) { cifs_dbg(FYI, ""bad length %d for count %d\n"", *nbytes, io_parms->length); rc = -EIO; *nbytes = 0; } if (*buf) { memcpy(*buf, (char *)rsp + rsp->DataOffset, *nbytes); free_rsp_buf(resp_buftype, rsp_iov.iov_base); } else if (resp_buftype != CIFS_NO_BUFFER) { *buf = rsp_iov.iov_base; if (resp_buftype == CIFS_SMALL_BUFFER) *buf_type = CIFS_SMALL_BUFFER; else if (resp_buftype == CIFS_LARGE_BUFFER) *buf_type = CIFS_LARGE_BUFFER; } return rc; }","SMB2_read(const unsigned int xid, struct cifs_io_parms *io_parms, unsigned int *nbytes, char **buf, int *buf_type) { struct smb_rqst rqst; int resp_buftype, rc = -EACCES; struct smb2_read_plain_req *req = NULL; struct smb2_read_rsp *rsp = NULL; struct kvec iov[1]; struct kvec rsp_iov; unsigned int total_len; int flags = CIFS_LOG_ERROR; struct cifs_ses *ses = io_parms->tcon->ses; *nbytes = 0; rc = smb2_new_read_req((void **)&req, &total_len, io_parms, NULL, 0, 0); if (rc) return rc; if (smb3_encryption_required(io_parms->tcon)) flags |= CIFS_TRANSFORM_REQ; iov[0].iov_base = (char *)req; iov[0].iov_len = total_len; memset(&rqst, 0, sizeof(struct smb_rqst)); rqst.rq_iov = iov; rqst.rq_nvec = 1; rc = cifs_send_recv(xid, ses, &rqst, &resp_buftype, flags, &rsp_iov); rsp = (struct smb2_read_rsp *)rsp_iov.iov_base; if (rc) { if (rc != -ENODATA) { cifs_stats_fail_inc(io_parms->tcon, SMB2_READ_HE); cifs_dbg(VFS, ""Send error in read = %d\n"", rc); trace_smb3_read_err(xid, req->PersistentFileId, io_parms->tcon->tid, ses->Suid, io_parms->offset, io_parms->length, rc); } else trace_smb3_read_done(xid, req->PersistentFileId, io_parms->tcon->tid, ses->Suid, io_parms->offset, 0); free_rsp_buf(resp_buftype, rsp_iov.iov_base); return rc == -ENODATA ? 0 : rc; } else trace_smb3_read_done(xid, req->PersistentFileId, io_parms->tcon->tid, ses->Suid, io_parms->offset, io_parms->length); cifs_small_buf_release(req); *nbytes = le32_to_cpu(rsp->DataLength); if ((*nbytes > CIFS_MAX_MSGSIZE) || (*nbytes > io_parms->length)) { cifs_dbg(FYI, ""bad length %d for count %d\n"", *nbytes, io_parms->length); rc = -EIO; *nbytes = 0; } if (*buf) { memcpy(*buf, (char *)rsp + rsp->DataOffset, *nbytes); free_rsp_buf(resp_buftype, rsp_iov.iov_base); } else if (resp_buftype != CIFS_NO_BUFFER) { *buf = rsp_iov.iov_base; if (resp_buftype == CIFS_SMALL_BUFFER) *buf_type = CIFS_SMALL_BUFFER; else if (resp_buftype == CIFS_LARGE_BUFFER) *buf_type = CIFS_LARGE_BUFFER; } return rc; }","{'deleted': [{'line_no': 30, 'char_start': 802, 'char_end': 832, 'line': '\tcifs_small_buf_release(req);\n'}, {'line_no': 31, 'char_start': 832, 'char_end': 833, 'line': '\n'}], 'added': [{'line_no': 51, 'char_start': 1501, 'char_end': 1531, 'line': '\tcifs_small_buf_release(req);\n'}, {'line_no': 52, 'char_start': 1531, 'char_end': 1532, 'line': '\n'}]}","{'deleted': [{'char_start': 803, 'char_end': 834, 'chars': 'cifs_small_buf_release(req);\n\n\t'}], 'added': [{'char_start': 1497, 'char_end': 1528, 'chars': ');\n\n\tcifs_small_buf_release(req'}]}",github.com/torvalds/linux/commit/088aaf17aa79300cab14dbee2569c58cfafd7d6e,fs/cifs/smb2pdu.c,cwe-416,717 cwe-125,mxf_parse_structural_metadata,"static int mxf_parse_structural_metadata(MXFContext *mxf) { MXFPackage *material_package = NULL; int i, j, k, ret; av_log(mxf->fc, AV_LOG_TRACE, ""metadata sets count %d\n"", mxf->metadata_sets_count); /* TODO: handle multiple material packages (OP3x) */ for (i = 0; i < mxf->packages_count; i++) { material_package = mxf_resolve_strong_ref(mxf, &mxf->packages_refs[i], MaterialPackage); if (material_package) break; } if (!material_package) { av_log(mxf->fc, AV_LOG_ERROR, ""no material package found\n""); return AVERROR_INVALIDDATA; } mxf_add_umid_metadata(&mxf->fc->metadata, ""material_package_umid"", material_package); if (material_package->name && material_package->name[0]) av_dict_set(&mxf->fc->metadata, ""material_package_name"", material_package->name, 0); mxf_parse_package_comments(mxf, &mxf->fc->metadata, material_package); for (i = 0; i < material_package->tracks_count; i++) { MXFPackage *source_package = NULL; MXFTrack *material_track = NULL; MXFTrack *source_track = NULL; MXFTrack *temp_track = NULL; MXFDescriptor *descriptor = NULL; MXFStructuralComponent *component = NULL; MXFTimecodeComponent *mxf_tc = NULL; UID *essence_container_ul = NULL; const MXFCodecUL *codec_ul = NULL; const MXFCodecUL *container_ul = NULL; const MXFCodecUL *pix_fmt_ul = NULL; AVStream *st; AVTimecode tc; int flags; if (!(material_track = mxf_resolve_strong_ref(mxf, &material_package->tracks_refs[i], Track))) { av_log(mxf->fc, AV_LOG_ERROR, ""could not resolve material track strong ref\n""); continue; } if ((component = mxf_resolve_strong_ref(mxf, &material_track->sequence_ref, TimecodeComponent))) { mxf_tc = (MXFTimecodeComponent*)component; flags = mxf_tc->drop_frame == 1 ? AV_TIMECODE_FLAG_DROPFRAME : 0; if (av_timecode_init(&tc, mxf_tc->rate, flags, mxf_tc->start_frame, mxf->fc) == 0) { mxf_add_timecode_metadata(&mxf->fc->metadata, ""timecode"", &tc); } } if (!(material_track->sequence = mxf_resolve_strong_ref(mxf, &material_track->sequence_ref, Sequence))) { av_log(mxf->fc, AV_LOG_ERROR, ""could not resolve material track sequence strong ref\n""); continue; } for (j = 0; j < material_track->sequence->structural_components_count; j++) { component = mxf_resolve_strong_ref(mxf, &material_track->sequence->structural_components_refs[j], TimecodeComponent); if (!component) continue; mxf_tc = (MXFTimecodeComponent*)component; flags = mxf_tc->drop_frame == 1 ? AV_TIMECODE_FLAG_DROPFRAME : 0; if (av_timecode_init(&tc, mxf_tc->rate, flags, mxf_tc->start_frame, mxf->fc) == 0) { mxf_add_timecode_metadata(&mxf->fc->metadata, ""timecode"", &tc); break; } } /* TODO: handle multiple source clips, only finds first valid source clip */ if(material_track->sequence->structural_components_count > 1) av_log(mxf->fc, AV_LOG_WARNING, ""material track %d: has %d components\n"", material_track->track_id, material_track->sequence->structural_components_count); for (j = 0; j < material_track->sequence->structural_components_count; j++) { component = mxf_resolve_sourceclip(mxf, &material_track->sequence->structural_components_refs[j]); if (!component) continue; source_package = mxf_resolve_source_package(mxf, component->source_package_ul, component->source_package_uid); if (!source_package) { av_log(mxf->fc, AV_LOG_TRACE, ""material track %d: no corresponding source package found\n"", material_track->track_id); continue; } for (k = 0; k < source_package->tracks_count; k++) { if (!(temp_track = mxf_resolve_strong_ref(mxf, &source_package->tracks_refs[k], Track))) { av_log(mxf->fc, AV_LOG_ERROR, ""could not resolve source track strong ref\n""); ret = AVERROR_INVALIDDATA; goto fail_and_free; } if (temp_track->track_id == component->source_track_id) { source_track = temp_track; break; } } if (!source_track) { av_log(mxf->fc, AV_LOG_ERROR, ""material track %d: no corresponding source track found\n"", material_track->track_id); break; } for (k = 0; k < mxf->essence_container_data_count; k++) { MXFEssenceContainerData *essence_data; if (!(essence_data = mxf_resolve_strong_ref(mxf, &mxf->essence_container_data_refs[k], EssenceContainerData))) { av_log(mxf, AV_LOG_TRACE, ""could not resolve essence container data strong ref\n""); continue; } if (!memcmp(component->source_package_ul, essence_data->package_ul, sizeof(UID)) && !memcmp(component->source_package_uid, essence_data->package_uid, sizeof(UID))) { source_track->body_sid = essence_data->body_sid; source_track->index_sid = essence_data->index_sid; break; } } if(source_track && component) break; } if (!source_track || !component || !source_package) { if((ret = mxf_add_metadata_stream(mxf, material_track))) goto fail_and_free; continue; } if (!(source_track->sequence = mxf_resolve_strong_ref(mxf, &source_track->sequence_ref, Sequence))) { av_log(mxf->fc, AV_LOG_ERROR, ""could not resolve source track sequence strong ref\n""); ret = AVERROR_INVALIDDATA; goto fail_and_free; } /* 0001GL00.MXF.A1.mxf_opatom.mxf has the same SourcePackageID as 0001GL.MXF.V1.mxf_opatom.mxf * This would result in both files appearing to have two streams. Work around this by sanity checking DataDefinition */ if (memcmp(material_track->sequence->data_definition_ul, source_track->sequence->data_definition_ul, 16)) { av_log(mxf->fc, AV_LOG_ERROR, ""material track %d: DataDefinition mismatch\n"", material_track->track_id); continue; } st = avformat_new_stream(mxf->fc, NULL); if (!st) { av_log(mxf->fc, AV_LOG_ERROR, ""could not allocate stream\n""); ret = AVERROR(ENOMEM); goto fail_and_free; } st->id = material_track->track_id; st->priv_data = source_track; source_package->descriptor = mxf_resolve_strong_ref(mxf, &source_package->descriptor_ref, AnyType); descriptor = mxf_resolve_multidescriptor(mxf, source_package->descriptor, source_track->track_id); /* A SourceClip from a EssenceGroup may only be a single frame of essence data. The clips duration is then how many * frames its suppose to repeat for. Descriptor->duration, if present, contains the real duration of the essence data */ if (descriptor && descriptor->duration != AV_NOPTS_VALUE) source_track->original_duration = st->duration = FFMIN(descriptor->duration, component->duration); else source_track->original_duration = st->duration = component->duration; if (st->duration == -1) st->duration = AV_NOPTS_VALUE; st->start_time = component->start_position; if (material_track->edit_rate.num <= 0 || material_track->edit_rate.den <= 0) { av_log(mxf->fc, AV_LOG_WARNING, ""Invalid edit rate (%d/%d) found on stream #%d, "" ""defaulting to 25/1\n"", material_track->edit_rate.num, material_track->edit_rate.den, st->index); material_track->edit_rate = (AVRational){25, 1}; } avpriv_set_pts_info(st, 64, material_track->edit_rate.den, material_track->edit_rate.num); /* ensure SourceTrack EditRate == MaterialTrack EditRate since only * the former is accessible via st->priv_data */ source_track->edit_rate = material_track->edit_rate; PRINT_KEY(mxf->fc, ""data definition ul"", source_track->sequence->data_definition_ul); codec_ul = mxf_get_codec_ul(ff_mxf_data_definition_uls, &source_track->sequence->data_definition_ul); st->codecpar->codec_type = codec_ul->id; if (!descriptor) { av_log(mxf->fc, AV_LOG_INFO, ""source track %d: stream %d, no descriptor found\n"", source_track->track_id, st->index); continue; } PRINT_KEY(mxf->fc, ""essence codec ul"", descriptor->essence_codec_ul); PRINT_KEY(mxf->fc, ""essence container ul"", descriptor->essence_container_ul); essence_container_ul = &descriptor->essence_container_ul; source_track->wrapping = (mxf->op == OPAtom) ? ClipWrapped : mxf_get_wrapping_kind(essence_container_ul); if (source_track->wrapping == UnknownWrapped) av_log(mxf->fc, AV_LOG_INFO, ""wrapping of stream %d is unknown\n"", st->index); /* HACK: replacing the original key with mxf_encrypted_essence_container * is not allowed according to s429-6, try to find correct information anyway */ if (IS_KLV_KEY(essence_container_ul, mxf_encrypted_essence_container)) { av_log(mxf->fc, AV_LOG_INFO, ""broken encrypted mxf file\n""); for (k = 0; k < mxf->metadata_sets_count; k++) { MXFMetadataSet *metadata = mxf->metadata_sets[k]; if (metadata->type == CryptoContext) { essence_container_ul = &((MXFCryptoContext *)metadata)->source_container_ul; break; } } } /* TODO: drop PictureEssenceCoding and SoundEssenceCompression, only check EssenceContainer */ codec_ul = mxf_get_codec_ul(ff_mxf_codec_uls, &descriptor->essence_codec_ul); st->codecpar->codec_id = (enum AVCodecID)codec_ul->id; if (st->codecpar->codec_id == AV_CODEC_ID_NONE) { codec_ul = mxf_get_codec_ul(ff_mxf_codec_uls, &descriptor->codec_ul); st->codecpar->codec_id = (enum AVCodecID)codec_ul->id; } av_log(mxf->fc, AV_LOG_VERBOSE, ""%s: Universal Label: "", avcodec_get_name(st->codecpar->codec_id)); for (k = 0; k < 16; k++) { av_log(mxf->fc, AV_LOG_VERBOSE, ""%.2x"", descriptor->essence_codec_ul[k]); if (!(k+1 & 19) || k == 5) av_log(mxf->fc, AV_LOG_VERBOSE, "".""); } av_log(mxf->fc, AV_LOG_VERBOSE, ""\n""); mxf_add_umid_metadata(&st->metadata, ""file_package_umid"", source_package); if (source_package->name && source_package->name[0]) av_dict_set(&st->metadata, ""file_package_name"", source_package->name, 0); if (material_track->name && material_track->name[0]) av_dict_set(&st->metadata, ""track_name"", material_track->name, 0); mxf_parse_physical_source_package(mxf, source_track, st); if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) { source_track->intra_only = mxf_is_intra_only(descriptor); container_ul = mxf_get_codec_ul(mxf_picture_essence_container_uls, essence_container_ul); if (st->codecpar->codec_id == AV_CODEC_ID_NONE) st->codecpar->codec_id = container_ul->id; st->codecpar->width = descriptor->width; st->codecpar->height = descriptor->height; /* Field height, not frame height */ switch (descriptor->frame_layout) { case FullFrame: st->codecpar->field_order = AV_FIELD_PROGRESSIVE; break; case OneField: /* Every other line is stored and needs to be duplicated. */ av_log(mxf->fc, AV_LOG_INFO, ""OneField frame layout isn't currently supported\n""); break; /* The correct thing to do here is fall through, but by breaking we might be able to decode some streams at half the vertical resolution, rather than not al all. It's also for compatibility with the old behavior. */ case MixedFields: break; case SegmentedFrame: st->codecpar->field_order = AV_FIELD_PROGRESSIVE; case SeparateFields: av_log(mxf->fc, AV_LOG_DEBUG, ""video_line_map: (%d, %d), field_dominance: %d\n"", descriptor->video_line_map[0], descriptor->video_line_map[1], descriptor->field_dominance); if ((descriptor->video_line_map[0] > 0) && (descriptor->video_line_map[1] > 0)) { /* Detect coded field order from VideoLineMap: * (even, even) => bottom field coded first * (even, odd) => top field coded first * (odd, even) => top field coded first * (odd, odd) => bottom field coded first */ if ((descriptor->video_line_map[0] + descriptor->video_line_map[1]) % 2) { switch (descriptor->field_dominance) { case MXF_FIELD_DOMINANCE_DEFAULT: case MXF_FIELD_DOMINANCE_FF: st->codecpar->field_order = AV_FIELD_TT; break; case MXF_FIELD_DOMINANCE_FL: st->codecpar->field_order = AV_FIELD_TB; break; default: avpriv_request_sample(mxf->fc, ""Field dominance %d support"", descriptor->field_dominance); } } else { switch (descriptor->field_dominance) { case MXF_FIELD_DOMINANCE_DEFAULT: case MXF_FIELD_DOMINANCE_FF: st->codecpar->field_order = AV_FIELD_BB; break; case MXF_FIELD_DOMINANCE_FL: st->codecpar->field_order = AV_FIELD_BT; break; default: avpriv_request_sample(mxf->fc, ""Field dominance %d support"", descriptor->field_dominance); } } } /* Turn field height into frame height. */ st->codecpar->height *= 2; break; default: av_log(mxf->fc, AV_LOG_INFO, ""Unknown frame layout type: %d\n"", descriptor->frame_layout); } if (st->codecpar->codec_id == AV_CODEC_ID_RAWVIDEO) { st->codecpar->format = descriptor->pix_fmt; if (st->codecpar->format == AV_PIX_FMT_NONE) { pix_fmt_ul = mxf_get_codec_ul(ff_mxf_pixel_format_uls, &descriptor->essence_codec_ul); st->codecpar->format = (enum AVPixelFormat)pix_fmt_ul->id; if (st->codecpar->format== AV_PIX_FMT_NONE) { st->codecpar->codec_tag = mxf_get_codec_ul(ff_mxf_codec_tag_uls, &descriptor->essence_codec_ul)->id; if (!st->codecpar->codec_tag) { /* support files created before RP224v10 by defaulting to UYVY422 if subsampling is 4:2:2 and component depth is 8-bit */ if (descriptor->horiz_subsampling == 2 && descriptor->vert_subsampling == 1 && descriptor->component_depth == 8) { st->codecpar->format = AV_PIX_FMT_UYVY422; } } } } } st->need_parsing = AVSTREAM_PARSE_HEADERS; if (material_track->sequence->origin) { av_dict_set_int(&st->metadata, ""material_track_origin"", material_track->sequence->origin, 0); } if (source_track->sequence->origin) { av_dict_set_int(&st->metadata, ""source_track_origin"", source_track->sequence->origin, 0); } if (descriptor->aspect_ratio.num && descriptor->aspect_ratio.den) st->display_aspect_ratio = descriptor->aspect_ratio; } else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) { container_ul = mxf_get_codec_ul(mxf_sound_essence_container_uls, essence_container_ul); /* Only overwrite existing codec ID if it is unset or A-law, which is the default according to SMPTE RP 224. */ if (st->codecpar->codec_id == AV_CODEC_ID_NONE || (st->codecpar->codec_id == AV_CODEC_ID_PCM_ALAW && (enum AVCodecID)container_ul->id != AV_CODEC_ID_NONE)) st->codecpar->codec_id = (enum AVCodecID)container_ul->id; st->codecpar->channels = descriptor->channels; st->codecpar->bits_per_coded_sample = descriptor->bits_per_sample; if (descriptor->sample_rate.den > 0) { st->codecpar->sample_rate = descriptor->sample_rate.num / descriptor->sample_rate.den; avpriv_set_pts_info(st, 64, descriptor->sample_rate.den, descriptor->sample_rate.num); } else { av_log(mxf->fc, AV_LOG_WARNING, ""invalid sample rate (%d/%d) "" ""found for stream #%d, time base forced to 1/48000\n"", descriptor->sample_rate.num, descriptor->sample_rate.den, st->index); avpriv_set_pts_info(st, 64, 1, 48000); } /* if duration is set, rescale it from EditRate to SampleRate */ if (st->duration != AV_NOPTS_VALUE) st->duration = av_rescale_q(st->duration, av_inv_q(material_track->edit_rate), st->time_base); /* TODO: implement AV_CODEC_ID_RAWAUDIO */ if (st->codecpar->codec_id == AV_CODEC_ID_PCM_S16LE) { if (descriptor->bits_per_sample > 16 && descriptor->bits_per_sample <= 24) st->codecpar->codec_id = AV_CODEC_ID_PCM_S24LE; else if (descriptor->bits_per_sample == 32) st->codecpar->codec_id = AV_CODEC_ID_PCM_S32LE; } else if (st->codecpar->codec_id == AV_CODEC_ID_PCM_S16BE) { if (descriptor->bits_per_sample > 16 && descriptor->bits_per_sample <= 24) st->codecpar->codec_id = AV_CODEC_ID_PCM_S24BE; else if (descriptor->bits_per_sample == 32) st->codecpar->codec_id = AV_CODEC_ID_PCM_S32BE; } else if (st->codecpar->codec_id == AV_CODEC_ID_MP2) { st->need_parsing = AVSTREAM_PARSE_FULL; } } else if (st->codecpar->codec_type == AVMEDIA_TYPE_DATA) { enum AVMediaType type; container_ul = mxf_get_codec_ul(mxf_data_essence_container_uls, essence_container_ul); if (st->codecpar->codec_id == AV_CODEC_ID_NONE) st->codecpar->codec_id = container_ul->id; type = avcodec_get_type(st->codecpar->codec_id); if (type == AVMEDIA_TYPE_SUBTITLE) st->codecpar->codec_type = type; if (container_ul->desc) av_dict_set(&st->metadata, ""data_type"", container_ul->desc, 0); } if (descriptor->extradata) { if (!ff_alloc_extradata(st->codecpar, descriptor->extradata_size)) { memcpy(st->codecpar->extradata, descriptor->extradata, descriptor->extradata_size); } } else if (st->codecpar->codec_id == AV_CODEC_ID_H264) { int coded_width = mxf_get_codec_ul(mxf_intra_only_picture_coded_width, &descriptor->essence_codec_ul)->id; if (coded_width) st->codecpar->width = coded_width; ret = ff_generate_avci_extradata(st); if (ret < 0) return ret; } if (st->codecpar->codec_type != AVMEDIA_TYPE_DATA && source_track->wrapping != FrameWrapped) { /* TODO: decode timestamps */ st->need_parsing = AVSTREAM_PARSE_TIMESTAMPS; } } ret = 0; fail_and_free: return ret; }","static int mxf_parse_structural_metadata(MXFContext *mxf) { MXFPackage *material_package = NULL; int i, j, k, ret; av_log(mxf->fc, AV_LOG_TRACE, ""metadata sets count %d\n"", mxf->metadata_sets_count); /* TODO: handle multiple material packages (OP3x) */ for (i = 0; i < mxf->packages_count; i++) { material_package = mxf_resolve_strong_ref(mxf, &mxf->packages_refs[i], MaterialPackage); if (material_package) break; } if (!material_package) { av_log(mxf->fc, AV_LOG_ERROR, ""no material package found\n""); return AVERROR_INVALIDDATA; } mxf_add_umid_metadata(&mxf->fc->metadata, ""material_package_umid"", material_package); if (material_package->name && material_package->name[0]) av_dict_set(&mxf->fc->metadata, ""material_package_name"", material_package->name, 0); mxf_parse_package_comments(mxf, &mxf->fc->metadata, material_package); for (i = 0; i < material_package->tracks_count; i++) { MXFPackage *source_package = NULL; MXFTrack *material_track = NULL; MXFTrack *source_track = NULL; MXFTrack *temp_track = NULL; MXFDescriptor *descriptor = NULL; MXFStructuralComponent *component = NULL; MXFTimecodeComponent *mxf_tc = NULL; UID *essence_container_ul = NULL; const MXFCodecUL *codec_ul = NULL; const MXFCodecUL *container_ul = NULL; const MXFCodecUL *pix_fmt_ul = NULL; AVStream *st; AVTimecode tc; int flags; if (!(material_track = mxf_resolve_strong_ref(mxf, &material_package->tracks_refs[i], Track))) { av_log(mxf->fc, AV_LOG_ERROR, ""could not resolve material track strong ref\n""); continue; } if ((component = mxf_resolve_strong_ref(mxf, &material_track->sequence_ref, TimecodeComponent))) { mxf_tc = (MXFTimecodeComponent*)component; flags = mxf_tc->drop_frame == 1 ? AV_TIMECODE_FLAG_DROPFRAME : 0; if (av_timecode_init(&tc, mxf_tc->rate, flags, mxf_tc->start_frame, mxf->fc) == 0) { mxf_add_timecode_metadata(&mxf->fc->metadata, ""timecode"", &tc); } } if (!(material_track->sequence = mxf_resolve_strong_ref(mxf, &material_track->sequence_ref, Sequence))) { av_log(mxf->fc, AV_LOG_ERROR, ""could not resolve material track sequence strong ref\n""); continue; } for (j = 0; j < material_track->sequence->structural_components_count; j++) { component = mxf_resolve_strong_ref(mxf, &material_track->sequence->structural_components_refs[j], TimecodeComponent); if (!component) continue; mxf_tc = (MXFTimecodeComponent*)component; flags = mxf_tc->drop_frame == 1 ? AV_TIMECODE_FLAG_DROPFRAME : 0; if (av_timecode_init(&tc, mxf_tc->rate, flags, mxf_tc->start_frame, mxf->fc) == 0) { mxf_add_timecode_metadata(&mxf->fc->metadata, ""timecode"", &tc); break; } } /* TODO: handle multiple source clips, only finds first valid source clip */ if(material_track->sequence->structural_components_count > 1) av_log(mxf->fc, AV_LOG_WARNING, ""material track %d: has %d components\n"", material_track->track_id, material_track->sequence->structural_components_count); for (j = 0; j < material_track->sequence->structural_components_count; j++) { component = mxf_resolve_sourceclip(mxf, &material_track->sequence->structural_components_refs[j]); if (!component) continue; source_package = mxf_resolve_source_package(mxf, component->source_package_ul, component->source_package_uid); if (!source_package) { av_log(mxf->fc, AV_LOG_TRACE, ""material track %d: no corresponding source package found\n"", material_track->track_id); continue; } for (k = 0; k < source_package->tracks_count; k++) { if (!(temp_track = mxf_resolve_strong_ref(mxf, &source_package->tracks_refs[k], Track))) { av_log(mxf->fc, AV_LOG_ERROR, ""could not resolve source track strong ref\n""); ret = AVERROR_INVALIDDATA; goto fail_and_free; } if (temp_track->track_id == component->source_track_id) { source_track = temp_track; break; } } if (!source_track) { av_log(mxf->fc, AV_LOG_ERROR, ""material track %d: no corresponding source track found\n"", material_track->track_id); break; } for (k = 0; k < mxf->essence_container_data_count; k++) { MXFEssenceContainerData *essence_data; if (!(essence_data = mxf_resolve_strong_ref(mxf, &mxf->essence_container_data_refs[k], EssenceContainerData))) { av_log(mxf->fc, AV_LOG_TRACE, ""could not resolve essence container data strong ref\n""); continue; } if (!memcmp(component->source_package_ul, essence_data->package_ul, sizeof(UID)) && !memcmp(component->source_package_uid, essence_data->package_uid, sizeof(UID))) { source_track->body_sid = essence_data->body_sid; source_track->index_sid = essence_data->index_sid; break; } } if(source_track && component) break; } if (!source_track || !component || !source_package) { if((ret = mxf_add_metadata_stream(mxf, material_track))) goto fail_and_free; continue; } if (!(source_track->sequence = mxf_resolve_strong_ref(mxf, &source_track->sequence_ref, Sequence))) { av_log(mxf->fc, AV_LOG_ERROR, ""could not resolve source track sequence strong ref\n""); ret = AVERROR_INVALIDDATA; goto fail_and_free; } /* 0001GL00.MXF.A1.mxf_opatom.mxf has the same SourcePackageID as 0001GL.MXF.V1.mxf_opatom.mxf * This would result in both files appearing to have two streams. Work around this by sanity checking DataDefinition */ if (memcmp(material_track->sequence->data_definition_ul, source_track->sequence->data_definition_ul, 16)) { av_log(mxf->fc, AV_LOG_ERROR, ""material track %d: DataDefinition mismatch\n"", material_track->track_id); continue; } st = avformat_new_stream(mxf->fc, NULL); if (!st) { av_log(mxf->fc, AV_LOG_ERROR, ""could not allocate stream\n""); ret = AVERROR(ENOMEM); goto fail_and_free; } st->id = material_track->track_id; st->priv_data = source_track; source_package->descriptor = mxf_resolve_strong_ref(mxf, &source_package->descriptor_ref, AnyType); descriptor = mxf_resolve_multidescriptor(mxf, source_package->descriptor, source_track->track_id); /* A SourceClip from a EssenceGroup may only be a single frame of essence data. The clips duration is then how many * frames its suppose to repeat for. Descriptor->duration, if present, contains the real duration of the essence data */ if (descriptor && descriptor->duration != AV_NOPTS_VALUE) source_track->original_duration = st->duration = FFMIN(descriptor->duration, component->duration); else source_track->original_duration = st->duration = component->duration; if (st->duration == -1) st->duration = AV_NOPTS_VALUE; st->start_time = component->start_position; if (material_track->edit_rate.num <= 0 || material_track->edit_rate.den <= 0) { av_log(mxf->fc, AV_LOG_WARNING, ""Invalid edit rate (%d/%d) found on stream #%d, "" ""defaulting to 25/1\n"", material_track->edit_rate.num, material_track->edit_rate.den, st->index); material_track->edit_rate = (AVRational){25, 1}; } avpriv_set_pts_info(st, 64, material_track->edit_rate.den, material_track->edit_rate.num); /* ensure SourceTrack EditRate == MaterialTrack EditRate since only * the former is accessible via st->priv_data */ source_track->edit_rate = material_track->edit_rate; PRINT_KEY(mxf->fc, ""data definition ul"", source_track->sequence->data_definition_ul); codec_ul = mxf_get_codec_ul(ff_mxf_data_definition_uls, &source_track->sequence->data_definition_ul); st->codecpar->codec_type = codec_ul->id; if (!descriptor) { av_log(mxf->fc, AV_LOG_INFO, ""source track %d: stream %d, no descriptor found\n"", source_track->track_id, st->index); continue; } PRINT_KEY(mxf->fc, ""essence codec ul"", descriptor->essence_codec_ul); PRINT_KEY(mxf->fc, ""essence container ul"", descriptor->essence_container_ul); essence_container_ul = &descriptor->essence_container_ul; source_track->wrapping = (mxf->op == OPAtom) ? ClipWrapped : mxf_get_wrapping_kind(essence_container_ul); if (source_track->wrapping == UnknownWrapped) av_log(mxf->fc, AV_LOG_INFO, ""wrapping of stream %d is unknown\n"", st->index); /* HACK: replacing the original key with mxf_encrypted_essence_container * is not allowed according to s429-6, try to find correct information anyway */ if (IS_KLV_KEY(essence_container_ul, mxf_encrypted_essence_container)) { av_log(mxf->fc, AV_LOG_INFO, ""broken encrypted mxf file\n""); for (k = 0; k < mxf->metadata_sets_count; k++) { MXFMetadataSet *metadata = mxf->metadata_sets[k]; if (metadata->type == CryptoContext) { essence_container_ul = &((MXFCryptoContext *)metadata)->source_container_ul; break; } } } /* TODO: drop PictureEssenceCoding and SoundEssenceCompression, only check EssenceContainer */ codec_ul = mxf_get_codec_ul(ff_mxf_codec_uls, &descriptor->essence_codec_ul); st->codecpar->codec_id = (enum AVCodecID)codec_ul->id; if (st->codecpar->codec_id == AV_CODEC_ID_NONE) { codec_ul = mxf_get_codec_ul(ff_mxf_codec_uls, &descriptor->codec_ul); st->codecpar->codec_id = (enum AVCodecID)codec_ul->id; } av_log(mxf->fc, AV_LOG_VERBOSE, ""%s: Universal Label: "", avcodec_get_name(st->codecpar->codec_id)); for (k = 0; k < 16; k++) { av_log(mxf->fc, AV_LOG_VERBOSE, ""%.2x"", descriptor->essence_codec_ul[k]); if (!(k+1 & 19) || k == 5) av_log(mxf->fc, AV_LOG_VERBOSE, "".""); } av_log(mxf->fc, AV_LOG_VERBOSE, ""\n""); mxf_add_umid_metadata(&st->metadata, ""file_package_umid"", source_package); if (source_package->name && source_package->name[0]) av_dict_set(&st->metadata, ""file_package_name"", source_package->name, 0); if (material_track->name && material_track->name[0]) av_dict_set(&st->metadata, ""track_name"", material_track->name, 0); mxf_parse_physical_source_package(mxf, source_track, st); if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) { source_track->intra_only = mxf_is_intra_only(descriptor); container_ul = mxf_get_codec_ul(mxf_picture_essence_container_uls, essence_container_ul); if (st->codecpar->codec_id == AV_CODEC_ID_NONE) st->codecpar->codec_id = container_ul->id; st->codecpar->width = descriptor->width; st->codecpar->height = descriptor->height; /* Field height, not frame height */ switch (descriptor->frame_layout) { case FullFrame: st->codecpar->field_order = AV_FIELD_PROGRESSIVE; break; case OneField: /* Every other line is stored and needs to be duplicated. */ av_log(mxf->fc, AV_LOG_INFO, ""OneField frame layout isn't currently supported\n""); break; /* The correct thing to do here is fall through, but by breaking we might be able to decode some streams at half the vertical resolution, rather than not al all. It's also for compatibility with the old behavior. */ case MixedFields: break; case SegmentedFrame: st->codecpar->field_order = AV_FIELD_PROGRESSIVE; case SeparateFields: av_log(mxf->fc, AV_LOG_DEBUG, ""video_line_map: (%d, %d), field_dominance: %d\n"", descriptor->video_line_map[0], descriptor->video_line_map[1], descriptor->field_dominance); if ((descriptor->video_line_map[0] > 0) && (descriptor->video_line_map[1] > 0)) { /* Detect coded field order from VideoLineMap: * (even, even) => bottom field coded first * (even, odd) => top field coded first * (odd, even) => top field coded first * (odd, odd) => bottom field coded first */ if ((descriptor->video_line_map[0] + descriptor->video_line_map[1]) % 2) { switch (descriptor->field_dominance) { case MXF_FIELD_DOMINANCE_DEFAULT: case MXF_FIELD_DOMINANCE_FF: st->codecpar->field_order = AV_FIELD_TT; break; case MXF_FIELD_DOMINANCE_FL: st->codecpar->field_order = AV_FIELD_TB; break; default: avpriv_request_sample(mxf->fc, ""Field dominance %d support"", descriptor->field_dominance); } } else { switch (descriptor->field_dominance) { case MXF_FIELD_DOMINANCE_DEFAULT: case MXF_FIELD_DOMINANCE_FF: st->codecpar->field_order = AV_FIELD_BB; break; case MXF_FIELD_DOMINANCE_FL: st->codecpar->field_order = AV_FIELD_BT; break; default: avpriv_request_sample(mxf->fc, ""Field dominance %d support"", descriptor->field_dominance); } } } /* Turn field height into frame height. */ st->codecpar->height *= 2; break; default: av_log(mxf->fc, AV_LOG_INFO, ""Unknown frame layout type: %d\n"", descriptor->frame_layout); } if (st->codecpar->codec_id == AV_CODEC_ID_RAWVIDEO) { st->codecpar->format = descriptor->pix_fmt; if (st->codecpar->format == AV_PIX_FMT_NONE) { pix_fmt_ul = mxf_get_codec_ul(ff_mxf_pixel_format_uls, &descriptor->essence_codec_ul); st->codecpar->format = (enum AVPixelFormat)pix_fmt_ul->id; if (st->codecpar->format== AV_PIX_FMT_NONE) { st->codecpar->codec_tag = mxf_get_codec_ul(ff_mxf_codec_tag_uls, &descriptor->essence_codec_ul)->id; if (!st->codecpar->codec_tag) { /* support files created before RP224v10 by defaulting to UYVY422 if subsampling is 4:2:2 and component depth is 8-bit */ if (descriptor->horiz_subsampling == 2 && descriptor->vert_subsampling == 1 && descriptor->component_depth == 8) { st->codecpar->format = AV_PIX_FMT_UYVY422; } } } } } st->need_parsing = AVSTREAM_PARSE_HEADERS; if (material_track->sequence->origin) { av_dict_set_int(&st->metadata, ""material_track_origin"", material_track->sequence->origin, 0); } if (source_track->sequence->origin) { av_dict_set_int(&st->metadata, ""source_track_origin"", source_track->sequence->origin, 0); } if (descriptor->aspect_ratio.num && descriptor->aspect_ratio.den) st->display_aspect_ratio = descriptor->aspect_ratio; } else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) { container_ul = mxf_get_codec_ul(mxf_sound_essence_container_uls, essence_container_ul); /* Only overwrite existing codec ID if it is unset or A-law, which is the default according to SMPTE RP 224. */ if (st->codecpar->codec_id == AV_CODEC_ID_NONE || (st->codecpar->codec_id == AV_CODEC_ID_PCM_ALAW && (enum AVCodecID)container_ul->id != AV_CODEC_ID_NONE)) st->codecpar->codec_id = (enum AVCodecID)container_ul->id; st->codecpar->channels = descriptor->channels; st->codecpar->bits_per_coded_sample = descriptor->bits_per_sample; if (descriptor->sample_rate.den > 0) { st->codecpar->sample_rate = descriptor->sample_rate.num / descriptor->sample_rate.den; avpriv_set_pts_info(st, 64, descriptor->sample_rate.den, descriptor->sample_rate.num); } else { av_log(mxf->fc, AV_LOG_WARNING, ""invalid sample rate (%d/%d) "" ""found for stream #%d, time base forced to 1/48000\n"", descriptor->sample_rate.num, descriptor->sample_rate.den, st->index); avpriv_set_pts_info(st, 64, 1, 48000); } /* if duration is set, rescale it from EditRate to SampleRate */ if (st->duration != AV_NOPTS_VALUE) st->duration = av_rescale_q(st->duration, av_inv_q(material_track->edit_rate), st->time_base); /* TODO: implement AV_CODEC_ID_RAWAUDIO */ if (st->codecpar->codec_id == AV_CODEC_ID_PCM_S16LE) { if (descriptor->bits_per_sample > 16 && descriptor->bits_per_sample <= 24) st->codecpar->codec_id = AV_CODEC_ID_PCM_S24LE; else if (descriptor->bits_per_sample == 32) st->codecpar->codec_id = AV_CODEC_ID_PCM_S32LE; } else if (st->codecpar->codec_id == AV_CODEC_ID_PCM_S16BE) { if (descriptor->bits_per_sample > 16 && descriptor->bits_per_sample <= 24) st->codecpar->codec_id = AV_CODEC_ID_PCM_S24BE; else if (descriptor->bits_per_sample == 32) st->codecpar->codec_id = AV_CODEC_ID_PCM_S32BE; } else if (st->codecpar->codec_id == AV_CODEC_ID_MP2) { st->need_parsing = AVSTREAM_PARSE_FULL; } } else if (st->codecpar->codec_type == AVMEDIA_TYPE_DATA) { enum AVMediaType type; container_ul = mxf_get_codec_ul(mxf_data_essence_container_uls, essence_container_ul); if (st->codecpar->codec_id == AV_CODEC_ID_NONE) st->codecpar->codec_id = container_ul->id; type = avcodec_get_type(st->codecpar->codec_id); if (type == AVMEDIA_TYPE_SUBTITLE) st->codecpar->codec_type = type; if (container_ul->desc) av_dict_set(&st->metadata, ""data_type"", container_ul->desc, 0); } if (descriptor->extradata) { if (!ff_alloc_extradata(st->codecpar, descriptor->extradata_size)) { memcpy(st->codecpar->extradata, descriptor->extradata, descriptor->extradata_size); } } else if (st->codecpar->codec_id == AV_CODEC_ID_H264) { int coded_width = mxf_get_codec_ul(mxf_intra_only_picture_coded_width, &descriptor->essence_codec_ul)->id; if (coded_width) st->codecpar->width = coded_width; ret = ff_generate_avci_extradata(st); if (ret < 0) return ret; } if (st->codecpar->codec_type != AVMEDIA_TYPE_DATA && source_track->wrapping != FrameWrapped) { /* TODO: decode timestamps */ st->need_parsing = AVSTREAM_PARSE_TIMESTAMPS; } } ret = 0; fail_and_free: return ret; }","{'deleted': [{'line_no': 104, 'char_start': 5013, 'char_end': 5117, 'line': ' av_log(mxf, AV_LOG_TRACE, ""could not resolve essence container data strong ref\\n"");\n'}], 'added': [{'line_no': 104, 'char_start': 5013, 'char_end': 5121, 'line': ' av_log(mxf->fc, AV_LOG_TRACE, ""could not resolve essence container data strong ref\\n"");\n'}]}","{'deleted': [], 'added': [{'char_start': 5043, 'char_end': 5047, 'chars': '->fc'}]}",github.com/FFmpeg/FFmpeg/commit/bab0716c7f4793ec42e05a5aa7e80d82a0dd4e75,libavformat/mxfdec.c,cwe-125,4817 cwe-416,blk_rq_map_user_iov,"int blk_rq_map_user_iov(struct request_queue *q, struct request *rq, struct rq_map_data *map_data, const struct iov_iter *iter, gfp_t gfp_mask) { bool copy = false; unsigned long align = q->dma_pad_mask | queue_dma_alignment(q); struct bio *bio = NULL; struct iov_iter i; int ret; if (map_data) copy = true; else if (iov_iter_alignment(iter) & align) copy = true; else if (queue_virt_boundary(q)) copy = queue_virt_boundary(q) & iov_iter_gap_alignment(iter); i = *iter; do { ret =__blk_rq_map_user_iov(rq, map_data, &i, gfp_mask, copy); if (ret) goto unmap_rq; if (!bio) bio = rq->bio; } while (iov_iter_count(&i)); if (!bio_flagged(bio, BIO_USER_MAPPED)) rq->cmd_flags |= REQ_COPY_USER; return 0; unmap_rq: __blk_rq_unmap_user(bio); rq->bio = NULL; return -EINVAL; }","int blk_rq_map_user_iov(struct request_queue *q, struct request *rq, struct rq_map_data *map_data, const struct iov_iter *iter, gfp_t gfp_mask) { bool copy = false; unsigned long align = q->dma_pad_mask | queue_dma_alignment(q); struct bio *bio = NULL; struct iov_iter i; int ret; if (!iter_is_iovec(iter)) goto fail; if (map_data) copy = true; else if (iov_iter_alignment(iter) & align) copy = true; else if (queue_virt_boundary(q)) copy = queue_virt_boundary(q) & iov_iter_gap_alignment(iter); i = *iter; do { ret =__blk_rq_map_user_iov(rq, map_data, &i, gfp_mask, copy); if (ret) goto unmap_rq; if (!bio) bio = rq->bio; } while (iov_iter_count(&i)); if (!bio_flagged(bio, BIO_USER_MAPPED)) rq->cmd_flags |= REQ_COPY_USER; return 0; unmap_rq: __blk_rq_unmap_user(bio); fail: rq->bio = NULL; return -EINVAL; }","{'deleted': [], 'added': [{'line_no': 11, 'char_start': 293, 'char_end': 320, 'line': '\tif (!iter_is_iovec(iter))\n'}, {'line_no': 12, 'char_start': 320, 'char_end': 333, 'line': '\t\tgoto fail;\n'}, {'line_no': 13, 'char_start': 333, 'char_end': 334, 'line': '\n'}, {'line_no': 36, 'char_start': 819, 'char_end': 825, 'line': 'fail:\n'}]}","{'deleted': [], 'added': [{'char_start': 298, 'char_end': 339, 'chars': '!iter_is_iovec(iter))\n\t\tgoto fail;\n\n\tif ('}, {'char_start': 818, 'char_end': 824, 'chars': '\nfail:'}]}",github.com/torvalds/linux/commit/a0ac402cfcdc904f9772e1762b3fda112dcc56a0,block/blk-map.c,cwe-416,249 cwe-476,megasas_alloc_cmds,"int megasas_alloc_cmds(struct megasas_instance *instance) { int i; int j; u16 max_cmd; struct megasas_cmd *cmd; max_cmd = instance->max_mfi_cmds; /* * instance->cmd_list is an array of struct megasas_cmd pointers. * Allocate the dynamic array first and then allocate individual * commands. */ instance->cmd_list = kcalloc(max_cmd, sizeof(struct megasas_cmd*), GFP_KERNEL); if (!instance->cmd_list) { dev_printk(KERN_DEBUG, &instance->pdev->dev, ""out of memory\n""); return -ENOMEM; } memset(instance->cmd_list, 0, sizeof(struct megasas_cmd *) *max_cmd); for (i = 0; i < max_cmd; i++) { instance->cmd_list[i] = kmalloc(sizeof(struct megasas_cmd), GFP_KERNEL); if (!instance->cmd_list[i]) { for (j = 0; j < i; j++) kfree(instance->cmd_list[j]); kfree(instance->cmd_list); instance->cmd_list = NULL; return -ENOMEM; } } for (i = 0; i < max_cmd; i++) { cmd = instance->cmd_list[i]; memset(cmd, 0, sizeof(struct megasas_cmd)); cmd->index = i; cmd->scmd = NULL; cmd->instance = instance; list_add_tail(&cmd->list, &instance->cmd_pool); } /* * Create a frame pool and assign one frame to each cmd */ if (megasas_create_frame_pool(instance)) { dev_printk(KERN_DEBUG, &instance->pdev->dev, ""Error creating frame DMA pool\n""); megasas_free_cmds(instance); } return 0; }","int megasas_alloc_cmds(struct megasas_instance *instance) { int i; int j; u16 max_cmd; struct megasas_cmd *cmd; max_cmd = instance->max_mfi_cmds; /* * instance->cmd_list is an array of struct megasas_cmd pointers. * Allocate the dynamic array first and then allocate individual * commands. */ instance->cmd_list = kcalloc(max_cmd, sizeof(struct megasas_cmd*), GFP_KERNEL); if (!instance->cmd_list) { dev_printk(KERN_DEBUG, &instance->pdev->dev, ""out of memory\n""); return -ENOMEM; } memset(instance->cmd_list, 0, sizeof(struct megasas_cmd *) *max_cmd); for (i = 0; i < max_cmd; i++) { instance->cmd_list[i] = kmalloc(sizeof(struct megasas_cmd), GFP_KERNEL); if (!instance->cmd_list[i]) { for (j = 0; j < i; j++) kfree(instance->cmd_list[j]); kfree(instance->cmd_list); instance->cmd_list = NULL; return -ENOMEM; } } for (i = 0; i < max_cmd; i++) { cmd = instance->cmd_list[i]; memset(cmd, 0, sizeof(struct megasas_cmd)); cmd->index = i; cmd->scmd = NULL; cmd->instance = instance; list_add_tail(&cmd->list, &instance->cmd_pool); } /* * Create a frame pool and assign one frame to each cmd */ if (megasas_create_frame_pool(instance)) { dev_printk(KERN_DEBUG, &instance->pdev->dev, ""Error creating frame DMA pool\n""); megasas_free_cmds(instance); return -ENOMEM; } return 0; }","{'deleted': [], 'added': [{'line_no': 56, 'char_start': 1333, 'char_end': 1351, 'line': '\t\treturn -ENOMEM;\n'}]}","{'deleted': [], 'added': [{'char_start': 1334, 'char_end': 1352, 'chars': '\treturn -ENOMEM;\n\t'}]}",github.com/torvalds/linux/commit/bcf3b67d16a4c8ffae0aa79de5853435e683945c,drivers/scsi/megaraid/megaraid_sas_base.c,cwe-476,395 cwe-089,send_message,"@frappe.whitelist(allow_guest=True) def send_message(subject=""Website Query"", message="""", sender="""", status=""Open""): from frappe.www.contact import send_message as website_send_message lead = customer = None website_send_message(subject, message, sender) customer = frappe.db.sql(""""""select distinct dl.link_name from `tabDynamic Link` dl left join `tabContact` c on dl.parent=c.name where dl.link_doctype='Customer' and c.email_id='{email_id}'"""""".format(email_id=sender)) if not customer: lead = frappe.db.get_value('Lead', dict(email_id=sender)) if not lead: new_lead = frappe.get_doc(dict( doctype='Lead', email_id = sender, lead_name = sender.split('@')[0].title() )).insert(ignore_permissions=True) opportunity = frappe.get_doc(dict( doctype ='Opportunity', enquiry_from = 'Customer' if customer else 'Lead', status = 'Open', title = subject, contact_email = sender, to_discuss = message )) if customer: opportunity.customer = customer[0][0] elif lead: opportunity.lead = lead else: opportunity.lead = new_lead.name opportunity.insert(ignore_permissions=True) comm = frappe.get_doc({ ""doctype"":""Communication"", ""subject"": subject, ""content"": message, ""sender"": sender, ""sent_or_received"": ""Received"", 'reference_doctype': 'Opportunity', 'reference_name': opportunity.name }) comm.insert(ignore_permissions=True) return ""okay""","@frappe.whitelist(allow_guest=True) def send_message(subject=""Website Query"", message="""", sender="""", status=""Open""): from frappe.www.contact import send_message as website_send_message lead = customer = None website_send_message(subject, message, sender) customer = frappe.db.sql(""""""select distinct dl.link_name from `tabDynamic Link` dl left join `tabContact` c on dl.parent=c.name where dl.link_doctype='Customer' and c.email_id = %s"""""", sender) if not customer: lead = frappe.db.get_value('Lead', dict(email_id=sender)) if not lead: new_lead = frappe.get_doc(dict( doctype='Lead', email_id = sender, lead_name = sender.split('@')[0].title() )).insert(ignore_permissions=True) opportunity = frappe.get_doc(dict( doctype ='Opportunity', enquiry_from = 'Customer' if customer else 'Lead', status = 'Open', title = subject, contact_email = sender, to_discuss = message )) if customer: opportunity.customer = customer[0][0] elif lead: opportunity.lead = lead else: opportunity.lead = new_lead.name opportunity.insert(ignore_permissions=True) comm = frappe.get_doc({ ""doctype"":""Communication"", ""subject"": subject, ""content"": message, ""sender"": sender, ""sent_or_received"": ""Received"", 'reference_doctype': 'Opportunity', 'reference_name': opportunity.name }) comm.insert(ignore_permissions=True) return ""okay""","{'deleted': [{'line_no': 10, 'char_start': 424, 'char_end': 482, 'line': '\t\tand c.email_id=\'{email_id}\'"""""".format(email_id=sender))\n'}], 'added': [{'line_no': 10, 'char_start': 424, 'char_end': 458, 'line': '\t\tand c.email_id = %s"""""", sender)\n'}]}","{'deleted': [{'char_start': 441, 'char_end': 453, 'chars': ""'{email_id}'""}, {'char_start': 456, 'char_end': 473, 'chars': '.format(email_id='}, {'char_start': 479, 'char_end': 480, 'chars': ')'}], 'added': [{'char_start': 440, 'char_end': 441, 'chars': ' '}, {'char_start': 442, 'char_end': 445, 'chars': ' %s'}, {'char_start': 448, 'char_end': 450, 'chars': ', '}]}",github.com/libracore/erpnext/commit/9acb885e60f77cd4e9ea8c98bdc39c18abcac731,erpnext/templates/utils.py,cwe-089,364 cwe-125,GetPSDRowSize,"static inline size_t GetPSDRowSize(Image *image) { if (image->depth == 1) return((image->columns+7)/8); else return(image->columns*GetPSDPacketSize(image)); }","static inline size_t GetPSDRowSize(Image *image) { if (image->depth == 1) return(((image->columns+7)/8)*GetPSDPacketSize(image)); else return(image->columns*GetPSDPacketSize(image)); }","{'deleted': [{'line_no': 4, 'char_start': 76, 'char_end': 110, 'line': ' return((image->columns+7)/8);\n'}], 'added': [{'line_no': 4, 'char_start': 76, 'char_end': 136, 'line': ' return(((image->columns+7)/8)*GetPSDPacketSize(image));\n'}]}","{'deleted': [], 'added': [{'char_start': 88, 'char_end': 89, 'chars': '('}, {'char_start': 108, 'char_end': 133, 'chars': ')*GetPSDPacketSize(image)'}]}",github.com/ImageMagick/ImageMagick/commit/5f16640725b1225e6337c62526e6577f0f88edb8,coders/psd.c,cwe-125,52 cwe-125,parse8BIM,"static ssize_t parse8BIM(Image *ifile, Image *ofile) { char brkused, quoted, *line, *token, *newstr, *name; int state, next; unsigned char dataset; unsigned int recnum; int inputlen = MaxTextExtent; MagickOffsetType savedpos, currentpos; ssize_t savedolen = 0L, outputlen = 0L; TokenInfo *token_info; dataset = 0; recnum = 0; line = (char *) AcquireQuantumMemory((size_t) inputlen,sizeof(*line)); if (line == (char *) NULL) return(-1); newstr = name = token = (char *) NULL; savedpos = 0; token_info=AcquireTokenInfo(); while (super_fgets(&line,&inputlen,ifile)!=NULL) { state=0; next=0; token=(char *) AcquireQuantumMemory((size_t) inputlen,sizeof(*token)); if (token == (char *) NULL) break; newstr=(char *) AcquireQuantumMemory((size_t) inputlen,sizeof(*newstr)); if (newstr == (char *) NULL) break; while (Tokenizer(token_info,0,token,(size_t) inputlen,line,"""",""="",""\"""",0, &brkused,&next,"ed)==0) { if (state == 0) { int state, next; char brkused, quoted; state=0; next=0; while (Tokenizer(token_info,0,newstr,(size_t) inputlen,token,"""",""#"", """", 0,&brkused,&next,"ed)==0) { switch (state) { case 0: if (strcmp(newstr,""8BIM"")==0) dataset = 255; else dataset = (unsigned char) StringToLong(newstr); break; case 1: recnum = (unsigned int) StringToUnsignedLong(newstr); break; case 2: name=(char *) AcquireQuantumMemory(strlen(newstr)+MaxTextExtent, sizeof(*name)); if (name) (void) strcpy(name,newstr); break; } state++; } } else if (state == 1) { int next; ssize_t len; char brkused, quoted; next=0; len = (ssize_t) strlen(token); while (Tokenizer(token_info,0,newstr,(size_t) inputlen,token,"""",""&"", """",0,&brkused,&next,"ed)==0) { if (brkused && next > 0) { char *s = &token[next-1]; len -= (ssize_t) convertHTMLcodes(s,(int) strlen(s)); } } if (dataset == 255) { unsigned char nlen = 0; int i; if (savedolen > 0) { MagickOffsetType offset; ssize_t diff = outputlen - savedolen; currentpos = TellBlob(ofile); if (currentpos < 0) return(-1); offset=SeekBlob(ofile,savedpos,SEEK_SET); if (offset < 0) return(-1); (void) WriteBlobMSBLong(ofile,(unsigned int) diff); offset=SeekBlob(ofile,currentpos,SEEK_SET); if (offset < 0) return(-1); savedolen = 0L; } if (outputlen & 1) { (void) WriteBlobByte(ofile,0x00); outputlen++; } (void) WriteBlobString(ofile,""8BIM""); (void) WriteBlobMSBShort(ofile,(unsigned short) recnum); outputlen += 6; if (name) nlen = (unsigned char) strlen(name); (void) WriteBlobByte(ofile,nlen); outputlen++; for (i=0; i 0) { MagickOffsetType offset; ssize_t diff = outputlen - savedolen; currentpos = TellBlob(ofile); if (currentpos < 0) return(-1); offset=SeekBlob(ofile,savedpos,SEEK_SET); if (offset < 0) return(-1); (void) WriteBlobMSBLong(ofile,(unsigned int) diff); offset=SeekBlob(ofile,currentpos,SEEK_SET); if (offset < 0) return(-1); savedolen = 0L; } return(outputlen); }","static ssize_t parse8BIM(Image *ifile, Image *ofile) { char brkused, quoted, *line, *token, *newstr, *name; int state, next; unsigned char dataset; unsigned int recnum; int inputlen = MaxTextExtent; MagickOffsetType savedpos, currentpos; ssize_t savedolen = 0L, outputlen = 0L; TokenInfo *token_info; dataset = 0; recnum = 0; line = (char *) AcquireQuantumMemory((size_t) inputlen,sizeof(*line)); if (line == (char *) NULL) return(-1); newstr = name = token = (char *) NULL; savedpos = 0; token_info=AcquireTokenInfo(); while (super_fgets(&line,&inputlen,ifile)!=NULL) { state=0; next=0; token=(char *) AcquireQuantumMemory((size_t) inputlen,sizeof(*token)); if (token == (char *) NULL) break; newstr=(char *) AcquireQuantumMemory((size_t) inputlen,sizeof(*newstr)); if (newstr == (char *) NULL) break; while (Tokenizer(token_info,0,token,(size_t) inputlen,line,"""",""="",""\"""",0, &brkused,&next,"ed)==0) { if (state == 0) { int state, next; char brkused, quoted; state=0; next=0; while (Tokenizer(token_info,0,newstr,(size_t) inputlen,token,"""",""#"", """", 0,&brkused,&next,"ed)==0) { switch (state) { case 0: if (strcmp(newstr,""8BIM"")==0) dataset = 255; else dataset = (unsigned char) StringToLong(newstr); break; case 1: recnum = (unsigned int) StringToUnsignedLong(newstr); break; case 2: name=(char *) AcquireQuantumMemory(strlen(newstr)+MaxTextExtent, sizeof(*name)); if (name) (void) strcpy(name,newstr); break; } state++; } } else if (state == 1) { int next; ssize_t len; char brkused, quoted; next=0; len = (ssize_t) strlen(token); while (Tokenizer(token_info,0,newstr,(size_t) inputlen,token,"""",""&"", """",0,&brkused,&next,"ed)==0) { if (brkused && next > 0) { char *s = &token[next-1]; len -= (ssize_t) convertHTMLcodes(s,(int) strlen(s)); } } if (dataset == 255) { unsigned char nlen = 0; int i; if (savedolen > 0) { MagickOffsetType offset; ssize_t diff = outputlen - savedolen; currentpos = TellBlob(ofile); if (currentpos < 0) return(-1); offset=SeekBlob(ofile,savedpos,SEEK_SET); if (offset < 0) return(-1); (void) WriteBlobMSBLong(ofile,(unsigned int) diff); offset=SeekBlob(ofile,currentpos,SEEK_SET); if (offset < 0) return(-1); savedolen = 0L; } if (outputlen & 1) { (void) WriteBlobByte(ofile,0x00); outputlen++; } (void) WriteBlobString(ofile,""8BIM""); (void) WriteBlobMSBShort(ofile,(unsigned short) recnum); outputlen += 6; if (name) nlen = (unsigned char) strlen(name); (void) WriteBlobByte(ofile,nlen); outputlen++; for (i=0; i 0) (void) WriteBlobByte(ofile,(unsigned char) token[next++]); if (outputlen & 1) { (void) WriteBlobByte(ofile,0x00); outputlen++; } } else { /* patch in a fake length for now and fix it later */ savedpos = TellBlob(ofile); if (savedpos < 0) return(-1); (void) WriteBlobMSBLong(ofile,0xFFFFFFFFU); outputlen += 4; savedolen = outputlen; } } else { if (len <= 0x7FFF) { (void) WriteBlobByte(ofile,0x1c); (void) WriteBlobByte(ofile,(unsigned char) dataset); (void) WriteBlobByte(ofile,(unsigned char) (recnum & 0xff)); (void) WriteBlobMSBShort(ofile,(unsigned short) len); outputlen += 5; next=0; outputlen += len; while (len-- > 0) (void) WriteBlobByte(ofile,(unsigned char) token[next++]); } } } state++; } if (token != (char *) NULL) token=DestroyString(token); if (newstr != (char *) NULL) newstr=DestroyString(newstr); if (name != (char *) NULL) name=DestroyString(name); } token_info=DestroyTokenInfo(token_info); if (token != (char *) NULL) token=DestroyString(token); if (newstr != (char *) NULL) newstr=DestroyString(newstr); if (name != (char *) NULL) name=DestroyString(name); line=DestroyString(line); if (savedolen > 0) { MagickOffsetType offset; ssize_t diff = outputlen - savedolen; currentpos = TellBlob(ofile); if (currentpos < 0) return(-1); offset=SeekBlob(ofile,savedpos,SEEK_SET); if (offset < 0) return(-1); (void) WriteBlobMSBLong(ofile,(unsigned int) diff); offset=SeekBlob(ofile,currentpos,SEEK_SET); if (offset < 0) return(-1); savedolen = 0L; } return(outputlen); }","{'deleted': [{'line_no': 173, 'char_start': 4538, 'char_end': 4572, 'line': ' while (len--)\n'}, {'line_no': 204, 'char_start': 5742, 'char_end': 5776, 'line': ' while (len--)\n'}], 'added': [{'line_no': 173, 'char_start': 4538, 'char_end': 4576, 'line': ' while (len-- > 0)\n'}, {'line_no': 204, 'char_start': 5746, 'char_end': 5784, 'line': ' while (len-- > 0)\n'}]}","{'deleted': [], 'added': [{'char_start': 4570, 'char_end': 4574, 'chars': ' > 0'}, {'char_start': 5778, 'char_end': 5782, 'chars': ' > 0'}]}",github.com/ImageMagick/ImageMagick/commit/97c9f438a9b3454d085895f4d1f66389fd22a0fb,coders/meta.c,cwe-125,1608 cwe-476,inet_rtm_getroute,"static int inet_rtm_getroute(struct sk_buff *in_skb, struct nlmsghdr *nlh, struct netlink_ext_ack *extack) { struct net *net = sock_net(in_skb->sk); struct rtmsg *rtm; struct nlattr *tb[RTA_MAX+1]; struct fib_result res = {}; struct rtable *rt = NULL; struct flowi4 fl4; __be32 dst = 0; __be32 src = 0; u32 iif; int err; int mark; struct sk_buff *skb; u32 table_id = RT_TABLE_MAIN; kuid_t uid; err = nlmsg_parse(nlh, sizeof(*rtm), tb, RTA_MAX, rtm_ipv4_policy, extack); if (err < 0) goto errout; rtm = nlmsg_data(nlh); skb = alloc_skb(NLMSG_GOODSIZE, GFP_KERNEL); if (!skb) { err = -ENOBUFS; goto errout; } /* Reserve room for dummy headers, this skb can pass through good chunk of routing engine. */ skb_reset_mac_header(skb); skb_reset_network_header(skb); src = tb[RTA_SRC] ? nla_get_in_addr(tb[RTA_SRC]) : 0; dst = tb[RTA_DST] ? nla_get_in_addr(tb[RTA_DST]) : 0; iif = tb[RTA_IIF] ? nla_get_u32(tb[RTA_IIF]) : 0; mark = tb[RTA_MARK] ? nla_get_u32(tb[RTA_MARK]) : 0; if (tb[RTA_UID]) uid = make_kuid(current_user_ns(), nla_get_u32(tb[RTA_UID])); else uid = (iif ? INVALID_UID : current_uid()); /* Bugfix: need to give ip_route_input enough of an IP header to * not gag. */ ip_hdr(skb)->protocol = IPPROTO_UDP; ip_hdr(skb)->saddr = src; ip_hdr(skb)->daddr = dst; skb_reserve(skb, MAX_HEADER + sizeof(struct iphdr)); memset(&fl4, 0, sizeof(fl4)); fl4.daddr = dst; fl4.saddr = src; fl4.flowi4_tos = rtm->rtm_tos; fl4.flowi4_oif = tb[RTA_OIF] ? nla_get_u32(tb[RTA_OIF]) : 0; fl4.flowi4_mark = mark; fl4.flowi4_uid = uid; rcu_read_lock(); if (iif) { struct net_device *dev; dev = dev_get_by_index_rcu(net, iif); if (!dev) { err = -ENODEV; goto errout_free; } skb->protocol = htons(ETH_P_IP); skb->dev = dev; skb->mark = mark; err = ip_route_input_rcu(skb, dst, src, rtm->rtm_tos, dev, &res); rt = skb_rtable(skb); if (err == 0 && rt->dst.error) err = -rt->dst.error; } else { rt = ip_route_output_key_hash_rcu(net, &fl4, &res, skb); err = 0; if (IS_ERR(rt)) err = PTR_ERR(rt); else skb_dst_set(skb, &rt->dst); } if (err) goto errout_free; if (rtm->rtm_flags & RTM_F_NOTIFY) rt->rt_flags |= RTCF_NOTIFY; if (rtm->rtm_flags & RTM_F_LOOKUP_TABLE) table_id = rt->rt_table_id; if (rtm->rtm_flags & RTM_F_FIB_MATCH) err = fib_dump_info(skb, NETLINK_CB(in_skb).portid, nlh->nlmsg_seq, RTM_NEWROUTE, table_id, rt->rt_type, res.prefix, res.prefixlen, fl4.flowi4_tos, res.fi, 0); else err = rt_fill_info(net, dst, src, table_id, &fl4, skb, NETLINK_CB(in_skb).portid, nlh->nlmsg_seq); if (err < 0) goto errout_free; rcu_read_unlock(); err = rtnl_unicast(skb, net, NETLINK_CB(in_skb).portid); errout: return err; errout_free: rcu_read_unlock(); kfree_skb(skb); goto errout; }","static int inet_rtm_getroute(struct sk_buff *in_skb, struct nlmsghdr *nlh, struct netlink_ext_ack *extack) { struct net *net = sock_net(in_skb->sk); struct rtmsg *rtm; struct nlattr *tb[RTA_MAX+1]; struct fib_result res = {}; struct rtable *rt = NULL; struct flowi4 fl4; __be32 dst = 0; __be32 src = 0; u32 iif; int err; int mark; struct sk_buff *skb; u32 table_id = RT_TABLE_MAIN; kuid_t uid; err = nlmsg_parse(nlh, sizeof(*rtm), tb, RTA_MAX, rtm_ipv4_policy, extack); if (err < 0) goto errout; rtm = nlmsg_data(nlh); skb = alloc_skb(NLMSG_GOODSIZE, GFP_KERNEL); if (!skb) { err = -ENOBUFS; goto errout; } /* Reserve room for dummy headers, this skb can pass through good chunk of routing engine. */ skb_reset_mac_header(skb); skb_reset_network_header(skb); src = tb[RTA_SRC] ? nla_get_in_addr(tb[RTA_SRC]) : 0; dst = tb[RTA_DST] ? nla_get_in_addr(tb[RTA_DST]) : 0; iif = tb[RTA_IIF] ? nla_get_u32(tb[RTA_IIF]) : 0; mark = tb[RTA_MARK] ? nla_get_u32(tb[RTA_MARK]) : 0; if (tb[RTA_UID]) uid = make_kuid(current_user_ns(), nla_get_u32(tb[RTA_UID])); else uid = (iif ? INVALID_UID : current_uid()); /* Bugfix: need to give ip_route_input enough of an IP header to * not gag. */ ip_hdr(skb)->protocol = IPPROTO_UDP; ip_hdr(skb)->saddr = src; ip_hdr(skb)->daddr = dst; skb_reserve(skb, MAX_HEADER + sizeof(struct iphdr)); memset(&fl4, 0, sizeof(fl4)); fl4.daddr = dst; fl4.saddr = src; fl4.flowi4_tos = rtm->rtm_tos; fl4.flowi4_oif = tb[RTA_OIF] ? nla_get_u32(tb[RTA_OIF]) : 0; fl4.flowi4_mark = mark; fl4.flowi4_uid = uid; rcu_read_lock(); if (iif) { struct net_device *dev; dev = dev_get_by_index_rcu(net, iif); if (!dev) { err = -ENODEV; goto errout_free; } skb->protocol = htons(ETH_P_IP); skb->dev = dev; skb->mark = mark; err = ip_route_input_rcu(skb, dst, src, rtm->rtm_tos, dev, &res); rt = skb_rtable(skb); if (err == 0 && rt->dst.error) err = -rt->dst.error; } else { rt = ip_route_output_key_hash_rcu(net, &fl4, &res, skb); err = 0; if (IS_ERR(rt)) err = PTR_ERR(rt); else skb_dst_set(skb, &rt->dst); } if (err) goto errout_free; if (rtm->rtm_flags & RTM_F_NOTIFY) rt->rt_flags |= RTCF_NOTIFY; if (rtm->rtm_flags & RTM_F_LOOKUP_TABLE) table_id = rt->rt_table_id; if (rtm->rtm_flags & RTM_F_FIB_MATCH) { if (!res.fi) { err = fib_props[res.type].error; if (!err) err = -EHOSTUNREACH; goto errout_free; } err = fib_dump_info(skb, NETLINK_CB(in_skb).portid, nlh->nlmsg_seq, RTM_NEWROUTE, table_id, rt->rt_type, res.prefix, res.prefixlen, fl4.flowi4_tos, res.fi, 0); } else { err = rt_fill_info(net, dst, src, table_id, &fl4, skb, NETLINK_CB(in_skb).portid, nlh->nlmsg_seq); } if (err < 0) goto errout_free; rcu_read_unlock(); err = rtnl_unicast(skb, net, NETLINK_CB(in_skb).portid); errout: return err; errout_free: rcu_read_unlock(); kfree_skb(skb); goto errout; }","{'deleted': [{'line_no': 102, 'char_start': 2323, 'char_end': 2362, 'line': '\tif (rtm->rtm_flags & RTM_F_FIB_MATCH)\n'}, {'line_no': 107, 'char_start': 2548, 'char_end': 2554, 'line': '\telse\n'}], 'added': [{'line_no': 102, 'char_start': 2323, 'char_end': 2364, 'line': '\tif (rtm->rtm_flags & RTM_F_FIB_MATCH) {\n'}, {'line_no': 103, 'char_start': 2364, 'char_end': 2381, 'line': '\t\tif (!res.fi) {\n'}, {'line_no': 104, 'char_start': 2381, 'char_end': 2417, 'line': '\t\t\terr = fib_props[res.type].error;\n'}, {'line_no': 105, 'char_start': 2417, 'char_end': 2430, 'line': '\t\t\tif (!err)\n'}, {'line_no': 106, 'char_start': 2430, 'char_end': 2455, 'line': '\t\t\t\terr = -EHOSTUNREACH;\n'}, {'line_no': 107, 'char_start': 2455, 'char_end': 2476, 'line': '\t\t\tgoto errout_free;\n'}, {'line_no': 108, 'char_start': 2476, 'char_end': 2480, 'line': '\t\t}\n'}, {'line_no': 113, 'char_start': 2666, 'char_end': 2676, 'line': '\t} else {\n'}, {'line_no': 116, 'char_start': 2784, 'char_end': 2787, 'line': '\t}\n'}]}","{'deleted': [{'char_start': 2362, 'char_end': 2362, 'chars': ''}, {'char_start': 2611, 'char_end': 2611, 'chars': ''}], 'added': [{'char_start': 2361, 'char_end': 2479, 'chars': ' {\n\t\tif (!res.fi) {\n\t\t\terr = fib_props[res.type].error;\n\t\t\tif (!err)\n\t\t\t\terr = -EHOSTUNREACH;\n\t\t\tgoto errout_free;\n\t\t}'}, {'char_start': 2667, 'char_end': 2669, 'chars': '} '}, {'char_start': 2673, 'char_end': 2675, 'chars': ' {'}, {'char_start': 2783, 'char_end': 2786, 'chars': '\n\t}'}]}",github.com/torvalds/linux/commit/bc3aae2bbac46dd894c89db5d5e98f7f0ef9e205,net/ipv4/route.c,cwe-476,1016 cwe-089,test_process_as_form," @unpack def test_process_as_form(self, job_number, dcn_key, was_prev_matched, was_prev_closed, was_prev_tracked): email_obj = { 'sender' : ""Alex Roy "", 'subject' : ""DO NOT MODIFY MESSAGE BELOW - JUST HIT `SEND`"", 'date' : ""Tue, 7 May 2019 17:34:17 +0000"", 'content' : ( f""job_number={job_number}&title=TEST_ENTRY&city=Ottawa&"" f""address=2562+Del+Zotto+Ave.%2C+Ottawa%2C+Ontario&"" f""contractor=GCN&engineer=Goodkey&owner=Douglas+Stalker&"" f""quality=2&cc_email=&link_to_cert={dcn_key}\r\n"" ) } # set-up new entries in db, if necessary fake_dilfo_insert = """""" INSERT INTO df_dilfo (job_number, receiver_email, closed) VALUES ({}, 'alex.roy616@gmail.com', {}) """""" fake_match_insert = """""" INSERT INTO df_matched (job_number, verifier, ground_truth) VALUES ({}, 'alex.roy616@gmail.com', {}) """""" with create_connection() as conn: if was_prev_closed or was_prev_tracked: conn.cursor().execute(fake_dilfo_insert.format(job_number, was_prev_closed)) if was_prev_matched: if was_prev_closed: conn.cursor().execute(fake_match_insert.format(job_number, 1)) else: conn.cursor().execute(fake_match_insert.format(job_number, 0)) with create_connection() as conn: df_dilfo_pre = pd.read_sql(f""SELECT * FROM df_dilfo WHERE job_number={job_number}"", conn) df_matched_pre = pd.read_sql(f""SELECT * FROM df_matched WHERE job_number={job_number}"", conn) process_as_form(email_obj) # make assertions about db now that reply has been processed with create_connection() as conn: df_dilfo_post = pd.read_sql(f""SELECT * FROM df_dilfo WHERE job_number={job_number}"", conn) df_matched_post = pd.read_sql(f""SELECT * FROM df_matched WHERE job_number={job_number}"", conn) self.assertEqual(len(df_dilfo_post), 1) self.assertEqual(bool(df_dilfo_post.iloc[0].closed), bool(was_prev_closed or dcn_key)) self.assertEqual(any(df_matched_post.ground_truth), bool(was_prev_closed or dcn_key)) self.assertEqual(len(df_matched_pre) + bool(dcn_key and not(was_prev_closed)), len(df_matched_post)) self.assertEqual(list(df_matched_pre.columns), list(df_matched_post.columns)) self.assertEqual(list(df_dilfo_pre.columns), list(df_dilfo_post.columns))"," @unpack def test_process_as_form(self, job_number, dcn_key, was_prev_matched, was_prev_closed, was_prev_tracked): email_obj = { 'sender' : ""Alex Roy "", 'subject' : ""DO NOT MODIFY MESSAGE BELOW - JUST HIT `SEND`"", 'date' : ""Tue, 7 May 2019 17:34:17 +0000"", 'content' : ( f""job_number={job_number}&title=TEST_ENTRY&city=Ottawa&"" f""address=2562+Del+Zotto+Ave.%2C+Ottawa%2C+Ontario&"" f""contractor=GCN&engineer=Goodkey&owner=Douglas+Stalker&"" f""quality=2&cc_email=&link_to_cert={dcn_key}\r\n"" ) } # set-up new entries in db, if necessary fake_dilfo_insert = """""" INSERT INTO df_dilfo (job_number, receiver_email, closed) VALUES (?, 'alex.roy616@gmail.com', ?) """""" fake_match_insert = """""" INSERT INTO df_matched (job_number, verifier, ground_truth) VALUES (?, 'alex.roy616@gmail.com', ?) """""" with create_connection() as conn: if was_prev_closed or was_prev_tracked: conn.cursor().execute(fake_dilfo_insert, [job_number, was_prev_closed]) if was_prev_matched: if was_prev_closed: conn.cursor().execute(fake_match_insert, [job_number, 1]) else: conn.cursor().execute(fake_match_insert, [job_number, 0]) with create_connection() as conn: df_dilfo_pre = pd.read_sql(""SELECT * FROM df_dilfo WHERE job_number=?"", conn, params=[job_number]) df_matched_pre = pd.read_sql(""SELECT * FROM df_matched WHERE job_number=?"", conn, params=[job_number]) process_as_form(email_obj) # make assertions about db now that reply has been processed with create_connection() as conn: df_dilfo_post = pd.read_sql(""SELECT * FROM df_dilfo WHERE job_number=?"", conn, params=[job_number]) df_matched_post = pd.read_sql(""SELECT * FROM df_matched WHERE job_number=?"", conn, params=[job_number]) self.assertEqual(len(df_dilfo_post), 1) self.assertEqual(bool(df_dilfo_post.iloc[0].closed), bool(was_prev_closed or dcn_key)) self.assertEqual(any(df_matched_post.ground_truth), bool(was_prev_closed or dcn_key)) self.assertEqual(len(df_matched_pre) + bool(dcn_key and not(was_prev_closed)), len(df_matched_post)) self.assertEqual(list(df_matched_pre.columns), list(df_matched_post.columns)) self.assertEqual(list(df_dilfo_pre.columns), list(df_dilfo_post.columns))","{'deleted': [{'line_no': 18, 'char_start': 823, 'char_end': 876, 'line': "" VALUES ({}, 'alex.roy616@gmail.com', {})\n""}, {'line_no': 22, 'char_start': 992, 'char_end': 1045, 'line': "" VALUES ({}, 'alex.roy616@gmail.com', {})\n""}, {'line_no': 26, 'char_start': 1151, 'char_end': 1244, 'line': ' conn.cursor().execute(fake_dilfo_insert.format(job_number, was_prev_closed))\n'}, {'line_no': 29, 'char_start': 1313, 'char_end': 1396, 'line': ' conn.cursor().execute(fake_match_insert.format(job_number, 1))\n'}, {'line_no': 31, 'char_start': 1418, 'char_end': 1501, 'line': ' conn.cursor().execute(fake_match_insert.format(job_number, 0))\n'}, {'line_no': 33, 'char_start': 1543, 'char_end': 1645, 'line': ' df_dilfo_pre = pd.read_sql(f""SELECT * FROM df_dilfo WHERE job_number={job_number}"", conn)\n'}, {'line_no': 34, 'char_start': 1645, 'char_end': 1751, 'line': ' df_matched_pre = pd.read_sql(f""SELECT * FROM df_matched WHERE job_number={job_number}"", conn)\n'}, {'line_no': 38, 'char_start': 1897, 'char_end': 2000, 'line': ' df_dilfo_post = pd.read_sql(f""SELECT * FROM df_dilfo WHERE job_number={job_number}"", conn)\n'}, {'line_no': 39, 'char_start': 2000, 'char_end': 2107, 'line': ' df_matched_post = pd.read_sql(f""SELECT * FROM df_matched WHERE job_number={job_number}"", conn)\n'}], 'added': [{'line_no': 18, 'char_start': 823, 'char_end': 874, 'line': "" VALUES (?, 'alex.roy616@gmail.com', ?)\n""}, {'line_no': 22, 'char_start': 990, 'char_end': 1041, 'line': "" VALUES (?, 'alex.roy616@gmail.com', ?)\n""}, {'line_no': 26, 'char_start': 1147, 'char_end': 1235, 'line': ' conn.cursor().execute(fake_dilfo_insert, [job_number, was_prev_closed])\n'}, {'line_no': 29, 'char_start': 1304, 'char_end': 1382, 'line': ' conn.cursor().execute(fake_match_insert, [job_number, 1])\n'}, {'line_no': 31, 'char_start': 1404, 'char_end': 1482, 'line': ' conn.cursor().execute(fake_match_insert, [job_number, 0])\n'}, {'line_no': 33, 'char_start': 1524, 'char_end': 1635, 'line': ' df_dilfo_pre = pd.read_sql(""SELECT * FROM df_dilfo WHERE job_number=?"", conn, params=[job_number])\n'}, {'line_no': 34, 'char_start': 1635, 'char_end': 1750, 'line': ' df_matched_pre = pd.read_sql(""SELECT * FROM df_matched WHERE job_number=?"", conn, params=[job_number])\n'}, {'line_no': 38, 'char_start': 1896, 'char_end': 2008, 'line': ' df_dilfo_post = pd.read_sql(""SELECT * FROM df_dilfo WHERE job_number=?"", conn, params=[job_number])\n'}, {'line_no': 39, 'char_start': 2008, 'char_end': 2124, 'line': ' df_matched_post = pd.read_sql(""SELECT * FROM df_matched WHERE job_number=?"", conn, params=[job_number])\n'}]}","{'deleted': [{'char_start': 843, 'char_end': 845, 'chars': '{}'}, {'char_start': 872, 'char_end': 874, 'chars': '{}'}, {'char_start': 1012, 'char_end': 1014, 'chars': '{}'}, {'char_start': 1041, 'char_end': 1043, 'chars': '{}'}, {'char_start': 1206, 'char_end': 1214, 'chars': '.format('}, {'char_start': 1241, 'char_end': 1242, 'chars': ')'}, {'char_start': 1372, 'char_end': 1380, 'chars': '.format('}, {'char_start': 1393, 'char_end': 1394, 'chars': ')'}, {'char_start': 1477, 'char_end': 1485, 'chars': '.format('}, {'char_start': 1498, 'char_end': 1499, 'chars': ')'}, {'char_start': 1582, 'char_end': 1583, 'chars': 'f'}, {'char_start': 1624, 'char_end': 1625, 'chars': '{'}, {'char_start': 1635, 'char_end': 1643, 'chars': '}"", conn'}, {'char_start': 1686, 'char_end': 1687, 'chars': 'f'}, {'char_start': 1730, 'char_end': 1731, 'chars': '{'}, {'char_start': 1741, 'char_end': 1749, 'chars': '}"", conn'}, {'char_start': 1937, 'char_end': 1938, 'chars': 'f'}, {'char_start': 1979, 'char_end': 1980, 'chars': '{'}, {'char_start': 1990, 'char_end': 1998, 'chars': '}"", conn'}, {'char_start': 2042, 'char_end': 2043, 'chars': 'f'}, {'char_start': 2086, 'char_end': 2087, 'chars': '{'}, {'char_start': 2097, 'char_end': 2105, 'chars': '}"", conn'}], 'added': [{'char_start': 843, 'char_end': 844, 'chars': '?'}, {'char_start': 871, 'char_end': 872, 'chars': '?'}, {'char_start': 1010, 'char_end': 1011, 'chars': '?'}, {'char_start': 1038, 'char_end': 1039, 'chars': '?'}, {'char_start': 1202, 'char_end': 1205, 'chars': ', ['}, {'char_start': 1232, 'char_end': 1233, 'chars': ']'}, {'char_start': 1363, 'char_end': 1366, 'chars': ', ['}, {'char_start': 1379, 'char_end': 1380, 'chars': ']'}, {'char_start': 1463, 'char_end': 1466, 'chars': ', ['}, {'char_start': 1479, 'char_end': 1480, 'chars': ']'}, {'char_start': 1604, 'char_end': 1622, 'chars': '?"", conn, params=['}, {'char_start': 1632, 'char_end': 1633, 'chars': ']'}, {'char_start': 1719, 'char_end': 1737, 'chars': '?"", conn, params=['}, {'char_start': 1747, 'char_end': 1748, 'chars': ']'}, {'char_start': 1977, 'char_end': 1995, 'chars': '?"", conn, params=['}, {'char_start': 2005, 'char_end': 2006, 'chars': ']'}, {'char_start': 2093, 'char_end': 2111, 'chars': '?"", conn, params=['}, {'char_start': 2121, 'char_end': 2122, 'chars': ']'}]}",github.com/confirmationbias616/certificate_checker/commit/9e890b9613b627e3a5995d0e4a594c8e0831e2ce,tests.py,cwe-089,641 cwe-022,handle_method_call,"static void handle_method_call(GDBusConnection *connection, const gchar *caller, const gchar *object_path, const gchar *interface_name, const gchar *method_name, GVariant *parameters, GDBusMethodInvocation *invocation, gpointer user_data) { reset_timeout(); uid_t caller_uid; GVariant *response; caller_uid = get_caller_uid(connection, invocation, caller); log_notice(""caller_uid:%ld method:'%s'"", (long)caller_uid, method_name); if (caller_uid == (uid_t) -1) return; if (g_strcmp0(method_name, ""NewProblem"") == 0) { char *error = NULL; char *problem_id = handle_new_problem(g_variant_get_child_value(parameters, 0), caller_uid, &error); if (!problem_id) { g_dbus_method_invocation_return_dbus_error(invocation, ""org.freedesktop.problems.Failure"", error); free(error); return; } /* else */ response = g_variant_new(""(s)"", problem_id); g_dbus_method_invocation_return_value(invocation, response); free(problem_id); return; } if (g_strcmp0(method_name, ""GetProblems"") == 0) { GList *dirs = get_problem_dirs_for_uid(caller_uid, g_settings_dump_location); response = variant_from_string_list(dirs); list_free_with_free(dirs); g_dbus_method_invocation_return_value(invocation, response); //I was told that g_dbus_method frees the response //g_variant_unref(response); return; } if (g_strcmp0(method_name, ""GetAllProblems"") == 0) { /* - so, we have UID, - if it's 0, then we don't have to check anything and just return all directories - if uid != 0 then we want to ask for authorization */ if (caller_uid != 0) { if (polkit_check_authorization_dname(caller, ""org.freedesktop.problems.getall"") == PolkitYes) caller_uid = 0; } GList * dirs = get_problem_dirs_for_uid(caller_uid, g_settings_dump_location); response = variant_from_string_list(dirs); list_free_with_free(dirs); g_dbus_method_invocation_return_value(invocation, response); return; } if (g_strcmp0(method_name, ""GetForeignProblems"") == 0) { GList * dirs = get_problem_dirs_not_accessible_by_uid(caller_uid, g_settings_dump_location); response = variant_from_string_list(dirs); list_free_with_free(dirs); g_dbus_method_invocation_return_value(invocation, response); return; } if (g_strcmp0(method_name, ""ChownProblemDir"") == 0) { const gchar *problem_dir; g_variant_get(parameters, ""(&s)"", &problem_dir); log_notice(""problem_dir:'%s'"", problem_dir); if (!allowed_problem_dir(problem_dir)) { return_InvalidProblemDir_error(invocation, problem_dir); return; } int dir_fd = dd_openfd(problem_dir); if (dir_fd < 0) { perror_msg(""can't open problem directory '%s'"", problem_dir); return_InvalidProblemDir_error(invocation, problem_dir); return; } int ddstat = fdump_dir_stat_for_uid(dir_fd, caller_uid); if (ddstat < 0) { if (errno == ENOTDIR) { log_notice(""requested directory does not exist '%s'"", problem_dir); } else { perror_msg(""can't get stat of '%s'"", problem_dir); } return_InvalidProblemDir_error(invocation, problem_dir); close(dir_fd); return; } if (ddstat & DD_STAT_OWNED_BY_UID) { //caller seems to be in group with access to this dir, so no action needed log_notice(""caller has access to the requested directory %s"", problem_dir); g_dbus_method_invocation_return_value(invocation, NULL); close(dir_fd); return; } if ((ddstat & DD_STAT_ACCESSIBLE_BY_UID) == 0 && polkit_check_authorization_dname(caller, ""org.freedesktop.problems.getall"") != PolkitYes) { log_notice(""not authorized""); g_dbus_method_invocation_return_dbus_error(invocation, ""org.freedesktop.problems.AuthFailure"", _(""Not Authorized"")); close(dir_fd); return; } struct dump_dir *dd = dd_fdopendir(dir_fd, problem_dir, DD_OPEN_READONLY | DD_FAIL_QUIETLY_EACCES); if (!dd) { return_InvalidProblemDir_error(invocation, problem_dir); return; } int chown_res = dd_chown(dd, caller_uid); if (chown_res != 0) g_dbus_method_invocation_return_dbus_error(invocation, ""org.freedesktop.problems.ChownError"", _(""Chowning directory failed. Check system logs for more details."")); else g_dbus_method_invocation_return_value(invocation, NULL); dd_close(dd); return; } if (g_strcmp0(method_name, ""GetInfo"") == 0) { /* Parameter tuple is (sas) */ /* Get 1st param - problem dir name */ const gchar *problem_dir; g_variant_get_child(parameters, 0, ""&s"", &problem_dir); log_notice(""problem_dir:'%s'"", problem_dir); if (!allowed_problem_dir(problem_dir)) { return_InvalidProblemDir_error(invocation, problem_dir); return; } int dir_fd = dd_openfd(problem_dir); if (dir_fd < 0) { perror_msg(""can't open problem directory '%s'"", problem_dir); return_InvalidProblemDir_error(invocation, problem_dir); return; } if (!fdump_dir_accessible_by_uid(dir_fd, caller_uid)) { if (errno == ENOTDIR) { log_notice(""Requested directory does not exist '%s'"", problem_dir); return_InvalidProblemDir_error(invocation, problem_dir); close(dir_fd); return; } if (polkit_check_authorization_dname(caller, ""org.freedesktop.problems.getall"") != PolkitYes) { log_notice(""not authorized""); g_dbus_method_invocation_return_dbus_error(invocation, ""org.freedesktop.problems.AuthFailure"", _(""Not Authorized"")); close(dir_fd); return; } } struct dump_dir *dd = dd_fdopendir(dir_fd, problem_dir, DD_OPEN_READONLY | DD_FAIL_QUIETLY_EACCES); if (!dd) { return_InvalidProblemDir_error(invocation, problem_dir); return; } /* Get 2nd param - vector of element names */ GVariant *array = g_variant_get_child_value(parameters, 1); GList *elements = string_list_from_variant(array); g_variant_unref(array); GVariantBuilder *builder = NULL; for (GList *l = elements; l; l = l->next) { const char *element_name = (const char*)l->data; char *value = dd_load_text_ext(dd, element_name, 0 | DD_LOAD_TEXT_RETURN_NULL_ON_FAILURE | DD_FAIL_QUIETLY_ENOENT | DD_FAIL_QUIETLY_EACCES); log_notice(""element '%s' %s"", element_name, value ? ""fetched"" : ""not found""); if (value) { if (!builder) builder = g_variant_builder_new(G_VARIANT_TYPE_ARRAY); /* g_variant_builder_add makes a copy. No need to xstrdup here */ g_variant_builder_add(builder, ""{ss}"", element_name, value); free(value); } } list_free_with_free(elements); dd_close(dd); /* It is OK to call g_variant_new(""(a{ss})"", NULL) because */ /* G_VARIANT_TYPE_TUPLE allows NULL value */ GVariant *response = g_variant_new(""(a{ss})"", builder); if (builder) g_variant_builder_unref(builder); log_info(""GetInfo: returning value for '%s'"", problem_dir); g_dbus_method_invocation_return_value(invocation, response); return; } if (g_strcmp0(method_name, ""SetElement"") == 0) { const char *problem_id; const char *element; const char *value; g_variant_get(parameters, ""(&s&s&s)"", &problem_id, &element, &value); if (!str_is_correct_filename(element)) { log_notice(""'%s' is not a valid element name of '%s'"", element, problem_id); char *error = xasprintf(_(""'%s' is not a valid element name""), element); g_dbus_method_invocation_return_dbus_error(invocation, ""org.freedesktop.problems.InvalidElement"", error); free(error); return; } struct dump_dir *dd = open_directory_for_modification_of_element( invocation, caller_uid, problem_id, element); if (!dd) /* Already logged from open_directory_for_modification_of_element() */ return; /* Is it good idea to make it static? Is it possible to change the max size while a single run? */ const double max_dir_size = g_settings_nMaxCrashReportsSize * (1024 * 1024); const long item_size = dd_get_item_size(dd, element); if (item_size < 0) { log_notice(""Can't get size of '%s/%s'"", problem_id, element); char *error = xasprintf(_(""Can't get size of '%s'""), element); g_dbus_method_invocation_return_dbus_error(invocation, ""org.freedesktop.problems.Failure"", error); return; } const double requested_size = (double)strlen(value) - item_size; /* Don't want to check the size limit in case of reducing of size */ if (requested_size > 0 && requested_size > (max_dir_size - get_dirsize(g_settings_dump_location))) { log_notice(""No problem space left in '%s' (requested Bytes %f)"", problem_id, requested_size); g_dbus_method_invocation_return_dbus_error(invocation, ""org.freedesktop.problems.Failure"", _(""No problem space left"")); } else { dd_save_text(dd, element, value); g_dbus_method_invocation_return_value(invocation, NULL); } dd_close(dd); return; } if (g_strcmp0(method_name, ""DeleteElement"") == 0) { const char *problem_id; const char *element; g_variant_get(parameters, ""(&s&s)"", &problem_id, &element); if (!str_is_correct_filename(element)) { log_notice(""'%s' is not a valid element name of '%s'"", element, problem_id); char *error = xasprintf(_(""'%s' is not a valid element name""), element); g_dbus_method_invocation_return_dbus_error(invocation, ""org.freedesktop.problems.InvalidElement"", error); free(error); return; } struct dump_dir *dd = open_directory_for_modification_of_element( invocation, caller_uid, problem_id, element); if (!dd) /* Already logged from open_directory_for_modification_of_element() */ return; const int res = dd_delete_item(dd, element); dd_close(dd); if (res != 0) { log_notice(""Can't delete the element '%s' from the problem directory '%s'"", element, problem_id); char *error = xasprintf(_(""Can't delete the element '%s' from the problem directory '%s'""), element, problem_id); g_dbus_method_invocation_return_dbus_error(invocation, ""org.freedesktop.problems.Failure"", error); free(error); return; } g_dbus_method_invocation_return_value(invocation, NULL); return; } if (g_strcmp0(method_name, ""DeleteProblem"") == 0) { /* Dbus parameters are always tuples. * In this case, it's (as) - a tuple of one element (array of strings). * Need to fetch the array: */ GVariant *array = g_variant_get_child_value(parameters, 0); GList *problem_dirs = string_list_from_variant(array); g_variant_unref(array); for (GList *l = problem_dirs; l; l = l->next) { const char *dir_name = (const char*)l->data; log_notice(""dir_name:'%s'"", dir_name); if (!allowed_problem_dir(dir_name)) { return_InvalidProblemDir_error(invocation, dir_name); goto ret; } } for (GList *l = problem_dirs; l; l = l->next) { const char *dir_name = (const char*)l->data; int dir_fd = dd_openfd(dir_name); if (dir_fd < 0) { perror_msg(""can't open problem directory '%s'"", dir_name); return_InvalidProblemDir_error(invocation, dir_name); return; } if (!fdump_dir_accessible_by_uid(dir_fd, caller_uid)) { if (errno == ENOTDIR) { log_notice(""Requested directory does not exist '%s'"", dir_name); close(dir_fd); continue; } if (polkit_check_authorization_dname(caller, ""org.freedesktop.problems.getall"") != PolkitYes) { // if user didn't provide correct credentials, just move to the next dir close(dir_fd); continue; } } struct dump_dir *dd = dd_fdopendir(dir_fd, dir_name, /*flags:*/ 0); if (dd) { if (dd_delete(dd) != 0) { error_msg(""Failed to delete problem directory '%s'"", dir_name); dd_close(dd); } } } g_dbus_method_invocation_return_value(invocation, NULL); ret: list_free_with_free(problem_dirs); return; } if (g_strcmp0(method_name, ""FindProblemByElementInTimeRange"") == 0) { const gchar *element; const gchar *value; glong timestamp_from; glong timestamp_to; gboolean all; g_variant_get_child(parameters, 0, ""&s"", &element); g_variant_get_child(parameters, 1, ""&s"", &value); g_variant_get_child(parameters, 2, ""x"", ×tamp_from); g_variant_get_child(parameters, 3, ""x"", ×tamp_to); g_variant_get_child(parameters, 4, ""b"", &all); if (all && polkit_check_authorization_dname(caller, ""org.freedesktop.problems.getall"") == PolkitYes) caller_uid = 0; GList *dirs = get_problem_dirs_for_element_in_time(caller_uid, element, value, timestamp_from, timestamp_to); response = variant_from_string_list(dirs); list_free_with_free(dirs); g_dbus_method_invocation_return_value(invocation, response); return; } if (g_strcmp0(method_name, ""Quit"") == 0) { g_dbus_method_invocation_return_value(invocation, NULL); g_main_loop_quit(loop); return; } }","static void handle_method_call(GDBusConnection *connection, const gchar *caller, const gchar *object_path, const gchar *interface_name, const gchar *method_name, GVariant *parameters, GDBusMethodInvocation *invocation, gpointer user_data) { reset_timeout(); uid_t caller_uid; GVariant *response; caller_uid = get_caller_uid(connection, invocation, caller); log_notice(""caller_uid:%ld method:'%s'"", (long)caller_uid, method_name); if (caller_uid == (uid_t) -1) return; if (g_strcmp0(method_name, ""NewProblem"") == 0) { char *error = NULL; char *problem_id = handle_new_problem(g_variant_get_child_value(parameters, 0), caller_uid, &error); if (!problem_id) { g_dbus_method_invocation_return_dbus_error(invocation, ""org.freedesktop.problems.Failure"", error); free(error); return; } /* else */ response = g_variant_new(""(s)"", problem_id); g_dbus_method_invocation_return_value(invocation, response); free(problem_id); return; } if (g_strcmp0(method_name, ""GetProblems"") == 0) { GList *dirs = get_problem_dirs_for_uid(caller_uid, g_settings_dump_location); response = variant_from_string_list(dirs); list_free_with_free(dirs); g_dbus_method_invocation_return_value(invocation, response); //I was told that g_dbus_method frees the response //g_variant_unref(response); return; } if (g_strcmp0(method_name, ""GetAllProblems"") == 0) { /* - so, we have UID, - if it's 0, then we don't have to check anything and just return all directories - if uid != 0 then we want to ask for authorization */ if (caller_uid != 0) { if (polkit_check_authorization_dname(caller, ""org.freedesktop.problems.getall"") == PolkitYes) caller_uid = 0; } GList * dirs = get_problem_dirs_for_uid(caller_uid, g_settings_dump_location); response = variant_from_string_list(dirs); list_free_with_free(dirs); g_dbus_method_invocation_return_value(invocation, response); return; } if (g_strcmp0(method_name, ""GetForeignProblems"") == 0) { GList * dirs = get_problem_dirs_not_accessible_by_uid(caller_uid, g_settings_dump_location); response = variant_from_string_list(dirs); list_free_with_free(dirs); g_dbus_method_invocation_return_value(invocation, response); return; } if (g_strcmp0(method_name, ""ChownProblemDir"") == 0) { const gchar *problem_dir; g_variant_get(parameters, ""(&s)"", &problem_dir); log_notice(""problem_dir:'%s'"", problem_dir); if (!allowed_problem_dir(problem_dir)) { return_InvalidProblemDir_error(invocation, problem_dir); return; } int dir_fd = dd_openfd(problem_dir); if (dir_fd < 0) { perror_msg(""can't open problem directory '%s'"", problem_dir); return_InvalidProblemDir_error(invocation, problem_dir); return; } int ddstat = fdump_dir_stat_for_uid(dir_fd, caller_uid); if (ddstat < 0) { if (errno == ENOTDIR) { log_notice(""requested directory does not exist '%s'"", problem_dir); } else { perror_msg(""can't get stat of '%s'"", problem_dir); } return_InvalidProblemDir_error(invocation, problem_dir); close(dir_fd); return; } if (ddstat & DD_STAT_OWNED_BY_UID) { //caller seems to be in group with access to this dir, so no action needed log_notice(""caller has access to the requested directory %s"", problem_dir); g_dbus_method_invocation_return_value(invocation, NULL); close(dir_fd); return; } if ((ddstat & DD_STAT_ACCESSIBLE_BY_UID) == 0 && polkit_check_authorization_dname(caller, ""org.freedesktop.problems.getall"") != PolkitYes) { log_notice(""not authorized""); g_dbus_method_invocation_return_dbus_error(invocation, ""org.freedesktop.problems.AuthFailure"", _(""Not Authorized"")); close(dir_fd); return; } struct dump_dir *dd = dd_fdopendir(dir_fd, problem_dir, DD_OPEN_READONLY | DD_FAIL_QUIETLY_EACCES); if (!dd) { return_InvalidProblemDir_error(invocation, problem_dir); return; } int chown_res = dd_chown(dd, caller_uid); if (chown_res != 0) g_dbus_method_invocation_return_dbus_error(invocation, ""org.freedesktop.problems.ChownError"", _(""Chowning directory failed. Check system logs for more details."")); else g_dbus_method_invocation_return_value(invocation, NULL); dd_close(dd); return; } if (g_strcmp0(method_name, ""GetInfo"") == 0) { /* Parameter tuple is (sas) */ /* Get 1st param - problem dir name */ const gchar *problem_dir; g_variant_get_child(parameters, 0, ""&s"", &problem_dir); log_notice(""problem_dir:'%s'"", problem_dir); if (!allowed_problem_dir(problem_dir)) { return_InvalidProblemDir_error(invocation, problem_dir); return; } int dir_fd = dd_openfd(problem_dir); if (dir_fd < 0) { perror_msg(""can't open problem directory '%s'"", problem_dir); return_InvalidProblemDir_error(invocation, problem_dir); return; } if (!fdump_dir_accessible_by_uid(dir_fd, caller_uid)) { if (errno == ENOTDIR) { log_notice(""Requested directory does not exist '%s'"", problem_dir); return_InvalidProblemDir_error(invocation, problem_dir); close(dir_fd); return; } if (polkit_check_authorization_dname(caller, ""org.freedesktop.problems.getall"") != PolkitYes) { log_notice(""not authorized""); g_dbus_method_invocation_return_dbus_error(invocation, ""org.freedesktop.problems.AuthFailure"", _(""Not Authorized"")); close(dir_fd); return; } } struct dump_dir *dd = dd_fdopendir(dir_fd, problem_dir, DD_OPEN_READONLY | DD_FAIL_QUIETLY_EACCES); if (!dd) { return_InvalidProblemDir_error(invocation, problem_dir); return; } /* Get 2nd param - vector of element names */ GVariant *array = g_variant_get_child_value(parameters, 1); GList *elements = string_list_from_variant(array); g_variant_unref(array); GVariantBuilder *builder = NULL; for (GList *l = elements; l; l = l->next) { const char *element_name = (const char*)l->data; char *value = dd_load_text_ext(dd, element_name, 0 | DD_LOAD_TEXT_RETURN_NULL_ON_FAILURE | DD_FAIL_QUIETLY_ENOENT | DD_FAIL_QUIETLY_EACCES); log_notice(""element '%s' %s"", element_name, value ? ""fetched"" : ""not found""); if (value) { if (!builder) builder = g_variant_builder_new(G_VARIANT_TYPE_ARRAY); /* g_variant_builder_add makes a copy. No need to xstrdup here */ g_variant_builder_add(builder, ""{ss}"", element_name, value); free(value); } } list_free_with_free(elements); dd_close(dd); /* It is OK to call g_variant_new(""(a{ss})"", NULL) because */ /* G_VARIANT_TYPE_TUPLE allows NULL value */ GVariant *response = g_variant_new(""(a{ss})"", builder); if (builder) g_variant_builder_unref(builder); log_info(""GetInfo: returning value for '%s'"", problem_dir); g_dbus_method_invocation_return_value(invocation, response); return; } if (g_strcmp0(method_name, ""SetElement"") == 0) { const char *problem_id; const char *element; const char *value; g_variant_get(parameters, ""(&s&s&s)"", &problem_id, &element, &value); if (!allowed_problem_dir(problem_id)) { return_InvalidProblemDir_error(invocation, problem_id); return; } if (!str_is_correct_filename(element)) { log_notice(""'%s' is not a valid element name of '%s'"", element, problem_id); char *error = xasprintf(_(""'%s' is not a valid element name""), element); g_dbus_method_invocation_return_dbus_error(invocation, ""org.freedesktop.problems.InvalidElement"", error); free(error); return; } struct dump_dir *dd = open_directory_for_modification_of_element( invocation, caller_uid, problem_id, element); if (!dd) /* Already logged from open_directory_for_modification_of_element() */ return; /* Is it good idea to make it static? Is it possible to change the max size while a single run? */ const double max_dir_size = g_settings_nMaxCrashReportsSize * (1024 * 1024); const long item_size = dd_get_item_size(dd, element); if (item_size < 0) { log_notice(""Can't get size of '%s/%s'"", problem_id, element); char *error = xasprintf(_(""Can't get size of '%s'""), element); g_dbus_method_invocation_return_dbus_error(invocation, ""org.freedesktop.problems.Failure"", error); return; } const double requested_size = (double)strlen(value) - item_size; /* Don't want to check the size limit in case of reducing of size */ if (requested_size > 0 && requested_size > (max_dir_size - get_dirsize(g_settings_dump_location))) { log_notice(""No problem space left in '%s' (requested Bytes %f)"", problem_id, requested_size); g_dbus_method_invocation_return_dbus_error(invocation, ""org.freedesktop.problems.Failure"", _(""No problem space left"")); } else { dd_save_text(dd, element, value); g_dbus_method_invocation_return_value(invocation, NULL); } dd_close(dd); return; } if (g_strcmp0(method_name, ""DeleteElement"") == 0) { const char *problem_id; const char *element; g_variant_get(parameters, ""(&s&s)"", &problem_id, &element); if (!allowed_problem_dir(problem_id)) { return_InvalidProblemDir_error(invocation, problem_id); return; } if (!str_is_correct_filename(element)) { log_notice(""'%s' is not a valid element name of '%s'"", element, problem_id); char *error = xasprintf(_(""'%s' is not a valid element name""), element); g_dbus_method_invocation_return_dbus_error(invocation, ""org.freedesktop.problems.InvalidElement"", error); free(error); return; } struct dump_dir *dd = open_directory_for_modification_of_element( invocation, caller_uid, problem_id, element); if (!dd) /* Already logged from open_directory_for_modification_of_element() */ return; const int res = dd_delete_item(dd, element); dd_close(dd); if (res != 0) { log_notice(""Can't delete the element '%s' from the problem directory '%s'"", element, problem_id); char *error = xasprintf(_(""Can't delete the element '%s' from the problem directory '%s'""), element, problem_id); g_dbus_method_invocation_return_dbus_error(invocation, ""org.freedesktop.problems.Failure"", error); free(error); return; } g_dbus_method_invocation_return_value(invocation, NULL); return; } if (g_strcmp0(method_name, ""DeleteProblem"") == 0) { /* Dbus parameters are always tuples. * In this case, it's (as) - a tuple of one element (array of strings). * Need to fetch the array: */ GVariant *array = g_variant_get_child_value(parameters, 0); GList *problem_dirs = string_list_from_variant(array); g_variant_unref(array); for (GList *l = problem_dirs; l; l = l->next) { const char *dir_name = (const char*)l->data; log_notice(""dir_name:'%s'"", dir_name); if (!allowed_problem_dir(dir_name)) { return_InvalidProblemDir_error(invocation, dir_name); goto ret; } } for (GList *l = problem_dirs; l; l = l->next) { const char *dir_name = (const char*)l->data; int dir_fd = dd_openfd(dir_name); if (dir_fd < 0) { perror_msg(""can't open problem directory '%s'"", dir_name); return_InvalidProblemDir_error(invocation, dir_name); return; } if (!fdump_dir_accessible_by_uid(dir_fd, caller_uid)) { if (errno == ENOTDIR) { log_notice(""Requested directory does not exist '%s'"", dir_name); close(dir_fd); continue; } if (polkit_check_authorization_dname(caller, ""org.freedesktop.problems.getall"") != PolkitYes) { // if user didn't provide correct credentials, just move to the next dir close(dir_fd); continue; } } struct dump_dir *dd = dd_fdopendir(dir_fd, dir_name, /*flags:*/ 0); if (dd) { if (dd_delete(dd) != 0) { error_msg(""Failed to delete problem directory '%s'"", dir_name); dd_close(dd); } } } g_dbus_method_invocation_return_value(invocation, NULL); ret: list_free_with_free(problem_dirs); return; } if (g_strcmp0(method_name, ""FindProblemByElementInTimeRange"") == 0) { const gchar *element; const gchar *value; glong timestamp_from; glong timestamp_to; gboolean all; g_variant_get_child(parameters, 0, ""&s"", &element); g_variant_get_child(parameters, 1, ""&s"", &value); g_variant_get_child(parameters, 2, ""x"", ×tamp_from); g_variant_get_child(parameters, 3, ""x"", ×tamp_to); g_variant_get_child(parameters, 4, ""b"", &all); if (!str_is_correct_filename(element)) { log_notice(""'%s' is not a valid element name"", element); char *error = xasprintf(_(""'%s' is not a valid element name""), element); g_dbus_method_invocation_return_dbus_error(invocation, ""org.freedesktop.problems.InvalidElement"", error); free(error); return; } if (all && polkit_check_authorization_dname(caller, ""org.freedesktop.problems.getall"") == PolkitYes) caller_uid = 0; GList *dirs = get_problem_dirs_for_element_in_time(caller_uid, element, value, timestamp_from, timestamp_to); response = variant_from_string_list(dirs); list_free_with_free(dirs); g_dbus_method_invocation_return_value(invocation, response); return; } if (g_strcmp0(method_name, ""Quit"") == 0) { g_dbus_method_invocation_return_value(invocation, NULL); g_main_loop_quit(loop); return; } }","{'deleted': [], 'added': [{'line_no': 259, 'char_start': 9073, 'char_end': 9119, 'line': ' if (!allowed_problem_dir(problem_id))\n'}, {'line_no': 260, 'char_start': 9119, 'char_end': 9129, 'line': ' {\n'}, {'line_no': 261, 'char_start': 9129, 'char_end': 9197, 'line': ' return_InvalidProblemDir_error(invocation, problem_id);\n'}, {'line_no': 262, 'char_start': 9197, 'char_end': 9217, 'line': ' return;\n'}, {'line_no': 263, 'char_start': 9217, 'char_end': 9227, 'line': ' }\n'}, {'line_no': 264, 'char_start': 9227, 'char_end': 9228, 'line': '\n'}, {'line_no': 324, 'char_start': 11714, 'char_end': 11760, 'line': ' if (!allowed_problem_dir(problem_id))\n'}, {'line_no': 325, 'char_start': 11760, 'char_end': 11770, 'line': ' {\n'}, {'line_no': 326, 'char_start': 11770, 'char_end': 11838, 'line': ' return_InvalidProblemDir_error(invocation, problem_id);\n'}, {'line_no': 327, 'char_start': 11838, 'char_end': 11858, 'line': ' return;\n'}, {'line_no': 328, 'char_start': 11858, 'char_end': 11868, 'line': ' }\n'}, {'line_no': 329, 'char_start': 11868, 'char_end': 11869, 'line': '\n'}, {'line_no': 447, 'char_start': 16070, 'char_end': 16117, 'line': ' if (!str_is_correct_filename(element))\n'}, {'line_no': 448, 'char_start': 16117, 'char_end': 16127, 'line': ' {\n'}, {'line_no': 449, 'char_start': 16127, 'char_end': 16196, 'line': ' log_notice(""\'%s\' is not a valid element name"", element);\n'}, {'line_no': 450, 'char_start': 16196, 'char_end': 16281, 'line': ' char *error = xasprintf(_(""\'%s\' is not a valid element name""), element);\n'}, {'line_no': 451, 'char_start': 16281, 'char_end': 16348, 'line': ' g_dbus_method_invocation_return_dbus_error(invocation,\n'}, {'line_no': 452, 'char_start': 16348, 'char_end': 16437, 'line': ' ""org.freedesktop.problems.InvalidElement"",\n'}, {'line_no': 453, 'char_start': 16437, 'char_end': 16491, 'line': ' error);\n'}, {'line_no': 454, 'char_start': 16491, 'char_end': 16492, 'line': '\n'}, {'line_no': 455, 'char_start': 16492, 'char_end': 16517, 'line': ' free(error);\n'}, {'line_no': 456, 'char_start': 16517, 'char_end': 16537, 'line': ' return;\n'}, {'line_no': 457, 'char_start': 16537, 'char_end': 16547, 'line': ' }\n'}, {'line_no': 458, 'char_start': 16547, 'char_end': 16548, 'line': '\n'}]}","{'deleted': [], 'added': [{'char_start': 9086, 'char_end': 9241, 'chars': 'allowed_problem_dir(problem_id))\n {\n return_InvalidProblemDir_error(invocation, problem_id);\n return;\n }\n\n if (!'}, {'char_start': 11712, 'char_end': 11867, 'chars': '\n\n if (!allowed_problem_dir(problem_id))\n {\n return_InvalidProblemDir_error(invocation, problem_id);\n return;\n }'}, {'char_start': 16068, 'char_end': 16546, 'chars': '\n\n if (!str_is_correct_filename(element))\n {\n log_notice(""\'%s\' is not a valid element name"", element);\n char *error = xasprintf(_(""\'%s\' is not a valid element name""), element);\n g_dbus_method_invocation_return_dbus_error(invocation,\n ""org.freedesktop.problems.InvalidElement"",\n error);\n\n free(error);\n return;\n }'}]}",github.com/abrt/abrt/commit/7a47f57975be0d285a2f20758e4572dca6d9cdd3,src/dbus/abrt-dbus.c,cwe-022,3466 cwe-476,archive_acl_from_text_l,"archive_acl_from_text_l(struct archive_acl *acl, const char *text, int want_type, struct archive_string_conv *sc) { struct { const char *start; const char *end; } field[6], name; const char *s, *st; int numfields, fields, n, r, sol, ret; int type, types, tag, permset, id; size_t len; char sep; switch (want_type) { case ARCHIVE_ENTRY_ACL_TYPE_POSIX1E: want_type = ARCHIVE_ENTRY_ACL_TYPE_ACCESS; __LA_FALLTHROUGH; case ARCHIVE_ENTRY_ACL_TYPE_ACCESS: case ARCHIVE_ENTRY_ACL_TYPE_DEFAULT: numfields = 5; break; case ARCHIVE_ENTRY_ACL_TYPE_NFS4: numfields = 6; break; default: return (ARCHIVE_FATAL); } ret = ARCHIVE_OK; types = 0; while (text != NULL && *text != '\0') { /* * Parse the fields out of the next entry, * advance 'text' to start of next entry. */ fields = 0; do { const char *start, *end; next_field(&text, &start, &end, &sep); if (fields < numfields) { field[fields].start = start; field[fields].end = end; } ++fields; } while (sep == ':'); /* Set remaining fields to blank. */ for (n = fields; n < numfields; ++n) field[n].start = field[n].end = NULL; if (field[0].start != NULL && *(field[0].start) == '#') { /* Comment, skip entry */ continue; } n = 0; sol = 0; id = -1; permset = 0; name.start = name.end = NULL; if (want_type != ARCHIVE_ENTRY_ACL_TYPE_NFS4) { /* POSIX.1e ACLs */ /* * Default keyword ""default:user::rwx"" * if found, we have one more field * * We also support old Solaris extension: * ""defaultuser::rwx"" is the default ACL corresponding * to ""user::rwx"", etc. valid only for first field */ s = field[0].start; len = field[0].end - field[0].start; if (*s == 'd' && (len == 1 || (len >= 7 && memcmp((s + 1), ""efault"", 6) == 0))) { type = ARCHIVE_ENTRY_ACL_TYPE_DEFAULT; if (len > 7) field[0].start += 7; else n = 1; } else type = want_type; /* Check for a numeric ID in field n+1 or n+3. */ isint(field[n + 1].start, field[n + 1].end, &id); /* Field n+3 is optional. */ if (id == -1 && fields > (n + 3)) isint(field[n + 3].start, field[n + 3].end, &id); tag = 0; s = field[n].start; st = field[n].start + 1; len = field[n].end - field[n].start; switch (*s) { case 'u': if (len == 1 || (len == 4 && memcmp(st, ""ser"", 3) == 0)) tag = ARCHIVE_ENTRY_ACL_USER_OBJ; break; case 'g': if (len == 1 || (len == 5 && memcmp(st, ""roup"", 4) == 0)) tag = ARCHIVE_ENTRY_ACL_GROUP_OBJ; break; case 'o': if (len == 1 || (len == 5 && memcmp(st, ""ther"", 4) == 0)) tag = ARCHIVE_ENTRY_ACL_OTHER; break; case 'm': if (len == 1 || (len == 4 && memcmp(st, ""ask"", 3) == 0)) tag = ARCHIVE_ENTRY_ACL_MASK; break; default: break; } switch (tag) { case ARCHIVE_ENTRY_ACL_OTHER: case ARCHIVE_ENTRY_ACL_MASK: if (fields == (n + 2) && field[n + 1].start < field[n + 1].end && ismode(field[n + 1].start, field[n + 1].end, &permset)) { /* This is Solaris-style ""other:rwx"" */ sol = 1; } else if (fields == (n + 3) && field[n + 1].start < field[n + 1].end) { /* Invalid mask or other field */ ret = ARCHIVE_WARN; continue; } break; case ARCHIVE_ENTRY_ACL_USER_OBJ: case ARCHIVE_ENTRY_ACL_GROUP_OBJ: if (id != -1 || field[n + 1].start < field[n + 1].end) { name = field[n + 1]; if (tag == ARCHIVE_ENTRY_ACL_USER_OBJ) tag = ARCHIVE_ENTRY_ACL_USER; else tag = ARCHIVE_ENTRY_ACL_GROUP; } break; default: /* Invalid tag, skip entry */ ret = ARCHIVE_WARN; continue; } /* * Without ""default:"" we expect mode in field 3 * Exception: Solaris other and mask fields */ if (permset == 0 && !ismode(field[n + 2 - sol].start, field[n + 2 - sol].end, &permset)) { /* Invalid mode, skip entry */ ret = ARCHIVE_WARN; continue; } } else { /* NFS4 ACLs */ s = field[0].start; len = field[0].end - field[0].start; tag = 0; switch (len) { case 4: if (memcmp(s, ""user"", 4) == 0) tag = ARCHIVE_ENTRY_ACL_USER; break; case 5: if (memcmp(s, ""group"", 5) == 0) tag = ARCHIVE_ENTRY_ACL_GROUP; break; case 6: if (memcmp(s, ""owner@"", 6) == 0) tag = ARCHIVE_ENTRY_ACL_USER_OBJ; else if (memcmp(s, ""group@"", 6) == 0) tag = ARCHIVE_ENTRY_ACL_GROUP_OBJ; break; case 9: if (memcmp(s, ""everyone@"", 9) == 0) tag = ARCHIVE_ENTRY_ACL_EVERYONE; break; default: break; } if (tag == 0) { /* Invalid tag, skip entry */ ret = ARCHIVE_WARN; continue; } else if (tag == ARCHIVE_ENTRY_ACL_USER || tag == ARCHIVE_ENTRY_ACL_GROUP) { n = 1; name = field[1]; isint(name.start, name.end, &id); } else n = 0; if (!is_nfs4_perms(field[1 + n].start, field[1 + n].end, &permset)) { /* Invalid NFSv4 perms, skip entry */ ret = ARCHIVE_WARN; continue; } if (!is_nfs4_flags(field[2 + n].start, field[2 + n].end, &permset)) { /* Invalid NFSv4 flags, skip entry */ ret = ARCHIVE_WARN; continue; } s = field[3 + n].start; len = field[3 + n].end - field[3 + n].start; type = 0; if (len == 4) { if (memcmp(s, ""deny"", 4) == 0) type = ARCHIVE_ENTRY_ACL_TYPE_DENY; } else if (len == 5) { if (memcmp(s, ""allow"", 5) == 0) type = ARCHIVE_ENTRY_ACL_TYPE_ALLOW; else if (memcmp(s, ""audit"", 5) == 0) type = ARCHIVE_ENTRY_ACL_TYPE_AUDIT; else if (memcmp(s, ""alarm"", 5) == 0) type = ARCHIVE_ENTRY_ACL_TYPE_ALARM; } if (type == 0) { /* Invalid entry type, skip entry */ ret = ARCHIVE_WARN; continue; } isint(field[4 + n].start, field[4 + n].end, &id); } /* Add entry to the internal list. */ r = archive_acl_add_entry_len_l(acl, type, permset, tag, id, name.start, name.end - name.start, sc); if (r < ARCHIVE_WARN) return (r); if (r != ARCHIVE_OK) ret = ARCHIVE_WARN; types |= type; } /* Reset ACL */ archive_acl_reset(acl, types); return (ret); }","archive_acl_from_text_l(struct archive_acl *acl, const char *text, int want_type, struct archive_string_conv *sc) { struct { const char *start; const char *end; } field[6], name; const char *s, *st; int numfields, fields, n, r, sol, ret; int type, types, tag, permset, id; size_t len; char sep; switch (want_type) { case ARCHIVE_ENTRY_ACL_TYPE_POSIX1E: want_type = ARCHIVE_ENTRY_ACL_TYPE_ACCESS; __LA_FALLTHROUGH; case ARCHIVE_ENTRY_ACL_TYPE_ACCESS: case ARCHIVE_ENTRY_ACL_TYPE_DEFAULT: numfields = 5; break; case ARCHIVE_ENTRY_ACL_TYPE_NFS4: numfields = 6; break; default: return (ARCHIVE_FATAL); } ret = ARCHIVE_OK; types = 0; while (text != NULL && *text != '\0') { /* * Parse the fields out of the next entry, * advance 'text' to start of next entry. */ fields = 0; do { const char *start, *end; next_field(&text, &start, &end, &sep); if (fields < numfields) { field[fields].start = start; field[fields].end = end; } ++fields; } while (sep == ':'); /* Set remaining fields to blank. */ for (n = fields; n < numfields; ++n) field[n].start = field[n].end = NULL; if (field[0].start != NULL && *(field[0].start) == '#') { /* Comment, skip entry */ continue; } n = 0; sol = 0; id = -1; permset = 0; name.start = name.end = NULL; if (want_type != ARCHIVE_ENTRY_ACL_TYPE_NFS4) { /* POSIX.1e ACLs */ /* * Default keyword ""default:user::rwx"" * if found, we have one more field * * We also support old Solaris extension: * ""defaultuser::rwx"" is the default ACL corresponding * to ""user::rwx"", etc. valid only for first field */ s = field[0].start; len = field[0].end - field[0].start; if (*s == 'd' && (len == 1 || (len >= 7 && memcmp((s + 1), ""efault"", 6) == 0))) { type = ARCHIVE_ENTRY_ACL_TYPE_DEFAULT; if (len > 7) field[0].start += 7; else n = 1; } else type = want_type; /* Check for a numeric ID in field n+1 or n+3. */ isint(field[n + 1].start, field[n + 1].end, &id); /* Field n+3 is optional. */ if (id == -1 && fields > (n + 3)) isint(field[n + 3].start, field[n + 3].end, &id); tag = 0; s = field[n].start; st = field[n].start + 1; len = field[n].end - field[n].start; if (len == 0) { ret = ARCHIVE_WARN; continue; } switch (*s) { case 'u': if (len == 1 || (len == 4 && memcmp(st, ""ser"", 3) == 0)) tag = ARCHIVE_ENTRY_ACL_USER_OBJ; break; case 'g': if (len == 1 || (len == 5 && memcmp(st, ""roup"", 4) == 0)) tag = ARCHIVE_ENTRY_ACL_GROUP_OBJ; break; case 'o': if (len == 1 || (len == 5 && memcmp(st, ""ther"", 4) == 0)) tag = ARCHIVE_ENTRY_ACL_OTHER; break; case 'm': if (len == 1 || (len == 4 && memcmp(st, ""ask"", 3) == 0)) tag = ARCHIVE_ENTRY_ACL_MASK; break; default: break; } switch (tag) { case ARCHIVE_ENTRY_ACL_OTHER: case ARCHIVE_ENTRY_ACL_MASK: if (fields == (n + 2) && field[n + 1].start < field[n + 1].end && ismode(field[n + 1].start, field[n + 1].end, &permset)) { /* This is Solaris-style ""other:rwx"" */ sol = 1; } else if (fields == (n + 3) && field[n + 1].start < field[n + 1].end) { /* Invalid mask or other field */ ret = ARCHIVE_WARN; continue; } break; case ARCHIVE_ENTRY_ACL_USER_OBJ: case ARCHIVE_ENTRY_ACL_GROUP_OBJ: if (id != -1 || field[n + 1].start < field[n + 1].end) { name = field[n + 1]; if (tag == ARCHIVE_ENTRY_ACL_USER_OBJ) tag = ARCHIVE_ENTRY_ACL_USER; else tag = ARCHIVE_ENTRY_ACL_GROUP; } break; default: /* Invalid tag, skip entry */ ret = ARCHIVE_WARN; continue; } /* * Without ""default:"" we expect mode in field 3 * Exception: Solaris other and mask fields */ if (permset == 0 && !ismode(field[n + 2 - sol].start, field[n + 2 - sol].end, &permset)) { /* Invalid mode, skip entry */ ret = ARCHIVE_WARN; continue; } } else { /* NFS4 ACLs */ s = field[0].start; len = field[0].end - field[0].start; tag = 0; switch (len) { case 4: if (memcmp(s, ""user"", 4) == 0) tag = ARCHIVE_ENTRY_ACL_USER; break; case 5: if (memcmp(s, ""group"", 5) == 0) tag = ARCHIVE_ENTRY_ACL_GROUP; break; case 6: if (memcmp(s, ""owner@"", 6) == 0) tag = ARCHIVE_ENTRY_ACL_USER_OBJ; else if (memcmp(s, ""group@"", 6) == 0) tag = ARCHIVE_ENTRY_ACL_GROUP_OBJ; break; case 9: if (memcmp(s, ""everyone@"", 9) == 0) tag = ARCHIVE_ENTRY_ACL_EVERYONE; break; default: break; } if (tag == 0) { /* Invalid tag, skip entry */ ret = ARCHIVE_WARN; continue; } else if (tag == ARCHIVE_ENTRY_ACL_USER || tag == ARCHIVE_ENTRY_ACL_GROUP) { n = 1; name = field[1]; isint(name.start, name.end, &id); } else n = 0; if (!is_nfs4_perms(field[1 + n].start, field[1 + n].end, &permset)) { /* Invalid NFSv4 perms, skip entry */ ret = ARCHIVE_WARN; continue; } if (!is_nfs4_flags(field[2 + n].start, field[2 + n].end, &permset)) { /* Invalid NFSv4 flags, skip entry */ ret = ARCHIVE_WARN; continue; } s = field[3 + n].start; len = field[3 + n].end - field[3 + n].start; type = 0; if (len == 4) { if (memcmp(s, ""deny"", 4) == 0) type = ARCHIVE_ENTRY_ACL_TYPE_DENY; } else if (len == 5) { if (memcmp(s, ""allow"", 5) == 0) type = ARCHIVE_ENTRY_ACL_TYPE_ALLOW; else if (memcmp(s, ""audit"", 5) == 0) type = ARCHIVE_ENTRY_ACL_TYPE_AUDIT; else if (memcmp(s, ""alarm"", 5) == 0) type = ARCHIVE_ENTRY_ACL_TYPE_ALARM; } if (type == 0) { /* Invalid entry type, skip entry */ ret = ARCHIVE_WARN; continue; } isint(field[4 + n].start, field[4 + n].end, &id); } /* Add entry to the internal list. */ r = archive_acl_add_entry_len_l(acl, type, permset, tag, id, name.start, name.end - name.start, sc); if (r < ARCHIVE_WARN) return (r); if (r != ARCHIVE_OK) ret = ARCHIVE_WARN; types |= type; } /* Reset ACL */ archive_acl_reset(acl, types); return (ret); }","{'deleted': [], 'added': [{'line_no': 98, 'char_start': 2311, 'char_end': 2330, 'line': '\t\t\tif (len == 0) {\n'}, {'line_no': 99, 'char_start': 2330, 'char_end': 2354, 'line': '\t\t\t\tret = ARCHIVE_WARN;\n'}, {'line_no': 100, 'char_start': 2354, 'char_end': 2368, 'line': '\t\t\t\tcontinue;\n'}, {'line_no': 101, 'char_start': 2368, 'char_end': 2373, 'line': '\t\t\t}\n'}, {'line_no': 102, 'char_start': 2373, 'char_end': 2374, 'line': '\n'}]}","{'deleted': [], 'added': [{'char_start': 2314, 'char_end': 2377, 'chars': 'if (len == 0) {\n\t\t\t\tret = ARCHIVE_WARN;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t'}]}",github.com/libarchive/libarchive/commit/15bf44fd2c1ad0e3fd87048b3fcc90c4dcff1175,libarchive/archive_acl.c,cwe-476,2072 cwe-416,sctp_do_peeloff,"int sctp_do_peeloff(struct sock *sk, sctp_assoc_t id, struct socket **sockp) { struct sctp_association *asoc = sctp_id2assoc(sk, id); struct sctp_sock *sp = sctp_sk(sk); struct socket *sock; int err = 0; if (!asoc) return -EINVAL; /* If there is a thread waiting on more sndbuf space for * sending on this asoc, it cannot be peeled. */ if (waitqueue_active(&asoc->wait)) return -EBUSY; /* An association cannot be branched off from an already peeled-off * socket, nor is this supported for tcp style sockets. */ if (!sctp_style(sk, UDP)) return -EINVAL; /* Create a new socket. */ err = sock_create(sk->sk_family, SOCK_SEQPACKET, IPPROTO_SCTP, &sock); if (err < 0) return err; sctp_copy_sock(sock->sk, sk, asoc); /* Make peeled-off sockets more like 1-1 accepted sockets. * Set the daddr and initialize id to something more random */ sp->pf->to_sk_daddr(&asoc->peer.primary_addr, sk); /* Populate the fields of the newsk from the oldsk and migrate the * asoc to the newsk. */ sctp_sock_migrate(sk, sock->sk, asoc, SCTP_SOCKET_UDP_HIGH_BANDWIDTH); *sockp = sock; return err; }","int sctp_do_peeloff(struct sock *sk, sctp_assoc_t id, struct socket **sockp) { struct sctp_association *asoc = sctp_id2assoc(sk, id); struct sctp_sock *sp = sctp_sk(sk); struct socket *sock; int err = 0; /* Do not peel off from one netns to another one. */ if (!net_eq(current->nsproxy->net_ns, sock_net(sk))) return -EINVAL; if (!asoc) return -EINVAL; /* If there is a thread waiting on more sndbuf space for * sending on this asoc, it cannot be peeled. */ if (waitqueue_active(&asoc->wait)) return -EBUSY; /* An association cannot be branched off from an already peeled-off * socket, nor is this supported for tcp style sockets. */ if (!sctp_style(sk, UDP)) return -EINVAL; /* Create a new socket. */ err = sock_create(sk->sk_family, SOCK_SEQPACKET, IPPROTO_SCTP, &sock); if (err < 0) return err; sctp_copy_sock(sock->sk, sk, asoc); /* Make peeled-off sockets more like 1-1 accepted sockets. * Set the daddr and initialize id to something more random */ sp->pf->to_sk_daddr(&asoc->peer.primary_addr, sk); /* Populate the fields of the newsk from the oldsk and migrate the * asoc to the newsk. */ sctp_sock_migrate(sk, sock->sk, asoc, SCTP_SOCKET_UDP_HIGH_BANDWIDTH); *sockp = sock; return err; }","{'deleted': [], 'added': [{'line_no': 8, 'char_start': 209, 'char_end': 263, 'line': '\t/* Do not peel off from one netns to another one. */\n'}, {'line_no': 9, 'char_start': 263, 'char_end': 317, 'line': '\tif (!net_eq(current->nsproxy->net_ns, sock_net(sk)))\n'}, {'line_no': 10, 'char_start': 317, 'char_end': 335, 'line': '\t\treturn -EINVAL;\n'}, {'line_no': 11, 'char_start': 335, 'char_end': 336, 'line': '\n'}]}","{'deleted': [], 'added': [{'char_start': 210, 'char_end': 337, 'chars': '/* Do not peel off from one netns to another one. */\n\tif (!net_eq(current->nsproxy->net_ns, sock_net(sk)))\n\t\treturn -EINVAL;\n\n\t'}]}",github.com/torvalds/linux/commit/df80cd9b28b9ebaa284a41df611dbf3a2d05ca74,net/sctp/socket.c,cwe-416,333 cwe-078,on_message," def on_message( self, profile_id, profile_name, level, message, timeout ): if 1 == level: cmd = ""notify-send "" if timeout > 0: cmd = cmd + "" -t %s"" % (1000 * timeout) title = ""Back In Time (%s) : %s"" % (self.user, profile_name) message = message.replace(""\n"", ' ') message = message.replace(""\r"", '') cmd = cmd + "" \""%s\"" \""%s\"""" % (title, message) print(cmd) os.system(cmd) return"," def on_message( self, profile_id, profile_name, level, message, timeout ): if 1 == level: cmd = ['notify-send'] if timeout > 0: cmd.extend(['-t', str(1000 * timeout)]) title = ""Back In Time (%s) : %s"" % (self.user, profile_name) message = message.replace(""\n"", ' ') message = message.replace(""\r"", '') cmd.append(title) cmd.append(message) subprocess.Popen(cmd).communicate() return","{'deleted': [{'line_no': 3, 'char_start': 102, 'char_end': 135, 'line': ' cmd = ""notify-send ""\n'}, {'line_no': 5, 'char_start': 163, 'char_end': 219, 'line': ' cmd = cmd + "" -t %s"" % (1000 * timeout)\n'}, {'line_no': 11, 'char_start': 391, 'char_end': 451, 'line': ' cmd = cmd + "" \\""%s\\"" \\""%s\\"""" % (title, message)\n'}, {'line_no': 12, 'char_start': 451, 'char_end': 474, 'line': ' print(cmd)\n'}, {'line_no': 13, 'char_start': 474, 'char_end': 501, 'line': ' os.system(cmd)\n'}], 'added': [{'line_no': 3, 'char_start': 102, 'char_end': 136, 'line': "" cmd = ['notify-send']\n""}, {'line_no': 5, 'char_start': 164, 'char_end': 220, 'line': "" cmd.extend(['-t', str(1000 * timeout)])\n""}, {'line_no': 11, 'char_start': 392, 'char_end': 422, 'line': ' cmd.append(title)\n'}, {'line_no': 12, 'char_start': 422, 'char_end': 454, 'line': ' cmd.append(message)\n'}, {'line_no': 13, 'char_start': 454, 'char_end': 502, 'line': ' subprocess.Popen(cmd).communicate()\n'}]}","{'deleted': [{'char_start': 120, 'char_end': 121, 'chars': '""'}, {'char_start': 132, 'char_end': 134, 'chars': ' ""'}, {'char_start': 182, 'char_end': 187, 'chars': ' = cm'}, {'char_start': 188, 'char_end': 193, 'chars': ' + "" '}, {'char_start': 196, 'char_end': 197, 'chars': '%'}, {'char_start': 198, 'char_end': 202, 'chars': '"" % '}, {'char_start': 406, 'char_end': 411, 'chars': ' = cm'}, {'char_start': 412, 'char_end': 434, 'chars': ' + "" \\""%s\\"" \\""%s\\"""" % '}, {'char_start': 440, 'char_end': 449, 'chars': ', message'}, {'char_start': 464, 'char_end': 466, 'chars': 'ri'}, {'char_start': 467, 'char_end': 468, 'chars': 't'}, {'char_start': 469, 'char_end': 470, 'chars': 'c'}, {'char_start': 471, 'char_end': 472, 'chars': 'd'}, {'char_start': 486, 'char_end': 487, 'chars': 'o'}, {'char_start': 488, 'char_end': 489, 'chars': '.'}, {'char_start': 490, 'char_end': 491, 'chars': 'y'}, {'char_start': 492, 'char_end': 493, 'chars': 't'}, {'char_start': 494, 'char_end': 495, 'chars': 'm'}], 'added': [{'char_start': 120, 'char_end': 122, 'chars': ""['""}, {'char_start': 133, 'char_end': 135, 'chars': ""']""}, {'char_start': 183, 'char_end': 189, 'chars': '.exten'}, {'char_start': 190, 'char_end': 193, 'chars': ""(['""}, {'char_start': 195, 'char_end': 197, 'chars': ""',""}, {'char_start': 199, 'char_end': 201, 'chars': 'tr'}, {'char_start': 216, 'char_end': 218, 'chars': ')]'}, {'char_start': 407, 'char_end': 413, 'chars': '.appen'}, {'char_start': 434, 'char_end': 439, 'chars': 'cmd.a'}, {'char_start': 440, 'char_end': 442, 'chars': 'pe'}, {'char_start': 443, 'char_end': 444, 'chars': 'd'}, {'char_start': 446, 'char_end': 452, 'chars': 'essage'}, {'char_start': 466, 'char_end': 471, 'chars': 'subpr'}, {'char_start': 472, 'char_end': 475, 'chars': 'ces'}, {'char_start': 477, 'char_end': 480, 'chars': 'Pop'}, {'char_start': 481, 'char_end': 482, 'chars': 'n'}, {'char_start': 486, 'char_end': 500, 'chars': ').communicate('}]}",github.com/bit-team/backintime/commit/cef81d0da93ff601252607df3db1a48f7f6f01b3,qt4/plugins/notifyplugin.py,cwe-078,130 cwe-416,kvm_ioctl_create_device,"static int kvm_ioctl_create_device(struct kvm *kvm, struct kvm_create_device *cd) { struct kvm_device_ops *ops = NULL; struct kvm_device *dev; bool test = cd->flags & KVM_CREATE_DEVICE_TEST; int ret; if (cd->type >= ARRAY_SIZE(kvm_device_ops_table)) return -ENODEV; ops = kvm_device_ops_table[cd->type]; if (ops == NULL) return -ENODEV; if (test) return 0; dev = kzalloc(sizeof(*dev), GFP_KERNEL); if (!dev) return -ENOMEM; dev->ops = ops; dev->kvm = kvm; mutex_lock(&kvm->lock); ret = ops->create(dev, cd->type); if (ret < 0) { mutex_unlock(&kvm->lock); kfree(dev); return ret; } list_add(&dev->vm_node, &kvm->devices); mutex_unlock(&kvm->lock); if (ops->init) ops->init(dev); ret = anon_inode_getfd(ops->name, &kvm_device_fops, dev, O_RDWR | O_CLOEXEC); if (ret < 0) { ops->destroy(dev); mutex_lock(&kvm->lock); list_del(&dev->vm_node); mutex_unlock(&kvm->lock); return ret; } kvm_get_kvm(kvm); cd->fd = ret; return 0; }","static int kvm_ioctl_create_device(struct kvm *kvm, struct kvm_create_device *cd) { struct kvm_device_ops *ops = NULL; struct kvm_device *dev; bool test = cd->flags & KVM_CREATE_DEVICE_TEST; int ret; if (cd->type >= ARRAY_SIZE(kvm_device_ops_table)) return -ENODEV; ops = kvm_device_ops_table[cd->type]; if (ops == NULL) return -ENODEV; if (test) return 0; dev = kzalloc(sizeof(*dev), GFP_KERNEL); if (!dev) return -ENOMEM; dev->ops = ops; dev->kvm = kvm; mutex_lock(&kvm->lock); ret = ops->create(dev, cd->type); if (ret < 0) { mutex_unlock(&kvm->lock); kfree(dev); return ret; } list_add(&dev->vm_node, &kvm->devices); mutex_unlock(&kvm->lock); if (ops->init) ops->init(dev); ret = anon_inode_getfd(ops->name, &kvm_device_fops, dev, O_RDWR | O_CLOEXEC); if (ret < 0) { mutex_lock(&kvm->lock); list_del(&dev->vm_node); mutex_unlock(&kvm->lock); ops->destroy(dev); return ret; } kvm_get_kvm(kvm); cd->fd = ret; return 0; }","{'deleted': [{'line_no': 41, 'char_start': 823, 'char_end': 844, 'line': '\t\tops->destroy(dev);\n'}], 'added': [{'line_no': 44, 'char_start': 904, 'char_end': 925, 'line': '\t\tops->destroy(dev);\n'}]}","{'deleted': [{'char_start': 825, 'char_end': 846, 'chars': 'ops->destroy(dev);\n\t\t'}], 'added': [{'char_start': 901, 'char_end': 922, 'chars': ');\n\t\tops->destroy(dev'}]}",github.com/torvalds/linux/commit/a0f1d21c1ccb1da66629627a74059dd7f5ac9c61,virt/kvm/kvm_main.c,cwe-416,314 cwe-125,glyph_cache_put,"BOOL glyph_cache_put(rdpGlyphCache* glyphCache, UINT32 id, UINT32 index, rdpGlyph* glyph) { rdpGlyph* prevGlyph; if (id > 9) { WLog_ERR(TAG, ""invalid glyph cache id: %"" PRIu32 """", id); return FALSE; } if (index > glyphCache->glyphCache[id].number) { WLog_ERR(TAG, ""invalid glyph cache index: %"" PRIu32 "" in cache id: %"" PRIu32 """", index, id); return FALSE; } WLog_Print(glyphCache->log, WLOG_DEBUG, ""GlyphCachePut: id: %"" PRIu32 "" index: %"" PRIu32 """", id, index); prevGlyph = glyphCache->glyphCache[id].entries[index]; if (prevGlyph) prevGlyph->Free(glyphCache->context, prevGlyph); glyphCache->glyphCache[id].entries[index] = glyph; return TRUE; }","BOOL glyph_cache_put(rdpGlyphCache* glyphCache, UINT32 id, UINT32 index, rdpGlyph* glyph) { rdpGlyph* prevGlyph; if (id > 9) { WLog_ERR(TAG, ""invalid glyph cache id: %"" PRIu32 """", id); return FALSE; } if (index >= glyphCache->glyphCache[id].number) { WLog_ERR(TAG, ""invalid glyph cache index: %"" PRIu32 "" in cache id: %"" PRIu32 """", index, id); return FALSE; } WLog_Print(glyphCache->log, WLOG_DEBUG, ""GlyphCachePut: id: %"" PRIu32 "" index: %"" PRIu32 """", id, index); prevGlyph = glyphCache->glyphCache[id].entries[index]; if (prevGlyph) prevGlyph->Free(glyphCache->context, prevGlyph); glyphCache->glyphCache[id].entries[index] = glyph; return TRUE; }","{'deleted': [{'line_no': 11, 'char_start': 211, 'char_end': 259, 'line': '\tif (index > glyphCache->glyphCache[id].number)\n'}], 'added': [{'line_no': 11, 'char_start': 211, 'char_end': 260, 'line': '\tif (index >= glyphCache->glyphCache[id].number)\n'}]}","{'deleted': [], 'added': [{'char_start': 223, 'char_end': 224, 'chars': '='}]}",github.com/FreeRDP/FreeRDP/commit/c0fd449ec0870b050d350d6d844b1ea6dad4bc7d,libfreerdp/cache/glyph.c,cwe-125,213 cwe-125,store_versioninfo_gnu_verdef,"static Sdb *store_versioninfo_gnu_verdef(ELFOBJ *bin, Elf_(Shdr) *shdr, int sz) { const char *section_name = """"; const char *link_section_name = """"; char *end = NULL; Elf_(Shdr) *link_shdr = NULL; ut8 dfs[sizeof (Elf_(Verdef))] = {0}; Sdb *sdb; int cnt, i; if (shdr->sh_link > bin->ehdr.e_shnum) { return false; } link_shdr = &bin->shdr[shdr->sh_link]; if (shdr->sh_size < 1) { return false; } Elf_(Verdef) *defs = calloc (shdr->sh_size, sizeof (char)); if (!defs) { return false; } if (bin->shstrtab && shdr->sh_name < bin->shstrtab_size) { section_name = &bin->shstrtab[shdr->sh_name]; } if (link_shdr && bin->shstrtab && link_shdr->sh_name < bin->shstrtab_size) { link_section_name = &bin->shstrtab[link_shdr->sh_name]; } if (!defs) { bprintf (""Warning: Cannot allocate memory (Check Elf_(Verdef))\n""); return NULL; } sdb = sdb_new0 (); end = (char *)defs + shdr->sh_size; sdb_set (sdb, ""section_name"", section_name, 0); sdb_num_set (sdb, ""entries"", shdr->sh_info, 0); sdb_num_set (sdb, ""addr"", shdr->sh_addr, 0); sdb_num_set (sdb, ""offset"", shdr->sh_offset, 0); sdb_num_set (sdb, ""link"", shdr->sh_link, 0); sdb_set (sdb, ""link_section_name"", link_section_name, 0); for (cnt = 0, i = 0; i >= 0 && cnt < shdr->sh_info && ((char *)defs + i < end); ++cnt) { Sdb *sdb_verdef = sdb_new0 (); char *vstart = ((char*)defs) + i; char key[32] = {0}; Elf_(Verdef) *verdef = (Elf_(Verdef)*)vstart; Elf_(Verdaux) aux = {0}; int j = 0; int isum = 0; r_buf_read_at (bin->b, shdr->sh_offset + i, dfs, sizeof (Elf_(Verdef))); verdef->vd_version = READ16 (dfs, j) verdef->vd_flags = READ16 (dfs, j) verdef->vd_ndx = READ16 (dfs, j) verdef->vd_cnt = READ16 (dfs, j) verdef->vd_hash = READ32 (dfs, j) verdef->vd_aux = READ32 (dfs, j) verdef->vd_next = READ32 (dfs, j) vstart += verdef->vd_aux; if (vstart > end || vstart + sizeof (Elf_(Verdaux)) > end) { sdb_free (sdb_verdef); goto out_error; } j = 0; aux.vda_name = READ32 (vstart, j) aux.vda_next = READ32 (vstart, j) isum = i + verdef->vd_aux; if (aux.vda_name > bin->dynstr_size) { sdb_free (sdb_verdef); goto out_error; } sdb_num_set (sdb_verdef, ""idx"", i, 0); sdb_num_set (sdb_verdef, ""vd_version"", verdef->vd_version, 0); sdb_num_set (sdb_verdef, ""vd_ndx"", verdef->vd_ndx, 0); sdb_num_set (sdb_verdef, ""vd_cnt"", verdef->vd_cnt, 0); sdb_set (sdb_verdef, ""vda_name"", &bin->dynstr[aux.vda_name], 0); sdb_set (sdb_verdef, ""flags"", get_ver_flags (verdef->vd_flags), 0); for (j = 1; j < verdef->vd_cnt; ++j) { int k; Sdb *sdb_parent = sdb_new0 (); isum += aux.vda_next; vstart += aux.vda_next; if (vstart > end || vstart + sizeof(Elf_(Verdaux)) > end) { sdb_free (sdb_verdef); sdb_free (sdb_parent); goto out_error; } k = 0; aux.vda_name = READ32 (vstart, k) aux.vda_next = READ32 (vstart, k) if (aux.vda_name > bin->dynstr_size) { sdb_free (sdb_verdef); sdb_free (sdb_parent); goto out_error; } sdb_num_set (sdb_parent, ""idx"", isum, 0); sdb_num_set (sdb_parent, ""parent"", j, 0); sdb_set (sdb_parent, ""vda_name"", &bin->dynstr[aux.vda_name], 0); snprintf (key, sizeof (key), ""parent%d"", j - 1); sdb_ns_set (sdb_verdef, key, sdb_parent); } snprintf (key, sizeof (key), ""verdef%d"", cnt); sdb_ns_set (sdb, key, sdb_verdef); if (!verdef->vd_next) { sdb_free (sdb_verdef); goto out_error; } if ((st32)verdef->vd_next < 1) { eprintf (""Warning: Invalid vd_next in the ELF version\n""); break; } i += verdef->vd_next; } free (defs); return sdb; out_error: free (defs); sdb_free (sdb); return NULL; }","static Sdb *store_versioninfo_gnu_verdef(ELFOBJ *bin, Elf_(Shdr) *shdr, int sz) { const char *section_name = """"; const char *link_section_name = """"; char *end = NULL; Elf_(Shdr) *link_shdr = NULL; ut8 dfs[sizeof (Elf_(Verdef))] = {0}; Sdb *sdb; int cnt, i; if (shdr->sh_link > bin->ehdr.e_shnum) { return false; } link_shdr = &bin->shdr[shdr->sh_link]; if (shdr->sh_size < 1) { return false; } Elf_(Verdef) *defs = calloc (shdr->sh_size, sizeof (char)); if (!defs) { return false; } if (bin->shstrtab && shdr->sh_name < bin->shstrtab_size) { section_name = &bin->shstrtab[shdr->sh_name]; } if (link_shdr && bin->shstrtab && link_shdr->sh_name < bin->shstrtab_size) { link_section_name = &bin->shstrtab[link_shdr->sh_name]; } if (!defs) { bprintf (""Warning: Cannot allocate memory (Check Elf_(Verdef))\n""); return NULL; } sdb = sdb_new0 (); end = (char *)defs + shdr->sh_size; sdb_set (sdb, ""section_name"", section_name, 0); sdb_num_set (sdb, ""entries"", shdr->sh_info, 0); sdb_num_set (sdb, ""addr"", shdr->sh_addr, 0); sdb_num_set (sdb, ""offset"", shdr->sh_offset, 0); sdb_num_set (sdb, ""link"", shdr->sh_link, 0); sdb_set (sdb, ""link_section_name"", link_section_name, 0); for (cnt = 0, i = 0; i >= 0 && cnt < shdr->sh_info && ((char *)defs + i < end); ++cnt) { Sdb *sdb_verdef = sdb_new0 (); char *vstart = ((char*)defs) + i; char key[32] = {0}; Elf_(Verdef) *verdef = (Elf_(Verdef)*)vstart; Elf_(Verdaux) aux = {0}; int j = 0; int isum = 0; r_buf_read_at (bin->b, shdr->sh_offset + i, dfs, sizeof (Elf_(Verdef))); verdef->vd_version = READ16 (dfs, j) verdef->vd_flags = READ16 (dfs, j) verdef->vd_ndx = READ16 (dfs, j) verdef->vd_cnt = READ16 (dfs, j) verdef->vd_hash = READ32 (dfs, j) verdef->vd_aux = READ32 (dfs, j) verdef->vd_next = READ32 (dfs, j) int vdaux = verdef->vd_aux; if (vdaux < 1) { sdb_free (sdb_verdef); goto out_error; } vstart += vdaux; if (vstart > end || vstart + sizeof (Elf_(Verdaux)) > end) { sdb_free (sdb_verdef); goto out_error; } j = 0; aux.vda_name = READ32 (vstart, j) aux.vda_next = READ32 (vstart, j) isum = i + verdef->vd_aux; if (aux.vda_name > bin->dynstr_size) { sdb_free (sdb_verdef); goto out_error; } sdb_num_set (sdb_verdef, ""idx"", i, 0); sdb_num_set (sdb_verdef, ""vd_version"", verdef->vd_version, 0); sdb_num_set (sdb_verdef, ""vd_ndx"", verdef->vd_ndx, 0); sdb_num_set (sdb_verdef, ""vd_cnt"", verdef->vd_cnt, 0); sdb_set (sdb_verdef, ""vda_name"", &bin->dynstr[aux.vda_name], 0); sdb_set (sdb_verdef, ""flags"", get_ver_flags (verdef->vd_flags), 0); for (j = 1; j < verdef->vd_cnt; ++j) { int k; Sdb *sdb_parent = sdb_new0 (); isum += aux.vda_next; vstart += aux.vda_next; if (vstart > end || vstart + sizeof(Elf_(Verdaux)) > end) { sdb_free (sdb_verdef); sdb_free (sdb_parent); goto out_error; } k = 0; aux.vda_name = READ32 (vstart, k) aux.vda_next = READ32 (vstart, k) if (aux.vda_name > bin->dynstr_size) { sdb_free (sdb_verdef); sdb_free (sdb_parent); goto out_error; } sdb_num_set (sdb_parent, ""idx"", isum, 0); sdb_num_set (sdb_parent, ""parent"", j, 0); sdb_set (sdb_parent, ""vda_name"", &bin->dynstr[aux.vda_name], 0); snprintf (key, sizeof (key), ""parent%d"", j - 1); sdb_ns_set (sdb_verdef, key, sdb_parent); } snprintf (key, sizeof (key), ""verdef%d"", cnt); sdb_ns_set (sdb, key, sdb_verdef); if (!verdef->vd_next) { sdb_free (sdb_verdef); goto out_error; } if ((st32)verdef->vd_next < 1) { eprintf (""Warning: Invalid vd_next in the ELF version\n""); break; } i += verdef->vd_next; } free (defs); return sdb; out_error: free (defs); sdb_free (sdb); return NULL; }","{'deleted': [{'line_no': 56, 'char_start': 1827, 'char_end': 1855, 'line': '\t\tvstart += verdef->vd_aux;\n'}], 'added': [{'line_no': 56, 'char_start': 1827, 'char_end': 1857, 'line': '\t\tint vdaux = verdef->vd_aux;\n'}, {'line_no': 57, 'char_start': 1857, 'char_end': 1876, 'line': '\t\tif (vdaux < 1) {\n'}, {'line_no': 58, 'char_start': 1876, 'char_end': 1902, 'line': '\t\t\tsdb_free (sdb_verdef);\n'}, {'line_no': 59, 'char_start': 1902, 'char_end': 1921, 'line': '\t\t\tgoto out_error;\n'}, {'line_no': 60, 'char_start': 1921, 'char_end': 1925, 'line': '\t\t}\n'}, {'line_no': 61, 'char_start': 1925, 'char_end': 1944, 'line': '\t\tvstart += vdaux;\n'}]}","{'deleted': [{'char_start': 1829, 'char_end': 1831, 'chars': 'vs'}, {'char_start': 1833, 'char_end': 1835, 'chars': 'rt'}, {'char_start': 1836, 'char_end': 1837, 'chars': '+'}], 'added': [{'char_start': 1829, 'char_end': 1833, 'chars': 'int '}, {'char_start': 1834, 'char_end': 1835, 'chars': 'd'}, {'char_start': 1836, 'char_end': 1838, 'chars': 'ux'}, {'char_start': 1852, 'char_end': 1939, 'chars': 'aux;\n\t\tif (vdaux < 1) {\n\t\t\tsdb_free (sdb_verdef);\n\t\t\tgoto out_error;\n\t\t}\n\t\tvstart += vd'}]}",github.com/radare/radare2/commit/44ded3ff35b8264f54b5a900cab32ec489d9e5b9,libr/bin/format/elf/elf.c,cwe-125,1404 cwe-022,is_cgi," def is_cgi(self): """"""Test whether self.path corresponds to a CGI script, and return a boolean. This function sets self.cgi_info to a tuple (dir, rest) when it returns True, where dir is the directory part before the CGI script name. Note that rest begins with a slash if it is not empty. The default implementation tests whether the path begins with one of the strings in the list self.cgi_directories (and the next character is a '/' or the end of the string). """""" path = self.path for x in self.cgi_directories: i = len(x) if path[:i] == x and (not path[i:] or path[i] == '/'): self.cgi_info = path[:i], path[i+1:] return True return False"," def is_cgi(self): """"""Test whether self.path corresponds to a CGI script. Returns True and updates the cgi_info attribute to the tuple (dir, rest) if self.path requires running a CGI script. Returns False otherwise. The default implementation tests whether the normalized url path begins with one of the strings in self.cgi_directories (and the next character is a '/' or the end of the string). """""" splitpath = _url_collapse_path_split(self.path) if splitpath[0] in self.cgi_directories: self.cgi_info = splitpath return True return False","{'deleted': [{'line_no': 2, 'char_start': 22, 'char_end': 85, 'line': ' """"""Test whether self.path corresponds to a CGI script,\n'}, {'line_no': 3, 'char_start': 85, 'char_end': 115, 'line': ' and return a boolean.\n'}, {'line_no': 4, 'char_start': 115, 'char_end': 116, 'line': '\n'}, {'line_no': 5, 'char_start': 116, 'char_end': 180, 'line': ' This function sets self.cgi_info to a tuple (dir, rest)\n'}, {'line_no': 6, 'char_start': 180, 'char_end': 249, 'line': ' when it returns True, where dir is the directory part before\n'}, {'line_no': 7, 'char_start': 249, 'char_end': 308, 'line': ' the CGI script name. Note that rest begins with a\n'}, {'line_no': 8, 'char_start': 308, 'char_end': 342, 'line': ' slash if it is not empty.\n'}, {'line_no': 9, 'char_start': 342, 'char_end': 343, 'line': '\n'}, {'line_no': 10, 'char_start': 343, 'char_end': 401, 'line': ' The default implementation tests whether the path\n'}, {'line_no': 11, 'char_start': 401, 'char_end': 452, 'line': ' begins with one of the strings in the list\n'}, {'line_no': 12, 'char_start': 452, 'char_end': 514, 'line': "" self.cgi_directories (and the next character is a '/'\n""}, {'line_no': 13, 'char_start': 514, 'char_end': 549, 'line': ' or the end of the string).\n'}, {'line_no': 14, 'char_start': 549, 'char_end': 561, 'line': ' """"""\n'}, {'line_no': 16, 'char_start': 562, 'char_end': 587, 'line': ' path = self.path\n'}, {'line_no': 18, 'char_start': 588, 'char_end': 627, 'line': ' for x in self.cgi_directories:\n'}, {'line_no': 19, 'char_start': 627, 'char_end': 650, 'line': ' i = len(x)\n'}, {'line_no': 20, 'char_start': 650, 'char_end': 717, 'line': "" if path[:i] == x and (not path[i:] or path[i] == '/'):\n""}, {'line_no': 21, 'char_start': 717, 'char_end': 770, 'line': ' self.cgi_info = path[:i], path[i+1:]\n'}, {'line_no': 22, 'char_start': 770, 'char_end': 798, 'line': ' return True\n'}], 'added': [{'line_no': 2, 'char_start': 22, 'char_end': 85, 'line': ' """"""Test whether self.path corresponds to a CGI script.\n'}, {'line_no': 4, 'char_start': 86, 'char_end': 155, 'line': ' Returns True and updates the cgi_info attribute to the tuple\n'}, {'line_no': 5, 'char_start': 155, 'char_end': 219, 'line': ' (dir, rest) if self.path requires running a CGI script.\n'}, {'line_no': 6, 'char_start': 219, 'char_end': 252, 'line': ' Returns False otherwise.\n'}, {'line_no': 8, 'char_start': 253, 'char_end': 321, 'line': ' The default implementation tests whether the normalized url\n'}, {'line_no': 9, 'char_start': 321, 'char_end': 389, 'line': ' path begins with one of the strings in self.cgi_directories\n'}, {'line_no': 10, 'char_start': 389, 'char_end': 457, 'line': "" (and the next character is a '/' or the end of the string).\n""}, {'line_no': 11, 'char_start': 457, 'char_end': 469, 'line': ' """"""\n'}, {'line_no': 12, 'char_start': 469, 'char_end': 525, 'line': ' splitpath = _url_collapse_path_split(self.path)\n'}, {'line_no': 13, 'char_start': 525, 'char_end': 574, 'line': ' if splitpath[0] in self.cgi_directories:\n'}, {'line_no': 14, 'char_start': 574, 'char_end': 612, 'line': ' self.cgi_info = splitpath\n'}, {'line_no': 15, 'char_start': 612, 'char_end': 636, 'line': ' return True\n'}]}","{'deleted': [{'char_start': 83, 'char_end': 84, 'chars': ','}, {'char_start': 93, 'char_end': 98, 'chars': 'and r'}, {'char_start': 104, 'char_end': 110, 'chars': 'a bool'}, {'char_start': 113, 'char_end': 120, 'chars': '.\n\n '}, {'char_start': 121, 'char_end': 130, 'chars': ' This f'}, {'char_start': 131, 'char_end': 133, 'chars': 'nc'}, {'char_start': 134, 'char_end': 139, 'chars': 'ion s'}, {'char_start': 140, 'char_end': 141, 'chars': 't'}, {'char_start': 143, 'char_end': 144, 'chars': 's'}, {'char_start': 145, 'char_end': 148, 'chars': 'lf.'}, {'char_start': 160, 'char_end': 161, 'chars': 'a'}, {'char_start': 167, 'char_end': 179, 'chars': ' (dir, rest)'}, {'char_start': 188, 'char_end': 193, 'chars': 'when '}, {'char_start': 194, 'char_end': 196, 'chars': 't '}, {'char_start': 197, 'char_end': 208, 'chars': 'eturns True'}, {'char_start': 210, 'char_end': 213, 'chars': 'whe'}, {'char_start': 215, 'char_end': 221, 'chars': ' dir i'}, {'char_start': 222, 'char_end': 223, 'chars': ' '}, {'char_start': 224, 'char_end': 226, 'chars': 'he'}, {'char_start': 227, 'char_end': 228, 'chars': 'd'}, {'char_start': 229, 'char_end': 236, 'chars': 'rectory'}, {'char_start': 239, 'char_end': 240, 'chars': 'r'}, {'char_start': 242, 'char_end': 243, 'chars': 'b'}, {'char_start': 244, 'char_end': 246, 'chars': 'fo'}, {'char_start': 248, 'char_end': 250, 'chars': '\n '}, {'char_start': 251, 'char_end': 255, 'chars': ' '}, {'char_start': 256, 'char_end': 260, 'chars': ' the'}, {'char_start': 271, 'char_end': 276, 'chars': ' name'}, {'char_start': 277, 'char_end': 307, 'chars': ' Note that rest begins with a'}, {'char_start': 317, 'char_end': 318, 'chars': 'l'}, {'char_start': 320, 'char_end': 321, 'chars': 'h'}, {'char_start': 322, 'char_end': 326, 'chars': 'if i'}, {'char_start': 327, 'char_end': 328, 'chars': ' '}, {'char_start': 330, 'char_end': 335, 'chars': ' not '}, {'char_start': 336, 'char_end': 340, 'chars': 'mpty'}, {'char_start': 396, 'char_end': 397, 'chars': 'p'}, {'char_start': 398, 'char_end': 400, 'chars': 'th'}, {'char_start': 443, 'char_end': 460, 'chars': 'the list\n '}, {'char_start': 513, 'char_end': 521, 'chars': '\n '}, {'char_start': 561, 'char_end': 562, 'chars': '\n'}, {'char_start': 586, 'char_end': 587, 'chars': '\n'}, {'char_start': 597, 'char_end': 599, 'chars': 'or'}, {'char_start': 600, 'char_end': 601, 'chars': 'x'}, {'char_start': 639, 'char_end': 733, 'chars': ""i = len(x)\n if path[:i] == x and (not path[i:] or path[i] == '/'):\n ""}, {'char_start': 750, 'char_end': 755, 'chars': 'ath[:'}, {'char_start': 756, 'char_end': 759, 'chars': '], '}, {'char_start': 763, 'char_end': 769, 'chars': '[i+1:]'}, {'char_start': 770, 'char_end': 774, 'chars': ' '}], 'added': [{'char_start': 83, 'char_end': 85, 'chars': '.\n'}, {'char_start': 94, 'char_end': 95, 'chars': 'R'}, {'char_start': 100, 'char_end': 101, 'chars': 's'}, {'char_start': 102, 'char_end': 106, 'chars': 'True'}, {'char_start': 109, 'char_end': 110, 'chars': 'd'}, {'char_start': 112, 'char_end': 115, 'chars': 'pda'}, {'char_start': 119, 'char_end': 121, 'chars': 'th'}, {'char_start': 122, 'char_end': 123, 'chars': ' '}, {'char_start': 132, 'char_end': 142, 'chars': 'attribute '}, {'char_start': 145, 'char_end': 148, 'chars': 'the'}, {'char_start': 163, 'char_end': 165, 'chars': '(d'}, {'char_start': 171, 'char_end': 174, 'chars': 'st)'}, {'char_start': 176, 'char_end': 177, 'chars': 'f'}, {'char_start': 180, 'char_end': 183, 'chars': 'lf.'}, {'char_start': 186, 'char_end': 187, 'chars': 'h'}, {'char_start': 188, 'char_end': 189, 'chars': 'r'}, {'char_start': 190, 'char_end': 193, 'chars': 'qui'}, {'char_start': 195, 'char_end': 196, 'chars': 's'}, {'char_start': 197, 'char_end': 204, 'chars': 'running'}, {'char_start': 205, 'char_end': 206, 'chars': 'a'}, {'char_start': 217, 'char_end': 219, 'chars': '.\n'}, {'char_start': 220, 'char_end': 223, 'chars': ' '}, {'char_start': 227, 'char_end': 228, 'chars': 'R'}, {'char_start': 230, 'char_end': 232, 'chars': 'ur'}, {'char_start': 235, 'char_end': 236, 'chars': 'F'}, {'char_start': 239, 'char_end': 240, 'chars': 'e'}, {'char_start': 241, 'char_end': 242, 'chars': 'o'}, {'char_start': 243, 'char_end': 247, 'chars': 'herw'}, {'char_start': 306, 'char_end': 310, 'chars': 'norm'}, {'char_start': 311, 'char_end': 320, 'chars': 'lized url'}, {'char_start': 328, 'char_end': 333, 'chars': ' path'}, {'char_start': 388, 'char_end': 396, 'chars': '\n '}, {'char_start': 477, 'char_end': 482, 'chars': 'split'}, {'char_start': 489, 'char_end': 514, 'chars': '_url_collapse_path_split('}, {'char_start': 523, 'char_end': 524, 'chars': ')'}, {'char_start': 533, 'char_end': 534, 'chars': 'i'}, {'char_start': 536, 'char_end': 548, 'chars': 'splitpath[0]'}, {'char_start': 602, 'char_end': 603, 'chars': 's'}, {'char_start': 604, 'char_end': 605, 'chars': 'l'}, {'char_start': 606, 'char_end': 607, 'chars': 't'}]}",github.com/Ricky-Wilson/Python/commit/c5abced949e6a4b001d1dee321593e74ecadecfe,Lib/CGIHTTPServer.py,cwe-022,182 cwe-022,_normalize," def _normalize(self, metaerrors): """"""Normalize output format to be usable by Anaconda's linting frontend """""" errors = [] for error in metaerrors: if self.filepath not in error.get('path', ''): continue error_type = error.get('severity', 'X').capitalize()[0] if error_type == 'X': continue if error_type not in ['E', 'W']: error_type = 'V' errors.append({ 'underline_range': True, 'lineno': error.get('line', 0), 'offset': error.get('col', 0), 'raw_message': error.get('message', ''), 'code': 0, 'level': error_type, 'message': '[{0}] {1} ({2}): {3}'.format( error_type, error.get('linter', 'none'), error.get('severity', 'none'), error.get('message') ) }) return errors"," def _normalize(self, metaerrors): """"""Normalize output format to be usable by Anaconda's linting frontend """""" errors = [] for error in metaerrors: last_path = os.path.join( os.path.basename(os.path.dirname(self.filepath)), os.path.basename(self.filepath) ) if last_path not in error.get('path', ''): continue error_type = error.get('severity', 'X').capitalize()[0] if error_type == 'X': continue if error_type not in ['E', 'W']: error_type = 'V' errors.append({ 'underline_range': True, 'lineno': error.get('line', 0), 'offset': error.get('col', 0), 'raw_message': error.get('message', ''), 'code': 0, 'level': error_type, 'message': '[{0}] {1} ({2}): {3}'.format( error_type, error.get('linter', 'none'), error.get('severity', 'none'), error.get('message') ) }) return errors","{'deleted': [{'line_no': 7, 'char_start': 183, 'char_end': 242, 'line': "" if self.filepath not in error.get('path', ''):\n""}], 'added': [{'line_no': 7, 'char_start': 183, 'char_end': 221, 'line': ' last_path = os.path.join(\n'}, {'line_no': 8, 'char_start': 221, 'char_end': 287, 'line': ' os.path.basename(os.path.dirname(self.filepath)),\n'}, {'line_no': 9, 'char_start': 287, 'char_end': 335, 'line': ' os.path.basename(self.filepath)\n'}, {'line_no': 10, 'char_start': 335, 'char_end': 349, 'line': ' )\n'}, {'line_no': 11, 'char_start': 349, 'char_end': 404, 'line': "" if last_path not in error.get('path', ''):\n""}]}","{'deleted': [], 'added': [{'char_start': 195, 'char_end': 217, 'chars': 'last_path = os.path.jo'}, {'char_start': 218, 'char_end': 273, 'chars': 'n(\n os.path.basename(os.path.dirname(sel'}, {'char_start': 274, 'char_end': 287, 'chars': '.filepath)),\n'}, {'char_start': 288, 'char_end': 320, 'chars': ' os.path.basename('}, {'char_start': 329, 'char_end': 369, 'chars': 'path)\n )\n if last_'}]}",github.com/DamnWidget/anaconda_go/commit/d3db90bb8853d832927818699591b91f56f6413c,plugin/handlers_go/anagonda/context/gometalinter.py,cwe-022,216 cwe-089,set_language," def set_language(self, lang): """""" Update language of user in the User object and in the database :param lang: string with language tag like ""en-US"" :return: None """""" log.debug('Updating info about user %s language ' 'in memory & database...', self) self.language = lang query = (""UPDATE users "" f""SET language='{self.language}' "" f""WHERE chat_id='{self.chat_id}'"") try: db.add(query) except DatabaseError: log.error(""Can't add new language of %s to the database"", self) else: log.debug('Language updated.')"," def set_language(self, lang): """""" Update language of user in the User object and in the database :param lang: string with language tag like ""en-US"" :return: None """""" log.debug('Updating info about user %s language ' 'in memory & database...', self) self.language = lang query = (""UPDATE users "" f""SET language=%s "" f""WHERE chat_id=%s"") parameters = self.language, self.chat_id try: db.add(query, parameters) except DatabaseError: log.error(""Can't add new language of %s to the database"", self) else: log.debug('Language updated.')","{'deleted': [{'line_no': 13, 'char_start': 383, 'char_end': 435, 'line': ' f""SET language=\'{self.language}\' ""\n'}, {'line_no': 14, 'char_start': 435, 'char_end': 487, 'line': ' f""WHERE chat_id=\'{self.chat_id}\'"")\n'}, {'line_no': 17, 'char_start': 501, 'char_end': 527, 'line': ' db.add(query)\n'}], 'added': [{'line_no': 13, 'char_start': 383, 'char_end': 420, 'line': ' f""SET language=%s ""\n'}, {'line_no': 14, 'char_start': 420, 'char_end': 458, 'line': ' f""WHERE chat_id=%s"")\n'}, {'line_no': 16, 'char_start': 459, 'char_end': 508, 'line': ' parameters = self.language, self.chat_id\n'}, {'line_no': 18, 'char_start': 521, 'char_end': 559, 'line': ' db.add(query, parameters)\n'}]}","{'deleted': [{'char_start': 415, 'char_end': 417, 'chars': ""'{""}, {'char_start': 418, 'char_end': 432, 'chars': ""elf.language}'""}, {'char_start': 468, 'char_end': 470, 'chars': ""'{""}, {'char_start': 482, 'char_end': 487, 'chars': '}\'"")\n'}], 'added': [{'char_start': 415, 'char_end': 416, 'chars': '%'}, {'char_start': 453, 'char_end': 495, 'chars': '%s"")\n\n parameters = self.language, '}, {'char_start': 545, 'char_end': 557, 'chars': ', parameters'}]}",github.com/RandyRomero/photoGPSbot/commit/0e9f57f13e61863b3672f5730e27f149da00786a,photogpsbot/users.py,cwe-089,143 cwe-078,_exec_cmd," def _exec_cmd(self, cmd): """"""Executes adb commands in a new shell. This is specific to executing adb binary because stderr is not a good indicator of cmd execution status. Args: cmds: A string that is the adb command to execute. Returns: The output of the adb command run if exit code is 0. Raises: AdbError is raised if the adb command exit code is not 0. """""" proc = subprocess.Popen( cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) (out, err) = proc.communicate() ret = proc.returncode logging.debug('cmd: %s, stdout: %s, stderr: %s, ret: %s', cmd, out, err, ret) if ret == 0: return out else: raise AdbError(cmd=cmd, stdout=out, stderr=err, ret_code=ret)"," def _exec_cmd(self, args, shell): """"""Executes adb commands. Args: args: string or list of strings, program arguments. See subprocess.Popen() documentation. shell: bool, True to run this command through the system shell, False to invoke it directly. See subprocess.Popen() docs. Returns: The output of the adb command run if exit code is 0. Raises: AdbError is raised if the adb command exit code is not 0. """""" proc = subprocess.Popen( args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=shell) (out, err) = proc.communicate() ret = proc.returncode logging.debug('cmd: %s, stdout: %s, stderr: %s, ret: %s', args, out, err, ret) if ret == 0: return out else: raise AdbError(cmd=args, stdout=out, stderr=err, ret_code=ret)","{'deleted': [{'line_no': 1, 'char_start': 0, 'char_end': 30, 'line': ' def _exec_cmd(self, cmd):\n'}, {'line_no': 8, 'char_start': 216, 'char_end': 279, 'line': ' cmds: A string that is the adb command to execute.\n'}, {'line_no': 17, 'char_start': 494, 'char_end': 571, 'line': ' cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)\n'}, {'line_no': 20, 'char_start': 641, 'char_end': 717, 'line': "" logging.debug('cmd: %s, stdout: %s, stderr: %s, ret: %s', cmd, out,\n""}, {'line_no': 25, 'char_start': 807, 'char_end': 880, 'line': ' raise AdbError(cmd=cmd, stdout=out, stderr=err, ret_code=ret)\n'}], 'added': [{'line_no': 1, 'char_start': 0, 'char_end': 38, 'line': ' def _exec_cmd(self, args, shell):\n'}, {'line_no': 2, 'char_start': 38, 'char_end': 72, 'line': ' """"""Executes adb commands.\n'}, {'line_no': 5, 'char_start': 87, 'char_end': 151, 'line': ' args: string or list of strings, program arguments.\n'}, {'line_no': 6, 'char_start': 151, 'char_end': 205, 'line': ' See subprocess.Popen() documentation.\n'}, {'line_no': 7, 'char_start': 205, 'char_end': 281, 'line': ' shell: bool, True to run this command through the system shell,\n'}, {'line_no': 8, 'char_start': 281, 'char_end': 355, 'line': ' False to invoke it directly. See subprocess.Popen() docs.\n'}, {'line_no': 17, 'char_start': 570, 'char_end': 649, 'line': ' args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=shell)\n'}, {'line_no': 20, 'char_start': 719, 'char_end': 796, 'line': "" logging.debug('cmd: %s, stdout: %s, stderr: %s, ret: %s', args, out,\n""}]}","{'deleted': [{'char_start': 24, 'char_end': 27, 'chars': 'cmd'}, {'char_start': 63, 'char_end': 65, 'chars': 'in'}, {'char_start': 66, 'char_end': 67, 'chars': 'a'}, {'char_start': 68, 'char_end': 71, 'chars': 'new'}, {'char_start': 73, 'char_end': 79, 'chars': 'hell.\n'}, {'char_start': 88, 'char_end': 92, 'chars': 'This'}, {'char_start': 93, 'char_end': 94, 'chars': 'i'}, {'char_start': 97, 'char_end': 102, 'chars': 'pecif'}, {'char_start': 103, 'char_end': 104, 'chars': 'c'}, {'char_start': 108, 'char_end': 113, 'chars': 'execu'}, {'char_start': 119, 'char_end': 121, 'chars': 'db'}, {'char_start': 122, 'char_end': 125, 'chars': 'bin'}, {'char_start': 127, 'char_end': 133, 'chars': 'y beca'}, {'char_start': 134, 'char_end': 135, 'chars': 's'}, {'char_start': 136, 'char_end': 138, 'chars': ' s'}, {'char_start': 139, 'char_end': 145, 'chars': 'derr i'}, {'char_start': 147, 'char_end': 150, 'chars': 'not'}, {'char_start': 151, 'char_end': 152, 'chars': 'a'}, {'char_start': 153, 'char_end': 158, 'chars': 'good\n'}, {'char_start': 166, 'char_end': 175, 'chars': 'indicator'}, {'char_start': 176, 'char_end': 178, 'chars': 'of'}, {'char_start': 179, 'char_end': 182, 'chars': 'cmd'}, {'char_start': 184, 'char_end': 185, 'chars': 'x'}, {'char_start': 186, 'char_end': 187, 'chars': 'c'}, {'char_start': 188, 'char_end': 190, 'chars': 'ti'}, {'char_start': 193, 'char_end': 194, 'chars': 's'}, {'char_start': 197, 'char_end': 199, 'chars': 'us'}, {'char_start': 200, 'char_end': 201, 'chars': '\n'}, {'char_start': 210, 'char_end': 218, 'chars': 'Args:\n '}, {'char_start': 231, 'char_end': 233, 'chars': 's:'}, {'char_start': 234, 'char_end': 237, 'chars': 'A s'}, {'char_start': 239, 'char_end': 241, 'chars': 'in'}, {'char_start': 245, 'char_end': 247, 'chars': 'at'}, {'char_start': 248, 'char_end': 249, 'chars': 'i'}, {'char_start': 250, 'char_end': 251, 'chars': ' '}, {'char_start': 255, 'char_end': 258, 'chars': 'adb'}, {'char_start': 259, 'char_end': 263, 'chars': 'comm'}, {'char_start': 264, 'char_end': 266, 'chars': 'nd'}, {'char_start': 271, 'char_end': 272, 'chars': 'x'}, {'char_start': 274, 'char_end': 275, 'chars': 'u'}, {'char_start': 506, 'char_end': 509, 'chars': 'cmd'}, {'char_start': 565, 'char_end': 568, 'chars': 'Tru'}, {'char_start': 707, 'char_end': 710, 'chars': 'cmd'}, {'char_start': 838, 'char_end': 841, 'chars': 'cmd'}], 'added': [{'char_start': 24, 'char_end': 35, 'chars': 'args, shell'}, {'char_start': 70, 'char_end': 73, 'chars': '.\n\n'}, {'char_start': 76, 'char_end': 80, 'chars': ' '}, {'char_start': 81, 'char_end': 84, 'chars': 'Arg'}, {'char_start': 85, 'char_end': 86, 'chars': ':'}, {'char_start': 96, 'char_end': 102, 'chars': ' arg'}, {'char_start': 103, 'char_end': 104, 'chars': ':'}, {'char_start': 106, 'char_end': 108, 'chars': 'tr'}, {'char_start': 109, 'char_end': 116, 'chars': 'ng or l'}, {'char_start': 117, 'char_end': 118, 'chars': 's'}, {'char_start': 119, 'char_end': 120, 'chars': ' '}, {'char_start': 121, 'char_end': 122, 'chars': 'f'}, {'char_start': 123, 'char_end': 124, 'chars': 's'}, {'char_start': 125, 'char_end': 126, 'chars': 'r'}, {'char_start': 129, 'char_end': 131, 'chars': 's,'}, {'char_start': 132, 'char_end': 137, 'chars': 'progr'}, {'char_start': 138, 'char_end': 139, 'chars': 'm'}, {'char_start': 142, 'char_end': 145, 'chars': 'gum'}, {'char_start': 146, 'char_end': 148, 'chars': 'nt'}, {'char_start': 149, 'char_end': 151, 'chars': '.\n'}, {'char_start': 167, 'char_end': 168, 'chars': 'S'}, {'char_start': 170, 'char_end': 177, 'chars': ' subpro'}, {'char_start': 178, 'char_end': 183, 'chars': 'ess.P'}, {'char_start': 184, 'char_end': 186, 'chars': 'pe'}, {'char_start': 187, 'char_end': 189, 'chars': '()'}, {'char_start': 190, 'char_end': 197, 'chars': 'documen'}, {'char_start': 200, 'char_end': 203, 'chars': 'ion'}, {'char_start': 217, 'char_end': 223, 'chars': 'shell:'}, {'char_start': 224, 'char_end': 229, 'chars': 'bool,'}, {'char_start': 230, 'char_end': 234, 'chars': 'True'}, {'char_start': 235, 'char_end': 237, 'chars': 'to'}, {'char_start': 238, 'char_end': 241, 'chars': 'run'}, {'char_start': 242, 'char_end': 246, 'chars': 'this'}, {'char_start': 248, 'char_end': 250, 'chars': 'om'}, {'char_start': 251, 'char_end': 253, 'chars': 'an'}, {'char_start': 256, 'char_end': 257, 'chars': 'h'}, {'char_start': 258, 'char_end': 260, 'chars': 'ou'}, {'char_start': 261, 'char_end': 262, 'chars': 'h'}, {'char_start': 265, 'char_end': 270, 'chars': 'e sys'}, {'char_start': 271, 'char_end': 273, 'chars': 'em'}, {'char_start': 277, 'char_end': 293, 'chars': 'll,\n '}, {'char_start': 294, 'char_end': 298, 'chars': ' F'}, {'char_start': 299, 'char_end': 302, 'chars': 'lse'}, {'char_start': 303, 'char_end': 304, 'chars': 't'}, {'char_start': 305, 'char_end': 307, 'chars': ' i'}, {'char_start': 308, 'char_end': 316, 'chars': 'voke it '}, {'char_start': 317, 'char_end': 321, 'chars': 'irec'}, {'char_start': 322, 'char_end': 325, 'chars': 'ly.'}, {'char_start': 326, 'char_end': 327, 'chars': 'S'}, {'char_start': 329, 'char_end': 336, 'chars': ' subpro'}, {'char_start': 338, 'char_end': 353, 'chars': 'ss.Popen() docs'}, {'char_start': 582, 'char_end': 586, 'chars': 'args'}, {'char_start': 642, 'char_end': 644, 'chars': 'sh'}, {'char_start': 645, 'char_end': 647, 'chars': 'll'}, {'char_start': 785, 'char_end': 789, 'chars': 'args'}, {'char_start': 917, 'char_end': 921, 'chars': 'args'}]}",github.com/google/mobly/commit/3862e8ba359040fbdd6e1a6d36e51d07cda8e1ee,mobly/controllers/android_device_lib/adb.py,cwe-078,204 cwe-022,cleanup_pathname,"cleanup_pathname(struct archive_write_disk *a) { char *dest, *src; char separator = '\0'; dest = src = a->name; if (*src == '\0') { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, ""Invalid empty pathname""); return (ARCHIVE_FAILED); } #if defined(__CYGWIN__) cleanup_pathname_win(a); #endif /* Skip leading '/'. */ if (*src == '/') separator = *src++; /* Scan the pathname one element at a time. */ for (;;) { /* src points to first char after '/' */ if (src[0] == '\0') { break; } else if (src[0] == '/') { /* Found '//', ignore second one. */ src++; continue; } else if (src[0] == '.') { if (src[1] == '\0') { /* Ignore trailing '.' */ break; } else if (src[1] == '/') { /* Skip './'. */ src += 2; continue; } else if (src[1] == '.') { if (src[2] == '/' || src[2] == '\0') { /* Conditionally warn about '..' */ if (a->flags & ARCHIVE_EXTRACT_SECURE_NODOTDOT) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, ""Path contains '..'""); return (ARCHIVE_FAILED); } } /* * Note: Under no circumstances do we * remove '..' elements. In * particular, restoring * '/foo/../bar/' should create the * 'foo' dir as a side-effect. */ } } /* Copy current element, including leading '/'. */ if (separator) *dest++ = '/'; while (*src != '\0' && *src != '/') { *dest++ = *src++; } if (*src == '\0') break; /* Skip '/' separator. */ separator = *src++; } /* * We've just copied zero or more path elements, not including the * final '/'. */ if (dest == a->name) { /* * Nothing got copied. The path must have been something * like '.' or '/' or './' or '/././././/./'. */ if (separator) *dest++ = '/'; else *dest++ = '.'; } /* Terminate the result. */ *dest = '\0'; return (ARCHIVE_OK); }","cleanup_pathname(struct archive_write_disk *a) { char *dest, *src; char separator = '\0'; dest = src = a->name; if (*src == '\0') { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, ""Invalid empty pathname""); return (ARCHIVE_FAILED); } #if defined(__CYGWIN__) cleanup_pathname_win(a); #endif /* Skip leading '/'. */ if (*src == '/') { if (a->flags & ARCHIVE_EXTRACT_SECURE_NOABSOLUTEPATHS) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, ""Path is absolute""); return (ARCHIVE_FAILED); } separator = *src++; } /* Scan the pathname one element at a time. */ for (;;) { /* src points to first char after '/' */ if (src[0] == '\0') { break; } else if (src[0] == '/') { /* Found '//', ignore second one. */ src++; continue; } else if (src[0] == '.') { if (src[1] == '\0') { /* Ignore trailing '.' */ break; } else if (src[1] == '/') { /* Skip './'. */ src += 2; continue; } else if (src[1] == '.') { if (src[2] == '/' || src[2] == '\0') { /* Conditionally warn about '..' */ if (a->flags & ARCHIVE_EXTRACT_SECURE_NODOTDOT) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, ""Path contains '..'""); return (ARCHIVE_FAILED); } } /* * Note: Under no circumstances do we * remove '..' elements. In * particular, restoring * '/foo/../bar/' should create the * 'foo' dir as a side-effect. */ } } /* Copy current element, including leading '/'. */ if (separator) *dest++ = '/'; while (*src != '\0' && *src != '/') { *dest++ = *src++; } if (*src == '\0') break; /* Skip '/' separator. */ separator = *src++; } /* * We've just copied zero or more path elements, not including the * final '/'. */ if (dest == a->name) { /* * Nothing got copied. The path must have been something * like '.' or '/' or './' or '/././././/./'. */ if (separator) *dest++ = '/'; else *dest++ = '.'; } /* Terminate the result. */ *dest = '\0'; return (ARCHIVE_OK); }","{'deleted': [{'line_no': 17, 'char_start': 336, 'char_end': 354, 'line': ""\tif (*src == '/')\n""}], 'added': [{'line_no': 17, 'char_start': 336, 'char_end': 356, 'line': ""\tif (*src == '/') {\n""}, {'line_no': 18, 'char_start': 356, 'char_end': 415, 'line': '\t\tif (a->flags & ARCHIVE_EXTRACT_SECURE_NOABSOLUTEPATHS) {\n'}, {'line_no': 19, 'char_start': 415, 'char_end': 469, 'line': '\t\t\tarchive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,\n'}, {'line_no': 20, 'char_start': 469, 'char_end': 511, 'line': '\t\t\t ""Path is absolute"");\n'}, {'line_no': 21, 'char_start': 511, 'char_end': 539, 'line': '\t\t\treturn (ARCHIVE_FAILED);\n'}, {'line_no': 22, 'char_start': 539, 'char_end': 543, 'line': '\t\t}\n'}, {'line_no': 23, 'char_start': 543, 'char_end': 544, 'line': '\n'}, {'line_no': 25, 'char_start': 566, 'char_end': 569, 'line': '\t}\n'}]}","{'deleted': [], 'added': [{'char_start': 353, 'char_end': 543, 'chars': ' {\n\t\tif (a->flags & ARCHIVE_EXTRACT_SECURE_NOABSOLUTEPATHS) {\n\t\t\tarchive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,\n\t\t\t ""Path is absolute"");\n\t\t\treturn (ARCHIVE_FAILED);\n\t\t}\n'}, {'char_start': 565, 'char_end': 568, 'chars': '\n\t}'}]}",github.com/libarchive/libarchive/commit/59357157706d47c365b2227739e17daba3607526,libarchive/archive_write_disk_posix.c,cwe-022,591 cwe-476,xfs_attr_shortform_to_leaf,"xfs_attr_shortform_to_leaf( struct xfs_da_args *args, struct xfs_buf **leaf_bp) { xfs_inode_t *dp; xfs_attr_shortform_t *sf; xfs_attr_sf_entry_t *sfe; xfs_da_args_t nargs; char *tmpbuffer; int error, i, size; xfs_dablk_t blkno; struct xfs_buf *bp; xfs_ifork_t *ifp; trace_xfs_attr_sf_to_leaf(args); dp = args->dp; ifp = dp->i_afp; sf = (xfs_attr_shortform_t *)ifp->if_u1.if_data; size = be16_to_cpu(sf->hdr.totsize); tmpbuffer = kmem_alloc(size, KM_SLEEP); ASSERT(tmpbuffer != NULL); memcpy(tmpbuffer, ifp->if_u1.if_data, size); sf = (xfs_attr_shortform_t *)tmpbuffer; xfs_idata_realloc(dp, -size, XFS_ATTR_FORK); xfs_bmap_local_to_extents_empty(dp, XFS_ATTR_FORK); bp = NULL; error = xfs_da_grow_inode(args, &blkno); if (error) { /* * If we hit an IO error middle of the transaction inside * grow_inode(), we may have inconsistent data. Bail out. */ if (error == -EIO) goto out; xfs_idata_realloc(dp, size, XFS_ATTR_FORK); /* try to put */ memcpy(ifp->if_u1.if_data, tmpbuffer, size); /* it back */ goto out; } ASSERT(blkno == 0); error = xfs_attr3_leaf_create(args, blkno, &bp); if (error) { error = xfs_da_shrink_inode(args, 0, bp); bp = NULL; if (error) goto out; xfs_idata_realloc(dp, size, XFS_ATTR_FORK); /* try to put */ memcpy(ifp->if_u1.if_data, tmpbuffer, size); /* it back */ goto out; } memset((char *)&nargs, 0, sizeof(nargs)); nargs.dp = dp; nargs.geo = args->geo; nargs.firstblock = args->firstblock; nargs.dfops = args->dfops; nargs.total = args->total; nargs.whichfork = XFS_ATTR_FORK; nargs.trans = args->trans; nargs.op_flags = XFS_DA_OP_OKNOENT; sfe = &sf->list[0]; for (i = 0; i < sf->hdr.count; i++) { nargs.name = sfe->nameval; nargs.namelen = sfe->namelen; nargs.value = &sfe->nameval[nargs.namelen]; nargs.valuelen = sfe->valuelen; nargs.hashval = xfs_da_hashname(sfe->nameval, sfe->namelen); nargs.flags = XFS_ATTR_NSP_ONDISK_TO_ARGS(sfe->flags); error = xfs_attr3_leaf_lookup_int(bp, &nargs); /* set a->index */ ASSERT(error == -ENOATTR); error = xfs_attr3_leaf_add(bp, &nargs); ASSERT(error != -ENOSPC); if (error) goto out; sfe = XFS_ATTR_SF_NEXTENTRY(sfe); } error = 0; *leaf_bp = bp; out: kmem_free(tmpbuffer); return error; }","xfs_attr_shortform_to_leaf( struct xfs_da_args *args, struct xfs_buf **leaf_bp) { xfs_inode_t *dp; xfs_attr_shortform_t *sf; xfs_attr_sf_entry_t *sfe; xfs_da_args_t nargs; char *tmpbuffer; int error, i, size; xfs_dablk_t blkno; struct xfs_buf *bp; xfs_ifork_t *ifp; trace_xfs_attr_sf_to_leaf(args); dp = args->dp; ifp = dp->i_afp; sf = (xfs_attr_shortform_t *)ifp->if_u1.if_data; size = be16_to_cpu(sf->hdr.totsize); tmpbuffer = kmem_alloc(size, KM_SLEEP); ASSERT(tmpbuffer != NULL); memcpy(tmpbuffer, ifp->if_u1.if_data, size); sf = (xfs_attr_shortform_t *)tmpbuffer; xfs_idata_realloc(dp, -size, XFS_ATTR_FORK); xfs_bmap_local_to_extents_empty(dp, XFS_ATTR_FORK); bp = NULL; error = xfs_da_grow_inode(args, &blkno); if (error) { /* * If we hit an IO error middle of the transaction inside * grow_inode(), we may have inconsistent data. Bail out. */ if (error == -EIO) goto out; xfs_idata_realloc(dp, size, XFS_ATTR_FORK); /* try to put */ memcpy(ifp->if_u1.if_data, tmpbuffer, size); /* it back */ goto out; } ASSERT(blkno == 0); error = xfs_attr3_leaf_create(args, blkno, &bp); if (error) { /* xfs_attr3_leaf_create may not have instantiated a block */ if (bp && (xfs_da_shrink_inode(args, 0, bp) != 0)) goto out; xfs_idata_realloc(dp, size, XFS_ATTR_FORK); /* try to put */ memcpy(ifp->if_u1.if_data, tmpbuffer, size); /* it back */ goto out; } memset((char *)&nargs, 0, sizeof(nargs)); nargs.dp = dp; nargs.geo = args->geo; nargs.firstblock = args->firstblock; nargs.dfops = args->dfops; nargs.total = args->total; nargs.whichfork = XFS_ATTR_FORK; nargs.trans = args->trans; nargs.op_flags = XFS_DA_OP_OKNOENT; sfe = &sf->list[0]; for (i = 0; i < sf->hdr.count; i++) { nargs.name = sfe->nameval; nargs.namelen = sfe->namelen; nargs.value = &sfe->nameval[nargs.namelen]; nargs.valuelen = sfe->valuelen; nargs.hashval = xfs_da_hashname(sfe->nameval, sfe->namelen); nargs.flags = XFS_ATTR_NSP_ONDISK_TO_ARGS(sfe->flags); error = xfs_attr3_leaf_lookup_int(bp, &nargs); /* set a->index */ ASSERT(error == -ENOATTR); error = xfs_attr3_leaf_add(bp, &nargs); ASSERT(error != -ENOSPC); if (error) goto out; sfe = XFS_ATTR_SF_NEXTENTRY(sfe); } error = 0; *leaf_bp = bp; out: kmem_free(tmpbuffer); return error; }","{'deleted': [{'line_no': 46, 'char_start': 1151, 'char_end': 1195, 'line': '\t\terror = xfs_da_shrink_inode(args, 0, bp);\n'}, {'line_no': 47, 'char_start': 1195, 'char_end': 1208, 'line': '\t\tbp = NULL;\n'}, {'line_no': 48, 'char_start': 1208, 'char_end': 1221, 'line': '\t\tif (error)\n'}], 'added': [{'line_no': 46, 'char_start': 1151, 'char_end': 1215, 'line': '\t\t/* xfs_attr3_leaf_create may not have instantiated a block */\n'}, {'line_no': 47, 'char_start': 1215, 'char_end': 1268, 'line': '\t\tif (bp && (xfs_da_shrink_inode(args, 0, bp) != 0))\n'}]}","{'deleted': [{'char_start': 1155, 'char_end': 1156, 'chars': 'r'}, {'char_start': 1157, 'char_end': 1158, 'chars': 'r'}, {'char_start': 1159, 'char_end': 1160, 'chars': '='}, {'char_start': 1193, 'char_end': 1199, 'chars': ';\n\t\tbp'}, {'char_start': 1202, 'char_end': 1219, 'chars': 'NULL;\n\t\tif (error'}], 'added': [{'char_start': 1153, 'char_end': 1167, 'chars': '/* xfs_attr3_l'}, {'char_start': 1168, 'char_end': 1172, 'chars': 'af_c'}, {'char_start': 1173, 'char_end': 1183, 'chars': 'eate may n'}, {'char_start': 1184, 'char_end': 1185, 'chars': 't'}, {'char_start': 1186, 'char_end': 1190, 'chars': 'have'}, {'char_start': 1191, 'char_end': 1228, 'chars': 'instantiated a block */\n\t\tif (bp && ('}, {'char_start': 1261, 'char_end': 1262, 'chars': '!'}, {'char_start': 1264, 'char_end': 1266, 'chars': '0)'}]}",github.com/torvalds/linux/commit/bb3d48dcf86a97dc25fe9fc2c11938e19cb4399a,fs/xfs/libxfs/xfs_attr_leaf.c,cwe-476,780 cwe-089,isValidAdmToken,"def isValidAdmToken(adm_token): conn, c = connectDB() req = ""SELECT * from {} where adm_token='{}'"".format(CFG(""admintoken_table_name""), adm_token) answer = bool(queryOne(c, req)) closeDB(conn) return answer","def isValidAdmToken(adm_token): conn, c = connectDB() req = ""SELECT * from {} where adm_token=?"".format(CFG(""admintoken_table_name"")) answer = bool(queryOne(c, req, (adm_token,))) closeDB(conn) return answer","{'deleted': [{'line_no': 3, 'char_start': 58, 'char_end': 157, 'line': ' req = ""SELECT * from {} where adm_token=\'{}\'"".format(CFG(""admintoken_table_name""), adm_token)\n'}, {'line_no': 4, 'char_start': 157, 'char_end': 193, 'line': ' answer = bool(queryOne(c, req))\n'}], 'added': [{'line_no': 3, 'char_start': 58, 'char_end': 143, 'line': ' req = ""SELECT * from {} where adm_token=?"".format(CFG(""admintoken_table_name""))\n'}, {'line_no': 4, 'char_start': 143, 'char_end': 193, 'line': ' answer = bool(queryOne(c, req, (adm_token,)))\n'}]}","{'deleted': [{'char_start': 103, 'char_end': 107, 'chars': ""'{}'""}, {'char_start': 144, 'char_end': 155, 'chars': ', adm_token'}], 'added': [{'char_start': 103, 'char_end': 104, 'chars': '?'}, {'char_start': 176, 'char_end': 190, 'chars': ', (adm_token,)'}]}",github.com/FAUSheppy/simple-python-poll/commit/186c5ff5cdf58272e253a1bb432419ee50d93109,database.py,cwe-089,64 cwe-125,next_line,"next_line(struct archive_read *a, const char **b, ssize_t *avail, ssize_t *ravail, ssize_t *nl) { ssize_t len; int quit; quit = 0; if (*avail == 0) { *nl = 0; len = 0; } else len = get_line_size(*b, *avail, nl); /* * Read bytes more while it does not reach the end of line. */ while (*nl == 0 && len == *avail && !quit) { ssize_t diff = *ravail - *avail; size_t nbytes_req = (*ravail+1023) & ~1023U; ssize_t tested; /* Increase reading bytes if it is not enough to at least * new two lines. */ if (nbytes_req < (size_t)*ravail + 160) nbytes_req <<= 1; *b = __archive_read_ahead(a, nbytes_req, avail); if (*b == NULL) { if (*ravail >= *avail) return (0); /* Reading bytes reaches the end of file. */ *b = __archive_read_ahead(a, *avail, avail); quit = 1; } *ravail = *avail; *b += diff; *avail -= diff; tested = len;/* Skip some bytes we already determinated. */ len = get_line_size(*b, *avail, nl); if (len >= 0) len += tested; } return (len); }","next_line(struct archive_read *a, const char **b, ssize_t *avail, ssize_t *ravail, ssize_t *nl) { ssize_t len; int quit; quit = 0; if (*avail == 0) { *nl = 0; len = 0; } else len = get_line_size(*b, *avail, nl); /* * Read bytes more while it does not reach the end of line. */ while (*nl == 0 && len == *avail && !quit) { ssize_t diff = *ravail - *avail; size_t nbytes_req = (*ravail+1023) & ~1023U; ssize_t tested; /* Increase reading bytes if it is not enough to at least * new two lines. */ if (nbytes_req < (size_t)*ravail + 160) nbytes_req <<= 1; *b = __archive_read_ahead(a, nbytes_req, avail); if (*b == NULL) { if (*ravail >= *avail) return (0); /* Reading bytes reaches the end of file. */ *b = __archive_read_ahead(a, *avail, avail); quit = 1; } *ravail = *avail; *b += diff; *avail -= diff; tested = len;/* Skip some bytes we already determinated. */ len = get_line_size(*b + len, *avail - len, nl); if (len >= 0) len += tested; } return (len); }","{'deleted': [{'line_no': 38, 'char_start': 933, 'char_end': 972, 'line': '\t\tlen = get_line_size(*b, *avail, nl);\n'}], 'added': [{'line_no': 38, 'char_start': 933, 'char_end': 984, 'line': '\t\tlen = get_line_size(*b + len, *avail - len, nl);\n'}]}","{'deleted': [], 'added': [{'char_start': 957, 'char_end': 963, 'chars': ' + len'}, {'char_start': 971, 'char_end': 977, 'chars': ' - len'}]}",github.com/libarchive/libarchive/commit/eec077f52bfa2d3f7103b4b74d52572ba8a15aca,libarchive/archive_read_support_format_mtree.c,cwe-125,358 cwe-125,lha_read_file_header_1,"lha_read_file_header_1(struct archive_read *a, struct lha *lha) { const unsigned char *p; size_t extdsize; int i, err, err2; int namelen, padding; unsigned char headersum, sum_calculated; err = ARCHIVE_OK; if ((p = __archive_read_ahead(a, H1_FIXED_SIZE, NULL)) == NULL) return (truncated_error(a)); lha->header_size = p[H1_HEADER_SIZE_OFFSET] + 2; headersum = p[H1_HEADER_SUM_OFFSET]; /* Note: An extended header size is included in a compsize. */ lha->compsize = archive_le32dec(p + H1_COMP_SIZE_OFFSET); lha->origsize = archive_le32dec(p + H1_ORIG_SIZE_OFFSET); lha->mtime = lha_dos_time(p + H1_DOS_TIME_OFFSET); namelen = p[H1_NAME_LEN_OFFSET]; /* Calculate a padding size. The result will be normally 0 only(?) */ padding = ((int)lha->header_size) - H1_FIXED_SIZE - namelen; if (namelen > 230 || padding < 0) goto invalid; if ((p = __archive_read_ahead(a, lha->header_size, NULL)) == NULL) return (truncated_error(a)); for (i = 0; i < namelen; i++) { if (p[i + H1_FILE_NAME_OFFSET] == 0xff) goto invalid;/* Invalid filename. */ } archive_strncpy(&lha->filename, p + H1_FILE_NAME_OFFSET, namelen); lha->crc = archive_le16dec(p + H1_FILE_NAME_OFFSET + namelen); lha->setflag |= CRC_IS_SET; sum_calculated = lha_calcsum(0, p, 2, lha->header_size - 2); /* Consume used bytes but not include `next header size' data * since it will be consumed in lha_read_file_extended_header(). */ __archive_read_consume(a, lha->header_size - 2); /* Read extended headers */ err2 = lha_read_file_extended_header(a, lha, NULL, 2, (size_t)(lha->compsize + 2), &extdsize); if (err2 < ARCHIVE_WARN) return (err2); if (err2 < err) err = err2; /* Get a real compressed file size. */ lha->compsize -= extdsize - 2; if (sum_calculated != headersum) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, ""LHa header sum error""); return (ARCHIVE_FATAL); } return (err); invalid: archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, ""Invalid LHa header""); return (ARCHIVE_FATAL); }","lha_read_file_header_1(struct archive_read *a, struct lha *lha) { const unsigned char *p; size_t extdsize; int i, err, err2; int namelen, padding; unsigned char headersum, sum_calculated; err = ARCHIVE_OK; if ((p = __archive_read_ahead(a, H1_FIXED_SIZE, NULL)) == NULL) return (truncated_error(a)); lha->header_size = p[H1_HEADER_SIZE_OFFSET] + 2; headersum = p[H1_HEADER_SUM_OFFSET]; /* Note: An extended header size is included in a compsize. */ lha->compsize = archive_le32dec(p + H1_COMP_SIZE_OFFSET); lha->origsize = archive_le32dec(p + H1_ORIG_SIZE_OFFSET); lha->mtime = lha_dos_time(p + H1_DOS_TIME_OFFSET); namelen = p[H1_NAME_LEN_OFFSET]; /* Calculate a padding size. The result will be normally 0 only(?) */ padding = ((int)lha->header_size) - H1_FIXED_SIZE - namelen; if (namelen > 230 || padding < 0) goto invalid; if ((p = __archive_read_ahead(a, lha->header_size, NULL)) == NULL) return (truncated_error(a)); for (i = 0; i < namelen; i++) { if (p[i + H1_FILE_NAME_OFFSET] == 0xff) goto invalid;/* Invalid filename. */ } archive_strncpy(&lha->filename, p + H1_FILE_NAME_OFFSET, namelen); lha->crc = archive_le16dec(p + H1_FILE_NAME_OFFSET + namelen); lha->setflag |= CRC_IS_SET; sum_calculated = lha_calcsum(0, p, 2, lha->header_size - 2); /* Consume used bytes but not include `next header size' data * since it will be consumed in lha_read_file_extended_header(). */ __archive_read_consume(a, lha->header_size - 2); /* Read extended headers */ err2 = lha_read_file_extended_header(a, lha, NULL, 2, (size_t)(lha->compsize + 2), &extdsize); if (err2 < ARCHIVE_WARN) return (err2); if (err2 < err) err = err2; /* Get a real compressed file size. */ lha->compsize -= extdsize - 2; if (lha->compsize < 0) goto invalid; /* Invalid compressed file size */ if (sum_calculated != headersum) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, ""LHa header sum error""); return (ARCHIVE_FATAL); } return (err); invalid: archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, ""Invalid LHa header""); return (ARCHIVE_FATAL); }","{'deleted': [], 'added': [{'line_no': 53, 'char_start': 1755, 'char_end': 1779, 'line': '\tif (lha->compsize < 0)\n'}, {'line_no': 54, 'char_start': 1779, 'char_end': 1830, 'line': '\t\tgoto invalid;\t/* Invalid compressed file size */\n'}, {'line_no': 55, 'char_start': 1830, 'char_end': 1831, 'line': '\n'}]}","{'deleted': [], 'added': [{'char_start': 1760, 'char_end': 1836, 'chars': 'lha->compsize < 0)\n\t\tgoto invalid;\t/* Invalid compressed file size */\n\n\tif ('}]}",github.com/libarchive/libarchive/commit/98dcbbf0bf4854bf987557e55e55fff7abbf3ea9,libarchive/archive_read_support_format_lha.c,cwe-125,635 cwe-089,auto_unlock_tasks," @staticmethod def auto_unlock_tasks(project_id: int): """"""Unlock all tasks locked for longer than the auto-unlock delta"""""" expiry_delta = Task.auto_unlock_delta() lock_duration = (datetime.datetime.min + expiry_delta).time().isoformat() expiry_date = datetime.datetime.utcnow() - expiry_delta old_locks_query = '''SELECT t.id FROM tasks t, task_history th WHERE t.id = th.task_id AND t.project_id = th.project_id AND t.task_status IN (1,3) AND th.action IN ( 'LOCKED_FOR_VALIDATION','LOCKED_FOR_MAPPING' ) AND th.action_text IS NULL AND t.project_id = {0} AND th.action_date <= '{1}' '''.format(project_id, str(expiry_date)) old_tasks = db.engine.execute(old_locks_query) if old_tasks.rowcount == 0: # no tasks older than the delta found, return without further processing return for old_task in old_tasks: task = Task.get(old_task[0], project_id) task.auto_unlock_expired_tasks(expiry_date, lock_duration)"," @staticmethod def auto_unlock_tasks(project_id: int): """"""Unlock all tasks locked for longer than the auto-unlock delta"""""" expiry_delta = Task.auto_unlock_delta() lock_duration = (datetime.datetime.min + expiry_delta).time().isoformat() expiry_date = datetime.datetime.utcnow() - expiry_delta old_locks_query = '''SELECT t.id FROM tasks t, task_history th WHERE t.id = th.task_id AND t.project_id = th.project_id AND t.task_status IN (1,3) AND th.action IN ( 'LOCKED_FOR_VALIDATION','LOCKED_FOR_MAPPING' ) AND th.action_text IS NULL AND t.project_id = :project_id AND th.action_date <= :expiry_date ''' old_tasks = db.engine.execute(text(old_locks_query), project_id=project_id, expiry_date=str(expiry_date)) if old_tasks.rowcount == 0: # no tasks older than the delta found, return without further processing return for old_task in old_tasks: task = Task.get(old_task[0], project_id) task.auto_unlock_expired_tasks(expiry_date, lock_duration)","{'deleted': [{'line_no': 14, 'char_start': 652, 'char_end': 687, 'line': ' AND t.project_id = {0}\n'}, {'line_no': 15, 'char_start': 687, 'char_end': 727, 'line': "" AND th.action_date <= '{1}'\n""}, {'line_no': 16, 'char_start': 727, 'char_end': 780, 'line': "" '''.format(project_id, str(expiry_date))\n""}, {'line_no': 18, 'char_start': 781, 'char_end': 836, 'line': ' old_tasks = db.engine.execute(old_locks_query)\n'}], 'added': [{'line_no': 14, 'char_start': 652, 'char_end': 695, 'line': ' AND t.project_id = :project_id\n'}, {'line_no': 15, 'char_start': 695, 'char_end': 742, 'line': ' AND th.action_date <= :expiry_date\n'}, {'line_no': 16, 'char_start': 742, 'char_end': 758, 'line': "" '''\n""}, {'line_no': 18, 'char_start': 759, 'char_end': 873, 'line': ' old_tasks = db.engine.execute(text(old_locks_query), project_id=project_id, expiry_date=str(expiry_date))\n'}]}","{'deleted': [{'char_start': 683, 'char_end': 686, 'chars': '{0}'}, {'char_start': 721, 'char_end': 726, 'chars': ""'{1}'""}, {'char_start': 742, 'char_end': 779, 'chars': '.format(project_id, str(expiry_date))'}], 'added': [{'char_start': 683, 'char_end': 694, 'chars': ':project_id'}, {'char_start': 729, 'char_end': 741, 'chars': ':expiry_date'}, {'char_start': 797, 'char_end': 802, 'chars': 'text('}, {'char_start': 817, 'char_end': 871, 'chars': '), project_id=project_id, expiry_date=str(expiry_date)'}]}",github.com/hotosm/tasking-manager/commit/dee040a2d22b3c4d5e38e2dbf8c6b651ad4c241a,server/models/postgis/task.py,cwe-089,248 cwe-125,ttm_put_pages,"static void ttm_put_pages(struct page **pages, unsigned npages, int flags, enum ttm_caching_state cstate) { struct ttm_page_pool *pool = ttm_get_pool(flags, false, cstate); #ifdef CONFIG_TRANSPARENT_HUGEPAGE struct ttm_page_pool *huge = ttm_get_pool(flags, true, cstate); #endif unsigned long irq_flags; unsigned i; if (pool == NULL) { /* No pool for this memory type so free the pages */ i = 0; while (i < npages) { #ifdef CONFIG_TRANSPARENT_HUGEPAGE struct page *p = pages[i]; #endif unsigned order = 0, j; if (!pages[i]) { ++i; continue; } #ifdef CONFIG_TRANSPARENT_HUGEPAGE if (!(flags & TTM_PAGE_FLAG_DMA32) && (npages - i) >= HPAGE_PMD_NR) { for (j = 1; j < HPAGE_PMD_NR; ++j) if (p++ != pages[i + j]) break; if (j == HPAGE_PMD_NR) order = HPAGE_PMD_ORDER; } #endif if (page_count(pages[i]) != 1) pr_err(""Erroneous page count. Leaking pages.\n""); __free_pages(pages[i], order); j = 1 << order; while (j) { pages[i++] = NULL; --j; } } return; } i = 0; #ifdef CONFIG_TRANSPARENT_HUGEPAGE if (huge) { unsigned max_size, n2free; spin_lock_irqsave(&huge->lock, irq_flags); while ((npages - i) >= HPAGE_PMD_NR) { struct page *p = pages[i]; unsigned j; if (!p) break; for (j = 1; j < HPAGE_PMD_NR; ++j) if (p++ != pages[i + j]) break; if (j != HPAGE_PMD_NR) break; list_add_tail(&pages[i]->lru, &huge->list); for (j = 0; j < HPAGE_PMD_NR; ++j) pages[i++] = NULL; huge->npages++; } /* Check that we don't go over the pool limit */ max_size = _manager->options.max_size; max_size /= HPAGE_PMD_NR; if (huge->npages > max_size) n2free = huge->npages - max_size; else n2free = 0; spin_unlock_irqrestore(&huge->lock, irq_flags); if (n2free) ttm_page_pool_free(huge, n2free, false); } #endif spin_lock_irqsave(&pool->lock, irq_flags); while (i < npages) { if (pages[i]) { if (page_count(pages[i]) != 1) pr_err(""Erroneous page count. Leaking pages.\n""); list_add_tail(&pages[i]->lru, &pool->list); pages[i] = NULL; pool->npages++; } ++i; } /* Check that we don't go over the pool limit */ npages = 0; if (pool->npages > _manager->options.max_size) { npages = pool->npages - _manager->options.max_size; /* free at least NUM_PAGES_TO_ALLOC number of pages * to reduce calls to set_memory_wb */ if (npages < NUM_PAGES_TO_ALLOC) npages = NUM_PAGES_TO_ALLOC; } spin_unlock_irqrestore(&pool->lock, irq_flags); if (npages) ttm_page_pool_free(pool, npages, false); }","static void ttm_put_pages(struct page **pages, unsigned npages, int flags, enum ttm_caching_state cstate) { struct ttm_page_pool *pool = ttm_get_pool(flags, false, cstate); #ifdef CONFIG_TRANSPARENT_HUGEPAGE struct ttm_page_pool *huge = ttm_get_pool(flags, true, cstate); #endif unsigned long irq_flags; unsigned i; if (pool == NULL) { /* No pool for this memory type so free the pages */ i = 0; while (i < npages) { #ifdef CONFIG_TRANSPARENT_HUGEPAGE struct page *p = pages[i]; #endif unsigned order = 0, j; if (!pages[i]) { ++i; continue; } #ifdef CONFIG_TRANSPARENT_HUGEPAGE if (!(flags & TTM_PAGE_FLAG_DMA32) && (npages - i) >= HPAGE_PMD_NR) { for (j = 1; j < HPAGE_PMD_NR; ++j) if (++p != pages[i + j]) break; if (j == HPAGE_PMD_NR) order = HPAGE_PMD_ORDER; } #endif if (page_count(pages[i]) != 1) pr_err(""Erroneous page count. Leaking pages.\n""); __free_pages(pages[i], order); j = 1 << order; while (j) { pages[i++] = NULL; --j; } } return; } i = 0; #ifdef CONFIG_TRANSPARENT_HUGEPAGE if (huge) { unsigned max_size, n2free; spin_lock_irqsave(&huge->lock, irq_flags); while ((npages - i) >= HPAGE_PMD_NR) { struct page *p = pages[i]; unsigned j; if (!p) break; for (j = 1; j < HPAGE_PMD_NR; ++j) if (++p != pages[i + j]) break; if (j != HPAGE_PMD_NR) break; list_add_tail(&pages[i]->lru, &huge->list); for (j = 0; j < HPAGE_PMD_NR; ++j) pages[i++] = NULL; huge->npages++; } /* Check that we don't go over the pool limit */ max_size = _manager->options.max_size; max_size /= HPAGE_PMD_NR; if (huge->npages > max_size) n2free = huge->npages - max_size; else n2free = 0; spin_unlock_irqrestore(&huge->lock, irq_flags); if (n2free) ttm_page_pool_free(huge, n2free, false); } #endif spin_lock_irqsave(&pool->lock, irq_flags); while (i < npages) { if (pages[i]) { if (page_count(pages[i]) != 1) pr_err(""Erroneous page count. Leaking pages.\n""); list_add_tail(&pages[i]->lru, &pool->list); pages[i] = NULL; pool->npages++; } ++i; } /* Check that we don't go over the pool limit */ npages = 0; if (pool->npages > _manager->options.max_size) { npages = pool->npages - _manager->options.max_size; /* free at least NUM_PAGES_TO_ALLOC number of pages * to reduce calls to set_memory_wb */ if (npages < NUM_PAGES_TO_ALLOC) npages = NUM_PAGES_TO_ALLOC; } spin_unlock_irqrestore(&pool->lock, irq_flags); if (npages) ttm_page_pool_free(pool, npages, false); }","{'deleted': [{'line_no': 29, 'char_start': 736, 'char_end': 766, 'line': '\t\t\t\t\tif (p++ != pages[i + j])\n'}, {'line_no': 64, 'char_start': 1344, 'char_end': 1373, 'line': '\t\t\t\tif (p++ != pages[i + j])\n'}], 'added': [{'line_no': 29, 'char_start': 736, 'char_end': 766, 'line': '\t\t\t\t\tif (++p != pages[i + j])\n'}, {'line_no': 64, 'char_start': 1344, 'char_end': 1373, 'line': '\t\t\t\tif (++p != pages[i + j])\n'}]}","{'deleted': [{'char_start': 745, 'char_end': 746, 'chars': 'p'}, {'char_start': 1352, 'char_end': 1353, 'chars': 'p'}], 'added': [{'char_start': 747, 'char_end': 748, 'chars': 'p'}, {'char_start': 1354, 'char_end': 1355, 'chars': 'p'}]}",github.com/torvalds/linux/commit/453393369dc9806d2455151e329c599684762428,drivers/gpu/drm/ttm/ttm_page_alloc.c,cwe-125,854 cwe-125,CSoundFile::GetLength,"std::vector CSoundFile::GetLength(enmGetLengthResetMode adjustMode, GetLengthTarget target) { std::vector results; GetLengthType retval; retval.startOrder = target.startOrder; retval.startRow = target.startRow; // Are we trying to reach a certain pattern position? const bool hasSearchTarget = target.mode != GetLengthTarget::NoTarget; const bool adjustSamplePos = (adjustMode & eAdjustSamplePositions) == eAdjustSamplePositions; SEQUENCEINDEX sequence = target.sequence; if(sequence >= Order.GetNumSequences()) sequence = Order.GetCurrentSequenceIndex(); const ModSequence &orderList = Order(sequence); GetLengthMemory memory(*this); CSoundFile::PlayState &playState = *memory.state; // Temporary visited rows vector (so that GetLength() won't interfere with the player code if the module is playing at the same time) RowVisitor visitedRows(*this, sequence); playState.m_nNextRow = playState.m_nRow = target.startRow; playState.m_nNextOrder = playState.m_nCurrentOrder = target.startOrder; // Fast LUTs for commands that are too weird / complicated / whatever to emulate in sample position adjust mode. std::bitset forbiddenCommands; std::bitset forbiddenVolCommands; if(adjustSamplePos) { forbiddenCommands.set(CMD_ARPEGGIO); forbiddenCommands.set(CMD_PORTAMENTOUP); forbiddenCommands.set(CMD_PORTAMENTODOWN); forbiddenCommands.set(CMD_XFINEPORTAUPDOWN); forbiddenCommands.set(CMD_NOTESLIDEUP); forbiddenCommands.set(CMD_NOTESLIDEUPRETRIG); forbiddenCommands.set(CMD_NOTESLIDEDOWN); forbiddenCommands.set(CMD_NOTESLIDEDOWNRETRIG); forbiddenVolCommands.set(VOLCMD_PORTAUP); forbiddenVolCommands.set(VOLCMD_PORTADOWN); // Optimize away channels for which it's pointless to adjust sample positions for(CHANNELINDEX i = 0; i < GetNumChannels(); i++) { if(ChnSettings[i].dwFlags[CHN_MUTE]) memory.chnSettings[i].ticksToRender = GetLengthMemory::IGNORE_CHANNEL; } if(target.mode == GetLengthTarget::SeekPosition && target.pos.order < orderList.size()) { // If we know where to seek, we can directly rule out any channels on which a new note would be triggered right at the start. const PATTERNINDEX seekPat = orderList[target.pos.order]; if(Patterns.IsValidPat(seekPat) && Patterns[seekPat].IsValidRow(target.pos.row)) { const ModCommand *m = Patterns[seekPat].GetRow(target.pos.row); for(CHANNELINDEX i = 0; i < GetNumChannels(); i++, m++) { if(m->note == NOTE_NOTECUT || m->note == NOTE_KEYOFF || (m->note == NOTE_FADE && GetNumInstruments()) || (m->IsNote() && !m->IsPortamento())) { memory.chnSettings[i].ticksToRender = GetLengthMemory::IGNORE_CHANNEL; } } } } } // If samples are being synced, force them to resync if tick duration changes uint32 oldTickDuration = 0; for (;;) { // Time target reached. if(target.mode == GetLengthTarget::SeekSeconds && memory.elapsedTime >= target.time) { retval.targetReached = true; break; } uint32 rowDelay = 0, tickDelay = 0; playState.m_nRow = playState.m_nNextRow; playState.m_nCurrentOrder = playState.m_nNextOrder; if(orderList.IsValidPat(playState.m_nCurrentOrder) && playState.m_nRow >= Patterns[orderList[playState.m_nCurrentOrder]].GetNumRows()) { playState.m_nRow = 0; if(m_playBehaviour[kFT2LoopE60Restart]) { playState.m_nRow = playState.m_nNextPatStartRow; playState.m_nNextPatStartRow = 0; } playState.m_nCurrentOrder = ++playState.m_nNextOrder; } // Check if pattern is valid playState.m_nPattern = playState.m_nCurrentOrder < orderList.size() ? orderList[playState.m_nCurrentOrder] : orderList.GetInvalidPatIndex(); bool positionJumpOnThisRow = false; bool patternBreakOnThisRow = false; bool patternLoopEndedOnThisRow = false, patternLoopStartedOnThisRow = false; if(!Patterns.IsValidPat(playState.m_nPattern) && playState.m_nPattern != orderList.GetInvalidPatIndex() && target.mode == GetLengthTarget::SeekPosition && playState.m_nCurrentOrder == target.pos.order) { // Early test: Target is inside +++ or non-existing pattern retval.targetReached = true; break; } while(playState.m_nPattern >= Patterns.Size()) { // End of song? if((playState.m_nPattern == orderList.GetInvalidPatIndex()) || (playState.m_nCurrentOrder >= orderList.size())) { if(playState.m_nCurrentOrder == orderList.GetRestartPos()) break; else playState.m_nCurrentOrder = orderList.GetRestartPos(); } else { playState.m_nCurrentOrder++; } playState.m_nPattern = (playState.m_nCurrentOrder < orderList.size()) ? orderList[playState.m_nCurrentOrder] : orderList.GetInvalidPatIndex(); playState.m_nNextOrder = playState.m_nCurrentOrder; if((!Patterns.IsValidPat(playState.m_nPattern)) && visitedRows.IsVisited(playState.m_nCurrentOrder, 0, true)) { if(!hasSearchTarget || !visitedRows.GetFirstUnvisitedRow(playState.m_nNextOrder, playState.m_nRow, true)) { // We aren't searching for a specific row, or we couldn't find any more unvisited rows. break; } else { // We haven't found the target row yet, but we found some other unplayed row... continue searching from here. retval.duration = memory.elapsedTime; results.push_back(retval); retval.startRow = playState.m_nRow; retval.startOrder = playState.m_nNextOrder; memory.Reset(); playState.m_nCurrentOrder = playState.m_nNextOrder; playState.m_nPattern = orderList[playState.m_nCurrentOrder]; playState.m_nNextRow = playState.m_nRow; break; } } } if(playState.m_nNextOrder == ORDERINDEX_INVALID) { // GetFirstUnvisitedRow failed, so there is nothing more to play break; } // Skip non-existing patterns if(!Patterns.IsValidPat(playState.m_nPattern)) { // If there isn't even a tune, we should probably stop here. if(playState.m_nCurrentOrder == orderList.GetRestartPos()) { if(!hasSearchTarget || !visitedRows.GetFirstUnvisitedRow(playState.m_nNextOrder, playState.m_nRow, true)) { // We aren't searching for a specific row, or we couldn't find any more unvisited rows. break; } else { // We haven't found the target row yet, but we found some other unplayed row... continue searching from here. retval.duration = memory.elapsedTime; results.push_back(retval); retval.startRow = playState.m_nRow; retval.startOrder = playState.m_nNextOrder; memory.Reset(); playState.m_nNextRow = playState.m_nRow; continue; } } playState.m_nNextOrder = playState.m_nCurrentOrder + 1; continue; } // Should never happen if(playState.m_nRow >= Patterns[playState.m_nPattern].GetNumRows()) playState.m_nRow = 0; // Check whether target was reached. if(target.mode == GetLengthTarget::SeekPosition && playState.m_nCurrentOrder == target.pos.order && playState.m_nRow == target.pos.row) { retval.targetReached = true; break; } if(visitedRows.IsVisited(playState.m_nCurrentOrder, playState.m_nRow, true)) { if(!hasSearchTarget || !visitedRows.GetFirstUnvisitedRow(playState.m_nNextOrder, playState.m_nRow, true)) { // We aren't searching for a specific row, or we couldn't find any more unvisited rows. break; } else { // We haven't found the target row yet, but we found some other unplayed row... continue searching from here. retval.duration = memory.elapsedTime; results.push_back(retval); retval.startRow = playState.m_nRow; retval.startOrder = playState.m_nNextOrder; memory.Reset(); playState.m_nNextRow = playState.m_nRow; continue; } } retval.endOrder = playState.m_nCurrentOrder; retval.endRow = playState.m_nRow; // Update next position playState.m_nNextRow = playState.m_nRow + 1; // Jumped to invalid pattern row? if(playState.m_nRow >= Patterns[playState.m_nPattern].GetNumRows()) { playState.m_nRow = 0; } // New pattern? if(!playState.m_nRow) { for(CHANNELINDEX chn = 0; chn < GetNumChannels(); chn++) { memory.chnSettings[chn].patLoop = memory.elapsedTime; memory.chnSettings[chn].patLoopSmp = playState.m_lTotalSampleCount; } } ModChannel *pChn = playState.Chn; // For various effects, we need to know first how many ticks there are in this row. const ModCommand *p = Patterns[playState.m_nPattern].GetpModCommand(playState.m_nRow, 0); for(CHANNELINDEX nChn = 0; nChn < GetNumChannels(); nChn++, p++) { if(m_playBehaviour[kST3NoMutedChannels] && ChnSettings[nChn].dwFlags[CHN_MUTE]) // not even effects are processed on muted S3M channels continue; if(p->IsPcNote()) { #ifndef NO_PLUGINS if((adjustMode & eAdjust) && p->instr > 0 && p->instr <= MAX_MIXPLUGINS) { memory.plugParams[std::make_pair(p->instr, p->GetValueVolCol())] = p->GetValueEffectCol(); } #endif // NO_PLUGINS pChn[nChn].rowCommand.Clear(); continue; } pChn[nChn].rowCommand = *p; switch(p->command) { case CMD_SPEED: SetSpeed(playState, p->param); break; case CMD_TEMPO: if(m_playBehaviour[kMODVBlankTiming]) { // ProTracker MODs with VBlank timing: All Fxx parameters set the tick count. if(p->param != 0) SetSpeed(playState, p->param); } break; case CMD_S3MCMDEX: if((p->param & 0xF0) == 0x60) { // Fine Pattern Delay tickDelay += (p->param & 0x0F); } else if((p->param & 0xF0) == 0xE0 && !rowDelay) { // Pattern Delay if(!(GetType() & MOD_TYPE_S3M) || (p->param & 0x0F) != 0) { // While Impulse Tracker *does* count S60 as a valid row delay (and thus ignores any other row delay commands on the right), // Scream Tracker 3 simply ignores such commands. rowDelay = 1 + (p->param & 0x0F); } } break; case CMD_MODCMDEX: if((p->param & 0xF0) == 0xE0) { // Pattern Delay rowDelay = 1 + (p->param & 0x0F); } break; } } if(rowDelay == 0) rowDelay = 1; const uint32 numTicks = (playState.m_nMusicSpeed + tickDelay) * rowDelay; const uint32 nonRowTicks = numTicks - rowDelay; for(CHANNELINDEX nChn = 0; nChn < GetNumChannels(); pChn++, nChn++) if(!pChn->rowCommand.IsEmpty()) { if(m_playBehaviour[kST3NoMutedChannels] && ChnSettings[nChn].dwFlags[CHN_MUTE]) // not even effects are processed on muted S3M channels continue; ModCommand::COMMAND command = pChn->rowCommand.command; ModCommand::PARAM param = pChn->rowCommand.param; ModCommand::NOTE note = pChn->rowCommand.note; if (pChn->rowCommand.instr) { pChn->nNewIns = pChn->rowCommand.instr; pChn->nLastNote = NOTE_NONE; memory.chnSettings[nChn].vol = 0xFF; } if (pChn->rowCommand.IsNote()) pChn->nLastNote = note; // Update channel panning if(pChn->rowCommand.IsNote() || pChn->rowCommand.instr) { SAMPLEINDEX smp = 0; if(GetNumInstruments()) { ModInstrument *pIns; if(pChn->nNewIns <= GetNumInstruments() && (pIns = Instruments[pChn->nNewIns]) != nullptr) { if(pIns->dwFlags[INS_SETPANNING]) pChn->nPan = pIns->nPan; if(ModCommand::IsNote(note)) smp = pIns->Keyboard[note - NOTE_MIN]; } } else { smp = pChn->nNewIns; } if(smp > 0 && smp <= GetNumSamples() && Samples[smp].uFlags[CHN_PANNING]) { pChn->nPan = Samples[smp].nPan; } } switch(pChn->rowCommand.volcmd) { case VOLCMD_VOLUME: memory.chnSettings[nChn].vol = pChn->rowCommand.vol; break; case VOLCMD_VOLSLIDEUP: case VOLCMD_VOLSLIDEDOWN: if(pChn->rowCommand.vol != 0) pChn->nOldVolParam = pChn->rowCommand.vol; break; } switch(command) { // Position Jump case CMD_POSITIONJUMP: positionJumpOnThisRow = true; playState.m_nNextOrder = static_cast(CalculateXParam(playState.m_nPattern, playState.m_nRow, nChn)); playState.m_nNextPatStartRow = 0; // FT2 E60 bug // see https://forum.openmpt.org/index.php?topic=2769.0 - FastTracker resets Dxx if Bxx is called _after_ Dxx // Test case: PatternJump.mod if(!patternBreakOnThisRow || (GetType() & (MOD_TYPE_MOD | MOD_TYPE_XM))) playState.m_nNextRow = 0; if (adjustMode & eAdjust) { pChn->nPatternLoopCount = 0; pChn->nPatternLoop = 0; } break; // Pattern Break case CMD_PATTERNBREAK: { ROWINDEX row = PatternBreak(playState, nChn, param); if(row != ROWINDEX_INVALID) { patternBreakOnThisRow = true; playState.m_nNextRow = row; if(!positionJumpOnThisRow) { playState.m_nNextOrder = playState.m_nCurrentOrder + 1; } if(adjustMode & eAdjust) { pChn->nPatternLoopCount = 0; pChn->nPatternLoop = 0; } } } break; // Set Tempo case CMD_TEMPO: if(!m_playBehaviour[kMODVBlankTiming]) { TEMPO tempo(CalculateXParam(playState.m_nPattern, playState.m_nRow, nChn), 0); if ((adjustMode & eAdjust) && (GetType() & (MOD_TYPE_S3M | MOD_TYPE_IT | MOD_TYPE_MPT))) { if (tempo.GetInt()) pChn->nOldTempo = static_cast(tempo.GetInt()); else tempo.Set(pChn->nOldTempo); } if (tempo.GetInt() >= 0x20) playState.m_nMusicTempo = tempo; else { // Tempo Slide TEMPO tempoDiff((tempo.GetInt() & 0x0F) * nonRowTicks, 0); if ((tempo.GetInt() & 0xF0) == 0x10) { playState.m_nMusicTempo += tempoDiff; } else { if(tempoDiff < playState.m_nMusicTempo) playState.m_nMusicTempo -= tempoDiff; else playState.m_nMusicTempo.Set(0); } } TEMPO tempoMin = GetModSpecifications().GetTempoMin(), tempoMax = GetModSpecifications().GetTempoMax(); if(m_playBehaviour[kTempoClamp]) // clamp tempo correctly in compatible mode { tempoMax.Set(255); } Limit(playState.m_nMusicTempo, tempoMin, tempoMax); } break; case CMD_S3MCMDEX: switch(param & 0xF0) { case 0x90: if(param <= 0x91) { pChn->dwFlags.set(CHN_SURROUND, param == 0x91); } break; case 0xA0: // High sample offset pChn->nOldHiOffset = param & 0x0F; break; case 0xB0: // Pattern Loop if (param & 0x0F) { patternLoopEndedOnThisRow = true; } else { CHANNELINDEX firstChn = nChn, lastChn = nChn; if(GetType() == MOD_TYPE_S3M) { // ST3 has only one global loop memory. firstChn = 0; lastChn = GetNumChannels() - 1; } for(CHANNELINDEX c = firstChn; c <= lastChn; c++) { memory.chnSettings[c].patLoop = memory.elapsedTime; memory.chnSettings[c].patLoopSmp = playState.m_lTotalSampleCount; memory.chnSettings[c].patLoopStart = playState.m_nRow; } patternLoopStartedOnThisRow = true; } break; case 0xF0: // Active macro pChn->nActiveMacro = param & 0x0F; break; } break; case CMD_MODCMDEX: switch(param & 0xF0) { case 0x60: // Pattern Loop if (param & 0x0F) { playState.m_nNextPatStartRow = memory.chnSettings[nChn].patLoopStart; // FT2 E60 bug patternLoopEndedOnThisRow = true; } else { patternLoopStartedOnThisRow = true; memory.chnSettings[nChn].patLoop = memory.elapsedTime; memory.chnSettings[nChn].patLoopSmp = playState.m_lTotalSampleCount; memory.chnSettings[nChn].patLoopStart = playState.m_nRow; } break; case 0xF0: // Active macro pChn->nActiveMacro = param & 0x0F; break; } break; case CMD_XFINEPORTAUPDOWN: // ignore high offset in compatible mode if(((param & 0xF0) == 0xA0) && !m_playBehaviour[kFT2RestrictXCommand]) pChn->nOldHiOffset = param & 0x0F; break; } // The following calculations are not interesting if we just want to get the song length. if (!(adjustMode & eAdjust)) continue; switch(command) { // Portamento Up/Down case CMD_PORTAMENTOUP: if(param) { // FT2 compatibility: Separate effect memory for all portamento commands // Test case: Porta-LinkMem.xm if(!m_playBehaviour[kFT2PortaUpDownMemory]) pChn->nOldPortaDown = param; pChn->nOldPortaUp = param; } break; case CMD_PORTAMENTODOWN: if(param) { // FT2 compatibility: Separate effect memory for all portamento commands // Test case: Porta-LinkMem.xm if(!m_playBehaviour[kFT2PortaUpDownMemory]) pChn->nOldPortaUp = param; pChn->nOldPortaDown = param; } break; // Tone-Portamento case CMD_TONEPORTAMENTO: if (param) pChn->nPortamentoSlide = param << 2; break; // Offset case CMD_OFFSET: if (param) pChn->oldOffset = param << 8; break; // Volume Slide case CMD_VOLUMESLIDE: case CMD_TONEPORTAVOL: if (param) pChn->nOldVolumeSlide = param; break; // Set Volume case CMD_VOLUME: memory.chnSettings[nChn].vol = param; break; // Global Volume case CMD_GLOBALVOLUME: if(!(GetType() & GLOBALVOL_7BIT_FORMATS) && param < 128) param *= 2; // IT compatibility 16. ST3 and IT ignore out-of-range values if(param <= 128) { playState.m_nGlobalVolume = param * 2; } else if(!(GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT | MOD_TYPE_S3M))) { playState.m_nGlobalVolume = 256; } break; // Global Volume Slide case CMD_GLOBALVOLSLIDE: if(m_playBehaviour[kPerChannelGlobalVolSlide]) { // IT compatibility 16. Global volume slide params are stored per channel (FT2/IT) if (param) pChn->nOldGlobalVolSlide = param; else param = pChn->nOldGlobalVolSlide; } else { if (param) playState.Chn[0].nOldGlobalVolSlide = param; else param = playState.Chn[0].nOldGlobalVolSlide; } if (((param & 0x0F) == 0x0F) && (param & 0xF0)) { param >>= 4; if (!(GetType() & GLOBALVOL_7BIT_FORMATS)) param <<= 1; playState.m_nGlobalVolume += param << 1; } else if (((param & 0xF0) == 0xF0) && (param & 0x0F)) { param = (param & 0x0F) << 1; if (!(GetType() & GLOBALVOL_7BIT_FORMATS)) param <<= 1; playState.m_nGlobalVolume -= param; } else if (param & 0xF0) { param >>= 4; param <<= 1; if (!(GetType() & GLOBALVOL_7BIT_FORMATS)) param <<= 1; playState.m_nGlobalVolume += param * nonRowTicks; } else { param = (param & 0x0F) << 1; if (!(GetType() & GLOBALVOL_7BIT_FORMATS)) param <<= 1; playState.m_nGlobalVolume -= param * nonRowTicks; } Limit(playState.m_nGlobalVolume, 0, 256); break; case CMD_CHANNELVOLUME: if (param <= 64) pChn->nGlobalVol = param; break; case CMD_CHANNELVOLSLIDE: { if (param) pChn->nOldChnVolSlide = param; else param = pChn->nOldChnVolSlide; int32 volume = pChn->nGlobalVol; if((param & 0x0F) == 0x0F && (param & 0xF0)) volume += (param >> 4); // Fine Up else if((param & 0xF0) == 0xF0 && (param & 0x0F)) volume -= (param & 0x0F); // Fine Down else if(param & 0x0F) // Down volume -= (param & 0x0F) * nonRowTicks; else // Up volume += ((param & 0xF0) >> 4) * nonRowTicks; Limit(volume, 0, 64); pChn->nGlobalVol = volume; } break; case CMD_PANNING8: Panning(pChn, param, Pan8bit); break; case CMD_MODCMDEX: if(param < 0x10) { // LED filter for(CHANNELINDEX chn = 0; chn < GetNumChannels(); chn++) { playState.Chn[chn].dwFlags.set(CHN_AMIGAFILTER, !(param & 1)); } } MPT_FALLTHROUGH; case CMD_S3MCMDEX: if((param & 0xF0) == 0x80) { Panning(pChn, (param & 0x0F), Pan4bit); } break; case CMD_VIBRATOVOL: if (param) pChn->nOldVolumeSlide = param; param = 0; MPT_FALLTHROUGH; case CMD_VIBRATO: Vibrato(pChn, param); break; case CMD_FINEVIBRATO: FineVibrato(pChn, param); break; case CMD_TREMOLO: Tremolo(pChn, param); break; case CMD_PANBRELLO: Panbrello(pChn, param); break; } switch(pChn->rowCommand.volcmd) { case VOLCMD_PANNING: Panning(pChn, pChn->rowCommand.vol, Pan6bit); break; case VOLCMD_VIBRATOSPEED: // FT2 does not automatically enable vibrato with the ""set vibrato speed"" command if(m_playBehaviour[kFT2VolColVibrato]) pChn->nVibratoSpeed = pChn->rowCommand.vol & 0x0F; else Vibrato(pChn, pChn->rowCommand.vol << 4); break; case VOLCMD_VIBRATODEPTH: Vibrato(pChn, pChn->rowCommand.vol); break; } // Process vibrato / tremolo / panbrello switch(pChn->rowCommand.command) { case CMD_VIBRATO: case CMD_FINEVIBRATO: case CMD_VIBRATOVOL: if(adjustMode & eAdjust) { uint32 vibTicks = ((GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT)) && !m_SongFlags[SONG_ITOLDEFFECTS]) ? numTicks : nonRowTicks; uint32 inc = pChn->nVibratoSpeed * vibTicks; if(m_playBehaviour[kITVibratoTremoloPanbrello]) inc *= 4; pChn->nVibratoPos += static_cast(inc); } break; case CMD_TREMOLO: if(adjustMode & eAdjust) { uint32 tremTicks = ((GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT)) && !m_SongFlags[SONG_ITOLDEFFECTS]) ? numTicks : nonRowTicks; uint32 inc = pChn->nTremoloSpeed * tremTicks; if(m_playBehaviour[kITVibratoTremoloPanbrello]) inc *= 4; pChn->nTremoloPos += static_cast(inc); } break; case CMD_PANBRELLO: if(adjustMode & eAdjust) { // Panbrello effect is permanent in compatible mode, so actually apply panbrello for the last tick of this row pChn->nPanbrelloPos += static_cast(pChn->nPanbrelloSpeed * (numTicks - 1)); ProcessPanbrello(pChn); } break; } } // Interpret F00 effect in XM files as ""stop song"" if(GetType() == MOD_TYPE_XM && playState.m_nMusicSpeed == uint16_max) { break; } playState.m_nCurrentRowsPerBeat = m_nDefaultRowsPerBeat; if(Patterns[playState.m_nPattern].GetOverrideSignature()) { playState.m_nCurrentRowsPerBeat = Patterns[playState.m_nPattern].GetRowsPerBeat(); } const uint32 tickDuration = GetTickDuration(playState); const uint32 rowDuration = tickDuration * numTicks; memory.elapsedTime += static_cast(rowDuration) / static_cast(m_MixerSettings.gdwMixingFreq); playState.m_lTotalSampleCount += rowDuration; if(adjustSamplePos) { // Super experimental and dirty sample seeking pChn = playState.Chn; for(CHANNELINDEX nChn = 0; nChn < GetNumChannels(); pChn++, nChn++) { if(memory.chnSettings[nChn].ticksToRender == GetLengthMemory::IGNORE_CHANNEL) continue; uint32 startTick = 0; const ModCommand &m = pChn->rowCommand; uint32 paramHi = m.param >> 4, paramLo = m.param & 0x0F; bool porta = m.command == CMD_TONEPORTAMENTO || m.command == CMD_TONEPORTAVOL || m.volcmd == VOLCMD_TONEPORTAMENTO; bool stopNote = patternLoopStartedOnThisRow; // It's too much trouble to keep those pattern loops in sync... if(m.instr) pChn->proTrackerOffset = 0; if(m.IsNote()) { if(porta && memory.chnSettings[nChn].incChanged) { // If there's a portamento, the current channel increment mustn't be 0 in NoteChange() pChn->increment = GetChannelIncrement(pChn, pChn->nPeriod, 0); } int32 setPan = pChn->nPan; pChn->nNewNote = pChn->nLastNote; if(pChn->nNewIns != 0) InstrumentChange(pChn, pChn->nNewIns, porta); NoteChange(pChn, m.note, porta); memory.chnSettings[nChn].incChanged = true; if((m.command == CMD_MODCMDEX || m.command == CMD_S3MCMDEX) && (m.param & 0xF0) == 0xD0 && paramLo < numTicks) { startTick = paramLo; } else if(m.command == CMD_DELAYCUT && paramHi < numTicks) { startTick = paramHi; } if(rowDelay > 1 && startTick != 0 && (GetType() & (MOD_TYPE_S3M | MOD_TYPE_IT | MOD_TYPE_MPT))) { startTick += (playState.m_nMusicSpeed + tickDelay) * (rowDelay - 1); } if(!porta) memory.chnSettings[nChn].ticksToRender = 0; // Panning commands have to be re-applied after a note change with potential pan change. if(m.command == CMD_PANNING8 || ((m.command == CMD_MODCMDEX || m.command == CMD_S3MCMDEX) && paramHi == 0x8) || m.volcmd == VOLCMD_PANNING) { pChn->nPan = setPan; } if(m.command == CMD_OFFSET) { bool isExtended = false; SmpLength offset = CalculateXParam(playState.m_nPattern, playState.m_nRow, nChn, &isExtended); if(!isExtended) { offset <<= 8; if(offset == 0) offset = pChn->oldOffset; offset += static_cast(pChn->nOldHiOffset) << 16; } SampleOffset(*pChn, offset); } else if(m.command == CMD_OFFSETPERCENTAGE) { SampleOffset(*pChn, Util::muldiv_unsigned(pChn->nLength, m.param, 255)); } else if(m.command == CMD_REVERSEOFFSET && pChn->pModSample != nullptr) { memory.RenderChannel(nChn, oldTickDuration); // Re-sync what we've got so far ReverseSampleOffset(*pChn, m.param); startTick = playState.m_nMusicSpeed - 1; } else if(m.volcmd == VOLCMD_OFFSET) { if(m.vol <= CountOf(pChn->pModSample->cues) && pChn->pModSample != nullptr) { SmpLength offset; if(m.vol == 0) offset = pChn->oldOffset; else offset = pChn->oldOffset = pChn->pModSample->cues[m.vol - 1]; SampleOffset(*pChn, offset); } } } if(m.note == NOTE_KEYOFF || m.note == NOTE_NOTECUT || (m.note == NOTE_FADE && GetNumInstruments()) || ((m.command == CMD_MODCMDEX || m.command == CMD_S3MCMDEX) && (m.param & 0xF0) == 0xC0 && paramLo < numTicks) || (m.command == CMD_DELAYCUT && paramLo != 0 && startTick + paramLo < numTicks)) { stopNote = true; } if(m.command == CMD_VOLUME) { pChn->nVolume = m.param * 4; } else if(m.volcmd == VOLCMD_VOLUME) { pChn->nVolume = m.vol * 4; } if(pChn->pModSample && !stopNote) { // Check if we don't want to emulate some effect and thus stop processing. if(m.command < MAX_EFFECTS) { if(forbiddenCommands[m.command]) { stopNote = true; } else if(m.command == CMD_MODCMDEX) { // Special case: Slides using extended commands switch(m.param & 0xF0) { case 0x10: case 0x20: stopNote = true; } } } if(m.volcmd < forbiddenVolCommands.size() && forbiddenVolCommands[m.volcmd]) { stopNote = true; } } if(stopNote) { pChn->Stop(); memory.chnSettings[nChn].ticksToRender = 0; } else { if(oldTickDuration != tickDuration && oldTickDuration != 0) { memory.RenderChannel(nChn, oldTickDuration); // Re-sync what we've got so far } switch(m.command) { case CMD_TONEPORTAVOL: case CMD_VOLUMESLIDE: case CMD_VIBRATOVOL: if(m.param || (GetType() != MOD_TYPE_MOD)) { for(uint32 i = 0; i < numTicks; i++) { pChn->isFirstTick = (i == 0); VolumeSlide(pChn, m.param); } } break; case CMD_MODCMDEX: if((m.param & 0x0F) || (GetType() & (MOD_TYPE_XM | MOD_TYPE_MT2))) { pChn->isFirstTick = true; switch(m.param & 0xF0) { case 0xA0: FineVolumeUp(pChn, m.param & 0x0F, false); break; case 0xB0: FineVolumeDown(pChn, m.param & 0x0F, false); break; } } break; case CMD_S3MCMDEX: if(m.param == 0x9E) { // Play forward memory.RenderChannel(nChn, oldTickDuration); // Re-sync what we've got so far pChn->dwFlags.reset(CHN_PINGPONGFLAG); } else if(m.param == 0x9F) { // Reverse memory.RenderChannel(nChn, oldTickDuration); // Re-sync what we've got so far pChn->dwFlags.set(CHN_PINGPONGFLAG); if(!pChn->position.GetInt() && pChn->nLength && (m.IsNote() || !pChn->dwFlags[CHN_LOOP])) { pChn->position.Set(pChn->nLength - 1, SamplePosition::fractMax); } } else if((m.param & 0xF0) == 0x70) { // TODO //ExtendedS3MCommands(nChn, param); } break; } pChn->isFirstTick = true; switch(m.volcmd) { case VOLCMD_FINEVOLUP: FineVolumeUp(pChn, m.vol, m_playBehaviour[kITVolColMemory]); break; case VOLCMD_FINEVOLDOWN: FineVolumeDown(pChn, m.vol, m_playBehaviour[kITVolColMemory]); break; case VOLCMD_VOLSLIDEUP: case VOLCMD_VOLSLIDEDOWN: { // IT Compatibility: Volume column volume slides have their own memory // Test case: VolColMemory.it ModCommand::VOL vol = m.vol; if(vol == 0 && m_playBehaviour[kITVolColMemory]) { vol = pChn->nOldVolParam; if(vol == 0) break; } if(m.volcmd == VOLCMD_VOLSLIDEUP) vol <<= 4; for(uint32 i = 0; i < numTicks; i++) { pChn->isFirstTick = (i == 0); VolumeSlide(pChn, vol); } } break; } if(porta) { // Portamento needs immediate syncing, as the pitch changes on each tick uint32 portaTick = memory.chnSettings[nChn].ticksToRender + startTick + 1; memory.chnSettings[nChn].ticksToRender += numTicks; memory.RenderChannel(nChn, tickDuration, portaTick); } else { memory.chnSettings[nChn].ticksToRender += (numTicks - startTick); } } } } oldTickDuration = tickDuration; // Pattern loop is not executed in FT2 if there are any position jump or pattern break commands on the same row. // Pattern loop is not executed in IT if there are any position jump commands on the same row. // Test case for FT2 exception: PatLoop-Jumps.xm, PatLoop-Various.xm // Test case for IT: exception: LoopBreak.it if(patternLoopEndedOnThisRow && (!m_playBehaviour[kFT2PatternLoopWithJumps] || !(positionJumpOnThisRow || patternBreakOnThisRow)) && (!m_playBehaviour[kITPatternLoopWithJumps] || !positionJumpOnThisRow)) { std::map startTimes; // This is really just a simple estimation for nested pattern loops. It should handle cases correctly where all parallel loops start and end on the same row. // If one of them starts or ends ""in between"", it will most likely calculate a wrong duration. // For S3M files, it's also way off. pChn = playState.Chn; for(CHANNELINDEX nChn = 0; nChn < GetNumChannels(); nChn++, pChn++) { ModCommand::COMMAND command = pChn->rowCommand.command; ModCommand::PARAM param = pChn->rowCommand.param; if((command == CMD_S3MCMDEX && param >= 0xB1 && param <= 0xBF) || (command == CMD_MODCMDEX && param >= 0x61 && param <= 0x6F)) { const double start = memory.chnSettings[nChn].patLoop; if(!startTimes[start]) startTimes[start] = 1; startTimes[start] = mpt::lcm(startTimes[start], 1 + (param & 0x0F)); } } for(const auto &i : startTimes) { memory.elapsedTime += (memory.elapsedTime - i.first) * (double)(i.second - 1); for(CHANNELINDEX nChn = 0; nChn < GetNumChannels(); nChn++, pChn++) { if(memory.chnSettings[nChn].patLoop == i.first) { playState.m_lTotalSampleCount += (playState.m_lTotalSampleCount - memory.chnSettings[nChn].patLoopSmp) * (i.second - 1); if(m_playBehaviour[kITPatternLoopTargetReset] || (GetType() == MOD_TYPE_S3M)) { memory.chnSettings[nChn].patLoop = memory.elapsedTime; memory.chnSettings[nChn].patLoopSmp = playState.m_lTotalSampleCount; memory.chnSettings[nChn].patLoopStart = playState.m_nRow + 1; } break; } } } if(GetType() == MOD_TYPE_IT) { // IT pattern loop start row update - at the end of a pattern loop, set pattern loop start to next row (for upcoming pattern loops with missing SB0) for(CHANNELINDEX nChn = 0; nChn < GetNumChannels(); nChn++) { if((pChn->rowCommand.command == CMD_S3MCMDEX && pChn->rowCommand.param >= 0xB1 && pChn->rowCommand.param <= 0xBF)) { memory.chnSettings[nChn].patLoop = memory.elapsedTime; memory.chnSettings[nChn].patLoopSmp = playState.m_lTotalSampleCount; } } } } } // Now advance the sample positions for sample seeking on channels that are still playing if(adjustSamplePos) { for(CHANNELINDEX nChn = 0; nChn < GetNumChannels(); nChn++) { if(memory.chnSettings[nChn].ticksToRender != GetLengthMemory::IGNORE_CHANNEL) { memory.RenderChannel(nChn, oldTickDuration); } } } if(retval.targetReached || target.mode == GetLengthTarget::NoTarget) { retval.lastOrder = playState.m_nCurrentOrder; retval.lastRow = playState.m_nRow; } retval.duration = memory.elapsedTime; results.push_back(retval); // Store final variables if(adjustMode & eAdjust) { if(retval.targetReached || target.mode == GetLengthTarget::NoTarget) { // Target found, or there is no target (i.e. play whole song)... m_PlayState = std::move(playState); m_PlayState.m_nNextRow = m_PlayState.m_nRow; m_PlayState.m_nFrameDelay = m_PlayState.m_nPatternDelay = 0; m_PlayState.m_nTickCount = Util::MaxValueOfType(m_PlayState.m_nTickCount) - 1; m_PlayState.m_bPositionChanged = true; for(CHANNELINDEX n = 0; n < GetNumChannels(); n++) { if(m_PlayState.Chn[n].nLastNote != NOTE_NONE) { m_PlayState.Chn[n].nNewNote = m_PlayState.Chn[n].nLastNote; } if(memory.chnSettings[n].vol != 0xFF && !adjustSamplePos) { m_PlayState.Chn[n].nVolume = std::min(memory.chnSettings[n].vol, uint8(64)) * 4; } } #ifndef NO_PLUGINS // If there were any PC events, update plugin parameters to their latest value. std::bitset plugSetProgram; for(const auto ¶m : memory.plugParams) { PLUGINDEX plug = param.first.first - 1; IMixPlugin *plugin = m_MixPlugins[plug].pMixPlugin; if(plugin != nullptr) { if(!plugSetProgram[plug]) { // Used for bridged plugins to avoid sending out individual messages for each parameter. plugSetProgram.set(plug); plugin->BeginSetProgram(); } plugin->SetParameter(param.first.second, param.second / PlugParamValue(ModCommand::maxColumnValue)); } } if(plugSetProgram.any()) { for(PLUGINDEX i = 0; i < MAX_MIXPLUGINS; i++) { if(plugSetProgram[i]) { m_MixPlugins[i].pMixPlugin->EndSetProgram(); } } } #endif // NO_PLUGINS } else if(adjustMode != eAdjustOnSuccess) { // Target not found (e.g. when jumping to a hidden sub song), reset global variables... m_PlayState.m_nMusicSpeed = m_nDefaultSpeed; m_PlayState.m_nMusicTempo = m_nDefaultTempo; m_PlayState.m_nGlobalVolume = m_nDefaultGlobalVolume; } // When adjusting the playback status, we will also want to update the visited rows vector according to the current position. if(sequence != Order.GetCurrentSequenceIndex()) { Order.SetSequence(sequence); } visitedSongRows.Set(visitedRows); } return results; }","std::vector CSoundFile::GetLength(enmGetLengthResetMode adjustMode, GetLengthTarget target) { std::vector results; GetLengthType retval; retval.startOrder = target.startOrder; retval.startRow = target.startRow; // Are we trying to reach a certain pattern position? const bool hasSearchTarget = target.mode != GetLengthTarget::NoTarget; const bool adjustSamplePos = (adjustMode & eAdjustSamplePositions) == eAdjustSamplePositions; SEQUENCEINDEX sequence = target.sequence; if(sequence >= Order.GetNumSequences()) sequence = Order.GetCurrentSequenceIndex(); const ModSequence &orderList = Order(sequence); GetLengthMemory memory(*this); CSoundFile::PlayState &playState = *memory.state; // Temporary visited rows vector (so that GetLength() won't interfere with the player code if the module is playing at the same time) RowVisitor visitedRows(*this, sequence); playState.m_nNextRow = playState.m_nRow = target.startRow; playState.m_nNextOrder = playState.m_nCurrentOrder = target.startOrder; // Fast LUTs for commands that are too weird / complicated / whatever to emulate in sample position adjust mode. std::bitset forbiddenCommands; std::bitset forbiddenVolCommands; if(adjustSamplePos) { forbiddenCommands.set(CMD_ARPEGGIO); forbiddenCommands.set(CMD_PORTAMENTOUP); forbiddenCommands.set(CMD_PORTAMENTODOWN); forbiddenCommands.set(CMD_XFINEPORTAUPDOWN); forbiddenCommands.set(CMD_NOTESLIDEUP); forbiddenCommands.set(CMD_NOTESLIDEUPRETRIG); forbiddenCommands.set(CMD_NOTESLIDEDOWN); forbiddenCommands.set(CMD_NOTESLIDEDOWNRETRIG); forbiddenVolCommands.set(VOLCMD_PORTAUP); forbiddenVolCommands.set(VOLCMD_PORTADOWN); // Optimize away channels for which it's pointless to adjust sample positions for(CHANNELINDEX i = 0; i < GetNumChannels(); i++) { if(ChnSettings[i].dwFlags[CHN_MUTE]) memory.chnSettings[i].ticksToRender = GetLengthMemory::IGNORE_CHANNEL; } if(target.mode == GetLengthTarget::SeekPosition && target.pos.order < orderList.size()) { // If we know where to seek, we can directly rule out any channels on which a new note would be triggered right at the start. const PATTERNINDEX seekPat = orderList[target.pos.order]; if(Patterns.IsValidPat(seekPat) && Patterns[seekPat].IsValidRow(target.pos.row)) { const ModCommand *m = Patterns[seekPat].GetRow(target.pos.row); for(CHANNELINDEX i = 0; i < GetNumChannels(); i++, m++) { if(m->note == NOTE_NOTECUT || m->note == NOTE_KEYOFF || (m->note == NOTE_FADE && GetNumInstruments()) || (m->IsNote() && !m->IsPortamento())) { memory.chnSettings[i].ticksToRender = GetLengthMemory::IGNORE_CHANNEL; } } } } } // If samples are being synced, force them to resync if tick duration changes uint32 oldTickDuration = 0; for (;;) { // Time target reached. if(target.mode == GetLengthTarget::SeekSeconds && memory.elapsedTime >= target.time) { retval.targetReached = true; break; } uint32 rowDelay = 0, tickDelay = 0; playState.m_nRow = playState.m_nNextRow; playState.m_nCurrentOrder = playState.m_nNextOrder; if(orderList.IsValidPat(playState.m_nCurrentOrder) && playState.m_nRow >= Patterns[orderList[playState.m_nCurrentOrder]].GetNumRows()) { playState.m_nRow = 0; if(m_playBehaviour[kFT2LoopE60Restart]) { playState.m_nRow = playState.m_nNextPatStartRow; playState.m_nNextPatStartRow = 0; } playState.m_nCurrentOrder = ++playState.m_nNextOrder; } // Check if pattern is valid playState.m_nPattern = playState.m_nCurrentOrder < orderList.size() ? orderList[playState.m_nCurrentOrder] : orderList.GetInvalidPatIndex(); bool positionJumpOnThisRow = false; bool patternBreakOnThisRow = false; bool patternLoopEndedOnThisRow = false, patternLoopStartedOnThisRow = false; if(!Patterns.IsValidPat(playState.m_nPattern) && playState.m_nPattern != orderList.GetInvalidPatIndex() && target.mode == GetLengthTarget::SeekPosition && playState.m_nCurrentOrder == target.pos.order) { // Early test: Target is inside +++ or non-existing pattern retval.targetReached = true; break; } while(playState.m_nPattern >= Patterns.Size()) { // End of song? if((playState.m_nPattern == orderList.GetInvalidPatIndex()) || (playState.m_nCurrentOrder >= orderList.size())) { if(playState.m_nCurrentOrder == orderList.GetRestartPos()) break; else playState.m_nCurrentOrder = orderList.GetRestartPos(); } else { playState.m_nCurrentOrder++; } playState.m_nPattern = (playState.m_nCurrentOrder < orderList.size()) ? orderList[playState.m_nCurrentOrder] : orderList.GetInvalidPatIndex(); playState.m_nNextOrder = playState.m_nCurrentOrder; if((!Patterns.IsValidPat(playState.m_nPattern)) && visitedRows.IsVisited(playState.m_nCurrentOrder, 0, true)) { if(!hasSearchTarget || !visitedRows.GetFirstUnvisitedRow(playState.m_nNextOrder, playState.m_nRow, true)) { // We aren't searching for a specific row, or we couldn't find any more unvisited rows. break; } else { // We haven't found the target row yet, but we found some other unplayed row... continue searching from here. retval.duration = memory.elapsedTime; results.push_back(retval); retval.startRow = playState.m_nRow; retval.startOrder = playState.m_nNextOrder; memory.Reset(); playState.m_nCurrentOrder = playState.m_nNextOrder; playState.m_nPattern = orderList[playState.m_nCurrentOrder]; playState.m_nNextRow = playState.m_nRow; break; } } } if(playState.m_nNextOrder == ORDERINDEX_INVALID) { // GetFirstUnvisitedRow failed, so there is nothing more to play break; } // Skip non-existing patterns if(!Patterns.IsValidPat(playState.m_nPattern)) { // If there isn't even a tune, we should probably stop here. if(playState.m_nCurrentOrder == orderList.GetRestartPos()) { if(!hasSearchTarget || !visitedRows.GetFirstUnvisitedRow(playState.m_nNextOrder, playState.m_nRow, true)) { // We aren't searching for a specific row, or we couldn't find any more unvisited rows. break; } else { // We haven't found the target row yet, but we found some other unplayed row... continue searching from here. retval.duration = memory.elapsedTime; results.push_back(retval); retval.startRow = playState.m_nRow; retval.startOrder = playState.m_nNextOrder; memory.Reset(); playState.m_nNextRow = playState.m_nRow; continue; } } playState.m_nNextOrder = playState.m_nCurrentOrder + 1; continue; } // Should never happen if(playState.m_nRow >= Patterns[playState.m_nPattern].GetNumRows()) playState.m_nRow = 0; // Check whether target was reached. if(target.mode == GetLengthTarget::SeekPosition && playState.m_nCurrentOrder == target.pos.order && playState.m_nRow == target.pos.row) { retval.targetReached = true; break; } if(visitedRows.IsVisited(playState.m_nCurrentOrder, playState.m_nRow, true)) { if(!hasSearchTarget || !visitedRows.GetFirstUnvisitedRow(playState.m_nNextOrder, playState.m_nRow, true)) { // We aren't searching for a specific row, or we couldn't find any more unvisited rows. break; } else { // We haven't found the target row yet, but we found some other unplayed row... continue searching from here. retval.duration = memory.elapsedTime; results.push_back(retval); retval.startRow = playState.m_nRow; retval.startOrder = playState.m_nNextOrder; memory.Reset(); playState.m_nNextRow = playState.m_nRow; continue; } } retval.endOrder = playState.m_nCurrentOrder; retval.endRow = playState.m_nRow; // Update next position playState.m_nNextRow = playState.m_nRow + 1; // Jumped to invalid pattern row? if(playState.m_nRow >= Patterns[playState.m_nPattern].GetNumRows()) { playState.m_nRow = 0; } // New pattern? if(!playState.m_nRow) { for(CHANNELINDEX chn = 0; chn < GetNumChannels(); chn++) { memory.chnSettings[chn].patLoop = memory.elapsedTime; memory.chnSettings[chn].patLoopSmp = playState.m_lTotalSampleCount; } } ModChannel *pChn = playState.Chn; // For various effects, we need to know first how many ticks there are in this row. const ModCommand *p = Patterns[playState.m_nPattern].GetpModCommand(playState.m_nRow, 0); for(CHANNELINDEX nChn = 0; nChn < GetNumChannels(); nChn++, p++) { if(m_playBehaviour[kST3NoMutedChannels] && ChnSettings[nChn].dwFlags[CHN_MUTE]) // not even effects are processed on muted S3M channels continue; if(p->IsPcNote()) { #ifndef NO_PLUGINS if((adjustMode & eAdjust) && p->instr > 0 && p->instr <= MAX_MIXPLUGINS) { memory.plugParams[std::make_pair(p->instr, p->GetValueVolCol())] = p->GetValueEffectCol(); } #endif // NO_PLUGINS pChn[nChn].rowCommand.Clear(); continue; } pChn[nChn].rowCommand = *p; switch(p->command) { case CMD_SPEED: SetSpeed(playState, p->param); break; case CMD_TEMPO: if(m_playBehaviour[kMODVBlankTiming]) { // ProTracker MODs with VBlank timing: All Fxx parameters set the tick count. if(p->param != 0) SetSpeed(playState, p->param); } break; case CMD_S3MCMDEX: if((p->param & 0xF0) == 0x60) { // Fine Pattern Delay tickDelay += (p->param & 0x0F); } else if((p->param & 0xF0) == 0xE0 && !rowDelay) { // Pattern Delay if(!(GetType() & MOD_TYPE_S3M) || (p->param & 0x0F) != 0) { // While Impulse Tracker *does* count S60 as a valid row delay (and thus ignores any other row delay commands on the right), // Scream Tracker 3 simply ignores such commands. rowDelay = 1 + (p->param & 0x0F); } } break; case CMD_MODCMDEX: if((p->param & 0xF0) == 0xE0) { // Pattern Delay rowDelay = 1 + (p->param & 0x0F); } break; } } if(rowDelay == 0) rowDelay = 1; const uint32 numTicks = (playState.m_nMusicSpeed + tickDelay) * rowDelay; const uint32 nonRowTicks = numTicks - rowDelay; for(CHANNELINDEX nChn = 0; nChn < GetNumChannels(); pChn++, nChn++) if(!pChn->rowCommand.IsEmpty()) { if(m_playBehaviour[kST3NoMutedChannels] && ChnSettings[nChn].dwFlags[CHN_MUTE]) // not even effects are processed on muted S3M channels continue; ModCommand::COMMAND command = pChn->rowCommand.command; ModCommand::PARAM param = pChn->rowCommand.param; ModCommand::NOTE note = pChn->rowCommand.note; if (pChn->rowCommand.instr) { pChn->nNewIns = pChn->rowCommand.instr; pChn->nLastNote = NOTE_NONE; memory.chnSettings[nChn].vol = 0xFF; } if (pChn->rowCommand.IsNote()) pChn->nLastNote = note; // Update channel panning if(pChn->rowCommand.IsNote() || pChn->rowCommand.instr) { SAMPLEINDEX smp = 0; if(GetNumInstruments()) { ModInstrument *pIns; if(pChn->nNewIns <= GetNumInstruments() && (pIns = Instruments[pChn->nNewIns]) != nullptr) { if(pIns->dwFlags[INS_SETPANNING]) pChn->nPan = pIns->nPan; if(ModCommand::IsNote(note)) smp = pIns->Keyboard[note - NOTE_MIN]; } } else { smp = pChn->nNewIns; } if(smp > 0 && smp <= GetNumSamples() && Samples[smp].uFlags[CHN_PANNING]) { pChn->nPan = Samples[smp].nPan; } } switch(pChn->rowCommand.volcmd) { case VOLCMD_VOLUME: memory.chnSettings[nChn].vol = pChn->rowCommand.vol; break; case VOLCMD_VOLSLIDEUP: case VOLCMD_VOLSLIDEDOWN: if(pChn->rowCommand.vol != 0) pChn->nOldVolParam = pChn->rowCommand.vol; break; } switch(command) { // Position Jump case CMD_POSITIONJUMP: positionJumpOnThisRow = true; playState.m_nNextOrder = static_cast(CalculateXParam(playState.m_nPattern, playState.m_nRow, nChn)); playState.m_nNextPatStartRow = 0; // FT2 E60 bug // see https://forum.openmpt.org/index.php?topic=2769.0 - FastTracker resets Dxx if Bxx is called _after_ Dxx // Test case: PatternJump.mod if(!patternBreakOnThisRow || (GetType() & (MOD_TYPE_MOD | MOD_TYPE_XM))) playState.m_nNextRow = 0; if (adjustMode & eAdjust) { pChn->nPatternLoopCount = 0; pChn->nPatternLoop = 0; } break; // Pattern Break case CMD_PATTERNBREAK: { ROWINDEX row = PatternBreak(playState, nChn, param); if(row != ROWINDEX_INVALID) { patternBreakOnThisRow = true; playState.m_nNextRow = row; if(!positionJumpOnThisRow) { playState.m_nNextOrder = playState.m_nCurrentOrder + 1; } if(adjustMode & eAdjust) { pChn->nPatternLoopCount = 0; pChn->nPatternLoop = 0; } } } break; // Set Tempo case CMD_TEMPO: if(!m_playBehaviour[kMODVBlankTiming]) { TEMPO tempo(CalculateXParam(playState.m_nPattern, playState.m_nRow, nChn), 0); if ((adjustMode & eAdjust) && (GetType() & (MOD_TYPE_S3M | MOD_TYPE_IT | MOD_TYPE_MPT))) { if (tempo.GetInt()) pChn->nOldTempo = static_cast(tempo.GetInt()); else tempo.Set(pChn->nOldTempo); } if (tempo.GetInt() >= 0x20) playState.m_nMusicTempo = tempo; else { // Tempo Slide TEMPO tempoDiff((tempo.GetInt() & 0x0F) * nonRowTicks, 0); if ((tempo.GetInt() & 0xF0) == 0x10) { playState.m_nMusicTempo += tempoDiff; } else { if(tempoDiff < playState.m_nMusicTempo) playState.m_nMusicTempo -= tempoDiff; else playState.m_nMusicTempo.Set(0); } } TEMPO tempoMin = GetModSpecifications().GetTempoMin(), tempoMax = GetModSpecifications().GetTempoMax(); if(m_playBehaviour[kTempoClamp]) // clamp tempo correctly in compatible mode { tempoMax.Set(255); } Limit(playState.m_nMusicTempo, tempoMin, tempoMax); } break; case CMD_S3MCMDEX: switch(param & 0xF0) { case 0x90: if(param <= 0x91) { pChn->dwFlags.set(CHN_SURROUND, param == 0x91); } break; case 0xA0: // High sample offset pChn->nOldHiOffset = param & 0x0F; break; case 0xB0: // Pattern Loop if (param & 0x0F) { patternLoopEndedOnThisRow = true; } else { CHANNELINDEX firstChn = nChn, lastChn = nChn; if(GetType() == MOD_TYPE_S3M) { // ST3 has only one global loop memory. firstChn = 0; lastChn = GetNumChannels() - 1; } for(CHANNELINDEX c = firstChn; c <= lastChn; c++) { memory.chnSettings[c].patLoop = memory.elapsedTime; memory.chnSettings[c].patLoopSmp = playState.m_lTotalSampleCount; memory.chnSettings[c].patLoopStart = playState.m_nRow; } patternLoopStartedOnThisRow = true; } break; case 0xF0: // Active macro pChn->nActiveMacro = param & 0x0F; break; } break; case CMD_MODCMDEX: switch(param & 0xF0) { case 0x60: // Pattern Loop if (param & 0x0F) { playState.m_nNextPatStartRow = memory.chnSettings[nChn].patLoopStart; // FT2 E60 bug patternLoopEndedOnThisRow = true; } else { patternLoopStartedOnThisRow = true; memory.chnSettings[nChn].patLoop = memory.elapsedTime; memory.chnSettings[nChn].patLoopSmp = playState.m_lTotalSampleCount; memory.chnSettings[nChn].patLoopStart = playState.m_nRow; } break; case 0xF0: // Active macro pChn->nActiveMacro = param & 0x0F; break; } break; case CMD_XFINEPORTAUPDOWN: // ignore high offset in compatible mode if(((param & 0xF0) == 0xA0) && !m_playBehaviour[kFT2RestrictXCommand]) pChn->nOldHiOffset = param & 0x0F; break; } // The following calculations are not interesting if we just want to get the song length. if (!(adjustMode & eAdjust)) continue; switch(command) { // Portamento Up/Down case CMD_PORTAMENTOUP: if(param) { // FT2 compatibility: Separate effect memory for all portamento commands // Test case: Porta-LinkMem.xm if(!m_playBehaviour[kFT2PortaUpDownMemory]) pChn->nOldPortaDown = param; pChn->nOldPortaUp = param; } break; case CMD_PORTAMENTODOWN: if(param) { // FT2 compatibility: Separate effect memory for all portamento commands // Test case: Porta-LinkMem.xm if(!m_playBehaviour[kFT2PortaUpDownMemory]) pChn->nOldPortaUp = param; pChn->nOldPortaDown = param; } break; // Tone-Portamento case CMD_TONEPORTAMENTO: if (param) pChn->nPortamentoSlide = param << 2; break; // Offset case CMD_OFFSET: if (param) pChn->oldOffset = param << 8; break; // Volume Slide case CMD_VOLUMESLIDE: case CMD_TONEPORTAVOL: if (param) pChn->nOldVolumeSlide = param; break; // Set Volume case CMD_VOLUME: memory.chnSettings[nChn].vol = param; break; // Global Volume case CMD_GLOBALVOLUME: if(!(GetType() & GLOBALVOL_7BIT_FORMATS) && param < 128) param *= 2; // IT compatibility 16. ST3 and IT ignore out-of-range values if(param <= 128) { playState.m_nGlobalVolume = param * 2; } else if(!(GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT | MOD_TYPE_S3M))) { playState.m_nGlobalVolume = 256; } break; // Global Volume Slide case CMD_GLOBALVOLSLIDE: if(m_playBehaviour[kPerChannelGlobalVolSlide]) { // IT compatibility 16. Global volume slide params are stored per channel (FT2/IT) if (param) pChn->nOldGlobalVolSlide = param; else param = pChn->nOldGlobalVolSlide; } else { if (param) playState.Chn[0].nOldGlobalVolSlide = param; else param = playState.Chn[0].nOldGlobalVolSlide; } if (((param & 0x0F) == 0x0F) && (param & 0xF0)) { param >>= 4; if (!(GetType() & GLOBALVOL_7BIT_FORMATS)) param <<= 1; playState.m_nGlobalVolume += param << 1; } else if (((param & 0xF0) == 0xF0) && (param & 0x0F)) { param = (param & 0x0F) << 1; if (!(GetType() & GLOBALVOL_7BIT_FORMATS)) param <<= 1; playState.m_nGlobalVolume -= param; } else if (param & 0xF0) { param >>= 4; param <<= 1; if (!(GetType() & GLOBALVOL_7BIT_FORMATS)) param <<= 1; playState.m_nGlobalVolume += param * nonRowTicks; } else { param = (param & 0x0F) << 1; if (!(GetType() & GLOBALVOL_7BIT_FORMATS)) param <<= 1; playState.m_nGlobalVolume -= param * nonRowTicks; } Limit(playState.m_nGlobalVolume, 0, 256); break; case CMD_CHANNELVOLUME: if (param <= 64) pChn->nGlobalVol = param; break; case CMD_CHANNELVOLSLIDE: { if (param) pChn->nOldChnVolSlide = param; else param = pChn->nOldChnVolSlide; int32 volume = pChn->nGlobalVol; if((param & 0x0F) == 0x0F && (param & 0xF0)) volume += (param >> 4); // Fine Up else if((param & 0xF0) == 0xF0 && (param & 0x0F)) volume -= (param & 0x0F); // Fine Down else if(param & 0x0F) // Down volume -= (param & 0x0F) * nonRowTicks; else // Up volume += ((param & 0xF0) >> 4) * nonRowTicks; Limit(volume, 0, 64); pChn->nGlobalVol = volume; } break; case CMD_PANNING8: Panning(pChn, param, Pan8bit); break; case CMD_MODCMDEX: if(param < 0x10) { // LED filter for(CHANNELINDEX chn = 0; chn < GetNumChannels(); chn++) { playState.Chn[chn].dwFlags.set(CHN_AMIGAFILTER, !(param & 1)); } } MPT_FALLTHROUGH; case CMD_S3MCMDEX: if((param & 0xF0) == 0x80) { Panning(pChn, (param & 0x0F), Pan4bit); } break; case CMD_VIBRATOVOL: if (param) pChn->nOldVolumeSlide = param; param = 0; MPT_FALLTHROUGH; case CMD_VIBRATO: Vibrato(pChn, param); break; case CMD_FINEVIBRATO: FineVibrato(pChn, param); break; case CMD_TREMOLO: Tremolo(pChn, param); break; case CMD_PANBRELLO: Panbrello(pChn, param); break; } switch(pChn->rowCommand.volcmd) { case VOLCMD_PANNING: Panning(pChn, pChn->rowCommand.vol, Pan6bit); break; case VOLCMD_VIBRATOSPEED: // FT2 does not automatically enable vibrato with the ""set vibrato speed"" command if(m_playBehaviour[kFT2VolColVibrato]) pChn->nVibratoSpeed = pChn->rowCommand.vol & 0x0F; else Vibrato(pChn, pChn->rowCommand.vol << 4); break; case VOLCMD_VIBRATODEPTH: Vibrato(pChn, pChn->rowCommand.vol); break; } // Process vibrato / tremolo / panbrello switch(pChn->rowCommand.command) { case CMD_VIBRATO: case CMD_FINEVIBRATO: case CMD_VIBRATOVOL: if(adjustMode & eAdjust) { uint32 vibTicks = ((GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT)) && !m_SongFlags[SONG_ITOLDEFFECTS]) ? numTicks : nonRowTicks; uint32 inc = pChn->nVibratoSpeed * vibTicks; if(m_playBehaviour[kITVibratoTremoloPanbrello]) inc *= 4; pChn->nVibratoPos += static_cast(inc); } break; case CMD_TREMOLO: if(adjustMode & eAdjust) { uint32 tremTicks = ((GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT)) && !m_SongFlags[SONG_ITOLDEFFECTS]) ? numTicks : nonRowTicks; uint32 inc = pChn->nTremoloSpeed * tremTicks; if(m_playBehaviour[kITVibratoTremoloPanbrello]) inc *= 4; pChn->nTremoloPos += static_cast(inc); } break; case CMD_PANBRELLO: if(adjustMode & eAdjust) { // Panbrello effect is permanent in compatible mode, so actually apply panbrello for the last tick of this row pChn->nPanbrelloPos += static_cast(pChn->nPanbrelloSpeed * (numTicks - 1)); ProcessPanbrello(pChn); } break; } } // Interpret F00 effect in XM files as ""stop song"" if(GetType() == MOD_TYPE_XM && playState.m_nMusicSpeed == uint16_max) { break; } playState.m_nCurrentRowsPerBeat = m_nDefaultRowsPerBeat; if(Patterns[playState.m_nPattern].GetOverrideSignature()) { playState.m_nCurrentRowsPerBeat = Patterns[playState.m_nPattern].GetRowsPerBeat(); } const uint32 tickDuration = GetTickDuration(playState); const uint32 rowDuration = tickDuration * numTicks; memory.elapsedTime += static_cast(rowDuration) / static_cast(m_MixerSettings.gdwMixingFreq); playState.m_lTotalSampleCount += rowDuration; if(adjustSamplePos) { // Super experimental and dirty sample seeking pChn = playState.Chn; for(CHANNELINDEX nChn = 0; nChn < GetNumChannels(); pChn++, nChn++) { if(memory.chnSettings[nChn].ticksToRender == GetLengthMemory::IGNORE_CHANNEL) continue; uint32 startTick = 0; const ModCommand &m = pChn->rowCommand; uint32 paramHi = m.param >> 4, paramLo = m.param & 0x0F; bool porta = m.command == CMD_TONEPORTAMENTO || m.command == CMD_TONEPORTAVOL || m.volcmd == VOLCMD_TONEPORTAMENTO; bool stopNote = patternLoopStartedOnThisRow; // It's too much trouble to keep those pattern loops in sync... if(m.instr) pChn->proTrackerOffset = 0; if(m.IsNote()) { if(porta && memory.chnSettings[nChn].incChanged) { // If there's a portamento, the current channel increment mustn't be 0 in NoteChange() pChn->increment = GetChannelIncrement(pChn, pChn->nPeriod, 0); } int32 setPan = pChn->nPan; pChn->nNewNote = pChn->nLastNote; if(pChn->nNewIns != 0) InstrumentChange(pChn, pChn->nNewIns, porta); NoteChange(pChn, m.note, porta); memory.chnSettings[nChn].incChanged = true; if((m.command == CMD_MODCMDEX || m.command == CMD_S3MCMDEX) && (m.param & 0xF0) == 0xD0 && paramLo < numTicks) { startTick = paramLo; } else if(m.command == CMD_DELAYCUT && paramHi < numTicks) { startTick = paramHi; } if(rowDelay > 1 && startTick != 0 && (GetType() & (MOD_TYPE_S3M | MOD_TYPE_IT | MOD_TYPE_MPT))) { startTick += (playState.m_nMusicSpeed + tickDelay) * (rowDelay - 1); } if(!porta) memory.chnSettings[nChn].ticksToRender = 0; // Panning commands have to be re-applied after a note change with potential pan change. if(m.command == CMD_PANNING8 || ((m.command == CMD_MODCMDEX || m.command == CMD_S3MCMDEX) && paramHi == 0x8) || m.volcmd == VOLCMD_PANNING) { pChn->nPan = setPan; } if(m.command == CMD_OFFSET) { bool isExtended = false; SmpLength offset = CalculateXParam(playState.m_nPattern, playState.m_nRow, nChn, &isExtended); if(!isExtended) { offset <<= 8; if(offset == 0) offset = pChn->oldOffset; offset += static_cast(pChn->nOldHiOffset) << 16; } SampleOffset(*pChn, offset); } else if(m.command == CMD_OFFSETPERCENTAGE) { SampleOffset(*pChn, Util::muldiv_unsigned(pChn->nLength, m.param, 255)); } else if(m.command == CMD_REVERSEOFFSET && pChn->pModSample != nullptr) { memory.RenderChannel(nChn, oldTickDuration); // Re-sync what we've got so far ReverseSampleOffset(*pChn, m.param); startTick = playState.m_nMusicSpeed - 1; } else if(m.volcmd == VOLCMD_OFFSET) { if(m.vol <= CountOf(pChn->pModSample->cues) && pChn->pModSample != nullptr) { SmpLength offset; if(m.vol == 0) offset = pChn->oldOffset; else offset = pChn->oldOffset = pChn->pModSample->cues[m.vol - 1]; SampleOffset(*pChn, offset); } } } if(m.note == NOTE_KEYOFF || m.note == NOTE_NOTECUT || (m.note == NOTE_FADE && GetNumInstruments()) || ((m.command == CMD_MODCMDEX || m.command == CMD_S3MCMDEX) && (m.param & 0xF0) == 0xC0 && paramLo < numTicks) || (m.command == CMD_DELAYCUT && paramLo != 0 && startTick + paramLo < numTicks)) { stopNote = true; } if(m.command == CMD_VOLUME) { pChn->nVolume = m.param * 4; } else if(m.volcmd == VOLCMD_VOLUME) { pChn->nVolume = m.vol * 4; } if(pChn->pModSample && !stopNote) { // Check if we don't want to emulate some effect and thus stop processing. if(m.command < MAX_EFFECTS) { if(forbiddenCommands[m.command]) { stopNote = true; } else if(m.command == CMD_MODCMDEX) { // Special case: Slides using extended commands switch(m.param & 0xF0) { case 0x10: case 0x20: stopNote = true; } } } if(m.volcmd < forbiddenVolCommands.size() && forbiddenVolCommands[m.volcmd]) { stopNote = true; } } if(stopNote) { pChn->Stop(); memory.chnSettings[nChn].ticksToRender = 0; } else { if(oldTickDuration != tickDuration && oldTickDuration != 0) { memory.RenderChannel(nChn, oldTickDuration); // Re-sync what we've got so far } switch(m.command) { case CMD_TONEPORTAVOL: case CMD_VOLUMESLIDE: case CMD_VIBRATOVOL: if(m.param || (GetType() != MOD_TYPE_MOD)) { for(uint32 i = 0; i < numTicks; i++) { pChn->isFirstTick = (i == 0); VolumeSlide(pChn, m.param); } } break; case CMD_MODCMDEX: if((m.param & 0x0F) || (GetType() & (MOD_TYPE_XM | MOD_TYPE_MT2))) { pChn->isFirstTick = true; switch(m.param & 0xF0) { case 0xA0: FineVolumeUp(pChn, m.param & 0x0F, false); break; case 0xB0: FineVolumeDown(pChn, m.param & 0x0F, false); break; } } break; case CMD_S3MCMDEX: if(m.param == 0x9E) { // Play forward memory.RenderChannel(nChn, oldTickDuration); // Re-sync what we've got so far pChn->dwFlags.reset(CHN_PINGPONGFLAG); } else if(m.param == 0x9F) { // Reverse memory.RenderChannel(nChn, oldTickDuration); // Re-sync what we've got so far pChn->dwFlags.set(CHN_PINGPONGFLAG); if(!pChn->position.GetInt() && pChn->nLength && (m.IsNote() || !pChn->dwFlags[CHN_LOOP])) { pChn->position.Set(pChn->nLength - 1, SamplePosition::fractMax); } } else if((m.param & 0xF0) == 0x70) { // TODO //ExtendedS3MCommands(nChn, param); } break; } pChn->isFirstTick = true; switch(m.volcmd) { case VOLCMD_FINEVOLUP: FineVolumeUp(pChn, m.vol, m_playBehaviour[kITVolColMemory]); break; case VOLCMD_FINEVOLDOWN: FineVolumeDown(pChn, m.vol, m_playBehaviour[kITVolColMemory]); break; case VOLCMD_VOLSLIDEUP: case VOLCMD_VOLSLIDEDOWN: { // IT Compatibility: Volume column volume slides have their own memory // Test case: VolColMemory.it ModCommand::VOL vol = m.vol; if(vol == 0 && m_playBehaviour[kITVolColMemory]) { vol = pChn->nOldVolParam; if(vol == 0) break; } if(m.volcmd == VOLCMD_VOLSLIDEUP) vol <<= 4; for(uint32 i = 0; i < numTicks; i++) { pChn->isFirstTick = (i == 0); VolumeSlide(pChn, vol); } } break; } if(porta) { // Portamento needs immediate syncing, as the pitch changes on each tick uint32 portaTick = memory.chnSettings[nChn].ticksToRender + startTick + 1; memory.chnSettings[nChn].ticksToRender += numTicks; memory.RenderChannel(nChn, tickDuration, portaTick); } else { memory.chnSettings[nChn].ticksToRender += (numTicks - startTick); } } } } oldTickDuration = tickDuration; // Pattern loop is not executed in FT2 if there are any position jump or pattern break commands on the same row. // Pattern loop is not executed in IT if there are any position jump commands on the same row. // Test case for FT2 exception: PatLoop-Jumps.xm, PatLoop-Various.xm // Test case for IT: exception: LoopBreak.it if(patternLoopEndedOnThisRow && (!m_playBehaviour[kFT2PatternLoopWithJumps] || !(positionJumpOnThisRow || patternBreakOnThisRow)) && (!m_playBehaviour[kITPatternLoopWithJumps] || !positionJumpOnThisRow)) { std::map startTimes; // This is really just a simple estimation for nested pattern loops. It should handle cases correctly where all parallel loops start and end on the same row. // If one of them starts or ends ""in between"", it will most likely calculate a wrong duration. // For S3M files, it's also way off. pChn = playState.Chn; for(CHANNELINDEX nChn = 0; nChn < GetNumChannels(); nChn++, pChn++) { ModCommand::COMMAND command = pChn->rowCommand.command; ModCommand::PARAM param = pChn->rowCommand.param; if((command == CMD_S3MCMDEX && param >= 0xB1 && param <= 0xBF) || (command == CMD_MODCMDEX && param >= 0x61 && param <= 0x6F)) { const double start = memory.chnSettings[nChn].patLoop; if(!startTimes[start]) startTimes[start] = 1; startTimes[start] = mpt::lcm(startTimes[start], 1 + (param & 0x0F)); } } for(const auto &i : startTimes) { memory.elapsedTime += (memory.elapsedTime - i.first) * (double)(i.second - 1); for(CHANNELINDEX nChn = 0; nChn < GetNumChannels(); nChn++, pChn++) { if(memory.chnSettings[nChn].patLoop == i.first) { playState.m_lTotalSampleCount += (playState.m_lTotalSampleCount - memory.chnSettings[nChn].patLoopSmp) * (i.second - 1); if(m_playBehaviour[kITPatternLoopTargetReset] || (GetType() == MOD_TYPE_S3M)) { memory.chnSettings[nChn].patLoop = memory.elapsedTime; memory.chnSettings[nChn].patLoopSmp = playState.m_lTotalSampleCount; memory.chnSettings[nChn].patLoopStart = playState.m_nRow + 1; } break; } } } if(GetType() == MOD_TYPE_IT) { // IT pattern loop start row update - at the end of a pattern loop, set pattern loop start to next row (for upcoming pattern loops with missing SB0) pChn = playState.Chn; for(CHANNELINDEX nChn = 0; nChn < GetNumChannels(); nChn++, pChn++) { if((pChn->rowCommand.command == CMD_S3MCMDEX && pChn->rowCommand.param >= 0xB1 && pChn->rowCommand.param <= 0xBF)) { memory.chnSettings[nChn].patLoop = memory.elapsedTime; memory.chnSettings[nChn].patLoopSmp = playState.m_lTotalSampleCount; } } } } } // Now advance the sample positions for sample seeking on channels that are still playing if(adjustSamplePos) { for(CHANNELINDEX nChn = 0; nChn < GetNumChannels(); nChn++) { if(memory.chnSettings[nChn].ticksToRender != GetLengthMemory::IGNORE_CHANNEL) { memory.RenderChannel(nChn, oldTickDuration); } } } if(retval.targetReached || target.mode == GetLengthTarget::NoTarget) { retval.lastOrder = playState.m_nCurrentOrder; retval.lastRow = playState.m_nRow; } retval.duration = memory.elapsedTime; results.push_back(retval); // Store final variables if(adjustMode & eAdjust) { if(retval.targetReached || target.mode == GetLengthTarget::NoTarget) { // Target found, or there is no target (i.e. play whole song)... m_PlayState = std::move(playState); m_PlayState.m_nNextRow = m_PlayState.m_nRow; m_PlayState.m_nFrameDelay = m_PlayState.m_nPatternDelay = 0; m_PlayState.m_nTickCount = Util::MaxValueOfType(m_PlayState.m_nTickCount) - 1; m_PlayState.m_bPositionChanged = true; for(CHANNELINDEX n = 0; n < GetNumChannels(); n++) { if(m_PlayState.Chn[n].nLastNote != NOTE_NONE) { m_PlayState.Chn[n].nNewNote = m_PlayState.Chn[n].nLastNote; } if(memory.chnSettings[n].vol != 0xFF && !adjustSamplePos) { m_PlayState.Chn[n].nVolume = std::min(memory.chnSettings[n].vol, uint8(64)) * 4; } } #ifndef NO_PLUGINS // If there were any PC events, update plugin parameters to their latest value. std::bitset plugSetProgram; for(const auto ¶m : memory.plugParams) { PLUGINDEX plug = param.first.first - 1; IMixPlugin *plugin = m_MixPlugins[plug].pMixPlugin; if(plugin != nullptr) { if(!plugSetProgram[plug]) { // Used for bridged plugins to avoid sending out individual messages for each parameter. plugSetProgram.set(plug); plugin->BeginSetProgram(); } plugin->SetParameter(param.first.second, param.second / PlugParamValue(ModCommand::maxColumnValue)); } } if(plugSetProgram.any()) { for(PLUGINDEX i = 0; i < MAX_MIXPLUGINS; i++) { if(plugSetProgram[i]) { m_MixPlugins[i].pMixPlugin->EndSetProgram(); } } } #endif // NO_PLUGINS } else if(adjustMode != eAdjustOnSuccess) { // Target not found (e.g. when jumping to a hidden sub song), reset global variables... m_PlayState.m_nMusicSpeed = m_nDefaultSpeed; m_PlayState.m_nMusicTempo = m_nDefaultTempo; m_PlayState.m_nGlobalVolume = m_nDefaultGlobalVolume; } // When adjusting the playback status, we will also want to update the visited rows vector according to the current position. if(sequence != Order.GetCurrentSequenceIndex()) { Order.SetSequence(sequence); } visitedSongRows.Set(visitedRows); } return results; }","{'deleted': [{'line_no': 978, 'char_start': 31995, 'char_end': 32059, 'line': '\t\t\t\tfor(CHANNELINDEX nChn = 0; nChn < GetNumChannels(); nChn++)\n'}], 'added': [{'line_no': 978, 'char_start': 31995, 'char_end': 32021, 'line': '\t\t\t\tpChn = playState.Chn;\n'}, {'line_no': 979, 'char_start': 32021, 'char_end': 32093, 'line': '\t\t\t\tfor(CHANNELINDEX nChn = 0; nChn < GetNumChannels(); nChn++, pChn++)\n'}]}","{'deleted': [], 'added': [{'char_start': 31999, 'char_end': 32025, 'chars': 'pChn = playState.Chn;\n\t\t\t\t'}, {'char_start': 32078, 'char_end': 32086, 'chars': 'Chn++, p'}]}",github.com/OpenMPT/openmpt/commit/492022c7297ede682161d9c0ec2de15526424e76,soundlib/Snd_fx.cpp,cwe-125,11000 cwe-416,usb_audio_probe,"static int usb_audio_probe(struct usb_interface *intf, const struct usb_device_id *usb_id) { struct usb_device *dev = interface_to_usbdev(intf); const struct snd_usb_audio_quirk *quirk = (const struct snd_usb_audio_quirk *)usb_id->driver_info; struct snd_usb_audio *chip; int i, err; struct usb_host_interface *alts; int ifnum; u32 id; alts = &intf->altsetting[0]; ifnum = get_iface_desc(alts)->bInterfaceNumber; id = USB_ID(le16_to_cpu(dev->descriptor.idVendor), le16_to_cpu(dev->descriptor.idProduct)); if (get_alias_id(dev, &id)) quirk = get_alias_quirk(dev, id); if (quirk && quirk->ifnum >= 0 && ifnum != quirk->ifnum) return -ENXIO; err = snd_usb_apply_boot_quirk(dev, intf, quirk, id); if (err < 0) return err; /* * found a config. now register to ALSA */ /* check whether it's already registered */ chip = NULL; mutex_lock(®ister_mutex); for (i = 0; i < SNDRV_CARDS; i++) { if (usb_chip[i] && usb_chip[i]->dev == dev) { if (atomic_read(&usb_chip[i]->shutdown)) { dev_err(&dev->dev, ""USB device is in the shutdown state, cannot create a card instance\n""); err = -EIO; goto __error; } chip = usb_chip[i]; atomic_inc(&chip->active); /* avoid autopm */ break; } } if (! chip) { /* it's a fresh one. * now look for an empty slot and create a new card instance */ for (i = 0; i < SNDRV_CARDS; i++) if (!usb_chip[i] && (vid[i] == -1 || vid[i] == USB_ID_VENDOR(id)) && (pid[i] == -1 || pid[i] == USB_ID_PRODUCT(id))) { if (enable[i]) { err = snd_usb_audio_create(intf, dev, i, quirk, id, &chip); if (err < 0) goto __error; chip->pm_intf = intf; break; } else if (vid[i] != -1 || pid[i] != -1) { dev_info(&dev->dev, ""device (%04x:%04x) is disabled\n"", USB_ID_VENDOR(id), USB_ID_PRODUCT(id)); err = -ENOENT; goto __error; } } if (!chip) { dev_err(&dev->dev, ""no available usb audio device\n""); err = -ENODEV; goto __error; } } dev_set_drvdata(&dev->dev, chip); /* * For devices with more than one control interface, we assume the * first contains the audio controls. We might need a more specific * check here in the future. */ if (!chip->ctrl_intf) chip->ctrl_intf = alts; chip->txfr_quirk = 0; err = 1; /* continue */ if (quirk && quirk->ifnum != QUIRK_NO_INTERFACE) { /* need some special handlings */ err = snd_usb_create_quirk(chip, intf, &usb_audio_driver, quirk); if (err < 0) goto __error; } if (err > 0) { /* create normal USB audio interfaces */ err = snd_usb_create_streams(chip, ifnum); if (err < 0) goto __error; err = snd_usb_create_mixer(chip, ifnum, ignore_ctl_error); if (err < 0) goto __error; } /* we are allowed to call snd_card_register() many times */ err = snd_card_register(chip->card); if (err < 0) goto __error; usb_chip[chip->index] = chip; chip->num_interfaces++; usb_set_intfdata(intf, chip); atomic_dec(&chip->active); mutex_unlock(®ister_mutex); return 0; __error: if (chip) { if (!chip->num_interfaces) snd_card_free(chip->card); atomic_dec(&chip->active); } mutex_unlock(®ister_mutex); return err; }","static int usb_audio_probe(struct usb_interface *intf, const struct usb_device_id *usb_id) { struct usb_device *dev = interface_to_usbdev(intf); const struct snd_usb_audio_quirk *quirk = (const struct snd_usb_audio_quirk *)usb_id->driver_info; struct snd_usb_audio *chip; int i, err; struct usb_host_interface *alts; int ifnum; u32 id; alts = &intf->altsetting[0]; ifnum = get_iface_desc(alts)->bInterfaceNumber; id = USB_ID(le16_to_cpu(dev->descriptor.idVendor), le16_to_cpu(dev->descriptor.idProduct)); if (get_alias_id(dev, &id)) quirk = get_alias_quirk(dev, id); if (quirk && quirk->ifnum >= 0 && ifnum != quirk->ifnum) return -ENXIO; err = snd_usb_apply_boot_quirk(dev, intf, quirk, id); if (err < 0) return err; /* * found a config. now register to ALSA */ /* check whether it's already registered */ chip = NULL; mutex_lock(®ister_mutex); for (i = 0; i < SNDRV_CARDS; i++) { if (usb_chip[i] && usb_chip[i]->dev == dev) { if (atomic_read(&usb_chip[i]->shutdown)) { dev_err(&dev->dev, ""USB device is in the shutdown state, cannot create a card instance\n""); err = -EIO; goto __error; } chip = usb_chip[i]; atomic_inc(&chip->active); /* avoid autopm */ break; } } if (! chip) { /* it's a fresh one. * now look for an empty slot and create a new card instance */ for (i = 0; i < SNDRV_CARDS; i++) if (!usb_chip[i] && (vid[i] == -1 || vid[i] == USB_ID_VENDOR(id)) && (pid[i] == -1 || pid[i] == USB_ID_PRODUCT(id))) { if (enable[i]) { err = snd_usb_audio_create(intf, dev, i, quirk, id, &chip); if (err < 0) goto __error; chip->pm_intf = intf; break; } else if (vid[i] != -1 || pid[i] != -1) { dev_info(&dev->dev, ""device (%04x:%04x) is disabled\n"", USB_ID_VENDOR(id), USB_ID_PRODUCT(id)); err = -ENOENT; goto __error; } } if (!chip) { dev_err(&dev->dev, ""no available usb audio device\n""); err = -ENODEV; goto __error; } } dev_set_drvdata(&dev->dev, chip); /* * For devices with more than one control interface, we assume the * first contains the audio controls. We might need a more specific * check here in the future. */ if (!chip->ctrl_intf) chip->ctrl_intf = alts; chip->txfr_quirk = 0; err = 1; /* continue */ if (quirk && quirk->ifnum != QUIRK_NO_INTERFACE) { /* need some special handlings */ err = snd_usb_create_quirk(chip, intf, &usb_audio_driver, quirk); if (err < 0) goto __error; } if (err > 0) { /* create normal USB audio interfaces */ err = snd_usb_create_streams(chip, ifnum); if (err < 0) goto __error; err = snd_usb_create_mixer(chip, ifnum, ignore_ctl_error); if (err < 0) goto __error; } /* we are allowed to call snd_card_register() many times */ err = snd_card_register(chip->card); if (err < 0) goto __error; usb_chip[chip->index] = chip; chip->num_interfaces++; usb_set_intfdata(intf, chip); atomic_dec(&chip->active); mutex_unlock(®ister_mutex); return 0; __error: if (chip) { /* chip->active is inside the chip->card object, * decrement before memory is possibly returned. */ atomic_dec(&chip->active); if (!chip->num_interfaces) snd_card_free(chip->card); } mutex_unlock(®ister_mutex); return err; }","{'deleted': [{'line_no': 120, 'char_start': 3144, 'char_end': 3173, 'line': '\t\tatomic_dec(&chip->active);\n'}], 'added': [{'line_no': 118, 'char_start': 3085, 'char_end': 3136, 'line': '\t\t/* chip->active is inside the chip->card object,\n'}, {'line_no': 119, 'char_start': 3136, 'char_end': 3187, 'line': '\t\t * decrement before memory is possibly returned.\n'}, {'line_no': 120, 'char_start': 3187, 'char_end': 3193, 'line': '\t\t */\n'}, {'line_no': 121, 'char_start': 3193, 'char_end': 3222, 'line': '\t\tatomic_dec(&chip->active);\n'}]}","{'deleted': [{'char_start': 3087, 'char_end': 3089, 'chars': 'if'}, {'char_start': 3090, 'char_end': 3092, 'chars': '(!'}, {'char_start': 3098, 'char_end': 3102, 'chars': 'num_'}, {'char_start': 3107, 'char_end': 3109, 'chars': 'fa'}, {'char_start': 3110, 'char_end': 3113, 'chars': 'es)'}, {'char_start': 3116, 'char_end': 3119, 'chars': '\tsn'}, {'char_start': 3120, 'char_end': 3121, 'chars': '_'}, {'char_start': 3122, 'char_end': 3123, 'chars': 'a'}, {'char_start': 3124, 'char_end': 3126, 'chars': 'd_'}, {'char_start': 3130, 'char_end': 3133, 'chars': '(ch'}, {'char_start': 3135, 'char_end': 3139, 'chars': '->ca'}, {'char_start': 3141, 'char_end': 3143, 'chars': ');'}], 'added': [{'char_start': 3087, 'char_end': 3224, 'chars': '/* chip->active is inside the chip->card object,\n\t\t * decrement before memory is possibly returned.\n\t\t */\n\t\tatomic_dec(&chip->active);\n\t\t'}]}",github.com/torvalds/linux/commit/5f8cf712582617d523120df67d392059eaf2fc4b,sound/usb/card.c,cwe-416,987 cwe-125,ReadPSDChannelPixels,"static MagickBooleanType ReadPSDChannelPixels(Image *image, const size_t channels,const size_t row,const ssize_t type, const unsigned char *pixels,ExceptionInfo *exception) { Quantum pixel; register const unsigned char *p; register Quantum *q; register ssize_t x; size_t packet_size; unsigned short nibble; p=pixels; q=GetAuthenticPixels(image,0,row,image->columns,1,exception); if (q == (Quantum *) NULL) return MagickFalse; packet_size=GetPSDPacketSize(image); for (x=0; x < (ssize_t) image->columns; x++) { if (packet_size == 1) pixel=ScaleCharToQuantum(*p++); else { p=PushShortPixel(MSBEndian,p,&nibble); pixel=ScaleShortToQuantum(nibble); } switch (type) { case -1: { SetPixelAlpha(image,pixel,q); break; } case -2: case 0: { SetPixelRed(image,pixel,q); if (channels == 1 || type == -2) SetPixelGray(image,pixel,q); if (image->storage_class == PseudoClass) { if (packet_size == 1) SetPixelIndex(image,ScaleQuantumToChar(pixel),q); else SetPixelIndex(image,ScaleQuantumToShort(pixel),q); SetPixelViaPixelInfo(image,image->colormap+(ssize_t) ConstrainColormapIndex(image,GetPixelIndex(image,q),exception),q); if (image->depth == 1) { ssize_t bit, number_bits; number_bits=image->columns-x; if (number_bits > 8) number_bits=8; for (bit=0; bit < number_bits; bit++) { SetPixelIndex(image,(((unsigned char) pixel) & (0x01 << (7-bit))) != 0 ? 0 : 255,q); SetPixelViaPixelInfo(image,image->colormap+(ssize_t) GetPixelIndex(image,q),q); q+=GetPixelChannels(image); x++; } x--; continue; } } break; } case 1: { if (image->storage_class == PseudoClass) SetPixelAlpha(image,pixel,q); else SetPixelGreen(image,pixel,q); break; } case 2: { if (image->storage_class == PseudoClass) SetPixelAlpha(image,pixel,q); else SetPixelBlue(image,pixel,q); break; } case 3: { if (image->colorspace == CMYKColorspace) SetPixelBlack(image,pixel,q); else if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(image,pixel,q); break; } case 4: { if ((IssRGBCompatibleColorspace(image->colorspace) != MagickFalse) && (channels > 3)) break; if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(image,pixel,q); break; } default: break; } q+=GetPixelChannels(image); } return(SyncAuthenticPixels(image,exception)); }","static MagickBooleanType ReadPSDChannelPixels(Image *image, const size_t channels,const size_t row,const ssize_t type, const unsigned char *pixels,ExceptionInfo *exception) { Quantum pixel; register const unsigned char *p; register Quantum *q; register ssize_t x; size_t packet_size; unsigned short nibble; p=pixels; q=GetAuthenticPixels(image,0,row,image->columns,1,exception); if (q == (Quantum *) NULL) return MagickFalse; packet_size=GetPSDPacketSize(image); for (x=0; x < (ssize_t) image->columns; x++) { if (packet_size == 1) pixel=ScaleCharToQuantum(*p++); else { p=PushShortPixel(MSBEndian,p,&nibble); pixel=ScaleShortToQuantum(nibble); } switch (type) { case -1: { SetPixelAlpha(image,pixel,q); break; } case -2: case 0: { SetPixelRed(image,pixel,q); if (channels == 1 || type == -2) SetPixelGray(image,pixel,q); if (image->storage_class == PseudoClass) { if (packet_size == 1) SetPixelIndex(image,ScaleQuantumToChar(pixel),q); else SetPixelIndex(image,ScaleQuantumToShort(pixel),q); SetPixelViaPixelInfo(image,image->colormap+(ssize_t) ConstrainColormapIndex(image,GetPixelIndex(image,q),exception),q); if (image->depth == 1) { ssize_t bit, number_bits; number_bits=image->columns-x; if (number_bits > 8) number_bits=8; for (bit=0; bit < number_bits; bit++) { SetPixelIndex(image,(((unsigned char) pixel) & (0x01 << (7-bit))) != 0 ? 0 : 255,q); SetPixelViaPixelInfo(image,image->colormap+(ssize_t) ConstrainColormapIndex(image,GetPixelIndex(image,q), exception),q); q+=GetPixelChannels(image); x++; } x--; continue; } } break; } case 1: { if (image->storage_class == PseudoClass) SetPixelAlpha(image,pixel,q); else SetPixelGreen(image,pixel,q); break; } case 2: { if (image->storage_class == PseudoClass) SetPixelAlpha(image,pixel,q); else SetPixelBlue(image,pixel,q); break; } case 3: { if (image->colorspace == CMYKColorspace) SetPixelBlack(image,pixel,q); else if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(image,pixel,q); break; } case 4: { if ((IssRGBCompatibleColorspace(image->colorspace) != MagickFalse) && (channels > 3)) break; if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(image,pixel,q); break; } default: break; } q+=GetPixelChannels(image); } return(SyncAuthenticPixels(image,exception)); }","{'deleted': [{'line_no': 72, 'char_start': 1913, 'char_end': 1960, 'line': ' GetPixelIndex(image,q),q);\n'}], 'added': [{'line_no': 72, 'char_start': 1913, 'char_end': 1986, 'line': ' ConstrainColormapIndex(image,GetPixelIndex(image,q),\n'}, {'line_no': 73, 'char_start': 1986, 'char_end': 2023, 'line': ' exception),q);\n'}]}","{'deleted': [], 'added': [{'char_start': 1933, 'char_end': 1962, 'chars': 'ConstrainColormapIndex(image,'}, {'char_start': 1983, 'char_end': 2017, 'chars': '),\n exception'}]}",github.com/ImageMagick/ImageMagick/commit/e14fd0a2801f73bdc123baf4fbab97dec55919eb,coders/psd.c,cwe-125,764 cwe-078,process_statistics," def process_statistics(self, metadata, _): args = [metadata.hostname, '-p', metadata.profile, '-g', ':'.join([g for g in metadata.groups])] for notifier in os.listdir(self.data): if ((notifier[-1] == '~') or (notifier[:2] == '.#') or (notifier[-4:] == '.swp') or (notifier in ['SCCS', '.svn', '4913'])): continue npath = self.data + '/' + notifier self.logger.debug(""Running %s %s"" % (npath, "" "".join(args))) async_run(npath, args)"," def process_statistics(self, metadata, _): args = [metadata.hostname, '-p', metadata.profile, '-g', ':'.join([g for g in metadata.groups])] self.debug_log(""running triggers"") for notifier in os.listdir(self.data): self.debug_log(""running %s"" % notifier) if ((notifier[-1] == '~') or (notifier[:2] == '.#') or (notifier[-4:] == '.swp') or (notifier in ['SCCS', '.svn', '4913'])): continue npath = os.path.join(self.data, notifier) self.async_run([npath] + args)","{'deleted': [{'line_no': 10, 'char_start': 425, 'char_end': 472, 'line': "" npath = self.data + '/' + notifier\n""}, {'line_no': 11, 'char_start': 472, 'char_end': 545, 'line': ' self.logger.debug(""Running %s %s"" % (npath, "" "".join(args)))\n'}, {'line_no': 12, 'char_start': 545, 'char_end': 579, 'line': ' async_run(npath, args)\n'}], 'added': [{'line_no': 4, 'char_start': 168, 'char_end': 211, 'line': ' self.debug_log(""running triggers"")\n'}, {'line_no': 6, 'char_start': 258, 'char_end': 310, 'line': ' self.debug_log(""running %s"" % notifier)\n'}, {'line_no': 12, 'char_start': 520, 'char_end': 574, 'line': ' npath = os.path.join(self.data, notifier)\n'}, {'line_no': 13, 'char_start': 574, 'char_end': 616, 'line': ' self.async_run([npath] + args)'}]}","{'deleted': [{'char_start': 454, 'char_end': 462, 'chars': "" + '/' +""}, {'char_start': 489, 'char_end': 557, 'chars': 'logger.debug(""Running %s %s"" % (npath, "" "".join(args)))\n '}, {'char_start': 572, 'char_end': 573, 'chars': ','}], 'added': [{'char_start': 176, 'char_end': 219, 'chars': 'self.debug_log(""running triggers"")\n '}, {'char_start': 257, 'char_end': 309, 'chars': '\n self.debug_log(""running %s"" % notifier)'}, {'char_start': 540, 'char_end': 553, 'chars': 'os.path.join('}, {'char_start': 562, 'char_end': 563, 'chars': ','}, {'char_start': 572, 'char_end': 573, 'chars': ')'}, {'char_start': 601, 'char_end': 602, 'chars': '['}, {'char_start': 607, 'char_end': 610, 'chars': '] +'}]}",github.com/Bcfg2/bcfg2/commit/a524967e8d5c4c22e49cd619aed20c87a316c0be,src/lib/Server/Plugins/Trigger.py,cwe-078,149 cwe-078,do_setup," def do_setup(self, ctxt): """"""Check that we have all configuration details from the storage."""""" LOG.debug(_('enter: do_setup')) self._context = ctxt # Validate that the pool exists ssh_cmd = 'svcinfo lsmdiskgrp -delim ! -nohdr' out, err = self._run_ssh(ssh_cmd) self._assert_ssh_return(len(out.strip()), 'do_setup', ssh_cmd, out, err) search_text = '!%s!' % self.configuration.storwize_svc_volpool_name if search_text not in out: raise exception.InvalidInput( reason=(_('pool %s doesn\'t exist') % self.configuration.storwize_svc_volpool_name)) # Check if compression is supported self._compression_enabled = False try: ssh_cmd = 'svcinfo lslicense -delim !' out, err = self._run_ssh(ssh_cmd) license_lines = out.strip().split('\n') for license_line in license_lines: name, foo, value = license_line.partition('!') if name in ('license_compression_enclosures', 'license_compression_capacity') and value != '0': self._compression_enabled = True break except exception.ProcessExecutionError: LOG.exception(_('Failed to get license information.')) # Get the iSCSI and FC names of the Storwize/SVC nodes ssh_cmd = 'svcinfo lsnode -delim !' out, err = self._run_ssh(ssh_cmd) self._assert_ssh_return(len(out.strip()), 'do_setup', ssh_cmd, out, err) nodes = out.strip().split('\n') self._assert_ssh_return(len(nodes), 'do_setup', ssh_cmd, out, err) header = nodes.pop(0) for node_line in nodes: try: node_data = self._get_hdr_dic(header, node_line, '!') except exception.VolumeBackendAPIException: with excutils.save_and_reraise_exception(): self._log_cli_output_error('do_setup', ssh_cmd, out, err) node = {} try: node['id'] = node_data['id'] node['name'] = node_data['name'] node['IO_group'] = node_data['IO_group_id'] node['iscsi_name'] = node_data['iscsi_name'] node['WWNN'] = node_data['WWNN'] node['status'] = node_data['status'] node['WWPN'] = [] node['ipv4'] = [] node['ipv6'] = [] node['enabled_protocols'] = [] if node['status'] == 'online': self._storage_nodes[node['id']] = node except KeyError: self._handle_keyerror('lsnode', header) # Get the iSCSI IP addresses and WWPNs of the Storwize/SVC nodes self._get_iscsi_ip_addrs() self._get_fc_wwpns() # For each node, check what connection modes it supports. Delete any # nodes that do not support any types (may be partially configured). to_delete = [] for k, node in self._storage_nodes.iteritems(): if ((len(node['ipv4']) or len(node['ipv6'])) and len(node['iscsi_name'])): node['enabled_protocols'].append('iSCSI') self._enabled_protocols.add('iSCSI') if len(node['WWPN']): node['enabled_protocols'].append('FC') self._enabled_protocols.add('FC') if not len(node['enabled_protocols']): to_delete.append(k) for delkey in to_delete: del self._storage_nodes[delkey] # Make sure we have at least one node configured self._driver_assert(len(self._storage_nodes), _('do_setup: No configured nodes')) LOG.debug(_('leave: do_setup'))"," def do_setup(self, ctxt): """"""Check that we have all configuration details from the storage."""""" LOG.debug(_('enter: do_setup')) self._context = ctxt # Validate that the pool exists ssh_cmd = ['svcinfo', 'lsmdiskgrp', '-delim', '!', '-nohdr'] out, err = self._run_ssh(ssh_cmd) self._assert_ssh_return(len(out.strip()), 'do_setup', ssh_cmd, out, err) search_text = '!%s!' % self.configuration.storwize_svc_volpool_name if search_text not in out: raise exception.InvalidInput( reason=(_('pool %s doesn\'t exist') % self.configuration.storwize_svc_volpool_name)) # Check if compression is supported self._compression_enabled = False try: ssh_cmd = ['svcinfo', 'lslicense', '-delim', '!'] out, err = self._run_ssh(ssh_cmd) license_lines = out.strip().split('\n') for license_line in license_lines: name, foo, value = license_line.partition('!') if name in ('license_compression_enclosures', 'license_compression_capacity') and value != '0': self._compression_enabled = True break except exception.ProcessExecutionError: LOG.exception(_('Failed to get license information.')) # Get the iSCSI and FC names of the Storwize/SVC nodes ssh_cmd = ['svcinfo', 'lsnode', '-delim', '!'] out, err = self._run_ssh(ssh_cmd) self._assert_ssh_return(len(out.strip()), 'do_setup', ssh_cmd, out, err) nodes = out.strip().split('\n') self._assert_ssh_return(len(nodes), 'do_setup', ssh_cmd, out, err) header = nodes.pop(0) for node_line in nodes: try: node_data = self._get_hdr_dic(header, node_line, '!') except exception.VolumeBackendAPIException: with excutils.save_and_reraise_exception(): self._log_cli_output_error('do_setup', ssh_cmd, out, err) node = {} try: node['id'] = node_data['id'] node['name'] = node_data['name'] node['IO_group'] = node_data['IO_group_id'] node['iscsi_name'] = node_data['iscsi_name'] node['WWNN'] = node_data['WWNN'] node['status'] = node_data['status'] node['WWPN'] = [] node['ipv4'] = [] node['ipv6'] = [] node['enabled_protocols'] = [] if node['status'] == 'online': self._storage_nodes[node['id']] = node except KeyError: self._handle_keyerror('lsnode', header) # Get the iSCSI IP addresses and WWPNs of the Storwize/SVC nodes self._get_iscsi_ip_addrs() self._get_fc_wwpns() # For each node, check what connection modes it supports. Delete any # nodes that do not support any types (may be partially configured). to_delete = [] for k, node in self._storage_nodes.iteritems(): if ((len(node['ipv4']) or len(node['ipv6'])) and len(node['iscsi_name'])): node['enabled_protocols'].append('iSCSI') self._enabled_protocols.add('iSCSI') if len(node['WWPN']): node['enabled_protocols'].append('FC') self._enabled_protocols.add('FC') if not len(node['enabled_protocols']): to_delete.append(k) for delkey in to_delete: del self._storage_nodes[delkey] # Make sure we have at least one node configured self._driver_assert(len(self._storage_nodes), _('do_setup: No configured nodes')) LOG.debug(_('leave: do_setup'))","{'deleted': [{'line_no': 8, 'char_start': 218, 'char_end': 273, 'line': "" ssh_cmd = 'svcinfo lsmdiskgrp -delim ! -nohdr'\n""}, {'line_no': 21, 'char_start': 806, 'char_end': 857, 'line': "" ssh_cmd = 'svcinfo lslicense -delim !'\n""}, {'line_no': 34, 'char_start': 1463, 'char_end': 1507, 'line': "" ssh_cmd = 'svcinfo lsnode -delim !'\n""}], 'added': [{'line_no': 8, 'char_start': 218, 'char_end': 287, 'line': "" ssh_cmd = ['svcinfo', 'lsmdiskgrp', '-delim', '!', '-nohdr']\n""}, {'line_no': 21, 'char_start': 820, 'char_end': 882, 'line': "" ssh_cmd = ['svcinfo', 'lslicense', '-delim', '!']\n""}, {'line_no': 34, 'char_start': 1488, 'char_end': 1543, 'line': "" ssh_cmd = ['svcinfo', 'lsnode', '-delim', '!']\n""}]}","{'deleted': [], 'added': [{'char_start': 236, 'char_end': 237, 'chars': '['}, {'char_start': 245, 'char_end': 247, 'chars': ""',""}, {'char_start': 248, 'char_end': 249, 'chars': ""'""}, {'char_start': 259, 'char_end': 261, 'chars': ""',""}, {'char_start': 262, 'char_end': 263, 'chars': ""'""}, {'char_start': 269, 'char_end': 271, 'chars': ""',""}, {'char_start': 272, 'char_end': 273, 'chars': ""'""}, {'char_start': 274, 'char_end': 276, 'chars': ""',""}, {'char_start': 277, 'char_end': 278, 'chars': ""'""}, {'char_start': 285, 'char_end': 286, 'chars': ']'}, {'char_start': 842, 'char_end': 843, 'chars': '['}, {'char_start': 851, 'char_end': 853, 'chars': ""',""}, {'char_start': 854, 'char_end': 855, 'chars': ""'""}, {'char_start': 864, 'char_end': 866, 'chars': ""',""}, {'char_start': 867, 'char_end': 868, 'chars': ""'""}, {'char_start': 874, 'char_end': 876, 'chars': ""',""}, {'char_start': 877, 'char_end': 878, 'chars': ""'""}, {'char_start': 880, 'char_end': 881, 'chars': ']'}, {'char_start': 1506, 'char_end': 1507, 'chars': '['}, {'char_start': 1515, 'char_end': 1517, 'chars': ""',""}, {'char_start': 1518, 'char_end': 1519, 'chars': ""'""}, {'char_start': 1525, 'char_end': 1527, 'chars': ""',""}, {'char_start': 1528, 'char_end': 1529, 'chars': ""'""}, {'char_start': 1535, 'char_end': 1537, 'chars': ""',""}, {'char_start': 1538, 'char_end': 1539, 'chars': ""'""}, {'char_start': 1541, 'char_end': 1542, 'chars': ']'}]}",github.com/thatsdone/cinder/commit/f752302d181583a95cf44354aea607ce9d9283f4,cinder/volume/drivers/storwize_svc.py,cwe-078,861 cwe-125,ReadOneMNGImage,"static Image *ReadOneMNGImage(MngInfo* mng_info, const ImageInfo *image_info, ExceptionInfo *exception) { char page_geometry[MaxTextExtent]; Image *image; MagickBooleanType logging; volatile int first_mng_object, object_id, term_chunk_found, skip_to_iend; volatile ssize_t image_count=0; MagickBooleanType status; MagickOffsetType offset; MngBox default_fb, fb, previous_fb; #if defined(MNG_INSERT_LAYERS) PixelPacket mng_background_color; #endif register unsigned char *p; register ssize_t i; size_t count; ssize_t loop_level; volatile short skipping_loop; #if defined(MNG_INSERT_LAYERS) unsigned int mandatory_back=0; #endif volatile unsigned int #ifdef MNG_OBJECT_BUFFERS mng_background_object=0, #endif mng_type=0; /* 0: PNG or JNG; 1: MNG; 2: MNG-LC; 3: MNG-VLC */ size_t default_frame_timeout, frame_timeout, #if defined(MNG_INSERT_LAYERS) image_height, image_width, #endif length; /* These delays are all measured in image ticks_per_second, * not in MNG ticks_per_second */ volatile size_t default_frame_delay, final_delay, final_image_delay, frame_delay, #if defined(MNG_INSERT_LAYERS) insert_layers, #endif mng_iterations=1, simplicity=0, subframe_height=0, subframe_width=0; previous_fb.top=0; previous_fb.bottom=0; previous_fb.left=0; previous_fb.right=0; default_fb.top=0; default_fb.bottom=0; default_fb.left=0; default_fb.right=0; logging=LogMagickEvent(CoderEvent,GetMagickModule(), "" Enter ReadOneMNGImage()""); image=mng_info->image; if (LocaleCompare(image_info->magick,""MNG"") == 0) { char magic_number[MaxTextExtent]; /* Verify MNG signature. */ count=(size_t) ReadBlob(image,8,(unsigned char *) magic_number); if (memcmp(magic_number,""\212MNG\r\n\032\n"",8) != 0) ThrowReaderException(CorruptImageError,""ImproperImageHeader""); /* Initialize some nonzero members of the MngInfo structure. */ for (i=0; i < MNG_MAX_OBJECTS; i++) { mng_info->object_clip[i].right=(ssize_t) PNG_UINT_31_MAX; mng_info->object_clip[i].bottom=(ssize_t) PNG_UINT_31_MAX; } mng_info->exists[0]=MagickTrue; } skipping_loop=(-1); first_mng_object=MagickTrue; mng_type=0; #if defined(MNG_INSERT_LAYERS) insert_layers=MagickFalse; /* should be False when converting or mogrifying */ #endif default_frame_delay=0; default_frame_timeout=0; frame_delay=0; final_delay=1; mng_info->ticks_per_second=1UL*image->ticks_per_second; object_id=0; skip_to_iend=MagickFalse; term_chunk_found=MagickFalse; mng_info->framing_mode=1; #if defined(MNG_INSERT_LAYERS) mandatory_back=MagickFalse; #endif #if defined(MNG_INSERT_LAYERS) mng_background_color=image->background_color; #endif default_fb=mng_info->frame; previous_fb=mng_info->frame; do { char type[MaxTextExtent]; if (LocaleCompare(image_info->magick,""MNG"") == 0) { unsigned char *chunk; /* Read a new chunk. */ type[0]='\0'; (void) ConcatenateMagickString(type,""errr"",MaxTextExtent); length=ReadBlobMSBLong(image); count=(size_t) ReadBlob(image,4,(unsigned char *) type); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" Reading MNG chunk type %c%c%c%c, length: %.20g"", type[0],type[1],type[2],type[3],(double) length); if (length > PNG_UINT_31_MAX) { status=MagickFalse; break; } if (count == 0) ThrowReaderException(CorruptImageError,""CorruptImage""); p=NULL; chunk=(unsigned char *) NULL; if (length != 0) { chunk=(unsigned char *) AcquireQuantumMemory(length+ MagickPathExtent,sizeof(*chunk)); if (chunk == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); for (i=0; i < (ssize_t) length; i++) { int c; c=ReadBlobByte(image); if (c == EOF) break; chunk[i]=(unsigned char) c; } p=chunk; } (void) ReadBlobMSBLong(image); /* read crc word */ #if !defined(JNG_SUPPORTED) if (memcmp(type,mng_JHDR,4) == 0) { skip_to_iend=MagickTrue; if (mng_info->jhdr_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,""JNGCompressNotSupported"",""`%s'"",image->filename); mng_info->jhdr_warning++; } #endif if (memcmp(type,mng_DHDR,4) == 0) { skip_to_iend=MagickTrue; if (mng_info->dhdr_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,""DeltaPNGNotSupported"",""`%s'"",image->filename); mng_info->dhdr_warning++; } if (memcmp(type,mng_MEND,4) == 0) break; if (skip_to_iend) { if (memcmp(type,mng_IEND,4) == 0) skip_to_iend=MagickFalse; if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" Skip to IEND.""); continue; } if (memcmp(type,mng_MHDR,4) == 0) { if (length != 28) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(CorruptImageError,""CorruptImage""); } mng_info->mng_width=(size_t) ((p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3]); mng_info->mng_height=(size_t) ((p[4] << 24) | (p[5] << 16) | (p[6] << 8) | p[7]); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" MNG width: %.20g"",(double) mng_info->mng_width); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" MNG height: %.20g"",(double) mng_info->mng_height); } p+=8; mng_info->ticks_per_second=(size_t) mng_get_long(p); if (mng_info->ticks_per_second == 0) default_frame_delay=0; else default_frame_delay=1UL*image->ticks_per_second/ mng_info->ticks_per_second; frame_delay=default_frame_delay; simplicity=0; /* Skip nominal layer count, frame count, and play time */ p+=16; simplicity=(size_t) mng_get_long(p); mng_type=1; /* Full MNG */ if ((simplicity != 0) && ((simplicity | 11) == 11)) mng_type=2; /* LC */ if ((simplicity != 0) && ((simplicity | 9) == 9)) mng_type=3; /* VLC */ #if defined(MNG_INSERT_LAYERS) if (mng_type != 3) insert_layers=MagickTrue; #endif if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); mng_info->image=image; } if ((mng_info->mng_width > 65535L) || (mng_info->mng_height > 65535L)) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(ImageError,""WidthOrHeightExceedsLimit""); } (void) FormatLocaleString(page_geometry,MaxTextExtent, ""%.20gx%.20g+0+0"",(double) mng_info->mng_width,(double) mng_info->mng_height); mng_info->frame.left=0; mng_info->frame.right=(ssize_t) mng_info->mng_width; mng_info->frame.top=0; mng_info->frame.bottom=(ssize_t) mng_info->mng_height; mng_info->clip=default_fb=previous_fb=mng_info->frame; for (i=0; i < MNG_MAX_OBJECTS; i++) mng_info->object_clip[i]=mng_info->frame; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_TERM,4) == 0) { int repeat=0; if (length != 0) repeat=p[0]; if (repeat == 3 && length > 8) { final_delay=(png_uint_32) mng_get_long(&p[2]); mng_iterations=(png_uint_32) mng_get_long(&p[6]); if (mng_iterations == PNG_UINT_31_MAX) mng_iterations=0; image->iterations=mng_iterations; term_chunk_found=MagickTrue; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" repeat=%d, final_delay=%.20g, iterations=%.20g"", repeat,(double) final_delay, (double) image->iterations); } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_DEFI,4) == 0) { if (mng_type == 3) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,""DEFI chunk found in MNG-VLC datastream"",""`%s'"", image->filename); if (length > 1) { object_id=(p[0] << 8) | p[1]; if (mng_type == 2 && object_id != 0) (void) ThrowMagickException(&image->exception, GetMagickModule(), CoderError,""Nonzero object_id in MNG-LC datastream"", ""`%s'"", image->filename); if (object_id > MNG_MAX_OBJECTS) { /* Instead of using a warning we should allocate a larger MngInfo structure and continue. */ (void) ThrowMagickException(&image->exception, GetMagickModule(), CoderError, ""object id too large"",""`%s'"",image->filename); object_id=MNG_MAX_OBJECTS; } if (mng_info->exists[object_id]) if (mng_info->frozen[object_id]) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); (void) ThrowMagickException(&image->exception, GetMagickModule(),CoderError, ""DEFI cannot redefine a frozen MNG object"",""`%s'"", image->filename); continue; } mng_info->exists[object_id]=MagickTrue; if (length > 2) mng_info->invisible[object_id]=p[2]; /* Extract object offset info. */ if (length > 11) { mng_info->x_off[object_id]=(ssize_t) ((p[4] << 24) | (p[5] << 16) | (p[6] << 8) | p[7]); mng_info->y_off[object_id]=(ssize_t) ((p[8] << 24) | (p[9] << 16) | (p[10] << 8) | p[11]); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" x_off[%d]: %.20g, y_off[%d]: %.20g"", object_id,(double) mng_info->x_off[object_id], object_id,(double) mng_info->y_off[object_id]); } } /* Extract object clipping info. */ if (length > 27) mng_info->object_clip[object_id]= mng_read_box(mng_info->frame,0, &p[12]); } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_bKGD,4) == 0) { mng_info->have_global_bkgd=MagickFalse; if (length > 5) { mng_info->mng_global_bkgd.red= ScaleShortToQuantum((unsigned short) ((p[0] << 8) | p[1])); mng_info->mng_global_bkgd.green= ScaleShortToQuantum((unsigned short) ((p[2] << 8) | p[3])); mng_info->mng_global_bkgd.blue= ScaleShortToQuantum((unsigned short) ((p[4] << 8) | p[5])); mng_info->have_global_bkgd=MagickTrue; } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_BACK,4) == 0) { #if defined(MNG_INSERT_LAYERS) if (length > 6) mandatory_back=p[6]; else mandatory_back=0; if (mandatory_back && length > 5) { mng_background_color.red= ScaleShortToQuantum((unsigned short) ((p[0] << 8) | p[1])); mng_background_color.green= ScaleShortToQuantum((unsigned short) ((p[2] << 8) | p[3])); mng_background_color.blue= ScaleShortToQuantum((unsigned short) ((p[4] << 8) | p[5])); mng_background_color.opacity=OpaqueOpacity; } #ifdef MNG_OBJECT_BUFFERS if (length > 8) mng_background_object=(p[7] << 8) | p[8]; #endif #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_PLTE,4) == 0) { /* Read global PLTE. */ if (length && (length < 769)) { if (mng_info->global_plte == (png_colorp) NULL) mng_info->global_plte=(png_colorp) AcquireQuantumMemory(256, sizeof(*mng_info->global_plte)); for (i=0; i < (ssize_t) (length/3); i++) { mng_info->global_plte[i].red=p[3*i]; mng_info->global_plte[i].green=p[3*i+1]; mng_info->global_plte[i].blue=p[3*i+2]; } mng_info->global_plte_length=(unsigned int) (length/3); } #ifdef MNG_LOOSE for ( ; i < 256; i++) { mng_info->global_plte[i].red=i; mng_info->global_plte[i].green=i; mng_info->global_plte[i].blue=i; } if (length != 0) mng_info->global_plte_length=256; #endif else mng_info->global_plte_length=0; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_tRNS,4) == 0) { /* read global tRNS */ if (length > 0 && length < 257) for (i=0; i < (ssize_t) length; i++) mng_info->global_trns[i]=p[i]; #ifdef MNG_LOOSE for ( ; i < 256; i++) mng_info->global_trns[i]=255; #endif mng_info->global_trns_length=(unsigned int) length; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_gAMA,4) == 0) { if (length == 4) { ssize_t igamma; igamma=mng_get_long(p); mng_info->global_gamma=((float) igamma)*0.00001; mng_info->have_global_gama=MagickTrue; } else mng_info->have_global_gama=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_cHRM,4) == 0) { /* Read global cHRM */ if (length == 32) { mng_info->global_chrm.white_point.x=0.00001*mng_get_long(p); mng_info->global_chrm.white_point.y=0.00001*mng_get_long(&p[4]); mng_info->global_chrm.red_primary.x=0.00001*mng_get_long(&p[8]); mng_info->global_chrm.red_primary.y=0.00001* mng_get_long(&p[12]); mng_info->global_chrm.green_primary.x=0.00001* mng_get_long(&p[16]); mng_info->global_chrm.green_primary.y=0.00001* mng_get_long(&p[20]); mng_info->global_chrm.blue_primary.x=0.00001* mng_get_long(&p[24]); mng_info->global_chrm.blue_primary.y=0.00001* mng_get_long(&p[28]); mng_info->have_global_chrm=MagickTrue; } else mng_info->have_global_chrm=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_sRGB,4) == 0) { /* Read global sRGB. */ if (length != 0) { mng_info->global_srgb_intent= Magick_RenderingIntent_from_PNG_RenderingIntent(p[0]); mng_info->have_global_srgb=MagickTrue; } else mng_info->have_global_srgb=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_iCCP,4) == 0) { /* To do: */ /* Read global iCCP. */ if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_FRAM,4) == 0) { if (mng_type == 3) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,""FRAM chunk found in MNG-VLC datastream"",""`%s'"", image->filename); if ((mng_info->framing_mode == 2) || (mng_info->framing_mode == 4)) image->delay=frame_delay; frame_delay=default_frame_delay; frame_timeout=default_frame_timeout; fb=default_fb; if (length > 0) if (p[0]) mng_info->framing_mode=p[0]; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" Framing_mode=%d"",mng_info->framing_mode); if (length > 6) { /* Note the delay and frame clipping boundaries. */ p++; /* framing mode */ while (*p && ((p-chunk) < (ssize_t) length)) p++; /* frame name */ p++; /* frame name terminator */ if ((p-chunk) < (ssize_t) (length-4)) { int change_delay, change_timeout, change_clipping; change_delay=(*p++); change_timeout=(*p++); change_clipping=(*p++); p++; /* change_sync */ if (change_delay && (p-chunk) < (ssize_t) (length-4)) { frame_delay=1UL*image->ticks_per_second* mng_get_long(p); if (mng_info->ticks_per_second != 0) frame_delay/=mng_info->ticks_per_second; else frame_delay=PNG_UINT_31_MAX; if (change_delay == 2) default_frame_delay=frame_delay; p+=4; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" Framing_delay=%.20g"",(double) frame_delay); } if (change_timeout && (p-chunk) < (ssize_t) (length-4)) { frame_timeout=1UL*image->ticks_per_second* mng_get_long(p); if (mng_info->ticks_per_second != 0) frame_timeout/=mng_info->ticks_per_second; else frame_timeout=PNG_UINT_31_MAX; if (change_timeout == 2) default_frame_timeout=frame_timeout; p+=4; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" Framing_timeout=%.20g"",(double) frame_timeout); } if (change_clipping && (p-chunk) < (ssize_t) (length-17)) { fb=mng_read_box(previous_fb,(char) p[0],&p[1]); p+=17; previous_fb=fb; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" Frame_clip: L=%.20g R=%.20g T=%.20g B=%.20g"", (double) fb.left,(double) fb.right,(double) fb.top, (double) fb.bottom); if (change_clipping == 2) default_fb=fb; } } } mng_info->clip=fb; mng_info->clip=mng_minimum_box(fb,mng_info->frame); subframe_width=(size_t) (mng_info->clip.right -mng_info->clip.left); subframe_height=(size_t) (mng_info->clip.bottom -mng_info->clip.top); /* Insert a background layer behind the frame if framing_mode is 4. */ #if defined(MNG_INSERT_LAYERS) if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" subframe_width=%.20g, subframe_height=%.20g"",(double) subframe_width,(double) subframe_height); if (insert_layers && (mng_info->framing_mode == 4) && (subframe_width) && (subframe_height)) { /* Allocate next image structure. */ if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; if (term_chunk_found) { image->start_loop=MagickTrue; image->iterations=mng_iterations; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; image->columns=subframe_width; image->rows=subframe_height; image->page.width=subframe_width; image->page.height=subframe_height; image->page.x=mng_info->clip.left; image->page.y=mng_info->clip.top; image->background_color=mng_background_color; image->matte=MagickFalse; image->delay=0; (void) SetImageBackgroundColor(image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" Insert backgd layer, L=%.20g, R=%.20g T=%.20g, B=%.20g"", (double) mng_info->clip.left,(double) mng_info->clip.right, (double) mng_info->clip.top,(double) mng_info->clip.bottom); } #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_CLIP,4) == 0) { unsigned int first_object, last_object; /* Read CLIP. */ if (length > 3) { first_object=(p[0] << 8) | p[1]; last_object=(p[2] << 8) | p[3]; p+=4; for (i=(int) first_object; i <= (int) last_object; i++) { if (mng_info->exists[i] && !mng_info->frozen[i]) { MngBox box; box=mng_info->object_clip[i]; if ((p-chunk) < (ssize_t) (length-17)) mng_info->object_clip[i]= mng_read_box(box,(char) p[0],&p[1]); } } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_SAVE,4) == 0) { for (i=1; i < MNG_MAX_OBJECTS; i++) if (mng_info->exists[i]) { mng_info->frozen[i]=MagickTrue; #ifdef MNG_OBJECT_BUFFERS if (mng_info->ob[i] != (MngBuffer *) NULL) mng_info->ob[i]->frozen=MagickTrue; #endif } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if ((memcmp(type,mng_DISC,4) == 0) || (memcmp(type,mng_SEEK,4) == 0)) { /* Read DISC or SEEK. */ if ((length == 0) || !memcmp(type,mng_SEEK,4)) { for (i=1; i < MNG_MAX_OBJECTS; i++) MngInfoDiscardObject(mng_info,i); } else { register ssize_t j; for (j=1; j < (ssize_t) length; j+=2) { i=p[j-1] << 8 | p[j]; MngInfoDiscardObject(mng_info,i); } } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_MOVE,4) == 0) { size_t first_object, last_object; /* read MOVE */ if (length > 3) { first_object=(p[0] << 8) | p[1]; last_object=(p[2] << 8) | p[3]; p+=4; for (i=(ssize_t) first_object; i <= (ssize_t) last_object; i++) { if (mng_info->exists[i] && !mng_info->frozen[i] && (p-chunk) < (ssize_t) (length-8)) { MngPair new_pair; MngPair old_pair; old_pair.a=mng_info->x_off[i]; old_pair.b=mng_info->y_off[i]; new_pair=mng_read_pair(old_pair,(int) p[0],&p[1]); mng_info->x_off[i]=new_pair.a; mng_info->y_off[i]=new_pair.b; } } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_LOOP,4) == 0) { ssize_t loop_iters=1; if (length > 4) { loop_level=chunk[0]; mng_info->loop_active[loop_level]=1; /* mark loop active */ /* Record starting point. */ loop_iters=mng_get_long(&chunk[1]); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" LOOP level %.20g has %.20g iterations "", (double) loop_level, (double) loop_iters); if (loop_iters == 0) skipping_loop=loop_level; else { mng_info->loop_jump[loop_level]=TellBlob(image); mng_info->loop_count[loop_level]=loop_iters; } mng_info->loop_iteration[loop_level]=0; } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_ENDL,4) == 0) { if (length > 0) { loop_level=chunk[0]; if (skipping_loop > 0) { if (skipping_loop == loop_level) { /* Found end of zero-iteration loop. */ skipping_loop=(-1); mng_info->loop_active[loop_level]=0; } } else { if (mng_info->loop_active[loop_level] == 1) { mng_info->loop_count[loop_level]--; mng_info->loop_iteration[loop_level]++; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" ENDL: LOOP level %.20g has %.20g remaining iters "", (double) loop_level,(double) mng_info->loop_count[loop_level]); if (mng_info->loop_count[loop_level] != 0) { offset=SeekBlob(image, mng_info->loop_jump[loop_level], SEEK_SET); if (offset < 0) { chunk=(unsigned char *) RelinquishMagickMemory( chunk); ThrowReaderException(CorruptImageError, ""ImproperImageHeader""); } } else { short last_level; /* Finished loop. */ mng_info->loop_active[loop_level]=0; last_level=(-1); for (i=0; i < loop_level; i++) if (mng_info->loop_active[i] == 1) last_level=(short) i; loop_level=last_level; } } } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_CLON,4) == 0) { if (mng_info->clon_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,""CLON is not implemented yet"",""`%s'"", image->filename); mng_info->clon_warning++; } if (memcmp(type,mng_MAGN,4) == 0) { png_uint_16 magn_first, magn_last, magn_mb, magn_ml, magn_mr, magn_mt, magn_mx, magn_my, magn_methx, magn_methy; if (length > 1) magn_first=(p[0] << 8) | p[1]; else magn_first=0; if (length > 3) magn_last=(p[2] << 8) | p[3]; else magn_last=magn_first; #ifndef MNG_OBJECT_BUFFERS if (magn_first || magn_last) if (mng_info->magn_warning == 0) { (void) ThrowMagickException(&image->exception, GetMagickModule(),CoderError, ""MAGN is not implemented yet for nonzero objects"", ""`%s'"",image->filename); mng_info->magn_warning++; } #endif if (length > 4) magn_methx=p[4]; else magn_methx=0; if (length > 6) magn_mx=(p[5] << 8) | p[6]; else magn_mx=1; if (magn_mx == 0) magn_mx=1; if (length > 8) magn_my=(p[7] << 8) | p[8]; else magn_my=magn_mx; if (magn_my == 0) magn_my=1; if (length > 10) magn_ml=(p[9] << 8) | p[10]; else magn_ml=magn_mx; if (magn_ml == 0) magn_ml=1; if (length > 12) magn_mr=(p[11] << 8) | p[12]; else magn_mr=magn_mx; if (magn_mr == 0) magn_mr=1; if (length > 14) magn_mt=(p[13] << 8) | p[14]; else magn_mt=magn_my; if (magn_mt == 0) magn_mt=1; if (length > 16) magn_mb=(p[15] << 8) | p[16]; else magn_mb=magn_my; if (magn_mb == 0) magn_mb=1; if (length > 17) magn_methy=p[17]; else magn_methy=magn_methx; if (magn_methx > 5 || magn_methy > 5) if (mng_info->magn_warning == 0) { (void) ThrowMagickException(&image->exception, GetMagickModule(),CoderError, ""Unknown MAGN method in MNG datastream"",""`%s'"", image->filename); mng_info->magn_warning++; } #ifdef MNG_OBJECT_BUFFERS /* Magnify existing objects in the range magn_first to magn_last */ #endif if (magn_first == 0 || magn_last == 0) { /* Save the magnification factors for object 0 */ mng_info->magn_mb=magn_mb; mng_info->magn_ml=magn_ml; mng_info->magn_mr=magn_mr; mng_info->magn_mt=magn_mt; mng_info->magn_mx=magn_mx; mng_info->magn_my=magn_my; mng_info->magn_methx=magn_methx; mng_info->magn_methy=magn_methy; } } if (memcmp(type,mng_PAST,4) == 0) { if (mng_info->past_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,""PAST is not implemented yet"",""`%s'"", image->filename); mng_info->past_warning++; } if (memcmp(type,mng_SHOW,4) == 0) { if (mng_info->show_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,""SHOW is not implemented yet"",""`%s'"", image->filename); mng_info->show_warning++; } if (memcmp(type,mng_sBIT,4) == 0) { if (length < 4) mng_info->have_global_sbit=MagickFalse; else { mng_info->global_sbit.gray=p[0]; mng_info->global_sbit.red=p[0]; mng_info->global_sbit.green=p[1]; mng_info->global_sbit.blue=p[2]; mng_info->global_sbit.alpha=p[3]; mng_info->have_global_sbit=MagickTrue; } } if (memcmp(type,mng_pHYs,4) == 0) { if (length > 8) { mng_info->global_x_pixels_per_unit= (size_t) mng_get_long(p); mng_info->global_y_pixels_per_unit= (size_t) mng_get_long(&p[4]); mng_info->global_phys_unit_type=p[8]; mng_info->have_global_phys=MagickTrue; } else mng_info->have_global_phys=MagickFalse; } if (memcmp(type,mng_pHYg,4) == 0) { if (mng_info->phyg_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,""pHYg is not implemented."",""`%s'"",image->filename); mng_info->phyg_warning++; } if (memcmp(type,mng_BASI,4) == 0) { skip_to_iend=MagickTrue; if (mng_info->basi_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,""BASI is not implemented yet"",""`%s'"", image->filename); mng_info->basi_warning++; #ifdef MNG_BASI_SUPPORTED if (length > 11) { basi_width=(size_t) ((p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3]); basi_height=(size_t) ((p[4] << 24) | (p[5] << 16) | (p[6] << 8) | p[7]); basi_color_type=p[8]; basi_compression_method=p[9]; basi_filter_type=p[10]; basi_interlace_method=p[11]; } if (length > 13) basi_red=(p[12] << 8) & p[13]; else basi_red=0; if (length > 15) basi_green=(p[14] << 8) & p[15]; else basi_green=0; if (length > 17) basi_blue=(p[16] << 8) & p[17]; else basi_blue=0; if (length > 19) basi_alpha=(p[18] << 8) & p[19]; else { if (basi_sample_depth == 16) basi_alpha=65535L; else basi_alpha=255; } if (length > 20) basi_viewable=p[20]; else basi_viewable=0; #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_IHDR,4) #if defined(JNG_SUPPORTED) && memcmp(type,mng_JHDR,4) #endif ) { /* Not an IHDR or JHDR chunk */ if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } /* Process IHDR */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" Processing %c%c%c%c chunk"",type[0],type[1],type[2],type[3]); mng_info->exists[object_id]=MagickTrue; mng_info->viewable[object_id]=MagickTrue; if (mng_info->invisible[object_id]) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" Skipping invisible object""); skip_to_iend=MagickTrue; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } #if defined(MNG_INSERT_LAYERS) if (length < 8) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(CorruptImageError,""ImproperImageHeader""); } image_width=(size_t) mng_get_long(p); image_height=(size_t) mng_get_long(&p[4]); #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); /* Insert a transparent background layer behind the entire animation if it is not full screen. */ #if defined(MNG_INSERT_LAYERS) if (insert_layers && mng_type && first_mng_object) { if ((mng_info->clip.left > 0) || (mng_info->clip.top > 0) || (image_width < mng_info->mng_width) || (mng_info->clip.right < (ssize_t) mng_info->mng_width) || (image_height < mng_info->mng_height) || (mng_info->clip.bottom < (ssize_t) mng_info->mng_height)) { if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; if (term_chunk_found) { image->start_loop=MagickTrue; image->iterations=mng_iterations; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; /* Make a background rectangle. */ image->delay=0; image->columns=mng_info->mng_width; image->rows=mng_info->mng_height; image->page.width=mng_info->mng_width; image->page.height=mng_info->mng_height; image->page.x=0; image->page.y=0; image->background_color=mng_background_color; (void) SetImageBackgroundColor(image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" Inserted transparent background layer, W=%.20g, H=%.20g"", (double) mng_info->mng_width,(double) mng_info->mng_height); } } /* Insert a background layer behind the upcoming image if framing_mode is 3, and we haven't already inserted one. */ if (insert_layers && (mng_info->framing_mode == 3) && (subframe_width) && (subframe_height) && (simplicity == 0 || (simplicity & 0x08))) { if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; if (term_chunk_found) { image->start_loop=MagickTrue; image->iterations=mng_iterations; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; image->delay=0; image->columns=subframe_width; image->rows=subframe_height; image->page.width=subframe_width; image->page.height=subframe_height; image->page.x=mng_info->clip.left; image->page.y=mng_info->clip.top; image->background_color=mng_background_color; image->matte=MagickFalse; (void) SetImageBackgroundColor(image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" Insert background layer, L=%.20g, R=%.20g T=%.20g, B=%.20g"", (double) mng_info->clip.left,(double) mng_info->clip.right, (double) mng_info->clip.top,(double) mng_info->clip.bottom); } #endif /* MNG_INSERT_LAYERS */ first_mng_object=MagickFalse; if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; if (term_chunk_found) { image->start_loop=MagickTrue; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; if (mng_info->framing_mode == 1 || mng_info->framing_mode == 3) { image->delay=frame_delay; frame_delay=default_frame_delay; } else image->delay=0; image->page.width=mng_info->mng_width; image->page.height=mng_info->mng_height; image->page.x=mng_info->x_off[object_id]; image->page.y=mng_info->y_off[object_id]; image->iterations=mng_iterations; /* Seek back to the beginning of the IHDR or JHDR chunk's length field. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" Seeking back to beginning of %c%c%c%c chunk"",type[0],type[1], type[2],type[3]); offset=SeekBlob(image,-((ssize_t) length+12),SEEK_CUR); if (offset < 0) ThrowReaderException(CorruptImageError,""ImproperImageHeader""); } mng_info->image=image; mng_info->mng_type=mng_type; mng_info->object_id=object_id; if (memcmp(type,mng_IHDR,4) == 0) image=ReadOnePNGImage(mng_info,image_info,exception); #if defined(JNG_SUPPORTED) else image=ReadOneJNGImage(mng_info,image_info,exception); #endif if (image == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), ""exit ReadJNGImage() with error""); return((Image *) NULL); } if (image->columns == 0 || image->rows == 0) { (void) CloseBlob(image); return(DestroyImageList(image)); } mng_info->image=image; if (mng_type) { MngBox crop_box; if (mng_info->magn_methx || mng_info->magn_methy) { png_uint_32 magnified_height, magnified_width; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" Processing MNG MAGN chunk""); if (mng_info->magn_methx == 1) { magnified_width=mng_info->magn_ml; if (image->columns > 1) magnified_width += mng_info->magn_mr; if (image->columns > 2) magnified_width += (png_uint_32) ((image->columns-2)*(mng_info->magn_mx)); } else { magnified_width=(png_uint_32) image->columns; if (image->columns > 1) magnified_width += mng_info->magn_ml-1; if (image->columns > 2) magnified_width += mng_info->magn_mr-1; if (image->columns > 3) magnified_width += (png_uint_32) ((image->columns-3)*(mng_info->magn_mx-1)); } if (mng_info->magn_methy == 1) { magnified_height=mng_info->magn_mt; if (image->rows > 1) magnified_height += mng_info->magn_mb; if (image->rows > 2) magnified_height += (png_uint_32) ((image->rows-2)*(mng_info->magn_my)); } else { magnified_height=(png_uint_32) image->rows; if (image->rows > 1) magnified_height += mng_info->magn_mt-1; if (image->rows > 2) magnified_height += mng_info->magn_mb-1; if (image->rows > 3) magnified_height += (png_uint_32) ((image->rows-3)*(mng_info->magn_my-1)); } if (magnified_height > image->rows || magnified_width > image->columns) { Image *large_image; int yy; ssize_t m, y; register ssize_t x; register PixelPacket *n, *q; PixelPacket *next, *prev; png_uint_16 magn_methx, magn_methy; /* Allocate next image structure. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" Allocate magnified image""); AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); large_image=SyncNextImageInList(image); large_image->columns=magnified_width; large_image->rows=magnified_height; magn_methx=mng_info->magn_methx; magn_methy=mng_info->magn_methy; #if (MAGICKCORE_QUANTUM_DEPTH > 16) #define QM unsigned short if (magn_methx != 1 || magn_methy != 1) { /* Scale pixels to unsigned shorts to prevent overflow of intermediate values of interpolations */ for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1, exception); for (x=(ssize_t) image->columns-1; x >= 0; x--) { SetPixelRed(q,ScaleQuantumToShort( GetPixelRed(q))); SetPixelGreen(q,ScaleQuantumToShort( GetPixelGreen(q))); SetPixelBlue(q,ScaleQuantumToShort( GetPixelBlue(q))); SetPixelOpacity(q,ScaleQuantumToShort( GetPixelOpacity(q))); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } #else #define QM Quantum #endif if (image->matte != MagickFalse) (void) SetImageBackgroundColor(large_image); else { large_image->background_color.opacity=OpaqueOpacity; (void) SetImageBackgroundColor(large_image); if (magn_methx == 4) magn_methx=2; if (magn_methx == 5) magn_methx=3; if (magn_methy == 4) magn_methy=2; if (magn_methy == 5) magn_methy=3; } /* magnify the rows into the right side of the large image */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" Magnify the rows to %.20g"",(double) large_image->rows); m=(ssize_t) mng_info->magn_mt; yy=0; length=(size_t) image->columns; next=(PixelPacket *) AcquireQuantumMemory(length,sizeof(*next)); prev=(PixelPacket *) AcquireQuantumMemory(length,sizeof(*prev)); if ((prev == (PixelPacket *) NULL) || (next == (PixelPacket *) NULL)) { image=DestroyImageList(image); ThrowReaderException(ResourceLimitError, ""MemoryAllocationFailed""); } n=GetAuthenticPixels(image,0,0,image->columns,1,exception); (void) CopyMagickMemory(next,n,length); for (y=0; y < (ssize_t) image->rows; y++) { if (y == 0) m=(ssize_t) mng_info->magn_mt; else if (magn_methy > 1 && y == (ssize_t) image->rows-2) m=(ssize_t) mng_info->magn_mb; else if (magn_methy <= 1 && y == (ssize_t) image->rows-1) m=(ssize_t) mng_info->magn_mb; else if (magn_methy > 1 && y == (ssize_t) image->rows-1) m=1; else m=(ssize_t) mng_info->magn_my; n=prev; prev=next; next=n; if (y < (ssize_t) image->rows-1) { n=GetAuthenticPixels(image,0,y+1,image->columns,1, exception); (void) CopyMagickMemory(next,n,length); } for (i=0; i < m; i++, yy++) { register PixelPacket *pixels; assert(yy < (ssize_t) large_image->rows); pixels=prev; n=next; q=GetAuthenticPixels(large_image,0,yy,large_image->columns, 1,exception); q+=(large_image->columns-image->columns); for (x=(ssize_t) image->columns-1; x >= 0; x--) { /* To do: get color as function of indexes[x] */ /* if (image->storage_class == PseudoClass) { } */ if (magn_methy <= 1) { /* replicate previous */ SetPixelRGBO(q,(pixels)); } else if (magn_methy == 2 || magn_methy == 4) { if (i == 0) { SetPixelRGBO(q,(pixels)); } else { /* Interpolate */ SetPixelRed(q, ((QM) (((ssize_t) (2*i*(GetPixelRed(n) -GetPixelRed(pixels)+m))/ ((ssize_t) (m*2)) +GetPixelRed(pixels))))); SetPixelGreen(q, ((QM) (((ssize_t) (2*i*(GetPixelGreen(n) -GetPixelGreen(pixels)+m))/ ((ssize_t) (m*2)) +GetPixelGreen(pixels))))); SetPixelBlue(q, ((QM) (((ssize_t) (2*i*(GetPixelBlue(n) -GetPixelBlue(pixels)+m))/ ((ssize_t) (m*2)) +GetPixelBlue(pixels))))); if (image->matte != MagickFalse) SetPixelOpacity(q, ((QM) (((ssize_t) (2*i*(GetPixelOpacity(n) -GetPixelOpacity(pixels)+m)) /((ssize_t) (m*2))+ GetPixelOpacity(pixels))))); } if (magn_methy == 4) { /* Replicate nearest */ if (i <= ((m+1) << 1)) SetPixelOpacity(q, (*pixels).opacity+0); else SetPixelOpacity(q, (*n).opacity+0); } } else /* if (magn_methy == 3 || magn_methy == 5) */ { /* Replicate nearest */ if (i <= ((m+1) << 1)) { SetPixelRGBO(q,(pixels)); } else { SetPixelRGBO(q,(n)); } if (magn_methy == 5) { SetPixelOpacity(q, (QM) (((ssize_t) (2*i* (GetPixelOpacity(n) -GetPixelOpacity(pixels)) +m))/((ssize_t) (m*2)) +GetPixelOpacity(pixels))); } } n++; q++; pixels++; } /* x */ if (SyncAuthenticPixels(large_image,exception) == 0) break; } /* i */ } /* y */ prev=(PixelPacket *) RelinquishMagickMemory(prev); next=(PixelPacket *) RelinquishMagickMemory(next); length=image->columns; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" Delete original image""); DeleteImageFromList(&image); image=large_image; mng_info->image=image; /* magnify the columns */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" Magnify the columns to %.20g"",(double) image->columns); for (y=0; y < (ssize_t) image->rows; y++) { register PixelPacket *pixels; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); pixels=q+(image->columns-length); n=pixels+1; for (x=(ssize_t) (image->columns-length); x < (ssize_t) image->columns; x++) { /* To do: Rewrite using Get/Set***PixelComponent() */ if (x == (ssize_t) (image->columns-length)) m=(ssize_t) mng_info->magn_ml; else if (magn_methx > 1 && x == (ssize_t) image->columns-2) m=(ssize_t) mng_info->magn_mr; else if (magn_methx <= 1 && x == (ssize_t) image->columns-1) m=(ssize_t) mng_info->magn_mr; else if (magn_methx > 1 && x == (ssize_t) image->columns-1) m=1; else m=(ssize_t) mng_info->magn_mx; for (i=0; i < m; i++) { if (magn_methx <= 1) { /* replicate previous */ SetPixelRGBO(q,(pixels)); } else if (magn_methx == 2 || magn_methx == 4) { if (i == 0) { SetPixelRGBO(q,(pixels)); } /* To do: Rewrite using Get/Set***PixelComponent() */ else { /* Interpolate */ SetPixelRed(q, (QM) ((2*i*( GetPixelRed(n) -GetPixelRed(pixels))+m) /((ssize_t) (m*2))+ GetPixelRed(pixels))); SetPixelGreen(q, (QM) ((2*i*( GetPixelGreen(n) -GetPixelGreen(pixels))+m) /((ssize_t) (m*2))+ GetPixelGreen(pixels))); SetPixelBlue(q, (QM) ((2*i*( GetPixelBlue(n) -GetPixelBlue(pixels))+m) /((ssize_t) (m*2))+ GetPixelBlue(pixels))); if (image->matte != MagickFalse) SetPixelOpacity(q, (QM) ((2*i*( GetPixelOpacity(n) -GetPixelOpacity(pixels))+m) /((ssize_t) (m*2))+ GetPixelOpacity(pixels))); } if (magn_methx == 4) { /* Replicate nearest */ if (i <= ((m+1) << 1)) { SetPixelOpacity(q, GetPixelOpacity(pixels)+0); } else { SetPixelOpacity(q, GetPixelOpacity(n)+0); } } } else /* if (magn_methx == 3 || magn_methx == 5) */ { /* Replicate nearest */ if (i <= ((m+1) << 1)) { SetPixelRGBO(q,(pixels)); } else { SetPixelRGBO(q,(n)); } if (magn_methx == 5) { /* Interpolate */ SetPixelOpacity(q, (QM) ((2*i*( GetPixelOpacity(n) -GetPixelOpacity(pixels))+m)/ ((ssize_t) (m*2)) +GetPixelOpacity(pixels))); } } q++; } n++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } #if (MAGICKCORE_QUANTUM_DEPTH > 16) if (magn_methx != 1 || magn_methy != 1) { /* Rescale pixels to Quantum */ for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); for (x=(ssize_t) image->columns-1; x >= 0; x--) { SetPixelRed(q,ScaleShortToQuantum( GetPixelRed(q))); SetPixelGreen(q,ScaleShortToQuantum( GetPixelGreen(q))); SetPixelBlue(q,ScaleShortToQuantum( GetPixelBlue(q))); SetPixelOpacity(q,ScaleShortToQuantum( GetPixelOpacity(q))); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } #endif if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" Finished MAGN processing""); } } /* Crop_box is with respect to the upper left corner of the MNG. */ crop_box.left=mng_info->image_box.left+mng_info->x_off[object_id]; crop_box.right=mng_info->image_box.right+mng_info->x_off[object_id]; crop_box.top=mng_info->image_box.top+mng_info->y_off[object_id]; crop_box.bottom=mng_info->image_box.bottom+mng_info->y_off[object_id]; crop_box=mng_minimum_box(crop_box,mng_info->clip); crop_box=mng_minimum_box(crop_box,mng_info->frame); crop_box=mng_minimum_box(crop_box,mng_info->object_clip[object_id]); if ((crop_box.left != (mng_info->image_box.left +mng_info->x_off[object_id])) || (crop_box.right != (mng_info->image_box.right +mng_info->x_off[object_id])) || (crop_box.top != (mng_info->image_box.top +mng_info->y_off[object_id])) || (crop_box.bottom != (mng_info->image_box.bottom +mng_info->y_off[object_id]))) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" Crop the PNG image""); if ((crop_box.left < crop_box.right) && (crop_box.top < crop_box.bottom)) { Image *im; RectangleInfo crop_info; /* Crop_info is with respect to the upper left corner of the image. */ crop_info.x=(crop_box.left-mng_info->x_off[object_id]); crop_info.y=(crop_box.top-mng_info->y_off[object_id]); crop_info.width=(size_t) (crop_box.right-crop_box.left); crop_info.height=(size_t) (crop_box.bottom-crop_box.top); image->page.width=image->columns; image->page.height=image->rows; image->page.x=0; image->page.y=0; im=CropImage(image,&crop_info,exception); if (im != (Image *) NULL) { image->columns=im->columns; image->rows=im->rows; im=DestroyImage(im); image->page.width=image->columns; image->page.height=image->rows; image->page.x=crop_box.left; image->page.y=crop_box.top; } } else { /* No pixels in crop area. The MNG spec still requires a layer, though, so make a single transparent pixel in the top left corner. */ image->columns=1; image->rows=1; image->colors=2; (void) SetImageBackgroundColor(image); image->page.width=1; image->page.height=1; image->page.x=0; image->page.y=0; } } #ifndef PNG_READ_EMPTY_PLTE_SUPPORTED image=mng_info->image; #endif } #if (MAGICKCORE_QUANTUM_DEPTH > 16) /* PNG does not handle depths greater than 16 so reduce it even * if lossy, and promote any depths > 8 to 16. */ if (image->depth > 16) image->depth=16; #endif #if (MAGICKCORE_QUANTUM_DEPTH > 8) if (image->depth > 8) { /* To do: fill low byte properly */ image->depth=16; } if (LosslessReduceDepthOK(image) != MagickFalse) image->depth = 8; #endif GetImageException(image,exception); if (image_info->number_scenes != 0) { if (mng_info->scenes_found > (ssize_t) (image_info->first_scene+image_info->number_scenes)) break; } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" Finished reading image datastream.""); } while (LocaleCompare(image_info->magick,""MNG"") == 0); (void) CloseBlob(image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" Finished reading all image datastreams.""); #if defined(MNG_INSERT_LAYERS) if (insert_layers && !mng_info->image_found && (mng_info->mng_width) && (mng_info->mng_height)) { /* Insert a background layer if nothing else was found. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" No images found. Inserting a background layer.""); if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" Allocation failed, returning NULL.""); return(DestroyImageList(image)); } image=SyncNextImageInList(image); } image->columns=mng_info->mng_width; image->rows=mng_info->mng_height; image->page.width=mng_info->mng_width; image->page.height=mng_info->mng_height; image->page.x=0; image->page.y=0; image->background_color=mng_background_color; image->matte=MagickFalse; if (image_info->ping == MagickFalse) (void) SetImageBackgroundColor(image); mng_info->image_found++; } #endif image->iterations=mng_iterations; if (mng_iterations == 1) image->start_loop=MagickTrue; while (GetPreviousImageInList(image) != (Image *) NULL) { image_count++; if (image_count > 10*mng_info->image_found) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),"" No beginning""); (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,""Linked list is corrupted, beginning of list not found"", ""`%s'"",image_info->filename); return(DestroyImageList(image)); } image=GetPreviousImageInList(image); if (GetNextImageInList(image) == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),"" Corrupt list""); (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,""Linked list is corrupted; next_image is NULL"",""`%s'"", image_info->filename); } } if (mng_info->ticks_per_second && mng_info->image_found > 1 && GetNextImageInList(image) == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" First image null""); (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,""image->next for first image is NULL but shouldn't be."", ""`%s'"",image_info->filename); } if (mng_info->image_found == 0) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" No visible images found.""); (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,""No visible images in file"",""`%s'"",image_info->filename); return(DestroyImageList(image)); } if (mng_info->ticks_per_second) final_delay=1UL*MagickMax(image->ticks_per_second,1L)* final_delay/mng_info->ticks_per_second; else image->start_loop=MagickTrue; /* Find final nonzero image delay */ final_image_delay=0; while (GetNextImageInList(image) != (Image *) NULL) { if (image->delay) final_image_delay=image->delay; image=GetNextImageInList(image); } if (final_delay < final_image_delay) final_delay=final_image_delay; image->delay=final_delay; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" image->delay=%.20g, final_delay=%.20g"",(double) image->delay, (double) final_delay); if (logging != MagickFalse) { int scene; scene=0; image=GetFirstImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" Before coalesce:""); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" scene 0 delay=%.20g"",(double) image->delay); while (GetNextImageInList(image) != (Image *) NULL) { image=GetNextImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" scene %.20g delay=%.20g"",(double) scene++,(double) image->delay); } } image=GetFirstImageInList(image); #ifdef MNG_COALESCE_LAYERS if (insert_layers) { Image *next_image, *next; size_t scene; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),"" Coalesce Images""); scene=image->scene; next_image=CoalesceImages(image,&image->exception); if (next_image == (Image *) NULL) ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); image=DestroyImageList(image); image=next_image; for (next=image; next != (Image *) NULL; next=next_image) { next->page.width=mng_info->mng_width; next->page.height=mng_info->mng_height; next->page.x=0; next->page.y=0; next->scene=scene++; next_image=GetNextImageInList(next); if (next_image == (Image *) NULL) break; if (next->delay == 0) { scene--; next_image->previous=GetPreviousImageInList(next); if (GetPreviousImageInList(next) == (Image *) NULL) image=next_image; else next->previous->next=next_image; next=DestroyImage(next); } } } #endif while (GetNextImageInList(image) != (Image *) NULL) image=GetNextImageInList(image); image->dispose=BackgroundDispose; if (logging != MagickFalse) { int scene; scene=0; image=GetFirstImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" After coalesce:""); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" scene 0 delay=%.20g dispose=%.20g"",(double) image->delay, (double) image->dispose); while (GetNextImageInList(image) != (Image *) NULL) { image=GetNextImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" scene %.20g delay=%.20g dispose=%.20g"",(double) scene++, (double) image->delay,(double) image->dispose); } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" exit ReadOneJNGImage();""); return(image); }","static Image *ReadOneMNGImage(MngInfo* mng_info, const ImageInfo *image_info, ExceptionInfo *exception) { char page_geometry[MaxTextExtent]; Image *image; MagickBooleanType logging; volatile int first_mng_object, object_id, term_chunk_found, skip_to_iend; volatile ssize_t image_count=0; MagickBooleanType status; MagickOffsetType offset; MngBox default_fb, fb, previous_fb; #if defined(MNG_INSERT_LAYERS) PixelPacket mng_background_color; #endif register unsigned char *p; register ssize_t i; size_t count; ssize_t loop_level; volatile short skipping_loop; #if defined(MNG_INSERT_LAYERS) unsigned int mandatory_back=0; #endif volatile unsigned int #ifdef MNG_OBJECT_BUFFERS mng_background_object=0, #endif mng_type=0; /* 0: PNG or JNG; 1: MNG; 2: MNG-LC; 3: MNG-VLC */ size_t default_frame_timeout, frame_timeout, #if defined(MNG_INSERT_LAYERS) image_height, image_width, #endif length; /* These delays are all measured in image ticks_per_second, * not in MNG ticks_per_second */ volatile size_t default_frame_delay, final_delay, final_image_delay, frame_delay, #if defined(MNG_INSERT_LAYERS) insert_layers, #endif mng_iterations=1, simplicity=0, subframe_height=0, subframe_width=0; previous_fb.top=0; previous_fb.bottom=0; previous_fb.left=0; previous_fb.right=0; default_fb.top=0; default_fb.bottom=0; default_fb.left=0; default_fb.right=0; logging=LogMagickEvent(CoderEvent,GetMagickModule(), "" Enter ReadOneMNGImage()""); image=mng_info->image; if (LocaleCompare(image_info->magick,""MNG"") == 0) { char magic_number[MaxTextExtent]; /* Verify MNG signature. */ count=(size_t) ReadBlob(image,8,(unsigned char *) magic_number); if (memcmp(magic_number,""\212MNG\r\n\032\n"",8) != 0) ThrowReaderException(CorruptImageError,""ImproperImageHeader""); /* Initialize some nonzero members of the MngInfo structure. */ for (i=0; i < MNG_MAX_OBJECTS; i++) { mng_info->object_clip[i].right=(ssize_t) PNG_UINT_31_MAX; mng_info->object_clip[i].bottom=(ssize_t) PNG_UINT_31_MAX; } mng_info->exists[0]=MagickTrue; } skipping_loop=(-1); first_mng_object=MagickTrue; mng_type=0; #if defined(MNG_INSERT_LAYERS) insert_layers=MagickFalse; /* should be False when converting or mogrifying */ #endif default_frame_delay=0; default_frame_timeout=0; frame_delay=0; final_delay=1; mng_info->ticks_per_second=1UL*image->ticks_per_second; object_id=0; skip_to_iend=MagickFalse; term_chunk_found=MagickFalse; mng_info->framing_mode=1; #if defined(MNG_INSERT_LAYERS) mandatory_back=MagickFalse; #endif #if defined(MNG_INSERT_LAYERS) mng_background_color=image->background_color; #endif default_fb=mng_info->frame; previous_fb=mng_info->frame; do { char type[MaxTextExtent]; if (LocaleCompare(image_info->magick,""MNG"") == 0) { unsigned char *chunk; /* Read a new chunk. */ type[0]='\0'; (void) ConcatenateMagickString(type,""errr"",MaxTextExtent); length=ReadBlobMSBLong(image); count=(size_t) ReadBlob(image,4,(unsigned char *) type); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" Reading MNG chunk type %c%c%c%c, length: %.20g"", type[0],type[1],type[2],type[3],(double) length); if (length > PNG_UINT_31_MAX) { status=MagickFalse; break; } if (count == 0) ThrowReaderException(CorruptImageError,""CorruptImage""); p=NULL; chunk=(unsigned char *) NULL; if (length != 0) { chunk=(unsigned char *) AcquireQuantumMemory(length+ MagickPathExtent,sizeof(*chunk)); if (chunk == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); for (i=0; i < (ssize_t) length; i++) { int c; c=ReadBlobByte(image); if (c == EOF) break; chunk[i]=(unsigned char) c; } p=chunk; } (void) ReadBlobMSBLong(image); /* read crc word */ #if !defined(JNG_SUPPORTED) if (memcmp(type,mng_JHDR,4) == 0) { skip_to_iend=MagickTrue; if (mng_info->jhdr_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,""JNGCompressNotSupported"",""`%s'"",image->filename); mng_info->jhdr_warning++; } #endif if (memcmp(type,mng_DHDR,4) == 0) { skip_to_iend=MagickTrue; if (mng_info->dhdr_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,""DeltaPNGNotSupported"",""`%s'"",image->filename); mng_info->dhdr_warning++; } if (memcmp(type,mng_MEND,4) == 0) break; if (skip_to_iend) { if (memcmp(type,mng_IEND,4) == 0) skip_to_iend=MagickFalse; if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" Skip to IEND.""); continue; } if (memcmp(type,mng_MHDR,4) == 0) { if (length != 28) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(CorruptImageError,""CorruptImage""); } mng_info->mng_width=(size_t) ((p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3]); mng_info->mng_height=(size_t) ((p[4] << 24) | (p[5] << 16) | (p[6] << 8) | p[7]); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" MNG width: %.20g"",(double) mng_info->mng_width); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" MNG height: %.20g"",(double) mng_info->mng_height); } p+=8; mng_info->ticks_per_second=(size_t) mng_get_long(p); if (mng_info->ticks_per_second == 0) default_frame_delay=0; else default_frame_delay=1UL*image->ticks_per_second/ mng_info->ticks_per_second; frame_delay=default_frame_delay; simplicity=0; /* Skip nominal layer count, frame count, and play time */ p+=16; simplicity=(size_t) mng_get_long(p); mng_type=1; /* Full MNG */ if ((simplicity != 0) && ((simplicity | 11) == 11)) mng_type=2; /* LC */ if ((simplicity != 0) && ((simplicity | 9) == 9)) mng_type=3; /* VLC */ #if defined(MNG_INSERT_LAYERS) if (mng_type != 3) insert_layers=MagickTrue; #endif if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); mng_info->image=image; } if ((mng_info->mng_width > 65535L) || (mng_info->mng_height > 65535L)) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(ImageError,""WidthOrHeightExceedsLimit""); } (void) FormatLocaleString(page_geometry,MaxTextExtent, ""%.20gx%.20g+0+0"",(double) mng_info->mng_width,(double) mng_info->mng_height); mng_info->frame.left=0; mng_info->frame.right=(ssize_t) mng_info->mng_width; mng_info->frame.top=0; mng_info->frame.bottom=(ssize_t) mng_info->mng_height; mng_info->clip=default_fb=previous_fb=mng_info->frame; for (i=0; i < MNG_MAX_OBJECTS; i++) mng_info->object_clip[i]=mng_info->frame; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_TERM,4) == 0) { int repeat=0; if (length != 0) repeat=p[0]; if (repeat == 3 && length > 8) { final_delay=(png_uint_32) mng_get_long(&p[2]); mng_iterations=(png_uint_32) mng_get_long(&p[6]); if (mng_iterations == PNG_UINT_31_MAX) mng_iterations=0; image->iterations=mng_iterations; term_chunk_found=MagickTrue; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" repeat=%d, final_delay=%.20g, iterations=%.20g"", repeat,(double) final_delay, (double) image->iterations); } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_DEFI,4) == 0) { if (mng_type == 3) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,""DEFI chunk found in MNG-VLC datastream"",""`%s'"", image->filename); if (length > 1) { object_id=(p[0] << 8) | p[1]; if (mng_type == 2 && object_id != 0) (void) ThrowMagickException(&image->exception, GetMagickModule(), CoderError,""Nonzero object_id in MNG-LC datastream"", ""`%s'"", image->filename); if (object_id > MNG_MAX_OBJECTS) { /* Instead of using a warning we should allocate a larger MngInfo structure and continue. */ (void) ThrowMagickException(&image->exception, GetMagickModule(), CoderError, ""object id too large"",""`%s'"",image->filename); object_id=MNG_MAX_OBJECTS; } if (mng_info->exists[object_id]) if (mng_info->frozen[object_id]) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); (void) ThrowMagickException(&image->exception, GetMagickModule(),CoderError, ""DEFI cannot redefine a frozen MNG object"",""`%s'"", image->filename); continue; } mng_info->exists[object_id]=MagickTrue; if (length > 2) mng_info->invisible[object_id]=p[2]; /* Extract object offset info. */ if (length > 11) { mng_info->x_off[object_id]=(ssize_t) ((p[4] << 24) | (p[5] << 16) | (p[6] << 8) | p[7]); mng_info->y_off[object_id]=(ssize_t) ((p[8] << 24) | (p[9] << 16) | (p[10] << 8) | p[11]); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" x_off[%d]: %.20g, y_off[%d]: %.20g"", object_id,(double) mng_info->x_off[object_id], object_id,(double) mng_info->y_off[object_id]); } } /* Extract object clipping info. */ if (length > 27) mng_info->object_clip[object_id]= mng_read_box(mng_info->frame,0, &p[12]); } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_bKGD,4) == 0) { mng_info->have_global_bkgd=MagickFalse; if (length > 5) { mng_info->mng_global_bkgd.red= ScaleShortToQuantum((unsigned short) ((p[0] << 8) | p[1])); mng_info->mng_global_bkgd.green= ScaleShortToQuantum((unsigned short) ((p[2] << 8) | p[3])); mng_info->mng_global_bkgd.blue= ScaleShortToQuantum((unsigned short) ((p[4] << 8) | p[5])); mng_info->have_global_bkgd=MagickTrue; } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_BACK,4) == 0) { #if defined(MNG_INSERT_LAYERS) if (length > 6) mandatory_back=p[6]; else mandatory_back=0; if (mandatory_back && length > 5) { mng_background_color.red= ScaleShortToQuantum((unsigned short) ((p[0] << 8) | p[1])); mng_background_color.green= ScaleShortToQuantum((unsigned short) ((p[2] << 8) | p[3])); mng_background_color.blue= ScaleShortToQuantum((unsigned short) ((p[4] << 8) | p[5])); mng_background_color.opacity=OpaqueOpacity; } #ifdef MNG_OBJECT_BUFFERS if (length > 8) mng_background_object=(p[7] << 8) | p[8]; #endif #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_PLTE,4) == 0) { /* Read global PLTE. */ if (length && (length < 769)) { if (mng_info->global_plte == (png_colorp) NULL) mng_info->global_plte=(png_colorp) AcquireQuantumMemory(256, sizeof(*mng_info->global_plte)); for (i=0; i < (ssize_t) (length/3); i++) { mng_info->global_plte[i].red=p[3*i]; mng_info->global_plte[i].green=p[3*i+1]; mng_info->global_plte[i].blue=p[3*i+2]; } mng_info->global_plte_length=(unsigned int) (length/3); } #ifdef MNG_LOOSE for ( ; i < 256; i++) { mng_info->global_plte[i].red=i; mng_info->global_plte[i].green=i; mng_info->global_plte[i].blue=i; } if (length != 0) mng_info->global_plte_length=256; #endif else mng_info->global_plte_length=0; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_tRNS,4) == 0) { /* read global tRNS */ if (length > 0 && length < 257) for (i=0; i < (ssize_t) length; i++) mng_info->global_trns[i]=p[i]; #ifdef MNG_LOOSE for ( ; i < 256; i++) mng_info->global_trns[i]=255; #endif mng_info->global_trns_length=(unsigned int) length; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_gAMA,4) == 0) { if (length == 4) { ssize_t igamma; igamma=mng_get_long(p); mng_info->global_gamma=((float) igamma)*0.00001; mng_info->have_global_gama=MagickTrue; } else mng_info->have_global_gama=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_cHRM,4) == 0) { /* Read global cHRM */ if (length == 32) { mng_info->global_chrm.white_point.x=0.00001*mng_get_long(p); mng_info->global_chrm.white_point.y=0.00001*mng_get_long(&p[4]); mng_info->global_chrm.red_primary.x=0.00001*mng_get_long(&p[8]); mng_info->global_chrm.red_primary.y=0.00001* mng_get_long(&p[12]); mng_info->global_chrm.green_primary.x=0.00001* mng_get_long(&p[16]); mng_info->global_chrm.green_primary.y=0.00001* mng_get_long(&p[20]); mng_info->global_chrm.blue_primary.x=0.00001* mng_get_long(&p[24]); mng_info->global_chrm.blue_primary.y=0.00001* mng_get_long(&p[28]); mng_info->have_global_chrm=MagickTrue; } else mng_info->have_global_chrm=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_sRGB,4) == 0) { /* Read global sRGB. */ if (length != 0) { mng_info->global_srgb_intent= Magick_RenderingIntent_from_PNG_RenderingIntent(p[0]); mng_info->have_global_srgb=MagickTrue; } else mng_info->have_global_srgb=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_iCCP,4) == 0) { /* To do: */ /* Read global iCCP. */ if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_FRAM,4) == 0) { if (mng_type == 3) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,""FRAM chunk found in MNG-VLC datastream"",""`%s'"", image->filename); if ((mng_info->framing_mode == 2) || (mng_info->framing_mode == 4)) image->delay=frame_delay; frame_delay=default_frame_delay; frame_timeout=default_frame_timeout; fb=default_fb; if (length > 0) if (p[0]) mng_info->framing_mode=p[0]; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" Framing_mode=%d"",mng_info->framing_mode); if (length > 6) { /* Note the delay and frame clipping boundaries. */ p++; /* framing mode */ while (*p && ((p-chunk) < (ssize_t) length)) p++; /* frame name */ p++; /* frame name terminator */ if ((p-chunk) < (ssize_t) (length-4)) { int change_delay, change_timeout, change_clipping; change_delay=(*p++); change_timeout=(*p++); change_clipping=(*p++); p++; /* change_sync */ if (change_delay && (p-chunk) < (ssize_t) (length-4)) { frame_delay=1UL*image->ticks_per_second* mng_get_long(p); if (mng_info->ticks_per_second != 0) frame_delay/=mng_info->ticks_per_second; else frame_delay=PNG_UINT_31_MAX; if (change_delay == 2) default_frame_delay=frame_delay; p+=4; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" Framing_delay=%.20g"",(double) frame_delay); } if (change_timeout && (p-chunk) < (ssize_t) (length-4)) { frame_timeout=1UL*image->ticks_per_second* mng_get_long(p); if (mng_info->ticks_per_second != 0) frame_timeout/=mng_info->ticks_per_second; else frame_timeout=PNG_UINT_31_MAX; if (change_timeout == 2) default_frame_timeout=frame_timeout; p+=4; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" Framing_timeout=%.20g"",(double) frame_timeout); } if (change_clipping && (p-chunk) < (ssize_t) (length-17)) { fb=mng_read_box(previous_fb,(char) p[0],&p[1]); p+=17; previous_fb=fb; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" Frame_clip: L=%.20g R=%.20g T=%.20g B=%.20g"", (double) fb.left,(double) fb.right,(double) fb.top, (double) fb.bottom); if (change_clipping == 2) default_fb=fb; } } } mng_info->clip=fb; mng_info->clip=mng_minimum_box(fb,mng_info->frame); subframe_width=(size_t) (mng_info->clip.right -mng_info->clip.left); subframe_height=(size_t) (mng_info->clip.bottom -mng_info->clip.top); /* Insert a background layer behind the frame if framing_mode is 4. */ #if defined(MNG_INSERT_LAYERS) if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" subframe_width=%.20g, subframe_height=%.20g"",(double) subframe_width,(double) subframe_height); if (insert_layers && (mng_info->framing_mode == 4) && (subframe_width) && (subframe_height)) { /* Allocate next image structure. */ if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; if (term_chunk_found) { image->start_loop=MagickTrue; image->iterations=mng_iterations; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; image->columns=subframe_width; image->rows=subframe_height; image->page.width=subframe_width; image->page.height=subframe_height; image->page.x=mng_info->clip.left; image->page.y=mng_info->clip.top; image->background_color=mng_background_color; image->matte=MagickFalse; image->delay=0; (void) SetImageBackgroundColor(image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" Insert backgd layer, L=%.20g, R=%.20g T=%.20g, B=%.20g"", (double) mng_info->clip.left,(double) mng_info->clip.right, (double) mng_info->clip.top,(double) mng_info->clip.bottom); } #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_CLIP,4) == 0) { unsigned int first_object, last_object; /* Read CLIP. */ if (length > 3) { first_object=(p[0] << 8) | p[1]; last_object=(p[2] << 8) | p[3]; p+=4; for (i=(int) first_object; i <= (int) last_object; i++) { if (mng_info->exists[i] && !mng_info->frozen[i]) { MngBox box; box=mng_info->object_clip[i]; if ((p-chunk) < (ssize_t) (length-17)) mng_info->object_clip[i]= mng_read_box(box,(char) p[0],&p[1]); } } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_SAVE,4) == 0) { for (i=1; i < MNG_MAX_OBJECTS; i++) if (mng_info->exists[i]) { mng_info->frozen[i]=MagickTrue; #ifdef MNG_OBJECT_BUFFERS if (mng_info->ob[i] != (MngBuffer *) NULL) mng_info->ob[i]->frozen=MagickTrue; #endif } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if ((memcmp(type,mng_DISC,4) == 0) || (memcmp(type,mng_SEEK,4) == 0)) { /* Read DISC or SEEK. */ if ((length == 0) || !memcmp(type,mng_SEEK,4)) { for (i=1; i < MNG_MAX_OBJECTS; i++) MngInfoDiscardObject(mng_info,i); } else { register ssize_t j; for (j=1; j < (ssize_t) length; j+=2) { i=p[j-1] << 8 | p[j]; MngInfoDiscardObject(mng_info,i); } } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_MOVE,4) == 0) { size_t first_object, last_object; /* read MOVE */ if (length > 3) { first_object=(p[0] << 8) | p[1]; last_object=(p[2] << 8) | p[3]; p+=4; for (i=(ssize_t) first_object; i <= (ssize_t) last_object; i++) { if ((i < 0) || (i >= MNG_MAX_OBJECTS)) continue; if (mng_info->exists[i] && !mng_info->frozen[i] && (p-chunk) < (ssize_t) (length-8)) { MngPair new_pair; MngPair old_pair; old_pair.a=mng_info->x_off[i]; old_pair.b=mng_info->y_off[i]; new_pair=mng_read_pair(old_pair,(int) p[0],&p[1]); mng_info->x_off[i]=new_pair.a; mng_info->y_off[i]=new_pair.b; } } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_LOOP,4) == 0) { ssize_t loop_iters=1; if (length > 4) { loop_level=chunk[0]; mng_info->loop_active[loop_level]=1; /* mark loop active */ /* Record starting point. */ loop_iters=mng_get_long(&chunk[1]); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" LOOP level %.20g has %.20g iterations "", (double) loop_level, (double) loop_iters); if (loop_iters == 0) skipping_loop=loop_level; else { mng_info->loop_jump[loop_level]=TellBlob(image); mng_info->loop_count[loop_level]=loop_iters; } mng_info->loop_iteration[loop_level]=0; } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_ENDL,4) == 0) { if (length > 0) { loop_level=chunk[0]; if (skipping_loop > 0) { if (skipping_loop == loop_level) { /* Found end of zero-iteration loop. */ skipping_loop=(-1); mng_info->loop_active[loop_level]=0; } } else { if (mng_info->loop_active[loop_level] == 1) { mng_info->loop_count[loop_level]--; mng_info->loop_iteration[loop_level]++; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" ENDL: LOOP level %.20g has %.20g remaining iters "", (double) loop_level,(double) mng_info->loop_count[loop_level]); if (mng_info->loop_count[loop_level] != 0) { offset=SeekBlob(image, mng_info->loop_jump[loop_level], SEEK_SET); if (offset < 0) { chunk=(unsigned char *) RelinquishMagickMemory( chunk); ThrowReaderException(CorruptImageError, ""ImproperImageHeader""); } } else { short last_level; /* Finished loop. */ mng_info->loop_active[loop_level]=0; last_level=(-1); for (i=0; i < loop_level; i++) if (mng_info->loop_active[i] == 1) last_level=(short) i; loop_level=last_level; } } } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_CLON,4) == 0) { if (mng_info->clon_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,""CLON is not implemented yet"",""`%s'"", image->filename); mng_info->clon_warning++; } if (memcmp(type,mng_MAGN,4) == 0) { png_uint_16 magn_first, magn_last, magn_mb, magn_ml, magn_mr, magn_mt, magn_mx, magn_my, magn_methx, magn_methy; if (length > 1) magn_first=(p[0] << 8) | p[1]; else magn_first=0; if (length > 3) magn_last=(p[2] << 8) | p[3]; else magn_last=magn_first; #ifndef MNG_OBJECT_BUFFERS if (magn_first || magn_last) if (mng_info->magn_warning == 0) { (void) ThrowMagickException(&image->exception, GetMagickModule(),CoderError, ""MAGN is not implemented yet for nonzero objects"", ""`%s'"",image->filename); mng_info->magn_warning++; } #endif if (length > 4) magn_methx=p[4]; else magn_methx=0; if (length > 6) magn_mx=(p[5] << 8) | p[6]; else magn_mx=1; if (magn_mx == 0) magn_mx=1; if (length > 8) magn_my=(p[7] << 8) | p[8]; else magn_my=magn_mx; if (magn_my == 0) magn_my=1; if (length > 10) magn_ml=(p[9] << 8) | p[10]; else magn_ml=magn_mx; if (magn_ml == 0) magn_ml=1; if (length > 12) magn_mr=(p[11] << 8) | p[12]; else magn_mr=magn_mx; if (magn_mr == 0) magn_mr=1; if (length > 14) magn_mt=(p[13] << 8) | p[14]; else magn_mt=magn_my; if (magn_mt == 0) magn_mt=1; if (length > 16) magn_mb=(p[15] << 8) | p[16]; else magn_mb=magn_my; if (magn_mb == 0) magn_mb=1; if (length > 17) magn_methy=p[17]; else magn_methy=magn_methx; if (magn_methx > 5 || magn_methy > 5) if (mng_info->magn_warning == 0) { (void) ThrowMagickException(&image->exception, GetMagickModule(),CoderError, ""Unknown MAGN method in MNG datastream"",""`%s'"", image->filename); mng_info->magn_warning++; } #ifdef MNG_OBJECT_BUFFERS /* Magnify existing objects in the range magn_first to magn_last */ #endif if (magn_first == 0 || magn_last == 0) { /* Save the magnification factors for object 0 */ mng_info->magn_mb=magn_mb; mng_info->magn_ml=magn_ml; mng_info->magn_mr=magn_mr; mng_info->magn_mt=magn_mt; mng_info->magn_mx=magn_mx; mng_info->magn_my=magn_my; mng_info->magn_methx=magn_methx; mng_info->magn_methy=magn_methy; } } if (memcmp(type,mng_PAST,4) == 0) { if (mng_info->past_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,""PAST is not implemented yet"",""`%s'"", image->filename); mng_info->past_warning++; } if (memcmp(type,mng_SHOW,4) == 0) { if (mng_info->show_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,""SHOW is not implemented yet"",""`%s'"", image->filename); mng_info->show_warning++; } if (memcmp(type,mng_sBIT,4) == 0) { if (length < 4) mng_info->have_global_sbit=MagickFalse; else { mng_info->global_sbit.gray=p[0]; mng_info->global_sbit.red=p[0]; mng_info->global_sbit.green=p[1]; mng_info->global_sbit.blue=p[2]; mng_info->global_sbit.alpha=p[3]; mng_info->have_global_sbit=MagickTrue; } } if (memcmp(type,mng_pHYs,4) == 0) { if (length > 8) { mng_info->global_x_pixels_per_unit= (size_t) mng_get_long(p); mng_info->global_y_pixels_per_unit= (size_t) mng_get_long(&p[4]); mng_info->global_phys_unit_type=p[8]; mng_info->have_global_phys=MagickTrue; } else mng_info->have_global_phys=MagickFalse; } if (memcmp(type,mng_pHYg,4) == 0) { if (mng_info->phyg_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,""pHYg is not implemented."",""`%s'"",image->filename); mng_info->phyg_warning++; } if (memcmp(type,mng_BASI,4) == 0) { skip_to_iend=MagickTrue; if (mng_info->basi_warning == 0) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,""BASI is not implemented yet"",""`%s'"", image->filename); mng_info->basi_warning++; #ifdef MNG_BASI_SUPPORTED if (length > 11) { basi_width=(size_t) ((p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3]); basi_height=(size_t) ((p[4] << 24) | (p[5] << 16) | (p[6] << 8) | p[7]); basi_color_type=p[8]; basi_compression_method=p[9]; basi_filter_type=p[10]; basi_interlace_method=p[11]; } if (length > 13) basi_red=(p[12] << 8) & p[13]; else basi_red=0; if (length > 15) basi_green=(p[14] << 8) & p[15]; else basi_green=0; if (length > 17) basi_blue=(p[16] << 8) & p[17]; else basi_blue=0; if (length > 19) basi_alpha=(p[18] << 8) & p[19]; else { if (basi_sample_depth == 16) basi_alpha=65535L; else basi_alpha=255; } if (length > 20) basi_viewable=p[20]; else basi_viewable=0; #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_IHDR,4) #if defined(JNG_SUPPORTED) && memcmp(type,mng_JHDR,4) #endif ) { /* Not an IHDR or JHDR chunk */ if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } /* Process IHDR */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" Processing %c%c%c%c chunk"",type[0],type[1],type[2],type[3]); mng_info->exists[object_id]=MagickTrue; mng_info->viewable[object_id]=MagickTrue; if (mng_info->invisible[object_id]) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" Skipping invisible object""); skip_to_iend=MagickTrue; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } #if defined(MNG_INSERT_LAYERS) if (length < 8) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(CorruptImageError,""ImproperImageHeader""); } image_width=(size_t) mng_get_long(p); image_height=(size_t) mng_get_long(&p[4]); #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); /* Insert a transparent background layer behind the entire animation if it is not full screen. */ #if defined(MNG_INSERT_LAYERS) if (insert_layers && mng_type && first_mng_object) { if ((mng_info->clip.left > 0) || (mng_info->clip.top > 0) || (image_width < mng_info->mng_width) || (mng_info->clip.right < (ssize_t) mng_info->mng_width) || (image_height < mng_info->mng_height) || (mng_info->clip.bottom < (ssize_t) mng_info->mng_height)) { if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; if (term_chunk_found) { image->start_loop=MagickTrue; image->iterations=mng_iterations; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; /* Make a background rectangle. */ image->delay=0; image->columns=mng_info->mng_width; image->rows=mng_info->mng_height; image->page.width=mng_info->mng_width; image->page.height=mng_info->mng_height; image->page.x=0; image->page.y=0; image->background_color=mng_background_color; (void) SetImageBackgroundColor(image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" Inserted transparent background layer, W=%.20g, H=%.20g"", (double) mng_info->mng_width,(double) mng_info->mng_height); } } /* Insert a background layer behind the upcoming image if framing_mode is 3, and we haven't already inserted one. */ if (insert_layers && (mng_info->framing_mode == 3) && (subframe_width) && (subframe_height) && (simplicity == 0 || (simplicity & 0x08))) { if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; if (term_chunk_found) { image->start_loop=MagickTrue; image->iterations=mng_iterations; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; image->delay=0; image->columns=subframe_width; image->rows=subframe_height; image->page.width=subframe_width; image->page.height=subframe_height; image->page.x=mng_info->clip.left; image->page.y=mng_info->clip.top; image->background_color=mng_background_color; image->matte=MagickFalse; (void) SetImageBackgroundColor(image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" Insert background layer, L=%.20g, R=%.20g T=%.20g, B=%.20g"", (double) mng_info->clip.left,(double) mng_info->clip.right, (double) mng_info->clip.top,(double) mng_info->clip.bottom); } #endif /* MNG_INSERT_LAYERS */ first_mng_object=MagickFalse; if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; if (term_chunk_found) { image->start_loop=MagickTrue; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; if (mng_info->framing_mode == 1 || mng_info->framing_mode == 3) { image->delay=frame_delay; frame_delay=default_frame_delay; } else image->delay=0; image->page.width=mng_info->mng_width; image->page.height=mng_info->mng_height; image->page.x=mng_info->x_off[object_id]; image->page.y=mng_info->y_off[object_id]; image->iterations=mng_iterations; /* Seek back to the beginning of the IHDR or JHDR chunk's length field. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" Seeking back to beginning of %c%c%c%c chunk"",type[0],type[1], type[2],type[3]); offset=SeekBlob(image,-((ssize_t) length+12),SEEK_CUR); if (offset < 0) ThrowReaderException(CorruptImageError,""ImproperImageHeader""); } mng_info->image=image; mng_info->mng_type=mng_type; mng_info->object_id=object_id; if (memcmp(type,mng_IHDR,4) == 0) image=ReadOnePNGImage(mng_info,image_info,exception); #if defined(JNG_SUPPORTED) else image=ReadOneJNGImage(mng_info,image_info,exception); #endif if (image == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), ""exit ReadJNGImage() with error""); return((Image *) NULL); } if (image->columns == 0 || image->rows == 0) { (void) CloseBlob(image); return(DestroyImageList(image)); } mng_info->image=image; if (mng_type) { MngBox crop_box; if (mng_info->magn_methx || mng_info->magn_methy) { png_uint_32 magnified_height, magnified_width; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" Processing MNG MAGN chunk""); if (mng_info->magn_methx == 1) { magnified_width=mng_info->magn_ml; if (image->columns > 1) magnified_width += mng_info->magn_mr; if (image->columns > 2) magnified_width += (png_uint_32) ((image->columns-2)*(mng_info->magn_mx)); } else { magnified_width=(png_uint_32) image->columns; if (image->columns > 1) magnified_width += mng_info->magn_ml-1; if (image->columns > 2) magnified_width += mng_info->magn_mr-1; if (image->columns > 3) magnified_width += (png_uint_32) ((image->columns-3)*(mng_info->magn_mx-1)); } if (mng_info->magn_methy == 1) { magnified_height=mng_info->magn_mt; if (image->rows > 1) magnified_height += mng_info->magn_mb; if (image->rows > 2) magnified_height += (png_uint_32) ((image->rows-2)*(mng_info->magn_my)); } else { magnified_height=(png_uint_32) image->rows; if (image->rows > 1) magnified_height += mng_info->magn_mt-1; if (image->rows > 2) magnified_height += mng_info->magn_mb-1; if (image->rows > 3) magnified_height += (png_uint_32) ((image->rows-3)*(mng_info->magn_my-1)); } if (magnified_height > image->rows || magnified_width > image->columns) { Image *large_image; int yy; ssize_t m, y; register ssize_t x; register PixelPacket *n, *q; PixelPacket *next, *prev; png_uint_16 magn_methx, magn_methy; /* Allocate next image structure. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" Allocate magnified image""); AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); large_image=SyncNextImageInList(image); large_image->columns=magnified_width; large_image->rows=magnified_height; magn_methx=mng_info->magn_methx; magn_methy=mng_info->magn_methy; #if (MAGICKCORE_QUANTUM_DEPTH > 16) #define QM unsigned short if (magn_methx != 1 || magn_methy != 1) { /* Scale pixels to unsigned shorts to prevent overflow of intermediate values of interpolations */ for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1, exception); for (x=(ssize_t) image->columns-1; x >= 0; x--) { SetPixelRed(q,ScaleQuantumToShort( GetPixelRed(q))); SetPixelGreen(q,ScaleQuantumToShort( GetPixelGreen(q))); SetPixelBlue(q,ScaleQuantumToShort( GetPixelBlue(q))); SetPixelOpacity(q,ScaleQuantumToShort( GetPixelOpacity(q))); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } #else #define QM Quantum #endif if (image->matte != MagickFalse) (void) SetImageBackgroundColor(large_image); else { large_image->background_color.opacity=OpaqueOpacity; (void) SetImageBackgroundColor(large_image); if (magn_methx == 4) magn_methx=2; if (magn_methx == 5) magn_methx=3; if (magn_methy == 4) magn_methy=2; if (magn_methy == 5) magn_methy=3; } /* magnify the rows into the right side of the large image */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" Magnify the rows to %.20g"",(double) large_image->rows); m=(ssize_t) mng_info->magn_mt; yy=0; length=(size_t) image->columns; next=(PixelPacket *) AcquireQuantumMemory(length,sizeof(*next)); prev=(PixelPacket *) AcquireQuantumMemory(length,sizeof(*prev)); if ((prev == (PixelPacket *) NULL) || (next == (PixelPacket *) NULL)) { image=DestroyImageList(image); ThrowReaderException(ResourceLimitError, ""MemoryAllocationFailed""); } n=GetAuthenticPixels(image,0,0,image->columns,1,exception); (void) CopyMagickMemory(next,n,length); for (y=0; y < (ssize_t) image->rows; y++) { if (y == 0) m=(ssize_t) mng_info->magn_mt; else if (magn_methy > 1 && y == (ssize_t) image->rows-2) m=(ssize_t) mng_info->magn_mb; else if (magn_methy <= 1 && y == (ssize_t) image->rows-1) m=(ssize_t) mng_info->magn_mb; else if (magn_methy > 1 && y == (ssize_t) image->rows-1) m=1; else m=(ssize_t) mng_info->magn_my; n=prev; prev=next; next=n; if (y < (ssize_t) image->rows-1) { n=GetAuthenticPixels(image,0,y+1,image->columns,1, exception); (void) CopyMagickMemory(next,n,length); } for (i=0; i < m; i++, yy++) { register PixelPacket *pixels; assert(yy < (ssize_t) large_image->rows); pixels=prev; n=next; q=GetAuthenticPixels(large_image,0,yy,large_image->columns, 1,exception); q+=(large_image->columns-image->columns); for (x=(ssize_t) image->columns-1; x >= 0; x--) { /* To do: get color as function of indexes[x] */ /* if (image->storage_class == PseudoClass) { } */ if (magn_methy <= 1) { /* replicate previous */ SetPixelRGBO(q,(pixels)); } else if (magn_methy == 2 || magn_methy == 4) { if (i == 0) { SetPixelRGBO(q,(pixels)); } else { /* Interpolate */ SetPixelRed(q, ((QM) (((ssize_t) (2*i*(GetPixelRed(n) -GetPixelRed(pixels)+m))/ ((ssize_t) (m*2)) +GetPixelRed(pixels))))); SetPixelGreen(q, ((QM) (((ssize_t) (2*i*(GetPixelGreen(n) -GetPixelGreen(pixels)+m))/ ((ssize_t) (m*2)) +GetPixelGreen(pixels))))); SetPixelBlue(q, ((QM) (((ssize_t) (2*i*(GetPixelBlue(n) -GetPixelBlue(pixels)+m))/ ((ssize_t) (m*2)) +GetPixelBlue(pixels))))); if (image->matte != MagickFalse) SetPixelOpacity(q, ((QM) (((ssize_t) (2*i*(GetPixelOpacity(n) -GetPixelOpacity(pixels)+m)) /((ssize_t) (m*2))+ GetPixelOpacity(pixels))))); } if (magn_methy == 4) { /* Replicate nearest */ if (i <= ((m+1) << 1)) SetPixelOpacity(q, (*pixels).opacity+0); else SetPixelOpacity(q, (*n).opacity+0); } } else /* if (magn_methy == 3 || magn_methy == 5) */ { /* Replicate nearest */ if (i <= ((m+1) << 1)) { SetPixelRGBO(q,(pixels)); } else { SetPixelRGBO(q,(n)); } if (magn_methy == 5) { SetPixelOpacity(q, (QM) (((ssize_t) (2*i* (GetPixelOpacity(n) -GetPixelOpacity(pixels)) +m))/((ssize_t) (m*2)) +GetPixelOpacity(pixels))); } } n++; q++; pixels++; } /* x */ if (SyncAuthenticPixels(large_image,exception) == 0) break; } /* i */ } /* y */ prev=(PixelPacket *) RelinquishMagickMemory(prev); next=(PixelPacket *) RelinquishMagickMemory(next); length=image->columns; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" Delete original image""); DeleteImageFromList(&image); image=large_image; mng_info->image=image; /* magnify the columns */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" Magnify the columns to %.20g"",(double) image->columns); for (y=0; y < (ssize_t) image->rows; y++) { register PixelPacket *pixels; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); pixels=q+(image->columns-length); n=pixels+1; for (x=(ssize_t) (image->columns-length); x < (ssize_t) image->columns; x++) { /* To do: Rewrite using Get/Set***PixelComponent() */ if (x == (ssize_t) (image->columns-length)) m=(ssize_t) mng_info->magn_ml; else if (magn_methx > 1 && x == (ssize_t) image->columns-2) m=(ssize_t) mng_info->magn_mr; else if (magn_methx <= 1 && x == (ssize_t) image->columns-1) m=(ssize_t) mng_info->magn_mr; else if (magn_methx > 1 && x == (ssize_t) image->columns-1) m=1; else m=(ssize_t) mng_info->magn_mx; for (i=0; i < m; i++) { if (magn_methx <= 1) { /* replicate previous */ SetPixelRGBO(q,(pixels)); } else if (magn_methx == 2 || magn_methx == 4) { if (i == 0) { SetPixelRGBO(q,(pixels)); } /* To do: Rewrite using Get/Set***PixelComponent() */ else { /* Interpolate */ SetPixelRed(q, (QM) ((2*i*( GetPixelRed(n) -GetPixelRed(pixels))+m) /((ssize_t) (m*2))+ GetPixelRed(pixels))); SetPixelGreen(q, (QM) ((2*i*( GetPixelGreen(n) -GetPixelGreen(pixels))+m) /((ssize_t) (m*2))+ GetPixelGreen(pixels))); SetPixelBlue(q, (QM) ((2*i*( GetPixelBlue(n) -GetPixelBlue(pixels))+m) /((ssize_t) (m*2))+ GetPixelBlue(pixels))); if (image->matte != MagickFalse) SetPixelOpacity(q, (QM) ((2*i*( GetPixelOpacity(n) -GetPixelOpacity(pixels))+m) /((ssize_t) (m*2))+ GetPixelOpacity(pixels))); } if (magn_methx == 4) { /* Replicate nearest */ if (i <= ((m+1) << 1)) { SetPixelOpacity(q, GetPixelOpacity(pixels)+0); } else { SetPixelOpacity(q, GetPixelOpacity(n)+0); } } } else /* if (magn_methx == 3 || magn_methx == 5) */ { /* Replicate nearest */ if (i <= ((m+1) << 1)) { SetPixelRGBO(q,(pixels)); } else { SetPixelRGBO(q,(n)); } if (magn_methx == 5) { /* Interpolate */ SetPixelOpacity(q, (QM) ((2*i*( GetPixelOpacity(n) -GetPixelOpacity(pixels))+m)/ ((ssize_t) (m*2)) +GetPixelOpacity(pixels))); } } q++; } n++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } #if (MAGICKCORE_QUANTUM_DEPTH > 16) if (magn_methx != 1 || magn_methy != 1) { /* Rescale pixels to Quantum */ for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); for (x=(ssize_t) image->columns-1; x >= 0; x--) { SetPixelRed(q,ScaleShortToQuantum( GetPixelRed(q))); SetPixelGreen(q,ScaleShortToQuantum( GetPixelGreen(q))); SetPixelBlue(q,ScaleShortToQuantum( GetPixelBlue(q))); SetPixelOpacity(q,ScaleShortToQuantum( GetPixelOpacity(q))); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } #endif if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" Finished MAGN processing""); } } /* Crop_box is with respect to the upper left corner of the MNG. */ crop_box.left=mng_info->image_box.left+mng_info->x_off[object_id]; crop_box.right=mng_info->image_box.right+mng_info->x_off[object_id]; crop_box.top=mng_info->image_box.top+mng_info->y_off[object_id]; crop_box.bottom=mng_info->image_box.bottom+mng_info->y_off[object_id]; crop_box=mng_minimum_box(crop_box,mng_info->clip); crop_box=mng_minimum_box(crop_box,mng_info->frame); crop_box=mng_minimum_box(crop_box,mng_info->object_clip[object_id]); if ((crop_box.left != (mng_info->image_box.left +mng_info->x_off[object_id])) || (crop_box.right != (mng_info->image_box.right +mng_info->x_off[object_id])) || (crop_box.top != (mng_info->image_box.top +mng_info->y_off[object_id])) || (crop_box.bottom != (mng_info->image_box.bottom +mng_info->y_off[object_id]))) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" Crop the PNG image""); if ((crop_box.left < crop_box.right) && (crop_box.top < crop_box.bottom)) { Image *im; RectangleInfo crop_info; /* Crop_info is with respect to the upper left corner of the image. */ crop_info.x=(crop_box.left-mng_info->x_off[object_id]); crop_info.y=(crop_box.top-mng_info->y_off[object_id]); crop_info.width=(size_t) (crop_box.right-crop_box.left); crop_info.height=(size_t) (crop_box.bottom-crop_box.top); image->page.width=image->columns; image->page.height=image->rows; image->page.x=0; image->page.y=0; im=CropImage(image,&crop_info,exception); if (im != (Image *) NULL) { image->columns=im->columns; image->rows=im->rows; im=DestroyImage(im); image->page.width=image->columns; image->page.height=image->rows; image->page.x=crop_box.left; image->page.y=crop_box.top; } } else { /* No pixels in crop area. The MNG spec still requires a layer, though, so make a single transparent pixel in the top left corner. */ image->columns=1; image->rows=1; image->colors=2; (void) SetImageBackgroundColor(image); image->page.width=1; image->page.height=1; image->page.x=0; image->page.y=0; } } #ifndef PNG_READ_EMPTY_PLTE_SUPPORTED image=mng_info->image; #endif } #if (MAGICKCORE_QUANTUM_DEPTH > 16) /* PNG does not handle depths greater than 16 so reduce it even * if lossy, and promote any depths > 8 to 16. */ if (image->depth > 16) image->depth=16; #endif #if (MAGICKCORE_QUANTUM_DEPTH > 8) if (image->depth > 8) { /* To do: fill low byte properly */ image->depth=16; } if (LosslessReduceDepthOK(image) != MagickFalse) image->depth = 8; #endif GetImageException(image,exception); if (image_info->number_scenes != 0) { if (mng_info->scenes_found > (ssize_t) (image_info->first_scene+image_info->number_scenes)) break; } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" Finished reading image datastream.""); } while (LocaleCompare(image_info->magick,""MNG"") == 0); (void) CloseBlob(image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" Finished reading all image datastreams.""); #if defined(MNG_INSERT_LAYERS) if (insert_layers && !mng_info->image_found && (mng_info->mng_width) && (mng_info->mng_height)) { /* Insert a background layer if nothing else was found. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" No images found. Inserting a background layer.""); if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" Allocation failed, returning NULL.""); return(DestroyImageList(image)); } image=SyncNextImageInList(image); } image->columns=mng_info->mng_width; image->rows=mng_info->mng_height; image->page.width=mng_info->mng_width; image->page.height=mng_info->mng_height; image->page.x=0; image->page.y=0; image->background_color=mng_background_color; image->matte=MagickFalse; if (image_info->ping == MagickFalse) (void) SetImageBackgroundColor(image); mng_info->image_found++; } #endif image->iterations=mng_iterations; if (mng_iterations == 1) image->start_loop=MagickTrue; while (GetPreviousImageInList(image) != (Image *) NULL) { image_count++; if (image_count > 10*mng_info->image_found) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),"" No beginning""); (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,""Linked list is corrupted, beginning of list not found"", ""`%s'"",image_info->filename); return(DestroyImageList(image)); } image=GetPreviousImageInList(image); if (GetNextImageInList(image) == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),"" Corrupt list""); (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,""Linked list is corrupted; next_image is NULL"",""`%s'"", image_info->filename); } } if (mng_info->ticks_per_second && mng_info->image_found > 1 && GetNextImageInList(image) == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" First image null""); (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,""image->next for first image is NULL but shouldn't be."", ""`%s'"",image_info->filename); } if (mng_info->image_found == 0) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" No visible images found.""); (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,""No visible images in file"",""`%s'"",image_info->filename); return(DestroyImageList(image)); } if (mng_info->ticks_per_second) final_delay=1UL*MagickMax(image->ticks_per_second,1L)* final_delay/mng_info->ticks_per_second; else image->start_loop=MagickTrue; /* Find final nonzero image delay */ final_image_delay=0; while (GetNextImageInList(image) != (Image *) NULL) { if (image->delay) final_image_delay=image->delay; image=GetNextImageInList(image); } if (final_delay < final_image_delay) final_delay=final_image_delay; image->delay=final_delay; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" image->delay=%.20g, final_delay=%.20g"",(double) image->delay, (double) final_delay); if (logging != MagickFalse) { int scene; scene=0; image=GetFirstImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" Before coalesce:""); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" scene 0 delay=%.20g"",(double) image->delay); while (GetNextImageInList(image) != (Image *) NULL) { image=GetNextImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" scene %.20g delay=%.20g"",(double) scene++,(double) image->delay); } } image=GetFirstImageInList(image); #ifdef MNG_COALESCE_LAYERS if (insert_layers) { Image *next_image, *next; size_t scene; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),"" Coalesce Images""); scene=image->scene; next_image=CoalesceImages(image,&image->exception); if (next_image == (Image *) NULL) ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); image=DestroyImageList(image); image=next_image; for (next=image; next != (Image *) NULL; next=next_image) { next->page.width=mng_info->mng_width; next->page.height=mng_info->mng_height; next->page.x=0; next->page.y=0; next->scene=scene++; next_image=GetNextImageInList(next); if (next_image == (Image *) NULL) break; if (next->delay == 0) { scene--; next_image->previous=GetPreviousImageInList(next); if (GetPreviousImageInList(next) == (Image *) NULL) image=next_image; else next->previous->next=next_image; next=DestroyImage(next); } } } #endif while (GetNextImageInList(image) != (Image *) NULL) image=GetNextImageInList(image); image->dispose=BackgroundDispose; if (logging != MagickFalse) { int scene; scene=0; image=GetFirstImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" After coalesce:""); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" scene 0 delay=%.20g dispose=%.20g"",(double) image->delay, (double) image->dispose); while (GetNextImageInList(image) != (Image *) NULL) { image=GetNextImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" scene %.20g delay=%.20g dispose=%.20g"",(double) scene++, (double) image->delay,(double) image->dispose); } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "" exit ReadOneJNGImage();""); return(image); }","{'deleted': [], 'added': [{'line_no': 885, 'char_start': 27353, 'char_end': 27408, 'line': ' if ((i < 0) || (i >= MNG_MAX_OBJECTS))\n'}, {'line_no': 886, 'char_start': 27408, 'char_end': 27436, 'line': ' continue;\n'}]}","{'deleted': [], 'added': [{'char_start': 27373, 'char_end': 27456, 'chars': '(i < 0) || (i >= MNG_MAX_OBJECTS))\n continue;\n if ('}]}",github.com/ImageMagick/ImageMagick/commit/78d4c5db50fbab0b4beb69c46c6167f2c6513dec,coders/png.c,cwe-125,17324 cwe-078,_cmd_to_dict," def _cmd_to_dict(self, cmd): arg_list = cmd.split() no_param_args = [ 'autodelete', 'autoexpand', 'bytes', 'compressed', 'force', 'nohdr', ] one_param_args = [ 'chapsecret', 'cleanrate', 'copyrate', 'delim', 'filtervalue', 'grainsize', 'hbawwpn', 'host', 'iogrp', 'iscsiname', 'mdiskgrp', 'name', 'rsize', 'scsi', 'size', 'source', 'target', 'unit', 'easytier', 'warning', 'wwpn', ] # Handle the special case of lsnode which is a two-word command # Use the one word version of the command internally if arg_list[0] in ('svcinfo', 'svctask'): if arg_list[1] == 'lsnode': if len(arg_list) > 4: # e.g. svcinfo lsnode -delim ! ret = {'cmd': 'lsnode', 'node_id': arg_list[-1]} else: ret = {'cmd': 'lsnodecanister'} else: ret = {'cmd': arg_list[1]} arg_list.pop(0) else: ret = {'cmd': arg_list[0]} skip = False for i in range(1, len(arg_list)): if skip: skip = False continue if arg_list[i][0] == '-': if arg_list[i][1:] in no_param_args: ret[arg_list[i][1:]] = True elif arg_list[i][1:] in one_param_args: ret[arg_list[i][1:]] = arg_list[i + 1] skip = True else: raise exception.InvalidInput( reason=_('unrecognized argument %s') % arg_list[i]) else: ret['obj'] = arg_list[i] return ret"," def _cmd_to_dict(self, arg_list): no_param_args = [ 'autodelete', 'autoexpand', 'bytes', 'compressed', 'force', 'nohdr', ] one_param_args = [ 'chapsecret', 'cleanrate', 'copyrate', 'delim', 'filtervalue', 'grainsize', 'hbawwpn', 'host', 'iogrp', 'iscsiname', 'mdiskgrp', 'name', 'rsize', 'scsi', 'size', 'source', 'target', 'unit', 'easytier', 'warning', 'wwpn', ] # Handle the special case of lsnode which is a two-word command # Use the one word version of the command internally if arg_list[0] in ('svcinfo', 'svctask'): if arg_list[1] == 'lsnode': if len(arg_list) > 4: # e.g. svcinfo lsnode -delim ! ret = {'cmd': 'lsnode', 'node_id': arg_list[-1]} else: ret = {'cmd': 'lsnodecanister'} else: ret = {'cmd': arg_list[1]} arg_list.pop(0) else: ret = {'cmd': arg_list[0]} skip = False for i in range(1, len(arg_list)): if skip: skip = False continue if arg_list[i][0] == '-': if arg_list[i][1:] in no_param_args: ret[arg_list[i][1:]] = True elif arg_list[i][1:] in one_param_args: ret[arg_list[i][1:]] = arg_list[i + 1] skip = True else: raise exception.InvalidInput( reason=_('unrecognized argument %s') % arg_list[i]) else: ret['obj'] = arg_list[i] return ret","{'deleted': [{'line_no': 1, 'char_start': 0, 'char_end': 33, 'line': ' def _cmd_to_dict(self, cmd):\n'}], 'added': [{'line_no': 1, 'char_start': 0, 'char_end': 38, 'line': ' def _cmd_to_dict(self, arg_list):\n'}]}","{'deleted': [{'char_start': 27, 'char_end': 41, 'chars': 'cmd):\n '}, {'char_start': 49, 'char_end': 62, 'chars': ' = cmd.split('}], 'added': [{'char_start': 36, 'char_end': 37, 'chars': ':'}]}",github.com/thatsdone/cinder/commit/f752302d181583a95cf44354aea607ce9d9283f4,cinder/tests/test_storwize_svc.py,cwe-078,459 cwe-787,adminchild,"void * adminchild(struct clientparam* param) { int i, res; char * buf; char username[256]; char *sb; char *req = NULL; struct printparam pp; int contentlen = 0; int isform = 0; pp.inbuf = 0; pp.cp = param; buf = myalloc(LINESIZE); if(!buf) {RETURN(555);} i = sockgetlinebuf(param, CLIENT, (unsigned char *)buf, LINESIZE - 1, '\n', conf.timeouts[STRING_S]); if(i<5 || ((buf[0]!='G' || buf[1]!='E' || buf[2]!='T' || buf[3]!=' ' || buf[4]!='/') && (buf[0]!='P' || buf[1]!='O' || buf[2]!='S' || buf[3]!='T' || buf[4]!=' ' || buf[5]!='/'))) { RETURN(701); } buf[i] = 0; sb = strchr(buf+5, ' '); if(!sb){ RETURN(702); } *sb = 0; req = mystrdup(buf + ((*buf == 'P')? 6 : 5)); while((i = sockgetlinebuf(param, CLIENT, (unsigned char *)buf, LINESIZE - 1, '\n', conf.timeouts[STRING_S])) > 2){ buf[i] = 0; if(i > 19 && (!strncasecmp(buf, ""authorization"", 13))){ sb = strchr(buf, ':'); if(!sb)continue; ++sb; while(isspace(*sb))sb++; if(!*sb || strncasecmp(sb, ""basic"", 5)){ continue; } sb+=5; while(isspace(*sb))sb++; i = de64((unsigned char *)sb, (unsigned char *)username, 255); if(i<=0)continue; username[i] = 0; sb = strchr((char *)username, ':'); if(sb){ *sb = 0; if(param->password)myfree(param->password); param->password = (unsigned char *)mystrdup(sb+1); } if(param->username) myfree(param->username); param->username = (unsigned char *)mystrdup(username); continue; } else if(i > 15 && (!strncasecmp(buf, ""content-length:"", 15))){ sb = buf + 15; while(isspace(*sb))sb++; contentlen = atoi(sb); } else if(i > 13 && (!strncasecmp(buf, ""content-type:"", 13))){ sb = buf + 13; while(isspace(*sb))sb++; if(!strncasecmp(sb, ""x-www-form-urlencoded"", 21)) isform = 1; } } param->operation = ADMIN; if(isform && contentlen) { printstr(&pp, ""HTTP/1.0 100 Continue\r\n\r\n""); stdpr(&pp, NULL, 0); } res = (*param->srv->authfunc)(param); if(res && res != 10) { printstr(&pp, authreq); RETURN(res); } if(param->srv->singlepacket || param->redirected){ if(*req == 'C') req[1] = 0; else *req = 0; } sprintf(buf, ok, conf.stringtable?(char *)conf.stringtable[2]:""3proxy"", conf.stringtable?(char *)conf.stringtable[2]:""3[APA3A] tiny proxy"", conf.stringtable?(char *)conf.stringtable[3]:""""); if(*req != 'S') printstr(&pp, buf); switch(*req){ case 'C': printstr(&pp, counters); { struct trafcount *cp; int num = 0; for(cp = conf.trafcounter; cp; cp = cp->next, num++){ int inbuf = 0; if(cp->ace && (param->srv->singlepacket || param->redirected)){ if(!ACLmatches(cp->ace, param))continue; } if(req[1] == 'S' && atoi(req+2) == num) cp->disabled=0; if(req[1] == 'D' && atoi(req+2) == num) cp->disabled=1; inbuf += sprintf(buf, """" ""%s%s"", (cp->comment)?cp->comment:"" "", (cp->disabled)?'S':'D', num, (cp->disabled)?""NO"":""YES"" ); if(!cp->ace || !cp->ace->users){ inbuf += sprintf(buf+inbuf, ""
ANY
""); } else { inbuf += printuserlist(buf+inbuf, LINESIZE-800, cp->ace->users, "",
\r\n""); } inbuf += sprintf(buf+inbuf, """"); if(!cp->ace || !cp->ace->src){ inbuf += sprintf(buf+inbuf, ""
ANY
""); } else { inbuf += printiplist(buf+inbuf, LINESIZE-512, cp->ace->src, "",
\r\n""); } inbuf += sprintf(buf+inbuf, """"); if(!cp->ace || !cp->ace->dst){ inbuf += sprintf(buf+inbuf, ""
ANY
""); } else { inbuf += printiplist(buf+inbuf, LINESIZE-512, cp->ace->dst, "",
\r\n""); } inbuf += sprintf(buf+inbuf, """"); if(!cp->ace || !cp->ace->ports){ inbuf += sprintf(buf+inbuf, ""
ANY
""); } else { inbuf += printportlist(buf+inbuf, LINESIZE-128, cp->ace->ports, "",
\r\n""); } if(cp->type == NONE) { inbuf += sprintf(buf+inbuf, ""exclude from limitation\r\n"" ); } else { inbuf += sprintf(buf+inbuf, ""%""PRINTF_INT64_MODIFIER""u"" ""MB%s"" ""%""PRINTF_INT64_MODIFIER""u"" ""%s"", cp->traflim64 / (1024 * 1024), rotations[cp->type], cp->traf64, cp->cleared?ctime(&cp->cleared):""never"" ); inbuf += sprintf(buf + inbuf, ""%s"" ""%i"" ""\r\n"", cp->updated?ctime(&cp->updated):""never"", cp->number ); } printstr(&pp, buf); } } printstr(&pp, counterstail); break; case 'R': conf.needreload = 1; printstr(&pp, ""

Reload scheduled

""); break; case 'S': { if(req[1] == 'X'){ printstr(&pp, style); break; } printstr(&pp, xml); printval(conf.services, TYPE_SERVER, 0, &pp); printstr(&pp, postxml); } break; case 'F': { FILE *fp; char buf[256]; fp = confopen(); if(!fp){ printstr(&pp, ""

Failed to open config file

""); break; } printstr(&pp, ""

Please be careful editing config file remotely

""); printstr(&pp, ""

""); break; } case 'U': { int l=0; int error = 0; if(!writable || fseek(writable, 0, 0)){ error = 1; } while((i = sockgetlinebuf(param, CLIENT, (unsigned char *)buf, LINESIZE - 1, '+', conf.timeouts[STRING_S])) > 0){ if(i > (contentlen - l)) i = (contentlen - l); buf[i] = 0; if(!l){ if(strncasecmp(buf, ""conffile="", 9)) error = 1; } if(!error){ decodeurl((unsigned char *)buf, 1); fprintf(writable, ""%s"", l? buf : buf + 9); } l += i; if(l >= contentlen) break; } if(writable && !error){ fflush(writable); #ifndef _WINCE ftruncate(fileno(writable), ftell(writable)); #endif } printstr(&pp, error? ""

Config file is not writable

Make sure you have \""writable\"" command in configuration file"": ""

Configuration updated

""); } break; default: printstr(&pp, (char *)conf.stringtable[WEBBANNERS]); break; } if(*req != 'S') printstr(&pp, tail); CLEANRET: printstr(&pp, NULL); if(buf) myfree(buf); (*param->srv->logfunc)(param, (unsigned char *)req); if(req)myfree(req); freeparam(param); return (NULL); }","void * adminchild(struct clientparam* param) { int i, res; char * buf; char username[256]; char *sb; char *req = NULL; struct printparam pp; unsigned contentlen = 0; int isform = 0; pp.inbuf = 0; pp.cp = param; buf = myalloc(LINESIZE); if(!buf) {RETURN(555);} i = sockgetlinebuf(param, CLIENT, (unsigned char *)buf, LINESIZE - 1, '\n', conf.timeouts[STRING_S]); if(i<5 || ((buf[0]!='G' || buf[1]!='E' || buf[2]!='T' || buf[3]!=' ' || buf[4]!='/') && (buf[0]!='P' || buf[1]!='O' || buf[2]!='S' || buf[3]!='T' || buf[4]!=' ' || buf[5]!='/'))) { RETURN(701); } buf[i] = 0; sb = strchr(buf+5, ' '); if(!sb){ RETURN(702); } *sb = 0; req = mystrdup(buf + ((*buf == 'P')? 6 : 5)); while((i = sockgetlinebuf(param, CLIENT, (unsigned char *)buf, LINESIZE - 1, '\n', conf.timeouts[STRING_S])) > 2){ buf[i] = 0; if(i > 19 && (!strncasecmp(buf, ""authorization"", 13))){ sb = strchr(buf, ':'); if(!sb)continue; ++sb; while(isspace(*sb))sb++; if(!*sb || strncasecmp(sb, ""basic"", 5)){ continue; } sb+=5; while(isspace(*sb))sb++; i = de64((unsigned char *)sb, (unsigned char *)username, 255); if(i<=0)continue; username[i] = 0; sb = strchr((char *)username, ':'); if(sb){ *sb = 0; if(param->password)myfree(param->password); param->password = (unsigned char *)mystrdup(sb+1); } if(param->username) myfree(param->username); param->username = (unsigned char *)mystrdup(username); continue; } else if(i > 15 && (!strncasecmp(buf, ""content-length:"", 15))){ sb = buf + 15; while(isspace(*sb))sb++; sscanf(sb, ""%u"", &contentlen); if(contentlen > LINESIZE*1024) contentlen = 0; } else if(i > 13 && (!strncasecmp(buf, ""content-type:"", 13))){ sb = buf + 13; while(isspace(*sb))sb++; if(!strncasecmp(sb, ""x-www-form-urlencoded"", 21)) isform = 1; } } param->operation = ADMIN; if(isform && contentlen) { printstr(&pp, ""HTTP/1.0 100 Continue\r\n\r\n""); stdpr(&pp, NULL, 0); } res = (*param->srv->authfunc)(param); if(res && res != 10) { printstr(&pp, authreq); RETURN(res); } if(param->srv->singlepacket || param->redirected){ if(*req == 'C') req[1] = 0; else *req = 0; } sprintf(buf, ok, conf.stringtable?(char *)conf.stringtable[2]:""3proxy"", conf.stringtable?(char *)conf.stringtable[2]:""3[APA3A] tiny proxy"", conf.stringtable?(char *)conf.stringtable[3]:""""); if(*req != 'S') printstr(&pp, buf); switch(*req){ case 'C': printstr(&pp, counters); { struct trafcount *cp; int num = 0; for(cp = conf.trafcounter; cp; cp = cp->next, num++){ int inbuf = 0; if(cp->ace && (param->srv->singlepacket || param->redirected)){ if(!ACLmatches(cp->ace, param))continue; } if(req[1] == 'S' && atoi(req+2) == num) cp->disabled=0; if(req[1] == 'D' && atoi(req+2) == num) cp->disabled=1; inbuf += sprintf(buf, """" ""%s%s"", (cp->comment)?cp->comment:"" "", (cp->disabled)?'S':'D', num, (cp->disabled)?""NO"":""YES"" ); if(!cp->ace || !cp->ace->users){ inbuf += sprintf(buf+inbuf, ""
ANY
""); } else { inbuf += printuserlist(buf+inbuf, LINESIZE-800, cp->ace->users, "",
\r\n""); } inbuf += sprintf(buf+inbuf, """"); if(!cp->ace || !cp->ace->src){ inbuf += sprintf(buf+inbuf, ""
ANY
""); } else { inbuf += printiplist(buf+inbuf, LINESIZE-512, cp->ace->src, "",
\r\n""); } inbuf += sprintf(buf+inbuf, """"); if(!cp->ace || !cp->ace->dst){ inbuf += sprintf(buf+inbuf, ""
ANY
""); } else { inbuf += printiplist(buf+inbuf, LINESIZE-512, cp->ace->dst, "",
\r\n""); } inbuf += sprintf(buf+inbuf, """"); if(!cp->ace || !cp->ace->ports){ inbuf += sprintf(buf+inbuf, ""
ANY
""); } else { inbuf += printportlist(buf+inbuf, LINESIZE-128, cp->ace->ports, "",
\r\n""); } if(cp->type == NONE) { inbuf += sprintf(buf+inbuf, ""exclude from limitation\r\n"" ); } else { inbuf += sprintf(buf+inbuf, ""%""PRINTF_INT64_MODIFIER""u"" ""MB%s"" ""%""PRINTF_INT64_MODIFIER""u"" ""%s"", cp->traflim64 / (1024 * 1024), rotations[cp->type], cp->traf64, cp->cleared?ctime(&cp->cleared):""never"" ); inbuf += sprintf(buf + inbuf, ""%s"" ""%i"" ""\r\n"", cp->updated?ctime(&cp->updated):""never"", cp->number ); } printstr(&pp, buf); } } printstr(&pp, counterstail); break; case 'R': conf.needreload = 1; printstr(&pp, ""

Reload scheduled

""); break; case 'S': { if(req[1] == 'X'){ printstr(&pp, style); break; } printstr(&pp, xml); printval(conf.services, TYPE_SERVER, 0, &pp); printstr(&pp, postxml); } break; case 'F': { FILE *fp; char buf[256]; fp = confopen(); if(!fp){ printstr(&pp, ""

Failed to open config file

""); break; } printstr(&pp, ""

Please be careful editing config file remotely

""); printstr(&pp, ""

""); break; } case 'U': { unsigned l=0; int error = 0; if(!writable || !contentlen || fseek(writable, 0, 0)){ error = 1; } while(l < contentlen && (i = sockgetlinebuf(param, CLIENT, (unsigned char *)buf, (contentlen - l) > LINESIZE - 1?LINESIZE - 1:contentlen - l, '+', conf.timeouts[STRING_S])) > 0){ if(i > (contentlen - l)) i = (contentlen - l); if(!l){ if(i<9 || strncasecmp(buf, ""conffile="", 9)) error = 1; } if(!error){ buf[i] = 0; decodeurl((unsigned char *)buf, 1); fprintf(writable, ""%s"", l? buf : buf + 9); } l += i; } if(writable && !error){ fflush(writable); #ifndef _WINCE ftruncate(fileno(writable), ftell(writable)); #endif } printstr(&pp, error? ""

Config file is not writable

Make sure you have \""writable\"" command in configuration file"": ""

Configuration updated

""); } break; default: printstr(&pp, (char *)conf.stringtable[WEBBANNERS]); break; } if(*req != 'S') printstr(&pp, tail); CLEANRET: printstr(&pp, NULL); if(buf) myfree(buf); (*param->srv->logfunc)(param, (unsigned char *)req); if(req)myfree(req); freeparam(param); return (NULL); }","{'deleted': [{'line_no': 8, 'char_start': 147, 'char_end': 168, 'line': ' int contentlen = 0;\n'}, {'line_no': 57, 'char_start': 1557, 'char_end': 1582, 'line': '\t\tcontentlen = atoi(sb);\n'}, {'line_no': 187, 'char_start': 5131, 'char_end': 5242, 'line': '\t\t\t\tprintstr(&pp, ""