instruction
stringclasses
1 value
input
stringlengths
90
139k
output
stringlengths
16
138k
__index_level_0__
int64
165k
175k
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int __do_page_fault(struct mm_struct *mm, unsigned long addr, unsigned int mm_flags, unsigned long vm_flags, struct task_struct *tsk) { struct vm_area_struct *vma; int fault; vma = find_vma(mm, addr); fault = VM_FAULT_BADMAP; if (unlikely(!vma)) goto out; if (unlikely(vma->vm_start > addr)) goto check_stack; /* * Ok, we have a good vm_area for this memory access, so we can handle * it. */ good_area: /* * Check that the permissions on the VMA allow for the fault which * occurred. */ if (!(vma->vm_flags & vm_flags)) { fault = VM_FAULT_BADACCESS; goto out; } return handle_mm_fault(mm, vma, addr & PAGE_MASK, mm_flags); check_stack: if (vma->vm_flags & VM_GROWSDOWN && !expand_stack(vma, addr)) goto good_area; out: return fault; } Commit Message: Revert "arm64: Introduce execute-only page access permissions" This reverts commit bc07c2c6e9ed125d362af0214b6313dca180cb08. While the aim is increased security for --x memory maps, it does not protect against kernel level reads. Until SECCOMP is implemented for arm64, revert this patch to avoid giving a false idea of execute-only mappings. Signed-off-by: Catalin Marinas <[email protected]> CWE ID: CWE-19
static int __do_page_fault(struct mm_struct *mm, unsigned long addr, unsigned int mm_flags, unsigned long vm_flags, struct task_struct *tsk) { struct vm_area_struct *vma; int fault; vma = find_vma(mm, addr); fault = VM_FAULT_BADMAP; if (unlikely(!vma)) goto out; if (unlikely(vma->vm_start > addr)) goto check_stack; /* * Ok, we have a good vm_area for this memory access, so we can handle * it. */ good_area: /* * Check that the permissions on the VMA allow for the fault which * occurred. If we encountered a write or exec fault, we must have * appropriate permissions, otherwise we allow any permission. */ if (!(vma->vm_flags & vm_flags)) { fault = VM_FAULT_BADACCESS; goto out; } return handle_mm_fault(mm, vma, addr & PAGE_MASK, mm_flags); check_stack: if (vma->vm_flags & VM_GROWSDOWN && !expand_stack(vma, addr)) goto good_area; out: return fault; }
167,583
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: hb_buffer_ensure (hb_buffer_t *buffer, unsigned int size) { unsigned int new_allocated = buffer->allocated; if (size > new_allocated) { while (size > new_allocated) new_allocated += (new_allocated >> 1) + 8; if (buffer->pos) buffer->pos = (hb_internal_glyph_position_t *) realloc (buffer->pos, new_allocated * sizeof (buffer->pos[0])); if (buffer->out_info != buffer->info) { buffer->info = (hb_internal_glyph_info_t *) realloc (buffer->info, new_allocated * sizeof (buffer->info[0])); buffer->out_info = (hb_internal_glyph_info_t *) buffer->pos; } else { buffer->info = (hb_internal_glyph_info_t *) realloc (buffer->info, new_allocated * sizeof (buffer->info[0])); buffer->out_info = buffer->info; } buffer->allocated = new_allocated; } } Commit Message: CWE ID:
hb_buffer_ensure (hb_buffer_t *buffer, unsigned int size) { if (unlikely (size > buffer->allocated)) { if (unlikely (buffer->in_error)) return FALSE; unsigned int new_allocated = buffer->allocated; hb_internal_glyph_position_t *new_pos; hb_internal_glyph_info_t *new_info; bool separate_out; separate_out = buffer->out_info != buffer->info; while (size > new_allocated) new_allocated += (new_allocated >> 1) + 8; new_pos = (hb_internal_glyph_position_t *) realloc (buffer->pos, new_allocated * sizeof (buffer->pos[0])); new_info = (hb_internal_glyph_info_t *) realloc (buffer->info, new_allocated * sizeof (buffer->info[0])); if (unlikely (!new_pos || !new_info)) buffer->in_error = TRUE; if (likely (new_pos)) buffer->pos = new_pos; if (likely (new_info)) buffer->info = new_info; buffer->out_info = separate_out ? (hb_internal_glyph_info_t *) buffer->pos : buffer->info; if (likely (!buffer->in_error)) buffer->allocated = new_allocated; } return likely (!buffer->in_error); }
164,774
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: CompileKeymap(XkbFile *file, struct xkb_keymap *keymap, enum merge_mode merge) { bool ok; XkbFile *files[LAST_KEYMAP_FILE_TYPE + 1] = { NULL }; enum xkb_file_type type; struct xkb_context *ctx = keymap->ctx; /* Collect section files and check for duplicates. */ for (file = (XkbFile *) file->defs; file; file = (XkbFile *) file->common.next) { if (file->file_type < FIRST_KEYMAP_FILE_TYPE || file->file_type > LAST_KEYMAP_FILE_TYPE) { log_err(ctx, "Cannot define %s in a keymap file\n", xkb_file_type_to_string(file->file_type)); continue; } if (files[file->file_type]) { log_err(ctx, "More than one %s section in keymap file; " "All sections after the first ignored\n", xkb_file_type_to_string(file->file_type)); continue; } files[file->file_type] = file; } /* * Check that all required section were provided. * Report everything before failing. */ ok = true; for (type = FIRST_KEYMAP_FILE_TYPE; type <= LAST_KEYMAP_FILE_TYPE; type++) { if (files[type] == NULL) { log_err(ctx, "Required section %s missing from keymap\n", xkb_file_type_to_string(type)); ok = false; } } if (!ok) return false; /* Compile sections. */ for (type = FIRST_KEYMAP_FILE_TYPE; type <= LAST_KEYMAP_FILE_TYPE; type++) { log_dbg(ctx, "Compiling %s \"%s\"\n", xkb_file_type_to_string(type), files[type]->name); ok = compile_file_fns[type](files[type], keymap, merge); if (!ok) { log_err(ctx, "Failed to compile %s\n", xkb_file_type_to_string(type)); return false; } } return UpdateDerivedKeymapFields(keymap); } Commit Message: xkbcomp: fix crash when parsing an xkb_geometry section xkb_geometry sections are ignored; previously the had done so by returning NULL for the section's XkbFile, however some sections of the code do not expect this. Instead, create an XkbFile for it, it will never be processes and discarded later. Caught with the afl fuzzer. Signed-off-by: Ran Benita <[email protected]> CWE ID: CWE-476
CompileKeymap(XkbFile *file, struct xkb_keymap *keymap, enum merge_mode merge) { bool ok; XkbFile *files[LAST_KEYMAP_FILE_TYPE + 1] = { NULL }; enum xkb_file_type type; struct xkb_context *ctx = keymap->ctx; /* Collect section files and check for duplicates. */ for (file = (XkbFile *) file->defs; file; file = (XkbFile *) file->common.next) { if (file->file_type < FIRST_KEYMAP_FILE_TYPE || file->file_type > LAST_KEYMAP_FILE_TYPE) { if (file->file_type == FILE_TYPE_GEOMETRY) { log_vrb(ctx, 1, "Geometry sections are not supported; ignoring\n"); } else { log_err(ctx, "Cannot define %s in a keymap file\n", xkb_file_type_to_string(file->file_type)); } continue; } if (files[file->file_type]) { log_err(ctx, "More than one %s section in keymap file; " "All sections after the first ignored\n", xkb_file_type_to_string(file->file_type)); continue; } files[file->file_type] = file; } /* * Check that all required section were provided. * Report everything before failing. */ ok = true; for (type = FIRST_KEYMAP_FILE_TYPE; type <= LAST_KEYMAP_FILE_TYPE; type++) { if (files[type] == NULL) { log_err(ctx, "Required section %s missing from keymap\n", xkb_file_type_to_string(type)); ok = false; } } if (!ok) return false; /* Compile sections. */ for (type = FIRST_KEYMAP_FILE_TYPE; type <= LAST_KEYMAP_FILE_TYPE; type++) { log_dbg(ctx, "Compiling %s \"%s\"\n", xkb_file_type_to_string(type), files[type]->name); ok = compile_file_fns[type](files[type], keymap, merge); if (!ok) { log_err(ctx, "Failed to compile %s\n", xkb_file_type_to_string(type)); return false; } } return UpdateDerivedKeymapFields(keymap); }
169,095
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 ext4_io_end_t *ext4_init_io_end (struct inode *inode) { ext4_io_end_t *io = NULL; io = kmalloc(sizeof(*io), GFP_NOFS); if (io) { igrab(inode); io->inode = inode; io->flag = 0; io->offset = 0; io->size = 0; io->error = 0; INIT_WORK(&io->work, ext4_end_io_work); INIT_LIST_HEAD(&io->list); } return io; } Commit Message: ext4: use ext4_get_block_write in buffer write Allocate uninitialized extent before ext4 buffer write and convert the extent to initialized after io completes. The purpose is to make sure an extent can only be marked initialized after it has been written with new data so we can safely drop the i_mutex lock in ext4 DIO read without exposing stale data. This helps to improve multi-thread DIO read performance on high-speed disks. Skip the nobh and data=journal mount cases to make things simple for now. Signed-off-by: Jiaying Zhang <[email protected]> Signed-off-by: "Theodore Ts'o" <[email protected]> CWE ID:
static ext4_io_end_t *ext4_init_io_end (struct inode *inode) static ext4_io_end_t *ext4_init_io_end (struct inode *inode, gfp_t flags) { ext4_io_end_t *io = NULL; io = kmalloc(sizeof(*io), flags); if (io) { igrab(inode); io->inode = inode; io->flag = 0; io->offset = 0; io->size = 0; io->page = NULL; INIT_WORK(&io->work, ext4_end_io_work); INIT_LIST_HEAD(&io->list); } return io; }
167,546
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: my_object_increment (MyObject *obj, gint32 x, gint32 *ret, GError **error) { *ret = x +1; return TRUE; } Commit Message: CWE ID: CWE-264
my_object_increment (MyObject *obj, gint32 x, gint32 *ret, GError **error)
165,105
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 CL_InitRef( void ) { refimport_t ri; refexport_t *ret; #ifdef USE_RENDERER_DLOPEN GetRefAPI_t GetRefAPI; char dllName[MAX_OSPATH]; #endif Com_Printf( "----- Initializing Renderer ----\n" ); #ifdef USE_RENDERER_DLOPEN cl_renderer = Cvar_Get("cl_renderer", "opengl1", CVAR_ARCHIVE | CVAR_LATCH); Com_sprintf(dllName, sizeof(dllName), "renderer_sp_%s_" ARCH_STRING DLL_EXT, cl_renderer->string); if(!(rendererLib = Sys_LoadDll(dllName, qfalse)) && strcmp(cl_renderer->string, cl_renderer->resetString)) { Com_Printf("failed:\n\"%s\"\n", Sys_LibraryError()); Cvar_ForceReset("cl_renderer"); Com_sprintf(dllName, sizeof(dllName), "renderer_sp_opengl1_" ARCH_STRING DLL_EXT); rendererLib = Sys_LoadDll(dllName, qfalse); } if(!rendererLib) { Com_Printf("failed:\n\"%s\"\n", Sys_LibraryError()); Com_Error(ERR_FATAL, "Failed to load renderer"); } GetRefAPI = Sys_LoadFunction(rendererLib, "GetRefAPI"); if(!GetRefAPI) { Com_Error(ERR_FATAL, "Can't load symbol GetRefAPI: '%s'", Sys_LibraryError()); } #endif ri.Cmd_AddCommand = Cmd_AddCommand; ri.Cmd_RemoveCommand = Cmd_RemoveCommand; ri.Cmd_Argc = Cmd_Argc; ri.Cmd_Argv = Cmd_Argv; ri.Cmd_ExecuteText = Cbuf_ExecuteText; ri.Printf = CL_RefPrintf; ri.Error = Com_Error; ri.Milliseconds = CL_ScaledMilliseconds; ri.Z_Malloc = Z_Malloc; ri.Free = Z_Free; ri.Hunk_Clear = Hunk_ClearToMark; #ifdef HUNK_DEBUG ri.Hunk_AllocDebug = Hunk_AllocDebug; #else ri.Hunk_Alloc = Hunk_Alloc; #endif ri.Hunk_AllocateTempMemory = Hunk_AllocateTempMemory; ri.Hunk_FreeTempMemory = Hunk_FreeTempMemory; ri.CM_ClusterPVS = CM_ClusterPVS; ri.CM_DrawDebugSurface = CM_DrawDebugSurface; ri.FS_ReadFile = FS_ReadFile; ri.FS_FreeFile = FS_FreeFile; ri.FS_WriteFile = FS_WriteFile; ri.FS_FreeFileList = FS_FreeFileList; ri.FS_ListFiles = FS_ListFiles; ri.FS_FileIsInPAK = FS_FileIsInPAK; ri.FS_FileExists = FS_FileExists; ri.Cvar_Get = Cvar_Get; ri.Cvar_Set = Cvar_Set; ri.Cvar_SetValue = Cvar_SetValue; ri.Cvar_CheckRange = Cvar_CheckRange; ri.Cvar_VariableIntegerValue = Cvar_VariableIntegerValue; ri.CIN_UploadCinematic = CIN_UploadCinematic; ri.CIN_PlayCinematic = CIN_PlayCinematic; ri.CIN_RunCinematic = CIN_RunCinematic; ri.CL_WriteAVIVideoFrame = CL_WriteAVIVideoFrame; ri.IN_Init = IN_Init; ri.IN_Shutdown = IN_Shutdown; ri.IN_Restart = IN_Restart; ri.ftol = Q_ftol; ri.Sys_SetEnv = Sys_SetEnv; ri.Sys_GLimpSafeInit = Sys_GLimpSafeInit; ri.Sys_GLimpInit = Sys_GLimpInit; ri.Sys_LowPhysicalMemory = Sys_LowPhysicalMemory; ret = GetRefAPI( REF_API_VERSION, &ri ); if ( !ret ) { Com_Error( ERR_FATAL, "Couldn't initialize refresh" ); } re = *ret; Com_Printf( "---- Renderer Initialization Complete ----\n" ); Cvar_Set( "cl_paused", "0" ); } Commit Message: All: Don't load .pk3s as .dlls, and don't load user config files from .pk3s CWE ID: CWE-269
void CL_InitRef( void ) { refimport_t ri; refexport_t *ret; #ifdef USE_RENDERER_DLOPEN GetRefAPI_t GetRefAPI; char dllName[MAX_OSPATH]; #endif Com_Printf( "----- Initializing Renderer ----\n" ); #ifdef USE_RENDERER_DLOPEN cl_renderer = Cvar_Get("cl_renderer", "opengl1", CVAR_ARCHIVE | CVAR_LATCH | CVAR_PROTECTED); Com_sprintf(dllName, sizeof(dllName), "renderer_sp_%s_" ARCH_STRING DLL_EXT, cl_renderer->string); if(!(rendererLib = Sys_LoadDll(dllName, qfalse)) && strcmp(cl_renderer->string, cl_renderer->resetString)) { Com_Printf("failed:\n\"%s\"\n", Sys_LibraryError()); Cvar_ForceReset("cl_renderer"); Com_sprintf(dllName, sizeof(dllName), "renderer_sp_opengl1_" ARCH_STRING DLL_EXT); rendererLib = Sys_LoadDll(dllName, qfalse); } if(!rendererLib) { Com_Printf("failed:\n\"%s\"\n", Sys_LibraryError()); Com_Error(ERR_FATAL, "Failed to load renderer"); } GetRefAPI = Sys_LoadFunction(rendererLib, "GetRefAPI"); if(!GetRefAPI) { Com_Error(ERR_FATAL, "Can't load symbol GetRefAPI: '%s'", Sys_LibraryError()); } #endif ri.Cmd_AddCommand = Cmd_AddCommand; ri.Cmd_RemoveCommand = Cmd_RemoveCommand; ri.Cmd_Argc = Cmd_Argc; ri.Cmd_Argv = Cmd_Argv; ri.Cmd_ExecuteText = Cbuf_ExecuteText; ri.Printf = CL_RefPrintf; ri.Error = Com_Error; ri.Milliseconds = CL_ScaledMilliseconds; ri.Z_Malloc = Z_Malloc; ri.Free = Z_Free; ri.Hunk_Clear = Hunk_ClearToMark; #ifdef HUNK_DEBUG ri.Hunk_AllocDebug = Hunk_AllocDebug; #else ri.Hunk_Alloc = Hunk_Alloc; #endif ri.Hunk_AllocateTempMemory = Hunk_AllocateTempMemory; ri.Hunk_FreeTempMemory = Hunk_FreeTempMemory; ri.CM_ClusterPVS = CM_ClusterPVS; ri.CM_DrawDebugSurface = CM_DrawDebugSurface; ri.FS_ReadFile = FS_ReadFile; ri.FS_FreeFile = FS_FreeFile; ri.FS_WriteFile = FS_WriteFile; ri.FS_FreeFileList = FS_FreeFileList; ri.FS_ListFiles = FS_ListFiles; ri.FS_FileIsInPAK = FS_FileIsInPAK; ri.FS_FileExists = FS_FileExists; ri.Cvar_Get = Cvar_Get; ri.Cvar_Set = Cvar_Set; ri.Cvar_SetValue = Cvar_SetValue; ri.Cvar_CheckRange = Cvar_CheckRange; ri.Cvar_VariableIntegerValue = Cvar_VariableIntegerValue; ri.CIN_UploadCinematic = CIN_UploadCinematic; ri.CIN_PlayCinematic = CIN_PlayCinematic; ri.CIN_RunCinematic = CIN_RunCinematic; ri.CL_WriteAVIVideoFrame = CL_WriteAVIVideoFrame; ri.IN_Init = IN_Init; ri.IN_Shutdown = IN_Shutdown; ri.IN_Restart = IN_Restart; ri.ftol = Q_ftol; ri.Sys_SetEnv = Sys_SetEnv; ri.Sys_GLimpSafeInit = Sys_GLimpSafeInit; ri.Sys_GLimpInit = Sys_GLimpInit; ri.Sys_LowPhysicalMemory = Sys_LowPhysicalMemory; ret = GetRefAPI( REF_API_VERSION, &ri ); if ( !ret ) { Com_Error( ERR_FATAL, "Couldn't initialize refresh" ); } re = *ret; Com_Printf( "---- Renderer Initialization Complete ----\n" ); Cvar_Set( "cl_paused", "0" ); }
170,086
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 sent_status_t send_data_to_app(int fd, BT_HDR *p_buf) { if (p_buf->len == 0) return SENT_ALL; ssize_t sent = send(fd, p_buf->data + p_buf->offset, p_buf->len, MSG_DONTWAIT); if (sent == -1) { if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) return SENT_NONE; LOG_ERROR("%s error writing RFCOMM data back to app: %s", __func__, strerror(errno)); return SENT_FAILED; } if (sent == 0) return SENT_FAILED; if (sent == p_buf->len) return SENT_ALL; p_buf->offset += sent; p_buf->len -= sent; return SENT_PARTIAL; } Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process Bug: 28885210 Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360 Conflicts: btif/co/bta_hh_co.c btif/src/btif_core.c Merge conflict resolution of ag/1161415 (referencing ag/1164670) - Directly into mnc-mr2-release CWE ID: CWE-284
static sent_status_t send_data_to_app(int fd, BT_HDR *p_buf) { if (p_buf->len == 0) return SENT_ALL; ssize_t sent = TEMP_FAILURE_RETRY(send(fd, p_buf->data + p_buf->offset, p_buf->len, MSG_DONTWAIT)); if (sent == -1) { if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) return SENT_NONE; LOG_ERROR("%s error writing RFCOMM data back to app: %s", __func__, strerror(errno)); return SENT_FAILED; } if (sent == 0) return SENT_FAILED; if (sent == p_buf->len) return SENT_ALL; p_buf->offset += sent; p_buf->len -= sent; return SENT_PARTIAL; }
173,458
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 bmp_read_info_header(FILE* IN, OPJ_BITMAPINFOHEADER* header) { memset(header, 0, sizeof(*header)); /* INFO HEADER */ /* ------------- */ header->biSize = (OPJ_UINT32)getc(IN); header->biSize |= (OPJ_UINT32)getc(IN) << 8; header->biSize |= (OPJ_UINT32)getc(IN) << 16; header->biSize |= (OPJ_UINT32)getc(IN) << 24; switch (header->biSize) { case 12U: /* BITMAPCOREHEADER */ case 40U: /* BITMAPINFOHEADER */ case 52U: /* BITMAPV2INFOHEADER */ case 56U: /* BITMAPV3INFOHEADER */ case 108U: /* BITMAPV4HEADER */ case 124U: /* BITMAPV5HEADER */ break; default: fprintf(stderr, "Error, unknown BMP header size %d\n", header->biSize); return OPJ_FALSE; } header->biWidth = (OPJ_UINT32)getc(IN); header->biWidth |= (OPJ_UINT32)getc(IN) << 8; header->biWidth |= (OPJ_UINT32)getc(IN) << 16; header->biWidth |= (OPJ_UINT32)getc(IN) << 24; header->biHeight = (OPJ_UINT32)getc(IN); header->biHeight |= (OPJ_UINT32)getc(IN) << 8; header->biHeight |= (OPJ_UINT32)getc(IN) << 16; header->biHeight |= (OPJ_UINT32)getc(IN) << 24; header->biPlanes = (OPJ_UINT16)getc(IN); header->biPlanes |= (OPJ_UINT16)((OPJ_UINT32)getc(IN) << 8); header->biBitCount = (OPJ_UINT16)getc(IN); header->biBitCount |= (OPJ_UINT16)((OPJ_UINT32)getc(IN) << 8); if (header->biSize >= 40U) { header->biCompression = (OPJ_UINT32)getc(IN); header->biCompression |= (OPJ_UINT32)getc(IN) << 8; header->biCompression |= (OPJ_UINT32)getc(IN) << 16; header->biCompression |= (OPJ_UINT32)getc(IN) << 24; header->biSizeImage = (OPJ_UINT32)getc(IN); header->biSizeImage |= (OPJ_UINT32)getc(IN) << 8; header->biSizeImage |= (OPJ_UINT32)getc(IN) << 16; header->biSizeImage |= (OPJ_UINT32)getc(IN) << 24; header->biXpelsPerMeter = (OPJ_UINT32)getc(IN); header->biXpelsPerMeter |= (OPJ_UINT32)getc(IN) << 8; header->biXpelsPerMeter |= (OPJ_UINT32)getc(IN) << 16; header->biXpelsPerMeter |= (OPJ_UINT32)getc(IN) << 24; header->biYpelsPerMeter = (OPJ_UINT32)getc(IN); header->biYpelsPerMeter |= (OPJ_UINT32)getc(IN) << 8; header->biYpelsPerMeter |= (OPJ_UINT32)getc(IN) << 16; header->biYpelsPerMeter |= (OPJ_UINT32)getc(IN) << 24; header->biClrUsed = (OPJ_UINT32)getc(IN); header->biClrUsed |= (OPJ_UINT32)getc(IN) << 8; header->biClrUsed |= (OPJ_UINT32)getc(IN) << 16; header->biClrUsed |= (OPJ_UINT32)getc(IN) << 24; header->biClrImportant = (OPJ_UINT32)getc(IN); header->biClrImportant |= (OPJ_UINT32)getc(IN) << 8; header->biClrImportant |= (OPJ_UINT32)getc(IN) << 16; header->biClrImportant |= (OPJ_UINT32)getc(IN) << 24; } if (header->biSize >= 56U) { header->biRedMask = (OPJ_UINT32)getc(IN); header->biRedMask |= (OPJ_UINT32)getc(IN) << 8; header->biRedMask |= (OPJ_UINT32)getc(IN) << 16; header->biRedMask |= (OPJ_UINT32)getc(IN) << 24; header->biGreenMask = (OPJ_UINT32)getc(IN); header->biGreenMask |= (OPJ_UINT32)getc(IN) << 8; header->biGreenMask |= (OPJ_UINT32)getc(IN) << 16; header->biGreenMask |= (OPJ_UINT32)getc(IN) << 24; header->biBlueMask = (OPJ_UINT32)getc(IN); header->biBlueMask |= (OPJ_UINT32)getc(IN) << 8; header->biBlueMask |= (OPJ_UINT32)getc(IN) << 16; header->biBlueMask |= (OPJ_UINT32)getc(IN) << 24; header->biAlphaMask = (OPJ_UINT32)getc(IN); header->biAlphaMask |= (OPJ_UINT32)getc(IN) << 8; header->biAlphaMask |= (OPJ_UINT32)getc(IN) << 16; header->biAlphaMask |= (OPJ_UINT32)getc(IN) << 24; } if (header->biSize >= 108U) { header->biColorSpaceType = (OPJ_UINT32)getc(IN); header->biColorSpaceType |= (OPJ_UINT32)getc(IN) << 8; header->biColorSpaceType |= (OPJ_UINT32)getc(IN) << 16; header->biColorSpaceType |= (OPJ_UINT32)getc(IN) << 24; if (fread(&(header->biColorSpaceEP), 1U, sizeof(header->biColorSpaceEP), IN) != sizeof(header->biColorSpaceEP)) { fprintf(stderr, "Error, can't read BMP header\n"); return OPJ_FALSE; } header->biRedGamma = (OPJ_UINT32)getc(IN); header->biRedGamma |= (OPJ_UINT32)getc(IN) << 8; header->biRedGamma |= (OPJ_UINT32)getc(IN) << 16; header->biRedGamma |= (OPJ_UINT32)getc(IN) << 24; header->biGreenGamma = (OPJ_UINT32)getc(IN); header->biGreenGamma |= (OPJ_UINT32)getc(IN) << 8; header->biGreenGamma |= (OPJ_UINT32)getc(IN) << 16; header->biGreenGamma |= (OPJ_UINT32)getc(IN) << 24; header->biBlueGamma = (OPJ_UINT32)getc(IN); header->biBlueGamma |= (OPJ_UINT32)getc(IN) << 8; header->biBlueGamma |= (OPJ_UINT32)getc(IN) << 16; header->biBlueGamma |= (OPJ_UINT32)getc(IN) << 24; } if (header->biSize >= 124U) { header->biIntent = (OPJ_UINT32)getc(IN); header->biIntent |= (OPJ_UINT32)getc(IN) << 8; header->biIntent |= (OPJ_UINT32)getc(IN) << 16; header->biIntent |= (OPJ_UINT32)getc(IN) << 24; header->biIccProfileData = (OPJ_UINT32)getc(IN); header->biIccProfileData |= (OPJ_UINT32)getc(IN) << 8; header->biIccProfileData |= (OPJ_UINT32)getc(IN) << 16; header->biIccProfileData |= (OPJ_UINT32)getc(IN) << 24; header->biIccProfileSize = (OPJ_UINT32)getc(IN); header->biIccProfileSize |= (OPJ_UINT32)getc(IN) << 8; header->biIccProfileSize |= (OPJ_UINT32)getc(IN) << 16; header->biIccProfileSize |= (OPJ_UINT32)getc(IN) << 24; header->biReserved = (OPJ_UINT32)getc(IN); header->biReserved |= (OPJ_UINT32)getc(IN) << 8; header->biReserved |= (OPJ_UINT32)getc(IN) << 16; header->biReserved |= (OPJ_UINT32)getc(IN) << 24; } return OPJ_TRUE; } Commit Message: bmp_read_info_header(): reject bmp files with biBitCount == 0 (#983) CWE ID: CWE-119
static OPJ_BOOL bmp_read_info_header(FILE* IN, OPJ_BITMAPINFOHEADER* header) { memset(header, 0, sizeof(*header)); /* INFO HEADER */ /* ------------- */ header->biSize = (OPJ_UINT32)getc(IN); header->biSize |= (OPJ_UINT32)getc(IN) << 8; header->biSize |= (OPJ_UINT32)getc(IN) << 16; header->biSize |= (OPJ_UINT32)getc(IN) << 24; switch (header->biSize) { case 12U: /* BITMAPCOREHEADER */ case 40U: /* BITMAPINFOHEADER */ case 52U: /* BITMAPV2INFOHEADER */ case 56U: /* BITMAPV3INFOHEADER */ case 108U: /* BITMAPV4HEADER */ case 124U: /* BITMAPV5HEADER */ break; default: fprintf(stderr, "Error, unknown BMP header size %d\n", header->biSize); return OPJ_FALSE; } header->biWidth = (OPJ_UINT32)getc(IN); header->biWidth |= (OPJ_UINT32)getc(IN) << 8; header->biWidth |= (OPJ_UINT32)getc(IN) << 16; header->biWidth |= (OPJ_UINT32)getc(IN) << 24; header->biHeight = (OPJ_UINT32)getc(IN); header->biHeight |= (OPJ_UINT32)getc(IN) << 8; header->biHeight |= (OPJ_UINT32)getc(IN) << 16; header->biHeight |= (OPJ_UINT32)getc(IN) << 24; header->biPlanes = (OPJ_UINT16)getc(IN); header->biPlanes |= (OPJ_UINT16)((OPJ_UINT32)getc(IN) << 8); header->biBitCount = (OPJ_UINT16)getc(IN); header->biBitCount |= (OPJ_UINT16)((OPJ_UINT32)getc(IN) << 8); if (header->biBitCount == 0) { fprintf(stderr, "Error, invalid biBitCount %d\n", 0); return OPJ_FALSE; } if (header->biSize >= 40U) { header->biCompression = (OPJ_UINT32)getc(IN); header->biCompression |= (OPJ_UINT32)getc(IN) << 8; header->biCompression |= (OPJ_UINT32)getc(IN) << 16; header->biCompression |= (OPJ_UINT32)getc(IN) << 24; header->biSizeImage = (OPJ_UINT32)getc(IN); header->biSizeImage |= (OPJ_UINT32)getc(IN) << 8; header->biSizeImage |= (OPJ_UINT32)getc(IN) << 16; header->biSizeImage |= (OPJ_UINT32)getc(IN) << 24; header->biXpelsPerMeter = (OPJ_UINT32)getc(IN); header->biXpelsPerMeter |= (OPJ_UINT32)getc(IN) << 8; header->biXpelsPerMeter |= (OPJ_UINT32)getc(IN) << 16; header->biXpelsPerMeter |= (OPJ_UINT32)getc(IN) << 24; header->biYpelsPerMeter = (OPJ_UINT32)getc(IN); header->biYpelsPerMeter |= (OPJ_UINT32)getc(IN) << 8; header->biYpelsPerMeter |= (OPJ_UINT32)getc(IN) << 16; header->biYpelsPerMeter |= (OPJ_UINT32)getc(IN) << 24; header->biClrUsed = (OPJ_UINT32)getc(IN); header->biClrUsed |= (OPJ_UINT32)getc(IN) << 8; header->biClrUsed |= (OPJ_UINT32)getc(IN) << 16; header->biClrUsed |= (OPJ_UINT32)getc(IN) << 24; header->biClrImportant = (OPJ_UINT32)getc(IN); header->biClrImportant |= (OPJ_UINT32)getc(IN) << 8; header->biClrImportant |= (OPJ_UINT32)getc(IN) << 16; header->biClrImportant |= (OPJ_UINT32)getc(IN) << 24; } if (header->biSize >= 56U) { header->biRedMask = (OPJ_UINT32)getc(IN); header->biRedMask |= (OPJ_UINT32)getc(IN) << 8; header->biRedMask |= (OPJ_UINT32)getc(IN) << 16; header->biRedMask |= (OPJ_UINT32)getc(IN) << 24; header->biGreenMask = (OPJ_UINT32)getc(IN); header->biGreenMask |= (OPJ_UINT32)getc(IN) << 8; header->biGreenMask |= (OPJ_UINT32)getc(IN) << 16; header->biGreenMask |= (OPJ_UINT32)getc(IN) << 24; header->biBlueMask = (OPJ_UINT32)getc(IN); header->biBlueMask |= (OPJ_UINT32)getc(IN) << 8; header->biBlueMask |= (OPJ_UINT32)getc(IN) << 16; header->biBlueMask |= (OPJ_UINT32)getc(IN) << 24; header->biAlphaMask = (OPJ_UINT32)getc(IN); header->biAlphaMask |= (OPJ_UINT32)getc(IN) << 8; header->biAlphaMask |= (OPJ_UINT32)getc(IN) << 16; header->biAlphaMask |= (OPJ_UINT32)getc(IN) << 24; } if (header->biSize >= 108U) { header->biColorSpaceType = (OPJ_UINT32)getc(IN); header->biColorSpaceType |= (OPJ_UINT32)getc(IN) << 8; header->biColorSpaceType |= (OPJ_UINT32)getc(IN) << 16; header->biColorSpaceType |= (OPJ_UINT32)getc(IN) << 24; if (fread(&(header->biColorSpaceEP), 1U, sizeof(header->biColorSpaceEP), IN) != sizeof(header->biColorSpaceEP)) { fprintf(stderr, "Error, can't read BMP header\n"); return OPJ_FALSE; } header->biRedGamma = (OPJ_UINT32)getc(IN); header->biRedGamma |= (OPJ_UINT32)getc(IN) << 8; header->biRedGamma |= (OPJ_UINT32)getc(IN) << 16; header->biRedGamma |= (OPJ_UINT32)getc(IN) << 24; header->biGreenGamma = (OPJ_UINT32)getc(IN); header->biGreenGamma |= (OPJ_UINT32)getc(IN) << 8; header->biGreenGamma |= (OPJ_UINT32)getc(IN) << 16; header->biGreenGamma |= (OPJ_UINT32)getc(IN) << 24; header->biBlueGamma = (OPJ_UINT32)getc(IN); header->biBlueGamma |= (OPJ_UINT32)getc(IN) << 8; header->biBlueGamma |= (OPJ_UINT32)getc(IN) << 16; header->biBlueGamma |= (OPJ_UINT32)getc(IN) << 24; } if (header->biSize >= 124U) { header->biIntent = (OPJ_UINT32)getc(IN); header->biIntent |= (OPJ_UINT32)getc(IN) << 8; header->biIntent |= (OPJ_UINT32)getc(IN) << 16; header->biIntent |= (OPJ_UINT32)getc(IN) << 24; header->biIccProfileData = (OPJ_UINT32)getc(IN); header->biIccProfileData |= (OPJ_UINT32)getc(IN) << 8; header->biIccProfileData |= (OPJ_UINT32)getc(IN) << 16; header->biIccProfileData |= (OPJ_UINT32)getc(IN) << 24; header->biIccProfileSize = (OPJ_UINT32)getc(IN); header->biIccProfileSize |= (OPJ_UINT32)getc(IN) << 8; header->biIccProfileSize |= (OPJ_UINT32)getc(IN) << 16; header->biIccProfileSize |= (OPJ_UINT32)getc(IN) << 24; header->biReserved = (OPJ_UINT32)getc(IN); header->biReserved |= (OPJ_UINT32)getc(IN) << 8; header->biReserved |= (OPJ_UINT32)getc(IN) << 16; header->biReserved |= (OPJ_UINT32)getc(IN) << 24; } return OPJ_TRUE; }
167,932
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: Response DOMHandler::SetFileInputFiles( std::unique_ptr<protocol::Array<std::string>> files, Maybe<DOM::NodeId> node_id, Maybe<DOM::BackendNodeId> backend_node_id, Maybe<String> in_object_id) { if (host_) { for (size_t i = 0; i < files->length(); i++) { #if defined(OS_WIN) ChildProcessSecurityPolicyImpl::GetInstance()->GrantReadFile( host_->GetProcess()->GetID(), base::FilePath(base::UTF8ToUTF16(files->get(i)))); #else ChildProcessSecurityPolicyImpl::GetInstance()->GrantReadFile( host_->GetProcess()->GetID(), base::FilePath(files->get(i))); #endif // OS_WIN } } return Response::FallThrough(); } Commit Message: [DevTools] Guard DOM.setFileInputFiles under MayAffectLocalFiles Bug: 805557 Change-Id: Ib6f37ec6e1d091ee54621cc0c5c44f1a6beab10f Reviewed-on: https://chromium-review.googlesource.com/c/1334847 Reviewed-by: Pavel Feldman <[email protected]> Commit-Queue: Dmitry Gozman <[email protected]> Cr-Commit-Position: refs/heads/master@{#607902} CWE ID: CWE-254
Response DOMHandler::SetFileInputFiles( std::unique_ptr<protocol::Array<std::string>> files, Maybe<DOM::NodeId> node_id, Maybe<DOM::BackendNodeId> backend_node_id, Maybe<String> in_object_id) { if (!allow_file_access_) return Response::Error("Not allowed"); if (host_) { for (size_t i = 0; i < files->length(); i++) { #if defined(OS_WIN) ChildProcessSecurityPolicyImpl::GetInstance()->GrantReadFile( host_->GetProcess()->GetID(), base::FilePath(base::UTF8ToUTF16(files->get(i)))); #else ChildProcessSecurityPolicyImpl::GetInstance()->GrantReadFile( host_->GetProcess()->GetID(), base::FilePath(files->get(i))); #endif // OS_WIN } } return Response::FallThrough(); }
173,113
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: psf_fwrite (const void *ptr, sf_count_t bytes, sf_count_t items, SF_PRIVATE *psf) { sf_count_t total = 0 ; ssize_t count ; if (psf->virtual_io) return psf->vio.write (ptr, bytes*items, psf->vio_user_data) / bytes ; items *= bytes ; /* Do this check after the multiplication above. */ if (items <= 0) return 0 ; while (items > 0) { /* Break the writes down to a sensible size. */ count = (items > SENSIBLE_SIZE) ? SENSIBLE_SIZE : items ; count = write (psf->file.filedes, ((const char*) ptr) + total, count) ; if (count == -1) { if (errno == EINTR) continue ; psf_log_syserr (psf, errno) ; break ; } ; if (count == 0) break ; total += count ; items -= count ; } ; if (psf->is_pipe) psf->pipeoffset += total ; return total / bytes ; } /* psf_fwrite */ Commit Message: src/file_io.c : Prevent potential divide-by-zero. Closes: https://github.com/erikd/libsndfile/issues/92 CWE ID: CWE-189
psf_fwrite (const void *ptr, sf_count_t bytes, sf_count_t items, SF_PRIVATE *psf) { sf_count_t total = 0 ; ssize_t count ; if (bytes == 0 || items == 0) return 0 ; if (psf->virtual_io) return psf->vio.write (ptr, bytes*items, psf->vio_user_data) / bytes ; items *= bytes ; /* Do this check after the multiplication above. */ if (items <= 0) return 0 ; while (items > 0) { /* Break the writes down to a sensible size. */ count = (items > SENSIBLE_SIZE) ? SENSIBLE_SIZE : items ; count = write (psf->file.filedes, ((const char*) ptr) + total, count) ; if (count == -1) { if (errno == EINTR) continue ; psf_log_syserr (psf, errno) ; break ; } ; if (count == 0) break ; total += count ; items -= count ; } ; if (psf->is_pipe) psf->pipeoffset += total ; return total / bytes ; } /* psf_fwrite */
166,754
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 SessionRestore::IsRestoring(const Profile* profile) { return (profiles_getting_restored && profiles_getting_restored->find(profile) != profiles_getting_restored->end()); } Commit Message: Lands http://codereview.chromium.org/9316065/ for Marja. I reviewed this, so I'm using TBR to land it. Don't crash if multiple SessionRestoreImpl:s refer to the same Profile. It shouldn't ever happen but it seems to happen anyway. BUG=111238 TEST=NONE [email protected] [email protected] Review URL: https://chromiumcodereview.appspot.com/9343005 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@120648 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
bool SessionRestore::IsRestoring(const Profile* profile) { if (active_session_restorers == NULL) return false; for (std::set<SessionRestoreImpl*>::const_iterator it = active_session_restorers->begin(); it != active_session_restorers->end(); ++it) { if ((*it)->profile() == profile) return true; } return false; }
171,036
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 __ip6_datagram_connect(struct sock *sk, struct sockaddr *uaddr, int addr_len) { struct sockaddr_in6 *usin = (struct sockaddr_in6 *) uaddr; struct inet_sock *inet = inet_sk(sk); struct ipv6_pinfo *np = inet6_sk(sk); struct in6_addr *daddr, *final_p, final; struct dst_entry *dst; struct flowi6 fl6; struct ip6_flowlabel *flowlabel = NULL; struct ipv6_txoptions *opt; int addr_type; int err; if (usin->sin6_family == AF_INET) { if (__ipv6_only_sock(sk)) return -EAFNOSUPPORT; err = __ip4_datagram_connect(sk, uaddr, addr_len); goto ipv4_connected; } if (addr_len < SIN6_LEN_RFC2133) return -EINVAL; if (usin->sin6_family != AF_INET6) return -EAFNOSUPPORT; memset(&fl6, 0, sizeof(fl6)); if (np->sndflow) { fl6.flowlabel = usin->sin6_flowinfo&IPV6_FLOWINFO_MASK; if (fl6.flowlabel&IPV6_FLOWLABEL_MASK) { flowlabel = fl6_sock_lookup(sk, fl6.flowlabel); if (!flowlabel) return -EINVAL; } } addr_type = ipv6_addr_type(&usin->sin6_addr); if (addr_type == IPV6_ADDR_ANY) { /* * connect to self */ usin->sin6_addr.s6_addr[15] = 0x01; } daddr = &usin->sin6_addr; if (addr_type == IPV6_ADDR_MAPPED) { struct sockaddr_in sin; if (__ipv6_only_sock(sk)) { err = -ENETUNREACH; goto out; } sin.sin_family = AF_INET; sin.sin_addr.s_addr = daddr->s6_addr32[3]; sin.sin_port = usin->sin6_port; err = __ip4_datagram_connect(sk, (struct sockaddr *) &sin, sizeof(sin)); ipv4_connected: if (err) goto out; ipv6_addr_set_v4mapped(inet->inet_daddr, &sk->sk_v6_daddr); if (ipv6_addr_any(&np->saddr) || ipv6_mapped_addr_any(&np->saddr)) ipv6_addr_set_v4mapped(inet->inet_saddr, &np->saddr); if (ipv6_addr_any(&sk->sk_v6_rcv_saddr) || ipv6_mapped_addr_any(&sk->sk_v6_rcv_saddr)) { ipv6_addr_set_v4mapped(inet->inet_rcv_saddr, &sk->sk_v6_rcv_saddr); if (sk->sk_prot->rehash) sk->sk_prot->rehash(sk); } goto out; } if (__ipv6_addr_needs_scope_id(addr_type)) { if (addr_len >= sizeof(struct sockaddr_in6) && usin->sin6_scope_id) { if (sk->sk_bound_dev_if && sk->sk_bound_dev_if != usin->sin6_scope_id) { err = -EINVAL; goto out; } sk->sk_bound_dev_if = usin->sin6_scope_id; } if (!sk->sk_bound_dev_if && (addr_type & IPV6_ADDR_MULTICAST)) sk->sk_bound_dev_if = np->mcast_oif; /* Connect to link-local address requires an interface */ if (!sk->sk_bound_dev_if) { err = -EINVAL; goto out; } } sk->sk_v6_daddr = *daddr; np->flow_label = fl6.flowlabel; inet->inet_dport = usin->sin6_port; /* * Check for a route to destination an obtain the * destination cache for it. */ fl6.flowi6_proto = sk->sk_protocol; fl6.daddr = sk->sk_v6_daddr; fl6.saddr = np->saddr; fl6.flowi6_oif = sk->sk_bound_dev_if; fl6.flowi6_mark = sk->sk_mark; fl6.fl6_dport = inet->inet_dport; fl6.fl6_sport = inet->inet_sport; if (!fl6.flowi6_oif && (addr_type&IPV6_ADDR_MULTICAST)) fl6.flowi6_oif = np->mcast_oif; security_sk_classify_flow(sk, flowi6_to_flowi(&fl6)); opt = flowlabel ? flowlabel->opt : np->opt; final_p = fl6_update_dst(&fl6, opt, &final); dst = ip6_dst_lookup_flow(sk, &fl6, final_p); err = 0; if (IS_ERR(dst)) { err = PTR_ERR(dst); goto out; } /* source address lookup done in ip6_dst_lookup */ if (ipv6_addr_any(&np->saddr)) np->saddr = fl6.saddr; if (ipv6_addr_any(&sk->sk_v6_rcv_saddr)) { sk->sk_v6_rcv_saddr = fl6.saddr; inet->inet_rcv_saddr = LOOPBACK4_IPV6; if (sk->sk_prot->rehash) sk->sk_prot->rehash(sk); } ip6_dst_store(sk, dst, ipv6_addr_equal(&fl6.daddr, &sk->sk_v6_daddr) ? &sk->sk_v6_daddr : NULL, #ifdef CONFIG_IPV6_SUBTREES ipv6_addr_equal(&fl6.saddr, &np->saddr) ? &np->saddr : #endif NULL); sk->sk_state = TCP_ESTABLISHED; sk_set_txhash(sk); out: fl6_sock_release(flowlabel); return err; } 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
static int __ip6_datagram_connect(struct sock *sk, struct sockaddr *uaddr, int addr_len) { struct sockaddr_in6 *usin = (struct sockaddr_in6 *) uaddr; struct inet_sock *inet = inet_sk(sk); struct ipv6_pinfo *np = inet6_sk(sk); struct in6_addr *daddr, *final_p, final; struct dst_entry *dst; struct flowi6 fl6; struct ip6_flowlabel *flowlabel = NULL; struct ipv6_txoptions *opt; int addr_type; int err; if (usin->sin6_family == AF_INET) { if (__ipv6_only_sock(sk)) return -EAFNOSUPPORT; err = __ip4_datagram_connect(sk, uaddr, addr_len); goto ipv4_connected; } if (addr_len < SIN6_LEN_RFC2133) return -EINVAL; if (usin->sin6_family != AF_INET6) return -EAFNOSUPPORT; memset(&fl6, 0, sizeof(fl6)); if (np->sndflow) { fl6.flowlabel = usin->sin6_flowinfo&IPV6_FLOWINFO_MASK; if (fl6.flowlabel&IPV6_FLOWLABEL_MASK) { flowlabel = fl6_sock_lookup(sk, fl6.flowlabel); if (!flowlabel) return -EINVAL; } } addr_type = ipv6_addr_type(&usin->sin6_addr); if (addr_type == IPV6_ADDR_ANY) { /* * connect to self */ usin->sin6_addr.s6_addr[15] = 0x01; } daddr = &usin->sin6_addr; if (addr_type == IPV6_ADDR_MAPPED) { struct sockaddr_in sin; if (__ipv6_only_sock(sk)) { err = -ENETUNREACH; goto out; } sin.sin_family = AF_INET; sin.sin_addr.s_addr = daddr->s6_addr32[3]; sin.sin_port = usin->sin6_port; err = __ip4_datagram_connect(sk, (struct sockaddr *) &sin, sizeof(sin)); ipv4_connected: if (err) goto out; ipv6_addr_set_v4mapped(inet->inet_daddr, &sk->sk_v6_daddr); if (ipv6_addr_any(&np->saddr) || ipv6_mapped_addr_any(&np->saddr)) ipv6_addr_set_v4mapped(inet->inet_saddr, &np->saddr); if (ipv6_addr_any(&sk->sk_v6_rcv_saddr) || ipv6_mapped_addr_any(&sk->sk_v6_rcv_saddr)) { ipv6_addr_set_v4mapped(inet->inet_rcv_saddr, &sk->sk_v6_rcv_saddr); if (sk->sk_prot->rehash) sk->sk_prot->rehash(sk); } goto out; } if (__ipv6_addr_needs_scope_id(addr_type)) { if (addr_len >= sizeof(struct sockaddr_in6) && usin->sin6_scope_id) { if (sk->sk_bound_dev_if && sk->sk_bound_dev_if != usin->sin6_scope_id) { err = -EINVAL; goto out; } sk->sk_bound_dev_if = usin->sin6_scope_id; } if (!sk->sk_bound_dev_if && (addr_type & IPV6_ADDR_MULTICAST)) sk->sk_bound_dev_if = np->mcast_oif; /* Connect to link-local address requires an interface */ if (!sk->sk_bound_dev_if) { err = -EINVAL; goto out; } } sk->sk_v6_daddr = *daddr; np->flow_label = fl6.flowlabel; inet->inet_dport = usin->sin6_port; /* * Check for a route to destination an obtain the * destination cache for it. */ fl6.flowi6_proto = sk->sk_protocol; fl6.daddr = sk->sk_v6_daddr; fl6.saddr = np->saddr; fl6.flowi6_oif = sk->sk_bound_dev_if; fl6.flowi6_mark = sk->sk_mark; fl6.fl6_dport = inet->inet_dport; fl6.fl6_sport = inet->inet_sport; if (!fl6.flowi6_oif && (addr_type&IPV6_ADDR_MULTICAST)) fl6.flowi6_oif = np->mcast_oif; security_sk_classify_flow(sk, flowi6_to_flowi(&fl6)); rcu_read_lock(); opt = flowlabel ? flowlabel->opt : rcu_dereference(np->opt); final_p = fl6_update_dst(&fl6, opt, &final); rcu_read_unlock(); dst = ip6_dst_lookup_flow(sk, &fl6, final_p); err = 0; if (IS_ERR(dst)) { err = PTR_ERR(dst); goto out; } /* source address lookup done in ip6_dst_lookup */ if (ipv6_addr_any(&np->saddr)) np->saddr = fl6.saddr; if (ipv6_addr_any(&sk->sk_v6_rcv_saddr)) { sk->sk_v6_rcv_saddr = fl6.saddr; inet->inet_rcv_saddr = LOOPBACK4_IPV6; if (sk->sk_prot->rehash) sk->sk_prot->rehash(sk); } ip6_dst_store(sk, dst, ipv6_addr_equal(&fl6.daddr, &sk->sk_v6_daddr) ? &sk->sk_v6_daddr : NULL, #ifdef CONFIG_IPV6_SUBTREES ipv6_addr_equal(&fl6.saddr, &np->saddr) ? &np->saddr : #endif NULL); sk->sk_state = TCP_ESTABLISHED; sk_set_txhash(sk); out: fl6_sock_release(flowlabel); return err; }
167,329
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 am_check_url(request_rec *r, const char *url) { const char *i; for (i = url; *i; i++) { if (*i >= 0 && *i < ' ') { /* Deny all control-characters. */ AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, HTTP_BAD_REQUEST, r, "Control character detected in URL."); return HTTP_BAD_REQUEST; } } return OK; } Commit Message: Fix redirect URL validation bypass It turns out that browsers silently convert backslash characters into forward slashes, while apr_uri_parse() does not. This mismatch allows an attacker to bypass the redirect URL validation by using an URL like: https://sp.example.org/mellon/logout?ReturnTo=https:%5c%5cmalicious.example.org/ mod_auth_mellon will assume that it is a relative URL and allow the request to pass through, while the browsers will use it as an absolute url and redirect to https://malicious.example.org/ . This patch fixes this issue by rejecting all redirect URLs with backslashes. CWE ID: CWE-601
int am_check_url(request_rec *r, const char *url) { const char *i; for (i = url; *i; i++) { if (*i >= 0 && *i < ' ') { /* Deny all control-characters. */ AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, HTTP_BAD_REQUEST, r, "Control character detected in URL."); return HTTP_BAD_REQUEST; } if (*i == '\\') { /* Reject backslash character, as it can be used to bypass * redirect URL validation. */ AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, HTTP_BAD_REQUEST, r, "Backslash character detected in URL."); return HTTP_BAD_REQUEST; } } return OK; }
169,749
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 main(int argc, char **argv) { int frame_cnt = 0; FILE *outfile = NULL; vpx_codec_ctx_t codec; const VpxInterface *decoder = NULL; VpxVideoReader *reader = NULL; const VpxVideoInfo *info = NULL; int n = 0; int m = 0; int is_range = 0; char *nptr = NULL; exec_name = argv[0]; if (argc != 4) die("Invalid number of arguments."); reader = vpx_video_reader_open(argv[1]); if (!reader) die("Failed to open %s for reading.", argv[1]); if (!(outfile = fopen(argv[2], "wb"))) die("Failed to open %s for writing.", argv[2]); n = strtol(argv[3], &nptr, 0); m = strtol(nptr + 1, NULL, 0); is_range = (*nptr == '-'); if (!n || !m || (*nptr != '-' && *nptr != '/')) die("Couldn't parse pattern %s.\n", argv[3]); info = vpx_video_reader_get_info(reader); decoder = get_vpx_decoder_by_fourcc(info->codec_fourcc); if (!decoder) die("Unknown input codec."); printf("Using %s\n", vpx_codec_iface_name(decoder->interface())); if (vpx_codec_dec_init(&codec, decoder->interface(), NULL, 0)) die_codec(&codec, "Failed to initialize decoder."); while (vpx_video_reader_read_frame(reader)) { vpx_codec_iter_t iter = NULL; vpx_image_t *img = NULL; size_t frame_size = 0; int skip; const unsigned char *frame = vpx_video_reader_get_frame(reader, &frame_size); if (vpx_codec_decode(&codec, frame, (unsigned int)frame_size, NULL, 0)) die_codec(&codec, "Failed to decode frame."); ++frame_cnt; skip = (is_range && frame_cnt >= n && frame_cnt <= m) || (!is_range && m - (frame_cnt - 1) % m <= n); if (!skip) { putc('.', stdout); while ((img = vpx_codec_get_frame(&codec, &iter)) != NULL) vpx_img_write(img, outfile); } else { putc('X', stdout); } fflush(stdout); } printf("Processed %d frames.\n", frame_cnt); if (vpx_codec_destroy(&codec)) die_codec(&codec, "Failed to destroy codec."); printf("Play: ffplay -f rawvideo -pix_fmt yuv420p -s %dx%d %s\n", info->frame_width, info->frame_height, argv[2]); vpx_video_reader_close(reader); fclose(outfile); return EXIT_SUCCESS; } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119
int main(int argc, char **argv) { int frame_cnt = 0; FILE *outfile = NULL; vpx_codec_ctx_t codec; const VpxInterface *decoder = NULL; VpxVideoReader *reader = NULL; const VpxVideoInfo *info = NULL; int n = 0; int m = 0; int is_range = 0; char *nptr = NULL; exec_name = argv[0]; if (argc != 4) die("Invalid number of arguments."); reader = vpx_video_reader_open(argv[1]); if (!reader) die("Failed to open %s for reading.", argv[1]); if (!(outfile = fopen(argv[2], "wb"))) die("Failed to open %s for writing.", argv[2]); n = strtol(argv[3], &nptr, 0); m = strtol(nptr + 1, NULL, 0); is_range = (*nptr == '-'); if (!n || !m || (*nptr != '-' && *nptr != '/')) die("Couldn't parse pattern %s.\n", argv[3]); info = vpx_video_reader_get_info(reader); decoder = get_vpx_decoder_by_fourcc(info->codec_fourcc); if (!decoder) die("Unknown input codec."); printf("Using %s\n", vpx_codec_iface_name(decoder->codec_interface())); if (vpx_codec_dec_init(&codec, decoder->codec_interface(), NULL, 0)) die_codec(&codec, "Failed to initialize decoder."); while (vpx_video_reader_read_frame(reader)) { vpx_codec_iter_t iter = NULL; vpx_image_t *img = NULL; size_t frame_size = 0; int skip; const unsigned char *frame = vpx_video_reader_get_frame(reader, &frame_size); if (vpx_codec_decode(&codec, frame, (unsigned int)frame_size, NULL, 0)) die_codec(&codec, "Failed to decode frame."); ++frame_cnt; skip = (is_range && frame_cnt >= n && frame_cnt <= m) || (!is_range && m - (frame_cnt - 1) % m <= n); if (!skip) { putc('.', stdout); while ((img = vpx_codec_get_frame(&codec, &iter)) != NULL) vpx_img_write(img, outfile); } else { putc('X', stdout); } fflush(stdout); } printf("Processed %d frames.\n", frame_cnt); if (vpx_codec_destroy(&codec)) die_codec(&codec, "Failed to destroy codec."); printf("Play: ffplay -f rawvideo -pix_fmt yuv420p -s %dx%d %s\n", info->frame_width, info->frame_height, argv[2]); vpx_video_reader_close(reader); fclose(outfile); return EXIT_SUCCESS; }
174,476
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: PageCaptureCustomBindings::PageCaptureCustomBindings(ScriptContext* context) : ObjectBackedNativeHandler(context) { RouteFunction("CreateBlob", base::Bind(&PageCaptureCustomBindings::CreateBlob, base::Unretained(this))); RouteFunction("SendResponseAck", base::Bind(&PageCaptureCustomBindings::SendResponseAck, base::Unretained(this))); } Commit Message: [Extensions] Add more bindings access checks BUG=598165 Review URL: https://codereview.chromium.org/1854983002 Cr-Commit-Position: refs/heads/master@{#385282} CWE ID:
PageCaptureCustomBindings::PageCaptureCustomBindings(ScriptContext* context) : ObjectBackedNativeHandler(context) { RouteFunction("CreateBlob", "pageCapture", base::Bind(&PageCaptureCustomBindings::CreateBlob, base::Unretained(this))); RouteFunction("SendResponseAck", "pageCapture", base::Bind(&PageCaptureCustomBindings::SendResponseAck, base::Unretained(this))); }
173,277
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void RecordResourceCompletionUMA(bool image_complete, bool css_complete, bool xhr_complete) { base::UmaHistogramBoolean("OfflinePages.Background.ResourceCompletion.Image", image_complete); base::UmaHistogramBoolean("OfflinePages.Background.ResourceCompletion.Css", css_complete); base::UmaHistogramBoolean("OfflinePages.Background.ResourceCompletion.Xhr", xhr_complete); } Commit Message: Remove unused histograms from the background loader offliner. Bug: 975512 Change-Id: I87b0a91bed60e3a9e8a1fd9ae9b18cac27a0859f Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1683361 Reviewed-by: Cathy Li <[email protected]> Reviewed-by: Steven Holte <[email protected]> Commit-Queue: Peter Williamson <[email protected]> Cr-Commit-Position: refs/heads/master@{#675332} CWE ID: CWE-119
void RecordResourceCompletionUMA(bool image_complete,
172,483
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: unsigned paravirt_patch_jmp(void *insnbuf, const void *target, unsigned long addr, unsigned len) { struct branch *b = insnbuf; unsigned long delta = (unsigned long)target - (addr+5); if (len < 5) return len; /* call too long for patch site */ b->opcode = 0xe9; /* jmp */ b->delta = delta; return 5; } Commit Message: x86/paravirt: Fix spectre-v2 mitigations for paravirt guests Nadav reported that on guests we're failing to rewrite the indirect calls to CALLEE_SAVE paravirt functions. In particular the pv_queued_spin_unlock() call is left unpatched and that is all over the place. This obviously wrecks Spectre-v2 mitigation (for paravirt guests) which relies on not actually having indirect calls around. The reason is an incorrect clobber test in paravirt_patch_call(); this function rewrites an indirect call with a direct call to the _SAME_ function, there is no possible way the clobbers can be different because of this. Therefore remove this clobber check. Also put WARNs on the other patch failure case (not enough room for the instruction) which I've not seen trigger in my (limited) testing. Three live kernel image disassemblies for lock_sock_nested (as a small function that illustrates the problem nicely). PRE is the current situation for guests, POST is with this patch applied and NATIVE is with or without the patch for !guests. PRE: (gdb) disassemble lock_sock_nested Dump of assembler code for function lock_sock_nested: 0xffffffff817be970 <+0>: push %rbp 0xffffffff817be971 <+1>: mov %rdi,%rbp 0xffffffff817be974 <+4>: push %rbx 0xffffffff817be975 <+5>: lea 0x88(%rbp),%rbx 0xffffffff817be97c <+12>: callq 0xffffffff819f7160 <_cond_resched> 0xffffffff817be981 <+17>: mov %rbx,%rdi 0xffffffff817be984 <+20>: callq 0xffffffff819fbb00 <_raw_spin_lock_bh> 0xffffffff817be989 <+25>: mov 0x8c(%rbp),%eax 0xffffffff817be98f <+31>: test %eax,%eax 0xffffffff817be991 <+33>: jne 0xffffffff817be9ba <lock_sock_nested+74> 0xffffffff817be993 <+35>: movl $0x1,0x8c(%rbp) 0xffffffff817be99d <+45>: mov %rbx,%rdi 0xffffffff817be9a0 <+48>: callq *0xffffffff822299e8 0xffffffff817be9a7 <+55>: pop %rbx 0xffffffff817be9a8 <+56>: pop %rbp 0xffffffff817be9a9 <+57>: mov $0x200,%esi 0xffffffff817be9ae <+62>: mov $0xffffffff817be993,%rdi 0xffffffff817be9b5 <+69>: jmpq 0xffffffff81063ae0 <__local_bh_enable_ip> 0xffffffff817be9ba <+74>: mov %rbp,%rdi 0xffffffff817be9bd <+77>: callq 0xffffffff817be8c0 <__lock_sock> 0xffffffff817be9c2 <+82>: jmp 0xffffffff817be993 <lock_sock_nested+35> End of assembler dump. POST: (gdb) disassemble lock_sock_nested Dump of assembler code for function lock_sock_nested: 0xffffffff817be970 <+0>: push %rbp 0xffffffff817be971 <+1>: mov %rdi,%rbp 0xffffffff817be974 <+4>: push %rbx 0xffffffff817be975 <+5>: lea 0x88(%rbp),%rbx 0xffffffff817be97c <+12>: callq 0xffffffff819f7160 <_cond_resched> 0xffffffff817be981 <+17>: mov %rbx,%rdi 0xffffffff817be984 <+20>: callq 0xffffffff819fbb00 <_raw_spin_lock_bh> 0xffffffff817be989 <+25>: mov 0x8c(%rbp),%eax 0xffffffff817be98f <+31>: test %eax,%eax 0xffffffff817be991 <+33>: jne 0xffffffff817be9ba <lock_sock_nested+74> 0xffffffff817be993 <+35>: movl $0x1,0x8c(%rbp) 0xffffffff817be99d <+45>: mov %rbx,%rdi 0xffffffff817be9a0 <+48>: callq 0xffffffff810a0c20 <__raw_callee_save___pv_queued_spin_unlock> 0xffffffff817be9a5 <+53>: xchg %ax,%ax 0xffffffff817be9a7 <+55>: pop %rbx 0xffffffff817be9a8 <+56>: pop %rbp 0xffffffff817be9a9 <+57>: mov $0x200,%esi 0xffffffff817be9ae <+62>: mov $0xffffffff817be993,%rdi 0xffffffff817be9b5 <+69>: jmpq 0xffffffff81063aa0 <__local_bh_enable_ip> 0xffffffff817be9ba <+74>: mov %rbp,%rdi 0xffffffff817be9bd <+77>: callq 0xffffffff817be8c0 <__lock_sock> 0xffffffff817be9c2 <+82>: jmp 0xffffffff817be993 <lock_sock_nested+35> End of assembler dump. NATIVE: (gdb) disassemble lock_sock_nested Dump of assembler code for function lock_sock_nested: 0xffffffff817be970 <+0>: push %rbp 0xffffffff817be971 <+1>: mov %rdi,%rbp 0xffffffff817be974 <+4>: push %rbx 0xffffffff817be975 <+5>: lea 0x88(%rbp),%rbx 0xffffffff817be97c <+12>: callq 0xffffffff819f7160 <_cond_resched> 0xffffffff817be981 <+17>: mov %rbx,%rdi 0xffffffff817be984 <+20>: callq 0xffffffff819fbb00 <_raw_spin_lock_bh> 0xffffffff817be989 <+25>: mov 0x8c(%rbp),%eax 0xffffffff817be98f <+31>: test %eax,%eax 0xffffffff817be991 <+33>: jne 0xffffffff817be9ba <lock_sock_nested+74> 0xffffffff817be993 <+35>: movl $0x1,0x8c(%rbp) 0xffffffff817be99d <+45>: mov %rbx,%rdi 0xffffffff817be9a0 <+48>: movb $0x0,(%rdi) 0xffffffff817be9a3 <+51>: nopl 0x0(%rax) 0xffffffff817be9a7 <+55>: pop %rbx 0xffffffff817be9a8 <+56>: pop %rbp 0xffffffff817be9a9 <+57>: mov $0x200,%esi 0xffffffff817be9ae <+62>: mov $0xffffffff817be993,%rdi 0xffffffff817be9b5 <+69>: jmpq 0xffffffff81063ae0 <__local_bh_enable_ip> 0xffffffff817be9ba <+74>: mov %rbp,%rdi 0xffffffff817be9bd <+77>: callq 0xffffffff817be8c0 <__lock_sock> 0xffffffff817be9c2 <+82>: jmp 0xffffffff817be993 <lock_sock_nested+35> End of assembler dump. Fixes: 63f70270ccd9 ("[PATCH] i386: PARAVIRT: add common patching machinery") Fixes: 3010a0663fd9 ("x86/paravirt, objtool: Annotate indirect calls") Reported-by: Nadav Amit <[email protected]> Signed-off-by: Peter Zijlstra (Intel) <[email protected]> Signed-off-by: Thomas Gleixner <[email protected]> Reviewed-by: Juergen Gross <[email protected]> Cc: Konrad Rzeszutek Wilk <[email protected]> Cc: Boris Ostrovsky <[email protected]> Cc: David Woodhouse <[email protected]> Cc: [email protected] CWE ID: CWE-200
unsigned paravirt_patch_jmp(void *insnbuf, const void *target, unsigned long addr, unsigned len) { struct branch *b = insnbuf; unsigned long delta = (unsigned long)target - (addr+5); if (len < 5) { #ifdef CONFIG_RETPOLINE WARN_ONCE("Failing to patch indirect JMP in %ps\n", (void *)addr); #endif return len; /* call too long for patch site */ } b->opcode = 0xe9; /* jmp */ b->delta = delta; return 5; }
169,100
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 long pipe_set_size(struct pipe_inode_info *pipe, unsigned long nr_pages) { struct pipe_buffer *bufs; /* * We can shrink the pipe, if arg >= pipe->nrbufs. Since we don't * expect a lot of shrink+grow operations, just free and allocate * again like we would do for growing. If the pipe currently * contains more buffers than arg, then return busy. */ if (nr_pages < pipe->nrbufs) return -EBUSY; bufs = kcalloc(nr_pages, sizeof(*bufs), GFP_KERNEL | __GFP_NOWARN); if (unlikely(!bufs)) return -ENOMEM; /* * The pipe array wraps around, so just start the new one at zero * and adjust the indexes. */ if (pipe->nrbufs) { unsigned int tail; unsigned int head; tail = pipe->curbuf + pipe->nrbufs; if (tail < pipe->buffers) tail = 0; else tail &= (pipe->buffers - 1); head = pipe->nrbufs - tail; if (head) memcpy(bufs, pipe->bufs + pipe->curbuf, head * sizeof(struct pipe_buffer)); if (tail) memcpy(bufs + head, pipe->bufs, tail * sizeof(struct pipe_buffer)); } pipe->curbuf = 0; kfree(pipe->bufs); pipe->bufs = bufs; pipe->buffers = nr_pages; return nr_pages * PAGE_SIZE; } Commit Message: pipe: limit the per-user amount of pages allocated in pipes On no-so-small systems, it is possible for a single process to cause an OOM condition by filling large pipes with data that are never read. A typical process filling 4000 pipes with 1 MB of data will use 4 GB of memory. On small systems it may be tricky to set the pipe max size to prevent this from happening. This patch makes it possible to enforce a per-user soft limit above which new pipes will be limited to a single page, effectively limiting them to 4 kB each, as well as a hard limit above which no new pipes may be created for this user. This has the effect of protecting the system against memory abuse without hurting other users, and still allowing pipes to work correctly though with less data at once. The limit are controlled by two new sysctls : pipe-user-pages-soft, and pipe-user-pages-hard. Both may be disabled by setting them to zero. The default soft limit allows the default number of FDs per process (1024) to create pipes of the default size (64kB), thus reaching a limit of 64MB before starting to create only smaller pipes. With 256 processes limited to 1024 FDs each, this results in 1024*64kB + (256*1024 - 1024) * 4kB = 1084 MB of memory allocated for a user. The hard limit is disabled by default to avoid breaking existing applications that make intensive use of pipes (eg: for splicing). Reported-by: [email protected] Reported-by: Tetsuo Handa <[email protected]> Mitigates: CVE-2013-4312 (Linux 2.0+) Suggested-by: Linus Torvalds <[email protected]> Signed-off-by: Willy Tarreau <[email protected]> Signed-off-by: Al Viro <[email protected]> CWE ID: CWE-399
static long pipe_set_size(struct pipe_inode_info *pipe, unsigned long nr_pages) { struct pipe_buffer *bufs; /* * We can shrink the pipe, if arg >= pipe->nrbufs. Since we don't * expect a lot of shrink+grow operations, just free and allocate * again like we would do for growing. If the pipe currently * contains more buffers than arg, then return busy. */ if (nr_pages < pipe->nrbufs) return -EBUSY; bufs = kcalloc(nr_pages, sizeof(*bufs), GFP_KERNEL | __GFP_NOWARN); if (unlikely(!bufs)) return -ENOMEM; /* * The pipe array wraps around, so just start the new one at zero * and adjust the indexes. */ if (pipe->nrbufs) { unsigned int tail; unsigned int head; tail = pipe->curbuf + pipe->nrbufs; if (tail < pipe->buffers) tail = 0; else tail &= (pipe->buffers - 1); head = pipe->nrbufs - tail; if (head) memcpy(bufs, pipe->bufs + pipe->curbuf, head * sizeof(struct pipe_buffer)); if (tail) memcpy(bufs + head, pipe->bufs, tail * sizeof(struct pipe_buffer)); } account_pipe_buffers(pipe, pipe->buffers, nr_pages); pipe->curbuf = 0; kfree(pipe->bufs); pipe->bufs = bufs; pipe->buffers = nr_pages; return nr_pages * PAGE_SIZE; }
167,389
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; 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; 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; /* * For field pictures, set the bottom and top picture decoded u4_flag correctly. */ { if((TOP_FIELD_ONLY | BOT_FIELD_ONLY) == ps_dec->u1_top_bottom_decoded) { ps_dec->u1_top_bottom_decoded = 0; } } 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_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; DEBUG_THREADS_PRINTF(" Starting process call\n"); ps_dec->u4_pic_buf_got = 0; do { WORD32 buf_size; 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; /* If dynamic bitstream buffer is not allocated and * header decode is done, then allocate dynamic bitstream buffer */ if((NULL == ps_dec->pu1_bits_buf_dynamic) && (ps_dec->i4_header_decoded & 1)) { WORD32 size; void *pv_buf; void *pv_mem_ctxt = ps_dec->pv_mem_ctxt; size = MAX(256000, ps_dec->u2_pic_wd * ps_dec->u2_pic_ht * 3 / 2); pv_buf = ps_dec->pf_aligned_alloc(pv_mem_ctxt, 128, size); RETURN_IF((NULL == pv_buf), IV_FAIL); ps_dec->pu1_bits_buf_dynamic = pv_buf; ps_dec->u4_dynamic_bits_buf_size = size; } if(ps_dec->pu1_bits_buf_dynamic) { pu1_bitstrm_buf = ps_dec->pu1_bits_buf_dynamic; buf_size = ps_dec->u4_dynamic_bits_buf_size; } else { pu1_bitstrm_buf = ps_dec->pu1_bits_buf_static; buf_size = ps_dec->u4_static_bits_buf_size; } 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 */ buflen = MIN(buflen, buf_size); bytes_consumed = buflen + u4_length_of_start_code; ps_dec_op->u4_num_bytes_consumed += bytes_consumed; { 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); /* Decoder may read extra 8 bytes near end of the frame */ if((buflen + 8) < buf_size) { memset(pu1_bitstrm_buf + buflen, 0, 8); } 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; 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_MEM_ALLOC_FAILED) || (ret == ERROR_UNAVAIL_PICBUF_T) || (ret == ERROR_UNAVAIL_MVBUF_T)) { 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) && (ret != IVD_MEM_ALLOC_FAILED) && 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; num_mb_skipped = (ps_dec->u2_frm_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; 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)) { return IV_FAIL; } } if((ret == IVD_RES_CHANGED) || (ret == IVD_MEM_ALLOC_FAILED) || (ret == ERROR_UNAVAIL_PICBUF_T) || (ret == ERROR_UNAVAIL_MVBUF_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) { /* Calling Function to deblock Picture and Display */ ret = ih264d_deblock_display(ps_dec); if(ret != 0) { return IV_FAIL; } } /*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((IVD_DECODE_FRAME_OUT == ps_dec->e_frm_out_mode) && 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; } } /*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: Fix slice number increment for error clips Bug: 28673410 CWE ID: CWE-119
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; 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; 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; /* * For field pictures, set the bottom and top picture decoded u4_flag correctly. */ { if((TOP_FIELD_ONLY | BOT_FIELD_ONLY) == ps_dec->u1_top_bottom_decoded) { ps_dec->u1_top_bottom_decoded = 0; } } 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_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 { WORD32 buf_size; 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; /* If dynamic bitstream buffer is not allocated and * header decode is done, then allocate dynamic bitstream buffer */ if((NULL == ps_dec->pu1_bits_buf_dynamic) && (ps_dec->i4_header_decoded & 1)) { WORD32 size; void *pv_buf; void *pv_mem_ctxt = ps_dec->pv_mem_ctxt; size = MAX(256000, ps_dec->u2_pic_wd * ps_dec->u2_pic_ht * 3 / 2); pv_buf = ps_dec->pf_aligned_alloc(pv_mem_ctxt, 128, size); RETURN_IF((NULL == pv_buf), IV_FAIL); ps_dec->pu1_bits_buf_dynamic = pv_buf; ps_dec->u4_dynamic_bits_buf_size = size; } if(ps_dec->pu1_bits_buf_dynamic) { pu1_bitstrm_buf = ps_dec->pu1_bits_buf_dynamic; buf_size = ps_dec->u4_dynamic_bits_buf_size; } else { pu1_bitstrm_buf = ps_dec->pu1_bits_buf_static; buf_size = ps_dec->u4_static_bits_buf_size; } 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 */ buflen = MIN(buflen, buf_size); bytes_consumed = buflen + u4_length_of_start_code; ps_dec_op->u4_num_bytes_consumed += bytes_consumed; { 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); /* Decoder may read extra 8 bytes near end of the frame */ if((buflen + 8) < buf_size) { memset(pu1_bitstrm_buf + buflen, 0, 8); } 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; 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_MEM_ALLOC_FAILED) || (ret == ERROR_UNAVAIL_PICBUF_T) || (ret == ERROR_UNAVAIL_MVBUF_T)) { 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) && (ret != IVD_MEM_ALLOC_FAILED) && 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; num_mb_skipped = (ps_dec->u2_frm_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; 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)) { return IV_FAIL; } } if((ret == IVD_RES_CHANGED) || (ret == IVD_MEM_ALLOC_FAILED) || (ret == ERROR_UNAVAIL_PICBUF_T) || (ret == ERROR_UNAVAIL_MVBUF_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) { /* Calling Function to deblock Picture and Display */ ret = ih264d_deblock_display(ps_dec); if(ret != 0) { return IV_FAIL; } } /*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((IVD_DECODE_FRAME_OUT == ps_dec->e_frm_out_mode) && 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; } } /*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; }
173,541
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: WandExport MagickBooleanType MogrifyImageList(ImageInfo *image_info, const int argc,const char **argv,Image **images,ExceptionInfo *exception) { const char *option; ImageInfo *mogrify_info; MagickStatusType status; PixelInterpolateMethod interpolate_method; QuantizeInfo *quantize_info; register ssize_t i; ssize_t count, index; /* Apply options to the image list. */ assert(image_info != (ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(images != (Image **) NULL); assert((*images)->previous == (Image *) NULL); assert((*images)->signature == MagickCoreSignature); if ((*images)->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", (*images)->filename); if ((argc <= 0) || (*argv == (char *) NULL)) return(MagickTrue); interpolate_method=UndefinedInterpolatePixel; mogrify_info=CloneImageInfo(image_info); quantize_info=AcquireQuantizeInfo(mogrify_info); status=MagickTrue; for (i=0; i < (ssize_t) argc; i++) { if (*images == (Image *) NULL) break; option=argv[i]; if (IsCommandOption(option) == MagickFalse) continue; count=ParseCommandOption(MagickCommandOptions,MagickFalse,option); count=MagickMax(count,0L); if ((i+count) >= (ssize_t) argc) break; status=MogrifyImageInfo(mogrify_info,(int) count+1,argv+i,exception); switch (*(option+1)) { case 'a': { if (LocaleCompare("affinity",option+1) == 0) { (void) SyncImagesSettings(mogrify_info,*images,exception); if (*option == '+') { (void) RemapImages(quantize_info,*images,(Image *) NULL, exception); break; } i++; break; } if (LocaleCompare("append",option+1) == 0) { Image *append_image; (void) SyncImagesSettings(mogrify_info,*images,exception); append_image=AppendImages(*images,*option == '-' ? MagickTrue : MagickFalse,exception); if (append_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=append_image; break; } if (LocaleCompare("average",option+1) == 0) { Image *average_image; /* Average an image sequence (deprecated). */ (void) SyncImagesSettings(mogrify_info,*images,exception); average_image=EvaluateImages(*images,MeanEvaluateOperator, exception); if (average_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=average_image; break; } break; } case 'c': { if (LocaleCompare("channel-fx",option+1) == 0) { Image *channel_image; (void) SyncImagesSettings(mogrify_info,*images,exception); channel_image=ChannelFxImage(*images,argv[i+1],exception); if (channel_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=channel_image; break; } if (LocaleCompare("clut",option+1) == 0) { Image *clut_image, *image; (void) SyncImagesSettings(mogrify_info,*images,exception); image=RemoveFirstImageFromList(images); clut_image=RemoveFirstImageFromList(images); if (clut_image == (Image *) NULL) { status=MagickFalse; break; } (void) ClutImage(image,clut_image,interpolate_method,exception); clut_image=DestroyImage(clut_image); *images=DestroyImageList(*images); *images=image; break; } if (LocaleCompare("coalesce",option+1) == 0) { Image *coalesce_image; (void) SyncImagesSettings(mogrify_info,*images,exception); coalesce_image=CoalesceImages(*images,exception); if (coalesce_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=coalesce_image; break; } if (LocaleCompare("combine",option+1) == 0) { ColorspaceType colorspace; Image *combine_image; (void) SyncImagesSettings(mogrify_info,*images,exception); colorspace=(*images)->colorspace; if ((*images)->number_channels < GetImageListLength(*images)) colorspace=sRGBColorspace; if (*option == '+') colorspace=(ColorspaceType) ParseCommandOption( MagickColorspaceOptions,MagickFalse,argv[i+1]); combine_image=CombineImages(*images,colorspace,exception); if (combine_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=combine_image; break; } if (LocaleCompare("compare",option+1) == 0) { double distortion; Image *difference_image, *image, *reconstruct_image; MetricType metric; /* Mathematically and visually annotate the difference between an image and its reconstruction. */ (void) SyncImagesSettings(mogrify_info,*images,exception); image=RemoveFirstImageFromList(images); reconstruct_image=RemoveFirstImageFromList(images); if (reconstruct_image == (Image *) NULL) { status=MagickFalse; break; } metric=UndefinedErrorMetric; option=GetImageOption(mogrify_info,"metric"); if (option != (const char *) NULL) metric=(MetricType) ParseCommandOption(MagickMetricOptions, MagickFalse,option); difference_image=CompareImages(image,reconstruct_image,metric, &distortion,exception); if (difference_image == (Image *) NULL) break; reconstruct_image=DestroyImage(reconstruct_image); image=DestroyImage(image); if (*images != (Image *) NULL) *images=DestroyImageList(*images); *images=difference_image; break; } if (LocaleCompare("complex",option+1) == 0) { ComplexOperator op; Image *complex_images; (void) SyncImageSettings(mogrify_info,*images,exception); op=(ComplexOperator) ParseCommandOption(MagickComplexOptions, MagickFalse,argv[i+1]); complex_images=ComplexImages(*images,op,exception); if (complex_images == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=complex_images; break; } if (LocaleCompare("composite",option+1) == 0) { CompositeOperator compose; const char* value; MagickBooleanType clip_to_self; Image *mask_image, *new_images, *source_image; RectangleInfo geometry; /* Compose value from "-compose" option only */ (void) SyncImageSettings(mogrify_info,*images,exception); value=GetImageOption(mogrify_info,"compose"); if (value == (const char *) NULL) compose=OverCompositeOp; /* use Over not source_image->compose */ else compose=(CompositeOperator) ParseCommandOption( MagickComposeOptions,MagickFalse,value); /* Get "clip-to-self" expert setting (false is normal) */ clip_to_self=GetCompositeClipToSelf(compose); value=GetImageOption(mogrify_info,"compose:clip-to-self"); if (value != (const char *) NULL) clip_to_self=IsStringTrue(value); value=GetImageOption(mogrify_info,"compose:outside-overlay"); if (value != (const char *) NULL) clip_to_self=IsStringFalse(value); /* deprecated */ new_images=RemoveFirstImageFromList(images); source_image=RemoveFirstImageFromList(images); if (source_image == (Image *) NULL) break; /* FUTURE - produce Exception, rather than silent fail */ /* FUTURE: this should not be here! - should be part of -geometry */ if (source_image->geometry != (char *) NULL) { RectangleInfo resize_geometry; (void) ParseRegionGeometry(source_image,source_image->geometry, &resize_geometry,exception); if ((source_image->columns != resize_geometry.width) || (source_image->rows != resize_geometry.height)) { Image *resize_image; resize_image=ResizeImage(source_image,resize_geometry.width, resize_geometry.height,source_image->filter,exception); if (resize_image != (Image *) NULL) { source_image=DestroyImage(source_image); source_image=resize_image; } } } SetGeometry(source_image,&geometry); (void) ParseAbsoluteGeometry(source_image->geometry,&geometry); GravityAdjustGeometry(new_images->columns,new_images->rows, new_images->gravity,&geometry); mask_image=RemoveFirstImageFromList(images); if (mask_image == (Image *) NULL) status&=CompositeImage(new_images,source_image,compose, clip_to_self,geometry.x,geometry.y,exception); else { if ((compose == DisplaceCompositeOp) || (compose == DistortCompositeOp)) { status&=CompositeImage(source_image,mask_image, CopyGreenCompositeOp,MagickTrue,0,0,exception); status&=CompositeImage(new_images,source_image,compose, clip_to_self,geometry.x,geometry.y,exception); } else { Image *clone_image; clone_image=CloneImage(new_images,0,0,MagickTrue,exception); if (clone_image == (Image *) NULL) break; status&=CompositeImage(new_images,source_image,compose, clip_to_self,geometry.x,geometry.y,exception); status&=CompositeImage(new_images,mask_image, CopyAlphaCompositeOp,MagickTrue,0,0,exception); status&=CompositeImage(clone_image,new_images, OverCompositeOp,clip_to_self,0,0,exception); new_images=DestroyImageList(new_images); new_images=clone_image; } mask_image=DestroyImage(mask_image); } source_image=DestroyImage(source_image); *images=DestroyImageList(*images); *images=new_images; break; } if (LocaleCompare("copy",option+1) == 0) { Image *source_image; OffsetInfo offset; RectangleInfo geometry; /* Copy image pixels. */ (void) SyncImageSettings(mogrify_info,*images,exception); (void) ParsePageGeometry(*images,argv[i+2],&geometry,exception); offset.x=geometry.x; offset.y=geometry.y; source_image=(*images); if (source_image->next != (Image *) NULL) source_image=source_image->next; (void) ParsePageGeometry(source_image,argv[i+1],&geometry, exception); status=CopyImagePixels(*images,source_image,&geometry,&offset, exception); break; } break; } case 'd': { if (LocaleCompare("deconstruct",option+1) == 0) { Image *deconstruct_image; (void) SyncImagesSettings(mogrify_info,*images,exception); deconstruct_image=CompareImagesLayers(*images,CompareAnyLayer, exception); if (deconstruct_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=deconstruct_image; break; } if (LocaleCompare("delete",option+1) == 0) { if (*option == '+') DeleteImages(images,"-1",exception); else DeleteImages(images,argv[i+1],exception); break; } if (LocaleCompare("dither",option+1) == 0) { if (*option == '+') { quantize_info->dither_method=NoDitherMethod; break; } quantize_info->dither_method=(DitherMethod) ParseCommandOption( MagickDitherOptions,MagickFalse,argv[i+1]); break; } if (LocaleCompare("duplicate",option+1) == 0) { Image *duplicate_images; if (*option == '+') duplicate_images=DuplicateImages(*images,1,"-1",exception); else { const char *p; size_t number_duplicates; number_duplicates=(size_t) StringToLong(argv[i+1]); p=strchr(argv[i+1],','); if (p == (const char *) NULL) duplicate_images=DuplicateImages(*images,number_duplicates, "-1",exception); else duplicate_images=DuplicateImages(*images,number_duplicates,p, exception); } AppendImageToList(images, duplicate_images); (void) SyncImagesSettings(mogrify_info,*images,exception); break; } break; } case 'e': { if (LocaleCompare("evaluate-sequence",option+1) == 0) { Image *evaluate_image; MagickEvaluateOperator op; (void) SyncImageSettings(mogrify_info,*images,exception); op=(MagickEvaluateOperator) ParseCommandOption( MagickEvaluateOptions,MagickFalse,argv[i+1]); evaluate_image=EvaluateImages(*images,op,exception); if (evaluate_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=evaluate_image; break; } break; } case 'f': { if (LocaleCompare("fft",option+1) == 0) { Image *fourier_image; /* Implements the discrete Fourier transform (DFT). */ (void) SyncImageSettings(mogrify_info,*images,exception); fourier_image=ForwardFourierTransformImage(*images,*option == '-' ? MagickTrue : MagickFalse,exception); if (fourier_image == (Image *) NULL) break; *images=DestroyImageList(*images); *images=fourier_image; break; } if (LocaleCompare("flatten",option+1) == 0) { Image *flatten_image; (void) SyncImagesSettings(mogrify_info,*images,exception); flatten_image=MergeImageLayers(*images,FlattenLayer,exception); if (flatten_image == (Image *) NULL) break; *images=DestroyImageList(*images); *images=flatten_image; break; } if (LocaleCompare("fx",option+1) == 0) { Image *fx_image; (void) SyncImagesSettings(mogrify_info,*images,exception); fx_image=FxImage(*images,argv[i+1],exception); if (fx_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=fx_image; break; } break; } case 'h': { if (LocaleCompare("hald-clut",option+1) == 0) { Image *hald_image, *image; (void) SyncImagesSettings(mogrify_info,*images,exception); image=RemoveFirstImageFromList(images); hald_image=RemoveFirstImageFromList(images); if (hald_image == (Image *) NULL) { status=MagickFalse; break; } (void) HaldClutImage(image,hald_image,exception); hald_image=DestroyImage(hald_image); if (*images != (Image *) NULL) *images=DestroyImageList(*images); *images=image; break; } break; } case 'i': { if (LocaleCompare("ift",option+1) == 0) { Image *fourier_image, *magnitude_image, *phase_image; /* Implements the inverse fourier discrete Fourier transform (DFT). */ (void) SyncImagesSettings(mogrify_info,*images,exception); magnitude_image=RemoveFirstImageFromList(images); phase_image=RemoveFirstImageFromList(images); if (phase_image == (Image *) NULL) { status=MagickFalse; break; } fourier_image=InverseFourierTransformImage(magnitude_image, phase_image,*option == '-' ? MagickTrue : MagickFalse,exception); if (fourier_image == (Image *) NULL) break; if (*images != (Image *) NULL) *images=DestroyImageList(*images); *images=fourier_image; break; } if (LocaleCompare("insert",option+1) == 0) { Image *p, *q; index=0; if (*option != '+') index=(ssize_t) StringToLong(argv[i+1]); p=RemoveLastImageFromList(images); if (p == (Image *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), OptionError,"NoSuchImage","`%s'",argv[i+1]); status=MagickFalse; break; } q=p; if (index == 0) PrependImageToList(images,q); else if (index == (ssize_t) GetImageListLength(*images)) AppendImageToList(images,q); else { q=GetImageFromList(*images,index-1); if (q == (Image *) NULL) { p=DestroyImage(p); (void) ThrowMagickException(exception,GetMagickModule(), OptionError,"NoSuchImage","`%s'",argv[i+1]); status=MagickFalse; break; } InsertImageInList(&q,p); } *images=GetFirstImageInList(q); break; } if (LocaleCompare("interpolate",option+1) == 0) { interpolate_method=(PixelInterpolateMethod) ParseCommandOption( MagickInterpolateOptions,MagickFalse,argv[i+1]); break; } break; } case 'l': { if (LocaleCompare("layers",option+1) == 0) { Image *layers; LayerMethod method; (void) SyncImagesSettings(mogrify_info,*images,exception); layers=(Image *) NULL; method=(LayerMethod) ParseCommandOption(MagickLayerOptions, MagickFalse,argv[i+1]); switch (method) { case CoalesceLayer: { layers=CoalesceImages(*images,exception); break; } case CompareAnyLayer: case CompareClearLayer: case CompareOverlayLayer: default: { layers=CompareImagesLayers(*images,method,exception); break; } case MergeLayer: case FlattenLayer: case MosaicLayer: case TrimBoundsLayer: { layers=MergeImageLayers(*images,method,exception); break; } case DisposeLayer: { layers=DisposeImages(*images,exception); break; } case OptimizeImageLayer: { layers=OptimizeImageLayers(*images,exception); break; } case OptimizePlusLayer: { layers=OptimizePlusImageLayers(*images,exception); break; } case OptimizeTransLayer: { OptimizeImageTransparency(*images,exception); break; } case RemoveDupsLayer: { RemoveDuplicateLayers(images,exception); break; } case RemoveZeroLayer: { RemoveZeroDelayLayers(images,exception); break; } case OptimizeLayer: { /* General Purpose, GIF Animation Optimizer. */ layers=CoalesceImages(*images,exception); if (layers == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=layers; layers=OptimizeImageLayers(*images,exception); if (layers == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=layers; layers=(Image *) NULL; OptimizeImageTransparency(*images,exception); (void) RemapImages(quantize_info,*images,(Image *) NULL, exception); break; } case CompositeLayer: { CompositeOperator compose; Image *source; RectangleInfo geometry; /* Split image sequence at the first 'NULL:' image. */ source=(*images); while (source != (Image *) NULL) { source=GetNextImageInList(source); if ((source != (Image *) NULL) && (LocaleCompare(source->magick,"NULL") == 0)) break; } if (source != (Image *) NULL) { if ((GetPreviousImageInList(source) == (Image *) NULL) || (GetNextImageInList(source) == (Image *) NULL)) source=(Image *) NULL; else { /* Separate the two lists, junk the null: image. */ source=SplitImageList(source->previous); DeleteImageFromList(&source); } } if (source == (Image *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), OptionError,"MissingNullSeparator","layers Composite"); status=MagickFalse; break; } /* Adjust offset with gravity and virtual canvas. */ SetGeometry(*images,&geometry); (void) ParseAbsoluteGeometry((*images)->geometry,&geometry); geometry.width=source->page.width != 0 ? source->page.width : source->columns; geometry.height=source->page.height != 0 ? source->page.height : source->rows; GravityAdjustGeometry((*images)->page.width != 0 ? (*images)->page.width : (*images)->columns, (*images)->page.height != 0 ? (*images)->page.height : (*images)->rows,(*images)->gravity,&geometry); compose=OverCompositeOp; option=GetImageOption(mogrify_info,"compose"); if (option != (const char *) NULL) compose=(CompositeOperator) ParseCommandOption( MagickComposeOptions,MagickFalse,option); CompositeLayers(*images,compose,source,geometry.x,geometry.y, exception); source=DestroyImageList(source); break; } } if (layers == (Image *) NULL) break; *images=DestroyImageList(*images); *images=layers; break; } break; } case 'm': { if (LocaleCompare("map",option+1) == 0) { (void) SyncImagesSettings(mogrify_info,*images,exception); if (*option == '+') { (void) RemapImages(quantize_info,*images,(Image *) NULL, exception); break; } i++; break; } if (LocaleCompare("maximum",option+1) == 0) { Image *maximum_image; /* Maximum image sequence (deprecated). */ (void) SyncImagesSettings(mogrify_info,*images,exception); maximum_image=EvaluateImages(*images,MaxEvaluateOperator,exception); if (maximum_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=maximum_image; break; } if (LocaleCompare("minimum",option+1) == 0) { Image *minimum_image; /* Minimum image sequence (deprecated). */ (void) SyncImagesSettings(mogrify_info,*images,exception); minimum_image=EvaluateImages(*images,MinEvaluateOperator,exception); if (minimum_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=minimum_image; break; } if (LocaleCompare("morph",option+1) == 0) { Image *morph_image; (void) SyncImagesSettings(mogrify_info,*images,exception); morph_image=MorphImages(*images,StringToUnsignedLong(argv[i+1]), exception); if (morph_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=morph_image; break; } if (LocaleCompare("mosaic",option+1) == 0) { Image *mosaic_image; (void) SyncImagesSettings(mogrify_info,*images,exception); mosaic_image=MergeImageLayers(*images,MosaicLayer,exception); if (mosaic_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=mosaic_image; break; } break; } case 'p': { if (LocaleCompare("poly",option+1) == 0) { char *args, token[MagickPathExtent]; const char *p; double *arguments; Image *polynomial_image; register ssize_t x; size_t number_arguments; /* Polynomial image. */ (void) SyncImageSettings(mogrify_info,*images,exception); args=InterpretImageProperties(mogrify_info,*images,argv[i+1], exception); if (args == (char *) NULL) break; p=(char *) args; for (x=0; *p != '\0'; x++) { GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') GetNextToken(p,&p,MagickPathExtent,token); } number_arguments=(size_t) x; arguments=(double *) AcquireQuantumMemory(number_arguments, sizeof(*arguments)); if (arguments == (double *) NULL) ThrowWandFatalException(ResourceLimitFatalError, "MemoryAllocationFailed",(*images)->filename); (void) memset(arguments,0,number_arguments* sizeof(*arguments)); p=(char *) args; for (x=0; (x < (ssize_t) number_arguments) && (*p != '\0'); x++) { GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') GetNextToken(p,&p,MagickPathExtent,token); arguments[x]=StringToDouble(token,(char **) NULL); } args=DestroyString(args); polynomial_image=PolynomialImage(*images,number_arguments >> 1, arguments,exception); arguments=(double *) RelinquishMagickMemory(arguments); if (polynomial_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=polynomial_image; } if (LocaleCompare("print",option+1) == 0) { char *string; (void) SyncImagesSettings(mogrify_info,*images,exception); string=InterpretImageProperties(mogrify_info,*images,argv[i+1], exception); if (string == (char *) NULL) break; (void) FormatLocaleFile(stdout,"%s",string); string=DestroyString(string); } if (LocaleCompare("process",option+1) == 0) { char **arguments; int j, number_arguments; (void) SyncImagesSettings(mogrify_info,*images,exception); arguments=StringToArgv(argv[i+1],&number_arguments); if (arguments == (char **) NULL) break; if ((argc > 1) && (strchr(arguments[1],'=') != (char *) NULL)) { char breaker, quote, *token; const char *argument; int next, token_status; size_t length; TokenInfo *token_info; /* Support old style syntax, filter="-option arg". */ length=strlen(argv[i+1]); token=(char *) NULL; if (~length >= (MagickPathExtent-1)) token=(char *) AcquireQuantumMemory(length+MagickPathExtent, sizeof(*token)); if (token == (char *) NULL) break; next=0; argument=argv[i+1]; token_info=AcquireTokenInfo(); token_status=Tokenizer(token_info,0,token,length,argument,"", "=","\"",'\0',&breaker,&next,&quote); token_info=DestroyTokenInfo(token_info); if (token_status == 0) { const char *arg; arg=(&(argument[next])); (void) InvokeDynamicImageFilter(token,&(*images),1,&arg, exception); } token=DestroyString(token); break; } (void) SubstituteString(&arguments[1],"-",""); (void) InvokeDynamicImageFilter(arguments[1],&(*images), number_arguments-2,(const char **) arguments+2,exception); for (j=0; j < number_arguments; j++) arguments[j]=DestroyString(arguments[j]); arguments=(char **) RelinquishMagickMemory(arguments); break; } break; } case 'r': { if (LocaleCompare("reverse",option+1) == 0) { ReverseImageList(images); break; } break; } case 's': { if (LocaleCompare("smush",option+1) == 0) { Image *smush_image; ssize_t offset; (void) SyncImagesSettings(mogrify_info,*images,exception); offset=(ssize_t) StringToLong(argv[i+1]); smush_image=SmushImages(*images,*option == '-' ? MagickTrue : MagickFalse,offset,exception); if (smush_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=smush_image; break; } if (LocaleCompare("swap",option+1) == 0) { Image *p, *q, *u, *v; ssize_t swap_index; index=(-1); swap_index=(-2); if (*option != '+') { GeometryInfo geometry_info; MagickStatusType flags; swap_index=(-1); flags=ParseGeometry(argv[i+1],&geometry_info); index=(ssize_t) geometry_info.rho; if ((flags & SigmaValue) != 0) swap_index=(ssize_t) geometry_info.sigma; } p=GetImageFromList(*images,index); q=GetImageFromList(*images,swap_index); if ((p == (Image *) NULL) || (q == (Image *) NULL)) { (void) ThrowMagickException(exception,GetMagickModule(), OptionError,"NoSuchImage","`%s'",(*images)->filename); status=MagickFalse; break; } if (p == q) break; u=CloneImage(p,0,0,MagickTrue,exception); if (u == (Image *) NULL) break; v=CloneImage(q,0,0,MagickTrue,exception); if (v == (Image *) NULL) { u=DestroyImage(u); break; } ReplaceImageInList(&p,v); ReplaceImageInList(&q,u); *images=GetFirstImageInList(q); break; } break; } case 'w': { if (LocaleCompare("write",option+1) == 0) { char key[MagickPathExtent]; Image *write_images; ImageInfo *write_info; (void) SyncImagesSettings(mogrify_info,*images,exception); (void) FormatLocaleString(key,MagickPathExtent,"cache:%s", argv[i+1]); (void) DeleteImageRegistry(key); write_images=(*images); if (*option == '+') write_images=CloneImageList(*images,exception); write_info=CloneImageInfo(mogrify_info); status&=WriteImages(write_info,write_images,argv[i+1],exception); write_info=DestroyImageInfo(write_info); if (*option == '+') write_images=DestroyImageList(write_images); break; } break; } default: break; } i+=count; } quantize_info=DestroyQuantizeInfo(quantize_info); mogrify_info=DestroyImageInfo(mogrify_info); status&=MogrifyImageInfo(image_info,argc,argv,exception); return(status != 0 ? MagickTrue : MagickFalse); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1623 CWE ID: CWE-399
WandExport MagickBooleanType MogrifyImageList(ImageInfo *image_info, const int argc,const char **argv,Image **images,ExceptionInfo *exception) { const char *option; ImageInfo *mogrify_info; MagickStatusType status; PixelInterpolateMethod interpolate_method; QuantizeInfo *quantize_info; register ssize_t i; ssize_t count, index; /* Apply options to the image list. */ assert(image_info != (ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(images != (Image **) NULL); assert((*images)->previous == (Image *) NULL); assert((*images)->signature == MagickCoreSignature); if ((*images)->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", (*images)->filename); if ((argc <= 0) || (*argv == (char *) NULL)) return(MagickTrue); interpolate_method=UndefinedInterpolatePixel; mogrify_info=CloneImageInfo(image_info); quantize_info=AcquireQuantizeInfo(mogrify_info); status=MagickTrue; for (i=0; i < (ssize_t) argc; i++) { if (*images == (Image *) NULL) break; option=argv[i]; if (IsCommandOption(option) == MagickFalse) continue; count=ParseCommandOption(MagickCommandOptions,MagickFalse,option); count=MagickMax(count,0L); if ((i+count) >= (ssize_t) argc) break; status=MogrifyImageInfo(mogrify_info,(int) count+1,argv+i,exception); switch (*(option+1)) { case 'a': { if (LocaleCompare("affinity",option+1) == 0) { (void) SyncImagesSettings(mogrify_info,*images,exception); if (*option == '+') { (void) RemapImages(quantize_info,*images,(Image *) NULL, exception); break; } i++; break; } if (LocaleCompare("append",option+1) == 0) { Image *append_image; (void) SyncImagesSettings(mogrify_info,*images,exception); append_image=AppendImages(*images,*option == '-' ? MagickTrue : MagickFalse,exception); if (append_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=append_image; break; } if (LocaleCompare("average",option+1) == 0) { Image *average_image; /* Average an image sequence (deprecated). */ (void) SyncImagesSettings(mogrify_info,*images,exception); average_image=EvaluateImages(*images,MeanEvaluateOperator, exception); if (average_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=average_image; break; } break; } case 'c': { if (LocaleCompare("channel-fx",option+1) == 0) { Image *channel_image; (void) SyncImagesSettings(mogrify_info,*images,exception); channel_image=ChannelFxImage(*images,argv[i+1],exception); if (channel_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=channel_image; break; } if (LocaleCompare("clut",option+1) == 0) { Image *clut_image, *image; (void) SyncImagesSettings(mogrify_info,*images,exception); image=RemoveFirstImageFromList(images); clut_image=RemoveFirstImageFromList(images); if (clut_image == (Image *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), OptionError,"ImageSequenceRequired","`%s'",option); image=DestroyImage(image); status=MagickFalse; break; } (void) ClutImage(image,clut_image,interpolate_method,exception); clut_image=DestroyImage(clut_image); *images=DestroyImageList(*images); *images=image; break; } if (LocaleCompare("coalesce",option+1) == 0) { Image *coalesce_image; (void) SyncImagesSettings(mogrify_info,*images,exception); coalesce_image=CoalesceImages(*images,exception); if (coalesce_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=coalesce_image; break; } if (LocaleCompare("combine",option+1) == 0) { ColorspaceType colorspace; Image *combine_image; (void) SyncImagesSettings(mogrify_info,*images,exception); colorspace=(*images)->colorspace; if ((*images)->number_channels < GetImageListLength(*images)) colorspace=sRGBColorspace; if (*option == '+') colorspace=(ColorspaceType) ParseCommandOption( MagickColorspaceOptions,MagickFalse,argv[i+1]); combine_image=CombineImages(*images,colorspace,exception); if (combine_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=combine_image; break; } if (LocaleCompare("compare",option+1) == 0) { double distortion; Image *difference_image, *image, *reconstruct_image; MetricType metric; /* Mathematically and visually annotate the difference between an image and its reconstruction. */ (void) SyncImagesSettings(mogrify_info,*images,exception); image=RemoveFirstImageFromList(images); reconstruct_image=RemoveFirstImageFromList(images); if (reconstruct_image == (Image *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), OptionError,"ImageSequenceRequired","`%s'",option); image=DestroyImage(image); status=MagickFalse; break; } metric=UndefinedErrorMetric; option=GetImageOption(mogrify_info,"metric"); if (option != (const char *) NULL) metric=(MetricType) ParseCommandOption(MagickMetricOptions, MagickFalse,option); difference_image=CompareImages(image,reconstruct_image,metric, &distortion,exception); if (difference_image == (Image *) NULL) break; reconstruct_image=DestroyImage(reconstruct_image); image=DestroyImage(image); if (*images != (Image *) NULL) *images=DestroyImageList(*images); *images=difference_image; break; } if (LocaleCompare("complex",option+1) == 0) { ComplexOperator op; Image *complex_images; (void) SyncImageSettings(mogrify_info,*images,exception); op=(ComplexOperator) ParseCommandOption(MagickComplexOptions, MagickFalse,argv[i+1]); complex_images=ComplexImages(*images,op,exception); if (complex_images == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=complex_images; break; } if (LocaleCompare("composite",option+1) == 0) { CompositeOperator compose; const char* value; MagickBooleanType clip_to_self; Image *mask_image, *new_images, *source_image; RectangleInfo geometry; /* Compose value from "-compose" option only */ (void) SyncImageSettings(mogrify_info,*images,exception); value=GetImageOption(mogrify_info,"compose"); if (value == (const char *) NULL) compose=OverCompositeOp; /* use Over not source_image->compose */ else compose=(CompositeOperator) ParseCommandOption( MagickComposeOptions,MagickFalse,value); /* Get "clip-to-self" expert setting (false is normal) */ clip_to_self=GetCompositeClipToSelf(compose); value=GetImageOption(mogrify_info,"compose:clip-to-self"); if (value != (const char *) NULL) clip_to_self=IsStringTrue(value); value=GetImageOption(mogrify_info,"compose:outside-overlay"); if (value != (const char *) NULL) clip_to_self=IsStringFalse(value); /* deprecated */ new_images=RemoveFirstImageFromList(images); source_image=RemoveFirstImageFromList(images); if (source_image == (Image *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), OptionError,"ImageSequenceRequired","`%s'",option); new_images=DestroyImage(new_images); status=MagickFalse; break; } /* FUTURE: this should not be here! - should be part of -geometry */ if (source_image->geometry != (char *) NULL) { RectangleInfo resize_geometry; (void) ParseRegionGeometry(source_image,source_image->geometry, &resize_geometry,exception); if ((source_image->columns != resize_geometry.width) || (source_image->rows != resize_geometry.height)) { Image *resize_image; resize_image=ResizeImage(source_image,resize_geometry.width, resize_geometry.height,source_image->filter,exception); if (resize_image != (Image *) NULL) { source_image=DestroyImage(source_image); source_image=resize_image; } } } SetGeometry(source_image,&geometry); (void) ParseAbsoluteGeometry(source_image->geometry,&geometry); GravityAdjustGeometry(new_images->columns,new_images->rows, new_images->gravity,&geometry); mask_image=RemoveFirstImageFromList(images); if (mask_image == (Image *) NULL) status&=CompositeImage(new_images,source_image,compose, clip_to_self,geometry.x,geometry.y,exception); else { if ((compose == DisplaceCompositeOp) || (compose == DistortCompositeOp)) { status&=CompositeImage(source_image,mask_image, CopyGreenCompositeOp,MagickTrue,0,0,exception); status&=CompositeImage(new_images,source_image,compose, clip_to_self,geometry.x,geometry.y,exception); } else { Image *clone_image; clone_image=CloneImage(new_images,0,0,MagickTrue,exception); if (clone_image == (Image *) NULL) break; status&=CompositeImage(new_images,source_image,compose, clip_to_self,geometry.x,geometry.y,exception); status&=CompositeImage(new_images,mask_image, CopyAlphaCompositeOp,MagickTrue,0,0,exception); status&=CompositeImage(clone_image,new_images, OverCompositeOp,clip_to_self,0,0,exception); new_images=DestroyImageList(new_images); new_images=clone_image; } mask_image=DestroyImage(mask_image); } source_image=DestroyImage(source_image); *images=DestroyImageList(*images); *images=new_images; break; } if (LocaleCompare("copy",option+1) == 0) { Image *source_image; OffsetInfo offset; RectangleInfo geometry; /* Copy image pixels. */ (void) SyncImageSettings(mogrify_info,*images,exception); (void) ParsePageGeometry(*images,argv[i+2],&geometry,exception); offset.x=geometry.x; offset.y=geometry.y; source_image=(*images); if (source_image->next != (Image *) NULL) source_image=source_image->next; (void) ParsePageGeometry(source_image,argv[i+1],&geometry, exception); status=CopyImagePixels(*images,source_image,&geometry,&offset, exception); break; } break; } case 'd': { if (LocaleCompare("deconstruct",option+1) == 0) { Image *deconstruct_image; (void) SyncImagesSettings(mogrify_info,*images,exception); deconstruct_image=CompareImagesLayers(*images,CompareAnyLayer, exception); if (deconstruct_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=deconstruct_image; break; } if (LocaleCompare("delete",option+1) == 0) { if (*option == '+') DeleteImages(images,"-1",exception); else DeleteImages(images,argv[i+1],exception); break; } if (LocaleCompare("dither",option+1) == 0) { if (*option == '+') { quantize_info->dither_method=NoDitherMethod; break; } quantize_info->dither_method=(DitherMethod) ParseCommandOption( MagickDitherOptions,MagickFalse,argv[i+1]); break; } if (LocaleCompare("duplicate",option+1) == 0) { Image *duplicate_images; if (*option == '+') duplicate_images=DuplicateImages(*images,1,"-1",exception); else { const char *p; size_t number_duplicates; number_duplicates=(size_t) StringToLong(argv[i+1]); p=strchr(argv[i+1],','); if (p == (const char *) NULL) duplicate_images=DuplicateImages(*images,number_duplicates, "-1",exception); else duplicate_images=DuplicateImages(*images,number_duplicates,p, exception); } AppendImageToList(images, duplicate_images); (void) SyncImagesSettings(mogrify_info,*images,exception); break; } break; } case 'e': { if (LocaleCompare("evaluate-sequence",option+1) == 0) { Image *evaluate_image; MagickEvaluateOperator op; (void) SyncImageSettings(mogrify_info,*images,exception); op=(MagickEvaluateOperator) ParseCommandOption( MagickEvaluateOptions,MagickFalse,argv[i+1]); evaluate_image=EvaluateImages(*images,op,exception); if (evaluate_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=evaluate_image; break; } break; } case 'f': { if (LocaleCompare("fft",option+1) == 0) { Image *fourier_image; /* Implements the discrete Fourier transform (DFT). */ (void) SyncImageSettings(mogrify_info,*images,exception); fourier_image=ForwardFourierTransformImage(*images,*option == '-' ? MagickTrue : MagickFalse,exception); if (fourier_image == (Image *) NULL) break; *images=DestroyImageList(*images); *images=fourier_image; break; } if (LocaleCompare("flatten",option+1) == 0) { Image *flatten_image; (void) SyncImagesSettings(mogrify_info,*images,exception); flatten_image=MergeImageLayers(*images,FlattenLayer,exception); if (flatten_image == (Image *) NULL) break; *images=DestroyImageList(*images); *images=flatten_image; break; } if (LocaleCompare("fx",option+1) == 0) { Image *fx_image; (void) SyncImagesSettings(mogrify_info,*images,exception); fx_image=FxImage(*images,argv[i+1],exception); if (fx_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=fx_image; break; } break; } case 'h': { if (LocaleCompare("hald-clut",option+1) == 0) { Image *hald_image, *image; (void) SyncImagesSettings(mogrify_info,*images,exception); image=RemoveFirstImageFromList(images); hald_image=RemoveFirstImageFromList(images); if (hald_image == (Image *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), OptionError,"ImageSequenceRequired","`%s'",option); image=DestroyImage(image); status=MagickFalse; break; } (void) HaldClutImage(image,hald_image,exception); hald_image=DestroyImage(hald_image); if (*images != (Image *) NULL) *images=DestroyImageList(*images); *images=image; break; } break; } case 'i': { if (LocaleCompare("ift",option+1) == 0) { Image *fourier_image, *magnitude_image, *phase_image; /* Implements the inverse fourier discrete Fourier transform (DFT). */ (void) SyncImagesSettings(mogrify_info,*images,exception); magnitude_image=RemoveFirstImageFromList(images); phase_image=RemoveFirstImageFromList(images); if (phase_image == (Image *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), OptionError,"ImageSequenceRequired","`%s'",option); magnitude_image=DestroyImage(magnitude_image); status=MagickFalse; break; } fourier_image=InverseFourierTransformImage(magnitude_image, phase_image,*option == '-' ? MagickTrue : MagickFalse,exception); magnitude_image=DestroyImage(magnitude_image); phase_image=DestroyImage(phase_image); if (fourier_image == (Image *) NULL) break; if (*images != (Image *) NULL) *images=DestroyImageList(*images); *images=fourier_image; break; } if (LocaleCompare("insert",option+1) == 0) { Image *p, *q; index=0; if (*option != '+') index=(ssize_t) StringToLong(argv[i+1]); p=RemoveLastImageFromList(images); if (p == (Image *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), OptionError,"NoSuchImage","`%s'",argv[i+1]); status=MagickFalse; break; } q=p; if (index == 0) PrependImageToList(images,q); else if (index == (ssize_t) GetImageListLength(*images)) AppendImageToList(images,q); else { q=GetImageFromList(*images,index-1); if (q == (Image *) NULL) { p=DestroyImage(p); (void) ThrowMagickException(exception,GetMagickModule(), OptionError,"NoSuchImage","`%s'",argv[i+1]); status=MagickFalse; break; } InsertImageInList(&q,p); } *images=GetFirstImageInList(q); break; } if (LocaleCompare("interpolate",option+1) == 0) { interpolate_method=(PixelInterpolateMethod) ParseCommandOption( MagickInterpolateOptions,MagickFalse,argv[i+1]); break; } break; } case 'l': { if (LocaleCompare("layers",option+1) == 0) { Image *layers; LayerMethod method; (void) SyncImagesSettings(mogrify_info,*images,exception); layers=(Image *) NULL; method=(LayerMethod) ParseCommandOption(MagickLayerOptions, MagickFalse,argv[i+1]); switch (method) { case CoalesceLayer: { layers=CoalesceImages(*images,exception); break; } case CompareAnyLayer: case CompareClearLayer: case CompareOverlayLayer: default: { layers=CompareImagesLayers(*images,method,exception); break; } case MergeLayer: case FlattenLayer: case MosaicLayer: case TrimBoundsLayer: { layers=MergeImageLayers(*images,method,exception); break; } case DisposeLayer: { layers=DisposeImages(*images,exception); break; } case OptimizeImageLayer: { layers=OptimizeImageLayers(*images,exception); break; } case OptimizePlusLayer: { layers=OptimizePlusImageLayers(*images,exception); break; } case OptimizeTransLayer: { OptimizeImageTransparency(*images,exception); break; } case RemoveDupsLayer: { RemoveDuplicateLayers(images,exception); break; } case RemoveZeroLayer: { RemoveZeroDelayLayers(images,exception); break; } case OptimizeLayer: { /* General Purpose, GIF Animation Optimizer. */ layers=CoalesceImages(*images,exception); if (layers == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=layers; layers=OptimizeImageLayers(*images,exception); if (layers == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=layers; layers=(Image *) NULL; OptimizeImageTransparency(*images,exception); (void) RemapImages(quantize_info,*images,(Image *) NULL, exception); break; } case CompositeLayer: { CompositeOperator compose; Image *source; RectangleInfo geometry; /* Split image sequence at the first 'NULL:' image. */ source=(*images); while (source != (Image *) NULL) { source=GetNextImageInList(source); if ((source != (Image *) NULL) && (LocaleCompare(source->magick,"NULL") == 0)) break; } if (source != (Image *) NULL) { if ((GetPreviousImageInList(source) == (Image *) NULL) || (GetNextImageInList(source) == (Image *) NULL)) source=(Image *) NULL; else { /* Separate the two lists, junk the null: image. */ source=SplitImageList(source->previous); DeleteImageFromList(&source); } } if (source == (Image *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), OptionError,"MissingNullSeparator","layers Composite"); status=MagickFalse; break; } /* Adjust offset with gravity and virtual canvas. */ SetGeometry(*images,&geometry); (void) ParseAbsoluteGeometry((*images)->geometry,&geometry); geometry.width=source->page.width != 0 ? source->page.width : source->columns; geometry.height=source->page.height != 0 ? source->page.height : source->rows; GravityAdjustGeometry((*images)->page.width != 0 ? (*images)->page.width : (*images)->columns, (*images)->page.height != 0 ? (*images)->page.height : (*images)->rows,(*images)->gravity,&geometry); compose=OverCompositeOp; option=GetImageOption(mogrify_info,"compose"); if (option != (const char *) NULL) compose=(CompositeOperator) ParseCommandOption( MagickComposeOptions,MagickFalse,option); CompositeLayers(*images,compose,source,geometry.x,geometry.y, exception); source=DestroyImageList(source); break; } } if (layers == (Image *) NULL) break; *images=DestroyImageList(*images); *images=layers; break; } break; } case 'm': { if (LocaleCompare("map",option+1) == 0) { (void) SyncImagesSettings(mogrify_info,*images,exception); if (*option == '+') { (void) RemapImages(quantize_info,*images,(Image *) NULL, exception); break; } i++; break; } if (LocaleCompare("maximum",option+1) == 0) { Image *maximum_image; /* Maximum image sequence (deprecated). */ (void) SyncImagesSettings(mogrify_info,*images,exception); maximum_image=EvaluateImages(*images,MaxEvaluateOperator,exception); if (maximum_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=maximum_image; break; } if (LocaleCompare("minimum",option+1) == 0) { Image *minimum_image; /* Minimum image sequence (deprecated). */ (void) SyncImagesSettings(mogrify_info,*images,exception); minimum_image=EvaluateImages(*images,MinEvaluateOperator,exception); if (minimum_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=minimum_image; break; } if (LocaleCompare("morph",option+1) == 0) { Image *morph_image; (void) SyncImagesSettings(mogrify_info,*images,exception); morph_image=MorphImages(*images,StringToUnsignedLong(argv[i+1]), exception); if (morph_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=morph_image; break; } if (LocaleCompare("mosaic",option+1) == 0) { Image *mosaic_image; (void) SyncImagesSettings(mogrify_info,*images,exception); mosaic_image=MergeImageLayers(*images,MosaicLayer,exception); if (mosaic_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=mosaic_image; break; } break; } case 'p': { if (LocaleCompare("poly",option+1) == 0) { char *args, token[MagickPathExtent]; const char *p; double *arguments; Image *polynomial_image; register ssize_t x; size_t number_arguments; /* Polynomial image. */ (void) SyncImageSettings(mogrify_info,*images,exception); args=InterpretImageProperties(mogrify_info,*images,argv[i+1], exception); if (args == (char *) NULL) break; p=(char *) args; for (x=0; *p != '\0'; x++) { GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') GetNextToken(p,&p,MagickPathExtent,token); } number_arguments=(size_t) x; arguments=(double *) AcquireQuantumMemory(number_arguments, sizeof(*arguments)); if (arguments == (double *) NULL) ThrowWandFatalException(ResourceLimitFatalError, "MemoryAllocationFailed",(*images)->filename); (void) memset(arguments,0,number_arguments* sizeof(*arguments)); p=(char *) args; for (x=0; (x < (ssize_t) number_arguments) && (*p != '\0'); x++) { GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') GetNextToken(p,&p,MagickPathExtent,token); arguments[x]=StringToDouble(token,(char **) NULL); } args=DestroyString(args); polynomial_image=PolynomialImage(*images,number_arguments >> 1, arguments,exception); arguments=(double *) RelinquishMagickMemory(arguments); if (polynomial_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=polynomial_image; } if (LocaleCompare("print",option+1) == 0) { char *string; (void) SyncImagesSettings(mogrify_info,*images,exception); string=InterpretImageProperties(mogrify_info,*images,argv[i+1], exception); if (string == (char *) NULL) break; (void) FormatLocaleFile(stdout,"%s",string); string=DestroyString(string); } if (LocaleCompare("process",option+1) == 0) { char **arguments; int j, number_arguments; (void) SyncImagesSettings(mogrify_info,*images,exception); arguments=StringToArgv(argv[i+1],&number_arguments); if (arguments == (char **) NULL) break; if ((argc > 1) && (strchr(arguments[1],'=') != (char *) NULL)) { char breaker, quote, *token; const char *argument; int next, token_status; size_t length; TokenInfo *token_info; /* Support old style syntax, filter="-option arg". */ length=strlen(argv[i+1]); token=(char *) NULL; if (~length >= (MagickPathExtent-1)) token=(char *) AcquireQuantumMemory(length+MagickPathExtent, sizeof(*token)); if (token == (char *) NULL) break; next=0; argument=argv[i+1]; token_info=AcquireTokenInfo(); token_status=Tokenizer(token_info,0,token,length,argument,"", "=","\"",'\0',&breaker,&next,&quote); token_info=DestroyTokenInfo(token_info); if (token_status == 0) { const char *arg; arg=(&(argument[next])); (void) InvokeDynamicImageFilter(token,&(*images),1,&arg, exception); } token=DestroyString(token); break; } (void) SubstituteString(&arguments[1],"-",""); (void) InvokeDynamicImageFilter(arguments[1],&(*images), number_arguments-2,(const char **) arguments+2,exception); for (j=0; j < number_arguments; j++) arguments[j]=DestroyString(arguments[j]); arguments=(char **) RelinquishMagickMemory(arguments); break; } break; } case 'r': { if (LocaleCompare("reverse",option+1) == 0) { ReverseImageList(images); break; } break; } case 's': { if (LocaleCompare("smush",option+1) == 0) { Image *smush_image; ssize_t offset; (void) SyncImagesSettings(mogrify_info,*images,exception); offset=(ssize_t) StringToLong(argv[i+1]); smush_image=SmushImages(*images,*option == '-' ? MagickTrue : MagickFalse,offset,exception); if (smush_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=smush_image; break; } if (LocaleCompare("swap",option+1) == 0) { Image *p, *q, *u, *v; ssize_t swap_index; index=(-1); swap_index=(-2); if (*option != '+') { GeometryInfo geometry_info; MagickStatusType flags; swap_index=(-1); flags=ParseGeometry(argv[i+1],&geometry_info); index=(ssize_t) geometry_info.rho; if ((flags & SigmaValue) != 0) swap_index=(ssize_t) geometry_info.sigma; } p=GetImageFromList(*images,index); q=GetImageFromList(*images,swap_index); if ((p == (Image *) NULL) || (q == (Image *) NULL)) { (void) ThrowMagickException(exception,GetMagickModule(), OptionError,"NoSuchImage","`%s'",(*images)->filename); status=MagickFalse; break; } if (p == q) break; u=CloneImage(p,0,0,MagickTrue,exception); if (u == (Image *) NULL) break; v=CloneImage(q,0,0,MagickTrue,exception); if (v == (Image *) NULL) { u=DestroyImage(u); break; } ReplaceImageInList(&p,v); ReplaceImageInList(&q,u); *images=GetFirstImageInList(q); break; } break; } case 'w': { if (LocaleCompare("write",option+1) == 0) { char key[MagickPathExtent]; Image *write_images; ImageInfo *write_info; (void) SyncImagesSettings(mogrify_info,*images,exception); (void) FormatLocaleString(key,MagickPathExtent,"cache:%s", argv[i+1]); (void) DeleteImageRegistry(key); write_images=(*images); if (*option == '+') write_images=CloneImageList(*images,exception); write_info=CloneImageInfo(mogrify_info); status&=WriteImages(write_info,write_images,argv[i+1],exception); write_info=DestroyImageInfo(write_info); if (*option == '+') write_images=DestroyImageList(write_images); break; } break; } default: break; } i+=count; } quantize_info=DestroyQuantizeInfo(quantize_info); mogrify_info=DestroyImageInfo(mogrify_info); status&=MogrifyImageInfo(image_info,argc,argv,exception); return(status != 0 ? MagickTrue : MagickFalse); }
170,195
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 coroutine_fn v9fs_link(void *opaque) { V9fsPDU *pdu = opaque; int32_t dfid, oldfid; V9fsFidState *dfidp, *oldfidp; V9fsString name; size_t offset = 7; int err = 0; v9fs_string_init(&name); err = pdu_unmarshal(pdu, offset, "dds", &dfid, &oldfid, &name); if (err < 0) { goto out_nofid; } trace_v9fs_link(pdu->tag, pdu->id, dfid, oldfid, name.data); if (name_is_illegal(name.data)) { err = -ENOENT; goto out_nofid; } if (!strcmp(".", name.data) || !strcmp("..", name.data)) { err = -EEXIST; goto out_nofid; } dfidp = get_fid(pdu, dfid); if (dfidp == NULL) { err = -ENOENT; goto out_nofid; } oldfidp = get_fid(pdu, oldfid); if (oldfidp == NULL) { err = -ENOENT; goto out; } err = v9fs_co_link(pdu, oldfidp, dfidp, &name); if (!err) { err = offset; } out: put_fid(pdu, dfidp); out_nofid: pdu_complete(pdu, err); } Commit Message: CWE ID: CWE-399
static void coroutine_fn v9fs_link(void *opaque) { V9fsPDU *pdu = opaque; int32_t dfid, oldfid; V9fsFidState *dfidp, *oldfidp; V9fsString name; size_t offset = 7; int err = 0; v9fs_string_init(&name); err = pdu_unmarshal(pdu, offset, "dds", &dfid, &oldfid, &name); if (err < 0) { goto out_nofid; } trace_v9fs_link(pdu->tag, pdu->id, dfid, oldfid, name.data); if (name_is_illegal(name.data)) { err = -ENOENT; goto out_nofid; } if (!strcmp(".", name.data) || !strcmp("..", name.data)) { err = -EEXIST; goto out_nofid; } dfidp = get_fid(pdu, dfid); if (dfidp == NULL) { err = -ENOENT; goto out_nofid; } oldfidp = get_fid(pdu, oldfid); if (oldfidp == NULL) { err = -ENOENT; goto out; } err = v9fs_co_link(pdu, oldfidp, dfidp, &name); if (!err) { err = offset; } put_fid(pdu, oldfidp); out: put_fid(pdu, dfidp); out_nofid: pdu_complete(pdu, err); }
164,907
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 CSSDefaultStyleSheets::initDefaultStyle(Element* root) { if (!defaultStyle) { if (!root || elementCanUseSimpleDefaultStyle(root)) loadSimpleDefaultStyle(); else loadFullDefaultStyle(); } } Commit Message: Remove the Simple Default Stylesheet, it's just a foot-gun. We've been bitten by the Simple Default Stylesheet being out of sync with the real html.css twice this week. The Simple Default Stylesheet was invented years ago for Mac: http://trac.webkit.org/changeset/36135 It nicely handles the case where you just want to create a single WebView and parse some simple HTML either without styling said HTML, or only to display a small string, etc. Note that this optimization/complexity *only* helps for the very first document, since the default stylesheets are all static (process-global) variables. Since any real page on the internet uses a tag not covered by the simple default stylesheet, not real load benefits from this optimization. Only uses of WebView which were just rendering small bits of text might have benefited from this. about:blank would also have used this sheet. This was a common application for some uses of WebView back in those days. These days, even with WebView on Android, there are likely much larger overheads than parsing the html.css stylesheet, so making it required seems like the right tradeoff of code-simplicity for this case. BUG=319556 Review URL: https://codereview.chromium.org/73723005 git-svn-id: svn://svn.chromium.org/blink/trunk@162153 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399
void CSSDefaultStyleSheets::initDefaultStyle(Element* root) void CSSDefaultStyleSheets::loadDefaultStylesheetIfNecessary() { if (!defaultStyle) loadDefaultStyle(); }
171,580
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: ext4_xattr_release_block(handle_t *handle, struct inode *inode, struct buffer_head *bh) { struct mb_cache_entry *ce = NULL; int error = 0; struct mb_cache *ext4_mb_cache = EXT4_GET_MB_CACHE(inode); ce = mb_cache_entry_get(ext4_mb_cache, bh->b_bdev, bh->b_blocknr); BUFFER_TRACE(bh, "get_write_access"); error = ext4_journal_get_write_access(handle, bh); if (error) goto out; lock_buffer(bh); if (BHDR(bh)->h_refcount == cpu_to_le32(1)) { ea_bdebug(bh, "refcount now=0; freeing"); if (ce) mb_cache_entry_free(ce); get_bh(bh); unlock_buffer(bh); ext4_free_blocks(handle, inode, bh, 0, 1, EXT4_FREE_BLOCKS_METADATA | EXT4_FREE_BLOCKS_FORGET); } else { le32_add_cpu(&BHDR(bh)->h_refcount, -1); if (ce) mb_cache_entry_release(ce); /* * Beware of this ugliness: Releasing of xattr block references * from different inodes can race and so we have to protect * from a race where someone else frees the block (and releases * its journal_head) before we are done dirtying the buffer. In * nojournal mode this race is harmless and we actually cannot * call ext4_handle_dirty_xattr_block() with locked buffer as * that function can call sync_dirty_buffer() so for that case * we handle the dirtying after unlocking the buffer. */ if (ext4_handle_valid(handle)) error = ext4_handle_dirty_xattr_block(handle, inode, bh); unlock_buffer(bh); if (!ext4_handle_valid(handle)) error = ext4_handle_dirty_xattr_block(handle, inode, bh); if (IS_SYNC(inode)) ext4_handle_sync(handle); dquot_free_block(inode, EXT4_C2B(EXT4_SB(inode->i_sb), 1)); ea_bdebug(bh, "refcount now=%d; releasing", le32_to_cpu(BHDR(bh)->h_refcount)); } out: ext4_std_error(inode->i_sb, error); return; } Commit Message: ext4: convert to mbcache2 The conversion is generally straightforward. The only tricky part is that xattr block corresponding to found mbcache entry can get freed before we get buffer lock for that block. So we have to check whether the entry is still valid after getting buffer lock. Signed-off-by: Jan Kara <[email protected]> Signed-off-by: Theodore Ts'o <[email protected]> CWE ID: CWE-19
ext4_xattr_release_block(handle_t *handle, struct inode *inode, struct buffer_head *bh) { int error = 0; BUFFER_TRACE(bh, "get_write_access"); error = ext4_journal_get_write_access(handle, bh); if (error) goto out; lock_buffer(bh); if (BHDR(bh)->h_refcount == cpu_to_le32(1)) { __u32 hash = le32_to_cpu(BHDR(bh)->h_hash); ea_bdebug(bh, "refcount now=0; freeing"); /* * This must happen under buffer lock for * ext4_xattr_block_set() to reliably detect freed block */ mb2_cache_entry_delete_block(EXT4_GET_MB_CACHE(inode), hash, bh->b_blocknr); get_bh(bh); unlock_buffer(bh); ext4_free_blocks(handle, inode, bh, 0, 1, EXT4_FREE_BLOCKS_METADATA | EXT4_FREE_BLOCKS_FORGET); } else { le32_add_cpu(&BHDR(bh)->h_refcount, -1); /* * Beware of this ugliness: Releasing of xattr block references * from different inodes can race and so we have to protect * from a race where someone else frees the block (and releases * its journal_head) before we are done dirtying the buffer. In * nojournal mode this race is harmless and we actually cannot * call ext4_handle_dirty_xattr_block() with locked buffer as * that function can call sync_dirty_buffer() so for that case * we handle the dirtying after unlocking the buffer. */ if (ext4_handle_valid(handle)) error = ext4_handle_dirty_xattr_block(handle, inode, bh); unlock_buffer(bh); if (!ext4_handle_valid(handle)) error = ext4_handle_dirty_xattr_block(handle, inode, bh); if (IS_SYNC(inode)) ext4_handle_sync(handle); dquot_free_block(inode, EXT4_C2B(EXT4_SB(inode->i_sb), 1)); ea_bdebug(bh, "refcount now=%d; releasing", le32_to_cpu(BHDR(bh)->h_refcount)); } out: ext4_std_error(inode->i_sb, error); return; }
169,996
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: esis_print(netdissect_options *ndo, const uint8_t *pptr, u_int length) { const uint8_t *optr; u_int li,esis_pdu_type,source_address_length, source_address_number; const struct esis_header_t *esis_header; if (!ndo->ndo_eflag) ND_PRINT((ndo, "ES-IS")); if (length <= 2) { ND_PRINT((ndo, ndo->ndo_qflag ? "bad pkt!" : "no header at all!")); return; } esis_header = (const struct esis_header_t *) pptr; ND_TCHECK(*esis_header); li = esis_header->length_indicator; optr = pptr; /* * Sanity checking of the header. */ if (esis_header->nlpid != NLPID_ESIS) { ND_PRINT((ndo, " nlpid 0x%02x packet not supported", esis_header->nlpid)); return; } if (esis_header->version != ESIS_VERSION) { ND_PRINT((ndo, " version %d packet not supported", esis_header->version)); return; } if (li > length) { ND_PRINT((ndo, " length indicator(%u) > PDU size (%u)!", li, length)); return; } if (li < sizeof(struct esis_header_t) + 2) { ND_PRINT((ndo, " length indicator %u < min PDU size:", li)); while (pptr < ndo->ndo_snapend) ND_PRINT((ndo, "%02X", *pptr++)); return; } esis_pdu_type = esis_header->type & ESIS_PDU_TYPE_MASK; if (ndo->ndo_vflag < 1) { ND_PRINT((ndo, "%s%s, length %u", ndo->ndo_eflag ? "" : ", ", tok2str(esis_pdu_values,"unknown type (%u)",esis_pdu_type), length)); return; } else ND_PRINT((ndo, "%slength %u\n\t%s (%u)", ndo->ndo_eflag ? "" : ", ", length, tok2str(esis_pdu_values,"unknown type: %u", esis_pdu_type), esis_pdu_type)); ND_PRINT((ndo, ", v: %u%s", esis_header->version, esis_header->version == ESIS_VERSION ? "" : "unsupported" )); ND_PRINT((ndo, ", checksum: 0x%04x", EXTRACT_16BITS(esis_header->cksum))); osi_print_cksum(ndo, pptr, EXTRACT_16BITS(esis_header->cksum), 7, li); ND_PRINT((ndo, ", holding time: %us, length indicator: %u", EXTRACT_16BITS(esis_header->holdtime), li)); if (ndo->ndo_vflag > 1) print_unknown_data(ndo, optr, "\n\t", sizeof(struct esis_header_t)); pptr += sizeof(struct esis_header_t); li -= sizeof(struct esis_header_t); switch (esis_pdu_type) { case ESIS_PDU_REDIRECT: { const uint8_t *dst, *snpa, *neta; u_int dstl, snpal, netal; ND_TCHECK(*pptr); if (li < 1) { ND_PRINT((ndo, ", bad redirect/li")); return; } dstl = *pptr; pptr++; li--; ND_TCHECK2(*pptr, dstl); if (li < dstl) { ND_PRINT((ndo, ", bad redirect/li")); return; } dst = pptr; pptr += dstl; li -= dstl; ND_PRINT((ndo, "\n\t %s", isonsap_string(ndo, dst, dstl))); ND_TCHECK(*pptr); if (li < 1) { ND_PRINT((ndo, ", bad redirect/li")); return; } snpal = *pptr; pptr++; li--; ND_TCHECK2(*pptr, snpal); if (li < snpal) { ND_PRINT((ndo, ", bad redirect/li")); return; } snpa = pptr; pptr += snpal; li -= snpal; ND_TCHECK(*pptr); if (li < 1) { ND_PRINT((ndo, ", bad redirect/li")); return; } netal = *pptr; pptr++; ND_TCHECK2(*pptr, netal); if (li < netal) { ND_PRINT((ndo, ", bad redirect/li")); return; } neta = pptr; pptr += netal; li -= netal; if (netal == 0) ND_PRINT((ndo, "\n\t %s", etheraddr_string(ndo, snpa))); else ND_PRINT((ndo, "\n\t %s", isonsap_string(ndo, neta, netal))); break; } case ESIS_PDU_ESH: ND_TCHECK(*pptr); if (li < 1) { ND_PRINT((ndo, ", bad esh/li")); return; } source_address_number = *pptr; pptr++; li--; ND_PRINT((ndo, "\n\t Number of Source Addresses: %u", source_address_number)); while (source_address_number > 0) { ND_TCHECK(*pptr); if (li < 1) { ND_PRINT((ndo, ", bad esh/li")); return; } source_address_length = *pptr; pptr++; li--; ND_TCHECK2(*pptr, source_address_length); if (li < source_address_length) { ND_PRINT((ndo, ", bad esh/li")); return; } ND_PRINT((ndo, "\n\t NET (length: %u): %s", source_address_length, isonsap_string(ndo, pptr, source_address_length))); pptr += source_address_length; li -= source_address_length; source_address_number--; } break; case ESIS_PDU_ISH: { ND_TCHECK(*pptr); if (li < 1) { ND_PRINT((ndo, ", bad ish/li")); return; } source_address_length = *pptr; pptr++; li--; ND_TCHECK2(*pptr, source_address_length); if (li < source_address_length) { ND_PRINT((ndo, ", bad ish/li")); return; } ND_PRINT((ndo, "\n\t NET (length: %u): %s", source_address_length, isonsap_string(ndo, pptr, source_address_length))); pptr += source_address_length; li -= source_address_length; break; } default: if (ndo->ndo_vflag <= 1) { if (pptr < ndo->ndo_snapend) print_unknown_data(ndo, pptr, "\n\t ", ndo->ndo_snapend - pptr); } return; } /* now walk the options */ while (li != 0) { u_int op, opli; const uint8_t *tptr; if (li < 2) { ND_PRINT((ndo, ", bad opts/li")); return; } ND_TCHECK2(*pptr, 2); op = *pptr++; opli = *pptr++; li -= 2; if (opli > li) { ND_PRINT((ndo, ", opt (%d) too long", op)); return; } li -= opli; tptr = pptr; ND_PRINT((ndo, "\n\t %s Option #%u, length %u, value: ", tok2str(esis_option_values,"Unknown",op), op, opli)); switch (op) { case ESIS_OPTION_ES_CONF_TIME: if (opli == 2) { ND_TCHECK2(*pptr, 2); ND_PRINT((ndo, "%us", EXTRACT_16BITS(tptr))); } else ND_PRINT((ndo, "(bad length)")); break; case ESIS_OPTION_PROTOCOLS: while (opli>0) { ND_TCHECK(*pptr); ND_PRINT((ndo, "%s (0x%02x)", tok2str(nlpid_values, "unknown", *tptr), *tptr)); if (opli>1) /* further NPLIDs ? - put comma */ ND_PRINT((ndo, ", ")); tptr++; opli--; } break; /* * FIXME those are the defined Options that lack a decoder * you are welcome to contribute code ;-) */ case ESIS_OPTION_QOS_MAINTENANCE: case ESIS_OPTION_SECURITY: case ESIS_OPTION_PRIORITY: case ESIS_OPTION_ADDRESS_MASK: case ESIS_OPTION_SNPA_MASK: default: print_unknown_data(ndo, tptr, "\n\t ", opli); break; } if (ndo->ndo_vflag > 1) print_unknown_data(ndo, pptr, "\n\t ", opli); pptr += opli; } trunc: return; } Commit Message: CVE-2017-13016/ES-IS: Fix printing of addresses in RD PDUs. Always print the SNPA, and flag it as such; only print it as a MAC address if it's 6 bytes long. Identify the NET as such. This fixes a buffer over-read discovered by Bhargava Shastry, SecT/TU Berlin. Add tests using the capture files supplied by the reporter(s), modified so the capture files won't be rejected as an invalid capture. CWE ID: CWE-125
esis_print(netdissect_options *ndo, const uint8_t *pptr, u_int length) { const uint8_t *optr; u_int li,esis_pdu_type,source_address_length, source_address_number; const struct esis_header_t *esis_header; if (!ndo->ndo_eflag) ND_PRINT((ndo, "ES-IS")); if (length <= 2) { ND_PRINT((ndo, ndo->ndo_qflag ? "bad pkt!" : "no header at all!")); return; } esis_header = (const struct esis_header_t *) pptr; ND_TCHECK(*esis_header); li = esis_header->length_indicator; optr = pptr; /* * Sanity checking of the header. */ if (esis_header->nlpid != NLPID_ESIS) { ND_PRINT((ndo, " nlpid 0x%02x packet not supported", esis_header->nlpid)); return; } if (esis_header->version != ESIS_VERSION) { ND_PRINT((ndo, " version %d packet not supported", esis_header->version)); return; } if (li > length) { ND_PRINT((ndo, " length indicator(%u) > PDU size (%u)!", li, length)); return; } if (li < sizeof(struct esis_header_t) + 2) { ND_PRINT((ndo, " length indicator %u < min PDU size:", li)); while (pptr < ndo->ndo_snapend) ND_PRINT((ndo, "%02X", *pptr++)); return; } esis_pdu_type = esis_header->type & ESIS_PDU_TYPE_MASK; if (ndo->ndo_vflag < 1) { ND_PRINT((ndo, "%s%s, length %u", ndo->ndo_eflag ? "" : ", ", tok2str(esis_pdu_values,"unknown type (%u)",esis_pdu_type), length)); return; } else ND_PRINT((ndo, "%slength %u\n\t%s (%u)", ndo->ndo_eflag ? "" : ", ", length, tok2str(esis_pdu_values,"unknown type: %u", esis_pdu_type), esis_pdu_type)); ND_PRINT((ndo, ", v: %u%s", esis_header->version, esis_header->version == ESIS_VERSION ? "" : "unsupported" )); ND_PRINT((ndo, ", checksum: 0x%04x", EXTRACT_16BITS(esis_header->cksum))); osi_print_cksum(ndo, pptr, EXTRACT_16BITS(esis_header->cksum), 7, li); ND_PRINT((ndo, ", holding time: %us, length indicator: %u", EXTRACT_16BITS(esis_header->holdtime), li)); if (ndo->ndo_vflag > 1) print_unknown_data(ndo, optr, "\n\t", sizeof(struct esis_header_t)); pptr += sizeof(struct esis_header_t); li -= sizeof(struct esis_header_t); switch (esis_pdu_type) { case ESIS_PDU_REDIRECT: { const uint8_t *dst, *snpa, *neta; u_int dstl, snpal, netal; ND_TCHECK(*pptr); if (li < 1) { ND_PRINT((ndo, ", bad redirect/li")); return; } dstl = *pptr; pptr++; li--; ND_TCHECK2(*pptr, dstl); if (li < dstl) { ND_PRINT((ndo, ", bad redirect/li")); return; } dst = pptr; pptr += dstl; li -= dstl; ND_PRINT((ndo, "\n\t %s", isonsap_string(ndo, dst, dstl))); ND_TCHECK(*pptr); if (li < 1) { ND_PRINT((ndo, ", bad redirect/li")); return; } snpal = *pptr; pptr++; li--; ND_TCHECK2(*pptr, snpal); if (li < snpal) { ND_PRINT((ndo, ", bad redirect/li")); return; } snpa = pptr; pptr += snpal; li -= snpal; ND_TCHECK(*pptr); if (li < 1) { ND_PRINT((ndo, ", bad redirect/li")); return; } netal = *pptr; pptr++; ND_TCHECK2(*pptr, netal); if (li < netal) { ND_PRINT((ndo, ", bad redirect/li")); return; } neta = pptr; pptr += netal; li -= netal; if (snpal == 6) ND_PRINT((ndo, "\n\t SNPA (length: %u): %s", snpal, etheraddr_string(ndo, snpa))); else ND_PRINT((ndo, "\n\t SNPA (length: %u): %s", snpal, linkaddr_string(ndo, snpa, LINKADDR_OTHER, snpal))); if (netal != 0) ND_PRINT((ndo, "\n\t NET (length: %u) %s", netal, isonsap_string(ndo, neta, netal))); break; } case ESIS_PDU_ESH: ND_TCHECK(*pptr); if (li < 1) { ND_PRINT((ndo, ", bad esh/li")); return; } source_address_number = *pptr; pptr++; li--; ND_PRINT((ndo, "\n\t Number of Source Addresses: %u", source_address_number)); while (source_address_number > 0) { ND_TCHECK(*pptr); if (li < 1) { ND_PRINT((ndo, ", bad esh/li")); return; } source_address_length = *pptr; pptr++; li--; ND_TCHECK2(*pptr, source_address_length); if (li < source_address_length) { ND_PRINT((ndo, ", bad esh/li")); return; } ND_PRINT((ndo, "\n\t NET (length: %u): %s", source_address_length, isonsap_string(ndo, pptr, source_address_length))); pptr += source_address_length; li -= source_address_length; source_address_number--; } break; case ESIS_PDU_ISH: { ND_TCHECK(*pptr); if (li < 1) { ND_PRINT((ndo, ", bad ish/li")); return; } source_address_length = *pptr; pptr++; li--; ND_TCHECK2(*pptr, source_address_length); if (li < source_address_length) { ND_PRINT((ndo, ", bad ish/li")); return; } ND_PRINT((ndo, "\n\t NET (length: %u): %s", source_address_length, isonsap_string(ndo, pptr, source_address_length))); pptr += source_address_length; li -= source_address_length; break; } default: if (ndo->ndo_vflag <= 1) { if (pptr < ndo->ndo_snapend) print_unknown_data(ndo, pptr, "\n\t ", ndo->ndo_snapend - pptr); } return; } /* now walk the options */ while (li != 0) { u_int op, opli; const uint8_t *tptr; if (li < 2) { ND_PRINT((ndo, ", bad opts/li")); return; } ND_TCHECK2(*pptr, 2); op = *pptr++; opli = *pptr++; li -= 2; if (opli > li) { ND_PRINT((ndo, ", opt (%d) too long", op)); return; } li -= opli; tptr = pptr; ND_PRINT((ndo, "\n\t %s Option #%u, length %u, value: ", tok2str(esis_option_values,"Unknown",op), op, opli)); switch (op) { case ESIS_OPTION_ES_CONF_TIME: if (opli == 2) { ND_TCHECK2(*pptr, 2); ND_PRINT((ndo, "%us", EXTRACT_16BITS(tptr))); } else ND_PRINT((ndo, "(bad length)")); break; case ESIS_OPTION_PROTOCOLS: while (opli>0) { ND_TCHECK(*pptr); ND_PRINT((ndo, "%s (0x%02x)", tok2str(nlpid_values, "unknown", *tptr), *tptr)); if (opli>1) /* further NPLIDs ? - put comma */ ND_PRINT((ndo, ", ")); tptr++; opli--; } break; /* * FIXME those are the defined Options that lack a decoder * you are welcome to contribute code ;-) */ case ESIS_OPTION_QOS_MAINTENANCE: case ESIS_OPTION_SECURITY: case ESIS_OPTION_PRIORITY: case ESIS_OPTION_ADDRESS_MASK: case ESIS_OPTION_SNPA_MASK: default: print_unknown_data(ndo, tptr, "\n\t ", opli); break; } if (ndo->ndo_vflag > 1) print_unknown_data(ndo, pptr, "\n\t ", opli); pptr += opli; } trunc: return; }
167,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: ps_parser_to_token( PS_Parser parser, T1_Token token ) { FT_Byte* cur; FT_Byte* limit; FT_Int embed; token->type = T1_TOKEN_TYPE_NONE; token->start = NULL; token->limit = NULL; /* first of all, skip leading whitespace */ ps_parser_skip_spaces( parser ); cur = parser->cursor; limit = parser->limit; if ( cur >= limit ) return; switch ( *cur ) { /************* check for literal string *****************/ case '(': token->type = T1_TOKEN_TYPE_STRING; token->start = cur; if ( skip_literal_string( &cur, limit ) == FT_Err_Ok ) token->limit = cur; break; /************* check for programs/array *****************/ case '{': token->type = T1_TOKEN_TYPE_ARRAY; token->start = cur; if ( skip_procedure( &cur, limit ) == FT_Err_Ok ) token->limit = cur; break; /************* check for table/array ********************/ /* XXX: in theory we should also look for "<<" */ /* since this is semantically equivalent to "["; */ /* in practice it doesn't matter (?) */ case '[': token->type = T1_TOKEN_TYPE_ARRAY; embed = 1; token->start = cur++; /* we need this to catch `[ ]' */ parser->cursor = cur; ps_parser_skip_spaces( parser ); cur = parser->cursor; while ( cur < limit && !parser->error ) { /* XXX: this is wrong because it does not */ /* skip comments, procedures, and strings */ if ( *cur == '[' ) embed++; else if ( *cur == ']' ) { embed--; if ( embed <= 0 ) { token->limit = ++cur; break; } } parser->cursor = cur; ps_parser_skip_PS_token( parser ); /* we need this to catch `[XXX ]' */ ps_parser_skip_spaces ( parser ); cur = parser->cursor; } break; /* ************ otherwise, it is any token **************/ default: token->start = cur; token->type = ( *cur == '/' ) ? T1_TOKEN_TYPE_KEY : T1_TOKEN_TYPE_ANY; ps_parser_skip_PS_token( parser ); cur = parser->cursor; if ( !parser->error ) token->limit = cur; } if ( !token->limit ) { token->start = NULL; token->type = T1_TOKEN_TYPE_NONE; } parser->cursor = cur; } /* NB: `tokens' can be NULL if we only want to count */ /* the number of array elements */ FT_LOCAL_DEF( void ) ps_parser_to_token_array( PS_Parser parser, T1_Token tokens, FT_UInt max_tokens, FT_Int* pnum_tokens ) { T1_TokenRec master; *pnum_tokens = -1; /* this also handles leading whitespace */ ps_parser_to_token( parser, &master ); if ( master.type == T1_TOKEN_TYPE_ARRAY ) { FT_Byte* old_cursor = parser->cursor; FT_Byte* old_limit = parser->limit; T1_Token cur = tokens; T1_Token limit = cur + max_tokens; /* don't include outermost delimiters */ parser->cursor = master.start + 1; parser->limit = master.limit - 1; while ( parser->cursor < parser->limit ) { T1_TokenRec token; ps_parser_to_token( parser, &token ); if ( !token.type ) break; if ( tokens && cur < limit ) *cur = token; cur++; } *pnum_tokens = (FT_Int)( cur - tokens ); parser->cursor = old_cursor; parser->limit = old_limit; } } /* first character must be a delimiter or a part of a number */ /* NB: `coords' can be NULL if we just want to skip the */ /* array; in this case we ignore `max_coords' */ static FT_Int ps_tocoordarray( FT_Byte* *acur, FT_Byte* limit, FT_Int max_coords, FT_Short* coords ) { FT_Byte* cur = *acur; FT_Int count = 0; FT_Byte c, ender; if ( cur >= limit ) goto Exit; /* check for the beginning of an array; otherwise, only one number */ /* will be read */ c = *cur; ender = 0; if ( c == '[' ) ender = ']'; else if ( c == '{' ) ender = '}'; if ( ender ) cur++; /* now, read the coordinates */ while ( cur < limit ) { FT_Short dummy; FT_Byte* old_cur; /* skip whitespace in front of data */ skip_spaces( &cur, limit ); if ( cur >= limit ) goto Exit; if ( *cur == ender ) { cur++; break; } old_cur = cur; if ( coords && count >= max_coords ) break; /* call PS_Conv_ToFixed() even if coords == NULL */ /* to properly parse number at `cur' */ *( coords ? &coords[count] : &dummy ) = (FT_Short)( PS_Conv_ToFixed( &cur, limit, 0 ) >> 16 ); if ( old_cur == cur ) { count = -1; goto Exit; } else count++; if ( !ender ) break; } Exit: *acur = cur; return count; } /* first character must be a delimiter or a part of a number */ /* NB: `values' can be NULL if we just want to skip the */ /* array; in this case we ignore `max_values' */ /* */ /* return number of successfully parsed values */ static FT_Int ps_tofixedarray( FT_Byte* *acur, FT_Byte* limit, FT_Int max_values, FT_Fixed* values, FT_Int power_ten ) { FT_Byte* cur = *acur; FT_Int count = 0; FT_Byte c, ender; if ( cur >= limit ) goto Exit; /* Check for the beginning of an array. Otherwise, only one number */ /* will be read. */ c = *cur; ender = 0; if ( c == '[' ) ender = ']'; else if ( c == '{' ) ender = '}'; if ( ender ) cur++; /* now, read the values */ while ( cur < limit ) { FT_Fixed dummy; FT_Byte* old_cur; /* skip whitespace in front of data */ skip_spaces( &cur, limit ); if ( cur >= limit ) goto Exit; if ( *cur == ender ) { cur++; break; } old_cur = cur; if ( values && count >= max_values ) break; /* call PS_Conv_ToFixed() even if coords == NULL */ /* to properly parse number at `cur' */ *( values ? &values[count] : &dummy ) = PS_Conv_ToFixed( &cur, limit, power_ten ); if ( old_cur == cur ) { count = -1; goto Exit; } else count++; if ( !ender ) break; } Exit: *acur = cur; return count; } #if 0 static FT_String* ps_tostring( FT_Byte** cursor, FT_Byte* limit, FT_Memory memory ) { FT_Byte* cur = *cursor; FT_UInt len = 0; FT_Int count; FT_String* result; FT_Error error; /* XXX: some stupid fonts have a `Notice' or `Copyright' string */ /* that simply doesn't begin with an opening parenthesis, even */ /* though they have a closing one! E.g. "amuncial.pfb" */ /* */ /* We must deal with these ill-fated cases there. Note that */ /* these fonts didn't work with the old Type 1 driver as the */ /* notice/copyright was not recognized as a valid string token */ /* and made the old token parser commit errors. */ while ( cur < limit && ( *cur == ' ' || *cur == '\t' ) ) cur++; if ( cur + 1 >= limit ) return 0; if ( *cur == '(' ) cur++; /* skip the opening parenthesis, if there is one */ *cursor = cur; count = 0; /* then, count its length */ for ( ; cur < limit; cur++ ) { if ( *cur == '(' ) count++; else if ( *cur == ')' ) { count--; if ( count < 0 ) break; } } len = (FT_UInt)( cur - *cursor ); if ( cur >= limit || FT_ALLOC( result, len + 1 ) ) return 0; /* now copy the string */ FT_MEM_COPY( result, *cursor, len ); result[len] = '\0'; *cursor = cur; return result; } #endif /* 0 */ static int ps_tobool( FT_Byte* *acur, FT_Byte* limit ) { FT_Byte* cur = *acur; FT_Bool result = 0; /* return 1 if we find `true', 0 otherwise */ if ( cur + 3 < limit && cur[0] == 't' && cur[1] == 'r' && cur[2] == 'u' && cur[3] == 'e' ) { result = 1; cur += 5; } else if ( cur + 4 < limit && cur[0] == 'f' && cur[1] == 'a' && cur[2] == 'l' && cur[3] == 's' && cur[4] == 'e' ) { result = 0; cur += 6; } *acur = cur; return result; } /* load a simple field (i.e. non-table) into the current list of objects */ FT_LOCAL_DEF( FT_Error ) ps_parser_load_field( PS_Parser parser, const T1_Field field, void** objects, FT_UInt max_objects, FT_ULong* pflags ) { T1_TokenRec token; FT_Byte* cur; FT_Byte* limit; FT_UInt count; FT_UInt idx; FT_Error error; T1_FieldType type; /* this also skips leading whitespace */ ps_parser_to_token( parser, &token ); if ( !token.type ) goto Fail; count = 1; idx = 0; cur = token.start; limit = token.limit; type = field->type; /* we must detect arrays in /FontBBox */ if ( type == T1_FIELD_TYPE_BBOX ) { T1_TokenRec token2; FT_Byte* old_cur = parser->cursor; FT_Byte* old_limit = parser->limit; /* don't include delimiters */ parser->cursor = token.start + 1; parser->limit = token.limit - 1; ps_parser_to_token( parser, &token2 ); parser->cursor = old_cur; parser->limit = old_limit; if ( token2.type == T1_TOKEN_TYPE_ARRAY ) { type = T1_FIELD_TYPE_MM_BBOX; goto FieldArray; } } else if ( token.type == T1_TOKEN_TYPE_ARRAY ) { count = max_objects; FieldArray: /* if this is an array and we have no blend, an error occurs */ if ( max_objects == 0 ) goto Fail; idx = 1; /* don't include delimiters */ cur++; limit--; } for ( ; count > 0; count--, idx++ ) { FT_Byte* q = (FT_Byte*)objects[idx] + field->offset; FT_Long val; FT_String* string = NULL; skip_spaces( &cur, limit ); switch ( type ) { case T1_FIELD_TYPE_BOOL: val = ps_tobool( &cur, limit ); goto Store_Integer; case T1_FIELD_TYPE_FIXED: val = PS_Conv_ToFixed( &cur, limit, 0 ); goto Store_Integer; case T1_FIELD_TYPE_FIXED_1000: val = PS_Conv_ToFixed( &cur, limit, 3 ); goto Store_Integer; case T1_FIELD_TYPE_INTEGER: val = PS_Conv_ToInt( &cur, limit ); /* fall through */ Store_Integer: switch ( field->size ) { case (8 / FT_CHAR_BIT): *(FT_Byte*)q = (FT_Byte)val; break; case (16 / FT_CHAR_BIT): *(FT_UShort*)q = (FT_UShort)val; break; case (32 / FT_CHAR_BIT): *(FT_UInt32*)q = (FT_UInt32)val; break; default: /* for 64-bit systems */ *(FT_Long*)q = val; } break; case T1_FIELD_TYPE_STRING: case T1_FIELD_TYPE_KEY: { FT_Memory memory = parser->memory; FT_UInt len = (FT_UInt)( limit - cur ); if ( cur >= limit ) break; /* we allow both a string or a name */ /* for cases like /FontName (foo) def */ if ( token.type == T1_TOKEN_TYPE_KEY ) { /* don't include leading `/' */ len--; cur++; } else if ( token.type == T1_TOKEN_TYPE_STRING ) { /* don't include delimiting parentheses */ /* XXX we don't handle <<...>> here */ /* XXX should we convert octal escapes? */ /* if so, what encoding should we use? */ cur++; len -= 2; } else { FT_ERROR(( "ps_parser_load_field:" " expected a name or string\n" " " " but found token of type %d instead\n", token.type )); error = FT_THROW( Invalid_File_Format ); goto Exit; } /* for this to work (FT_String**)q must have been */ /* initialized to NULL */ if ( *(FT_String**)q ) { FT_TRACE0(( "ps_parser_load_field: overwriting field %s\n", field->ident )); FT_FREE( *(FT_String**)q ); *(FT_String**)q = NULL; } if ( FT_ALLOC( string, len + 1 ) ) goto Exit; FT_MEM_COPY( string, cur, len ); string[len] = 0; *(FT_String**)q = string; } break; case T1_FIELD_TYPE_BBOX: { FT_Fixed temp[4]; FT_BBox* bbox = (FT_BBox*)q; FT_Int result; result = ps_tofixedarray( &cur, limit, 4, temp, 0 ); if ( result < 4 ) { FT_ERROR(( "ps_parser_load_field:" " expected four integers in bounding box\n" )); error = FT_THROW( Invalid_File_Format ); goto Exit; } bbox->xMin = FT_RoundFix( temp[0] ); bbox->yMin = FT_RoundFix( temp[1] ); bbox->xMax = FT_RoundFix( temp[2] ); bbox->yMax = FT_RoundFix( temp[3] ); } break; case T1_FIELD_TYPE_MM_BBOX: { FT_Memory memory = parser->memory; FT_Fixed* temp = NULL; FT_Int result; FT_UInt i; if ( FT_NEW_ARRAY( temp, max_objects * 4 ) ) goto Exit; for ( i = 0; i < 4; i++ ) { result = ps_tofixedarray( &cur, limit, (FT_Int)max_objects, temp + i * max_objects, 0 ); if ( result < 0 || (FT_UInt)result < max_objects ) { FT_ERROR(( "ps_parser_load_field:" " expected %d integer%s in the %s subarray\n" " " " of /FontBBox in the /Blend dictionary\n", max_objects, max_objects > 1 ? "s" : "", i == 0 ? "first" : ( i == 1 ? "second" : ( i == 2 ? "third" : "fourth" ) ) )); error = FT_THROW( Invalid_File_Format ); FT_FREE( temp ); goto Exit; } skip_spaces( &cur, limit ); } for ( i = 0; i < max_objects; i++ ) { FT_BBox* bbox = (FT_BBox*)objects[i]; bbox->xMin = FT_RoundFix( temp[i ] ); bbox->yMin = FT_RoundFix( temp[i + max_objects] ); bbox->xMax = FT_RoundFix( temp[i + 2 * max_objects] ); bbox->yMax = FT_RoundFix( temp[i + 3 * max_objects] ); } FT_FREE( temp ); } break; default: /* an error occurred */ goto Fail; } } #if 0 /* obsolete -- keep for reference */ if ( pflags ) *pflags |= 1L << field->flag_bit; #else FT_UNUSED( pflags ); #endif error = FT_Err_Ok; Exit: return error; Fail: error = FT_THROW( Invalid_File_Format ); goto Exit; } #define T1_MAX_TABLE_ELEMENTS 32 FT_LOCAL_DEF( FT_Error ) ps_parser_load_field_table( PS_Parser parser, const T1_Field field, void** objects, FT_UInt max_objects, FT_ULong* pflags ) { T1_TokenRec elements[T1_MAX_TABLE_ELEMENTS]; T1_Token token; FT_Int num_elements; FT_Error error = FT_Err_Ok; FT_Byte* old_cursor; FT_Byte* old_limit; T1_FieldRec fieldrec = *(T1_Field)field; fieldrec.type = T1_FIELD_TYPE_INTEGER; if ( field->type == T1_FIELD_TYPE_FIXED_ARRAY || field->type == T1_FIELD_TYPE_BBOX ) fieldrec.type = T1_FIELD_TYPE_FIXED; ps_parser_to_token_array( parser, elements, T1_MAX_TABLE_ELEMENTS, &num_elements ); if ( num_elements < 0 ) { error = FT_ERR( Ignore ); goto Exit; } if ( (FT_UInt)num_elements > field->array_max ) num_elements = (FT_Int)field->array_max; old_cursor = parser->cursor; old_limit = parser->limit; /* we store the elements count if necessary; */ /* we further assume that `count_offset' can't be zero */ if ( field->type != T1_FIELD_TYPE_BBOX && field->count_offset != 0 ) *(FT_Byte*)( (FT_Byte*)objects[0] + field->count_offset ) = (FT_Byte)num_elements; /* we now load each element, adjusting the field.offset on each one */ token = elements; for ( ; num_elements > 0; num_elements--, token++ ) { parser->cursor = token->start; parser->limit = token->limit; error = ps_parser_load_field( parser, &fieldrec, objects, max_objects, 0 ); if ( error ) break; fieldrec.offset += fieldrec.size; } #if 0 /* obsolete -- keep for reference */ if ( pflags ) *pflags |= 1L << field->flag_bit; #else FT_UNUSED( pflags ); #endif parser->cursor = old_cursor; parser->limit = old_limit; Exit: return error; } FT_LOCAL_DEF( FT_Long ) ps_parser_to_int( PS_Parser parser ) { ps_parser_skip_spaces( parser ); return PS_Conv_ToInt( &parser->cursor, parser->limit ); } /* first character must be `<' if `delimiters' is non-zero */ FT_LOCAL_DEF( FT_Error ) ps_parser_to_bytes( PS_Parser parser, FT_Byte* bytes, FT_Offset max_bytes, FT_ULong* pnum_bytes, FT_Bool delimiters ) { FT_Error error = FT_Err_Ok; FT_Byte* cur; ps_parser_skip_spaces( parser ); cur = parser->cursor; if ( cur >= parser->limit ) goto Exit; if ( delimiters ) { if ( *cur != '<' ) { FT_ERROR(( "ps_parser_to_bytes: Missing starting delimiter `<'\n" )); error = FT_THROW( Invalid_File_Format ); goto Exit; } cur++; } *pnum_bytes = PS_Conv_ASCIIHexDecode( &cur, parser->limit, bytes, max_bytes ); if ( delimiters ) { if ( cur < parser->limit && *cur != '>' ) { FT_ERROR(( "ps_parser_to_bytes: Missing closing delimiter `>'\n" )); error = FT_THROW( Invalid_File_Format ); goto Exit; } cur++; } parser->cursor = cur; Exit: return error; } FT_LOCAL_DEF( FT_Fixed ) ps_parser_to_fixed( PS_Parser parser, FT_Int power_ten ) { ps_parser_skip_spaces( parser ); return PS_Conv_ToFixed( &parser->cursor, parser->limit, power_ten ); } FT_LOCAL_DEF( FT_Int ) ps_parser_to_coord_array( PS_Parser parser, FT_Int max_coords, FT_Short* coords ) { ps_parser_skip_spaces( parser ); return ps_tocoordarray( &parser->cursor, parser->limit, max_coords, coords ); } FT_LOCAL_DEF( FT_Int ) ps_parser_to_fixed_array( PS_Parser parser, FT_Int max_values, FT_Fixed* values, FT_Int power_ten ) { ps_parser_skip_spaces( parser ); return ps_tofixedarray( &parser->cursor, parser->limit, max_values, values, power_ten ); } #if 0 FT_LOCAL_DEF( FT_String* ) T1_ToString( PS_Parser parser ) { return ps_tostring( &parser->cursor, parser->limit, parser->memory ); } FT_LOCAL_DEF( FT_Bool ) T1_ToBool( PS_Parser parser ) { return ps_tobool( &parser->cursor, parser->limit ); } #endif /* 0 */ FT_LOCAL_DEF( void ) ps_parser_init( PS_Parser parser, FT_Byte* base, FT_Byte* limit, FT_Memory memory ) { parser->error = FT_Err_Ok; parser->base = base; parser->limit = limit; parser->cursor = base; parser->memory = memory; parser->funcs = ps_parser_funcs; } FT_LOCAL_DEF( void ) ps_parser_done( PS_Parser parser ) { FT_UNUSED( parser ); } /*************************************************************************/ /*************************************************************************/ /***** *****/ /***** T1 BUILDER *****/ /***** *****/ /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /* */ /* <Function> */ /* t1_builder_init */ /* */ /* <Description> */ /* Initializes a given glyph builder. */ /* */ /* <InOut> */ /* builder :: A pointer to the glyph builder to initialize. */ /* */ /* <Input> */ /* face :: The current face object. */ /* */ /* size :: The current size object. */ /* */ /* glyph :: The current glyph object. */ /* */ /* hinting :: Whether hinting should be applied. */ /* */ FT_LOCAL_DEF( void ) t1_builder_init( T1_Builder builder, FT_Face face, FT_Size size, FT_GlyphSlot glyph, FT_Bool hinting ) { builder->parse_state = T1_Parse_Start; builder->load_points = 1; builder->face = face; builder->glyph = glyph; builder->memory = face->memory; if ( glyph ) { FT_GlyphLoader loader = glyph->internal->loader; builder->loader = loader; builder->base = &loader->base.outline; builder->current = &loader->current.outline; FT_GlyphLoader_Rewind( loader ); builder->hints_globals = size->internal; builder->hints_funcs = NULL; if ( hinting ) builder->hints_funcs = glyph->internal->glyph_hints; } builder->pos_x = 0; builder->pos_y = 0; builder->left_bearing.x = 0; builder->left_bearing.y = 0; builder->advance.x = 0; builder->advance.y = 0; builder->funcs = t1_builder_funcs; } /*************************************************************************/ /* */ /* <Function> */ /* t1_builder_done */ /* */ /* <Description> */ /* Finalizes a given glyph builder. Its contents can still be used */ /* after the call, but the function saves important information */ /* within the corresponding glyph slot. */ /* */ /* <Input> */ /* builder :: A pointer to the glyph builder to finalize. */ /* */ FT_LOCAL_DEF( void ) t1_builder_done( T1_Builder builder ) { FT_GlyphSlot glyph = builder->glyph; if ( glyph ) glyph->outline = *builder->base; } /* check that there is enough space for `count' more points */ FT_LOCAL_DEF( FT_Error ) t1_builder_check_points( T1_Builder builder, FT_Int count ) { return FT_GLYPHLOADER_CHECK_POINTS( builder->loader, count, 0 ); } /* add a new point, do not check space */ FT_LOCAL_DEF( void ) t1_builder_add_point( T1_Builder builder, FT_Pos x, FT_Pos y, FT_Byte flag ) { FT_Outline* outline = builder->current; if ( builder->load_points ) { FT_Vector* point = outline->points + outline->n_points; FT_Byte* control = (FT_Byte*)outline->tags + outline->n_points; point->x = FIXED_TO_INT( x ); point->y = FIXED_TO_INT( y ); *control = (FT_Byte)( flag ? FT_CURVE_TAG_ON : FT_CURVE_TAG_CUBIC ); } outline->n_points++; } /* check space for a new on-curve point, then add it */ FT_LOCAL_DEF( FT_Error ) t1_builder_add_point1( T1_Builder builder, FT_Pos x, FT_Pos y ) { FT_Error error; error = t1_builder_check_points( builder, 1 ); if ( !error ) t1_builder_add_point( builder, x, y, 1 ); return error; } /* check space for a new contour, then add it */ FT_LOCAL_DEF( FT_Error ) t1_builder_add_contour( T1_Builder builder ) { FT_Outline* outline = builder->current; FT_Error error; /* this might happen in invalid fonts */ if ( !outline ) { FT_ERROR(( "t1_builder_add_contour: no outline to add points to\n" )); return FT_THROW( Invalid_File_Format ); } if ( !builder->load_points ) { outline->n_contours++; return FT_Err_Ok; } error = FT_GLYPHLOADER_CHECK_POINTS( builder->loader, 0, 1 ); if ( !error ) { if ( outline->n_contours > 0 ) outline->contours[outline->n_contours - 1] = (short)( outline->n_points - 1 ); outline->n_contours++; } return error; } /* if a path was begun, add its first on-curve point */ FT_LOCAL_DEF( FT_Error ) t1_builder_start_point( T1_Builder builder, FT_Pos x, FT_Pos y ) { FT_Error error = FT_ERR( Invalid_File_Format ); /* test whether we are building a new contour */ if ( builder->parse_state == T1_Parse_Have_Path ) error = FT_Err_Ok; else { builder->parse_state = T1_Parse_Have_Path; error = t1_builder_add_contour( builder ); if ( !error ) error = t1_builder_add_point1( builder, x, y ); } return error; } /* close the current contour */ FT_LOCAL_DEF( void ) t1_builder_close_contour( T1_Builder builder ) { FT_Outline* outline = builder->current; FT_Int first; if ( !outline ) return; first = outline->n_contours <= 1 ? 0 : outline->contours[outline->n_contours - 2] + 1; /* We must not include the last point in the path if it */ /* is located on the first point. */ if ( outline->n_points > 1 ) if ( p1->x == p2->x && p1->y == p2->y ) if ( *control == FT_CURVE_TAG_ON ) outline->n_points--; } if ( outline->n_contours > 0 ) { /* Don't add contours only consisting of one point, i.e., */ /* check whether the first and the last point is the same. */ if ( first == outline->n_points - 1 ) { outline->n_contours--; outline->n_points--; } else outline->contours[outline->n_contours - 1] = (short)( outline->n_points - 1 ); } } Commit Message: CWE ID: CWE-119
ps_parser_to_token( PS_Parser parser, T1_Token token ) { FT_Byte* cur; FT_Byte* limit; FT_Int embed; token->type = T1_TOKEN_TYPE_NONE; token->start = NULL; token->limit = NULL; /* first of all, skip leading whitespace */ ps_parser_skip_spaces( parser ); cur = parser->cursor; limit = parser->limit; if ( cur >= limit ) return; switch ( *cur ) { /************* check for literal string *****************/ case '(': token->type = T1_TOKEN_TYPE_STRING; token->start = cur; if ( skip_literal_string( &cur, limit ) == FT_Err_Ok ) token->limit = cur; break; /************* check for programs/array *****************/ case '{': token->type = T1_TOKEN_TYPE_ARRAY; token->start = cur; if ( skip_procedure( &cur, limit ) == FT_Err_Ok ) token->limit = cur; break; /************* check for table/array ********************/ /* XXX: in theory we should also look for "<<" */ /* since this is semantically equivalent to "["; */ /* in practice it doesn't matter (?) */ case '[': token->type = T1_TOKEN_TYPE_ARRAY; embed = 1; token->start = cur++; /* we need this to catch `[ ]' */ parser->cursor = cur; ps_parser_skip_spaces( parser ); cur = parser->cursor; while ( cur < limit && !parser->error ) { /* XXX: this is wrong because it does not */ /* skip comments, procedures, and strings */ if ( *cur == '[' ) embed++; else if ( *cur == ']' ) { embed--; if ( embed <= 0 ) { token->limit = ++cur; break; } } parser->cursor = cur; ps_parser_skip_PS_token( parser ); /* we need this to catch `[XXX ]' */ ps_parser_skip_spaces ( parser ); cur = parser->cursor; } break; /* ************ otherwise, it is any token **************/ default: token->start = cur; token->type = ( *cur == '/' ) ? T1_TOKEN_TYPE_KEY : T1_TOKEN_TYPE_ANY; ps_parser_skip_PS_token( parser ); cur = parser->cursor; if ( !parser->error ) token->limit = cur; } if ( !token->limit ) { token->start = NULL; token->type = T1_TOKEN_TYPE_NONE; } parser->cursor = cur; } /* NB: `tokens' can be NULL if we only want to count */ /* the number of array elements */ FT_LOCAL_DEF( void ) ps_parser_to_token_array( PS_Parser parser, T1_Token tokens, FT_UInt max_tokens, FT_Int* pnum_tokens ) { T1_TokenRec master; *pnum_tokens = -1; /* this also handles leading whitespace */ ps_parser_to_token( parser, &master ); if ( master.type == T1_TOKEN_TYPE_ARRAY ) { FT_Byte* old_cursor = parser->cursor; FT_Byte* old_limit = parser->limit; T1_Token cur = tokens; T1_Token limit = cur + max_tokens; /* don't include outermost delimiters */ parser->cursor = master.start + 1; parser->limit = master.limit - 1; while ( parser->cursor < parser->limit ) { T1_TokenRec token; ps_parser_to_token( parser, &token ); if ( !token.type ) break; if ( tokens && cur < limit ) *cur = token; cur++; } *pnum_tokens = (FT_Int)( cur - tokens ); parser->cursor = old_cursor; parser->limit = old_limit; } } /* first character must be a delimiter or a part of a number */ /* NB: `coords' can be NULL if we just want to skip the */ /* array; in this case we ignore `max_coords' */ static FT_Int ps_tocoordarray( FT_Byte* *acur, FT_Byte* limit, FT_Int max_coords, FT_Short* coords ) { FT_Byte* cur = *acur; FT_Int count = 0; FT_Byte c, ender; if ( cur >= limit ) goto Exit; /* check for the beginning of an array; otherwise, only one number */ /* will be read */ c = *cur; ender = 0; if ( c == '[' ) ender = ']'; else if ( c == '{' ) ender = '}'; if ( ender ) cur++; /* now, read the coordinates */ while ( cur < limit ) { FT_Short dummy; FT_Byte* old_cur; /* skip whitespace in front of data */ skip_spaces( &cur, limit ); if ( cur >= limit ) goto Exit; if ( *cur == ender ) { cur++; break; } old_cur = cur; if ( coords && count >= max_coords ) break; /* call PS_Conv_ToFixed() even if coords == NULL */ /* to properly parse number at `cur' */ *( coords ? &coords[count] : &dummy ) = (FT_Short)( PS_Conv_ToFixed( &cur, limit, 0 ) >> 16 ); if ( old_cur == cur ) { count = -1; goto Exit; } else count++; if ( !ender ) break; } Exit: *acur = cur; return count; } /* first character must be a delimiter or a part of a number */ /* NB: `values' can be NULL if we just want to skip the */ /* array; in this case we ignore `max_values' */ /* */ /* return number of successfully parsed values */ static FT_Int ps_tofixedarray( FT_Byte* *acur, FT_Byte* limit, FT_Int max_values, FT_Fixed* values, FT_Int power_ten ) { FT_Byte* cur = *acur; FT_Int count = 0; FT_Byte c, ender; if ( cur >= limit ) goto Exit; /* Check for the beginning of an array. Otherwise, only one number */ /* will be read. */ c = *cur; ender = 0; if ( c == '[' ) ender = ']'; else if ( c == '{' ) ender = '}'; if ( ender ) cur++; /* now, read the values */ while ( cur < limit ) { FT_Fixed dummy; FT_Byte* old_cur; /* skip whitespace in front of data */ skip_spaces( &cur, limit ); if ( cur >= limit ) goto Exit; if ( *cur == ender ) { cur++; break; } old_cur = cur; if ( values && count >= max_values ) break; /* call PS_Conv_ToFixed() even if coords == NULL */ /* to properly parse number at `cur' */ *( values ? &values[count] : &dummy ) = PS_Conv_ToFixed( &cur, limit, power_ten ); if ( old_cur == cur ) { count = -1; goto Exit; } else count++; if ( !ender ) break; } Exit: *acur = cur; return count; } #if 0 static FT_String* ps_tostring( FT_Byte** cursor, FT_Byte* limit, FT_Memory memory ) { FT_Byte* cur = *cursor; FT_UInt len = 0; FT_Int count; FT_String* result; FT_Error error; /* XXX: some stupid fonts have a `Notice' or `Copyright' string */ /* that simply doesn't begin with an opening parenthesis, even */ /* though they have a closing one! E.g. "amuncial.pfb" */ /* */ /* We must deal with these ill-fated cases there. Note that */ /* these fonts didn't work with the old Type 1 driver as the */ /* notice/copyright was not recognized as a valid string token */ /* and made the old token parser commit errors. */ while ( cur < limit && ( *cur == ' ' || *cur == '\t' ) ) cur++; if ( cur + 1 >= limit ) return 0; if ( *cur == '(' ) cur++; /* skip the opening parenthesis, if there is one */ *cursor = cur; count = 0; /* then, count its length */ for ( ; cur < limit; cur++ ) { if ( *cur == '(' ) count++; else if ( *cur == ')' ) { count--; if ( count < 0 ) break; } } len = (FT_UInt)( cur - *cursor ); if ( cur >= limit || FT_ALLOC( result, len + 1 ) ) return 0; /* now copy the string */ FT_MEM_COPY( result, *cursor, len ); result[len] = '\0'; *cursor = cur; return result; } #endif /* 0 */ static int ps_tobool( FT_Byte* *acur, FT_Byte* limit ) { FT_Byte* cur = *acur; FT_Bool result = 0; /* return 1 if we find `true', 0 otherwise */ if ( cur + 3 < limit && cur[0] == 't' && cur[1] == 'r' && cur[2] == 'u' && cur[3] == 'e' ) { result = 1; cur += 5; } else if ( cur + 4 < limit && cur[0] == 'f' && cur[1] == 'a' && cur[2] == 'l' && cur[3] == 's' && cur[4] == 'e' ) { result = 0; cur += 6; } *acur = cur; return result; } /* load a simple field (i.e. non-table) into the current list of objects */ FT_LOCAL_DEF( FT_Error ) ps_parser_load_field( PS_Parser parser, const T1_Field field, void** objects, FT_UInt max_objects, FT_ULong* pflags ) { T1_TokenRec token; FT_Byte* cur; FT_Byte* limit; FT_UInt count; FT_UInt idx; FT_Error error; T1_FieldType type; /* this also skips leading whitespace */ ps_parser_to_token( parser, &token ); if ( !token.type ) goto Fail; count = 1; idx = 0; cur = token.start; limit = token.limit; type = field->type; /* we must detect arrays in /FontBBox */ if ( type == T1_FIELD_TYPE_BBOX ) { T1_TokenRec token2; FT_Byte* old_cur = parser->cursor; FT_Byte* old_limit = parser->limit; /* don't include delimiters */ parser->cursor = token.start + 1; parser->limit = token.limit - 1; ps_parser_to_token( parser, &token2 ); parser->cursor = old_cur; parser->limit = old_limit; if ( token2.type == T1_TOKEN_TYPE_ARRAY ) { type = T1_FIELD_TYPE_MM_BBOX; goto FieldArray; } } else if ( token.type == T1_TOKEN_TYPE_ARRAY ) { count = max_objects; FieldArray: /* if this is an array and we have no blend, an error occurs */ if ( max_objects == 0 ) goto Fail; idx = 1; /* don't include delimiters */ cur++; limit--; } for ( ; count > 0; count--, idx++ ) { FT_Byte* q = (FT_Byte*)objects[idx] + field->offset; FT_Long val; FT_String* string = NULL; skip_spaces( &cur, limit ); switch ( type ) { case T1_FIELD_TYPE_BOOL: val = ps_tobool( &cur, limit ); goto Store_Integer; case T1_FIELD_TYPE_FIXED: val = PS_Conv_ToFixed( &cur, limit, 0 ); goto Store_Integer; case T1_FIELD_TYPE_FIXED_1000: val = PS_Conv_ToFixed( &cur, limit, 3 ); goto Store_Integer; case T1_FIELD_TYPE_INTEGER: val = PS_Conv_ToInt( &cur, limit ); /* fall through */ Store_Integer: switch ( field->size ) { case (8 / FT_CHAR_BIT): *(FT_Byte*)q = (FT_Byte)val; break; case (16 / FT_CHAR_BIT): *(FT_UShort*)q = (FT_UShort)val; break; case (32 / FT_CHAR_BIT): *(FT_UInt32*)q = (FT_UInt32)val; break; default: /* for 64-bit systems */ *(FT_Long*)q = val; } break; case T1_FIELD_TYPE_STRING: case T1_FIELD_TYPE_KEY: { FT_Memory memory = parser->memory; FT_UInt len = (FT_UInt)( limit - cur ); if ( cur >= limit ) break; /* we allow both a string or a name */ /* for cases like /FontName (foo) def */ if ( token.type == T1_TOKEN_TYPE_KEY ) { /* don't include leading `/' */ len--; cur++; } else if ( token.type == T1_TOKEN_TYPE_STRING ) { /* don't include delimiting parentheses */ /* XXX we don't handle <<...>> here */ /* XXX should we convert octal escapes? */ /* if so, what encoding should we use? */ cur++; len -= 2; } else { FT_ERROR(( "ps_parser_load_field:" " expected a name or string\n" " " " but found token of type %d instead\n", token.type )); error = FT_THROW( Invalid_File_Format ); goto Exit; } /* for this to work (FT_String**)q must have been */ /* initialized to NULL */ if ( *(FT_String**)q ) { FT_TRACE0(( "ps_parser_load_field: overwriting field %s\n", field->ident )); FT_FREE( *(FT_String**)q ); *(FT_String**)q = NULL; } if ( FT_ALLOC( string, len + 1 ) ) goto Exit; FT_MEM_COPY( string, cur, len ); string[len] = 0; *(FT_String**)q = string; } break; case T1_FIELD_TYPE_BBOX: { FT_Fixed temp[4]; FT_BBox* bbox = (FT_BBox*)q; FT_Int result; result = ps_tofixedarray( &cur, limit, 4, temp, 0 ); if ( result < 4 ) { FT_ERROR(( "ps_parser_load_field:" " expected four integers in bounding box\n" )); error = FT_THROW( Invalid_File_Format ); goto Exit; } bbox->xMin = FT_RoundFix( temp[0] ); bbox->yMin = FT_RoundFix( temp[1] ); bbox->xMax = FT_RoundFix( temp[2] ); bbox->yMax = FT_RoundFix( temp[3] ); } break; case T1_FIELD_TYPE_MM_BBOX: { FT_Memory memory = parser->memory; FT_Fixed* temp = NULL; FT_Int result; FT_UInt i; if ( FT_NEW_ARRAY( temp, max_objects * 4 ) ) goto Exit; for ( i = 0; i < 4; i++ ) { result = ps_tofixedarray( &cur, limit, (FT_Int)max_objects, temp + i * max_objects, 0 ); if ( result < 0 || (FT_UInt)result < max_objects ) { FT_ERROR(( "ps_parser_load_field:" " expected %d integer%s in the %s subarray\n" " " " of /FontBBox in the /Blend dictionary\n", max_objects, max_objects > 1 ? "s" : "", i == 0 ? "first" : ( i == 1 ? "second" : ( i == 2 ? "third" : "fourth" ) ) )); error = FT_THROW( Invalid_File_Format ); FT_FREE( temp ); goto Exit; } skip_spaces( &cur, limit ); } for ( i = 0; i < max_objects; i++ ) { FT_BBox* bbox = (FT_BBox*)objects[i]; bbox->xMin = FT_RoundFix( temp[i ] ); bbox->yMin = FT_RoundFix( temp[i + max_objects] ); bbox->xMax = FT_RoundFix( temp[i + 2 * max_objects] ); bbox->yMax = FT_RoundFix( temp[i + 3 * max_objects] ); } FT_FREE( temp ); } break; default: /* an error occurred */ goto Fail; } } #if 0 /* obsolete -- keep for reference */ if ( pflags ) *pflags |= 1L << field->flag_bit; #else FT_UNUSED( pflags ); #endif error = FT_Err_Ok; Exit: return error; Fail: error = FT_THROW( Invalid_File_Format ); goto Exit; } #define T1_MAX_TABLE_ELEMENTS 32 FT_LOCAL_DEF( FT_Error ) ps_parser_load_field_table( PS_Parser parser, const T1_Field field, void** objects, FT_UInt max_objects, FT_ULong* pflags ) { T1_TokenRec elements[T1_MAX_TABLE_ELEMENTS]; T1_Token token; FT_Int num_elements; FT_Error error = FT_Err_Ok; FT_Byte* old_cursor; FT_Byte* old_limit; T1_FieldRec fieldrec = *(T1_Field)field; fieldrec.type = T1_FIELD_TYPE_INTEGER; if ( field->type == T1_FIELD_TYPE_FIXED_ARRAY || field->type == T1_FIELD_TYPE_BBOX ) fieldrec.type = T1_FIELD_TYPE_FIXED; ps_parser_to_token_array( parser, elements, T1_MAX_TABLE_ELEMENTS, &num_elements ); if ( num_elements < 0 ) { error = FT_ERR( Ignore ); goto Exit; } if ( (FT_UInt)num_elements > field->array_max ) num_elements = (FT_Int)field->array_max; old_cursor = parser->cursor; old_limit = parser->limit; /* we store the elements count if necessary; */ /* we further assume that `count_offset' can't be zero */ if ( field->type != T1_FIELD_TYPE_BBOX && field->count_offset != 0 ) *(FT_Byte*)( (FT_Byte*)objects[0] + field->count_offset ) = (FT_Byte)num_elements; /* we now load each element, adjusting the field.offset on each one */ token = elements; for ( ; num_elements > 0; num_elements--, token++ ) { parser->cursor = token->start; parser->limit = token->limit; error = ps_parser_load_field( parser, &fieldrec, objects, max_objects, 0 ); if ( error ) break; fieldrec.offset += fieldrec.size; } #if 0 /* obsolete -- keep for reference */ if ( pflags ) *pflags |= 1L << field->flag_bit; #else FT_UNUSED( pflags ); #endif parser->cursor = old_cursor; parser->limit = old_limit; Exit: return error; } FT_LOCAL_DEF( FT_Long ) ps_parser_to_int( PS_Parser parser ) { ps_parser_skip_spaces( parser ); return PS_Conv_ToInt( &parser->cursor, parser->limit ); } /* first character must be `<' if `delimiters' is non-zero */ FT_LOCAL_DEF( FT_Error ) ps_parser_to_bytes( PS_Parser parser, FT_Byte* bytes, FT_Offset max_bytes, FT_ULong* pnum_bytes, FT_Bool delimiters ) { FT_Error error = FT_Err_Ok; FT_Byte* cur; ps_parser_skip_spaces( parser ); cur = parser->cursor; if ( cur >= parser->limit ) goto Exit; if ( delimiters ) { if ( *cur != '<' ) { FT_ERROR(( "ps_parser_to_bytes: Missing starting delimiter `<'\n" )); error = FT_THROW( Invalid_File_Format ); goto Exit; } cur++; } *pnum_bytes = PS_Conv_ASCIIHexDecode( &cur, parser->limit, bytes, max_bytes ); if ( delimiters ) { if ( cur < parser->limit && *cur != '>' ) { FT_ERROR(( "ps_parser_to_bytes: Missing closing delimiter `>'\n" )); error = FT_THROW( Invalid_File_Format ); goto Exit; } cur++; } parser->cursor = cur; Exit: return error; } FT_LOCAL_DEF( FT_Fixed ) ps_parser_to_fixed( PS_Parser parser, FT_Int power_ten ) { ps_parser_skip_spaces( parser ); return PS_Conv_ToFixed( &parser->cursor, parser->limit, power_ten ); } FT_LOCAL_DEF( FT_Int ) ps_parser_to_coord_array( PS_Parser parser, FT_Int max_coords, FT_Short* coords ) { ps_parser_skip_spaces( parser ); return ps_tocoordarray( &parser->cursor, parser->limit, max_coords, coords ); } FT_LOCAL_DEF( FT_Int ) ps_parser_to_fixed_array( PS_Parser parser, FT_Int max_values, FT_Fixed* values, FT_Int power_ten ) { ps_parser_skip_spaces( parser ); return ps_tofixedarray( &parser->cursor, parser->limit, max_values, values, power_ten ); } #if 0 FT_LOCAL_DEF( FT_String* ) T1_ToString( PS_Parser parser ) { return ps_tostring( &parser->cursor, parser->limit, parser->memory ); } FT_LOCAL_DEF( FT_Bool ) T1_ToBool( PS_Parser parser ) { return ps_tobool( &parser->cursor, parser->limit ); } #endif /* 0 */ FT_LOCAL_DEF( void ) ps_parser_init( PS_Parser parser, FT_Byte* base, FT_Byte* limit, FT_Memory memory ) { parser->error = FT_Err_Ok; parser->base = base; parser->limit = limit; parser->cursor = base; parser->memory = memory; parser->funcs = ps_parser_funcs; } FT_LOCAL_DEF( void ) ps_parser_done( PS_Parser parser ) { FT_UNUSED( parser ); } /*************************************************************************/ /*************************************************************************/ /***** *****/ /***** T1 BUILDER *****/ /***** *****/ /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /* */ /* <Function> */ /* t1_builder_init */ /* */ /* <Description> */ /* Initializes a given glyph builder. */ /* */ /* <InOut> */ /* builder :: A pointer to the glyph builder to initialize. */ /* */ /* <Input> */ /* face :: The current face object. */ /* */ /* size :: The current size object. */ /* */ /* glyph :: The current glyph object. */ /* */ /* hinting :: Whether hinting should be applied. */ /* */ FT_LOCAL_DEF( void ) t1_builder_init( T1_Builder builder, FT_Face face, FT_Size size, FT_GlyphSlot glyph, FT_Bool hinting ) { builder->parse_state = T1_Parse_Start; builder->load_points = 1; builder->face = face; builder->glyph = glyph; builder->memory = face->memory; if ( glyph ) { FT_GlyphLoader loader = glyph->internal->loader; builder->loader = loader; builder->base = &loader->base.outline; builder->current = &loader->current.outline; FT_GlyphLoader_Rewind( loader ); builder->hints_globals = size->internal; builder->hints_funcs = NULL; if ( hinting ) builder->hints_funcs = glyph->internal->glyph_hints; } builder->pos_x = 0; builder->pos_y = 0; builder->left_bearing.x = 0; builder->left_bearing.y = 0; builder->advance.x = 0; builder->advance.y = 0; builder->funcs = t1_builder_funcs; } /*************************************************************************/ /* */ /* <Function> */ /* t1_builder_done */ /* */ /* <Description> */ /* Finalizes a given glyph builder. Its contents can still be used */ /* after the call, but the function saves important information */ /* within the corresponding glyph slot. */ /* */ /* <Input> */ /* builder :: A pointer to the glyph builder to finalize. */ /* */ FT_LOCAL_DEF( void ) t1_builder_done( T1_Builder builder ) { FT_GlyphSlot glyph = builder->glyph; if ( glyph ) glyph->outline = *builder->base; } /* check that there is enough space for `count' more points */ FT_LOCAL_DEF( FT_Error ) t1_builder_check_points( T1_Builder builder, FT_Int count ) { return FT_GLYPHLOADER_CHECK_POINTS( builder->loader, count, 0 ); } /* add a new point, do not check space */ FT_LOCAL_DEF( void ) t1_builder_add_point( T1_Builder builder, FT_Pos x, FT_Pos y, FT_Byte flag ) { FT_Outline* outline = builder->current; if ( builder->load_points ) { FT_Vector* point = outline->points + outline->n_points; FT_Byte* control = (FT_Byte*)outline->tags + outline->n_points; point->x = FIXED_TO_INT( x ); point->y = FIXED_TO_INT( y ); *control = (FT_Byte)( flag ? FT_CURVE_TAG_ON : FT_CURVE_TAG_CUBIC ); } outline->n_points++; } /* check space for a new on-curve point, then add it */ FT_LOCAL_DEF( FT_Error ) t1_builder_add_point1( T1_Builder builder, FT_Pos x, FT_Pos y ) { FT_Error error; error = t1_builder_check_points( builder, 1 ); if ( !error ) t1_builder_add_point( builder, x, y, 1 ); return error; } /* check space for a new contour, then add it */ FT_LOCAL_DEF( FT_Error ) t1_builder_add_contour( T1_Builder builder ) { FT_Outline* outline = builder->current; FT_Error error; /* this might happen in invalid fonts */ if ( !outline ) { FT_ERROR(( "t1_builder_add_contour: no outline to add points to\n" )); return FT_THROW( Invalid_File_Format ); } if ( !builder->load_points ) { outline->n_contours++; return FT_Err_Ok; } error = FT_GLYPHLOADER_CHECK_POINTS( builder->loader, 0, 1 ); if ( !error ) { if ( outline->n_contours > 0 ) outline->contours[outline->n_contours - 1] = (short)( outline->n_points - 1 ); outline->n_contours++; } return error; } /* if a path was begun, add its first on-curve point */ FT_LOCAL_DEF( FT_Error ) t1_builder_start_point( T1_Builder builder, FT_Pos x, FT_Pos y ) { FT_Error error = FT_ERR( Invalid_File_Format ); /* test whether we are building a new contour */ if ( builder->parse_state == T1_Parse_Have_Path ) error = FT_Err_Ok; else { builder->parse_state = T1_Parse_Have_Path; error = t1_builder_add_contour( builder ); if ( !error ) error = t1_builder_add_point1( builder, x, y ); } return error; } /* close the current contour */ FT_LOCAL_DEF( void ) t1_builder_close_contour( T1_Builder builder ) { FT_Outline* outline = builder->current; FT_Int first; if ( !outline ) return; first = outline->n_contours <= 1 ? 0 : outline->contours[outline->n_contours - 2] + 1; /* in malformed fonts it can happen that a contour was started */ /* but no points were added */ if ( outline->n_contours && first == outline->n_points ) { outline->n_contours--; return; } /* We must not include the last point in the path if it */ /* is located on the first point. */ if ( outline->n_points > 1 ) if ( p1->x == p2->x && p1->y == p2->y ) if ( *control == FT_CURVE_TAG_ON ) outline->n_points--; } if ( outline->n_contours > 0 ) { /* Don't add contours only consisting of one point, i.e., */ /* check whether the first and the last point is the same. */ if ( first == outline->n_points - 1 ) { outline->n_contours--; outline->n_points--; } else outline->contours[outline->n_contours - 1] = (short)( outline->n_points - 1 ); } }
164,875
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(imageaffinematrixconcat) { double m1[6]; double m2[6]; double mr[6]; zval **tmp; zval *z_m1; zval *z_m2; int i, nelems; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "aa", &z_m1, &z_m2) == FAILURE) { return; } if (((nelems = zend_hash_num_elements(Z_ARRVAL_P(z_m1))) != 6) || (nelems = zend_hash_num_elements(Z_ARRVAL_P(z_m2))) != 6) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Affine arrays must have six elements"); RETURN_FALSE; } for (i = 0; i < 6; i++) { if (zend_hash_index_find(Z_ARRVAL_P(z_m1), i, (void **) &tmp) == SUCCESS) { switch (Z_TYPE_PP(tmp)) { case IS_LONG: m1[i] = Z_LVAL_PP(tmp); break; case IS_DOUBLE: m1[i] = Z_DVAL_PP(tmp); break; case IS_STRING: convert_to_double_ex(tmp); m1[i] = Z_DVAL_PP(tmp); break; default: php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid type for element %i", i); RETURN_FALSE; } } if (zend_hash_index_find(Z_ARRVAL_P(z_m2), i, (void **) &tmp) == SUCCESS) { switch (Z_TYPE_PP(tmp)) { case IS_LONG: m2[i] = Z_LVAL_PP(tmp); break; case IS_DOUBLE: m2[i] = Z_DVAL_PP(tmp); break; case IS_STRING: convert_to_double_ex(tmp); m2[i] = Z_DVAL_PP(tmp); break; default: php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid type for element %i", i); RETURN_FALSE; } } } if (gdAffineConcat (mr, m1, m2) != GD_TRUE) { RETURN_FALSE; } array_init(return_value); for (i = 0; i < 6; i++) { add_index_double(return_value, i, mr[i]); } } Commit Message: Fixed bug #66356 (Heap Overflow Vulnerability in imagecrop()) And also fixed the bug: arguments are altered after some calls CWE ID: CWE-189
PHP_FUNCTION(imageaffinematrixconcat) { double m1[6]; double m2[6]; double mr[6]; zval **tmp; zval *z_m1; zval *z_m2; int i, nelems; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "aa", &z_m1, &z_m2) == FAILURE) { return; } if (((nelems = zend_hash_num_elements(Z_ARRVAL_P(z_m1))) != 6) || (nelems = zend_hash_num_elements(Z_ARRVAL_P(z_m2))) != 6) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Affine arrays must have six elements"); RETURN_FALSE; } for (i = 0; i < 6; i++) { if (zend_hash_index_find(Z_ARRVAL_P(z_m1), i, (void **) &tmp) == SUCCESS) { switch (Z_TYPE_PP(tmp)) { case IS_LONG: m1[i] = Z_LVAL_PP(tmp); break; case IS_DOUBLE: m1[i] = Z_DVAL_PP(tmp); break; case IS_STRING: { zval dval; dval = **tmp; zval_copy_ctor(&dval); convert_to_double(&dval); m1[i] = Z_DVAL(dval); } break; default: php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid type for element %i", i); RETURN_FALSE; } } if (zend_hash_index_find(Z_ARRVAL_P(z_m2), i, (void **) &tmp) == SUCCESS) { switch (Z_TYPE_PP(tmp)) { case IS_LONG: m2[i] = Z_LVAL_PP(tmp); break; case IS_DOUBLE: m2[i] = Z_DVAL_PP(tmp); break; case IS_STRING: { zval dval; dval = **tmp; zval_copy_ctor(&dval); convert_to_double(&dval); m2[i] = Z_DVAL(dval); } break; default: php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid type for element %i", i); RETURN_FALSE; } } } if (gdAffineConcat (mr, m1, m2) != GD_TRUE) { RETURN_FALSE; } array_init(return_value); for (i = 0; i < 6; i++) { add_index_double(return_value, i, mr[i]); } }
166,430
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static ssize_t cm_write(struct file *file, const char __user * user_buf, size_t count, loff_t *ppos) { static char *buf; static u32 max_size; static u32 uncopied_bytes; struct acpi_table_header table; acpi_status status; if (!(*ppos)) { /* parse the table header to get the table length */ if (count <= sizeof(struct acpi_table_header)) return -EINVAL; if (copy_from_user(&table, user_buf, sizeof(struct acpi_table_header))) return -EFAULT; uncopied_bytes = max_size = table.length; buf = kzalloc(max_size, GFP_KERNEL); if (!buf) return -ENOMEM; } if (buf == NULL) return -EINVAL; if ((*ppos > max_size) || (*ppos + count > max_size) || (*ppos + count < count) || (count > uncopied_bytes)) return -EINVAL; if (copy_from_user(buf + (*ppos), user_buf, count)) { kfree(buf); buf = NULL; return -EFAULT; } uncopied_bytes -= count; *ppos += count; if (!uncopied_bytes) { status = acpi_install_method(buf); kfree(buf); buf = NULL; if (ACPI_FAILURE(status)) return -EINVAL; add_taint(TAINT_OVERRIDDEN_ACPI_TABLE); } return count; } Commit Message: ACPI: Split out custom_method functionality into an own driver With /sys/kernel/debug/acpi/custom_method root can write to arbitrary memory and increase his priveleges, even if these are restricted. -> Make this an own debug .config option and warn about the security issue in the config description. -> Still keep acpi/debugfs.c which now only creates an empty /sys/kernel/debug/acpi directory. There might be other users of it later. Signed-off-by: Thomas Renninger <[email protected]> Acked-by: Rafael J. Wysocki <[email protected]> Acked-by: [email protected] Signed-off-by: Len Brown <[email protected]> CWE ID: CWE-264
static ssize_t cm_write(struct file *file, const char __user * user_buf,
165,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: long Track::GetType() const { return m_info.type; } 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 Track::GetType() const
174,375
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 PixelChannels **AcquirePixelThreadSet(const Image *images) { const Image *next; PixelChannels **pixels; register ssize_t i; size_t columns, number_threads; number_threads=(size_t) GetMagickResourceLimit(ThreadResource); pixels=(PixelChannels **) AcquireQuantumMemory(number_threads, sizeof(*pixels)); if (pixels == (PixelChannels **) NULL) return((PixelChannels **) NULL); (void) memset(pixels,0,number_threads*sizeof(*pixels)); columns=images->columns; for (next=images; next != (Image *) NULL; next=next->next) columns=MagickMax(next->columns,columns); for (i=0; i < (ssize_t) number_threads; i++) { register ssize_t j; pixels[i]=(PixelChannels *) AcquireQuantumMemory(columns,sizeof(**pixels)); if (pixels[i] == (PixelChannels *) NULL) return(DestroyPixelThreadSet(pixels)); for (j=0; j < (ssize_t) columns; j++) { register ssize_t k; for (k=0; k < MaxPixelChannels; k++) pixels[i][j].channel[k]=0.0; } } return(pixels); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1615 CWE ID: CWE-119
static PixelChannels **AcquirePixelThreadSet(const Image *images) { const Image *next; PixelChannels **pixels; register ssize_t i; size_t columns, rows; rows=MagickMax(GetImageListLength(images), (size_t) GetMagickResourceLimit(ThreadResource)); pixels=(PixelChannels **) AcquireQuantumMemory(rows,sizeof(*pixels)); if (pixels == (PixelChannels **) NULL) return((PixelChannels **) NULL); columns=MaxPixelChannels; for (next=images; next != (Image *) NULL; next=next->next) columns=MagickMax(next->columns,columns); for (i=0; i < (ssize_t) rows; i++) { register ssize_t j; pixels[i]=(PixelChannels *) AcquireQuantumMemory(columns,sizeof(**pixels)); if (pixels[i] == (PixelChannels *) NULL) return(DestroyPixelThreadSet(pixels)); for (j=0; j < (ssize_t) columns; j++) { register ssize_t k; for (k=0; k < MaxPixelChannels; k++) pixels[i][j].channel[k]=0.0; } } return(pixels); }
170,201
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: IndexedDBDispatcher* IndexedDBDispatcher::ThreadSpecificInstance() { if (g_idb_dispatcher_tls.Pointer()->Get()) return g_idb_dispatcher_tls.Pointer()->Get(); IndexedDBDispatcher* dispatcher = new IndexedDBDispatcher; if (WorkerTaskRunner::Instance()->CurrentWorkerId()) webkit_glue::WorkerTaskRunner::Instance()->AddStopObserver(dispatcher); return dispatcher; } Commit Message: Add DCHECK to ensure IndexedDBDispatcher doesn't get re-created. This could happen if there are IDB objects that survive the call to didStopWorkerRunLoop. BUG=121734 TEST= Review URL: http://codereview.chromium.org/9999035 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@131679 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
IndexedDBDispatcher* IndexedDBDispatcher::ThreadSpecificInstance() { if (g_idb_dispatcher_tls.Pointer()->Get() == HAS_BEEN_DELETED) { NOTREACHED() << "Re-instantiating TLS IndexedDBDispatcher."; g_idb_dispatcher_tls.Pointer()->Set(NULL); } if (g_idb_dispatcher_tls.Pointer()->Get()) return g_idb_dispatcher_tls.Pointer()->Get(); IndexedDBDispatcher* dispatcher = new IndexedDBDispatcher; if (WorkerTaskRunner::Instance()->CurrentWorkerId()) webkit_glue::WorkerTaskRunner::Instance()->AddStopObserver(dispatcher); return dispatcher; }
171,039
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: IPV6DefragDoSturgesNovakTest(int policy, u_char *expected, size_t expected_len) { int i; int ret = 0; DefragInit(); /* * Build the packets. */ int id = 1; Packet *packets[17]; memset(packets, 0x00, sizeof(packets)); /* * Original fragments. */ /* A*24 at 0. */ packets[0] = IPV6BuildTestPacket(id, 0, 1, 'A', 24); /* B*15 at 32. */ packets[1] = IPV6BuildTestPacket(id, 32 >> 3, 1, 'B', 16); /* C*24 at 48. */ packets[2] = IPV6BuildTestPacket(id, 48 >> 3, 1, 'C', 24); /* D*8 at 80. */ packets[3] = IPV6BuildTestPacket(id, 80 >> 3, 1, 'D', 8); /* E*16 at 104. */ packets[4] = IPV6BuildTestPacket(id, 104 >> 3, 1, 'E', 16); /* F*24 at 120. */ packets[5] = IPV6BuildTestPacket(id, 120 >> 3, 1, 'F', 24); /* G*16 at 144. */ packets[6] = IPV6BuildTestPacket(id, 144 >> 3, 1, 'G', 16); /* H*16 at 160. */ packets[7] = IPV6BuildTestPacket(id, 160 >> 3, 1, 'H', 16); /* I*8 at 176. */ packets[8] = IPV6BuildTestPacket(id, 176 >> 3, 1, 'I', 8); /* * Overlapping subsequent fragments. */ /* J*32 at 8. */ packets[9] = IPV6BuildTestPacket(id, 8 >> 3, 1, 'J', 32); /* K*24 at 48. */ packets[10] = IPV6BuildTestPacket(id, 48 >> 3, 1, 'K', 24); /* L*24 at 72. */ packets[11] = IPV6BuildTestPacket(id, 72 >> 3, 1, 'L', 24); /* M*24 at 96. */ packets[12] = IPV6BuildTestPacket(id, 96 >> 3, 1, 'M', 24); /* N*8 at 128. */ packets[13] = IPV6BuildTestPacket(id, 128 >> 3, 1, 'N', 8); /* O*8 at 152. */ packets[14] = IPV6BuildTestPacket(id, 152 >> 3, 1, 'O', 8); /* P*8 at 160. */ packets[15] = IPV6BuildTestPacket(id, 160 >> 3, 1, 'P', 8); /* Q*16 at 176. */ packets[16] = IPV6BuildTestPacket(id, 176 >> 3, 0, 'Q', 16); default_policy = policy; /* Send all but the last. */ for (i = 0; i < 9; i++) { Packet *tp = Defrag(NULL, NULL, packets[i], NULL); if (tp != NULL) { SCFree(tp); goto end; } if (ENGINE_ISSET_EVENT(packets[i], IPV6_FRAG_OVERLAP)) { goto end; } } int overlap = 0; for (; i < 16; i++) { Packet *tp = Defrag(NULL, NULL, packets[i], NULL); if (tp != NULL) { SCFree(tp); goto end; } if (ENGINE_ISSET_EVENT(packets[i], IPV6_FRAG_OVERLAP)) { overlap++; } } if (!overlap) goto end; /* And now the last one. */ Packet *reassembled = Defrag(NULL, NULL, packets[16], NULL); if (reassembled == NULL) goto end; if (memcmp(GET_PKT_DATA(reassembled) + 40, expected, expected_len) != 0) goto end; if (IPV6_GET_PLEN(reassembled) != 192) goto end; SCFree(reassembled); /* Make sure all frags were returned to the pool. */ if (defrag_context->frag_pool->outstanding != 0) { printf("defrag_context->frag_pool->outstanding %u: ", defrag_context->frag_pool->outstanding); goto end; } ret = 1; end: for (i = 0; i < 17; i++) { SCFree(packets[i]); } 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
IPV6DefragDoSturgesNovakTest(int policy, u_char *expected, size_t expected_len) { int i; int ret = 0; DefragInit(); /* * Build the packets. */ int id = 1; Packet *packets[17]; memset(packets, 0x00, sizeof(packets)); /* * Original fragments. */ /* A*24 at 0. */ packets[0] = IPV6BuildTestPacket(IPPROTO_ICMPV6, id, 0, 1, 'A', 24); /* B*15 at 32. */ packets[1] = IPV6BuildTestPacket(IPPROTO_ICMPV6, id, 32 >> 3, 1, 'B', 16); /* C*24 at 48. */ packets[2] = IPV6BuildTestPacket(IPPROTO_ICMPV6, id, 48 >> 3, 1, 'C', 24); /* D*8 at 80. */ packets[3] = IPV6BuildTestPacket(IPPROTO_ICMPV6, id, 80 >> 3, 1, 'D', 8); /* E*16 at 104. */ packets[4] = IPV6BuildTestPacket(IPPROTO_ICMPV6, id, 104 >> 3, 1, 'E', 16); /* F*24 at 120. */ packets[5] = IPV6BuildTestPacket(IPPROTO_ICMPV6, id, 120 >> 3, 1, 'F', 24); /* G*16 at 144. */ packets[6] = IPV6BuildTestPacket(IPPROTO_ICMPV6, id, 144 >> 3, 1, 'G', 16); /* H*16 at 160. */ packets[7] = IPV6BuildTestPacket(IPPROTO_ICMPV6, id, 160 >> 3, 1, 'H', 16); /* I*8 at 176. */ packets[8] = IPV6BuildTestPacket(IPPROTO_ICMPV6, id, 176 >> 3, 1, 'I', 8); /* * Overlapping subsequent fragments. */ /* J*32 at 8. */ packets[9] = IPV6BuildTestPacket(IPPROTO_ICMPV6, id, 8 >> 3, 1, 'J', 32); /* K*24 at 48. */ packets[10] = IPV6BuildTestPacket(IPPROTO_ICMPV6, id, 48 >> 3, 1, 'K', 24); /* L*24 at 72. */ packets[11] = IPV6BuildTestPacket(IPPROTO_ICMPV6, id, 72 >> 3, 1, 'L', 24); /* M*24 at 96. */ packets[12] = IPV6BuildTestPacket(IPPROTO_ICMPV6, id, 96 >> 3, 1, 'M', 24); /* N*8 at 128. */ packets[13] = IPV6BuildTestPacket(IPPROTO_ICMPV6, id, 128 >> 3, 1, 'N', 8); /* O*8 at 152. */ packets[14] = IPV6BuildTestPacket(IPPROTO_ICMPV6, id, 152 >> 3, 1, 'O', 8); /* P*8 at 160. */ packets[15] = IPV6BuildTestPacket(IPPROTO_ICMPV6, id, 160 >> 3, 1, 'P', 8); /* Q*16 at 176. */ packets[16] = IPV6BuildTestPacket(IPPROTO_ICMPV6, id, 176 >> 3, 0, 'Q', 16); default_policy = policy; /* Send all but the last. */ for (i = 0; i < 9; i++) { Packet *tp = Defrag(NULL, NULL, packets[i], NULL); if (tp != NULL) { SCFree(tp); goto end; } if (ENGINE_ISSET_EVENT(packets[i], IPV6_FRAG_OVERLAP)) { goto end; } } int overlap = 0; for (; i < 16; i++) { Packet *tp = Defrag(NULL, NULL, packets[i], NULL); if (tp != NULL) { SCFree(tp); goto end; } if (ENGINE_ISSET_EVENT(packets[i], IPV6_FRAG_OVERLAP)) { overlap++; } } if (!overlap) goto end; /* And now the last one. */ Packet *reassembled = Defrag(NULL, NULL, packets[16], NULL); if (reassembled == NULL) goto end; if (memcmp(GET_PKT_DATA(reassembled) + 40, expected, expected_len) != 0) goto end; if (IPV6_GET_PLEN(reassembled) != 192) goto end; SCFree(reassembled); /* Make sure all frags were returned to the pool. */ if (defrag_context->frag_pool->outstanding != 0) { printf("defrag_context->frag_pool->outstanding %u: ", defrag_context->frag_pool->outstanding); goto end; } ret = 1; end: for (i = 0; i < 17; i++) { SCFree(packets[i]); } DefragDestroy(); return ret; }
168,308
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 PPB_Widget_Impl::Invalidate(const PP_Rect* dirty) { const PPP_Widget_Dev* widget = static_cast<const PPP_Widget_Dev*>( instance()->module()->GetPluginInterface(PPP_WIDGET_DEV_INTERFACE)); if (!widget) return; ScopedResourceId resource(this); widget->Invalidate(instance()->pp_instance(), resource.id, dirty); } Commit Message: Maintain a map of all resources in the resource tracker and clear instance back pointers when needed, BUG=85808 Review URL: http://codereview.chromium.org/7196001 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89746 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void PPB_Widget_Impl::Invalidate(const PP_Rect* dirty) { if (!instance()) return; const PPP_Widget_Dev* widget = static_cast<const PPP_Widget_Dev*>( instance()->module()->GetPluginInterface(PPP_WIDGET_DEV_INTERFACE)); if (!widget) return; ScopedResourceId resource(this); widget->Invalidate(instance()->pp_instance(), resource.id, dirty); }
170,412
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 ComponentControllerImpl::BindToRequest( fuchsia::sys::Package package, fuchsia::sys::StartupInfo startup_info, fidl::InterfaceRequest<fuchsia::sys::ComponentController> controller_request) { DCHECK(!service_directory_); DCHECK(!view_provider_binding_); url_ = GURL(*package.resolved_url); if (!url_.is_valid()) { LOG(ERROR) << "Rejected invalid URL: " << url_; return false; } if (controller_request.is_valid()) { controller_binding_.Bind(std::move(controller_request)); controller_binding_.set_error_handler( fit::bind_member(this, &ComponentControllerImpl::Kill)); } runner_->context()->CreateFrame(frame_observer_binding_.NewBinding(), frame_.NewRequest()); frame_->GetNavigationController(navigation_controller_.NewRequest()); navigation_controller_->LoadUrl(url_.spec(), nullptr); service_directory_ = std::make_unique<base::fuchsia::ServiceDirectory>( std::move(startup_info.launch_info.directory_request)); view_provider_binding_ = std::make_unique< base::fuchsia::ScopedServiceBinding<fuchsia::ui::viewsv1::ViewProvider>>( service_directory_.get(), this); return true; } Commit Message: [fuchsia] Implement browser tests for WebRunner Context service. Tests may interact with the WebRunner FIDL services and the underlying browser objects for end to end testing of service and browser functionality. * Add a browser test launcher main() for WebRunner. * Add some simple navigation tests. * Wire up GoBack()/GoForward() FIDL calls. * Add embedded test server resources and initialization logic. * Add missing deletion & notification calls to BrowserContext dtor. * Use FIDL events for navigation state changes. * Bug fixes: ** Move BrowserContext and Screen deletion to PostMainMessageLoopRun(), so that they may use the MessageLoop during teardown. ** Fix Frame dtor to allow for null WindowTreeHosts (headless case) ** Fix std::move logic in Frame ctor which lead to no WebContents observer being registered. Bug: 871594 Change-Id: I36bcbd2436d534d366c6be4eeb54b9f9feadd1ac Reviewed-on: https://chromium-review.googlesource.com/1164539 Commit-Queue: Kevin Marshall <[email protected]> Reviewed-by: Wez <[email protected]> Reviewed-by: Fabrice de Gans-Riberi <[email protected]> Reviewed-by: Scott Violet <[email protected]> Cr-Commit-Position: refs/heads/master@{#584155} CWE ID: CWE-264
bool ComponentControllerImpl::BindToRequest( fuchsia::sys::Package package, fuchsia::sys::StartupInfo startup_info, fidl::InterfaceRequest<fuchsia::sys::ComponentController> controller_request) { DCHECK(!service_directory_); DCHECK(!view_provider_binding_); url_ = GURL(*package.resolved_url); if (!url_.is_valid()) { LOG(ERROR) << "Rejected invalid URL: " << url_; return false; } if (controller_request.is_valid()) { controller_binding_.Bind(std::move(controller_request)); controller_binding_.set_error_handler( fit::bind_member(this, &ComponentControllerImpl::Kill)); } runner_->context()->CreateFrame(frame_.NewRequest()); frame_->GetNavigationController(navigation_controller_.NewRequest()); navigation_controller_->LoadUrl(url_.spec(), nullptr); service_directory_ = std::make_unique<base::fuchsia::ServiceDirectory>( std::move(startup_info.launch_info.directory_request)); view_provider_binding_ = std::make_unique< base::fuchsia::ScopedServiceBinding<fuchsia::ui::viewsv1::ViewProvider>>( service_directory_.get(), this); return true; }
172,148
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: standard_test(png_store* PNG_CONST psIn, png_uint_32 PNG_CONST id, int do_interlace, int use_update_info) { standard_display d; context(psIn, fault); /* Set up the display (stack frame) variables from the arguments to the * function and initialize the locals that are filled in later. */ standard_display_init(&d, psIn, id, do_interlace, use_update_info); /* Everything is protected by a Try/Catch. The functions called also * typically have local Try/Catch blocks. */ Try { png_structp pp; png_infop pi; /* Get a png_struct for reading the image. This will throw an error if it * fails, so we don't need to check the result. */ pp = set_store_for_read(d.ps, &pi, d.id, d.do_interlace ? (d.ps->progressive ? "pngvalid progressive deinterlacer" : "pngvalid sequential deinterlacer") : (d.ps->progressive ? "progressive reader" : "sequential reader")); /* Initialize the palette correctly from the png_store_file. */ standard_palette_init(&d); /* Introduce the correct read function. */ if (d.ps->progressive) { png_set_progressive_read_fn(pp, &d, standard_info, progressive_row, standard_end); /* Now feed data into the reader until we reach the end: */ store_progressive_read(d.ps, pp, pi); } else { /* Note that this takes the store, not the display. */ png_set_read_fn(pp, d.ps, store_read); /* Check the header values: */ png_read_info(pp, pi); /* The code tests both versions of the images that the sequential * reader can produce. */ standard_info_imp(&d, pp, pi, 2 /*images*/); /* Need the total bytes in the image below; we can't get to this point * unless the PNG file values have been checked against the expected * values. */ { sequential_row(&d, pp, pi, 0, 1); /* After the last pass loop over the rows again to check that the * image is correct. */ if (!d.speed) { standard_text_validate(&d, pp, pi, 1/*check_end*/); standard_image_validate(&d, pp, 0, 1); } else d.ps->validated = 1; } } /* Check for validation. */ if (!d.ps->validated) png_error(pp, "image read failed silently"); /* Successful completion. */ } Catch(fault) d.ps = fault; /* make sure this hasn't been clobbered. */ /* In either case clean up the store. */ store_read_reset(d.ps); } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
standard_test(png_store* PNG_CONST psIn, png_uint_32 PNG_CONST id, standard_test(png_store* const psIn, png_uint_32 const id, int do_interlace, int use_update_info) { standard_display d; context(psIn, fault); /* Set up the display (stack frame) variables from the arguments to the * function and initialize the locals that are filled in later. */ standard_display_init(&d, psIn, id, do_interlace, use_update_info); /* Everything is protected by a Try/Catch. The functions called also * typically have local Try/Catch blocks. */ Try { png_structp pp; png_infop pi; /* Get a png_struct for reading the image. This will throw an error if it * fails, so we don't need to check the result. */ pp = set_store_for_read(d.ps, &pi, d.id, d.do_interlace ? (d.ps->progressive ? "pngvalid progressive deinterlacer" : "pngvalid sequential deinterlacer") : (d.ps->progressive ? "progressive reader" : "sequential reader")); /* Initialize the palette correctly from the png_store_file. */ standard_palette_init(&d); /* Introduce the correct read function. */ if (d.ps->progressive) { png_set_progressive_read_fn(pp, &d, standard_info, progressive_row, standard_end); /* Now feed data into the reader until we reach the end: */ store_progressive_read(d.ps, pp, pi); } else { /* Note that this takes the store, not the display. */ png_set_read_fn(pp, d.ps, store_read); /* Check the header values: */ png_read_info(pp, pi); /* The code tests both versions of the images that the sequential * reader can produce. */ standard_info_imp(&d, pp, pi, 2 /*images*/); /* Need the total bytes in the image below; we can't get to this point * unless the PNG file values have been checked against the expected * values. */ { sequential_row(&d, pp, pi, 0, 1); /* After the last pass loop over the rows again to check that the * image is correct. */ if (!d.speed) { standard_text_validate(&d, pp, pi, 1/*check_end*/); standard_image_validate(&d, pp, 0, 1); } else d.ps->validated = 1; } } /* Check for validation. */ if (!d.ps->validated) png_error(pp, "image read failed silently"); /* Successful completion. */ } Catch(fault) d.ps = fault; /* make sure this hasn't been clobbered. */ /* In either case clean up the store. */ store_read_reset(d.ps); }
173,702
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 test_parser(void) { int i, retval; bzrtpPacket_t *zrtpPacket; /* Create zrtp Context to use H0-H3 chains and others */ bzrtpContext_t *context87654321 = bzrtp_createBzrtpContext(0x87654321); bzrtpContext_t *context12345678 = bzrtp_createBzrtpContext(0x12345678); /* replace created H by the patterns one to be able to generate the correct packet */ memcpy (context12345678->channelContext[0]->selfH[0], H12345678[0], 32); memcpy (context12345678->channelContext[0]->selfH[1], H12345678[1], 32); memcpy (context12345678->channelContext[0]->selfH[2], H12345678[2], 32); memcpy (context12345678->channelContext[0]->selfH[3], H12345678[3], 32); memcpy (context87654321->channelContext[0]->selfH[0], H87654321[0], 32); memcpy (context87654321->channelContext[0]->selfH[1], H87654321[1], 32); memcpy (context87654321->channelContext[0]->selfH[2], H87654321[2], 32); memcpy (context87654321->channelContext[0]->selfH[3], H87654321[3], 32); /* preset the key agreement algo in the contexts */ context87654321->channelContext[0]->keyAgreementAlgo = ZRTP_KEYAGREEMENT_DH3k; context12345678->channelContext[0]->keyAgreementAlgo = ZRTP_KEYAGREEMENT_DH3k; context87654321->channelContext[0]->cipherAlgo = ZRTP_CIPHER_AES1; context12345678->channelContext[0]->cipherAlgo = ZRTP_CIPHER_AES1; context87654321->channelContext[0]->hashAlgo = ZRTP_HASH_S256; context12345678->channelContext[0]->hashAlgo = ZRTP_HASH_S256; updateCryptoFunctionPointers(context87654321->channelContext[0]); updateCryptoFunctionPointers(context12345678->channelContext[0]); /* set the zrtp and mac keys */ context87654321->channelContext[0]->mackeyi = (uint8_t *)malloc(32); context12345678->channelContext[0]->mackeyi = (uint8_t *)malloc(32); context87654321->channelContext[0]->mackeyr = (uint8_t *)malloc(32); context12345678->channelContext[0]->mackeyr = (uint8_t *)malloc(32); context87654321->channelContext[0]->zrtpkeyi = (uint8_t *)malloc(16); context12345678->channelContext[0]->zrtpkeyi = (uint8_t *)malloc(16); context87654321->channelContext[0]->zrtpkeyr = (uint8_t *)malloc(16); context12345678->channelContext[0]->zrtpkeyr = (uint8_t *)malloc(16); memcpy(context12345678->channelContext[0]->mackeyi, mackeyi, 32); memcpy(context12345678->channelContext[0]->mackeyr, mackeyr, 32); memcpy(context12345678->channelContext[0]->zrtpkeyi, zrtpkeyi, 16); memcpy(context12345678->channelContext[0]->zrtpkeyr, zrtpkeyr, 16); memcpy(context87654321->channelContext[0]->mackeyi, mackeyi, 32); memcpy(context87654321->channelContext[0]->mackeyr, mackeyr, 32); memcpy(context87654321->channelContext[0]->zrtpkeyi, zrtpkeyi, 16); memcpy(context87654321->channelContext[0]->zrtpkeyr, zrtpkeyr, 16); /* set the role: 87654321 is initiator in our exchange pattern */ context12345678->channelContext[0]->role = RESPONDER; for (i=0; i<TEST_PACKET_NUMBER; i++) { uint8_t freePacketFlag = 1; /* parse a packet string from patterns */ zrtpPacket = bzrtp_packetCheck(patternZRTPPackets[i], patternZRTPMetaData[i][0], (patternZRTPMetaData[i][1])-1, &retval); retval += bzrtp_packetParser((patternZRTPMetaData[i][2]==0x87654321)?context12345678:context87654321, (patternZRTPMetaData[i][2]==0x87654321)?context12345678->channelContext[0]:context87654321->channelContext[0], patternZRTPPackets[i], patternZRTPMetaData[i][0], zrtpPacket); /*printf("parsing Ret val is %x index is %d\n", retval, i);*/ /* We must store some packets in the context if we want to be able to parse further packets */ if (zrtpPacket->messageType==MSGTYPE_HELLO) { if (patternZRTPMetaData[i][2]==0x87654321) { context12345678->channelContext[0]->peerPackets[HELLO_MESSAGE_STORE_ID] = zrtpPacket; } else { context87654321->channelContext[0]->peerPackets[HELLO_MESSAGE_STORE_ID] = zrtpPacket; } freePacketFlag = 0; } if (zrtpPacket->messageType==MSGTYPE_COMMIT) { if (patternZRTPMetaData[i][2]==0x87654321) { context12345678->channelContext[0]->peerPackets[COMMIT_MESSAGE_STORE_ID] = zrtpPacket; } else { context87654321->channelContext[0]->peerPackets[COMMIT_MESSAGE_STORE_ID] = zrtpPacket; } freePacketFlag = 0; } if (zrtpPacket->messageType==MSGTYPE_DHPART1 || zrtpPacket->messageType==MSGTYPE_DHPART2) { if (patternZRTPMetaData[i][2]==0x87654321) { context12345678->channelContext[0]->peerPackets[DHPART_MESSAGE_STORE_ID] = zrtpPacket; } else { context87654321->channelContext[0]->peerPackets[DHPART_MESSAGE_STORE_ID] = zrtpPacket; } freePacketFlag = 0; } /* free the packet string as will be created again by the packetBuild function and might have been copied by packetParser */ free(zrtpPacket->packetString); /* build a packet string from the parser packet*/ retval = bzrtp_packetBuild((patternZRTPMetaData[i][2]==0x12345678)?context12345678:context87654321, (patternZRTPMetaData[i][2]==0x12345678)?context12345678->channelContext[0]:context87654321->channelContext[0], zrtpPacket, patternZRTPMetaData[i][1]); /* if (retval ==0) { packetDump(zrtpPacket, 1); } else { bzrtp_message("Ret val is %x index is %d\n", retval, i); }*/ /* check they are the same */ if (zrtpPacket->packetString != NULL) { CU_ASSERT_TRUE(memcmp(zrtpPacket->packetString, patternZRTPPackets[i], patternZRTPMetaData[i][0]) == 0); } else { CU_FAIL("Unable to build packet"); } if (freePacketFlag == 1) { bzrtp_freeZrtpPacket(zrtpPacket); } } bzrtp_destroyBzrtpContext(context87654321, 0x87654321); bzrtp_destroyBzrtpContext(context12345678, 0x12345678); } Commit Message: Add ZRTP Commit packet hvi check on DHPart2 packet reception CWE ID: CWE-254
void test_parser(void) { void test_parser_param(uint8_t hvi_trick) { int i, retval; bzrtpPacket_t *zrtpPacket; /* Create zrtp Context to use H0-H3 chains and others */ bzrtpContext_t *context87654321 = bzrtp_createBzrtpContext(0x87654321); bzrtpContext_t *context12345678 = bzrtp_createBzrtpContext(0x12345678); /* replace created H by the patterns one to be able to generate the correct packet */ memcpy (context12345678->channelContext[0]->selfH[0], H12345678[0], 32); memcpy (context12345678->channelContext[0]->selfH[1], H12345678[1], 32); memcpy (context12345678->channelContext[0]->selfH[2], H12345678[2], 32); memcpy (context12345678->channelContext[0]->selfH[3], H12345678[3], 32); memcpy (context87654321->channelContext[0]->selfH[0], H87654321[0], 32); memcpy (context87654321->channelContext[0]->selfH[1], H87654321[1], 32); memcpy (context87654321->channelContext[0]->selfH[2], H87654321[2], 32); memcpy (context87654321->channelContext[0]->selfH[3], H87654321[3], 32); /* preset the key agreement algo in the contexts */ context87654321->channelContext[0]->keyAgreementAlgo = ZRTP_KEYAGREEMENT_DH3k; context12345678->channelContext[0]->keyAgreementAlgo = ZRTP_KEYAGREEMENT_DH3k; context87654321->channelContext[0]->cipherAlgo = ZRTP_CIPHER_AES1; context12345678->channelContext[0]->cipherAlgo = ZRTP_CIPHER_AES1; context87654321->channelContext[0]->hashAlgo = ZRTP_HASH_S256; context12345678->channelContext[0]->hashAlgo = ZRTP_HASH_S256; updateCryptoFunctionPointers(context87654321->channelContext[0]); updateCryptoFunctionPointers(context12345678->channelContext[0]); /* set the zrtp and mac keys */ context87654321->channelContext[0]->mackeyi = (uint8_t *)malloc(32); context12345678->channelContext[0]->mackeyi = (uint8_t *)malloc(32); context87654321->channelContext[0]->mackeyr = (uint8_t *)malloc(32); context12345678->channelContext[0]->mackeyr = (uint8_t *)malloc(32); context87654321->channelContext[0]->zrtpkeyi = (uint8_t *)malloc(16); context12345678->channelContext[0]->zrtpkeyi = (uint8_t *)malloc(16); context87654321->channelContext[0]->zrtpkeyr = (uint8_t *)malloc(16); context12345678->channelContext[0]->zrtpkeyr = (uint8_t *)malloc(16); memcpy(context12345678->channelContext[0]->mackeyi, mackeyi, 32); memcpy(context12345678->channelContext[0]->mackeyr, mackeyr, 32); memcpy(context12345678->channelContext[0]->zrtpkeyi, zrtpkeyi, 16); memcpy(context12345678->channelContext[0]->zrtpkeyr, zrtpkeyr, 16); memcpy(context87654321->channelContext[0]->mackeyi, mackeyi, 32); memcpy(context87654321->channelContext[0]->mackeyr, mackeyr, 32); memcpy(context87654321->channelContext[0]->zrtpkeyi, zrtpkeyi, 16); memcpy(context87654321->channelContext[0]->zrtpkeyr, zrtpkeyr, 16); /* set the role: 87654321 is initiator in our exchange pattern */ context12345678->channelContext[0]->role = RESPONDER; for (i=0; i<TEST_PACKET_NUMBER; i++) { uint8_t freePacketFlag = 1; /* parse a packet string from patterns */ zrtpPacket = bzrtp_packetCheck(patternZRTPPackets[i], patternZRTPMetaData[i][0], (patternZRTPMetaData[i][1])-1, &retval); retval += bzrtp_packetParser((patternZRTPMetaData[i][2]==0x87654321)?context12345678:context87654321, (patternZRTPMetaData[i][2]==0x87654321)?context12345678->channelContext[0]:context87654321->channelContext[0], patternZRTPPackets[i], patternZRTPMetaData[i][0], zrtpPacket); if (hvi_trick==0) { CU_ASSERT_EQUAL_FATAL(retval,0); } else { /* when hvi trick is enable, the DH2 parsing shall fail and return BZRTP_PARSER_ERROR_UNMATCHINGHVI */ if (zrtpPacket->messageType==MSGTYPE_DHPART2) { CU_ASSERT_EQUAL_FATAL(retval, BZRTP_PARSER_ERROR_UNMATCHINGHVI); /* We shall then anyway skip the end of the test */ /* reset pointers to selfHello packet in order to avoid double free */ context87654321->channelContext[0]->selfPackets[HELLO_MESSAGE_STORE_ID] = NULL; context12345678->channelContext[0]->selfPackets[HELLO_MESSAGE_STORE_ID] = NULL; bzrtp_destroyBzrtpContext(context87654321, 0x87654321); bzrtp_destroyBzrtpContext(context12345678, 0x12345678); return; } else { CU_ASSERT_EQUAL_FATAL(retval,0); } } bzrtp_message("parsing Ret val is %x index is %d\n", retval, i); /* We must store some packets in the context if we want to be able to parse further packets */ if (zrtpPacket->messageType==MSGTYPE_HELLO) { if (patternZRTPMetaData[i][2]==0x87654321) { context12345678->channelContext[0]->peerPackets[HELLO_MESSAGE_STORE_ID] = zrtpPacket; context87654321->channelContext[0]->selfPackets[HELLO_MESSAGE_STORE_ID] = zrtpPacket; } else { context87654321->channelContext[0]->peerPackets[HELLO_MESSAGE_STORE_ID] = zrtpPacket; context12345678->channelContext[0]->selfPackets[HELLO_MESSAGE_STORE_ID] = zrtpPacket; } freePacketFlag = 0; } if (zrtpPacket->messageType==MSGTYPE_COMMIT) { if (patternZRTPMetaData[i][2]==0x87654321) { context12345678->channelContext[0]->peerPackets[COMMIT_MESSAGE_STORE_ID] = zrtpPacket; } else { context87654321->channelContext[0]->peerPackets[COMMIT_MESSAGE_STORE_ID] = zrtpPacket; } freePacketFlag = 0; } if (zrtpPacket->messageType==MSGTYPE_DHPART1 || zrtpPacket->messageType==MSGTYPE_DHPART2) { if (patternZRTPMetaData[i][2]==0x87654321) { context12345678->channelContext[0]->peerPackets[DHPART_MESSAGE_STORE_ID] = zrtpPacket; } else { context87654321->channelContext[0]->peerPackets[DHPART_MESSAGE_STORE_ID] = zrtpPacket; } freePacketFlag = 0; } /* free the packet string as will be created again by the packetBuild function and might have been copied by packetParser */ free(zrtpPacket->packetString); /* build a packet string from the parser packet*/ retval = bzrtp_packetBuild((patternZRTPMetaData[i][2]==0x12345678)?context12345678:context87654321, (patternZRTPMetaData[i][2]==0x12345678)?context12345678->channelContext[0]:context87654321->channelContext[0], zrtpPacket, patternZRTPMetaData[i][1]); /* if (retval ==0) { packetDump(zrtpPacket, 1); } else { bzrtp_message("Ret val is %x index is %d\n", retval, i); }*/ /* check they are the same */ if (zrtpPacket->packetString != NULL) { CU_ASSERT_TRUE(memcmp(zrtpPacket->packetString, patternZRTPPackets[i], patternZRTPMetaData[i][0]) == 0); } else { CU_FAIL("Unable to build packet"); } if (freePacketFlag == 1) { bzrtp_freeZrtpPacket(zrtpPacket); } /* modify the hvi stored in the peerPackets, this shall result in parsing failure on DH2 packet */ if (hvi_trick == 1) { if (zrtpPacket->messageType==MSGTYPE_COMMIT) { if (patternZRTPMetaData[i][2]==0x87654321) { bzrtpCommitMessage_t *peerCommitMessageData; peerCommitMessageData = (bzrtpCommitMessage_t *)zrtpPacket->messageData; peerCommitMessageData->hvi[0]=0xFF; } } } } /* reset pointers to selfHello packet in order to avoid double free */ context87654321->channelContext[0]->selfPackets[HELLO_MESSAGE_STORE_ID] = NULL; context12345678->channelContext[0]->selfPackets[HELLO_MESSAGE_STORE_ID] = NULL; bzrtp_destroyBzrtpContext(context87654321, 0x87654321); bzrtp_destroyBzrtpContext(context12345678, 0x12345678); }
168,829
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int acm_probe(struct usb_interface *intf, const struct usb_device_id *id) { struct usb_cdc_union_desc *union_header = NULL; struct usb_cdc_country_functional_desc *cfd = NULL; unsigned char *buffer = intf->altsetting->extra; int buflen = intf->altsetting->extralen; struct usb_interface *control_interface; struct usb_interface *data_interface; struct usb_endpoint_descriptor *epctrl = NULL; struct usb_endpoint_descriptor *epread = NULL; struct usb_endpoint_descriptor *epwrite = NULL; struct usb_device *usb_dev = interface_to_usbdev(intf); struct acm *acm; int minor; int ctrlsize, readsize; u8 *buf; u8 ac_management_function = 0; u8 call_management_function = 0; int call_interface_num = -1; int data_interface_num = -1; unsigned long quirks; int num_rx_buf; int i; unsigned int elength = 0; int combined_interfaces = 0; struct device *tty_dev; int rv = -ENOMEM; /* normal quirks */ quirks = (unsigned long)id->driver_info; if (quirks == IGNORE_DEVICE) return -ENODEV; num_rx_buf = (quirks == SINGLE_RX_URB) ? 1 : ACM_NR; /* handle quirks deadly to normal probing*/ if (quirks == NO_UNION_NORMAL) { data_interface = usb_ifnum_to_if(usb_dev, 1); control_interface = usb_ifnum_to_if(usb_dev, 0); goto skip_normal_probe; } /* normal probing*/ if (!buffer) { dev_err(&intf->dev, "Weird descriptor references\n"); return -EINVAL; } if (!buflen) { if (intf->cur_altsetting->endpoint && intf->cur_altsetting->endpoint->extralen && intf->cur_altsetting->endpoint->extra) { dev_dbg(&intf->dev, "Seeking extra descriptors on endpoint\n"); buflen = intf->cur_altsetting->endpoint->extralen; buffer = intf->cur_altsetting->endpoint->extra; } else { dev_err(&intf->dev, "Zero length descriptor references\n"); return -EINVAL; } } while (buflen > 0) { elength = buffer[0]; if (!elength) { dev_err(&intf->dev, "skipping garbage byte\n"); elength = 1; goto next_desc; } if (buffer[1] != USB_DT_CS_INTERFACE) { dev_err(&intf->dev, "skipping garbage\n"); goto next_desc; } switch (buffer[2]) { case USB_CDC_UNION_TYPE: /* we've found it */ if (elength < sizeof(struct usb_cdc_union_desc)) goto next_desc; if (union_header) { dev_err(&intf->dev, "More than one " "union descriptor, skipping ...\n"); goto next_desc; } union_header = (struct usb_cdc_union_desc *)buffer; break; case USB_CDC_COUNTRY_TYPE: /* export through sysfs*/ if (elength < sizeof(struct usb_cdc_country_functional_desc)) goto next_desc; cfd = (struct usb_cdc_country_functional_desc *)buffer; break; case USB_CDC_HEADER_TYPE: /* maybe check version */ break; /* for now we ignore it */ case USB_CDC_ACM_TYPE: if (elength < 4) goto next_desc; ac_management_function = buffer[3]; break; case USB_CDC_CALL_MANAGEMENT_TYPE: if (elength < 5) goto next_desc; call_management_function = buffer[3]; call_interface_num = buffer[4]; break; default: /* * there are LOTS more CDC descriptors that * could legitimately be found here. */ dev_dbg(&intf->dev, "Ignoring descriptor: " "type %02x, length %ud\n", buffer[2], elength); break; } next_desc: buflen -= elength; buffer += elength; } if (!union_header) { if (call_interface_num > 0) { dev_dbg(&intf->dev, "No union descriptor, using call management descriptor\n"); /* quirks for Droids MuIn LCD */ if (quirks & NO_DATA_INTERFACE) data_interface = usb_ifnum_to_if(usb_dev, 0); else data_interface = usb_ifnum_to_if(usb_dev, (data_interface_num = call_interface_num)); control_interface = intf; } else { if (intf->cur_altsetting->desc.bNumEndpoints != 3) { dev_dbg(&intf->dev,"No union descriptor, giving up\n"); return -ENODEV; } else { dev_warn(&intf->dev,"No union descriptor, testing for castrated device\n"); combined_interfaces = 1; control_interface = data_interface = intf; goto look_for_collapsed_interface; } } } else { control_interface = usb_ifnum_to_if(usb_dev, union_header->bMasterInterface0); data_interface = usb_ifnum_to_if(usb_dev, (data_interface_num = union_header->bSlaveInterface0)); } if (!control_interface || !data_interface) { dev_dbg(&intf->dev, "no interfaces\n"); return -ENODEV; } if (data_interface_num != call_interface_num) dev_dbg(&intf->dev, "Separate call control interface. That is not fully supported.\n"); if (control_interface == data_interface) { /* some broken devices designed for windows work this way */ dev_warn(&intf->dev,"Control and data interfaces are not separated!\n"); combined_interfaces = 1; /* a popular other OS doesn't use it */ quirks |= NO_CAP_LINE; if (data_interface->cur_altsetting->desc.bNumEndpoints != 3) { dev_err(&intf->dev, "This needs exactly 3 endpoints\n"); return -EINVAL; } look_for_collapsed_interface: for (i = 0; i < 3; i++) { struct usb_endpoint_descriptor *ep; ep = &data_interface->cur_altsetting->endpoint[i].desc; if (usb_endpoint_is_int_in(ep)) epctrl = ep; else if (usb_endpoint_is_bulk_out(ep)) epwrite = ep; else if (usb_endpoint_is_bulk_in(ep)) epread = ep; else return -EINVAL; } if (!epctrl || !epread || !epwrite) return -ENODEV; else goto made_compressed_probe; } skip_normal_probe: /*workaround for switched interfaces */ if (data_interface->cur_altsetting->desc.bInterfaceClass != CDC_DATA_INTERFACE_TYPE) { if (control_interface->cur_altsetting->desc.bInterfaceClass == CDC_DATA_INTERFACE_TYPE) { dev_dbg(&intf->dev, "Your device has switched interfaces.\n"); swap(control_interface, data_interface); } else { return -EINVAL; } } /* Accept probe requests only for the control interface */ if (!combined_interfaces && intf != control_interface) return -ENODEV; if (!combined_interfaces && usb_interface_claimed(data_interface)) { /* valid in this context */ dev_dbg(&intf->dev, "The data interface isn't available\n"); return -EBUSY; } if (data_interface->cur_altsetting->desc.bNumEndpoints < 2 || control_interface->cur_altsetting->desc.bNumEndpoints == 0) return -EINVAL; epctrl = &control_interface->cur_altsetting->endpoint[0].desc; epread = &data_interface->cur_altsetting->endpoint[0].desc; epwrite = &data_interface->cur_altsetting->endpoint[1].desc; /* workaround for switched endpoints */ if (!usb_endpoint_dir_in(epread)) { /* descriptors are swapped */ dev_dbg(&intf->dev, "The data interface has switched endpoints\n"); swap(epread, epwrite); } made_compressed_probe: dev_dbg(&intf->dev, "interfaces are valid\n"); acm = kzalloc(sizeof(struct acm), GFP_KERNEL); if (acm == NULL) goto alloc_fail; minor = acm_alloc_minor(acm); if (minor < 0) { dev_err(&intf->dev, "no more free acm devices\n"); kfree(acm); return -ENODEV; } ctrlsize = usb_endpoint_maxp(epctrl); readsize = usb_endpoint_maxp(epread) * (quirks == SINGLE_RX_URB ? 1 : 2); acm->combined_interfaces = combined_interfaces; acm->writesize = usb_endpoint_maxp(epwrite) * 20; acm->control = control_interface; acm->data = data_interface; acm->minor = minor; acm->dev = usb_dev; acm->ctrl_caps = ac_management_function; if (quirks & NO_CAP_LINE) acm->ctrl_caps &= ~USB_CDC_CAP_LINE; acm->ctrlsize = ctrlsize; acm->readsize = readsize; acm->rx_buflimit = num_rx_buf; INIT_WORK(&acm->work, acm_softint); init_waitqueue_head(&acm->wioctl); spin_lock_init(&acm->write_lock); spin_lock_init(&acm->read_lock); mutex_init(&acm->mutex); acm->rx_endpoint = usb_rcvbulkpipe(usb_dev, epread->bEndpointAddress); acm->is_int_ep = usb_endpoint_xfer_int(epread); if (acm->is_int_ep) acm->bInterval = epread->bInterval; tty_port_init(&acm->port); acm->port.ops = &acm_port_ops; init_usb_anchor(&acm->delayed); acm->quirks = quirks; buf = usb_alloc_coherent(usb_dev, ctrlsize, GFP_KERNEL, &acm->ctrl_dma); if (!buf) goto alloc_fail2; acm->ctrl_buffer = buf; if (acm_write_buffers_alloc(acm) < 0) goto alloc_fail4; acm->ctrlurb = usb_alloc_urb(0, GFP_KERNEL); if (!acm->ctrlurb) goto alloc_fail5; for (i = 0; i < num_rx_buf; i++) { struct acm_rb *rb = &(acm->read_buffers[i]); struct urb *urb; rb->base = usb_alloc_coherent(acm->dev, readsize, GFP_KERNEL, &rb->dma); if (!rb->base) goto alloc_fail6; rb->index = i; rb->instance = acm; urb = usb_alloc_urb(0, GFP_KERNEL); if (!urb) goto alloc_fail6; urb->transfer_flags |= URB_NO_TRANSFER_DMA_MAP; urb->transfer_dma = rb->dma; if (acm->is_int_ep) { usb_fill_int_urb(urb, acm->dev, acm->rx_endpoint, rb->base, acm->readsize, acm_read_bulk_callback, rb, acm->bInterval); } else { usb_fill_bulk_urb(urb, acm->dev, acm->rx_endpoint, rb->base, acm->readsize, acm_read_bulk_callback, rb); } acm->read_urbs[i] = urb; __set_bit(i, &acm->read_urbs_free); } for (i = 0; i < ACM_NW; i++) { struct acm_wb *snd = &(acm->wb[i]); snd->urb = usb_alloc_urb(0, GFP_KERNEL); if (snd->urb == NULL) goto alloc_fail7; if (usb_endpoint_xfer_int(epwrite)) usb_fill_int_urb(snd->urb, usb_dev, usb_sndintpipe(usb_dev, epwrite->bEndpointAddress), NULL, acm->writesize, acm_write_bulk, snd, epwrite->bInterval); else usb_fill_bulk_urb(snd->urb, usb_dev, usb_sndbulkpipe(usb_dev, epwrite->bEndpointAddress), NULL, acm->writesize, acm_write_bulk, snd); snd->urb->transfer_flags |= URB_NO_TRANSFER_DMA_MAP; if (quirks & SEND_ZERO_PACKET) snd->urb->transfer_flags |= URB_ZERO_PACKET; snd->instance = acm; } usb_set_intfdata(intf, acm); i = device_create_file(&intf->dev, &dev_attr_bmCapabilities); if (i < 0) goto alloc_fail7; if (cfd) { /* export the country data */ acm->country_codes = kmalloc(cfd->bLength - 4, GFP_KERNEL); if (!acm->country_codes) goto skip_countries; acm->country_code_size = cfd->bLength - 4; memcpy(acm->country_codes, (u8 *)&cfd->wCountyCode0, cfd->bLength - 4); acm->country_rel_date = cfd->iCountryCodeRelDate; i = device_create_file(&intf->dev, &dev_attr_wCountryCodes); if (i < 0) { kfree(acm->country_codes); acm->country_codes = NULL; acm->country_code_size = 0; goto skip_countries; } i = device_create_file(&intf->dev, &dev_attr_iCountryCodeRelDate); if (i < 0) { device_remove_file(&intf->dev, &dev_attr_wCountryCodes); kfree(acm->country_codes); acm->country_codes = NULL; acm->country_code_size = 0; goto skip_countries; } } skip_countries: usb_fill_int_urb(acm->ctrlurb, usb_dev, usb_rcvintpipe(usb_dev, epctrl->bEndpointAddress), acm->ctrl_buffer, ctrlsize, acm_ctrl_irq, acm, /* works around buggy devices */ epctrl->bInterval ? epctrl->bInterval : 16); acm->ctrlurb->transfer_flags |= URB_NO_TRANSFER_DMA_MAP; acm->ctrlurb->transfer_dma = acm->ctrl_dma; dev_info(&intf->dev, "ttyACM%d: USB ACM device\n", minor); acm->line.dwDTERate = cpu_to_le32(9600); acm->line.bDataBits = 8; acm_set_line(acm, &acm->line); usb_driver_claim_interface(&acm_driver, data_interface, acm); usb_set_intfdata(data_interface, acm); usb_get_intf(control_interface); tty_dev = tty_port_register_device(&acm->port, acm_tty_driver, minor, &control_interface->dev); if (IS_ERR(tty_dev)) { rv = PTR_ERR(tty_dev); goto alloc_fail8; } if (quirks & CLEAR_HALT_CONDITIONS) { usb_clear_halt(usb_dev, usb_rcvbulkpipe(usb_dev, epread->bEndpointAddress)); usb_clear_halt(usb_dev, usb_sndbulkpipe(usb_dev, epwrite->bEndpointAddress)); } return 0; alloc_fail8: if (acm->country_codes) { device_remove_file(&acm->control->dev, &dev_attr_wCountryCodes); device_remove_file(&acm->control->dev, &dev_attr_iCountryCodeRelDate); kfree(acm->country_codes); } device_remove_file(&acm->control->dev, &dev_attr_bmCapabilities); alloc_fail7: usb_set_intfdata(intf, NULL); for (i = 0; i < ACM_NW; i++) usb_free_urb(acm->wb[i].urb); alloc_fail6: for (i = 0; i < num_rx_buf; i++) usb_free_urb(acm->read_urbs[i]); acm_read_buffers_free(acm); usb_free_urb(acm->ctrlurb); alloc_fail5: acm_write_buffers_free(acm); alloc_fail4: usb_free_coherent(usb_dev, ctrlsize, acm->ctrl_buffer, acm->ctrl_dma); alloc_fail2: acm_release_minor(acm); kfree(acm); alloc_fail: return rv; } Commit Message: USB: cdc-acm: more sanity checking An attack has become available which pretends to be a quirky device circumventing normal sanity checks and crashes the kernel by an insufficient number of interfaces. This patch adds a check to the code path for quirky devices. Signed-off-by: Oliver Neukum <[email protected]> CC: [email protected] Signed-off-by: Greg Kroah-Hartman <[email protected]> CWE ID:
static int acm_probe(struct usb_interface *intf, const struct usb_device_id *id) { struct usb_cdc_union_desc *union_header = NULL; struct usb_cdc_country_functional_desc *cfd = NULL; unsigned char *buffer = intf->altsetting->extra; int buflen = intf->altsetting->extralen; struct usb_interface *control_interface; struct usb_interface *data_interface; struct usb_endpoint_descriptor *epctrl = NULL; struct usb_endpoint_descriptor *epread = NULL; struct usb_endpoint_descriptor *epwrite = NULL; struct usb_device *usb_dev = interface_to_usbdev(intf); struct acm *acm; int minor; int ctrlsize, readsize; u8 *buf; u8 ac_management_function = 0; u8 call_management_function = 0; int call_interface_num = -1; int data_interface_num = -1; unsigned long quirks; int num_rx_buf; int i; unsigned int elength = 0; int combined_interfaces = 0; struct device *tty_dev; int rv = -ENOMEM; /* normal quirks */ quirks = (unsigned long)id->driver_info; if (quirks == IGNORE_DEVICE) return -ENODEV; num_rx_buf = (quirks == SINGLE_RX_URB) ? 1 : ACM_NR; /* handle quirks deadly to normal probing*/ if (quirks == NO_UNION_NORMAL) { data_interface = usb_ifnum_to_if(usb_dev, 1); control_interface = usb_ifnum_to_if(usb_dev, 0); /* we would crash */ if (!data_interface || !control_interface) return -ENODEV; goto skip_normal_probe; } /* normal probing*/ if (!buffer) { dev_err(&intf->dev, "Weird descriptor references\n"); return -EINVAL; } if (!buflen) { if (intf->cur_altsetting->endpoint && intf->cur_altsetting->endpoint->extralen && intf->cur_altsetting->endpoint->extra) { dev_dbg(&intf->dev, "Seeking extra descriptors on endpoint\n"); buflen = intf->cur_altsetting->endpoint->extralen; buffer = intf->cur_altsetting->endpoint->extra; } else { dev_err(&intf->dev, "Zero length descriptor references\n"); return -EINVAL; } } while (buflen > 0) { elength = buffer[0]; if (!elength) { dev_err(&intf->dev, "skipping garbage byte\n"); elength = 1; goto next_desc; } if (buffer[1] != USB_DT_CS_INTERFACE) { dev_err(&intf->dev, "skipping garbage\n"); goto next_desc; } switch (buffer[2]) { case USB_CDC_UNION_TYPE: /* we've found it */ if (elength < sizeof(struct usb_cdc_union_desc)) goto next_desc; if (union_header) { dev_err(&intf->dev, "More than one " "union descriptor, skipping ...\n"); goto next_desc; } union_header = (struct usb_cdc_union_desc *)buffer; break; case USB_CDC_COUNTRY_TYPE: /* export through sysfs*/ if (elength < sizeof(struct usb_cdc_country_functional_desc)) goto next_desc; cfd = (struct usb_cdc_country_functional_desc *)buffer; break; case USB_CDC_HEADER_TYPE: /* maybe check version */ break; /* for now we ignore it */ case USB_CDC_ACM_TYPE: if (elength < 4) goto next_desc; ac_management_function = buffer[3]; break; case USB_CDC_CALL_MANAGEMENT_TYPE: if (elength < 5) goto next_desc; call_management_function = buffer[3]; call_interface_num = buffer[4]; break; default: /* * there are LOTS more CDC descriptors that * could legitimately be found here. */ dev_dbg(&intf->dev, "Ignoring descriptor: " "type %02x, length %ud\n", buffer[2], elength); break; } next_desc: buflen -= elength; buffer += elength; } if (!union_header) { if (call_interface_num > 0) { dev_dbg(&intf->dev, "No union descriptor, using call management descriptor\n"); /* quirks for Droids MuIn LCD */ if (quirks & NO_DATA_INTERFACE) data_interface = usb_ifnum_to_if(usb_dev, 0); else data_interface = usb_ifnum_to_if(usb_dev, (data_interface_num = call_interface_num)); control_interface = intf; } else { if (intf->cur_altsetting->desc.bNumEndpoints != 3) { dev_dbg(&intf->dev,"No union descriptor, giving up\n"); return -ENODEV; } else { dev_warn(&intf->dev,"No union descriptor, testing for castrated device\n"); combined_interfaces = 1; control_interface = data_interface = intf; goto look_for_collapsed_interface; } } } else { control_interface = usb_ifnum_to_if(usb_dev, union_header->bMasterInterface0); data_interface = usb_ifnum_to_if(usb_dev, (data_interface_num = union_header->bSlaveInterface0)); } if (!control_interface || !data_interface) { dev_dbg(&intf->dev, "no interfaces\n"); return -ENODEV; } if (data_interface_num != call_interface_num) dev_dbg(&intf->dev, "Separate call control interface. That is not fully supported.\n"); if (control_interface == data_interface) { /* some broken devices designed for windows work this way */ dev_warn(&intf->dev,"Control and data interfaces are not separated!\n"); combined_interfaces = 1; /* a popular other OS doesn't use it */ quirks |= NO_CAP_LINE; if (data_interface->cur_altsetting->desc.bNumEndpoints != 3) { dev_err(&intf->dev, "This needs exactly 3 endpoints\n"); return -EINVAL; } look_for_collapsed_interface: for (i = 0; i < 3; i++) { struct usb_endpoint_descriptor *ep; ep = &data_interface->cur_altsetting->endpoint[i].desc; if (usb_endpoint_is_int_in(ep)) epctrl = ep; else if (usb_endpoint_is_bulk_out(ep)) epwrite = ep; else if (usb_endpoint_is_bulk_in(ep)) epread = ep; else return -EINVAL; } if (!epctrl || !epread || !epwrite) return -ENODEV; else goto made_compressed_probe; } skip_normal_probe: /*workaround for switched interfaces */ if (data_interface->cur_altsetting->desc.bInterfaceClass != CDC_DATA_INTERFACE_TYPE) { if (control_interface->cur_altsetting->desc.bInterfaceClass == CDC_DATA_INTERFACE_TYPE) { dev_dbg(&intf->dev, "Your device has switched interfaces.\n"); swap(control_interface, data_interface); } else { return -EINVAL; } } /* Accept probe requests only for the control interface */ if (!combined_interfaces && intf != control_interface) return -ENODEV; if (!combined_interfaces && usb_interface_claimed(data_interface)) { /* valid in this context */ dev_dbg(&intf->dev, "The data interface isn't available\n"); return -EBUSY; } if (data_interface->cur_altsetting->desc.bNumEndpoints < 2 || control_interface->cur_altsetting->desc.bNumEndpoints == 0) return -EINVAL; epctrl = &control_interface->cur_altsetting->endpoint[0].desc; epread = &data_interface->cur_altsetting->endpoint[0].desc; epwrite = &data_interface->cur_altsetting->endpoint[1].desc; /* workaround for switched endpoints */ if (!usb_endpoint_dir_in(epread)) { /* descriptors are swapped */ dev_dbg(&intf->dev, "The data interface has switched endpoints\n"); swap(epread, epwrite); } made_compressed_probe: dev_dbg(&intf->dev, "interfaces are valid\n"); acm = kzalloc(sizeof(struct acm), GFP_KERNEL); if (acm == NULL) goto alloc_fail; minor = acm_alloc_minor(acm); if (minor < 0) { dev_err(&intf->dev, "no more free acm devices\n"); kfree(acm); return -ENODEV; } ctrlsize = usb_endpoint_maxp(epctrl); readsize = usb_endpoint_maxp(epread) * (quirks == SINGLE_RX_URB ? 1 : 2); acm->combined_interfaces = combined_interfaces; acm->writesize = usb_endpoint_maxp(epwrite) * 20; acm->control = control_interface; acm->data = data_interface; acm->minor = minor; acm->dev = usb_dev; acm->ctrl_caps = ac_management_function; if (quirks & NO_CAP_LINE) acm->ctrl_caps &= ~USB_CDC_CAP_LINE; acm->ctrlsize = ctrlsize; acm->readsize = readsize; acm->rx_buflimit = num_rx_buf; INIT_WORK(&acm->work, acm_softint); init_waitqueue_head(&acm->wioctl); spin_lock_init(&acm->write_lock); spin_lock_init(&acm->read_lock); mutex_init(&acm->mutex); acm->rx_endpoint = usb_rcvbulkpipe(usb_dev, epread->bEndpointAddress); acm->is_int_ep = usb_endpoint_xfer_int(epread); if (acm->is_int_ep) acm->bInterval = epread->bInterval; tty_port_init(&acm->port); acm->port.ops = &acm_port_ops; init_usb_anchor(&acm->delayed); acm->quirks = quirks; buf = usb_alloc_coherent(usb_dev, ctrlsize, GFP_KERNEL, &acm->ctrl_dma); if (!buf) goto alloc_fail2; acm->ctrl_buffer = buf; if (acm_write_buffers_alloc(acm) < 0) goto alloc_fail4; acm->ctrlurb = usb_alloc_urb(0, GFP_KERNEL); if (!acm->ctrlurb) goto alloc_fail5; for (i = 0; i < num_rx_buf; i++) { struct acm_rb *rb = &(acm->read_buffers[i]); struct urb *urb; rb->base = usb_alloc_coherent(acm->dev, readsize, GFP_KERNEL, &rb->dma); if (!rb->base) goto alloc_fail6; rb->index = i; rb->instance = acm; urb = usb_alloc_urb(0, GFP_KERNEL); if (!urb) goto alloc_fail6; urb->transfer_flags |= URB_NO_TRANSFER_DMA_MAP; urb->transfer_dma = rb->dma; if (acm->is_int_ep) { usb_fill_int_urb(urb, acm->dev, acm->rx_endpoint, rb->base, acm->readsize, acm_read_bulk_callback, rb, acm->bInterval); } else { usb_fill_bulk_urb(urb, acm->dev, acm->rx_endpoint, rb->base, acm->readsize, acm_read_bulk_callback, rb); } acm->read_urbs[i] = urb; __set_bit(i, &acm->read_urbs_free); } for (i = 0; i < ACM_NW; i++) { struct acm_wb *snd = &(acm->wb[i]); snd->urb = usb_alloc_urb(0, GFP_KERNEL); if (snd->urb == NULL) goto alloc_fail7; if (usb_endpoint_xfer_int(epwrite)) usb_fill_int_urb(snd->urb, usb_dev, usb_sndintpipe(usb_dev, epwrite->bEndpointAddress), NULL, acm->writesize, acm_write_bulk, snd, epwrite->bInterval); else usb_fill_bulk_urb(snd->urb, usb_dev, usb_sndbulkpipe(usb_dev, epwrite->bEndpointAddress), NULL, acm->writesize, acm_write_bulk, snd); snd->urb->transfer_flags |= URB_NO_TRANSFER_DMA_MAP; if (quirks & SEND_ZERO_PACKET) snd->urb->transfer_flags |= URB_ZERO_PACKET; snd->instance = acm; } usb_set_intfdata(intf, acm); i = device_create_file(&intf->dev, &dev_attr_bmCapabilities); if (i < 0) goto alloc_fail7; if (cfd) { /* export the country data */ acm->country_codes = kmalloc(cfd->bLength - 4, GFP_KERNEL); if (!acm->country_codes) goto skip_countries; acm->country_code_size = cfd->bLength - 4; memcpy(acm->country_codes, (u8 *)&cfd->wCountyCode0, cfd->bLength - 4); acm->country_rel_date = cfd->iCountryCodeRelDate; i = device_create_file(&intf->dev, &dev_attr_wCountryCodes); if (i < 0) { kfree(acm->country_codes); acm->country_codes = NULL; acm->country_code_size = 0; goto skip_countries; } i = device_create_file(&intf->dev, &dev_attr_iCountryCodeRelDate); if (i < 0) { device_remove_file(&intf->dev, &dev_attr_wCountryCodes); kfree(acm->country_codes); acm->country_codes = NULL; acm->country_code_size = 0; goto skip_countries; } } skip_countries: usb_fill_int_urb(acm->ctrlurb, usb_dev, usb_rcvintpipe(usb_dev, epctrl->bEndpointAddress), acm->ctrl_buffer, ctrlsize, acm_ctrl_irq, acm, /* works around buggy devices */ epctrl->bInterval ? epctrl->bInterval : 16); acm->ctrlurb->transfer_flags |= URB_NO_TRANSFER_DMA_MAP; acm->ctrlurb->transfer_dma = acm->ctrl_dma; dev_info(&intf->dev, "ttyACM%d: USB ACM device\n", minor); acm->line.dwDTERate = cpu_to_le32(9600); acm->line.bDataBits = 8; acm_set_line(acm, &acm->line); usb_driver_claim_interface(&acm_driver, data_interface, acm); usb_set_intfdata(data_interface, acm); usb_get_intf(control_interface); tty_dev = tty_port_register_device(&acm->port, acm_tty_driver, minor, &control_interface->dev); if (IS_ERR(tty_dev)) { rv = PTR_ERR(tty_dev); goto alloc_fail8; } if (quirks & CLEAR_HALT_CONDITIONS) { usb_clear_halt(usb_dev, usb_rcvbulkpipe(usb_dev, epread->bEndpointAddress)); usb_clear_halt(usb_dev, usb_sndbulkpipe(usb_dev, epwrite->bEndpointAddress)); } return 0; alloc_fail8: if (acm->country_codes) { device_remove_file(&acm->control->dev, &dev_attr_wCountryCodes); device_remove_file(&acm->control->dev, &dev_attr_iCountryCodeRelDate); kfree(acm->country_codes); } device_remove_file(&acm->control->dev, &dev_attr_bmCapabilities); alloc_fail7: usb_set_intfdata(intf, NULL); for (i = 0; i < ACM_NW; i++) usb_free_urb(acm->wb[i].urb); alloc_fail6: for (i = 0; i < num_rx_buf; i++) usb_free_urb(acm->read_urbs[i]); acm_read_buffers_free(acm); usb_free_urb(acm->ctrlurb); alloc_fail5: acm_write_buffers_free(acm); alloc_fail4: usb_free_coherent(usb_dev, ctrlsize, acm->ctrl_buffer, acm->ctrl_dma); alloc_fail2: acm_release_minor(acm); kfree(acm); alloc_fail: return rv; }
167,358
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 yr_object_array_set_item( YR_OBJECT* object, YR_OBJECT* item, int index) { YR_OBJECT_ARRAY* array; int i; int count; assert(index >= 0); assert(object->type == OBJECT_TYPE_ARRAY); array = object_as_array(object); if (array->items == NULL) { count = yr_max(64, (index + 1) * 2); array->items = (YR_ARRAY_ITEMS*) yr_malloc( sizeof(YR_ARRAY_ITEMS) + count * sizeof(YR_OBJECT*)); if (array->items == NULL) return ERROR_INSUFFICIENT_MEMORY; memset(array->items->objects, 0, count * sizeof(YR_OBJECT*)); array->items->count = count; } else if (index >= array->items->count) { count = array->items->count * 2; array->items = (YR_ARRAY_ITEMS*) yr_realloc( array->items, sizeof(YR_ARRAY_ITEMS) + count * sizeof(YR_OBJECT*)); if (array->items == NULL) return ERROR_INSUFFICIENT_MEMORY; for (i = array->items->count; i < count; i++) array->items->objects[i] = NULL; array->items->count = count; } item->parent = object; array->items->objects[index] = item; return ERROR_SUCCESS; } Commit Message: Fix heap overflow (reported by Jurriaan Bremer) When setting a new array item with yr_object_array_set_item() the array size is doubled if the index for the new item is larger than the already allocated ones. No further checks were made to ensure that the index fits into the array after doubling its capacity. If the array capacity was for example 64, and a new object is assigned to an index larger than 128 the overflow occurs. As yr_object_array_set_item() is usually invoked with indexes that increase monotonically by one, this bug never triggered before. But the new "dotnet" module has the potential to allow the exploitation of this bug by scanning a specially crafted .NET binary. CWE ID: CWE-119
int yr_object_array_set_item( YR_OBJECT* object, YR_OBJECT* item, int index) { YR_OBJECT_ARRAY* array; int i; int count; assert(index >= 0); assert(object->type == OBJECT_TYPE_ARRAY); array = object_as_array(object); if (array->items == NULL) { count = 64; while (count <= index) count *= 2; array->items = (YR_ARRAY_ITEMS*) yr_malloc( sizeof(YR_ARRAY_ITEMS) + count * sizeof(YR_OBJECT*)); if (array->items == NULL) return ERROR_INSUFFICIENT_MEMORY; memset(array->items->objects, 0, count * sizeof(YR_OBJECT*)); array->items->count = count; } else if (index >= array->items->count) { count = array->items->count * 2; while (count <= index) count *= 2; array->items = (YR_ARRAY_ITEMS*) yr_realloc( array->items, sizeof(YR_ARRAY_ITEMS) + count * sizeof(YR_OBJECT*)); if (array->items == NULL) return ERROR_INSUFFICIENT_MEMORY; for (i = array->items->count; i < count; i++) array->items->objects[i] = NULL; array->items->count = count; } item->parent = object; array->items->objects[index] = item; return ERROR_SUCCESS; }
168,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: void CreateTwoTabs(bool focus_tab_strip, LifecycleUnit** first_lifecycle_unit, LifecycleUnit** second_lifecycle_unit) { if (focus_tab_strip) source_->SetFocusedTabStripModelForTesting(tab_strip_model_.get()); task_runner_->FastForwardBy(kShortDelay); auto time_before_first_tab = NowTicks(); EXPECT_CALL(source_observer_, OnLifecycleUnitCreated(testing::_)) .WillOnce(testing::Invoke([&](LifecycleUnit* lifecycle_unit) { *first_lifecycle_unit = lifecycle_unit; if (focus_tab_strip) { EXPECT_TRUE(IsFocused(*first_lifecycle_unit)); } else { EXPECT_EQ(time_before_first_tab, (*first_lifecycle_unit)->GetLastFocusedTime()); } })); std::unique_ptr<content::WebContents> first_web_contents = CreateAndNavigateWebContents(); content::WebContents* raw_first_web_contents = first_web_contents.get(); tab_strip_model_->AppendWebContents(std::move(first_web_contents), true); testing::Mock::VerifyAndClear(&source_observer_); EXPECT_TRUE(source_->GetTabLifecycleUnitExternal(raw_first_web_contents)); task_runner_->FastForwardBy(kShortDelay); auto time_before_second_tab = NowTicks(); EXPECT_CALL(source_observer_, OnLifecycleUnitCreated(testing::_)) .WillOnce(testing::Invoke([&](LifecycleUnit* lifecycle_unit) { *second_lifecycle_unit = lifecycle_unit; if (focus_tab_strip) { EXPECT_EQ(time_before_second_tab, (*first_lifecycle_unit)->GetLastFocusedTime()); EXPECT_TRUE(IsFocused(*second_lifecycle_unit)); } else { EXPECT_EQ(time_before_first_tab, (*first_lifecycle_unit)->GetLastFocusedTime()); EXPECT_EQ(time_before_second_tab, (*second_lifecycle_unit)->GetLastFocusedTime()); } })); std::unique_ptr<content::WebContents> second_web_contents = CreateAndNavigateWebContents(); content::WebContents* raw_second_web_contents = second_web_contents.get(); tab_strip_model_->AppendWebContents(std::move(second_web_contents), true); testing::Mock::VerifyAndClear(&source_observer_); EXPECT_TRUE(source_->GetTabLifecycleUnitExternal(raw_second_web_contents)); raw_first_web_contents->WasHidden(); } Commit Message: Connect the LocalDB to TabManager. Bug: 773382 Change-Id: Iec8fe5226ee175105d51f300f30b4865478ac099 Reviewed-on: https://chromium-review.googlesource.com/1118611 Commit-Queue: Sébastien Marchand <[email protected]> Reviewed-by: François Doray <[email protected]> Cr-Commit-Position: refs/heads/master@{#572871} CWE ID:
void CreateTwoTabs(bool focus_tab_strip, LifecycleUnit** first_lifecycle_unit, LifecycleUnit** second_lifecycle_unit) { if (focus_tab_strip) source_->SetFocusedTabStripModelForTesting(tab_strip_model_.get()); task_runner_->FastForwardBy(kShortDelay); auto time_before_first_tab = NowTicks(); EXPECT_CALL(source_observer_, OnLifecycleUnitCreated(::testing::_)) .WillOnce(::testing::Invoke([&](LifecycleUnit* lifecycle_unit) { *first_lifecycle_unit = lifecycle_unit; if (focus_tab_strip) { EXPECT_TRUE(IsFocused(*first_lifecycle_unit)); } else { EXPECT_EQ(time_before_first_tab, (*first_lifecycle_unit)->GetLastFocusedTime()); } })); std::unique_ptr<content::WebContents> first_web_contents = CreateAndNavigateWebContents(); content::WebContents* raw_first_web_contents = first_web_contents.get(); tab_strip_model_->AppendWebContents(std::move(first_web_contents), true); ::testing::Mock::VerifyAndClear(&source_observer_); EXPECT_TRUE(source_->GetTabLifecycleUnitExternal(raw_first_web_contents)); base::RepeatingClosure run_loop_cb = base::BindRepeating( &base::TestMockTimeTaskRunner::RunUntilIdle, task_runner_); testing::WaitForLocalDBEntryToBeInitialized(raw_first_web_contents, run_loop_cb); testing::ExpireLocalDBObservationWindows(raw_first_web_contents); task_runner_->FastForwardBy(kShortDelay); auto time_before_second_tab = NowTicks(); EXPECT_CALL(source_observer_, OnLifecycleUnitCreated(::testing::_)) .WillOnce(::testing::Invoke([&](LifecycleUnit* lifecycle_unit) { *second_lifecycle_unit = lifecycle_unit; if (focus_tab_strip) { EXPECT_EQ(time_before_second_tab, (*first_lifecycle_unit)->GetLastFocusedTime()); EXPECT_TRUE(IsFocused(*second_lifecycle_unit)); } else { EXPECT_EQ(time_before_first_tab, (*first_lifecycle_unit)->GetLastFocusedTime()); EXPECT_EQ(time_before_second_tab, (*second_lifecycle_unit)->GetLastFocusedTime()); } })); std::unique_ptr<content::WebContents> second_web_contents = CreateAndNavigateWebContents(); content::WebContents* raw_second_web_contents = second_web_contents.get(); tab_strip_model_->AppendWebContents(std::move(second_web_contents), true); ::testing::Mock::VerifyAndClear(&source_observer_); EXPECT_TRUE(source_->GetTabLifecycleUnitExternal(raw_second_web_contents)); testing::WaitForLocalDBEntryToBeInitialized(raw_second_web_contents, run_loop_cb); testing::ExpireLocalDBObservationWindows(raw_second_web_contents); raw_first_web_contents->WasHidden(); }
172,222
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 __u8 *pl_report_fixup(struct hid_device *hdev, __u8 *rdesc, unsigned int *rsize) { if (*rsize >= 60 && rdesc[39] == 0x2a && rdesc[40] == 0xf5 && rdesc[41] == 0x00 && rdesc[59] == 0x26 && rdesc[60] == 0xf9 && rdesc[61] == 0x00) { hid_info(hdev, "fixing up Petalynx Maxter Remote report descriptor\n"); rdesc[60] = 0xfa; rdesc[40] = 0xfa; } return rdesc; } Commit Message: HID: fix a couple of off-by-ones There are a few very theoretical off-by-one bugs in report descriptor size checking when performing a pre-parsing fixup. Fix those. Cc: [email protected] Reported-by: Ben Hawkes <[email protected]> Reviewed-by: Benjamin Tissoires <[email protected]> Signed-off-by: Jiri Kosina <[email protected]> CWE ID: CWE-119
static __u8 *pl_report_fixup(struct hid_device *hdev, __u8 *rdesc, unsigned int *rsize) { if (*rsize >= 62 && rdesc[39] == 0x2a && rdesc[40] == 0xf5 && rdesc[41] == 0x00 && rdesc[59] == 0x26 && rdesc[60] == 0xf9 && rdesc[61] == 0x00) { hid_info(hdev, "fixing up Petalynx Maxter Remote report descriptor\n"); rdesc[60] = 0xfa; rdesc[40] = 0xfa; } return rdesc; }
166,374
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: get_endpoints(struct usbtest_dev *dev, struct usb_interface *intf) { int tmp; struct usb_host_interface *alt; struct usb_host_endpoint *in, *out; struct usb_host_endpoint *iso_in, *iso_out; struct usb_host_endpoint *int_in, *int_out; struct usb_device *udev; for (tmp = 0; tmp < intf->num_altsetting; tmp++) { unsigned ep; in = out = NULL; iso_in = iso_out = NULL; int_in = int_out = NULL; alt = intf->altsetting + tmp; if (override_alt >= 0 && override_alt != alt->desc.bAlternateSetting) continue; /* take the first altsetting with in-bulk + out-bulk; * ignore other endpoints and altsettings. */ for (ep = 0; ep < alt->desc.bNumEndpoints; ep++) { struct usb_host_endpoint *e; int edi; e = alt->endpoint + ep; edi = usb_endpoint_dir_in(&e->desc); switch (usb_endpoint_type(&e->desc)) { case USB_ENDPOINT_XFER_BULK: endpoint_update(edi, &in, &out, e); continue; case USB_ENDPOINT_XFER_INT: if (dev->info->intr) endpoint_update(edi, &int_in, &int_out, e); continue; case USB_ENDPOINT_XFER_ISOC: if (dev->info->iso) endpoint_update(edi, &iso_in, &iso_out, e); /* FALLTHROUGH */ default: continue; } } if ((in && out) || iso_in || iso_out || int_in || int_out) goto found; } return -EINVAL; found: udev = testdev_to_usbdev(dev); dev->info->alt = alt->desc.bAlternateSetting; if (alt->desc.bAlternateSetting != 0) { tmp = usb_set_interface(udev, alt->desc.bInterfaceNumber, alt->desc.bAlternateSetting); if (tmp < 0) return tmp; } if (in) { dev->in_pipe = usb_rcvbulkpipe(udev, in->desc.bEndpointAddress & USB_ENDPOINT_NUMBER_MASK); dev->out_pipe = usb_sndbulkpipe(udev, out->desc.bEndpointAddress & USB_ENDPOINT_NUMBER_MASK); } if (iso_in) { dev->iso_in = &iso_in->desc; dev->in_iso_pipe = usb_rcvisocpipe(udev, iso_in->desc.bEndpointAddress & USB_ENDPOINT_NUMBER_MASK); } if (iso_out) { dev->iso_out = &iso_out->desc; dev->out_iso_pipe = usb_sndisocpipe(udev, iso_out->desc.bEndpointAddress & USB_ENDPOINT_NUMBER_MASK); } if (int_in) { dev->int_in = &int_in->desc; dev->in_int_pipe = usb_rcvintpipe(udev, int_in->desc.bEndpointAddress & USB_ENDPOINT_NUMBER_MASK); } if (int_out) { dev->int_out = &int_out->desc; dev->out_int_pipe = usb_sndintpipe(udev, int_out->desc.bEndpointAddress & USB_ENDPOINT_NUMBER_MASK); } return 0; } Commit Message: usb: usbtest: fix NULL pointer dereference If the usbtest driver encounters a device with an IN bulk endpoint but no OUT bulk endpoint, it will try to dereference a NULL pointer (out->desc.bEndpointAddress). The problem can be solved by adding a missing test. Signed-off-by: Alan Stern <[email protected]> Reported-by: Andrey Konovalov <[email protected]> Tested-by: Andrey Konovalov <[email protected]> Signed-off-by: Felipe Balbi <[email protected]> CWE ID: CWE-476
get_endpoints(struct usbtest_dev *dev, struct usb_interface *intf) { int tmp; struct usb_host_interface *alt; struct usb_host_endpoint *in, *out; struct usb_host_endpoint *iso_in, *iso_out; struct usb_host_endpoint *int_in, *int_out; struct usb_device *udev; for (tmp = 0; tmp < intf->num_altsetting; tmp++) { unsigned ep; in = out = NULL; iso_in = iso_out = NULL; int_in = int_out = NULL; alt = intf->altsetting + tmp; if (override_alt >= 0 && override_alt != alt->desc.bAlternateSetting) continue; /* take the first altsetting with in-bulk + out-bulk; * ignore other endpoints and altsettings. */ for (ep = 0; ep < alt->desc.bNumEndpoints; ep++) { struct usb_host_endpoint *e; int edi; e = alt->endpoint + ep; edi = usb_endpoint_dir_in(&e->desc); switch (usb_endpoint_type(&e->desc)) { case USB_ENDPOINT_XFER_BULK: endpoint_update(edi, &in, &out, e); continue; case USB_ENDPOINT_XFER_INT: if (dev->info->intr) endpoint_update(edi, &int_in, &int_out, e); continue; case USB_ENDPOINT_XFER_ISOC: if (dev->info->iso) endpoint_update(edi, &iso_in, &iso_out, e); /* FALLTHROUGH */ default: continue; } } if ((in && out) || iso_in || iso_out || int_in || int_out) goto found; } return -EINVAL; found: udev = testdev_to_usbdev(dev); dev->info->alt = alt->desc.bAlternateSetting; if (alt->desc.bAlternateSetting != 0) { tmp = usb_set_interface(udev, alt->desc.bInterfaceNumber, alt->desc.bAlternateSetting); if (tmp < 0) return tmp; } if (in) dev->in_pipe = usb_rcvbulkpipe(udev, in->desc.bEndpointAddress & USB_ENDPOINT_NUMBER_MASK); if (out) dev->out_pipe = usb_sndbulkpipe(udev, out->desc.bEndpointAddress & USB_ENDPOINT_NUMBER_MASK); if (iso_in) { dev->iso_in = &iso_in->desc; dev->in_iso_pipe = usb_rcvisocpipe(udev, iso_in->desc.bEndpointAddress & USB_ENDPOINT_NUMBER_MASK); } if (iso_out) { dev->iso_out = &iso_out->desc; dev->out_iso_pipe = usb_sndisocpipe(udev, iso_out->desc.bEndpointAddress & USB_ENDPOINT_NUMBER_MASK); } if (int_in) { dev->int_in = &int_in->desc; dev->in_int_pipe = usb_rcvintpipe(udev, int_in->desc.bEndpointAddress & USB_ENDPOINT_NUMBER_MASK); } if (int_out) { dev->int_out = &int_out->desc; dev->out_int_pipe = usb_sndintpipe(udev, int_out->desc.bEndpointAddress & USB_ENDPOINT_NUMBER_MASK); } return 0; }
167,678
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: WORK_STATE tls_finish_handshake(SSL *s, WORK_STATE wst) { void (*cb) (const SSL *ssl, int type, int val) = NULL; #ifndef OPENSSL_NO_SCTP if (SSL_IS_DTLS(s) && BIO_dgram_is_sctp(SSL_get_wbio(s))) { WORK_STATE ret; ret = dtls_wait_for_dry(s); if (ret != WORK_FINISHED_CONTINUE) return ret; } #endif /* clean a few things up */ ssl3_cleanup_key_block(s); if (!SSL_IS_DTLS(s)) { /* * We don't do this in DTLS because we may still need the init_buf * in case there are any unexpected retransmits */ BUF_MEM_free(s->init_buf); s->init_buf = NULL; } ssl_free_wbio_buffer(s); s->init_num = 0; if (!s->server || s->renegotiate == 2) { /* skipped if we just sent a HelloRequest */ s->renegotiate = 0; s->new_session = 0; if (s->server) { ssl_update_cache(s, SSL_SESS_CACHE_SERVER); s->ctx->stats.sess_accept_good++; s->handshake_func = ossl_statem_accept; } else { ssl_update_cache(s, SSL_SESS_CACHE_CLIENT); if (s->hit) s->ctx->stats.sess_hit++; s->handshake_func = ossl_statem_connect; s->ctx->stats.sess_connect_good++; } if (s->info_callback != NULL) cb = s->info_callback; else if (s->ctx->info_callback != NULL) cb = s->ctx->info_callback; if (cb != NULL) cb(s, SSL_CB_HANDSHAKE_DONE, 1); if (SSL_IS_DTLS(s)) { /* done with handshaking */ s->d1->handshake_read_seq = 0; s->d1->handshake_write_seq = 0; s->d1->next_handshake_write_seq = 0; } } } Commit Message: CWE ID: CWE-399
WORK_STATE tls_finish_handshake(SSL *s, WORK_STATE wst) { void (*cb) (const SSL *ssl, int type, int val) = NULL; #ifndef OPENSSL_NO_SCTP if (SSL_IS_DTLS(s) && BIO_dgram_is_sctp(SSL_get_wbio(s))) { WORK_STATE ret; ret = dtls_wait_for_dry(s); if (ret != WORK_FINISHED_CONTINUE) return ret; } #endif /* clean a few things up */ ssl3_cleanup_key_block(s); if (!SSL_IS_DTLS(s)) { /* * We don't do this in DTLS because we may still need the init_buf * in case there are any unexpected retransmits */ BUF_MEM_free(s->init_buf); s->init_buf = NULL; } ssl_free_wbio_buffer(s); s->init_num = 0; if (!s->server || s->renegotiate == 2) { /* skipped if we just sent a HelloRequest */ s->renegotiate = 0; s->new_session = 0; if (s->server) { ssl_update_cache(s, SSL_SESS_CACHE_SERVER); s->ctx->stats.sess_accept_good++; s->handshake_func = ossl_statem_accept; } else { ssl_update_cache(s, SSL_SESS_CACHE_CLIENT); if (s->hit) s->ctx->stats.sess_hit++; s->handshake_func = ossl_statem_connect; s->ctx->stats.sess_connect_good++; } if (s->info_callback != NULL) cb = s->info_callback; else if (s->ctx->info_callback != NULL) cb = s->ctx->info_callback; if (cb != NULL) cb(s, SSL_CB_HANDSHAKE_DONE, 1); if (SSL_IS_DTLS(s)) { /* done with handshaking */ s->d1->handshake_read_seq = 0; s->d1->handshake_write_seq = 0; s->d1->next_handshake_write_seq = 0; dtls1_clear_received_buffer(s); } } }
165,198
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: OMX_ERRORTYPE omx_vdec::fill_this_buffer(OMX_IN OMX_HANDLETYPE hComp, OMX_IN OMX_BUFFERHEADERTYPE* buffer) { unsigned nPortIndex = 0; if (dynamic_buf_mode) { private_handle_t *handle = NULL; struct VideoDecoderOutputMetaData *meta; unsigned int nPortIndex = 0; if (!buffer || !buffer->pBuffer) { DEBUG_PRINT_ERROR("%s: invalid params: %p", __FUNCTION__, buffer); return OMX_ErrorBadParameter; } meta = (struct VideoDecoderOutputMetaData *)buffer->pBuffer; handle = (private_handle_t *)meta->pHandle; DEBUG_PRINT_LOW("FTB: metabuf: %p buftype: %d bufhndl: %p ", meta, meta->eType, meta->pHandle); if (!handle) { DEBUG_PRINT_ERROR("FTB: Error: IL client passed an invalid buf handle - %p", handle); return OMX_ErrorBadParameter; } nPortIndex = buffer-((OMX_BUFFERHEADERTYPE *)client_buffers.get_il_buf_hdr()); drv_ctx.ptr_outputbuffer[nPortIndex].pmem_fd = handle->fd; drv_ctx.ptr_outputbuffer[nPortIndex].bufferaddr = (OMX_U8*) buffer; native_buffer[nPortIndex].privatehandle = handle; native_buffer[nPortIndex].nativehandle = handle; buffer->nFilledLen = 0; buffer->nAllocLen = handle->size; } if (m_state == OMX_StateInvalid) { DEBUG_PRINT_ERROR("FTB in Invalid State"); return OMX_ErrorInvalidState; } if (!m_out_bEnabled) { DEBUG_PRINT_ERROR("ERROR:FTB incorrect state operation, output port is disabled."); return OMX_ErrorIncorrectStateOperation; } nPortIndex = buffer - client_buffers.get_il_buf_hdr(); if (buffer == NULL || (nPortIndex >= drv_ctx.op_buf.actualcount)) { DEBUG_PRINT_ERROR("FTB: ERROR: invalid buffer index, nPortIndex %u bufCount %u", nPortIndex, drv_ctx.op_buf.actualcount); return OMX_ErrorBadParameter; } if (buffer->nOutputPortIndex != OMX_CORE_OUTPUT_PORT_INDEX) { DEBUG_PRINT_ERROR("ERROR:FTB invalid port in header %u", (unsigned int)buffer->nOutputPortIndex); return OMX_ErrorBadPortIndex; } DEBUG_PRINT_LOW("[FTB] bufhdr = %p, bufhdr->pBuffer = %p", buffer, buffer->pBuffer); post_event((unsigned long) hComp, (unsigned long)buffer, m_fill_output_msg); return OMX_ErrorNone; } Commit Message: DO NOT MERGE mm-video-v4l2: vdec: Avoid processing ETBs/FTBs in invalid states (per the spec) ETB/FTB should not be handled in states other than Executing, Paused and Idle. This avoids accessing invalid buffers. Also add a lock to protect the private-buffers from being deleted while accessing from another thread. Bug: 27890802 Security Vulnerability - Heap Use-After-Free and Possible LPE in MediaServer (libOmxVdec problem #6) CRs-Fixed: 1008882 Change-Id: Iaac2e383cd53cf9cf8042c9ed93ddc76dba3907e CWE ID:
OMX_ERRORTYPE omx_vdec::fill_this_buffer(OMX_IN OMX_HANDLETYPE hComp, OMX_IN OMX_BUFFERHEADERTYPE* buffer) { if (m_state != OMX_StateExecuting && m_state != OMX_StatePause && m_state != OMX_StateIdle) { DEBUG_PRINT_ERROR("FTB in Invalid State"); return OMX_ErrorInvalidState; } if (!m_out_bEnabled) { DEBUG_PRINT_ERROR("ERROR:FTB incorrect state operation, output port is disabled."); return OMX_ErrorIncorrectStateOperation; } unsigned nPortIndex = 0; if (dynamic_buf_mode) { private_handle_t *handle = NULL; struct VideoDecoderOutputMetaData *meta; unsigned int nPortIndex = 0; if (!buffer || !buffer->pBuffer) { DEBUG_PRINT_ERROR("%s: invalid params: %p", __FUNCTION__, buffer); return OMX_ErrorBadParameter; } meta = (struct VideoDecoderOutputMetaData *)buffer->pBuffer; handle = (private_handle_t *)meta->pHandle; DEBUG_PRINT_LOW("FTB: metabuf: %p buftype: %d bufhndl: %p ", meta, meta->eType, meta->pHandle); if (!handle) { DEBUG_PRINT_ERROR("FTB: Error: IL client passed an invalid buf handle - %p", handle); return OMX_ErrorBadParameter; } nPortIndex = buffer-((OMX_BUFFERHEADERTYPE *)client_buffers.get_il_buf_hdr()); drv_ctx.ptr_outputbuffer[nPortIndex].pmem_fd = handle->fd; drv_ctx.ptr_outputbuffer[nPortIndex].bufferaddr = (OMX_U8*) buffer; native_buffer[nPortIndex].privatehandle = handle; native_buffer[nPortIndex].nativehandle = handle; buffer->nFilledLen = 0; buffer->nAllocLen = handle->size; } nPortIndex = buffer - client_buffers.get_il_buf_hdr(); if (buffer == NULL || (nPortIndex >= drv_ctx.op_buf.actualcount)) { DEBUG_PRINT_ERROR("FTB: ERROR: invalid buffer index, nPortIndex %u bufCount %u", nPortIndex, drv_ctx.op_buf.actualcount); return OMX_ErrorBadParameter; } if (buffer->nOutputPortIndex != OMX_CORE_OUTPUT_PORT_INDEX) { DEBUG_PRINT_ERROR("ERROR:FTB invalid port in header %u", (unsigned int)buffer->nOutputPortIndex); return OMX_ErrorBadPortIndex; } DEBUG_PRINT_LOW("[FTB] bufhdr = %p, bufhdr->pBuffer = %p", buffer, buffer->pBuffer); post_event((unsigned long) hComp, (unsigned long)buffer, m_fill_output_msg); return OMX_ErrorNone; }
173,751
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void perf_event_comm_output(struct perf_event *event, struct perf_comm_event *comm_event) { struct perf_output_handle handle; struct perf_sample_data sample; int size = comm_event->event_id.header.size; int ret; perf_event_header__init_id(&comm_event->event_id.header, &sample, event); ret = perf_output_begin(&handle, event, comm_event->event_id.header.size, 0, 0); if (ret) goto out; comm_event->event_id.pid = perf_event_pid(event, comm_event->task); comm_event->event_id.tid = perf_event_tid(event, comm_event->task); perf_output_put(&handle, comm_event->event_id); __output_copy(&handle, comm_event->comm, comm_event->comm_size); perf_event__output_id_sample(event, &handle, &sample); perf_output_end(&handle); out: comm_event->event_id.header.size = size; } Commit Message: perf: Remove the nmi parameter from the swevent and overflow interface The nmi parameter indicated if we could do wakeups from the current context, if not, we would set some state and self-IPI and let the resulting interrupt do the wakeup. For the various event classes: - hardware: nmi=0; PMI is in fact an NMI or we run irq_work_run from the PMI-tail (ARM etc.) - tracepoint: nmi=0; since tracepoint could be from NMI context. - software: nmi=[0,1]; some, like the schedule thing cannot perform wakeups, and hence need 0. As one can see, there is very little nmi=1 usage, and the down-side of not using it is that on some platforms some software events can have a jiffy delay in wakeup (when arch_irq_work_raise isn't implemented). The up-side however is that we can remove the nmi parameter and save a bunch of conditionals in fast paths. Signed-off-by: Peter Zijlstra <[email protected]> Cc: Michael Cree <[email protected]> Cc: Will Deacon <[email protected]> Cc: Deng-Cheng Zhu <[email protected]> Cc: Anton Blanchard <[email protected]> Cc: Eric B Munson <[email protected]> Cc: Heiko Carstens <[email protected]> Cc: Paul Mundt <[email protected]> Cc: David S. Miller <[email protected]> Cc: Frederic Weisbecker <[email protected]> Cc: Jason Wessel <[email protected]> Cc: Don Zickus <[email protected]> Link: http://lkml.kernel.org/n/[email protected] Signed-off-by: Ingo Molnar <[email protected]> CWE ID: CWE-399
static void perf_event_comm_output(struct perf_event *event, struct perf_comm_event *comm_event) { struct perf_output_handle handle; struct perf_sample_data sample; int size = comm_event->event_id.header.size; int ret; perf_event_header__init_id(&comm_event->event_id.header, &sample, event); ret = perf_output_begin(&handle, event, comm_event->event_id.header.size, 0); if (ret) goto out; comm_event->event_id.pid = perf_event_pid(event, comm_event->task); comm_event->event_id.tid = perf_event_tid(event, comm_event->task); perf_output_put(&handle, comm_event->event_id); __output_copy(&handle, comm_event->comm, comm_event->comm_size); perf_event__output_id_sample(event, &handle, &sample); perf_output_end(&handle); out: comm_event->event_id.header.size = size; }
165,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: my_object_finalize (GObject *object) { MyObject *mobject = MY_OBJECT (object); g_free (mobject->this_is_a_string); (G_OBJECT_CLASS (my_object_parent_class)->finalize) (object); } Commit Message: CWE ID: CWE-264
my_object_finalize (GObject *object)
165,099
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: sctp_disposition_t sctp_sf_ootb(struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, const sctp_subtype_t type, void *arg, sctp_cmd_seq_t *commands) { struct sctp_chunk *chunk = arg; struct sk_buff *skb = chunk->skb; sctp_chunkhdr_t *ch; sctp_errhdr_t *err; __u8 *ch_end; int ootb_shut_ack = 0; int ootb_cookie_ack = 0; SCTP_INC_STATS(net, SCTP_MIB_OUTOFBLUES); ch = (sctp_chunkhdr_t *) chunk->chunk_hdr; do { /* Report violation if the chunk is less then minimal */ if (ntohs(ch->length) < sizeof(sctp_chunkhdr_t)) return sctp_sf_violation_chunklen(net, ep, asoc, type, arg, commands); /* Now that we know we at least have a chunk header, * do things that are type appropriate. */ if (SCTP_CID_SHUTDOWN_ACK == ch->type) ootb_shut_ack = 1; /* RFC 2960, Section 3.3.7 * Moreover, under any circumstances, an endpoint that * receives an ABORT MUST NOT respond to that ABORT by * sending an ABORT of its own. */ if (SCTP_CID_ABORT == ch->type) return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands); /* RFC 8.4, 7) If the packet contains a "Stale cookie" ERROR * or a COOKIE ACK the SCTP Packet should be silently * discarded. */ if (SCTP_CID_COOKIE_ACK == ch->type) ootb_cookie_ack = 1; if (SCTP_CID_ERROR == ch->type) { sctp_walk_errors(err, ch) { if (SCTP_ERROR_STALE_COOKIE == err->cause) { ootb_cookie_ack = 1; break; } } } /* Report violation if chunk len overflows */ ch_end = ((__u8 *)ch) + SCTP_PAD4(ntohs(ch->length)); if (ch_end > skb_tail_pointer(skb)) return sctp_sf_violation_chunklen(net, ep, asoc, type, arg, commands); ch = (sctp_chunkhdr_t *) ch_end; } while (ch_end < skb_tail_pointer(skb)); if (ootb_shut_ack) return sctp_sf_shut_8_4_5(net, ep, asoc, type, arg, commands); else if (ootb_cookie_ack) return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands); else return sctp_sf_tabort_8_4_8(net, ep, asoc, type, arg, commands); } Commit Message: sctp: validate chunk len before actually using it Andrey Konovalov reported that KASAN detected that SCTP was using a slab beyond the boundaries. It was caused because when handling out of the blue packets in function sctp_sf_ootb() it was checking the chunk len only after already processing the first chunk, validating only for the 2nd and subsequent ones. The fix is to just move the check upwards so it's also validated for the 1st chunk. Reported-by: Andrey Konovalov <[email protected]> Tested-by: Andrey Konovalov <[email protected]> Signed-off-by: Marcelo Ricardo Leitner <[email protected]> Reviewed-by: Xin Long <[email protected]> Acked-by: Neil Horman <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-125
sctp_disposition_t sctp_sf_ootb(struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, const sctp_subtype_t type, void *arg, sctp_cmd_seq_t *commands) { struct sctp_chunk *chunk = arg; struct sk_buff *skb = chunk->skb; sctp_chunkhdr_t *ch; sctp_errhdr_t *err; __u8 *ch_end; int ootb_shut_ack = 0; int ootb_cookie_ack = 0; SCTP_INC_STATS(net, SCTP_MIB_OUTOFBLUES); ch = (sctp_chunkhdr_t *) chunk->chunk_hdr; do { /* Report violation if the chunk is less then minimal */ if (ntohs(ch->length) < sizeof(sctp_chunkhdr_t)) return sctp_sf_violation_chunklen(net, ep, asoc, type, arg, commands); /* Report violation if chunk len overflows */ ch_end = ((__u8 *)ch) + SCTP_PAD4(ntohs(ch->length)); if (ch_end > skb_tail_pointer(skb)) return sctp_sf_violation_chunklen(net, ep, asoc, type, arg, commands); /* Now that we know we at least have a chunk header, * do things that are type appropriate. */ if (SCTP_CID_SHUTDOWN_ACK == ch->type) ootb_shut_ack = 1; /* RFC 2960, Section 3.3.7 * Moreover, under any circumstances, an endpoint that * receives an ABORT MUST NOT respond to that ABORT by * sending an ABORT of its own. */ if (SCTP_CID_ABORT == ch->type) return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands); /* RFC 8.4, 7) If the packet contains a "Stale cookie" ERROR * or a COOKIE ACK the SCTP Packet should be silently * discarded. */ if (SCTP_CID_COOKIE_ACK == ch->type) ootb_cookie_ack = 1; if (SCTP_CID_ERROR == ch->type) { sctp_walk_errors(err, ch) { if (SCTP_ERROR_STALE_COOKIE == err->cause) { ootb_cookie_ack = 1; break; } } } ch = (sctp_chunkhdr_t *) ch_end; } while (ch_end < skb_tail_pointer(skb)); if (ootb_shut_ack) return sctp_sf_shut_8_4_5(net, ep, asoc, type, arg, commands); else if (ootb_cookie_ack) return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands); else return sctp_sf_tabort_8_4_8(net, ep, asoc, type, arg, commands); }
166,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: bool decode(const SharedBuffer& data, bool onlySize) { m_decodingSizeOnly = onlySize; unsigned newByteCount = data.size() - m_bufferLength; unsigned readOffset = m_bufferLength - m_info.src->bytes_in_buffer; m_info.src->bytes_in_buffer += newByteCount; m_info.src->next_input_byte = (JOCTET*)(data.data()) + readOffset; if (m_bytesToSkip) skipBytes(m_bytesToSkip); m_bufferLength = data.size(); if (setjmp(m_err.setjmp_buffer)) return m_decoder->setFailed(); switch (m_state) { case JPEG_HEADER: if (jpeg_read_header(&m_info, true) == JPEG_SUSPENDED) return false; // I/O suspension. switch (m_info.jpeg_color_space) { case JCS_GRAYSCALE: case JCS_RGB: case JCS_YCbCr: m_info.out_color_space = rgbOutputColorSpace(); #if defined(TURBO_JPEG_RGB_SWIZZLE) if (m_info.saw_JFIF_marker) break; if (m_info.saw_Adobe_marker && !m_info.Adobe_transform) m_info.out_color_space = JCS_RGB; #endif break; case JCS_CMYK: case JCS_YCCK: m_info.out_color_space = JCS_CMYK; break; default: return m_decoder->setFailed(); } m_state = JPEG_START_DECOMPRESS; if (!m_decoder->setSize(m_info.image_width, m_info.image_height)) return false; m_decoder->setOrientation(readImageOrientation(info())); #if ENABLE(IMAGE_DECODER_DOWN_SAMPLING) && defined(TURBO_JPEG_RGB_SWIZZLE) if (m_decoder->willDownSample() && turboSwizzled(m_info.out_color_space)) m_info.out_color_space = JCS_RGB; #endif #if USE(QCMSLIB) if (!m_decoder->ignoresGammaAndColorProfile()) { ColorProfile colorProfile = readColorProfile(info()); createColorTransform(colorProfile, colorSpaceHasAlpha(m_info.out_color_space)); #if defined(TURBO_JPEG_RGB_SWIZZLE) if (m_transform && m_info.out_color_space == JCS_EXT_BGRA) m_info.out_color_space = JCS_EXT_RGBA; #endif } #endif m_info.buffered_image = jpeg_has_multiple_scans(&m_info); jpeg_calc_output_dimensions(&m_info); m_samples = (*m_info.mem->alloc_sarray)((j_common_ptr) &m_info, JPOOL_IMAGE, m_info.output_width * 4, 1); if (m_decodingSizeOnly) { m_bufferLength -= m_info.src->bytes_in_buffer; m_info.src->bytes_in_buffer = 0; return true; } case JPEG_START_DECOMPRESS: m_info.dct_method = dctMethod(); m_info.dither_mode = ditherMode(); m_info.do_fancy_upsampling = doFancyUpsampling(); m_info.enable_2pass_quant = false; m_info.do_block_smoothing = true; if (!jpeg_start_decompress(&m_info)) return false; // I/O suspension. m_state = (m_info.buffered_image) ? JPEG_DECOMPRESS_PROGRESSIVE : JPEG_DECOMPRESS_SEQUENTIAL; case JPEG_DECOMPRESS_SEQUENTIAL: if (m_state == JPEG_DECOMPRESS_SEQUENTIAL) { if (!m_decoder->outputScanlines()) return false; // I/O suspension. ASSERT(m_info.output_scanline == m_info.output_height); m_state = JPEG_DONE; } case JPEG_DECOMPRESS_PROGRESSIVE: if (m_state == JPEG_DECOMPRESS_PROGRESSIVE) { int status; do { status = jpeg_consume_input(&m_info); } while ((status != JPEG_SUSPENDED) && (status != JPEG_REACHED_EOI)); for (;;) { if (!m_info.output_scanline) { int scan = m_info.input_scan_number; if (!m_info.output_scan_number && (scan > 1) && (status != JPEG_REACHED_EOI)) --scan; if (!jpeg_start_output(&m_info, scan)) return false; // I/O suspension. } if (m_info.output_scanline == 0xffffff) m_info.output_scanline = 0; if (!m_decoder->outputScanlines()) { if (!m_info.output_scanline) m_info.output_scanline = 0xffffff; return false; // I/O suspension. } if (m_info.output_scanline == m_info.output_height) { if (!jpeg_finish_output(&m_info)) return false; // I/O suspension. if (jpeg_input_complete(&m_info) && (m_info.input_scan_number == m_info.output_scan_number)) break; m_info.output_scanline = 0; } } m_state = JPEG_DONE; } case JPEG_DONE: return jpeg_finish_decompress(&m_info); case JPEG_ERROR: return m_decoder->setFailed(); } return true; } Commit Message: Progressive JPEG outputScanlines() calls should handle failure outputScanlines() can fail and delete |this|, so any attempt to access members thereafter should be avoided. Copy the decoder pointer member, and use that copy to detect and handle the failure case. BUG=232763 [email protected] Review URL: https://codereview.chromium.org/14844003 git-svn-id: svn://svn.chromium.org/blink/trunk@150545 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399
bool decode(const SharedBuffer& data, bool onlySize) { m_decodingSizeOnly = onlySize; unsigned newByteCount = data.size() - m_bufferLength; unsigned readOffset = m_bufferLength - m_info.src->bytes_in_buffer; m_info.src->bytes_in_buffer += newByteCount; m_info.src->next_input_byte = (JOCTET*)(data.data()) + readOffset; if (m_bytesToSkip) skipBytes(m_bytesToSkip); m_bufferLength = data.size(); if (setjmp(m_err.setjmp_buffer)) return m_decoder->setFailed(); switch (m_state) { case JPEG_HEADER: if (jpeg_read_header(&m_info, true) == JPEG_SUSPENDED) return false; // I/O suspension. switch (m_info.jpeg_color_space) { case JCS_GRAYSCALE: case JCS_RGB: case JCS_YCbCr: m_info.out_color_space = rgbOutputColorSpace(); #if defined(TURBO_JPEG_RGB_SWIZZLE) if (m_info.saw_JFIF_marker) break; if (m_info.saw_Adobe_marker && !m_info.Adobe_transform) m_info.out_color_space = JCS_RGB; #endif break; case JCS_CMYK: case JCS_YCCK: m_info.out_color_space = JCS_CMYK; break; default: return m_decoder->setFailed(); } m_state = JPEG_START_DECOMPRESS; if (!m_decoder->setSize(m_info.image_width, m_info.image_height)) return false; m_decoder->setOrientation(readImageOrientation(info())); #if ENABLE(IMAGE_DECODER_DOWN_SAMPLING) && defined(TURBO_JPEG_RGB_SWIZZLE) if (m_decoder->willDownSample() && turboSwizzled(m_info.out_color_space)) m_info.out_color_space = JCS_RGB; #endif #if USE(QCMSLIB) if (!m_decoder->ignoresGammaAndColorProfile()) { ColorProfile colorProfile = readColorProfile(info()); createColorTransform(colorProfile, colorSpaceHasAlpha(m_info.out_color_space)); #if defined(TURBO_JPEG_RGB_SWIZZLE) if (m_transform && m_info.out_color_space == JCS_EXT_BGRA) m_info.out_color_space = JCS_EXT_RGBA; #endif } #endif m_info.buffered_image = jpeg_has_multiple_scans(&m_info); jpeg_calc_output_dimensions(&m_info); m_samples = (*m_info.mem->alloc_sarray)((j_common_ptr) &m_info, JPOOL_IMAGE, m_info.output_width * 4, 1); if (m_decodingSizeOnly) { m_bufferLength -= m_info.src->bytes_in_buffer; m_info.src->bytes_in_buffer = 0; return true; } case JPEG_START_DECOMPRESS: m_info.dct_method = dctMethod(); m_info.dither_mode = ditherMode(); m_info.do_fancy_upsampling = doFancyUpsampling(); m_info.enable_2pass_quant = false; m_info.do_block_smoothing = true; if (!jpeg_start_decompress(&m_info)) return false; // I/O suspension. m_state = (m_info.buffered_image) ? JPEG_DECOMPRESS_PROGRESSIVE : JPEG_DECOMPRESS_SEQUENTIAL; case JPEG_DECOMPRESS_SEQUENTIAL: if (m_state == JPEG_DECOMPRESS_SEQUENTIAL) { if (!m_decoder->outputScanlines()) return false; // I/O suspension. ASSERT(m_info.output_scanline == m_info.output_height); m_state = JPEG_DONE; } case JPEG_DECOMPRESS_PROGRESSIVE: if (m_state == JPEG_DECOMPRESS_PROGRESSIVE) { int status; do { status = jpeg_consume_input(&m_info); } while ((status != JPEG_SUSPENDED) && (status != JPEG_REACHED_EOI)); for (;;) { if (!m_info.output_scanline) { int scan = m_info.input_scan_number; if (!m_info.output_scan_number && (scan > 1) && (status != JPEG_REACHED_EOI)) --scan; if (!jpeg_start_output(&m_info, scan)) return false; // I/O suspension. } if (m_info.output_scanline == 0xffffff) m_info.output_scanline = 0; // If outputScanlines() fails, it deletes |this|. Therefore, // copy the decoder pointer and use it to check for failure // to avoid member access in the failure case. JPEGImageDecoder* decoder = m_decoder; if (!decoder->outputScanlines()) { if (decoder->failed()) // Careful; |this| is deleted. return false; if (!m_info.output_scanline) m_info.output_scanline = 0xffffff; return false; // I/O suspension. } if (m_info.output_scanline == m_info.output_height) { if (!jpeg_finish_output(&m_info)) return false; // I/O suspension. if (jpeg_input_complete(&m_info) && (m_info.input_scan_number == m_info.output_scan_number)) break; m_info.output_scanline = 0; } } m_state = JPEG_DONE; } case JPEG_DONE: return jpeg_finish_decompress(&m_info); case JPEG_ERROR: return m_decoder->setFailed(); } return true; }
171,590
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static BOOL region16_simplify_bands(REGION16* region) { /** Simplify consecutive bands that touch and have the same items * * ==================== ==================== * | 1 | | 2 | | | | | * ==================== | | | | * | 1 | | 2 | ====> | 1 | | 2 | * ==================== | | | | * | 1 | | 2 | | | | | * ==================== ==================== * */ RECTANGLE_16* band1, *band2, *endPtr, *endBand, *tmp; int nbRects, finalNbRects; int bandItems, toMove; finalNbRects = nbRects = region16_n_rects(region); if (nbRects < 2) return TRUE; band1 = region16_rects_noconst(region); endPtr = band1 + nbRects; do { band2 = next_band(band1, endPtr, &bandItems); if (band2 == endPtr) break; if ((band1->bottom == band2->top) && band_match(band1, band2, endPtr)) { /* adjust the bottom of band1 items */ tmp = band1; while (tmp < band2) { tmp->bottom = band2->bottom; tmp++; } /* override band2, we don't move band1 pointer as the band after band2 * may be merged too */ endBand = band2 + bandItems; toMove = (endPtr - endBand) * sizeof(RECTANGLE_16); if (toMove) MoveMemory(band2, endBand, toMove); finalNbRects -= bandItems; endPtr -= bandItems; } else { band1 = band2; } } while (TRUE); if (finalNbRects != nbRects) { int allocSize = sizeof(REGION16_DATA) + (finalNbRects * sizeof(RECTANGLE_16)); region->data = realloc(region->data, allocSize); if (!region->data) { region->data = &empty_region; return FALSE; } region->data->nbRects = finalNbRects; region->data->size = allocSize; } return TRUE; } Commit Message: Fixed #5645: realloc return handling CWE ID: CWE-772
static BOOL region16_simplify_bands(REGION16* region) { /** Simplify consecutive bands that touch and have the same items * * ==================== ==================== * | 1 | | 2 | | | | | * ==================== | | | | * | 1 | | 2 | ====> | 1 | | 2 | * ==================== | | | | * | 1 | | 2 | | | | | * ==================== ==================== * */ RECTANGLE_16* band1, *band2, *endPtr, *endBand, *tmp; int nbRects, finalNbRects; int bandItems, toMove; finalNbRects = nbRects = region16_n_rects(region); if (nbRects < 2) return TRUE; band1 = region16_rects_noconst(region); endPtr = band1 + nbRects; do { band2 = next_band(band1, endPtr, &bandItems); if (band2 == endPtr) break; if ((band1->bottom == band2->top) && band_match(band1, band2, endPtr)) { /* adjust the bottom of band1 items */ tmp = band1; while (tmp < band2) { tmp->bottom = band2->bottom; tmp++; } /* override band2, we don't move band1 pointer as the band after band2 * may be merged too */ endBand = band2 + bandItems; toMove = (endPtr - endBand) * sizeof(RECTANGLE_16); if (toMove) MoveMemory(band2, endBand, toMove); finalNbRects -= bandItems; endPtr -= bandItems; } else { band1 = band2; } } while (TRUE); if (finalNbRects != nbRects) { REGION16_DATA* data; size_t allocSize = sizeof(REGION16_DATA) + (finalNbRects * sizeof(RECTANGLE_16)); data = realloc(region->data, allocSize); if (!data) free(region->data); region->data = data; if (!region->data) { region->data = &empty_region; return FALSE; } region->data->nbRects = finalNbRects; region->data->size = allocSize; } return TRUE; }
169,497
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void xen_netbk_fill_frags(struct xen_netbk *netbk, struct sk_buff *skb) { struct skb_shared_info *shinfo = skb_shinfo(skb); int nr_frags = shinfo->nr_frags; int i; for (i = 0; i < nr_frags; i++) { skb_frag_t *frag = shinfo->frags + i; struct xen_netif_tx_request *txp; struct page *page; u16 pending_idx; pending_idx = frag_get_pending_idx(frag); txp = &netbk->pending_tx_info[pending_idx].req; page = virt_to_page(idx_to_kaddr(netbk, pending_idx)); __skb_fill_page_desc(skb, i, page, txp->offset, txp->size); skb->len += txp->size; skb->data_len += txp->size; skb->truesize += txp->size; /* Take an extra reference to offset xen_netbk_idx_release */ get_page(netbk->mmap_pages[pending_idx]); xen_netbk_idx_release(netbk, pending_idx); } } Commit Message: xen/netback: don't leak pages on failure in xen_netbk_tx_check_gop. Signed-off-by: Matthew Daley <[email protected]> Reviewed-by: Konrad Rzeszutek Wilk <[email protected]> Acked-by: Ian Campbell <[email protected]> Acked-by: Jan Beulich <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-399
static void xen_netbk_fill_frags(struct xen_netbk *netbk, struct sk_buff *skb) { struct skb_shared_info *shinfo = skb_shinfo(skb); int nr_frags = shinfo->nr_frags; int i; for (i = 0; i < nr_frags; i++) { skb_frag_t *frag = shinfo->frags + i; struct xen_netif_tx_request *txp; struct page *page; u16 pending_idx; pending_idx = frag_get_pending_idx(frag); txp = &netbk->pending_tx_info[pending_idx].req; page = virt_to_page(idx_to_kaddr(netbk, pending_idx)); __skb_fill_page_desc(skb, i, page, txp->offset, txp->size); skb->len += txp->size; skb->data_len += txp->size; skb->truesize += txp->size; /* Take an extra reference to offset xen_netbk_idx_release */ get_page(netbk->mmap_pages[pending_idx]); xen_netbk_idx_release(netbk, pending_idx, XEN_NETIF_RSP_OKAY); } }
166,167
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 svc_can_register(const uint16_t *name, size_t name_len, pid_t spid, uid_t uid) { const char *perm = "add"; return check_mac_perms_from_lookup(spid, uid, perm, str8(name, name_len)) ? 1 : 0; } Commit Message: ServiceManager: Restore basic uid check Prevent apps from registering services without relying on selinux checks. Bug: 29431260 Change-Id: I38c6e8bc7f7cba1cbd3568e8fed1ae7ac2054a9b (cherry picked from commit 2b74d2c1d2a2c1bb6e9c420f7e9b339ba2a95179) CWE ID: CWE-264
static int svc_can_register(const uint16_t *name, size_t name_len, pid_t spid, uid_t uid) { const char *perm = "add"; if (uid >= AID_APP) { return 0; /* Don't allow apps to register services */ } return check_mac_perms_from_lookup(spid, uid, perm, str8(name, name_len)) ? 1 : 0; }
174,149
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool PrintWebViewHelper::CheckForCancel() { bool cancel = false; Send(new PrintHostMsg_CheckForCancel( routing_id(), print_pages_params_->params.preview_ui_addr, print_pages_params_->params.preview_request_id, &cancel)); if (cancel) notify_browser_of_print_failure_ = false; return cancel; } Commit Message: Print preview: Use an ID instead of memory pointer string in WebUI. BUG=144051 Review URL: https://chromiumcodereview.appspot.com/10870003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@153342 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-200
bool PrintWebViewHelper::CheckForCancel() { const PrintMsg_Print_Params& print_params = print_pages_params_->params; bool cancel = false; Send(new PrintHostMsg_CheckForCancel(routing_id(), print_params.preview_ui_id, print_params.preview_request_id, &cancel)); if (cancel) notify_browser_of_print_failure_ = false; return cancel; }
170,856
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: OMX_ERRORTYPE SoftAMRWBEncoder::internalSetParameter( OMX_INDEXTYPE index, const OMX_PTR params) { switch (index) { case OMX_IndexParamStandardComponentRole: { const OMX_PARAM_COMPONENTROLETYPE *roleParams = (const OMX_PARAM_COMPONENTROLETYPE *)params; if (strncmp((const char *)roleParams->cRole, "audio_encoder.amrwb", OMX_MAX_STRINGNAME_SIZE - 1)) { return OMX_ErrorUndefined; } return OMX_ErrorNone; } case OMX_IndexParamAudioPortFormat: { const OMX_AUDIO_PARAM_PORTFORMATTYPE *formatParams = (const OMX_AUDIO_PARAM_PORTFORMATTYPE *)params; if (formatParams->nPortIndex > 1) { return OMX_ErrorUndefined; } if (formatParams->nIndex > 0) { return OMX_ErrorNoMore; } if ((formatParams->nPortIndex == 0 && formatParams->eEncoding != OMX_AUDIO_CodingPCM) || (formatParams->nPortIndex == 1 && formatParams->eEncoding != OMX_AUDIO_CodingAMR)) { return OMX_ErrorUndefined; } return OMX_ErrorNone; } case OMX_IndexParamAudioAmr: { OMX_AUDIO_PARAM_AMRTYPE *amrParams = (OMX_AUDIO_PARAM_AMRTYPE *)params; if (amrParams->nPortIndex != 1) { return OMX_ErrorUndefined; } if (amrParams->nChannels != 1 || amrParams->eAMRDTXMode != OMX_AUDIO_AMRDTXModeOff || amrParams->eAMRFrameFormat != OMX_AUDIO_AMRFrameFormatFSF || amrParams->eAMRBandMode < OMX_AUDIO_AMRBandModeWB0 || amrParams->eAMRBandMode > OMX_AUDIO_AMRBandModeWB8) { return OMX_ErrorUndefined; } mBitRate = amrParams->nBitRate; mMode = (VOAMRWBMODE)( amrParams->eAMRBandMode - OMX_AUDIO_AMRBandModeWB0); amrParams->eAMRDTXMode = OMX_AUDIO_AMRDTXModeOff; amrParams->eAMRFrameFormat = OMX_AUDIO_AMRFrameFormatFSF; if (VO_ERR_NONE != mApiHandle->SetParam( mEncoderHandle, VO_PID_AMRWB_MODE, &mMode)) { ALOGE("Failed to set AMRWB encoder mode to %d", mMode); return OMX_ErrorUndefined; } return OMX_ErrorNone; } case OMX_IndexParamAudioPcm: { OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams = (OMX_AUDIO_PARAM_PCMMODETYPE *)params; if (pcmParams->nPortIndex != 0) { return OMX_ErrorUndefined; } if (pcmParams->nChannels != 1 || pcmParams->nSamplingRate != (OMX_U32)kSampleRate) { return OMX_ErrorUndefined; } return OMX_ErrorNone; } default: return SimpleSoftOMXComponent::internalSetParameter(index, params); } } Commit Message: DO NOT MERGE Verify OMX buffer sizes prior to access Bug: 27207275 Change-Id: I4412825d1ee233d993af0a67708bea54304ff62d CWE ID: CWE-119
OMX_ERRORTYPE SoftAMRWBEncoder::internalSetParameter( OMX_INDEXTYPE index, const OMX_PTR params) { switch (index) { case OMX_IndexParamStandardComponentRole: { const OMX_PARAM_COMPONENTROLETYPE *roleParams = (const OMX_PARAM_COMPONENTROLETYPE *)params; if (!isValidOMXParam(roleParams)) { return OMX_ErrorBadParameter; } if (strncmp((const char *)roleParams->cRole, "audio_encoder.amrwb", OMX_MAX_STRINGNAME_SIZE - 1)) { return OMX_ErrorUndefined; } return OMX_ErrorNone; } case OMX_IndexParamAudioPortFormat: { const OMX_AUDIO_PARAM_PORTFORMATTYPE *formatParams = (const OMX_AUDIO_PARAM_PORTFORMATTYPE *)params; if (!isValidOMXParam(formatParams)) { return OMX_ErrorBadParameter; } if (formatParams->nPortIndex > 1) { return OMX_ErrorUndefined; } if (formatParams->nIndex > 0) { return OMX_ErrorNoMore; } if ((formatParams->nPortIndex == 0 && formatParams->eEncoding != OMX_AUDIO_CodingPCM) || (formatParams->nPortIndex == 1 && formatParams->eEncoding != OMX_AUDIO_CodingAMR)) { return OMX_ErrorUndefined; } return OMX_ErrorNone; } case OMX_IndexParamAudioAmr: { OMX_AUDIO_PARAM_AMRTYPE *amrParams = (OMX_AUDIO_PARAM_AMRTYPE *)params; if (!isValidOMXParam(amrParams)) { return OMX_ErrorBadParameter; } if (amrParams->nPortIndex != 1) { return OMX_ErrorUndefined; } if (amrParams->nChannels != 1 || amrParams->eAMRDTXMode != OMX_AUDIO_AMRDTXModeOff || amrParams->eAMRFrameFormat != OMX_AUDIO_AMRFrameFormatFSF || amrParams->eAMRBandMode < OMX_AUDIO_AMRBandModeWB0 || amrParams->eAMRBandMode > OMX_AUDIO_AMRBandModeWB8) { return OMX_ErrorUndefined; } mBitRate = amrParams->nBitRate; mMode = (VOAMRWBMODE)( amrParams->eAMRBandMode - OMX_AUDIO_AMRBandModeWB0); amrParams->eAMRDTXMode = OMX_AUDIO_AMRDTXModeOff; amrParams->eAMRFrameFormat = OMX_AUDIO_AMRFrameFormatFSF; if (VO_ERR_NONE != mApiHandle->SetParam( mEncoderHandle, VO_PID_AMRWB_MODE, &mMode)) { ALOGE("Failed to set AMRWB encoder mode to %d", mMode); return OMX_ErrorUndefined; } return OMX_ErrorNone; } case OMX_IndexParamAudioPcm: { OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams = (OMX_AUDIO_PARAM_PCMMODETYPE *)params; if (!isValidOMXParam(pcmParams)) { return OMX_ErrorBadParameter; } if (pcmParams->nPortIndex != 0) { return OMX_ErrorUndefined; } if (pcmParams->nChannels != 1 || pcmParams->nSamplingRate != (OMX_U32)kSampleRate) { return OMX_ErrorUndefined; } return OMX_ErrorNone; } default: return SimpleSoftOMXComponent::internalSetParameter(index, params); } }
174,197
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 OnGetDevicesOnServiceThread( const std::vector<UsbDeviceFilter>& filters, const base::Callback<void(mojo::Array<DeviceInfoPtr>)>& callback, scoped_refptr<base::TaskRunner> callback_task_runner, const std::vector<scoped_refptr<UsbDevice>>& devices) { mojo::Array<DeviceInfoPtr> mojo_devices(0); for (size_t i = 0; i < devices.size(); ++i) { if (UsbDeviceFilter::MatchesAny(devices[i], filters)) mojo_devices.push_back(DeviceInfo::From(*devices[i])); } callback_task_runner->PostTask( FROM_HERE, base::Bind(callback, base::Passed(&mojo_devices))); } Commit Message: Connect WebUSB client interface to the devices app This provides a basic WebUSB client interface in content/renderer. Most of the interface is unimplemented, but this CL hooks up navigator.usb.getDevices() to the browser's Mojo devices app to enumerate available USB devices. BUG=492204 Review URL: https://codereview.chromium.org/1293253002 Cr-Commit-Position: refs/heads/master@{#344881} CWE ID: CWE-399
void OnGetDevicesOnServiceThread( const std::vector<UsbDeviceFilter>& filters, const base::Callback<void(mojo::Array<DeviceInfoPtr>)>& callback, scoped_refptr<base::TaskRunner> callback_task_runner, const std::vector<scoped_refptr<UsbDevice>>& devices) { mojo::Array<DeviceInfoPtr> mojo_devices(0); for (size_t i = 0; i < devices.size(); ++i) { if (UsbDeviceFilter::MatchesAny(devices[i], filters) || filters.empty()) mojo_devices.push_back(DeviceInfo::From(*devices[i])); } callback_task_runner->PostTask( FROM_HERE, base::Bind(callback, base::Passed(&mojo_devices))); }
171,698
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 key_verify(pam_handle_t *pamh, int flags, PKCS11_KEY *authkey) { int ok = 0; unsigned char challenge[30]; unsigned char signature[256]; unsigned int siglen = sizeof signature; const EVP_MD *md = EVP_sha1(); EVP_MD_CTX *md_ctx = EVP_MD_CTX_new(); EVP_PKEY *privkey = PKCS11_get_private_key(authkey); EVP_PKEY *pubkey = PKCS11_get_public_key(authkey); /* Verify a SHA-1 hash of random data, signed by the key. * * Note that this will not work keys that aren't eligible for signing. * Unfortunately, libp11 currently has no way of checking * C_GetAttributeValue(CKA_SIGN), see * https://github.com/OpenSC/libp11/issues/219. Since we don't want to * implement try and error, we live with this limitation */ if (1 != randomize(pamh, challenge, sizeof challenge)) { goto err; } if (NULL == pubkey || NULL == privkey || NULL == md_ctx || NULL == md || !EVP_SignInit(md_ctx, md) || !EVP_SignUpdate(md_ctx, challenge, sizeof challenge) || !EVP_SignFinal(md_ctx, signature, &siglen, privkey) || !EVP_MD_CTX_reset(md_ctx) || !EVP_VerifyInit(md_ctx, md) || !EVP_VerifyUpdate(md_ctx, challenge, sizeof challenge) || 1 != EVP_VerifyFinal(md_ctx, signature, siglen, pubkey)) { pam_syslog(pamh, LOG_DEBUG, "Error verifying key: %s\n", ERR_reason_error_string(ERR_get_error())); prompt(flags, pamh, PAM_ERROR_MSG, NULL, _("Error verifying key")); goto err; } ok = 1; err: if (NULL != pubkey) EVP_PKEY_free(pubkey); if (NULL != privkey) EVP_PKEY_free(privkey); if (NULL != md_ctx) { EVP_MD_CTX_free(md_ctx); } return ok; } Commit Message: Use EVP_PKEY_size() to allocate correct size of signature buffer. (#18) Do not use fixed buffer size for signature, EVP_SignFinal() requires buffer for signature at least EVP_PKEY_size(pkey) bytes in size. Fixes crash when using 4K RSA signatures (https://github.com/OpenSC/pam_p11/issues/16, https://github.com/OpenSC/pam_p11/issues/15) CWE ID: CWE-119
static int key_verify(pam_handle_t *pamh, int flags, PKCS11_KEY *authkey) { int ok = 0; unsigned char challenge[30]; unsigned char *signature = NULL; unsigned int siglen; const EVP_MD *md = EVP_sha1(); EVP_MD_CTX *md_ctx = EVP_MD_CTX_new(); EVP_PKEY *privkey = PKCS11_get_private_key(authkey); EVP_PKEY *pubkey = PKCS11_get_public_key(authkey); if (NULL == privkey) goto err; siglen = EVP_PKEY_size(privkey); if (siglen <= 0) goto err; signature = malloc(siglen); if (NULL == signature) goto err; /* Verify a SHA-1 hash of random data, signed by the key. * * Note that this will not work keys that aren't eligible for signing. * Unfortunately, libp11 currently has no way of checking * C_GetAttributeValue(CKA_SIGN), see * https://github.com/OpenSC/libp11/issues/219. Since we don't want to * implement try and error, we live with this limitation */ if (1 != randomize(pamh, challenge, sizeof challenge)) { goto err; } if (NULL == pubkey || NULL == privkey || NULL == md_ctx || NULL == md || !EVP_SignInit(md_ctx, md) || !EVP_SignUpdate(md_ctx, challenge, sizeof challenge) || !EVP_SignFinal(md_ctx, signature, &siglen, privkey) || !EVP_MD_CTX_reset(md_ctx) || !EVP_VerifyInit(md_ctx, md) || !EVP_VerifyUpdate(md_ctx, challenge, sizeof challenge) || 1 != EVP_VerifyFinal(md_ctx, signature, siglen, pubkey)) { pam_syslog(pamh, LOG_DEBUG, "Error verifying key: %s\n", ERR_reason_error_string(ERR_get_error())); prompt(flags, pamh, PAM_ERROR_MSG, NULL, _("Error verifying key")); goto err; } ok = 1; err: free(signature); if (NULL != pubkey) EVP_PKEY_free(pubkey); if (NULL != privkey) EVP_PKEY_free(privkey); if (NULL != md_ctx) { EVP_MD_CTX_free(md_ctx); } return ok; }
169,513
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 vmx_set_constant_host_state(struct vcpu_vmx *vmx) { u32 low32, high32; unsigned long tmpl; struct desc_ptr dt; vmcs_writel(HOST_CR0, read_cr0() & ~X86_CR0_TS); /* 22.2.3 */ vmcs_writel(HOST_CR4, read_cr4()); /* 22.2.3, 22.2.5 */ vmcs_writel(HOST_CR3, read_cr3()); /* 22.2.3 FIXME: shadow tables */ vmcs_write16(HOST_CS_SELECTOR, __KERNEL_CS); /* 22.2.4 */ #ifdef CONFIG_X86_64 /* * Load null selectors, so we can avoid reloading them in * __vmx_load_host_state(), in case userspace uses the null selectors * too (the expected case). */ vmcs_write16(HOST_DS_SELECTOR, 0); vmcs_write16(HOST_ES_SELECTOR, 0); #else vmcs_write16(HOST_DS_SELECTOR, __KERNEL_DS); /* 22.2.4 */ vmcs_write16(HOST_ES_SELECTOR, __KERNEL_DS); /* 22.2.4 */ #endif vmcs_write16(HOST_SS_SELECTOR, __KERNEL_DS); /* 22.2.4 */ vmcs_write16(HOST_TR_SELECTOR, GDT_ENTRY_TSS*8); /* 22.2.4 */ native_store_idt(&dt); vmcs_writel(HOST_IDTR_BASE, dt.address); /* 22.2.4 */ vmx->host_idt_base = dt.address; vmcs_writel(HOST_RIP, vmx_return); /* 22.2.5 */ rdmsr(MSR_IA32_SYSENTER_CS, low32, high32); vmcs_write32(HOST_IA32_SYSENTER_CS, low32); rdmsrl(MSR_IA32_SYSENTER_EIP, tmpl); vmcs_writel(HOST_IA32_SYSENTER_EIP, tmpl); /* 22.2.3 */ if (vmcs_config.vmexit_ctrl & VM_EXIT_LOAD_IA32_PAT) { rdmsr(MSR_IA32_CR_PAT, low32, high32); vmcs_write64(HOST_IA32_PAT, low32 | ((u64) high32 << 32)); } } Commit Message: x86,kvm,vmx: Preserve CR4 across VM entry CR4 isn't constant; at least the TSD and PCE bits can vary. TBH, treating CR0 and CR3 as constant scares me a bit, too, but it looks like it's correct. This adds a branch and a read from cr4 to each vm entry. Because it is extremely likely that consecutive entries into the same vcpu will have the same host cr4 value, this fixes up the vmcs instead of restoring cr4 after the fact. A subsequent patch will add a kernel-wide cr4 shadow, reducing the overhead in the common case to just two memory reads and a branch. Signed-off-by: Andy Lutomirski <[email protected]> Acked-by: Paolo Bonzini <[email protected]> Cc: [email protected] Cc: Petr Matousek <[email protected]> Cc: Gleb Natapov <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-399
static void vmx_set_constant_host_state(struct vcpu_vmx *vmx) { u32 low32, high32; unsigned long tmpl; struct desc_ptr dt; unsigned long cr4; vmcs_writel(HOST_CR0, read_cr0() & ~X86_CR0_TS); /* 22.2.3 */ vmcs_writel(HOST_CR3, read_cr3()); /* 22.2.3 FIXME: shadow tables */ /* Save the most likely value for this task's CR4 in the VMCS. */ cr4 = read_cr4(); vmcs_writel(HOST_CR4, cr4); /* 22.2.3, 22.2.5 */ vmx->host_state.vmcs_host_cr4 = cr4; vmcs_write16(HOST_CS_SELECTOR, __KERNEL_CS); /* 22.2.4 */ #ifdef CONFIG_X86_64 /* * Load null selectors, so we can avoid reloading them in * __vmx_load_host_state(), in case userspace uses the null selectors * too (the expected case). */ vmcs_write16(HOST_DS_SELECTOR, 0); vmcs_write16(HOST_ES_SELECTOR, 0); #else vmcs_write16(HOST_DS_SELECTOR, __KERNEL_DS); /* 22.2.4 */ vmcs_write16(HOST_ES_SELECTOR, __KERNEL_DS); /* 22.2.4 */ #endif vmcs_write16(HOST_SS_SELECTOR, __KERNEL_DS); /* 22.2.4 */ vmcs_write16(HOST_TR_SELECTOR, GDT_ENTRY_TSS*8); /* 22.2.4 */ native_store_idt(&dt); vmcs_writel(HOST_IDTR_BASE, dt.address); /* 22.2.4 */ vmx->host_idt_base = dt.address; vmcs_writel(HOST_RIP, vmx_return); /* 22.2.5 */ rdmsr(MSR_IA32_SYSENTER_CS, low32, high32); vmcs_write32(HOST_IA32_SYSENTER_CS, low32); rdmsrl(MSR_IA32_SYSENTER_EIP, tmpl); vmcs_writel(HOST_IA32_SYSENTER_EIP, tmpl); /* 22.2.3 */ if (vmcs_config.vmexit_ctrl & VM_EXIT_LOAD_IA32_PAT) { rdmsr(MSR_IA32_CR_PAT, low32, high32); vmcs_write64(HOST_IA32_PAT, low32 | ((u64) high32 << 32)); } }
166,328
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static Image *ReadVIFFImage(const ImageInfo *image_info, ExceptionInfo *exception) { #define VFF_CM_genericRGB 15 #define VFF_CM_ntscRGB 1 #define VFF_CM_NONE 0 #define VFF_DEP_DECORDER 0x4 #define VFF_DEP_NSORDER 0x8 #define VFF_DES_RAW 0 #define VFF_LOC_IMPLICIT 1 #define VFF_MAPTYP_NONE 0 #define VFF_MAPTYP_1_BYTE 1 #define VFF_MAPTYP_2_BYTE 2 #define VFF_MAPTYP_4_BYTE 4 #define VFF_MAPTYP_FLOAT 5 #define VFF_MAPTYP_DOUBLE 7 #define VFF_MS_NONE 0 #define VFF_MS_ONEPERBAND 1 #define VFF_MS_SHARED 3 #define VFF_TYP_BIT 0 #define VFF_TYP_1_BYTE 1 #define VFF_TYP_2_BYTE 2 #define VFF_TYP_4_BYTE 4 #define VFF_TYP_FLOAT 5 #define VFF_TYP_DOUBLE 9 typedef struct _ViffInfo { unsigned char identifier, file_type, release, version, machine_dependency, reserve[3]; char comment[512]; unsigned int rows, columns, subrows; int x_offset, y_offset; float x_bits_per_pixel, y_bits_per_pixel; unsigned int location_type, location_dimension, number_of_images, number_data_bands, data_storage_type, data_encode_scheme, map_scheme, map_storage_type, map_rows, map_columns, map_subrows, map_enable, maps_per_cycle, color_space_model; } ViffInfo; double min_value, scale_factor, value; Image *image; int bit; MagickBooleanType status; MagickSizeType number_pixels; register IndexPacket *indexes; register ssize_t x; register PixelPacket *q; register ssize_t i; register unsigned char *p; size_t bytes_per_pixel, lsb_first, max_packets, quantum; ssize_t count, y; unsigned char *pixels; ViffInfo viff_info; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read VIFF header (1024 bytes). */ count=ReadBlob(image,1,&viff_info.identifier); do { /* Verify VIFF identifier. */ if ((count == 0) || ((unsigned char) viff_info.identifier != 0xab)) ThrowReaderException(CorruptImageError,"NotAVIFFImage"); /* Initialize VIFF image. */ (void) ReadBlob(image,sizeof(viff_info.file_type),&viff_info.file_type); (void) ReadBlob(image,sizeof(viff_info.release),&viff_info.release); (void) ReadBlob(image,sizeof(viff_info.version),&viff_info.version); (void) ReadBlob(image,sizeof(viff_info.machine_dependency), &viff_info.machine_dependency); (void) ReadBlob(image,sizeof(viff_info.reserve),viff_info.reserve); count=ReadBlob(image,512,(unsigned char *) viff_info.comment); viff_info.comment[511]='\0'; if (strlen(viff_info.comment) > 4) (void) SetImageProperty(image,"comment",viff_info.comment); if ((viff_info.machine_dependency == VFF_DEP_DECORDER) || (viff_info.machine_dependency == VFF_DEP_NSORDER)) image->endian=LSBEndian; else image->endian=MSBEndian; viff_info.rows=ReadBlobLong(image); viff_info.columns=ReadBlobLong(image); viff_info.subrows=ReadBlobLong(image); viff_info.x_offset=(int) ReadBlobLong(image); viff_info.y_offset=(int) ReadBlobLong(image); viff_info.x_bits_per_pixel=(float) ReadBlobLong(image); viff_info.y_bits_per_pixel=(float) ReadBlobLong(image); viff_info.location_type=ReadBlobLong(image); viff_info.location_dimension=ReadBlobLong(image); viff_info.number_of_images=ReadBlobLong(image); viff_info.number_data_bands=ReadBlobLong(image); viff_info.data_storage_type=ReadBlobLong(image); viff_info.data_encode_scheme=ReadBlobLong(image); viff_info.map_scheme=ReadBlobLong(image); viff_info.map_storage_type=ReadBlobLong(image); viff_info.map_rows=ReadBlobLong(image); viff_info.map_columns=ReadBlobLong(image); viff_info.map_subrows=ReadBlobLong(image); viff_info.map_enable=ReadBlobLong(image); viff_info.maps_per_cycle=ReadBlobLong(image); viff_info.color_space_model=ReadBlobLong(image); for (i=0; i < 420; i++) (void) ReadBlobByte(image); image->columns=viff_info.rows; image->rows=viff_info.columns; image->depth=viff_info.x_bits_per_pixel <= 8 ? 8UL : MAGICKCORE_QUANTUM_DEPTH; /* Verify that we can read this VIFF image. */ number_pixels=(MagickSizeType) viff_info.columns*viff_info.rows; if (number_pixels != (size_t) number_pixels) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); if (number_pixels == 0) ThrowReaderException(CoderError,"ImageColumnOrRowSizeIsNotSupported"); if ((viff_info.number_data_bands < 1) || (viff_info.number_data_bands > 4)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if ((viff_info.data_storage_type != VFF_TYP_BIT) && (viff_info.data_storage_type != VFF_TYP_1_BYTE) && (viff_info.data_storage_type != VFF_TYP_2_BYTE) && (viff_info.data_storage_type != VFF_TYP_4_BYTE) && (viff_info.data_storage_type != VFF_TYP_FLOAT) && (viff_info.data_storage_type != VFF_TYP_DOUBLE)) ThrowReaderException(CoderError,"DataStorageTypeIsNotSupported"); if (viff_info.data_encode_scheme != VFF_DES_RAW) ThrowReaderException(CoderError,"DataEncodingSchemeIsNotSupported"); if ((viff_info.map_storage_type != VFF_MAPTYP_NONE) && (viff_info.map_storage_type != VFF_MAPTYP_1_BYTE) && (viff_info.map_storage_type != VFF_MAPTYP_2_BYTE) && (viff_info.map_storage_type != VFF_MAPTYP_4_BYTE) && (viff_info.map_storage_type != VFF_MAPTYP_FLOAT) && (viff_info.map_storage_type != VFF_MAPTYP_DOUBLE)) ThrowReaderException(CoderError,"MapStorageTypeIsNotSupported"); if ((viff_info.color_space_model != VFF_CM_NONE) && (viff_info.color_space_model != VFF_CM_ntscRGB) && (viff_info.color_space_model != VFF_CM_genericRGB)) ThrowReaderException(CoderError,"ColorspaceModelIsNotSupported"); if (viff_info.location_type != VFF_LOC_IMPLICIT) ThrowReaderException(CoderError,"LocationTypeIsNotSupported"); if (viff_info.number_of_images != 1) ThrowReaderException(CoderError,"NumberOfImagesIsNotSupported"); if (viff_info.map_rows == 0) viff_info.map_scheme=VFF_MS_NONE; switch ((int) viff_info.map_scheme) { case VFF_MS_NONE: { if (viff_info.number_data_bands < 3) { /* Create linear color ramp. */ if (viff_info.data_storage_type == VFF_TYP_BIT) image->colors=2; else if (viff_info.data_storage_type == VFF_MAPTYP_1_BYTE) image->colors=256UL; else image->colors=image->depth <= 8 ? 256UL : 65536UL; if (AcquireImageColormap(image,image->colors) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } break; } case VFF_MS_ONEPERBAND: case VFF_MS_SHARED: { unsigned char *viff_colormap; /* Allocate VIFF colormap. */ switch ((int) viff_info.map_storage_type) { case VFF_MAPTYP_1_BYTE: bytes_per_pixel=1; break; case VFF_MAPTYP_2_BYTE: bytes_per_pixel=2; break; case VFF_MAPTYP_4_BYTE: bytes_per_pixel=4; break; case VFF_MAPTYP_FLOAT: bytes_per_pixel=4; break; case VFF_MAPTYP_DOUBLE: bytes_per_pixel=8; break; default: bytes_per_pixel=1; break; } image->colors=viff_info.map_columns; if (AcquireImageColormap(image,image->colors) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); viff_colormap=(unsigned char *) AcquireQuantumMemory(image->colors, viff_info.map_rows*bytes_per_pixel*sizeof(*viff_colormap)); if (viff_colormap == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); /* Read VIFF raster colormap. */ count=ReadBlob(image,bytes_per_pixel*image->colors*viff_info.map_rows, viff_colormap); lsb_first=1; if (*(char *) &lsb_first && ((viff_info.machine_dependency != VFF_DEP_DECORDER) && (viff_info.machine_dependency != VFF_DEP_NSORDER))) switch ((int) viff_info.map_storage_type) { case VFF_MAPTYP_2_BYTE: { MSBOrderShort(viff_colormap,(bytes_per_pixel*image->colors* viff_info.map_rows)); break; } case VFF_MAPTYP_4_BYTE: case VFF_MAPTYP_FLOAT: { MSBOrderLong(viff_colormap,(bytes_per_pixel*image->colors* viff_info.map_rows)); break; } default: break; } for (i=0; i < (ssize_t) (viff_info.map_rows*image->colors); i++) { switch ((int) viff_info.map_storage_type) { case VFF_MAPTYP_2_BYTE: value=1.0*((short *) viff_colormap)[i]; break; case VFF_MAPTYP_4_BYTE: value=1.0*((int *) viff_colormap)[i]; break; case VFF_MAPTYP_FLOAT: value=((float *) viff_colormap)[i]; break; case VFF_MAPTYP_DOUBLE: value=((double *) viff_colormap)[i]; break; default: value=1.0*viff_colormap[i]; break; } if (i < (ssize_t) image->colors) { image->colormap[i].red=ScaleCharToQuantum((unsigned char) value); image->colormap[i].green=ScaleCharToQuantum((unsigned char) value); image->colormap[i].blue=ScaleCharToQuantum((unsigned char) value); } else if (i < (ssize_t) (2*image->colors)) image->colormap[i % image->colors].green=ScaleCharToQuantum( (unsigned char) value); else if (i < (ssize_t) (3*image->colors)) image->colormap[i % image->colors].blue=ScaleCharToQuantum( (unsigned char) value); } viff_colormap=(unsigned char *) RelinquishMagickMemory(viff_colormap); break; } default: ThrowReaderException(CoderError,"ColormapTypeNotSupported"); } /* Initialize image structure. */ image->matte=viff_info.number_data_bands == 4 ? MagickTrue : MagickFalse; image->storage_class= (viff_info.number_data_bands < 3 ? PseudoClass : DirectClass); image->columns=viff_info.rows; image->rows=viff_info.columns; if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; /* Allocate VIFF pixels. */ switch ((int) viff_info.data_storage_type) { case VFF_TYP_2_BYTE: bytes_per_pixel=2; break; case VFF_TYP_4_BYTE: bytes_per_pixel=4; break; case VFF_TYP_FLOAT: bytes_per_pixel=4; break; case VFF_TYP_DOUBLE: bytes_per_pixel=8; break; default: bytes_per_pixel=1; break; } if (viff_info.data_storage_type == VFF_TYP_BIT) max_packets=((image->columns+7UL) >> 3UL)*image->rows; else max_packets=(size_t) (number_pixels*viff_info.number_data_bands); pixels=(unsigned char *) AcquireQuantumMemory(max_packets, bytes_per_pixel*sizeof(*pixels)); if (pixels == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=ReadBlob(image,bytes_per_pixel*max_packets,pixels); lsb_first=1; if (*(char *) &lsb_first && ((viff_info.machine_dependency != VFF_DEP_DECORDER) && (viff_info.machine_dependency != VFF_DEP_NSORDER))) switch ((int) viff_info.data_storage_type) { case VFF_TYP_2_BYTE: { MSBOrderShort(pixels,bytes_per_pixel*max_packets); break; } case VFF_TYP_4_BYTE: case VFF_TYP_FLOAT: { MSBOrderLong(pixels,bytes_per_pixel*max_packets); break; } default: break; } min_value=0.0; scale_factor=1.0; if ((viff_info.data_storage_type != VFF_TYP_1_BYTE) && (viff_info.map_scheme == VFF_MS_NONE)) { double max_value; /* Determine scale factor. */ switch ((int) viff_info.data_storage_type) { case VFF_TYP_2_BYTE: value=1.0*((short *) pixels)[0]; break; case VFF_TYP_4_BYTE: value=1.0*((int *) pixels)[0]; break; case VFF_TYP_FLOAT: value=((float *) pixels)[0]; break; case VFF_TYP_DOUBLE: value=((double *) pixels)[0]; break; default: value=1.0*pixels[0]; break; } max_value=value; min_value=value; for (i=0; i < (ssize_t) max_packets; i++) { switch ((int) viff_info.data_storage_type) { case VFF_TYP_2_BYTE: value=1.0*((short *) pixels)[i]; break; case VFF_TYP_4_BYTE: value=1.0*((int *) pixels)[i]; break; case VFF_TYP_FLOAT: value=((float *) pixels)[i]; break; case VFF_TYP_DOUBLE: value=((double *) pixels)[i]; break; default: value=1.0*pixels[i]; break; } if (value > max_value) max_value=value; else if (value < min_value) min_value=value; } if ((min_value == 0) && (max_value == 0)) scale_factor=0; else if (min_value == max_value) { scale_factor=(MagickRealType) QuantumRange/min_value; min_value=0; } else scale_factor=(MagickRealType) QuantumRange/(max_value-min_value); } /* Convert pixels to Quantum size. */ p=(unsigned char *) pixels; for (i=0; i < (ssize_t) max_packets; i++) { switch ((int) viff_info.data_storage_type) { case VFF_TYP_2_BYTE: value=1.0*((short *) pixels)[i]; break; case VFF_TYP_4_BYTE: value=1.0*((int *) pixels)[i]; break; case VFF_TYP_FLOAT: value=((float *) pixels)[i]; break; case VFF_TYP_DOUBLE: value=((double *) pixels)[i]; break; default: value=1.0*pixels[i]; break; } if (viff_info.map_scheme == VFF_MS_NONE) { value=(value-min_value)*scale_factor; if (value > QuantumRange) value=QuantumRange; else if (value < 0) value=0; } *p=(unsigned char) value; p++; } /* Convert VIFF raster image to pixel packets. */ p=(unsigned char *) pixels; if (viff_info.data_storage_type == VFF_TYP_BIT) { /* Convert bitmap scanline. */ for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=0; x < (ssize_t) (image->columns-7); x+=8) { for (bit=0; bit < 8; bit++) { quantum=(size_t) ((*p) & (0x01 << bit) ? 0 : 1); SetPixelIndex(indexes+x+bit,quantum); } p++; } if ((image->columns % 8) != 0) { for (bit=0; bit < (int) (image->columns % 8); bit++) { quantum=(size_t) ((*p) & (0x01 << bit) ? 0 : 1); SetPixelIndex(indexes+x+bit,quantum); } p++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } } else if (image->storage_class == PseudoClass) for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) SetPixelIndex(indexes+x,*p++); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } else { /* Convert DirectColor scanline. */ number_pixels=(MagickSizeType) image->columns*image->rows; for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,ScaleCharToQuantum(*p)); SetPixelGreen(q,ScaleCharToQuantum(*(p+number_pixels))); SetPixelBlue(q,ScaleCharToQuantum(*(p+2*number_pixels))); if (image->colors != 0) { ssize_t index; index=(ssize_t) GetPixelRed(q); SetPixelRed(q,image->colormap[(ssize_t) ConstrainColormapIndex(image,index)].red); index=(ssize_t) GetPixelGreen(q); SetPixelGreen(q,image->colormap[(ssize_t) ConstrainColormapIndex(image,index)].green); index=(ssize_t) GetPixelRed(q); SetPixelBlue(q,image->colormap[(ssize_t) ConstrainColormapIndex(image,index)].blue); } SetPixelOpacity(q,image->matte != MagickFalse ? QuantumRange- ScaleCharToQuantum(*(p+number_pixels*3)) : OpaqueOpacity); p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } } pixels=(unsigned char *) RelinquishMagickMemory(pixels); if (image->storage_class == PseudoClass) (void) SyncImage(image); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; count=ReadBlob(image,1,&viff_info.identifier); if ((count != 0) && (viff_info.identifier == 0xab)) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } while ((count != 0) && (viff_info.identifier == 0xab)); (void) CloseBlob(image); return(GetFirstImageInList(image)); } Commit Message: CWE ID: CWE-119
static Image *ReadVIFFImage(const ImageInfo *image_info, ExceptionInfo *exception) { #define VFF_CM_genericRGB 15 #define VFF_CM_ntscRGB 1 #define VFF_CM_NONE 0 #define VFF_DEP_DECORDER 0x4 #define VFF_DEP_NSORDER 0x8 #define VFF_DES_RAW 0 #define VFF_LOC_IMPLICIT 1 #define VFF_MAPTYP_NONE 0 #define VFF_MAPTYP_1_BYTE 1 #define VFF_MAPTYP_2_BYTE 2 #define VFF_MAPTYP_4_BYTE 4 #define VFF_MAPTYP_FLOAT 5 #define VFF_MAPTYP_DOUBLE 7 #define VFF_MS_NONE 0 #define VFF_MS_ONEPERBAND 1 #define VFF_MS_SHARED 3 #define VFF_TYP_BIT 0 #define VFF_TYP_1_BYTE 1 #define VFF_TYP_2_BYTE 2 #define VFF_TYP_4_BYTE 4 #define VFF_TYP_FLOAT 5 #define VFF_TYP_DOUBLE 9 typedef struct _ViffInfo { unsigned char identifier, file_type, release, version, machine_dependency, reserve[3]; char comment[512]; unsigned int rows, columns, subrows; int x_offset, y_offset; float x_bits_per_pixel, y_bits_per_pixel; unsigned int location_type, location_dimension, number_of_images, number_data_bands, data_storage_type, data_encode_scheme, map_scheme, map_storage_type, map_rows, map_columns, map_subrows, map_enable, maps_per_cycle, color_space_model; } ViffInfo; double min_value, scale_factor, value; Image *image; int bit; MagickBooleanType status; MagickSizeType number_pixels; register IndexPacket *indexes; register ssize_t x; register PixelPacket *q; register ssize_t i; register unsigned char *p; size_t bytes_per_pixel, lsb_first, max_packets, quantum; ssize_t count, y; unsigned char *pixels; ViffInfo viff_info; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read VIFF header (1024 bytes). */ count=ReadBlob(image,1,&viff_info.identifier); do { /* Verify VIFF identifier. */ if ((count == 0) || ((unsigned char) viff_info.identifier != 0xab)) ThrowReaderException(CorruptImageError,"NotAVIFFImage"); /* Initialize VIFF image. */ (void) ReadBlob(image,sizeof(viff_info.file_type),&viff_info.file_type); (void) ReadBlob(image,sizeof(viff_info.release),&viff_info.release); (void) ReadBlob(image,sizeof(viff_info.version),&viff_info.version); (void) ReadBlob(image,sizeof(viff_info.machine_dependency), &viff_info.machine_dependency); (void) ReadBlob(image,sizeof(viff_info.reserve),viff_info.reserve); count=ReadBlob(image,512,(unsigned char *) viff_info.comment); viff_info.comment[511]='\0'; if (strlen(viff_info.comment) > 4) (void) SetImageProperty(image,"comment",viff_info.comment); if ((viff_info.machine_dependency == VFF_DEP_DECORDER) || (viff_info.machine_dependency == VFF_DEP_NSORDER)) image->endian=LSBEndian; else image->endian=MSBEndian; viff_info.rows=ReadBlobLong(image); viff_info.columns=ReadBlobLong(image); viff_info.subrows=ReadBlobLong(image); viff_info.x_offset=(int) ReadBlobLong(image); viff_info.y_offset=(int) ReadBlobLong(image); viff_info.x_bits_per_pixel=(float) ReadBlobLong(image); viff_info.y_bits_per_pixel=(float) ReadBlobLong(image); viff_info.location_type=ReadBlobLong(image); viff_info.location_dimension=ReadBlobLong(image); viff_info.number_of_images=ReadBlobLong(image); viff_info.number_data_bands=ReadBlobLong(image); viff_info.data_storage_type=ReadBlobLong(image); viff_info.data_encode_scheme=ReadBlobLong(image); viff_info.map_scheme=ReadBlobLong(image); viff_info.map_storage_type=ReadBlobLong(image); viff_info.map_rows=ReadBlobLong(image); viff_info.map_columns=ReadBlobLong(image); viff_info.map_subrows=ReadBlobLong(image); viff_info.map_enable=ReadBlobLong(image); viff_info.maps_per_cycle=ReadBlobLong(image); viff_info.color_space_model=ReadBlobLong(image); for (i=0; i < 420; i++) (void) ReadBlobByte(image); image->columns=viff_info.rows; image->rows=viff_info.columns; image->depth=viff_info.x_bits_per_pixel <= 8 ? 8UL : MAGICKCORE_QUANTUM_DEPTH; /* Verify that we can read this VIFF image. */ number_pixels=(MagickSizeType) viff_info.columns*viff_info.rows; if (number_pixels != (size_t) number_pixels) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); if (number_pixels == 0) ThrowReaderException(CoderError,"ImageColumnOrRowSizeIsNotSupported"); if ((viff_info.number_data_bands < 1) || (viff_info.number_data_bands > 4)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if ((viff_info.data_storage_type != VFF_TYP_BIT) && (viff_info.data_storage_type != VFF_TYP_1_BYTE) && (viff_info.data_storage_type != VFF_TYP_2_BYTE) && (viff_info.data_storage_type != VFF_TYP_4_BYTE) && (viff_info.data_storage_type != VFF_TYP_FLOAT) && (viff_info.data_storage_type != VFF_TYP_DOUBLE)) ThrowReaderException(CoderError,"DataStorageTypeIsNotSupported"); if (viff_info.data_encode_scheme != VFF_DES_RAW) ThrowReaderException(CoderError,"DataEncodingSchemeIsNotSupported"); if ((viff_info.map_storage_type != VFF_MAPTYP_NONE) && (viff_info.map_storage_type != VFF_MAPTYP_1_BYTE) && (viff_info.map_storage_type != VFF_MAPTYP_2_BYTE) && (viff_info.map_storage_type != VFF_MAPTYP_4_BYTE) && (viff_info.map_storage_type != VFF_MAPTYP_FLOAT) && (viff_info.map_storage_type != VFF_MAPTYP_DOUBLE)) ThrowReaderException(CoderError,"MapStorageTypeIsNotSupported"); if ((viff_info.color_space_model != VFF_CM_NONE) && (viff_info.color_space_model != VFF_CM_ntscRGB) && (viff_info.color_space_model != VFF_CM_genericRGB)) ThrowReaderException(CoderError,"ColorspaceModelIsNotSupported"); if (viff_info.location_type != VFF_LOC_IMPLICIT) ThrowReaderException(CoderError,"LocationTypeIsNotSupported"); if (viff_info.number_of_images != 1) ThrowReaderException(CoderError,"NumberOfImagesIsNotSupported"); if (viff_info.map_rows == 0) viff_info.map_scheme=VFF_MS_NONE; switch ((int) viff_info.map_scheme) { case VFF_MS_NONE: { if (viff_info.number_data_bands < 3) { /* Create linear color ramp. */ if (viff_info.data_storage_type == VFF_TYP_BIT) image->colors=2; else if (viff_info.data_storage_type == VFF_MAPTYP_1_BYTE) image->colors=256UL; else image->colors=image->depth <= 8 ? 256UL : 65536UL; if (AcquireImageColormap(image,image->colors) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } break; } case VFF_MS_ONEPERBAND: case VFF_MS_SHARED: { unsigned char *viff_colormap; /* Allocate VIFF colormap. */ switch ((int) viff_info.map_storage_type) { case VFF_MAPTYP_1_BYTE: bytes_per_pixel=1; break; case VFF_MAPTYP_2_BYTE: bytes_per_pixel=2; break; case VFF_MAPTYP_4_BYTE: bytes_per_pixel=4; break; case VFF_MAPTYP_FLOAT: bytes_per_pixel=4; break; case VFF_MAPTYP_DOUBLE: bytes_per_pixel=8; break; default: bytes_per_pixel=1; break; } image->colors=viff_info.map_columns; if (AcquireImageColormap(image,image->colors) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); viff_colormap=(unsigned char *) AcquireQuantumMemory(image->colors, viff_info.map_rows*bytes_per_pixel*sizeof(*viff_colormap)); if (viff_colormap == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); /* Read VIFF raster colormap. */ count=ReadBlob(image,bytes_per_pixel*image->colors*viff_info.map_rows, viff_colormap); lsb_first=1; if (*(char *) &lsb_first && ((viff_info.machine_dependency != VFF_DEP_DECORDER) && (viff_info.machine_dependency != VFF_DEP_NSORDER))) switch ((int) viff_info.map_storage_type) { case VFF_MAPTYP_2_BYTE: { MSBOrderShort(viff_colormap,(bytes_per_pixel*image->colors* viff_info.map_rows)); break; } case VFF_MAPTYP_4_BYTE: case VFF_MAPTYP_FLOAT: { MSBOrderLong(viff_colormap,(bytes_per_pixel*image->colors* viff_info.map_rows)); break; } default: break; } for (i=0; i < (ssize_t) (viff_info.map_rows*image->colors); i++) { switch ((int) viff_info.map_storage_type) { case VFF_MAPTYP_2_BYTE: value=1.0*((short *) viff_colormap)[i]; break; case VFF_MAPTYP_4_BYTE: value=1.0*((int *) viff_colormap)[i]; break; case VFF_MAPTYP_FLOAT: value=((float *) viff_colormap)[i]; break; case VFF_MAPTYP_DOUBLE: value=((double *) viff_colormap)[i]; break; default: value=1.0*viff_colormap[i]; break; } if (i < (ssize_t) image->colors) { image->colormap[i].red=ScaleCharToQuantum((unsigned char) value); image->colormap[i].green=ScaleCharToQuantum((unsigned char) value); image->colormap[i].blue=ScaleCharToQuantum((unsigned char) value); } else if (i < (ssize_t) (2*image->colors)) image->colormap[i % image->colors].green=ScaleCharToQuantum( (unsigned char) value); else if (i < (ssize_t) (3*image->colors)) image->colormap[i % image->colors].blue=ScaleCharToQuantum( (unsigned char) value); } viff_colormap=(unsigned char *) RelinquishMagickMemory(viff_colormap); break; } default: ThrowReaderException(CoderError,"ColormapTypeNotSupported"); } /* Initialize image structure. */ image->matte=viff_info.number_data_bands == 4 ? MagickTrue : MagickFalse; image->storage_class= (viff_info.number_data_bands < 3 ? PseudoClass : DirectClass); image->columns=viff_info.rows; image->rows=viff_info.columns; if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } /* Allocate VIFF pixels. */ switch ((int) viff_info.data_storage_type) { case VFF_TYP_2_BYTE: bytes_per_pixel=2; break; case VFF_TYP_4_BYTE: bytes_per_pixel=4; break; case VFF_TYP_FLOAT: bytes_per_pixel=4; break; case VFF_TYP_DOUBLE: bytes_per_pixel=8; break; default: bytes_per_pixel=1; break; } if (viff_info.data_storage_type == VFF_TYP_BIT) max_packets=((image->columns+7UL) >> 3UL)*image->rows; else max_packets=(size_t) (number_pixels*viff_info.number_data_bands); pixels=(unsigned char *) AcquireQuantumMemory(max_packets, bytes_per_pixel*sizeof(*pixels)); if (pixels == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=ReadBlob(image,bytes_per_pixel*max_packets,pixels); lsb_first=1; if (*(char *) &lsb_first && ((viff_info.machine_dependency != VFF_DEP_DECORDER) && (viff_info.machine_dependency != VFF_DEP_NSORDER))) switch ((int) viff_info.data_storage_type) { case VFF_TYP_2_BYTE: { MSBOrderShort(pixels,bytes_per_pixel*max_packets); break; } case VFF_TYP_4_BYTE: case VFF_TYP_FLOAT: { MSBOrderLong(pixels,bytes_per_pixel*max_packets); break; } default: break; } min_value=0.0; scale_factor=1.0; if ((viff_info.data_storage_type != VFF_TYP_1_BYTE) && (viff_info.map_scheme == VFF_MS_NONE)) { double max_value; /* Determine scale factor. */ switch ((int) viff_info.data_storage_type) { case VFF_TYP_2_BYTE: value=1.0*((short *) pixels)[0]; break; case VFF_TYP_4_BYTE: value=1.0*((int *) pixels)[0]; break; case VFF_TYP_FLOAT: value=((float *) pixels)[0]; break; case VFF_TYP_DOUBLE: value=((double *) pixels)[0]; break; default: value=1.0*pixels[0]; break; } max_value=value; min_value=value; for (i=0; i < (ssize_t) max_packets; i++) { switch ((int) viff_info.data_storage_type) { case VFF_TYP_2_BYTE: value=1.0*((short *) pixels)[i]; break; case VFF_TYP_4_BYTE: value=1.0*((int *) pixels)[i]; break; case VFF_TYP_FLOAT: value=((float *) pixels)[i]; break; case VFF_TYP_DOUBLE: value=((double *) pixels)[i]; break; default: value=1.0*pixels[i]; break; } if (value > max_value) max_value=value; else if (value < min_value) min_value=value; } if ((min_value == 0) && (max_value == 0)) scale_factor=0; else if (min_value == max_value) { scale_factor=(MagickRealType) QuantumRange/min_value; min_value=0; } else scale_factor=(MagickRealType) QuantumRange/(max_value-min_value); } /* Convert pixels to Quantum size. */ p=(unsigned char *) pixels; for (i=0; i < (ssize_t) max_packets; i++) { switch ((int) viff_info.data_storage_type) { case VFF_TYP_2_BYTE: value=1.0*((short *) pixels)[i]; break; case VFF_TYP_4_BYTE: value=1.0*((int *) pixels)[i]; break; case VFF_TYP_FLOAT: value=((float *) pixels)[i]; break; case VFF_TYP_DOUBLE: value=((double *) pixels)[i]; break; default: value=1.0*pixels[i]; break; } if (viff_info.map_scheme == VFF_MS_NONE) { value=(value-min_value)*scale_factor; if (value > QuantumRange) value=QuantumRange; else if (value < 0) value=0; } *p=(unsigned char) value; p++; } /* Convert VIFF raster image to pixel packets. */ p=(unsigned char *) pixels; if (viff_info.data_storage_type == VFF_TYP_BIT) { /* Convert bitmap scanline. */ for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=0; x < (ssize_t) (image->columns-7); x+=8) { for (bit=0; bit < 8; bit++) { quantum=(size_t) ((*p) & (0x01 << bit) ? 0 : 1); SetPixelIndex(indexes+x+bit,quantum); } p++; } if ((image->columns % 8) != 0) { for (bit=0; bit < (int) (image->columns % 8); bit++) { quantum=(size_t) ((*p) & (0x01 << bit) ? 0 : 1); SetPixelIndex(indexes+x+bit,quantum); } p++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } } else if (image->storage_class == PseudoClass) for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) SetPixelIndex(indexes+x,*p++); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } else { /* Convert DirectColor scanline. */ number_pixels=(MagickSizeType) image->columns*image->rows; for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,ScaleCharToQuantum(*p)); SetPixelGreen(q,ScaleCharToQuantum(*(p+number_pixels))); SetPixelBlue(q,ScaleCharToQuantum(*(p+2*number_pixels))); if (image->colors != 0) { ssize_t index; index=(ssize_t) GetPixelRed(q); SetPixelRed(q,image->colormap[(ssize_t) ConstrainColormapIndex(image,index)].red); index=(ssize_t) GetPixelGreen(q); SetPixelGreen(q,image->colormap[(ssize_t) ConstrainColormapIndex(image,index)].green); index=(ssize_t) GetPixelRed(q); SetPixelBlue(q,image->colormap[(ssize_t) ConstrainColormapIndex(image,index)].blue); } SetPixelOpacity(q,image->matte != MagickFalse ? QuantumRange- ScaleCharToQuantum(*(p+number_pixels*3)) : OpaqueOpacity); p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } } pixels=(unsigned char *) RelinquishMagickMemory(pixels); if (image->storage_class == PseudoClass) (void) SyncImage(image); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; count=ReadBlob(image,1,&viff_info.identifier); if ((count != 0) && (viff_info.identifier == 0xab)) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } while ((count != 0) && (viff_info.identifier == 0xab)); (void) CloseBlob(image); return(GetFirstImageInList(image)); }
168,617
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 asn1_ex_i2c(ASN1_VALUE **pval, unsigned char *cout, int *putype, const ASN1_ITEM *it) { ASN1_BOOLEAN *tbool = NULL; ASN1_STRING *strtmp; ASN1_OBJECT *otmp; int utype; const unsigned char *cont; unsigned char c; int len; const ASN1_PRIMITIVE_FUNCS *pf; pf = it->funcs; if (pf && pf->prim_i2c) return pf->prim_i2c(pval, cout, putype, it); /* Should type be omitted? */ if ((it->itype != ASN1_ITYPE_PRIMITIVE) || (it->utype != V_ASN1_BOOLEAN)) { if (!*pval) return -1; } if (it->itype == ASN1_ITYPE_MSTRING) { /* If MSTRING type set the underlying type */ strtmp = (ASN1_STRING *)*pval; utype = strtmp->type; *putype = utype; } else if (it->utype == V_ASN1_ANY) { /* If ANY set type and pointer to value */ ASN1_TYPE *typ; typ = (ASN1_TYPE *)*pval; utype = typ->type; *putype = utype; pval = &typ->value.asn1_value; } else utype = *putype; switch (utype) { case V_ASN1_OBJECT: otmp = (ASN1_OBJECT *)*pval; cont = otmp->data; len = otmp->length; break; case V_ASN1_NULL: cont = NULL; len = 0; break; case V_ASN1_BOOLEAN: tbool = (ASN1_BOOLEAN *)pval; if (*tbool == -1) return -1; if (it->utype != V_ASN1_ANY) { /* * Default handling if value == size field then omit */ if (*tbool && (it->size > 0)) return -1; if (!*tbool && !it->size) return -1; } c = (unsigned char)*tbool; cont = &c; len = 1; break; case V_ASN1_BIT_STRING: return i2c_ASN1_BIT_STRING((ASN1_BIT_STRING *)*pval, cout ? &cout : NULL); break; case V_ASN1_INTEGER: case V_ASN1_NEG_INTEGER: case V_ASN1_ENUMERATED: case V_ASN1_NEG_ENUMERATED: /* * These are all have the same content format as ASN1_INTEGER */ * These are all have the same content format as ASN1_INTEGER */ return i2c_ASN1_INTEGER((ASN1_INTEGER *)*pval, cout ? &cout : NULL); break; case V_ASN1_OCTET_STRING: case V_ASN1_NUMERICSTRING: case V_ASN1_PRINTABLESTRING: case V_ASN1_T61STRING: case V_ASN1_VIDEOTEXSTRING: case V_ASN1_IA5STRING: case V_ASN1_UTCTIME: case V_ASN1_GENERALIZEDTIME: case V_ASN1_GRAPHICSTRING: case V_ASN1_VISIBLESTRING: case V_ASN1_GENERALSTRING: case V_ASN1_UNIVERSALSTRING: case V_ASN1_BMPSTRING: case V_ASN1_UTF8STRING: case V_ASN1_SEQUENCE: case V_ASN1_SET: default: /* All based on ASN1_STRING and handled the same */ strtmp = (ASN1_STRING *)*pval; /* Special handling for NDEF */ if ((it->size == ASN1_TFLG_NDEF) && (strtmp->flags & ASN1_STRING_FLAG_NDEF)) { if (cout) { strtmp->data = cout; strtmp->length = 0; } /* Special return code */ return -2; } cont = strtmp->data; len = strtmp->length; break; } if (cout && len) memcpy(cout, cont, len); return len; } Commit Message: CWE ID: CWE-119
int asn1_ex_i2c(ASN1_VALUE **pval, unsigned char *cout, int *putype, const ASN1_ITEM *it) { ASN1_BOOLEAN *tbool = NULL; ASN1_STRING *strtmp; ASN1_OBJECT *otmp; int utype; const unsigned char *cont; unsigned char c; int len; const ASN1_PRIMITIVE_FUNCS *pf; pf = it->funcs; if (pf && pf->prim_i2c) return pf->prim_i2c(pval, cout, putype, it); /* Should type be omitted? */ if ((it->itype != ASN1_ITYPE_PRIMITIVE) || (it->utype != V_ASN1_BOOLEAN)) { if (!*pval) return -1; } if (it->itype == ASN1_ITYPE_MSTRING) { /* If MSTRING type set the underlying type */ strtmp = (ASN1_STRING *)*pval; utype = strtmp->type; *putype = utype; } else if (it->utype == V_ASN1_ANY) { /* If ANY set type and pointer to value */ ASN1_TYPE *typ; typ = (ASN1_TYPE *)*pval; utype = typ->type; *putype = utype; pval = &typ->value.asn1_value; } else utype = *putype; switch (utype) { case V_ASN1_OBJECT: otmp = (ASN1_OBJECT *)*pval; cont = otmp->data; len = otmp->length; break; case V_ASN1_NULL: cont = NULL; len = 0; break; case V_ASN1_BOOLEAN: tbool = (ASN1_BOOLEAN *)pval; if (*tbool == -1) return -1; if (it->utype != V_ASN1_ANY) { /* * Default handling if value == size field then omit */ if (*tbool && (it->size > 0)) return -1; if (!*tbool && !it->size) return -1; } c = (unsigned char)*tbool; cont = &c; len = 1; break; case V_ASN1_BIT_STRING: return i2c_ASN1_BIT_STRING((ASN1_BIT_STRING *)*pval, cout ? &cout : NULL); break; case V_ASN1_INTEGER: case V_ASN1_ENUMERATED: /* * These are all have the same content format as ASN1_INTEGER */ * These are all have the same content format as ASN1_INTEGER */ return i2c_ASN1_INTEGER((ASN1_INTEGER *)*pval, cout ? &cout : NULL); break; case V_ASN1_OCTET_STRING: case V_ASN1_NUMERICSTRING: case V_ASN1_PRINTABLESTRING: case V_ASN1_T61STRING: case V_ASN1_VIDEOTEXSTRING: case V_ASN1_IA5STRING: case V_ASN1_UTCTIME: case V_ASN1_GENERALIZEDTIME: case V_ASN1_GRAPHICSTRING: case V_ASN1_VISIBLESTRING: case V_ASN1_GENERALSTRING: case V_ASN1_UNIVERSALSTRING: case V_ASN1_BMPSTRING: case V_ASN1_UTF8STRING: case V_ASN1_SEQUENCE: case V_ASN1_SET: default: /* All based on ASN1_STRING and handled the same */ strtmp = (ASN1_STRING *)*pval; /* Special handling for NDEF */ if ((it->size == ASN1_TFLG_NDEF) && (strtmp->flags & ASN1_STRING_FLAG_NDEF)) { if (cout) { strtmp->data = cout; strtmp->length = 0; } /* Special return code */ return -2; } cont = strtmp->data; len = strtmp->length; break; } if (cout && len) memcpy(cout, cont, len); return len; }
165,213
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 __iov_iter_advance_iov(struct iov_iter *i, size_t bytes) { if (likely(i->nr_segs == 1)) { i->iov_offset += bytes; } else { const struct iovec *iov = i->iov; size_t base = i->iov_offset; while (bytes) { int copy = min(bytes, iov->iov_len - base); bytes -= copy; base += copy; if (iov->iov_len == base) { iov++; base = 0; } } i->iov = iov; i->iov_offset = base; } } Commit Message: fix writev regression: pan hanging unkillable and un-straceable Frederik Himpe reported an unkillable and un-straceable pan process. Zero length iovecs can go into an infinite loop in writev, because the iovec iterator does not always advance over them. The sequence required to trigger this is not trivial. I think it requires that a zero-length iovec be followed by a non-zero-length iovec which causes a pagefault in the atomic usercopy. This causes the writev code to drop back into single-segment copy mode, which then tries to copy the 0 bytes of the zero-length iovec; a zero length copy looks like a failure though, so it loops. Put a test into iov_iter_advance to catch zero-length iovecs. We could just put the test in the fallback path, but I feel it is more robust to skip over zero-length iovecs throughout the code (iovec iterator may be used in filesystems too, so it should be robust). Signed-off-by: Nick Piggin <[email protected]> Signed-off-by: Ingo Molnar <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-20
static void __iov_iter_advance_iov(struct iov_iter *i, size_t bytes) { if (likely(i->nr_segs == 1)) { i->iov_offset += bytes; } else { const struct iovec *iov = i->iov; size_t base = i->iov_offset; /* * The !iov->iov_len check ensures we skip over unlikely * zero-length segments. */ while (bytes || !iov->iov_len) { int copy = min(bytes, iov->iov_len - base); bytes -= copy; base += copy; if (iov->iov_len == base) { iov++; base = 0; } } i->iov = iov; i->iov_offset = base; } }
167,617
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: DataPipeConsumerDispatcher::Deserialize(const void* data, size_t num_bytes, const ports::PortName* ports, size_t num_ports, PlatformHandle* handles, size_t num_handles) { if (num_ports != 1 || num_handles != 1 || num_bytes != sizeof(SerializedState)) { return nullptr; } const SerializedState* state = static_cast<const SerializedState*>(data); if (!state->options.capacity_num_bytes || !state->options.element_num_bytes || state->options.capacity_num_bytes < state->options.element_num_bytes) { return nullptr; } NodeController* node_controller = Core::Get()->GetNodeController(); ports::PortRef port; if (node_controller->node()->GetPort(ports[0], &port) != ports::OK) return nullptr; auto region_handle = CreateSharedMemoryRegionHandleFromPlatformHandles( std::move(handles[0]), PlatformHandle()); auto region = base::subtle::PlatformSharedMemoryRegion::Take( std::move(region_handle), base::subtle::PlatformSharedMemoryRegion::Mode::kUnsafe, state->options.capacity_num_bytes, base::UnguessableToken::Deserialize(state->buffer_guid_high, state->buffer_guid_low)); auto ring_buffer = base::UnsafeSharedMemoryRegion::Deserialize(std::move(region)); if (!ring_buffer.IsValid()) { DLOG(ERROR) << "Failed to deserialize shared buffer handle."; return nullptr; } scoped_refptr<DataPipeConsumerDispatcher> dispatcher = new DataPipeConsumerDispatcher(node_controller, port, std::move(ring_buffer), state->options, state->pipe_id); { base::AutoLock lock(dispatcher->lock_); dispatcher->read_offset_ = state->read_offset; dispatcher->bytes_available_ = state->bytes_available; dispatcher->new_data_available_ = state->bytes_available > 0; dispatcher->peer_closed_ = state->flags & kFlagPeerClosed; if (!dispatcher->InitializeNoLock()) return nullptr; dispatcher->UpdateSignalsStateNoLock(); } return dispatcher; } Commit Message: [mojo-core] Validate data pipe endpoint metadata Ensures that we don't blindly trust specified buffer size and offset metadata when deserializing data pipe consumer and producer handles. Bug: 877182 Change-Id: I30f3eceafb5cee06284c2714d08357ef911d6fd9 Reviewed-on: https://chromium-review.googlesource.com/1192922 Reviewed-by: Reilly Grant <[email protected]> Commit-Queue: Ken Rockot <[email protected]> Cr-Commit-Position: refs/heads/master@{#586704} CWE ID: CWE-20
DataPipeConsumerDispatcher::Deserialize(const void* data, size_t num_bytes, const ports::PortName* ports, size_t num_ports, PlatformHandle* handles, size_t num_handles) { if (num_ports != 1 || num_handles != 1 || num_bytes != sizeof(SerializedState)) { return nullptr; } const SerializedState* state = static_cast<const SerializedState*>(data); if (!state->options.capacity_num_bytes || !state->options.element_num_bytes || state->options.capacity_num_bytes < state->options.element_num_bytes || state->read_offset >= state->options.capacity_num_bytes || state->bytes_available > state->options.capacity_num_bytes) { return nullptr; } NodeController* node_controller = Core::Get()->GetNodeController(); ports::PortRef port; if (node_controller->node()->GetPort(ports[0], &port) != ports::OK) return nullptr; auto region_handle = CreateSharedMemoryRegionHandleFromPlatformHandles( std::move(handles[0]), PlatformHandle()); auto region = base::subtle::PlatformSharedMemoryRegion::Take( std::move(region_handle), base::subtle::PlatformSharedMemoryRegion::Mode::kUnsafe, state->options.capacity_num_bytes, base::UnguessableToken::Deserialize(state->buffer_guid_high, state->buffer_guid_low)); auto ring_buffer = base::UnsafeSharedMemoryRegion::Deserialize(std::move(region)); if (!ring_buffer.IsValid()) { DLOG(ERROR) << "Failed to deserialize shared buffer handle."; return nullptr; } scoped_refptr<DataPipeConsumerDispatcher> dispatcher = new DataPipeConsumerDispatcher(node_controller, port, std::move(ring_buffer), state->options, state->pipe_id); { base::AutoLock lock(dispatcher->lock_); dispatcher->read_offset_ = state->read_offset; dispatcher->bytes_available_ = state->bytes_available; dispatcher->new_data_available_ = state->bytes_available > 0; dispatcher->peer_closed_ = state->flags & kFlagPeerClosed; if (!dispatcher->InitializeNoLock()) return nullptr; if (state->options.capacity_num_bytes > dispatcher->ring_buffer_mapping_.mapped_size()) { return nullptr; } dispatcher->UpdateSignalsStateNoLock(); } return dispatcher; }
173,176
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 CrosLibrary::TestApi::SetSystemLibrary( SystemLibrary* library, bool own) { library_->system_lib_.SetImpl(library, own); } Commit Message: chromeos: Replace copy-and-pasted code with macros. This replaces a bunch of duplicated-per-library cros function definitions and comments. BUG=none TEST=built it Review URL: http://codereview.chromium.org/6086007 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@70070 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-189
void CrosLibrary::TestApi::SetSystemLibrary(
170,647
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 vmxnet3_post_load(void *opaque, int version_id) { VMXNET3State *s = opaque; PCIDevice *d = PCI_DEVICE(s); vmxnet_tx_pkt_init(&s->tx_pkt, s->max_tx_frags, s->peer_has_vhdr); vmxnet_rx_pkt_init(&s->rx_pkt, s->peer_has_vhdr); if (s->msix_used) { if (!vmxnet3_use_msix_vectors(s, VMXNET3_MAX_INTRS)) { VMW_WRPRN("Failed to re-use MSI-X vectors"); msix_uninit(d, &s->msix_bar, &s->msix_bar); s->msix_used = false; return -1; } } return 0; } Commit Message: CWE ID: CWE-20
static int vmxnet3_post_load(void *opaque, int version_id) { VMXNET3State *s = opaque; PCIDevice *d = PCI_DEVICE(s); vmxnet_tx_pkt_init(&s->tx_pkt, s->max_tx_frags, s->peer_has_vhdr); vmxnet_rx_pkt_init(&s->rx_pkt, s->peer_has_vhdr); if (s->msix_used) { if (!vmxnet3_use_msix_vectors(s, VMXNET3_MAX_INTRS)) { VMW_WRPRN("Failed to re-use MSI-X vectors"); msix_uninit(d, &s->msix_bar, &s->msix_bar); s->msix_used = false; return -1; } } vmxnet3_validate_interrupts(s); return 0; }
165,354
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 frag_kfree_skb(struct netns_frags *nf, struct sk_buff *skb) { atomic_sub(skb->truesize, &nf->mem); kfree_skb(skb); } Commit Message: ipv6: discard overlapping fragment RFC5722 prohibits reassembling fragments when some data overlaps. Bug spotted by Zhang Zuotao <[email protected]>. Signed-off-by: Nicolas Dichtel <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID:
static void frag_kfree_skb(struct netns_frags *nf, struct sk_buff *skb)
165,538
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static inline void constructBidiRunsForSegment(InlineBidiResolver& topResolver, BidiRunList<BidiRun>& bidiRuns, const InlineIterator& endOfRuns, VisualDirectionOverride override, bool previousLineBrokeCleanly) { ASSERT(&topResolver.runs() == &bidiRuns); ASSERT(topResolver.position() != endOfRuns); RenderObject* currentRoot = topResolver.position().root(); topResolver.createBidiRunsForLine(endOfRuns, override, previousLineBrokeCleanly); while (!topResolver.isolatedRuns().isEmpty()) { BidiRun* isolatedRun = topResolver.isolatedRuns().last(); topResolver.isolatedRuns().removeLast(); RenderObject* startObj = isolatedRun->object(); RenderInline* isolatedInline = toRenderInline(containingIsolate(startObj, currentRoot)); InlineBidiResolver isolatedResolver; EUnicodeBidi unicodeBidi = isolatedInline->style()->unicodeBidi(); TextDirection direction = isolatedInline->style()->direction(); if (unicodeBidi == Plaintext) direction = determinePlaintextDirectionality(isolatedInline, startObj); else { ASSERT(unicodeBidi == Isolate || unicodeBidi == IsolateOverride); direction = isolatedInline->style()->direction(); } isolatedResolver.setStatus(statusWithDirection(direction, isOverride(unicodeBidi))); setupResolverToResumeInIsolate(isolatedResolver, isolatedInline, startObj); InlineIterator iter = InlineIterator(isolatedInline, startObj, isolatedRun->m_start); isolatedResolver.setPositionIgnoringNestedIsolates(iter); isolatedResolver.createBidiRunsForLine(endOfRuns, NoVisualOverride, previousLineBrokeCleanly); if (isolatedResolver.runs().runCount()) bidiRuns.replaceRunWithRuns(isolatedRun, isolatedResolver.runs()); if (!isolatedResolver.isolatedRuns().isEmpty()) { topResolver.isolatedRuns().append(isolatedResolver.isolatedRuns()); isolatedResolver.isolatedRuns().clear(); currentRoot = isolatedInline; } } } Commit Message: Update containtingIsolate to go back all the way to top isolate from current root, rather than stopping at the first isolate it finds. This works because the current root is always updated with each isolate run. BUG=279277 Review URL: https://chromiumcodereview.appspot.com/23972003 git-svn-id: svn://svn.chromium.org/blink/trunk@157268 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399
static inline void constructBidiRunsForSegment(InlineBidiResolver& topResolver, BidiRunList<BidiRun>& bidiRuns, const InlineIterator& endOfRuns, VisualDirectionOverride override, bool previousLineBrokeCleanly) { ASSERT(&topResolver.runs() == &bidiRuns); ASSERT(topResolver.position() != endOfRuns); RenderObject* currentRoot = topResolver.position().root(); topResolver.createBidiRunsForLine(endOfRuns, override, previousLineBrokeCleanly); while (!topResolver.isolatedRuns().isEmpty()) { BidiRun* isolatedRun = topResolver.isolatedRuns().last(); topResolver.isolatedRuns().removeLast(); RenderObject* startObj = isolatedRun->object(); RenderInline* isolatedInline = toRenderInline(highestContainingIsolateWithinRoot(startObj, currentRoot)); ASSERT(isolatedInline); InlineBidiResolver isolatedResolver; EUnicodeBidi unicodeBidi = isolatedInline->style()->unicodeBidi(); TextDirection direction = isolatedInline->style()->direction(); if (unicodeBidi == Plaintext) direction = determinePlaintextDirectionality(isolatedInline, startObj); else { ASSERT(unicodeBidi == Isolate || unicodeBidi == IsolateOverride); direction = isolatedInline->style()->direction(); } isolatedResolver.setStatus(statusWithDirection(direction, isOverride(unicodeBidi))); setupResolverToResumeInIsolate(isolatedResolver, isolatedInline, startObj); InlineIterator iter = InlineIterator(isolatedInline, startObj, isolatedRun->m_start); isolatedResolver.setPositionIgnoringNestedIsolates(iter); isolatedResolver.createBidiRunsForLine(endOfRuns, NoVisualOverride, previousLineBrokeCleanly); if (isolatedResolver.runs().runCount()) bidiRuns.replaceRunWithRuns(isolatedRun, isolatedResolver.runs()); if (!isolatedResolver.isolatedRuns().isEmpty()) { topResolver.isolatedRuns().append(isolatedResolver.isolatedRuns()); isolatedResolver.isolatedRuns().clear(); currentRoot = isolatedInline; } } }
171,180
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 InputHandler::SetRenderer(RenderProcessHost* process_host, RenderFrameHostImpl* frame_host) { if (frame_host == host_) return; ClearInputState(); if (host_) { host_->GetRenderWidgetHost()->RemoveInputEventObserver(this); if (ignore_input_events_) host_->GetRenderWidgetHost()->SetIgnoreInputEvents(false); } host_ = frame_host; if (host_) { host_->GetRenderWidgetHost()->AddInputEventObserver(this); if (ignore_input_events_) host_->GetRenderWidgetHost()->SetIgnoreInputEvents(true); } } Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable This keeps BrowserContext* and StoragePartition* instead of RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost upon closure of DevTools front-end. Bug: 801117, 783067, 780694 Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b Reviewed-on: https://chromium-review.googlesource.com/876657 Commit-Queue: Andrey Kosyakov <[email protected]> Reviewed-by: Dmitry Gozman <[email protected]> Cr-Commit-Position: refs/heads/master@{#531157} CWE ID: CWE-20
void InputHandler::SetRenderer(RenderProcessHost* process_host, void InputHandler::SetRenderer(int process_host_id, RenderFrameHostImpl* frame_host) { if (frame_host == host_) return; ClearInputState(); if (host_) { host_->GetRenderWidgetHost()->RemoveInputEventObserver(this); if (ignore_input_events_) host_->GetRenderWidgetHost()->SetIgnoreInputEvents(false); } host_ = frame_host; if (host_) { host_->GetRenderWidgetHost()->AddInputEventObserver(this); if (ignore_input_events_) host_->GetRenderWidgetHost()->SetIgnoreInputEvents(true); } }
172,747
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 jpg_dec_parseopts(char *optstr, jpg_dec_importopts_t *opts) { jas_tvparser_t *tvp; opts->max_size = 0; if (!(tvp = jas_tvparser_create(optstr ? optstr : ""))) { return -1; } while (!jas_tvparser_next(tvp)) { switch (jas_taginfo_nonull(jas_taginfos_lookup(decopts, jas_tvparser_gettag(tvp)))->id) { case OPT_MAXSIZE: opts->max_size = atoi(jas_tvparser_getval(tvp)); break; default: jas_eprintf("warning: ignoring invalid option %s\n", jas_tvparser_gettag(tvp)); break; } } jas_tvparser_destroy(tvp); 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 int jpg_dec_parseopts(char *optstr, jpg_dec_importopts_t *opts) { jas_tvparser_t *tvp; opts->max_samples = 64 * JAS_MEBI; if (!(tvp = jas_tvparser_create(optstr ? optstr : ""))) { return -1; } while (!jas_tvparser_next(tvp)) { switch (jas_taginfo_nonull(jas_taginfos_lookup(decopts, jas_tvparser_gettag(tvp)))->id) { case OPT_MAXSIZE: opts->max_samples = atoi(jas_tvparser_getval(tvp)); break; default: jas_eprintf("warning: ignoring invalid option %s\n", jas_tvparser_gettag(tvp)); break; } } jas_tvparser_destroy(tvp); return 0; }
168,721
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: check_acl(pam_handle_t *pamh, const char *sense, const char *this_user, const char *other_user, int noent_code, int debug) { struct passwd *pwd; FILE *fp = NULL; int i, fd = -1, save_errno; uid_t fsuid; struct stat st; /* Check this user's <sense> file. */ pwd = pam_modutil_getpwnam(pamh, this_user); if (pwd == NULL) { pam_syslog(pamh, LOG_ERR, "error determining home directory for '%s'", this_user); return PAM_SESSION_ERR; } /* Figure out what that file is really named. */ i = snprintf(path, sizeof(path), "%s/.xauth/%s", pwd->pw_dir, sense); if ((i >= (int)sizeof(path)) || (i < 0)) { pam_syslog(pamh, LOG_ERR, "name of user's home directory is too long"); return PAM_SESSION_ERR; } fsuid = setfsuid(pwd->pw_uid); if (!stat(path, &st)) { if (!S_ISREG(st.st_mode)) errno = EINVAL; fd = open(path, O_RDONLY | O_NOCTTY); fd = open(path, O_RDONLY | O_NOCTTY); } save_errno = errno; setfsuid(fsuid); if (fd >= 0) { if (!fstat(fd, &st)) { if (!S_ISREG(st.st_mode)) save_errno = errno; close(fd); } } if (fp) { char buf[LINE_MAX], *tmp; /* Scan the file for a list of specs of users to "trust". */ while (fgets(buf, sizeof(buf), fp) != NULL) { tmp = memchr(buf, '\r', sizeof(buf)); if (tmp != NULL) { *tmp = '\0'; } tmp = memchr(buf, '\n', sizeof(buf)); if (tmp != NULL) { *tmp = '\0'; } if (fnmatch(buf, other_user, 0) == 0) { if (debug) { pam_syslog(pamh, LOG_DEBUG, "%s %s allowed by %s", other_user, sense, path); } fclose(fp); return PAM_SUCCESS; } } /* If there's no match in the file, we fail. */ if (debug) { pam_syslog(pamh, LOG_DEBUG, "%s not listed in %s", other_user, path); } fclose(fp); return PAM_PERM_DENIED; } else { /* Default to okay if the file doesn't exist. */ errno = save_errno; switch (errno) { case ENOENT: if (noent_code == PAM_SUCCESS) { if (debug) { pam_syslog(pamh, LOG_DEBUG, "%s does not exist, ignoring", path); } } else { if (debug) { pam_syslog(pamh, LOG_DEBUG, "%s does not exist, failing", path); } } return noent_code; default: if (debug) { pam_syslog(pamh, LOG_DEBUG, "error opening %s: %m", path); } return PAM_PERM_DENIED; } } } Commit Message: CWE ID:
check_acl(pam_handle_t *pamh, const char *sense, const char *this_user, const char *other_user, int noent_code, int debug) { struct passwd *pwd; FILE *fp = NULL; int i, fd = -1, save_errno; struct stat st; PAM_MODUTIL_DEF_PRIVS(privs); /* Check this user's <sense> file. */ pwd = pam_modutil_getpwnam(pamh, this_user); if (pwd == NULL) { pam_syslog(pamh, LOG_ERR, "error determining home directory for '%s'", this_user); return PAM_SESSION_ERR; } /* Figure out what that file is really named. */ i = snprintf(path, sizeof(path), "%s/.xauth/%s", pwd->pw_dir, sense); if ((i >= (int)sizeof(path)) || (i < 0)) { pam_syslog(pamh, LOG_ERR, "name of user's home directory is too long"); return PAM_SESSION_ERR; } if (pam_modutil_drop_priv(pamh, &privs, pwd)) return PAM_SESSION_ERR; if (!stat(path, &st)) { if (!S_ISREG(st.st_mode)) errno = EINVAL; fd = open(path, O_RDONLY | O_NOCTTY); fd = open(path, O_RDONLY | O_NOCTTY); } save_errno = errno; if (pam_modutil_regain_priv(pamh, &privs)) { if (fd >= 0) close(fd); return PAM_SESSION_ERR; } if (fd >= 0) { if (!fstat(fd, &st)) { if (!S_ISREG(st.st_mode)) save_errno = errno; close(fd); } } if (fp) { char buf[LINE_MAX], *tmp; /* Scan the file for a list of specs of users to "trust". */ while (fgets(buf, sizeof(buf), fp) != NULL) { tmp = memchr(buf, '\r', sizeof(buf)); if (tmp != NULL) { *tmp = '\0'; } tmp = memchr(buf, '\n', sizeof(buf)); if (tmp != NULL) { *tmp = '\0'; } if (fnmatch(buf, other_user, 0) == 0) { if (debug) { pam_syslog(pamh, LOG_DEBUG, "%s %s allowed by %s", other_user, sense, path); } fclose(fp); return PAM_SUCCESS; } } /* If there's no match in the file, we fail. */ if (debug) { pam_syslog(pamh, LOG_DEBUG, "%s not listed in %s", other_user, path); } fclose(fp); return PAM_PERM_DENIED; } else { /* Default to okay if the file doesn't exist. */ errno = save_errno; switch (errno) { case ENOENT: if (noent_code == PAM_SUCCESS) { if (debug) { pam_syslog(pamh, LOG_DEBUG, "%s does not exist, ignoring", path); } } else { if (debug) { pam_syslog(pamh, LOG_DEBUG, "%s does not exist, failing", path); } } return noent_code; default: if (debug) { pam_syslog(pamh, LOG_DEBUG, "error opening %s: %m", path); } return PAM_PERM_DENIED; } } }
164,818
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 svc_rdma_sendto(struct svc_rqst *rqstp) { struct svc_xprt *xprt = rqstp->rq_xprt; struct svcxprt_rdma *rdma = container_of(xprt, struct svcxprt_rdma, sc_xprt); struct rpcrdma_msg *rdma_argp; struct rpcrdma_msg *rdma_resp; struct rpcrdma_write_array *wr_ary, *rp_ary; int ret; int inline_bytes; struct page *res_page; struct svc_rdma_req_map *vec; u32 inv_rkey; __be32 *p; dprintk("svcrdma: sending response for rqstp=%p\n", rqstp); /* Get the RDMA request header. The receive logic always * places this at the start of page 0. */ rdma_argp = page_address(rqstp->rq_pages[0]); svc_rdma_get_write_arrays(rdma_argp, &wr_ary, &rp_ary); inv_rkey = 0; if (rdma->sc_snd_w_inv) inv_rkey = svc_rdma_get_inv_rkey(rdma_argp, wr_ary, rp_ary); /* Build an req vec for the XDR */ vec = svc_rdma_get_req_map(rdma); ret = svc_rdma_map_xdr(rdma, &rqstp->rq_res, vec, wr_ary != NULL); if (ret) goto err0; inline_bytes = rqstp->rq_res.len; /* Create the RDMA response header. xprt->xpt_mutex, * acquired in svc_send(), serializes RPC replies. The * code path below that inserts the credit grant value * into each transport header runs only inside this * critical section. */ ret = -ENOMEM; res_page = alloc_page(GFP_KERNEL); if (!res_page) goto err0; rdma_resp = page_address(res_page); p = &rdma_resp->rm_xid; *p++ = rdma_argp->rm_xid; *p++ = rdma_argp->rm_vers; *p++ = rdma->sc_fc_credits; *p++ = rp_ary ? rdma_nomsg : rdma_msg; /* Start with empty chunks */ *p++ = xdr_zero; *p++ = xdr_zero; *p = xdr_zero; /* Send any write-chunk data and build resp write-list */ if (wr_ary) { ret = send_write_chunks(rdma, wr_ary, rdma_resp, rqstp, vec); if (ret < 0) goto err1; inline_bytes -= ret + xdr_padsize(ret); } /* Send any reply-list data and update resp reply-list */ if (rp_ary) { ret = send_reply_chunks(rdma, rp_ary, rdma_resp, rqstp, vec); if (ret < 0) goto err1; inline_bytes -= ret; } /* Post a fresh Receive buffer _before_ sending the reply */ ret = svc_rdma_post_recv(rdma, GFP_KERNEL); if (ret) goto err1; ret = send_reply(rdma, rqstp, res_page, rdma_resp, vec, inline_bytes, inv_rkey); if (ret < 0) goto err0; svc_rdma_put_req_map(rdma, vec); dprintk("svcrdma: send_reply returns %d\n", ret); return ret; err1: put_page(res_page); err0: svc_rdma_put_req_map(rdma, vec); pr_err("svcrdma: Could not send reply, err=%d. Closing transport.\n", ret); set_bit(XPT_CLOSE, &rdma->sc_xprt.xpt_flags); return -ENOTCONN; } Commit Message: Merge tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux Pull nfsd updates from Bruce Fields: "Another RDMA update from Chuck Lever, and a bunch of miscellaneous bugfixes" * tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux: (26 commits) nfsd: Fix up the "supattr_exclcreat" attributes nfsd: encoders mustn't use unitialized values in error cases nfsd: fix undefined behavior in nfsd4_layout_verify lockd: fix lockd shutdown race NFSv4: Fix callback server shutdown SUNRPC: Refactor svc_set_num_threads() NFSv4.x/callback: Create the callback service through svc_create_pooled lockd: remove redundant check on block svcrdma: Clean out old XDR encoders svcrdma: Remove the req_map cache svcrdma: Remove unused RDMA Write completion handler svcrdma: Reduce size of sge array in struct svc_rdma_op_ctxt svcrdma: Clean up RPC-over-RDMA backchannel reply processing svcrdma: Report Write/Reply chunk overruns svcrdma: Clean up RDMA_ERROR path svcrdma: Use rdma_rw API in RPC reply path svcrdma: Introduce local rdma_rw API helpers svcrdma: Clean up svc_rdma_get_inv_rkey() svcrdma: Add helper to save pages under I/O svcrdma: Eliminate RPCRDMA_SQ_DEPTH_MULT ... CWE ID: CWE-404
int svc_rdma_sendto(struct svc_rqst *rqstp) { struct svc_xprt *xprt = rqstp->rq_xprt; struct svcxprt_rdma *rdma = container_of(xprt, struct svcxprt_rdma, sc_xprt); __be32 *p, *rdma_argp, *rdma_resp, *wr_lst, *rp_ch; struct xdr_buf *xdr = &rqstp->rq_res; struct page *res_page; int ret; /* Find the call's chunk lists to decide how to send the reply. * Receive places the Call's xprt header at the start of page 0. */ rdma_argp = page_address(rqstp->rq_pages[0]); svc_rdma_get_write_arrays(rdma_argp, &wr_lst, &rp_ch); dprintk("svcrdma: preparing response for XID 0x%08x\n", be32_to_cpup(rdma_argp)); /* Create the RDMA response header. xprt->xpt_mutex, * acquired in svc_send(), serializes RPC replies. The * code path below that inserts the credit grant value * into each transport header runs only inside this * critical section. */ ret = -ENOMEM; res_page = alloc_page(GFP_KERNEL); if (!res_page) goto err0; rdma_resp = page_address(res_page); p = rdma_resp; *p++ = *rdma_argp; *p++ = *(rdma_argp + 1); *p++ = rdma->sc_fc_credits; *p++ = rp_ch ? rdma_nomsg : rdma_msg; /* Start with empty chunks */ *p++ = xdr_zero; *p++ = xdr_zero; *p = xdr_zero; if (wr_lst) { /* XXX: Presume the client sent only one Write chunk */ ret = svc_rdma_send_write_chunk(rdma, wr_lst, xdr); if (ret < 0) goto err2; svc_rdma_xdr_encode_write_list(rdma_resp, wr_lst, ret); } if (rp_ch) { ret = svc_rdma_send_reply_chunk(rdma, rp_ch, wr_lst, xdr); if (ret < 0) goto err2; svc_rdma_xdr_encode_reply_chunk(rdma_resp, rp_ch, ret); } ret = svc_rdma_post_recv(rdma, GFP_KERNEL); if (ret) goto err1; ret = svc_rdma_send_reply_msg(rdma, rdma_argp, rdma_resp, rqstp, wr_lst, rp_ch); if (ret < 0) goto err0; return 0; err2: if (ret != -E2BIG) goto err1; ret = svc_rdma_post_recv(rdma, GFP_KERNEL); if (ret) goto err1; ret = svc_rdma_send_error_msg(rdma, rdma_resp, rqstp); if (ret < 0) goto err0; return 0; err1: put_page(res_page); err0: pr_err("svcrdma: Could not send reply, err=%d. Closing transport.\n", ret); set_bit(XPT_CLOSE, &xprt->xpt_flags); return -ENOTCONN; }
168,175
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 _moddeinit(module_unload_intent_t intent) { service_named_unbind_command("chanserv", &cs_flags); } Commit Message: chanserv/flags: make Anope FLAGS compatibility an option Previously, ChanServ FLAGS behavior could be modified by registering or dropping the keyword nicks "LIST", "CLEAR", and "MODIFY". Now, a configuration option is available that when turned on (default), disables registration of these keyword nicks and enables this compatibility feature. When turned off, registration of these keyword nicks is possible, and compatibility to Anope's FLAGS command is disabled. Fixes atheme/atheme#397 CWE ID: CWE-284
void _moddeinit(module_unload_intent_t intent) { service_named_unbind_command("chanserv", &cs_flags); hook_del_nick_can_register(check_registration_keywords); hook_del_user_can_register(check_registration_keywords); del_conf_item("ANOPE_FLAGS_COMPAT", &chansvs.me->conf_table); }
167,585
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 udp_recvmsg(struct sock *sk, struct msghdr *msg, size_t len, int noblock, int flags, int *addr_len) { struct inet_sock *inet = inet_sk(sk); DECLARE_SOCKADDR(struct sockaddr_in *, sin, msg->msg_name); struct sk_buff *skb; unsigned int ulen, copied; int peeked, off = 0; int err; int is_udplite = IS_UDPLITE(sk); bool slow; if (flags & MSG_ERRQUEUE) return ip_recv_error(sk, msg, len, addr_len); try_again: skb = __skb_recv_datagram(sk, flags | (noblock ? MSG_DONTWAIT : 0), &peeked, &off, &err); if (!skb) goto out; ulen = skb->len - sizeof(struct udphdr); copied = len; if (copied > ulen) copied = ulen; else if (copied < ulen) msg->msg_flags |= MSG_TRUNC; /* * If checksum is needed at all, try to do it while copying the * data. If the data is truncated, or if we only want a partial * coverage checksum (UDP-Lite), do it before the copy. */ if (copied < ulen || UDP_SKB_CB(skb)->partial_cov) { if (udp_lib_checksum_complete(skb)) goto csum_copy_err; } if (skb_csum_unnecessary(skb)) err = skb_copy_datagram_msg(skb, sizeof(struct udphdr), msg, copied); else { err = skb_copy_and_csum_datagram_msg(skb, sizeof(struct udphdr), msg); if (err == -EINVAL) goto csum_copy_err; } if (unlikely(err)) { trace_kfree_skb(skb, udp_recvmsg); if (!peeked) { atomic_inc(&sk->sk_drops); UDP_INC_STATS_USER(sock_net(sk), UDP_MIB_INERRORS, is_udplite); } goto out_free; } if (!peeked) UDP_INC_STATS_USER(sock_net(sk), UDP_MIB_INDATAGRAMS, is_udplite); sock_recv_ts_and_drops(msg, sk, skb); /* Copy the address. */ if (sin) { sin->sin_family = AF_INET; sin->sin_port = udp_hdr(skb)->source; sin->sin_addr.s_addr = ip_hdr(skb)->saddr; memset(sin->sin_zero, 0, sizeof(sin->sin_zero)); *addr_len = sizeof(*sin); } if (inet->cmsg_flags) ip_cmsg_recv_offset(msg, skb, sizeof(struct udphdr)); err = copied; if (flags & MSG_TRUNC) err = ulen; out_free: skb_free_datagram_locked(sk, skb); out: return err; csum_copy_err: slow = lock_sock_fast(sk); if (!skb_kill_datagram(sk, skb, flags)) { UDP_INC_STATS_USER(sock_net(sk), UDP_MIB_CSUMERRORS, is_udplite); UDP_INC_STATS_USER(sock_net(sk), UDP_MIB_INERRORS, is_udplite); } unlock_sock_fast(sk, slow); if (noblock) return -EAGAIN; /* starting over for a new packet */ msg->msg_flags &= ~MSG_TRUNC; goto try_again; } Commit Message: udp: fix behavior of wrong checksums We have two problems in UDP stack related to bogus checksums : 1) We return -EAGAIN to application even if receive queue is not empty. This breaks applications using edge trigger epoll() 2) Under UDP flood, we can loop forever without yielding to other processes, potentially hanging the host, especially on non SMP. This patch is an attempt to make things better. We might in the future add extra support for rt applications wanting to better control time spent doing a recv() in a hostile environment. For example we could validate checksums before queuing packets in socket receive queue. Signed-off-by: Eric Dumazet <[email protected]> Cc: Willem de Bruijn <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-399
int udp_recvmsg(struct sock *sk, struct msghdr *msg, size_t len, int noblock, int flags, int *addr_len) { struct inet_sock *inet = inet_sk(sk); DECLARE_SOCKADDR(struct sockaddr_in *, sin, msg->msg_name); struct sk_buff *skb; unsigned int ulen, copied; int peeked, off = 0; int err; int is_udplite = IS_UDPLITE(sk); bool slow; if (flags & MSG_ERRQUEUE) return ip_recv_error(sk, msg, len, addr_len); try_again: skb = __skb_recv_datagram(sk, flags | (noblock ? MSG_DONTWAIT : 0), &peeked, &off, &err); if (!skb) goto out; ulen = skb->len - sizeof(struct udphdr); copied = len; if (copied > ulen) copied = ulen; else if (copied < ulen) msg->msg_flags |= MSG_TRUNC; /* * If checksum is needed at all, try to do it while copying the * data. If the data is truncated, or if we only want a partial * coverage checksum (UDP-Lite), do it before the copy. */ if (copied < ulen || UDP_SKB_CB(skb)->partial_cov) { if (udp_lib_checksum_complete(skb)) goto csum_copy_err; } if (skb_csum_unnecessary(skb)) err = skb_copy_datagram_msg(skb, sizeof(struct udphdr), msg, copied); else { err = skb_copy_and_csum_datagram_msg(skb, sizeof(struct udphdr), msg); if (err == -EINVAL) goto csum_copy_err; } if (unlikely(err)) { trace_kfree_skb(skb, udp_recvmsg); if (!peeked) { atomic_inc(&sk->sk_drops); UDP_INC_STATS_USER(sock_net(sk), UDP_MIB_INERRORS, is_udplite); } goto out_free; } if (!peeked) UDP_INC_STATS_USER(sock_net(sk), UDP_MIB_INDATAGRAMS, is_udplite); sock_recv_ts_and_drops(msg, sk, skb); /* Copy the address. */ if (sin) { sin->sin_family = AF_INET; sin->sin_port = udp_hdr(skb)->source; sin->sin_addr.s_addr = ip_hdr(skb)->saddr; memset(sin->sin_zero, 0, sizeof(sin->sin_zero)); *addr_len = sizeof(*sin); } if (inet->cmsg_flags) ip_cmsg_recv_offset(msg, skb, sizeof(struct udphdr)); err = copied; if (flags & MSG_TRUNC) err = ulen; out_free: skb_free_datagram_locked(sk, skb); out: return err; csum_copy_err: slow = lock_sock_fast(sk); if (!skb_kill_datagram(sk, skb, flags)) { UDP_INC_STATS_USER(sock_net(sk), UDP_MIB_CSUMERRORS, is_udplite); UDP_INC_STATS_USER(sock_net(sk), UDP_MIB_INERRORS, is_udplite); } unlock_sock_fast(sk, slow); /* starting over for a new packet, but check if we need to yield */ cond_resched(); msg->msg_flags &= ~MSG_TRUNC; goto try_again; }
166,596
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 DrawingBuffer::RestoreAllState() { client_->DrawingBufferClientRestoreScissorTest(); client_->DrawingBufferClientRestoreMaskAndClearValues(); client_->DrawingBufferClientRestorePixelPackAlignment(); client_->DrawingBufferClientRestoreTexture2DBinding(); client_->DrawingBufferClientRestoreRenderbufferBinding(); client_->DrawingBufferClientRestoreFramebufferBinding(); client_->DrawingBufferClientRestorePixelUnpackBufferBinding(); } Commit Message: Reset ES3 pixel pack parameters and PIXEL_PACK_BUFFER binding in DrawingBuffer before ReadPixels() and recover them later. BUG=740603 TEST=new conformance test [email protected],[email protected] Change-Id: I3ea54c6cc34f34e249f7c8b9f792d93c5e1958f4 Reviewed-on: https://chromium-review.googlesource.com/570840 Reviewed-by: Antoine Labour <[email protected]> Reviewed-by: Kenneth Russell <[email protected]> Commit-Queue: Zhenyao Mo <[email protected]> Cr-Commit-Position: refs/heads/master@{#486518} CWE ID: CWE-119
void DrawingBuffer::RestoreAllState() { client_->DrawingBufferClientRestoreScissorTest(); client_->DrawingBufferClientRestoreMaskAndClearValues(); client_->DrawingBufferClientRestorePixelPackParameters(); client_->DrawingBufferClientRestoreTexture2DBinding(); client_->DrawingBufferClientRestoreRenderbufferBinding(); client_->DrawingBufferClientRestoreFramebufferBinding(); client_->DrawingBufferClientRestorePixelUnpackBufferBinding(); client_->DrawingBufferClientRestorePixelPackBufferBinding(); }
172,295
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: FileEntrySync* DirectoryEntrySync::getFile(const String& path, const Dictionary& options, ExceptionState& exceptionState) { FileSystemFlags flags(options); RefPtr<EntrySyncCallbackHelper> helper = EntrySyncCallbackHelper::create(); m_fileSystem->getFile(this, path, flags, helper->successCallback(), helper->errorCallback(), DOMFileSystemBase::Synchronous); return static_cast<FileEntrySync*>(helper->getResult(exceptionState)); } 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
FileEntrySync* DirectoryEntrySync::getFile(const String& path, const Dictionary& options, ExceptionState& exceptionState) { FileSystemFlags flags(options); EntrySyncCallbackHelper* helper = EntrySyncCallbackHelper::create(); m_fileSystem->getFile(this, path, flags, helper->successCallback(), helper->errorCallback(), DOMFileSystemBase::Synchronous); return static_cast<FileEntrySync*>(helper->getResult(exceptionState)); }
171,418
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 install_process_keyring(void) { struct cred *new; int ret; new = prepare_creds(); if (!new) return -ENOMEM; ret = install_process_keyring_to_cred(new); if (ret < 0) { abort_creds(new); return ret != -EEXIST ? ret : 0; } return commit_creds(new); } Commit Message: KEYS: fix keyctl_set_reqkey_keyring() to not leak thread keyrings This fixes CVE-2017-7472. Running the following program as an unprivileged user exhausts kernel memory by leaking thread keyrings: #include <keyutils.h> int main() { for (;;) keyctl_set_reqkey_keyring(KEY_REQKEY_DEFL_THREAD_KEYRING); } Fix it by only creating a new thread keyring if there wasn't one before. To make things more consistent, make install_thread_keyring_to_cred() and install_process_keyring_to_cred() both return 0 if the corresponding keyring is already present. Fixes: d84f4f992cbd ("CRED: Inaugurate COW credentials") Cc: [email protected] # 2.6.29+ Signed-off-by: Eric Biggers <[email protected]> Signed-off-by: David Howells <[email protected]> CWE ID: CWE-404
static int install_process_keyring(void) { struct cred *new; int ret; new = prepare_creds(); if (!new) return -ENOMEM; ret = install_process_keyring_to_cred(new); if (ret < 0) { abort_creds(new); return ret; } return commit_creds(new); }
168,274
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 finalizeStreamTask(void* context) { OwnPtr<BlobRegistryContext> blobRegistryContext = adoptPtr(static_cast<BlobRegistryContext*>(context)); blobRegistry().finalizeStream(blobRegistryContext->url); } Commit Message: Remove BlobRegistry indirection since there is only one implementation. BUG= Review URL: https://chromiumcodereview.appspot.com/15851008 git-svn-id: svn://svn.chromium.org/blink/trunk@152746 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID:
static void finalizeStreamTask(void* context) { OwnPtr<BlobRegistryContext> blobRegistryContext = adoptPtr(static_cast<BlobRegistryContext*>(context)); if (WebBlobRegistry* registry = blobRegistry()) registry->finalizeStream(blobRegistryContext->url); }
170,683
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 ExtensionViewGuest::NavigateGuest(const std::string& src, bool force_navigation) { GURL url = extension_url_.Resolve(src); bool url_not_allowed = (url != GURL(url::kAboutBlankURL)) && (url.GetOrigin() != extension_url_.GetOrigin()); if (!url.is_valid() || url_not_allowed) return NavigateGuest(url::kAboutBlankURL, true /* force_navigation */); if (!force_navigation && (url_ == url)) return false; web_contents()->GetRenderProcessHost()->FilterURL(false, &url); web_contents()->GetController().LoadURL(url, content::Referrer(), ui::PAGE_TRANSITION_AUTO_TOPLEVEL, std::string()); url_ = url; return true; } Commit Message: Make extensions use a correct same-origin check. GURL::GetOrigin does not do the right thing for all types of URLs. BUG=573317 Review URL: https://codereview.chromium.org/1658913002 Cr-Commit-Position: refs/heads/master@{#373381} CWE ID: CWE-284
bool ExtensionViewGuest::NavigateGuest(const std::string& src, bool force_navigation) { GURL url = extension_url_.Resolve(src); bool url_not_allowed = url != GURL(url::kAboutBlankURL) && !url::IsSameOriginWith(url, extension_url_); if (!url.is_valid() || url_not_allowed) return NavigateGuest(url::kAboutBlankURL, true /* force_navigation */); if (!force_navigation && (url_ == url)) return false; web_contents()->GetRenderProcessHost()->FilterURL(false, &url); web_contents()->GetController().LoadURL(url, content::Referrer(), ui::PAGE_TRANSITION_AUTO_TOPLEVEL, std::string()); url_ = url; return true; }
172,284
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 f_parser (lua_State *L, void *ud) { int i; Proto *tf; Closure *cl; struct SParser *p = cast(struct SParser *, ud); int c = luaZ_lookahead(p->z); luaC_checkGC(L); tf = ((c == LUA_SIGNATURE[0]) ? luaU_undump : luaY_parser)(L, p->z, &p->buff, p->name); cl = luaF_newLclosure(L, tf->nups, hvalue(gt(L))); cl->l.p = tf; for (i = 0; i < tf->nups; i++) /* initialize eventual upvalues */ cl->l.upvals[i] = luaF_newupval(L); setclvalue(L, L->top, cl); incr_top(L); } Commit Message: disable loading lua bytecode CWE ID: CWE-17
static void f_parser (lua_State *L, void *ud) { int i; Proto *tf; Closure *cl; struct SParser *p = cast(struct SParser *, ud); int c = luaZ_lookahead(p->z); luaC_checkGC(L); tf = (luaY_parser)(L, p->z, &p->buff, p->name); cl = luaF_newLclosure(L, tf->nups, hvalue(gt(L))); cl->l.p = tf; for (i = 0; i < tf->nups; i++) /* initialize eventual upvalues */ cl->l.upvals[i] = luaF_newupval(L); setclvalue(L, L->top, cl); incr_top(L); }
166,613
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: virtual void SetUp() { InitializeConfig(); SetMode(GET_PARAM(1)); set_cpu_used_ = GET_PARAM(2); } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119
virtual void SetUp() { InitializeConfig(); SetMode(encoding_mode_); if (encoding_mode_ != ::libvpx_test::kRealTime) { cfg_.g_lag_in_frames = 25; cfg_.rc_end_usage = VPX_VBR; } else { cfg_.g_lag_in_frames = 0; cfg_.rc_end_usage = VPX_CBR; } } virtual void BeginPassHook(unsigned int /*pass*/) { min_psnr_ = kMaxPSNR; }
174,514
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 nsc_rle_decode(BYTE* in, BYTE* out, UINT32 originalSize) { UINT32 len; UINT32 left; BYTE value; left = originalSize; while (left > 4) { value = *in++; if (left == 5) { *out++ = value; left--; } else if (value == *in) { in++; if (*in < 0xFF) { len = (UINT32) * in++; len += 2; } else { in++; len = *((UINT32*) in); in += 4; } FillMemory(out, len, value); out += len; left -= len; } else { *out++ = value; left--; } } *((UINT32*)out) = *((UINT32*)in); } Commit Message: Fixed CVE-2018-8788 Thanks to Eyal Itkin from Check Point Software Technologies. CWE ID: CWE-787
static void nsc_rle_decode(BYTE* in, BYTE* out, UINT32 originalSize) static BOOL nsc_rle_decode(BYTE* in, BYTE* out, UINT32 outSize, UINT32 originalSize) { UINT32 len; UINT32 left; BYTE value; left = originalSize; while (left > 4) { value = *in++; if (left == 5) { if (outSize < 1) return FALSE; outSize--; *out++ = value; left--; } else if (value == *in) { in++; if (*in < 0xFF) { len = (UINT32) * in++; len += 2; } else { in++; len = *((UINT32*) in); in += 4; } if (outSize < len) return FALSE; outSize -= len; FillMemory(out, len, value); out += len; left -= len; } else { if (outSize < 1) return FALSE; outSize--; *out++ = value; left--; } } if ((outSize < 4) || (left < 4)) return FALSE; memcpy(out, in, 4); return TRUE; }
169,284
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 get_rock_ridge_filename(struct iso_directory_record *de, char *retname, struct inode *inode) { struct rock_state rs; struct rock_ridge *rr; int sig; int retnamlen = 0; int truncate = 0; int ret = 0; if (!ISOFS_SB(inode->i_sb)->s_rock) return 0; *retname = 0; init_rock_state(&rs, inode); setup_rock_ridge(de, inode, &rs); repeat: while (rs.len > 2) { /* There may be one byte for padding somewhere */ rr = (struct rock_ridge *)rs.chr; /* * Ignore rock ridge info if rr->len is out of range, but * don't return -EIO because that would make the file * invisible. */ if (rr->len < 3) goto out; /* Something got screwed up here */ sig = isonum_721(rs.chr); if (rock_check_overflow(&rs, sig)) goto eio; rs.chr += rr->len; rs.len -= rr->len; /* * As above, just ignore the rock ridge info if rr->len * is bogus. */ if (rs.len < 0) goto out; /* Something got screwed up here */ switch (sig) { case SIG('R', 'R'): if ((rr->u.RR.flags[0] & RR_NM) == 0) goto out; break; case SIG('S', 'P'): if (check_sp(rr, inode)) goto out; break; case SIG('C', 'E'): rs.cont_extent = isonum_733(rr->u.CE.extent); rs.cont_offset = isonum_733(rr->u.CE.offset); rs.cont_size = isonum_733(rr->u.CE.size); break; case SIG('N', 'M'): if (truncate) break; if (rr->len < 5) break; /* * If the flags are 2 or 4, this indicates '.' or '..'. * We don't want to do anything with this, because it * screws up the code that calls us. We don't really * care anyways, since we can just use the non-RR * name. */ if (rr->u.NM.flags & 6) break; if (rr->u.NM.flags & ~1) { printk("Unsupported NM flag settings (%d)\n", rr->u.NM.flags); break; } if ((strlen(retname) + rr->len - 5) >= 254) { truncate = 1; break; } strncat(retname, rr->u.NM.name, rr->len - 5); retnamlen += rr->len - 5; break; case SIG('R', 'E'): kfree(rs.buffer); return -1; default: break; } } ret = rock_continue(&rs); if (ret == 0) goto repeat; if (ret == 1) return retnamlen; /* If 0, this file did not have a NM field */ out: kfree(rs.buffer); return ret; eio: ret = -EIO; goto out; } Commit Message: get_rock_ridge_filename(): handle malformed NM entries Payloads of NM entries are not supposed to contain NUL. When we run into such, only the part prior to the first NUL goes into the concatenation (i.e. the directory entry name being encoded by a bunch of NM entries). We do stop when the amount collected so far + the claimed amount in the current NM entry exceed 254. So far, so good, but what we return as the total length is the sum of *claimed* sizes, not the actual amount collected. And that can grow pretty large - not unlimited, since you'd need to put CE entries in between to be able to get more than the maximum that could be contained in one isofs directory entry / continuation chunk and we are stop once we'd encountered 32 CEs, but you can get about 8Kb easily. And that's what will be passed to readdir callback as the name length. 8Kb __copy_to_user() from a buffer allocated by __get_free_page() Cc: [email protected] # 0.98pl6+ (yes, really) Signed-off-by: Al Viro <[email protected]> CWE ID: CWE-200
int get_rock_ridge_filename(struct iso_directory_record *de, char *retname, struct inode *inode) { struct rock_state rs; struct rock_ridge *rr; int sig; int retnamlen = 0; int truncate = 0; int ret = 0; char *p; int len; if (!ISOFS_SB(inode->i_sb)->s_rock) return 0; *retname = 0; init_rock_state(&rs, inode); setup_rock_ridge(de, inode, &rs); repeat: while (rs.len > 2) { /* There may be one byte for padding somewhere */ rr = (struct rock_ridge *)rs.chr; /* * Ignore rock ridge info if rr->len is out of range, but * don't return -EIO because that would make the file * invisible. */ if (rr->len < 3) goto out; /* Something got screwed up here */ sig = isonum_721(rs.chr); if (rock_check_overflow(&rs, sig)) goto eio; rs.chr += rr->len; rs.len -= rr->len; /* * As above, just ignore the rock ridge info if rr->len * is bogus. */ if (rs.len < 0) goto out; /* Something got screwed up here */ switch (sig) { case SIG('R', 'R'): if ((rr->u.RR.flags[0] & RR_NM) == 0) goto out; break; case SIG('S', 'P'): if (check_sp(rr, inode)) goto out; break; case SIG('C', 'E'): rs.cont_extent = isonum_733(rr->u.CE.extent); rs.cont_offset = isonum_733(rr->u.CE.offset); rs.cont_size = isonum_733(rr->u.CE.size); break; case SIG('N', 'M'): if (truncate) break; if (rr->len < 5) break; /* * If the flags are 2 or 4, this indicates '.' or '..'. * We don't want to do anything with this, because it * screws up the code that calls us. We don't really * care anyways, since we can just use the non-RR * name. */ if (rr->u.NM.flags & 6) break; if (rr->u.NM.flags & ~1) { printk("Unsupported NM flag settings (%d)\n", rr->u.NM.flags); break; } len = rr->len - 5; if (retnamlen + len >= 254) { truncate = 1; break; } p = memchr(rr->u.NM.name, '\0', len); if (unlikely(p)) len = p - rr->u.NM.name; memcpy(retname + retnamlen, rr->u.NM.name, len); retnamlen += len; retname[retnamlen] = '\0'; break; case SIG('R', 'E'): kfree(rs.buffer); return -1; default: break; } } ret = rock_continue(&rs); if (ret == 0) goto repeat; if (ret == 1) return retnamlen; /* If 0, this file did not have a NM field */ out: kfree(rs.buffer); return ret; eio: ret = -EIO; goto out; }
167,224
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 do_check(struct bpf_verifier_env *env) { struct bpf_verifier_state *state = &env->cur_state; struct bpf_insn *insns = env->prog->insnsi; struct bpf_reg_state *regs = state->regs; int insn_cnt = env->prog->len; int insn_idx, prev_insn_idx = 0; int insn_processed = 0; bool do_print_state = false; init_reg_state(regs); insn_idx = 0; env->varlen_map_value_access = false; for (;;) { struct bpf_insn *insn; u8 class; int err; if (insn_idx >= insn_cnt) { verbose("invalid insn idx %d insn_cnt %d\n", insn_idx, insn_cnt); return -EFAULT; } insn = &insns[insn_idx]; class = BPF_CLASS(insn->code); if (++insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) { verbose("BPF program is too large. Processed %d insn\n", insn_processed); return -E2BIG; } err = is_state_visited(env, insn_idx); if (err < 0) return err; if (err == 1) { /* found equivalent state, can prune the search */ if (log_level) { if (do_print_state) verbose("\nfrom %d to %d: safe\n", prev_insn_idx, insn_idx); else verbose("%d: safe\n", insn_idx); } goto process_bpf_exit; } if (log_level && do_print_state) { verbose("\nfrom %d to %d:", prev_insn_idx, insn_idx); print_verifier_state(&env->cur_state); do_print_state = false; } if (log_level) { verbose("%d: ", insn_idx); print_bpf_insn(insn); } err = ext_analyzer_insn_hook(env, insn_idx, prev_insn_idx); if (err) return err; if (class == BPF_ALU || class == BPF_ALU64) { err = check_alu_op(env, insn); if (err) return err; } else if (class == BPF_LDX) { enum bpf_reg_type *prev_src_type, src_reg_type; /* check for reserved fields is already done */ /* check src operand */ err = check_reg_arg(regs, insn->src_reg, SRC_OP); if (err) return err; err = check_reg_arg(regs, insn->dst_reg, DST_OP_NO_MARK); if (err) return err; src_reg_type = regs[insn->src_reg].type; /* check that memory (src_reg + off) is readable, * the state of dst_reg will be updated by this func */ err = check_mem_access(env, insn->src_reg, insn->off, BPF_SIZE(insn->code), BPF_READ, insn->dst_reg); if (err) return err; if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) { insn_idx++; continue; } prev_src_type = &env->insn_aux_data[insn_idx].ptr_type; if (*prev_src_type == NOT_INIT) { /* saw a valid insn * dst_reg = *(u32 *)(src_reg + off) * save type to validate intersecting paths */ *prev_src_type = src_reg_type; } else if (src_reg_type != *prev_src_type && (src_reg_type == PTR_TO_CTX || *prev_src_type == PTR_TO_CTX)) { /* ABuser program is trying to use the same insn * dst_reg = *(u32*) (src_reg + off) * with different pointer types: * src_reg == ctx in one branch and * src_reg == stack|map in some other branch. * Reject it. */ verbose("same insn cannot be used with different pointers\n"); return -EINVAL; } } else if (class == BPF_STX) { enum bpf_reg_type *prev_dst_type, dst_reg_type; if (BPF_MODE(insn->code) == BPF_XADD) { err = check_xadd(env, insn); if (err) return err; insn_idx++; continue; } /* check src1 operand */ err = check_reg_arg(regs, insn->src_reg, SRC_OP); if (err) return err; /* check src2 operand */ err = check_reg_arg(regs, insn->dst_reg, SRC_OP); if (err) return err; dst_reg_type = regs[insn->dst_reg].type; /* check that memory (dst_reg + off) is writeable */ err = check_mem_access(env, insn->dst_reg, insn->off, BPF_SIZE(insn->code), BPF_WRITE, insn->src_reg); if (err) return err; prev_dst_type = &env->insn_aux_data[insn_idx].ptr_type; if (*prev_dst_type == NOT_INIT) { *prev_dst_type = dst_reg_type; } else if (dst_reg_type != *prev_dst_type && (dst_reg_type == PTR_TO_CTX || *prev_dst_type == PTR_TO_CTX)) { verbose("same insn cannot be used with different pointers\n"); return -EINVAL; } } else if (class == BPF_ST) { if (BPF_MODE(insn->code) != BPF_MEM || insn->src_reg != BPF_REG_0) { verbose("BPF_ST uses reserved fields\n"); return -EINVAL; } /* check src operand */ err = check_reg_arg(regs, insn->dst_reg, SRC_OP); if (err) return err; /* check that memory (dst_reg + off) is writeable */ err = check_mem_access(env, insn->dst_reg, insn->off, BPF_SIZE(insn->code), BPF_WRITE, -1); if (err) return err; } else if (class == BPF_JMP) { u8 opcode = BPF_OP(insn->code); if (opcode == BPF_CALL) { if (BPF_SRC(insn->code) != BPF_K || insn->off != 0 || insn->src_reg != BPF_REG_0 || insn->dst_reg != BPF_REG_0) { verbose("BPF_CALL uses reserved fields\n"); return -EINVAL; } err = check_call(env, insn->imm, insn_idx); if (err) return err; } else if (opcode == BPF_JA) { if (BPF_SRC(insn->code) != BPF_K || insn->imm != 0 || insn->src_reg != BPF_REG_0 || insn->dst_reg != BPF_REG_0) { verbose("BPF_JA uses reserved fields\n"); return -EINVAL; } insn_idx += insn->off + 1; continue; } else if (opcode == BPF_EXIT) { if (BPF_SRC(insn->code) != BPF_K || insn->imm != 0 || insn->src_reg != BPF_REG_0 || insn->dst_reg != BPF_REG_0) { verbose("BPF_EXIT uses reserved fields\n"); return -EINVAL; } /* eBPF calling convetion is such that R0 is used * to return the value from eBPF program. * Make sure that it's readable at this time * of bpf_exit, which means that program wrote * something into it earlier */ err = check_reg_arg(regs, BPF_REG_0, SRC_OP); if (err) return err; if (is_pointer_value(env, BPF_REG_0)) { verbose("R0 leaks addr as return value\n"); return -EACCES; } process_bpf_exit: insn_idx = pop_stack(env, &prev_insn_idx); if (insn_idx < 0) { break; } else { do_print_state = true; continue; } } else { err = check_cond_jmp_op(env, insn, &insn_idx); if (err) return err; } } else if (class == BPF_LD) { u8 mode = BPF_MODE(insn->code); if (mode == BPF_ABS || mode == BPF_IND) { err = check_ld_abs(env, insn); if (err) return err; } else if (mode == BPF_IMM) { err = check_ld_imm(env, insn); if (err) return err; insn_idx++; } else { verbose("invalid BPF_LD mode\n"); return -EINVAL; } reset_reg_range_values(regs, insn->dst_reg); } else { verbose("unknown insn class %d\n", class); return -EINVAL; } insn_idx++; } verbose("processed %d insns\n", insn_processed); return 0; } Commit Message: bpf: don't let ldimm64 leak map addresses on unprivileged The patch fixes two things at once: 1) It checks the env->allow_ptr_leaks and only prints the map address to the log if we have the privileges to do so, otherwise it just dumps 0 as we would when kptr_restrict is enabled on %pK. Given the latter is off by default and not every distro sets it, I don't want to rely on this, hence the 0 by default for unprivileged. 2) Printing of ldimm64 in the verifier log is currently broken in that we don't print the full immediate, but only the 32 bit part of the first insn part for ldimm64. Thus, fix this up as well; it's okay to access, since we verified all ldimm64 earlier already (including just constants) through replace_map_fd_with_map_ptr(). Fixes: 1be7f75d1668 ("bpf: enable non-root eBPF programs") Fixes: cbd357008604 ("bpf: verifier (add ability to receive verification log)") Reported-by: Jann Horn <[email protected]> Signed-off-by: Daniel Borkmann <[email protected]> Acked-by: Alexei Starovoitov <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-200
static int do_check(struct bpf_verifier_env *env) { struct bpf_verifier_state *state = &env->cur_state; struct bpf_insn *insns = env->prog->insnsi; struct bpf_reg_state *regs = state->regs; int insn_cnt = env->prog->len; int insn_idx, prev_insn_idx = 0; int insn_processed = 0; bool do_print_state = false; init_reg_state(regs); insn_idx = 0; env->varlen_map_value_access = false; for (;;) { struct bpf_insn *insn; u8 class; int err; if (insn_idx >= insn_cnt) { verbose("invalid insn idx %d insn_cnt %d\n", insn_idx, insn_cnt); return -EFAULT; } insn = &insns[insn_idx]; class = BPF_CLASS(insn->code); if (++insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) { verbose("BPF program is too large. Processed %d insn\n", insn_processed); return -E2BIG; } err = is_state_visited(env, insn_idx); if (err < 0) return err; if (err == 1) { /* found equivalent state, can prune the search */ if (log_level) { if (do_print_state) verbose("\nfrom %d to %d: safe\n", prev_insn_idx, insn_idx); else verbose("%d: safe\n", insn_idx); } goto process_bpf_exit; } if (log_level && do_print_state) { verbose("\nfrom %d to %d:", prev_insn_idx, insn_idx); print_verifier_state(&env->cur_state); do_print_state = false; } if (log_level) { verbose("%d: ", insn_idx); print_bpf_insn(env, insn); } err = ext_analyzer_insn_hook(env, insn_idx, prev_insn_idx); if (err) return err; if (class == BPF_ALU || class == BPF_ALU64) { err = check_alu_op(env, insn); if (err) return err; } else if (class == BPF_LDX) { enum bpf_reg_type *prev_src_type, src_reg_type; /* check for reserved fields is already done */ /* check src operand */ err = check_reg_arg(regs, insn->src_reg, SRC_OP); if (err) return err; err = check_reg_arg(regs, insn->dst_reg, DST_OP_NO_MARK); if (err) return err; src_reg_type = regs[insn->src_reg].type; /* check that memory (src_reg + off) is readable, * the state of dst_reg will be updated by this func */ err = check_mem_access(env, insn->src_reg, insn->off, BPF_SIZE(insn->code), BPF_READ, insn->dst_reg); if (err) return err; if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) { insn_idx++; continue; } prev_src_type = &env->insn_aux_data[insn_idx].ptr_type; if (*prev_src_type == NOT_INIT) { /* saw a valid insn * dst_reg = *(u32 *)(src_reg + off) * save type to validate intersecting paths */ *prev_src_type = src_reg_type; } else if (src_reg_type != *prev_src_type && (src_reg_type == PTR_TO_CTX || *prev_src_type == PTR_TO_CTX)) { /* ABuser program is trying to use the same insn * dst_reg = *(u32*) (src_reg + off) * with different pointer types: * src_reg == ctx in one branch and * src_reg == stack|map in some other branch. * Reject it. */ verbose("same insn cannot be used with different pointers\n"); return -EINVAL; } } else if (class == BPF_STX) { enum bpf_reg_type *prev_dst_type, dst_reg_type; if (BPF_MODE(insn->code) == BPF_XADD) { err = check_xadd(env, insn); if (err) return err; insn_idx++; continue; } /* check src1 operand */ err = check_reg_arg(regs, insn->src_reg, SRC_OP); if (err) return err; /* check src2 operand */ err = check_reg_arg(regs, insn->dst_reg, SRC_OP); if (err) return err; dst_reg_type = regs[insn->dst_reg].type; /* check that memory (dst_reg + off) is writeable */ err = check_mem_access(env, insn->dst_reg, insn->off, BPF_SIZE(insn->code), BPF_WRITE, insn->src_reg); if (err) return err; prev_dst_type = &env->insn_aux_data[insn_idx].ptr_type; if (*prev_dst_type == NOT_INIT) { *prev_dst_type = dst_reg_type; } else if (dst_reg_type != *prev_dst_type && (dst_reg_type == PTR_TO_CTX || *prev_dst_type == PTR_TO_CTX)) { verbose("same insn cannot be used with different pointers\n"); return -EINVAL; } } else if (class == BPF_ST) { if (BPF_MODE(insn->code) != BPF_MEM || insn->src_reg != BPF_REG_0) { verbose("BPF_ST uses reserved fields\n"); return -EINVAL; } /* check src operand */ err = check_reg_arg(regs, insn->dst_reg, SRC_OP); if (err) return err; /* check that memory (dst_reg + off) is writeable */ err = check_mem_access(env, insn->dst_reg, insn->off, BPF_SIZE(insn->code), BPF_WRITE, -1); if (err) return err; } else if (class == BPF_JMP) { u8 opcode = BPF_OP(insn->code); if (opcode == BPF_CALL) { if (BPF_SRC(insn->code) != BPF_K || insn->off != 0 || insn->src_reg != BPF_REG_0 || insn->dst_reg != BPF_REG_0) { verbose("BPF_CALL uses reserved fields\n"); return -EINVAL; } err = check_call(env, insn->imm, insn_idx); if (err) return err; } else if (opcode == BPF_JA) { if (BPF_SRC(insn->code) != BPF_K || insn->imm != 0 || insn->src_reg != BPF_REG_0 || insn->dst_reg != BPF_REG_0) { verbose("BPF_JA uses reserved fields\n"); return -EINVAL; } insn_idx += insn->off + 1; continue; } else if (opcode == BPF_EXIT) { if (BPF_SRC(insn->code) != BPF_K || insn->imm != 0 || insn->src_reg != BPF_REG_0 || insn->dst_reg != BPF_REG_0) { verbose("BPF_EXIT uses reserved fields\n"); return -EINVAL; } /* eBPF calling convetion is such that R0 is used * to return the value from eBPF program. * Make sure that it's readable at this time * of bpf_exit, which means that program wrote * something into it earlier */ err = check_reg_arg(regs, BPF_REG_0, SRC_OP); if (err) return err; if (is_pointer_value(env, BPF_REG_0)) { verbose("R0 leaks addr as return value\n"); return -EACCES; } process_bpf_exit: insn_idx = pop_stack(env, &prev_insn_idx); if (insn_idx < 0) { break; } else { do_print_state = true; continue; } } else { err = check_cond_jmp_op(env, insn, &insn_idx); if (err) return err; } } else if (class == BPF_LD) { u8 mode = BPF_MODE(insn->code); if (mode == BPF_ABS || mode == BPF_IND) { err = check_ld_abs(env, insn); if (err) return err; } else if (mode == BPF_IMM) { err = check_ld_imm(env, insn); if (err) return err; insn_idx++; } else { verbose("invalid BPF_LD mode\n"); return -EINVAL; } reset_reg_range_values(regs, insn->dst_reg); } else { verbose("unknown insn class %d\n", class); return -EINVAL; } insn_idx++; } verbose("processed %d insns\n", insn_processed); return 0; }
168,120
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static bool ldb_dn_explode(struct ldb_dn *dn) { char *p, *ex_name = NULL, *ex_value = NULL, *data, *d, *dt, *t; bool trim = true; bool in_extended = true; bool in_ex_name = false; bool in_ex_value = false; bool in_attr = false; bool in_value = false; bool in_quote = false; bool is_oid = false; bool escape = false; unsigned int x; size_t l = 0; int ret; char *parse_dn; bool is_index; if ( ! dn || dn->invalid) return false; if (dn->components) { return true; } if (dn->ext_linearized) { parse_dn = dn->ext_linearized; } else { parse_dn = dn->linearized; } if ( ! parse_dn ) { return false; } is_index = (strncmp(parse_dn, "DN=@INDEX:", 10) == 0); /* Empty DNs */ if (parse_dn[0] == '\0') { return true; } /* Special DNs case */ if (dn->special) { return true; } /* make sure we free this if allocated previously before replacing */ LDB_FREE(dn->components); dn->comp_num = 0; LDB_FREE(dn->ext_components); dn->ext_comp_num = 0; /* in the common case we have 3 or more components */ /* make sure all components are zeroed, other functions depend on it */ dn->components = talloc_zero_array(dn, struct ldb_dn_component, 3); if ( ! dn->components) { return false; } /* Components data space is allocated here once */ data = talloc_array(dn->components, char, strlen(parse_dn) + 1); if (!data) { return false; } p = parse_dn; t = NULL; d = dt = data; while (*p) { if (in_extended) { if (!in_ex_name && !in_ex_value) { if (p[0] == '<') { p++; ex_name = d; in_ex_name = true; continue; } else if (p[0] == '\0') { p++; continue; } else { in_extended = false; in_attr = true; dt = d; continue; } } if (in_ex_name && *p == '=') { *d++ = '\0'; p++; ex_value = d; in_ex_name = false; in_ex_value = true; continue; } if (in_ex_value && *p == '>') { const struct ldb_dn_extended_syntax *ext_syntax; struct ldb_val ex_val = { .data = (uint8_t *)ex_value, .length = d - ex_value }; *d++ = '\0'; p++; in_ex_value = false; /* Process name and ex_value */ dn->ext_components = talloc_realloc(dn, dn->ext_components, struct ldb_dn_ext_component, dn->ext_comp_num + 1); if ( ! dn->ext_components) { /* ouch ! */ goto failed; } ext_syntax = ldb_dn_extended_syntax_by_name(dn->ldb, ex_name); if (!ext_syntax) { /* We don't know about this type of extended DN */ goto failed; } dn->ext_components[dn->ext_comp_num].name = talloc_strdup(dn->ext_components, ex_name); if (!dn->ext_components[dn->ext_comp_num].name) { /* ouch */ goto failed; } ret = ext_syntax->read_fn(dn->ldb, dn->ext_components, &ex_val, &dn->ext_components[dn->ext_comp_num].value); if (ret != LDB_SUCCESS) { ldb_dn_mark_invalid(dn); goto failed; } dn->ext_comp_num++; if (*p == '\0') { /* We have reached the end (extended component only)! */ talloc_free(data); return true; } else if (*p == ';') { p++; continue; } else { ldb_dn_mark_invalid(dn); goto failed; } } *d++ = *p++; continue; } if (in_attr) { if (trim) { if (*p == ' ') { p++; continue; } /* first char */ trim = false; if (!isascii(*p)) { /* attr names must be ascii only */ ldb_dn_mark_invalid(dn); goto failed; } if (isdigit(*p)) { is_oid = true; } else if ( ! isalpha(*p)) { /* not a digit nor an alpha, * invalid attribute name */ ldb_dn_mark_invalid(dn); goto failed; } /* Copy this character across from parse_dn, * now we have trimmed out spaces */ *d++ = *p++; continue; } if (*p == ' ') { p++; /* valid only if we are at the end */ trim = true; continue; } if (trim && (*p != '=')) { /* spaces/tabs are not allowed */ ldb_dn_mark_invalid(dn); goto failed; } if (*p == '=') { /* attribute terminated */ in_attr = false; in_value = true; trim = true; l = 0; /* Terminate this string in d * (which is a copy of parse_dn * with spaces trimmed) */ *d++ = '\0'; dn->components[dn->comp_num].name = talloc_strdup(dn->components, dt); if ( ! dn->components[dn->comp_num].name) { /* ouch */ goto failed; } dt = d; p++; continue; } if (!isascii(*p)) { /* attr names must be ascii only */ ldb_dn_mark_invalid(dn); goto failed; } if (is_oid && ( ! (isdigit(*p) || (*p == '.')))) { /* not a digit nor a dot, * invalid attribute oid */ ldb_dn_mark_invalid(dn); goto failed; } else if ( ! (isalpha(*p) || isdigit(*p) || (*p == '-'))) { /* not ALPHA, DIGIT or HYPHEN */ ldb_dn_mark_invalid(dn); goto failed; } *d++ = *p++; continue; } if (in_value) { if (in_quote) { if (*p == '\"') { if (p[-1] != '\\') { p++; in_quote = false; continue; } } *d++ = *p++; l++; continue; } if (trim) { if (*p == ' ') { p++; continue; } /* first char */ trim = false; if (*p == '\"') { in_quote = true; p++; continue; } } switch (*p) { /* TODO: support ber encoded values case '#': */ case ',': if (escape) { *d++ = *p++; l++; escape = false; continue; } /* ok found value terminator */ if ( t ) { /* trim back */ d -= (p - t); l -= (p - t); } in_attr = true; in_value = false; trim = true; p++; *d++ = '\0'; dn->components[dn->comp_num].value.data = (uint8_t *)talloc_strdup(dn->components, dt); dn->components[dn->comp_num].value.length = l; if ( ! dn->components[dn->comp_num].value.data) { /* ouch ! */ goto failed; } dt = d; dn->components, struct ldb_dn_component, dn->comp_num + 1); if ( ! dn->components) { /* ouch ! */ goto failed; } /* make sure all components are zeroed, other functions depend on this */ memset(&dn->components[dn->comp_num], '\0', sizeof(struct ldb_dn_component)); } continue; case '+': case '=': /* to main compatibility with earlier versions of ldb indexing, we have to accept the base64 encoded binary index values, which contain a '+' or '=' which should normally be escaped */ if (is_index) { if ( t ) t = NULL; *d++ = *p++; l++; break; } /* fall through */ case '\"': case '<': case '>': case ';': /* a string with not escaped specials is invalid (tested) */ if ( ! escape) { ldb_dn_mark_invalid(dn); goto failed; } escape = false; *d++ = *p++; l++; if ( t ) t = NULL; break; case '\\': if ( ! escape) { escape = true; p++; continue; } escape = false; *d++ = *p++; l++; if ( t ) t = NULL; break; default: if (escape) { if (isxdigit(p[0]) && isxdigit(p[1])) { if (sscanf(p, "%02x", &x) != 1) { /* invalid escaping sequence */ ldb_dn_mark_invalid(dn); goto failed; } p += 2; *d++ = (unsigned char)x; } else { *d++ = *p++; } escape = false; l++; if ( t ) t = NULL; break; } if (*p == ' ') { if ( ! t) t = p; } else { if ( t ) t = NULL; } *d++ = *p++; l++; break; } } } Commit Message: CWE ID: CWE-200
static bool ldb_dn_explode(struct ldb_dn *dn) { char *p, *ex_name = NULL, *ex_value = NULL, *data, *d, *dt, *t; bool trim = true; bool in_extended = true; bool in_ex_name = false; bool in_ex_value = false; bool in_attr = false; bool in_value = false; bool in_quote = false; bool is_oid = false; bool escape = false; unsigned int x; size_t l = 0; int ret; char *parse_dn; bool is_index; if ( ! dn || dn->invalid) return false; if (dn->components) { return true; } if (dn->ext_linearized) { parse_dn = dn->ext_linearized; } else { parse_dn = dn->linearized; } if ( ! parse_dn ) { return false; } is_index = (strncmp(parse_dn, "DN=@INDEX:", 10) == 0); /* Empty DNs */ if (parse_dn[0] == '\0') { return true; } /* Special DNs case */ if (dn->special) { return true; } /* make sure we free this if allocated previously before replacing */ LDB_FREE(dn->components); dn->comp_num = 0; LDB_FREE(dn->ext_components); dn->ext_comp_num = 0; /* in the common case we have 3 or more components */ /* make sure all components are zeroed, other functions depend on it */ dn->components = talloc_zero_array(dn, struct ldb_dn_component, 3); if ( ! dn->components) { return false; } /* Components data space is allocated here once */ data = talloc_array(dn->components, char, strlen(parse_dn) + 1); if (!data) { return false; } p = parse_dn; t = NULL; d = dt = data; while (*p) { if (in_extended) { if (!in_ex_name && !in_ex_value) { if (p[0] == '<') { p++; ex_name = d; in_ex_name = true; continue; } else if (p[0] == '\0') { p++; continue; } else { in_extended = false; in_attr = true; dt = d; continue; } } if (in_ex_name && *p == '=') { *d++ = '\0'; p++; ex_value = d; in_ex_name = false; in_ex_value = true; continue; } if (in_ex_value && *p == '>') { const struct ldb_dn_extended_syntax *ext_syntax; struct ldb_val ex_val = { .data = (uint8_t *)ex_value, .length = d - ex_value }; *d++ = '\0'; p++; in_ex_value = false; /* Process name and ex_value */ dn->ext_components = talloc_realloc(dn, dn->ext_components, struct ldb_dn_ext_component, dn->ext_comp_num + 1); if ( ! dn->ext_components) { /* ouch ! */ goto failed; } ext_syntax = ldb_dn_extended_syntax_by_name(dn->ldb, ex_name); if (!ext_syntax) { /* We don't know about this type of extended DN */ goto failed; } dn->ext_components[dn->ext_comp_num].name = talloc_strdup(dn->ext_components, ex_name); if (!dn->ext_components[dn->ext_comp_num].name) { /* ouch */ goto failed; } ret = ext_syntax->read_fn(dn->ldb, dn->ext_components, &ex_val, &dn->ext_components[dn->ext_comp_num].value); if (ret != LDB_SUCCESS) { ldb_dn_mark_invalid(dn); goto failed; } dn->ext_comp_num++; if (*p == '\0') { /* We have reached the end (extended component only)! */ talloc_free(data); return true; } else if (*p == ';') { p++; continue; } else { ldb_dn_mark_invalid(dn); goto failed; } } *d++ = *p++; continue; } if (in_attr) { if (trim) { if (*p == ' ') { p++; continue; } /* first char */ trim = false; if (!isascii(*p)) { /* attr names must be ascii only */ ldb_dn_mark_invalid(dn); goto failed; } if (isdigit(*p)) { is_oid = true; } else if ( ! isalpha(*p)) { /* not a digit nor an alpha, * invalid attribute name */ ldb_dn_mark_invalid(dn); goto failed; } /* Copy this character across from parse_dn, * now we have trimmed out spaces */ *d++ = *p++; continue; } if (*p == ' ') { p++; /* valid only if we are at the end */ trim = true; continue; } if (trim && (*p != '=')) { /* spaces/tabs are not allowed */ ldb_dn_mark_invalid(dn); goto failed; } if (*p == '=') { /* attribute terminated */ in_attr = false; in_value = true; trim = true; l = 0; /* Terminate this string in d * (which is a copy of parse_dn * with spaces trimmed) */ *d++ = '\0'; dn->components[dn->comp_num].name = talloc_strdup(dn->components, dt); if ( ! dn->components[dn->comp_num].name) { /* ouch */ goto failed; } dt = d; p++; continue; } if (!isascii(*p)) { /* attr names must be ascii only */ ldb_dn_mark_invalid(dn); goto failed; } if (is_oid && ( ! (isdigit(*p) || (*p == '.')))) { /* not a digit nor a dot, * invalid attribute oid */ ldb_dn_mark_invalid(dn); goto failed; } else if ( ! (isalpha(*p) || isdigit(*p) || (*p == '-'))) { /* not ALPHA, DIGIT or HYPHEN */ ldb_dn_mark_invalid(dn); goto failed; } *d++ = *p++; continue; } if (in_value) { if (in_quote) { if (*p == '\"') { if (p[-1] != '\\') { p++; in_quote = false; continue; } } *d++ = *p++; l++; continue; } if (trim) { if (*p == ' ') { p++; continue; } /* first char */ trim = false; if (*p == '\"') { in_quote = true; p++; continue; } } switch (*p) { /* TODO: support ber encoded values case '#': */ case ',': if (escape) { *d++ = *p++; l++; escape = false; continue; } /* ok found value terminator */ if ( t ) { /* trim back */ d -= (p - t); l -= (p - t); } in_attr = true; in_value = false; trim = true; p++; *d++ = '\0'; dn->components[dn->comp_num].value.data = \ (uint8_t *)talloc_memdup(dn->components, dt, l + 1); dn->components[dn->comp_num].value.length = l; if ( ! dn->components[dn->comp_num].value.data) { /* ouch ! */ goto failed; } talloc_set_name_const(dn->components[dn->comp_num].value.data, (const char *)dn->components[dn->comp_num].value.data); dt = d; dn->components, struct ldb_dn_component, dn->comp_num + 1); if ( ! dn->components) { /* ouch ! */ goto failed; } /* make sure all components are zeroed, other functions depend on this */ memset(&dn->components[dn->comp_num], '\0', sizeof(struct ldb_dn_component)); } continue; case '+': case '=': /* to main compatibility with earlier versions of ldb indexing, we have to accept the base64 encoded binary index values, which contain a '+' or '=' which should normally be escaped */ if (is_index) { if ( t ) t = NULL; *d++ = *p++; l++; break; } /* fall through */ case '\"': case '<': case '>': case ';': /* a string with not escaped specials is invalid (tested) */ if ( ! escape) { ldb_dn_mark_invalid(dn); goto failed; } escape = false; *d++ = *p++; l++; if ( t ) t = NULL; break; case '\\': if ( ! escape) { escape = true; p++; continue; } escape = false; *d++ = *p++; l++; if ( t ) t = NULL; break; default: if (escape) { if (isxdigit(p[0]) && isxdigit(p[1])) { if (sscanf(p, "%02x", &x) != 1) { /* invalid escaping sequence */ ldb_dn_mark_invalid(dn); goto failed; } p += 2; *d++ = (unsigned char)x; } else { *d++ = *p++; } escape = false; l++; if ( t ) t = NULL; break; } if (*p == ' ') { if ( ! t) t = p; } else { if ( t ) t = NULL; } *d++ = *p++; l++; break; } } }
164,673
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 *ReadDDSImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *image; MagickBooleanType status, cubemap = MagickFalse, volume = MagickFalse, matte; CompressionType compression; DDSInfo dds_info; DDSDecoder *decoder; size_t n, num_images; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Initialize image structure. */ if (ReadDDSInfo(image, &dds_info) != MagickTrue) { ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP) cubemap = MagickTrue; if (dds_info.ddscaps2 & DDSCAPS2_VOLUME && dds_info.depth > 0) volume = MagickTrue; (void) SeekBlob(image, 128, SEEK_SET); /* Determine pixel format */ if (dds_info.pixelformat.flags & DDPF_RGB) { compression = NoCompression; if (dds_info.pixelformat.flags & DDPF_ALPHAPIXELS) { matte = MagickTrue; decoder = ReadUncompressedRGBA; } else { matte = MagickTrue; decoder = ReadUncompressedRGB; } } else if (dds_info.pixelformat.flags & DDPF_LUMINANCE) { compression = NoCompression; if (dds_info.pixelformat.flags & DDPF_ALPHAPIXELS) { /* Not sure how to handle this */ ThrowReaderException(CorruptImageError, "ImageTypeNotSupported"); } else { matte = MagickFalse; decoder = ReadUncompressedRGB; } } else if (dds_info.pixelformat.flags & DDPF_FOURCC) { switch (dds_info.pixelformat.fourcc) { case FOURCC_DXT1: { matte = MagickFalse; compression = DXT1Compression; decoder = ReadDXT1; break; } case FOURCC_DXT3: { matte = MagickTrue; compression = DXT3Compression; decoder = ReadDXT3; break; } case FOURCC_DXT5: { matte = MagickTrue; compression = DXT5Compression; decoder = ReadDXT5; break; } default: { /* Unknown FOURCC */ ThrowReaderException(CorruptImageError, "ImageTypeNotSupported"); } } } else { /* Neither compressed nor uncompressed... thus unsupported */ ThrowReaderException(CorruptImageError, "ImageTypeNotSupported"); } num_images = 1; if (cubemap) { /* Determine number of faces defined in the cubemap */ num_images = 0; if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_POSITIVEX) num_images++; if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_NEGATIVEX) num_images++; if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_POSITIVEY) num_images++; if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_NEGATIVEY) num_images++; if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_POSITIVEZ) num_images++; if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_NEGATIVEZ) num_images++; } if (volume) num_images = dds_info.depth; for (n = 0; n < num_images; n++) { if (n != 0) { /* Start a new image */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } image->matte = matte; image->compression = compression; image->columns = dds_info.width; image->rows = dds_info.height; image->storage_class = DirectClass; image->endian = LSBEndian; image->depth = 8; if (image_info->ping != MagickFalse) { (void) CloseBlob(image); return(GetFirstImageInList(image)); } if ((decoder)(image, &dds_info, exception) != MagickTrue) { (void) CloseBlob(image); return(GetFirstImageInList(image)); } } if (EOFBlob(image) != MagickFalse) ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); (void) CloseBlob(image); return(GetFirstImageInList(image)); } Commit Message: CWE ID: CWE-119
static Image *ReadDDSImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *image; MagickBooleanType status, cubemap = MagickFalse, volume = MagickFalse, matte; CompressionType compression; DDSInfo dds_info; DDSDecoder *decoder; size_t n, num_images; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Initialize image structure. */ if (ReadDDSInfo(image, &dds_info) != MagickTrue) { ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP) cubemap = MagickTrue; if (dds_info.ddscaps2 & DDSCAPS2_VOLUME && dds_info.depth > 0) volume = MagickTrue; (void) SeekBlob(image, 128, SEEK_SET); /* Determine pixel format */ if (dds_info.pixelformat.flags & DDPF_RGB) { compression = NoCompression; if (dds_info.pixelformat.flags & DDPF_ALPHAPIXELS) { matte = MagickTrue; decoder = ReadUncompressedRGBA; } else { matte = MagickTrue; decoder = ReadUncompressedRGB; } } else if (dds_info.pixelformat.flags & DDPF_LUMINANCE) { compression = NoCompression; if (dds_info.pixelformat.flags & DDPF_ALPHAPIXELS) { /* Not sure how to handle this */ ThrowReaderException(CorruptImageError, "ImageTypeNotSupported"); } else { matte = MagickFalse; decoder = ReadUncompressedRGB; } } else if (dds_info.pixelformat.flags & DDPF_FOURCC) { switch (dds_info.pixelformat.fourcc) { case FOURCC_DXT1: { matte = MagickFalse; compression = DXT1Compression; decoder = ReadDXT1; break; } case FOURCC_DXT3: { matte = MagickTrue; compression = DXT3Compression; decoder = ReadDXT3; break; } case FOURCC_DXT5: { matte = MagickTrue; compression = DXT5Compression; decoder = ReadDXT5; break; } default: { /* Unknown FOURCC */ ThrowReaderException(CorruptImageError, "ImageTypeNotSupported"); } } } else { /* Neither compressed nor uncompressed... thus unsupported */ ThrowReaderException(CorruptImageError, "ImageTypeNotSupported"); } num_images = 1; if (cubemap) { /* Determine number of faces defined in the cubemap */ num_images = 0; if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_POSITIVEX) num_images++; if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_NEGATIVEX) num_images++; if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_POSITIVEY) num_images++; if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_NEGATIVEY) num_images++; if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_POSITIVEZ) num_images++; if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_NEGATIVEZ) num_images++; } if (volume) num_images = dds_info.depth; for (n = 0; n < num_images; n++) { if (n != 0) { /* Start a new image */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } image->matte = matte; image->compression = compression; image->columns = dds_info.width; image->rows = dds_info.height; image->storage_class = DirectClass; image->endian = LSBEndian; image->depth = 8; if (image_info->ping != MagickFalse) { (void) CloseBlob(image); return(GetFirstImageInList(image)); } status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } if ((decoder)(image, &dds_info, exception) != MagickTrue) { (void) CloseBlob(image); return(GetFirstImageInList(image)); } } if (EOFBlob(image) != MagickFalse) ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); (void) CloseBlob(image); return(GetFirstImageInList(image)); }
168,556
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: virtual void PreEncodeFrameHook(::libvpx_test::VideoSource *video, ::libvpx_test::Encoder *encoder) { if (video->frame() == 1) { encoder->Control(VP8E_SET_CPUUSED, cpu_used_); } else if (video->frame() == 3) { vpx_active_map_t map = {0}; uint8_t active_map[9 * 13] = { 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, }; map.cols = (kWidth + 15) / 16; map.rows = (kHeight + 15) / 16; ASSERT_EQ(map.cols, 13u); ASSERT_EQ(map.rows, 9u); map.active_map = active_map; encoder->Control(VP8E_SET_ACTIVEMAP, &map); } else if (video->frame() == 15) { vpx_active_map_t map = {0}; map.cols = (kWidth + 15) / 16; map.rows = (kHeight + 15) / 16; map.active_map = NULL; encoder->Control(VP8E_SET_ACTIVEMAP, &map); } } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119
virtual void PreEncodeFrameHook(::libvpx_test::VideoSource *video, ::libvpx_test::Encoder *encoder) { if (video->frame() == 1) { encoder->Control(VP8E_SET_CPUUSED, cpu_used_); } else if (video->frame() == 3) { vpx_active_map_t map = vpx_active_map_t(); uint8_t active_map[9 * 13] = { 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, }; map.cols = (kWidth + 15) / 16; map.rows = (kHeight + 15) / 16; ASSERT_EQ(map.cols, 13u); ASSERT_EQ(map.rows, 9u); map.active_map = active_map; encoder->Control(VP8E_SET_ACTIVEMAP, &map); } else if (video->frame() == 15) { vpx_active_map_t map = vpx_active_map_t(); map.cols = (kWidth + 15) / 16; map.rows = (kHeight + 15) / 16; map.active_map = NULL; encoder->Control(VP8E_SET_ACTIVEMAP, &map); } }
174,501
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 dynamicGetbuf(gdIOCtxPtr ctx, void *buf, int len) { int rlen, remain; dpIOCtxPtr dctx; dynamicPtr *dp; dctx = (dpIOCtxPtr) ctx; dp = dctx->dp; remain = dp->logicalSize - dp->pos; if(remain >= len) { rlen = len; } else { if(remain == 0) { /* 2.0.34: EOF is incorrect. We use 0 for * errors and EOF, just like fileGetbuf, * which is a simple fread() wrapper. * TBB. Original bug report: Daniel Cowgill. */ return 0; /* NOT EOF */ } rlen = remain; } memcpy(buf, (void *) ((char *)dp->data + dp->pos), rlen); dp->pos += rlen; return rlen; } Commit Message: Avoid potentially dangerous signed to unsigned conversion We make sure to never pass a negative `rlen` as size to memcpy(). See also <https://bugs.php.net/bug.php?id=73280>. Patch provided by Emmanuel Law. CWE ID: CWE-119
static int dynamicGetbuf(gdIOCtxPtr ctx, void *buf, int len) { int rlen, remain; dpIOCtxPtr dctx; dynamicPtr *dp; dctx = (dpIOCtxPtr) ctx; dp = dctx->dp; remain = dp->logicalSize - dp->pos; if(remain >= len) { rlen = len; } else { if(remain <= 0) { /* 2.0.34: EOF is incorrect. We use 0 for * errors and EOF, just like fileGetbuf, * which is a simple fread() wrapper. * TBB. Original bug report: Daniel Cowgill. */ return 0; /* NOT EOF */ } rlen = remain; } memcpy(buf, (void *) ((char *)dp->data + dp->pos), rlen); dp->pos += rlen; return rlen; }
168,769
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(mcrypt_list_algorithms) { char **modules; char *lib_dir = MCG(algorithms_dir); int lib_dir_len; int i, count; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|s", &lib_dir, &lib_dir_len) == FAILURE) { return; } array_init(return_value); modules = mcrypt_list_algorithms(lib_dir, &count); if (count == 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "No algorithms found in module dir"); } for (i = 0; i < count; i++) { add_index_string(return_value, i, modules[i], 1); } mcrypt_free_p(modules, count); } Commit Message: Fix bug #72455: Heap Overflow due to integer overflows CWE ID: CWE-190
PHP_FUNCTION(mcrypt_list_algorithms) { char **modules; char *lib_dir = MCG(algorithms_dir); int lib_dir_len; int i, count; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|s", &lib_dir, &lib_dir_len) == FAILURE) { return; } array_init(return_value); modules = mcrypt_list_algorithms(lib_dir, &count); if (count == 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "No algorithms found in module dir"); } for (i = 0; i < count; i++) { add_index_string(return_value, i, modules[i], 1); } mcrypt_free_p(modules, count); }
167,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 impeg2d_peek_next_start_code(dec_state_t *ps_dec) { stream_t *ps_stream; ps_stream = &ps_dec->s_bit_stream; impeg2d_bit_stream_flush_to_byte_boundary(ps_stream); while ((impeg2d_bit_stream_nxt(ps_stream,START_CODE_PREFIX_LEN) != START_CODE_PREFIX) && (ps_dec->s_bit_stream.u4_offset <= ps_dec->s_bit_stream.u4_max_offset)) { impeg2d_bit_stream_get(ps_stream,8); } return; } Commit Message: Fixed bit stream access to make sure that it is not read beyond the allocated size. Bug: 25765591 Change-Id: I98c23a3c3f84f6710f29bffe5ed73adcf51d47f6 CWE ID: CWE-254
void impeg2d_peek_next_start_code(dec_state_t *ps_dec) { stream_t *ps_stream; ps_stream = &ps_dec->s_bit_stream; impeg2d_bit_stream_flush_to_byte_boundary(ps_stream); while ((impeg2d_bit_stream_nxt(ps_stream,START_CODE_PREFIX_LEN) != START_CODE_PREFIX) && (ps_dec->s_bit_stream.u4_offset < ps_dec->s_bit_stream.u4_max_offset)) { impeg2d_bit_stream_get(ps_stream,8); } return; }
173,951
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: cosine_seek_read(wtap *wth, gint64 seek_off, struct wtap_pkthdr *phdr, Buffer *buf, int *err, gchar **err_info) { int pkt_len; char line[COSINE_LINE_LENGTH]; if (file_seek(wth->random_fh, seek_off, SEEK_SET, err) == -1) return FALSE; if (file_gets(line, COSINE_LINE_LENGTH, wth->random_fh) == NULL) { *err = file_error(wth->random_fh, err_info); if (*err == 0) { *err = WTAP_ERR_SHORT_READ; } return FALSE; } /* Parse the header */ pkt_len = parse_cosine_rec_hdr(phdr, line, err, err_info); if (pkt_len == -1) return FALSE; /* Convert the ASCII hex dump to binary data */ return parse_cosine_hex_dump(wth->random_fh, phdr, pkt_len, buf, err, err_info); } Commit Message: Fix packet length handling. Treat the packet length as unsigned - it shouldn't be negative in the file. If it is, that'll probably cause the sscanf to fail, so we'll report the file as bad. Check it against WTAP_MAX_PACKET_SIZE to make sure we don't try to allocate a huge amount of memory, just as we do in other file readers. Use the now-validated packet size as the length in ws_buffer_assure_space(), so we are certain to have enough space, and don't allocate too much space. Merge the header and packet data parsing routines while we're at it. Bug: 12395 Change-Id: Ia70f33b71ff28451190fcf144c333fd1362646b2 Reviewed-on: https://code.wireshark.org/review/15172 Reviewed-by: Guy Harris <[email protected]> CWE ID: CWE-119
cosine_seek_read(wtap *wth, gint64 seek_off, struct wtap_pkthdr *phdr, Buffer *buf, int *err, gchar **err_info) { char line[COSINE_LINE_LENGTH]; if (file_seek(wth->random_fh, seek_off, SEEK_SET, err) == -1) return FALSE; if (file_gets(line, COSINE_LINE_LENGTH, wth->random_fh) == NULL) { *err = file_error(wth->random_fh, err_info); if (*err == 0) { *err = WTAP_ERR_SHORT_READ; } return FALSE; } /* Parse the header and convert the ASCII hex dump to binary data */ return parse_cosine_packet(wth->random_fh, phdr, buf, line, err, err_info); }
169,964
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 parse_csum_name(const char *name, int len) { if (len < 0 && name) len = strlen(name); if (!name || (len == 4 && strncasecmp(name, "auto", 4) == 0)) { if (protocol_version >= 30) return CSUM_MD5; if (protocol_version >= 27) return CSUM_MD4_OLD; if (protocol_version >= 21) return CSUM_MD4_BUSTED; return CSUM_ARCHAIC; } if (len == 3 && strncasecmp(name, "md4", 3) == 0) return CSUM_MD4; if (len == 3 && strncasecmp(name, "md5", 3) == 0) return CSUM_MD5; if (len == 4 && strncasecmp(name, "none", 4) == 0) return CSUM_NONE; rprintf(FERROR, "unknown checksum name: %s\n", name); exit_cleanup(RERR_UNSUPPORTED); } Commit Message: CWE ID: CWE-354
int parse_csum_name(const char *name, int len) { if (len < 0 && name) len = strlen(name); if (!name || (len == 4 && strncasecmp(name, "auto", 4) == 0)) { if (protocol_version >= 30) return CSUM_MD5; if (protocol_version >= 27) return CSUM_MD4_OLD; if (protocol_version >= 21) return CSUM_MD4_BUSTED; return CSUM_MD4_ARCHAIC; } if (len == 3 && strncasecmp(name, "md4", 3) == 0) return CSUM_MD4; if (len == 3 && strncasecmp(name, "md5", 3) == 0) return CSUM_MD5; if (len == 4 && strncasecmp(name, "none", 4) == 0) return CSUM_NONE; rprintf(FERROR, "unknown checksum name: %s\n", name); exit_cleanup(RERR_UNSUPPORTED); }
164,645
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 dev_ifconf(struct net *net, struct compat_ifconf __user *uifc32) { struct compat_ifconf ifc32; struct ifconf ifc; struct ifconf __user *uifc; struct compat_ifreq __user *ifr32; struct ifreq __user *ifr; unsigned int i, j; int err; if (copy_from_user(&ifc32, uifc32, sizeof(struct compat_ifconf))) return -EFAULT; if (ifc32.ifcbuf == 0) { ifc32.ifc_len = 0; ifc.ifc_len = 0; ifc.ifc_req = NULL; uifc = compat_alloc_user_space(sizeof(struct ifconf)); } else { size_t len = ((ifc32.ifc_len / sizeof(struct compat_ifreq)) + 1) * sizeof(struct ifreq); uifc = compat_alloc_user_space(sizeof(struct ifconf) + len); ifc.ifc_len = len; ifr = ifc.ifc_req = (void __user *)(uifc + 1); ifr32 = compat_ptr(ifc32.ifcbuf); for (i = 0; i < ifc32.ifc_len; i += sizeof(struct compat_ifreq)) { if (copy_in_user(ifr, ifr32, sizeof(struct compat_ifreq))) return -EFAULT; ifr++; ifr32++; } } if (copy_to_user(uifc, &ifc, sizeof(struct ifconf))) return -EFAULT; err = dev_ioctl(net, SIOCGIFCONF, uifc); if (err) return err; if (copy_from_user(&ifc, uifc, sizeof(struct ifconf))) return -EFAULT; ifr = ifc.ifc_req; ifr32 = compat_ptr(ifc32.ifcbuf); for (i = 0, j = 0; i + sizeof(struct compat_ifreq) <= ifc32.ifc_len && j < ifc.ifc_len; i += sizeof(struct compat_ifreq), j += sizeof(struct ifreq)) { if (copy_in_user(ifr32, ifr, sizeof(struct compat_ifreq))) return -EFAULT; ifr32++; ifr++; } if (ifc32.ifcbuf == 0) { /* Translate from 64-bit structure multiple to * a 32-bit one. */ i = ifc.ifc_len; i = ((i / sizeof(struct ifreq)) * sizeof(struct compat_ifreq)); ifc32.ifc_len = i; } else { ifc32.ifc_len = i; } if (copy_to_user(uifc32, &ifc32, sizeof(struct compat_ifconf))) return -EFAULT; return 0; } Commit Message: net: fix info leak in compat dev_ifconf() The implementation of dev_ifconf() for the compat ioctl interface uses an intermediate ifc structure allocated in userland for the duration of the syscall. Though, it fails to initialize the padding bytes inserted for alignment and that for leaks four bytes of kernel stack. Add an explicit memset(0) before filling the structure to avoid the info leak. Signed-off-by: Mathias Krause <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-200
static int dev_ifconf(struct net *net, struct compat_ifconf __user *uifc32) { struct compat_ifconf ifc32; struct ifconf ifc; struct ifconf __user *uifc; struct compat_ifreq __user *ifr32; struct ifreq __user *ifr; unsigned int i, j; int err; if (copy_from_user(&ifc32, uifc32, sizeof(struct compat_ifconf))) return -EFAULT; memset(&ifc, 0, sizeof(ifc)); if (ifc32.ifcbuf == 0) { ifc32.ifc_len = 0; ifc.ifc_len = 0; ifc.ifc_req = NULL; uifc = compat_alloc_user_space(sizeof(struct ifconf)); } else { size_t len = ((ifc32.ifc_len / sizeof(struct compat_ifreq)) + 1) * sizeof(struct ifreq); uifc = compat_alloc_user_space(sizeof(struct ifconf) + len); ifc.ifc_len = len; ifr = ifc.ifc_req = (void __user *)(uifc + 1); ifr32 = compat_ptr(ifc32.ifcbuf); for (i = 0; i < ifc32.ifc_len; i += sizeof(struct compat_ifreq)) { if (copy_in_user(ifr, ifr32, sizeof(struct compat_ifreq))) return -EFAULT; ifr++; ifr32++; } } if (copy_to_user(uifc, &ifc, sizeof(struct ifconf))) return -EFAULT; err = dev_ioctl(net, SIOCGIFCONF, uifc); if (err) return err; if (copy_from_user(&ifc, uifc, sizeof(struct ifconf))) return -EFAULT; ifr = ifc.ifc_req; ifr32 = compat_ptr(ifc32.ifcbuf); for (i = 0, j = 0; i + sizeof(struct compat_ifreq) <= ifc32.ifc_len && j < ifc.ifc_len; i += sizeof(struct compat_ifreq), j += sizeof(struct ifreq)) { if (copy_in_user(ifr32, ifr, sizeof(struct compat_ifreq))) return -EFAULT; ifr32++; ifr++; } if (ifc32.ifcbuf == 0) { /* Translate from 64-bit structure multiple to * a 32-bit one. */ i = ifc.ifc_len; i = ((i / sizeof(struct ifreq)) * sizeof(struct compat_ifreq)); ifc32.ifc_len = i; } else { ifc32.ifc_len = i; } if (copy_to_user(uifc32, &ifc32, sizeof(struct compat_ifconf))) return -EFAULT; return 0; }
166,187
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: EncodedJSValue JSC_HOST_CALL JSTestNamedConstructorNamedConstructor::constructJSTestNamedConstructor(ExecState* exec) { JSTestNamedConstructorNamedConstructor* castedThis = jsCast<JSTestNamedConstructorNamedConstructor*>(exec->callee()); if (exec->argumentCount() < 1) return throwVMError(exec, createTypeError(exec, "Not enough arguments")); ExceptionCode ec = 0; const String& str1(ustringToString(MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined).isEmpty() ? UString() : MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined).toString(exec)->value(exec))); if (exec->hadException()) return JSValue::encode(jsUndefined()); const String& str2(ustringToString(MAYBE_MISSING_PARAMETER(exec, 1, DefaultIsUndefined).isEmpty() ? UString() : MAYBE_MISSING_PARAMETER(exec, 1, DefaultIsUndefined).toString(exec)->value(exec))); if (exec->hadException()) return JSValue::encode(jsUndefined()); const String& str3(ustringToString(MAYBE_MISSING_PARAMETER(exec, 2, DefaultIsNullString).isEmpty() ? UString() : MAYBE_MISSING_PARAMETER(exec, 2, DefaultIsNullString).toString(exec)->value(exec))); if (exec->hadException()) return JSValue::encode(jsUndefined()); RefPtr<TestNamedConstructor> object = TestNamedConstructor::createForJSConstructor(castedThis->document(), str1, str2, str3, ec); if (ec) { setDOMException(exec, ec); return JSValue::encode(JSValue()); } return JSValue::encode(asObject(toJS(exec, castedThis->globalObject(), object.get()))); } Commit Message: [JSC] Implement a helper method createNotEnoughArgumentsError() https://bugs.webkit.org/show_bug.cgi?id=85102 Reviewed by Geoffrey Garen. In bug 84787, kbr@ requested to avoid hard-coding createTypeError(exec, "Not enough arguments") here and there. This patch implements createNotEnoughArgumentsError(exec) and uses it in JSC bindings. c.f. a corresponding bug for V8 bindings is bug 85097. Source/JavaScriptCore: * runtime/Error.cpp: (JSC::createNotEnoughArgumentsError): (JSC): * runtime/Error.h: (JSC): Source/WebCore: Test: bindings/scripts/test/TestObj.idl * bindings/scripts/CodeGeneratorJS.pm: Modified as described above. (GenerateArgumentsCountCheck): * bindings/js/JSDataViewCustom.cpp: Ditto. (WebCore::getDataViewMember): (WebCore::setDataViewMember): * bindings/js/JSDeprecatedPeerConnectionCustom.cpp: (WebCore::JSDeprecatedPeerConnectionConstructor::constructJSDeprecatedPeerConnection): * bindings/js/JSDirectoryEntryCustom.cpp: (WebCore::JSDirectoryEntry::getFile): (WebCore::JSDirectoryEntry::getDirectory): * bindings/js/JSSharedWorkerCustom.cpp: (WebCore::JSSharedWorkerConstructor::constructJSSharedWorker): * bindings/js/JSWebKitMutationObserverCustom.cpp: (WebCore::JSWebKitMutationObserverConstructor::constructJSWebKitMutationObserver): (WebCore::JSWebKitMutationObserver::observe): * bindings/js/JSWorkerCustom.cpp: (WebCore::JSWorkerConstructor::constructJSWorker): * bindings/scripts/test/JS/JSFloat64Array.cpp: Updated run-bindings-tests. (WebCore::jsFloat64ArrayPrototypeFunctionFoo): * bindings/scripts/test/JS/JSTestActiveDOMObject.cpp: (WebCore::jsTestActiveDOMObjectPrototypeFunctionExcitingFunction): (WebCore::jsTestActiveDOMObjectPrototypeFunctionPostMessage): * bindings/scripts/test/JS/JSTestCustomNamedGetter.cpp: (WebCore::jsTestCustomNamedGetterPrototypeFunctionAnotherFunction): * bindings/scripts/test/JS/JSTestEventTarget.cpp: (WebCore::jsTestEventTargetPrototypeFunctionItem): (WebCore::jsTestEventTargetPrototypeFunctionAddEventListener): (WebCore::jsTestEventTargetPrototypeFunctionRemoveEventListener): (WebCore::jsTestEventTargetPrototypeFunctionDispatchEvent): * bindings/scripts/test/JS/JSTestInterface.cpp: (WebCore::JSTestInterfaceConstructor::constructJSTestInterface): (WebCore::jsTestInterfacePrototypeFunctionSupplementalMethod2): * bindings/scripts/test/JS/JSTestMediaQueryListListener.cpp: (WebCore::jsTestMediaQueryListListenerPrototypeFunctionMethod): * bindings/scripts/test/JS/JSTestNamedConstructor.cpp: (WebCore::JSTestNamedConstructorNamedConstructor::constructJSTestNamedConstructor): * bindings/scripts/test/JS/JSTestObj.cpp: (WebCore::JSTestObjConstructor::constructJSTestObj): (WebCore::jsTestObjPrototypeFunctionVoidMethodWithArgs): (WebCore::jsTestObjPrototypeFunctionIntMethodWithArgs): (WebCore::jsTestObjPrototypeFunctionObjMethodWithArgs): (WebCore::jsTestObjPrototypeFunctionMethodWithSequenceArg): (WebCore::jsTestObjPrototypeFunctionMethodReturningSequence): (WebCore::jsTestObjPrototypeFunctionMethodThatRequiresAllArgsAndThrows): (WebCore::jsTestObjPrototypeFunctionSerializedValue): (WebCore::jsTestObjPrototypeFunctionIdbKey): (WebCore::jsTestObjPrototypeFunctionOptionsObject): (WebCore::jsTestObjPrototypeFunctionAddEventListener): (WebCore::jsTestObjPrototypeFunctionRemoveEventListener): (WebCore::jsTestObjPrototypeFunctionMethodWithNonOptionalArgAndOptionalArg): (WebCore::jsTestObjPrototypeFunctionMethodWithNonOptionalArgAndTwoOptionalArgs): (WebCore::jsTestObjPrototypeFunctionMethodWithCallbackArg): (WebCore::jsTestObjPrototypeFunctionMethodWithNonCallbackArgAndCallbackArg): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod1): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod2): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod3): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod4): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod5): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod6): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod7): (WebCore::jsTestObjConstructorFunctionClassMethod2): (WebCore::jsTestObjConstructorFunctionOverloadedMethod11): (WebCore::jsTestObjConstructorFunctionOverloadedMethod12): (WebCore::jsTestObjPrototypeFunctionMethodWithUnsignedLongArray): (WebCore::jsTestObjPrototypeFunctionConvert1): (WebCore::jsTestObjPrototypeFunctionConvert2): (WebCore::jsTestObjPrototypeFunctionConvert3): (WebCore::jsTestObjPrototypeFunctionConvert4): (WebCore::jsTestObjPrototypeFunctionConvert5): (WebCore::jsTestObjPrototypeFunctionStrictFunction): * bindings/scripts/test/JS/JSTestSerializedScriptValueInterface.cpp: (WebCore::JSTestSerializedScriptValueInterfaceConstructor::constructJSTestSerializedScriptValueInterface): (WebCore::jsTestSerializedScriptValueInterfacePrototypeFunctionAcceptTransferList): git-svn-id: svn://svn.chromium.org/blink/trunk@115536 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-20
EncodedJSValue JSC_HOST_CALL JSTestNamedConstructorNamedConstructor::constructJSTestNamedConstructor(ExecState* exec) { JSTestNamedConstructorNamedConstructor* castedThis = jsCast<JSTestNamedConstructorNamedConstructor*>(exec->callee()); if (exec->argumentCount() < 1) return throwVMError(exec, createNotEnoughArgumentsError(exec)); ExceptionCode ec = 0; const String& str1(ustringToString(MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined).isEmpty() ? UString() : MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined).toString(exec)->value(exec))); if (exec->hadException()) return JSValue::encode(jsUndefined()); const String& str2(ustringToString(MAYBE_MISSING_PARAMETER(exec, 1, DefaultIsUndefined).isEmpty() ? UString() : MAYBE_MISSING_PARAMETER(exec, 1, DefaultIsUndefined).toString(exec)->value(exec))); if (exec->hadException()) return JSValue::encode(jsUndefined()); const String& str3(ustringToString(MAYBE_MISSING_PARAMETER(exec, 2, DefaultIsNullString).isEmpty() ? UString() : MAYBE_MISSING_PARAMETER(exec, 2, DefaultIsNullString).toString(exec)->value(exec))); if (exec->hadException()) return JSValue::encode(jsUndefined()); RefPtr<TestNamedConstructor> object = TestNamedConstructor::createForJSConstructor(castedThis->document(), str1, str2, str3, ec); if (ec) { setDOMException(exec, ec); return JSValue::encode(JSValue()); } return JSValue::encode(asObject(toJS(exec, castedThis->globalObject(), object.get()))); }
170,577
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 hashtable_set(hashtable_t *hashtable, const char *key, size_t serial, json_t *value) { pair_t *pair; bucket_t *bucket; size_t hash, index; /* rehash if the load ratio exceeds 1 */ if(hashtable->size >= num_buckets(hashtable)) if(hashtable_do_rehash(hashtable)) return -1; hash = hash_str(key); index = hash % num_buckets(hashtable); bucket = &hashtable->buckets[index]; pair = hashtable_find_pair(hashtable, bucket, key, hash); if(pair) { json_decref(pair->value); pair->value = value; } else { /* offsetof(...) returns the size of pair_t without the last, flexible member. This way, the correct amount is allocated. */ pair = jsonp_malloc(offsetof(pair_t, key) + strlen(key) + 1); if(!pair) return -1; pair->hash = hash; pair->serial = serial; strcpy(pair->key, key); pair->value = value; list_init(&pair->list); insert_to_bucket(hashtable, bucket, &pair->list); hashtable->size++; } return 0; } Commit Message: CVE-2013-6401: Change hash function, randomize hashes Thanks to Florian Weimer and Eric Sesterhenn for reporting, reviewing and testing. CWE ID: CWE-310
int hashtable_set(hashtable_t *hashtable, const char *key, size_t serial, json_t *value) { pair_t *pair; bucket_t *bucket; size_t hash, index; /* rehash if the load ratio exceeds 1 */ if(hashtable->size >= hashsize(hashtable->order)) if(hashtable_do_rehash(hashtable)) return -1; hash = hash_str(key); index = hash & hashmask(hashtable->order); bucket = &hashtable->buckets[index]; pair = hashtable_find_pair(hashtable, bucket, key, hash); if(pair) { json_decref(pair->value); pair->value = value; } else { /* offsetof(...) returns the size of pair_t without the last, flexible member. This way, the correct amount is allocated. */ pair = jsonp_malloc(offsetof(pair_t, key) + strlen(key) + 1); if(!pair) return -1; pair->hash = hash; pair->serial = serial; strcpy(pair->key, key); pair->value = value; list_init(&pair->list); insert_to_bucket(hashtable, bucket, &pair->list); hashtable->size++; } return 0; }
166,533
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 CallCompositorWithSuccess(mojom::PdfCompositorPtr ptr) { auto handle = CreateMSKPInSharedMemory(); ASSERT_TRUE(handle.IsValid()); mojo::ScopedSharedBufferHandle buffer_handle = mojo::WrapSharedMemoryHandle(handle, handle.GetSize(), true); ASSERT_TRUE(buffer_handle->is_valid()); EXPECT_CALL(*this, CallbackOnSuccess(testing::_)).Times(1); ptr->CompositePdf(std::move(buffer_handle), base::BindOnce(&PdfCompositorServiceTest::OnCallback, base::Unretained(this))); run_loop_->Run(); } Commit Message: Correct mojo::WrapSharedMemoryHandle usage Fixes some incorrect uses of mojo::WrapSharedMemoryHandle which were assuming that the call actually has any control over the memory protection applied to a handle when mapped. Where fixing usage is infeasible for this CL, TODOs are added to annotate follow-up work. Also updates the API and documentation to (hopefully) improve clarity and avoid similar mistakes from being made in the future. BUG=792900 Cq-Include-Trybots: master.tryserver.chromium.android:android_optional_gpu_tests_rel;master.tryserver.chromium.linux:linux_optional_gpu_tests_rel;master.tryserver.chromium.mac:mac_optional_gpu_tests_rel;master.tryserver.chromium.win:win_optional_gpu_tests_rel Change-Id: I0578aaa9ca3bfcb01aaf2451315d1ede95458477 Reviewed-on: https://chromium-review.googlesource.com/818282 Reviewed-by: Wei Li <[email protected]> Reviewed-by: Lei Zhang <[email protected]> Reviewed-by: John Abd-El-Malek <[email protected]> Reviewed-by: Daniel Cheng <[email protected]> Reviewed-by: Sadrul Chowdhury <[email protected]> Reviewed-by: Yuzhu Shen <[email protected]> Reviewed-by: Robert Sesek <[email protected]> Commit-Queue: Ken Rockot <[email protected]> Cr-Commit-Position: refs/heads/master@{#530268} CWE ID: CWE-787
void CallCompositorWithSuccess(mojom::PdfCompositorPtr ptr) { auto handle = CreateMSKPInSharedMemory(); ASSERT_TRUE(handle.IsValid()); mojo::ScopedSharedBufferHandle buffer_handle = mojo::WrapSharedMemoryHandle( handle, handle.GetSize(), mojo::UnwrappedSharedMemoryHandleProtection::kReadOnly); ASSERT_TRUE(buffer_handle->is_valid()); EXPECT_CALL(*this, CallbackOnSuccess(testing::_)).Times(1); ptr->CompositePdf(std::move(buffer_handle), base::BindOnce(&PdfCompositorServiceTest::OnCallback, base::Unretained(this))); run_loop_->Run(); }
172,856
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: gss_get_mic (minor_status, context_handle, qop_req, message_buffer, msg_token) OM_uint32 * minor_status; gss_ctx_id_t context_handle; gss_qop_t qop_req; gss_buffer_t message_buffer; gss_buffer_t msg_token; { OM_uint32 status; gss_union_ctx_id_t ctx; gss_mechanism mech; status = val_get_mic_args(minor_status, context_handle, qop_req, message_buffer, msg_token); if (status != GSS_S_COMPLETE) return (status); /* * select the approprate underlying mechanism routine and * call it. */ ctx = (gss_union_ctx_id_t) context_handle; mech = gssint_get_mechanism (ctx->mech_type); if (mech) { if (mech->gss_get_mic) { status = mech->gss_get_mic( minor_status, ctx->internal_ctx_id, qop_req, message_buffer, msg_token); if (status != GSS_S_COMPLETE) map_error(minor_status, mech); } else status = GSS_S_UNAVAILABLE; return(status); } return (GSS_S_BAD_MECH); } Commit Message: Preserve GSS context on init/accept failure After gss_init_sec_context() or gss_accept_sec_context() has created a context, don't delete the mechglue context on failures from subsequent calls, even if the mechanism deletes the mech-specific context (which is allowed by RFC 2744 but not preferred). Check for union contexts with no mechanism context in each GSS function which accepts a gss_ctx_id_t. CVE-2017-11462: RFC 2744 permits a GSS-API implementation to delete an existing security context on a second or subsequent call to gss_init_sec_context() or gss_accept_sec_context() if the call results in an error. This API behavior has been found to be dangerous, leading to the possibility of memory errors in some callers. For safety, GSS-API implementations should instead preserve existing security contexts on error until the caller deletes them. All versions of MIT krb5 prior to this change may delete acceptor contexts on error. Versions 1.13.4 through 1.13.7, 1.14.1 through 1.14.5, and 1.15 through 1.15.1 may also delete initiator contexts on error. ticket: 8598 (new) target_version: 1.15-next target_version: 1.14-next tags: pullup CWE ID: CWE-415
gss_get_mic (minor_status, context_handle, qop_req, message_buffer, msg_token) OM_uint32 * minor_status; gss_ctx_id_t context_handle; gss_qop_t qop_req; gss_buffer_t message_buffer; gss_buffer_t msg_token; { OM_uint32 status; gss_union_ctx_id_t ctx; gss_mechanism mech; status = val_get_mic_args(minor_status, context_handle, qop_req, message_buffer, msg_token); if (status != GSS_S_COMPLETE) return (status); /* * select the approprate underlying mechanism routine and * call it. */ ctx = (gss_union_ctx_id_t) context_handle; if (ctx->internal_ctx_id == GSS_C_NO_CONTEXT) return (GSS_S_NO_CONTEXT); mech = gssint_get_mechanism (ctx->mech_type); if (mech) { if (mech->gss_get_mic) { status = mech->gss_get_mic( minor_status, ctx->internal_ctx_id, qop_req, message_buffer, msg_token); if (status != GSS_S_COMPLETE) map_error(minor_status, mech); } else status = GSS_S_UNAVAILABLE; return(status); } return (GSS_S_BAD_MECH); }
168,022
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 Document::SetFocusedElement(Element* new_focused_element, const FocusParams& params) { DCHECK(!lifecycle_.InDetach()); clear_focused_element_timer_.Stop(); if (new_focused_element && (new_focused_element->GetDocument() != this)) return true; if (NodeChildRemovalTracker::IsBeingRemoved(new_focused_element)) return true; if (focused_element_ == new_focused_element) return true; bool focus_change_blocked = false; Element* old_focused_element = focused_element_; focused_element_ = nullptr; UpdateDistributionForFlatTreeTraversal(); Node* ancestor = (old_focused_element && old_focused_element->isConnected() && new_focused_element) ? FlatTreeTraversal::CommonAncestor(*old_focused_element, *new_focused_element) : nullptr; if (old_focused_element) { old_focused_element->SetFocused(false, params.type); old_focused_element->SetHasFocusWithinUpToAncestor(false, ancestor); if (GetPage() && (GetPage()->GetFocusController().IsFocused())) { old_focused_element->DispatchBlurEvent(new_focused_element, params.type, params.source_capabilities); if (focused_element_) { focus_change_blocked = true; new_focused_element = nullptr; } old_focused_element->DispatchFocusOutEvent(event_type_names::kFocusout, new_focused_element, params.source_capabilities); old_focused_element->DispatchFocusOutEvent(event_type_names::kDOMFocusOut, new_focused_element, params.source_capabilities); if (focused_element_) { focus_change_blocked = true; new_focused_element = nullptr; } } } if (new_focused_element) UpdateStyleAndLayoutTreeForNode(new_focused_element); if (new_focused_element && new_focused_element->IsFocusable()) { if (IsRootEditableElement(*new_focused_element) && !AcceptsEditingFocus(*new_focused_element)) { focus_change_blocked = true; goto SetFocusedElementDone; } focused_element_ = new_focused_element; SetSequentialFocusNavigationStartingPoint(focused_element_.Get()); if (params.type != kWebFocusTypeNone) last_focus_type_ = params.type; focused_element_->SetFocused(true, params.type); focused_element_->SetHasFocusWithinUpToAncestor(true, ancestor); if (focused_element_ != new_focused_element) { focus_change_blocked = true; goto SetFocusedElementDone; } CancelFocusAppearanceUpdate(); EnsurePaintLocationDataValidForNode(focused_element_); if (focused_element_ != new_focused_element) { focus_change_blocked = true; goto SetFocusedElementDone; } focused_element_->UpdateFocusAppearanceWithOptions( params.selection_behavior, params.options); if (GetPage() && (GetPage()->GetFocusController().IsFocused())) { focused_element_->DispatchFocusEvent(old_focused_element, params.type, params.source_capabilities); if (focused_element_ != new_focused_element) { focus_change_blocked = true; goto SetFocusedElementDone; } focused_element_->DispatchFocusInEvent(event_type_names::kFocusin, old_focused_element, params.type, params.source_capabilities); if (focused_element_ != new_focused_element) { focus_change_blocked = true; goto SetFocusedElementDone; } focused_element_->DispatchFocusInEvent(event_type_names::kDOMFocusIn, old_focused_element, params.type, params.source_capabilities); if (focused_element_ != new_focused_element) { focus_change_blocked = true; goto SetFocusedElementDone; } } } if (!focus_change_blocked && focused_element_) { if (AXObjectCache* cache = ExistingAXObjectCache()) { cache->HandleFocusedUIElementChanged(old_focused_element, new_focused_element); } } if (!focus_change_blocked && GetPage()) { GetPage()->GetChromeClient().FocusedNodeChanged(old_focused_element, focused_element_.Get()); } SetFocusedElementDone: UpdateStyleAndLayoutTree(); if (LocalFrame* frame = GetFrame()) frame->Selection().DidChangeFocus(); return !focus_change_blocked; } Commit Message: Cleanup and remove dead code in SetFocusedElement This early-out was added in: https://crrev.com/ce8ea3446283965c7eabab592cbffe223b1cf2bc Back then, we applied fragment focus in LayoutUpdated() which could cause this issue. This got cleaned up in: https://crrev.com/45236fd563e9df53dc45579be1f3d0b4784885a2 so that focus is no longer applied after layout. +Cleanup: Goto considered harmful Bug: 795381 Change-Id: Ifeb4d2e03e872fd48cca6720b1d4de36ad1ecbb7 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1524417 Commit-Queue: David Bokan <[email protected]> Reviewed-by: Stefan Zager <[email protected]> Cr-Commit-Position: refs/heads/master@{#641101} CWE ID: CWE-416
bool Document::SetFocusedElement(Element* new_focused_element, const FocusParams& params) { DCHECK(!lifecycle_.InDetach()); clear_focused_element_timer_.Stop(); if (new_focused_element && (new_focused_element->GetDocument() != this)) return true; if (NodeChildRemovalTracker::IsBeingRemoved(new_focused_element)) return true; if (focused_element_ == new_focused_element) return true; bool focus_change_blocked = false; Element* old_focused_element = focused_element_; focused_element_ = nullptr; UpdateDistributionForFlatTreeTraversal(); Node* ancestor = (old_focused_element && old_focused_element->isConnected() && new_focused_element) ? FlatTreeTraversal::CommonAncestor(*old_focused_element, *new_focused_element) : nullptr; if (old_focused_element) { old_focused_element->SetFocused(false, params.type); old_focused_element->SetHasFocusWithinUpToAncestor(false, ancestor); if (GetPage() && (GetPage()->GetFocusController().IsFocused())) { old_focused_element->DispatchBlurEvent(new_focused_element, params.type, params.source_capabilities); if (focused_element_) { focus_change_blocked = true; new_focused_element = nullptr; } old_focused_element->DispatchFocusOutEvent(event_type_names::kFocusout, new_focused_element, params.source_capabilities); old_focused_element->DispatchFocusOutEvent(event_type_names::kDOMFocusOut, new_focused_element, params.source_capabilities); if (focused_element_) { focus_change_blocked = true; new_focused_element = nullptr; } } } if (new_focused_element) UpdateStyleAndLayoutTreeForNode(new_focused_element); if (new_focused_element && new_focused_element->IsFocusable()) { if (IsRootEditableElement(*new_focused_element) && !AcceptsEditingFocus(*new_focused_element)) { UpdateStyleAndLayoutTree(); if (LocalFrame* frame = GetFrame()) frame->Selection().DidChangeFocus(); return false; } focused_element_ = new_focused_element; SetSequentialFocusNavigationStartingPoint(focused_element_.Get()); if (params.type != kWebFocusTypeNone) last_focus_type_ = params.type; focused_element_->SetFocused(true, params.type); focused_element_->SetHasFocusWithinUpToAncestor(true, ancestor); if (focused_element_ != new_focused_element) { UpdateStyleAndLayoutTree(); if (LocalFrame* frame = GetFrame()) frame->Selection().DidChangeFocus(); return false; } CancelFocusAppearanceUpdate(); EnsurePaintLocationDataValidForNode(focused_element_); focused_element_->UpdateFocusAppearanceWithOptions( params.selection_behavior, params.options); if (GetPage() && (GetPage()->GetFocusController().IsFocused())) { focused_element_->DispatchFocusEvent(old_focused_element, params.type, params.source_capabilities); if (focused_element_ != new_focused_element) { UpdateStyleAndLayoutTree(); if (LocalFrame* frame = GetFrame()) frame->Selection().DidChangeFocus(); return false; } focused_element_->DispatchFocusInEvent(event_type_names::kFocusin, old_focused_element, params.type, params.source_capabilities); if (focused_element_ != new_focused_element) { UpdateStyleAndLayoutTree(); if (LocalFrame* frame = GetFrame()) frame->Selection().DidChangeFocus(); return false; } focused_element_->DispatchFocusInEvent(event_type_names::kDOMFocusIn, old_focused_element, params.type, params.source_capabilities); if (focused_element_ != new_focused_element) { UpdateStyleAndLayoutTree(); if (LocalFrame* frame = GetFrame()) frame->Selection().DidChangeFocus(); return false; } } } if (!focus_change_blocked && focused_element_) { if (AXObjectCache* cache = ExistingAXObjectCache()) { cache->HandleFocusedUIElementChanged(old_focused_element, new_focused_element); } } if (!focus_change_blocked && GetPage()) { GetPage()->GetChromeClient().FocusedNodeChanged(old_focused_element, focused_element_.Get()); } UpdateStyleAndLayoutTree(); if (LocalFrame* frame = GetFrame()) frame->Selection().DidChangeFocus(); return !focus_change_blocked; }
172,046
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: _exsltDateTruncateDate (exsltDateValPtr dt, exsltDateType type) { if (dt == NULL) return 1; if ((type & XS_TIME) != XS_TIME) { dt->value.date.hour = 0; dt->value.date.min = 0; dt->value.date.sec = 0.0; } if ((type & XS_GDAY) != XS_GDAY) dt->value.date.day = 0; if ((type & XS_GMONTH) != XS_GMONTH) dt->value.date.mon = 0; if ((type & XS_GYEAR) != XS_GYEAR) dt->value.date.year = 0; dt->type = type; return 0; } Commit Message: Roll libxslt to 891681e3e948f31732229f53cb6db7215f740fc7 BUG=583156,583171 Review URL: https://codereview.chromium.org/1853083002 Cr-Commit-Position: refs/heads/master@{#385338} CWE ID: CWE-119
_exsltDateTruncateDate (exsltDateValPtr dt, exsltDateType type) { if (dt == NULL) return 1; if ((type & XS_TIME) != XS_TIME) { dt->value.date.hour = 0; dt->value.date.min = 0; dt->value.date.sec = 0.0; } if ((type & XS_GDAY) != XS_GDAY) dt->value.date.day = 1; if ((type & XS_GMONTH) != XS_GMONTH) dt->value.date.mon = 1; if ((type & XS_GYEAR) != XS_GYEAR) dt->value.date.year = 0; dt->type = type; return 0; }
173,290
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: cJSON *cJSON_CreateBool( int b ) { cJSON *item = cJSON_New_Item(); if ( item ) item->type = b ? cJSON_True : cJSON_False; return item; } Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a malformed JSON string was passed on the control channel. This issue, present in the cJSON library, was already fixed upstream, so was addressed here in iperf3 by importing a newer version of cJSON (plus local ESnet modifications). Discovered and reported by Dave McDaniel, Cisco Talos. Based on a patch by @dopheide-esnet, with input from @DaveGamble. Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001, CVE-2016-4303 (cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40) Signed-off-by: Bruce A. Mah <[email protected]> CWE ID: CWE-119
cJSON *cJSON_CreateBool( int b )
167,270
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 X509_cmp_time(const ASN1_TIME *ctm, time_t *cmp_time) { char *str; ASN1_TIME atm; long offset; char buff1[24], buff2[24], *p; int i, j; p = buff1; i = ctm->length; str = (char *)ctm->data; if (ctm->type == V_ASN1_UTCTIME) { if ((i < 11) || (i > 17)) return 0; memcpy(p, str, 10); p += 10; str += 10; } else { if (i < 13) return 0; memcpy(p, str, 12); p += 12; str += 12; } if ((*str == 'Z') || (*str == '-') || (*str == '+')) { *(p++) = '0'; *(p++) = '0'; } else { *(p++) = *(str++); *(p++) = *(str++); /* Skip any fractional seconds... */ if (*str == '.') { str++; while ((*str >= '0') && (*str <= '9')) str++; } } *(p++) = 'Z'; *(p++) = '\0'; if (*str == 'Z') offset = 0; else { if ((*str != '+') && (*str != '-')) return 0; offset = ((str[1] - '0') * 10 + (str[2] - '0')) * 60; offset += (str[3] - '0') * 10 + (str[4] - '0'); if (*str == '-') offset = -offset; } atm.type = ctm->type; atm.flags = 0; atm.length = sizeof(buff2); atm.data = (unsigned char *)buff2; if (X509_time_adj(&atm, offset * 60, cmp_time) == NULL) return 0; if (ctm->type == V_ASN1_UTCTIME) { i = (buff1[0] - '0') * 10 + (buff1[1] - '0'); if (i < 50) i += 100; /* cf. RFC 2459 */ j = (buff2[0] - '0') * 10 + (buff2[1] - '0'); if (j < 50) j += 100; if (i < j) return -1; if (i > j) return 1; } i = strcmp(buff1, buff2); if (i == 0) /* wait a second then return younger :-) */ return -1; else return i; } Commit Message: Fix length checks in X509_cmp_time to avoid out-of-bounds reads. Also tighten X509_cmp_time to reject more than three fractional seconds in the time; and to reject trailing garbage after the offset. CVE-2015-1789 Reviewed-by: Viktor Dukhovni <[email protected]> Reviewed-by: Richard Levitte <[email protected]> CWE ID: CWE-119
int X509_cmp_time(const ASN1_TIME *ctm, time_t *cmp_time) { char *str; ASN1_TIME atm; long offset; char buff1[24], buff2[24], *p; int i, j, remaining; p = buff1; remaining = ctm->length; str = (char *)ctm->data; /* * Note that the following (historical) code allows much more slack in the * time format than RFC5280. In RFC5280, the representation is fixed: * UTCTime: YYMMDDHHMMSSZ * GeneralizedTime: YYYYMMDDHHMMSSZ */ if (ctm->type == V_ASN1_UTCTIME) { /* YYMMDDHHMM[SS]Z or YYMMDDHHMM[SS](+-)hhmm */ int min_length = sizeof("YYMMDDHHMMZ") - 1; int max_length = sizeof("YYMMDDHHMMSS+hhmm") - 1; if (remaining < min_length || remaining > max_length) return 0; memcpy(p, str, 10); p += 10; str += 10; remaining -= 10; } else { /* YYYYMMDDHHMM[SS[.fff]]Z or YYYYMMDDHHMM[SS[.f[f[f]]]](+-)hhmm */ int min_length = sizeof("YYYYMMDDHHMMZ") - 1; int max_length = sizeof("YYYYMMDDHHMMSS.fff+hhmm") - 1; if (remaining < min_length || remaining > max_length) return 0; memcpy(p, str, 12); p += 12; str += 12; remaining -= 12; } if ((*str == 'Z') || (*str == '-') || (*str == '+')) { *(p++) = '0'; *(p++) = '0'; } else { /* SS (seconds) */ if (remaining < 2) return 0; *(p++) = *(str++); *(p++) = *(str++); remaining -= 2; /* * Skip any (up to three) fractional seconds... * TODO(emilia): in RFC5280, fractional seconds are forbidden. * Can we just kill them altogether? */ if (remaining && *str == '.') { str++; remaining--; for (i = 0; i < 3 && remaining; i++, str++, remaining--) { if (*str < '0' || *str > '9') break; } } } *(p++) = 'Z'; *(p++) = '\0'; /* We now need either a terminating 'Z' or an offset. */ if (!remaining) return 0; if (*str == 'Z') { if (remaining != 1) return 0; offset = 0; } else { /* (+-)HHMM */ if ((*str != '+') && (*str != '-')) return 0; /* Historical behaviour: the (+-)hhmm offset is forbidden in RFC5280. */ if (remaining != 5) return 0; if (str[1] < '0' || str[1] > '9' || str[2] < '0' || str[2] > '9' || str[3] < '0' || str[3] > '9' || str[4] < '0' || str[4] > '9') return 0; offset = ((str[1] - '0') * 10 + (str[2] - '0')) * 60; offset += (str[3] - '0') * 10 + (str[4] - '0'); if (*str == '-') offset = -offset; } atm.type = ctm->type; atm.flags = 0; atm.length = sizeof(buff2); atm.data = (unsigned char *)buff2; if (X509_time_adj(&atm, offset * 60, cmp_time) == NULL) return 0; if (ctm->type == V_ASN1_UTCTIME) { i = (buff1[0] - '0') * 10 + (buff1[1] - '0'); if (i < 50) i += 100; /* cf. RFC 2459 */ j = (buff2[0] - '0') * 10 + (buff2[1] - '0'); if (j < 50) j += 100; if (i < j) return -1; if (i > j) return 1; } i = strcmp(buff1, buff2); if (i == 0) /* wait a second then return younger :-) */ return -1; else return i; }
166,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: Cluster* Cluster::Create(Segment* pSegment, long idx, long long off) { assert(pSegment); assert(off >= 0); const long long element_start = pSegment->m_start + off; Cluster* const pCluster = new Cluster(pSegment, idx, element_start); assert(pCluster); return pCluster; } Commit Message: external/libvpx/libwebm: Update snapshot Update libwebm snapshot. This update contains security fixes from upstream. Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b BUG=23167726 Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207 (cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a) CWE ID: CWE-20
Cluster* Cluster::Create(Segment* pSegment, long idx, long long off) Cluster* Cluster::Create(Segment* pSegment, long idx, long long off) { if (!pSegment || off < 0) return NULL; const long long element_start = pSegment->m_start + off; Cluster* const pCluster = new (std::nothrow) Cluster(pSegment, idx, element_start); return pCluster; }
173,804
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 *btif_hl_select_thread(void *arg){ fd_set org_set, curr_set; int r, max_curr_s, max_org_s; UNUSED(arg); BTIF_TRACE_DEBUG("entered btif_hl_select_thread"); FD_ZERO(&org_set); max_org_s = btif_hl_select_wakeup_init(&org_set); BTIF_TRACE_DEBUG("max_s=%d ", max_org_s); for (;;) { r = 0; BTIF_TRACE_DEBUG("set curr_set = org_set "); curr_set = org_set; max_curr_s = max_org_s; int ret = select((max_curr_s + 1), &curr_set, NULL, NULL, NULL); BTIF_TRACE_DEBUG("select unblocked ret=%d", ret); if (ret == -1) { BTIF_TRACE_DEBUG("select() ret -1, exit the thread"); btif_hl_thread_cleanup(); select_thread_id = -1; return 0; } else if (ret) { BTIF_TRACE_DEBUG("btif_hl_select_wake_signaled, signal ret=%d", ret); if (btif_hl_select_wake_signaled(&curr_set)) { r = btif_hl_select_wake_reset(); BTIF_TRACE_DEBUG("btif_hl_select_wake_signaled, signal:%d", r); if (r == btif_hl_signal_select_wakeup || r == btif_hl_signal_select_close_connected ) { btif_hl_select_wakeup_callback(&org_set, r); } else if( r == btif_hl_signal_select_exit) { btif_hl_thread_cleanup(); BTIF_TRACE_DEBUG("Exit hl_select_thread for btif_hl_signal_select_exit"); return 0; } } btif_hl_select_monitor_callback(&curr_set, &org_set); max_org_s = btif_hl_update_maxfd(max_org_s); } else BTIF_TRACE_DEBUG("no data, select ret: %d\n", ret); } BTIF_TRACE_DEBUG("leaving hl_select_thread"); return 0; } Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process Bug: 28885210 Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360 Conflicts: btif/co/bta_hh_co.c btif/src/btif_core.c Merge conflict resolution of ag/1161415 (referencing ag/1164670) - Directly into mnc-mr2-release CWE ID: CWE-284
static void *btif_hl_select_thread(void *arg){ fd_set org_set, curr_set; int r, max_curr_s, max_org_s; UNUSED(arg); BTIF_TRACE_DEBUG("entered btif_hl_select_thread"); FD_ZERO(&org_set); max_org_s = btif_hl_select_wakeup_init(&org_set); BTIF_TRACE_DEBUG("max_s=%d ", max_org_s); for (;;) { r = 0; BTIF_TRACE_DEBUG("set curr_set = org_set "); curr_set = org_set; max_curr_s = max_org_s; int ret = TEMP_FAILURE_RETRY(select((max_curr_s + 1), &curr_set, NULL, NULL, NULL)); BTIF_TRACE_DEBUG("select unblocked ret=%d", ret); if (ret == -1) { BTIF_TRACE_DEBUG("select() ret -1, exit the thread"); btif_hl_thread_cleanup(); select_thread_id = -1; return 0; } else if (ret) { BTIF_TRACE_DEBUG("btif_hl_select_wake_signaled, signal ret=%d", ret); if (btif_hl_select_wake_signaled(&curr_set)) { r = btif_hl_select_wake_reset(); BTIF_TRACE_DEBUG("btif_hl_select_wake_signaled, signal:%d", r); if (r == btif_hl_signal_select_wakeup || r == btif_hl_signal_select_close_connected ) { btif_hl_select_wakeup_callback(&org_set, r); } else if( r == btif_hl_signal_select_exit) { btif_hl_thread_cleanup(); BTIF_TRACE_DEBUG("Exit hl_select_thread for btif_hl_signal_select_exit"); return 0; } } btif_hl_select_monitor_callback(&curr_set, &org_set); max_org_s = btif_hl_update_maxfd(max_org_s); } else BTIF_TRACE_DEBUG("no data, select ret: %d\n", ret); } BTIF_TRACE_DEBUG("leaving hl_select_thread"); return 0; }
173,442
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: header_put_byte (SF_PRIVATE *psf, char x) { if (psf->headindex < SIGNED_SIZEOF (psf->header) - 1) psf->header [psf->headindex++] = x ; } /* header_put_byte */ Commit Message: src/ : Move to a variable length header buffer Previously, the `psf->header` buffer was a fixed length specified by `SF_HEADER_LEN` which was set to `12292`. This was problematic for two reasons; this value was un-necessarily large for the majority of files and too small for some others. Now the size of the header buffer starts at 256 bytes and grows as necessary up to a maximum of 100k. CWE ID: CWE-119
header_put_byte (SF_PRIVATE *psf, char x) { psf->header.ptr [psf->header.indx++] = x ; } /* header_put_byte */
170,053
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_METHOD(Phar, addFile) { char *fname, *localname = NULL; size_t fname_len, localname_len = 0; php_stream *resource; zval zresource; PHAR_ARCHIVE_OBJECT(); if (zend_parse_parameters(ZEND_NUM_ARGS(), "s|s", &fname, &fname_len, &localname, &localname_len) == FAILURE) { return; } #if PHP_API_VERSION < 20100412 if (PG(safe_mode) && (!php_checkuid(fname, NULL, CHECKUID_ALLOW_ONLY_FILE))) { zend_throw_exception_ex(spl_ce_RuntimeException, 0, "phar error: unable to open file \"%s\" to add to phar archive, safe_mode restrictions prevent this", fname); return; } #endif if (!strstr(fname, "://") && php_check_open_basedir(fname)) { zend_throw_exception_ex(spl_ce_RuntimeException, 0, "phar error: unable to open file \"%s\" to add to phar archive, open_basedir restrictions prevent this", fname); return; } if (!(resource = php_stream_open_wrapper(fname, "rb", 0, NULL))) { zend_throw_exception_ex(spl_ce_RuntimeException, 0, "phar error: unable to open file \"%s\" to add to phar archive", fname); return; } if (localname) { fname = localname; fname_len = localname_len; } php_stream_to_zval(resource, &zresource); phar_add_file(&(phar_obj->archive), fname, fname_len, NULL, 0, &zresource); zval_ptr_dtor(&zresource); } Commit Message: CWE ID: CWE-20
PHP_METHOD(Phar, addFile) { char *fname, *localname = NULL; size_t fname_len, localname_len = 0; php_stream *resource; zval zresource; PHAR_ARCHIVE_OBJECT(); if (zend_parse_parameters(ZEND_NUM_ARGS(), "p|s", &fname, &fname_len, &localname, &localname_len) == FAILURE) { return; } #if PHP_API_VERSION < 20100412 if (PG(safe_mode) && (!php_checkuid(fname, NULL, CHECKUID_ALLOW_ONLY_FILE))) { zend_throw_exception_ex(spl_ce_RuntimeException, 0, "phar error: unable to open file \"%s\" to add to phar archive, safe_mode restrictions prevent this", fname); return; } #endif if (!strstr(fname, "://") && php_check_open_basedir(fname)) { zend_throw_exception_ex(spl_ce_RuntimeException, 0, "phar error: unable to open file \"%s\" to add to phar archive, open_basedir restrictions prevent this", fname); return; } if (!(resource = php_stream_open_wrapper(fname, "rb", 0, NULL))) { zend_throw_exception_ex(spl_ce_RuntimeException, 0, "phar error: unable to open file \"%s\" to add to phar archive", fname); return; } if (localname) { fname = localname; fname_len = localname_len; } php_stream_to_zval(resource, &zresource); phar_add_file(&(phar_obj->archive), fname, fname_len, NULL, 0, &zresource); zval_ptr_dtor(&zresource); }
165,070
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 tpm_open(struct inode *inode, struct file *file) { int minor = iminor(inode); struct tpm_chip *chip = NULL, *pos; rcu_read_lock(); list_for_each_entry_rcu(pos, &tpm_chip_list, list) { if (pos->vendor.miscdev.minor == minor) { chip = pos; get_device(chip->dev); break; } } rcu_read_unlock(); if (!chip) return -ENODEV; if (test_and_set_bit(0, &chip->is_open)) { dev_dbg(chip->dev, "Another process owns this TPM\n"); put_device(chip->dev); return -EBUSY; } chip->data_buffer = kmalloc(TPM_BUFSIZE * sizeof(u8), GFP_KERNEL); if (chip->data_buffer == NULL) { clear_bit(0, &chip->is_open); put_device(chip->dev); return -ENOMEM; } atomic_set(&chip->data_pending, 0); file->private_data = chip; return 0; } Commit Message: char/tpm: Fix unitialized usage of data buffer This patch fixes information leakage to the userspace by initializing the data buffer to zero. Reported-by: Peter Huewe <[email protected]> Signed-off-by: Peter Huewe <[email protected]> Signed-off-by: Marcel Selhorst <[email protected]> [ Also removed the silly "* sizeof(u8)". If that isn't 1, we have way deeper problems than a simple multiplication can fix. - Linus ] Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-200
int tpm_open(struct inode *inode, struct file *file) { int minor = iminor(inode); struct tpm_chip *chip = NULL, *pos; rcu_read_lock(); list_for_each_entry_rcu(pos, &tpm_chip_list, list) { if (pos->vendor.miscdev.minor == minor) { chip = pos; get_device(chip->dev); break; } } rcu_read_unlock(); if (!chip) return -ENODEV; if (test_and_set_bit(0, &chip->is_open)) { dev_dbg(chip->dev, "Another process owns this TPM\n"); put_device(chip->dev); return -EBUSY; } chip->data_buffer = kzalloc(TPM_BUFSIZE, GFP_KERNEL); if (chip->data_buffer == NULL) { clear_bit(0, &chip->is_open); put_device(chip->dev); return -ENOMEM; } atomic_set(&chip->data_pending, 0); file->private_data = chip; return 0; }
165,895