instruction
stringclasses
1 value
input
stringlengths
90
139k
output
stringlengths
16
138k
__index_level_0__
int64
165k
175k
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: grub_ext2_iterate_dir (grub_fshelp_node_t dir, int (*hook) (const char *filename, enum grub_fshelp_filetype filetype, grub_fshelp_node_t node, void *closure), void *closure) { unsigned int fpos = 0; struct grub_fshelp_node *diro = (struct grub_fshelp_node *) dir; if (! diro->inode_read) { grub_ext2_read_inode (diro->data, diro->ino, &diro->inode); if (grub_errno) return 0; } /* Search the file. */ if (hook) while (fpos < grub_le_to_cpu32 (diro->inode.size)) { struct ext2_dirent dirent; grub_ext2_read_file (diro, NULL, NULL, 0, fpos, sizeof (dirent), (char *) &dirent); if (grub_errno) return 0; if (dirent.direntlen == 0) return 0; if (dirent.namelen != 0) { #ifndef _MSC_VER char filename[dirent.namelen + 1]; #else char * filename = grub_malloc (dirent.namelen + 1); #endif struct grub_fshelp_node *fdiro; enum grub_fshelp_filetype type = GRUB_FSHELP_UNKNOWN; grub_ext2_read_file (diro, 0, 0, 0, fpos + sizeof (struct ext2_dirent), dirent.namelen, filename); if (grub_errno) return 0; fdiro = grub_malloc (sizeof (struct grub_fshelp_node)); if (! fdiro) return 0; fdiro->data = diro->data; fdiro->ino = grub_le_to_cpu32 (dirent.inode); filename[dirent.namelen] = '\0'; if (dirent.filetype != FILETYPE_UNKNOWN) { fdiro->inode_read = 0; if (dirent.filetype == FILETYPE_DIRECTORY) type = GRUB_FSHELP_DIR; else if (dirent.filetype == FILETYPE_SYMLINK) type = GRUB_FSHELP_SYMLINK; else if (dirent.filetype == FILETYPE_REG) type = GRUB_FSHELP_REG; } else { /* The filetype can not be read from the dirent, read the inode to get more information. */ grub_ext2_read_inode (diro->data, grub_le_to_cpu32 (dirent.inode), &fdiro->inode); if (grub_errno) { grub_free (fdiro); return 0; } fdiro->inode_read = 1; if ((grub_le_to_cpu16 (fdiro->inode.mode) & FILETYPE_INO_MASK) == FILETYPE_INO_DIRECTORY) type = GRUB_FSHELP_DIR; else if ((grub_le_to_cpu16 (fdiro->inode.mode) & FILETYPE_INO_MASK) == FILETYPE_INO_SYMLINK) type = GRUB_FSHELP_SYMLINK; else if ((grub_le_to_cpu16 (fdiro->inode.mode) & FILETYPE_INO_MASK) == FILETYPE_INO_REG) type = GRUB_FSHELP_REG; } if (hook (filename, type, fdiro, closure)) return 1; } fpos += grub_le_to_cpu16 (dirent.direntlen); } return 0; } Commit Message: Fix ext2 buffer overflow in r2_sbu_grub_memmove CWE ID: CWE-787
grub_ext2_iterate_dir (grub_fshelp_node_t dir, int (*hook) (const char *filename, enum grub_fshelp_filetype filetype, grub_fshelp_node_t node, void *closure), void *closure) { unsigned int fpos = 0; struct grub_fshelp_node *diro = (struct grub_fshelp_node *) dir; if (! diro->inode_read) { grub_ext2_read_inode (diro->data, diro->ino, &diro->inode); if (grub_errno) return 0; } /* Search the file. */ if (hook) while (fpos < grub_le_to_cpu32 (diro->inode.size)) { struct ext2_dirent dirent; grub_ext2_read_file (diro, NULL, NULL, 0, fpos, sizeof (dirent), (char *) &dirent); if (grub_errno) return 0; if (dirent.direntlen == 0) return 0; if (dirent.namelen != 0) { char * filename = grub_malloc (dirent.namelen + 1); struct grub_fshelp_node *fdiro; enum grub_fshelp_filetype type = GRUB_FSHELP_UNKNOWN; if (!filename) { break; } grub_ext2_read_file (diro, 0, 0, 0, fpos + sizeof (struct ext2_dirent), dirent.namelen, filename); if (grub_errno) { free (filename); return 0; } fdiro = grub_malloc (sizeof (struct grub_fshelp_node)); if (! fdiro) { free (filename); return 0; } fdiro->data = diro->data; fdiro->ino = grub_le_to_cpu32 (dirent.inode); filename[dirent.namelen] = '\0'; if (dirent.filetype != FILETYPE_UNKNOWN) { fdiro->inode_read = 0; if (dirent.filetype == FILETYPE_DIRECTORY) type = GRUB_FSHELP_DIR; else if (dirent.filetype == FILETYPE_SYMLINK) type = GRUB_FSHELP_SYMLINK; else if (dirent.filetype == FILETYPE_REG) type = GRUB_FSHELP_REG; } else { /* The filetype can not be read from the dirent, read the inode to get more information. */ grub_ext2_read_inode (diro->data, grub_le_to_cpu32 (dirent.inode), &fdiro->inode); if (grub_errno) { free (filename); grub_free (fdiro); return 0; } fdiro->inode_read = 1; if ((grub_le_to_cpu16 (fdiro->inode.mode) & FILETYPE_INO_MASK) == FILETYPE_INO_DIRECTORY) type = GRUB_FSHELP_DIR; else if ((grub_le_to_cpu16 (fdiro->inode.mode) & FILETYPE_INO_MASK) == FILETYPE_INO_SYMLINK) type = GRUB_FSHELP_SYMLINK; else if ((grub_le_to_cpu16 (fdiro->inode.mode) & FILETYPE_INO_MASK) == FILETYPE_INO_REG) type = GRUB_FSHELP_REG; } if (hook (filename, type, fdiro, closure)) { free (filename); return 1; } free (filename); } fpos += grub_le_to_cpu16 (dirent.direntlen); } return 0; }
168,082
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: ZEND_METHOD(CURLFile, __wakeup) { zend_update_property_string(curl_CURLFile_class, getThis(), "name", sizeof("name")-1, "" TSRMLS_CC); zend_throw_exception(NULL, "Unserialization of CURLFile instances is not allowed", 0 TSRMLS_CC); } Commit Message: CWE ID: CWE-416
ZEND_METHOD(CURLFile, __wakeup) { zval *_this = getThis(); zend_unset_property(curl_CURLFile_class, _this, "name", sizeof("name")-1 TSRMLS_CC); zend_update_property_string(curl_CURLFile_class, _this, "name", sizeof("name")-1, "" TSRMLS_CC); zend_throw_exception(NULL, "Unserialization of CURLFile instances is not allowed", 0 TSRMLS_CC); }
165,259
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int sysMapBlockFile(FILE* mapf, MemMapping* pMap) { char block_dev[PATH_MAX+1]; size_t size; unsigned int blksize; unsigned int blocks; unsigned int range_count; unsigned int i; if (fgets(block_dev, sizeof(block_dev), mapf) == NULL) { LOGW("failed to read block device from header\n"); return -1; } for (i = 0; i < sizeof(block_dev); ++i) { if (block_dev[i] == '\n') { block_dev[i] = 0; break; } } if (fscanf(mapf, "%zu %u\n%u\n", &size, &blksize, &range_count) != 3) { LOGW("failed to parse block map header\n"); return -1; } blocks = ((size-1) / blksize) + 1; pMap->range_count = range_count; pMap->ranges = malloc(range_count * sizeof(MappedRange)); memset(pMap->ranges, 0, range_count * sizeof(MappedRange)); unsigned char* reserve; reserve = mmap64(NULL, blocks * blksize, PROT_NONE, MAP_PRIVATE | MAP_ANON, -1, 0); if (reserve == MAP_FAILED) { LOGW("failed to reserve address space: %s\n", strerror(errno)); return -1; } pMap->ranges[range_count-1].addr = reserve; pMap->ranges[range_count-1].length = blocks * blksize; int fd = open(block_dev, O_RDONLY); if (fd < 0) { LOGW("failed to open block device %s: %s\n", block_dev, strerror(errno)); return -1; } unsigned char* next = reserve; for (i = 0; i < range_count; ++i) { int start, end; if (fscanf(mapf, "%d %d\n", &start, &end) != 2) { LOGW("failed to parse range %d in block map\n", i); return -1; } void* addr = mmap64(next, (end-start)*blksize, PROT_READ, MAP_PRIVATE | MAP_FIXED, fd, ((off64_t)start)*blksize); if (addr == MAP_FAILED) { LOGW("failed to map block %d: %s\n", i, strerror(errno)); return -1; } pMap->ranges[i].addr = addr; pMap->ranges[i].length = (end-start)*blksize; next += pMap->ranges[i].length; } pMap->addr = reserve; pMap->length = size; LOGI("mmapped %d ranges\n", range_count); return 0; } Commit Message: Fix integer overflows in recovery procedure. Bug: 26960931 Change-Id: Ieae45caccfb4728fcf514f0d920976585d8e6caf (cherry picked from commit 4f2df162c6ab4a71ca86e4b38735b681729c353b) CWE ID: CWE-189
static int sysMapBlockFile(FILE* mapf, MemMapping* pMap) { char block_dev[PATH_MAX+1]; size_t size; unsigned int blksize; size_t blocks; unsigned int range_count; unsigned int i; if (fgets(block_dev, sizeof(block_dev), mapf) == NULL) { LOGW("failed to read block device from header\n"); return -1; } for (i = 0; i < sizeof(block_dev); ++i) { if (block_dev[i] == '\n') { block_dev[i] = 0; break; } } if (fscanf(mapf, "%zu %u\n%u\n", &size, &blksize, &range_count) != 3) { LOGW("failed to parse block map header\n"); return -1; } if (blksize != 0) { blocks = ((size-1) / blksize) + 1; } if (size == 0 || blksize == 0 || blocks > SIZE_MAX / blksize || range_count == 0) { LOGE("invalid data in block map file: size %zu, blksize %u, range_count %u\n", size, blksize, range_count); return -1; } pMap->range_count = range_count; pMap->ranges = calloc(range_count, sizeof(MappedRange)); if (pMap->ranges == NULL) { LOGE("calloc(%u, %zu) failed: %s\n", range_count, sizeof(MappedRange), strerror(errno)); return -1; } unsigned char* reserve; reserve = mmap64(NULL, blocks * blksize, PROT_NONE, MAP_PRIVATE | MAP_ANON, -1, 0); if (reserve == MAP_FAILED) { LOGW("failed to reserve address space: %s\n", strerror(errno)); free(pMap->ranges); return -1; } int fd = open(block_dev, O_RDONLY); if (fd < 0) { LOGW("failed to open block device %s: %s\n", block_dev, strerror(errno)); munmap(reserve, blocks * blksize); free(pMap->ranges); return -1; } unsigned char* next = reserve; size_t remaining_size = blocks * blksize; bool success = true; for (i = 0; i < range_count; ++i) { size_t start, end; if (fscanf(mapf, "%zu %zu\n", &start, &end) != 2) { LOGW("failed to parse range %d in block map\n", i); success = false; break; } size_t length = (end - start) * blksize; if (end <= start || (end - start) > SIZE_MAX / blksize || length > remaining_size) { LOGE("unexpected range in block map: %zu %zu\n", start, end); success = false; break; } void* addr = mmap64(next, length, PROT_READ, MAP_PRIVATE | MAP_FIXED, fd, ((off64_t)start)*blksize); if (addr == MAP_FAILED) { LOGW("failed to map block %d: %s\n", i, strerror(errno)); success = false; break; } pMap->ranges[i].addr = addr; pMap->ranges[i].length = length; next += length; remaining_size -= length; } if (success && remaining_size != 0) { LOGE("ranges in block map are invalid: remaining_size = %zu\n", remaining_size); success = false; } if (!success) { close(fd); munmap(reserve, blocks * blksize); free(pMap->ranges); return -1; } close(fd); pMap->addr = reserve; pMap->length = size; LOGI("mmapped %d ranges\n", range_count); return 0; }
173,903
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: double ConvolverNode::latencyTime() const { return m_reverb ? m_reverb->latencyFrames() / static_cast<double>(sampleRate()) : 0; } Commit Message: Fix threading races on ConvolverNode::m_reverb in ConvolverNode::latencyFrames() According to the crash report (https://cluster-fuzz.appspot.com/testcase?key=6515787040817152), ConvolverNode::m_reverb races between ConvolverNode::latencyFrames() and ConvolverNode::setBuffer(). This CL adds a proper lock for ConvolverNode::m_reverb. BUG=223962 No tests because the crash depends on threading races and thus not reproducible. Review URL: https://chromiumcodereview.appspot.com/23514037 git-svn-id: svn://svn.chromium.org/blink/trunk@157245 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-362
double ConvolverNode::latencyTime() const { MutexTryLocker tryLocker(m_processLock); if (tryLocker.locked()) return m_reverb ? m_reverb->latencyFrames() / static_cast<double>(sampleRate()) : 0; // Since we don't want to block the Audio Device thread, we return a large value // instead of trying to acquire the lock. return std::numeric_limits<double>::infinity(); }
171,172
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void 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--; } } Commit Message: Fix bug #72750: wddx_deserialize null dereference CWE ID: CWE-476
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--; } }
166,950
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: long VideoTrack::Seek( long long time_ns, const BlockEntry*& pResult) const { const long status = GetFirst(pResult); if (status < 0) //buffer underflow, etc return status; assert(pResult); if (pResult->EOS()) return 0; const Cluster* pCluster = pResult->GetCluster(); assert(pCluster); assert(pCluster->GetIndex() >= 0); if (time_ns <= pResult->GetBlock()->GetTime(pCluster)) return 0; Cluster** const clusters = m_pSegment->m_clusters; assert(clusters); const long count = m_pSegment->GetCount(); //loaded only, not pre-loaded assert(count > 0); Cluster** const i = clusters + pCluster->GetIndex(); assert(i); assert(*i == pCluster); assert(pCluster->GetTime() <= time_ns); Cluster** const j = clusters + count; Cluster** lo = i; Cluster** hi = j; while (lo < hi) { Cluster** const mid = lo + (hi - lo) / 2; assert(mid < hi); pCluster = *mid; assert(pCluster); assert(pCluster->GetIndex() >= 0); assert(pCluster->GetIndex() == long(mid - m_pSegment->m_clusters)); const long long t = pCluster->GetTime(); if (t <= time_ns) lo = mid + 1; else hi = mid; assert(lo <= hi); } assert(lo == hi); assert(lo > i); assert(lo <= j); pCluster = *--lo; assert(pCluster); assert(pCluster->GetTime() <= time_ns); pResult = pCluster->GetEntry(this, time_ns); if ((pResult != 0) && !pResult->EOS()) //found a keyframe return 0; while (lo != i) { pCluster = *--lo; assert(pCluster); assert(pCluster->GetTime() <= time_ns); #if 0 pResult = pCluster->GetMaxKey(this); #else pResult = pCluster->GetEntry(this, time_ns); #endif if ((pResult != 0) && !pResult->EOS()) return 0; } pResult = GetEOS(); return 0; } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
long VideoTrack::Seek( if (status < 0) return status; if (rate <= 0) return E_FILE_FORMAT_INVALID; } pos += size; // consume payload assert(pos <= stop); } assert(pos == stop); VideoTrack* const pTrack = new (std::nothrow) VideoTrack(pSegment, element_start, element_size); if (pTrack == NULL) return -1; // generic error const int status = info.Copy(pTrack->m_info); if (status) { // error delete pTrack; return status; } pTrack->m_width = width; pTrack->m_height = height; pTrack->m_rate = rate; pResult = pTrack; return 0; // success } bool VideoTrack::VetEntry(const BlockEntry* pBlockEntry) const { return Track::VetEntry(pBlockEntry) && pBlockEntry->GetBlock()->IsKey(); } long VideoTrack::Seek(long long time_ns, const BlockEntry*& pResult) const { const long status = GetFirst(pResult); if (status < 0) // buffer underflow, etc return status; assert(pResult); if (pResult->EOS()) return 0; const Cluster* pCluster = pResult->GetCluster(); assert(pCluster); assert(pCluster->GetIndex() >= 0); if (time_ns <= pResult->GetBlock()->GetTime(pCluster)) return 0; Cluster** const clusters = m_pSegment->m_clusters; assert(clusters); const long count = m_pSegment->GetCount(); // loaded only, not pre-loaded assert(count > 0); Cluster** const i = clusters + pCluster->GetIndex(); assert(i); assert(*i == pCluster); assert(pCluster->GetTime() <= time_ns); Cluster** const j = clusters + count; Cluster** lo = i; Cluster** hi = j; while (lo < hi) { // INVARIANT: //[i, lo) <= time_ns //[lo, hi) ? //[hi, j) > time_ns Cluster** const mid = lo + (hi - lo) / 2; assert(mid < hi); pCluster = *mid; assert(pCluster); assert(pCluster->GetIndex() >= 0); assert(pCluster->GetIndex() == long(mid - m_pSegment->m_clusters)); const long long t = pCluster->GetTime(); if (t <= time_ns) lo = mid + 1; else hi = mid; assert(lo <= hi); } assert(lo == hi); assert(lo > i); assert(lo <= j); pCluster = *--lo; assert(pCluster); assert(pCluster->GetTime() <= time_ns); pResult = pCluster->GetEntry(this, time_ns); if ((pResult != 0) && !pResult->EOS()) // found a keyframe return 0; while (lo != i) { pCluster = *--lo; assert(pCluster); assert(pCluster->GetTime() <= time_ns); #if 0 pResult = pCluster->GetMaxKey(this); #else pResult = pCluster->GetEntry(this, time_ns); #endif if ((pResult != 0) && !pResult->EOS()) return 0; } // weird: we're on the first cluster, but no keyframe found // should never happen but we must return something anyway pResult = GetEOS(); return 0; } long long VideoTrack::GetWidth() const { return m_width; } long long VideoTrack::GetHeight() const { return m_height; } double VideoTrack::GetFrameRate() const { return m_rate; } AudioTrack::AudioTrack(Segment* pSegment, long long element_start, long long element_size) : Track(pSegment, element_start, element_size) {} long AudioTrack::Parse(Segment* pSegment, const Info& info, long long element_start, long long element_size, AudioTrack*& pResult) { if (pResult) return -1; if (info.type != Track::kAudio) return -1; IMkvReader* const pReader = pSegment->m_pReader; const Settings& s = info.settings; assert(s.start >= 0); assert(s.size >= 0); long long pos = s.start; assert(pos >= 0); const long long stop = pos + s.size; double rate = 8000.0; // MKV default long long channels = 1; long long bit_depth = 0; while (pos < stop) { long long id, size; long status = ParseElementHeader(pReader, pos, stop, id, size); if (status < 0) // error return status; if (id == 0x35) { // Sample Rate status = UnserializeFloat(pReader, pos, size, rate); if (status < 0) return status; if (rate <= 0) return E_FILE_FORMAT_INVALID; } else if (id == 0x1F) { // Channel Count channels = UnserializeUInt(pReader, pos, size); if (channels <= 0) return E_FILE_FORMAT_INVALID; } else if (id == 0x2264) { // Bit Depth bit_depth = UnserializeUInt(pReader, pos, size); if (bit_depth <= 0) return E_FILE_FORMAT_INVALID; } pos += size; // consume payload assert(pos <= stop); } assert(pos == stop); AudioTrack* const pTrack = new (std::nothrow) AudioTrack(pSegment, element_start, element_size); if (pTrack == NULL) return -1; // generic error const int status = info.Copy(pTrack->m_info); if (status) { delete pTrack; return status; } pTrack->m_rate = rate; pTrack->m_channels = channels; pTrack->m_bitDepth = bit_depth; pResult = pTrack; return 0; // success }
174,436
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void SandboxIPCHandler::HandleLocaltime( int fd, base::PickleIterator iter, const std::vector<base::ScopedFD>& fds) { std::string time_string; if (!iter.ReadString(&time_string) || time_string.size() != sizeof(time_t)) return; time_t time; memcpy(&time, time_string.data(), sizeof(time)); const struct tm* expanded_time = localtime(&time); std::string result_string; const char* time_zone_string = ""; if (expanded_time) { result_string = std::string(reinterpret_cast<const char*>(expanded_time), sizeof(struct tm)); time_zone_string = expanded_time->tm_zone; } base::Pickle reply; reply.WriteString(result_string); reply.WriteString(time_zone_string); SendRendererReply(fds, reply, -1); } Commit Message: Serialize struct tm in a safe way. BUG=765512 Change-Id: If235b8677eb527be2ac0fe621fc210e4116a7566 Reviewed-on: https://chromium-review.googlesource.com/679441 Commit-Queue: Chris Palmer <[email protected]> Reviewed-by: Julien Tinnes <[email protected]> Cr-Commit-Position: refs/heads/master@{#503948} CWE ID: CWE-119
void SandboxIPCHandler::HandleLocaltime( int fd, base::PickleIterator iter, const std::vector<base::ScopedFD>& fds) { // The other side of this call is in |ProxyLocaltimeCallToBrowser|, in // zygote_main_linux.cc. std::string time_string; if (!iter.ReadString(&time_string) || time_string.size() != sizeof(time_t)) return; time_t time; memcpy(&time, time_string.data(), sizeof(time)); // We use |localtime| here because we need the |tm_zone| field to be filled const struct tm* expanded_time = localtime(&time); base::Pickle reply; if (expanded_time) { WriteTimeStruct(&reply, expanded_time); } else { // The {} constructor ensures the struct is 0-initialized. struct tm zeroed_time = {}; WriteTimeStruct(&reply, &zeroed_time); } SendRendererReply(fds, reply, -1); }
172,925
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: AudioParameters GetInputParametersOnDeviceThread(AudioManager* audio_manager, const std::string& device_id) { DCHECK(audio_manager->GetTaskRunner()->BelongsToCurrentThread()); if (!audio_manager->HasAudioInputDevices()) return AudioParameters(); return audio_manager->GetInputStreamParameters(device_id); } Commit Message: Switching AudioOutputAuthorizationHandler from using AudioManager interface to AudioSystem one. BUG=672468 CQ_INCLUDE_TRYBOTS=master.tryserver.chromium.linux:linux_optional_gpu_tests_rel;master.tryserver.chromium.mac:mac_optional_gpu_tests_rel;master.tryserver.chromium.win:win_optional_gpu_tests_rel Review-Url: https://codereview.chromium.org/2692203003 Cr-Commit-Position: refs/heads/master@{#450939} CWE ID:
AudioParameters GetInputParametersOnDeviceThread(AudioManager* audio_manager, const std::string& device_id) { DCHECK(audio_manager->GetTaskRunner()->BelongsToCurrentThread()); // returns invalid parameters if the device is not found. if (!audio_manager->HasAudioInputDevices()) return AudioParameters(); return audio_manager->GetInputStreamParameters(device_id); }
171,988
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: BrowserContext* OTRBrowserContextImpl::GetOriginalContext() const { return original_context_.get(); } Commit Message: CWE ID: CWE-20
BrowserContext* OTRBrowserContextImpl::GetOriginalContext() const { BrowserContext* OTRBrowserContextImpl::GetOriginalContext() { return original_context_; }
165,414
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: dophn_core(struct magic_set *ms, int clazz, int swap, int fd, off_t off, int num, size_t size, off_t fsize, int *flags) { Elf32_Phdr ph32; Elf64_Phdr ph64; size_t offset, len; unsigned char nbuf[BUFSIZ]; ssize_t bufsize; if (size != xph_sizeof) { if (file_printf(ms, ", corrupted program header size") == -1) return -1; return 0; } /* * Loop through all the program headers. */ for ( ; num; num--) { if (pread(fd, xph_addr, xph_sizeof, off) < (ssize_t)xph_sizeof) { file_badread(ms); return -1; } off += size; if (fsize != SIZE_UNKNOWN && xph_offset > fsize) { /* Perhaps warn here */ continue; } if (xph_type != PT_NOTE) continue; /* * This is a PT_NOTE section; loop through all the notes * in the section. */ len = xph_filesz < sizeof(nbuf) ? xph_filesz : sizeof(nbuf); if ((bufsize = pread(fd, nbuf, len, xph_offset)) == -1) { file_badread(ms); return -1; } offset = 0; for (;;) { if (offset >= (size_t)bufsize) break; offset = donote(ms, nbuf, offset, (size_t)bufsize, clazz, swap, 4, flags); if (offset == 0) break; } } return 0; } Commit Message: - Add a limit to the number of ELF notes processed (Suggested by Alexander Cherepanov) - Restructure ELF note printing so that we don't print the same message multiple times on repeated notes of the same kind. CWE ID: CWE-399
dophn_core(struct magic_set *ms, int clazz, int swap, int fd, off_t off, int num, size_t size, off_t fsize, int *flags, uint16_t *notecount) { Elf32_Phdr ph32; Elf64_Phdr ph64; size_t offset, len; unsigned char nbuf[BUFSIZ]; ssize_t bufsize; if (size != xph_sizeof) { if (file_printf(ms, ", corrupted program header size") == -1) return -1; return 0; } /* * Loop through all the program headers. */ for ( ; num; num--) { if (pread(fd, xph_addr, xph_sizeof, off) < (ssize_t)xph_sizeof) { file_badread(ms); return -1; } off += size; if (fsize != SIZE_UNKNOWN && xph_offset > fsize) { /* Perhaps warn here */ continue; } if (xph_type != PT_NOTE) continue; /* * This is a PT_NOTE section; loop through all the notes * in the section. */ len = xph_filesz < sizeof(nbuf) ? xph_filesz : sizeof(nbuf); if ((bufsize = pread(fd, nbuf, len, xph_offset)) == -1) { file_badread(ms); return -1; } offset = 0; for (;;) { if (offset >= (size_t)bufsize) break; offset = donote(ms, nbuf, offset, (size_t)bufsize, clazz, swap, 4, flags, notecount); if (offset == 0) break; } } return 0; }
166,777
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: INST_HANDLER (sts) { // STS k, Rr int r = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x1) << 4); int k = (buf[3] << 8) | buf[2]; op->ptr = k; ESIL_A ("r%d,", r); __generic_ld_st (op, "ram", 0, 1, 0, k, 1); op->cycles = 2; } Commit Message: Fix #10091 - crash in AVR analysis CWE ID: CWE-125
INST_HANDLER (sts) { // STS k, Rr if (len < 4) { return; } int r = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x1) << 4); int k = (buf[3] << 8) | buf[2]; op->ptr = k; ESIL_A ("r%d,", r); __generic_ld_st (op, "ram", 0, 1, 0, k, 1); op->cycles = 2; }
169,223
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void vrend_renderer_init_blit_ctx(struct vrend_blitter_ctx *blit_ctx) { struct virgl_gl_ctx_param ctx_params; int i; if (blit_ctx->initialised) { vrend_clicbs->make_current(0, blit_ctx->gl_context); return; } ctx_params.shared = true; ctx_params.major_ver = VREND_GL_VER_MAJOR; ctx_params.minor_ver = VREND_GL_VER_MINOR; vrend_clicbs->make_current(0, blit_ctx->gl_context); glGenVertexArrays(1, &blit_ctx->vaoid); glGenFramebuffers(1, &blit_ctx->fb_id); glGenBuffers(1, &blit_ctx->vbo_id); blit_build_vs_passthrough(blit_ctx); for (i = 0; i < 4; i++) blit_ctx->vertices[i][0][3] = 1; /*v.w*/ glBindVertexArray(blit_ctx->vaoid); glBindBuffer(GL_ARRAY_BUFFER, blit_ctx->vbo_id); } Commit Message: CWE ID: CWE-772
static void vrend_renderer_init_blit_ctx(struct vrend_blitter_ctx *blit_ctx) { struct virgl_gl_ctx_param ctx_params; int i; if (blit_ctx->initialised) { vrend_clicbs->make_current(0, blit_ctx->gl_context); return; } blit_ctx->initialised = true; ctx_params.shared = true; ctx_params.major_ver = VREND_GL_VER_MAJOR; ctx_params.minor_ver = VREND_GL_VER_MINOR; vrend_clicbs->make_current(0, blit_ctx->gl_context); glGenVertexArrays(1, &blit_ctx->vaoid); glGenFramebuffers(1, &blit_ctx->fb_id); glGenBuffers(1, &blit_ctx->vbo_id); blit_build_vs_passthrough(blit_ctx); for (i = 0; i < 4; i++) blit_ctx->vertices[i][0][3] = 1; /*v.w*/ glBindVertexArray(blit_ctx->vaoid); glBindBuffer(GL_ARRAY_BUFFER, blit_ctx->vbo_id); }
164,955
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static cJSON *get_object_item(const cJSON * const object, const char * const name, const cJSON_bool case_sensitive) { cJSON *current_element = NULL; if ((object == NULL) || (name == NULL)) { return NULL; } current_element = object->child; if (case_sensitive) { while ((current_element != NULL) && (strcmp(name, current_element->string) != 0)) { current_element = current_element->next; } } else { while ((current_element != NULL) && (case_insensitive_strcmp((const unsigned char*)name, (const unsigned char*)(current_element->string)) != 0)) { current_element = current_element->next; } } return current_element; } Commit Message: Fix crash of cJSON_GetObjectItemCaseSensitive when calling it on arrays CWE ID: CWE-754
static cJSON *get_object_item(const cJSON * const object, const char * const name, const cJSON_bool case_sensitive) { cJSON *current_element = NULL; if ((object == NULL) || (name == NULL)) { return NULL; } current_element = object->child; if (case_sensitive) { while ((current_element != NULL) && (current_element->string != NULL) && (strcmp(name, current_element->string) != 0)) { current_element = current_element->next; } } else { while ((current_element != NULL) && (case_insensitive_strcmp((const unsigned char*)name, (const unsigned char*)(current_element->string)) != 0)) { current_element = current_element->next; } } if ((current_element == NULL) || (current_element->string == NULL)) { return NULL; } return current_element; }
169,480
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool VaapiVideoDecodeAccelerator::VaapiVP9Accelerator::GetFrameContext( const scoped_refptr<VP9Picture>& pic, Vp9FrameContext* frame_ctx) { NOTIMPLEMENTED() << "Frame context update not supported"; return false; } Commit Message: vaapi vda: Delete owned objects on worker thread in Cleanup() This CL adds a SEQUENCE_CHECKER to Vaapi*Accelerator classes, and posts the destruction of those objects to the appropriate thread on Cleanup(). Also makes {H264,VP8,VP9}Picture RefCountedThreadSafe, see miu@ comment in https://chromium-review.googlesource.com/c/chromium/src/+/794091#message-a64bed985cfaf8a19499a517bb110a7ce581dc0f TEST=play back VP9/VP8/H264 w/ simplechrome on soraka, Release build unstripped, let video play for a few seconds then navigate back; no crashes. Unittests as before: video_decode_accelerator_unittest --test_video_data=test-25fps.vp9:320:240:250:250:35:150:12 video_decode_accelerator_unittest --test_video_data=test-25fps.vp8:320:240:250:250:35:150:11 video_decode_accelerator_unittest --test_video_data=test-25fps.h264:320:240:250:258:35:150:1 Bug: 789160 Cq-Include-Trybots: master.tryserver.chromium.android:android_optional_gpu_tests_rel;master.tryserver.chromium.linux:linux_optional_gpu_tests_rel;master.tryserver.chromium.mac:mac_optional_gpu_tests_rel;master.tryserver.chromium.win:win_optional_gpu_tests_rel Change-Id: I7d96aaf89c92bf46f00c8b8b36798e057a842ed2 Reviewed-on: https://chromium-review.googlesource.com/794091 Reviewed-by: Pawel Osciak <[email protected]> Commit-Queue: Miguel Casas <[email protected]> Cr-Commit-Position: refs/heads/master@{#523372} CWE ID: CWE-362
bool VaapiVideoDecodeAccelerator::VaapiVP9Accelerator::GetFrameContext( const scoped_refptr<VP9Picture>& pic, Vp9FrameContext* frame_ctx) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); NOTIMPLEMENTED() << "Frame context update not supported"; return false; }
172,802
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: LogLuvSetupEncode(TIFF* tif) { static const char module[] = "LogLuvSetupEncode"; LogLuvState* sp = EncoderState(tif); TIFFDirectory* td = &tif->tif_dir; switch (td->td_photometric) { case PHOTOMETRIC_LOGLUV: if (!LogLuvInitState(tif)) break; if (td->td_compression == COMPRESSION_SGILOG24) { tif->tif_encoderow = LogLuvEncode24; switch (sp->user_datafmt) { case SGILOGDATAFMT_FLOAT: sp->tfunc = Luv24fromXYZ; break; case SGILOGDATAFMT_16BIT: sp->tfunc = Luv24fromLuv48; break; case SGILOGDATAFMT_RAW: break; default: goto notsupported; } } else { tif->tif_encoderow = LogLuvEncode32; switch (sp->user_datafmt) { case SGILOGDATAFMT_FLOAT: sp->tfunc = Luv32fromXYZ; break; case SGILOGDATAFMT_16BIT: sp->tfunc = Luv32fromLuv48; break; case SGILOGDATAFMT_RAW: break; default: goto notsupported; } } break; case PHOTOMETRIC_LOGL: if (!LogL16InitState(tif)) break; tif->tif_encoderow = LogL16Encode; switch (sp->user_datafmt) { case SGILOGDATAFMT_FLOAT: sp->tfunc = L16fromY; break; case SGILOGDATAFMT_16BIT: break; default: goto notsupported; } break; default: TIFFErrorExt(tif->tif_clientdata, module, "Inappropriate photometric interpretation %d for SGILog compression; %s", td->td_photometric, "must be either LogLUV or LogL"); break; } return (1); notsupported: TIFFErrorExt(tif->tif_clientdata, module, "SGILog compression supported only for %s, or raw data", td->td_photometric == PHOTOMETRIC_LOGL ? "Y, L" : "XYZ, Luv"); return (0); } Commit Message: * libtiff/tif_pixarlog.c, libtiff/tif_luv.c: fix heap-based buffer overflow on generation of PixarLog / LUV compressed files, with ColorMap, TransferFunction attached and nasty plays with bitspersample. The fix for LUV has not been tested, but suffers from the same kind of issue of PixarLog. Reported by Agostino Sarubbo. Fixes http://bugzilla.maptools.org/show_bug.cgi?id=2604 CWE ID: CWE-125
LogLuvSetupEncode(TIFF* tif) { static const char module[] = "LogLuvSetupEncode"; LogLuvState* sp = EncoderState(tif); TIFFDirectory* td = &tif->tif_dir; switch (td->td_photometric) { case PHOTOMETRIC_LOGLUV: if (!LogLuvInitState(tif)) break; if (td->td_compression == COMPRESSION_SGILOG24) { tif->tif_encoderow = LogLuvEncode24; switch (sp->user_datafmt) { case SGILOGDATAFMT_FLOAT: sp->tfunc = Luv24fromXYZ; break; case SGILOGDATAFMT_16BIT: sp->tfunc = Luv24fromLuv48; break; case SGILOGDATAFMT_RAW: break; default: goto notsupported; } } else { tif->tif_encoderow = LogLuvEncode32; switch (sp->user_datafmt) { case SGILOGDATAFMT_FLOAT: sp->tfunc = Luv32fromXYZ; break; case SGILOGDATAFMT_16BIT: sp->tfunc = Luv32fromLuv48; break; case SGILOGDATAFMT_RAW: break; default: goto notsupported; } } break; case PHOTOMETRIC_LOGL: if (!LogL16InitState(tif)) break; tif->tif_encoderow = LogL16Encode; switch (sp->user_datafmt) { case SGILOGDATAFMT_FLOAT: sp->tfunc = L16fromY; break; case SGILOGDATAFMT_16BIT: break; default: goto notsupported; } break; default: TIFFErrorExt(tif->tif_clientdata, module, "Inappropriate photometric interpretation %d for SGILog compression; %s", td->td_photometric, "must be either LogLUV or LogL"); break; } sp->encoder_state = 1; return (1); notsupported: TIFFErrorExt(tif->tif_clientdata, module, "SGILog compression supported only for %s, or raw data", td->td_photometric == PHOTOMETRIC_LOGL ? "Y, L" : "XYZ, Luv"); return (0); }
168,465
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void QuicStreamHost::Finish() { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); DCHECK(p2p_stream_); p2p_stream_->Finish(); writeable_ = false; if (!readable_ && !writeable_) { Delete(); } } Commit Message: P2PQuicStream write functionality. This adds the P2PQuicStream::WriteData function and adds tests. It also adds the concept of a write buffered amount, enforcing this at the P2PQuicStreamImpl. Bug: 874296 Change-Id: Id02c8aa8d5368a87bb24a2e50dab5ef94bcae131 Reviewed-on: https://chromium-review.googlesource.com/c/1315534 Commit-Queue: Seth Hampson <[email protected]> Reviewed-by: Henrik Boström <[email protected]> Cr-Commit-Position: refs/heads/master@{#605766} CWE ID: CWE-284
void QuicStreamHost::Finish() { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); DCHECK(p2p_stream_); std::vector<uint8_t> data; p2p_stream_->WriteData(data, true); writeable_ = false; if (!readable_ && !writeable_) { Delete(); } }
172,269
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void LocalFileSystem::fileSystemNotAllowedInternal( PassRefPtrWillBeRawPtr<ExecutionContext> context, PassRefPtr<CallbackWrapper> callbacks) { context->postTask(createCrossThreadTask(&reportFailure, callbacks->release(), FileError::ABORT_ERR)); } Commit Message: Oilpan: Ship Oilpan for SyncCallbackHelper, CreateFileResult and CallbackWrapper in filesystem/ These are leftovers when we shipped Oilpan for filesystem/ once. BUG=340522 Review URL: https://codereview.chromium.org/501263003 git-svn-id: svn://svn.chromium.org/blink/trunk@180909 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-119
void LocalFileSystem::fileSystemNotAllowedInternal( PassRefPtrWillBeRawPtr<ExecutionContext> context, CallbackWrapper* callbacks) { context->postTask(createCrossThreadTask(&reportFailure, callbacks->release(), FileError::ABORT_ERR)); }
171,427
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: QString IRCView::closeToTagString(TextHtmlData* data, const QString& _tag) { QString ret; QString tag; int i = data->openHtmlTags.count() - 1; for ( ; i >= 0 ; --i) { tag = data->openHtmlTags.at(i); ret += QLatin1String("</") + tag + QLatin1Char('>'); if (tag == _tag) { data->openHtmlTags.removeAt(i); break; } } ret += openTags(data, i); return ret; } Commit Message: CWE ID:
QString IRCView::closeToTagString(TextHtmlData* data, const QString& _tag) { QString ret; QString tag; int i = data->openHtmlTags.count() - 1; for ( ; i >= 0 ; --i) { tag = data->openHtmlTags.at(i); ret += QLatin1String("</") + tag + QLatin1Char('>'); if (tag == _tag) { data->openHtmlTags.removeAt(i); break; } } if (i > -1) ret += openTags(data, i); return ret; }
164,648
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: PassRefPtr<DocumentFragment> createFragmentFromMarkup(Document* document, const String& markup, const String& baseURL, FragmentScriptingPermission scriptingPermission) { RefPtr<HTMLBodyElement> fakeBody = HTMLBodyElement::create(document); RefPtr<DocumentFragment> fragment = Range::createDocumentFragmentForElement(markup, fakeBody.get(), scriptingPermission); if (fragment && !baseURL.isEmpty() && baseURL != blankURL() && baseURL != document->baseURL()) completeURLs(fragment.get(), baseURL); return fragment.release(); } Commit Message: There are too many poorly named functions to create a fragment from markup https://bugs.webkit.org/show_bug.cgi?id=87339 Reviewed by Eric Seidel. Source/WebCore: Moved all functions that create a fragment from markup to markup.h/cpp. There should be no behavioral change. * dom/Range.cpp: (WebCore::Range::createContextualFragment): * dom/Range.h: Removed createDocumentFragmentForElement. * dom/ShadowRoot.cpp: (WebCore::ShadowRoot::setInnerHTML): * editing/markup.cpp: (WebCore::createFragmentFromMarkup): (WebCore::createFragmentForInnerOuterHTML): Renamed from createFragmentFromSource. (WebCore::createFragmentForTransformToFragment): Moved from XSLTProcessor. (WebCore::removeElementPreservingChildren): Moved from Range. (WebCore::createContextualFragment): Ditto. * editing/markup.h: * html/HTMLElement.cpp: (WebCore::HTMLElement::setInnerHTML): (WebCore::HTMLElement::setOuterHTML): (WebCore::HTMLElement::insertAdjacentHTML): * inspector/DOMPatchSupport.cpp: (WebCore::DOMPatchSupport::patchNode): Added a FIXME since this code should be using one of the functions listed in markup.h * xml/XSLTProcessor.cpp: (WebCore::XSLTProcessor::transformToFragment): Source/WebKit/qt: Replace calls to Range::createDocumentFragmentForElement by calls to createContextualDocumentFragment. * Api/qwebelement.cpp: (QWebElement::appendInside): (QWebElement::prependInside): (QWebElement::prependOutside): (QWebElement::appendOutside): (QWebElement::encloseContentsWith): (QWebElement::encloseWith): git-svn-id: svn://svn.chromium.org/blink/trunk@118414 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-264
PassRefPtr<DocumentFragment> createFragmentFromMarkup(Document* document, const String& markup, const String& baseURL, FragmentScriptingPermission scriptingPermission) { RefPtr<HTMLBodyElement> fakeBody = HTMLBodyElement::create(document); RefPtr<DocumentFragment> fragment = createContextualFragment(markup, fakeBody.get(), scriptingPermission); if (fragment && !baseURL.isEmpty() && baseURL != blankURL() && baseURL != document->baseURL()) completeURLs(fragment.get(), baseURL); return fragment.release(); }
170,438
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static size_t consume_init_expr (ut8 *buf, ut8 *max, ut8 eoc, void *out, ut32 *offset) { ut32 i = 0; while (buf + i < max && buf[i] != eoc) { i += 1; } if (buf[i] != eoc) { return 0; } if (offset) { *offset += i + 1; } return i + 1; } Commit Message: Fix crash in fuzzed wasm r2_hoobr_consume_init_expr CWE ID: CWE-125
static size_t consume_init_expr (ut8 *buf, ut8 *max, ut8 eoc, void *out, ut32 *offset) { ut32 i = 0; while (buf + i < max && buf[i] != eoc) { i++; } if (buf[i] != eoc) { return 0; } if (offset) { *offset += i + 1; } return i + 1; }
168,250
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: ssh_packet_set_state(struct ssh *ssh, struct sshbuf *m) { struct session_state *state = ssh->state; const u_char *ssh1key, *ivin, *ivout, *keyin, *keyout, *input, *output; size_t ssh1keylen, rlen, slen, ilen, olen; int r; u_int ssh1cipher = 0; if (!compat20) { if ((r = sshbuf_get_u32(m, &state->remote_protocol_flags)) != 0 || (r = sshbuf_get_u32(m, &ssh1cipher)) != 0 || (r = sshbuf_get_string_direct(m, &ssh1key, &ssh1keylen)) != 0 || (r = sshbuf_get_string_direct(m, &ivout, &slen)) != 0 || (r = sshbuf_get_string_direct(m, &ivin, &rlen)) != 0) return r; if (ssh1cipher > INT_MAX) return SSH_ERR_KEY_UNKNOWN_CIPHER; ssh_packet_set_encryption_key(ssh, ssh1key, ssh1keylen, (int)ssh1cipher); if (cipher_get_keyiv_len(state->send_context) != (int)slen || cipher_get_keyiv_len(state->receive_context) != (int)rlen) return SSH_ERR_INVALID_FORMAT; if ((r = cipher_set_keyiv(state->send_context, ivout)) != 0 || (r = cipher_set_keyiv(state->receive_context, ivin)) != 0) return r; } else { if ((r = kex_from_blob(m, &ssh->kex)) != 0 || (r = newkeys_from_blob(m, ssh, MODE_OUT)) != 0 || (r = newkeys_from_blob(m, ssh, MODE_IN)) != 0 || (r = sshbuf_get_u64(m, &state->rekey_limit)) != 0 || (r = sshbuf_get_u32(m, &state->rekey_interval)) != 0 || (r = sshbuf_get_u32(m, &state->p_send.seqnr)) != 0 || (r = sshbuf_get_u64(m, &state->p_send.blocks)) != 0 || (r = sshbuf_get_u32(m, &state->p_send.packets)) != 0 || (r = sshbuf_get_u64(m, &state->p_send.bytes)) != 0 || (r = sshbuf_get_u32(m, &state->p_read.seqnr)) != 0 || (r = sshbuf_get_u64(m, &state->p_read.blocks)) != 0 || (r = sshbuf_get_u32(m, &state->p_read.packets)) != 0 || (r = sshbuf_get_u64(m, &state->p_read.bytes)) != 0) return r; /* * We set the time here so that in post-auth privsep slave we * count from the completion of the authentication. */ state->rekey_time = monotime(); /* XXX ssh_set_newkeys overrides p_read.packets? XXX */ if ((r = ssh_set_newkeys(ssh, MODE_IN)) != 0 || (r = ssh_set_newkeys(ssh, MODE_OUT)) != 0) return r; } if ((r = sshbuf_get_string_direct(m, &keyout, &slen)) != 0 || (r = sshbuf_get_string_direct(m, &keyin, &rlen)) != 0) return r; if (cipher_get_keycontext(state->send_context, NULL) != (int)slen || cipher_get_keycontext(state->receive_context, NULL) != (int)rlen) return SSH_ERR_INVALID_FORMAT; cipher_set_keycontext(state->send_context, keyout); cipher_set_keycontext(state->receive_context, keyin); if ((r = ssh_packet_set_compress_state(ssh, m)) != 0 || (r = ssh_packet_set_postauth(ssh)) != 0) return r; sshbuf_reset(state->input); sshbuf_reset(state->output); if ((r = sshbuf_get_string_direct(m, &input, &ilen)) != 0 || (r = sshbuf_get_string_direct(m, &output, &olen)) != 0 || (r = sshbuf_put(state->input, input, ilen)) != 0 || (r = sshbuf_put(state->output, output, olen)) != 0) return r; if (sshbuf_len(m)) return SSH_ERR_INVALID_FORMAT; debug3("%s: done", __func__); return 0; } Commit Message: Remove support for pre-authentication compression. Doing compression early in the protocol probably seemed reasonable in the 1990s, but today it's clearly a bad idea in terms of both cryptography (cf. multiple compression oracle attacks in TLS) and attack surface. Moreover, to support it across privilege-separation zlib needed the assistance of a complex shared-memory manager that made the required attack surface considerably larger. Prompted by Guido Vranken pointing out a compiler-elided security check in the shared memory manager found by Stack (http://css.csail.mit.edu/stack/); ok deraadt@ markus@ NB. pre-auth authentication has been disabled by default in sshd for >10 years. CWE ID: CWE-119
ssh_packet_set_state(struct ssh *ssh, struct sshbuf *m) { struct session_state *state = ssh->state; const u_char *ssh1key, *ivin, *ivout, *keyin, *keyout, *input, *output; size_t ssh1keylen, rlen, slen, ilen, olen; int r; u_int ssh1cipher = 0; if (!compat20) { if ((r = sshbuf_get_u32(m, &state->remote_protocol_flags)) != 0 || (r = sshbuf_get_u32(m, &ssh1cipher)) != 0 || (r = sshbuf_get_string_direct(m, &ssh1key, &ssh1keylen)) != 0 || (r = sshbuf_get_string_direct(m, &ivout, &slen)) != 0 || (r = sshbuf_get_string_direct(m, &ivin, &rlen)) != 0) return r; if (ssh1cipher > INT_MAX) return SSH_ERR_KEY_UNKNOWN_CIPHER; ssh_packet_set_encryption_key(ssh, ssh1key, ssh1keylen, (int)ssh1cipher); if (cipher_get_keyiv_len(state->send_context) != (int)slen || cipher_get_keyiv_len(state->receive_context) != (int)rlen) return SSH_ERR_INVALID_FORMAT; if ((r = cipher_set_keyiv(state->send_context, ivout)) != 0 || (r = cipher_set_keyiv(state->receive_context, ivin)) != 0) return r; } else { if ((r = kex_from_blob(m, &ssh->kex)) != 0 || (r = newkeys_from_blob(m, ssh, MODE_OUT)) != 0 || (r = newkeys_from_blob(m, ssh, MODE_IN)) != 0 || (r = sshbuf_get_u64(m, &state->rekey_limit)) != 0 || (r = sshbuf_get_u32(m, &state->rekey_interval)) != 0 || (r = sshbuf_get_u32(m, &state->p_send.seqnr)) != 0 || (r = sshbuf_get_u64(m, &state->p_send.blocks)) != 0 || (r = sshbuf_get_u32(m, &state->p_send.packets)) != 0 || (r = sshbuf_get_u64(m, &state->p_send.bytes)) != 0 || (r = sshbuf_get_u32(m, &state->p_read.seqnr)) != 0 || (r = sshbuf_get_u64(m, &state->p_read.blocks)) != 0 || (r = sshbuf_get_u32(m, &state->p_read.packets)) != 0 || (r = sshbuf_get_u64(m, &state->p_read.bytes)) != 0) return r; /* * We set the time here so that in post-auth privsep slave we * count from the completion of the authentication. */ state->rekey_time = monotime(); /* XXX ssh_set_newkeys overrides p_read.packets? XXX */ if ((r = ssh_set_newkeys(ssh, MODE_IN)) != 0 || (r = ssh_set_newkeys(ssh, MODE_OUT)) != 0) return r; } if ((r = sshbuf_get_string_direct(m, &keyout, &slen)) != 0 || (r = sshbuf_get_string_direct(m, &keyin, &rlen)) != 0) return r; if (cipher_get_keycontext(state->send_context, NULL) != (int)slen || cipher_get_keycontext(state->receive_context, NULL) != (int)rlen) return SSH_ERR_INVALID_FORMAT; cipher_set_keycontext(state->send_context, keyout); cipher_set_keycontext(state->receive_context, keyin); if ((r = ssh_packet_set_postauth(ssh)) != 0) return r; sshbuf_reset(state->input); sshbuf_reset(state->output); if ((r = sshbuf_get_string_direct(m, &input, &ilen)) != 0 || (r = sshbuf_get_string_direct(m, &output, &olen)) != 0 || (r = sshbuf_put(state->input, input, ilen)) != 0 || (r = sshbuf_put(state->output, output, olen)) != 0) return r; if (sshbuf_len(m)) return SSH_ERR_INVALID_FORMAT; debug3("%s: done", __func__); return 0; }
168,656
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void LogoService::SetClockForTests(std::unique_ptr<base::Clock> clock) { clock_for_test_ = std::move(clock); } Commit Message: Local NTP: add smoke tests for doodles Split LogoService into LogoService interface and LogoServiceImpl to make it easier to provide fake data to the test. Bug: 768419 Cq-Include-Trybots: master.tryserver.chromium.linux:closure_compilation Change-Id: I84639189d2db1b24a2e139936c99369352bab587 Reviewed-on: https://chromium-review.googlesource.com/690198 Reviewed-by: Sylvain Defresne <[email protected]> Reviewed-by: Marc Treib <[email protected]> Commit-Queue: Chris Pickel <[email protected]> Cr-Commit-Position: refs/heads/master@{#505374} CWE ID: CWE-119
void LogoService::SetClockForTests(std::unique_ptr<base::Clock> clock) {
171,959
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: BackendImpl::BackendImpl( const base::FilePath& path, uint32_t mask, const scoped_refptr<base::SingleThreadTaskRunner>& cache_thread, net::NetLog* net_log) : background_queue_(this, FallbackToInternalIfNull(cache_thread)), path_(path), block_files_(path), mask_(mask), max_size_(0), up_ticks_(0), cache_type_(net::DISK_CACHE), uma_report_(0), user_flags_(kMask), init_(false), restarted_(false), unit_test_(false), read_only_(false), disabled_(false), new_eviction_(false), first_timer_(true), user_load_(false), net_log_(net_log), done_(base::WaitableEvent::ResetPolicy::MANUAL, base::WaitableEvent::InitialState::NOT_SIGNALED), ptr_factory_(this) {} Commit Message: Blockfile cache: fix long-standing sparse + evict reentrancy problem Thanks to nedwilliamson@ (on gmail) for an alternative perspective plus a reduction to make fixing this much easier. Bug: 826626, 518908, 537063, 802886 Change-Id: Ibfa01416f9a8e7f7b361e4f93b4b6b134728b85f Reviewed-on: https://chromium-review.googlesource.com/985052 Reviewed-by: Matt Menke <[email protected]> Commit-Queue: Maks Orlovich <[email protected]> Cr-Commit-Position: refs/heads/master@{#547103} CWE ID: CWE-20
BackendImpl::BackendImpl( const base::FilePath& path, uint32_t mask, const scoped_refptr<base::SingleThreadTaskRunner>& cache_thread, net::NetLog* net_log) : background_queue_(this, FallbackToInternalIfNull(cache_thread)), path_(path), block_files_(path), mask_(mask), max_size_(0), up_ticks_(0), cache_type_(net::DISK_CACHE), uma_report_(0), user_flags_(kMask), init_(false), restarted_(false), unit_test_(false), read_only_(false), disabled_(false), new_eviction_(false), first_timer_(true), user_load_(false), consider_evicting_at_op_end_(false), net_log_(net_log), done_(base::WaitableEvent::ResetPolicy::MANUAL, base::WaitableEvent::InitialState::NOT_SIGNALED), ptr_factory_(this) {}
172,697
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void nfs4_open_prepare(struct rpc_task *task, void *calldata) { struct nfs4_opendata *data = calldata; struct nfs4_state_owner *sp = data->owner; if (nfs_wait_on_sequence(data->o_arg.seqid, task) != 0) return; /* * Check if we still need to send an OPEN call, or if we can use * a delegation instead. */ if (data->state != NULL) { struct nfs_delegation *delegation; if (can_open_cached(data->state, data->o_arg.open_flags & (FMODE_READ|FMODE_WRITE|O_EXCL))) goto out_no_action; rcu_read_lock(); delegation = rcu_dereference(NFS_I(data->state->inode)->delegation); if (delegation != NULL && test_bit(NFS_DELEGATION_NEED_RECLAIM, &delegation->flags) == 0) { rcu_read_unlock(); goto out_no_action; } rcu_read_unlock(); } /* Update sequence id. */ data->o_arg.id = sp->so_owner_id.id; data->o_arg.clientid = sp->so_client->cl_clientid; if (data->o_arg.claim == NFS4_OPEN_CLAIM_PREVIOUS) { task->tk_msg.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_OPEN_NOATTR]; nfs_copy_fh(&data->o_res.fh, data->o_arg.fh); } data->timestamp = jiffies; rpc_call_start(task); return; out_no_action: task->tk_action = NULL; } Commit Message: NFSv4: Convert the open and close ops to use fmode Signed-off-by: Trond Myklebust <[email protected]> CWE ID:
static void nfs4_open_prepare(struct rpc_task *task, void *calldata) { struct nfs4_opendata *data = calldata; struct nfs4_state_owner *sp = data->owner; if (nfs_wait_on_sequence(data->o_arg.seqid, task) != 0) return; /* * Check if we still need to send an OPEN call, or if we can use * a delegation instead. */ if (data->state != NULL) { struct nfs_delegation *delegation; if (can_open_cached(data->state, data->o_arg.fmode, data->o_arg.open_flags)) goto out_no_action; rcu_read_lock(); delegation = rcu_dereference(NFS_I(data->state->inode)->delegation); if (delegation != NULL && test_bit(NFS_DELEGATION_NEED_RECLAIM, &delegation->flags) == 0) { rcu_read_unlock(); goto out_no_action; } rcu_read_unlock(); } /* Update sequence id. */ data->o_arg.id = sp->so_owner_id.id; data->o_arg.clientid = sp->so_client->cl_clientid; if (data->o_arg.claim == NFS4_OPEN_CLAIM_PREVIOUS) { task->tk_msg.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_OPEN_NOATTR]; nfs_copy_fh(&data->o_res.fh, data->o_arg.fh); } data->timestamp = jiffies; rpc_call_start(task); return; out_no_action: task->tk_action = NULL; }
165,695
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: png_write_init_3(png_structpp ptr_ptr, png_const_charp user_png_ver, png_size_t png_struct_size) { png_structp png_ptr = *ptr_ptr; #ifdef PNG_SETJMP_SUPPORTED jmp_buf tmp_jmp; /* to save current jump buffer */ #endif int i = 0; if (png_ptr == NULL) return; do { if (user_png_ver[i] != png_libpng_ver[i]) { #ifdef PNG_LEGACY_SUPPORTED png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH; #else png_ptr->warning_fn = NULL; png_warning(png_ptr, "Application uses deprecated png_write_init() and should be recompiled."); #endif } i++; } while (png_libpng_ver[i] != 0 && user_png_ver[i] != 0); png_debug(1, "in png_write_init_3"); #ifdef PNG_SETJMP_SUPPORTED /* Save jump buffer and error functions */ png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof(jmp_buf)); #endif if (png_sizeof(png_struct) > png_struct_size) { png_destroy_struct(png_ptr); png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG); *ptr_ptr = png_ptr; } /* Reset all variables to 0 */ png_memset(png_ptr, 0, png_sizeof(png_struct)); /* Added at libpng-1.2.6 */ #ifdef PNG_SET_USER_LIMITS_SUPPORTED png_ptr->user_width_max = PNG_USER_WIDTH_MAX; png_ptr->user_height_max = PNG_USER_HEIGHT_MAX; #endif #ifdef PNG_SETJMP_SUPPORTED /* Restore jump buffer */ png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof(jmp_buf)); #endif png_set_write_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL, png_flush_ptr_NULL); /* Initialize zbuf - compression buffer */ png_ptr->zbuf_size = PNG_ZBUF_SIZE; png_ptr->zbuf = (png_bytep)png_malloc(png_ptr, (png_uint_32)png_ptr->zbuf_size); #ifdef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED png_set_filter_heuristics(png_ptr, PNG_FILTER_HEURISTIC_DEFAULT, 1, png_doublep_NULL, png_doublep_NULL); #endif } Commit Message: third_party/libpng: update to 1.2.54 [email protected] BUG=560291 Review URL: https://codereview.chromium.org/1467263003 Cr-Commit-Position: refs/heads/master@{#362298} CWE ID: CWE-119
png_write_init_3(png_structpp ptr_ptr, png_const_charp user_png_ver, png_size_t png_struct_size) { png_structp png_ptr = *ptr_ptr; #ifdef PNG_SETJMP_SUPPORTED jmp_buf tmp_jmp; /* to save current jump buffer */ #endif int i = 0; if (png_ptr == NULL) return; do { if (user_png_ver[i] != png_libpng_ver[i]) { #ifdef PNG_LEGACY_SUPPORTED png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH; #else png_ptr->warning_fn = NULL; png_warning(png_ptr, "Application uses deprecated png_write_init() and should be recompiled."); #endif } i++; } while (png_libpng_ver[i] != 0 && user_png_ver[i] != 0); png_debug(1, "in png_write_init_3"); #ifdef PNG_SETJMP_SUPPORTED /* Save jump buffer and error functions */ png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof(jmp_buf)); #endif if (png_sizeof(png_struct) > png_struct_size) { png_destroy_struct(png_ptr); png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG); *ptr_ptr = png_ptr; } /* Reset all variables to 0 */ png_memset(png_ptr, 0, png_sizeof(png_struct)); /* Added at libpng-1.2.6 */ #ifdef PNG_SET_USER_LIMITS_SUPPORTED png_ptr->user_width_max = PNG_USER_WIDTH_MAX; png_ptr->user_height_max = PNG_USER_HEIGHT_MAX; #endif #ifdef PNG_SETJMP_SUPPORTED /* Restore jump buffer */ png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof(jmp_buf)); #endif png_set_write_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL, png_flush_ptr_NULL); /* Initialize zbuf - compression buffer */ png_ptr->zbuf_size = PNG_ZBUF_SIZE; png_ptr->zbuf = (png_bytep)png_malloc(png_ptr, (png_uint_32)png_ptr->zbuf_size); }
172,190
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static Maybe<bool> IncludesValueImpl(Isolate* isolate, Handle<JSObject> object, Handle<Object> value, uint32_t start_from, uint32_t length) { DCHECK(JSObject::PrototypeHasNoElements(isolate, *object)); Handle<Map> original_map = handle(object->map(), isolate); Handle<FixedArray> parameter_map(FixedArray::cast(object->elements()), isolate); bool search_for_hole = value->IsUndefined(isolate); for (uint32_t k = start_from; k < length; ++k) { uint32_t entry = GetEntryForIndexImpl(isolate, *object, *parameter_map, k, ALL_PROPERTIES); if (entry == kMaxUInt32) { if (search_for_hole) return Just(true); continue; } Handle<Object> element_k = Subclass::GetImpl(isolate, *parameter_map, entry); if (element_k->IsAccessorPair()) { LookupIterator it(isolate, object, k, LookupIterator::OWN); DCHECK(it.IsFound()); DCHECK_EQ(it.state(), LookupIterator::ACCESSOR); ASSIGN_RETURN_ON_EXCEPTION_VALUE(isolate, element_k, Object::GetPropertyWithAccessor(&it), Nothing<bool>()); if (value->SameValueZero(*element_k)) return Just(true); if (object->map() != *original_map) { return IncludesValueSlowPath(isolate, object, value, k + 1, length); } } else if (value->SameValueZero(*element_k)) { return Just(true); } } return Just(false); } Commit Message: Backport: Fix Object.entries/values with changing elements Bug: 111274046 Test: m -j proxy_resolver_v8_unittest && adb sync && adb shell \ /data/nativetest64/proxy_resolver_v8_unittest/proxy_resolver_v8_unittest Change-Id: I705fc512cc5837e9364ed187559cc75d079aa5cb (cherry picked from commit d8be9a10287afed07705ac8af027d6a46d4def99) CWE ID: CWE-704
static Maybe<bool> IncludesValueImpl(Isolate* isolate, Handle<JSObject> object, Handle<Object> value, uint32_t start_from, uint32_t length) { DCHECK(JSObject::PrototypeHasNoElements(isolate, *object)); Handle<Map> original_map(object->map(), isolate); Handle<FixedArray> parameter_map(FixedArray::cast(object->elements()), isolate); bool search_for_hole = value->IsUndefined(isolate); for (uint32_t k = start_from; k < length; ++k) { DCHECK_EQ(object->map(), *original_map); uint32_t entry = GetEntryForIndexImpl(isolate, *object, *parameter_map, k, ALL_PROPERTIES); if (entry == kMaxUInt32) { if (search_for_hole) return Just(true); continue; } Handle<Object> element_k = Subclass::GetImpl(isolate, *parameter_map, entry); if (element_k->IsAccessorPair()) { LookupIterator it(isolate, object, k, LookupIterator::OWN); DCHECK(it.IsFound()); DCHECK_EQ(it.state(), LookupIterator::ACCESSOR); ASSIGN_RETURN_ON_EXCEPTION_VALUE(isolate, element_k, Object::GetPropertyWithAccessor(&it), Nothing<bool>()); if (value->SameValueZero(*element_k)) return Just(true); if (object->map() != *original_map) { return IncludesValueSlowPath(isolate, object, value, k + 1, length); } } else if (value->SameValueZero(*element_k)) { return Just(true); } } return Just(false); }
174,097
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int cqspi_setup_flash(struct cqspi_st *cqspi, struct device_node *np) { struct platform_device *pdev = cqspi->pdev; struct device *dev = &pdev->dev; struct cqspi_flash_pdata *f_pdata; struct spi_nor *nor; struct mtd_info *mtd; unsigned int cs; int i, ret; /* Get flash device data */ for_each_available_child_of_node(dev->of_node, np) { if (of_property_read_u32(np, "reg", &cs)) { dev_err(dev, "Couldn't determine chip select.\n"); goto err; } if (cs > CQSPI_MAX_CHIPSELECT) { dev_err(dev, "Chip select %d out of range.\n", cs); goto err; } f_pdata = &cqspi->f_pdata[cs]; f_pdata->cqspi = cqspi; f_pdata->cs = cs; ret = cqspi_of_get_flash_pdata(pdev, f_pdata, np); if (ret) goto err; nor = &f_pdata->nor; mtd = &nor->mtd; mtd->priv = nor; nor->dev = dev; spi_nor_set_flash_node(nor, np); nor->priv = f_pdata; nor->read_reg = cqspi_read_reg; nor->write_reg = cqspi_write_reg; nor->read = cqspi_read; nor->write = cqspi_write; nor->erase = cqspi_erase; nor->prepare = cqspi_prep; nor->unprepare = cqspi_unprep; mtd->name = devm_kasprintf(dev, GFP_KERNEL, "%s.%d", dev_name(dev), cs); if (!mtd->name) { ret = -ENOMEM; goto err; } ret = spi_nor_scan(nor, NULL, SPI_NOR_QUAD); if (ret) goto err; ret = mtd_device_register(mtd, NULL, 0); if (ret) goto err; f_pdata->registered = true; } return 0; err: for (i = 0; i < CQSPI_MAX_CHIPSELECT; i++) if (cqspi->f_pdata[i].registered) mtd_device_unregister(&cqspi->f_pdata[i].nor.mtd); return ret; } Commit Message: mtd: spi-nor: Off by one in cqspi_setup_flash() There are CQSPI_MAX_CHIPSELECT elements in the ->f_pdata array so the > should be >=. Fixes: 140623410536 ('mtd: spi-nor: Add driver for Cadence Quad SPI Flash Controller') Signed-off-by: Dan Carpenter <[email protected]> Reviewed-by: Marek Vasut <[email protected]> Signed-off-by: Cyrille Pitchen <[email protected]> CWE ID: CWE-119
static int cqspi_setup_flash(struct cqspi_st *cqspi, struct device_node *np) { struct platform_device *pdev = cqspi->pdev; struct device *dev = &pdev->dev; struct cqspi_flash_pdata *f_pdata; struct spi_nor *nor; struct mtd_info *mtd; unsigned int cs; int i, ret; /* Get flash device data */ for_each_available_child_of_node(dev->of_node, np) { if (of_property_read_u32(np, "reg", &cs)) { dev_err(dev, "Couldn't determine chip select.\n"); goto err; } if (cs >= CQSPI_MAX_CHIPSELECT) { dev_err(dev, "Chip select %d out of range.\n", cs); goto err; } f_pdata = &cqspi->f_pdata[cs]; f_pdata->cqspi = cqspi; f_pdata->cs = cs; ret = cqspi_of_get_flash_pdata(pdev, f_pdata, np); if (ret) goto err; nor = &f_pdata->nor; mtd = &nor->mtd; mtd->priv = nor; nor->dev = dev; spi_nor_set_flash_node(nor, np); nor->priv = f_pdata; nor->read_reg = cqspi_read_reg; nor->write_reg = cqspi_write_reg; nor->read = cqspi_read; nor->write = cqspi_write; nor->erase = cqspi_erase; nor->prepare = cqspi_prep; nor->unprepare = cqspi_unprep; mtd->name = devm_kasprintf(dev, GFP_KERNEL, "%s.%d", dev_name(dev), cs); if (!mtd->name) { ret = -ENOMEM; goto err; } ret = spi_nor_scan(nor, NULL, SPI_NOR_QUAD); if (ret) goto err; ret = mtd_device_register(mtd, NULL, 0); if (ret) goto err; f_pdata->registered = true; } return 0; err: for (i = 0; i < CQSPI_MAX_CHIPSELECT; i++) if (cqspi->f_pdata[i].registered) mtd_device_unregister(&cqspi->f_pdata[i].nor.mtd); return ret; }
169,861
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int SocketStream::HandleCertificateError(int result) { DCHECK(IsCertificateError(result)); SSLClientSocket* ssl_socket = static_cast<SSLClientSocket*>(socket_.get()); DCHECK(ssl_socket); if (!context_.get()) return result; if (SSLClientSocket::IgnoreCertError(result, LOAD_IGNORE_ALL_CERT_ERRORS)) { const HttpNetworkSession::Params* session_params = context_->GetNetworkSessionParams(); if (session_params && session_params->ignore_certificate_errors) return OK; } if (!delegate_) return result; SSLInfo ssl_info; ssl_socket->GetSSLInfo(&ssl_info); TransportSecurityState::DomainState domain_state; const bool fatal = context_->transport_security_state() && context_->transport_security_state()->GetDomainState(url_.host(), SSLConfigService::IsSNIAvailable(context_->ssl_config_service()), &domain_state) && domain_state.ShouldSSLErrorsBeFatal(); delegate_->OnSSLCertificateError(this, ssl_info, fatal); return ERR_IO_PENDING; } Commit Message: Revert a workaround commit for a Use-After-Free crash. Revert a workaround commit r20158 for a Use-After-Free issue (http://crbug.com/244746) because a cleaner CL r207218 is landed. URLRequestContext does not inherit SupportsWeakPtr now. R=mmenke BUG=244746 Review URL: https://chromiumcodereview.appspot.com/16870008 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@207811 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
int SocketStream::HandleCertificateError(int result) { DCHECK(IsCertificateError(result)); SSLClientSocket* ssl_socket = static_cast<SSLClientSocket*>(socket_.get()); DCHECK(ssl_socket); if (!context_) return result; if (SSLClientSocket::IgnoreCertError(result, LOAD_IGNORE_ALL_CERT_ERRORS)) { const HttpNetworkSession::Params* session_params = context_->GetNetworkSessionParams(); if (session_params && session_params->ignore_certificate_errors) return OK; } if (!delegate_) return result; SSLInfo ssl_info; ssl_socket->GetSSLInfo(&ssl_info); TransportSecurityState::DomainState domain_state; const bool fatal = context_->transport_security_state() && context_->transport_security_state()->GetDomainState(url_.host(), SSLConfigService::IsSNIAvailable(context_->ssl_config_service()), &domain_state) && domain_state.ShouldSSLErrorsBeFatal(); delegate_->OnSSLCertificateError(this, ssl_info, fatal); return ERR_IO_PENDING; }
171,255
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void __sock_recv_timestamp(struct msghdr *msg, struct sock *sk, struct sk_buff *skb) { int need_software_tstamp = sock_flag(sk, SOCK_RCVTSTAMP); struct scm_timestamping tss; int empty = 1; struct skb_shared_hwtstamps *shhwtstamps = skb_hwtstamps(skb); /* Race occurred between timestamp enabling and packet receiving. Fill in the current time for now. */ if (need_software_tstamp && skb->tstamp == 0) __net_timestamp(skb); if (need_software_tstamp) { if (!sock_flag(sk, SOCK_RCVTSTAMPNS)) { struct timeval tv; skb_get_timestamp(skb, &tv); put_cmsg(msg, SOL_SOCKET, SCM_TIMESTAMP, sizeof(tv), &tv); } else { struct timespec ts; skb_get_timestampns(skb, &ts); put_cmsg(msg, SOL_SOCKET, SCM_TIMESTAMPNS, sizeof(ts), &ts); } } memset(&tss, 0, sizeof(tss)); if ((sk->sk_tsflags & SOF_TIMESTAMPING_SOFTWARE) && ktime_to_timespec_cond(skb->tstamp, tss.ts + 0)) empty = 0; if (shhwtstamps && (sk->sk_tsflags & SOF_TIMESTAMPING_RAW_HARDWARE) && ktime_to_timespec_cond(shhwtstamps->hwtstamp, tss.ts + 2)) empty = 0; if (!empty) { put_cmsg(msg, SOL_SOCKET, SCM_TIMESTAMPING, sizeof(tss), &tss); if (skb_is_err_queue(skb) && skb->len && (sk->sk_tsflags & SOF_TIMESTAMPING_OPT_STATS)) put_cmsg(msg, SOL_SOCKET, SCM_TIMESTAMPING_OPT_STATS, skb->len, skb->data); } } Commit Message: tcp: mark skbs with SCM_TIMESTAMPING_OPT_STATS SOF_TIMESTAMPING_OPT_STATS can be enabled and disabled while packets are collected on the error queue. So, checking SOF_TIMESTAMPING_OPT_STATS in sk->sk_tsflags is not enough to safely assume that the skb contains OPT_STATS data. Add a bit in sock_exterr_skb to indicate whether the skb contains opt_stats data. Fixes: 1c885808e456 ("tcp: SOF_TIMESTAMPING_OPT_STATS option for SO_TIMESTAMPING") Reported-by: JongHwan Kim <[email protected]> Signed-off-by: Soheil Hassas Yeganeh <[email protected]> Signed-off-by: Eric Dumazet <[email protected]> Signed-off-by: Willem de Bruijn <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-125
void __sock_recv_timestamp(struct msghdr *msg, struct sock *sk, struct sk_buff *skb) { int need_software_tstamp = sock_flag(sk, SOCK_RCVTSTAMP); struct scm_timestamping tss; int empty = 1; struct skb_shared_hwtstamps *shhwtstamps = skb_hwtstamps(skb); /* Race occurred between timestamp enabling and packet receiving. Fill in the current time for now. */ if (need_software_tstamp && skb->tstamp == 0) __net_timestamp(skb); if (need_software_tstamp) { if (!sock_flag(sk, SOCK_RCVTSTAMPNS)) { struct timeval tv; skb_get_timestamp(skb, &tv); put_cmsg(msg, SOL_SOCKET, SCM_TIMESTAMP, sizeof(tv), &tv); } else { struct timespec ts; skb_get_timestampns(skb, &ts); put_cmsg(msg, SOL_SOCKET, SCM_TIMESTAMPNS, sizeof(ts), &ts); } } memset(&tss, 0, sizeof(tss)); if ((sk->sk_tsflags & SOF_TIMESTAMPING_SOFTWARE) && ktime_to_timespec_cond(skb->tstamp, tss.ts + 0)) empty = 0; if (shhwtstamps && (sk->sk_tsflags & SOF_TIMESTAMPING_RAW_HARDWARE) && ktime_to_timespec_cond(shhwtstamps->hwtstamp, tss.ts + 2)) empty = 0; if (!empty) { put_cmsg(msg, SOL_SOCKET, SCM_TIMESTAMPING, sizeof(tss), &tss); if (skb_is_err_queue(skb) && skb->len && SKB_EXT_ERR(skb)->opt_stats) put_cmsg(msg, SOL_SOCKET, SCM_TIMESTAMPING_OPT_STATS, skb->len, skb->data); } }
170,074
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void ImportGrayQuantum(const Image *image,QuantumInfo *quantum_info, const MagickSizeType number_pixels,const unsigned char *magick_restrict p, Quantum *magick_restrict q,ExceptionInfo *exception) { QuantumAny range; register ssize_t x; ssize_t bit; unsigned int pixel; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); switch (quantum_info->depth) { case 1: { register Quantum black, white; black=0; white=QuantumRange; if (quantum_info->min_is_white != MagickFalse) { black=QuantumRange; white=0; } for (x=0; x < ((ssize_t) number_pixels-7); x+=8) { for (bit=0; bit < 8; bit++) { SetPixelGray(image,((*p) & (1 << (7-bit))) == 0 ? black : white,q); q+=GetPixelChannels(image); } p++; } for (bit=0; bit < (ssize_t) (number_pixels % 8); bit++) { SetPixelGray(image,((*p) & (0x01 << (7-bit))) == 0 ? black : white,q); q+=GetPixelChannels(image); } if (bit != 0) p++; break; } case 4: { register unsigned char pixel; range=GetQuantumRange(quantum_info->depth); for (x=0; x < ((ssize_t) number_pixels-1); x+=2) { pixel=(unsigned char) ((*p >> 4) & 0xf); SetPixelGray(image,ScaleAnyToQuantum(pixel,range),q); q+=GetPixelChannels(image); pixel=(unsigned char) ((*p) & 0xf); SetPixelGray(image,ScaleAnyToQuantum(pixel,range),q); p++; q+=GetPixelChannels(image); } for (bit=0; bit < (ssize_t) (number_pixels % 2); bit++) { pixel=(unsigned char) (*p++ >> 4); SetPixelGray(image,ScaleAnyToQuantum(pixel,range),q); q+=GetPixelChannels(image); } break; } case 8: { unsigned char pixel; if (quantum_info->min_is_white != MagickFalse) { for (x=0; x < (ssize_t) number_pixels; x++) { p=PushCharPixel(p,&pixel); SetPixelGray(image,ScaleCharToQuantum(pixel),q); SetPixelAlpha(image,OpaqueAlpha,q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } for (x=0; x < (ssize_t) number_pixels; x++) { p=PushCharPixel(p,&pixel); SetPixelGray(image,ScaleCharToQuantum(pixel),q); SetPixelAlpha(image,OpaqueAlpha,q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } case 10: { range=GetQuantumRange(quantum_info->depth); if (quantum_info->pack == MagickFalse) { if (image->endian == LSBEndian) { for (x=0; x < (ssize_t) (number_pixels-2); x+=3) { p=PushLongPixel(quantum_info->endian,p,&pixel); SetPixelGray(image,ScaleAnyToQuantum((pixel >> 22) & 0x3ff, range),q); q+=GetPixelChannels(image); SetPixelGray(image,ScaleAnyToQuantum((pixel >> 12) & 0x3ff, range),q); q+=GetPixelChannels(image); SetPixelGray(image,ScaleAnyToQuantum((pixel >> 2) & 0x3ff, range),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } p=PushLongPixel(quantum_info->endian,p,&pixel); if (x++ < (ssize_t) (number_pixels-1)) { SetPixelGray(image,ScaleAnyToQuantum((pixel >> 22) & 0x3ff, range),q); q+=GetPixelChannels(image); } if (x++ < (ssize_t) number_pixels) { SetPixelGray(image,ScaleAnyToQuantum((pixel >> 12) & 0x3ff, range),q); q+=GetPixelChannels(image); } break; } for (x=0; x < (ssize_t) (number_pixels-2); x+=3) { p=PushLongPixel(quantum_info->endian,p,&pixel); SetPixelGray(image,ScaleAnyToQuantum((pixel >> 2) & 0x3ff,range), q); q+=GetPixelChannels(image); SetPixelGray(image,ScaleAnyToQuantum((pixel >> 12) & 0x3ff,range), q); q+=GetPixelChannels(image); SetPixelGray(image,ScaleAnyToQuantum((pixel >> 22) & 0x3ff,range), q); p+=quantum_info->pad; q+=GetPixelChannels(image); } p=PushLongPixel(quantum_info->endian,p,&pixel); if (x++ < (ssize_t) (number_pixels-1)) { SetPixelGray(image,ScaleAnyToQuantum((pixel >> 2) & 0x3ff, range),q); q+=GetPixelChannels(image); } if (x++ < (ssize_t) number_pixels) { SetPixelGray(image,ScaleAnyToQuantum((pixel >> 12) & 0x3ff, range),q); q+=GetPixelChannels(image); } break; } for (x=0; x < (ssize_t) number_pixels; x++) { p=PushQuantumPixel(quantum_info,p,&pixel); SetPixelGray(image,ScaleAnyToQuantum(pixel,range),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } case 12: { range=GetQuantumRange(quantum_info->depth); if (quantum_info->pack == MagickFalse) { unsigned short pixel; for (x=0; x < (ssize_t) (number_pixels-1); x+=2) { p=PushShortPixel(quantum_info->endian,p,&pixel); SetPixelGray(image,ScaleAnyToQuantum((QuantumAny) (pixel >> 4), range),q); q+=GetPixelChannels(image); p=PushShortPixel(quantum_info->endian,p,&pixel); SetPixelGray(image,ScaleAnyToQuantum((QuantumAny) (pixel >> 4), range),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } for (bit=0; bit < (ssize_t) (number_pixels % 2); bit++) { p=PushShortPixel(quantum_info->endian,p,&pixel); SetPixelGray(image,ScaleAnyToQuantum((QuantumAny) (pixel >> 4), range),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } if (bit != 0) p++; break; } for (x=0; x < (ssize_t) number_pixels; x++) { p=PushQuantumPixel(quantum_info,p,&pixel); SetPixelGray(image,ScaleAnyToQuantum(pixel,range),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } case 16: { unsigned short pixel; if (quantum_info->min_is_white != MagickFalse) { for (x=0; x < (ssize_t) number_pixels; x++) { p=PushShortPixel(quantum_info->endian,p,&pixel); SetPixelGray(image,ScaleShortToQuantum(pixel),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } if (quantum_info->format == FloatingPointQuantumFormat) { for (x=0; x < (ssize_t) number_pixels; x++) { p=PushShortPixel(quantum_info->endian,p,&pixel); SetPixelGray(image,ClampToQuantum(QuantumRange* HalfToSinglePrecision(pixel)),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } for (x=0; x < (ssize_t) number_pixels; x++) { p=PushShortPixel(quantum_info->endian,p,&pixel); SetPixelGray(image,ScaleShortToQuantum(pixel),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } case 32: { unsigned int pixel; if (quantum_info->format == FloatingPointQuantumFormat) { float pixel; for (x=0; x < (ssize_t) number_pixels; x++) { p=PushFloatPixel(quantum_info,p,&pixel); SetPixelGray(image,ClampToQuantum(pixel),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } for (x=0; x < (ssize_t) number_pixels; x++) { p=PushLongPixel(quantum_info->endian,p,&pixel); SetPixelGray(image,ScaleLongToQuantum(pixel),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } case 64: { if (quantum_info->format == FloatingPointQuantumFormat) { double pixel; for (x=0; x < (ssize_t) number_pixels; x++) { p=PushDoublePixel(quantum_info,p,&pixel); SetPixelGray(image,ClampToQuantum(pixel),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } } default: { range=GetQuantumRange(quantum_info->depth); for (x=0; x < (ssize_t) number_pixels; x++) { p=PushQuantumPixel(quantum_info,p,&pixel); SetPixelGray(image,ScaleAnyToQuantum(pixel,range),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } } } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/129 CWE ID: CWE-284
static void ImportGrayQuantum(const Image *image,QuantumInfo *quantum_info, const MagickSizeType number_pixels,const unsigned char *magick_restrict p, Quantum *magick_restrict q,ExceptionInfo *exception) { QuantumAny range; register ssize_t x; ssize_t bit; unsigned int pixel; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); pixel=0; switch (quantum_info->depth) { case 1: { register Quantum black, white; black=0; white=QuantumRange; if (quantum_info->min_is_white != MagickFalse) { black=QuantumRange; white=0; } for (x=0; x < ((ssize_t) number_pixels-7); x+=8) { for (bit=0; bit < 8; bit++) { SetPixelGray(image,((*p) & (1 << (7-bit))) == 0 ? black : white,q); q+=GetPixelChannels(image); } p++; } for (bit=0; bit < (ssize_t) (number_pixels % 8); bit++) { SetPixelGray(image,((*p) & (0x01 << (7-bit))) == 0 ? black : white,q); q+=GetPixelChannels(image); } if (bit != 0) p++; break; } case 4: { register unsigned char pixel; range=GetQuantumRange(quantum_info->depth); for (x=0; x < ((ssize_t) number_pixels-1); x+=2) { pixel=(unsigned char) ((*p >> 4) & 0xf); SetPixelGray(image,ScaleAnyToQuantum(pixel,range),q); q+=GetPixelChannels(image); pixel=(unsigned char) ((*p) & 0xf); SetPixelGray(image,ScaleAnyToQuantum(pixel,range),q); p++; q+=GetPixelChannels(image); } for (bit=0; bit < (ssize_t) (number_pixels % 2); bit++) { pixel=(unsigned char) (*p++ >> 4); SetPixelGray(image,ScaleAnyToQuantum(pixel,range),q); q+=GetPixelChannels(image); } break; } case 8: { unsigned char pixel; if (quantum_info->min_is_white != MagickFalse) { for (x=0; x < (ssize_t) number_pixels; x++) { p=PushCharPixel(p,&pixel); SetPixelGray(image,ScaleCharToQuantum(pixel),q); SetPixelAlpha(image,OpaqueAlpha,q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } for (x=0; x < (ssize_t) number_pixels; x++) { p=PushCharPixel(p,&pixel); SetPixelGray(image,ScaleCharToQuantum(pixel),q); SetPixelAlpha(image,OpaqueAlpha,q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } case 10: { range=GetQuantumRange(quantum_info->depth); if (quantum_info->pack == MagickFalse) { if (image->endian == LSBEndian) { for (x=0; x < (ssize_t) (number_pixels-2); x+=3) { p=PushLongPixel(quantum_info->endian,p,&pixel); SetPixelGray(image,ScaleAnyToQuantum((pixel >> 22) & 0x3ff, range),q); q+=GetPixelChannels(image); SetPixelGray(image,ScaleAnyToQuantum((pixel >> 12) & 0x3ff, range),q); q+=GetPixelChannels(image); SetPixelGray(image,ScaleAnyToQuantum((pixel >> 2) & 0x3ff, range),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } p=PushLongPixel(quantum_info->endian,p,&pixel); if (x++ < (ssize_t) (number_pixels-1)) { SetPixelGray(image,ScaleAnyToQuantum((pixel >> 22) & 0x3ff, range),q); q+=GetPixelChannels(image); } if (x++ < (ssize_t) number_pixels) { SetPixelGray(image,ScaleAnyToQuantum((pixel >> 12) & 0x3ff, range),q); q+=GetPixelChannels(image); } break; } for (x=0; x < (ssize_t) (number_pixels-2); x+=3) { p=PushLongPixel(quantum_info->endian,p,&pixel); SetPixelGray(image,ScaleAnyToQuantum((pixel >> 2) & 0x3ff,range), q); q+=GetPixelChannels(image); SetPixelGray(image,ScaleAnyToQuantum((pixel >> 12) & 0x3ff,range), q); q+=GetPixelChannels(image); SetPixelGray(image,ScaleAnyToQuantum((pixel >> 22) & 0x3ff,range), q); p+=quantum_info->pad; q+=GetPixelChannels(image); } p=PushLongPixel(quantum_info->endian,p,&pixel); if (x++ < (ssize_t) (number_pixels-1)) { SetPixelGray(image,ScaleAnyToQuantum((pixel >> 2) & 0x3ff, range),q); q+=GetPixelChannels(image); } if (x++ < (ssize_t) number_pixels) { SetPixelGray(image,ScaleAnyToQuantum((pixel >> 12) & 0x3ff, range),q); q+=GetPixelChannels(image); } break; } for (x=0; x < (ssize_t) number_pixels; x++) { p=PushQuantumPixel(quantum_info,p,&pixel); SetPixelGray(image,ScaleAnyToQuantum(pixel,range),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } case 12: { range=GetQuantumRange(quantum_info->depth); if (quantum_info->pack == MagickFalse) { unsigned short pixel; for (x=0; x < (ssize_t) (number_pixels-1); x+=2) { p=PushShortPixel(quantum_info->endian,p,&pixel); SetPixelGray(image,ScaleAnyToQuantum((QuantumAny) (pixel >> 4), range),q); q+=GetPixelChannels(image); p=PushShortPixel(quantum_info->endian,p,&pixel); SetPixelGray(image,ScaleAnyToQuantum((QuantumAny) (pixel >> 4), range),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } for (bit=0; bit < (ssize_t) (number_pixels % 2); bit++) { p=PushShortPixel(quantum_info->endian,p,&pixel); SetPixelGray(image,ScaleAnyToQuantum((QuantumAny) (pixel >> 4), range),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } if (bit != 0) p++; break; } for (x=0; x < (ssize_t) number_pixels; x++) { p=PushQuantumPixel(quantum_info,p,&pixel); SetPixelGray(image,ScaleAnyToQuantum(pixel,range),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } case 16: { unsigned short pixel; if (quantum_info->min_is_white != MagickFalse) { for (x=0; x < (ssize_t) number_pixels; x++) { p=PushShortPixel(quantum_info->endian,p,&pixel); SetPixelGray(image,ScaleShortToQuantum(pixel),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } if (quantum_info->format == FloatingPointQuantumFormat) { for (x=0; x < (ssize_t) number_pixels; x++) { p=PushShortPixel(quantum_info->endian,p,&pixel); SetPixelGray(image,ClampToQuantum(QuantumRange* HalfToSinglePrecision(pixel)),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } for (x=0; x < (ssize_t) number_pixels; x++) { p=PushShortPixel(quantum_info->endian,p,&pixel); SetPixelGray(image,ScaleShortToQuantum(pixel),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } case 32: { unsigned int pixel; if (quantum_info->format == FloatingPointQuantumFormat) { float pixel; for (x=0; x < (ssize_t) number_pixels; x++) { p=PushFloatPixel(quantum_info,p,&pixel); SetPixelGray(image,ClampToQuantum(pixel),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } for (x=0; x < (ssize_t) number_pixels; x++) { p=PushLongPixel(quantum_info->endian,p,&pixel); SetPixelGray(image,ScaleLongToQuantum(pixel),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } case 64: { if (quantum_info->format == FloatingPointQuantumFormat) { double pixel; for (x=0; x < (ssize_t) number_pixels; x++) { p=PushDoublePixel(quantum_info,p,&pixel); SetPixelGray(image,ClampToQuantum(pixel),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } } default: { range=GetQuantumRange(quantum_info->depth); for (x=0; x < (ssize_t) number_pixels; x++) { p=PushQuantumPixel(quantum_info,p,&pixel); SetPixelGray(image,ScaleAnyToQuantum(pixel,range),q); p+=quantum_info->pad; q+=GetPixelChannels(image); } break; } } }
168,623
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: opj_image_t* bmptoimage(const char *filename, opj_cparameters_t *parameters) { opj_image_cmptparm_t cmptparm[4]; /* maximum of 4 components */ OPJ_UINT8 lut_R[256], lut_G[256], lut_B[256]; OPJ_UINT8 const* pLUT[3]; opj_image_t * image = NULL; FILE *IN; OPJ_BITMAPFILEHEADER File_h; OPJ_BITMAPINFOHEADER Info_h; OPJ_UINT32 i, palette_len, numcmpts = 1U; OPJ_BOOL l_result = OPJ_FALSE; OPJ_UINT8* pData = NULL; OPJ_UINT32 stride; pLUT[0] = lut_R; pLUT[1] = lut_G; pLUT[2] = lut_B; IN = fopen(filename, "rb"); if (!IN) { fprintf(stderr, "Failed to open %s for reading !!\n", filename); return NULL; } if (!bmp_read_file_header(IN, &File_h)) { fclose(IN); return NULL; } if (!bmp_read_info_header(IN, &Info_h)) { fclose(IN); return NULL; } /* Load palette */ if (Info_h.biBitCount <= 8U) { memset(&lut_R[0], 0, sizeof(lut_R)); memset(&lut_G[0], 0, sizeof(lut_G)); memset(&lut_B[0], 0, sizeof(lut_B)); palette_len = Info_h.biClrUsed; if((palette_len == 0U) && (Info_h.biBitCount <= 8U)) { palette_len = (1U << Info_h.biBitCount); } if (palette_len > 256U) { palette_len = 256U; } if (palette_len > 0U) { OPJ_UINT8 has_color = 0U; for (i = 0U; i < palette_len; i++) { lut_B[i] = (OPJ_UINT8)getc(IN); lut_G[i] = (OPJ_UINT8)getc(IN); lut_R[i] = (OPJ_UINT8)getc(IN); (void)getc(IN); /* padding */ has_color |= (lut_B[i] ^ lut_G[i]) | (lut_G[i] ^ lut_R[i]); } if(has_color) { numcmpts = 3U; } } } else { numcmpts = 3U; if ((Info_h.biCompression == 3) && (Info_h.biAlphaMask != 0U)) { numcmpts++; } } stride = ((Info_h.biWidth * Info_h.biBitCount + 31U) / 32U) * 4U; /* rows are aligned on 32bits */ if (Info_h.biBitCount == 4 && Info_h.biCompression == 2) { /* RLE 4 gets decoded as 8 bits data for now... */ stride = ((Info_h.biWidth * 8U + 31U) / 32U) * 4U; } pData = (OPJ_UINT8 *) calloc(1, stride * Info_h.biHeight * sizeof(OPJ_UINT8)); if (pData == NULL) { fclose(IN); return NULL; } /* Place the cursor at the beginning of the image information */ fseek(IN, 0, SEEK_SET); fseek(IN, (long)File_h.bfOffBits, SEEK_SET); switch (Info_h.biCompression) { case 0: case 3: /* read raw data */ l_result = bmp_read_raw_data(IN, pData, stride, Info_h.biWidth, Info_h.biHeight); break; case 1: /* read rle8 data */ l_result = bmp_read_rle8_data(IN, pData, stride, Info_h.biWidth, Info_h.biHeight); break; case 2: /* read rle4 data */ l_result = bmp_read_rle4_data(IN, pData, stride, Info_h.biWidth, Info_h.biHeight); break; default: fprintf(stderr, "Unsupported BMP compression\n"); l_result = OPJ_FALSE; break; } if (!l_result) { free(pData); fclose(IN); return NULL; } /* create the image */ memset(&cmptparm[0], 0, sizeof(cmptparm)); for(i = 0; i < 4U; i++) { cmptparm[i].prec = 8; cmptparm[i].bpp = 8; cmptparm[i].sgnd = 0; cmptparm[i].dx = (OPJ_UINT32)parameters->subsampling_dx; cmptparm[i].dy = (OPJ_UINT32)parameters->subsampling_dy; cmptparm[i].w = Info_h.biWidth; cmptparm[i].h = Info_h.biHeight; } image = opj_image_create(numcmpts, &cmptparm[0], (numcmpts == 1U) ? OPJ_CLRSPC_GRAY : OPJ_CLRSPC_SRGB); if(!image) { fclose(IN); free(pData); return NULL; } if (numcmpts == 4U) { image->comps[3].alpha = 1; } /* set image offset and reference grid */ image->x0 = (OPJ_UINT32)parameters->image_offset_x0; image->y0 = (OPJ_UINT32)parameters->image_offset_y0; image->x1 = image->x0 + (Info_h.biWidth - 1U) * (OPJ_UINT32)parameters->subsampling_dx + 1U; image->y1 = image->y0 + (Info_h.biHeight - 1U) * (OPJ_UINT32)parameters->subsampling_dy + 1U; /* Read the data */ if (Info_h.biBitCount == 24 && Info_h.biCompression == 0) { /*RGB */ bmp24toimage(pData, stride, image); } else if (Info_h.biBitCount == 8 && Info_h.biCompression == 0) { /* RGB 8bpp Indexed */ bmp8toimage(pData, stride, image, pLUT); } else if (Info_h.biBitCount == 8 && Info_h.biCompression == 1) { /*RLE8*/ bmp8toimage(pData, stride, image, pLUT); } else if (Info_h.biBitCount == 4 && Info_h.biCompression == 2) { /*RLE4*/ bmp8toimage(pData, stride, image, pLUT); /* RLE 4 gets decoded as 8 bits data for now */ } else if (Info_h.biBitCount == 32 && Info_h.biCompression == 0) { /* RGBX */ bmpmask32toimage(pData, stride, image, 0x00FF0000U, 0x0000FF00U, 0x000000FFU, 0x00000000U); } else if (Info_h.biBitCount == 32 && Info_h.biCompression == 3) { /* bitmask */ bmpmask32toimage(pData, stride, image, Info_h.biRedMask, Info_h.biGreenMask, Info_h.biBlueMask, Info_h.biAlphaMask); } else if (Info_h.biBitCount == 16 && Info_h.biCompression == 0) { /* RGBX */ bmpmask16toimage(pData, stride, image, 0x7C00U, 0x03E0U, 0x001FU, 0x0000U); } else if (Info_h.biBitCount == 16 && Info_h.biCompression == 3) { /* bitmask */ if ((Info_h.biRedMask == 0U) && (Info_h.biGreenMask == 0U) && (Info_h.biBlueMask == 0U)) { Info_h.biRedMask = 0xF800U; Info_h.biGreenMask = 0x07E0U; Info_h.biBlueMask = 0x001FU; } bmpmask16toimage(pData, stride, image, Info_h.biRedMask, Info_h.biGreenMask, Info_h.biBlueMask, Info_h.biAlphaMask); } else { opj_image_destroy(image); image = NULL; fprintf(stderr, "Other system than 24 bits/pixels or 8 bits (no RLE coding) is not yet implemented [%d]\n", Info_h.biBitCount); } free(pData); fclose(IN); return image; } Commit Message: Merge pull request #834 from trylab/issue833 Fix issue 833. CWE ID: CWE-190
opj_image_t* bmptoimage(const char *filename, opj_cparameters_t *parameters) { opj_image_cmptparm_t cmptparm[4]; /* maximum of 4 components */ OPJ_UINT8 lut_R[256], lut_G[256], lut_B[256]; OPJ_UINT8 const* pLUT[3]; opj_image_t * image = NULL; FILE *IN; OPJ_BITMAPFILEHEADER File_h; OPJ_BITMAPINFOHEADER Info_h; OPJ_UINT32 i, palette_len, numcmpts = 1U; OPJ_BOOL l_result = OPJ_FALSE; OPJ_UINT8* pData = NULL; OPJ_UINT32 stride; pLUT[0] = lut_R; pLUT[1] = lut_G; pLUT[2] = lut_B; IN = fopen(filename, "rb"); if (!IN) { fprintf(stderr, "Failed to open %s for reading !!\n", filename); return NULL; } if (!bmp_read_file_header(IN, &File_h)) { fclose(IN); return NULL; } if (!bmp_read_info_header(IN, &Info_h)) { fclose(IN); return NULL; } /* Load palette */ if (Info_h.biBitCount <= 8U) { memset(&lut_R[0], 0, sizeof(lut_R)); memset(&lut_G[0], 0, sizeof(lut_G)); memset(&lut_B[0], 0, sizeof(lut_B)); palette_len = Info_h.biClrUsed; if((palette_len == 0U) && (Info_h.biBitCount <= 8U)) { palette_len = (1U << Info_h.biBitCount); } if (palette_len > 256U) { palette_len = 256U; } if (palette_len > 0U) { OPJ_UINT8 has_color = 0U; for (i = 0U; i < palette_len; i++) { lut_B[i] = (OPJ_UINT8)getc(IN); lut_G[i] = (OPJ_UINT8)getc(IN); lut_R[i] = (OPJ_UINT8)getc(IN); (void)getc(IN); /* padding */ has_color |= (lut_B[i] ^ lut_G[i]) | (lut_G[i] ^ lut_R[i]); } if(has_color) { numcmpts = 3U; } } } else { numcmpts = 3U; if ((Info_h.biCompression == 3) && (Info_h.biAlphaMask != 0U)) { numcmpts++; } } if (Info_h.biWidth == 0 || Info_h.biHeight == 0) { fclose(IN); return NULL; } if (Info_h.biBitCount > (((OPJ_UINT32)-1) - 31) / Info_h.biWidth) { fclose(IN); return NULL; } stride = ((Info_h.biWidth * Info_h.biBitCount + 31U) / 32U) * 4U; /* rows are aligned on 32bits */ if (Info_h.biBitCount == 4 && Info_h.biCompression == 2) { /* RLE 4 gets decoded as 8 bits data for now... */ if (8 > (((OPJ_UINT32)-1) - 31) / Info_h.biWidth) { fclose(IN); return NULL; } stride = ((Info_h.biWidth * 8U + 31U) / 32U) * 4U; } if (stride > ((OPJ_UINT32)-1) / sizeof(OPJ_UINT8) / Info_h.biHeight) { fclose(IN); return NULL; } pData = (OPJ_UINT8 *) calloc(1, stride * Info_h.biHeight * sizeof(OPJ_UINT8)); if (pData == NULL) { fclose(IN); return NULL; } /* Place the cursor at the beginning of the image information */ fseek(IN, 0, SEEK_SET); fseek(IN, (long)File_h.bfOffBits, SEEK_SET); switch (Info_h.biCompression) { case 0: case 3: /* read raw data */ l_result = bmp_read_raw_data(IN, pData, stride, Info_h.biWidth, Info_h.biHeight); break; case 1: /* read rle8 data */ l_result = bmp_read_rle8_data(IN, pData, stride, Info_h.biWidth, Info_h.biHeight); break; case 2: /* read rle4 data */ l_result = bmp_read_rle4_data(IN, pData, stride, Info_h.biWidth, Info_h.biHeight); break; default: fprintf(stderr, "Unsupported BMP compression\n"); l_result = OPJ_FALSE; break; } if (!l_result) { free(pData); fclose(IN); return NULL; } /* create the image */ memset(&cmptparm[0], 0, sizeof(cmptparm)); for(i = 0; i < 4U; i++) { cmptparm[i].prec = 8; cmptparm[i].bpp = 8; cmptparm[i].sgnd = 0; cmptparm[i].dx = (OPJ_UINT32)parameters->subsampling_dx; cmptparm[i].dy = (OPJ_UINT32)parameters->subsampling_dy; cmptparm[i].w = Info_h.biWidth; cmptparm[i].h = Info_h.biHeight; } image = opj_image_create(numcmpts, &cmptparm[0], (numcmpts == 1U) ? OPJ_CLRSPC_GRAY : OPJ_CLRSPC_SRGB); if(!image) { fclose(IN); free(pData); return NULL; } if (numcmpts == 4U) { image->comps[3].alpha = 1; } /* set image offset and reference grid */ image->x0 = (OPJ_UINT32)parameters->image_offset_x0; image->y0 = (OPJ_UINT32)parameters->image_offset_y0; image->x1 = image->x0 + (Info_h.biWidth - 1U) * (OPJ_UINT32)parameters->subsampling_dx + 1U; image->y1 = image->y0 + (Info_h.biHeight - 1U) * (OPJ_UINT32)parameters->subsampling_dy + 1U; /* Read the data */ if (Info_h.biBitCount == 24 && Info_h.biCompression == 0) { /*RGB */ bmp24toimage(pData, stride, image); } else if (Info_h.biBitCount == 8 && Info_h.biCompression == 0) { /* RGB 8bpp Indexed */ bmp8toimage(pData, stride, image, pLUT); } else if (Info_h.biBitCount == 8 && Info_h.biCompression == 1) { /*RLE8*/ bmp8toimage(pData, stride, image, pLUT); } else if (Info_h.biBitCount == 4 && Info_h.biCompression == 2) { /*RLE4*/ bmp8toimage(pData, stride, image, pLUT); /* RLE 4 gets decoded as 8 bits data for now */ } else if (Info_h.biBitCount == 32 && Info_h.biCompression == 0) { /* RGBX */ bmpmask32toimage(pData, stride, image, 0x00FF0000U, 0x0000FF00U, 0x000000FFU, 0x00000000U); } else if (Info_h.biBitCount == 32 && Info_h.biCompression == 3) { /* bitmask */ bmpmask32toimage(pData, stride, image, Info_h.biRedMask, Info_h.biGreenMask, Info_h.biBlueMask, Info_h.biAlphaMask); } else if (Info_h.biBitCount == 16 && Info_h.biCompression == 0) { /* RGBX */ bmpmask16toimage(pData, stride, image, 0x7C00U, 0x03E0U, 0x001FU, 0x0000U); } else if (Info_h.biBitCount == 16 && Info_h.biCompression == 3) { /* bitmask */ if ((Info_h.biRedMask == 0U) && (Info_h.biGreenMask == 0U) && (Info_h.biBlueMask == 0U)) { Info_h.biRedMask = 0xF800U; Info_h.biGreenMask = 0x07E0U; Info_h.biBlueMask = 0x001FU; } bmpmask16toimage(pData, stride, image, Info_h.biRedMask, Info_h.biGreenMask, Info_h.biBlueMask, Info_h.biAlphaMask); } else { opj_image_destroy(image); image = NULL; fprintf(stderr, "Other system than 24 bits/pixels or 8 bits (no RLE coding) is not yet implemented [%d]\n", Info_h.biBitCount); } free(pData); fclose(IN); return image; }
168,454
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void ext4_end_io_work(struct work_struct *work) { ext4_io_end_t *io = container_of(work, ext4_io_end_t, work); struct inode *inode = io->inode; int ret = 0; mutex_lock(&inode->i_mutex); ret = ext4_end_io_nolock(io); if (ret >= 0) { if (!list_empty(&io->list)) list_del_init(&io->list); ext4_free_io_end(io); } mutex_unlock(&inode->i_mutex); } Commit Message: ext4: use ext4_get_block_write in buffer write Allocate uninitialized extent before ext4 buffer write and convert the extent to initialized after io completes. The purpose is to make sure an extent can only be marked initialized after it has been written with new data so we can safely drop the i_mutex lock in ext4 DIO read without exposing stale data. This helps to improve multi-thread DIO read performance on high-speed disks. Skip the nobh and data=journal mount cases to make things simple for now. Signed-off-by: Jiaying Zhang <[email protected]> Signed-off-by: "Theodore Ts'o" <[email protected]> CWE ID:
static void ext4_end_io_work(struct work_struct *work) { ext4_io_end_t *io = container_of(work, ext4_io_end_t, work); struct inode *inode = io->inode; struct ext4_inode_info *ei = EXT4_I(inode); unsigned long flags; int ret; mutex_lock(&inode->i_mutex); ret = ext4_end_io_nolock(io); if (ret < 0) { mutex_unlock(&inode->i_mutex); return; } spin_lock_irqsave(&ei->i_completed_io_lock, flags); if (!list_empty(&io->list)) list_del_init(&io->list); spin_unlock_irqrestore(&ei->i_completed_io_lock, flags); mutex_unlock(&inode->i_mutex); ext4_free_io_end(io); }
167,542
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: DECLAREwriteFunc(writeBufferToContigTiles) { uint32 imagew = TIFFScanlineSize(out); uint32 tilew = TIFFTileRowSize(out); int iskew = imagew - tilew; tsize_t tilesize = TIFFTileSize(out); tdata_t obuf; uint8* bufp = (uint8*) buf; uint32 tl, tw; uint32 row; (void) spp; obuf = _TIFFmalloc(TIFFTileSize(out)); if (obuf == NULL) return 0; _TIFFmemset(obuf, 0, tilesize); (void) TIFFGetField(out, TIFFTAG_TILELENGTH, &tl); (void) TIFFGetField(out, TIFFTAG_TILEWIDTH, &tw); for (row = 0; row < imagelength; row += tilelength) { uint32 nrow = (row+tl > imagelength) ? imagelength-row : tl; uint32 colb = 0; uint32 col; for (col = 0; col < imagewidth; col += tw) { /* * Tile is clipped horizontally. Calculate * visible portion and skewing factors. */ if (colb + tilew > imagew) { uint32 width = imagew - colb; int oskew = tilew - width; cpStripToTile(obuf, bufp + colb, nrow, width, oskew, oskew + iskew); } else cpStripToTile(obuf, bufp + colb, nrow, tilew, 0, iskew); if (TIFFWriteTile(out, obuf, col, row, 0, 0) < 0) { TIFFError(TIFFFileName(out), "Error, can't write tile at %lu %lu", (unsigned long) col, (unsigned long) row); _TIFFfree(obuf); return 0; } colb += tilew; } bufp += nrow * imagew; } _TIFFfree(obuf); return 1; } Commit Message: * tools/tiffcp.c: fix out-of-bounds write on tiled images with odd tile width vs image width. Reported as MSVR 35103 by Axel Souchet and Vishal Chauhan from the MSRC Vulnerabilities & Mitigations team. CWE ID: CWE-787
DECLAREwriteFunc(writeBufferToContigTiles) { uint32 imagew = TIFFScanlineSize(out); uint32 tilew = TIFFTileRowSize(out); int iskew = imagew - tilew; tsize_t tilesize = TIFFTileSize(out); tdata_t obuf; uint8* bufp = (uint8*) buf; uint32 tl, tw; uint32 row; (void) spp; obuf = _TIFFmalloc(TIFFTileSize(out)); if (obuf == NULL) return 0; _TIFFmemset(obuf, 0, tilesize); (void) TIFFGetField(out, TIFFTAG_TILELENGTH, &tl); (void) TIFFGetField(out, TIFFTAG_TILEWIDTH, &tw); for (row = 0; row < imagelength; row += tilelength) { uint32 nrow = (row+tl > imagelength) ? imagelength-row : tl; uint32 colb = 0; uint32 col; for (col = 0; col < imagewidth && colb < imagew; col += tw) { /* * Tile is clipped horizontally. Calculate * visible portion and skewing factors. */ if (colb + tilew > imagew) { uint32 width = imagew - colb; int oskew = tilew - width; cpStripToTile(obuf, bufp + colb, nrow, width, oskew, oskew + iskew); } else cpStripToTile(obuf, bufp + colb, nrow, tilew, 0, iskew); if (TIFFWriteTile(out, obuf, col, row, 0, 0) < 0) { TIFFError(TIFFFileName(out), "Error, can't write tile at %lu %lu", (unsigned long) col, (unsigned long) row); _TIFFfree(obuf); return 0; } colb += tilew; } bufp += nrow * imagew; } _TIFFfree(obuf); return 1; }
166,863
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static struct block_device *ext3_blkdev_get(dev_t dev, struct super_block *sb) { struct block_device *bdev; char b[BDEVNAME_SIZE]; bdev = blkdev_get_by_dev(dev, FMODE_READ|FMODE_WRITE|FMODE_EXCL, sb); if (IS_ERR(bdev)) goto fail; return bdev; fail: ext3_msg(sb, "error: failed to open journal device %s: %ld", __bdevname(dev, b), PTR_ERR(bdev)); return NULL; } Commit Message: ext3: Fix format string issues ext3_msg() takes the printk prefix as the second parameter and the format string as the third parameter. Two callers of ext3_msg omit the prefix and pass the format string as the second parameter and the first parameter to the format string as the third parameter. In both cases this string comes from an arbitrary source. Which means the string may contain format string characters, which will lead to undefined and potentially harmful behavior. The issue was introduced in commit 4cf46b67eb("ext3: Unify log messages in ext3") and is fixed by this patch. CC: [email protected] Signed-off-by: Lars-Peter Clausen <[email protected]> Signed-off-by: Jan Kara <[email protected]> CWE ID: CWE-20
static struct block_device *ext3_blkdev_get(dev_t dev, struct super_block *sb) { struct block_device *bdev; char b[BDEVNAME_SIZE]; bdev = blkdev_get_by_dev(dev, FMODE_READ|FMODE_WRITE|FMODE_EXCL, sb); if (IS_ERR(bdev)) goto fail; return bdev; fail: ext3_msg(sb, KERN_ERR, "error: failed to open journal device %s: %ld", __bdevname(dev, b), PTR_ERR(bdev)); return NULL; }
166,109
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void skel(const char *homedir, uid_t u, gid_t g) { char *fname; if (arg_zsh) { if (asprintf(&fname, "%s/.zshrc", homedir) == -1) errExit("asprintf"); struct stat s; if (stat(fname, &s) == 0) return; if (stat("/etc/skel/.zshrc", &s) == 0) { if (is_link("/etc/skel/.zshrc")) { fprintf(stderr, "Error: invalid /etc/skel/.zshrc file\n"); exit(1); } if (copy_file("/etc/skel/.zshrc", fname) == 0) { if (chown(fname, u, g) == -1) errExit("chown"); fs_logger("clone /etc/skel/.zshrc"); } } else { // FILE *fp = fopen(fname, "w"); if (fp) { fprintf(fp, "\n"); fclose(fp); if (chown(fname, u, g) == -1) errExit("chown"); if (chmod(fname, S_IRUSR | S_IWUSR) < 0) errExit("chown"); fs_logger2("touch", fname); } } free(fname); } else if (arg_csh) { if (asprintf(&fname, "%s/.cshrc", homedir) == -1) errExit("asprintf"); struct stat s; if (stat(fname, &s) == 0) return; if (stat("/etc/skel/.cshrc", &s) == 0) { if (is_link("/etc/skel/.cshrc")) { fprintf(stderr, "Error: invalid /etc/skel/.cshrc file\n"); exit(1); } if (copy_file("/etc/skel/.cshrc", fname) == 0) { if (chown(fname, u, g) == -1) errExit("chown"); fs_logger("clone /etc/skel/.cshrc"); } } else { // /* coverity[toctou] */ FILE *fp = fopen(fname, "w"); if (fp) { fprintf(fp, "\n"); fclose(fp); if (chown(fname, u, g) == -1) errExit("chown"); if (chmod(fname, S_IRUSR | S_IWUSR) < 0) errExit("chown"); fs_logger2("touch", fname); } } free(fname); } else { if (asprintf(&fname, "%s/.bashrc", homedir) == -1) errExit("asprintf"); struct stat s; if (stat(fname, &s) == 0) return; if (stat("/etc/skel/.bashrc", &s) == 0) { if (is_link("/etc/skel/.bashrc")) { fprintf(stderr, "Error: invalid /etc/skel/.bashrc file\n"); exit(1); } if (copy_file("/etc/skel/.bashrc", fname) == 0) { /* coverity[toctou] */ if (chown(fname, u, g) == -1) errExit("chown"); fs_logger("clone /etc/skel/.bashrc"); } } free(fname); } } Commit Message: security fix CWE ID: CWE-269
static void skel(const char *homedir, uid_t u, gid_t g) { char *fname; if (arg_zsh) { if (asprintf(&fname, "%s/.zshrc", homedir) == -1) errExit("asprintf"); struct stat s; if (stat(fname, &s) == 0) return; if (is_link(fname)) { // stat on dangling symlinks fails, try again using lstat fprintf(stderr, "Error: invalid %s file\n", fname); exit(1); } if (stat("/etc/skel/.zshrc", &s) == 0) { copy_file_as_user("/etc/skel/.zshrc", fname, u, g, 0644); // regular user fs_logger("clone /etc/skel/.zshrc"); } else { touch_file_as_user(fname, u, g, 0644); fs_logger2("touch", fname); } free(fname); } else if (arg_csh) { if (asprintf(&fname, "%s/.cshrc", homedir) == -1) errExit("asprintf"); struct stat s; if (stat(fname, &s) == 0) return; if (is_link(fname)) { // stat on dangling symlinks fails, try again using lstat fprintf(stderr, "Error: invalid %s file\n", fname); exit(1); } if (stat("/etc/skel/.cshrc", &s) == 0) { copy_file_as_user("/etc/skel/.cshrc", fname, u, g, 0644); // regular user fs_logger("clone /etc/skel/.cshrc"); } else { touch_file_as_user(fname, u, g, 0644); fs_logger2("touch", fname); } free(fname); } else { if (asprintf(&fname, "%s/.bashrc", homedir) == -1) errExit("asprintf"); struct stat s; if (stat(fname, &s) == 0) return; if (is_link(fname)) { // stat on dangling symlinks fails, try again using lstat fprintf(stderr, "Error: invalid %s file\n", fname); exit(1); } if (stat("/etc/skel/.bashrc", &s) == 0) { copy_file_as_user("/etc/skel/.bashrc", fname, u, g, 0644); // regular user fs_logger("clone /etc/skel/.bashrc"); } free(fname); } }
170,098
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool TestDataReductionProxyConfig::ShouldAddDefaultProxyBypassRules() const { return add_default_proxy_bypass_rules_; } Commit Message: Implicitly bypass localhost when proxying requests. This aligns Chrome's behavior with the Windows and macOS proxy resolvers (but not Firefox). Concretely: * localhost names (as determined by net::IsLocalhost) now implicitly bypass the proxy * link-local IP addresses implicitly bypass the proxy The implicit rules are handled by ProxyBypassRules, and it is possible to override them when manually configuring proxy settings (but not when using PAC or auto-detect). This change also adds support for the "<-loopback>" proxy bypass rule, with similar semantics as it has on Windows (removes the implicit bypass rules for localhost and link-local). The compatibility risk of this change should be low as proxying through localhost was not universally supported. It is however an idiom used in testing (a number of our own tests had such a dependency). Impacted users can use the "<-loopback>" bypass rule as a workaround. Bug: 413511, 899126, 901896 Change-Id: I263ca21ef9f12d4759a20cb4751dc3261bda6ac0 Reviewed-on: https://chromium-review.googlesource.com/c/1303626 Commit-Queue: Eric Roman <[email protected]> Reviewed-by: Dominick Ng <[email protected]> Reviewed-by: Tarun Bansal <[email protected]> Reviewed-by: Matt Menke <[email protected]> Reviewed-by: Sami Kyöstilä <[email protected]> Cr-Commit-Position: refs/heads/master@{#606112} CWE ID: CWE-20
bool TestDataReductionProxyConfig::ShouldAddDefaultProxyBypassRules() const { void TestDataReductionProxyConfig::AddDefaultProxyBypassRules() { if (!add_default_proxy_bypass_rules_) { // Set bypass rules which allow proxying localhost. configurator_->SetBypassRules( net::ProxyBypassRules::GetRulesToSubtractImplicit()); } }
172,642
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: WORD32 ih264d_video_decode(iv_obj_t *dec_hdl, void *pv_api_ip, void *pv_api_op) { /* ! */ dec_struct_t * ps_dec = (dec_struct_t *)(dec_hdl->pv_codec_handle); WORD32 i4_err_status = 0; UWORD8 *pu1_buf = NULL; WORD32 buflen; UWORD32 u4_max_ofst, u4_length_of_start_code = 0; UWORD32 bytes_consumed = 0; UWORD32 cur_slice_is_nonref = 0; UWORD32 u4_next_is_aud; UWORD32 u4_first_start_code_found = 0; WORD32 ret = 0,api_ret_value = IV_SUCCESS; WORD32 header_data_left = 0,frame_data_left = 0; UWORD8 *pu1_bitstrm_buf; ivd_video_decode_ip_t *ps_dec_ip; ivd_video_decode_op_t *ps_dec_op; ithread_set_name((void*)"Parse_thread"); ps_dec_ip = (ivd_video_decode_ip_t *)pv_api_ip; ps_dec_op = (ivd_video_decode_op_t *)pv_api_op; { UWORD32 u4_size; u4_size = ps_dec_op->u4_size; memset(ps_dec_op, 0, sizeof(ivd_video_decode_op_t)); ps_dec_op->u4_size = u4_size; } ps_dec->pv_dec_out = ps_dec_op; ps_dec->process_called = 1; if(ps_dec->init_done != 1) { return IV_FAIL; } /*Data memory barries instruction,so that bitstream write by the application is complete*/ DATA_SYNC(); if(0 == ps_dec->u1_flushfrm) { if(ps_dec_ip->pv_stream_buffer == NULL) { ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM; ps_dec_op->u4_error_code |= IVD_DEC_FRM_BS_BUF_NULL; return IV_FAIL; } if(ps_dec_ip->u4_num_Bytes <= 0) { ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM; ps_dec_op->u4_error_code |= IVD_DEC_NUMBYTES_INV; return IV_FAIL; } } ps_dec->u1_pic_decode_done = 0; ps_dec_op->u4_num_bytes_consumed = 0; ps_dec->ps_out_buffer = NULL; if(ps_dec_ip->u4_size >= offsetof(ivd_video_decode_ip_t, s_out_buffer)) ps_dec->ps_out_buffer = &ps_dec_ip->s_out_buffer; ps_dec->u4_fmt_conv_cur_row = 0; ps_dec->u4_output_present = 0; ps_dec->s_disp_op.u4_error_code = 1; ps_dec->u4_fmt_conv_num_rows = FMT_CONV_NUM_ROWS; ps_dec->u4_stop_threads = 0; if(0 == ps_dec->u4_share_disp_buf && ps_dec->i4_decode_header == 0) { UWORD32 i; if(ps_dec->ps_out_buffer->u4_num_bufs == 0) { ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM; ps_dec_op->u4_error_code |= IVD_DISP_FRM_ZERO_OP_BUFS; return IV_FAIL; } for(i = 0; i < ps_dec->ps_out_buffer->u4_num_bufs; i++) { if(ps_dec->ps_out_buffer->pu1_bufs[i] == NULL) { ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM; ps_dec_op->u4_error_code |= IVD_DISP_FRM_OP_BUF_NULL; return IV_FAIL; } if(ps_dec->ps_out_buffer->u4_min_out_buf_size[i] == 0) { ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM; ps_dec_op->u4_error_code |= IVD_DISP_FRM_ZERO_OP_BUF_SIZE; return IV_FAIL; } } } if(ps_dec->u4_total_frames_decoded >= NUM_FRAMES_LIMIT) { ps_dec_op->u4_error_code = ERROR_FRAME_LIMIT_OVER; return IV_FAIL; } /* ! */ ps_dec->u4_ts = ps_dec_ip->u4_ts; ps_dec_op->u4_error_code = 0; ps_dec_op->e_pic_type = -1; ps_dec_op->u4_output_present = 0; ps_dec_op->u4_frame_decoded_flag = 0; ps_dec->i4_frametype = -1; ps_dec->i4_content_type = -1; ps_dec->u4_slice_start_code_found = 0; /* In case the deocder is not in flush mode(in shared mode), then decoder has to pick up a buffer to write current frame. Check if a frame is available in such cases */ if(ps_dec->u1_init_dec_flag == 1 && ps_dec->u4_share_disp_buf == 1 && ps_dec->u1_flushfrm == 0) { UWORD32 i; WORD32 disp_avail = 0, free_id; /* Check if at least one buffer is available with the codec */ /* If not then return to application with error */ for(i = 0; i < ps_dec->u1_pic_bufs; i++) { if(0 == ps_dec->u4_disp_buf_mapping[i] || 1 == ps_dec->u4_disp_buf_to_be_freed[i]) { disp_avail = 1; break; } } if(0 == disp_avail) { /* If something is queued for display wait for that buffer to be returned */ ps_dec_op->u4_error_code = IVD_DEC_REF_BUF_NULL; ps_dec_op->u4_error_code |= (1 << IVD_UNSUPPORTEDPARAM); return (IV_FAIL); } while(1) { pic_buffer_t *ps_pic_buf; ps_pic_buf = (pic_buffer_t *)ih264_buf_mgr_get_next_free( (buf_mgr_t *)ps_dec->pv_pic_buf_mgr, &free_id); if(ps_pic_buf == NULL) { UWORD32 i, display_queued = 0; /* check if any buffer was given for display which is not returned yet */ for(i = 0; i < (MAX_DISP_BUFS_NEW); i++) { if(0 != ps_dec->u4_disp_buf_mapping[i]) { display_queued = 1; break; } } /* If some buffer is queued for display, then codec has to singal an error and wait for that buffer to be returned. If nothing is queued for display then codec has ownership of all display buffers and it can reuse any of the existing buffers and continue decoding */ if(1 == display_queued) { /* If something is queued for display wait for that buffer to be returned */ ps_dec_op->u4_error_code = IVD_DEC_REF_BUF_NULL; ps_dec_op->u4_error_code |= (1 << IVD_UNSUPPORTEDPARAM); return (IV_FAIL); } } else { /* If the buffer is with display, then mark it as in use and then look for a buffer again */ if(1 == ps_dec->u4_disp_buf_mapping[free_id]) { ih264_buf_mgr_set_status( (buf_mgr_t *)ps_dec->pv_pic_buf_mgr, free_id, BUF_MGR_IO); } else { /** * Found a free buffer for present call. Release it now. * Will be again obtained later. */ ih264_buf_mgr_release((buf_mgr_t *)ps_dec->pv_pic_buf_mgr, free_id, BUF_MGR_IO); break; } } } } if(ps_dec->u1_flushfrm && ps_dec->u1_init_dec_flag) { ih264d_get_next_display_field(ps_dec, ps_dec->ps_out_buffer, &(ps_dec->s_disp_op)); if(0 == ps_dec->s_disp_op.u4_error_code) { ps_dec->u4_fmt_conv_cur_row = 0; ps_dec->u4_fmt_conv_num_rows = ps_dec->s_disp_frame_info.u4_y_ht; ih264d_format_convert(ps_dec, &(ps_dec->s_disp_op), ps_dec->u4_fmt_conv_cur_row, ps_dec->u4_fmt_conv_num_rows); ps_dec->u4_fmt_conv_cur_row += ps_dec->u4_fmt_conv_num_rows; ps_dec->u4_output_present = 1; } ih264d_release_display_field(ps_dec, &(ps_dec->s_disp_op)); ps_dec_op->u4_pic_wd = (UWORD32)ps_dec->u2_disp_width; ps_dec_op->u4_pic_ht = (UWORD32)ps_dec->u2_disp_height; ps_dec_op->u4_new_seq = 0; ps_dec_op->u4_output_present = ps_dec->u4_output_present; ps_dec_op->u4_progressive_frame_flag = ps_dec->s_disp_op.u4_progressive_frame_flag; ps_dec_op->e_output_format = ps_dec->s_disp_op.e_output_format; ps_dec_op->s_disp_frm_buf = ps_dec->s_disp_op.s_disp_frm_buf; ps_dec_op->e4_fld_type = ps_dec->s_disp_op.e4_fld_type; ps_dec_op->u4_ts = ps_dec->s_disp_op.u4_ts; ps_dec_op->u4_disp_buf_id = ps_dec->s_disp_op.u4_disp_buf_id; /*In the case of flush ,since no frame is decoded set pic type as invalid*/ ps_dec_op->u4_is_ref_flag = -1; ps_dec_op->e_pic_type = IV_NA_FRAME; ps_dec_op->u4_frame_decoded_flag = 0; if(0 == ps_dec->s_disp_op.u4_error_code) { return (IV_SUCCESS); } else return (IV_FAIL); } if(ps_dec->u1_res_changed == 1) { /*if resolution has changed and all buffers have been flushed, reset decoder*/ ih264d_init_decoder(ps_dec); } ps_dec->u4_prev_nal_skipped = 0; ps_dec->u2_cur_mb_addr = 0; ps_dec->u2_total_mbs_coded = 0; ps_dec->u2_cur_slice_num = 0; ps_dec->cur_dec_mb_num = 0; ps_dec->cur_recon_mb_num = 0; ps_dec->u4_first_slice_in_pic = 2; ps_dec->u1_first_pb_nal_in_pic = 1; ps_dec->u1_slice_header_done = 0; ps_dec->u1_dangling_field = 0; ps_dec->u4_dec_thread_created = 0; ps_dec->u4_bs_deblk_thread_created = 0; ps_dec->u4_cur_bs_mb_num = 0; ps_dec->u4_start_recon_deblk = 0; DEBUG_THREADS_PRINTF(" Starting process call\n"); ps_dec->u4_pic_buf_got = 0; do { pu1_buf = (UWORD8*)ps_dec_ip->pv_stream_buffer + ps_dec_op->u4_num_bytes_consumed; u4_max_ofst = ps_dec_ip->u4_num_Bytes - ps_dec_op->u4_num_bytes_consumed; pu1_bitstrm_buf = ps_dec->ps_mem_tab[MEM_REC_BITSBUF].pv_base; u4_next_is_aud = 0; buflen = ih264d_find_start_code(pu1_buf, 0, u4_max_ofst, &u4_length_of_start_code, &u4_next_is_aud); if(buflen == -1) buflen = 0; /* Ignore bytes beyond the allocated size of intermediate buffer */ /* Since 8 bytes are read ahead, ensure 8 bytes are free at the end of the buffer, which will be memset to 0 after emulation prevention */ buflen = MIN(buflen, (WORD32)(ps_dec->ps_mem_tab[MEM_REC_BITSBUF].u4_mem_size - 8)); bytes_consumed = buflen + u4_length_of_start_code; ps_dec_op->u4_num_bytes_consumed += bytes_consumed; if(buflen >= MAX_NAL_UNIT_SIZE) { ih264d_fill_output_struct_from_context(ps_dec, ps_dec_op); H264_DEC_DEBUG_PRINT( "\nNal Size exceeded %d, Processing Stopped..\n", MAX_NAL_UNIT_SIZE); ps_dec->i4_error_code = 1 << IVD_CORRUPTEDDATA; ps_dec_op->e_pic_type = -1; /*signal the decode thread*/ ih264d_signal_decode_thread(ps_dec); /*signal end of frame decode for curren frame*/ if(ps_dec->u4_pic_buf_got == 0) { if(ps_dec->i4_header_decoded == 3) { ps_dec->u2_total_mbs_coded = ps_dec->ps_cur_sps->u2_max_mb_addr + 1; } /* close deblock thread if it is not closed yet*/ if(ps_dec->u4_num_cores == 3) { ih264d_signal_bs_deblk_thread(ps_dec); } return IV_FAIL; } else { ps_dec->u1_pic_decode_done = 1; continue; } } { UWORD8 u1_firstbyte, u1_nal_ref_idc; if(ps_dec->i4_app_skip_mode == IVD_SKIP_B) { u1_firstbyte = *(pu1_buf + u4_length_of_start_code); u1_nal_ref_idc = (UWORD8)(NAL_REF_IDC(u1_firstbyte)); if(u1_nal_ref_idc == 0) { /*skip non reference frames*/ cur_slice_is_nonref = 1; continue; } else { if(1 == cur_slice_is_nonref) { /*We have encountered a referenced frame,return to app*/ ps_dec_op->u4_num_bytes_consumed -= bytes_consumed; ps_dec_op->e_pic_type = IV_B_FRAME; ps_dec_op->u4_error_code = IVD_DEC_FRM_SKIPPED; ps_dec_op->u4_error_code |= (1 << IVD_UNSUPPORTEDPARAM); ps_dec_op->u4_frame_decoded_flag = 0; ps_dec_op->u4_size = sizeof(ivd_video_decode_op_t); /*signal the decode thread*/ ih264d_signal_decode_thread(ps_dec); /* close deblock thread if it is not closed yet*/ if(ps_dec->u4_num_cores == 3) { ih264d_signal_bs_deblk_thread(ps_dec); } return (IV_FAIL); } } } } if(buflen) { memcpy(pu1_bitstrm_buf, pu1_buf + u4_length_of_start_code, buflen); u4_first_start_code_found = 1; } else { /*start code not found*/ if(u4_first_start_code_found == 0) { /*no start codes found in current process call*/ ps_dec->i4_error_code = ERROR_START_CODE_NOT_FOUND; ps_dec_op->u4_error_code |= 1 << IVD_INSUFFICIENTDATA; if(ps_dec->u4_pic_buf_got == 0) { ih264d_fill_output_struct_from_context(ps_dec, ps_dec_op); ps_dec_op->u4_error_code = ps_dec->i4_error_code; ps_dec_op->u4_frame_decoded_flag = 0; return (IV_FAIL); } else { ps_dec->u1_pic_decode_done = 1; continue; } } else { /* a start code has already been found earlier in the same process call*/ frame_data_left = 0; header_data_left = 0; continue; } } ps_dec->u4_return_to_app = 0; ret = ih264d_parse_nal_unit(dec_hdl, ps_dec_op, pu1_bitstrm_buf, buflen); if(ret != OK) { UWORD32 error = ih264d_map_error(ret); ps_dec_op->u4_error_code = error | ret; api_ret_value = IV_FAIL; if((ret == IVD_RES_CHANGED) || (ret == IVD_STREAM_WIDTH_HEIGHT_NOT_SUPPORTED) || (ret == ERROR_UNAVAIL_PICBUF_T) || (ret == ERROR_UNAVAIL_MVBUF_T) || (ret == ERROR_INV_SPS_PPS_T)) { ps_dec->u4_slice_start_code_found = 0; break; } if((ret == ERROR_INCOMPLETE_FRAME) || (ret == ERROR_DANGLING_FIELD_IN_PIC)) { ps_dec_op->u4_num_bytes_consumed -= bytes_consumed; api_ret_value = IV_FAIL; break; } if(ret == ERROR_IN_LAST_SLICE_OF_PIC) { api_ret_value = IV_FAIL; break; } } if(ps_dec->u4_return_to_app) { /*We have encountered a referenced frame,return to app*/ ps_dec_op->u4_num_bytes_consumed -= bytes_consumed; ps_dec_op->u4_error_code = IVD_DEC_FRM_SKIPPED; ps_dec_op->u4_error_code |= (1 << IVD_UNSUPPORTEDPARAM); ps_dec_op->u4_frame_decoded_flag = 0; ps_dec_op->u4_size = sizeof(ivd_video_decode_op_t); /*signal the decode thread*/ ih264d_signal_decode_thread(ps_dec); /* close deblock thread if it is not closed yet*/ if(ps_dec->u4_num_cores == 3) { ih264d_signal_bs_deblk_thread(ps_dec); } return (IV_FAIL); } header_data_left = ((ps_dec->i4_decode_header == 1) && (ps_dec->i4_header_decoded != 3) && (ps_dec_op->u4_num_bytes_consumed < ps_dec_ip->u4_num_Bytes)); frame_data_left = (((ps_dec->i4_decode_header == 0) && ((ps_dec->u1_pic_decode_done == 0) || (u4_next_is_aud == 1))) && (ps_dec_op->u4_num_bytes_consumed < ps_dec_ip->u4_num_Bytes)); } while(( header_data_left == 1)||(frame_data_left == 1)); if((ps_dec->u4_slice_start_code_found == 1) && ps_dec->u2_total_mbs_coded < ps_dec->u2_frm_ht_in_mbs * ps_dec->u2_frm_wd_in_mbs) { WORD32 num_mb_skipped; WORD32 prev_slice_err; pocstruct_t temp_poc; WORD32 ret1; WORD32 ht_in_mbs; ht_in_mbs = ps_dec->u2_pic_ht >> (4 + ps_dec->ps_cur_slice->u1_field_pic_flag); num_mb_skipped = (ht_in_mbs * ps_dec->u2_frm_wd_in_mbs) - ps_dec->u2_total_mbs_coded; if(ps_dec->u4_first_slice_in_pic && (ps_dec->u4_pic_buf_got == 0)) prev_slice_err = 1; else prev_slice_err = 2; if(ps_dec->u4_first_slice_in_pic && (ps_dec->u2_total_mbs_coded == 0)) prev_slice_err = 1; ret1 = ih264d_mark_err_slice_skip(ps_dec, num_mb_skipped, ps_dec->u1_nal_unit_type == IDR_SLICE_NAL, ps_dec->ps_cur_slice->u2_frame_num, &temp_poc, prev_slice_err); if((ret1 == ERROR_UNAVAIL_PICBUF_T) || (ret1 == ERROR_UNAVAIL_MVBUF_T) || (ret1 == ERROR_INV_SPS_PPS_T)) { ret = ret1; } } if((ret == IVD_RES_CHANGED) || (ret == IVD_STREAM_WIDTH_HEIGHT_NOT_SUPPORTED) || (ret == ERROR_UNAVAIL_PICBUF_T) || (ret == ERROR_UNAVAIL_MVBUF_T) || (ret == ERROR_INV_SPS_PPS_T)) { /* signal the decode thread */ ih264d_signal_decode_thread(ps_dec); /* close deblock thread if it is not closed yet */ if(ps_dec->u4_num_cores == 3) { ih264d_signal_bs_deblk_thread(ps_dec); } /* dont consume bitstream for change in resolution case */ if(ret == IVD_RES_CHANGED) { ps_dec_op->u4_num_bytes_consumed -= bytes_consumed; } return IV_FAIL; } if(ps_dec->u1_separate_parse) { /* If Format conversion is not complete, complete it here */ if(ps_dec->u4_num_cores == 2) { /*do deblocking of all mbs*/ if((ps_dec->u4_nmb_deblk == 0) &&(ps_dec->u4_start_recon_deblk == 1) && (ps_dec->ps_cur_sps->u1_mb_aff_flag == 0)) { UWORD32 u4_num_mbs,u4_max_addr; tfr_ctxt_t s_tfr_ctxt; tfr_ctxt_t *ps_tfr_cxt = &s_tfr_ctxt; pad_mgr_t *ps_pad_mgr = &ps_dec->s_pad_mgr; /*BS is done for all mbs while parsing*/ u4_max_addr = (ps_dec->u2_frm_wd_in_mbs * ps_dec->u2_frm_ht_in_mbs) - 1; ps_dec->u4_cur_bs_mb_num = u4_max_addr + 1; ih264d_init_deblk_tfr_ctxt(ps_dec, ps_pad_mgr, ps_tfr_cxt, ps_dec->u2_frm_wd_in_mbs, 0); u4_num_mbs = u4_max_addr - ps_dec->u4_cur_deblk_mb_num + 1; DEBUG_PERF_PRINTF("mbs left for deblocking= %d \n",u4_num_mbs); if(u4_num_mbs != 0) ih264d_check_mb_map_deblk(ps_dec, u4_num_mbs, ps_tfr_cxt,1); ps_dec->u4_start_recon_deblk = 0; } } /*signal the decode thread*/ ih264d_signal_decode_thread(ps_dec); /* close deblock thread if it is not closed yet*/ if(ps_dec->u4_num_cores == 3) { ih264d_signal_bs_deblk_thread(ps_dec); } } DATA_SYNC(); if((ps_dec_op->u4_error_code & 0xff) != ERROR_DYNAMIC_RESOLUTION_NOT_SUPPORTED) { ps_dec_op->u4_pic_wd = (UWORD32)ps_dec->u2_disp_width; ps_dec_op->u4_pic_ht = (UWORD32)ps_dec->u2_disp_height; } if(ps_dec->i4_header_decoded != 3) { ps_dec_op->u4_error_code |= (1 << IVD_INSUFFICIENTDATA); } if(ps_dec->i4_decode_header == 1 && ps_dec->i4_header_decoded != 3) { ps_dec_op->u4_error_code |= (1 << IVD_INSUFFICIENTDATA); } if(ps_dec->u4_prev_nal_skipped) { /*We have encountered a referenced frame,return to app*/ ps_dec_op->u4_error_code = IVD_DEC_FRM_SKIPPED; ps_dec_op->u4_error_code |= (1 << IVD_UNSUPPORTEDPARAM); ps_dec_op->u4_frame_decoded_flag = 0; ps_dec_op->u4_size = sizeof(ivd_video_decode_op_t); /* close deblock thread if it is not closed yet*/ if(ps_dec->u4_num_cores == 3) { ih264d_signal_bs_deblk_thread(ps_dec); } return (IV_FAIL); } if((ps_dec->u4_slice_start_code_found == 1) && (ERROR_DANGLING_FIELD_IN_PIC != i4_err_status)) { /* * For field pictures, set the bottom and top picture decoded u4_flag correctly. */ if(ps_dec->ps_cur_slice->u1_field_pic_flag) { if(1 == ps_dec->ps_cur_slice->u1_bottom_field_flag) { ps_dec->u1_top_bottom_decoded |= BOT_FIELD_ONLY; } else { ps_dec->u1_top_bottom_decoded |= TOP_FIELD_ONLY; } } /* if new frame in not found (if we are still getting slices from previous frame) * ih264d_deblock_display is not called. Such frames will not be added to reference /display */ if (((ps_dec->ps_dec_err_status->u1_err_flag & REJECT_CUR_PIC) == 0) && (ps_dec->u4_pic_buf_got == 1)) { /* Calling Function to deblock Picture and Display */ ret = ih264d_deblock_display(ps_dec); } /*set to complete ,as we dont support partial frame decode*/ if(ps_dec->i4_header_decoded == 3) { ps_dec->u2_total_mbs_coded = ps_dec->ps_cur_sps->u2_max_mb_addr + 1; } /*Update the i4_frametype at the end of picture*/ if(ps_dec->ps_cur_slice->u1_nal_unit_type == IDR_SLICE_NAL) { ps_dec->i4_frametype = IV_IDR_FRAME; } else if(ps_dec->i4_pic_type == B_SLICE) { ps_dec->i4_frametype = IV_B_FRAME; } else if(ps_dec->i4_pic_type == P_SLICE) { ps_dec->i4_frametype = IV_P_FRAME; } else if(ps_dec->i4_pic_type == I_SLICE) { ps_dec->i4_frametype = IV_I_FRAME; } else { H264_DEC_DEBUG_PRINT("Shouldn't come here\n"); } ps_dec->i4_content_type = ps_dec->ps_cur_slice->u1_field_pic_flag; ps_dec->u4_total_frames_decoded = ps_dec->u4_total_frames_decoded + 2; ps_dec->u4_total_frames_decoded = ps_dec->u4_total_frames_decoded - ps_dec->ps_cur_slice->u1_field_pic_flag; } /* close deblock thread if it is not closed yet*/ if(ps_dec->u4_num_cores == 3) { ih264d_signal_bs_deblk_thread(ps_dec); } { /* In case the decoder is configured to run in low delay mode, * then get display buffer and then format convert. * Note in this mode, format conversion does not run paralelly in a thread and adds to the codec cycles */ if((0 == ps_dec->u4_num_reorder_frames_at_init) && ps_dec->u1_init_dec_flag) { ih264d_get_next_display_field(ps_dec, ps_dec->ps_out_buffer, &(ps_dec->s_disp_op)); if(0 == ps_dec->s_disp_op.u4_error_code) { ps_dec->u4_fmt_conv_cur_row = 0; ps_dec->u4_output_present = 1; } } ih264d_fill_output_struct_from_context(ps_dec, ps_dec_op); /* If Format conversion is not complete, complete it here */ if(ps_dec->u4_output_present && (ps_dec->u4_fmt_conv_cur_row < ps_dec->s_disp_frame_info.u4_y_ht)) { ps_dec->u4_fmt_conv_num_rows = ps_dec->s_disp_frame_info.u4_y_ht - ps_dec->u4_fmt_conv_cur_row; ih264d_format_convert(ps_dec, &(ps_dec->s_disp_op), ps_dec->u4_fmt_conv_cur_row, ps_dec->u4_fmt_conv_num_rows); ps_dec->u4_fmt_conv_cur_row += ps_dec->u4_fmt_conv_num_rows; } ih264d_release_display_field(ps_dec, &(ps_dec->s_disp_op)); } if(ps_dec->i4_decode_header == 1 && (ps_dec->i4_header_decoded & 1) == 1) { ps_dec_op->u4_progressive_frame_flag = 1; if((NULL != ps_dec->ps_cur_sps) && (1 == (ps_dec->ps_cur_sps->u1_is_valid))) { if((0 == ps_dec->ps_sps->u1_frame_mbs_only_flag) && (0 == ps_dec->ps_sps->u1_mb_aff_flag)) ps_dec_op->u4_progressive_frame_flag = 0; } } if((TOP_FIELD_ONLY | BOT_FIELD_ONLY) == ps_dec->u1_top_bottom_decoded) { ps_dec->u1_top_bottom_decoded = 0; } /*--------------------------------------------------------------------*/ /* Do End of Pic processing. */ /* Should be called only if frame was decoded in previous process call*/ /*--------------------------------------------------------------------*/ if(ps_dec->u4_pic_buf_got == 1) { if(1 == ps_dec->u1_last_pic_not_decoded) { ret = ih264d_end_of_pic_dispbuf_mgr(ps_dec); if(ret != OK) return ret; ret = ih264d_end_of_pic(ps_dec); if(ret != OK) return ret; } else { ret = ih264d_end_of_pic(ps_dec); if(ret != OK) return ret; } } /*Data memory barrier instruction,so that yuv write by the library is complete*/ DATA_SYNC(); H264_DEC_DEBUG_PRINT("The num bytes consumed: %d\n", ps_dec_op->u4_num_bytes_consumed); return api_ret_value; } Commit Message: Decoder: Fixed initialization of first_slice_in_pic To handle some errors, first_slice_in_pic was being set to 2. This is now cleaned up and first_slice_in_pic is set to 1 only once per pic. This will ensure picture level initializations are done only once even in case of error clips Bug: 33717589 Bug: 33551775 Bug: 33716442 Bug: 33677995 Change-Id: If341436b3cbaa724017eedddd88c2e6fac36d8ba CWE ID: CWE-200
WORD32 ih264d_video_decode(iv_obj_t *dec_hdl, void *pv_api_ip, void *pv_api_op) { /* ! */ dec_struct_t * ps_dec = (dec_struct_t *)(dec_hdl->pv_codec_handle); WORD32 i4_err_status = 0; UWORD8 *pu1_buf = NULL; WORD32 buflen; UWORD32 u4_max_ofst, u4_length_of_start_code = 0; UWORD32 bytes_consumed = 0; UWORD32 cur_slice_is_nonref = 0; UWORD32 u4_next_is_aud; UWORD32 u4_first_start_code_found = 0; WORD32 ret = 0,api_ret_value = IV_SUCCESS; WORD32 header_data_left = 0,frame_data_left = 0; UWORD8 *pu1_bitstrm_buf; ivd_video_decode_ip_t *ps_dec_ip; ivd_video_decode_op_t *ps_dec_op; ithread_set_name((void*)"Parse_thread"); ps_dec_ip = (ivd_video_decode_ip_t *)pv_api_ip; ps_dec_op = (ivd_video_decode_op_t *)pv_api_op; { UWORD32 u4_size; u4_size = ps_dec_op->u4_size; memset(ps_dec_op, 0, sizeof(ivd_video_decode_op_t)); ps_dec_op->u4_size = u4_size; } ps_dec->pv_dec_out = ps_dec_op; ps_dec->process_called = 1; if(ps_dec->init_done != 1) { return IV_FAIL; } /*Data memory barries instruction,so that bitstream write by the application is complete*/ DATA_SYNC(); if(0 == ps_dec->u1_flushfrm) { if(ps_dec_ip->pv_stream_buffer == NULL) { ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM; ps_dec_op->u4_error_code |= IVD_DEC_FRM_BS_BUF_NULL; return IV_FAIL; } if(ps_dec_ip->u4_num_Bytes <= 0) { ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM; ps_dec_op->u4_error_code |= IVD_DEC_NUMBYTES_INV; return IV_FAIL; } } ps_dec->u1_pic_decode_done = 0; ps_dec_op->u4_num_bytes_consumed = 0; ps_dec->ps_out_buffer = NULL; if(ps_dec_ip->u4_size >= offsetof(ivd_video_decode_ip_t, s_out_buffer)) ps_dec->ps_out_buffer = &ps_dec_ip->s_out_buffer; ps_dec->u4_fmt_conv_cur_row = 0; ps_dec->u4_output_present = 0; ps_dec->s_disp_op.u4_error_code = 1; ps_dec->u4_fmt_conv_num_rows = FMT_CONV_NUM_ROWS; ps_dec->u4_stop_threads = 0; if(0 == ps_dec->u4_share_disp_buf && ps_dec->i4_decode_header == 0) { UWORD32 i; if(ps_dec->ps_out_buffer->u4_num_bufs == 0) { ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM; ps_dec_op->u4_error_code |= IVD_DISP_FRM_ZERO_OP_BUFS; return IV_FAIL; } for(i = 0; i < ps_dec->ps_out_buffer->u4_num_bufs; i++) { if(ps_dec->ps_out_buffer->pu1_bufs[i] == NULL) { ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM; ps_dec_op->u4_error_code |= IVD_DISP_FRM_OP_BUF_NULL; return IV_FAIL; } if(ps_dec->ps_out_buffer->u4_min_out_buf_size[i] == 0) { ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM; ps_dec_op->u4_error_code |= IVD_DISP_FRM_ZERO_OP_BUF_SIZE; return IV_FAIL; } } } if(ps_dec->u4_total_frames_decoded >= NUM_FRAMES_LIMIT) { ps_dec_op->u4_error_code = ERROR_FRAME_LIMIT_OVER; return IV_FAIL; } /* ! */ ps_dec->u4_ts = ps_dec_ip->u4_ts; ps_dec_op->u4_error_code = 0; ps_dec_op->e_pic_type = -1; ps_dec_op->u4_output_present = 0; ps_dec_op->u4_frame_decoded_flag = 0; ps_dec->i4_frametype = -1; ps_dec->i4_content_type = -1; ps_dec->u4_slice_start_code_found = 0; /* In case the deocder is not in flush mode(in shared mode), then decoder has to pick up a buffer to write current frame. Check if a frame is available in such cases */ if(ps_dec->u1_init_dec_flag == 1 && ps_dec->u4_share_disp_buf == 1 && ps_dec->u1_flushfrm == 0) { UWORD32 i; WORD32 disp_avail = 0, free_id; /* Check if at least one buffer is available with the codec */ /* If not then return to application with error */ for(i = 0; i < ps_dec->u1_pic_bufs; i++) { if(0 == ps_dec->u4_disp_buf_mapping[i] || 1 == ps_dec->u4_disp_buf_to_be_freed[i]) { disp_avail = 1; break; } } if(0 == disp_avail) { /* If something is queued for display wait for that buffer to be returned */ ps_dec_op->u4_error_code = IVD_DEC_REF_BUF_NULL; ps_dec_op->u4_error_code |= (1 << IVD_UNSUPPORTEDPARAM); return (IV_FAIL); } while(1) { pic_buffer_t *ps_pic_buf; ps_pic_buf = (pic_buffer_t *)ih264_buf_mgr_get_next_free( (buf_mgr_t *)ps_dec->pv_pic_buf_mgr, &free_id); if(ps_pic_buf == NULL) { UWORD32 i, display_queued = 0; /* check if any buffer was given for display which is not returned yet */ for(i = 0; i < (MAX_DISP_BUFS_NEW); i++) { if(0 != ps_dec->u4_disp_buf_mapping[i]) { display_queued = 1; break; } } /* If some buffer is queued for display, then codec has to singal an error and wait for that buffer to be returned. If nothing is queued for display then codec has ownership of all display buffers and it can reuse any of the existing buffers and continue decoding */ if(1 == display_queued) { /* If something is queued for display wait for that buffer to be returned */ ps_dec_op->u4_error_code = IVD_DEC_REF_BUF_NULL; ps_dec_op->u4_error_code |= (1 << IVD_UNSUPPORTEDPARAM); return (IV_FAIL); } } else { /* If the buffer is with display, then mark it as in use and then look for a buffer again */ if(1 == ps_dec->u4_disp_buf_mapping[free_id]) { ih264_buf_mgr_set_status( (buf_mgr_t *)ps_dec->pv_pic_buf_mgr, free_id, BUF_MGR_IO); } else { /** * Found a free buffer for present call. Release it now. * Will be again obtained later. */ ih264_buf_mgr_release((buf_mgr_t *)ps_dec->pv_pic_buf_mgr, free_id, BUF_MGR_IO); break; } } } } if(ps_dec->u1_flushfrm && ps_dec->u1_init_dec_flag) { ih264d_get_next_display_field(ps_dec, ps_dec->ps_out_buffer, &(ps_dec->s_disp_op)); if(0 == ps_dec->s_disp_op.u4_error_code) { ps_dec->u4_fmt_conv_cur_row = 0; ps_dec->u4_fmt_conv_num_rows = ps_dec->s_disp_frame_info.u4_y_ht; ih264d_format_convert(ps_dec, &(ps_dec->s_disp_op), ps_dec->u4_fmt_conv_cur_row, ps_dec->u4_fmt_conv_num_rows); ps_dec->u4_fmt_conv_cur_row += ps_dec->u4_fmt_conv_num_rows; ps_dec->u4_output_present = 1; } ih264d_release_display_field(ps_dec, &(ps_dec->s_disp_op)); ps_dec_op->u4_pic_wd = (UWORD32)ps_dec->u2_disp_width; ps_dec_op->u4_pic_ht = (UWORD32)ps_dec->u2_disp_height; ps_dec_op->u4_new_seq = 0; ps_dec_op->u4_output_present = ps_dec->u4_output_present; ps_dec_op->u4_progressive_frame_flag = ps_dec->s_disp_op.u4_progressive_frame_flag; ps_dec_op->e_output_format = ps_dec->s_disp_op.e_output_format; ps_dec_op->s_disp_frm_buf = ps_dec->s_disp_op.s_disp_frm_buf; ps_dec_op->e4_fld_type = ps_dec->s_disp_op.e4_fld_type; ps_dec_op->u4_ts = ps_dec->s_disp_op.u4_ts; ps_dec_op->u4_disp_buf_id = ps_dec->s_disp_op.u4_disp_buf_id; /*In the case of flush ,since no frame is decoded set pic type as invalid*/ ps_dec_op->u4_is_ref_flag = -1; ps_dec_op->e_pic_type = IV_NA_FRAME; ps_dec_op->u4_frame_decoded_flag = 0; if(0 == ps_dec->s_disp_op.u4_error_code) { return (IV_SUCCESS); } else return (IV_FAIL); } if(ps_dec->u1_res_changed == 1) { /*if resolution has changed and all buffers have been flushed, reset decoder*/ ih264d_init_decoder(ps_dec); } ps_dec->u4_prev_nal_skipped = 0; ps_dec->u2_cur_mb_addr = 0; ps_dec->u2_total_mbs_coded = 0; ps_dec->u2_cur_slice_num = 0; ps_dec->cur_dec_mb_num = 0; ps_dec->cur_recon_mb_num = 0; ps_dec->u4_first_slice_in_pic = 1; ps_dec->u1_first_pb_nal_in_pic = 1; ps_dec->u1_slice_header_done = 0; ps_dec->u1_dangling_field = 0; ps_dec->u4_dec_thread_created = 0; ps_dec->u4_bs_deblk_thread_created = 0; ps_dec->u4_cur_bs_mb_num = 0; ps_dec->u4_start_recon_deblk = 0; DEBUG_THREADS_PRINTF(" Starting process call\n"); ps_dec->u4_pic_buf_got = 0; do { pu1_buf = (UWORD8*)ps_dec_ip->pv_stream_buffer + ps_dec_op->u4_num_bytes_consumed; u4_max_ofst = ps_dec_ip->u4_num_Bytes - ps_dec_op->u4_num_bytes_consumed; pu1_bitstrm_buf = ps_dec->ps_mem_tab[MEM_REC_BITSBUF].pv_base; u4_next_is_aud = 0; buflen = ih264d_find_start_code(pu1_buf, 0, u4_max_ofst, &u4_length_of_start_code, &u4_next_is_aud); if(buflen == -1) buflen = 0; /* Ignore bytes beyond the allocated size of intermediate buffer */ /* Since 8 bytes are read ahead, ensure 8 bytes are free at the end of the buffer, which will be memset to 0 after emulation prevention */ buflen = MIN(buflen, (WORD32)(ps_dec->ps_mem_tab[MEM_REC_BITSBUF].u4_mem_size - 8)); bytes_consumed = buflen + u4_length_of_start_code; ps_dec_op->u4_num_bytes_consumed += bytes_consumed; if(buflen >= MAX_NAL_UNIT_SIZE) { ih264d_fill_output_struct_from_context(ps_dec, ps_dec_op); H264_DEC_DEBUG_PRINT( "\nNal Size exceeded %d, Processing Stopped..\n", MAX_NAL_UNIT_SIZE); ps_dec->i4_error_code = 1 << IVD_CORRUPTEDDATA; ps_dec_op->e_pic_type = -1; /*signal the decode thread*/ ih264d_signal_decode_thread(ps_dec); /*signal end of frame decode for curren frame*/ if(ps_dec->u4_pic_buf_got == 0) { if(ps_dec->i4_header_decoded == 3) { ps_dec->u2_total_mbs_coded = ps_dec->ps_cur_sps->u2_max_mb_addr + 1; } /* close deblock thread if it is not closed yet*/ if(ps_dec->u4_num_cores == 3) { ih264d_signal_bs_deblk_thread(ps_dec); } return IV_FAIL; } else { ps_dec->u1_pic_decode_done = 1; continue; } } { UWORD8 u1_firstbyte, u1_nal_ref_idc; if(ps_dec->i4_app_skip_mode == IVD_SKIP_B) { u1_firstbyte = *(pu1_buf + u4_length_of_start_code); u1_nal_ref_idc = (UWORD8)(NAL_REF_IDC(u1_firstbyte)); if(u1_nal_ref_idc == 0) { /*skip non reference frames*/ cur_slice_is_nonref = 1; continue; } else { if(1 == cur_slice_is_nonref) { /*We have encountered a referenced frame,return to app*/ ps_dec_op->u4_num_bytes_consumed -= bytes_consumed; ps_dec_op->e_pic_type = IV_B_FRAME; ps_dec_op->u4_error_code = IVD_DEC_FRM_SKIPPED; ps_dec_op->u4_error_code |= (1 << IVD_UNSUPPORTEDPARAM); ps_dec_op->u4_frame_decoded_flag = 0; ps_dec_op->u4_size = sizeof(ivd_video_decode_op_t); /*signal the decode thread*/ ih264d_signal_decode_thread(ps_dec); /* close deblock thread if it is not closed yet*/ if(ps_dec->u4_num_cores == 3) { ih264d_signal_bs_deblk_thread(ps_dec); } return (IV_FAIL); } } } } if(buflen) { memcpy(pu1_bitstrm_buf, pu1_buf + u4_length_of_start_code, buflen); u4_first_start_code_found = 1; } else { /*start code not found*/ if(u4_first_start_code_found == 0) { /*no start codes found in current process call*/ ps_dec->i4_error_code = ERROR_START_CODE_NOT_FOUND; ps_dec_op->u4_error_code |= 1 << IVD_INSUFFICIENTDATA; if(ps_dec->u4_pic_buf_got == 0) { ih264d_fill_output_struct_from_context(ps_dec, ps_dec_op); ps_dec_op->u4_error_code = ps_dec->i4_error_code; ps_dec_op->u4_frame_decoded_flag = 0; return (IV_FAIL); } else { ps_dec->u1_pic_decode_done = 1; continue; } } else { /* a start code has already been found earlier in the same process call*/ frame_data_left = 0; header_data_left = 0; continue; } } ps_dec->u4_return_to_app = 0; ret = ih264d_parse_nal_unit(dec_hdl, ps_dec_op, pu1_bitstrm_buf, buflen); if(ret != OK) { UWORD32 error = ih264d_map_error(ret); ps_dec_op->u4_error_code = error | ret; api_ret_value = IV_FAIL; if((ret == IVD_RES_CHANGED) || (ret == IVD_STREAM_WIDTH_HEIGHT_NOT_SUPPORTED) || (ret == ERROR_UNAVAIL_PICBUF_T) || (ret == ERROR_UNAVAIL_MVBUF_T) || (ret == ERROR_INV_SPS_PPS_T)) { ps_dec->u4_slice_start_code_found = 0; break; } if((ret == ERROR_INCOMPLETE_FRAME) || (ret == ERROR_DANGLING_FIELD_IN_PIC)) { ps_dec_op->u4_num_bytes_consumed -= bytes_consumed; api_ret_value = IV_FAIL; break; } if(ret == ERROR_IN_LAST_SLICE_OF_PIC) { api_ret_value = IV_FAIL; break; } } if(ps_dec->u4_return_to_app) { /*We have encountered a referenced frame,return to app*/ ps_dec_op->u4_num_bytes_consumed -= bytes_consumed; ps_dec_op->u4_error_code = IVD_DEC_FRM_SKIPPED; ps_dec_op->u4_error_code |= (1 << IVD_UNSUPPORTEDPARAM); ps_dec_op->u4_frame_decoded_flag = 0; ps_dec_op->u4_size = sizeof(ivd_video_decode_op_t); /*signal the decode thread*/ ih264d_signal_decode_thread(ps_dec); /* close deblock thread if it is not closed yet*/ if(ps_dec->u4_num_cores == 3) { ih264d_signal_bs_deblk_thread(ps_dec); } return (IV_FAIL); } header_data_left = ((ps_dec->i4_decode_header == 1) && (ps_dec->i4_header_decoded != 3) && (ps_dec_op->u4_num_bytes_consumed < ps_dec_ip->u4_num_Bytes)); frame_data_left = (((ps_dec->i4_decode_header == 0) && ((ps_dec->u1_pic_decode_done == 0) || (u4_next_is_aud == 1))) && (ps_dec_op->u4_num_bytes_consumed < ps_dec_ip->u4_num_Bytes)); } while(( header_data_left == 1)||(frame_data_left == 1)); if((ps_dec->u4_slice_start_code_found == 1) && ps_dec->u2_total_mbs_coded < ps_dec->u2_frm_ht_in_mbs * ps_dec->u2_frm_wd_in_mbs) { WORD32 num_mb_skipped; WORD32 prev_slice_err; pocstruct_t temp_poc; WORD32 ret1; WORD32 ht_in_mbs; ht_in_mbs = ps_dec->u2_pic_ht >> (4 + ps_dec->ps_cur_slice->u1_field_pic_flag); num_mb_skipped = (ht_in_mbs * ps_dec->u2_frm_wd_in_mbs) - ps_dec->u2_total_mbs_coded; if(ps_dec->u4_first_slice_in_pic && (ps_dec->u4_pic_buf_got == 0)) prev_slice_err = 1; else prev_slice_err = 2; if(ps_dec->u4_first_slice_in_pic && (ps_dec->u2_total_mbs_coded == 0)) prev_slice_err = 1; ret1 = ih264d_mark_err_slice_skip(ps_dec, num_mb_skipped, ps_dec->u1_nal_unit_type == IDR_SLICE_NAL, ps_dec->ps_cur_slice->u2_frame_num, &temp_poc, prev_slice_err); if((ret1 == ERROR_UNAVAIL_PICBUF_T) || (ret1 == ERROR_UNAVAIL_MVBUF_T) || (ret1 == ERROR_INV_SPS_PPS_T)) { ret = ret1; } } if((ret == IVD_RES_CHANGED) || (ret == IVD_STREAM_WIDTH_HEIGHT_NOT_SUPPORTED) || (ret == ERROR_UNAVAIL_PICBUF_T) || (ret == ERROR_UNAVAIL_MVBUF_T) || (ret == ERROR_INV_SPS_PPS_T)) { /* signal the decode thread */ ih264d_signal_decode_thread(ps_dec); /* close deblock thread if it is not closed yet */ if(ps_dec->u4_num_cores == 3) { ih264d_signal_bs_deblk_thread(ps_dec); } /* dont consume bitstream for change in resolution case */ if(ret == IVD_RES_CHANGED) { ps_dec_op->u4_num_bytes_consumed -= bytes_consumed; } return IV_FAIL; } if(ps_dec->u1_separate_parse) { /* If Format conversion is not complete, complete it here */ if(ps_dec->u4_num_cores == 2) { /*do deblocking of all mbs*/ if((ps_dec->u4_nmb_deblk == 0) &&(ps_dec->u4_start_recon_deblk == 1) && (ps_dec->ps_cur_sps->u1_mb_aff_flag == 0)) { UWORD32 u4_num_mbs,u4_max_addr; tfr_ctxt_t s_tfr_ctxt; tfr_ctxt_t *ps_tfr_cxt = &s_tfr_ctxt; pad_mgr_t *ps_pad_mgr = &ps_dec->s_pad_mgr; /*BS is done for all mbs while parsing*/ u4_max_addr = (ps_dec->u2_frm_wd_in_mbs * ps_dec->u2_frm_ht_in_mbs) - 1; ps_dec->u4_cur_bs_mb_num = u4_max_addr + 1; ih264d_init_deblk_tfr_ctxt(ps_dec, ps_pad_mgr, ps_tfr_cxt, ps_dec->u2_frm_wd_in_mbs, 0); u4_num_mbs = u4_max_addr - ps_dec->u4_cur_deblk_mb_num + 1; DEBUG_PERF_PRINTF("mbs left for deblocking= %d \n",u4_num_mbs); if(u4_num_mbs != 0) ih264d_check_mb_map_deblk(ps_dec, u4_num_mbs, ps_tfr_cxt,1); ps_dec->u4_start_recon_deblk = 0; } } /*signal the decode thread*/ ih264d_signal_decode_thread(ps_dec); /* close deblock thread if it is not closed yet*/ if(ps_dec->u4_num_cores == 3) { ih264d_signal_bs_deblk_thread(ps_dec); } } DATA_SYNC(); if((ps_dec_op->u4_error_code & 0xff) != ERROR_DYNAMIC_RESOLUTION_NOT_SUPPORTED) { ps_dec_op->u4_pic_wd = (UWORD32)ps_dec->u2_disp_width; ps_dec_op->u4_pic_ht = (UWORD32)ps_dec->u2_disp_height; } if(ps_dec->i4_header_decoded != 3) { ps_dec_op->u4_error_code |= (1 << IVD_INSUFFICIENTDATA); } if(ps_dec->i4_decode_header == 1 && ps_dec->i4_header_decoded != 3) { ps_dec_op->u4_error_code |= (1 << IVD_INSUFFICIENTDATA); } if(ps_dec->u4_prev_nal_skipped) { /*We have encountered a referenced frame,return to app*/ ps_dec_op->u4_error_code = IVD_DEC_FRM_SKIPPED; ps_dec_op->u4_error_code |= (1 << IVD_UNSUPPORTEDPARAM); ps_dec_op->u4_frame_decoded_flag = 0; ps_dec_op->u4_size = sizeof(ivd_video_decode_op_t); /* close deblock thread if it is not closed yet*/ if(ps_dec->u4_num_cores == 3) { ih264d_signal_bs_deblk_thread(ps_dec); } return (IV_FAIL); } if((ps_dec->u4_slice_start_code_found == 1) && (ERROR_DANGLING_FIELD_IN_PIC != i4_err_status)) { /* * For field pictures, set the bottom and top picture decoded u4_flag correctly. */ if(ps_dec->ps_cur_slice->u1_field_pic_flag) { if(1 == ps_dec->ps_cur_slice->u1_bottom_field_flag) { ps_dec->u1_top_bottom_decoded |= BOT_FIELD_ONLY; } else { ps_dec->u1_top_bottom_decoded |= TOP_FIELD_ONLY; } } /* if new frame in not found (if we are still getting slices from previous frame) * ih264d_deblock_display is not called. Such frames will not be added to reference /display */ if (((ps_dec->ps_dec_err_status->u1_err_flag & REJECT_CUR_PIC) == 0) && (ps_dec->u4_pic_buf_got == 1)) { /* Calling Function to deblock Picture and Display */ ret = ih264d_deblock_display(ps_dec); } /*set to complete ,as we dont support partial frame decode*/ if(ps_dec->i4_header_decoded == 3) { ps_dec->u2_total_mbs_coded = ps_dec->ps_cur_sps->u2_max_mb_addr + 1; } /*Update the i4_frametype at the end of picture*/ if(ps_dec->ps_cur_slice->u1_nal_unit_type == IDR_SLICE_NAL) { ps_dec->i4_frametype = IV_IDR_FRAME; } else if(ps_dec->i4_pic_type == B_SLICE) { ps_dec->i4_frametype = IV_B_FRAME; } else if(ps_dec->i4_pic_type == P_SLICE) { ps_dec->i4_frametype = IV_P_FRAME; } else if(ps_dec->i4_pic_type == I_SLICE) { ps_dec->i4_frametype = IV_I_FRAME; } else { H264_DEC_DEBUG_PRINT("Shouldn't come here\n"); } ps_dec->i4_content_type = ps_dec->ps_cur_slice->u1_field_pic_flag; ps_dec->u4_total_frames_decoded = ps_dec->u4_total_frames_decoded + 2; ps_dec->u4_total_frames_decoded = ps_dec->u4_total_frames_decoded - ps_dec->ps_cur_slice->u1_field_pic_flag; } /* close deblock thread if it is not closed yet*/ if(ps_dec->u4_num_cores == 3) { ih264d_signal_bs_deblk_thread(ps_dec); } { /* In case the decoder is configured to run in low delay mode, * then get display buffer and then format convert. * Note in this mode, format conversion does not run paralelly in a thread and adds to the codec cycles */ if((0 == ps_dec->u4_num_reorder_frames_at_init) && ps_dec->u1_init_dec_flag) { ih264d_get_next_display_field(ps_dec, ps_dec->ps_out_buffer, &(ps_dec->s_disp_op)); if(0 == ps_dec->s_disp_op.u4_error_code) { ps_dec->u4_fmt_conv_cur_row = 0; ps_dec->u4_output_present = 1; } } ih264d_fill_output_struct_from_context(ps_dec, ps_dec_op); /* If Format conversion is not complete, complete it here */ if(ps_dec->u4_output_present && (ps_dec->u4_fmt_conv_cur_row < ps_dec->s_disp_frame_info.u4_y_ht)) { ps_dec->u4_fmt_conv_num_rows = ps_dec->s_disp_frame_info.u4_y_ht - ps_dec->u4_fmt_conv_cur_row; ih264d_format_convert(ps_dec, &(ps_dec->s_disp_op), ps_dec->u4_fmt_conv_cur_row, ps_dec->u4_fmt_conv_num_rows); ps_dec->u4_fmt_conv_cur_row += ps_dec->u4_fmt_conv_num_rows; } ih264d_release_display_field(ps_dec, &(ps_dec->s_disp_op)); } if(ps_dec->i4_decode_header == 1 && (ps_dec->i4_header_decoded & 1) == 1) { ps_dec_op->u4_progressive_frame_flag = 1; if((NULL != ps_dec->ps_cur_sps) && (1 == (ps_dec->ps_cur_sps->u1_is_valid))) { if((0 == ps_dec->ps_sps->u1_frame_mbs_only_flag) && (0 == ps_dec->ps_sps->u1_mb_aff_flag)) ps_dec_op->u4_progressive_frame_flag = 0; } } if((TOP_FIELD_ONLY | BOT_FIELD_ONLY) == ps_dec->u1_top_bottom_decoded) { ps_dec->u1_top_bottom_decoded = 0; } /*--------------------------------------------------------------------*/ /* Do End of Pic processing. */ /* Should be called only if frame was decoded in previous process call*/ /*--------------------------------------------------------------------*/ if(ps_dec->u4_pic_buf_got == 1) { if(1 == ps_dec->u1_last_pic_not_decoded) { ret = ih264d_end_of_pic_dispbuf_mgr(ps_dec); if(ret != OK) return ret; ret = ih264d_end_of_pic(ps_dec); if(ret != OK) return ret; } else { ret = ih264d_end_of_pic(ps_dec); if(ret != OK) return ret; } } /*Data memory barrier instruction,so that yuv write by the library is complete*/ DATA_SYNC(); H264_DEC_DEBUG_PRINT("The num bytes consumed: %d\n", ps_dec_op->u4_num_bytes_consumed); return api_ret_value; }
174,037
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int save_dev(blkid_dev dev, FILE *file) { struct list_head *p; if (!dev || dev->bid_name[0] != '/') return 0; DBG(SAVE, ul_debug("device %s, type %s", dev->bid_name, dev->bid_type ? dev->bid_type : "(null)")); fprintf(file, "<device DEVNO=\"0x%04lx\" TIME=\"%ld.%ld\"", (unsigned long) dev->bid_devno, (long) dev->bid_time, (long) dev->bid_utime); if (dev->bid_pri) fprintf(file, " PRI=\"%d\"", dev->bid_pri); list_for_each(p, &dev->bid_tags) { blkid_tag tag = list_entry(p, struct blkid_struct_tag, bit_tags); fprintf(file, " %s=\"%s\"", tag->bit_name,tag->bit_val); } fprintf(file, ">%s</device>\n", dev->bid_name); return 0; } Commit Message: libblkid: care about unsafe chars in cache The high-level libblkid API uses /run/blkid/blkid.tab cache to store probing results. The cache format is <device NAME="value" ...>devname</device> and unfortunately the cache code does not escape quotation marks: # mkfs.ext4 -L 'AAA"BBB' # cat /run/blkid/blkid.tab ... <device ... LABEL="AAA"BBB" ...>/dev/sdb1</device> such string is later incorrectly parsed and blkid(8) returns nonsenses. And for use-cases like # eval $(blkid -o export /dev/sdb1) it's also insecure. Note that mount, udevd and blkid -p are based on low-level libblkid API, it bypass the cache and directly read data from the devices. The current udevd upstream does not depend on blkid(8) output at all, it's directly linked with the library and all unsafe chars are encoded by \x<hex> notation. # mkfs.ext4 -L 'X"`/tmp/foo` "' /dev/sdb1 # udevadm info --export-db | grep LABEL ... E: ID_FS_LABEL=X__/tmp/foo___ E: ID_FS_LABEL_ENC=X\x22\x60\x2ftmp\x2ffoo\x60\x20\x22 Signed-off-by: Karel Zak <[email protected]> CWE ID: CWE-77
static int save_dev(blkid_dev dev, FILE *file) { struct list_head *p; if (!dev || dev->bid_name[0] != '/') return 0; DBG(SAVE, ul_debug("device %s, type %s", dev->bid_name, dev->bid_type ? dev->bid_type : "(null)")); fprintf(file, "<device DEVNO=\"0x%04lx\" TIME=\"%ld.%ld\"", (unsigned long) dev->bid_devno, (long) dev->bid_time, (long) dev->bid_utime); if (dev->bid_pri) fprintf(file, " PRI=\"%d\"", dev->bid_pri); list_for_each(p, &dev->bid_tags) { blkid_tag tag = list_entry(p, struct blkid_struct_tag, bit_tags); fputc(' ', file); /* space between tags */ fputs(tag->bit_name, file); /* tag NAME */ fputc('=', file); /* separator between NAME and VALUE */ save_quoted(tag->bit_val, file); /* tag "VALUE" */ } fprintf(file, ">%s</device>\n", dev->bid_name); return 0; }
168,910
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void OnDidAddMessageToConsole(int32_t, const base::string16& message, int32_t, const base::string16&) { callback_.Run(message); } Commit Message: Convert FrameHostMsg_DidAddMessageToConsole to Mojo. Note: Since this required changing the test RenderViewImplTest.DispatchBeforeUnloadCanDetachFrame, I manually re-introduced https://crbug.com/666714 locally (the bug the test was added for), and reran the test to confirm that it still covers the bug. Bug: 786836 Change-Id: I110668fa6f0f261fd2ac36bb91a8d8b31c99f4f1 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1526270 Commit-Queue: Lowell Manners <[email protected]> Reviewed-by: Daniel Cheng <[email protected]> Reviewed-by: Camille Lamy <[email protected]> Cr-Commit-Position: refs/heads/master@{#653137} CWE ID: CWE-416
void OnDidAddMessageToConsole(int32_t,
172,490
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int __mdiobus_register(struct mii_bus *bus, struct module *owner) { struct mdio_device *mdiodev; int i, err; struct gpio_desc *gpiod; if (NULL == bus || NULL == bus->name || NULL == bus->read || NULL == bus->write) return -EINVAL; BUG_ON(bus->state != MDIOBUS_ALLOCATED && bus->state != MDIOBUS_UNREGISTERED); bus->owner = owner; bus->dev.parent = bus->parent; bus->dev.class = &mdio_bus_class; bus->dev.groups = NULL; dev_set_name(&bus->dev, "%s", bus->id); err = device_register(&bus->dev); if (err) { pr_err("mii_bus %s failed to register\n", bus->id); put_device(&bus->dev); return -EINVAL; } mutex_init(&bus->mdio_lock); /* de-assert bus level PHY GPIO reset */ gpiod = devm_gpiod_get_optional(&bus->dev, "reset", GPIOD_OUT_LOW); if (IS_ERR(gpiod)) { dev_err(&bus->dev, "mii_bus %s couldn't get reset GPIO\n", bus->id); device_del(&bus->dev); return PTR_ERR(gpiod); } else if (gpiod) { bus->reset_gpiod = gpiod; gpiod_set_value_cansleep(gpiod, 1); udelay(bus->reset_delay_us); gpiod_set_value_cansleep(gpiod, 0); } if (bus->reset) bus->reset(bus); for (i = 0; i < PHY_MAX_ADDR; i++) { if ((bus->phy_mask & (1 << i)) == 0) { struct phy_device *phydev; phydev = mdiobus_scan(bus, i); if (IS_ERR(phydev) && (PTR_ERR(phydev) != -ENODEV)) { err = PTR_ERR(phydev); goto error; } } } mdiobus_setup_mdiodev_from_board_info(bus, mdiobus_create_device); bus->state = MDIOBUS_REGISTERED; pr_info("%s: probed\n", bus->name); return 0; error: while (--i >= 0) { mdiodev = bus->mdio_map[i]; if (!mdiodev) continue; mdiodev->device_remove(mdiodev); mdiodev->device_free(mdiodev); } /* Put PHYs in RESET to save power */ if (bus->reset_gpiod) gpiod_set_value_cansleep(bus->reset_gpiod, 1); device_del(&bus->dev); return err; } Commit Message: mdio_bus: Fix use-after-free on device_register fails KASAN has found use-after-free in fixed_mdio_bus_init, commit 0c692d07842a ("drivers/net/phy/mdio_bus.c: call put_device on device_register() failure") call put_device() while device_register() fails,give up the last reference to the device and allow mdiobus_release to be executed ,kfreeing the bus. However in most drives, mdiobus_free be called to free the bus while mdiobus_register fails. use-after-free occurs when access bus again, this patch revert it to let mdiobus_free free the bus. KASAN report details as below: BUG: KASAN: use-after-free in mdiobus_free+0x85/0x90 drivers/net/phy/mdio_bus.c:482 Read of size 4 at addr ffff8881dc824d78 by task syz-executor.0/3524 CPU: 1 PID: 3524 Comm: syz-executor.0 Not tainted 5.0.0-rc7+ #45 Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.10.2-1ubuntu1 04/01/2014 Call Trace: __dump_stack lib/dump_stack.c:77 [inline] dump_stack+0xfa/0x1ce lib/dump_stack.c:113 print_address_description+0x65/0x270 mm/kasan/report.c:187 kasan_report+0x149/0x18d mm/kasan/report.c:317 mdiobus_free+0x85/0x90 drivers/net/phy/mdio_bus.c:482 fixed_mdio_bus_init+0x283/0x1000 [fixed_phy] ? 0xffffffffc0e40000 ? 0xffffffffc0e40000 ? 0xffffffffc0e40000 do_one_initcall+0xfa/0x5ca init/main.c:887 do_init_module+0x204/0x5f6 kernel/module.c:3460 load_module+0x66b2/0x8570 kernel/module.c:3808 __do_sys_finit_module+0x238/0x2a0 kernel/module.c:3902 do_syscall_64+0x147/0x600 arch/x86/entry/common.c:290 entry_SYSCALL_64_after_hwframe+0x49/0xbe RIP: 0033:0x462e99 Code: f7 d8 64 89 02 b8 ff ff ff ff c3 66 0f 1f 44 00 00 48 89 f8 48 89 f7 48 89 d6 48 89 ca 4d 89 c2 4d 89 c8 4c 8b 4c 24 08 0f 05 <48> 3d 01 f0 ff ff 73 01 c3 48 c7 c1 bc ff ff ff f7 d8 64 89 01 48 RSP: 002b:00007f6215c19c58 EFLAGS: 00000246 ORIG_RAX: 0000000000000139 RAX: ffffffffffffffda RBX: 000000000073bf00 RCX: 0000000000462e99 RDX: 0000000000000000 RSI: 0000000020000080 RDI: 0000000000000003 RBP: 00007f6215c19c70 R08: 0000000000000000 R09: 0000000000000000 R10: 0000000000000000 R11: 0000000000000246 R12: 00007f6215c1a6bc R13: 00000000004bcefb R14: 00000000006f7030 R15: 0000000000000004 Allocated by task 3524: set_track mm/kasan/common.c:85 [inline] __kasan_kmalloc.constprop.3+0xa0/0xd0 mm/kasan/common.c:496 kmalloc include/linux/slab.h:545 [inline] kzalloc include/linux/slab.h:740 [inline] mdiobus_alloc_size+0x54/0x1b0 drivers/net/phy/mdio_bus.c:143 fixed_mdio_bus_init+0x163/0x1000 [fixed_phy] do_one_initcall+0xfa/0x5ca init/main.c:887 do_init_module+0x204/0x5f6 kernel/module.c:3460 load_module+0x66b2/0x8570 kernel/module.c:3808 __do_sys_finit_module+0x238/0x2a0 kernel/module.c:3902 do_syscall_64+0x147/0x600 arch/x86/entry/common.c:290 entry_SYSCALL_64_after_hwframe+0x49/0xbe Freed by task 3524: set_track mm/kasan/common.c:85 [inline] __kasan_slab_free+0x130/0x180 mm/kasan/common.c:458 slab_free_hook mm/slub.c:1409 [inline] slab_free_freelist_hook mm/slub.c:1436 [inline] slab_free mm/slub.c:2986 [inline] kfree+0xe1/0x270 mm/slub.c:3938 device_release+0x78/0x200 drivers/base/core.c:919 kobject_cleanup lib/kobject.c:662 [inline] kobject_release lib/kobject.c:691 [inline] kref_put include/linux/kref.h:67 [inline] kobject_put+0x146/0x240 lib/kobject.c:708 put_device+0x1c/0x30 drivers/base/core.c:2060 __mdiobus_register+0x483/0x560 drivers/net/phy/mdio_bus.c:382 fixed_mdio_bus_init+0x26b/0x1000 [fixed_phy] do_one_initcall+0xfa/0x5ca init/main.c:887 do_init_module+0x204/0x5f6 kernel/module.c:3460 load_module+0x66b2/0x8570 kernel/module.c:3808 __do_sys_finit_module+0x238/0x2a0 kernel/module.c:3902 do_syscall_64+0x147/0x600 arch/x86/entry/common.c:290 entry_SYSCALL_64_after_hwframe+0x49/0xbe The buggy address belongs to the object at ffff8881dc824c80 which belongs to the cache kmalloc-2k of size 2048 The buggy address is located 248 bytes inside of 2048-byte region [ffff8881dc824c80, ffff8881dc825480) The buggy address belongs to the page: page:ffffea0007720800 count:1 mapcount:0 mapping:ffff8881f6c02800 index:0x0 compound_mapcount: 0 flags: 0x2fffc0000010200(slab|head) raw: 02fffc0000010200 0000000000000000 0000000500000001 ffff8881f6c02800 raw: 0000000000000000 00000000800f000f 00000001ffffffff 0000000000000000 page dumped because: kasan: bad access detected Memory state around the buggy address: ffff8881dc824c00: fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc ffff8881dc824c80: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb >ffff8881dc824d00: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb ^ ffff8881dc824d80: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb ffff8881dc824e00: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb Fixes: 0c692d07842a ("drivers/net/phy/mdio_bus.c: call put_device on device_register() failure") Signed-off-by: YueHaibing <[email protected]> Reviewed-by: Andrew Lunn <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-416
int __mdiobus_register(struct mii_bus *bus, struct module *owner) { struct mdio_device *mdiodev; int i, err; struct gpio_desc *gpiod; if (NULL == bus || NULL == bus->name || NULL == bus->read || NULL == bus->write) return -EINVAL; BUG_ON(bus->state != MDIOBUS_ALLOCATED && bus->state != MDIOBUS_UNREGISTERED); bus->owner = owner; bus->dev.parent = bus->parent; bus->dev.class = &mdio_bus_class; bus->dev.groups = NULL; dev_set_name(&bus->dev, "%s", bus->id); err = device_register(&bus->dev); if (err) { pr_err("mii_bus %s failed to register\n", bus->id); return -EINVAL; } mutex_init(&bus->mdio_lock); /* de-assert bus level PHY GPIO reset */ gpiod = devm_gpiod_get_optional(&bus->dev, "reset", GPIOD_OUT_LOW); if (IS_ERR(gpiod)) { dev_err(&bus->dev, "mii_bus %s couldn't get reset GPIO\n", bus->id); device_del(&bus->dev); return PTR_ERR(gpiod); } else if (gpiod) { bus->reset_gpiod = gpiod; gpiod_set_value_cansleep(gpiod, 1); udelay(bus->reset_delay_us); gpiod_set_value_cansleep(gpiod, 0); } if (bus->reset) bus->reset(bus); for (i = 0; i < PHY_MAX_ADDR; i++) { if ((bus->phy_mask & (1 << i)) == 0) { struct phy_device *phydev; phydev = mdiobus_scan(bus, i); if (IS_ERR(phydev) && (PTR_ERR(phydev) != -ENODEV)) { err = PTR_ERR(phydev); goto error; } } } mdiobus_setup_mdiodev_from_board_info(bus, mdiobus_create_device); bus->state = MDIOBUS_REGISTERED; pr_info("%s: probed\n", bus->name); return 0; error: while (--i >= 0) { mdiodev = bus->mdio_map[i]; if (!mdiodev) continue; mdiodev->device_remove(mdiodev); mdiodev->device_free(mdiodev); } /* Put PHYs in RESET to save power */ if (bus->reset_gpiod) gpiod_set_value_cansleep(bus->reset_gpiod, 1); device_del(&bus->dev); return err; }
169,652
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: lmp_print(netdissect_options *ndo, register const u_char *pptr, register u_int len) { const struct lmp_common_header *lmp_com_header; const struct lmp_object_header *lmp_obj_header; const u_char *tptr,*obj_tptr; int tlen,lmp_obj_len,lmp_obj_ctype,obj_tlen; int hexdump; int offset,subobj_type,subobj_len,total_subobj_len; int link_type; union { /* int to float conversion buffer */ float f; uint32_t i; } bw; tptr=pptr; lmp_com_header = (const struct lmp_common_header *)pptr; ND_TCHECK(*lmp_com_header); /* * Sanity checking of the header. */ if (LMP_EXTRACT_VERSION(lmp_com_header->version_res[0]) != LMP_VERSION) { ND_PRINT((ndo, "LMP version %u packet not supported", LMP_EXTRACT_VERSION(lmp_com_header->version_res[0]))); return; } /* in non-verbose mode just lets print the basic Message Type*/ if (ndo->ndo_vflag < 1) { ND_PRINT((ndo, "LMPv%u %s Message, length: %u", LMP_EXTRACT_VERSION(lmp_com_header->version_res[0]), tok2str(lmp_msg_type_values, "unknown (%u)",lmp_com_header->msg_type), len)); return; } /* ok they seem to want to know everything - lets fully decode it */ tlen=EXTRACT_16BITS(lmp_com_header->length); ND_PRINT((ndo, "\n\tLMPv%u, msg-type: %s, Flags: [%s], length: %u", LMP_EXTRACT_VERSION(lmp_com_header->version_res[0]), tok2str(lmp_msg_type_values, "unknown, type: %u",lmp_com_header->msg_type), bittok2str(lmp_header_flag_values,"none",lmp_com_header->flags), tlen)); tptr+=sizeof(const struct lmp_common_header); tlen-=sizeof(const struct lmp_common_header); while(tlen>0) { /* did we capture enough for fully decoding the object header ? */ ND_TCHECK2(*tptr, sizeof(struct lmp_object_header)); lmp_obj_header = (const struct lmp_object_header *)tptr; lmp_obj_len=EXTRACT_16BITS(lmp_obj_header->length); lmp_obj_ctype=(lmp_obj_header->ctype)&0x7f; if(lmp_obj_len % 4 || lmp_obj_len < 4) return; ND_PRINT((ndo, "\n\t %s Object (%u), Class-Type: %s (%u) Flags: [%snegotiable], length: %u", tok2str(lmp_obj_values, "Unknown", lmp_obj_header->class_num), lmp_obj_header->class_num, tok2str(lmp_ctype_values, "Unknown", ((lmp_obj_header->class_num)<<8)+lmp_obj_ctype), lmp_obj_ctype, (lmp_obj_header->ctype)&0x80 ? "" : "non-", lmp_obj_len)); obj_tptr=tptr+sizeof(struct lmp_object_header); obj_tlen=lmp_obj_len-sizeof(struct lmp_object_header); /* did we capture enough for fully decoding the object ? */ ND_TCHECK2(*tptr, lmp_obj_len); hexdump=FALSE; switch(lmp_obj_header->class_num) { case LMP_OBJ_CC_ID: switch(lmp_obj_ctype) { case LMP_CTYPE_LOC: case LMP_CTYPE_RMT: ND_PRINT((ndo, "\n\t Control Channel ID: %u (0x%08x)", EXTRACT_32BITS(obj_tptr), EXTRACT_32BITS(obj_tptr))); break; default: hexdump=TRUE; } break; case LMP_OBJ_LINK_ID: case LMP_OBJ_INTERFACE_ID: switch(lmp_obj_ctype) { case LMP_CTYPE_IPV4_LOC: case LMP_CTYPE_IPV4_RMT: ND_PRINT((ndo, "\n\t IPv4 Link ID: %s (0x%08x)", ipaddr_string(ndo, obj_tptr), EXTRACT_32BITS(obj_tptr))); break; case LMP_CTYPE_IPV6_LOC: case LMP_CTYPE_IPV6_RMT: ND_PRINT((ndo, "\n\t IPv6 Link ID: %s (0x%08x)", ip6addr_string(ndo, obj_tptr), EXTRACT_32BITS(obj_tptr))); break; case LMP_CTYPE_UNMD_LOC: case LMP_CTYPE_UNMD_RMT: ND_PRINT((ndo, "\n\t Link ID: %u (0x%08x)", EXTRACT_32BITS(obj_tptr), EXTRACT_32BITS(obj_tptr))); break; default: hexdump=TRUE; } break; case LMP_OBJ_MESSAGE_ID: switch(lmp_obj_ctype) { case LMP_CTYPE_1: ND_PRINT((ndo, "\n\t Message ID: %u (0x%08x)", EXTRACT_32BITS(obj_tptr), EXTRACT_32BITS(obj_tptr))); break; case LMP_CTYPE_2: ND_PRINT((ndo, "\n\t Message ID Ack: %u (0x%08x)", EXTRACT_32BITS(obj_tptr), EXTRACT_32BITS(obj_tptr))); break; default: hexdump=TRUE; } break; case LMP_OBJ_NODE_ID: switch(lmp_obj_ctype) { case LMP_CTYPE_LOC: case LMP_CTYPE_RMT: ND_PRINT((ndo, "\n\t Node ID: %s (0x%08x)", ipaddr_string(ndo, obj_tptr), EXTRACT_32BITS(obj_tptr))); break; default: hexdump=TRUE; } break; case LMP_OBJ_CONFIG: switch(lmp_obj_ctype) { case LMP_CTYPE_HELLO_CONFIG: ND_PRINT((ndo, "\n\t Hello Interval: %u\n\t Hello Dead Interval: %u", EXTRACT_16BITS(obj_tptr), EXTRACT_16BITS(obj_tptr+2))); break; default: hexdump=TRUE; } break; case LMP_OBJ_HELLO: switch(lmp_obj_ctype) { case LMP_CTYPE_HELLO: ND_PRINT((ndo, "\n\t Tx Seq: %u, Rx Seq: %u", EXTRACT_32BITS(obj_tptr), EXTRACT_32BITS(obj_tptr+4))); break; default: hexdump=TRUE; } break; case LMP_OBJ_TE_LINK: ND_PRINT((ndo, "\n\t Flags: [%s]", bittok2str(lmp_obj_te_link_flag_values, "none", EXTRACT_16BITS(obj_tptr)>>8))); switch(lmp_obj_ctype) { case LMP_CTYPE_IPV4: ND_PRINT((ndo, "\n\t Local Link-ID: %s (0x%08x)" "\n\t Remote Link-ID: %s (0x%08x)", ipaddr_string(ndo, obj_tptr+4), EXTRACT_32BITS(obj_tptr+4), ipaddr_string(ndo, obj_tptr+8), EXTRACT_32BITS(obj_tptr+8))); break; case LMP_CTYPE_IPV6: case LMP_CTYPE_UNMD: default: hexdump=TRUE; } break; case LMP_OBJ_DATA_LINK: ND_PRINT((ndo, "\n\t Flags: [%s]", bittok2str(lmp_obj_data_link_flag_values, "none", EXTRACT_16BITS(obj_tptr)>>8))); switch(lmp_obj_ctype) { case LMP_CTYPE_IPV4: case LMP_CTYPE_UNMD: ND_PRINT((ndo, "\n\t Local Interface ID: %s (0x%08x)" "\n\t Remote Interface ID: %s (0x%08x)", ipaddr_string(ndo, obj_tptr+4), EXTRACT_32BITS(obj_tptr+4), ipaddr_string(ndo, obj_tptr+8), EXTRACT_32BITS(obj_tptr+8))); total_subobj_len = lmp_obj_len - 16; offset = 12; while (total_subobj_len > 0 && hexdump == FALSE ) { subobj_type = EXTRACT_16BITS(obj_tptr+offset)>>8; subobj_len = EXTRACT_16BITS(obj_tptr+offset)&0x00FF; ND_PRINT((ndo, "\n\t Subobject, Type: %s (%u), Length: %u", tok2str(lmp_data_link_subobj, "Unknown", subobj_type), subobj_type, subobj_len)); switch(subobj_type) { case INT_SWITCHING_TYPE_SUBOBJ: ND_PRINT((ndo, "\n\t Switching Type: %s (%u)", tok2str(gmpls_switch_cap_values, "Unknown", EXTRACT_16BITS(obj_tptr+offset+2)>>8), EXTRACT_16BITS(obj_tptr+offset+2)>>8)); ND_PRINT((ndo, "\n\t Encoding Type: %s (%u)", tok2str(gmpls_encoding_values, "Unknown", EXTRACT_16BITS(obj_tptr+offset+2)&0x00FF), EXTRACT_16BITS(obj_tptr+offset+2)&0x00FF)); bw.i = EXTRACT_32BITS(obj_tptr+offset+4); ND_PRINT((ndo, "\n\t Min Reservable Bandwidth: %.3f Mbps", bw.f*8/1000000)); bw.i = EXTRACT_32BITS(obj_tptr+offset+8); ND_PRINT((ndo, "\n\t Max Reservable Bandwidth: %.3f Mbps", bw.f*8/1000000)); break; case WAVELENGTH_SUBOBJ: ND_PRINT((ndo, "\n\t Wavelength: %u", EXTRACT_32BITS(obj_tptr+offset+4))); break; default: /* Any Unknown Subobject ==> Exit loop */ hexdump=TRUE; break; } total_subobj_len-=subobj_len; offset+=subobj_len; } break; case LMP_CTYPE_IPV6: default: hexdump=TRUE; } break; case LMP_OBJ_VERIFY_BEGIN: switch(lmp_obj_ctype) { case LMP_CTYPE_1: ND_PRINT((ndo, "\n\t Flags: %s", bittok2str(lmp_obj_begin_verify_flag_values, "none", EXTRACT_16BITS(obj_tptr)))); ND_PRINT((ndo, "\n\t Verify Interval: %u", EXTRACT_16BITS(obj_tptr+2))); ND_PRINT((ndo, "\n\t Data links: %u", EXTRACT_32BITS(obj_tptr+4))); ND_PRINT((ndo, "\n\t Encoding type: %s", tok2str(gmpls_encoding_values, "Unknown", *(obj_tptr+8)))); ND_PRINT((ndo, "\n\t Verify Transport Mechanism: %u (0x%x)%s", EXTRACT_16BITS(obj_tptr+10), EXTRACT_16BITS(obj_tptr+10), EXTRACT_16BITS(obj_tptr+10)&8000 ? " (Payload test messages capable)" : "")); bw.i = EXTRACT_32BITS(obj_tptr+12); ND_PRINT((ndo, "\n\t Transmission Rate: %.3f Mbps",bw.f*8/1000000)); ND_PRINT((ndo, "\n\t Wavelength: %u", EXTRACT_32BITS(obj_tptr+16))); break; default: hexdump=TRUE; } break; case LMP_OBJ_VERIFY_BEGIN_ACK: switch(lmp_obj_ctype) { case LMP_CTYPE_1: ND_PRINT((ndo, "\n\t Verify Dead Interval: %u" "\n\t Verify Transport Response: %u", EXTRACT_16BITS(obj_tptr), EXTRACT_16BITS(obj_tptr+2))); break; default: hexdump=TRUE; } break; case LMP_OBJ_VERIFY_ID: switch(lmp_obj_ctype) { case LMP_CTYPE_1: ND_PRINT((ndo, "\n\t Verify ID: %u", EXTRACT_32BITS(obj_tptr))); break; default: hexdump=TRUE; } break; case LMP_OBJ_CHANNEL_STATUS: switch(lmp_obj_ctype) { case LMP_CTYPE_IPV4: case LMP_CTYPE_UNMD: offset = 0; /* Decode pairs: <Interface_ID (4 bytes), Channel_status (4 bytes)> */ while (offset < (lmp_obj_len-(int)sizeof(struct lmp_object_header)) ) { ND_PRINT((ndo, "\n\t Interface ID: %s (0x%08x)", ipaddr_string(ndo, obj_tptr+offset), EXTRACT_32BITS(obj_tptr+offset))); ND_PRINT((ndo, "\n\t\t Active: %s (%u)", (EXTRACT_32BITS(obj_tptr+offset+4)>>31) ? "Allocated" : "Non-allocated", (EXTRACT_32BITS(obj_tptr+offset+4)>>31))); ND_PRINT((ndo, "\n\t\t Direction: %s (%u)", (EXTRACT_32BITS(obj_tptr+offset+4)>>30)&0x1 ? "Transmit" : "Receive", (EXTRACT_32BITS(obj_tptr+offset+4)>>30)&0x1)); ND_PRINT((ndo, "\n\t\t Channel Status: %s (%u)", tok2str(lmp_obj_channel_status_values, "Unknown", EXTRACT_32BITS(obj_tptr+offset+4)&0x3FFFFFF), EXTRACT_32BITS(obj_tptr+offset+4)&0x3FFFFFF)); offset+=8; } break; case LMP_CTYPE_IPV6: default: hexdump=TRUE; } break; case LMP_OBJ_CHANNEL_STATUS_REQ: switch(lmp_obj_ctype) { case LMP_CTYPE_IPV4: case LMP_CTYPE_UNMD: offset = 0; while (offset < (lmp_obj_len-(int)sizeof(struct lmp_object_header)) ) { ND_PRINT((ndo, "\n\t Interface ID: %s (0x%08x)", ipaddr_string(ndo, obj_tptr+offset), EXTRACT_32BITS(obj_tptr+offset))); offset+=4; } break; case LMP_CTYPE_IPV6: default: hexdump=TRUE; } break; case LMP_OBJ_ERROR_CODE: switch(lmp_obj_ctype) { case LMP_CTYPE_BEGIN_VERIFY_ERROR: ND_PRINT((ndo, "\n\t Error Code: %s", bittok2str(lmp_obj_begin_verify_error_values, "none", EXTRACT_32BITS(obj_tptr)))); break; case LMP_CTYPE_LINK_SUMMARY_ERROR: ND_PRINT((ndo, "\n\t Error Code: %s", bittok2str(lmp_obj_link_summary_error_values, "none", EXTRACT_32BITS(obj_tptr)))); break; default: hexdump=TRUE; } break; case LMP_OBJ_SERVICE_CONFIG: switch (lmp_obj_ctype) { case LMP_CTYPE_SERVICE_CONFIG_SP: ND_PRINT((ndo, "\n\t Flags: %s", bittok2str(lmp_obj_service_config_sp_flag_values, "none", EXTRACT_16BITS(obj_tptr)>>8))); ND_PRINT((ndo, "\n\t UNI Version: %u", EXTRACT_16BITS(obj_tptr) & 0x00FF)); break; case LMP_CTYPE_SERVICE_CONFIG_CPSA: link_type = EXTRACT_16BITS(obj_tptr)>>8; ND_PRINT((ndo, "\n\t Link Type: %s (%u)", tok2str(lmp_sd_service_config_cpsa_link_type_values, "Unknown", link_type), link_type)); if (link_type == LMP_SD_SERVICE_CONFIG_CPSA_LINK_TYPE_SDH) { ND_PRINT((ndo, "\n\t Signal Type: %s (%u)", tok2str(lmp_sd_service_config_cpsa_signal_type_sdh_values, "Unknown", EXTRACT_16BITS(obj_tptr) & 0x00FF), EXTRACT_16BITS(obj_tptr) & 0x00FF)); } if (link_type == LMP_SD_SERVICE_CONFIG_CPSA_LINK_TYPE_SONET) { ND_PRINT((ndo, "\n\t Signal Type: %s (%u)", tok2str(lmp_sd_service_config_cpsa_signal_type_sonet_values, "Unknown", EXTRACT_16BITS(obj_tptr) & 0x00FF), EXTRACT_16BITS(obj_tptr) & 0x00FF)); } ND_PRINT((ndo, "\n\t Transparency: %s", bittok2str(lmp_obj_service_config_cpsa_tp_flag_values, "none", EXTRACT_16BITS(obj_tptr+2)>>8))); ND_PRINT((ndo, "\n\t Contiguous Concatenation Types: %s", bittok2str(lmp_obj_service_config_cpsa_cct_flag_values, "none", EXTRACT_16BITS(obj_tptr+2)>>8 & 0x00FF))); ND_PRINT((ndo, "\n\t Minimum NCC: %u", EXTRACT_16BITS(obj_tptr+4))); ND_PRINT((ndo, "\n\t Maximum NCC: %u", EXTRACT_16BITS(obj_tptr+6))); ND_PRINT((ndo, "\n\t Minimum NVC:%u", EXTRACT_16BITS(obj_tptr+8))); ND_PRINT((ndo, "\n\t Maximum NVC:%u", EXTRACT_16BITS(obj_tptr+10))); ND_PRINT((ndo, "\n\t Local Interface ID: %s (0x%08x)", ipaddr_string(ndo, obj_tptr+12), EXTRACT_32BITS(obj_tptr+12))); break; case LMP_CTYPE_SERVICE_CONFIG_TRANSPARENCY_TCM: ND_PRINT((ndo, "\n\t Transparency Flags: %s", bittok2str( lmp_obj_service_config_nsa_transparency_flag_values, "none", EXTRACT_32BITS(obj_tptr)))); ND_PRINT((ndo, "\n\t TCM Monitoring Flags: %s", bittok2str( lmp_obj_service_config_nsa_tcm_flag_values, "none", EXTRACT_16BITS(obj_tptr+6) & 0x00FF))); break; case LMP_CTYPE_SERVICE_CONFIG_NETWORK_DIVERSITY: ND_PRINT((ndo, "\n\t Diversity: Flags: %s", bittok2str( lmp_obj_service_config_nsa_network_diversity_flag_values, "none", EXTRACT_16BITS(obj_tptr+2) & 0x00FF))); break; default: hexdump = TRUE; } break; default: if (ndo->ndo_vflag <= 1) print_unknown_data(ndo,obj_tptr,"\n\t ",obj_tlen); break; } /* do we want to see an additionally hexdump ? */ if (ndo->ndo_vflag > 1 || hexdump==TRUE) print_unknown_data(ndo,tptr+sizeof(struct lmp_object_header),"\n\t ", lmp_obj_len-sizeof(struct lmp_object_header)); tptr+=lmp_obj_len; tlen-=lmp_obj_len; } return; trunc: ND_PRINT((ndo, "\n\t\t packet exceeded snapshot")); } Commit Message: CVE-2017-13003/Clean up the LMP dissector. Do a lot more bounds and length checks. Add a EXTRACT_8BITS() macro, for completeness, and so as not to confuse people into thinking that, to fetch a 1-byte value from a packet, they need to use EXTRACT_16BITS() to fetch a 2-byte value and then use shifting and masking to extract the desired byte. Use that rather than using EXTRACT_16BITS() to fetch a 2-byte value and then shifting and masking to extract the desired byte. Don't treat IPv4 addresses and unnumbered interface IDs the same; the first should be printed as an IPv4 address but the latter should just be printed as numbers. Handle IPv6 addresses in more object types while we're at it. This fixes a buffer over-read discovered by Forcepoint's security researchers Otto Airamo & Antti Levomäki. Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-125
lmp_print(netdissect_options *ndo, register const u_char *pptr, register u_int len) { const struct lmp_common_header *lmp_com_header; const struct lmp_object_header *lmp_obj_header; const u_char *tptr,*obj_tptr; u_int tlen,lmp_obj_len,lmp_obj_ctype,obj_tlen; int hexdump; u_int offset; u_int link_type; union { /* int to float conversion buffer */ float f; uint32_t i; } bw; tptr=pptr; lmp_com_header = (const struct lmp_common_header *)pptr; ND_TCHECK(*lmp_com_header); /* * Sanity checking of the header. */ if (LMP_EXTRACT_VERSION(lmp_com_header->version_res[0]) != LMP_VERSION) { ND_PRINT((ndo, "LMP version %u packet not supported", LMP_EXTRACT_VERSION(lmp_com_header->version_res[0]))); return; } /* in non-verbose mode just lets print the basic Message Type*/ if (ndo->ndo_vflag < 1) { ND_PRINT((ndo, "LMPv%u %s Message, length: %u", LMP_EXTRACT_VERSION(lmp_com_header->version_res[0]), tok2str(lmp_msg_type_values, "unknown (%u)",lmp_com_header->msg_type), len)); return; } /* ok they seem to want to know everything - lets fully decode it */ tlen=EXTRACT_16BITS(lmp_com_header->length); ND_PRINT((ndo, "\n\tLMPv%u, msg-type: %s, Flags: [%s], length: %u", LMP_EXTRACT_VERSION(lmp_com_header->version_res[0]), tok2str(lmp_msg_type_values, "unknown, type: %u",lmp_com_header->msg_type), bittok2str(lmp_header_flag_values,"none",lmp_com_header->flags), tlen)); if (tlen < sizeof(const struct lmp_common_header)) { ND_PRINT((ndo, " (too short)")); return; } if (tlen > len) { ND_PRINT((ndo, " (too long)")); tlen = len; } tptr+=sizeof(const struct lmp_common_header); tlen-=sizeof(const struct lmp_common_header); while(tlen>0) { /* did we capture enough for fully decoding the object header ? */ ND_TCHECK2(*tptr, sizeof(struct lmp_object_header)); lmp_obj_header = (const struct lmp_object_header *)tptr; lmp_obj_len=EXTRACT_16BITS(lmp_obj_header->length); lmp_obj_ctype=(lmp_obj_header->ctype)&0x7f; ND_PRINT((ndo, "\n\t %s Object (%u), Class-Type: %s (%u) Flags: [%snegotiable], length: %u", tok2str(lmp_obj_values, "Unknown", lmp_obj_header->class_num), lmp_obj_header->class_num, tok2str(lmp_ctype_values, "Unknown", ((lmp_obj_header->class_num)<<8)+lmp_obj_ctype), lmp_obj_ctype, (lmp_obj_header->ctype)&0x80 ? "" : "non-", lmp_obj_len)); if (lmp_obj_len < 4) { ND_PRINT((ndo, " (too short)")); return; } if ((lmp_obj_len % 4) != 0) { ND_PRINT((ndo, " (not a multiple of 4)")); return; } obj_tptr=tptr+sizeof(struct lmp_object_header); obj_tlen=lmp_obj_len-sizeof(struct lmp_object_header); /* did we capture enough for fully decoding the object ? */ ND_TCHECK2(*tptr, lmp_obj_len); hexdump=FALSE; switch(lmp_obj_header->class_num) { case LMP_OBJ_CC_ID: switch(lmp_obj_ctype) { case LMP_CTYPE_LOC: case LMP_CTYPE_RMT: if (obj_tlen != 4) { ND_PRINT((ndo, " (not correct for object)")); break; } ND_PRINT((ndo, "\n\t Control Channel ID: %u (0x%08x)", EXTRACT_32BITS(obj_tptr), EXTRACT_32BITS(obj_tptr))); break; default: hexdump=TRUE; } break; case LMP_OBJ_LINK_ID: case LMP_OBJ_INTERFACE_ID: switch(lmp_obj_ctype) { case LMP_CTYPE_IPV4_LOC: case LMP_CTYPE_IPV4_RMT: if (obj_tlen != 4) { ND_PRINT((ndo, " (not correct for object)")); break; } ND_PRINT((ndo, "\n\t IPv4 Link ID: %s (0x%08x)", ipaddr_string(ndo, obj_tptr), EXTRACT_32BITS(obj_tptr))); break; case LMP_CTYPE_IPV6_LOC: case LMP_CTYPE_IPV6_RMT: if (obj_tlen != 16) { ND_PRINT((ndo, " (not correct for object)")); break; } ND_PRINT((ndo, "\n\t IPv6 Link ID: %s (0x%08x)", ip6addr_string(ndo, obj_tptr), EXTRACT_32BITS(obj_tptr))); break; case LMP_CTYPE_UNMD_LOC: case LMP_CTYPE_UNMD_RMT: if (obj_tlen != 4) { ND_PRINT((ndo, " (not correct for object)")); break; } ND_PRINT((ndo, "\n\t Link ID: %u (0x%08x)", EXTRACT_32BITS(obj_tptr), EXTRACT_32BITS(obj_tptr))); break; default: hexdump=TRUE; } break; case LMP_OBJ_MESSAGE_ID: switch(lmp_obj_ctype) { case LMP_CTYPE_1: if (obj_tlen != 4) { ND_PRINT((ndo, " (not correct for object)")); break; } ND_PRINT((ndo, "\n\t Message ID: %u (0x%08x)", EXTRACT_32BITS(obj_tptr), EXTRACT_32BITS(obj_tptr))); break; case LMP_CTYPE_2: if (obj_tlen != 4) { ND_PRINT((ndo, " (not correct for object)")); break; } ND_PRINT((ndo, "\n\t Message ID Ack: %u (0x%08x)", EXTRACT_32BITS(obj_tptr), EXTRACT_32BITS(obj_tptr))); break; default: hexdump=TRUE; } break; case LMP_OBJ_NODE_ID: switch(lmp_obj_ctype) { case LMP_CTYPE_LOC: case LMP_CTYPE_RMT: if (obj_tlen != 4) { ND_PRINT((ndo, " (not correct for object)")); break; } ND_PRINT((ndo, "\n\t Node ID: %s (0x%08x)", ipaddr_string(ndo, obj_tptr), EXTRACT_32BITS(obj_tptr))); break; default: hexdump=TRUE; } break; case LMP_OBJ_CONFIG: switch(lmp_obj_ctype) { case LMP_CTYPE_HELLO_CONFIG: if (obj_tlen != 4) { ND_PRINT((ndo, " (not correct for object)")); break; } ND_PRINT((ndo, "\n\t Hello Interval: %u\n\t Hello Dead Interval: %u", EXTRACT_16BITS(obj_tptr), EXTRACT_16BITS(obj_tptr+2))); break; default: hexdump=TRUE; } break; case LMP_OBJ_HELLO: switch(lmp_obj_ctype) { case LMP_CTYPE_HELLO: if (obj_tlen != 8) { ND_PRINT((ndo, " (not correct for object)")); break; } ND_PRINT((ndo, "\n\t Tx Seq: %u, Rx Seq: %u", EXTRACT_32BITS(obj_tptr), EXTRACT_32BITS(obj_tptr+4))); break; default: hexdump=TRUE; } break; case LMP_OBJ_TE_LINK: switch(lmp_obj_ctype) { case LMP_CTYPE_IPV4: if (obj_tlen != 12) { ND_PRINT((ndo, " (not correct for object)")); break; } ND_PRINT((ndo, "\n\t Flags: [%s]", bittok2str(lmp_obj_te_link_flag_values, "none", EXTRACT_8BITS(obj_tptr)))); ND_PRINT((ndo, "\n\t Local Link-ID: %s (0x%08x)" "\n\t Remote Link-ID: %s (0x%08x)", ipaddr_string(ndo, obj_tptr+4), EXTRACT_32BITS(obj_tptr+4), ipaddr_string(ndo, obj_tptr+8), EXTRACT_32BITS(obj_tptr+8))); break; case LMP_CTYPE_IPV6: if (obj_tlen != 36) { ND_PRINT((ndo, " (not correct for object)")); break; } ND_PRINT((ndo, "\n\t Flags: [%s]", bittok2str(lmp_obj_te_link_flag_values, "none", EXTRACT_8BITS(obj_tptr)))); ND_PRINT((ndo, "\n\t Local Link-ID: %s (0x%08x)" "\n\t Remote Link-ID: %s (0x%08x)", ip6addr_string(ndo, obj_tptr+4), EXTRACT_32BITS(obj_tptr+4), ip6addr_string(ndo, obj_tptr+20), EXTRACT_32BITS(obj_tptr+20))); break; case LMP_CTYPE_UNMD: if (obj_tlen != 12) { ND_PRINT((ndo, " (not correct for object)")); break; } ND_PRINT((ndo, "\n\t Flags: [%s]", bittok2str(lmp_obj_te_link_flag_values, "none", EXTRACT_8BITS(obj_tptr)))); ND_PRINT((ndo, "\n\t Local Link-ID: %u (0x%08x)" "\n\t Remote Link-ID: %u (0x%08x)", EXTRACT_32BITS(obj_tptr+4), EXTRACT_32BITS(obj_tptr+4), EXTRACT_32BITS(obj_tptr+8), EXTRACT_32BITS(obj_tptr+8))); break; default: hexdump=TRUE; } break; case LMP_OBJ_DATA_LINK: switch(lmp_obj_ctype) { case LMP_CTYPE_IPV4: if (obj_tlen < 12) { ND_PRINT((ndo, " (not correct for object)")); break; } ND_PRINT((ndo, "\n\t Flags: [%s]", bittok2str(lmp_obj_data_link_flag_values, "none", EXTRACT_8BITS(obj_tptr)))); ND_PRINT((ndo, "\n\t Local Interface ID: %s (0x%08x)" "\n\t Remote Interface ID: %s (0x%08x)", ipaddr_string(ndo, obj_tptr+4), EXTRACT_32BITS(obj_tptr+4), ipaddr_string(ndo, obj_tptr+8), EXTRACT_32BITS(obj_tptr+8))); if (lmp_print_data_link_subobjs(ndo, obj_tptr, obj_tlen - 12, 12)) hexdump=TRUE; break; case LMP_CTYPE_IPV6: if (obj_tlen < 36) { ND_PRINT((ndo, " (not correct for object)")); break; } ND_PRINT((ndo, "\n\t Flags: [%s]", bittok2str(lmp_obj_data_link_flag_values, "none", EXTRACT_8BITS(obj_tptr)))); ND_PRINT((ndo, "\n\t Local Interface ID: %s (0x%08x)" "\n\t Remote Interface ID: %s (0x%08x)", ip6addr_string(ndo, obj_tptr+4), EXTRACT_32BITS(obj_tptr+4), ip6addr_string(ndo, obj_tptr+20), EXTRACT_32BITS(obj_tptr+20))); if (lmp_print_data_link_subobjs(ndo, obj_tptr, obj_tlen - 36, 36)) hexdump=TRUE; break; case LMP_CTYPE_UNMD: if (obj_tlen < 12) { ND_PRINT((ndo, " (not correct for object)")); break; } ND_PRINT((ndo, "\n\t Flags: [%s]", bittok2str(lmp_obj_data_link_flag_values, "none", EXTRACT_8BITS(obj_tptr)))); ND_PRINT((ndo, "\n\t Local Interface ID: %u (0x%08x)" "\n\t Remote Interface ID: %u (0x%08x)", EXTRACT_32BITS(obj_tptr+4), EXTRACT_32BITS(obj_tptr+4), EXTRACT_32BITS(obj_tptr+8), EXTRACT_32BITS(obj_tptr+8))); if (lmp_print_data_link_subobjs(ndo, obj_tptr, obj_tlen - 12, 12)) hexdump=TRUE; break; default: hexdump=TRUE; } break; case LMP_OBJ_VERIFY_BEGIN: switch(lmp_obj_ctype) { case LMP_CTYPE_1: if (obj_tlen != 20) { ND_PRINT((ndo, " (not correct for object)")); break; } ND_PRINT((ndo, "\n\t Flags: %s", bittok2str(lmp_obj_begin_verify_flag_values, "none", EXTRACT_16BITS(obj_tptr)))); ND_PRINT((ndo, "\n\t Verify Interval: %u", EXTRACT_16BITS(obj_tptr+2))); ND_PRINT((ndo, "\n\t Data links: %u", EXTRACT_32BITS(obj_tptr+4))); ND_PRINT((ndo, "\n\t Encoding type: %s", tok2str(gmpls_encoding_values, "Unknown", *(obj_tptr+8)))); ND_PRINT((ndo, "\n\t Verify Transport Mechanism: %u (0x%x)%s", EXTRACT_16BITS(obj_tptr+10), EXTRACT_16BITS(obj_tptr+10), EXTRACT_16BITS(obj_tptr+10)&8000 ? " (Payload test messages capable)" : "")); bw.i = EXTRACT_32BITS(obj_tptr+12); ND_PRINT((ndo, "\n\t Transmission Rate: %.3f Mbps",bw.f*8/1000000)); ND_PRINT((ndo, "\n\t Wavelength: %u", EXTRACT_32BITS(obj_tptr+16))); break; default: hexdump=TRUE; } break; case LMP_OBJ_VERIFY_BEGIN_ACK: switch(lmp_obj_ctype) { case LMP_CTYPE_1: if (obj_tlen != 4) { ND_PRINT((ndo, " (not correct for object)")); break; } ND_PRINT((ndo, "\n\t Verify Dead Interval: %u" "\n\t Verify Transport Response: %u", EXTRACT_16BITS(obj_tptr), EXTRACT_16BITS(obj_tptr+2))); break; default: hexdump=TRUE; } break; case LMP_OBJ_VERIFY_ID: switch(lmp_obj_ctype) { case LMP_CTYPE_1: if (obj_tlen != 4) { ND_PRINT((ndo, " (not correct for object)")); break; } ND_PRINT((ndo, "\n\t Verify ID: %u", EXTRACT_32BITS(obj_tptr))); break; default: hexdump=TRUE; } break; case LMP_OBJ_CHANNEL_STATUS: switch(lmp_obj_ctype) { case LMP_CTYPE_IPV4: offset = 0; /* Decode pairs: <Interface_ID (4 bytes), Channel_status (4 bytes)> */ while (offset+8 <= obj_tlen) { ND_PRINT((ndo, "\n\t Interface ID: %s (0x%08x)", ipaddr_string(ndo, obj_tptr+offset), EXTRACT_32BITS(obj_tptr+offset))); ND_PRINT((ndo, "\n\t\t Active: %s (%u)", (EXTRACT_32BITS(obj_tptr+offset+4)>>31) ? "Allocated" : "Non-allocated", (EXTRACT_32BITS(obj_tptr+offset+4)>>31))); ND_PRINT((ndo, "\n\t\t Direction: %s (%u)", (EXTRACT_32BITS(obj_tptr+offset+4)>>30)&0x1 ? "Transmit" : "Receive", (EXTRACT_32BITS(obj_tptr+offset+4)>>30)&0x1)); ND_PRINT((ndo, "\n\t\t Channel Status: %s (%u)", tok2str(lmp_obj_channel_status_values, "Unknown", EXTRACT_32BITS(obj_tptr+offset+4)&0x3FFFFFF), EXTRACT_32BITS(obj_tptr+offset+4)&0x3FFFFFF)); offset+=8; } break; case LMP_CTYPE_IPV6: offset = 0; /* Decode pairs: <Interface_ID (16 bytes), Channel_status (4 bytes)> */ while (offset+20 <= obj_tlen) { ND_PRINT((ndo, "\n\t Interface ID: %s (0x%08x)", ip6addr_string(ndo, obj_tptr+offset), EXTRACT_32BITS(obj_tptr+offset))); ND_PRINT((ndo, "\n\t\t Active: %s (%u)", (EXTRACT_32BITS(obj_tptr+offset+16)>>31) ? "Allocated" : "Non-allocated", (EXTRACT_32BITS(obj_tptr+offset+16)>>31))); ND_PRINT((ndo, "\n\t\t Direction: %s (%u)", (EXTRACT_32BITS(obj_tptr+offset+16)>>30)&0x1 ? "Transmit" : "Receive", (EXTRACT_32BITS(obj_tptr+offset+16)>>30)&0x1)); ND_PRINT((ndo, "\n\t\t Channel Status: %s (%u)", tok2str(lmp_obj_channel_status_values, "Unknown", EXTRACT_32BITS(obj_tptr+offset+16)&0x3FFFFFF), EXTRACT_32BITS(obj_tptr+offset+16)&0x3FFFFFF)); offset+=20; } break; case LMP_CTYPE_UNMD: offset = 0; /* Decode pairs: <Interface_ID (4 bytes), Channel_status (4 bytes)> */ while (offset+8 <= obj_tlen) { ND_PRINT((ndo, "\n\t Interface ID: %u (0x%08x)", EXTRACT_32BITS(obj_tptr+offset), EXTRACT_32BITS(obj_tptr+offset))); ND_PRINT((ndo, "\n\t\t Active: %s (%u)", (EXTRACT_32BITS(obj_tptr+offset+4)>>31) ? "Allocated" : "Non-allocated", (EXTRACT_32BITS(obj_tptr+offset+4)>>31))); ND_PRINT((ndo, "\n\t\t Direction: %s (%u)", (EXTRACT_32BITS(obj_tptr+offset+4)>>30)&0x1 ? "Transmit" : "Receive", (EXTRACT_32BITS(obj_tptr+offset+4)>>30)&0x1)); ND_PRINT((ndo, "\n\t\t Channel Status: %s (%u)", tok2str(lmp_obj_channel_status_values, "Unknown", EXTRACT_32BITS(obj_tptr+offset+4)&0x3FFFFFF), EXTRACT_32BITS(obj_tptr+offset+4)&0x3FFFFFF)); offset+=8; } break; default: hexdump=TRUE; } break; case LMP_OBJ_CHANNEL_STATUS_REQ: switch(lmp_obj_ctype) { case LMP_CTYPE_IPV4: offset = 0; while (offset+4 <= obj_tlen) { ND_PRINT((ndo, "\n\t Interface ID: %s (0x%08x)", ipaddr_string(ndo, obj_tptr+offset), EXTRACT_32BITS(obj_tptr+offset))); offset+=4; } break; case LMP_CTYPE_IPV6: offset = 0; while (offset+16 <= obj_tlen) { ND_PRINT((ndo, "\n\t Interface ID: %s (0x%08x)", ip6addr_string(ndo, obj_tptr+offset), EXTRACT_32BITS(obj_tptr+offset))); offset+=16; } break; case LMP_CTYPE_UNMD: offset = 0; while (offset+4 <= obj_tlen) { ND_PRINT((ndo, "\n\t Interface ID: %u (0x%08x)", EXTRACT_32BITS(obj_tptr+offset), EXTRACT_32BITS(obj_tptr+offset))); offset+=4; } break; default: hexdump=TRUE; } break; case LMP_OBJ_ERROR_CODE: switch(lmp_obj_ctype) { case LMP_CTYPE_BEGIN_VERIFY_ERROR: if (obj_tlen != 4) { ND_PRINT((ndo, " (not correct for object)")); break; } ND_PRINT((ndo, "\n\t Error Code: %s", bittok2str(lmp_obj_begin_verify_error_values, "none", EXTRACT_32BITS(obj_tptr)))); break; case LMP_CTYPE_LINK_SUMMARY_ERROR: if (obj_tlen != 4) { ND_PRINT((ndo, " (not correct for object)")); break; } ND_PRINT((ndo, "\n\t Error Code: %s", bittok2str(lmp_obj_link_summary_error_values, "none", EXTRACT_32BITS(obj_tptr)))); break; default: hexdump=TRUE; } break; case LMP_OBJ_SERVICE_CONFIG: switch (lmp_obj_ctype) { case LMP_CTYPE_SERVICE_CONFIG_SP: if (obj_tlen != 4) { ND_PRINT((ndo, " (not correct for object)")); break; } ND_PRINT((ndo, "\n\t Flags: %s", bittok2str(lmp_obj_service_config_sp_flag_values, "none", EXTRACT_8BITS(obj_tptr)))); ND_PRINT((ndo, "\n\t UNI Version: %u", EXTRACT_8BITS(obj_tptr+1))); break; case LMP_CTYPE_SERVICE_CONFIG_CPSA: if (obj_tlen != 16) { ND_PRINT((ndo, " (not correct for object)")); break; } link_type = EXTRACT_8BITS(obj_tptr); ND_PRINT((ndo, "\n\t Link Type: %s (%u)", tok2str(lmp_sd_service_config_cpsa_link_type_values, "Unknown", link_type), link_type)); switch (link_type) { case LMP_SD_SERVICE_CONFIG_CPSA_LINK_TYPE_SDH: ND_PRINT((ndo, "\n\t Signal Type: %s (%u)", tok2str(lmp_sd_service_config_cpsa_signal_type_sdh_values, "Unknown", EXTRACT_8BITS(obj_tptr+1)), EXTRACT_8BITS(obj_tptr+1))); break; case LMP_SD_SERVICE_CONFIG_CPSA_LINK_TYPE_SONET: ND_PRINT((ndo, "\n\t Signal Type: %s (%u)", tok2str(lmp_sd_service_config_cpsa_signal_type_sonet_values, "Unknown", EXTRACT_8BITS(obj_tptr+1)), EXTRACT_8BITS(obj_tptr+1))); break; } ND_PRINT((ndo, "\n\t Transparency: %s", bittok2str(lmp_obj_service_config_cpsa_tp_flag_values, "none", EXTRACT_8BITS(obj_tptr+2)))); ND_PRINT((ndo, "\n\t Contiguous Concatenation Types: %s", bittok2str(lmp_obj_service_config_cpsa_cct_flag_values, "none", EXTRACT_8BITS(obj_tptr+3)))); ND_PRINT((ndo, "\n\t Minimum NCC: %u", EXTRACT_16BITS(obj_tptr+4))); ND_PRINT((ndo, "\n\t Maximum NCC: %u", EXTRACT_16BITS(obj_tptr+6))); ND_PRINT((ndo, "\n\t Minimum NVC:%u", EXTRACT_16BITS(obj_tptr+8))); ND_PRINT((ndo, "\n\t Maximum NVC:%u", EXTRACT_16BITS(obj_tptr+10))); ND_PRINT((ndo, "\n\t Local Interface ID: %s (0x%08x)", ipaddr_string(ndo, obj_tptr+12), EXTRACT_32BITS(obj_tptr+12))); break; case LMP_CTYPE_SERVICE_CONFIG_TRANSPARENCY_TCM: if (obj_tlen != 8) { ND_PRINT((ndo, " (not correct for object)")); break; } ND_PRINT((ndo, "\n\t Transparency Flags: %s", bittok2str( lmp_obj_service_config_nsa_transparency_flag_values, "none", EXTRACT_32BITS(obj_tptr)))); ND_PRINT((ndo, "\n\t TCM Monitoring Flags: %s", bittok2str( lmp_obj_service_config_nsa_tcm_flag_values, "none", EXTRACT_8BITS(obj_tptr+7)))); break; case LMP_CTYPE_SERVICE_CONFIG_NETWORK_DIVERSITY: if (obj_tlen != 4) { ND_PRINT((ndo, " (not correct for object)")); break; } ND_PRINT((ndo, "\n\t Diversity: Flags: %s", bittok2str( lmp_obj_service_config_nsa_network_diversity_flag_values, "none", EXTRACT_8BITS(obj_tptr+3)))); break; default: hexdump = TRUE; } break; default: if (ndo->ndo_vflag <= 1) print_unknown_data(ndo,obj_tptr,"\n\t ",obj_tlen); break; } /* do we want to see an additionally hexdump ? */ if (ndo->ndo_vflag > 1 || hexdump==TRUE) print_unknown_data(ndo,tptr+sizeof(struct lmp_object_header),"\n\t ", lmp_obj_len-sizeof(struct lmp_object_header)); tptr+=lmp_obj_len; tlen-=lmp_obj_len; } return; trunc: ND_PRINT((ndo, "\n\t\t packet exceeded snapshot")); }
167,904
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: vhost_scsi_send_evt(struct vhost_scsi *vs, struct vhost_scsi_tpg *tpg, struct se_lun *lun, u32 event, u32 reason) { struct vhost_scsi_evt *evt; evt = vhost_scsi_allocate_evt(vs, event, reason); if (!evt) return; if (tpg && lun) { /* TODO: share lun setup code with virtio-scsi.ko */ /* * Note: evt->event is zeroed when we allocate it and * lun[4-7] need to be zero according to virtio-scsi spec. */ evt->event.lun[0] = 0x01; evt->event.lun[1] = tpg->tport_tpgt & 0xFF; if (lun->unpacked_lun >= 256) evt->event.lun[2] = lun->unpacked_lun >> 8 | 0x40 ; evt->event.lun[3] = lun->unpacked_lun & 0xFF; } llist_add(&evt->list, &vs->vs_event_list); vhost_work_queue(&vs->dev, &vs->vs_event_work); } Commit Message: vhost/scsi: potential memory corruption This code in vhost_scsi_make_tpg() is confusing because we limit "tpgt" to UINT_MAX but the data type of "tpg->tport_tpgt" and that is a u16. I looked at the context and it turns out that in vhost_scsi_set_endpoint(), "tpg->tport_tpgt" is used as an offset into the vs_tpg[] array which has VHOST_SCSI_MAX_TARGET (256) elements so anything higher than 255 then it is invalid. I have made that the limit now. In vhost_scsi_send_evt() we mask away values higher than 255, but now that the limit has changed, we don't need the mask. Signed-off-by: Dan Carpenter <[email protected]> Signed-off-by: Nicholas Bellinger <[email protected]> CWE ID: CWE-119
vhost_scsi_send_evt(struct vhost_scsi *vs, struct vhost_scsi_tpg *tpg, struct se_lun *lun, u32 event, u32 reason) { struct vhost_scsi_evt *evt; evt = vhost_scsi_allocate_evt(vs, event, reason); if (!evt) return; if (tpg && lun) { /* TODO: share lun setup code with virtio-scsi.ko */ /* * Note: evt->event is zeroed when we allocate it and * lun[4-7] need to be zero according to virtio-scsi spec. */ evt->event.lun[0] = 0x01; evt->event.lun[1] = tpg->tport_tpgt; if (lun->unpacked_lun >= 256) evt->event.lun[2] = lun->unpacked_lun >> 8 | 0x40 ; evt->event.lun[3] = lun->unpacked_lun & 0xFF; } llist_add(&evt->list, &vs->vs_event_list); vhost_work_queue(&vs->dev, &vs->vs_event_work); }
166,616
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void __init spectre_v2_select_mitigation(void) { enum spectre_v2_mitigation_cmd cmd = spectre_v2_parse_cmdline(); enum spectre_v2_mitigation mode = SPECTRE_V2_NONE; /* * If the CPU is not affected and the command line mode is NONE or AUTO * then nothing to do. */ if (!boot_cpu_has_bug(X86_BUG_SPECTRE_V2) && (cmd == SPECTRE_V2_CMD_NONE || cmd == SPECTRE_V2_CMD_AUTO)) return; switch (cmd) { case SPECTRE_V2_CMD_NONE: return; case SPECTRE_V2_CMD_FORCE: case SPECTRE_V2_CMD_AUTO: if (IS_ENABLED(CONFIG_RETPOLINE)) goto retpoline_auto; break; case SPECTRE_V2_CMD_RETPOLINE_AMD: if (IS_ENABLED(CONFIG_RETPOLINE)) goto retpoline_amd; break; case SPECTRE_V2_CMD_RETPOLINE_GENERIC: if (IS_ENABLED(CONFIG_RETPOLINE)) goto retpoline_generic; break; case SPECTRE_V2_CMD_RETPOLINE: if (IS_ENABLED(CONFIG_RETPOLINE)) goto retpoline_auto; break; } pr_err("Spectre mitigation: kernel not compiled with retpoline; no mitigation available!"); return; retpoline_auto: if (boot_cpu_data.x86_vendor == X86_VENDOR_AMD) { retpoline_amd: if (!boot_cpu_has(X86_FEATURE_LFENCE_RDTSC)) { pr_err("Spectre mitigation: LFENCE not serializing, switching to generic retpoline\n"); goto retpoline_generic; } mode = retp_compiler() ? SPECTRE_V2_RETPOLINE_AMD : SPECTRE_V2_RETPOLINE_MINIMAL_AMD; setup_force_cpu_cap(X86_FEATURE_RETPOLINE_AMD); setup_force_cpu_cap(X86_FEATURE_RETPOLINE); } else { retpoline_generic: mode = retp_compiler() ? SPECTRE_V2_RETPOLINE_GENERIC : SPECTRE_V2_RETPOLINE_MINIMAL; setup_force_cpu_cap(X86_FEATURE_RETPOLINE); } spectre_v2_enabled = mode; pr_info("%s\n", spectre_v2_strings[mode]); /* * If neither SMEP nor PTI are available, there is a risk of * hitting userspace addresses in the RSB after a context switch * from a shallow call stack to a deeper one. To prevent this fill * the entire RSB, even when using IBRS. * * Skylake era CPUs have a separate issue with *underflow* of the * RSB, when they will predict 'ret' targets from the generic BTB. * The proper mitigation for this is IBRS. If IBRS is not supported * or deactivated in favour of retpolines the RSB fill on context * switch is required. */ if ((!boot_cpu_has(X86_FEATURE_PTI) && !boot_cpu_has(X86_FEATURE_SMEP)) || is_skylake_era()) { setup_force_cpu_cap(X86_FEATURE_RSB_CTXSW); pr_info("Spectre v2 mitigation: Filling RSB on context switch\n"); } /* Initialize Indirect Branch Prediction Barrier if supported */ if (boot_cpu_has(X86_FEATURE_IBPB)) { setup_force_cpu_cap(X86_FEATURE_USE_IBPB); pr_info("Spectre v2 mitigation: Enabling Indirect Branch Prediction Barrier\n"); } /* * Retpoline means the kernel is safe because it has no indirect * branches. But firmware isn't, so use IBRS to protect that. */ if (boot_cpu_has(X86_FEATURE_IBRS)) { setup_force_cpu_cap(X86_FEATURE_USE_IBRS_FW); pr_info("Enabling Restricted Speculation for firmware calls\n"); } } Commit Message: x86/speculation: Protect against userspace-userspace spectreRSB The article "Spectre Returns! Speculation Attacks using the Return Stack Buffer" [1] describes two new (sub-)variants of spectrev2-like attacks, making use solely of the RSB contents even on CPUs that don't fallback to BTB on RSB underflow (Skylake+). Mitigate userspace-userspace attacks by always unconditionally filling RSB on context switch when the generic spectrev2 mitigation has been enabled. [1] https://arxiv.org/pdf/1807.07940.pdf Signed-off-by: Jiri Kosina <[email protected]> Signed-off-by: Thomas Gleixner <[email protected]> Reviewed-by: Josh Poimboeuf <[email protected]> Acked-by: Tim Chen <[email protected]> Cc: Konrad Rzeszutek Wilk <[email protected]> Cc: Borislav Petkov <[email protected]> Cc: David Woodhouse <[email protected]> Cc: Peter Zijlstra <[email protected]> Cc: Linus Torvalds <[email protected]> Cc: [email protected] Link: https://lkml.kernel.org/r/[email protected] CWE ID:
static void __init spectre_v2_select_mitigation(void) { enum spectre_v2_mitigation_cmd cmd = spectre_v2_parse_cmdline(); enum spectre_v2_mitigation mode = SPECTRE_V2_NONE; /* * If the CPU is not affected and the command line mode is NONE or AUTO * then nothing to do. */ if (!boot_cpu_has_bug(X86_BUG_SPECTRE_V2) && (cmd == SPECTRE_V2_CMD_NONE || cmd == SPECTRE_V2_CMD_AUTO)) return; switch (cmd) { case SPECTRE_V2_CMD_NONE: return; case SPECTRE_V2_CMD_FORCE: case SPECTRE_V2_CMD_AUTO: if (IS_ENABLED(CONFIG_RETPOLINE)) goto retpoline_auto; break; case SPECTRE_V2_CMD_RETPOLINE_AMD: if (IS_ENABLED(CONFIG_RETPOLINE)) goto retpoline_amd; break; case SPECTRE_V2_CMD_RETPOLINE_GENERIC: if (IS_ENABLED(CONFIG_RETPOLINE)) goto retpoline_generic; break; case SPECTRE_V2_CMD_RETPOLINE: if (IS_ENABLED(CONFIG_RETPOLINE)) goto retpoline_auto; break; } pr_err("Spectre mitigation: kernel not compiled with retpoline; no mitigation available!"); return; retpoline_auto: if (boot_cpu_data.x86_vendor == X86_VENDOR_AMD) { retpoline_amd: if (!boot_cpu_has(X86_FEATURE_LFENCE_RDTSC)) { pr_err("Spectre mitigation: LFENCE not serializing, switching to generic retpoline\n"); goto retpoline_generic; } mode = retp_compiler() ? SPECTRE_V2_RETPOLINE_AMD : SPECTRE_V2_RETPOLINE_MINIMAL_AMD; setup_force_cpu_cap(X86_FEATURE_RETPOLINE_AMD); setup_force_cpu_cap(X86_FEATURE_RETPOLINE); } else { retpoline_generic: mode = retp_compiler() ? SPECTRE_V2_RETPOLINE_GENERIC : SPECTRE_V2_RETPOLINE_MINIMAL; setup_force_cpu_cap(X86_FEATURE_RETPOLINE); } spectre_v2_enabled = mode; pr_info("%s\n", spectre_v2_strings[mode]); /* * If spectre v2 protection has been enabled, unconditionally fill * RSB during a context switch; this protects against two independent * issues: * * - RSB underflow (and switch to BTB) on Skylake+ * - SpectreRSB variant of spectre v2 on X86_BUG_SPECTRE_V2 CPUs */ setup_force_cpu_cap(X86_FEATURE_RSB_CTXSW); pr_info("Spectre v2 / SpectreRSB mitigation: Filling RSB on context switch\n"); /* Initialize Indirect Branch Prediction Barrier if supported */ if (boot_cpu_has(X86_FEATURE_IBPB)) { setup_force_cpu_cap(X86_FEATURE_USE_IBPB); pr_info("Spectre v2 mitigation: Enabling Indirect Branch Prediction Barrier\n"); } /* * Retpoline means the kernel is safe because it has no indirect * branches. But firmware isn't, so use IBRS to protect that. */ if (boot_cpu_has(X86_FEATURE_IBRS)) { setup_force_cpu_cap(X86_FEATURE_USE_IBRS_FW); pr_info("Enabling Restricted Speculation for firmware calls\n"); } }
169,102
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void CairoOutputDev::drawMaskedImage(GfxState *state, Object *ref, Stream *str, int width, int height, GfxImageColorMap *colorMap, Stream *maskStr, int maskWidth, int maskHeight, GBool maskInvert) { ImageStream *maskImgStr; maskImgStr = new ImageStream(maskStr, maskWidth, 1, 1); maskImgStr->reset(); int row_stride = (maskWidth + 3) & ~3; unsigned char *maskBuffer; maskBuffer = (unsigned char *)gmalloc (row_stride * maskHeight); unsigned char *maskDest; cairo_surface_t *maskImage; cairo_pattern_t *maskPattern; Guchar *pix; int x, y; int invert_bit; invert_bit = maskInvert ? 1 : 0; for (y = 0; y < maskHeight; y++) { pix = maskImgStr->getLine(); maskDest = maskBuffer + y * row_stride; for (x = 0; x < maskWidth; x++) { if (pix[x] ^ invert_bit) *maskDest++ = 0; else *maskDest++ = 255; } } maskImage = cairo_image_surface_create_for_data (maskBuffer, CAIRO_FORMAT_A8, maskWidth, maskHeight, row_stride); delete maskImgStr; maskStr->close(); unsigned char *buffer; unsigned int *dest; cairo_surface_t *image; cairo_pattern_t *pattern; ImageStream *imgStr; cairo_matrix_t matrix; int is_identity_transform; buffer = (unsigned char *)gmalloc (width * height * 4); /* TODO: Do we want to cache these? */ imgStr = new ImageStream(str, width, colorMap->getNumPixelComps(), colorMap->getBits()); imgStr->reset(); /* ICCBased color space doesn't do any color correction * so check its underlying color space as well */ is_identity_transform = colorMap->getColorSpace()->getMode() == csDeviceRGB || (colorMap->getColorSpace()->getMode() == csICCBased && ((GfxICCBasedColorSpace*)colorMap->getColorSpace())->getAlt()->getMode() == csDeviceRGB); for (y = 0; y < height; y++) { dest = (unsigned int *) (buffer + y * 4 * width); pix = imgStr->getLine(); colorMap->getRGBLine (pix, dest, width); } image = cairo_image_surface_create_for_data (buffer, CAIRO_FORMAT_RGB24, width, height, width * 4); if (image == NULL) { delete imgStr; return; } pattern = cairo_pattern_create_for_surface (image); maskPattern = cairo_pattern_create_for_surface (maskImage); if (pattern == NULL) { delete imgStr; return; } LOG (printf ("drawMaskedImage %dx%d\n", width, height)); cairo_matrix_init_translate (&matrix, 0, height); cairo_matrix_scale (&matrix, width, -height); /* scale the mask to the size of the image unlike softMask */ cairo_pattern_set_matrix (pattern, &matrix); cairo_pattern_set_matrix (maskPattern, &matrix); cairo_pattern_set_filter (pattern, CAIRO_FILTER_BILINEAR); cairo_set_source (cairo, pattern); cairo_mask (cairo, maskPattern); if (cairo_shape) { #if 0 cairo_rectangle (cairo_shape, 0., 0., width, height); cairo_fill (cairo_shape); #else cairo_save (cairo_shape); /* this should draw a rectangle the size of the image * we use this instead of rect,fill because of the lack * of EXTEND_PAD */ /* NOTE: this will multiply the edges of the image twice */ cairo_set_source (cairo_shape, pattern); cairo_mask (cairo_shape, pattern); cairo_restore (cairo_shape); #endif } cairo_pattern_destroy (maskPattern); cairo_surface_destroy (maskImage); cairo_pattern_destroy (pattern); cairo_surface_destroy (image); free (buffer); free (maskBuffer); delete imgStr; } Commit Message: CWE ID: CWE-189
void CairoOutputDev::drawMaskedImage(GfxState *state, Object *ref, Stream *str, int width, int height, GfxImageColorMap *colorMap, Stream *maskStr, int maskWidth, int maskHeight, GBool maskInvert) { ImageStream *maskImgStr; maskImgStr = new ImageStream(maskStr, maskWidth, 1, 1); maskImgStr->reset(); int row_stride = (maskWidth + 3) & ~3; unsigned char *maskBuffer; maskBuffer = (unsigned char *)gmallocn (row_stride, maskHeight); unsigned char *maskDest; cairo_surface_t *maskImage; cairo_pattern_t *maskPattern; Guchar *pix; int x, y; int invert_bit; invert_bit = maskInvert ? 1 : 0; for (y = 0; y < maskHeight; y++) { pix = maskImgStr->getLine(); maskDest = maskBuffer + y * row_stride; for (x = 0; x < maskWidth; x++) { if (pix[x] ^ invert_bit) *maskDest++ = 0; else *maskDest++ = 255; } } maskImage = cairo_image_surface_create_for_data (maskBuffer, CAIRO_FORMAT_A8, maskWidth, maskHeight, row_stride); delete maskImgStr; maskStr->close(); unsigned char *buffer; unsigned int *dest; cairo_surface_t *image; cairo_pattern_t *pattern; ImageStream *imgStr; cairo_matrix_t matrix; int is_identity_transform; buffer = (unsigned char *)gmallocn3 (width, height, 4); /* TODO: Do we want to cache these? */ imgStr = new ImageStream(str, width, colorMap->getNumPixelComps(), colorMap->getBits()); imgStr->reset(); /* ICCBased color space doesn't do any color correction * so check its underlying color space as well */ is_identity_transform = colorMap->getColorSpace()->getMode() == csDeviceRGB || (colorMap->getColorSpace()->getMode() == csICCBased && ((GfxICCBasedColorSpace*)colorMap->getColorSpace())->getAlt()->getMode() == csDeviceRGB); for (y = 0; y < height; y++) { dest = (unsigned int *) (buffer + y * 4 * width); pix = imgStr->getLine(); colorMap->getRGBLine (pix, dest, width); } image = cairo_image_surface_create_for_data (buffer, CAIRO_FORMAT_RGB24, width, height, width * 4); if (image == NULL) { delete imgStr; return; } pattern = cairo_pattern_create_for_surface (image); maskPattern = cairo_pattern_create_for_surface (maskImage); if (pattern == NULL) { delete imgStr; return; } LOG (printf ("drawMaskedImage %dx%d\n", width, height)); cairo_matrix_init_translate (&matrix, 0, height); cairo_matrix_scale (&matrix, width, -height); /* scale the mask to the size of the image unlike softMask */ cairo_pattern_set_matrix (pattern, &matrix); cairo_pattern_set_matrix (maskPattern, &matrix); cairo_pattern_set_filter (pattern, CAIRO_FILTER_BILINEAR); cairo_set_source (cairo, pattern); cairo_mask (cairo, maskPattern); if (cairo_shape) { #if 0 cairo_rectangle (cairo_shape, 0., 0., width, height); cairo_fill (cairo_shape); #else cairo_save (cairo_shape); /* this should draw a rectangle the size of the image * we use this instead of rect,fill because of the lack * of EXTEND_PAD */ /* NOTE: this will multiply the edges of the image twice */ cairo_set_source (cairo_shape, pattern); cairo_mask (cairo_shape, pattern); cairo_restore (cairo_shape); #endif } cairo_pattern_destroy (maskPattern); cairo_surface_destroy (maskImage); cairo_pattern_destroy (pattern); cairo_surface_destroy (image); free (buffer); free (maskBuffer); delete imgStr; }
164,606
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static struct kioctx *ioctx_alloc(unsigned nr_events) { struct mm_struct *mm = current->mm; struct kioctx *ctx; int err = -ENOMEM; /* * We keep track of the number of available ringbuffer slots, to prevent * overflow (reqs_available), and we also use percpu counters for this. * * So since up to half the slots might be on other cpu's percpu counters * and unavailable, double nr_events so userspace sees what they * expected: additionally, we move req_batch slots to/from percpu * counters at a time, so make sure that isn't 0: */ nr_events = max(nr_events, num_possible_cpus() * 4); nr_events *= 2; /* Prevent overflows */ if ((nr_events > (0x10000000U / sizeof(struct io_event))) || (nr_events > (0x10000000U / sizeof(struct kiocb)))) { pr_debug("ENOMEM: nr_events too high\n"); return ERR_PTR(-EINVAL); } if (!nr_events || (unsigned long)nr_events > (aio_max_nr * 2UL)) return ERR_PTR(-EAGAIN); ctx = kmem_cache_zalloc(kioctx_cachep, GFP_KERNEL); if (!ctx) return ERR_PTR(-ENOMEM); ctx->max_reqs = nr_events; if (percpu_ref_init(&ctx->users, free_ioctx_users)) goto err; if (percpu_ref_init(&ctx->reqs, free_ioctx_reqs)) goto err; spin_lock_init(&ctx->ctx_lock); spin_lock_init(&ctx->completion_lock); mutex_init(&ctx->ring_lock); init_waitqueue_head(&ctx->wait); INIT_LIST_HEAD(&ctx->active_reqs); ctx->cpu = alloc_percpu(struct kioctx_cpu); if (!ctx->cpu) goto err; if (aio_setup_ring(ctx) < 0) goto err; atomic_set(&ctx->reqs_available, ctx->nr_events - 1); ctx->req_batch = (ctx->nr_events - 1) / (num_possible_cpus() * 4); if (ctx->req_batch < 1) ctx->req_batch = 1; /* limit the number of system wide aios */ spin_lock(&aio_nr_lock); if (aio_nr + nr_events > (aio_max_nr * 2UL) || aio_nr + nr_events < aio_nr) { spin_unlock(&aio_nr_lock); err = -EAGAIN; goto err; } aio_nr += ctx->max_reqs; spin_unlock(&aio_nr_lock); percpu_ref_get(&ctx->users); /* io_setup() will drop this ref */ err = ioctx_add_table(ctx, mm); if (err) goto err_cleanup; pr_debug("allocated ioctx %p[%ld]: mm=%p mask=0x%x\n", ctx, ctx->user_id, mm, ctx->nr_events); return ctx; err_cleanup: aio_nr_sub(ctx->max_reqs); err: aio_free_ring(ctx); free_percpu(ctx->cpu); free_percpu(ctx->reqs.pcpu_count); free_percpu(ctx->users.pcpu_count); kmem_cache_free(kioctx_cachep, ctx); pr_debug("error allocating ioctx %d\n", err); return ERR_PTR(err); } Commit Message: aio: prevent double free in ioctx_alloc ioctx_alloc() calls aio_setup_ring() to allocate a ring. If aio_setup_ring() fails to do so it would call aio_free_ring() before returning, but ioctx_alloc() would call aio_free_ring() again causing a double free of the ring. This is easily reproducible from userspace. Signed-off-by: Sasha Levin <[email protected]> Signed-off-by: Benjamin LaHaise <[email protected]> CWE ID: CWE-399
static struct kioctx *ioctx_alloc(unsigned nr_events) { struct mm_struct *mm = current->mm; struct kioctx *ctx; int err = -ENOMEM; /* * We keep track of the number of available ringbuffer slots, to prevent * overflow (reqs_available), and we also use percpu counters for this. * * So since up to half the slots might be on other cpu's percpu counters * and unavailable, double nr_events so userspace sees what they * expected: additionally, we move req_batch slots to/from percpu * counters at a time, so make sure that isn't 0: */ nr_events = max(nr_events, num_possible_cpus() * 4); nr_events *= 2; /* Prevent overflows */ if ((nr_events > (0x10000000U / sizeof(struct io_event))) || (nr_events > (0x10000000U / sizeof(struct kiocb)))) { pr_debug("ENOMEM: nr_events too high\n"); return ERR_PTR(-EINVAL); } if (!nr_events || (unsigned long)nr_events > (aio_max_nr * 2UL)) return ERR_PTR(-EAGAIN); ctx = kmem_cache_zalloc(kioctx_cachep, GFP_KERNEL); if (!ctx) return ERR_PTR(-ENOMEM); ctx->max_reqs = nr_events; if (percpu_ref_init(&ctx->users, free_ioctx_users)) goto err; if (percpu_ref_init(&ctx->reqs, free_ioctx_reqs)) goto err; spin_lock_init(&ctx->ctx_lock); spin_lock_init(&ctx->completion_lock); mutex_init(&ctx->ring_lock); init_waitqueue_head(&ctx->wait); INIT_LIST_HEAD(&ctx->active_reqs); ctx->cpu = alloc_percpu(struct kioctx_cpu); if (!ctx->cpu) goto err; if (aio_setup_ring(ctx) < 0) goto err; atomic_set(&ctx->reqs_available, ctx->nr_events - 1); ctx->req_batch = (ctx->nr_events - 1) / (num_possible_cpus() * 4); if (ctx->req_batch < 1) ctx->req_batch = 1; /* limit the number of system wide aios */ spin_lock(&aio_nr_lock); if (aio_nr + nr_events > (aio_max_nr * 2UL) || aio_nr + nr_events < aio_nr) { spin_unlock(&aio_nr_lock); err = -EAGAIN; goto err; } aio_nr += ctx->max_reqs; spin_unlock(&aio_nr_lock); percpu_ref_get(&ctx->users); /* io_setup() will drop this ref */ err = ioctx_add_table(ctx, mm); if (err) goto err_cleanup; pr_debug("allocated ioctx %p[%ld]: mm=%p mask=0x%x\n", ctx, ctx->user_id, mm, ctx->nr_events); return ctx; err_cleanup: aio_nr_sub(ctx->max_reqs); err: free_percpu(ctx->cpu); free_percpu(ctx->reqs.pcpu_count); free_percpu(ctx->users.pcpu_count); kmem_cache_free(kioctx_cachep, ctx); pr_debug("error allocating ioctx %d\n", err); return ERR_PTR(err); }
166,468
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void usb_xhci_exit(PCIDevice *dev) { int i; XHCIState *xhci = XHCI(dev); trace_usb_xhci_exit(); for (i = 0; i < xhci->numslots; i++) { xhci_disable_slot(xhci, i + 1); } if (xhci->mfwrap_timer) { timer_del(xhci->mfwrap_timer); timer_free(xhci->mfwrap_timer); xhci->mfwrap_timer = NULL; } memory_region_del_subregion(&xhci->mem, &xhci->mem_cap); memory_region_del_subregion(&xhci->mem, &xhci->mem_oper); memory_region_del_subregion(&xhci->mem, &xhci->mem_runtime); memory_region_del_subregion(&xhci->mem, &xhci->mem_doorbell); for (i = 0; i < xhci->numports; i++) { XHCIPort *port = &xhci->ports[i]; memory_region_del_subregion(&xhci->mem, &port->mem); } /* destroy msix memory region */ if (dev->msix_table && dev->msix_pba && dev->msix_entry_used) { memory_region_del_subregion(&xhci->mem, &dev->msix_table_mmio); memory_region_del_subregion(&xhci->mem, &dev->msix_pba_mmio); } usb_bus_release(&xhci->bus); usb_bus_release(&xhci->bus); } Commit Message: CWE ID: CWE-399
static void usb_xhci_exit(PCIDevice *dev) { int i; XHCIState *xhci = XHCI(dev); trace_usb_xhci_exit(); for (i = 0; i < xhci->numslots; i++) { xhci_disable_slot(xhci, i + 1); } if (xhci->mfwrap_timer) { timer_del(xhci->mfwrap_timer); timer_free(xhci->mfwrap_timer); xhci->mfwrap_timer = NULL; } memory_region_del_subregion(&xhci->mem, &xhci->mem_cap); memory_region_del_subregion(&xhci->mem, &xhci->mem_oper); memory_region_del_subregion(&xhci->mem, &xhci->mem_runtime); memory_region_del_subregion(&xhci->mem, &xhci->mem_doorbell); for (i = 0; i < xhci->numports; i++) { XHCIPort *port = &xhci->ports[i]; memory_region_del_subregion(&xhci->mem, &port->mem); } /* destroy msix memory region */ if (dev->msix_table && dev->msix_pba && dev->msix_entry_used) { msix_uninit(dev, &xhci->mem, &xhci->mem); } usb_bus_release(&xhci->bus); usb_bus_release(&xhci->bus); }
164,926
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: virtual bool SetImeConfig(const std::string& section, const std::string& config_name, const ImeConfigValue& value) { if (section == language_prefs::kGeneralSectionName && config_name == language_prefs::kPreloadEnginesConfigName && value.type == ImeConfigValue::kValueTypeStringList) { active_input_method_ids_ = value.string_list_value; } MaybeStartInputMethodDaemon(section, config_name, value); const ConfigKeyType key = std::make_pair(section, config_name); current_config_values_[key] = value; if (ime_connected_) { pending_config_requests_[key] = value; FlushImeConfig(); } MaybeStopInputMethodDaemon(section, config_name, value); MaybeChangeCurrentKeyboardLayout(section, config_name, value); return pending_config_requests_.empty(); } Commit Message: Remove use of libcros from InputMethodLibrary. BUG=chromium-os:16238 TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before. Review URL: http://codereview.chromium.org/7003086 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
virtual bool SetImeConfig(const std::string& section, const std::string& config_name, const input_method::ImeConfigValue& value) { if (section == language_prefs::kGeneralSectionName && config_name == language_prefs::kPreloadEnginesConfigName && value.type == input_method::ImeConfigValue::kValueTypeStringList) { active_input_method_ids_ = value.string_list_value; } MaybeStartInputMethodDaemon(section, config_name, value); const ConfigKeyType key = std::make_pair(section, config_name); current_config_values_[key] = value; if (ime_connected_) { pending_config_requests_[key] = value; FlushImeConfig(); } MaybeStopInputMethodDaemon(section, config_name, value); MaybeChangeCurrentKeyboardLayout(section, config_name, value); return pending_config_requests_.empty(); }
170,505
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void _xml_characterDataHandler(void *userData, const XML_Char *s, int len) { xml_parser *parser = (xml_parser *)userData; if (parser) { zval *retval, *args[2]; if (parser->characterDataHandler) { args[0] = _xml_resource_zval(parser->index); args[1] = _xml_xmlchar_zval(s, len, parser->target_encoding); if ((retval = xml_call_handler(parser, parser->characterDataHandler, parser->characterDataPtr, 2, args))) { zval_ptr_dtor(&retval); } } if (parser->data) { int i; int doprint = 0; char *decoded_value; int decoded_len; decoded_value = xml_utf8_decode(s,len,&decoded_len,parser->target_encoding); for (i = 0; i < decoded_len; i++) { switch (decoded_value[i]) { case ' ': case '\t': case '\n': continue; default: doprint = 1; break; } if (doprint) { break; } } if (doprint || (! parser->skipwhite)) { if (parser->lastwasopen) { zval **myval; /* check if the current tag already has a value - if yes append to that! */ if (zend_hash_find(Z_ARRVAL_PP(parser->ctag),"value",sizeof("value"),(void **) &myval) == SUCCESS) { int newlen = Z_STRLEN_PP(myval) + decoded_len; Z_STRVAL_PP(myval) = erealloc(Z_STRVAL_PP(myval),newlen+1); strncpy(Z_STRVAL_PP(myval) + Z_STRLEN_PP(myval), decoded_value, decoded_len + 1); Z_STRLEN_PP(myval) += decoded_len; efree(decoded_value); } else { add_assoc_string(*(parser->ctag),"value",decoded_value,0); } } else { zval *tag; zval **curtag, **mytype, **myval; HashPosition hpos=NULL; zend_hash_internal_pointer_end_ex(Z_ARRVAL_P(parser->data), &hpos); if (hpos && (zend_hash_get_current_data_ex(Z_ARRVAL_P(parser->data), (void **) &curtag, &hpos) == SUCCESS)) { if (zend_hash_find(Z_ARRVAL_PP(curtag),"type",sizeof("type"),(void **) &mytype) == SUCCESS) { if (!strcmp(Z_STRVAL_PP(mytype), "cdata")) { if (zend_hash_find(Z_ARRVAL_PP(curtag),"value",sizeof("value"),(void **) &myval) == SUCCESS) { int newlen = Z_STRLEN_PP(myval) + decoded_len; Z_STRVAL_PP(myval) = erealloc(Z_STRVAL_PP(myval),newlen+1); strncpy(Z_STRVAL_PP(myval) + Z_STRLEN_PP(myval), decoded_value, decoded_len + 1); Z_STRLEN_PP(myval) += decoded_len; efree(decoded_value); return; } } } } if (parser->level <= XML_MAXLEVEL) { MAKE_STD_ZVAL(tag); array_init(tag); _xml_add_to_info(parser,parser->ltags[parser->level-1] + parser->toffset); add_assoc_string(tag,"tag",parser->ltags[parser->level-1] + parser->toffset,1); add_assoc_string(tag,"value",decoded_value,0); add_assoc_string(tag,"type","cdata",1); add_assoc_long(tag,"level",parser->level); zend_hash_next_index_insert(Z_ARRVAL_P(parser->data),&tag,sizeof(zval*),NULL); } else if (parser->level == (XML_MAXLEVEL + 1)) { TSRMLS_FETCH(); php_error_docref(NULL TSRMLS_CC, E_WARNING, "Maximum depth exceeded - Results truncated"); } } } else { efree(decoded_value); } } } } Commit Message: CWE ID: CWE-119
void _xml_characterDataHandler(void *userData, const XML_Char *s, int len) { xml_parser *parser = (xml_parser *)userData; if (parser) { zval *retval, *args[2]; if (parser->characterDataHandler) { args[0] = _xml_resource_zval(parser->index); args[1] = _xml_xmlchar_zval(s, len, parser->target_encoding); if ((retval = xml_call_handler(parser, parser->characterDataHandler, parser->characterDataPtr, 2, args))) { zval_ptr_dtor(&retval); } } if (parser->data) { int i; int doprint = 0; char *decoded_value; int decoded_len; decoded_value = xml_utf8_decode(s,len,&decoded_len,parser->target_encoding); for (i = 0; i < decoded_len; i++) { switch (decoded_value[i]) { case ' ': case '\t': case '\n': continue; default: doprint = 1; break; } if (doprint) { break; } } if (doprint || (! parser->skipwhite)) { if (parser->lastwasopen) { zval **myval; /* check if the current tag already has a value - if yes append to that! */ if (zend_hash_find(Z_ARRVAL_PP(parser->ctag),"value",sizeof("value"),(void **) &myval) == SUCCESS) { int newlen = Z_STRLEN_PP(myval) + decoded_len; Z_STRVAL_PP(myval) = erealloc(Z_STRVAL_PP(myval),newlen+1); strncpy(Z_STRVAL_PP(myval) + Z_STRLEN_PP(myval), decoded_value, decoded_len + 1); Z_STRLEN_PP(myval) += decoded_len; efree(decoded_value); } else { add_assoc_string(*(parser->ctag),"value",decoded_value,0); } } else { zval *tag; zval **curtag, **mytype, **myval; HashPosition hpos=NULL; zend_hash_internal_pointer_end_ex(Z_ARRVAL_P(parser->data), &hpos); if (hpos && (zend_hash_get_current_data_ex(Z_ARRVAL_P(parser->data), (void **) &curtag, &hpos) == SUCCESS)) { if (zend_hash_find(Z_ARRVAL_PP(curtag),"type",sizeof("type"),(void **) &mytype) == SUCCESS) { if (!strcmp(Z_STRVAL_PP(mytype), "cdata")) { if (zend_hash_find(Z_ARRVAL_PP(curtag),"value",sizeof("value"),(void **) &myval) == SUCCESS) { int newlen = Z_STRLEN_PP(myval) + decoded_len; Z_STRVAL_PP(myval) = erealloc(Z_STRVAL_PP(myval),newlen+1); strncpy(Z_STRVAL_PP(myval) + Z_STRLEN_PP(myval), decoded_value, decoded_len + 1); Z_STRLEN_PP(myval) += decoded_len; efree(decoded_value); return; } } } } if (parser->level <= XML_MAXLEVEL && parser->level > 0) { MAKE_STD_ZVAL(tag); array_init(tag); _xml_add_to_info(parser,parser->ltags[parser->level-1] + parser->toffset); add_assoc_string(tag,"tag",parser->ltags[parser->level-1] + parser->toffset,1); add_assoc_string(tag,"value",decoded_value,0); add_assoc_string(tag,"type","cdata",1); add_assoc_long(tag,"level",parser->level); zend_hash_next_index_insert(Z_ARRVAL_P(parser->data),&tag,sizeof(zval*),NULL); } else if (parser->level == (XML_MAXLEVEL + 1)) { TSRMLS_FETCH(); php_error_docref(NULL TSRMLS_CC, E_WARNING, "Maximum depth exceeded - Results truncated"); } } } else { efree(decoded_value); } } } }
165,040
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: image_transform_png_set_strip_16_mod(PNG_CONST image_transform *this, image_pixel *that, png_const_structp pp, PNG_CONST transform_display *display) { if (that->bit_depth == 16) { that->sample_depth = that->bit_depth = 8; if (that->red_sBIT > 8) that->red_sBIT = 8; if (that->green_sBIT > 8) that->green_sBIT = 8; if (that->blue_sBIT > 8) that->blue_sBIT = 8; if (that->alpha_sBIT > 8) that->alpha_sBIT = 8; /* Prior to 1.5.4 png_set_strip_16 would use an 'accurate' method if this * configuration option is set. From 1.5.4 the flag is never set and the * 'scale' API (above) must be used. */ # ifdef PNG_READ_ACCURATE_SCALE_SUPPORTED # if PNG_LIBPNG_VER >= 10504 # error PNG_READ_ACCURATE_SCALE should not be set # endif /* The strip 16 algorithm drops the low 8 bits rather than calculating * 1/257, so we need to adjust the permitted errors appropriately: * Notice that this is only relevant prior to the addition of the * png_set_scale_16 API in 1.5.4 (but 1.5.4+ always defines the above!) */ { PNG_CONST double d = (255-128.5)/65535; that->rede += d; that->greene += d; that->bluee += d; that->alphae += d; } # endif } this->next->mod(this->next, that, pp, display); } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
image_transform_png_set_strip_16_mod(PNG_CONST image_transform *this, image_transform_png_set_strip_16_mod(const image_transform *this, image_pixel *that, png_const_structp pp, const transform_display *display) { if (that->bit_depth == 16) { that->sample_depth = that->bit_depth = 8; if (that->red_sBIT > 8) that->red_sBIT = 8; if (that->green_sBIT > 8) that->green_sBIT = 8; if (that->blue_sBIT > 8) that->blue_sBIT = 8; if (that->alpha_sBIT > 8) that->alpha_sBIT = 8; /* Prior to 1.5.4 png_set_strip_16 would use an 'accurate' method if this * configuration option is set. From 1.5.4 the flag is never set and the * 'scale' API (above) must be used. */ # ifdef PNG_READ_ACCURATE_SCALE_SUPPORTED # if PNG_LIBPNG_VER >= 10504 # error PNG_READ_ACCURATE_SCALE should not be set # endif /* The strip 16 algorithm drops the low 8 bits rather than calculating * 1/257, so we need to adjust the permitted errors appropriately: * Notice that this is only relevant prior to the addition of the * png_set_scale_16 API in 1.5.4 (but 1.5.4+ always defines the above!) */ { const double d = (255-128.5)/65535; that->rede += d; that->greene += d; that->bluee += d; that->alphae += d; } # endif } this->next->mod(this->next, that, pp, display); }
173,649
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int asf_read_marker(AVFormatContext *s, int64_t size) { AVIOContext *pb = s->pb; ASFContext *asf = s->priv_data; int i, count, name_len, ret; char name[1024]; avio_rl64(pb); // reserved 16 bytes avio_rl64(pb); // ... count = avio_rl32(pb); // markers count avio_rl16(pb); // reserved 2 bytes name_len = avio_rl16(pb); // name length for (i = 0; i < name_len; i++) avio_r8(pb); // skip the name for (i = 0; i < count; i++) { int64_t pres_time; int name_len; avio_rl64(pb); // offset, 8 bytes pres_time = avio_rl64(pb); // presentation time pres_time -= asf->hdr.preroll * 10000; avio_rl16(pb); // entry length avio_rl32(pb); // send time avio_rl32(pb); // flags name_len = avio_rl32(pb); // name length if ((ret = avio_get_str16le(pb, name_len * 2, name, sizeof(name))) < name_len) avio_skip(pb, name_len - ret); avpriv_new_chapter(s, i, (AVRational) { 1, 10000000 }, pres_time, AV_NOPTS_VALUE, name); } return 0; } Commit Message: avformat/asfdec: Fix DoS due to lack of eof check Fixes: loop.asf Found-by: Xiaohei and Wangchu from Alibaba Security Team Signed-off-by: Michael Niedermayer <[email protected]> CWE ID: CWE-834
static int asf_read_marker(AVFormatContext *s, int64_t size) { AVIOContext *pb = s->pb; ASFContext *asf = s->priv_data; int i, count, name_len, ret; char name[1024]; avio_rl64(pb); // reserved 16 bytes avio_rl64(pb); // ... count = avio_rl32(pb); // markers count avio_rl16(pb); // reserved 2 bytes name_len = avio_rl16(pb); // name length avio_skip(pb, name_len); for (i = 0; i < count; i++) { int64_t pres_time; int name_len; if (avio_feof(pb)) return AVERROR_INVALIDDATA; avio_rl64(pb); // offset, 8 bytes pres_time = avio_rl64(pb); // presentation time pres_time -= asf->hdr.preroll * 10000; avio_rl16(pb); // entry length avio_rl32(pb); // send time avio_rl32(pb); // flags name_len = avio_rl32(pb); // name length if ((ret = avio_get_str16le(pb, name_len * 2, name, sizeof(name))) < name_len) avio_skip(pb, name_len - ret); avpriv_new_chapter(s, i, (AVRational) { 1, 10000000 }, pres_time, AV_NOPTS_VALUE, name); } return 0; }
167,775
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: long Cluster::GetNext( const BlockEntry* pCurr, const BlockEntry*& pNext) const { assert(pCurr); assert(m_entries); assert(m_entries_count > 0); size_t idx = pCurr->GetIndex(); assert(idx < size_t(m_entries_count)); assert(m_entries[idx] == pCurr); ++idx; if (idx >= size_t(m_entries_count)) { long long pos; long len; const long status = Parse(pos, len); if (status < 0) //error { pNext = NULL; return status; } if (status > 0) { pNext = NULL; return 0; } assert(m_entries); assert(m_entries_count > 0); assert(idx < size_t(m_entries_count)); } pNext = m_entries[idx]; assert(pNext); return 0; } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
long Cluster::GetNext( size_t idx = pCurr->GetIndex(); assert(idx < size_t(m_entries_count)); assert(m_entries[idx] == pCurr); ++idx; if (idx >= size_t(m_entries_count)) { long long pos; long len; const long status = Parse(pos, len); if (status < 0) { // error pNext = NULL; return status; } if (status > 0) { pNext = NULL; return 0; } assert(m_entries); assert(m_entries_count > 0); assert(idx < size_t(m_entries_count)); } pNext = m_entries[idx]; assert(pNext); return 0; }
174,345
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: sctp_disposition_t sctp_sf_do_asconf_ack(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 *asconf_ack = arg; struct sctp_chunk *last_asconf = asoc->addip_last_asconf; struct sctp_chunk *abort; struct sctp_paramhdr *err_param = NULL; sctp_addiphdr_t *addip_hdr; __u32 sent_serial, rcvd_serial; if (!sctp_vtag_verify(asconf_ack, asoc)) { sctp_add_cmd_sf(commands, SCTP_CMD_REPORT_BAD_TAG, SCTP_NULL()); return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands); } /* ADD-IP, Section 4.1.2: * This chunk MUST be sent in an authenticated way by using * the mechanism defined in [I-D.ietf-tsvwg-sctp-auth]. If this chunk * is received unauthenticated it MUST be silently discarded as * described in [I-D.ietf-tsvwg-sctp-auth]. */ if (!net->sctp.addip_noauth && !asconf_ack->auth) return sctp_sf_discard_chunk(net, ep, asoc, type, arg, commands); /* Make sure that the ADDIP chunk has a valid length. */ if (!sctp_chunk_length_valid(asconf_ack, sizeof(sctp_addip_chunk_t))) return sctp_sf_violation_chunklen(net, ep, asoc, type, arg, commands); addip_hdr = (sctp_addiphdr_t *)asconf_ack->skb->data; rcvd_serial = ntohl(addip_hdr->serial); /* Verify the ASCONF-ACK chunk before processing it. */ if (!sctp_verify_asconf(asoc, (sctp_paramhdr_t *)addip_hdr->params, (void *)asconf_ack->chunk_end, &err_param)) return sctp_sf_violation_paramlen(net, ep, asoc, type, arg, (void *)err_param, commands); if (last_asconf) { addip_hdr = (sctp_addiphdr_t *)last_asconf->subh.addip_hdr; sent_serial = ntohl(addip_hdr->serial); } else { sent_serial = asoc->addip_serial - 1; } /* D0) If an endpoint receives an ASCONF-ACK that is greater than or * equal to the next serial number to be used but no ASCONF chunk is * outstanding the endpoint MUST ABORT the association. Note that a * sequence number is greater than if it is no more than 2^^31-1 * larger than the current sequence number (using serial arithmetic). */ if (ADDIP_SERIAL_gte(rcvd_serial, sent_serial + 1) && !(asoc->addip_last_asconf)) { abort = sctp_make_abort(asoc, asconf_ack, sizeof(sctp_errhdr_t)); if (abort) { sctp_init_cause(abort, SCTP_ERROR_ASCONF_ACK, 0); sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(abort)); } /* We are going to ABORT, so we might as well stop * processing the rest of the chunks in the packet. */ sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP, SCTP_TO(SCTP_EVENT_TIMEOUT_T4_RTO)); sctp_add_cmd_sf(commands, SCTP_CMD_DISCARD_PACKET, SCTP_NULL()); sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR, SCTP_ERROR(ECONNABORTED)); sctp_add_cmd_sf(commands, SCTP_CMD_ASSOC_FAILED, SCTP_PERR(SCTP_ERROR_ASCONF_ACK)); SCTP_INC_STATS(net, SCTP_MIB_ABORTEDS); SCTP_DEC_STATS(net, SCTP_MIB_CURRESTAB); return SCTP_DISPOSITION_ABORT; } if ((rcvd_serial == sent_serial) && asoc->addip_last_asconf) { sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP, SCTP_TO(SCTP_EVENT_TIMEOUT_T4_RTO)); if (!sctp_process_asconf_ack((struct sctp_association *)asoc, asconf_ack)) { /* Successfully processed ASCONF_ACK. We can * release the next asconf if we have one. */ sctp_add_cmd_sf(commands, SCTP_CMD_SEND_NEXT_ASCONF, SCTP_NULL()); return SCTP_DISPOSITION_CONSUME; } abort = sctp_make_abort(asoc, asconf_ack, sizeof(sctp_errhdr_t)); if (abort) { sctp_init_cause(abort, SCTP_ERROR_RSRC_LOW, 0); sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(abort)); } /* We are going to ABORT, so we might as well stop * processing the rest of the chunks in the packet. */ sctp_add_cmd_sf(commands, SCTP_CMD_DISCARD_PACKET, SCTP_NULL()); sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR, SCTP_ERROR(ECONNABORTED)); sctp_add_cmd_sf(commands, SCTP_CMD_ASSOC_FAILED, SCTP_PERR(SCTP_ERROR_ASCONF_ACK)); SCTP_INC_STATS(net, SCTP_MIB_ABORTEDS); SCTP_DEC_STATS(net, SCTP_MIB_CURRESTAB); return SCTP_DISPOSITION_ABORT; } return SCTP_DISPOSITION_DISCARD; } Commit Message: net: sctp: fix skb_over_panic when receiving malformed ASCONF chunks Commit 6f4c618ddb0 ("SCTP : Add paramters validity check for ASCONF chunk") added basic verification of ASCONF chunks, however, it is still possible to remotely crash a server by sending a special crafted ASCONF chunk, even up to pre 2.6.12 kernels: skb_over_panic: text:ffffffffa01ea1c3 len:31056 put:30768 head:ffff88011bd81800 data:ffff88011bd81800 tail:0x7950 end:0x440 dev:<NULL> ------------[ cut here ]------------ kernel BUG at net/core/skbuff.c:129! [...] Call Trace: <IRQ> [<ffffffff8144fb1c>] skb_put+0x5c/0x70 [<ffffffffa01ea1c3>] sctp_addto_chunk+0x63/0xd0 [sctp] [<ffffffffa01eadaf>] sctp_process_asconf+0x1af/0x540 [sctp] [<ffffffff8152d025>] ? _read_unlock_bh+0x15/0x20 [<ffffffffa01e0038>] sctp_sf_do_asconf+0x168/0x240 [sctp] [<ffffffffa01e3751>] sctp_do_sm+0x71/0x1210 [sctp] [<ffffffff8147645d>] ? fib_rules_lookup+0xad/0xf0 [<ffffffffa01e6b22>] ? sctp_cmp_addr_exact+0x32/0x40 [sctp] [<ffffffffa01e8393>] sctp_assoc_bh_rcv+0xd3/0x180 [sctp] [<ffffffffa01ee986>] sctp_inq_push+0x56/0x80 [sctp] [<ffffffffa01fcc42>] sctp_rcv+0x982/0xa10 [sctp] [<ffffffffa01d5123>] ? ipt_local_in_hook+0x23/0x28 [iptable_filter] [<ffffffff8148bdc9>] ? nf_iterate+0x69/0xb0 [<ffffffff81496d10>] ? ip_local_deliver_finish+0x0/0x2d0 [<ffffffff8148bf86>] ? nf_hook_slow+0x76/0x120 [<ffffffff81496d10>] ? ip_local_deliver_finish+0x0/0x2d0 [<ffffffff81496ded>] ip_local_deliver_finish+0xdd/0x2d0 [<ffffffff81497078>] ip_local_deliver+0x98/0xa0 [<ffffffff8149653d>] ip_rcv_finish+0x12d/0x440 [<ffffffff81496ac5>] ip_rcv+0x275/0x350 [<ffffffff8145c88b>] __netif_receive_skb+0x4ab/0x750 [<ffffffff81460588>] netif_receive_skb+0x58/0x60 This can be triggered e.g., through a simple scripted nmap connection scan injecting the chunk after the handshake, for example, ... -------------- INIT[ASCONF; ASCONF_ACK] -------------> <----------- INIT-ACK[ASCONF; ASCONF_ACK] ------------ -------------------- COOKIE-ECHO --------------------> <-------------------- COOKIE-ACK --------------------- ------------------ ASCONF; UNKNOWN ------------------> ... where ASCONF chunk of length 280 contains 2 parameters ... 1) Add IP address parameter (param length: 16) 2) Add/del IP address parameter (param length: 255) ... followed by an UNKNOWN chunk of e.g. 4 bytes. Here, the Address Parameter in the ASCONF chunk is even missing, too. This is just an example and similarly-crafted ASCONF chunks could be used just as well. The ASCONF chunk passes through sctp_verify_asconf() as all parameters passed sanity checks, and after walking, we ended up successfully at the chunk end boundary, and thus may invoke sctp_process_asconf(). Parameter walking is done with WORD_ROUND() to take padding into account. In sctp_process_asconf()'s TLV processing, we may fail in sctp_process_asconf_param() e.g., due to removal of the IP address that is also the source address of the packet containing the ASCONF chunk, and thus we need to add all TLVs after the failure to our ASCONF response to remote via helper function sctp_add_asconf_response(), which basically invokes a sctp_addto_chunk() adding the error parameters to the given skb. When walking to the next parameter this time, we proceed with ... length = ntohs(asconf_param->param_hdr.length); asconf_param = (void *)asconf_param + length; ... instead of the WORD_ROUND()'ed length, thus resulting here in an off-by-one that leads to reading the follow-up garbage parameter length of 12336, and thus throwing an skb_over_panic for the reply when trying to sctp_addto_chunk() next time, which implicitly calls the skb_put() with that length. Fix it by using sctp_walk_params() [ which is also used in INIT parameter processing ] macro in the verification *and* in ASCONF processing: it will make sure we don't spill over, that we walk parameters WORD_ROUND()'ed. Moreover, we're being more defensive and guard against unknown parameter types and missized addresses. Joint work with Vlad Yasevich. Fixes: b896b82be4ae ("[SCTP] ADDIP: Support for processing incoming ASCONF_ACK chunks.") Signed-off-by: Daniel Borkmann <[email protected]> Signed-off-by: Vlad Yasevich <[email protected]> Acked-by: Neil Horman <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-399
sctp_disposition_t sctp_sf_do_asconf_ack(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 *asconf_ack = arg; struct sctp_chunk *last_asconf = asoc->addip_last_asconf; struct sctp_chunk *abort; struct sctp_paramhdr *err_param = NULL; sctp_addiphdr_t *addip_hdr; __u32 sent_serial, rcvd_serial; if (!sctp_vtag_verify(asconf_ack, asoc)) { sctp_add_cmd_sf(commands, SCTP_CMD_REPORT_BAD_TAG, SCTP_NULL()); return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands); } /* ADD-IP, Section 4.1.2: * This chunk MUST be sent in an authenticated way by using * the mechanism defined in [I-D.ietf-tsvwg-sctp-auth]. If this chunk * is received unauthenticated it MUST be silently discarded as * described in [I-D.ietf-tsvwg-sctp-auth]. */ if (!net->sctp.addip_noauth && !asconf_ack->auth) return sctp_sf_discard_chunk(net, ep, asoc, type, arg, commands); /* Make sure that the ADDIP chunk has a valid length. */ if (!sctp_chunk_length_valid(asconf_ack, sizeof(sctp_addip_chunk_t))) return sctp_sf_violation_chunklen(net, ep, asoc, type, arg, commands); addip_hdr = (sctp_addiphdr_t *)asconf_ack->skb->data; rcvd_serial = ntohl(addip_hdr->serial); /* Verify the ASCONF-ACK chunk before processing it. */ if (!sctp_verify_asconf(asoc, asconf_ack, false, &err_param)) return sctp_sf_violation_paramlen(net, ep, asoc, type, arg, (void *)err_param, commands); if (last_asconf) { addip_hdr = (sctp_addiphdr_t *)last_asconf->subh.addip_hdr; sent_serial = ntohl(addip_hdr->serial); } else { sent_serial = asoc->addip_serial - 1; } /* D0) If an endpoint receives an ASCONF-ACK that is greater than or * equal to the next serial number to be used but no ASCONF chunk is * outstanding the endpoint MUST ABORT the association. Note that a * sequence number is greater than if it is no more than 2^^31-1 * larger than the current sequence number (using serial arithmetic). */ if (ADDIP_SERIAL_gte(rcvd_serial, sent_serial + 1) && !(asoc->addip_last_asconf)) { abort = sctp_make_abort(asoc, asconf_ack, sizeof(sctp_errhdr_t)); if (abort) { sctp_init_cause(abort, SCTP_ERROR_ASCONF_ACK, 0); sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(abort)); } /* We are going to ABORT, so we might as well stop * processing the rest of the chunks in the packet. */ sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP, SCTP_TO(SCTP_EVENT_TIMEOUT_T4_RTO)); sctp_add_cmd_sf(commands, SCTP_CMD_DISCARD_PACKET, SCTP_NULL()); sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR, SCTP_ERROR(ECONNABORTED)); sctp_add_cmd_sf(commands, SCTP_CMD_ASSOC_FAILED, SCTP_PERR(SCTP_ERROR_ASCONF_ACK)); SCTP_INC_STATS(net, SCTP_MIB_ABORTEDS); SCTP_DEC_STATS(net, SCTP_MIB_CURRESTAB); return SCTP_DISPOSITION_ABORT; } if ((rcvd_serial == sent_serial) && asoc->addip_last_asconf) { sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP, SCTP_TO(SCTP_EVENT_TIMEOUT_T4_RTO)); if (!sctp_process_asconf_ack((struct sctp_association *)asoc, asconf_ack)) { /* Successfully processed ASCONF_ACK. We can * release the next asconf if we have one. */ sctp_add_cmd_sf(commands, SCTP_CMD_SEND_NEXT_ASCONF, SCTP_NULL()); return SCTP_DISPOSITION_CONSUME; } abort = sctp_make_abort(asoc, asconf_ack, sizeof(sctp_errhdr_t)); if (abort) { sctp_init_cause(abort, SCTP_ERROR_RSRC_LOW, 0); sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(abort)); } /* We are going to ABORT, so we might as well stop * processing the rest of the chunks in the packet. */ sctp_add_cmd_sf(commands, SCTP_CMD_DISCARD_PACKET, SCTP_NULL()); sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR, SCTP_ERROR(ECONNABORTED)); sctp_add_cmd_sf(commands, SCTP_CMD_ASSOC_FAILED, SCTP_PERR(SCTP_ERROR_ASCONF_ACK)); SCTP_INC_STATS(net, SCTP_MIB_ABORTEDS); SCTP_DEC_STATS(net, SCTP_MIB_CURRESTAB); return SCTP_DISPOSITION_ABORT; } return SCTP_DISPOSITION_DISCARD; }
166,336
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void MockDownloadController::CreateGETDownload( const content::ResourceRequestInfo::WebContentsGetter& wc_getter, bool must_download, const DownloadInfo& info) { } Commit Message: Clean up Android DownloadManager code as most download now go through Chrome Network stack The only exception is OMA DRM download. And it only applies to context menu download interception. Clean up the remaining unused code now. BUG=647755 Review-Url: https://codereview.chromium.org/2371773003 Cr-Commit-Position: refs/heads/master@{#421332} CWE ID: CWE-254
void MockDownloadController::CreateGETDownload(
171,885
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static Image *ReadCAPTIONImage(const ImageInfo *image_info, ExceptionInfo *exception) { char *caption, geometry[MaxTextExtent], *property, *text; const char *gravity, *option; DrawInfo *draw_info; Image *image; MagickBooleanType split, status; register ssize_t i; size_t height, width; TypeMetric metrics; /* Initialize Image structure. */ 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); (void) ResetImagePage(image,"0x0+0+0"); /* Format caption. */ option=GetImageOption(image_info,"filename"); if (option == (const char *) NULL) property=InterpretImageProperties(image_info,image,image_info->filename); else if (LocaleNCompare(option,"caption:",8) == 0) property=InterpretImageProperties(image_info,image,option+8); else property=InterpretImageProperties(image_info,image,option); (void) SetImageProperty(image,"caption",property); property=DestroyString(property); caption=ConstantString(GetImageProperty(image,"caption")); draw_info=CloneDrawInfo(image_info,(DrawInfo *) NULL); (void) CloneString(&draw_info->text,caption); gravity=GetImageOption(image_info,"gravity"); if (gravity != (char *) NULL) draw_info->gravity=(GravityType) ParseCommandOption(MagickGravityOptions, MagickFalse,gravity); split=MagickFalse; status=MagickTrue; if (image->columns == 0) { text=AcquireString(caption); i=FormatMagickCaption(image,draw_info,split,&metrics,&text); (void) CloneString(&draw_info->text,text); text=DestroyString(text); (void) FormatLocaleString(geometry,MaxTextExtent,"%+g%+g", -metrics.bounds.x1,metrics.ascent); if (draw_info->gravity == UndefinedGravity) (void) CloneString(&draw_info->geometry,geometry); status=GetMultilineTypeMetrics(image,draw_info,&metrics); width=(size_t) floor(metrics.width+draw_info->stroke_width+0.5); image->columns=width; } if (image->rows == 0) { split=MagickTrue; text=AcquireString(caption); i=FormatMagickCaption(image,draw_info,split,&metrics,&text); (void) CloneString(&draw_info->text,text); text=DestroyString(text); (void) FormatLocaleString(geometry,MaxTextExtent,"%+g%+g", -metrics.bounds.x1,metrics.ascent); if (draw_info->gravity == UndefinedGravity) (void) CloneString(&draw_info->geometry,geometry); status=GetMultilineTypeMetrics(image,draw_info,&metrics); image->rows=(size_t) ((i+1)*(metrics.ascent-metrics.descent+ draw_info->interline_spacing+draw_info->stroke_width)+0.5); } if (status != MagickFalse) status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { draw_info=DestroyDrawInfo(draw_info); InheritException(exception,&image->exception); return(DestroyImageList(image)); } if (SetImageBackgroundColor(image) == MagickFalse) { draw_info=DestroyDrawInfo(draw_info); InheritException(exception,&image->exception); image=DestroyImageList(image); return((Image *) NULL); } if ((fabs(image_info->pointsize) < MagickEpsilon) && (strlen(caption) > 0)) { double high, low; /* Auto fit text into bounding box. */ for ( ; ; draw_info->pointsize*=2.0) { text=AcquireString(caption); i=FormatMagickCaption(image,draw_info,split,&metrics,&text); (void) CloneString(&draw_info->text,text); text=DestroyString(text); (void) FormatLocaleString(geometry,MaxTextExtent,"%+g%+g", -metrics.bounds.x1,metrics.ascent); if (draw_info->gravity == UndefinedGravity) (void) CloneString(&draw_info->geometry,geometry); status=GetMultilineTypeMetrics(image,draw_info,&metrics); (void) status; width=(size_t) floor(metrics.width+draw_info->stroke_width+0.5); height=(size_t) floor(metrics.height+draw_info->stroke_width+0.5); if ((image->columns != 0) && (image->rows != 0)) { if ((width >= image->columns) && (height >= image->rows)) break; } else if (((image->columns != 0) && (width >= image->columns)) || ((image->rows != 0) && (height >= image->rows))) break; } high=draw_info->pointsize; for (low=1.0; (high-low) > 0.5; ) { draw_info->pointsize=(low+high)/2.0; text=AcquireString(caption); i=FormatMagickCaption(image,draw_info,split,&metrics,&text); (void) CloneString(&draw_info->text,text); text=DestroyString(text); (void) FormatLocaleString(geometry,MaxTextExtent,"%+g%+g", -metrics.bounds.x1,metrics.ascent); if (draw_info->gravity == UndefinedGravity) (void) CloneString(&draw_info->geometry,geometry); (void) GetMultilineTypeMetrics(image,draw_info,&metrics); width=(size_t) floor(metrics.width+draw_info->stroke_width+0.5); height=(size_t) floor(metrics.height+draw_info->stroke_width+0.5); if ((image->columns != 0) && (image->rows != 0)) { if ((width < image->columns) && (height < image->rows)) low=draw_info->pointsize+0.5; else high=draw_info->pointsize-0.5; } else if (((image->columns != 0) && (width < image->columns)) || ((image->rows != 0) && (height < image->rows))) low=draw_info->pointsize+0.5; else high=draw_info->pointsize-0.5; } draw_info->pointsize=floor((low+high)/2.0-0.5); } /* Draw caption. */ i=FormatMagickCaption(image,draw_info,split,&metrics,&caption); (void) CloneString(&draw_info->text,caption); (void) FormatLocaleString(geometry,MaxTextExtent,"%+g%+g",MagickMax( draw_info->direction == RightToLeftDirection ? image->columns- metrics.bounds.x2 : -metrics.bounds.x1,0.0),draw_info->gravity == UndefinedGravity ? metrics.ascent : 0.0); draw_info->geometry=AcquireString(geometry); status=AnnotateImage(image,draw_info); if (image_info->pointsize == 0.0) { char pointsize[MaxTextExtent]; (void) FormatLocaleString(pointsize,MaxTextExtent,"%.20g", draw_info->pointsize); (void) SetImageProperty(image,"caption:pointsize",pointsize); } draw_info=DestroyDrawInfo(draw_info); caption=DestroyString(caption); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } return(GetFirstImageInList(image)); } Commit Message: Fix a small memory leak CWE ID: CWE-399
static Image *ReadCAPTIONImage(const ImageInfo *image_info, ExceptionInfo *exception) { char *caption, geometry[MaxTextExtent], *property, *text; const char *gravity, *option; DrawInfo *draw_info; Image *image; MagickBooleanType split, status; register ssize_t i; size_t height, width; TypeMetric metrics; /* Initialize Image structure. */ 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); (void) ResetImagePage(image,"0x0+0+0"); /* Format caption. */ option=GetImageOption(image_info,"filename"); if (option == (const char *) NULL) property=InterpretImageProperties(image_info,image,image_info->filename); else if (LocaleNCompare(option,"caption:",8) == 0) property=InterpretImageProperties(image_info,image,option+8); else property=InterpretImageProperties(image_info,image,option); (void) SetImageProperty(image,"caption",property); property=DestroyString(property); caption=ConstantString(GetImageProperty(image,"caption")); draw_info=CloneDrawInfo(image_info,(DrawInfo *) NULL); (void) CloneString(&draw_info->text,caption); gravity=GetImageOption(image_info,"gravity"); if (gravity != (char *) NULL) draw_info->gravity=(GravityType) ParseCommandOption(MagickGravityOptions, MagickFalse,gravity); split=MagickFalse; status=MagickTrue; if (image->columns == 0) { text=AcquireString(caption); i=FormatMagickCaption(image,draw_info,split,&metrics,&text); (void) CloneString(&draw_info->text,text); text=DestroyString(text); (void) FormatLocaleString(geometry,MaxTextExtent,"%+g%+g", -metrics.bounds.x1,metrics.ascent); if (draw_info->gravity == UndefinedGravity) (void) CloneString(&draw_info->geometry,geometry); status=GetMultilineTypeMetrics(image,draw_info,&metrics); width=(size_t) floor(metrics.width+draw_info->stroke_width+0.5); image->columns=width; } if (image->rows == 0) { split=MagickTrue; text=AcquireString(caption); i=FormatMagickCaption(image,draw_info,split,&metrics,&text); (void) CloneString(&draw_info->text,text); text=DestroyString(text); (void) FormatLocaleString(geometry,MaxTextExtent,"%+g%+g", -metrics.bounds.x1,metrics.ascent); if (draw_info->gravity == UndefinedGravity) (void) CloneString(&draw_info->geometry,geometry); status=GetMultilineTypeMetrics(image,draw_info,&metrics); image->rows=(size_t) ((i+1)*(metrics.ascent-metrics.descent+ draw_info->interline_spacing+draw_info->stroke_width)+0.5); } if (status != MagickFalse) status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { draw_info=DestroyDrawInfo(draw_info); InheritException(exception,&image->exception); return(DestroyImageList(image)); } if (SetImageBackgroundColor(image) == MagickFalse) { draw_info=DestroyDrawInfo(draw_info); InheritException(exception,&image->exception); image=DestroyImageList(image); return((Image *) NULL); } if ((fabs(image_info->pointsize) < MagickEpsilon) && (strlen(caption) > 0)) { double high, low; /* Auto fit text into bounding box. */ for ( ; ; draw_info->pointsize*=2.0) { text=AcquireString(caption); i=FormatMagickCaption(image,draw_info,split,&metrics,&text); (void) CloneString(&draw_info->text,text); text=DestroyString(text); (void) FormatLocaleString(geometry,MaxTextExtent,"%+g%+g", -metrics.bounds.x1,metrics.ascent); if (draw_info->gravity == UndefinedGravity) (void) CloneString(&draw_info->geometry,geometry); status=GetMultilineTypeMetrics(image,draw_info,&metrics); (void) status; width=(size_t) floor(metrics.width+draw_info->stroke_width+0.5); height=(size_t) floor(metrics.height+draw_info->stroke_width+0.5); if ((image->columns != 0) && (image->rows != 0)) { if ((width >= image->columns) && (height >= image->rows)) break; } else if (((image->columns != 0) && (width >= image->columns)) || ((image->rows != 0) && (height >= image->rows))) break; } high=draw_info->pointsize; for (low=1.0; (high-low) > 0.5; ) { draw_info->pointsize=(low+high)/2.0; text=AcquireString(caption); i=FormatMagickCaption(image,draw_info,split,&metrics,&text); (void) CloneString(&draw_info->text,text); text=DestroyString(text); (void) FormatLocaleString(geometry,MaxTextExtent,"%+g%+g", -metrics.bounds.x1,metrics.ascent); if (draw_info->gravity == UndefinedGravity) (void) CloneString(&draw_info->geometry,geometry); (void) GetMultilineTypeMetrics(image,draw_info,&metrics); width=(size_t) floor(metrics.width+draw_info->stroke_width+0.5); height=(size_t) floor(metrics.height+draw_info->stroke_width+0.5); if ((image->columns != 0) && (image->rows != 0)) { if ((width < image->columns) && (height < image->rows)) low=draw_info->pointsize+0.5; else high=draw_info->pointsize-0.5; } else if (((image->columns != 0) && (width < image->columns)) || ((image->rows != 0) && (height < image->rows))) low=draw_info->pointsize+0.5; else high=draw_info->pointsize-0.5; } draw_info->pointsize=floor((low+high)/2.0-0.5); } /* Draw caption. */ i=FormatMagickCaption(image,draw_info,split,&metrics,&caption); (void) CloneString(&draw_info->text,caption); (void) FormatLocaleString(geometry,MaxTextExtent,"%+g%+g",MagickMax( draw_info->direction == RightToLeftDirection ? image->columns- metrics.bounds.x2 : -metrics.bounds.x1,0.0),draw_info->gravity == UndefinedGravity ? metrics.ascent : 0.0); (void) CloneString(&draw_info->geometry,geometry); status=AnnotateImage(image,draw_info); if (image_info->pointsize == 0.0) { char pointsize[MaxTextExtent]; (void) FormatLocaleString(pointsize,MaxTextExtent,"%.20g", draw_info->pointsize); (void) SetImageProperty(image,"caption:pointsize",pointsize); } draw_info=DestroyDrawInfo(draw_info); caption=DestroyString(caption); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } return(GetFirstImageInList(image)); }
168,522
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: print_prefix(netdissect_options *ndo, const u_char *prefix, u_int max_length) { int plenbytes; char buf[sizeof("xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx::/128")]; if (prefix[0] >= 96 && max_length >= IPV4_MAPPED_HEADING_LEN + 1 && is_ipv4_mapped_address(&prefix[1])) { struct in_addr addr; u_int plen; plen = prefix[0]-96; if (32 < plen) return -1; max_length -= 1; memset(&addr, 0, sizeof(addr)); plenbytes = (plen + 7) / 8; if (max_length < (u_int)plenbytes + IPV4_MAPPED_HEADING_LEN) return -3; memcpy(&addr, &prefix[1 + IPV4_MAPPED_HEADING_LEN], plenbytes); if (plen % 8) { ((u_char *)&addr)[plenbytes - 1] &= ((0xff00 >> (plen % 8)) & 0xff); } snprintf(buf, sizeof(buf), "%s/%d", ipaddr_string(ndo, &addr), plen); plenbytes += 1 + IPV4_MAPPED_HEADING_LEN; } else { plenbytes = decode_prefix6(ndo, prefix, max_length, buf, sizeof(buf)); } ND_PRINT((ndo, "%s", buf)); return plenbytes; } Commit Message: (for 4.9.3) CVE-2018-16228/HNCP: make buffer access safer print_prefix() has a buffer and does not initialize it. It may call decode_prefix6(), which also does not initialize the buffer on invalid input. When that happens, make sure to return from print_prefix() before trying to print the [still uninitialized] buffer. This fixes a buffer over-read discovered by Wang Junjie of 360 ESG Codesafe Team. Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-125
print_prefix(netdissect_options *ndo, const u_char *prefix, u_int max_length) { int plenbytes; char buf[sizeof("xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx::/128")]; if (prefix[0] >= 96 && max_length >= IPV4_MAPPED_HEADING_LEN + 1 && is_ipv4_mapped_address(&prefix[1])) { struct in_addr addr; u_int plen; plen = prefix[0]-96; if (32 < plen) return -1; max_length -= 1; memset(&addr, 0, sizeof(addr)); plenbytes = (plen + 7) / 8; if (max_length < (u_int)plenbytes + IPV4_MAPPED_HEADING_LEN) return -3; memcpy(&addr, &prefix[1 + IPV4_MAPPED_HEADING_LEN], plenbytes); if (plen % 8) { ((u_char *)&addr)[plenbytes - 1] &= ((0xff00 >> (plen % 8)) & 0xff); } snprintf(buf, sizeof(buf), "%s/%d", ipaddr_string(ndo, &addr), plen); plenbytes += 1 + IPV4_MAPPED_HEADING_LEN; } else { plenbytes = decode_prefix6(ndo, prefix, max_length, buf, sizeof(buf)); if (plenbytes < 0) return plenbytes; } ND_PRINT((ndo, "%s", buf)); return plenbytes; }
169,820
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int ssl_scan_clienthello_tlsext(SSL *s, unsigned char **p, unsigned char *limit, int *al) { unsigned short type; unsigned short size; unsigned short len; unsigned char *data = *p; int renegotiate_seen = 0; s->servername_done = 0; s->tlsext_status_type = -1; # ifndef OPENSSL_NO_NEXTPROTONEG s->s3->next_proto_neg_seen = 0; # endif if (s->s3->alpn_selected) { OPENSSL_free(s->s3->alpn_selected); s->s3->alpn_selected = NULL; } s->s3->alpn_selected_len = 0; if (s->cert->alpn_proposed) { OPENSSL_free(s->cert->alpn_proposed); s->cert->alpn_proposed = NULL; } s->cert->alpn_proposed_len = 0; # ifndef OPENSSL_NO_HEARTBEATS s->tlsext_heartbeat &= ~(SSL_TLSEXT_HB_ENABLED | SSL_TLSEXT_HB_DONT_SEND_REQUESTS); # endif # ifndef OPENSSL_NO_EC if (s->options & SSL_OP_SAFARI_ECDHE_ECDSA_BUG) ssl_check_for_safari(s, data, limit); # endif /* !OPENSSL_NO_EC */ /* Clear any signature algorithms extension received */ if (s->cert->peer_sigalgs) { OPENSSL_free(s->cert->peer_sigalgs); s->cert->peer_sigalgs = NULL; } # ifndef OPENSSL_NO_SRP if (s->srp_ctx.login != NULL) { OPENSSL_free(s->srp_ctx.login); s->srp_ctx.login = NULL; } # endif s->srtp_profile = NULL; if (data == limit) goto ri_check; if (data > (limit - 2)) goto err; n2s(data, len); if (data + len != limit) goto err; while (data <= (limit - 4)) { n2s(data, type); n2s(data, size); if (data + size > (limit)) goto err; # if 0 fprintf(stderr, "Received extension type %d size %d\n", type, size); # endif if (s->tlsext_debug_cb) s->tlsext_debug_cb(s, 0, type, data, size, s->tlsext_debug_arg); /*- * The servername extension is treated as follows: * * - Only the hostname type is supported with a maximum length of 255. * - The servername is rejected if too long or if it contains zeros, * in which case an fatal alert is generated. * - The servername field is maintained together with the session cache. * - When a session is resumed, the servername call back invoked in order * to allow the application to position itself to the right context. * - The servername is acknowledged if it is new for a session or when * it is identical to a previously used for the same session. * Applications can control the behaviour. They can at any time * set a 'desirable' servername for a new SSL object. This can be the * case for example with HTTPS when a Host: header field is received and * a renegotiation is requested. In this case, a possible servername * presented in the new client hello is only acknowledged if it matches * the value of the Host: field. * - Applications must use SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION * if they provide for changing an explicit servername context for the * session, i.e. when the session has been established with a servername * extension. * - On session reconnect, the servername extension may be absent. * */ if (type == TLSEXT_TYPE_server_name) { unsigned char *sdata; int servname_type; int dsize; if (size < 2) goto err; n2s(data, dsize); size -= 2; if (dsize > size) goto err; sdata = data; while (dsize > 3) { servname_type = *(sdata++); n2s(sdata, len); dsize -= 3; if (len > dsize) goto err; if (s->servername_done == 0) switch (servname_type) { case TLSEXT_NAMETYPE_host_name: if (!s->hit) { if (s->session->tlsext_hostname) goto err; if (len > TLSEXT_MAXLEN_host_name) { *al = TLS1_AD_UNRECOGNIZED_NAME; return 0; } if ((s->session->tlsext_hostname = OPENSSL_malloc(len + 1)) == NULL) { *al = TLS1_AD_INTERNAL_ERROR; return 0; } memcpy(s->session->tlsext_hostname, sdata, len); s->session->tlsext_hostname[len] = '\0'; if (strlen(s->session->tlsext_hostname) != len) { OPENSSL_free(s->session->tlsext_hostname); s->session->tlsext_hostname = NULL; *al = TLS1_AD_UNRECOGNIZED_NAME; return 0; } s->servername_done = 1; } else s->servername_done = s->session->tlsext_hostname && strlen(s->session->tlsext_hostname) == len && strncmp(s->session->tlsext_hostname, (char *)sdata, len) == 0; break; default: break; } dsize -= len; } if (dsize != 0) goto err; } # ifndef OPENSSL_NO_SRP else if (type == TLSEXT_TYPE_srp) { if (size == 0 || ((len = data[0])) != (size - 1)) goto err; if (s->srp_ctx.login != NULL) goto err; if ((s->srp_ctx.login = OPENSSL_malloc(len + 1)) == NULL) return -1; memcpy(s->srp_ctx.login, &data[1], len); s->srp_ctx.login[len] = '\0'; if (strlen(s->srp_ctx.login) != len) goto err; } # endif # ifndef OPENSSL_NO_EC else if (type == TLSEXT_TYPE_ec_point_formats) { unsigned char *sdata = data; int ecpointformatlist_length = *(sdata++); if (ecpointformatlist_length != size - 1 || ecpointformatlist_length < 1) goto err; if (!s->hit) { if (s->session->tlsext_ecpointformatlist) { OPENSSL_free(s->session->tlsext_ecpointformatlist); s->session->tlsext_ecpointformatlist = NULL; } s->session->tlsext_ecpointformatlist_length = 0; if ((s->session->tlsext_ecpointformatlist = OPENSSL_malloc(ecpointformatlist_length)) == NULL) { *al = TLS1_AD_INTERNAL_ERROR; return 0; } s->session->tlsext_ecpointformatlist_length = ecpointformatlist_length; memcpy(s->session->tlsext_ecpointformatlist, sdata, ecpointformatlist_length); } # if 0 fprintf(stderr, "ssl_parse_clienthello_tlsext s->session->tlsext_ecpointformatlist (length=%i) ", s->session->tlsext_ecpointformatlist_length); sdata = s->session->tlsext_ecpointformatlist; for (i = 0; i < s->session->tlsext_ecpointformatlist_length; i++) fprintf(stderr, "%i ", *(sdata++)); fprintf(stderr, "\n"); # endif } else if (type == TLSEXT_TYPE_elliptic_curves) { unsigned char *sdata = data; int ellipticcurvelist_length = (*(sdata++) << 8); ellipticcurvelist_length += (*(sdata++)); if (ellipticcurvelist_length != size - 2 || ellipticcurvelist_length < 1 || /* Each NamedCurve is 2 bytes. */ ellipticcurvelist_length & 1) goto err; if (!s->hit) { if (s->session->tlsext_ellipticcurvelist) goto err; s->session->tlsext_ellipticcurvelist_length = 0; if ((s->session->tlsext_ellipticcurvelist = OPENSSL_malloc(ellipticcurvelist_length)) == NULL) { *al = TLS1_AD_INTERNAL_ERROR; return 0; } s->session->tlsext_ellipticcurvelist_length = ellipticcurvelist_length; memcpy(s->session->tlsext_ellipticcurvelist, sdata, ellipticcurvelist_length); } # if 0 fprintf(stderr, "ssl_parse_clienthello_tlsext s->session->tlsext_ellipticcurvelist (length=%i) ", s->session->tlsext_ellipticcurvelist_length); sdata = s->session->tlsext_ellipticcurvelist; for (i = 0; i < s->session->tlsext_ellipticcurvelist_length; i++) fprintf(stderr, "%i ", *(sdata++)); fprintf(stderr, "\n"); # endif } # endif /* OPENSSL_NO_EC */ # ifdef TLSEXT_TYPE_opaque_prf_input else if (type == TLSEXT_TYPE_opaque_prf_input) { unsigned char *sdata = data; if (size < 2) { *al = SSL_AD_DECODE_ERROR; return 0; } n2s(sdata, s->s3->client_opaque_prf_input_len); if (s->s3->client_opaque_prf_input_len != size - 2) { *al = SSL_AD_DECODE_ERROR; return 0; } if (s->s3->client_opaque_prf_input != NULL) { /* shouldn't really happen */ OPENSSL_free(s->s3->client_opaque_prf_input); } /* dummy byte just to get non-NULL */ if (s->s3->client_opaque_prf_input_len == 0) s->s3->client_opaque_prf_input = OPENSSL_malloc(1); else s->s3->client_opaque_prf_input = BUF_memdup(sdata, s->s3->client_opaque_prf_input_len); if (s->s3->client_opaque_prf_input == NULL) { *al = TLS1_AD_INTERNAL_ERROR; return 0; } } # endif else if (type == TLSEXT_TYPE_session_ticket) { if (s->tls_session_ticket_ext_cb && !s->tls_session_ticket_ext_cb(s, data, size, s->tls_session_ticket_ext_cb_arg)) { *al = TLS1_AD_INTERNAL_ERROR; return 0; } } else if (type == TLSEXT_TYPE_renegotiate) { if (!ssl_parse_clienthello_renegotiate_ext(s, data, size, al)) return 0; renegotiate_seen = 1; } else if (type == TLSEXT_TYPE_signature_algorithms) { int dsize; if (s->cert->peer_sigalgs || size < 2) goto err; n2s(data, dsize); size -= 2; if (dsize != size || dsize & 1 || !dsize) goto err; if (!tls1_save_sigalgs(s, data, dsize)) goto err; } else if (type == TLSEXT_TYPE_status_request) { if (size < 5) goto err; s->tlsext_status_type = *data++; size--; if (s->tlsext_status_type == TLSEXT_STATUSTYPE_ocsp) { const unsigned char *sdata; int dsize; /* Read in responder_id_list */ n2s(data, dsize); size -= 2; if (dsize > size) goto err; while (dsize > 0) { OCSP_RESPID *id; int idsize; if (dsize < 4) goto err; n2s(data, idsize); dsize -= 2 + idsize; size -= 2 + idsize; if (dsize < 0) goto err; sdata = data; data += idsize; id = d2i_OCSP_RESPID(NULL, &sdata, idsize); if (!id) goto err; if (data != sdata) { OCSP_RESPID_free(id); goto err; } if (!s->tlsext_ocsp_ids && !(s->tlsext_ocsp_ids = sk_OCSP_RESPID_new_null())) { OCSP_RESPID_free(id); *al = SSL_AD_INTERNAL_ERROR; return 0; } if (!sk_OCSP_RESPID_push(s->tlsext_ocsp_ids, id)) { OCSP_RESPID_free(id); *al = SSL_AD_INTERNAL_ERROR; return 0; } } /* Read in request_extensions */ if (size < 2) goto err; n2s(data, dsize); size -= 2; if (dsize != size) goto err; sdata = data; if (dsize > 0) { if (s->tlsext_ocsp_exts) { sk_X509_EXTENSION_pop_free(s->tlsext_ocsp_exts, X509_EXTENSION_free); } s->tlsext_ocsp_exts = d2i_X509_EXTENSIONS(NULL, &sdata, dsize); if (!s->tlsext_ocsp_exts || (data + dsize != sdata)) goto err; } } /* * We don't know what to do with any other type * so ignore it. */ else s->tlsext_status_type = -1; } # ifndef OPENSSL_NO_HEARTBEATS else if (type == TLSEXT_TYPE_heartbeat) { switch (data[0]) { case 0x01: /* Client allows us to send HB requests */ s->tlsext_heartbeat |= SSL_TLSEXT_HB_ENABLED; break; case 0x02: /* Client doesn't accept HB requests */ s->tlsext_heartbeat |= SSL_TLSEXT_HB_ENABLED; s->tlsext_heartbeat |= SSL_TLSEXT_HB_DONT_SEND_REQUESTS; break; default: *al = SSL_AD_ILLEGAL_PARAMETER; return 0; } } # endif # ifndef OPENSSL_NO_NEXTPROTONEG else if (type == TLSEXT_TYPE_next_proto_neg && s->s3->tmp.finish_md_len == 0) { /*- * We shouldn't accept this extension on a * renegotiation. * * s->new_session will be set on renegotiation, but we * probably shouldn't rely that it couldn't be set on * the initial renegotation too in certain cases (when * there's some other reason to disallow resuming an * earlier session -- the current code won't be doing * anything like that, but this might change). * * A valid sign that there's been a previous handshake * in this connection is if s->s3->tmp.finish_md_len > * 0. (We are talking about a check that will happen * in the Hello protocol round, well before a new * Finished message could have been computed.) */ s->s3->next_proto_neg_seen = 1; } # endif else if (type == TLSEXT_TYPE_application_layer_protocol_negotiation && s->s3->tmp.finish_md_len == 0) { if (tls1_alpn_handle_client_hello(s, data, size, al) != 0) return 0; } /* session ticket processed earlier */ # ifndef OPENSSL_NO_SRTP else if (SSL_IS_DTLS(s) && SSL_get_srtp_profiles(s) && type == TLSEXT_TYPE_use_srtp) { if (ssl_parse_clienthello_use_srtp_ext(s, data, size, al)) return 0; } # endif data += size; } /* Spurious data on the end */ if (data != limit) goto err; *p = data; ri_check: /* Need RI if renegotiating */ if (!renegotiate_seen && s->renegotiate && !(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)) { *al = SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL_SCAN_CLIENTHELLO_TLSEXT, SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED); return 0; } return 1; err: *al = SSL_AD_DECODE_ERROR; return 0; } Commit Message: CWE ID: CWE-190
static int ssl_scan_clienthello_tlsext(SSL *s, unsigned char **p, unsigned char *limit, int *al) { unsigned short type; unsigned short size; unsigned short len; unsigned char *data = *p; int renegotiate_seen = 0; s->servername_done = 0; s->tlsext_status_type = -1; # ifndef OPENSSL_NO_NEXTPROTONEG s->s3->next_proto_neg_seen = 0; # endif if (s->s3->alpn_selected) { OPENSSL_free(s->s3->alpn_selected); s->s3->alpn_selected = NULL; } s->s3->alpn_selected_len = 0; if (s->cert->alpn_proposed) { OPENSSL_free(s->cert->alpn_proposed); s->cert->alpn_proposed = NULL; } s->cert->alpn_proposed_len = 0; # ifndef OPENSSL_NO_HEARTBEATS s->tlsext_heartbeat &= ~(SSL_TLSEXT_HB_ENABLED | SSL_TLSEXT_HB_DONT_SEND_REQUESTS); # endif # ifndef OPENSSL_NO_EC if (s->options & SSL_OP_SAFARI_ECDHE_ECDSA_BUG) ssl_check_for_safari(s, data, limit); # endif /* !OPENSSL_NO_EC */ /* Clear any signature algorithms extension received */ if (s->cert->peer_sigalgs) { OPENSSL_free(s->cert->peer_sigalgs); s->cert->peer_sigalgs = NULL; } # ifndef OPENSSL_NO_SRP if (s->srp_ctx.login != NULL) { OPENSSL_free(s->srp_ctx.login); s->srp_ctx.login = NULL; } # endif s->srtp_profile = NULL; if (data == limit) goto ri_check; if (limit - data < 2) goto err; n2s(data, len); if (limit - data != len) goto err; while (limit - data >= 4) { n2s(data, type); n2s(data, size); if (limit - data < size) goto err; # if 0 fprintf(stderr, "Received extension type %d size %d\n", type, size); # endif if (s->tlsext_debug_cb) s->tlsext_debug_cb(s, 0, type, data, size, s->tlsext_debug_arg); /*- * The servername extension is treated as follows: * * - Only the hostname type is supported with a maximum length of 255. * - The servername is rejected if too long or if it contains zeros, * in which case an fatal alert is generated. * - The servername field is maintained together with the session cache. * - When a session is resumed, the servername call back invoked in order * to allow the application to position itself to the right context. * - The servername is acknowledged if it is new for a session or when * it is identical to a previously used for the same session. * Applications can control the behaviour. They can at any time * set a 'desirable' servername for a new SSL object. This can be the * case for example with HTTPS when a Host: header field is received and * a renegotiation is requested. In this case, a possible servername * presented in the new client hello is only acknowledged if it matches * the value of the Host: field. * - Applications must use SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION * if they provide for changing an explicit servername context for the * session, i.e. when the session has been established with a servername * extension. * - On session reconnect, the servername extension may be absent. * */ if (type == TLSEXT_TYPE_server_name) { unsigned char *sdata; int servname_type; int dsize; if (size < 2) goto err; n2s(data, dsize); size -= 2; if (dsize > size) goto err; sdata = data; while (dsize > 3) { servname_type = *(sdata++); n2s(sdata, len); dsize -= 3; if (len > dsize) goto err; if (s->servername_done == 0) switch (servname_type) { case TLSEXT_NAMETYPE_host_name: if (!s->hit) { if (s->session->tlsext_hostname) goto err; if (len > TLSEXT_MAXLEN_host_name) { *al = TLS1_AD_UNRECOGNIZED_NAME; return 0; } if ((s->session->tlsext_hostname = OPENSSL_malloc(len + 1)) == NULL) { *al = TLS1_AD_INTERNAL_ERROR; return 0; } memcpy(s->session->tlsext_hostname, sdata, len); s->session->tlsext_hostname[len] = '\0'; if (strlen(s->session->tlsext_hostname) != len) { OPENSSL_free(s->session->tlsext_hostname); s->session->tlsext_hostname = NULL; *al = TLS1_AD_UNRECOGNIZED_NAME; return 0; } s->servername_done = 1; } else s->servername_done = s->session->tlsext_hostname && strlen(s->session->tlsext_hostname) == len && strncmp(s->session->tlsext_hostname, (char *)sdata, len) == 0; break; default: break; } dsize -= len; } if (dsize != 0) goto err; } # ifndef OPENSSL_NO_SRP else if (type == TLSEXT_TYPE_srp) { if (size == 0 || ((len = data[0])) != (size - 1)) goto err; if (s->srp_ctx.login != NULL) goto err; if ((s->srp_ctx.login = OPENSSL_malloc(len + 1)) == NULL) return -1; memcpy(s->srp_ctx.login, &data[1], len); s->srp_ctx.login[len] = '\0'; if (strlen(s->srp_ctx.login) != len) goto err; } # endif # ifndef OPENSSL_NO_EC else if (type == TLSEXT_TYPE_ec_point_formats) { unsigned char *sdata = data; int ecpointformatlist_length = *(sdata++); if (ecpointformatlist_length != size - 1 || ecpointformatlist_length < 1) goto err; if (!s->hit) { if (s->session->tlsext_ecpointformatlist) { OPENSSL_free(s->session->tlsext_ecpointformatlist); s->session->tlsext_ecpointformatlist = NULL; } s->session->tlsext_ecpointformatlist_length = 0; if ((s->session->tlsext_ecpointformatlist = OPENSSL_malloc(ecpointformatlist_length)) == NULL) { *al = TLS1_AD_INTERNAL_ERROR; return 0; } s->session->tlsext_ecpointformatlist_length = ecpointformatlist_length; memcpy(s->session->tlsext_ecpointformatlist, sdata, ecpointformatlist_length); } # if 0 fprintf(stderr, "ssl_parse_clienthello_tlsext s->session->tlsext_ecpointformatlist (length=%i) ", s->session->tlsext_ecpointformatlist_length); sdata = s->session->tlsext_ecpointformatlist; for (i = 0; i < s->session->tlsext_ecpointformatlist_length; i++) fprintf(stderr, "%i ", *(sdata++)); fprintf(stderr, "\n"); # endif } else if (type == TLSEXT_TYPE_elliptic_curves) { unsigned char *sdata = data; int ellipticcurvelist_length = (*(sdata++) << 8); ellipticcurvelist_length += (*(sdata++)); if (ellipticcurvelist_length != size - 2 || ellipticcurvelist_length < 1 || /* Each NamedCurve is 2 bytes. */ ellipticcurvelist_length & 1) goto err; if (!s->hit) { if (s->session->tlsext_ellipticcurvelist) goto err; s->session->tlsext_ellipticcurvelist_length = 0; if ((s->session->tlsext_ellipticcurvelist = OPENSSL_malloc(ellipticcurvelist_length)) == NULL) { *al = TLS1_AD_INTERNAL_ERROR; return 0; } s->session->tlsext_ellipticcurvelist_length = ellipticcurvelist_length; memcpy(s->session->tlsext_ellipticcurvelist, sdata, ellipticcurvelist_length); } # if 0 fprintf(stderr, "ssl_parse_clienthello_tlsext s->session->tlsext_ellipticcurvelist (length=%i) ", s->session->tlsext_ellipticcurvelist_length); sdata = s->session->tlsext_ellipticcurvelist; for (i = 0; i < s->session->tlsext_ellipticcurvelist_length; i++) fprintf(stderr, "%i ", *(sdata++)); fprintf(stderr, "\n"); # endif } # endif /* OPENSSL_NO_EC */ # ifdef TLSEXT_TYPE_opaque_prf_input else if (type == TLSEXT_TYPE_opaque_prf_input) { unsigned char *sdata = data; if (size < 2) { *al = SSL_AD_DECODE_ERROR; return 0; } n2s(sdata, s->s3->client_opaque_prf_input_len); if (s->s3->client_opaque_prf_input_len != size - 2) { *al = SSL_AD_DECODE_ERROR; return 0; } if (s->s3->client_opaque_prf_input != NULL) { /* shouldn't really happen */ OPENSSL_free(s->s3->client_opaque_prf_input); } /* dummy byte just to get non-NULL */ if (s->s3->client_opaque_prf_input_len == 0) s->s3->client_opaque_prf_input = OPENSSL_malloc(1); else s->s3->client_opaque_prf_input = BUF_memdup(sdata, s->s3->client_opaque_prf_input_len); if (s->s3->client_opaque_prf_input == NULL) { *al = TLS1_AD_INTERNAL_ERROR; return 0; } } # endif else if (type == TLSEXT_TYPE_session_ticket) { if (s->tls_session_ticket_ext_cb && !s->tls_session_ticket_ext_cb(s, data, size, s->tls_session_ticket_ext_cb_arg)) { *al = TLS1_AD_INTERNAL_ERROR; return 0; } } else if (type == TLSEXT_TYPE_renegotiate) { if (!ssl_parse_clienthello_renegotiate_ext(s, data, size, al)) return 0; renegotiate_seen = 1; } else if (type == TLSEXT_TYPE_signature_algorithms) { int dsize; if (s->cert->peer_sigalgs || size < 2) goto err; n2s(data, dsize); size -= 2; if (dsize != size || dsize & 1 || !dsize) goto err; if (!tls1_save_sigalgs(s, data, dsize)) goto err; } else if (type == TLSEXT_TYPE_status_request) { if (size < 5) goto err; s->tlsext_status_type = *data++; size--; if (s->tlsext_status_type == TLSEXT_STATUSTYPE_ocsp) { const unsigned char *sdata; int dsize; /* Read in responder_id_list */ n2s(data, dsize); size -= 2; if (dsize > size) goto err; while (dsize > 0) { OCSP_RESPID *id; int idsize; if (dsize < 4) goto err; n2s(data, idsize); dsize -= 2 + idsize; size -= 2 + idsize; if (dsize < 0) goto err; sdata = data; data += idsize; id = d2i_OCSP_RESPID(NULL, &sdata, idsize); if (!id) goto err; if (data != sdata) { OCSP_RESPID_free(id); goto err; } if (!s->tlsext_ocsp_ids && !(s->tlsext_ocsp_ids = sk_OCSP_RESPID_new_null())) { OCSP_RESPID_free(id); *al = SSL_AD_INTERNAL_ERROR; return 0; } if (!sk_OCSP_RESPID_push(s->tlsext_ocsp_ids, id)) { OCSP_RESPID_free(id); *al = SSL_AD_INTERNAL_ERROR; return 0; } } /* Read in request_extensions */ if (size < 2) goto err; n2s(data, dsize); size -= 2; if (dsize != size) goto err; sdata = data; if (dsize > 0) { if (s->tlsext_ocsp_exts) { sk_X509_EXTENSION_pop_free(s->tlsext_ocsp_exts, X509_EXTENSION_free); } s->tlsext_ocsp_exts = d2i_X509_EXTENSIONS(NULL, &sdata, dsize); if (!s->tlsext_ocsp_exts || (data + dsize != sdata)) goto err; } } /* * We don't know what to do with any other type * so ignore it. */ else s->tlsext_status_type = -1; } # ifndef OPENSSL_NO_HEARTBEATS else if (type == TLSEXT_TYPE_heartbeat) { switch (data[0]) { case 0x01: /* Client allows us to send HB requests */ s->tlsext_heartbeat |= SSL_TLSEXT_HB_ENABLED; break; case 0x02: /* Client doesn't accept HB requests */ s->tlsext_heartbeat |= SSL_TLSEXT_HB_ENABLED; s->tlsext_heartbeat |= SSL_TLSEXT_HB_DONT_SEND_REQUESTS; break; default: *al = SSL_AD_ILLEGAL_PARAMETER; return 0; } } # endif # ifndef OPENSSL_NO_NEXTPROTONEG else if (type == TLSEXT_TYPE_next_proto_neg && s->s3->tmp.finish_md_len == 0) { /*- * We shouldn't accept this extension on a * renegotiation. * * s->new_session will be set on renegotiation, but we * probably shouldn't rely that it couldn't be set on * the initial renegotation too in certain cases (when * there's some other reason to disallow resuming an * earlier session -- the current code won't be doing * anything like that, but this might change). * * A valid sign that there's been a previous handshake * in this connection is if s->s3->tmp.finish_md_len > * 0. (We are talking about a check that will happen * in the Hello protocol round, well before a new * Finished message could have been computed.) */ s->s3->next_proto_neg_seen = 1; } # endif else if (type == TLSEXT_TYPE_application_layer_protocol_negotiation && s->s3->tmp.finish_md_len == 0) { if (tls1_alpn_handle_client_hello(s, data, size, al) != 0) return 0; } /* session ticket processed earlier */ # ifndef OPENSSL_NO_SRTP else if (SSL_IS_DTLS(s) && SSL_get_srtp_profiles(s) && type == TLSEXT_TYPE_use_srtp) { if (ssl_parse_clienthello_use_srtp_ext(s, data, size, al)) return 0; } # endif data += size; } /* Spurious data on the end */ if (data != limit) goto err; *p = data; ri_check: /* Need RI if renegotiating */ if (!renegotiate_seen && s->renegotiate && !(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)) { *al = SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL_SCAN_CLIENTHELLO_TLSEXT, SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED); return 0; } return 1; err: *al = SSL_AD_DECODE_ERROR; return 0; }
165,204
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: hcom_client_init ( OUT p_hsm_com_client_hdl_t *p_hdl, IN char *server_path, IN char *client_path, IN int max_data_len ) { hsm_com_client_hdl_t *hdl = NULL; hsm_com_errno_t res = HSM_COM_OK; if((strlen(server_path) > (HSM_COM_SVR_MAX_PATH - 1)) || (strlen(server_path) == 0)){ res = HSM_COM_PATH_ERR; goto cleanup; } if((strlen(client_path) > (HSM_COM_SVR_MAX_PATH - 1)) || (strlen(client_path) == 0)){ res = HSM_COM_PATH_ERR; goto cleanup; } if((hdl = calloc(1,sizeof(hsm_com_client_hdl_t))) == NULL) { res = HSM_COM_NO_MEM; goto cleanup; } if((hdl->scr.scratch = malloc(max_data_len)) == NULL) { res = HSM_COM_NO_MEM; goto cleanup; } if((hdl->recv_buf = malloc(max_data_len)) == NULL) { res = HSM_COM_NO_MEM; goto cleanup; } if((hdl->send_buf = malloc(max_data_len)) == NULL) { res = HSM_COM_NO_MEM; goto cleanup; } hdl->scr.scratch_fill = 0; hdl->scr.scratch_len = max_data_len; hdl->buf_len = max_data_len; hdl->trans_id = 1; strcpy(hdl->s_path,server_path); strcpy(hdl->c_path,client_path); hdl->client_state = HSM_COM_C_STATE_IN; *p_hdl = hdl; return res; cleanup: if(hdl) { if (hdl->scr.scratch) { free(hdl->scr.scratch); } if (hdl->recv_buf) { free(hdl->recv_buf); } free(hdl); } return res; } Commit Message: Fix scripts and code that use well-known tmp files. CWE ID: CWE-362
hcom_client_init ( OUT p_hsm_com_client_hdl_t *p_hdl, IN char *server_path, IN char *client_path, IN int max_data_len ) { hsm_com_client_hdl_t *hdl = NULL; hsm_com_errno_t res = HSM_COM_OK; if((strlen(server_path) > (HSM_COM_SVR_MAX_PATH - 1)) || (strlen(server_path) == 0)){ res = HSM_COM_PATH_ERR; goto cleanup; } if((strlen(client_path) > (HSM_COM_SVR_MAX_PATH - 1)) || (strlen(client_path) == 0)){ res = HSM_COM_PATH_ERR; goto cleanup; } if((hdl = calloc(1,sizeof(hsm_com_client_hdl_t))) == NULL) { res = HSM_COM_NO_MEM; goto cleanup; } if((hdl->scr.scratch = malloc(max_data_len)) == NULL) { res = HSM_COM_NO_MEM; goto cleanup; } if((hdl->recv_buf = malloc(max_data_len)) == NULL) { res = HSM_COM_NO_MEM; goto cleanup; } if((hdl->send_buf = malloc(max_data_len)) == NULL) { res = HSM_COM_NO_MEM; goto cleanup; } hdl->scr.scratch_fill = 0; hdl->scr.scratch_len = max_data_len; hdl->buf_len = max_data_len; hdl->trans_id = 1; strcpy(hdl->s_path,server_path); strcpy(hdl->c_path,client_path); if (mkstemp(hdl->c_path) == -1) { res = HSM_COM_PATH_ERR; goto cleanup; } hdl->client_state = HSM_COM_C_STATE_IN; *p_hdl = hdl; return res; cleanup: if(hdl) { if (hdl->scr.scratch) { free(hdl->scr.scratch); } if (hdl->recv_buf) { free(hdl->recv_buf); } free(hdl); } return res; }
170,129
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: ExtensionTtsController::~ExtensionTtsController() { FinishCurrentUtterance(); ClearUtteranceQueue(); } Commit Message: Extend TTS extension API to support richer events returned from the engine to the client. Previously we just had a completed event; this adds start, word boundary, sentence boundary, and marker boundary. In addition, interrupted and canceled, which were previously errors, now become events. Mac and Windows implementations extended to support as many of these events as possible. BUG=67713 BUG=70198 BUG=75106 BUG=83404 TEST=Updates all TTS API tests to be event-based, and adds new tests. Review URL: http://codereview.chromium.org/6792014 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@91665 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
ExtensionTtsController::~ExtensionTtsController() {
170,396
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void SaveCardBubbleControllerImpl::ReshowBubble() { is_reshow_ = true; AutofillMetrics::LogSaveCardPromptMetric( AutofillMetrics::SAVE_CARD_PROMPT_SHOW_REQUESTED, is_uploading_, is_reshow_, pref_service_->GetInteger( prefs::kAutofillAcceptSaveCreditCardPromptState)); ShowBubble(); } Commit Message: [autofill] Avoid duplicate instances of the SaveCardBubble. autofill::SaveCardBubbleControllerImpl::ShowBubble() expects (via DCHECK) to only be called when the save card bubble is not already visible. This constraint is violated if the user clicks multiple times on a submit button. If the underlying page goes away, the last SaveCardBubbleView created by the controller will be automatically cleaned up, but any others are left visible on the screen... holding a refence to a possibly-deleted controller. This CL early exits the ShowBubbleFor*** and ReshowBubble logic if the bubble is already visible. BUG=708819 Review-Url: https://codereview.chromium.org/2862933002 Cr-Commit-Position: refs/heads/master@{#469768} CWE ID: CWE-416
void SaveCardBubbleControllerImpl::ReshowBubble() { // Don't show the bubble if it's already visible. if (save_card_bubble_view_) return; is_reshow_ = true; AutofillMetrics::LogSaveCardPromptMetric( AutofillMetrics::SAVE_CARD_PROMPT_SHOW_REQUESTED, is_uploading_, is_reshow_, pref_service_->GetInteger( prefs::kAutofillAcceptSaveCreditCardPromptState)); ShowBubble(); }
172,384
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void snd_timer_user_ccallback(struct snd_timer_instance *timeri, int event, struct timespec *tstamp, unsigned long resolution) { struct snd_timer_user *tu = timeri->callback_data; struct snd_timer_tread r1; unsigned long flags; if (event >= SNDRV_TIMER_EVENT_START && event <= SNDRV_TIMER_EVENT_PAUSE) tu->tstamp = *tstamp; if ((tu->filter & (1 << event)) == 0 || !tu->tread) return; r1.event = event; r1.tstamp = *tstamp; r1.val = resolution; spin_lock_irqsave(&tu->qlock, flags); snd_timer_user_append_to_tqueue(tu, &r1); spin_unlock_irqrestore(&tu->qlock, flags); kill_fasync(&tu->fasync, SIGIO, POLL_IN); wake_up(&tu->qchange_sleep); } Commit Message: ALSA: timer: Fix leak in events via snd_timer_user_ccallback The stack object “r1” has a total size of 32 bytes. Its field “event” and “val” both contain 4 bytes padding. These 8 bytes padding bytes are sent to user without being initialized. Signed-off-by: Kangjie Lu <[email protected]> Signed-off-by: Takashi Iwai <[email protected]> CWE ID: CWE-200
static void snd_timer_user_ccallback(struct snd_timer_instance *timeri, int event, struct timespec *tstamp, unsigned long resolution) { struct snd_timer_user *tu = timeri->callback_data; struct snd_timer_tread r1; unsigned long flags; if (event >= SNDRV_TIMER_EVENT_START && event <= SNDRV_TIMER_EVENT_PAUSE) tu->tstamp = *tstamp; if ((tu->filter & (1 << event)) == 0 || !tu->tread) return; memset(&r1, 0, sizeof(r1)); r1.event = event; r1.tstamp = *tstamp; r1.val = resolution; spin_lock_irqsave(&tu->qlock, flags); snd_timer_user_append_to_tqueue(tu, &r1); spin_unlock_irqrestore(&tu->qlock, flags); kill_fasync(&tu->fasync, SIGIO, POLL_IN); wake_up(&tu->qchange_sleep); }
169,969
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: struct _mdi *_WM_ParseNewXmi(uint8_t *xmi_data, uint32_t xmi_size) { struct _mdi *xmi_mdi = NULL; uint32_t xmi_tmpdata = 0; uint8_t xmi_formcnt = 0; uint32_t xmi_catlen = 0; uint32_t xmi_subformlen = 0; uint32_t i = 0; uint32_t j = 0; uint32_t xmi_evntlen = 0; uint32_t xmi_divisions = 60; uint32_t xmi_tempo = 500000; uint32_t xmi_sample_count = 0; float xmi_sample_count_f = 0.0; float xmi_sample_remainder = 0.0; float xmi_samples_per_delta_f = 0.0; uint8_t xmi_ch = 0; uint8_t xmi_note = 0; uint32_t *xmi_notelen = NULL; uint32_t setup_ret = 0; uint32_t xmi_delta = 0; uint32_t xmi_lowestdelta = 0; uint32_t xmi_evnt_cnt = 0; if (memcmp(xmi_data,"FORM",4)) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_XMI, NULL, 0); return NULL; } xmi_data += 4; xmi_size -= 4; xmi_tmpdata = *xmi_data++ << 24; xmi_tmpdata |= *xmi_data++ << 16; xmi_tmpdata |= *xmi_data++ << 8; xmi_tmpdata |= *xmi_data++; xmi_size -= 4; if (memcmp(xmi_data,"XDIRINFO",8)) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_XMI, NULL, 0); return NULL; } xmi_data += 8; xmi_size -= 8; /* 0x00 0x00 0x00 0x02 at this point are unknown so skip over them */ xmi_data += 4; xmi_size -= 4; xmi_formcnt = *xmi_data++; if (xmi_formcnt == 0) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_XMI, NULL, 0); return NULL; } xmi_size--; /* at this stage unsure if remaining data in this section means anything */ xmi_tmpdata -= 13; xmi_data += xmi_tmpdata; xmi_size -= xmi_tmpdata; /* FIXME: Check: may not even need to process CAT information */ if (memcmp(xmi_data,"CAT ",4)) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_XMI, NULL, 0); return NULL; } xmi_data += 4; xmi_size -= 4; xmi_catlen = *xmi_data++ << 24; xmi_catlen |= *xmi_data++ << 16; xmi_catlen |= *xmi_data++ << 8; xmi_catlen |= *xmi_data++; xmi_size -= 4; UNUSED(xmi_catlen); if (memcmp(xmi_data,"XMID",4)) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_XMI, NULL, 0); return NULL; } xmi_data += 4; xmi_size -= 4; xmi_mdi = _WM_initMDI(); _WM_midi_setup_divisions(xmi_mdi, xmi_divisions); _WM_midi_setup_tempo(xmi_mdi, xmi_tempo); xmi_samples_per_delta_f = _WM_GetSamplesPerTick(xmi_divisions, xmi_tempo); xmi_notelen = malloc(sizeof(uint32_t) * 16 * 128); memset(xmi_notelen, 0, (sizeof(uint32_t) * 16 * 128)); for (i = 0; i < xmi_formcnt; i++) { if (memcmp(xmi_data,"FORM",4)) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_XMI, NULL, 0); goto _xmi_end; } xmi_data += 4; xmi_size -= 4; xmi_subformlen = *xmi_data++ << 24; xmi_subformlen |= *xmi_data++ << 16; xmi_subformlen |= *xmi_data++ << 8; xmi_subformlen |= *xmi_data++; xmi_size -= 4; if (memcmp(xmi_data,"XMID",4)) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_XMI, NULL, 0); goto _xmi_end; } xmi_data += 4; xmi_size -= 4; xmi_subformlen -= 4; do { if (!memcmp(xmi_data,"TIMB",4)) { xmi_data += 4; xmi_tmpdata = *xmi_data++ << 24; xmi_tmpdata |= *xmi_data++ << 16; xmi_tmpdata |= *xmi_data++ << 8; xmi_tmpdata |= *xmi_data++; xmi_data += xmi_tmpdata; xmi_size -= (8 + xmi_tmpdata); xmi_subformlen -= (8 + xmi_tmpdata); } else if (!memcmp(xmi_data,"RBRN",4)) { xmi_data += 4; xmi_tmpdata = *xmi_data++ << 24; xmi_tmpdata |= *xmi_data++ << 16; xmi_tmpdata |= *xmi_data++ << 8; xmi_tmpdata |= *xmi_data++; xmi_data += xmi_tmpdata; xmi_size -= (8 + xmi_tmpdata); xmi_subformlen -= (8 + xmi_tmpdata); } else if (!memcmp(xmi_data,"EVNT",4)) { xmi_data += 4; xmi_evnt_cnt++; xmi_evntlen = *xmi_data++ << 24; xmi_evntlen |= *xmi_data++ << 16; xmi_evntlen |= *xmi_data++ << 8; xmi_evntlen |= *xmi_data++; xmi_size -= 8; xmi_subformlen -= 8; do { if (*xmi_data < 0x80) { xmi_delta = 0; if (*xmi_data > 0x7f) { while (*xmi_data > 0x7f) { xmi_delta = (xmi_delta << 7) | (*xmi_data++ & 0x7f); xmi_size--; xmi_evntlen--; xmi_subformlen--; } } xmi_delta = (xmi_delta << 7) | (*xmi_data++ & 0x7f); xmi_size--; xmi_evntlen--; xmi_subformlen--; do { if ((xmi_lowestdelta != 0) && (xmi_lowestdelta <= xmi_delta)) { xmi_tmpdata = xmi_lowestdelta; } else { xmi_tmpdata = xmi_delta; } xmi_sample_count_f= (((float) xmi_tmpdata * xmi_samples_per_delta_f) + xmi_sample_remainder); xmi_sample_count = (uint32_t) xmi_sample_count_f; xmi_sample_remainder = xmi_sample_count_f - (float) xmi_sample_count; xmi_mdi->events[xmi_mdi->event_count - 1].samples_to_next += xmi_sample_count; xmi_mdi->extra_info.approx_total_samples += xmi_sample_count; xmi_lowestdelta = 0; for (j = 0; j < (16*128); j++) { if (xmi_notelen[j] == 0) continue; xmi_notelen[j] -= xmi_tmpdata; if (xmi_notelen[j] == 0) { xmi_ch = j / 128; xmi_note = j - (xmi_ch * 128); _WM_midi_setup_noteoff(xmi_mdi, xmi_ch, xmi_note, 0); } else { if ((xmi_lowestdelta == 0) || (xmi_lowestdelta > xmi_notelen[j])) { xmi_lowestdelta = xmi_notelen[j]; } } } xmi_delta -= xmi_tmpdata; } while (xmi_delta); } else { if ((xmi_data[0] == 0xff) && (xmi_data[1] == 0x51) && (xmi_data[2] == 0x03)) { setup_ret = 6; goto _XMI_Next_Event; } if ((setup_ret = _WM_SetupMidiEvent(xmi_mdi,xmi_data,0)) == 0) { goto _xmi_end; } if ((*xmi_data & 0xf0) == 0x90) { xmi_ch = *xmi_data & 0x0f; xmi_note = xmi_data[1]; xmi_data += setup_ret; xmi_size -= setup_ret; xmi_evntlen -= setup_ret; xmi_subformlen -= setup_ret; xmi_tmpdata = 0; if (*xmi_data > 0x7f) { while (*xmi_data > 0x7f) { xmi_tmpdata = (xmi_tmpdata << 7) | (*xmi_data++ & 0x7f); xmi_size--; xmi_evntlen--; xmi_subformlen--; } } xmi_tmpdata = (xmi_tmpdata << 7) | (*xmi_data++ & 0x7f); xmi_size--; xmi_evntlen--; xmi_subformlen--; xmi_notelen[128 * xmi_ch + xmi_note] = xmi_tmpdata; if ((xmi_tmpdata > 0) && ((xmi_lowestdelta == 0) || (xmi_tmpdata < xmi_lowestdelta))) { xmi_lowestdelta = xmi_tmpdata; } } else { _XMI_Next_Event: xmi_data += setup_ret; xmi_size -= setup_ret; xmi_evntlen -= setup_ret; xmi_subformlen -= setup_ret; } } } while (xmi_evntlen); } else { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_XMI, NULL, 0); goto _xmi_end; } } while (xmi_subformlen); } if ((xmi_mdi->reverb = _WM_init_reverb(_WM_SampleRate, _WM_reverb_room_width, _WM_reverb_room_length, _WM_reverb_listen_posx, _WM_reverb_listen_posy)) == NULL) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_MEM, "to init reverb", 0); goto _xmi_end; } xmi_mdi->extra_info.current_sample = 0; xmi_mdi->current_event = &xmi_mdi->events[0]; xmi_mdi->samples_to_mix = 0; xmi_mdi->note = NULL; /* More than 1 event form in XMI means treat as type 2 */ if (xmi_evnt_cnt > 1) { xmi_mdi->is_type2 = 1; } _WM_ResetToStart(xmi_mdi); _xmi_end: if (xmi_notelen != NULL) free(xmi_notelen); if (xmi_mdi->reverb) return (xmi_mdi); _WM_freeMDI(xmi_mdi); return NULL; } Commit Message: Add a new size parameter to _WM_SetupMidiEvent() so that it knows where to stop reading, and adjust its users properly. Fixes bug #175 (CVE-2017-11661, CVE-2017-11662, CVE-2017-11663, CVE-2017-11664.) CWE ID: CWE-125
struct _mdi *_WM_ParseNewXmi(uint8_t *xmi_data, uint32_t xmi_size) { struct _mdi *xmi_mdi = NULL; uint32_t xmi_tmpdata = 0; uint8_t xmi_formcnt = 0; uint32_t xmi_catlen = 0; uint32_t xmi_subformlen = 0; uint32_t i = 0; uint32_t j = 0; uint32_t xmi_evntlen = 0; uint32_t xmi_divisions = 60; uint32_t xmi_tempo = 500000; uint32_t xmi_sample_count = 0; float xmi_sample_count_f = 0.0; float xmi_sample_remainder = 0.0; float xmi_samples_per_delta_f = 0.0; uint8_t xmi_ch = 0; uint8_t xmi_note = 0; uint32_t *xmi_notelen = NULL; uint32_t setup_ret = 0; uint32_t xmi_delta = 0; uint32_t xmi_lowestdelta = 0; uint32_t xmi_evnt_cnt = 0; if (memcmp(xmi_data,"FORM",4)) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_XMI, NULL, 0); return NULL; } xmi_data += 4; xmi_size -= 4; xmi_tmpdata = *xmi_data++ << 24; xmi_tmpdata |= *xmi_data++ << 16; xmi_tmpdata |= *xmi_data++ << 8; xmi_tmpdata |= *xmi_data++; xmi_size -= 4; if (memcmp(xmi_data,"XDIRINFO",8)) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_XMI, NULL, 0); return NULL; } xmi_data += 8; xmi_size -= 8; /* 0x00 0x00 0x00 0x02 at this point are unknown so skip over them */ xmi_data += 4; xmi_size -= 4; xmi_formcnt = *xmi_data++; if (xmi_formcnt == 0) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_XMI, NULL, 0); return NULL; } xmi_size--; /* at this stage unsure if remaining data in this section means anything */ xmi_tmpdata -= 13; xmi_data += xmi_tmpdata; xmi_size -= xmi_tmpdata; /* FIXME: Check: may not even need to process CAT information */ if (memcmp(xmi_data,"CAT ",4)) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_XMI, NULL, 0); return NULL; } xmi_data += 4; xmi_size -= 4; xmi_catlen = *xmi_data++ << 24; xmi_catlen |= *xmi_data++ << 16; xmi_catlen |= *xmi_data++ << 8; xmi_catlen |= *xmi_data++; xmi_size -= 4; UNUSED(xmi_catlen); if (memcmp(xmi_data,"XMID",4)) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_XMI, NULL, 0); return NULL; } xmi_data += 4; xmi_size -= 4; xmi_mdi = _WM_initMDI(); _WM_midi_setup_divisions(xmi_mdi, xmi_divisions); _WM_midi_setup_tempo(xmi_mdi, xmi_tempo); xmi_samples_per_delta_f = _WM_GetSamplesPerTick(xmi_divisions, xmi_tempo); xmi_notelen = malloc(sizeof(uint32_t) * 16 * 128); memset(xmi_notelen, 0, (sizeof(uint32_t) * 16 * 128)); for (i = 0; i < xmi_formcnt; i++) { if (memcmp(xmi_data,"FORM",4)) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_XMI, NULL, 0); goto _xmi_end; } xmi_data += 4; xmi_size -= 4; xmi_subformlen = *xmi_data++ << 24; xmi_subformlen |= *xmi_data++ << 16; xmi_subformlen |= *xmi_data++ << 8; xmi_subformlen |= *xmi_data++; xmi_size -= 4; if (memcmp(xmi_data,"XMID",4)) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_XMI, NULL, 0); goto _xmi_end; } xmi_data += 4; xmi_size -= 4; xmi_subformlen -= 4; do { if (!memcmp(xmi_data,"TIMB",4)) { xmi_data += 4; xmi_tmpdata = *xmi_data++ << 24; xmi_tmpdata |= *xmi_data++ << 16; xmi_tmpdata |= *xmi_data++ << 8; xmi_tmpdata |= *xmi_data++; xmi_data += xmi_tmpdata; xmi_size -= (8 + xmi_tmpdata); xmi_subformlen -= (8 + xmi_tmpdata); } else if (!memcmp(xmi_data,"RBRN",4)) { xmi_data += 4; xmi_tmpdata = *xmi_data++ << 24; xmi_tmpdata |= *xmi_data++ << 16; xmi_tmpdata |= *xmi_data++ << 8; xmi_tmpdata |= *xmi_data++; xmi_data += xmi_tmpdata; xmi_size -= (8 + xmi_tmpdata); xmi_subformlen -= (8 + xmi_tmpdata); } else if (!memcmp(xmi_data,"EVNT",4)) { xmi_data += 4; xmi_evnt_cnt++; xmi_evntlen = *xmi_data++ << 24; xmi_evntlen |= *xmi_data++ << 16; xmi_evntlen |= *xmi_data++ << 8; xmi_evntlen |= *xmi_data++; xmi_size -= 8; xmi_subformlen -= 8; do { if (*xmi_data < 0x80) { xmi_delta = 0; if (*xmi_data > 0x7f) { while (*xmi_data > 0x7f) { xmi_delta = (xmi_delta << 7) | (*xmi_data++ & 0x7f); xmi_size--; xmi_evntlen--; xmi_subformlen--; } } xmi_delta = (xmi_delta << 7) | (*xmi_data++ & 0x7f); xmi_size--; xmi_evntlen--; xmi_subformlen--; do { if ((xmi_lowestdelta != 0) && (xmi_lowestdelta <= xmi_delta)) { xmi_tmpdata = xmi_lowestdelta; } else { xmi_tmpdata = xmi_delta; } xmi_sample_count_f= (((float) xmi_tmpdata * xmi_samples_per_delta_f) + xmi_sample_remainder); xmi_sample_count = (uint32_t) xmi_sample_count_f; xmi_sample_remainder = xmi_sample_count_f - (float) xmi_sample_count; xmi_mdi->events[xmi_mdi->event_count - 1].samples_to_next += xmi_sample_count; xmi_mdi->extra_info.approx_total_samples += xmi_sample_count; xmi_lowestdelta = 0; for (j = 0; j < (16*128); j++) { if (xmi_notelen[j] == 0) continue; xmi_notelen[j] -= xmi_tmpdata; if (xmi_notelen[j] == 0) { xmi_ch = j / 128; xmi_note = j - (xmi_ch * 128); _WM_midi_setup_noteoff(xmi_mdi, xmi_ch, xmi_note, 0); } else { if ((xmi_lowestdelta == 0) || (xmi_lowestdelta > xmi_notelen[j])) { xmi_lowestdelta = xmi_notelen[j]; } } } xmi_delta -= xmi_tmpdata; } while (xmi_delta); } else { if ((xmi_data[0] == 0xff) && (xmi_data[1] == 0x51) && (xmi_data[2] == 0x03)) { setup_ret = 6; goto _XMI_Next_Event; } if ((setup_ret = _WM_SetupMidiEvent(xmi_mdi,xmi_data, xmi_size, 0)) == 0) { goto _xmi_end; } if ((*xmi_data & 0xf0) == 0x90) { xmi_ch = *xmi_data & 0x0f; xmi_note = xmi_data[1]; xmi_data += setup_ret; xmi_size -= setup_ret; xmi_evntlen -= setup_ret; xmi_subformlen -= setup_ret; xmi_tmpdata = 0; if (*xmi_data > 0x7f) { while (*xmi_data > 0x7f) { xmi_tmpdata = (xmi_tmpdata << 7) | (*xmi_data++ & 0x7f); xmi_size--; xmi_evntlen--; xmi_subformlen--; } } xmi_tmpdata = (xmi_tmpdata << 7) | (*xmi_data++ & 0x7f); xmi_size--; xmi_evntlen--; xmi_subformlen--; xmi_notelen[128 * xmi_ch + xmi_note] = xmi_tmpdata; if ((xmi_tmpdata > 0) && ((xmi_lowestdelta == 0) || (xmi_tmpdata < xmi_lowestdelta))) { xmi_lowestdelta = xmi_tmpdata; } } else { _XMI_Next_Event: xmi_data += setup_ret; xmi_size -= setup_ret; xmi_evntlen -= setup_ret; xmi_subformlen -= setup_ret; } } } while (xmi_evntlen); } else { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_XMI, NULL, 0); goto _xmi_end; } } while (xmi_subformlen); } if ((xmi_mdi->reverb = _WM_init_reverb(_WM_SampleRate, _WM_reverb_room_width, _WM_reverb_room_length, _WM_reverb_listen_posx, _WM_reverb_listen_posy)) == NULL) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_MEM, "to init reverb", 0); goto _xmi_end; } xmi_mdi->extra_info.current_sample = 0; xmi_mdi->current_event = &xmi_mdi->events[0]; xmi_mdi->samples_to_mix = 0; xmi_mdi->note = NULL; /* More than 1 event form in XMI means treat as type 2 */ if (xmi_evnt_cnt > 1) { xmi_mdi->is_type2 = 1; } _WM_ResetToStart(xmi_mdi); _xmi_end: if (xmi_notelen != NULL) free(xmi_notelen); if (xmi_mdi->reverb) return (xmi_mdi); _WM_freeMDI(xmi_mdi); return NULL; }
168,006
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: ipv6_dup_options(struct sock *sk, struct ipv6_txoptions *opt) { struct ipv6_txoptions *opt2; opt2 = sock_kmalloc(sk, opt->tot_len, GFP_ATOMIC); if (opt2) { long dif = (char *)opt2 - (char *)opt; memcpy(opt2, opt, opt->tot_len); if (opt2->hopopt) *((char **)&opt2->hopopt) += dif; if (opt2->dst0opt) *((char **)&opt2->dst0opt) += dif; if (opt2->dst1opt) *((char **)&opt2->dst1opt) += dif; if (opt2->srcrt) *((char **)&opt2->srcrt) += dif; } return opt2; } Commit Message: ipv6: add complete rcu protection around np->opt This patch addresses multiple problems : UDP/RAW sendmsg() need to get a stable struct ipv6_txoptions while socket is not locked : Other threads can change np->opt concurrently. Dmitry posted a syzkaller (http://github.com/google/syzkaller) program desmonstrating use-after-free. Starting with TCP/DCCP lockless listeners, tcp_v6_syn_recv_sock() and dccp_v6_request_recv_sock() also need to use RCU protection to dereference np->opt once (before calling ipv6_dup_options()) This patch adds full RCU protection to np->opt Reported-by: Dmitry Vyukov <[email protected]> Signed-off-by: Eric Dumazet <[email protected]> Acked-by: Hannes Frederic Sowa <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-416
ipv6_dup_options(struct sock *sk, struct ipv6_txoptions *opt) { struct ipv6_txoptions *opt2; opt2 = sock_kmalloc(sk, opt->tot_len, GFP_ATOMIC); if (opt2) { long dif = (char *)opt2 - (char *)opt; memcpy(opt2, opt, opt->tot_len); if (opt2->hopopt) *((char **)&opt2->hopopt) += dif; if (opt2->dst0opt) *((char **)&opt2->dst0opt) += dif; if (opt2->dst1opt) *((char **)&opt2->dst1opt) += dif; if (opt2->srcrt) *((char **)&opt2->srcrt) += dif; atomic_set(&opt2->refcnt, 1); } return opt2; }
167,330
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void ConnectionChangeHandler(void* object, bool connected) { if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) { LOG(ERROR) << "Not on UI thread"; return; } InputMethodLibraryImpl* input_method_library = static_cast<InputMethodLibraryImpl*>(object); input_method_library->ime_connected_ = connected; if (connected) { input_method_library->pending_config_requests_.clear(); input_method_library->pending_config_requests_.insert( input_method_library->current_config_values_.begin(), input_method_library->current_config_values_.end()); input_method_library->FlushImeConfig(); input_method_library->ChangeInputMethod( input_method_library->previous_input_method().id); input_method_library->ChangeInputMethod( input_method_library->current_input_method().id); } } Commit Message: Remove use of libcros from InputMethodLibrary. BUG=chromium-os:16238 TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before. Review URL: http://codereview.chromium.org/7003086 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
static void ConnectionChangeHandler(void* object, bool connected) { // IBusController override. virtual void OnConnectionChange(bool connected) { if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) { LOG(ERROR) << "Not on UI thread"; return; } ime_connected_ = connected; if (connected) { pending_config_requests_.clear(); pending_config_requests_.insert( current_config_values_.begin(), current_config_values_.end()); FlushImeConfig(); ChangeInputMethod(previous_input_method().id); ChangeInputMethod(current_input_method().id); } }
170,482
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: SPL_METHOD(SplFileInfo, getPath) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); char *path; int path_len; if (zend_parse_parameters_none() == FAILURE) { return; } path = spl_filesystem_object_get_path(intern, &path_len TSRMLS_CC); RETURN_STRINGL(path, path_len, 1); } Commit Message: Fix bug #72262 - do not overflow int CWE ID: CWE-190
SPL_METHOD(SplFileInfo, getPath) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); char *path; int path_len; if (zend_parse_parameters_none() == FAILURE) { return; } path = spl_filesystem_object_get_path(intern, &path_len TSRMLS_CC); RETURN_STRINGL(path, path_len, 1); }
167,031
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: CoordinatorImpl::CoordinatorImpl(service_manager::Connector* connector) : next_dump_id_(0), client_process_timeout_(base::TimeDelta::FromSeconds(15)) { process_map_ = std::make_unique<ProcessMap>(connector); DCHECK(!g_coordinator_impl); g_coordinator_impl = this; base::trace_event::MemoryDumpManager::GetInstance()->set_tracing_process_id( mojom::kServiceTracingProcessId); tracing_observer_ = std::make_unique<TracingObserver>( base::trace_event::TraceLog::GetInstance(), nullptr); } Commit Message: Fix heap-use-after-free by using weak factory instead of Unretained Bug: 856578 Change-Id: Ifb2a1b7e6c22e1af36e12eedba72427f51d925b9 Reviewed-on: https://chromium-review.googlesource.com/1114617 Reviewed-by: Hector Dearman <[email protected]> Commit-Queue: Hector Dearman <[email protected]> Cr-Commit-Position: refs/heads/master@{#571528} CWE ID: CWE-416
CoordinatorImpl::CoordinatorImpl(service_manager::Connector* connector) : next_dump_id_(0), client_process_timeout_(base::TimeDelta::FromSeconds(15)), weak_ptr_factory_(this) { process_map_ = std::make_unique<ProcessMap>(connector); DCHECK(!g_coordinator_impl); g_coordinator_impl = this; base::trace_event::MemoryDumpManager::GetInstance()->set_tracing_process_id( mojom::kServiceTracingProcessId); tracing_observer_ = std::make_unique<TracingObserver>( base::trace_event::TraceLog::GetInstance(), nullptr); }
173,211
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: const CuePoint::TrackPosition* CuePoint::Find(const Track* pTrack) const { assert(pTrack); const long long n = pTrack->GetNumber(); const TrackPosition* i = m_track_positions; const TrackPosition* const j = i + m_track_positions_count; while (i != j) { const TrackPosition& p = *i++; if (p.m_track == n) return &p; } return NULL; //no matching track number found } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
const CuePoint::TrackPosition* CuePoint::Find(const Track* pTrack) const const long long n = pTrack->GetNumber(); const TrackPosition* i = m_track_positions; const TrackPosition* const j = i + m_track_positions_count; while (i != j) { const TrackPosition& p = *i++; if (p.m_track == n) return &p; } return NULL; // no matching track number found }
174,278
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void WebBluetoothServiceImpl::ClearState() { characteristic_id_to_notify_session_.clear(); pending_primary_services_requests_.clear(); descriptor_id_to_characteristic_id_.clear(); characteristic_id_to_service_id_.clear(); service_id_to_device_address_.clear(); connected_devices_.reset( new FrameConnectedBluetoothDevices(render_frame_host_)); device_chooser_controller_.reset(); BluetoothAdapterFactoryWrapper::Get().ReleaseAdapter(this); } Commit Message: Ensure device choosers are closed on navigation The requestDevice() IPCs can race with navigation. This change ensures that choosers are closed on navigation and adds browser tests to exercise this for Web Bluetooth and WebUSB. Bug: 723503 Change-Id: I66760161220e17bd2be9309cca228d161fe76e9c Reviewed-on: https://chromium-review.googlesource.com/1099961 Commit-Queue: Reilly Grant <[email protected]> Reviewed-by: Michael Wasserman <[email protected]> Reviewed-by: Jeffrey Yasskin <[email protected]> Cr-Commit-Position: refs/heads/master@{#569900} CWE ID: CWE-362
void WebBluetoothServiceImpl::ClearState() { // Releasing the adapter will drop references to callbacks that have not yet // been executed. The binding must be closed first so that this is allowed. binding_.Close(); characteristic_id_to_notify_session_.clear(); pending_primary_services_requests_.clear(); descriptor_id_to_characteristic_id_.clear(); characteristic_id_to_service_id_.clear(); service_id_to_device_address_.clear(); connected_devices_.reset( new FrameConnectedBluetoothDevices(render_frame_host_)); device_chooser_controller_.reset(); BluetoothAdapterFactoryWrapper::Get().ReleaseAdapter(this); }
173,204
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void jslTokenAsString(int token, char *str, size_t len) { if (token>32 && token<128) { assert(len>=4); str[0] = '\''; str[1] = (char)token; str[2] = '\''; str[3] = 0; return; } switch (token) { case LEX_EOF : strncpy(str, "EOF", len); return; case LEX_ID : strncpy(str, "ID", len); return; case LEX_INT : strncpy(str, "INT", len); return; case LEX_FLOAT : strncpy(str, "FLOAT", len); return; case LEX_STR : strncpy(str, "STRING", len); return; case LEX_UNFINISHED_STR : strncpy(str, "UNFINISHED STRING", len); return; case LEX_TEMPLATE_LITERAL : strncpy(str, "TEMPLATE LITERAL", len); return; case LEX_UNFINISHED_TEMPLATE_LITERAL : strncpy(str, "UNFINISHED TEMPLATE LITERAL", len); return; case LEX_REGEX : strncpy(str, "REGEX", len); return; case LEX_UNFINISHED_REGEX : strncpy(str, "UNFINISHED REGEX", len); return; case LEX_UNFINISHED_COMMENT : strncpy(str, "UNFINISHED COMMENT", len); return; } if (token>=_LEX_OPERATOR_START && token<_LEX_R_LIST_END) { const char tokenNames[] = /* LEX_EQUAL : */ "==\0" /* LEX_TYPEEQUAL : */ "===\0" /* LEX_NEQUAL : */ "!=\0" /* LEX_NTYPEEQUAL : */ "!==\0" /* LEX_LEQUAL : */ "<=\0" /* LEX_LSHIFT : */ "<<\0" /* LEX_LSHIFTEQUAL : */ "<<=\0" /* LEX_GEQUAL : */ ">=\0" /* LEX_RSHIFT : */ ">>\0" /* LEX_RSHIFTUNSIGNED */ ">>>\0" /* LEX_RSHIFTEQUAL : */ ">>=\0" /* LEX_RSHIFTUNSIGNEDEQUAL */ ">>>=\0" /* LEX_PLUSEQUAL : */ "+=\0" /* LEX_MINUSEQUAL : */ "-=\0" /* LEX_PLUSPLUS : */ "++\0" /* LEX_MINUSMINUS */ "--\0" /* LEX_MULEQUAL : */ "*=\0" /* LEX_DIVEQUAL : */ "/=\0" /* LEX_MODEQUAL : */ "%=\0" /* LEX_ANDEQUAL : */ "&=\0" /* LEX_ANDAND : */ "&&\0" /* LEX_OREQUAL : */ "|=\0" /* LEX_OROR : */ "||\0" /* LEX_XOREQUAL : */ "^=\0" /* LEX_ARROW_FUNCTION */ "=>\0" /*LEX_R_IF : */ "if\0" /*LEX_R_ELSE : */ "else\0" /*LEX_R_DO : */ "do\0" /*LEX_R_WHILE : */ "while\0" /*LEX_R_FOR : */ "for\0" /*LEX_R_BREAK : */ "return\0" /*LEX_R_CONTINUE */ "continue\0" /*LEX_R_FUNCTION */ "function\0" /*LEX_R_RETURN */ "return\0" /*LEX_R_VAR : */ "var\0" /*LEX_R_LET : */ "let\0" /*LEX_R_CONST : */ "const\0" /*LEX_R_THIS : */ "this\0" /*LEX_R_THROW : */ "throw\0" /*LEX_R_TRY : */ "try\0" /*LEX_R_CATCH : */ "catch\0" /*LEX_R_FINALLY : */ "finally\0" /*LEX_R_TRUE : */ "true\0" /*LEX_R_FALSE : */ "false\0" /*LEX_R_NULL : */ "null\0" /*LEX_R_UNDEFINED */ "undefined\0" /*LEX_R_NEW : */ "new\0" /*LEX_R_IN : */ "in\0" /*LEX_R_INSTANCEOF */ "instanceof\0" /*LEX_R_SWITCH */ "switch\0" /*LEX_R_CASE */ "case\0" /*LEX_R_DEFAULT */ "default\0" /*LEX_R_DELETE */ "delete\0" /*LEX_R_TYPEOF : */ "typeof\0" /*LEX_R_VOID : */ "void\0" /*LEX_R_DEBUGGER : */ "debugger\0" /*LEX_R_CLASS : */ "class\0" /*LEX_R_EXTENDS : */ "extends\0" /*LEX_R_SUPER : */ "super\0" /*LEX_R_STATIC : */ "static\0" ; unsigned int p = 0; int n = token-_LEX_OPERATOR_START; while (n>0 && p<sizeof(tokenNames)) { while (tokenNames[p] && p<sizeof(tokenNames)) p++; p++; // skip the zero n--; // next token } assert(n==0); strncpy(str, &tokenNames[p], len); return; } assert(len>=10); strncpy(str, "?[",len); itostr(token, &str[2], 10); strncat(str, "]",len); } Commit Message: Fix strncat/cpy bounding issues (fix #1425) CWE ID: CWE-119
void jslTokenAsString(int token, char *str, size_t len) { if (token>32 && token<128) { assert(len>=4); str[0] = '\''; str[1] = (char)token; str[2] = '\''; str[3] = 0; return; } switch (token) { case LEX_EOF : strncpy(str, "EOF", len); return; case LEX_ID : strncpy(str, "ID", len); return; case LEX_INT : strncpy(str, "INT", len); return; case LEX_FLOAT : strncpy(str, "FLOAT", len); return; case LEX_STR : strncpy(str, "STRING", len); return; case LEX_UNFINISHED_STR : strncpy(str, "UNFINISHED STRING", len); return; case LEX_TEMPLATE_LITERAL : strncpy(str, "TEMPLATE LITERAL", len); return; case LEX_UNFINISHED_TEMPLATE_LITERAL : strncpy(str, "UNFINISHED TEMPLATE LITERAL", len); return; case LEX_REGEX : strncpy(str, "REGEX", len); return; case LEX_UNFINISHED_REGEX : strncpy(str, "UNFINISHED REGEX", len); return; case LEX_UNFINISHED_COMMENT : strncpy(str, "UNFINISHED COMMENT", len); return; } if (token>=_LEX_OPERATOR_START && token<_LEX_R_LIST_END) { const char tokenNames[] = /* LEX_EQUAL : */ "==\0" /* LEX_TYPEEQUAL : */ "===\0" /* LEX_NEQUAL : */ "!=\0" /* LEX_NTYPEEQUAL : */ "!==\0" /* LEX_LEQUAL : */ "<=\0" /* LEX_LSHIFT : */ "<<\0" /* LEX_LSHIFTEQUAL : */ "<<=\0" /* LEX_GEQUAL : */ ">=\0" /* LEX_RSHIFT : */ ">>\0" /* LEX_RSHIFTUNSIGNED */ ">>>\0" /* LEX_RSHIFTEQUAL : */ ">>=\0" /* LEX_RSHIFTUNSIGNEDEQUAL */ ">>>=\0" /* LEX_PLUSEQUAL : */ "+=\0" /* LEX_MINUSEQUAL : */ "-=\0" /* LEX_PLUSPLUS : */ "++\0" /* LEX_MINUSMINUS */ "--\0" /* LEX_MULEQUAL : */ "*=\0" /* LEX_DIVEQUAL : */ "/=\0" /* LEX_MODEQUAL : */ "%=\0" /* LEX_ANDEQUAL : */ "&=\0" /* LEX_ANDAND : */ "&&\0" /* LEX_OREQUAL : */ "|=\0" /* LEX_OROR : */ "||\0" /* LEX_XOREQUAL : */ "^=\0" /* LEX_ARROW_FUNCTION */ "=>\0" /*LEX_R_IF : */ "if\0" /*LEX_R_ELSE : */ "else\0" /*LEX_R_DO : */ "do\0" /*LEX_R_WHILE : */ "while\0" /*LEX_R_FOR : */ "for\0" /*LEX_R_BREAK : */ "return\0" /*LEX_R_CONTINUE */ "continue\0" /*LEX_R_FUNCTION */ "function\0" /*LEX_R_RETURN */ "return\0" /*LEX_R_VAR : */ "var\0" /*LEX_R_LET : */ "let\0" /*LEX_R_CONST : */ "const\0" /*LEX_R_THIS : */ "this\0" /*LEX_R_THROW : */ "throw\0" /*LEX_R_TRY : */ "try\0" /*LEX_R_CATCH : */ "catch\0" /*LEX_R_FINALLY : */ "finally\0" /*LEX_R_TRUE : */ "true\0" /*LEX_R_FALSE : */ "false\0" /*LEX_R_NULL : */ "null\0" /*LEX_R_UNDEFINED */ "undefined\0" /*LEX_R_NEW : */ "new\0" /*LEX_R_IN : */ "in\0" /*LEX_R_INSTANCEOF */ "instanceof\0" /*LEX_R_SWITCH */ "switch\0" /*LEX_R_CASE */ "case\0" /*LEX_R_DEFAULT */ "default\0" /*LEX_R_DELETE */ "delete\0" /*LEX_R_TYPEOF : */ "typeof\0" /*LEX_R_VOID : */ "void\0" /*LEX_R_DEBUGGER : */ "debugger\0" /*LEX_R_CLASS : */ "class\0" /*LEX_R_EXTENDS : */ "extends\0" /*LEX_R_SUPER : */ "super\0" /*LEX_R_STATIC : */ "static\0" ; unsigned int p = 0; int n = token-_LEX_OPERATOR_START; while (n>0 && p<sizeof(tokenNames)) { while (tokenNames[p] && p<sizeof(tokenNames)) p++; p++; // skip the zero n--; // next token } assert(n==0); strncpy(str, &tokenNames[p], len); return; } assert(len>=10); espruino_snprintf(str, len, "?[%d]", token); }
169,212
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void ResetScreenHandler::Show() { if (!page_is_ready()) { show_on_init_ = true; return; } PrefService* prefs = g_browser_process->local_state(); restart_required_ = !CommandLine::ForCurrentProcess()->HasSwitch( switches::kFirstExecAfterBoot); reboot_was_requested_ = false; rollback_available_ = false; if (!restart_required_) // First exec after boot. reboot_was_requested_ = prefs->GetBoolean(prefs::kFactoryResetRequested); if (!restart_required_ && reboot_was_requested_) { rollback_available_ = prefs->GetBoolean(prefs::kRollbackRequested); ShowWithParams(); } else { chromeos::DBusThreadManager::Get()->GetUpdateEngineClient()-> CanRollbackCheck(base::Bind(&ResetScreenHandler::OnRollbackCheck, weak_ptr_factory_.GetWeakPtr())); } } Commit Message: Rollback option put behind the flag. BUG=368860 Review URL: https://codereview.chromium.org/267393011 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@269753 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void ResetScreenHandler::Show() { if (!page_is_ready()) { show_on_init_ = true; return; } PrefService* prefs = g_browser_process->local_state(); restart_required_ = !CommandLine::ForCurrentProcess()->HasSwitch( switches::kFirstExecAfterBoot); reboot_was_requested_ = false; rollback_available_ = false; if (!restart_required_) // First exec after boot. reboot_was_requested_ = prefs->GetBoolean(prefs::kFactoryResetRequested); if (!CommandLine::ForCurrentProcess()->HasSwitch( switches::kEnableRollbackOption)) { rollback_available_ = false; ShowWithParams(); } else if (!restart_required_ && reboot_was_requested_) { rollback_available_ = prefs->GetBoolean(prefs::kRollbackRequested); ShowWithParams(); } else { chromeos::DBusThreadManager::Get()->GetUpdateEngineClient()-> CanRollbackCheck(base::Bind(&ResetScreenHandler::OnRollbackCheck, weak_ptr_factory_.GetWeakPtr())); } }
171,181
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void Textfield::OnBlur() { gfx::RenderText* render_text = GetRenderText(); render_text->set_focused(false); if (PlatformStyle::kTextfieldScrollsToStartOnFocusChange) model_->MoveCursorTo(gfx::SelectionModel(0, gfx::CURSOR_FORWARD)); if (GetInputMethod()) { GetInputMethod()->DetachTextInputClient(this); #if defined(OS_CHROMEOS) wm::RestoreWindowBoundsOnClientFocusLost( GetNativeView()->GetToplevelWindow()); #endif // defined(OS_CHROMEOS) } StopBlinkingCursor(); cursor_view_.SetVisible(false); DestroyTouchSelection(); if (use_focus_ring_) FocusRing::Uninstall(this); SchedulePaint(); View::OnBlur(); } Commit Message: MacViews: Enable secure text input for password Textfields. In Cocoa the NSTextInputContext automatically enables secure text input when activated and it's in the secure text entry mode. RenderWidgetHostViewMac did the similar thing for ages following the WebKit example. views::Textfield needs to do the same thing in a fashion that's sycnrhonized with RenderWidgetHostViewMac, otherwise the race conditions are possible when the Textfield gets focus, activates the secure text input mode and the RWHVM loses focus immediately afterwards and disables the secure text input instead of leaving it in the enabled state. BUG=818133,677220 Change-Id: I6db6c4b59e4a1a72cbb7f8c7056f71b04a3df08b Reviewed-on: https://chromium-review.googlesource.com/943064 Commit-Queue: Michail Pishchagin <[email protected]> Reviewed-by: Pavel Feldman <[email protected]> Reviewed-by: Avi Drissman <[email protected]> Reviewed-by: Peter Kasting <[email protected]> Cr-Commit-Position: refs/heads/master@{#542517} CWE ID:
void Textfield::OnBlur() { gfx::RenderText* render_text = GetRenderText(); render_text->set_focused(false); if (PlatformStyle::kTextfieldScrollsToStartOnFocusChange) model_->MoveCursorTo(gfx::SelectionModel(0, gfx::CURSOR_FORWARD)); if (GetInputMethod()) { GetInputMethod()->DetachTextInputClient(this); #if defined(OS_CHROMEOS) wm::RestoreWindowBoundsOnClientFocusLost( GetNativeView()->GetToplevelWindow()); #endif // defined(OS_CHROMEOS) } StopBlinkingCursor(); cursor_view_.SetVisible(false); DestroyTouchSelection(); if (use_focus_ring_) FocusRing::Uninstall(this); SchedulePaint(); View::OnBlur(); #if defined(OS_MACOSX) password_input_enabler_.reset(); #endif // defined(OS_MACOSX) }
171,860
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static jas_image_cmpt_t *jas_image_cmpt_create(int_fast32_t tlx, int_fast32_t tly, int_fast32_t hstep, int_fast32_t vstep, int_fast32_t width, int_fast32_t height, uint_fast16_t depth, bool sgnd, uint_fast32_t inmem) { jas_image_cmpt_t *cmpt; size_t size; cmpt = 0; if (width < 0 || height < 0 || hstep <= 0 || vstep <= 0) { goto error; } if (!jas_safe_intfast32_add(tlx, width, 0) || !jas_safe_intfast32_add(tly, height, 0)) { goto error; } if (!(cmpt = jas_malloc(sizeof(jas_image_cmpt_t)))) { goto error; } cmpt->type_ = JAS_IMAGE_CT_UNKNOWN; cmpt->tlx_ = tlx; cmpt->tly_ = tly; cmpt->hstep_ = hstep; cmpt->vstep_ = vstep; cmpt->width_ = width; cmpt->height_ = height; cmpt->prec_ = depth; cmpt->sgnd_ = sgnd; cmpt->stream_ = 0; cmpt->cps_ = (depth + 7) / 8; if (!jas_safe_size_mul(cmpt->width_, cmpt->height_, &size) || !jas_safe_size_mul(size, cmpt->cps_, &size)) { goto error; } cmpt->stream_ = (inmem) ? jas_stream_memopen2(0, size) : jas_stream_tmpfile(); if (!cmpt->stream_) { goto error; } /* Zero the component data. This isn't necessary, but it is convenient for debugging purposes. */ /* Note: conversion of size - 1 to long can overflow */ if (size > 0) { if (size - 1 > LONG_MAX) { goto error; } if (jas_stream_seek(cmpt->stream_, size - 1, SEEK_SET) < 0 || jas_stream_putc(cmpt->stream_, 0) == EOF || jas_stream_seek(cmpt->stream_, 0, SEEK_SET) < 0) { goto error; } } return cmpt; error: if (cmpt) { jas_image_cmpt_destroy(cmpt); } return 0; } Commit Message: The generation of the configuration file jas_config.h has been completely reworked in order to avoid pollution of the global namespace. Some problematic types like uchar, ulong, and friends have been replaced with names with a jas_ prefix. An option max_samples has been added to the BMP and JPEG decoders to restrict the maximum size of image that they can decode. This change was made as a (possibly temporary) fix to address security concerns. A max_samples command-line option has also been added to imginfo. Whether an image component (for jas_image_t) is stored in memory or on disk is now based on the component size (rather than the image size). Some debug log message were added. Some new integer overflow checks were added. Some new safe integer add/multiply functions were added. More pre-C99 cruft was removed. JasPer has numerous "hacks" to handle pre-C99 compilers. JasPer now assumes C99 support. So, this pre-C99 cruft is unnecessary and can be removed. The regression jasper-doublefree-mem_close.jpg has been re-enabled. Theoretically, it should work more predictably now. CWE ID: CWE-190
static jas_image_cmpt_t *jas_image_cmpt_create(int_fast32_t tlx, int_fast32_t tly, int_fast32_t hstep, int_fast32_t vstep, int_fast32_t width, int_fast32_t height, uint_fast16_t depth, bool sgnd, uint_fast32_t inmem) { jas_image_cmpt_t *cmpt; size_t size; JAS_DBGLOG(100, ( "jas_image_cmpt_create(%ld, %ld, %ld, %ld, %ld, %ld, %d, %d, %d)\n", JAS_CAST(long, tlx), JAS_CAST(long, tly), JAS_CAST(long, hstep), JAS_CAST(long, vstep), JAS_CAST(long, width), JAS_CAST(long, height), JAS_CAST(int, depth), sgnd, inmem )); cmpt = 0; if (width < 0 || height < 0 || hstep <= 0 || vstep <= 0) { goto error; } if (!jas_safe_intfast32_add(tlx, width, 0) || !jas_safe_intfast32_add(tly, height, 0)) { goto error; } if (!jas_safe_intfast32_mul3(width, height, depth, 0)) { goto error; } if (!(cmpt = jas_malloc(sizeof(jas_image_cmpt_t)))) { goto error; } cmpt->type_ = JAS_IMAGE_CT_UNKNOWN; cmpt->tlx_ = tlx; cmpt->tly_ = tly; cmpt->hstep_ = hstep; cmpt->vstep_ = vstep; cmpt->width_ = width; cmpt->height_ = height; cmpt->prec_ = depth; cmpt->sgnd_ = sgnd; cmpt->stream_ = 0; cmpt->cps_ = (depth + 7) / 8; if (!jas_safe_size_mul3(cmpt->width_, cmpt->height_, cmpt->cps_, &size)) { goto error; } cmpt->stream_ = (inmem) ? jas_stream_memopen2(0, size) : jas_stream_tmpfile(); if (!cmpt->stream_) { goto error; } /* Zero the component data. This isn't necessary, but it is convenient for debugging purposes. */ /* Note: conversion of size - 1 to long can overflow */ if (size > 0) { if (size - 1 > LONG_MAX) { goto error; } if (jas_stream_seek(cmpt->stream_, size - 1, SEEK_SET) < 0 || jas_stream_putc(cmpt->stream_, 0) == EOF || jas_stream_seek(cmpt->stream_, 0, SEEK_SET) < 0) { goto error; } } return cmpt; error: if (cmpt) { jas_image_cmpt_destroy(cmpt); } return 0; }
168,693
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static enum try_read_result try_read_network(conn *c) { enum try_read_result gotdata = READ_NO_DATA_RECEIVED; int res; assert(c != NULL); if (c->rcurr != c->rbuf) { if (c->rbytes != 0) /* otherwise there's nothing to copy */ memmove(c->rbuf, c->rcurr, c->rbytes); c->rcurr = c->rbuf; } while (1) { if (c->rbytes >= c->rsize) { char *new_rbuf = realloc(c->rbuf, c->rsize * 2); if (!new_rbuf) { if (settings.verbose > 0) fprintf(stderr, "Couldn't realloc input buffer\n"); c->rbytes = 0; /* ignore what we read */ out_string(c, "SERVER_ERROR out of memory reading request"); c->write_and_go = conn_closing; return READ_MEMORY_ERROR; } c->rcurr = c->rbuf = new_rbuf; c->rsize *= 2; } int avail = c->rsize - c->rbytes; res = read(c->sfd, c->rbuf + c->rbytes, avail); if (res > 0) { pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.bytes_read += res; pthread_mutex_unlock(&c->thread->stats.mutex); gotdata = READ_DATA_RECEIVED; c->rbytes += res; if (res == avail) { continue; } else { break; } } if (res == 0) { return READ_ERROR; } if (res == -1) { if (errno == EAGAIN || errno == EWOULDBLOCK) { break; } return READ_ERROR; } } return gotdata; } Commit Message: Issue 102: Piping null to the server will crash it CWE ID: CWE-20
static enum try_read_result try_read_network(conn *c) { enum try_read_result gotdata = READ_NO_DATA_RECEIVED; int res; int num_allocs = 0; assert(c != NULL); if (c->rcurr != c->rbuf) { if (c->rbytes != 0) /* otherwise there's nothing to copy */ memmove(c->rbuf, c->rcurr, c->rbytes); c->rcurr = c->rbuf; } while (1) { if (c->rbytes >= c->rsize) { if (num_allocs == 4) { return gotdata; } ++num_allocs; char *new_rbuf = realloc(c->rbuf, c->rsize * 2); if (!new_rbuf) { if (settings.verbose > 0) fprintf(stderr, "Couldn't realloc input buffer\n"); c->rbytes = 0; /* ignore what we read */ out_string(c, "SERVER_ERROR out of memory reading request"); c->write_and_go = conn_closing; return READ_MEMORY_ERROR; } c->rcurr = c->rbuf = new_rbuf; c->rsize *= 2; } int avail = c->rsize - c->rbytes; res = read(c->sfd, c->rbuf + c->rbytes, avail); if (res > 0) { pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.bytes_read += res; pthread_mutex_unlock(&c->thread->stats.mutex); gotdata = READ_DATA_RECEIVED; c->rbytes += res; if (res == avail) { continue; } else { break; } } if (res == 0) { return READ_ERROR; } if (res == -1) { if (errno == EAGAIN || errno == EWOULDBLOCK) { break; } return READ_ERROR; } } return gotdata; }
169,876
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: jbig2_end_of_stripe(Jbig2Ctx *ctx, Jbig2Segment *segment, const uint8_t *segment_data) { Jbig2Page page = ctx->pages[ctx->current_page]; int end_row; end_row = jbig2_get_int32(segment_data); if (end_row < page.end_row) { jbig2_error(ctx, JBIG2_SEVERITY_WARNING, segment->number, "end of stripe segment with non-positive end row advance" " (new end row %d vs current end row %d)", end_row, page.end_row); } else { jbig2_error(ctx, JBIG2_SEVERITY_INFO, segment->number, "end of stripe: advancing end row to %d", end_row); } page.end_row = end_row; return 0; } Commit Message: CWE ID: CWE-119
jbig2_end_of_stripe(Jbig2Ctx *ctx, Jbig2Segment *segment, const uint8_t *segment_data) { Jbig2Page page = ctx->pages[ctx->current_page]; uint32_t end_row; end_row = jbig2_get_uint32(segment_data); if (end_row < page.end_row) { jbig2_error(ctx, JBIG2_SEVERITY_WARNING, segment->number, "end of stripe segment with non-positive end row advance" " (new end row %d vs current end row %d)", end_row, page.end_row); } else { jbig2_error(ctx, JBIG2_SEVERITY_INFO, segment->number, "end of stripe: advancing end row to %d", end_row); } page.end_row = end_row; return 0; }
165,495
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool GesturePoint::IsOverMinFlickSpeed() { return velocity_calculator_.VelocitySquared() > kMinFlickSpeedSquared; } Commit Message: Add setters for the aura gesture recognizer constants. BUG=113227 TEST=none Review URL: http://codereview.chromium.org/9372040 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@122586 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
bool GesturePoint::IsOverMinFlickSpeed() { return velocity_calculator_.VelocitySquared() > GestureConfiguration::min_flick_speed_squared(); }
171,045
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: cliprdr_process(STREAM s) { uint16 type, status; uint32 length, format; uint8 *data; in_uint16_le(s, type); in_uint16_le(s, status); in_uint32_le(s, length); data = s->p; logger(Clipboard, Debug, "cliprdr_process(), type=%d, status=%d, length=%d", type, status, length); if (status == CLIPRDR_ERROR) { switch (type) { case CLIPRDR_FORMAT_ACK: /* FIXME: We seem to get this when we send an announce while the server is still processing a paste. Try sending another announce. */ cliprdr_send_native_format_announce(last_formats, last_formats_length); break; case CLIPRDR_DATA_RESPONSE: ui_clip_request_failed(); break; default: logger(Clipboard, Warning, "cliprdr_process(), unhandled error (type=%d)", type); } return; } switch (type) { case CLIPRDR_CONNECT: ui_clip_sync(); break; case CLIPRDR_FORMAT_ANNOUNCE: ui_clip_format_announce(data, length); cliprdr_send_packet(CLIPRDR_FORMAT_ACK, CLIPRDR_RESPONSE, NULL, 0); return; case CLIPRDR_FORMAT_ACK: break; case CLIPRDR_DATA_REQUEST: in_uint32_le(s, format); ui_clip_request_data(format); break; case CLIPRDR_DATA_RESPONSE: ui_clip_handle_data(data, length); break; case 7: /* TODO: W2K3 SP1 sends this on connect with a value of 1 */ break; default: logger(Clipboard, Warning, "cliprdr_process(), unhandled packet type %d", type); } } Commit Message: Malicious RDP server security fixes This commit includes fixes for a set of 21 vulnerabilities in rdesktop when a malicious RDP server is used. All vulnerabilities was identified and reported by Eyal Itkin. * Add rdp_protocol_error function that is used in several fixes * Refactor of process_bitmap_updates * Fix possible integer overflow in s_check_rem() on 32bit arch * Fix memory corruption in process_bitmap_data - CVE-2018-8794 * Fix remote code execution in process_bitmap_data - CVE-2018-8795 * Fix remote code execution in process_plane - CVE-2018-8797 * Fix Denial of Service in mcs_recv_connect_response - CVE-2018-20175 * Fix Denial of Service in mcs_parse_domain_params - CVE-2018-20175 * Fix Denial of Service in sec_parse_crypt_info - CVE-2018-20176 * Fix Denial of Service in sec_recv - CVE-2018-20176 * Fix minor information leak in rdpdr_process - CVE-2018-8791 * Fix Denial of Service in cssp_read_tsrequest - CVE-2018-8792 * Fix remote code execution in cssp_read_tsrequest - CVE-2018-8793 * Fix Denial of Service in process_bitmap_data - CVE-2018-8796 * Fix minor information leak in rdpsnd_process_ping - CVE-2018-8798 * Fix Denial of Service in process_secondary_order - CVE-2018-8799 * Fix remote code execution in in ui_clip_handle_data - CVE-2018-8800 * Fix major information leak in ui_clip_handle_data - CVE-2018-20174 * Fix memory corruption in rdp_in_unistr - CVE-2018-20177 * Fix Denial of Service in process_demand_active - CVE-2018-20178 * Fix remote code execution in lspci_process - CVE-2018-20179 * Fix remote code execution in rdpsnddbg_process - CVE-2018-20180 * Fix remote code execution in seamless_process - CVE-2018-20181 * Fix remote code execution in seamless_process_line - CVE-2018-20182 CWE ID: CWE-119
cliprdr_process(STREAM s) { uint16 type, status; uint32 length, format; uint8 *data; struct stream packet = *s; in_uint16_le(s, type); in_uint16_le(s, status); in_uint32_le(s, length); data = s->p; logger(Clipboard, Debug, "cliprdr_process(), type=%d, status=%d, length=%d", type, status, length); if (!s_check_rem(s, length)) { rdp_protocol_error("cliprdr_process(), consume of packet from stream would overrun", &packet); } if (status == CLIPRDR_ERROR) { switch (type) { case CLIPRDR_FORMAT_ACK: /* FIXME: We seem to get this when we send an announce while the server is still processing a paste. Try sending another announce. */ cliprdr_send_native_format_announce(last_formats, last_formats_length); break; case CLIPRDR_DATA_RESPONSE: ui_clip_request_failed(); break; default: logger(Clipboard, Warning, "cliprdr_process(), unhandled error (type=%d)", type); } return; } switch (type) { case CLIPRDR_CONNECT: ui_clip_sync(); break; case CLIPRDR_FORMAT_ANNOUNCE: ui_clip_format_announce(data, length); cliprdr_send_packet(CLIPRDR_FORMAT_ACK, CLIPRDR_RESPONSE, NULL, 0); return; case CLIPRDR_FORMAT_ACK: break; case CLIPRDR_DATA_REQUEST: in_uint32_le(s, format); ui_clip_request_data(format); break; case CLIPRDR_DATA_RESPONSE: ui_clip_handle_data(data, length); break; case 7: /* TODO: W2K3 SP1 sends this on connect with a value of 1 */ break; default: logger(Clipboard, Warning, "cliprdr_process(), unhandled packet type %d", type); } }
169,796
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: status_t MPEG4Source::read( MediaBuffer **out, const ReadOptions *options) { Mutex::Autolock autoLock(mLock); CHECK(mStarted); if (mFirstMoofOffset > 0) { return fragmentedRead(out, options); } *out = NULL; int64_t targetSampleTimeUs = -1; int64_t seekTimeUs; ReadOptions::SeekMode mode; if (options && options->getSeekTo(&seekTimeUs, &mode)) { uint32_t findFlags = 0; switch (mode) { case ReadOptions::SEEK_PREVIOUS_SYNC: findFlags = SampleTable::kFlagBefore; break; case ReadOptions::SEEK_NEXT_SYNC: findFlags = SampleTable::kFlagAfter; break; case ReadOptions::SEEK_CLOSEST_SYNC: case ReadOptions::SEEK_CLOSEST: findFlags = SampleTable::kFlagClosest; break; default: CHECK(!"Should not be here."); break; } uint32_t sampleIndex; status_t err = mSampleTable->findSampleAtTime( seekTimeUs, 1000000, mTimescale, &sampleIndex, findFlags); if (mode == ReadOptions::SEEK_CLOSEST) { findFlags = SampleTable::kFlagBefore; } uint32_t syncSampleIndex; if (err == OK) { err = mSampleTable->findSyncSampleNear( sampleIndex, &syncSampleIndex, findFlags); } uint32_t sampleTime; if (err == OK) { err = mSampleTable->getMetaDataForSample( sampleIndex, NULL, NULL, &sampleTime); } if (err != OK) { if (err == ERROR_OUT_OF_RANGE) { err = ERROR_END_OF_STREAM; } ALOGV("end of stream"); return err; } if (mode == ReadOptions::SEEK_CLOSEST) { targetSampleTimeUs = (sampleTime * 1000000ll) / mTimescale; } #if 0 uint32_t syncSampleTime; CHECK_EQ(OK, mSampleTable->getMetaDataForSample( syncSampleIndex, NULL, NULL, &syncSampleTime)); ALOGI("seek to time %lld us => sample at time %lld us, " "sync sample at time %lld us", seekTimeUs, sampleTime * 1000000ll / mTimescale, syncSampleTime * 1000000ll / mTimescale); #endif mCurrentSampleIndex = syncSampleIndex; if (mBuffer != NULL) { mBuffer->release(); mBuffer = NULL; } } off64_t offset; size_t size; uint32_t cts, stts; bool isSyncSample; bool newBuffer = false; if (mBuffer == NULL) { newBuffer = true; status_t err = mSampleTable->getMetaDataForSample( mCurrentSampleIndex, &offset, &size, &cts, &isSyncSample, &stts); if (err != OK) { return err; } err = mGroup->acquire_buffer(&mBuffer); if (err != OK) { CHECK(mBuffer == NULL); return err; } } if ((!mIsAVC && !mIsHEVC) || mWantsNALFragments) { if (newBuffer) { ssize_t num_bytes_read = mDataSource->readAt(offset, (uint8_t *)mBuffer->data(), size); if (num_bytes_read < (ssize_t)size) { mBuffer->release(); mBuffer = NULL; return ERROR_IO; } CHECK(mBuffer != NULL); mBuffer->set_range(0, size); mBuffer->meta_data()->clear(); mBuffer->meta_data()->setInt64( kKeyTime, ((int64_t)cts * 1000000) / mTimescale); mBuffer->meta_data()->setInt64( kKeyDuration, ((int64_t)stts * 1000000) / mTimescale); if (targetSampleTimeUs >= 0) { mBuffer->meta_data()->setInt64( kKeyTargetTime, targetSampleTimeUs); } if (isSyncSample) { mBuffer->meta_data()->setInt32(kKeyIsSyncFrame, 1); } ++mCurrentSampleIndex; } if (!mIsAVC && !mIsHEVC) { *out = mBuffer; mBuffer = NULL; return OK; } CHECK(mBuffer->range_length() >= mNALLengthSize); const uint8_t *src = (const uint8_t *)mBuffer->data() + mBuffer->range_offset(); size_t nal_size = parseNALSize(src); if (mBuffer->range_length() < mNALLengthSize + nal_size) { ALOGE("incomplete NAL unit."); mBuffer->release(); mBuffer = NULL; return ERROR_MALFORMED; } MediaBuffer *clone = mBuffer->clone(); CHECK(clone != NULL); clone->set_range(mBuffer->range_offset() + mNALLengthSize, nal_size); CHECK(mBuffer != NULL); mBuffer->set_range( mBuffer->range_offset() + mNALLengthSize + nal_size, mBuffer->range_length() - mNALLengthSize - nal_size); if (mBuffer->range_length() == 0) { mBuffer->release(); mBuffer = NULL; } *out = clone; return OK; } else { ssize_t num_bytes_read = 0; int32_t drm = 0; bool usesDRM = (mFormat->findInt32(kKeyIsDRM, &drm) && drm != 0); if (usesDRM) { num_bytes_read = mDataSource->readAt(offset, (uint8_t*)mBuffer->data(), size); } else { num_bytes_read = mDataSource->readAt(offset, mSrcBuffer, size); } if (num_bytes_read < (ssize_t)size) { mBuffer->release(); mBuffer = NULL; return ERROR_IO; } if (usesDRM) { CHECK(mBuffer != NULL); mBuffer->set_range(0, size); } else { uint8_t *dstData = (uint8_t *)mBuffer->data(); size_t srcOffset = 0; size_t dstOffset = 0; while (srcOffset < size) { bool isMalFormed = (srcOffset + mNALLengthSize > size); size_t nalLength = 0; if (!isMalFormed) { nalLength = parseNALSize(&mSrcBuffer[srcOffset]); srcOffset += mNALLengthSize; isMalFormed = srcOffset + nalLength > size; } if (isMalFormed) { ALOGE("Video is malformed"); mBuffer->release(); mBuffer = NULL; return ERROR_MALFORMED; } if (nalLength == 0) { continue; } CHECK(dstOffset + 4 <= mBuffer->size()); dstData[dstOffset++] = 0; dstData[dstOffset++] = 0; dstData[dstOffset++] = 0; dstData[dstOffset++] = 1; memcpy(&dstData[dstOffset], &mSrcBuffer[srcOffset], nalLength); srcOffset += nalLength; dstOffset += nalLength; } CHECK_EQ(srcOffset, size); CHECK(mBuffer != NULL); mBuffer->set_range(0, dstOffset); } mBuffer->meta_data()->clear(); mBuffer->meta_data()->setInt64( kKeyTime, ((int64_t)cts * 1000000) / mTimescale); mBuffer->meta_data()->setInt64( kKeyDuration, ((int64_t)stts * 1000000) / mTimescale); if (targetSampleTimeUs >= 0) { mBuffer->meta_data()->setInt64( kKeyTargetTime, targetSampleTimeUs); } if (isSyncSample) { mBuffer->meta_data()->setInt32(kKeyIsSyncFrame, 1); } ++mCurrentSampleIndex; *out = mBuffer; mBuffer = NULL; return OK; } } Commit Message: Add AUtils::isInRange, and use it to detect malformed MPEG4 nal sizes Bug: 19641538 Change-Id: I5aae3f100846c125decc61eec7cd6563e3f33777 CWE ID: CWE-119
status_t MPEG4Source::read( MediaBuffer **out, const ReadOptions *options) { Mutex::Autolock autoLock(mLock); CHECK(mStarted); if (mFirstMoofOffset > 0) { return fragmentedRead(out, options); } *out = NULL; int64_t targetSampleTimeUs = -1; int64_t seekTimeUs; ReadOptions::SeekMode mode; if (options && options->getSeekTo(&seekTimeUs, &mode)) { uint32_t findFlags = 0; switch (mode) { case ReadOptions::SEEK_PREVIOUS_SYNC: findFlags = SampleTable::kFlagBefore; break; case ReadOptions::SEEK_NEXT_SYNC: findFlags = SampleTable::kFlagAfter; break; case ReadOptions::SEEK_CLOSEST_SYNC: case ReadOptions::SEEK_CLOSEST: findFlags = SampleTable::kFlagClosest; break; default: CHECK(!"Should not be here."); break; } uint32_t sampleIndex; status_t err = mSampleTable->findSampleAtTime( seekTimeUs, 1000000, mTimescale, &sampleIndex, findFlags); if (mode == ReadOptions::SEEK_CLOSEST) { findFlags = SampleTable::kFlagBefore; } uint32_t syncSampleIndex; if (err == OK) { err = mSampleTable->findSyncSampleNear( sampleIndex, &syncSampleIndex, findFlags); } uint32_t sampleTime; if (err == OK) { err = mSampleTable->getMetaDataForSample( sampleIndex, NULL, NULL, &sampleTime); } if (err != OK) { if (err == ERROR_OUT_OF_RANGE) { err = ERROR_END_OF_STREAM; } ALOGV("end of stream"); return err; } if (mode == ReadOptions::SEEK_CLOSEST) { targetSampleTimeUs = (sampleTime * 1000000ll) / mTimescale; } #if 0 uint32_t syncSampleTime; CHECK_EQ(OK, mSampleTable->getMetaDataForSample( syncSampleIndex, NULL, NULL, &syncSampleTime)); ALOGI("seek to time %lld us => sample at time %lld us, " "sync sample at time %lld us", seekTimeUs, sampleTime * 1000000ll / mTimescale, syncSampleTime * 1000000ll / mTimescale); #endif mCurrentSampleIndex = syncSampleIndex; if (mBuffer != NULL) { mBuffer->release(); mBuffer = NULL; } } off64_t offset; size_t size; uint32_t cts, stts; bool isSyncSample; bool newBuffer = false; if (mBuffer == NULL) { newBuffer = true; status_t err = mSampleTable->getMetaDataForSample( mCurrentSampleIndex, &offset, &size, &cts, &isSyncSample, &stts); if (err != OK) { return err; } err = mGroup->acquire_buffer(&mBuffer); if (err != OK) { CHECK(mBuffer == NULL); return err; } } if ((!mIsAVC && !mIsHEVC) || mWantsNALFragments) { if (newBuffer) { ssize_t num_bytes_read = mDataSource->readAt(offset, (uint8_t *)mBuffer->data(), size); if (num_bytes_read < (ssize_t)size) { mBuffer->release(); mBuffer = NULL; return ERROR_IO; } CHECK(mBuffer != NULL); mBuffer->set_range(0, size); mBuffer->meta_data()->clear(); mBuffer->meta_data()->setInt64( kKeyTime, ((int64_t)cts * 1000000) / mTimescale); mBuffer->meta_data()->setInt64( kKeyDuration, ((int64_t)stts * 1000000) / mTimescale); if (targetSampleTimeUs >= 0) { mBuffer->meta_data()->setInt64( kKeyTargetTime, targetSampleTimeUs); } if (isSyncSample) { mBuffer->meta_data()->setInt32(kKeyIsSyncFrame, 1); } ++mCurrentSampleIndex; } if (!mIsAVC && !mIsHEVC) { *out = mBuffer; mBuffer = NULL; return OK; } CHECK(mBuffer->range_length() >= mNALLengthSize); const uint8_t *src = (const uint8_t *)mBuffer->data() + mBuffer->range_offset(); size_t nal_size = parseNALSize(src); if (mBuffer->range_length() < mNALLengthSize + nal_size) { ALOGE("incomplete NAL unit."); mBuffer->release(); mBuffer = NULL; return ERROR_MALFORMED; } MediaBuffer *clone = mBuffer->clone(); CHECK(clone != NULL); clone->set_range(mBuffer->range_offset() + mNALLengthSize, nal_size); CHECK(mBuffer != NULL); mBuffer->set_range( mBuffer->range_offset() + mNALLengthSize + nal_size, mBuffer->range_length() - mNALLengthSize - nal_size); if (mBuffer->range_length() == 0) { mBuffer->release(); mBuffer = NULL; } *out = clone; return OK; } else { ssize_t num_bytes_read = 0; int32_t drm = 0; bool usesDRM = (mFormat->findInt32(kKeyIsDRM, &drm) && drm != 0); if (usesDRM) { num_bytes_read = mDataSource->readAt(offset, (uint8_t*)mBuffer->data(), size); } else { num_bytes_read = mDataSource->readAt(offset, mSrcBuffer, size); } if (num_bytes_read < (ssize_t)size) { mBuffer->release(); mBuffer = NULL; return ERROR_IO; } if (usesDRM) { CHECK(mBuffer != NULL); mBuffer->set_range(0, size); } else { uint8_t *dstData = (uint8_t *)mBuffer->data(); size_t srcOffset = 0; size_t dstOffset = 0; while (srcOffset < size) { bool isMalFormed = !isInRange((size_t)0u, size, srcOffset, mNALLengthSize); size_t nalLength = 0; if (!isMalFormed) { nalLength = parseNALSize(&mSrcBuffer[srcOffset]); srcOffset += mNALLengthSize; isMalFormed = !isInRange((size_t)0u, size, srcOffset, nalLength); } if (isMalFormed) { ALOGE("Video is malformed"); mBuffer->release(); mBuffer = NULL; return ERROR_MALFORMED; } if (nalLength == 0) { continue; } CHECK(dstOffset + 4 <= mBuffer->size()); dstData[dstOffset++] = 0; dstData[dstOffset++] = 0; dstData[dstOffset++] = 0; dstData[dstOffset++] = 1; memcpy(&dstData[dstOffset], &mSrcBuffer[srcOffset], nalLength); srcOffset += nalLength; dstOffset += nalLength; } CHECK_EQ(srcOffset, size); CHECK(mBuffer != NULL); mBuffer->set_range(0, dstOffset); } mBuffer->meta_data()->clear(); mBuffer->meta_data()->setInt64( kKeyTime, ((int64_t)cts * 1000000) / mTimescale); mBuffer->meta_data()->setInt64( kKeyDuration, ((int64_t)stts * 1000000) / mTimescale); if (targetSampleTimeUs >= 0) { mBuffer->meta_data()->setInt64( kKeyTargetTime, targetSampleTimeUs); } if (isSyncSample) { mBuffer->meta_data()->setInt32(kKeyIsSyncFrame, 1); } ++mCurrentSampleIndex; *out = mBuffer; mBuffer = NULL; return OK; } }
173,363
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static opj_bool pi_next_cprl(opj_pi_iterator_t * pi) { opj_pi_comp_t *comp = NULL; opj_pi_resolution_t *res = NULL; long index = 0; if (!pi->first) { comp = &pi->comps[pi->compno]; goto LABEL_SKIP; } else { pi->first = 0; } for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) { int resno; comp = &pi->comps[pi->compno]; pi->dx = 0; pi->dy = 0; for (resno = 0; resno < comp->numresolutions; resno++) { int dx, dy; res = &comp->resolutions[resno]; dx = comp->dx * (1 << (res->pdx + comp->numresolutions - 1 - resno)); dy = comp->dy * (1 << (res->pdy + comp->numresolutions - 1 - resno)); pi->dx = !pi->dx ? dx : int_min(pi->dx, dx); pi->dy = !pi->dy ? dy : int_min(pi->dy, dy); } if (!pi->tp_on) { pi->poc.ty0 = pi->ty0; pi->poc.tx0 = pi->tx0; pi->poc.ty1 = pi->ty1; pi->poc.tx1 = pi->tx1; } for (pi->y = pi->poc.ty0; pi->y < pi->poc.ty1; pi->y += pi->dy - (pi->y % pi->dy)) { for (pi->x = pi->poc.tx0; pi->x < pi->poc.tx1; pi->x += pi->dx - (pi->x % pi->dx)) { for (pi->resno = pi->poc.resno0; pi->resno < int_min(pi->poc.resno1, comp->numresolutions); pi->resno++) { int levelno; int trx0, try0; int trx1, try1; int rpx, rpy; int prci, prcj; res = &comp->resolutions[pi->resno]; levelno = comp->numresolutions - 1 - pi->resno; trx0 = int_ceildiv(pi->tx0, comp->dx << levelno); try0 = int_ceildiv(pi->ty0, comp->dy << levelno); trx1 = int_ceildiv(pi->tx1, comp->dx << levelno); try1 = int_ceildiv(pi->ty1, comp->dy << levelno); rpx = res->pdx + levelno; rpy = res->pdy + levelno; if (!((pi->y % (comp->dy << rpy) == 0) || ((pi->y == pi->ty0) && ((try0 << levelno) % (1 << rpy))))) { continue; } if (!((pi->x % (comp->dx << rpx) == 0) || ((pi->x == pi->tx0) && ((trx0 << levelno) % (1 << rpx))))) { continue; } if ((res->pw == 0) || (res->ph == 0)) { continue; } if ((trx0 == trx1) || (try0 == try1)) { continue; } prci = int_floordivpow2(int_ceildiv(pi->x, comp->dx << levelno), res->pdx) - int_floordivpow2(trx0, res->pdx); prcj = int_floordivpow2(int_ceildiv(pi->y, comp->dy << levelno), res->pdy) - int_floordivpow2(try0, res->pdy); pi->precno = prci + prcj * res->pw; for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) { index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno * pi->step_c + pi->precno * pi->step_p; if (!pi->include[index]) { pi->include[index] = 1; return OPJ_TRUE; } LABEL_SKIP: ; } } } } } return OPJ_FALSE; } Commit Message: [MJ2] To avoid divisions by zero / undefined behaviour on shift Signed-off-by: Young_X <[email protected]> CWE ID: CWE-369
static opj_bool pi_next_cprl(opj_pi_iterator_t * pi) { opj_pi_comp_t *comp = NULL; opj_pi_resolution_t *res = NULL; long index = 0; if (!pi->first) { comp = &pi->comps[pi->compno]; goto LABEL_SKIP; } else { pi->first = 0; } for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) { int resno; comp = &pi->comps[pi->compno]; pi->dx = 0; pi->dy = 0; for (resno = 0; resno < comp->numresolutions; resno++) { int dx, dy; res = &comp->resolutions[resno]; dx = comp->dx * (1 << (res->pdx + comp->numresolutions - 1 - resno)); dy = comp->dy * (1 << (res->pdy + comp->numresolutions - 1 - resno)); pi->dx = !pi->dx ? dx : int_min(pi->dx, dx); pi->dy = !pi->dy ? dy : int_min(pi->dy, dy); } if (!pi->tp_on) { pi->poc.ty0 = pi->ty0; pi->poc.tx0 = pi->tx0; pi->poc.ty1 = pi->ty1; pi->poc.tx1 = pi->tx1; } for (pi->y = pi->poc.ty0; pi->y < pi->poc.ty1; pi->y += pi->dy - (pi->y % pi->dy)) { for (pi->x = pi->poc.tx0; pi->x < pi->poc.tx1; pi->x += pi->dx - (pi->x % pi->dx)) { for (pi->resno = pi->poc.resno0; pi->resno < int_min(pi->poc.resno1, comp->numresolutions); pi->resno++) { int levelno; int trx0, try0; int trx1, try1; int rpx, rpy; int prci, prcj; res = &comp->resolutions[pi->resno]; levelno = comp->numresolutions - 1 - pi->resno; trx0 = int_ceildiv(pi->tx0, comp->dx << levelno); try0 = int_ceildiv(pi->ty0, comp->dy << levelno); trx1 = int_ceildiv(pi->tx1, comp->dx << levelno); try1 = int_ceildiv(pi->ty1, comp->dy << levelno); rpx = res->pdx + levelno; rpy = res->pdy + levelno; /* To avoid divisions by zero / undefined behaviour on shift */ if (rpx >= 31 || ((comp->dx << rpx) >> rpx) != comp->dx || rpy >= 31 || ((comp->dy << rpy) >> rpy) != comp->dy) { continue; } if (!((pi->y % (comp->dy << rpy) == 0) || ((pi->y == pi->ty0) && ((try0 << levelno) % (1 << rpy))))) { continue; } if (!((pi->x % (comp->dx << rpx) == 0) || ((pi->x == pi->tx0) && ((trx0 << levelno) % (1 << rpx))))) { continue; } if ((res->pw == 0) || (res->ph == 0)) { continue; } if ((trx0 == trx1) || (try0 == try1)) { continue; } prci = int_floordivpow2(int_ceildiv(pi->x, comp->dx << levelno), res->pdx) - int_floordivpow2(trx0, res->pdx); prcj = int_floordivpow2(int_ceildiv(pi->y, comp->dy << levelno), res->pdy) - int_floordivpow2(try0, res->pdy); pi->precno = prci + prcj * res->pw; for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) { index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno * pi->step_c + pi->precno * pi->step_p; if (!pi->include[index]) { pi->include[index] = 1; return OPJ_TRUE; } LABEL_SKIP: ; } } } } } return OPJ_FALSE; }
169,772
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void cJSON_AddItemReferenceToArray( cJSON *array, cJSON *item ) { cJSON_AddItemToArray( array, create_reference( item ) ); } Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a malformed JSON string was passed on the control channel. This issue, present in the cJSON library, was already fixed upstream, so was addressed here in iperf3 by importing a newer version of cJSON (plus local ESnet modifications). Discovered and reported by Dave McDaniel, Cisco Talos. Based on a patch by @dopheide-esnet, with input from @DaveGamble. Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001, CVE-2016-4303 (cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40) Signed-off-by: Bruce A. Mah <[email protected]> CWE ID: CWE-119
void cJSON_AddItemReferenceToArray( cJSON *array, cJSON *item )
167,265
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void xfrm6_tunnel_spi_fini(void) { kmem_cache_destroy(xfrm6_tunnel_spi_kmem); } Commit Message: tunnels: fix netns vs proto registration ordering Same stuff as in ip_gre patch: receive hook can be called before netns setup is done, oopsing in net_generic(). Signed-off-by: Alexey Dobriyan <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-362
static void xfrm6_tunnel_spi_fini(void)
165,881
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: PHP_FUNCTION(grapheme_strpos) { unsigned char *haystack, *needle; int haystack_len, needle_len; unsigned char *found; long loffset = 0; int32_t offset = 0; int ret_pos; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss|l", (char **)&haystack, &haystack_len, (char **)&needle, &needle_len, &loffset) == FAILURE) { intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR, "grapheme_strpos: unable to parse input param", 0 TSRMLS_CC ); RETURN_FALSE; } if ( OUTSIDE_STRING(loffset, haystack_len) ) { intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR, "grapheme_strpos: Offset not contained in string", 1 TSRMLS_CC ); RETURN_FALSE; } /* we checked that it will fit: */ offset = (int32_t) loffset; /* the offset is 'grapheme count offset' so it still might be invalid - we'll check it later */ intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR, "grapheme_strpos: Empty delimiter", 1 TSRMLS_CC ); RETURN_FALSE; } Commit Message: CWE ID:
PHP_FUNCTION(grapheme_strpos) { unsigned char *haystack, *needle; int haystack_len, needle_len; unsigned char *found; long loffset = 0; int32_t offset = 0, noffset = 0; int ret_pos; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss|l", (char **)&haystack, &haystack_len, (char **)&needle, &needle_len, &loffset) == FAILURE) { intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR, "grapheme_strpos: unable to parse input param", 0 TSRMLS_CC ); RETURN_FALSE; } if ( OUTSIDE_STRING(loffset, haystack_len) ) { intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR, "grapheme_strpos: Offset not contained in string", 1 TSRMLS_CC ); RETURN_FALSE; } /* we checked that it will fit: */ offset = (int32_t) loffset; noffset = offset >= 0 ? offset : haystack_len + offset; /* the offset is 'grapheme count offset' so it still might be invalid - we'll check it later */ intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR, "grapheme_strpos: Empty delimiter", 1 TSRMLS_CC ); RETURN_FALSE; }
165,034
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: rpl_dio_print(netdissect_options *ndo, const u_char *bp, u_int length) { const struct nd_rpl_dio *dio = (const struct nd_rpl_dio *)bp; const char *dagid_str; ND_TCHECK(*dio); dagid_str = ip6addr_string (ndo, dio->rpl_dagid); ND_PRINT((ndo, " [dagid:%s,seq:%u,instance:%u,rank:%u,%smop:%s,prf:%u]", dagid_str, dio->rpl_dtsn, dio->rpl_instanceid, EXTRACT_16BITS(&dio->rpl_dagrank), RPL_DIO_GROUNDED(dio->rpl_mopprf) ? "grounded,":"", tok2str(rpl_mop_values, "mop%u", RPL_DIO_MOP(dio->rpl_mopprf)), RPL_DIO_PRF(dio->rpl_mopprf))); if(ndo->ndo_vflag > 1) { const struct rpl_dio_genoption *opt = (const struct rpl_dio_genoption *)&dio[1]; rpl_dio_printopt(ndo, opt, length); } return; trunc: ND_PRINT((ndo," [|truncated]")); return; } Commit Message: (for 4.9.3) CVE-2018-14882/ICMP6 RPL: Add a missing bounds check Moreover: Add and use *_tstr[] strings. Update four tests outputs accordingly. Fix a space. Wang Junjie of 360 ESG Codesafe Team had independently identified this vulnerability in 2018 by means of fuzzing and provided the packet capture file for the test. CWE ID: CWE-125
rpl_dio_print(netdissect_options *ndo, const u_char *bp, u_int length) { const struct nd_rpl_dio *dio = (const struct nd_rpl_dio *)bp; const char *dagid_str; ND_TCHECK(*dio); dagid_str = ip6addr_string (ndo, dio->rpl_dagid); ND_PRINT((ndo, " [dagid:%s,seq:%u,instance:%u,rank:%u,%smop:%s,prf:%u]", dagid_str, dio->rpl_dtsn, dio->rpl_instanceid, EXTRACT_16BITS(&dio->rpl_dagrank), RPL_DIO_GROUNDED(dio->rpl_mopprf) ? "grounded,":"", tok2str(rpl_mop_values, "mop%u", RPL_DIO_MOP(dio->rpl_mopprf)), RPL_DIO_PRF(dio->rpl_mopprf))); if(ndo->ndo_vflag > 1) { const struct rpl_dio_genoption *opt = (const struct rpl_dio_genoption *)&dio[1]; rpl_dio_printopt(ndo, opt, length); } return; trunc: ND_PRINT((ndo, "%s", rpl_tstr)); return; }
169,830
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int do_mathemu(struct pt_regs *regs, struct task_struct *fpt) { /* regs->pc isn't necessarily the PC at which the offending insn is sitting. * The FPU maintains a queue of FPops which cause traps. * When it hits an instruction that requires that the trapped op succeeded * (usually because it reads a reg. that the trapped op wrote) then it * causes this exception. We need to emulate all the insns on the queue * and then allow the op to proceed. * This code should also handle the case where the trap was precise, * in which case the queue length is zero and regs->pc points at the * single FPop to be emulated. (this case is untested, though :->) * You'll need this case if you want to be able to emulate all FPops * because the FPU either doesn't exist or has been software-disabled. * [The UltraSPARC makes FP a precise trap; this isn't as stupid as it * might sound because the Ultra does funky things with a superscalar * architecture.] */ /* You wouldn't believe how often I typed 'ftp' when I meant 'fpt' :-> */ int i; int retcode = 0; /* assume all succeed */ unsigned long insn; perf_sw_event(PERF_COUNT_SW_EMULATION_FAULTS, 1, 0, regs, 0); #ifdef DEBUG_MATHEMU printk("In do_mathemu()... pc is %08lx\n", regs->pc); printk("fpqdepth is %ld\n", fpt->thread.fpqdepth); for (i = 0; i < fpt->thread.fpqdepth; i++) printk("%d: %08lx at %08lx\n", i, fpt->thread.fpqueue[i].insn, (unsigned long)fpt->thread.fpqueue[i].insn_addr); #endif if (fpt->thread.fpqdepth == 0) { /* no queue, guilty insn is at regs->pc */ #ifdef DEBUG_MATHEMU printk("precise trap at %08lx\n", regs->pc); #endif if (!get_user(insn, (u32 __user *) regs->pc)) { retcode = do_one_mathemu(insn, &fpt->thread.fsr, fpt->thread.float_regs); if (retcode) { /* in this case we need to fix up PC & nPC */ regs->pc = regs->npc; regs->npc += 4; } } return retcode; } /* Normal case: need to empty the queue... */ for (i = 0; i < fpt->thread.fpqdepth; i++) { retcode = do_one_mathemu(fpt->thread.fpqueue[i].insn, &(fpt->thread.fsr), fpt->thread.float_regs); if (!retcode) /* insn failed, no point doing any more */ break; } /* Now empty the queue and clear the queue_not_empty flag */ if (retcode) fpt->thread.fsr &= ~(0x3000 | FSR_CEXC_MASK); else fpt->thread.fsr &= ~0x3000; fpt->thread.fpqdepth = 0; return retcode; } Commit Message: perf: Remove the nmi parameter from the swevent and overflow interface The nmi parameter indicated if we could do wakeups from the current context, if not, we would set some state and self-IPI and let the resulting interrupt do the wakeup. For the various event classes: - hardware: nmi=0; PMI is in fact an NMI or we run irq_work_run from the PMI-tail (ARM etc.) - tracepoint: nmi=0; since tracepoint could be from NMI context. - software: nmi=[0,1]; some, like the schedule thing cannot perform wakeups, and hence need 0. As one can see, there is very little nmi=1 usage, and the down-side of not using it is that on some platforms some software events can have a jiffy delay in wakeup (when arch_irq_work_raise isn't implemented). The up-side however is that we can remove the nmi parameter and save a bunch of conditionals in fast paths. Signed-off-by: Peter Zijlstra <[email protected]> Cc: Michael Cree <[email protected]> Cc: Will Deacon <[email protected]> Cc: Deng-Cheng Zhu <[email protected]> Cc: Anton Blanchard <[email protected]> Cc: Eric B Munson <[email protected]> Cc: Heiko Carstens <[email protected]> Cc: Paul Mundt <[email protected]> Cc: David S. Miller <[email protected]> Cc: Frederic Weisbecker <[email protected]> Cc: Jason Wessel <[email protected]> Cc: Don Zickus <[email protected]> Link: http://lkml.kernel.org/n/[email protected] Signed-off-by: Ingo Molnar <[email protected]> CWE ID: CWE-399
int do_mathemu(struct pt_regs *regs, struct task_struct *fpt) { /* regs->pc isn't necessarily the PC at which the offending insn is sitting. * The FPU maintains a queue of FPops which cause traps. * When it hits an instruction that requires that the trapped op succeeded * (usually because it reads a reg. that the trapped op wrote) then it * causes this exception. We need to emulate all the insns on the queue * and then allow the op to proceed. * This code should also handle the case where the trap was precise, * in which case the queue length is zero and regs->pc points at the * single FPop to be emulated. (this case is untested, though :->) * You'll need this case if you want to be able to emulate all FPops * because the FPU either doesn't exist or has been software-disabled. * [The UltraSPARC makes FP a precise trap; this isn't as stupid as it * might sound because the Ultra does funky things with a superscalar * architecture.] */ /* You wouldn't believe how often I typed 'ftp' when I meant 'fpt' :-> */ int i; int retcode = 0; /* assume all succeed */ unsigned long insn; perf_sw_event(PERF_COUNT_SW_EMULATION_FAULTS, 1, regs, 0); #ifdef DEBUG_MATHEMU printk("In do_mathemu()... pc is %08lx\n", regs->pc); printk("fpqdepth is %ld\n", fpt->thread.fpqdepth); for (i = 0; i < fpt->thread.fpqdepth; i++) printk("%d: %08lx at %08lx\n", i, fpt->thread.fpqueue[i].insn, (unsigned long)fpt->thread.fpqueue[i].insn_addr); #endif if (fpt->thread.fpqdepth == 0) { /* no queue, guilty insn is at regs->pc */ #ifdef DEBUG_MATHEMU printk("precise trap at %08lx\n", regs->pc); #endif if (!get_user(insn, (u32 __user *) regs->pc)) { retcode = do_one_mathemu(insn, &fpt->thread.fsr, fpt->thread.float_regs); if (retcode) { /* in this case we need to fix up PC & nPC */ regs->pc = regs->npc; regs->npc += 4; } } return retcode; } /* Normal case: need to empty the queue... */ for (i = 0; i < fpt->thread.fpqdepth; i++) { retcode = do_one_mathemu(fpt->thread.fpqueue[i].insn, &(fpt->thread.fsr), fpt->thread.float_regs); if (!retcode) /* insn failed, no point doing any more */ break; } /* Now empty the queue and clear the queue_not_empty flag */ if (retcode) fpt->thread.fsr &= ~(0x3000 | FSR_CEXC_MASK); else fpt->thread.fsr &= ~0x3000; fpt->thread.fpqdepth = 0; return retcode; }
165,814
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: WORD32 ih264d_start_of_pic(dec_struct_t *ps_dec, WORD32 i4_poc, pocstruct_t *ps_temp_poc, UWORD16 u2_frame_num, dec_pic_params_t *ps_pps) { pocstruct_t *ps_prev_poc = &ps_dec->s_cur_pic_poc; pocstruct_t *ps_cur_poc = ps_temp_poc; pic_buffer_t *pic_buf; ivd_video_decode_op_t * ps_dec_output = (ivd_video_decode_op_t *)ps_dec->pv_dec_out; dec_slice_params_t *ps_cur_slice = ps_dec->ps_cur_slice; dec_seq_params_t *ps_seq = ps_pps->ps_sps; UWORD8 u1_bottom_field_flag = ps_cur_slice->u1_bottom_field_flag; UWORD8 u1_field_pic_flag = ps_cur_slice->u1_field_pic_flag; /* high profile related declarations */ high_profile_tools_t s_high_profile; WORD32 ret; H264_MUTEX_LOCK(&ps_dec->process_disp_mutex); ps_prev_poc->i4_pic_order_cnt_lsb = ps_cur_poc->i4_pic_order_cnt_lsb; ps_prev_poc->i4_pic_order_cnt_msb = ps_cur_poc->i4_pic_order_cnt_msb; ps_prev_poc->i4_delta_pic_order_cnt_bottom = ps_cur_poc->i4_delta_pic_order_cnt_bottom; ps_prev_poc->i4_delta_pic_order_cnt[0] = ps_cur_poc->i4_delta_pic_order_cnt[0]; ps_prev_poc->i4_delta_pic_order_cnt[1] = ps_cur_poc->i4_delta_pic_order_cnt[1]; ps_prev_poc->u1_bot_field = ps_dec->ps_cur_slice->u1_bottom_field_flag; ps_prev_poc->i4_prev_frame_num_ofst = ps_cur_poc->i4_prev_frame_num_ofst; ps_prev_poc->u2_frame_num = u2_frame_num; ps_dec->i1_prev_mb_qp_delta = 0; ps_dec->i1_next_ctxt_idx = 0; ps_dec->u4_nmb_deblk = 0; if(ps_dec->u4_num_cores == 1) ps_dec->u4_nmb_deblk = 1; if(ps_seq->u1_mb_aff_flag == 1) { ps_dec->u4_nmb_deblk = 0; if(ps_dec->u4_num_cores > 2) ps_dec->u4_num_cores = 2; } ps_dec->u4_use_intrapred_line_copy = 0; if (ps_seq->u1_mb_aff_flag == 0) { ps_dec->u4_use_intrapred_line_copy = 1; } ps_dec->u4_app_disable_deblk_frm = 0; /* If degrade is enabled, set the degrade flags appropriately */ if(ps_dec->i4_degrade_type && ps_dec->i4_degrade_pics) { WORD32 degrade_pic; ps_dec->i4_degrade_pic_cnt++; degrade_pic = 0; /* If degrade is to be done in all frames, then do not check further */ switch(ps_dec->i4_degrade_pics) { case 4: { degrade_pic = 1; break; } case 3: { if(ps_cur_slice->u1_slice_type != I_SLICE) degrade_pic = 1; break; } case 2: { /* If pic count hits non-degrade interval or it is an islice, then do not degrade */ if((ps_cur_slice->u1_slice_type != I_SLICE) && (ps_dec->i4_degrade_pic_cnt != ps_dec->i4_nondegrade_interval)) degrade_pic = 1; break; } case 1: { /* Check if the current picture is non-ref */ if(0 == ps_cur_slice->u1_nal_ref_idc) { degrade_pic = 1; } break; } } if(degrade_pic) { if(ps_dec->i4_degrade_type & 0x2) ps_dec->u4_app_disable_deblk_frm = 1; /* MC degrading is done only for non-ref pictures */ if(0 == ps_cur_slice->u1_nal_ref_idc) { if(ps_dec->i4_degrade_type & 0x4) ps_dec->i4_mv_frac_mask = 0; if(ps_dec->i4_degrade_type & 0x8) ps_dec->i4_mv_frac_mask = 0; } } else ps_dec->i4_degrade_pic_cnt = 0; } { dec_err_status_t * ps_err = ps_dec->ps_dec_err_status; if(ps_dec->u1_sl_typ_5_9 && ((ps_cur_slice->u1_slice_type == I_SLICE) || (ps_cur_slice->u1_slice_type == SI_SLICE))) ps_err->u1_cur_pic_type = PIC_TYPE_I; else ps_err->u1_cur_pic_type = PIC_TYPE_UNKNOWN; if(ps_err->u1_pic_aud_i == PIC_TYPE_I) { ps_err->u1_cur_pic_type = PIC_TYPE_I; ps_err->u1_pic_aud_i = PIC_TYPE_UNKNOWN; } if(ps_cur_slice->u1_nal_unit_type == IDR_SLICE_NAL) { if(ps_err->u1_err_flag) ih264d_reset_ref_bufs(ps_dec->ps_dpb_mgr); ps_err->u1_err_flag = ACCEPT_ALL_PICS; } } if(ps_dec->u1_init_dec_flag && ps_dec->s_prev_seq_params.u1_eoseq_pending) { /* Reset the decoder picture buffers */ WORD32 j; for(j = 0; j < MAX_DISP_BUFS_NEW; j++) { ih264_buf_mgr_release((buf_mgr_t *)ps_dec->pv_pic_buf_mgr, j, BUF_MGR_REF); ih264_buf_mgr_release((buf_mgr_t *)ps_dec->pv_mv_buf_mgr, ps_dec->au1_pic_buf_id_mv_buf_id_map[j], BUF_MGR_REF); ih264_buf_mgr_release((buf_mgr_t *)ps_dec->pv_pic_buf_mgr, j, BUF_MGR_IO); } /* reset the decoder structure parameters related to buffer handling */ ps_dec->u1_second_field = 0; ps_dec->i4_cur_display_seq = 0; /********************************************************************/ /* indicate in the decoder output i4_status that some frames are being */ /* dropped, so that it resets timestamp and wait for a new sequence */ /********************************************************************/ ps_dec->s_prev_seq_params.u1_eoseq_pending = 0; } ret = ih264d_init_pic(ps_dec, u2_frame_num, i4_poc, ps_pps); if(ret != OK) return ret; ps_dec->pv_parse_tu_coeff_data = ps_dec->pv_pic_tu_coeff_data; ps_dec->pv_proc_tu_coeff_data = ps_dec->pv_pic_tu_coeff_data; ps_dec->ps_nmb_info = ps_dec->ps_frm_mb_info; if(ps_dec->u1_separate_parse) { UWORD16 pic_wd = ps_dec->u4_width_at_init; UWORD16 pic_ht = ps_dec->u4_height_at_init; UWORD32 num_mbs; if((NULL != ps_dec->ps_cur_sps) && (1 == (ps_dec->ps_cur_sps->u1_is_valid))) { pic_wd = ps_dec->u2_pic_wd; pic_ht = ps_dec->u2_pic_ht; } num_mbs = (pic_wd * pic_ht) >> 8; if(ps_dec->pu1_dec_mb_map) { memset((void *)ps_dec->pu1_dec_mb_map, 0, num_mbs); } if(ps_dec->pu1_recon_mb_map) { memset((void *)ps_dec->pu1_recon_mb_map, 0, num_mbs); } if(ps_dec->pu2_slice_num_map) { memset((void *)ps_dec->pu2_slice_num_map, 0, (num_mbs * sizeof(UWORD16))); } } ps_dec->ps_parse_cur_slice = &(ps_dec->ps_dec_slice_buf[0]); ps_dec->ps_decode_cur_slice = &(ps_dec->ps_dec_slice_buf[0]); ps_dec->ps_computebs_cur_slice = &(ps_dec->ps_dec_slice_buf[0]); ps_dec->u2_cur_slice_num = 0; /* Initialize all the HP toolsets to zero */ ps_dec->s_high_profile.u1_scaling_present = 0; ps_dec->s_high_profile.u1_transform8x8_present = 0; /* Get Next Free Picture */ if(1 == ps_dec->u4_share_disp_buf) { UWORD32 i; /* Free any buffer that is in the queue to be freed */ for(i = 0; i < MAX_DISP_BUFS_NEW; i++) { if(0 == ps_dec->u4_disp_buf_to_be_freed[i]) continue; ih264_buf_mgr_release((buf_mgr_t *)ps_dec->pv_pic_buf_mgr, i, BUF_MGR_IO); ps_dec->u4_disp_buf_to_be_freed[i] = 0; ps_dec->u4_disp_buf_mapping[i] = 0; } } if(!(u1_field_pic_flag && 0 != ps_dec->u1_top_bottom_decoded)) //ps_dec->u1_second_field)) { pic_buffer_t *ps_cur_pic; WORD32 cur_pic_buf_id, cur_mv_buf_id; col_mv_buf_t *ps_col_mv; while(1) { ps_cur_pic = (pic_buffer_t *)ih264_buf_mgr_get_next_free( (buf_mgr_t *)ps_dec->pv_pic_buf_mgr, &cur_pic_buf_id); if(ps_cur_pic == NULL) { ps_dec->i4_error_code = ERROR_UNAVAIL_PICBUF_T; return ERROR_UNAVAIL_PICBUF_T; } if(0 == ps_dec->u4_disp_buf_mapping[cur_pic_buf_id]) { break; } } ps_col_mv = (col_mv_buf_t *)ih264_buf_mgr_get_next_free((buf_mgr_t *)ps_dec->pv_mv_buf_mgr, &cur_mv_buf_id); if(ps_col_mv == NULL) { ps_dec->i4_error_code = ERROR_UNAVAIL_MVBUF_T; return ERROR_UNAVAIL_MVBUF_T; } ps_dec->ps_cur_pic = ps_cur_pic; ps_dec->u1_pic_buf_id = cur_pic_buf_id; ps_cur_pic->u4_ts = ps_dec->u4_ts; ps_cur_pic->u1_mv_buf_id = cur_mv_buf_id; ps_dec->au1_pic_buf_id_mv_buf_id_map[cur_pic_buf_id] = cur_mv_buf_id; ps_cur_pic->pu1_col_zero_flag = (UWORD8 *)ps_col_mv->pv_col_zero_flag; ps_cur_pic->ps_mv = (mv_pred_t *)ps_col_mv->pv_mv; ps_dec->au1_pic_buf_ref_flag[cur_pic_buf_id] = 0; { /*make first entry of list0 point to cur pic,so that if first Islice is in error, ref pic struct will have valid entries*/ ps_dec->ps_ref_pic_buf_lx[0] = ps_dec->ps_dpb_mgr->ps_init_dpb[0]; *(ps_dec->ps_dpb_mgr->ps_init_dpb[0][0]) = *ps_cur_pic; /* Initialize for field reference as well */ *(ps_dec->ps_dpb_mgr->ps_init_dpb[0][MAX_REF_BUFS]) = *ps_cur_pic; } if(!ps_dec->ps_cur_pic) { WORD32 j; H264_DEC_DEBUG_PRINT("------- Display Buffers Reset --------\n"); for(j = 0; j < MAX_DISP_BUFS_NEW; j++) { ih264_buf_mgr_release((buf_mgr_t *)ps_dec->pv_pic_buf_mgr, j, BUF_MGR_REF); ih264_buf_mgr_release((buf_mgr_t *)ps_dec->pv_mv_buf_mgr, ps_dec->au1_pic_buf_id_mv_buf_id_map[j], BUF_MGR_REF); ih264_buf_mgr_release((buf_mgr_t *)ps_dec->pv_pic_buf_mgr, j, BUF_MGR_IO); } ps_dec->i4_cur_display_seq = 0; ps_dec->i4_prev_max_display_seq = 0; ps_dec->i4_max_poc = 0; ps_cur_pic = (pic_buffer_t *)ih264_buf_mgr_get_next_free( (buf_mgr_t *)ps_dec->pv_pic_buf_mgr, &cur_pic_buf_id); if(ps_cur_pic == NULL) { ps_dec->i4_error_code = ERROR_UNAVAIL_PICBUF_T; return ERROR_UNAVAIL_PICBUF_T; } ps_col_mv = (col_mv_buf_t *)ih264_buf_mgr_get_next_free((buf_mgr_t *)ps_dec->pv_mv_buf_mgr, &cur_mv_buf_id); if(ps_col_mv == NULL) { ps_dec->i4_error_code = ERROR_UNAVAIL_MVBUF_T; return ERROR_UNAVAIL_MVBUF_T; } ps_dec->ps_cur_pic = ps_cur_pic; ps_dec->u1_pic_buf_id = cur_pic_buf_id; ps_cur_pic->u4_ts = ps_dec->u4_ts; ps_dec->apv_buf_id_pic_buf_map[cur_pic_buf_id] = (void *)ps_cur_pic; ps_cur_pic->u1_mv_buf_id = cur_mv_buf_id; ps_dec->au1_pic_buf_id_mv_buf_id_map[cur_pic_buf_id] = cur_mv_buf_id; ps_cur_pic->pu1_col_zero_flag = (UWORD8 *)ps_col_mv->pv_col_zero_flag; ps_cur_pic->ps_mv = (mv_pred_t *)ps_col_mv->pv_mv; ps_dec->au1_pic_buf_ref_flag[cur_pic_buf_id] = 0; } ps_dec->ps_cur_pic->u1_picturetype = u1_field_pic_flag; ps_dec->ps_cur_pic->u4_pack_slc_typ = SKIP_NONE; H264_DEC_DEBUG_PRINT("got a buffer\n"); } else { H264_DEC_DEBUG_PRINT("did not get a buffer\n"); } ps_dec->u4_pic_buf_got = 1; ps_dec->ps_cur_pic->i4_poc = i4_poc; ps_dec->ps_cur_pic->i4_frame_num = u2_frame_num; ps_dec->ps_cur_pic->i4_pic_num = u2_frame_num; ps_dec->ps_cur_pic->i4_top_field_order_cnt = ps_pps->i4_top_field_order_cnt; ps_dec->ps_cur_pic->i4_bottom_field_order_cnt = ps_pps->i4_bottom_field_order_cnt; ps_dec->ps_cur_pic->i4_avg_poc = ps_pps->i4_avg_poc; ps_dec->ps_cur_pic->u4_time_stamp = ps_dec->u4_pts; ps_dec->s_cur_pic = *(ps_dec->ps_cur_pic); if(u1_field_pic_flag && u1_bottom_field_flag) { WORD32 i4_temp_poc; WORD32 i4_top_field_order_poc, i4_bot_field_order_poc; /* Point to odd lines, since it's bottom field */ ps_dec->s_cur_pic.pu1_buf1 += ps_dec->s_cur_pic.u2_frm_wd_y; ps_dec->s_cur_pic.pu1_buf2 += ps_dec->s_cur_pic.u2_frm_wd_uv; ps_dec->s_cur_pic.pu1_buf3 += ps_dec->s_cur_pic.u2_frm_wd_uv; ps_dec->s_cur_pic.ps_mv += ((ps_dec->u2_pic_ht * ps_dec->u2_pic_wd) >> 5); ps_dec->s_cur_pic.pu1_col_zero_flag += ((ps_dec->u2_pic_ht * ps_dec->u2_pic_wd) >> 5); ps_dec->ps_cur_pic->u1_picturetype |= BOT_FLD; i4_top_field_order_poc = ps_dec->ps_cur_pic->i4_top_field_order_cnt; i4_bot_field_order_poc = ps_dec->ps_cur_pic->i4_bottom_field_order_cnt; i4_temp_poc = MIN(i4_top_field_order_poc, i4_bot_field_order_poc); ps_dec->ps_cur_pic->i4_avg_poc = i4_temp_poc; } ps_cur_slice->u1_mbaff_frame_flag = ps_seq->u1_mb_aff_flag && (!u1_field_pic_flag); ps_dec->ps_cur_pic->u1_picturetype |= (ps_cur_slice->u1_mbaff_frame_flag << 2); ps_dec->ps_cur_mb_row = ps_dec->ps_nbr_mb_row; //[0]; ps_dec->ps_cur_mb_row++; //Increment by 1 ,so that left mb will always be valid ps_dec->ps_top_mb_row = ps_dec->ps_nbr_mb_row + ((ps_dec->u2_frm_wd_in_mbs + 1) << (1 - ps_dec->ps_cur_sps->u1_frame_mbs_only_flag)); ps_dec->ps_top_mb_row++; //Increment by 1 ,so that left mb will always be valid ps_dec->pu1_y = ps_dec->pu1_y_scratch[0]; ps_dec->pu1_u = ps_dec->pu1_u_scratch[0]; ps_dec->pu1_v = ps_dec->pu1_v_scratch[0]; ps_dec->u1_yuv_scratch_idx = 0; /* CHANGED CODE */ ps_dec->ps_mv_cur = ps_dec->s_cur_pic.ps_mv; ps_dec->ps_mv_top = ps_dec->ps_mv_top_p[0]; /* CHANGED CODE */ ps_dec->u1_mv_top_p = 0; ps_dec->u1_mb_idx = 0; /* CHANGED CODE */ ps_dec->ps_mv_left = ps_dec->s_cur_pic.ps_mv; ps_dec->pu1_yleft = 0; ps_dec->pu1_uleft = 0; ps_dec->pu1_vleft = 0; ps_dec->u1_not_wait_rec = 2; ps_dec->u2_total_mbs_coded = 0; ps_dec->i4_submb_ofst = -(SUB_BLK_SIZE); ps_dec->u4_pred_info_idx = 0; ps_dec->u4_pred_info_pkd_idx = 0; ps_dec->u4_dma_buf_idx = 0; ps_dec->ps_mv = ps_dec->s_cur_pic.ps_mv; ps_dec->ps_mv_bank_cur = ps_dec->s_cur_pic.ps_mv; ps_dec->pu1_col_zero_flag = ps_dec->s_cur_pic.pu1_col_zero_flag; ps_dec->ps_part = ps_dec->ps_parse_part_params; ps_dec->i2_prev_slice_mbx = -1; ps_dec->i2_prev_slice_mby = 0; ps_dec->u2_mv_2mb[0] = 0; ps_dec->u2_mv_2mb[1] = 0; ps_dec->u1_last_pic_not_decoded = 0; ps_dec->u2_cur_slice_num_dec_thread = 0; ps_dec->u2_cur_slice_num_bs = 0; ps_dec->u4_intra_pred_line_ofst = 0; ps_dec->pu1_cur_y_intra_pred_line = ps_dec->pu1_y_intra_pred_line; ps_dec->pu1_cur_u_intra_pred_line = ps_dec->pu1_u_intra_pred_line; ps_dec->pu1_cur_v_intra_pred_line = ps_dec->pu1_v_intra_pred_line; ps_dec->pu1_cur_y_intra_pred_line_base = ps_dec->pu1_y_intra_pred_line; ps_dec->pu1_cur_u_intra_pred_line_base = ps_dec->pu1_u_intra_pred_line; ps_dec->pu1_cur_v_intra_pred_line_base = ps_dec->pu1_v_intra_pred_line; ps_dec->pu1_prev_y_intra_pred_line = ps_dec->pu1_y_intra_pred_line + (ps_dec->u2_frm_wd_in_mbs * MB_SIZE); ps_dec->pu1_prev_u_intra_pred_line = ps_dec->pu1_u_intra_pred_line + ps_dec->u2_frm_wd_in_mbs * BLK8x8SIZE * YUV420SP_FACTOR; ps_dec->pu1_prev_v_intra_pred_line = ps_dec->pu1_v_intra_pred_line + ps_dec->u2_frm_wd_in_mbs * BLK8x8SIZE; ps_dec->ps_deblk_mbn = ps_dec->ps_deblk_pic; ps_dec->ps_deblk_mbn_curr = ps_dec->ps_deblk_mbn; ps_dec->ps_deblk_mbn_prev = ps_dec->ps_deblk_mbn + ps_dec->u1_recon_mb_grp; /* Initialize The Function Pointer Depending Upon the Entropy and MbAff Flag */ { if(ps_cur_slice->u1_mbaff_frame_flag) { ps_dec->pf_compute_bs = ih264d_compute_bs_mbaff; ps_dec->pf_mvpred = ih264d_mvpred_mbaff; } else { ps_dec->pf_compute_bs = ih264d_compute_bs_non_mbaff; ps_dec->u1_cur_mb_fld_dec_flag = ps_cur_slice->u1_field_pic_flag; } } /* Set up the Parameter for DMA transfer */ { UWORD8 u1_field_pic_flag = ps_dec->ps_cur_slice->u1_field_pic_flag; UWORD8 u1_mbaff = ps_cur_slice->u1_mbaff_frame_flag; UWORD8 uc_lastmbs = (((ps_dec->u2_pic_wd) >> 4) % (ps_dec->u1_recon_mb_grp >> u1_mbaff)); UWORD16 ui16_lastmbs_widthY = (uc_lastmbs ? (uc_lastmbs << 4) : ((ps_dec->u1_recon_mb_grp >> u1_mbaff) << 4)); UWORD16 ui16_lastmbs_widthUV = uc_lastmbs ? (uc_lastmbs << 3) : ((ps_dec->u1_recon_mb_grp >> u1_mbaff) << 3); ps_dec->s_tran_addrecon.pu1_dest_y = ps_dec->s_cur_pic.pu1_buf1; ps_dec->s_tran_addrecon.pu1_dest_u = ps_dec->s_cur_pic.pu1_buf2; ps_dec->s_tran_addrecon.pu1_dest_v = ps_dec->s_cur_pic.pu1_buf3; ps_dec->s_tran_addrecon.u2_frm_wd_y = ps_dec->u2_frm_wd_y << u1_field_pic_flag; ps_dec->s_tran_addrecon.u2_frm_wd_uv = ps_dec->u2_frm_wd_uv << u1_field_pic_flag; if(u1_field_pic_flag) { ui16_lastmbs_widthY += ps_dec->u2_frm_wd_y; ui16_lastmbs_widthUV += ps_dec->u2_frm_wd_uv; } /* Normal Increment of Pointer */ ps_dec->s_tran_addrecon.u4_inc_y[0] = ((ps_dec->u1_recon_mb_grp << 4) >> u1_mbaff); ps_dec->s_tran_addrecon.u4_inc_uv[0] = ((ps_dec->u1_recon_mb_grp << 4) >> u1_mbaff); /* End of Row Increment */ ps_dec->s_tran_addrecon.u4_inc_y[1] = (ui16_lastmbs_widthY + (PAD_LEN_Y_H << 1) + ps_dec->s_tran_addrecon.u2_frm_wd_y * ((15 << u1_mbaff) + u1_mbaff)); ps_dec->s_tran_addrecon.u4_inc_uv[1] = (ui16_lastmbs_widthUV + (PAD_LEN_UV_H << 2) + ps_dec->s_tran_addrecon.u2_frm_wd_uv * ((15 << u1_mbaff) + u1_mbaff)); /* Assign picture numbers to each frame/field */ /* only once per picture. */ ih264d_assign_pic_num(ps_dec); ps_dec->s_tran_addrecon.u2_mv_top_left_inc = (ps_dec->u1_recon_mb_grp << 2) - 1 - (u1_mbaff << 2); ps_dec->s_tran_addrecon.u2_mv_left_inc = ((ps_dec->u1_recon_mb_grp >> u1_mbaff) - 1) << (4 + u1_mbaff); } /**********************************************************************/ /* High profile related initialization at pictrue level */ /**********************************************************************/ if(ps_seq->u1_profile_idc == HIGH_PROFILE_IDC) { if((ps_seq->i4_seq_scaling_matrix_present_flag) || (ps_pps->i4_pic_scaling_matrix_present_flag)) { ih264d_form_scaling_matrix_picture(ps_seq, ps_pps, ps_dec); ps_dec->s_high_profile.u1_scaling_present = 1; } else { ih264d_form_default_scaling_matrix(ps_dec); } if(ps_pps->i4_transform_8x8_mode_flag) { ps_dec->s_high_profile.u1_transform8x8_present = 1; } } else { ih264d_form_default_scaling_matrix(ps_dec); } /* required while reading the transform_size_8x8 u4_flag */ ps_dec->s_high_profile.u1_direct_8x8_inference_flag = ps_seq->u1_direct_8x8_inference_flag; ps_dec->s_high_profile.s_cavlc_ctxt = ps_dec->s_cavlc_ctxt; ps_dec->i1_recon_in_thread3_flag = 1; ps_dec->ps_frame_buf_ip_recon = &ps_dec->s_tran_addrecon; if(ps_dec->u1_separate_parse) { memcpy(&ps_dec->s_tran_addrecon_parse, &ps_dec->s_tran_addrecon, sizeof(tfr_ctxt_t)); if(ps_dec->u4_num_cores >= 3 && ps_dec->i1_recon_in_thread3_flag) { memcpy(&ps_dec->s_tran_iprecon, &ps_dec->s_tran_addrecon, sizeof(tfr_ctxt_t)); ps_dec->ps_frame_buf_ip_recon = &ps_dec->s_tran_iprecon; } } ih264d_init_deblk_tfr_ctxt(ps_dec,&(ps_dec->s_pad_mgr), &(ps_dec->s_tran_addrecon), ps_dec->u2_frm_wd_in_mbs, 0); ps_dec->ps_cur_deblk_mb = ps_dec->ps_deblk_pic; ps_dec->u4_cur_deblk_mb_num = 0; ps_dec->u4_deblk_mb_x = 0; ps_dec->u4_deblk_mb_y = 0; ps_dec->pu4_wt_ofsts = ps_dec->pu4_wts_ofsts_mat; H264_MUTEX_UNLOCK(&ps_dec->process_disp_mutex); return OK; } Commit Message: Decoder: Fixed initialization of first_slice_in_pic To handle some errors, first_slice_in_pic was being set to 2. This is now cleaned up and first_slice_in_pic is set to 1 only once per pic. This will ensure picture level initializations are done only once even in case of error clips Bug: 33717589 Bug: 33551775 Bug: 33716442 Bug: 33677995 Change-Id: If341436b3cbaa724017eedddd88c2e6fac36d8ba CWE ID: CWE-200
WORD32 ih264d_start_of_pic(dec_struct_t *ps_dec, WORD32 i4_poc, pocstruct_t *ps_temp_poc, UWORD16 u2_frame_num, dec_pic_params_t *ps_pps) { pocstruct_t *ps_prev_poc = &ps_dec->s_cur_pic_poc; pocstruct_t *ps_cur_poc = ps_temp_poc; pic_buffer_t *pic_buf; ivd_video_decode_op_t * ps_dec_output = (ivd_video_decode_op_t *)ps_dec->pv_dec_out; dec_slice_params_t *ps_cur_slice = ps_dec->ps_cur_slice; dec_seq_params_t *ps_seq = ps_pps->ps_sps; UWORD8 u1_bottom_field_flag = ps_cur_slice->u1_bottom_field_flag; UWORD8 u1_field_pic_flag = ps_cur_slice->u1_field_pic_flag; /* high profile related declarations */ high_profile_tools_t s_high_profile; WORD32 ret; H264_MUTEX_LOCK(&ps_dec->process_disp_mutex); ps_prev_poc->i4_pic_order_cnt_lsb = ps_cur_poc->i4_pic_order_cnt_lsb; ps_prev_poc->i4_pic_order_cnt_msb = ps_cur_poc->i4_pic_order_cnt_msb; ps_prev_poc->i4_delta_pic_order_cnt_bottom = ps_cur_poc->i4_delta_pic_order_cnt_bottom; ps_prev_poc->i4_delta_pic_order_cnt[0] = ps_cur_poc->i4_delta_pic_order_cnt[0]; ps_prev_poc->i4_delta_pic_order_cnt[1] = ps_cur_poc->i4_delta_pic_order_cnt[1]; ps_prev_poc->u1_bot_field = ps_dec->ps_cur_slice->u1_bottom_field_flag; ps_prev_poc->i4_prev_frame_num_ofst = ps_cur_poc->i4_prev_frame_num_ofst; ps_prev_poc->u2_frame_num = u2_frame_num; ps_dec->i1_prev_mb_qp_delta = 0; ps_dec->i1_next_ctxt_idx = 0; ps_dec->u4_nmb_deblk = 0; if(ps_dec->u4_num_cores == 1) ps_dec->u4_nmb_deblk = 1; if(ps_seq->u1_mb_aff_flag == 1) { ps_dec->u4_nmb_deblk = 0; if(ps_dec->u4_num_cores > 2) ps_dec->u4_num_cores = 2; } ps_dec->u4_use_intrapred_line_copy = 0; if (ps_seq->u1_mb_aff_flag == 0) { ps_dec->u4_use_intrapred_line_copy = 1; } ps_dec->u4_app_disable_deblk_frm = 0; /* If degrade is enabled, set the degrade flags appropriately */ if(ps_dec->i4_degrade_type && ps_dec->i4_degrade_pics) { WORD32 degrade_pic; ps_dec->i4_degrade_pic_cnt++; degrade_pic = 0; /* If degrade is to be done in all frames, then do not check further */ switch(ps_dec->i4_degrade_pics) { case 4: { degrade_pic = 1; break; } case 3: { if(ps_cur_slice->u1_slice_type != I_SLICE) degrade_pic = 1; break; } case 2: { /* If pic count hits non-degrade interval or it is an islice, then do not degrade */ if((ps_cur_slice->u1_slice_type != I_SLICE) && (ps_dec->i4_degrade_pic_cnt != ps_dec->i4_nondegrade_interval)) degrade_pic = 1; break; } case 1: { /* Check if the current picture is non-ref */ if(0 == ps_cur_slice->u1_nal_ref_idc) { degrade_pic = 1; } break; } } if(degrade_pic) { if(ps_dec->i4_degrade_type & 0x2) ps_dec->u4_app_disable_deblk_frm = 1; /* MC degrading is done only for non-ref pictures */ if(0 == ps_cur_slice->u1_nal_ref_idc) { if(ps_dec->i4_degrade_type & 0x4) ps_dec->i4_mv_frac_mask = 0; if(ps_dec->i4_degrade_type & 0x8) ps_dec->i4_mv_frac_mask = 0; } } else ps_dec->i4_degrade_pic_cnt = 0; } { dec_err_status_t * ps_err = ps_dec->ps_dec_err_status; if(ps_dec->u1_sl_typ_5_9 && ((ps_cur_slice->u1_slice_type == I_SLICE) || (ps_cur_slice->u1_slice_type == SI_SLICE))) ps_err->u1_cur_pic_type = PIC_TYPE_I; else ps_err->u1_cur_pic_type = PIC_TYPE_UNKNOWN; if(ps_err->u1_pic_aud_i == PIC_TYPE_I) { ps_err->u1_cur_pic_type = PIC_TYPE_I; ps_err->u1_pic_aud_i = PIC_TYPE_UNKNOWN; } if(ps_cur_slice->u1_nal_unit_type == IDR_SLICE_NAL) { if(ps_err->u1_err_flag) ih264d_reset_ref_bufs(ps_dec->ps_dpb_mgr); ps_err->u1_err_flag = ACCEPT_ALL_PICS; } } if(ps_dec->u1_init_dec_flag && ps_dec->s_prev_seq_params.u1_eoseq_pending) { /* Reset the decoder picture buffers */ WORD32 j; for(j = 0; j < MAX_DISP_BUFS_NEW; j++) { ih264_buf_mgr_release((buf_mgr_t *)ps_dec->pv_pic_buf_mgr, j, BUF_MGR_REF); ih264_buf_mgr_release((buf_mgr_t *)ps_dec->pv_mv_buf_mgr, ps_dec->au1_pic_buf_id_mv_buf_id_map[j], BUF_MGR_REF); ih264_buf_mgr_release((buf_mgr_t *)ps_dec->pv_pic_buf_mgr, j, BUF_MGR_IO); } /* reset the decoder structure parameters related to buffer handling */ ps_dec->u1_second_field = 0; ps_dec->i4_cur_display_seq = 0; /********************************************************************/ /* indicate in the decoder output i4_status that some frames are being */ /* dropped, so that it resets timestamp and wait for a new sequence */ /********************************************************************/ ps_dec->s_prev_seq_params.u1_eoseq_pending = 0; } ret = ih264d_init_pic(ps_dec, u2_frame_num, i4_poc, ps_pps); if(ret != OK) return ret; ps_dec->pv_parse_tu_coeff_data = ps_dec->pv_pic_tu_coeff_data; ps_dec->pv_proc_tu_coeff_data = ps_dec->pv_pic_tu_coeff_data; ps_dec->ps_nmb_info = ps_dec->ps_frm_mb_info; if(ps_dec->u1_separate_parse) { UWORD16 pic_wd = ps_dec->u4_width_at_init; UWORD16 pic_ht = ps_dec->u4_height_at_init; UWORD32 num_mbs; if((NULL != ps_dec->ps_cur_sps) && (1 == (ps_dec->ps_cur_sps->u1_is_valid))) { pic_wd = ps_dec->u2_pic_wd; pic_ht = ps_dec->u2_pic_ht; } num_mbs = (pic_wd * pic_ht) >> 8; if(ps_dec->pu1_dec_mb_map) { memset((void *)ps_dec->pu1_dec_mb_map, 0, num_mbs); } if(ps_dec->pu1_recon_mb_map) { memset((void *)ps_dec->pu1_recon_mb_map, 0, num_mbs); } if(ps_dec->pu2_slice_num_map) { memset((void *)ps_dec->pu2_slice_num_map, 0, (num_mbs * sizeof(UWORD16))); } } ps_dec->ps_parse_cur_slice = &(ps_dec->ps_dec_slice_buf[0]); ps_dec->ps_decode_cur_slice = &(ps_dec->ps_dec_slice_buf[0]); ps_dec->ps_computebs_cur_slice = &(ps_dec->ps_dec_slice_buf[0]); ps_dec->u2_cur_slice_num = 0; /* Initialize all the HP toolsets to zero */ ps_dec->s_high_profile.u1_scaling_present = 0; ps_dec->s_high_profile.u1_transform8x8_present = 0; /* Get Next Free Picture */ if(1 == ps_dec->u4_share_disp_buf) { UWORD32 i; /* Free any buffer that is in the queue to be freed */ for(i = 0; i < MAX_DISP_BUFS_NEW; i++) { if(0 == ps_dec->u4_disp_buf_to_be_freed[i]) continue; ih264_buf_mgr_release((buf_mgr_t *)ps_dec->pv_pic_buf_mgr, i, BUF_MGR_IO); ps_dec->u4_disp_buf_to_be_freed[i] = 0; ps_dec->u4_disp_buf_mapping[i] = 0; } } if(!(u1_field_pic_flag && 0 != ps_dec->u1_top_bottom_decoded)) //ps_dec->u1_second_field)) { pic_buffer_t *ps_cur_pic; WORD32 cur_pic_buf_id, cur_mv_buf_id; col_mv_buf_t *ps_col_mv; while(1) { ps_cur_pic = (pic_buffer_t *)ih264_buf_mgr_get_next_free( (buf_mgr_t *)ps_dec->pv_pic_buf_mgr, &cur_pic_buf_id); if(ps_cur_pic == NULL) { ps_dec->i4_error_code = ERROR_UNAVAIL_PICBUF_T; return ERROR_UNAVAIL_PICBUF_T; } if(0 == ps_dec->u4_disp_buf_mapping[cur_pic_buf_id]) { break; } } ps_col_mv = (col_mv_buf_t *)ih264_buf_mgr_get_next_free((buf_mgr_t *)ps_dec->pv_mv_buf_mgr, &cur_mv_buf_id); if(ps_col_mv == NULL) { ps_dec->i4_error_code = ERROR_UNAVAIL_MVBUF_T; return ERROR_UNAVAIL_MVBUF_T; } ps_dec->ps_cur_pic = ps_cur_pic; ps_dec->u1_pic_buf_id = cur_pic_buf_id; ps_cur_pic->u4_ts = ps_dec->u4_ts; ps_cur_pic->u1_mv_buf_id = cur_mv_buf_id; ps_dec->au1_pic_buf_id_mv_buf_id_map[cur_pic_buf_id] = cur_mv_buf_id; ps_cur_pic->pu1_col_zero_flag = (UWORD8 *)ps_col_mv->pv_col_zero_flag; ps_cur_pic->ps_mv = (mv_pred_t *)ps_col_mv->pv_mv; ps_dec->au1_pic_buf_ref_flag[cur_pic_buf_id] = 0; { /*make first entry of list0 point to cur pic,so that if first Islice is in error, ref pic struct will have valid entries*/ ps_dec->ps_ref_pic_buf_lx[0] = ps_dec->ps_dpb_mgr->ps_init_dpb[0]; *(ps_dec->ps_dpb_mgr->ps_init_dpb[0][0]) = *ps_cur_pic; /* Initialize for field reference as well */ *(ps_dec->ps_dpb_mgr->ps_init_dpb[0][MAX_REF_BUFS]) = *ps_cur_pic; } if(!ps_dec->ps_cur_pic) { WORD32 j; H264_DEC_DEBUG_PRINT("------- Display Buffers Reset --------\n"); for(j = 0; j < MAX_DISP_BUFS_NEW; j++) { ih264_buf_mgr_release((buf_mgr_t *)ps_dec->pv_pic_buf_mgr, j, BUF_MGR_REF); ih264_buf_mgr_release((buf_mgr_t *)ps_dec->pv_mv_buf_mgr, ps_dec->au1_pic_buf_id_mv_buf_id_map[j], BUF_MGR_REF); ih264_buf_mgr_release((buf_mgr_t *)ps_dec->pv_pic_buf_mgr, j, BUF_MGR_IO); } ps_dec->i4_cur_display_seq = 0; ps_dec->i4_prev_max_display_seq = 0; ps_dec->i4_max_poc = 0; ps_cur_pic = (pic_buffer_t *)ih264_buf_mgr_get_next_free( (buf_mgr_t *)ps_dec->pv_pic_buf_mgr, &cur_pic_buf_id); if(ps_cur_pic == NULL) { ps_dec->i4_error_code = ERROR_UNAVAIL_PICBUF_T; return ERROR_UNAVAIL_PICBUF_T; } ps_col_mv = (col_mv_buf_t *)ih264_buf_mgr_get_next_free((buf_mgr_t *)ps_dec->pv_mv_buf_mgr, &cur_mv_buf_id); if(ps_col_mv == NULL) { ps_dec->i4_error_code = ERROR_UNAVAIL_MVBUF_T; return ERROR_UNAVAIL_MVBUF_T; } ps_dec->ps_cur_pic = ps_cur_pic; ps_dec->u1_pic_buf_id = cur_pic_buf_id; ps_cur_pic->u4_ts = ps_dec->u4_ts; ps_dec->apv_buf_id_pic_buf_map[cur_pic_buf_id] = (void *)ps_cur_pic; ps_cur_pic->u1_mv_buf_id = cur_mv_buf_id; ps_dec->au1_pic_buf_id_mv_buf_id_map[cur_pic_buf_id] = cur_mv_buf_id; ps_cur_pic->pu1_col_zero_flag = (UWORD8 *)ps_col_mv->pv_col_zero_flag; ps_cur_pic->ps_mv = (mv_pred_t *)ps_col_mv->pv_mv; ps_dec->au1_pic_buf_ref_flag[cur_pic_buf_id] = 0; } ps_dec->ps_cur_pic->u1_picturetype = u1_field_pic_flag; ps_dec->ps_cur_pic->u4_pack_slc_typ = SKIP_NONE; H264_DEC_DEBUG_PRINT("got a buffer\n"); } else { H264_DEC_DEBUG_PRINT("did not get a buffer\n"); } ps_dec->u4_pic_buf_got = 1; ps_dec->ps_cur_pic->i4_poc = i4_poc; ps_dec->ps_cur_pic->i4_frame_num = u2_frame_num; ps_dec->ps_cur_pic->i4_pic_num = u2_frame_num; ps_dec->ps_cur_pic->i4_top_field_order_cnt = ps_pps->i4_top_field_order_cnt; ps_dec->ps_cur_pic->i4_bottom_field_order_cnt = ps_pps->i4_bottom_field_order_cnt; ps_dec->ps_cur_pic->i4_avg_poc = ps_pps->i4_avg_poc; ps_dec->ps_cur_pic->u4_time_stamp = ps_dec->u4_pts; ps_dec->s_cur_pic = *(ps_dec->ps_cur_pic); if(u1_field_pic_flag && u1_bottom_field_flag) { WORD32 i4_temp_poc; WORD32 i4_top_field_order_poc, i4_bot_field_order_poc; /* Point to odd lines, since it's bottom field */ ps_dec->s_cur_pic.pu1_buf1 += ps_dec->s_cur_pic.u2_frm_wd_y; ps_dec->s_cur_pic.pu1_buf2 += ps_dec->s_cur_pic.u2_frm_wd_uv; ps_dec->s_cur_pic.pu1_buf3 += ps_dec->s_cur_pic.u2_frm_wd_uv; ps_dec->s_cur_pic.ps_mv += ((ps_dec->u2_pic_ht * ps_dec->u2_pic_wd) >> 5); ps_dec->s_cur_pic.pu1_col_zero_flag += ((ps_dec->u2_pic_ht * ps_dec->u2_pic_wd) >> 5); ps_dec->ps_cur_pic->u1_picturetype |= BOT_FLD; i4_top_field_order_poc = ps_dec->ps_cur_pic->i4_top_field_order_cnt; i4_bot_field_order_poc = ps_dec->ps_cur_pic->i4_bottom_field_order_cnt; i4_temp_poc = MIN(i4_top_field_order_poc, i4_bot_field_order_poc); ps_dec->ps_cur_pic->i4_avg_poc = i4_temp_poc; } ps_cur_slice->u1_mbaff_frame_flag = ps_seq->u1_mb_aff_flag && (!u1_field_pic_flag); ps_dec->ps_cur_pic->u1_picturetype |= (ps_cur_slice->u1_mbaff_frame_flag << 2); ps_dec->ps_cur_mb_row = ps_dec->ps_nbr_mb_row; //[0]; ps_dec->ps_cur_mb_row++; //Increment by 1 ,so that left mb will always be valid ps_dec->ps_top_mb_row = ps_dec->ps_nbr_mb_row + ((ps_dec->u2_frm_wd_in_mbs + 1) << (1 - ps_dec->ps_cur_sps->u1_frame_mbs_only_flag)); ps_dec->ps_top_mb_row++; //Increment by 1 ,so that left mb will always be valid ps_dec->pu1_y = ps_dec->pu1_y_scratch[0]; ps_dec->pu1_u = ps_dec->pu1_u_scratch[0]; ps_dec->pu1_v = ps_dec->pu1_v_scratch[0]; ps_dec->u1_yuv_scratch_idx = 0; /* CHANGED CODE */ ps_dec->ps_mv_cur = ps_dec->s_cur_pic.ps_mv; ps_dec->ps_mv_top = ps_dec->ps_mv_top_p[0]; /* CHANGED CODE */ ps_dec->u1_mv_top_p = 0; ps_dec->u1_mb_idx = 0; /* CHANGED CODE */ ps_dec->ps_mv_left = ps_dec->s_cur_pic.ps_mv; ps_dec->pu1_yleft = 0; ps_dec->pu1_uleft = 0; ps_dec->pu1_vleft = 0; ps_dec->u1_not_wait_rec = 2; ps_dec->u2_total_mbs_coded = 0; ps_dec->i4_submb_ofst = -(SUB_BLK_SIZE); ps_dec->u4_pred_info_idx = 0; ps_dec->u4_pred_info_pkd_idx = 0; ps_dec->u4_dma_buf_idx = 0; ps_dec->ps_mv = ps_dec->s_cur_pic.ps_mv; ps_dec->ps_mv_bank_cur = ps_dec->s_cur_pic.ps_mv; ps_dec->pu1_col_zero_flag = ps_dec->s_cur_pic.pu1_col_zero_flag; ps_dec->ps_part = ps_dec->ps_parse_part_params; ps_dec->i2_prev_slice_mbx = -1; ps_dec->i2_prev_slice_mby = 0; ps_dec->u2_mv_2mb[0] = 0; ps_dec->u2_mv_2mb[1] = 0; ps_dec->u1_last_pic_not_decoded = 0; ps_dec->u2_cur_slice_num_dec_thread = 0; ps_dec->u2_cur_slice_num_bs = 0; ps_dec->u4_intra_pred_line_ofst = 0; ps_dec->pu1_cur_y_intra_pred_line = ps_dec->pu1_y_intra_pred_line; ps_dec->pu1_cur_u_intra_pred_line = ps_dec->pu1_u_intra_pred_line; ps_dec->pu1_cur_v_intra_pred_line = ps_dec->pu1_v_intra_pred_line; ps_dec->pu1_cur_y_intra_pred_line_base = ps_dec->pu1_y_intra_pred_line; ps_dec->pu1_cur_u_intra_pred_line_base = ps_dec->pu1_u_intra_pred_line; ps_dec->pu1_cur_v_intra_pred_line_base = ps_dec->pu1_v_intra_pred_line; ps_dec->pu1_prev_y_intra_pred_line = ps_dec->pu1_y_intra_pred_line + (ps_dec->u2_frm_wd_in_mbs * MB_SIZE); ps_dec->pu1_prev_u_intra_pred_line = ps_dec->pu1_u_intra_pred_line + ps_dec->u2_frm_wd_in_mbs * BLK8x8SIZE * YUV420SP_FACTOR; ps_dec->pu1_prev_v_intra_pred_line = ps_dec->pu1_v_intra_pred_line + ps_dec->u2_frm_wd_in_mbs * BLK8x8SIZE; ps_dec->ps_deblk_mbn = ps_dec->ps_deblk_pic; ps_dec->ps_deblk_mbn_curr = ps_dec->ps_deblk_mbn; ps_dec->ps_deblk_mbn_prev = ps_dec->ps_deblk_mbn + ps_dec->u1_recon_mb_grp; /* Initialize The Function Pointer Depending Upon the Entropy and MbAff Flag */ { if(ps_cur_slice->u1_mbaff_frame_flag) { ps_dec->pf_compute_bs = ih264d_compute_bs_mbaff; ps_dec->pf_mvpred = ih264d_mvpred_mbaff; } else { ps_dec->pf_compute_bs = ih264d_compute_bs_non_mbaff; ps_dec->u1_cur_mb_fld_dec_flag = ps_cur_slice->u1_field_pic_flag; } } /* Set up the Parameter for DMA transfer */ { UWORD8 u1_field_pic_flag = ps_dec->ps_cur_slice->u1_field_pic_flag; UWORD8 u1_mbaff = ps_cur_slice->u1_mbaff_frame_flag; UWORD8 uc_lastmbs = (((ps_dec->u2_pic_wd) >> 4) % (ps_dec->u1_recon_mb_grp >> u1_mbaff)); UWORD16 ui16_lastmbs_widthY = (uc_lastmbs ? (uc_lastmbs << 4) : ((ps_dec->u1_recon_mb_grp >> u1_mbaff) << 4)); UWORD16 ui16_lastmbs_widthUV = uc_lastmbs ? (uc_lastmbs << 3) : ((ps_dec->u1_recon_mb_grp >> u1_mbaff) << 3); ps_dec->s_tran_addrecon.pu1_dest_y = ps_dec->s_cur_pic.pu1_buf1; ps_dec->s_tran_addrecon.pu1_dest_u = ps_dec->s_cur_pic.pu1_buf2; ps_dec->s_tran_addrecon.pu1_dest_v = ps_dec->s_cur_pic.pu1_buf3; ps_dec->s_tran_addrecon.u2_frm_wd_y = ps_dec->u2_frm_wd_y << u1_field_pic_flag; ps_dec->s_tran_addrecon.u2_frm_wd_uv = ps_dec->u2_frm_wd_uv << u1_field_pic_flag; if(u1_field_pic_flag) { ui16_lastmbs_widthY += ps_dec->u2_frm_wd_y; ui16_lastmbs_widthUV += ps_dec->u2_frm_wd_uv; } /* Normal Increment of Pointer */ ps_dec->s_tran_addrecon.u4_inc_y[0] = ((ps_dec->u1_recon_mb_grp << 4) >> u1_mbaff); ps_dec->s_tran_addrecon.u4_inc_uv[0] = ((ps_dec->u1_recon_mb_grp << 4) >> u1_mbaff); /* End of Row Increment */ ps_dec->s_tran_addrecon.u4_inc_y[1] = (ui16_lastmbs_widthY + (PAD_LEN_Y_H << 1) + ps_dec->s_tran_addrecon.u2_frm_wd_y * ((15 << u1_mbaff) + u1_mbaff)); ps_dec->s_tran_addrecon.u4_inc_uv[1] = (ui16_lastmbs_widthUV + (PAD_LEN_UV_H << 2) + ps_dec->s_tran_addrecon.u2_frm_wd_uv * ((15 << u1_mbaff) + u1_mbaff)); /* Assign picture numbers to each frame/field */ /* only once per picture. */ ih264d_assign_pic_num(ps_dec); ps_dec->s_tran_addrecon.u2_mv_top_left_inc = (ps_dec->u1_recon_mb_grp << 2) - 1 - (u1_mbaff << 2); ps_dec->s_tran_addrecon.u2_mv_left_inc = ((ps_dec->u1_recon_mb_grp >> u1_mbaff) - 1) << (4 + u1_mbaff); } /**********************************************************************/ /* High profile related initialization at pictrue level */ /**********************************************************************/ if(ps_seq->u1_profile_idc == HIGH_PROFILE_IDC) { if((ps_seq->i4_seq_scaling_matrix_present_flag) || (ps_pps->i4_pic_scaling_matrix_present_flag)) { ih264d_form_scaling_matrix_picture(ps_seq, ps_pps, ps_dec); ps_dec->s_high_profile.u1_scaling_present = 1; } else { ih264d_form_default_scaling_matrix(ps_dec); } if(ps_pps->i4_transform_8x8_mode_flag) { ps_dec->s_high_profile.u1_transform8x8_present = 1; } } else { ih264d_form_default_scaling_matrix(ps_dec); } /* required while reading the transform_size_8x8 u4_flag */ ps_dec->s_high_profile.u1_direct_8x8_inference_flag = ps_seq->u1_direct_8x8_inference_flag; ps_dec->s_high_profile.s_cavlc_ctxt = ps_dec->s_cavlc_ctxt; ps_dec->i1_recon_in_thread3_flag = 1; ps_dec->ps_frame_buf_ip_recon = &ps_dec->s_tran_addrecon; if(ps_dec->u1_separate_parse) { memcpy(&ps_dec->s_tran_addrecon_parse, &ps_dec->s_tran_addrecon, sizeof(tfr_ctxt_t)); if(ps_dec->u4_num_cores >= 3 && ps_dec->i1_recon_in_thread3_flag) { memcpy(&ps_dec->s_tran_iprecon, &ps_dec->s_tran_addrecon, sizeof(tfr_ctxt_t)); ps_dec->ps_frame_buf_ip_recon = &ps_dec->s_tran_iprecon; } } ih264d_init_deblk_tfr_ctxt(ps_dec,&(ps_dec->s_pad_mgr), &(ps_dec->s_tran_addrecon), ps_dec->u2_frm_wd_in_mbs, 0); ps_dec->ps_cur_deblk_mb = ps_dec->ps_deblk_pic; ps_dec->u4_cur_deblk_mb_num = 0; ps_dec->u4_deblk_mb_x = 0; ps_dec->u4_deblk_mb_y = 0; ps_dec->pu4_wt_ofsts = ps_dec->pu4_wts_ofsts_mat; ps_dec->u4_first_slice_in_pic = 0; H264_MUTEX_UNLOCK(&ps_dec->process_disp_mutex); return OK; }
174,041
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: status_t OMXNodeInstance::allocateBuffer( OMX_U32 portIndex, size_t size, OMX::buffer_id *buffer, void **buffer_data) { Mutex::Autolock autoLock(mLock); BufferMeta *buffer_meta = new BufferMeta(size); OMX_BUFFERHEADERTYPE *header; OMX_ERRORTYPE err = OMX_AllocateBuffer( mHandle, &header, portIndex, buffer_meta, size); if (err != OMX_ErrorNone) { CLOG_ERROR(allocateBuffer, err, BUFFER_FMT(portIndex, "%zu@", size)); delete buffer_meta; buffer_meta = NULL; *buffer = 0; return StatusFromOMXError(err); } CHECK_EQ(header->pAppPrivate, buffer_meta); *buffer = makeBufferID(header); *buffer_data = header->pBuffer; addActiveBuffer(portIndex, *buffer); sp<GraphicBufferSource> bufferSource(getGraphicBufferSource()); if (bufferSource != NULL && portIndex == kPortIndexInput) { bufferSource->addCodecBuffer(header); } CLOG_BUFFER(allocateBuffer, NEW_BUFFER_FMT(*buffer, portIndex, "%zu@%p", size, *buffer_data)); return OK; } Commit Message: DO NOT MERGE omx: check buffer port before using Bug: 28816827 Change-Id: I3d5bad4a1ef96dec544b05bb31cc6f7109aae0a5 CWE ID: CWE-119
status_t OMXNodeInstance::allocateBuffer( OMX_U32 portIndex, size_t size, OMX::buffer_id *buffer, void **buffer_data) { Mutex::Autolock autoLock(mLock); BufferMeta *buffer_meta = new BufferMeta(size, portIndex); OMX_BUFFERHEADERTYPE *header; OMX_ERRORTYPE err = OMX_AllocateBuffer( mHandle, &header, portIndex, buffer_meta, size); if (err != OMX_ErrorNone) { CLOG_ERROR(allocateBuffer, err, BUFFER_FMT(portIndex, "%zu@", size)); delete buffer_meta; buffer_meta = NULL; *buffer = 0; return StatusFromOMXError(err); } CHECK_EQ(header->pAppPrivate, buffer_meta); *buffer = makeBufferID(header); *buffer_data = header->pBuffer; addActiveBuffer(portIndex, *buffer); sp<GraphicBufferSource> bufferSource(getGraphicBufferSource()); if (bufferSource != NULL && portIndex == kPortIndexInput) { bufferSource->addCodecBuffer(header); } CLOG_BUFFER(allocateBuffer, NEW_BUFFER_FMT(*buffer, portIndex, "%zu@%p", size, *buffer_data)); return OK; }
173,524
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int dv_extract_audio(uint8_t* frame, uint8_t* ppcm[4], const DVprofile *sys) { int size, chan, i, j, d, of, smpls, freq, quant, half_ch; uint16_t lc, rc; const uint8_t* as_pack; uint8_t *pcm, ipcm; as_pack = dv_extract_pack(frame, dv_audio_source); if (!as_pack) /* No audio ? */ return 0; smpls = as_pack[1] & 0x3f; /* samples in this frame - min. samples */ freq = (as_pack[4] >> 3) & 0x07; /* 0 - 48kHz, 1 - 44,1kHz, 2 - 32kHz */ quant = as_pack[4] & 0x07; /* 0 - 16bit linear, 1 - 12bit nonlinear */ if (quant > 1) return -1; /* unsupported quantization */ size = (sys->audio_min_samples[freq] + smpls) * 4; /* 2ch, 2bytes */ half_ch = sys->difseg_size / 2; /* We work with 720p frames split in half, thus even frames have * channels 0,1 and odd 2,3. */ ipcm = (sys->height == 720 && !(frame[1] & 0x0C)) ? 2 : 0; pcm = ppcm[ipcm++]; /* for each DIF channel */ for (chan = 0; chan < sys->n_difchan; chan++) { /* for each DIF segment */ for (i = 0; i < sys->difseg_size; i++) { frame += 6 * 80; /* skip DIF segment header */ break; } /* for each AV sequence */ for (j = 0; j < 9; j++) { for (d = 8; d < 80; d += 2) { if (quant == 0) { /* 16bit quantization */ of = sys->audio_shuffle[i][j] + (d - 8) / 2 * sys->audio_stride; if (of*2 >= size) continue; pcm[of*2] = frame[d+1]; // FIXME: maybe we have to admit pcm[of*2+1] = frame[d]; // that DV is a big-endian PCM if (pcm[of*2+1] == 0x80 && pcm[of*2] == 0x00) pcm[of*2+1] = 0; } else { /* 12bit quantization */ lc = ((uint16_t)frame[d] << 4) | ((uint16_t)frame[d+2] >> 4); rc = ((uint16_t)frame[d+1] << 4) | ((uint16_t)frame[d+2] & 0x0f); lc = (lc == 0x800 ? 0 : dv_audio_12to16(lc)); rc = (rc == 0x800 ? 0 : dv_audio_12to16(rc)); of = sys->audio_shuffle[i%half_ch][j] + (d - 8) / 3 * sys->audio_stride; if (of*2 >= size) continue; pcm[of*2] = lc & 0xff; // FIXME: maybe we have to admit pcm[of*2+1] = lc >> 8; // that DV is a big-endian PCM of = sys->audio_shuffle[i%half_ch+half_ch][j] + (d - 8) / 3 * sys->audio_stride; pcm[of*2] = rc & 0xff; // FIXME: maybe we have to admit pcm[of*2+1] = rc >> 8; // that DV is a big-endian PCM ++d; } } frame += 16 * 80; /* 15 Video DIFs + 1 Audio DIF */ } } frame += 16 * 80; /* 15 Video DIFs + 1 Audio DIF */ } Commit Message: CWE ID: CWE-20
static int dv_extract_audio(uint8_t* frame, uint8_t* ppcm[4], const DVprofile *sys) { int size, chan, i, j, d, of, smpls, freq, quant, half_ch; uint16_t lc, rc; const uint8_t* as_pack; uint8_t *pcm, ipcm; as_pack = dv_extract_pack(frame, dv_audio_source); if (!as_pack) /* No audio ? */ return 0; smpls = as_pack[1] & 0x3f; /* samples in this frame - min. samples */ freq = (as_pack[4] >> 3) & 0x07; /* 0 - 48kHz, 1 - 44,1kHz, 2 - 32kHz */ quant = as_pack[4] & 0x07; /* 0 - 16bit linear, 1 - 12bit nonlinear */ if (quant > 1) return -1; /* unsupported quantization */ size = (sys->audio_min_samples[freq] + smpls) * 4; /* 2ch, 2bytes */ half_ch = sys->difseg_size / 2; /* We work with 720p frames split in half, thus even frames have * channels 0,1 and odd 2,3. */ ipcm = (sys->height == 720 && !(frame[1] & 0x0C)) ? 2 : 0; /* for each DIF channel */ for (chan = 0; chan < sys->n_difchan; chan++) { /* next stereo channel (50Mbps and 100Mbps only) */ pcm = ppcm[ipcm++]; if (!pcm) break; /* for each DIF segment */ for (i = 0; i < sys->difseg_size; i++) { frame += 6 * 80; /* skip DIF segment header */ break; } /* for each AV sequence */ for (j = 0; j < 9; j++) { for (d = 8; d < 80; d += 2) { if (quant == 0) { /* 16bit quantization */ of = sys->audio_shuffle[i][j] + (d - 8) / 2 * sys->audio_stride; if (of*2 >= size) continue; pcm[of*2] = frame[d+1]; // FIXME: maybe we have to admit pcm[of*2+1] = frame[d]; // that DV is a big-endian PCM if (pcm[of*2+1] == 0x80 && pcm[of*2] == 0x00) pcm[of*2+1] = 0; } else { /* 12bit quantization */ lc = ((uint16_t)frame[d] << 4) | ((uint16_t)frame[d+2] >> 4); rc = ((uint16_t)frame[d+1] << 4) | ((uint16_t)frame[d+2] & 0x0f); lc = (lc == 0x800 ? 0 : dv_audio_12to16(lc)); rc = (rc == 0x800 ? 0 : dv_audio_12to16(rc)); of = sys->audio_shuffle[i%half_ch][j] + (d - 8) / 3 * sys->audio_stride; if (of*2 >= size) continue; pcm[of*2] = lc & 0xff; // FIXME: maybe we have to admit pcm[of*2+1] = lc >> 8; // that DV is a big-endian PCM of = sys->audio_shuffle[i%half_ch+half_ch][j] + (d - 8) / 3 * sys->audio_stride; pcm[of*2] = rc & 0xff; // FIXME: maybe we have to admit pcm[of*2+1] = rc >> 8; // that DV is a big-endian PCM ++d; } } frame += 16 * 80; /* 15 Video DIFs + 1 Audio DIF */ } } frame += 16 * 80; /* 15 Video DIFs + 1 Audio DIF */ }
165,242
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: DefragInOrderSimpleTest(void) { Packet *p1 = NULL, *p2 = NULL, *p3 = NULL; Packet *reassembled = NULL; int id = 12; int i; int ret = 0; DefragInit(); p1 = BuildTestPacket(id, 0, 1, 'A', 8); if (p1 == NULL) goto end; p2 = BuildTestPacket(id, 1, 1, 'B', 8); if (p2 == NULL) goto end; p3 = BuildTestPacket(id, 2, 0, 'C', 3); if (p3 == NULL) goto end; if (Defrag(NULL, NULL, p1, NULL) != NULL) goto end; if (Defrag(NULL, NULL, p2, NULL) != NULL) goto end; reassembled = Defrag(NULL, NULL, p3, NULL); if (reassembled == NULL) { goto end; } if (IPV4_GET_HLEN(reassembled) != 20) { goto end; } if (IPV4_GET_IPLEN(reassembled) != 39) { goto end; } /* 20 bytes in we should find 8 bytes of A. */ for (i = 20; i < 20 + 8; i++) { if (GET_PKT_DATA(reassembled)[i] != 'A') { goto end; } } /* 28 bytes in we should find 8 bytes of B. */ for (i = 28; i < 28 + 8; i++) { if (GET_PKT_DATA(reassembled)[i] != 'B') { goto end; } } /* And 36 bytes in we should find 3 bytes of C. */ for (i = 36; i < 36 + 3; i++) { if (GET_PKT_DATA(reassembled)[i] != 'C') goto end; } ret = 1; end: if (p1 != NULL) SCFree(p1); if (p2 != NULL) SCFree(p2); if (p3 != NULL) SCFree(p3); if (reassembled != NULL) SCFree(reassembled); DefragDestroy(); return ret; } Commit Message: defrag - take protocol into account during re-assembly The IP protocol was not being used to match fragments with their packets allowing a carefully constructed packet with a different protocol to be matched, allowing re-assembly to complete, creating a packet that would not be re-assembled by the destination host. CWE ID: CWE-358
DefragInOrderSimpleTest(void) { Packet *p1 = NULL, *p2 = NULL, *p3 = NULL; Packet *reassembled = NULL; int id = 12; int i; int ret = 0; DefragInit(); p1 = BuildTestPacket(IPPROTO_ICMP, id, 0, 1, 'A', 8); if (p1 == NULL) goto end; p2 = BuildTestPacket(IPPROTO_ICMP, id, 1, 1, 'B', 8); if (p2 == NULL) goto end; p3 = BuildTestPacket(IPPROTO_ICMP, id, 2, 0, 'C', 3); if (p3 == NULL) goto end; if (Defrag(NULL, NULL, p1, NULL) != NULL) goto end; if (Defrag(NULL, NULL, p2, NULL) != NULL) goto end; reassembled = Defrag(NULL, NULL, p3, NULL); if (reassembled == NULL) { goto end; } if (IPV4_GET_HLEN(reassembled) != 20) { goto end; } if (IPV4_GET_IPLEN(reassembled) != 39) { goto end; } /* 20 bytes in we should find 8 bytes of A. */ for (i = 20; i < 20 + 8; i++) { if (GET_PKT_DATA(reassembled)[i] != 'A') { goto end; } } /* 28 bytes in we should find 8 bytes of B. */ for (i = 28; i < 28 + 8; i++) { if (GET_PKT_DATA(reassembled)[i] != 'B') { goto end; } } /* And 36 bytes in we should find 3 bytes of C. */ for (i = 36; i < 36 + 3; i++) { if (GET_PKT_DATA(reassembled)[i] != 'C') goto end; } ret = 1; end: if (p1 != NULL) SCFree(p1); if (p2 != NULL) SCFree(p2); if (p3 != NULL) SCFree(p3); if (reassembled != NULL) SCFree(reassembled); DefragDestroy(); return ret; }
168,298
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void PageInfo::OnChangePasswordButtonPressed( content::WebContents* web_contents) { #if defined(FULL_SAFE_BROWSING) DCHECK(password_protection_service_); DCHECK(safe_browsing_status_ == SAFE_BROWSING_STATUS_SIGN_IN_PASSWORD_REUSE || safe_browsing_status_ == SAFE_BROWSING_STATUS_ENTERPRISE_PASSWORD_REUSE); password_protection_service_->OnUserAction( web_contents, safe_browsing_status_ == SAFE_BROWSING_STATUS_SIGN_IN_PASSWORD_REUSE ? PasswordReuseEvent::SIGN_IN_PASSWORD : PasswordReuseEvent::ENTERPRISE_PASSWORD, safe_browsing::WarningUIType::PAGE_INFO, safe_browsing::WarningAction::CHANGE_PASSWORD); #endif } Commit Message: Revert "PageInfo: decouple safe browsing and TLS statii." This reverts commit ee95bc44021230127c7e6e9a8cf9d3820760f77c. Reason for revert: suspect causing unit_tests failure on Linux MSAN Tests: https://ci.chromium.org/p/chromium/builders/ci/Linux%20MSan%20Tests/17649 PageInfoBubbleViewTest.ChangingFlashSettingForSiteIsRemembered PageInfoBubbleViewTest.EnsureCloseCallback PageInfoBubbleViewTest.NotificationPermissionRevokeUkm PageInfoBubbleViewTest.OpenPageInfoBubbleAfterNavigationStart PageInfoBubbleViewTest.SetPermissionInfo PageInfoBubbleViewTest.SetPermissionInfoForUsbGuard PageInfoBubbleViewTest.SetPermissionInfoWithPolicyUsbDevices PageInfoBubbleViewTest.SetPermissionInfoWithUsbDevice PageInfoBubbleViewTest.SetPermissionInfoWithUserAndPolicyUsbDevices PageInfoBubbleViewTest.UpdatingSiteDataRetainsLayout https://logs.chromium.org/logs/chromium/buildbucket/cr-buildbucket.appspot.com/8909718923797040064/+/steps/unit_tests/0/logs/Deterministic_failure:_PageInfoBubbleViewTest.ChangingFlashSettingForSiteIsRemembered__status_CRASH_/0 [ RUN ] PageInfoBubbleViewTest.ChangingFlashSettingForSiteIsRemembered ==9056==WARNING: MemorySanitizer: use-of-uninitialized-value #0 0x561baaab15ec in PageInfoUI::GetSecurityDescription(PageInfoUI::IdentityInfo const&) const ./../../chrome/browser/ui/page_info/page_info_ui.cc:250:3 #1 0x561bab6a1548 in PageInfoBubbleView::SetIdentityInfo(PageInfoUI::IdentityInfo const&) ./../../chrome/browser/ui/views/page_info/page_info_bubble_view.cc:802:7 #2 0x561baaaab3bb in PageInfo::PresentSiteIdentity() ./../../chrome/browser/ui/page_info/page_info.cc:969:8 #3 0x561baaaa0a21 in PageInfo::PageInfo(PageInfoUI*, Profile*, TabSpecificContentSettings*, content::WebContents*, GURL const&, security_state::SecurityLevel, security_state::VisibleSecurityState const&) ./../../chrome/browser/ui/page_info/page_info.cc:344:3 #4 0x561bab69b6dd in PageInfoBubbleView::PageInfoBubbleView(views::View*, gfx::Rect const&, aura::Window*, Profile*, content::WebContents*, GURL const&, security_state::SecurityLevel, security_state::VisibleSecurityState const&, base::OnceCallback<void (views::Widget::ClosedReason, bool)>) ./../../chrome/browser/ui/views/page_info/page_info_bubble_view.cc:576:24 ... Original change's description: > PageInfo: decouple safe browsing and TLS statii. > > Previously, the Page Info bubble maintained a single variable to > identify all reasons that a page might have a non-standard status. This > lead to the display logic making assumptions about, for instance, the > validity of a certificate when the page was flagged by Safe Browsing. > > This CL separates out the Safe Browsing status from the site identity > status so that the page info bubble can inform the user that the site's > certificate is invalid, even if it's also flagged by Safe Browsing. > > Bug: 869925 > Change-Id: I34107225b4206c8f32771ccd75e9367668d0a72b > Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1662537 > Reviewed-by: Mustafa Emre Acer <[email protected]> > Reviewed-by: Bret Sepulveda <[email protected]> > Auto-Submit: Joe DeBlasio <[email protected]> > Commit-Queue: Joe DeBlasio <[email protected]> > Cr-Commit-Position: refs/heads/master@{#671847} [email protected],[email protected],[email protected] Change-Id: I8be652952e7276bcc9266124693352e467159cc4 No-Presubmit: true No-Tree-Checks: true No-Try: true Bug: 869925 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1673985 Reviewed-by: Takashi Sakamoto <[email protected]> Commit-Queue: Takashi Sakamoto <[email protected]> Cr-Commit-Position: refs/heads/master@{#671932} CWE ID: CWE-311
void PageInfo::OnChangePasswordButtonPressed( content::WebContents* web_contents) { #if defined(FULL_SAFE_BROWSING) DCHECK(password_protection_service_); DCHECK(site_identity_status_ == SITE_IDENTITY_STATUS_SIGN_IN_PASSWORD_REUSE || site_identity_status_ == SITE_IDENTITY_STATUS_ENTERPRISE_PASSWORD_REUSE); password_protection_service_->OnUserAction( web_contents, site_identity_status_ == SITE_IDENTITY_STATUS_SIGN_IN_PASSWORD_REUSE ? PasswordReuseEvent::SIGN_IN_PASSWORD : PasswordReuseEvent::ENTERPRISE_PASSWORD, safe_browsing::WarningUIType::PAGE_INFO, safe_browsing::WarningAction::CHANGE_PASSWORD); #endif }
172,436
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void server_process_native_message( Server *s, const void *buffer, size_t buffer_size, struct ucred *ucred, struct timeval *tv, const char *label, size_t label_len) { struct iovec *iovec = NULL; unsigned n = 0, m = 0, j, tn = (unsigned) -1; const char *p; size_t remaining; int priority = LOG_INFO; char *identifier = NULL, *message = NULL; assert(s); assert(buffer || buffer_size == 0); p = buffer; remaining = buffer_size; while (remaining > 0) { const char *e, *q; e = memchr(p, '\n', remaining); if (!e) { /* Trailing noise, let's ignore it, and flush what we collected */ log_debug("Received message with trailing noise, ignoring."); break; } if (e == p) { /* Entry separator */ server_dispatch_message(s, iovec, n, m, ucred, tv, label, label_len, NULL, priority); n = 0; priority = LOG_INFO; p++; remaining--; continue; } if (*p == '.' || *p == '#') { /* Ignore control commands for now, and * comments too. */ remaining -= (e - p) + 1; p = e + 1; continue; } /* A property follows */ if (n+N_IOVEC_META_FIELDS >= m) { struct iovec *c; unsigned u; u = MAX((n+N_IOVEC_META_FIELDS+1) * 2U, 4U); c = realloc(iovec, u * sizeof(struct iovec)); if (!c) { log_oom(); break; } iovec = c; m = u; } q = memchr(p, '=', e - p); if (q) { if (valid_user_field(p, q - p)) { size_t l; l = e - p; /* If the field name starts with an * underscore, skip the variable, * since that indidates a trusted * field */ iovec[n].iov_base = (char*) p; iovec[n].iov_len = l; n++; /* We need to determine the priority * of this entry for the rate limiting * logic */ if (l == 10 && memcmp(p, "PRIORITY=", 9) == 0 && p[9] >= '0' && p[9] <= '9') priority = (priority & LOG_FACMASK) | (p[9] - '0'); else if (l == 17 && memcmp(p, "SYSLOG_FACILITY=", 16) == 0 && p[16] >= '0' && p[16] <= '9') priority = (priority & LOG_PRIMASK) | ((p[16] - '0') << 3); else if (l == 18 && memcmp(p, "SYSLOG_FACILITY=", 16) == 0 && p[16] >= '0' && p[16] <= '9' && p[17] >= '0' && p[17] <= '9') priority = (priority & LOG_PRIMASK) | (((p[16] - '0')*10 + (p[17] - '0')) << 3); else if (l >= 19 && memcmp(p, "SYSLOG_IDENTIFIER=", 18) == 0) { char *t; t = strndup(p + 18, l - 18); if (t) { free(identifier); identifier = t; } } else if (l >= 8 && memcmp(p, "MESSAGE=", 8) == 0) { char *t; t = strndup(p + 8, l - 8); if (t) { free(message); message = t; } } } remaining -= (e - p) + 1; p = e + 1; continue; } else { le64_t l_le; uint64_t l; char *k; if (remaining < e - p + 1 + sizeof(uint64_t) + 1) { log_debug("Failed to parse message, ignoring."); break; } memcpy(&l_le, e + 1, sizeof(uint64_t)); memcpy(&l_le, e + 1, sizeof(uint64_t)); l = le64toh(l_le); if (remaining < e - p + 1 + sizeof(uint64_t) + l + 1 || e[1+sizeof(uint64_t)+l] != '\n') { log_debug("Failed to parse message, ignoring."); break; } memcpy(k, p, e - p); k[e - p] = '='; memcpy(k + (e - p) + 1, e + 1 + sizeof(uint64_t), l); if (valid_user_field(p, e - p)) { iovec[n].iov_base = k; iovec[n].iov_len = (e - p) + 1 + l; n++; } else free(k); remaining -= (e - p) + 1 + sizeof(uint64_t) + l + 1; p = e + 1 + sizeof(uint64_t) + l + 1; } } if (n <= 0) goto finish; tn = n++; IOVEC_SET_STRING(iovec[tn], "_TRANSPORT=journal"); if (message) { if (s->forward_to_syslog) server_forward_syslog(s, priority, identifier, message, ucred, tv); if (s->forward_to_kmsg) server_forward_kmsg(s, priority, identifier, message, ucred); if (s->forward_to_console) server_forward_console(s, priority, identifier, message, ucred); } server_dispatch_message(s, iovec, n, m, ucred, tv, label, label_len, NULL, priority); finish: for (j = 0; j < n; j++) { if (j == tn) continue; if (iovec[j].iov_base < buffer || (const uint8_t*) iovec[j].iov_base >= (const uint8_t*) buffer + buffer_size) free(iovec[j].iov_base); } free(iovec); free(identifier); free(message); } Commit Message: CWE ID: CWE-189
void server_process_native_message( Server *s, const void *buffer, size_t buffer_size, struct ucred *ucred, struct timeval *tv, const char *label, size_t label_len) { struct iovec *iovec = NULL; unsigned n = 0, m = 0, j, tn = (unsigned) -1; const char *p; size_t remaining; int priority = LOG_INFO; char *identifier = NULL, *message = NULL; assert(s); assert(buffer || buffer_size == 0); p = buffer; remaining = buffer_size; while (remaining > 0) { const char *e, *q; e = memchr(p, '\n', remaining); if (!e) { /* Trailing noise, let's ignore it, and flush what we collected */ log_debug("Received message with trailing noise, ignoring."); break; } if (e == p) { /* Entry separator */ server_dispatch_message(s, iovec, n, m, ucred, tv, label, label_len, NULL, priority); n = 0; priority = LOG_INFO; p++; remaining--; continue; } if (*p == '.' || *p == '#') { /* Ignore control commands for now, and * comments too. */ remaining -= (e - p) + 1; p = e + 1; continue; } /* A property follows */ if (n+N_IOVEC_META_FIELDS >= m) { struct iovec *c; unsigned u; u = MAX((n+N_IOVEC_META_FIELDS+1) * 2U, 4U); c = realloc(iovec, u * sizeof(struct iovec)); if (!c) { log_oom(); break; } iovec = c; m = u; } q = memchr(p, '=', e - p); if (q) { if (valid_user_field(p, q - p)) { size_t l; l = e - p; /* If the field name starts with an * underscore, skip the variable, * since that indidates a trusted * field */ iovec[n].iov_base = (char*) p; iovec[n].iov_len = l; n++; /* We need to determine the priority * of this entry for the rate limiting * logic */ if (l == 10 && memcmp(p, "PRIORITY=", 9) == 0 && p[9] >= '0' && p[9] <= '9') priority = (priority & LOG_FACMASK) | (p[9] - '0'); else if (l == 17 && memcmp(p, "SYSLOG_FACILITY=", 16) == 0 && p[16] >= '0' && p[16] <= '9') priority = (priority & LOG_PRIMASK) | ((p[16] - '0') << 3); else if (l == 18 && memcmp(p, "SYSLOG_FACILITY=", 16) == 0 && p[16] >= '0' && p[16] <= '9' && p[17] >= '0' && p[17] <= '9') priority = (priority & LOG_PRIMASK) | (((p[16] - '0')*10 + (p[17] - '0')) << 3); else if (l >= 19 && memcmp(p, "SYSLOG_IDENTIFIER=", 18) == 0) { char *t; t = strndup(p + 18, l - 18); if (t) { free(identifier); identifier = t; } } else if (l >= 8 && memcmp(p, "MESSAGE=", 8) == 0) { char *t; t = strndup(p + 8, l - 8); if (t) { free(message); message = t; } } } remaining -= (e - p) + 1; p = e + 1; continue; } else { le64_t l_le; uint64_t l; char *k; if (remaining < e - p + 1 + sizeof(uint64_t) + 1) { log_debug("Failed to parse message, ignoring."); break; } memcpy(&l_le, e + 1, sizeof(uint64_t)); memcpy(&l_le, e + 1, sizeof(uint64_t)); l = le64toh(l_le); if (l > DATA_SIZE_MAX) { log_debug("Received binary data block too large, ignoring."); break; } if ((uint64_t) remaining < e - p + 1 + sizeof(uint64_t) + l + 1 || e[1+sizeof(uint64_t)+l] != '\n') { log_debug("Failed to parse message, ignoring."); break; } memcpy(k, p, e - p); k[e - p] = '='; memcpy(k + (e - p) + 1, e + 1 + sizeof(uint64_t), l); if (valid_user_field(p, e - p)) { iovec[n].iov_base = k; iovec[n].iov_len = (e - p) + 1 + l; n++; } else free(k); remaining -= (e - p) + 1 + sizeof(uint64_t) + l + 1; p = e + 1 + sizeof(uint64_t) + l + 1; } } if (n <= 0) goto finish; tn = n++; IOVEC_SET_STRING(iovec[tn], "_TRANSPORT=journal"); if (message) { if (s->forward_to_syslog) server_forward_syslog(s, priority, identifier, message, ucred, tv); if (s->forward_to_kmsg) server_forward_kmsg(s, priority, identifier, message, ucred); if (s->forward_to_console) server_forward_console(s, priority, identifier, message, ucred); } server_dispatch_message(s, iovec, n, m, ucred, tv, label, label_len, NULL, priority); finish: for (j = 0; j < n; j++) { if (j == tn) continue; if (iovec[j].iov_base < buffer || (const uint8_t*) iovec[j].iov_base >= (const uint8_t*) buffer + buffer_size) free(iovec[j].iov_base); } free(iovec); free(identifier); free(message); }
164,658
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static v8::Handle<v8::Value> convert3Callback(const v8::Arguments& args) { INC_STATS("DOM.TestObj.convert3"); if (args.Length() < 1) return V8Proxy::throwNotEnoughArgumentsError(); TestObj* imp = V8TestObj::toNative(args.Holder()); EXCEPTION_BLOCK(c*, , V8c::HasInstance(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)) ? V8c::toNative(v8::Handle<v8::Object>::Cast(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))) : 0); imp->convert3(); return v8::Handle<v8::Value>(); } Commit Message: [V8] Pass Isolate to throwNotEnoughArgumentsError() https://bugs.webkit.org/show_bug.cgi?id=86983 Reviewed by Adam Barth. The objective is to pass Isolate around in V8 bindings. This patch passes Isolate to throwNotEnoughArgumentsError(). No tests. No change in behavior. * bindings/scripts/CodeGeneratorV8.pm: (GenerateArgumentsCountCheck): (GenerateEventConstructorCallback): * bindings/scripts/test/V8/V8Float64Array.cpp: (WebCore::Float64ArrayV8Internal::fooCallback): * bindings/scripts/test/V8/V8TestActiveDOMObject.cpp: (WebCore::TestActiveDOMObjectV8Internal::excitingFunctionCallback): (WebCore::TestActiveDOMObjectV8Internal::postMessageCallback): * bindings/scripts/test/V8/V8TestCustomNamedGetter.cpp: (WebCore::TestCustomNamedGetterV8Internal::anotherFunctionCallback): * bindings/scripts/test/V8/V8TestEventConstructor.cpp: (WebCore::V8TestEventConstructor::constructorCallback): * bindings/scripts/test/V8/V8TestEventTarget.cpp: (WebCore::TestEventTargetV8Internal::itemCallback): (WebCore::TestEventTargetV8Internal::dispatchEventCallback): * bindings/scripts/test/V8/V8TestInterface.cpp: (WebCore::TestInterfaceV8Internal::supplementalMethod2Callback): (WebCore::V8TestInterface::constructorCallback): * bindings/scripts/test/V8/V8TestMediaQueryListListener.cpp: (WebCore::TestMediaQueryListListenerV8Internal::methodCallback): * bindings/scripts/test/V8/V8TestNamedConstructor.cpp: (WebCore::V8TestNamedConstructorConstructorCallback): * bindings/scripts/test/V8/V8TestObj.cpp: (WebCore::TestObjV8Internal::voidMethodWithArgsCallback): (WebCore::TestObjV8Internal::intMethodWithArgsCallback): (WebCore::TestObjV8Internal::objMethodWithArgsCallback): (WebCore::TestObjV8Internal::methodWithSequenceArgCallback): (WebCore::TestObjV8Internal::methodReturningSequenceCallback): (WebCore::TestObjV8Internal::methodThatRequiresAllArgsAndThrowsCallback): (WebCore::TestObjV8Internal::serializedValueCallback): (WebCore::TestObjV8Internal::idbKeyCallback): (WebCore::TestObjV8Internal::optionsObjectCallback): (WebCore::TestObjV8Internal::methodWithNonOptionalArgAndOptionalArgCallback): (WebCore::TestObjV8Internal::methodWithNonOptionalArgAndTwoOptionalArgsCallback): (WebCore::TestObjV8Internal::methodWithCallbackArgCallback): (WebCore::TestObjV8Internal::methodWithNonCallbackArgAndCallbackArgCallback): (WebCore::TestObjV8Internal::overloadedMethod1Callback): (WebCore::TestObjV8Internal::overloadedMethod2Callback): (WebCore::TestObjV8Internal::overloadedMethod3Callback): (WebCore::TestObjV8Internal::overloadedMethod4Callback): (WebCore::TestObjV8Internal::overloadedMethod5Callback): (WebCore::TestObjV8Internal::overloadedMethod6Callback): (WebCore::TestObjV8Internal::overloadedMethod7Callback): (WebCore::TestObjV8Internal::overloadedMethod11Callback): (WebCore::TestObjV8Internal::overloadedMethod12Callback): (WebCore::TestObjV8Internal::enabledAtRuntimeMethod1Callback): (WebCore::TestObjV8Internal::enabledAtRuntimeMethod2Callback): (WebCore::TestObjV8Internal::convert1Callback): (WebCore::TestObjV8Internal::convert2Callback): (WebCore::TestObjV8Internal::convert3Callback): (WebCore::TestObjV8Internal::convert4Callback): (WebCore::TestObjV8Internal::convert5Callback): (WebCore::TestObjV8Internal::strictFunctionCallback): (WebCore::V8TestObj::constructorCallback): * bindings/scripts/test/V8/V8TestSerializedScriptValueInterface.cpp: (WebCore::TestSerializedScriptValueInterfaceV8Internal::acceptTransferListCallback): (WebCore::V8TestSerializedScriptValueInterface::constructorCallback): * bindings/v8/ScriptController.cpp: (WebCore::setValueAndClosePopupCallback): * bindings/v8/V8Proxy.cpp: (WebCore::V8Proxy::throwNotEnoughArgumentsError): * bindings/v8/V8Proxy.h: (V8Proxy): * bindings/v8/custom/V8AudioContextCustom.cpp: (WebCore::V8AudioContext::constructorCallback): * bindings/v8/custom/V8DataViewCustom.cpp: (WebCore::V8DataView::getInt8Callback): (WebCore::V8DataView::getUint8Callback): (WebCore::V8DataView::setInt8Callback): (WebCore::V8DataView::setUint8Callback): * bindings/v8/custom/V8DirectoryEntryCustom.cpp: (WebCore::V8DirectoryEntry::getDirectoryCallback): (WebCore::V8DirectoryEntry::getFileCallback): * bindings/v8/custom/V8IntentConstructor.cpp: (WebCore::V8Intent::constructorCallback): * bindings/v8/custom/V8SVGLengthCustom.cpp: (WebCore::V8SVGLength::convertToSpecifiedUnitsCallback): * bindings/v8/custom/V8WebGLRenderingContextCustom.cpp: (WebCore::getObjectParameter): (WebCore::V8WebGLRenderingContext::getAttachedShadersCallback): (WebCore::V8WebGLRenderingContext::getExtensionCallback): (WebCore::V8WebGLRenderingContext::getFramebufferAttachmentParameterCallback): (WebCore::V8WebGLRenderingContext::getParameterCallback): (WebCore::V8WebGLRenderingContext::getProgramParameterCallback): (WebCore::V8WebGLRenderingContext::getShaderParameterCallback): (WebCore::V8WebGLRenderingContext::getUniformCallback): (WebCore::vertexAttribAndUniformHelperf): (WebCore::uniformHelperi): (WebCore::uniformMatrixHelper): * bindings/v8/custom/V8WebKitMutationObserverCustom.cpp: (WebCore::V8WebKitMutationObserver::constructorCallback): (WebCore::V8WebKitMutationObserver::observeCallback): * bindings/v8/custom/V8WebSocketCustom.cpp: (WebCore::V8WebSocket::constructorCallback): (WebCore::V8WebSocket::sendCallback): * bindings/v8/custom/V8XMLHttpRequestCustom.cpp: (WebCore::V8XMLHttpRequest::openCallback): git-svn-id: svn://svn.chromium.org/blink/trunk@117736 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID:
static v8::Handle<v8::Value> convert3Callback(const v8::Arguments& args) { INC_STATS("DOM.TestObj.convert3"); if (args.Length() < 1) return V8Proxy::throwNotEnoughArgumentsError(args.GetIsolate()); TestObj* imp = V8TestObj::toNative(args.Holder()); EXCEPTION_BLOCK(c*, , V8c::HasInstance(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)) ? V8c::toNative(v8::Handle<v8::Object>::Cast(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))) : 0); imp->convert3(); return v8::Handle<v8::Value>(); }
171,079
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: std::string print_valuetype(Value::ValueType e) { switch (e) { case Value::TYPE_NULL: return "NULL "; case Value::TYPE_BOOLEAN: return "BOOL"; case Value::TYPE_INTEGER: return "INT"; case Value::TYPE_DOUBLE: return "DOUBLE"; case Value::TYPE_STRING: return "STRING"; case Value::TYPE_BINARY: return "BIN"; case Value::TYPE_DICTIONARY: return "DICT"; case Value::TYPE_LIST: return "LIST"; default: return "ERROR"; } } Commit Message: In chromedriver, add /log url to get the contents of the chromedriver log remotely. Also add a 'chrome.verbose' boolean startup option. Remove usage of VLOG(1) in chromedriver. We do not need as complicated logging as in Chrome. BUG=85241 TEST=none Review URL: http://codereview.chromium.org/7104085 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@88591 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
std::string print_valuetype(Value::ValueType e) {
170,467
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool CmapCoverage::getCoverage(SparseBitSet& coverage, const uint8_t* cmap_data, size_t cmap_size) { vector<uint32_t> coverageVec; const size_t kHeaderSize = 4; const size_t kNumTablesOffset = 2; const size_t kTableSize = 8; const size_t kPlatformIdOffset = 0; const size_t kEncodingIdOffset = 2; const size_t kOffsetOffset = 4; const int kMicrosoftPlatformId = 3; const int kUnicodeBmpEncodingId = 1; const int kUnicodeUcs4EncodingId = 10; if (kHeaderSize > cmap_size) { return false; } int numTables = readU16(cmap_data, kNumTablesOffset); if (kHeaderSize + numTables * kTableSize > cmap_size) { return false; } int bestTable = -1; for (int i = 0; i < numTables; i++) { uint16_t platformId = readU16(cmap_data, kHeaderSize + i * kTableSize + kPlatformIdOffset); uint16_t encodingId = readU16(cmap_data, kHeaderSize + i * kTableSize + kEncodingIdOffset); if (platformId == kMicrosoftPlatformId && encodingId == kUnicodeUcs4EncodingId) { bestTable = i; break; } else if (platformId == kMicrosoftPlatformId && encodingId == kUnicodeBmpEncodingId) { bestTable = i; } } #ifdef PRINTF_DEBUG printf("best table = %d\n", bestTable); #endif if (bestTable < 0) { return false; } uint32_t offset = readU32(cmap_data, kHeaderSize + bestTable * kTableSize + kOffsetOffset); if (offset + 2 > cmap_size) { return false; } uint16_t format = readU16(cmap_data, offset); bool success = false; const uint8_t* tableData = cmap_data + offset; const size_t tableSize = cmap_size - offset; if (format == 4) { success = getCoverageFormat4(coverageVec, tableData, tableSize); } else if (format == 12) { success = getCoverageFormat12(coverageVec, tableData, tableSize); } if (success) { coverage.initFromRanges(&coverageVec.front(), coverageVec.size() >> 1); } #ifdef PRINTF_DEBUG for (int i = 0; i < coverageVec.size(); i += 2) { printf("%x:%x\n", coverageVec[i], coverageVec[i + 1]); } #endif return success; } Commit Message: Reject fonts with invalid ranges in cmap A corrupt or malicious font may have a negative size in its cmap range, which in turn could lead to memory corruption. This patch detects the case and rejects the font, and also includes an assertion in the sparse bit set implementation if we missed any such case. External issue: https://code.google.com/p/android/issues/detail?id=192618 Bug: 26413177 Change-Id: Icc0c80e4ef389abba0964495b89aa0fae3e9f4b2 CWE ID: CWE-20
bool CmapCoverage::getCoverage(SparseBitSet& coverage, const uint8_t* cmap_data, size_t cmap_size) { vector<uint32_t> coverageVec; const size_t kHeaderSize = 4; const size_t kNumTablesOffset = 2; const size_t kTableSize = 8; const size_t kPlatformIdOffset = 0; const size_t kEncodingIdOffset = 2; const size_t kOffsetOffset = 4; const uint16_t kMicrosoftPlatformId = 3; const uint16_t kUnicodeBmpEncodingId = 1; const uint16_t kUnicodeUcs4EncodingId = 10; const uint32_t kNoTable = UINT32_MAX; if (kHeaderSize > cmap_size) { return false; } uint32_t numTables = readU16(cmap_data, kNumTablesOffset); if (kHeaderSize + numTables * kTableSize > cmap_size) { return false; } uint32_t bestTable = kNoTable; for (uint32_t i = 0; i < numTables; i++) { uint16_t platformId = readU16(cmap_data, kHeaderSize + i * kTableSize + kPlatformIdOffset); uint16_t encodingId = readU16(cmap_data, kHeaderSize + i * kTableSize + kEncodingIdOffset); if (platformId == kMicrosoftPlatformId && encodingId == kUnicodeUcs4EncodingId) { bestTable = i; break; } else if (platformId == kMicrosoftPlatformId && encodingId == kUnicodeBmpEncodingId) { bestTable = i; } } #ifdef PRINTF_DEBUG printf("best table = %d\n", bestTable); #endif if (bestTable == kNoTable) { return false; } uint32_t offset = readU32(cmap_data, kHeaderSize + bestTable * kTableSize + kOffsetOffset); if (offset > cmap_size - 2) { return false; } uint16_t format = readU16(cmap_data, offset); bool success = false; const uint8_t* tableData = cmap_data + offset; const size_t tableSize = cmap_size - offset; if (format == 4) { success = getCoverageFormat4(coverageVec, tableData, tableSize); } else if (format == 12) { success = getCoverageFormat12(coverageVec, tableData, tableSize); } if (success) { coverage.initFromRanges(&coverageVec.front(), coverageVec.size() >> 1); } #ifdef PRINTF_DEBUG for (int i = 0; i < coverageVec.size(); i += 2) { printf("%x:%x\n", coverageVec[i], coverageVec[i + 1]); } #endif return success; }
174,233
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int cop1Emulate(struct pt_regs *xcp, struct mips_fpu_struct *ctx, void *__user *fault_addr) { mips_instruction ir; unsigned long emulpc, contpc; unsigned int cond; if (!access_ok(VERIFY_READ, xcp->cp0_epc, sizeof(mips_instruction))) { MIPS_FPU_EMU_INC_STATS(errors); *fault_addr = (mips_instruction __user *)xcp->cp0_epc; return SIGBUS; } if (__get_user(ir, (mips_instruction __user *) xcp->cp0_epc)) { MIPS_FPU_EMU_INC_STATS(errors); *fault_addr = (mips_instruction __user *)xcp->cp0_epc; return SIGSEGV; } /* XXX NEC Vr54xx bug workaround */ if ((xcp->cp0_cause & CAUSEF_BD) && !isBranchInstr(&ir)) xcp->cp0_cause &= ~CAUSEF_BD; if (xcp->cp0_cause & CAUSEF_BD) { /* * The instruction to be emulated is in a branch delay slot * which means that we have to emulate the branch instruction * BEFORE we do the cop1 instruction. * * This branch could be a COP1 branch, but in that case we * would have had a trap for that instruction, and would not * come through this route. * * Linux MIPS branch emulator operates on context, updating the * cp0_epc. */ emulpc = xcp->cp0_epc + 4; /* Snapshot emulation target */ if (__compute_return_epc(xcp)) { #ifdef CP1DBG printk("failed to emulate branch at %p\n", (void *) (xcp->cp0_epc)); #endif return SIGILL; } if (!access_ok(VERIFY_READ, emulpc, sizeof(mips_instruction))) { MIPS_FPU_EMU_INC_STATS(errors); *fault_addr = (mips_instruction __user *)emulpc; return SIGBUS; } if (__get_user(ir, (mips_instruction __user *) emulpc)) { MIPS_FPU_EMU_INC_STATS(errors); *fault_addr = (mips_instruction __user *)emulpc; return SIGSEGV; } /* __compute_return_epc() will have updated cp0_epc */ contpc = xcp->cp0_epc; /* In order not to confuse ptrace() et al, tweak context */ xcp->cp0_epc = emulpc - 4; } else { emulpc = xcp->cp0_epc; contpc = xcp->cp0_epc + 4; } emul: perf_sw_event(PERF_COUNT_SW_EMULATION_FAULTS, 1, 0, xcp, 0); MIPS_FPU_EMU_INC_STATS(emulated); switch (MIPSInst_OPCODE(ir)) { case ldc1_op:{ u64 __user *va = (u64 __user *) (xcp->regs[MIPSInst_RS(ir)] + MIPSInst_SIMM(ir)); u64 val; MIPS_FPU_EMU_INC_STATS(loads); if (!access_ok(VERIFY_READ, va, sizeof(u64))) { MIPS_FPU_EMU_INC_STATS(errors); *fault_addr = va; return SIGBUS; } if (__get_user(val, va)) { MIPS_FPU_EMU_INC_STATS(errors); *fault_addr = va; return SIGSEGV; } DITOREG(val, MIPSInst_RT(ir)); break; } case sdc1_op:{ u64 __user *va = (u64 __user *) (xcp->regs[MIPSInst_RS(ir)] + MIPSInst_SIMM(ir)); u64 val; MIPS_FPU_EMU_INC_STATS(stores); DIFROMREG(val, MIPSInst_RT(ir)); if (!access_ok(VERIFY_WRITE, va, sizeof(u64))) { MIPS_FPU_EMU_INC_STATS(errors); *fault_addr = va; return SIGBUS; } if (__put_user(val, va)) { MIPS_FPU_EMU_INC_STATS(errors); *fault_addr = va; return SIGSEGV; } break; } case lwc1_op:{ u32 __user *va = (u32 __user *) (xcp->regs[MIPSInst_RS(ir)] + MIPSInst_SIMM(ir)); u32 val; MIPS_FPU_EMU_INC_STATS(loads); if (!access_ok(VERIFY_READ, va, sizeof(u32))) { MIPS_FPU_EMU_INC_STATS(errors); *fault_addr = va; return SIGBUS; } if (__get_user(val, va)) { MIPS_FPU_EMU_INC_STATS(errors); *fault_addr = va; return SIGSEGV; } SITOREG(val, MIPSInst_RT(ir)); break; } case swc1_op:{ u32 __user *va = (u32 __user *) (xcp->regs[MIPSInst_RS(ir)] + MIPSInst_SIMM(ir)); u32 val; MIPS_FPU_EMU_INC_STATS(stores); SIFROMREG(val, MIPSInst_RT(ir)); if (!access_ok(VERIFY_WRITE, va, sizeof(u32))) { MIPS_FPU_EMU_INC_STATS(errors); *fault_addr = va; return SIGBUS; } if (__put_user(val, va)) { MIPS_FPU_EMU_INC_STATS(errors); *fault_addr = va; return SIGSEGV; } break; } case cop1_op: switch (MIPSInst_RS(ir)) { #if defined(__mips64) case dmfc_op: /* copregister fs -> gpr[rt] */ if (MIPSInst_RT(ir) != 0) { DIFROMREG(xcp->regs[MIPSInst_RT(ir)], MIPSInst_RD(ir)); } break; case dmtc_op: /* copregister fs <- rt */ DITOREG(xcp->regs[MIPSInst_RT(ir)], MIPSInst_RD(ir)); break; #endif case mfc_op: /* copregister rd -> gpr[rt] */ if (MIPSInst_RT(ir) != 0) { SIFROMREG(xcp->regs[MIPSInst_RT(ir)], MIPSInst_RD(ir)); } break; case mtc_op: /* copregister rd <- rt */ SITOREG(xcp->regs[MIPSInst_RT(ir)], MIPSInst_RD(ir)); break; case cfc_op:{ /* cop control register rd -> gpr[rt] */ u32 value; if (MIPSInst_RD(ir) == FPCREG_CSR) { value = ctx->fcr31; value = (value & ~FPU_CSR_RM) | mips_rm[modeindex(value)]; #ifdef CSRTRACE printk("%p gpr[%d]<-csr=%08x\n", (void *) (xcp->cp0_epc), MIPSInst_RT(ir), value); #endif } else if (MIPSInst_RD(ir) == FPCREG_RID) value = 0; else value = 0; if (MIPSInst_RT(ir)) xcp->regs[MIPSInst_RT(ir)] = value; break; } case ctc_op:{ /* copregister rd <- rt */ u32 value; if (MIPSInst_RT(ir) == 0) value = 0; else value = xcp->regs[MIPSInst_RT(ir)]; /* we only have one writable control reg */ if (MIPSInst_RD(ir) == FPCREG_CSR) { #ifdef CSRTRACE printk("%p gpr[%d]->csr=%08x\n", (void *) (xcp->cp0_epc), MIPSInst_RT(ir), value); #endif /* * Don't write reserved bits, * and convert to ieee library modes */ ctx->fcr31 = (value & ~(FPU_CSR_RSVD | FPU_CSR_RM)) | ieee_rm[modeindex(value)]; } if ((ctx->fcr31 >> 5) & ctx->fcr31 & FPU_CSR_ALL_E) { return SIGFPE; } break; } case bc_op:{ int likely = 0; if (xcp->cp0_cause & CAUSEF_BD) return SIGILL; #if __mips >= 4 cond = ctx->fcr31 & fpucondbit[MIPSInst_RT(ir) >> 2]; #else cond = ctx->fcr31 & FPU_CSR_COND; #endif switch (MIPSInst_RT(ir) & 3) { case bcfl_op: likely = 1; case bcf_op: cond = !cond; break; case bctl_op: likely = 1; case bct_op: break; default: /* thats an illegal instruction */ return SIGILL; } xcp->cp0_cause |= CAUSEF_BD; if (cond) { /* branch taken: emulate dslot * instruction */ xcp->cp0_epc += 4; contpc = (xcp->cp0_epc + (MIPSInst_SIMM(ir) << 2)); if (!access_ok(VERIFY_READ, xcp->cp0_epc, sizeof(mips_instruction))) { MIPS_FPU_EMU_INC_STATS(errors); *fault_addr = (mips_instruction __user *)xcp->cp0_epc; return SIGBUS; } if (__get_user(ir, (mips_instruction __user *) xcp->cp0_epc)) { MIPS_FPU_EMU_INC_STATS(errors); *fault_addr = (mips_instruction __user *)xcp->cp0_epc; return SIGSEGV; } switch (MIPSInst_OPCODE(ir)) { case lwc1_op: case swc1_op: #if (__mips >= 2 || defined(__mips64)) case ldc1_op: case sdc1_op: #endif case cop1_op: #if __mips >= 4 && __mips != 32 case cop1x_op: #endif /* its one of ours */ goto emul; #if __mips >= 4 case spec_op: if (MIPSInst_FUNC(ir) == movc_op) goto emul; break; #endif } /* * Single step the non-cp1 * instruction in the dslot */ return mips_dsemul(xcp, ir, contpc); } else { /* branch not taken */ if (likely) { /* * branch likely nullifies * dslot if not taken */ xcp->cp0_epc += 4; contpc += 4; /* * else continue & execute * dslot as normal insn */ } } break; } default: if (!(MIPSInst_RS(ir) & 0x10)) return SIGILL; { int sig; /* a real fpu computation instruction */ if ((sig = fpu_emu(xcp, ctx, ir))) return sig; } } break; #if __mips >= 4 && __mips != 32 case cop1x_op:{ int sig = fpux_emu(xcp, ctx, ir, fault_addr); if (sig) return sig; break; } #endif #if __mips >= 4 case spec_op: if (MIPSInst_FUNC(ir) != movc_op) return SIGILL; cond = fpucondbit[MIPSInst_RT(ir) >> 2]; if (((ctx->fcr31 & cond) != 0) == ((MIPSInst_RT(ir) & 1) != 0)) xcp->regs[MIPSInst_RD(ir)] = xcp->regs[MIPSInst_RS(ir)]; break; #endif default: return SIGILL; } /* we did it !! */ xcp->cp0_epc = contpc; xcp->cp0_cause &= ~CAUSEF_BD; return 0; } Commit Message: perf: Remove the nmi parameter from the swevent and overflow interface The nmi parameter indicated if we could do wakeups from the current context, if not, we would set some state and self-IPI and let the resulting interrupt do the wakeup. For the various event classes: - hardware: nmi=0; PMI is in fact an NMI or we run irq_work_run from the PMI-tail (ARM etc.) - tracepoint: nmi=0; since tracepoint could be from NMI context. - software: nmi=[0,1]; some, like the schedule thing cannot perform wakeups, and hence need 0. As one can see, there is very little nmi=1 usage, and the down-side of not using it is that on some platforms some software events can have a jiffy delay in wakeup (when arch_irq_work_raise isn't implemented). The up-side however is that we can remove the nmi parameter and save a bunch of conditionals in fast paths. Signed-off-by: Peter Zijlstra <[email protected]> Cc: Michael Cree <[email protected]> Cc: Will Deacon <[email protected]> Cc: Deng-Cheng Zhu <[email protected]> Cc: Anton Blanchard <[email protected]> Cc: Eric B Munson <[email protected]> Cc: Heiko Carstens <[email protected]> Cc: Paul Mundt <[email protected]> Cc: David S. Miller <[email protected]> Cc: Frederic Weisbecker <[email protected]> Cc: Jason Wessel <[email protected]> Cc: Don Zickus <[email protected]> Link: http://lkml.kernel.org/n/[email protected] Signed-off-by: Ingo Molnar <[email protected]> CWE ID: CWE-399
static int cop1Emulate(struct pt_regs *xcp, struct mips_fpu_struct *ctx, void *__user *fault_addr) { mips_instruction ir; unsigned long emulpc, contpc; unsigned int cond; if (!access_ok(VERIFY_READ, xcp->cp0_epc, sizeof(mips_instruction))) { MIPS_FPU_EMU_INC_STATS(errors); *fault_addr = (mips_instruction __user *)xcp->cp0_epc; return SIGBUS; } if (__get_user(ir, (mips_instruction __user *) xcp->cp0_epc)) { MIPS_FPU_EMU_INC_STATS(errors); *fault_addr = (mips_instruction __user *)xcp->cp0_epc; return SIGSEGV; } /* XXX NEC Vr54xx bug workaround */ if ((xcp->cp0_cause & CAUSEF_BD) && !isBranchInstr(&ir)) xcp->cp0_cause &= ~CAUSEF_BD; if (xcp->cp0_cause & CAUSEF_BD) { /* * The instruction to be emulated is in a branch delay slot * which means that we have to emulate the branch instruction * BEFORE we do the cop1 instruction. * * This branch could be a COP1 branch, but in that case we * would have had a trap for that instruction, and would not * come through this route. * * Linux MIPS branch emulator operates on context, updating the * cp0_epc. */ emulpc = xcp->cp0_epc + 4; /* Snapshot emulation target */ if (__compute_return_epc(xcp)) { #ifdef CP1DBG printk("failed to emulate branch at %p\n", (void *) (xcp->cp0_epc)); #endif return SIGILL; } if (!access_ok(VERIFY_READ, emulpc, sizeof(mips_instruction))) { MIPS_FPU_EMU_INC_STATS(errors); *fault_addr = (mips_instruction __user *)emulpc; return SIGBUS; } if (__get_user(ir, (mips_instruction __user *) emulpc)) { MIPS_FPU_EMU_INC_STATS(errors); *fault_addr = (mips_instruction __user *)emulpc; return SIGSEGV; } /* __compute_return_epc() will have updated cp0_epc */ contpc = xcp->cp0_epc; /* In order not to confuse ptrace() et al, tweak context */ xcp->cp0_epc = emulpc - 4; } else { emulpc = xcp->cp0_epc; contpc = xcp->cp0_epc + 4; } emul: perf_sw_event(PERF_COUNT_SW_EMULATION_FAULTS, 1, xcp, 0); MIPS_FPU_EMU_INC_STATS(emulated); switch (MIPSInst_OPCODE(ir)) { case ldc1_op:{ u64 __user *va = (u64 __user *) (xcp->regs[MIPSInst_RS(ir)] + MIPSInst_SIMM(ir)); u64 val; MIPS_FPU_EMU_INC_STATS(loads); if (!access_ok(VERIFY_READ, va, sizeof(u64))) { MIPS_FPU_EMU_INC_STATS(errors); *fault_addr = va; return SIGBUS; } if (__get_user(val, va)) { MIPS_FPU_EMU_INC_STATS(errors); *fault_addr = va; return SIGSEGV; } DITOREG(val, MIPSInst_RT(ir)); break; } case sdc1_op:{ u64 __user *va = (u64 __user *) (xcp->regs[MIPSInst_RS(ir)] + MIPSInst_SIMM(ir)); u64 val; MIPS_FPU_EMU_INC_STATS(stores); DIFROMREG(val, MIPSInst_RT(ir)); if (!access_ok(VERIFY_WRITE, va, sizeof(u64))) { MIPS_FPU_EMU_INC_STATS(errors); *fault_addr = va; return SIGBUS; } if (__put_user(val, va)) { MIPS_FPU_EMU_INC_STATS(errors); *fault_addr = va; return SIGSEGV; } break; } case lwc1_op:{ u32 __user *va = (u32 __user *) (xcp->regs[MIPSInst_RS(ir)] + MIPSInst_SIMM(ir)); u32 val; MIPS_FPU_EMU_INC_STATS(loads); if (!access_ok(VERIFY_READ, va, sizeof(u32))) { MIPS_FPU_EMU_INC_STATS(errors); *fault_addr = va; return SIGBUS; } if (__get_user(val, va)) { MIPS_FPU_EMU_INC_STATS(errors); *fault_addr = va; return SIGSEGV; } SITOREG(val, MIPSInst_RT(ir)); break; } case swc1_op:{ u32 __user *va = (u32 __user *) (xcp->regs[MIPSInst_RS(ir)] + MIPSInst_SIMM(ir)); u32 val; MIPS_FPU_EMU_INC_STATS(stores); SIFROMREG(val, MIPSInst_RT(ir)); if (!access_ok(VERIFY_WRITE, va, sizeof(u32))) { MIPS_FPU_EMU_INC_STATS(errors); *fault_addr = va; return SIGBUS; } if (__put_user(val, va)) { MIPS_FPU_EMU_INC_STATS(errors); *fault_addr = va; return SIGSEGV; } break; } case cop1_op: switch (MIPSInst_RS(ir)) { #if defined(__mips64) case dmfc_op: /* copregister fs -> gpr[rt] */ if (MIPSInst_RT(ir) != 0) { DIFROMREG(xcp->regs[MIPSInst_RT(ir)], MIPSInst_RD(ir)); } break; case dmtc_op: /* copregister fs <- rt */ DITOREG(xcp->regs[MIPSInst_RT(ir)], MIPSInst_RD(ir)); break; #endif case mfc_op: /* copregister rd -> gpr[rt] */ if (MIPSInst_RT(ir) != 0) { SIFROMREG(xcp->regs[MIPSInst_RT(ir)], MIPSInst_RD(ir)); } break; case mtc_op: /* copregister rd <- rt */ SITOREG(xcp->regs[MIPSInst_RT(ir)], MIPSInst_RD(ir)); break; case cfc_op:{ /* cop control register rd -> gpr[rt] */ u32 value; if (MIPSInst_RD(ir) == FPCREG_CSR) { value = ctx->fcr31; value = (value & ~FPU_CSR_RM) | mips_rm[modeindex(value)]; #ifdef CSRTRACE printk("%p gpr[%d]<-csr=%08x\n", (void *) (xcp->cp0_epc), MIPSInst_RT(ir), value); #endif } else if (MIPSInst_RD(ir) == FPCREG_RID) value = 0; else value = 0; if (MIPSInst_RT(ir)) xcp->regs[MIPSInst_RT(ir)] = value; break; } case ctc_op:{ /* copregister rd <- rt */ u32 value; if (MIPSInst_RT(ir) == 0) value = 0; else value = xcp->regs[MIPSInst_RT(ir)]; /* we only have one writable control reg */ if (MIPSInst_RD(ir) == FPCREG_CSR) { #ifdef CSRTRACE printk("%p gpr[%d]->csr=%08x\n", (void *) (xcp->cp0_epc), MIPSInst_RT(ir), value); #endif /* * Don't write reserved bits, * and convert to ieee library modes */ ctx->fcr31 = (value & ~(FPU_CSR_RSVD | FPU_CSR_RM)) | ieee_rm[modeindex(value)]; } if ((ctx->fcr31 >> 5) & ctx->fcr31 & FPU_CSR_ALL_E) { return SIGFPE; } break; } case bc_op:{ int likely = 0; if (xcp->cp0_cause & CAUSEF_BD) return SIGILL; #if __mips >= 4 cond = ctx->fcr31 & fpucondbit[MIPSInst_RT(ir) >> 2]; #else cond = ctx->fcr31 & FPU_CSR_COND; #endif switch (MIPSInst_RT(ir) & 3) { case bcfl_op: likely = 1; case bcf_op: cond = !cond; break; case bctl_op: likely = 1; case bct_op: break; default: /* thats an illegal instruction */ return SIGILL; } xcp->cp0_cause |= CAUSEF_BD; if (cond) { /* branch taken: emulate dslot * instruction */ xcp->cp0_epc += 4; contpc = (xcp->cp0_epc + (MIPSInst_SIMM(ir) << 2)); if (!access_ok(VERIFY_READ, xcp->cp0_epc, sizeof(mips_instruction))) { MIPS_FPU_EMU_INC_STATS(errors); *fault_addr = (mips_instruction __user *)xcp->cp0_epc; return SIGBUS; } if (__get_user(ir, (mips_instruction __user *) xcp->cp0_epc)) { MIPS_FPU_EMU_INC_STATS(errors); *fault_addr = (mips_instruction __user *)xcp->cp0_epc; return SIGSEGV; } switch (MIPSInst_OPCODE(ir)) { case lwc1_op: case swc1_op: #if (__mips >= 2 || defined(__mips64)) case ldc1_op: case sdc1_op: #endif case cop1_op: #if __mips >= 4 && __mips != 32 case cop1x_op: #endif /* its one of ours */ goto emul; #if __mips >= 4 case spec_op: if (MIPSInst_FUNC(ir) == movc_op) goto emul; break; #endif } /* * Single step the non-cp1 * instruction in the dslot */ return mips_dsemul(xcp, ir, contpc); } else { /* branch not taken */ if (likely) { /* * branch likely nullifies * dslot if not taken */ xcp->cp0_epc += 4; contpc += 4; /* * else continue & execute * dslot as normal insn */ } } break; } default: if (!(MIPSInst_RS(ir) & 0x10)) return SIGILL; { int sig; /* a real fpu computation instruction */ if ((sig = fpu_emu(xcp, ctx, ir))) return sig; } } break; #if __mips >= 4 && __mips != 32 case cop1x_op:{ int sig = fpux_emu(xcp, ctx, ir, fault_addr); if (sig) return sig; break; } #endif #if __mips >= 4 case spec_op: if (MIPSInst_FUNC(ir) != movc_op) return SIGILL; cond = fpucondbit[MIPSInst_RT(ir) >> 2]; if (((ctx->fcr31 & cond) != 0) == ((MIPSInst_RT(ir) & 1) != 0)) xcp->regs[MIPSInst_RD(ir)] = xcp->regs[MIPSInst_RS(ir)]; break; #endif default: return SIGILL; } /* we did it !! */ xcp->cp0_epc = contpc; xcp->cp0_cause &= ~CAUSEF_BD; return 0; }
165,786
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: _bdf_parse_glyphs( char* line, unsigned long linelen, unsigned long lineno, void* call_data, void* client_data ) { int c, mask_index; char* s; unsigned char* bp; unsigned long i, slen, nibbles; _bdf_parse_t* p; bdf_glyph_t* glyph; bdf_font_t* font; FT_Memory memory; FT_Error error = BDF_Err_Ok; FT_UNUSED( call_data ); FT_UNUSED( lineno ); /* only used in debug mode */ p = (_bdf_parse_t *)client_data; font = p->font; memory = font->memory; /* Check for a comment. */ if ( ft_memcmp( line, "COMMENT", 7 ) == 0 ) { linelen -= 7; s = line + 7; if ( *s != 0 ) { s++; linelen--; } error = _bdf_add_comment( p->font, s, linelen ); goto Exit; } /* The very first thing expected is the number of glyphs. */ if ( !( p->flags & _BDF_GLYPHS ) ) { if ( ft_memcmp( line, "CHARS", 5 ) != 0 ) { FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG1, lineno, "CHARS" )); error = BDF_Err_Missing_Chars_Field; goto Exit; } error = _bdf_list_split( &p->list, (char *)" +", line, linelen ); if ( error ) goto Exit; p->cnt = font->glyphs_size = _bdf_atoul( p->list.field[1], 0, 10 ); /* Make sure the number of glyphs is non-zero. */ if ( p->cnt == 0 ) font->glyphs_size = 64; /* Limit ourselves to 1,114,112 glyphs in the font (this is the */ /* number of code points available in Unicode). */ if ( p->cnt >= 0x110000UL ) { FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG5, lineno, "CHARS" )); error = BDF_Err_Invalid_Argument; goto Exit; } if ( FT_NEW_ARRAY( font->glyphs, font->glyphs_size ) ) goto Exit; p->flags |= _BDF_GLYPHS; goto Exit; } /* Check for the ENDFONT field. */ if ( ft_memcmp( line, "ENDFONT", 7 ) == 0 ) { /* Sort the glyphs by encoding. */ ft_qsort( (char *)font->glyphs, font->glyphs_used, sizeof ( bdf_glyph_t ), by_encoding ); p->flags &= ~_BDF_START; goto Exit; } /* Check for the ENDCHAR field. */ if ( ft_memcmp( line, "ENDCHAR", 7 ) == 0 ) { p->glyph_enc = 0; p->flags &= ~_BDF_GLYPH_BITS; goto Exit; } /* Check whether a glyph is being scanned but should be */ /* ignored because it is an unencoded glyph. */ if ( ( p->flags & _BDF_GLYPH ) && p->glyph_enc == -1 && p->opts->keep_unencoded == 0 ) goto Exit; /* Check for the STARTCHAR field. */ if ( ft_memcmp( line, "STARTCHAR", 9 ) == 0 ) { /* Set the character name in the parse info first until the */ /* encoding can be checked for an unencoded character. */ FT_FREE( p->glyph_name ); error = _bdf_list_split( &p->list, (char *)" +", line, linelen ); if ( error ) goto Exit; _bdf_list_shift( &p->list, 1 ); s = _bdf_list_join( &p->list, ' ', &slen ); if ( !s ) { FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG8, lineno, "STARTCHAR" )); error = BDF_Err_Invalid_File_Format; goto Exit; } if ( FT_NEW_ARRAY( p->glyph_name, slen + 1 ) ) goto Exit; FT_MEM_COPY( p->glyph_name, s, slen + 1 ); p->flags |= _BDF_GLYPH; FT_TRACE4(( DBGMSG1, lineno, s )); goto Exit; } /* Check for the ENCODING field. */ if ( ft_memcmp( line, "ENCODING", 8 ) == 0 ) { if ( !( p->flags & _BDF_GLYPH ) ) { /* Missing STARTCHAR field. */ FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG1, lineno, "STARTCHAR" )); error = BDF_Err_Missing_Startchar_Field; goto Exit; } error = _bdf_list_split( &p->list, (char *)" +", line, linelen ); if ( error ) goto Exit; p->glyph_enc = _bdf_atol( p->list.field[1], 0, 10 ); /* Normalize negative encoding values. The specification only */ /* allows -1, but we can be more generous here. */ if ( p->glyph_enc < -1 ) p->glyph_enc = -1; /* Check for alternative encoding format. */ if ( p->glyph_enc == -1 && p->list.used > 2 ) p->glyph_enc = _bdf_atol( p->list.field[2], 0, 10 ); FT_TRACE4(( DBGMSG2, p->glyph_enc )); /* Check that the encoding is in the Unicode range because */ /* otherwise p->have (a bitmap with static size) overflows. */ if ( p->glyph_enc > 0 && (size_t)p->glyph_enc >= sizeof ( p->have ) * 8 ) { FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG5, lineno, "ENCODING" )); error = BDF_Err_Invalid_File_Format; } /* Check whether this encoding has already been encountered. */ /* If it has then change it to unencoded so it gets added if */ /* indicated. */ if ( p->glyph_enc >= 0 ) { if ( _bdf_glyph_modified( p->have, p->glyph_enc ) ) { /* Emit a message saying a glyph has been moved to the */ /* unencoded area. */ FT_TRACE2(( "_bdf_parse_glyphs: " ACMSG12, p->glyph_enc, p->glyph_name )); p->glyph_enc = -1; font->modified = 1; } else _bdf_set_glyph_modified( p->have, p->glyph_enc ); } if ( p->glyph_enc >= 0 ) { /* Make sure there are enough glyphs allocated in case the */ /* number of characters happen to be wrong. */ if ( font->glyphs_used == font->glyphs_size ) { if ( FT_RENEW_ARRAY( font->glyphs, font->glyphs_size, font->glyphs_size + 64 ) ) goto Exit; font->glyphs_size += 64; } glyph = font->glyphs + font->glyphs_used++; glyph->name = p->glyph_name; glyph->encoding = p->glyph_enc; /* Reset the initial glyph info. */ p->glyph_name = 0; } else { /* Unencoded glyph. Check whether it should */ /* be added or not. */ if ( p->opts->keep_unencoded != 0 ) { /* Allocate the next unencoded glyph. */ if ( font->unencoded_used == font->unencoded_size ) { if ( FT_RENEW_ARRAY( font->unencoded , font->unencoded_size, font->unencoded_size + 4 ) ) goto Exit; font->unencoded_size += 4; } glyph = font->unencoded + font->unencoded_used; glyph->name = p->glyph_name; glyph->encoding = font->unencoded_used++; } else /* Free up the glyph name if the unencoded shouldn't be */ /* kept. */ FT_FREE( p->glyph_name ); p->glyph_name = 0; } /* Clear the flags that might be added when width and height are */ /* checked for consistency. */ p->flags &= ~( _BDF_GLYPH_WIDTH_CHECK | _BDF_GLYPH_HEIGHT_CHECK ); p->flags |= _BDF_ENCODING; goto Exit; } /* Point at the glyph being constructed. */ if ( p->glyph_enc == -1 ) glyph = font->unencoded + ( font->unencoded_used - 1 ); else glyph = font->glyphs + ( font->glyphs_used - 1 ); /* Check whether a bitmap is being constructed. */ if ( p->flags & _BDF_BITMAP ) { /* If there are more rows than are specified in the glyph metrics, */ /* ignore the remaining lines. */ if ( p->row >= (unsigned long)glyph->bbx.height ) { if ( !( p->flags & _BDF_GLYPH_HEIGHT_CHECK ) ) { FT_TRACE2(( "_bdf_parse_glyphs: " ACMSG13, glyph->encoding )); p->flags |= _BDF_GLYPH_HEIGHT_CHECK; font->modified = 1; } goto Exit; } /* Only collect the number of nibbles indicated by the glyph */ /* metrics. If there are more columns, they are simply ignored. */ nibbles = glyph->bpr << 1; bp = glyph->bitmap + p->row * glyph->bpr; for ( i = 0; i < nibbles; i++ ) { c = line[i]; if ( !sbitset( hdigits, c ) ) break; *bp = (FT_Byte)( ( *bp << 4 ) + a2i[c] ); if ( i + 1 < nibbles && ( i & 1 ) ) *++bp = 0; } /* If any line has not enough columns, */ /* indicate they have been padded with zero bits. */ if ( i < nibbles && !( p->flags & _BDF_GLYPH_WIDTH_CHECK ) ) { FT_TRACE2(( "_bdf_parse_glyphs: " ACMSG16, glyph->encoding )); p->flags |= _BDF_GLYPH_WIDTH_CHECK; font->modified = 1; } /* Remove possible garbage at the right. */ mask_index = ( glyph->bbx.width * p->font->bpp ) & 7; if ( glyph->bbx.width ) *bp &= nibble_mask[mask_index]; /* If any line has extra columns, indicate they have been removed. */ if ( i == nibbles && sbitset( hdigits, line[nibbles] ) && !( p->flags & _BDF_GLYPH_WIDTH_CHECK ) ) { FT_TRACE2(( "_bdf_parse_glyphs: " ACMSG14, glyph->encoding )); p->flags |= _BDF_GLYPH_WIDTH_CHECK; font->modified = 1; } p->row++; goto Exit; } /* Expect the SWIDTH (scalable width) field next. */ if ( ft_memcmp( line, "SWIDTH", 6 ) == 0 ) { if ( !( p->flags & _BDF_ENCODING ) ) goto Missing_Encoding; error = _bdf_list_split( &p->list, (char *)" +", line, linelen ); if ( error ) goto Exit; glyph->swidth = (unsigned short)_bdf_atoul( p->list.field[1], 0, 10 ); p->flags |= _BDF_SWIDTH; goto Exit; } /* Expect the DWIDTH (scalable width) field next. */ if ( ft_memcmp( line, "DWIDTH", 6 ) == 0 ) { if ( !( p->flags & _BDF_ENCODING ) ) goto Missing_Encoding; error = _bdf_list_split( &p->list, (char *)" +", line, linelen ); if ( error ) goto Exit; glyph->dwidth = (unsigned short)_bdf_atoul( p->list.field[1], 0, 10 ); if ( !( p->flags & _BDF_SWIDTH ) ) { /* Missing SWIDTH field. Emit an auto correction message and set */ /* the scalable width from the device width. */ FT_TRACE2(( "_bdf_parse_glyphs: " ACMSG9, lineno )); glyph->swidth = (unsigned short)FT_MulDiv( glyph->dwidth, 72000L, (FT_Long)( font->point_size * font->resolution_x ) ); } p->flags |= _BDF_DWIDTH; goto Exit; } /* Expect the BBX field next. */ if ( ft_memcmp( line, "BBX", 3 ) == 0 ) { if ( !( p->flags & _BDF_ENCODING ) ) goto Missing_Encoding; error = _bdf_list_split( &p->list, (char *)" +", line, linelen ); if ( error ) goto Exit; glyph->bbx.width = _bdf_atos( p->list.field[1], 0, 10 ); glyph->bbx.height = _bdf_atos( p->list.field[2], 0, 10 ); glyph->bbx.x_offset = _bdf_atos( p->list.field[3], 0, 10 ); glyph->bbx.y_offset = _bdf_atos( p->list.field[4], 0, 10 ); /* Generate the ascent and descent of the character. */ glyph->bbx.ascent = (short)( glyph->bbx.height + glyph->bbx.y_offset ); glyph->bbx.descent = (short)( -glyph->bbx.y_offset ); /* Determine the overall font bounding box as the characters are */ /* loaded so corrections can be done later if indicated. */ p->maxas = (short)FT_MAX( glyph->bbx.ascent, p->maxas ); p->maxds = (short)FT_MAX( glyph->bbx.descent, p->maxds ); p->rbearing = (short)( glyph->bbx.width + glyph->bbx.x_offset ); p->maxrb = (short)FT_MAX( p->rbearing, p->maxrb ); p->minlb = (short)FT_MIN( glyph->bbx.x_offset, p->minlb ); p->maxlb = (short)FT_MAX( glyph->bbx.x_offset, p->maxlb ); if ( !( p->flags & _BDF_DWIDTH ) ) { /* Missing DWIDTH field. Emit an auto correction message and set */ /* the device width to the glyph width. */ FT_TRACE2(( "_bdf_parse_glyphs: " ACMSG10, lineno )); glyph->dwidth = glyph->bbx.width; } /* If the BDF_CORRECT_METRICS flag is set, then adjust the SWIDTH */ /* value if necessary. */ if ( p->opts->correct_metrics != 0 ) { /* Determine the point size of the glyph. */ unsigned short sw = (unsigned short)FT_MulDiv( glyph->dwidth, 72000L, (FT_Long)( font->point_size * font->resolution_x ) ); if ( sw != glyph->swidth ) { glyph->swidth = sw; if ( p->glyph_enc == -1 ) _bdf_set_glyph_modified( font->umod, font->unencoded_used - 1 ); else _bdf_set_glyph_modified( font->nmod, glyph->encoding ); p->flags |= _BDF_SWIDTH_ADJ; font->modified = 1; } } p->flags |= _BDF_BBX; goto Exit; } /* And finally, gather up the bitmap. */ if ( ft_memcmp( line, "BITMAP", 6 ) == 0 ) { unsigned long bitmap_size; if ( !( p->flags & _BDF_BBX ) ) { /* Missing BBX field. */ FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG1, lineno, "BBX" )); error = BDF_Err_Missing_Bbx_Field; goto Exit; } /* Allocate enough space for the bitmap. */ glyph->bpr = ( glyph->bbx.width * p->font->bpp + 7 ) >> 3; bitmap_size = glyph->bpr * glyph->bbx.height; if ( glyph->bpr > 0xFFFFU || bitmap_size > 0xFFFFU ) { FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG4, lineno )); error = BDF_Err_Bbx_Too_Big; goto Exit; } else glyph->bytes = (unsigned short)bitmap_size; if ( FT_NEW_ARRAY( glyph->bitmap, glyph->bytes ) ) goto Exit; p->row = 0; p->flags |= _BDF_BITMAP; goto Exit; } FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG9, lineno )); error = BDF_Err_Invalid_File_Format; goto Exit; Missing_Encoding: /* Missing ENCODING field. */ FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG1, lineno, "ENCODING" )); error = BDF_Err_Missing_Encoding_Field; Exit: if ( error && ( p->flags & _BDF_GLYPH ) ) FT_FREE( p->glyph_name ); return error; } Commit Message: CWE ID: CWE-119
_bdf_parse_glyphs( char* line, unsigned long linelen, unsigned long lineno, void* call_data, void* client_data ) { int c, mask_index; char* s; unsigned char* bp; unsigned long i, slen, nibbles; _bdf_parse_t* p; bdf_glyph_t* glyph; bdf_font_t* font; FT_Memory memory; FT_Error error = BDF_Err_Ok; FT_UNUSED( call_data ); FT_UNUSED( lineno ); /* only used in debug mode */ p = (_bdf_parse_t *)client_data; font = p->font; memory = font->memory; /* Check for a comment. */ if ( ft_memcmp( line, "COMMENT", 7 ) == 0 ) { linelen -= 7; s = line + 7; if ( *s != 0 ) { s++; linelen--; } error = _bdf_add_comment( p->font, s, linelen ); goto Exit; } /* The very first thing expected is the number of glyphs. */ if ( !( p->flags & _BDF_GLYPHS ) ) { if ( ft_memcmp( line, "CHARS", 5 ) != 0 ) { FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG1, lineno, "CHARS" )); error = BDF_Err_Missing_Chars_Field; goto Exit; } error = _bdf_list_split( &p->list, (char *)" +", line, linelen ); if ( error ) goto Exit; p->cnt = font->glyphs_size = _bdf_atoul( p->list.field[1], 0, 10 ); /* Make sure the number of glyphs is non-zero. */ if ( p->cnt == 0 ) font->glyphs_size = 64; /* Limit ourselves to 1,114,112 glyphs in the font (this is the */ /* number of code points available in Unicode). */ if ( p->cnt >= 0x110000UL ) { FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG5, lineno, "CHARS" )); error = BDF_Err_Invalid_Argument; goto Exit; } if ( FT_NEW_ARRAY( font->glyphs, font->glyphs_size ) ) goto Exit; p->flags |= _BDF_GLYPHS; goto Exit; } /* Check for the ENDFONT field. */ if ( ft_memcmp( line, "ENDFONT", 7 ) == 0 ) { /* Sort the glyphs by encoding. */ ft_qsort( (char *)font->glyphs, font->glyphs_used, sizeof ( bdf_glyph_t ), by_encoding ); p->flags &= ~_BDF_START; goto Exit; } /* Check for the ENDCHAR field. */ if ( ft_memcmp( line, "ENDCHAR", 7 ) == 0 ) { p->glyph_enc = 0; p->flags &= ~_BDF_GLYPH_BITS; goto Exit; } /* Check whether a glyph is being scanned but should be */ /* ignored because it is an unencoded glyph. */ if ( ( p->flags & _BDF_GLYPH ) && p->glyph_enc == -1 && p->opts->keep_unencoded == 0 ) goto Exit; /* Check for the STARTCHAR field. */ if ( ft_memcmp( line, "STARTCHAR", 9 ) == 0 ) { /* Set the character name in the parse info first until the */ /* encoding can be checked for an unencoded character. */ FT_FREE( p->glyph_name ); error = _bdf_list_split( &p->list, (char *)" +", line, linelen ); if ( error ) goto Exit; _bdf_list_shift( &p->list, 1 ); s = _bdf_list_join( &p->list, ' ', &slen ); if ( !s ) { FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG8, lineno, "STARTCHAR" )); error = BDF_Err_Invalid_File_Format; goto Exit; } if ( FT_NEW_ARRAY( p->glyph_name, slen + 1 ) ) goto Exit; FT_MEM_COPY( p->glyph_name, s, slen + 1 ); p->flags |= _BDF_GLYPH; FT_TRACE4(( DBGMSG1, lineno, s )); goto Exit; } /* Check for the ENCODING field. */ if ( ft_memcmp( line, "ENCODING", 8 ) == 0 ) { if ( !( p->flags & _BDF_GLYPH ) ) { /* Missing STARTCHAR field. */ FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG1, lineno, "STARTCHAR" )); error = BDF_Err_Missing_Startchar_Field; goto Exit; } error = _bdf_list_split( &p->list, (char *)" +", line, linelen ); if ( error ) goto Exit; p->glyph_enc = _bdf_atol( p->list.field[1], 0, 10 ); /* Normalize negative encoding values. The specification only */ /* allows -1, but we can be more generous here. */ if ( p->glyph_enc < -1 ) p->glyph_enc = -1; /* Check for alternative encoding format. */ if ( p->glyph_enc == -1 && p->list.used > 2 ) p->glyph_enc = _bdf_atol( p->list.field[2], 0, 10 ); FT_TRACE4(( DBGMSG2, p->glyph_enc )); /* Check that the encoding is in the Unicode range because */ /* otherwise p->have (a bitmap with static size) overflows. */ if ( p->glyph_enc > 0 && (size_t)p->glyph_enc >= sizeof ( p->have ) / sizeof ( unsigned long ) * 32 ) { FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG5, lineno, "ENCODING" )); error = BDF_Err_Invalid_File_Format; } /* Check whether this encoding has already been encountered. */ /* If it has then change it to unencoded so it gets added if */ /* indicated. */ if ( p->glyph_enc >= 0 ) { if ( _bdf_glyph_modified( p->have, p->glyph_enc ) ) { /* Emit a message saying a glyph has been moved to the */ /* unencoded area. */ FT_TRACE2(( "_bdf_parse_glyphs: " ACMSG12, p->glyph_enc, p->glyph_name )); p->glyph_enc = -1; font->modified = 1; } else _bdf_set_glyph_modified( p->have, p->glyph_enc ); } if ( p->glyph_enc >= 0 ) { /* Make sure there are enough glyphs allocated in case the */ /* number of characters happen to be wrong. */ if ( font->glyphs_used == font->glyphs_size ) { if ( FT_RENEW_ARRAY( font->glyphs, font->glyphs_size, font->glyphs_size + 64 ) ) goto Exit; font->glyphs_size += 64; } glyph = font->glyphs + font->glyphs_used++; glyph->name = p->glyph_name; glyph->encoding = p->glyph_enc; /* Reset the initial glyph info. */ p->glyph_name = 0; } else { /* Unencoded glyph. Check whether it should */ /* be added or not. */ if ( p->opts->keep_unencoded != 0 ) { /* Allocate the next unencoded glyph. */ if ( font->unencoded_used == font->unencoded_size ) { if ( FT_RENEW_ARRAY( font->unencoded , font->unencoded_size, font->unencoded_size + 4 ) ) goto Exit; font->unencoded_size += 4; } glyph = font->unencoded + font->unencoded_used; glyph->name = p->glyph_name; glyph->encoding = font->unencoded_used++; } else /* Free up the glyph name if the unencoded shouldn't be */ /* kept. */ FT_FREE( p->glyph_name ); p->glyph_name = 0; } /* Clear the flags that might be added when width and height are */ /* checked for consistency. */ p->flags &= ~( _BDF_GLYPH_WIDTH_CHECK | _BDF_GLYPH_HEIGHT_CHECK ); p->flags |= _BDF_ENCODING; goto Exit; } /* Point at the glyph being constructed. */ if ( p->glyph_enc == -1 ) glyph = font->unencoded + ( font->unencoded_used - 1 ); else glyph = font->glyphs + ( font->glyphs_used - 1 ); /* Check whether a bitmap is being constructed. */ if ( p->flags & _BDF_BITMAP ) { /* If there are more rows than are specified in the glyph metrics, */ /* ignore the remaining lines. */ if ( p->row >= (unsigned long)glyph->bbx.height ) { if ( !( p->flags & _BDF_GLYPH_HEIGHT_CHECK ) ) { FT_TRACE2(( "_bdf_parse_glyphs: " ACMSG13, glyph->encoding )); p->flags |= _BDF_GLYPH_HEIGHT_CHECK; font->modified = 1; } goto Exit; } /* Only collect the number of nibbles indicated by the glyph */ /* metrics. If there are more columns, they are simply ignored. */ nibbles = glyph->bpr << 1; bp = glyph->bitmap + p->row * glyph->bpr; for ( i = 0; i < nibbles; i++ ) { c = line[i]; if ( !sbitset( hdigits, c ) ) break; *bp = (FT_Byte)( ( *bp << 4 ) + a2i[c] ); if ( i + 1 < nibbles && ( i & 1 ) ) *++bp = 0; } /* If any line has not enough columns, */ /* indicate they have been padded with zero bits. */ if ( i < nibbles && !( p->flags & _BDF_GLYPH_WIDTH_CHECK ) ) { FT_TRACE2(( "_bdf_parse_glyphs: " ACMSG16, glyph->encoding )); p->flags |= _BDF_GLYPH_WIDTH_CHECK; font->modified = 1; } /* Remove possible garbage at the right. */ mask_index = ( glyph->bbx.width * p->font->bpp ) & 7; if ( glyph->bbx.width ) *bp &= nibble_mask[mask_index]; /* If any line has extra columns, indicate they have been removed. */ if ( i == nibbles && sbitset( hdigits, line[nibbles] ) && !( p->flags & _BDF_GLYPH_WIDTH_CHECK ) ) { FT_TRACE2(( "_bdf_parse_glyphs: " ACMSG14, glyph->encoding )); p->flags |= _BDF_GLYPH_WIDTH_CHECK; font->modified = 1; } p->row++; goto Exit; } /* Expect the SWIDTH (scalable width) field next. */ if ( ft_memcmp( line, "SWIDTH", 6 ) == 0 ) { if ( !( p->flags & _BDF_ENCODING ) ) goto Missing_Encoding; error = _bdf_list_split( &p->list, (char *)" +", line, linelen ); if ( error ) goto Exit; glyph->swidth = (unsigned short)_bdf_atoul( p->list.field[1], 0, 10 ); p->flags |= _BDF_SWIDTH; goto Exit; } /* Expect the DWIDTH (scalable width) field next. */ if ( ft_memcmp( line, "DWIDTH", 6 ) == 0 ) { if ( !( p->flags & _BDF_ENCODING ) ) goto Missing_Encoding; error = _bdf_list_split( &p->list, (char *)" +", line, linelen ); if ( error ) goto Exit; glyph->dwidth = (unsigned short)_bdf_atoul( p->list.field[1], 0, 10 ); if ( !( p->flags & _BDF_SWIDTH ) ) { /* Missing SWIDTH field. Emit an auto correction message and set */ /* the scalable width from the device width. */ FT_TRACE2(( "_bdf_parse_glyphs: " ACMSG9, lineno )); glyph->swidth = (unsigned short)FT_MulDiv( glyph->dwidth, 72000L, (FT_Long)( font->point_size * font->resolution_x ) ); } p->flags |= _BDF_DWIDTH; goto Exit; } /* Expect the BBX field next. */ if ( ft_memcmp( line, "BBX", 3 ) == 0 ) { if ( !( p->flags & _BDF_ENCODING ) ) goto Missing_Encoding; error = _bdf_list_split( &p->list, (char *)" +", line, linelen ); if ( error ) goto Exit; glyph->bbx.width = _bdf_atos( p->list.field[1], 0, 10 ); glyph->bbx.height = _bdf_atos( p->list.field[2], 0, 10 ); glyph->bbx.x_offset = _bdf_atos( p->list.field[3], 0, 10 ); glyph->bbx.y_offset = _bdf_atos( p->list.field[4], 0, 10 ); /* Generate the ascent and descent of the character. */ glyph->bbx.ascent = (short)( glyph->bbx.height + glyph->bbx.y_offset ); glyph->bbx.descent = (short)( -glyph->bbx.y_offset ); /* Determine the overall font bounding box as the characters are */ /* loaded so corrections can be done later if indicated. */ p->maxas = (short)FT_MAX( glyph->bbx.ascent, p->maxas ); p->maxds = (short)FT_MAX( glyph->bbx.descent, p->maxds ); p->rbearing = (short)( glyph->bbx.width + glyph->bbx.x_offset ); p->maxrb = (short)FT_MAX( p->rbearing, p->maxrb ); p->minlb = (short)FT_MIN( glyph->bbx.x_offset, p->minlb ); p->maxlb = (short)FT_MAX( glyph->bbx.x_offset, p->maxlb ); if ( !( p->flags & _BDF_DWIDTH ) ) { /* Missing DWIDTH field. Emit an auto correction message and set */ /* the device width to the glyph width. */ FT_TRACE2(( "_bdf_parse_glyphs: " ACMSG10, lineno )); glyph->dwidth = glyph->bbx.width; } /* If the BDF_CORRECT_METRICS flag is set, then adjust the SWIDTH */ /* value if necessary. */ if ( p->opts->correct_metrics != 0 ) { /* Determine the point size of the glyph. */ unsigned short sw = (unsigned short)FT_MulDiv( glyph->dwidth, 72000L, (FT_Long)( font->point_size * font->resolution_x ) ); if ( sw != glyph->swidth ) { glyph->swidth = sw; if ( p->glyph_enc == -1 ) _bdf_set_glyph_modified( font->umod, font->unencoded_used - 1 ); else _bdf_set_glyph_modified( font->nmod, glyph->encoding ); p->flags |= _BDF_SWIDTH_ADJ; font->modified = 1; } } p->flags |= _BDF_BBX; goto Exit; } /* And finally, gather up the bitmap. */ if ( ft_memcmp( line, "BITMAP", 6 ) == 0 ) { unsigned long bitmap_size; if ( !( p->flags & _BDF_BBX ) ) { /* Missing BBX field. */ FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG1, lineno, "BBX" )); error = BDF_Err_Missing_Bbx_Field; goto Exit; } /* Allocate enough space for the bitmap. */ glyph->bpr = ( glyph->bbx.width * p->font->bpp + 7 ) >> 3; bitmap_size = glyph->bpr * glyph->bbx.height; if ( glyph->bpr > 0xFFFFU || bitmap_size > 0xFFFFU ) { FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG4, lineno )); error = BDF_Err_Bbx_Too_Big; goto Exit; } else glyph->bytes = (unsigned short)bitmap_size; if ( FT_NEW_ARRAY( glyph->bitmap, glyph->bytes ) ) goto Exit; p->row = 0; p->flags |= _BDF_BITMAP; goto Exit; } FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG9, lineno )); error = BDF_Err_Invalid_File_Format; goto Exit; Missing_Encoding: /* Missing ENCODING field. */ FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG1, lineno, "ENCODING" )); error = BDF_Err_Missing_Encoding_Field; Exit: if ( error && ( p->flags & _BDF_GLYPH ) ) FT_FREE( p->glyph_name ); return error; }
164,823
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void ptrace_siblings(pid_t pid, pid_t main_tid, std::set<pid_t>& tids) { char task_path[64]; //// Attach to a thread, and verify that it's still a member of the given process snprintf(task_path, sizeof(task_path), "/proc/%d/task", pid); std::unique_ptr<DIR, int (*)(DIR*)> d(opendir(task_path), closedir); if (!d) { ALOGE("debuggerd: failed to open /proc/%d/task: %s", pid, strerror(errno)); return; } struct dirent* de; while ((de = readdir(d.get())) != NULL) { if (!strcmp(de->d_name, ".") || !strcmp(de->d_name, "..")) { continue; } char* end; pid_t tid = strtoul(de->d_name, &end, 10); if (*end) { continue; } if (tid == main_tid) { continue; } if (ptrace(PTRACE_ATTACH, tid, 0, 0) < 0) { ALOGE("debuggerd: ptrace attach to %d failed: %s", tid, strerror(errno)); continue; } tids.insert(tid); } } Commit Message: debuggerd: verify that traced threads belong to the right process. Fix two races in debuggerd's PTRACE_ATTACH logic: 1. The target thread in a crash dump request could exit between the /proc/<pid>/task/<tid> check and the PTRACE_ATTACH. 2. Sibling threads could exit between listing /proc/<pid>/task and the PTRACE_ATTACH. Bug: http://b/29555636 Change-Id: I4dfe1ea30e2c211d2389321bd66e3684dd757591 CWE ID: CWE-264
static void ptrace_siblings(pid_t pid, pid_t main_tid, std::set<pid_t>& tids) { //// Attach to a thread, and verify that it's still a member of the given process static bool ptrace_attach_thread(pid_t pid, pid_t tid) { if (ptrace(PTRACE_ATTACH, tid, 0, 0) != 0) { return false; } // Make sure that the task we attached to is actually part of the pid we're dumping. if (!pid_contains_tid(pid, tid)) { if (ptrace(PTRACE_DETACH, tid, 0, 0) != 0) { ALOGE("debuggerd: failed to detach from thread '%d'", tid); exit(1); } return false; } return true; } static void ptrace_siblings(pid_t pid, pid_t main_tid, std::set<pid_t>& tids) { char task_path[PATH_MAX]; if (snprintf(task_path, PATH_MAX, "/proc/%d/task", pid) >= PATH_MAX) { ALOGE("debuggerd: task path overflow (pid = %d)\n", pid); abort(); } std::unique_ptr<DIR, int (*)(DIR*)> d(opendir(task_path), closedir); if (!d) { ALOGE("debuggerd: failed to open /proc/%d/task: %s", pid, strerror(errno)); return; } struct dirent* de; while ((de = readdir(d.get())) != NULL) { if (!strcmp(de->d_name, ".") || !strcmp(de->d_name, "..")) { continue; } char* end; pid_t tid = strtoul(de->d_name, &end, 10); if (*end) { continue; } if (tid == main_tid) { continue; } if (!ptrace_attach_thread(pid, tid)) { ALOGE("debuggerd: ptrace attach to %d failed: %s", tid, strerror(errno)); continue; } tids.insert(tid); } }
173,406
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: GLSurfaceEGLSurfaceControl::GLSurfaceEGLSurfaceControl( ANativeWindow* window, scoped_refptr<base::SingleThreadTaskRunner> task_runner) : root_surface_(new SurfaceControl::Surface(window, kRootSurfaceName)), gpu_task_runner_(std::move(task_runner)), weak_factory_(this) {} Commit Message: gpu/android : Add support for partial swap with surface control. Add support for PostSubBuffer to GLSurfaceEGLSurfaceControl. This should allow the display compositor to draw the minimum sub-rect necessary from the damage tracking in BufferQueue on the client-side, and also to pass this damage rect to the framework. [email protected] Bug: 926020 Change-Id: I73d3320cab68250d4c6865bf21c5531682d8bf61 Reviewed-on: https://chromium-review.googlesource.com/c/1457467 Commit-Queue: Khushal <[email protected]> Commit-Queue: Antoine Labour <[email protected]> Reviewed-by: Antoine Labour <[email protected]> Auto-Submit: Khushal <[email protected]> Cr-Commit-Position: refs/heads/master@{#629852} CWE ID:
GLSurfaceEGLSurfaceControl::GLSurfaceEGLSurfaceControl( ANativeWindow* window, scoped_refptr<base::SingleThreadTaskRunner> task_runner) : window_rect_(0, 0, ANativeWindow_getWidth(window), ANativeWindow_getHeight(window)), root_surface_(new SurfaceControl::Surface(window, kRootSurfaceName)), gpu_task_runner_(std::move(task_runner)), weak_factory_(this) {}
172,109
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: insert_hIST(png_structp png_ptr, png_infop info_ptr, int nparams, png_charpp params) { int i; png_uint_16 freq[256]; /* libpng takes the count from the PLTE count; we don't check it here but we * do set the array to 0 for unspecified entries. */ memset(freq, 0, sizeof freq); for (i=0; i<nparams; ++i) { char *endptr = NULL; unsigned long int l = strtoul(params[i], &endptr, 0/*base*/); if (params[i][0] && *endptr == 0 && l <= 65535) freq[i] = (png_uint_16)l; else { fprintf(stderr, "hIST[%d]: %s: invalid frequency\n", i, params[i]); exit(1); } } png_set_hIST(png_ptr, info_ptr, freq); } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
insert_hIST(png_structp png_ptr, png_infop info_ptr, int nparams, png_charpp params) insert_hIST(png_structp png_ptr, png_infop info_ptr, int nparams, png_charpp params) { int i; png_uint_16 freq[256]; /* libpng takes the count from the PLTE count; we don't check it here but we * do set the array to 0 for unspecified entries. */ memset(freq, 0, sizeof freq); for (i=0; i<nparams; ++i) { char *endptr = NULL; unsigned long int l = strtoul(params[i], &endptr, 0/*base*/); if (params[i][0] && *endptr == 0 && l <= 65535) freq[i] = (png_uint_16)l; else { fprintf(stderr, "hIST[%d]: %s: invalid frequency\n", i, params[i]); exit(1); } } png_set_hIST(png_ptr, info_ptr, freq); }
173,582
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int mxf_read_primer_pack(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset) { MXFContext *mxf = arg; int item_num = avio_rb32(pb); int item_len = avio_rb32(pb); if (item_len != 18) { avpriv_request_sample(pb, "Primer pack item length %d", item_len); return AVERROR_PATCHWELCOME; } if (item_num > 65536) { av_log(mxf->fc, AV_LOG_ERROR, "item_num %d is too large\n", item_num); return AVERROR_INVALIDDATA; } if (mxf->local_tags) av_log(mxf->fc, AV_LOG_VERBOSE, "Multiple primer packs\n"); av_free(mxf->local_tags); mxf->local_tags_count = 0; mxf->local_tags = av_calloc(item_num, item_len); if (!mxf->local_tags) return AVERROR(ENOMEM); mxf->local_tags_count = item_num; avio_read(pb, mxf->local_tags, item_num*item_len); return 0; } Commit Message: avformat/mxfdec: Fix Sign error in mxf_read_primer_pack() Fixes: 20170829B.mxf Co-Author: 张洪亮(望初)" <[email protected]> Found-by: Xiaohei and Wangchu from Alibaba Security Team Signed-off-by: Michael Niedermayer <[email protected]> CWE ID: CWE-20
static int mxf_read_primer_pack(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset) { MXFContext *mxf = arg; int item_num = avio_rb32(pb); int item_len = avio_rb32(pb); if (item_len != 18) { avpriv_request_sample(pb, "Primer pack item length %d", item_len); return AVERROR_PATCHWELCOME; } if (item_num > 65536 || item_num < 0) { av_log(mxf->fc, AV_LOG_ERROR, "item_num %d is too large\n", item_num); return AVERROR_INVALIDDATA; } if (mxf->local_tags) av_log(mxf->fc, AV_LOG_VERBOSE, "Multiple primer packs\n"); av_free(mxf->local_tags); mxf->local_tags_count = 0; mxf->local_tags = av_calloc(item_num, item_len); if (!mxf->local_tags) return AVERROR(ENOMEM); mxf->local_tags_count = item_num; avio_read(pb, mxf->local_tags, item_num*item_len); return 0; }
167,766
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int ssl3_write_bytes(SSL *s, int type, const void *buf_, int len) { const unsigned char *buf = buf_; int tot; unsigned int n, nw; #if !defined(OPENSSL_NO_MULTIBLOCK) && EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK unsigned int max_send_fragment; #endif SSL3_BUFFER *wb = &(s->s3->wbuf); int i; s->rwstate = SSL_NOTHING; OPENSSL_assert(s->s3->wnum <= INT_MAX); tot = s->s3->wnum; s->s3->wnum = 0; if (SSL_in_init(s) && !s->in_handshake) { i = s->handshake_func(s); if (i < 0) return (i); if (i == 0) { SSLerr(SSL_F_SSL3_WRITE_BYTES, SSL_R_SSL_HANDSHAKE_FAILURE); return -1; } } /* * ensure that if we end up with a smaller value of data to write out * than the the original len from a write which didn't complete for * non-blocking I/O and also somehow ended up avoiding the check for * this in ssl3_write_pending/SSL_R_BAD_WRITE_RETRY as it must never be * possible to end up with (len-tot) as a large number that will then * promptly send beyond the end of the users buffer ... so we trap and * report the error in a way the user will notice */ if (len < tot) { SSLerr(SSL_F_SSL3_WRITE_BYTES, SSL_R_BAD_LENGTH); return (-1); } /* * first check if there is a SSL3_BUFFER still being written out. This * will happen with non blocking IO */ if (wb->left != 0) { i = ssl3_write_pending(s, type, &buf[tot], s->s3->wpend_tot); if (i <= 0) { /* XXX should we ssl3_release_write_buffer if i<0? */ s->s3->wnum = tot; return i; } tot += i; /* this might be last fragment */ } #if !defined(OPENSSL_NO_MULTIBLOCK) && EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK /* * Depending on platform multi-block can deliver several *times* * better performance. Downside is that it has to allocate * jumbo buffer to accomodate up to 8 records, but the * compromise is considered worthy. */ if (type == SSL3_RT_APPLICATION_DATA && len >= 4 * (int)(max_send_fragment = s->max_send_fragment) && s->compress == NULL && s->msg_callback == NULL && SSL_USE_EXPLICIT_IV(s) && EVP_CIPHER_flags(s->enc_write_ctx->cipher) & EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK) { unsigned char aad[13]; EVP_CTRL_TLS1_1_MULTIBLOCK_PARAM mb_param; int packlen; /* minimize address aliasing conflicts */ if ((max_send_fragment & 0xfff) == 0) max_send_fragment -= 512; if (tot == 0 || wb->buf == NULL) { /* allocate jumbo buffer */ ssl3_release_write_buffer(s); packlen = EVP_CIPHER_CTX_ctrl(s->enc_write_ctx, EVP_CTRL_TLS1_1_MULTIBLOCK_MAX_BUFSIZE, max_send_fragment, NULL); if (len >= 8 * (int)max_send_fragment) packlen *= 8; else packlen *= 4; wb->buf = OPENSSL_malloc(packlen); if(!wb->buf) { SSLerr(SSL_F_SSL3_WRITE_BYTES, ERR_R_MALLOC_FAILURE); return -1; } wb->len = packlen; } else if (tot == len) { /* done? */ OPENSSL_free(wb->buf); /* free jumbo buffer */ wb->buf = NULL; return tot; } n = (len - tot); for (;;) { if (n < 4 * max_send_fragment) { OPENSSL_free(wb->buf); /* free jumbo buffer */ wb->buf = NULL; break; } if (s->s3->alert_dispatch) { i = s->method->ssl_dispatch_alert(s); if (i <= 0) { s->s3->wnum = tot; return i; } } if (n >= 8 * max_send_fragment) nw = max_send_fragment * (mb_param.interleave = 8); else nw = max_send_fragment * (mb_param.interleave = 4); memcpy(aad, s->s3->write_sequence, 8); aad[8] = type; aad[9] = (unsigned char)(s->version >> 8); aad[10] = (unsigned char)(s->version); aad[11] = 0; aad[12] = 0; mb_param.out = NULL; mb_param.inp = aad; mb_param.len = nw; packlen = EVP_CIPHER_CTX_ctrl(s->enc_write_ctx, EVP_CTRL_TLS1_1_MULTIBLOCK_AAD, sizeof(mb_param), &mb_param); if (packlen <= 0 || packlen > (int)wb->len) { /* never happens */ OPENSSL_free(wb->buf); /* free jumbo buffer */ wb->buf = NULL; break; } mb_param.out = wb->buf; mb_param.inp = &buf[tot]; mb_param.len = nw; if (EVP_CIPHER_CTX_ctrl(s->enc_write_ctx, EVP_CTRL_TLS1_1_MULTIBLOCK_ENCRYPT, sizeof(mb_param), &mb_param) <= 0) return -1; s->s3->write_sequence[7] += mb_param.interleave; if (s->s3->write_sequence[7] < mb_param.interleave) { int j = 6; while (j >= 0 && (++s->s3->write_sequence[j--]) == 0) ; } wb->offset = 0; wb->left = packlen; s->s3->wpend_tot = nw; s->s3->wpend_buf = &buf[tot]; s->s3->wpend_type = type; s->s3->wpend_ret = nw; i = ssl3_write_pending(s, type, &buf[tot], nw); if (i <= 0) { if (i < 0) { OPENSSL_free(wb->buf); wb->buf = NULL; } s->s3->wnum = tot; return i; } if (i == (int)n) { OPENSSL_free(wb->buf); /* free jumbo buffer */ wb->buf = NULL; return tot + i; } n -= i; tot += i; } } else #endif if (tot == len) { /* done? */ if (s->mode & SSL_MODE_RELEASE_BUFFERS && !SSL_IS_DTLS(s)) ssl3_release_write_buffer(s); return tot; } n = (len - tot); for (;;) { if (n > s->max_send_fragment) nw = s->max_send_fragment; else nw = n; i = do_ssl3_write(s, type, &(buf[tot]), nw, 0); if (i <= 0) { /* XXX should we ssl3_release_write_buffer if i<0? */ s->s3->wnum = tot; return i; } if ((i == (int)n) || (type == SSL3_RT_APPLICATION_DATA && (s->mode & SSL_MODE_ENABLE_PARTIAL_WRITE))) { /* * next chunk of data should get another prepended empty fragment * in ciphersuites with known-IV weakness: */ s->s3->empty_fragment_done = 0; if ((i == (int)n) && s->mode & SSL_MODE_RELEASE_BUFFERS && !SSL_IS_DTLS(s)) ssl3_release_write_buffer(s); return tot + i; } n -= i; tot += i; } } Commit Message: CWE ID: CWE-17
int ssl3_write_bytes(SSL *s, int type, const void *buf_, int len) { const unsigned char *buf = buf_; int tot; unsigned int n, nw; #if !defined(OPENSSL_NO_MULTIBLOCK) && EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK unsigned int max_send_fragment; #endif SSL3_BUFFER *wb = &(s->s3->wbuf); int i; s->rwstate = SSL_NOTHING; OPENSSL_assert(s->s3->wnum <= INT_MAX); tot = s->s3->wnum; s->s3->wnum = 0; if (SSL_in_init(s) && !s->in_handshake) { i = s->handshake_func(s); if (i < 0) return (i); if (i == 0) { SSLerr(SSL_F_SSL3_WRITE_BYTES, SSL_R_SSL_HANDSHAKE_FAILURE); return -1; } } /* * ensure that if we end up with a smaller value of data to write out * than the the original len from a write which didn't complete for * non-blocking I/O and also somehow ended up avoiding the check for * this in ssl3_write_pending/SSL_R_BAD_WRITE_RETRY as it must never be * possible to end up with (len-tot) as a large number that will then * promptly send beyond the end of the users buffer ... so we trap and * report the error in a way the user will notice */ if (len < tot) { SSLerr(SSL_F_SSL3_WRITE_BYTES, SSL_R_BAD_LENGTH); return (-1); } /* * first check if there is a SSL3_BUFFER still being written out. This * will happen with non blocking IO */ if (wb->left != 0) { i = ssl3_write_pending(s, type, &buf[tot], s->s3->wpend_tot); if (i <= 0) { /* XXX should we ssl3_release_write_buffer if i<0? */ s->s3->wnum = tot; return i; } tot += i; /* this might be last fragment */ } #if !defined(OPENSSL_NO_MULTIBLOCK) && EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK /* * Depending on platform multi-block can deliver several *times* * better performance. Downside is that it has to allocate * jumbo buffer to accomodate up to 8 records, but the * compromise is considered worthy. */ if (type == SSL3_RT_APPLICATION_DATA && len >= 4 * (int)(max_send_fragment = s->max_send_fragment) && s->compress == NULL && s->msg_callback == NULL && SSL_USE_EXPLICIT_IV(s) && EVP_CIPHER_flags(s->enc_write_ctx->cipher) & EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK) { unsigned char aad[13]; EVP_CTRL_TLS1_1_MULTIBLOCK_PARAM mb_param; int packlen; /* minimize address aliasing conflicts */ if ((max_send_fragment & 0xfff) == 0) max_send_fragment -= 512; if (tot == 0 || wb->buf == NULL) { /* allocate jumbo buffer */ ssl3_release_write_buffer(s); packlen = EVP_CIPHER_CTX_ctrl(s->enc_write_ctx, EVP_CTRL_TLS1_1_MULTIBLOCK_MAX_BUFSIZE, max_send_fragment, NULL); if (len >= 8 * (int)max_send_fragment) packlen *= 8; else packlen *= 4; wb->buf = OPENSSL_malloc(packlen); if(!wb->buf) { SSLerr(SSL_F_SSL3_WRITE_BYTES, ERR_R_MALLOC_FAILURE); return -1; } wb->len = packlen; } else if (tot == len) { /* done? */ OPENSSL_free(wb->buf); /* free jumbo buffer */ wb->buf = NULL; return tot; } n = (len - tot); for (;;) { if (n < 4 * max_send_fragment) { OPENSSL_free(wb->buf); /* free jumbo buffer */ wb->buf = NULL; break; } if (s->s3->alert_dispatch) { i = s->method->ssl_dispatch_alert(s); if (i <= 0) { s->s3->wnum = tot; return i; } } if (n >= 8 * max_send_fragment) nw = max_send_fragment * (mb_param.interleave = 8); else nw = max_send_fragment * (mb_param.interleave = 4); memcpy(aad, s->s3->write_sequence, 8); aad[8] = type; aad[9] = (unsigned char)(s->version >> 8); aad[10] = (unsigned char)(s->version); aad[11] = 0; aad[12] = 0; mb_param.out = NULL; mb_param.inp = aad; mb_param.len = nw; packlen = EVP_CIPHER_CTX_ctrl(s->enc_write_ctx, EVP_CTRL_TLS1_1_MULTIBLOCK_AAD, sizeof(mb_param), &mb_param); if (packlen <= 0 || packlen > (int)wb->len) { /* never happens */ OPENSSL_free(wb->buf); /* free jumbo buffer */ wb->buf = NULL; break; } mb_param.out = wb->buf; mb_param.inp = &buf[tot]; mb_param.len = nw; if (EVP_CIPHER_CTX_ctrl(s->enc_write_ctx, EVP_CTRL_TLS1_1_MULTIBLOCK_ENCRYPT, sizeof(mb_param), &mb_param) <= 0) return -1; s->s3->write_sequence[7] += mb_param.interleave; if (s->s3->write_sequence[7] < mb_param.interleave) { int j = 6; while (j >= 0 && (++s->s3->write_sequence[j--]) == 0) ; } wb->offset = 0; wb->left = packlen; s->s3->wpend_tot = nw; s->s3->wpend_buf = &buf[tot]; s->s3->wpend_type = type; s->s3->wpend_ret = nw; i = ssl3_write_pending(s, type, &buf[tot], nw); if (i <= 0) { if (i < 0 && (!s->wbio || !BIO_should_retry(s->wbio))) { OPENSSL_free(wb->buf); wb->buf = NULL; } s->s3->wnum = tot; return i; } if (i == (int)n) { OPENSSL_free(wb->buf); /* free jumbo buffer */ wb->buf = NULL; return tot + i; } n -= i; tot += i; } } else #endif if (tot == len) { /* done? */ if (s->mode & SSL_MODE_RELEASE_BUFFERS && !SSL_IS_DTLS(s)) ssl3_release_write_buffer(s); return tot; } n = (len - tot); for (;;) { if (n > s->max_send_fragment) nw = s->max_send_fragment; else nw = n; i = do_ssl3_write(s, type, &(buf[tot]), nw, 0); if (i <= 0) { /* XXX should we ssl3_release_write_buffer if i<0? */ s->s3->wnum = tot; return i; } if ((i == (int)n) || (type == SSL3_RT_APPLICATION_DATA && (s->mode & SSL_MODE_ENABLE_PARTIAL_WRITE))) { /* * next chunk of data should get another prepended empty fragment * in ciphersuites with known-IV weakness: */ s->s3->empty_fragment_done = 0; if ((i == (int)n) && s->mode & SSL_MODE_RELEASE_BUFFERS && !SSL_IS_DTLS(s)) ssl3_release_write_buffer(s); return tot + i; } n -= i; tot += i; } }
164,806
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool ChromeContentRendererClient::WillSendRequest(WebKit::WebFrame* frame, const GURL& url, GURL* new_url) { if (url.SchemeIs(chrome::kExtensionScheme) && !ExtensionResourceRequestPolicy::CanRequestResource( url, GURL(frame->document().url()), extension_dispatcher_->extensions())) { *new_url = GURL("chrome-extension://invalid/"); return true; } return false; } Commit Message: Do not require DevTools extension resources to be white-listed in manifest. Currently, resources used by DevTools extensions need to be white-listed as web_accessible_resources in manifest. This is quite inconvenitent and appears to be an overkill, given the fact that DevTools front-end is (a) trusted and (b) picky on the frames it loads. This change adds resources that belong to DevTools extensions and are being loaded into a DevTools front-end page to the list of exceptions from web_accessible_resources check. BUG=none TEST=DevToolsExtensionTest.* Review URL: https://chromiumcodereview.appspot.com/9663076 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@126378 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
bool ChromeContentRendererClient::WillSendRequest(WebKit::WebFrame* frame, const GURL& url, GURL* new_url) { if (url.SchemeIs(chrome::kExtensionScheme) && !ExtensionResourceRequestPolicy::CanRequestResource( url, frame, extension_dispatcher_->extensions())) { *new_url = GURL("chrome-extension://invalid/"); return true; } return false; }
171,000
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void TabStripGtk::TabDetachedAt(TabContents* contents, int index) { GenerateIdealBounds(); StartRemoveTabAnimation(index, contents->web_contents()); GetTabAt(index)->set_closing(true); } Commit Message: Remove TabContents from TabStripModelObserver::TabDetachedAt. BUG=107201 TEST=no visible change Review URL: https://chromiumcodereview.appspot.com/11293205 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@167122 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
void TabStripGtk::TabDetachedAt(TabContents* contents, int index) { void TabStripGtk::TabDetachedAt(WebContents* contents, int index) { GenerateIdealBounds(); StartRemoveTabAnimation(index, contents); GetTabAt(index)->set_closing(true); }
171,516